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.
 
 
 
 
 

120 lines
2.3 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 isqrt(x):
  32. assert(x.is_square())
  33. if x == 0: return 0
  34. else: return 1/sqrt(x)
  35. def decaf_encode_from_E_c(X,Y):
  36. Z = F.random_element()
  37. T = X*Y*Z
  38. X = X*Z
  39. Y = Y*Z
  40. assert X^2 + Y^2 == Z^2 + d*T^2
  41. # Precompute
  42. sd = sqrt(F(1-d))
  43. zx = Z^2-X^2
  44. TZ = T*Z
  45. assert zx.is_square
  46. ooAll = isqrt(zx*TZ^2)
  47. osx = ooAll * TZ
  48. ooTZ = ooAll * zx * osx
  49. floop = qpositive(T^2 * ooTZ)
  50. if floop:
  51. frob = zx * ooTZ
  52. else:
  53. frob = sd
  54. Y = -X
  55. osx *= frob
  56. if qpositive(-2*osx*Z) != floop: osx = -osx
  57. s = Y*(ooTZ*Z + osx)
  58. if not qpositive(s): s = -s
  59. return s
  60. def is_rotation((X,Y),(x,y)):
  61. return x*Y == X*y or x*X == -y*Y
  62. def decaf_decode_to_E(s):
  63. assert qpositive(s)
  64. t = sqrt(s^4 + (2-4*d)*s^2 + 1)
  65. if not qpositive(t/s): t = -t
  66. X,Y = 2*s / (1+s^2), (1-s^2) / t
  67. assert qpositive(X*Y)
  68. return X,Y
  69. def decaf_decode_to_E_c(s):
  70. assert qpositive(s)
  71. s2 = s^2
  72. s21 = 1+s2
  73. t2 = s21^2 - 4*d*s2
  74. alt = s21*s
  75. the = isqrt(t2*alt^2)
  76. oot = the * alt
  77. the *= t2
  78. tos = the * s21
  79. X = 2 * (tos-the) * oot
  80. Y = (1-s2) * oot
  81. if not qpositive(tos): Y = -Y
  82. assert qpositive(X*Y)
  83. return X,Y
  84. def test():
  85. P = 2*M.random_point()
  86. X,Y = M_to_E(P)
  87. s = decaf_encode_from_E(X,Y)
  88. assert s == decaf_encode_from_E_c(X,Y)
  89. XX,YY = decaf_decode_to_E(s)
  90. XX2,YY2 = decaf_decode_to_E_c(s)
  91. assert is_rotation((X,Y),(XX,YY))
  92. assert is_rotation((X,Y),(XX2,YY2))