You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

61 lines
1.2 KiB

  1. # This is as sketch of how to decaffeinate Curve25519
  2. F = GF(2^255-19)
  3. d = -121665
  4. M = EllipticCurve(F,[0,2-4*d,0,1,0])
  5. def maybe(): return randint(0,1)
  6. def qpositive(x):
  7. return int(x) <= (2^255-19-1)/2
  8. def M_to_E(P):
  9. # P must be even
  10. (x,y) = P.xy()
  11. assert x.is_square()
  12. s = sqrt(x)
  13. if s == 0: t = 1
  14. else: t = y/s
  15. X,Y = 2*s / (1+s^2), (1-s^2) / t
  16. if maybe(): X,Y = -X,-Y
  17. if maybe(): X,Y = Y,-X
  18. # OK, have point in ed
  19. return X,Y
  20. def decaf_encode_from_E(X,Y):
  21. assert X^2 + Y^2 == 1 + d*X^2*Y^2
  22. if not qpositive(X*Y): X,Y = Y,-X
  23. assert qpositive(X*Y)
  24. assert (1-X^2).is_square()
  25. sx = sqrt(1-X^2)
  26. tos = -2*sx/X/Y
  27. if not qpositive(tos): sx = -sx
  28. s = (1 + sx) / X
  29. if not qpositive(s): s = -s
  30. return s
  31. def is_rotation((X,Y),(x,y)):
  32. return x*Y == X*y or x*X == -y*Y
  33. def decaf_decode_to_E(s):
  34. assert qpositive(s)
  35. t = sqrt(s^4 + (2-4*d)*s^2 + 1)
  36. if not qpositive(t/s): t = -t
  37. X,Y = 2*s / (1+s^2), (1-s^2) / t
  38. assert qpositive(X*Y)
  39. return X,Y
  40. def test():
  41. P = 2*M.random_point()
  42. X,Y = M_to_E(P)
  43. s = decaf_encode_from_E(X,Y)
  44. XX,YY = decaf_decode_to_E(s)
  45. assert is_rotation((X,Y),(XX,YY))