Key.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. #include "crypto/Key.h"
  16. #include "util/Base32.h"
  17. #include "crypto/AddressCalc.h"
  18. #include <stddef.h>
  19. char* Key_parse_strerror(int error)
  20. {
  21. switch (error) {
  22. case 0: return "none";
  23. case Key_parse_TOO_SHORT: return "key must be 52 characters long";
  24. case Key_parse_MALFORMED: return "key must end in .k";
  25. case Key_parse_DECODE_FAILED: return "failed to base-32 decode key";
  26. case Key_parse_INVALID: return "not a valid cjdns public key";
  27. default: return "unknown error";
  28. }
  29. }
  30. #define Key_parse_TOO_SHORT -1
  31. #define Key_parse_MALFORMED -2
  32. #define Key_parse_DECODE_FAILED -3
  33. #define Key_parse_INVALID -4
  34. int Key_parse(String* key, uint8_t keyBytesOut[32], uint8_t ip6Out[16])
  35. {
  36. if (!key || key->len < 52) {
  37. return Key_parse_TOO_SHORT;
  38. }
  39. if (key->bytes[52] != '.' || key->bytes[53] != 'k') {
  40. return Key_parse_MALFORMED;
  41. }
  42. if (Base32_decode(keyBytesOut, 32, (uint8_t*)key->bytes, 52) != 32) {
  43. return Key_parse_DECODE_FAILED;
  44. }
  45. if (ip6Out) {
  46. AddressCalc_addressForPublicKey(ip6Out, keyBytesOut);
  47. if (!AddressCalc_validAddress(ip6Out)) {
  48. return Key_parse_INVALID;
  49. }
  50. }
  51. return 0;
  52. }
  53. String* Key_stringify(uint8_t key[32], struct Allocator* alloc)
  54. {
  55. String* out = String_newBinary(NULL, 54, alloc);
  56. Base32_encode((uint8_t*)out->bytes, 53, key, 32);
  57. out->bytes[52] = '.';
  58. out->bytes[53] = 'k';
  59. return out;
  60. }