keypair.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #include <string.h>
  2. #include "crypto_hash_sha512.h"
  3. #include "crypto_scalarmult_curve25519.h"
  4. #include "crypto_sign_ed25519.h"
  5. #include "sign_ed25519_ref10.h"
  6. #include "private/ed25519_ref10.h"
  7. #include "randombytes.h"
  8. #include "utils.h"
  9. int
  10. crypto_sign_ed25519_seed_keypair(unsigned char *pk, unsigned char *sk,
  11. const unsigned char *seed)
  12. {
  13. ge25519_p3 A;
  14. crypto_hash_sha512(sk, seed, 32);
  15. sk[0] &= 248;
  16. sk[31] &= 127;
  17. sk[31] |= 64;
  18. ge25519_scalarmult_base(&A, sk);
  19. ge25519_p3_tobytes(pk, &A);
  20. memmove(sk, seed, 32);
  21. memmove(sk + 32, pk, 32);
  22. return 0;
  23. }
  24. int
  25. crypto_sign_ed25519_keypair(unsigned char *pk, unsigned char *sk)
  26. {
  27. unsigned char seed[32];
  28. int ret;
  29. randombytes_buf(seed, sizeof seed);
  30. ret = crypto_sign_ed25519_seed_keypair(pk, sk, seed);
  31. sodium_memzero(seed, sizeof seed);
  32. return ret;
  33. }
  34. int
  35. crypto_sign_ed25519_pk_to_curve25519(unsigned char *curve25519_pk,
  36. const unsigned char *ed25519_pk)
  37. {
  38. ge25519_p3 A;
  39. fe25519 x;
  40. fe25519 one_minus_y;
  41. if (ge25519_has_small_order(ed25519_pk) != 0 ||
  42. ge25519_frombytes_negate_vartime(&A, ed25519_pk) != 0 ||
  43. ge25519_is_on_main_subgroup(&A) == 0) {
  44. return -1;
  45. }
  46. fe25519_1(one_minus_y);
  47. fe25519_sub(one_minus_y, one_minus_y, A.Y);
  48. fe25519_1(x);
  49. fe25519_add(x, x, A.Y);
  50. fe25519_invert(one_minus_y, one_minus_y);
  51. fe25519_mul(x, x, one_minus_y);
  52. fe25519_tobytes(curve25519_pk, x);
  53. return 0;
  54. }
  55. int
  56. crypto_sign_ed25519_sk_to_curve25519(unsigned char *curve25519_sk,
  57. const unsigned char *ed25519_sk)
  58. {
  59. unsigned char h[crypto_hash_sha512_BYTES];
  60. crypto_hash_sha512(h, ed25519_sk, 32);
  61. h[0] &= 248;
  62. h[31] &= 127;
  63. h[31] |= 64;
  64. memcpy(curve25519_sk, h, crypto_scalarmult_curve25519_BYTES);
  65. sodium_memzero(h, sizeof h);
  66. return 0;
  67. }