add_scalar.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #include "ed25519.h"
  2. #include "ge.h"
  3. #include "sc.h"
  4. #include "sha512.h"
  5. /* see http://crypto.stackexchange.com/a/6215/4697 */
  6. void ed25519_add_scalar(unsigned char *public_key, unsigned char *private_key, const unsigned char *scalar) {
  7. const unsigned char SC_1[32] = {1}; /* scalar with value 1 */
  8. unsigned char n[32];
  9. ge_p3 nB;
  10. ge_p1p1 A_p1p1;
  11. ge_p3 A;
  12. ge_p3 public_key_unpacked;
  13. ge_cached T;
  14. sha512_context hash;
  15. unsigned char hashbuf[64];
  16. int i;
  17. /* copy the scalar and clear highest bit */
  18. for (i = 0; i < 31; ++i) {
  19. n[i] = scalar[i];
  20. }
  21. n[31] = scalar[31] & 127;
  22. /* private key: a = n + t */
  23. if (private_key) {
  24. sc_muladd(private_key, SC_1, n, private_key);
  25. // https://github.com/orlp/ed25519/issues/3
  26. sha512_init(&hash);
  27. sha512_update(&hash, private_key + 32, 32);
  28. sha512_update(&hash, scalar, 32);
  29. sha512_final(&hash, hashbuf);
  30. for (i = 0; i < 32; ++i) {
  31. private_key[32 + i] = hashbuf[i];
  32. }
  33. }
  34. /* public key: A = nB + T */
  35. if (public_key) {
  36. /* if we know the private key we don't need a point addition, which is faster */
  37. /* using a "timing attack" you could find out wether or not we know the private
  38. key, but this information seems rather useless - if this is important pass
  39. public_key and private_key seperately in 2 function calls */
  40. if (private_key) {
  41. ge_scalarmult_base(&A, private_key);
  42. } else {
  43. /* unpack public key into T */
  44. ge_frombytes_negate_vartime(&public_key_unpacked, public_key);
  45. fe_neg(public_key_unpacked.X, public_key_unpacked.X); /* undo negate */
  46. fe_neg(public_key_unpacked.T, public_key_unpacked.T); /* undo negate */
  47. ge_p3_to_cached(&T, &public_key_unpacked);
  48. /* calculate n*B */
  49. ge_scalarmult_base(&nB, n);
  50. /* A = n*B + T */
  51. ge_add(&A_p1p1, &nB, &T);
  52. ge_p1p1_to_p3(&A, &A_p1p1);
  53. }
  54. /* pack public key */
  55. ge_p3_tobytes(public_key, &A);
  56. }
  57. }