ed25519.py 1.2 KB

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