curve25519_donna_helpers.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. Public domain by Andrew M. <liquidsun@gmail.com>
  3. See: https://github.com/floodyberry/curve25519-donna
  4. Curve25519 implementation agnostic helpers
  5. */
  6. #include "ed25519_donna.h"
  7. /*
  8. * In: b = 2^5 - 2^0
  9. * Out: b = 2^250 - 2^0
  10. */
  11. void curve25519_pow_two5mtwo0_two250mtwo0(bignum25519 b) {
  12. bignum25519 ALIGN(16) t0 = {0}, c = {0};
  13. /* 2^5 - 2^0 */ /* b */
  14. /* 2^10 - 2^5 */ curve25519_square_times(t0, b, 5);
  15. /* 2^10 - 2^0 */ curve25519_mul_noinline(b, t0, b);
  16. /* 2^20 - 2^10 */ curve25519_square_times(t0, b, 10);
  17. /* 2^20 - 2^0 */ curve25519_mul_noinline(c, t0, b);
  18. /* 2^40 - 2^20 */ curve25519_square_times(t0, c, 20);
  19. /* 2^40 - 2^0 */ curve25519_mul_noinline(t0, t0, c);
  20. /* 2^50 - 2^10 */ curve25519_square_times(t0, t0, 10);
  21. /* 2^50 - 2^0 */ curve25519_mul_noinline(b, t0, b);
  22. /* 2^100 - 2^50 */ curve25519_square_times(t0, b, 50);
  23. /* 2^100 - 2^0 */ curve25519_mul_noinline(c, t0, b);
  24. /* 2^200 - 2^100 */ curve25519_square_times(t0, c, 100);
  25. /* 2^200 - 2^0 */ curve25519_mul_noinline(t0, t0, c);
  26. /* 2^250 - 2^50 */ curve25519_square_times(t0, t0, 50);
  27. /* 2^250 - 2^0 */ curve25519_mul_noinline(b, t0, b);
  28. }
  29. /*
  30. * z^(p - 2) = z(2^255 - 21)
  31. */
  32. void curve25519_recip(bignum25519 out, const bignum25519 z) {
  33. bignum25519 ALIGN(16) a = {0}, t0 = {0}, b = {0};
  34. /* 2 */ curve25519_square_times(a, z, 1); /* a = 2 */
  35. /* 8 */ curve25519_square_times(t0, a, 2);
  36. /* 9 */ curve25519_mul_noinline(b, t0, z); /* b = 9 */
  37. /* 11 */ curve25519_mul_noinline(a, b, a); /* a = 11 */
  38. /* 22 */ curve25519_square_times(t0, a, 1);
  39. /* 2^5 - 2^0 = 31 */ curve25519_mul_noinline(b, t0, b);
  40. /* 2^250 - 2^0 */ curve25519_pow_two5mtwo0_two250mtwo0(b);
  41. /* 2^255 - 2^5 */ curve25519_square_times(b, b, 5);
  42. /* 2^255 - 21 */ curve25519_mul_noinline(out, b, a);
  43. }
  44. /*
  45. * z^((p-5)/8) = z^(2^252 - 3)
  46. */
  47. void curve25519_pow_two252m3(bignum25519 two252m3, const bignum25519 z) {
  48. bignum25519 ALIGN(16) b, c, t0;
  49. /* 2 */ curve25519_square_times(c, z, 1); /* c = 2 */
  50. /* 8 */ curve25519_square_times(t0, c, 2); /* t0 = 8 */
  51. /* 9 */ curve25519_mul_noinline(b, t0, z); /* b = 9 */
  52. /* 11 */ curve25519_mul_noinline(c, b, c); /* c = 11 */
  53. /* 22 */ curve25519_square_times(t0, c, 1);
  54. /* 2^5 - 2^0 = 31 */ curve25519_mul_noinline(b, t0, b);
  55. /* 2^250 - 2^0 */ curve25519_pow_two5mtwo0_two250mtwo0(b);
  56. /* 2^252 - 2^2 */ curve25519_square_times(b, b, 2);
  57. /* 2^252 - 3 */ curve25519_mul_noinline(two252m3, b, z);
  58. }