Key.c 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 <https://www.gnu.org/licenses/>.
  14. */
  15. #include "crypto/Key.h"
  16. #include "crypto/random/Random.h"
  17. #include "util/Base32.h"
  18. #include "crypto/AddressCalc.h"
  19. #include "crypto_scalarmult_curve25519.h"
  20. #include <stddef.h>
  21. int Key_gen(uint8_t addressOut[16],
  22. uint8_t publicKeyOut[32],
  23. uint8_t privateKeyOut[32],
  24. struct Random* rand)
  25. {
  26. for (;;) {
  27. Random_bytes(rand, privateKeyOut, 32);
  28. crypto_scalarmult_curve25519_base(publicKeyOut, privateKeyOut);
  29. // Brute force for keys until one matches FC00:/8
  30. if (AddressCalc_addressForPublicKey(addressOut, publicKeyOut)) {
  31. return 0;
  32. }
  33. }
  34. }
  35. char* Key_parse_strerror(int error)
  36. {
  37. switch (error) {
  38. case 0: return "none";
  39. case Key_parse_TOO_SHORT: return "key must be 52 characters long";
  40. case Key_parse_MALFORMED: return "key must end in .k";
  41. case Key_parse_DECODE_FAILED: return "failed to base-32 decode key";
  42. case Key_parse_INVALID: return "not a valid cjdns public key";
  43. default: return "unknown error";
  44. }
  45. }
  46. #define Key_parse_TOO_SHORT -1
  47. #define Key_parse_MALFORMED -2
  48. #define Key_parse_DECODE_FAILED -3
  49. #define Key_parse_INVALID -4
  50. int Key_parse(String* key, uint8_t keyBytesOut[32], uint8_t ip6Out[16])
  51. {
  52. if (!key || key->len < 52) {
  53. return Key_parse_TOO_SHORT;
  54. }
  55. if (key->bytes[52] != '.' || key->bytes[53] != 'k') {
  56. return Key_parse_MALFORMED;
  57. }
  58. if (Base32_decode(keyBytesOut, 32, (uint8_t*)key->bytes, 52) != 32) {
  59. return Key_parse_DECODE_FAILED;
  60. }
  61. if (ip6Out) {
  62. AddressCalc_addressForPublicKey(ip6Out, keyBytesOut);
  63. if (!AddressCalc_validAddress(ip6Out)) {
  64. return Key_parse_INVALID;
  65. }
  66. }
  67. return 0;
  68. }
  69. String* Key_stringify(uint8_t key[32], struct Allocator* alloc)
  70. {
  71. String* out = String_newBinary(NULL, 54, alloc);
  72. Base32_encode((uint8_t*)out->bytes, 53, key, 32);
  73. out->bytes[52] = '.';
  74. out->bytes[53] = 'k';
  75. return out;
  76. }