ed25519.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. # The reference Ed25519 software is in the public domain.
  2. # Source: https://ed25519.cr.yp.to/python/ed25519.py
  3. # Date accessed: 2 Nov. 2016
  4. b = 256
  5. q = 2**255 - 19
  6. l = 2**252 + 27742317777372353535851937790883648493
  7. def expmod(b, e, m):
  8. if e == 0:
  9. return 1
  10. t = expmod(b, e//2, m)**2 % m
  11. if e & 1:
  12. t = (t*b) % m
  13. return t
  14. def inv(x):
  15. return expmod(x, q-2, q)
  16. d = -121665 * inv(121666)
  17. I = expmod(2, (q-1)//4, q)
  18. def xrecover(y):
  19. xx = (y*y-1) * inv(d*y*y+1)
  20. x = expmod(xx, (q+3)//8, q)
  21. if (x*x - xx) % q != 0:
  22. x = (x*I) % q
  23. if x % 2 != 0:
  24. x = q-x
  25. return x
  26. By = 4 * inv(5)
  27. Bx = xrecover(By)
  28. B = [Bx%q, By%q]
  29. def edwards(P, Q):
  30. x1 = P[0]
  31. y1 = P[1]
  32. x2 = Q[0]
  33. y2 = Q[1]
  34. x3 = (x1*y2+x2*y1) * inv(1+d*x1*x2*y1*y2)
  35. y3 = (y1*y2+x1*x2) * inv(1-d*x1*x2*y1*y2)
  36. return [x3%q, y3%q]
  37. def scalarmult(P, e):
  38. if e == 0:
  39. return [0, 1]
  40. Q = scalarmult(P, e//2)
  41. Q = edwards(Q, Q)
  42. if e & 1:
  43. Q = edwards(Q, P)
  44. return Q
  45. def encodepoint(P):
  46. x = P[0]
  47. y = P[1]
  48. bits = [(y >> i) & 1 for i in range(b-1)] + [x & 1]
  49. return bytes([sum([bits[i * 8 + j] << j for j in range(8)]) for i in range(b//8)])