ed25519.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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: return 1
  9. t = expmod(b, e//2, m)**2 % m
  10. if e & 1: t = (t*b) % m
  11. return t
  12. def inv(x):
  13. return expmod(x, q-2, q)
  14. d = -121665 * inv(121666)
  15. I = expmod(2, (q-1)//4, q)
  16. def xrecover(y):
  17. xx = (y*y-1) * inv(d*y*y+1)
  18. x = expmod(xx, (q+3)//8, q)
  19. if (x*x - xx) % q != 0: x = (x*I) % q
  20. if x % 2 != 0: x = q-x
  21. return x
  22. By = 4 * inv(5)
  23. Bx = xrecover(By)
  24. B = [Bx%q, By%q]
  25. def edwards(P, Q):
  26. x1 = P[0]
  27. y1 = P[1]
  28. x2 = Q[0]
  29. y2 = Q[1]
  30. x3 = (x1*y2+x2*y1) * inv(1+d*x1*x2*y1*y2)
  31. y3 = (y1*y2+x1*x2) * inv(1-d*x1*x2*y1*y2)
  32. return [x3%q, y3%q]
  33. def scalarmult(P, e):
  34. if e == 0: return [0, 1]
  35. Q = scalarmult(P, e//2)
  36. Q = edwards(Q, Q)
  37. if e & 1: Q = edwards(Q, P)
  38. return Q
  39. def encodepoint(P):
  40. x = P[0]
  41. y = P[1]
  42. bits = [(y >> i) & 1 for i in range(b-1)] + [x & 1]
  43. return bytes([sum([bits[i * 8 + j] << j for j in range(8)]) for i in range(b//8)])