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.
 
 
 
 
 

466 lines
14 KiB

  1. import binascii
  2. class InvalidEncodingException(Exception): pass
  3. class NotOnCurveException(Exception): pass
  4. class SpecException(Exception): pass
  5. def lobit(x): return int(x) & 1
  6. def hibit(x): return lobit(2*x)
  7. def negative(x): return lobit(x)
  8. def enc_le(x,n): return bytearray([int(x)>>(8*i) & 0xFF for i in xrange(n)])
  9. def dec_le(x): return sum(b<<(8*i) for i,b in enumerate(x))
  10. def randombytes(n): return bytearray([randint(0,255) for _ in range(n)])
  11. def optimized_version_of(spec):
  12. """Decorator: This function is an optimized version of some specification"""
  13. def decorator(f):
  14. def wrapper(self,*args,**kwargs):
  15. try: spec_ans = getattr(self,spec,spec)(*args,**kwargs),None
  16. except Exception as e: spec_ans = None,e
  17. try: opt_ans = f(self,*args,**kwargs),None
  18. except Exception as e: opt_ans = None,e
  19. if spec_ans[1] is None and opt_ans[1] is not None:
  20. raise
  21. #raise SpecException("Mismatch in %s: spec returned %s but opt threw %s"
  22. # % (f.__name__,str(spec_ans[0]),str(opt_ans[1])))
  23. if spec_ans[1] is not None and opt_ans[1] is None:
  24. raise
  25. #raise SpecException("Mismatch in %s: spec threw %s but opt returned %s"
  26. # % (f.__name__,str(spec_ans[1]),str(opt_ans[0])))
  27. if spec_ans[0] != opt_ans[0]:
  28. raise SpecException("Mismatch in %s: %s != %s"
  29. % (f.__name__,str(spec_ans[0]),str(opt_ans[0])))
  30. if opt_ans[1] is not None: raise
  31. else: return opt_ans[0]
  32. wrapper.__name__ = f.__name__
  33. return wrapper
  34. return decorator
  35. def xsqrt(x,exn=InvalidEncodingException("Not on curve")):
  36. """Return sqrt(x)"""
  37. if not is_square(x): raise exn
  38. s = sqrt(x)
  39. if negative(s): s=-s
  40. return s
  41. def isqrt(x,exn=InvalidEncodingException("Not on curve")):
  42. """Return 1/sqrt(x)"""
  43. if x==0: return 0
  44. if not is_square(x): raise exn
  45. return 1/sqrt(x)
  46. def isqrt_i(x):
  47. """Return 1/sqrt(x) or 1/sqrt(zeta * x)"""
  48. if x==0: return 0
  49. gen = x.parent(-1)
  50. while is_square(gen): gen = sqrt(gen)
  51. if is_square(x): return True,1/sqrt(x)
  52. else: return False,1/sqrt(x*gen)
  53. class QuotientEdwardsPoint(object):
  54. """Abstract class for point an a quotiented Edwards curve; needs F,a,d,cofactor to work"""
  55. def __init__(self,x=0,y=1):
  56. x = self.x = self.F(x)
  57. y = self.y = self.F(y)
  58. if y^2 + self.a*x^2 != 1 + self.d*x^2*y^2:
  59. raise NotOnCurveException(str(self))
  60. def __repr__(self):
  61. return "%s(0x%x,0x%x)" % (self.__class__.__name__, self.x, self.y)
  62. def __iter__(self):
  63. yield self.x
  64. yield self.y
  65. def __add__(self,other):
  66. x,y = self
  67. X,Y = other
  68. a,d = self.a,self.d
  69. return self.__class__(
  70. (x*Y+y*X)/(1+d*x*y*X*Y),
  71. (y*Y-a*x*X)/(1-d*x*y*X*Y)
  72. )
  73. def __neg__(self): return self.__class__(-self.x,self.y)
  74. def __sub__(self,other): return self + (-other)
  75. def __rmul__(self,other): return self*other
  76. def __eq__(self,other):
  77. """NB: this is the only method that is different from the usual one"""
  78. x,y = self
  79. X,Y = other
  80. return x*Y == X*y or (self.cofactor==8 and -self.a*x*X == y*Y)
  81. def __ne__(self,other): return not (self==other)
  82. def __mul__(self,exp):
  83. exp = int(exp)
  84. if exp < 0: exp,self = -exp,-self
  85. total = self.__class__()
  86. work = self
  87. while exp != 0:
  88. if exp & 1: total += work
  89. work += work
  90. exp >>= 1
  91. return total
  92. def xyzt(self):
  93. x,y = self
  94. z = self.F.random_element()
  95. return x*z,y*z,z,x*y*z
  96. def torque(self):
  97. """Apply cofactor group, except keeping the point even"""
  98. if self.cofactor == 8:
  99. if self.a == -1: return self.__class__(self.y*self.i, self.x*self.i)
  100. if self.a == 1: return self.__class__(-self.y, self.x)
  101. else:
  102. return self.__class__(-self.x, -self.y)
  103. # Utility functions
  104. @classmethod
  105. def bytesToGf(cls,bytes,mustBeProper=True,mustBePositive=False):
  106. """Convert little-endian bytes to field element, sanity check length"""
  107. if len(bytes) != cls.encLen:
  108. raise InvalidEncodingException("wrong length %d" % len(bytes))
  109. s = dec_le(bytes)
  110. if mustBeProper and s >= cls.F.modulus():
  111. raise InvalidEncodingException("%d out of range!" % s)
  112. s = cls.F(s)
  113. if mustBePositive and negative(s):
  114. raise InvalidEncodingException("%d is negative!" % s)
  115. return s
  116. @classmethod
  117. def gfToBytes(cls,x,mustBePositive=False):
  118. """Convert little-endian bytes to field element, sanity check length"""
  119. if negative(x) and mustBePositive: x = -x
  120. return enc_le(x,cls.encLen)
  121. class RistrettoPoint(QuotientEdwardsPoint):
  122. """The new Ristretto group"""
  123. def encodeSpec(self):
  124. """Unoptimized specification for encoding"""
  125. x,y = self
  126. if self.cofactor==8 and (negative(x*y) or y==0): (x,y) = self.torque()
  127. if y == -1: y = 1 # Avoid divide by 0; doesn't affect impl
  128. if negative(x): x,y = -x,-y
  129. s = xsqrt(self.a*(y-1)/(y+1),exn=Exception("Unimplemented: point is odd: " + str(self)))
  130. return self.gfToBytes(s)
  131. @classmethod
  132. def decodeSpec(cls,s):
  133. """Unoptimized specification for decoding"""
  134. s = cls.bytesToGf(s,mustBePositive=True)
  135. a,d = cls.a,cls.d
  136. x = xsqrt(4*s^2 / (a*d*(1+a*s^2)^2 - (1-a*s^2)^2))
  137. y = (1+a*s^2) / (1-a*s^2)
  138. if cls.cofactor==8 and (negative(x*y) or y==0):
  139. raise InvalidEncodingException("x*y has high bit")
  140. return cls(x,y)
  141. @optimized_version_of("encodeSpec")
  142. def encode(self):
  143. """Encode, optimized version"""
  144. a,d = self.a,self.d
  145. x,y,z,t = self.xyzt()
  146. u1 = a*(y+z)*(y-z)
  147. u2 = x*y # = t*z
  148. isr = isqrt(u1*u2^2)
  149. i1 = isr*u1
  150. i2 = isr*u2
  151. z_inv = i1*i2*t
  152. if self.cofactor==8 and negative(t*z_inv):
  153. if a==-1: x,y = y*self.i,x*self.i
  154. else: x,y = -y,x # TODO: test
  155. den_inv = self.magic * i1
  156. else:
  157. den_inv = i2
  158. if negative(x*z_inv): y = -y
  159. s = (z-y) * den_inv
  160. return self.gfToBytes(s,mustBePositive=True)
  161. @classmethod
  162. @optimized_version_of("decodeSpec")
  163. def decode(cls,s):
  164. """Decode, optimized version"""
  165. s = cls.bytesToGf(s,mustBePositive=True)
  166. a,d = cls.a,cls.d
  167. yden = 1-a*s^2
  168. ynum = 1+a*s^2
  169. yden_sqr = yden^2
  170. xden_sqr = a*d*ynum^2 - yden_sqr
  171. isr = isqrt(xden_sqr * yden_sqr)
  172. xden_inv = isr * yden
  173. yden_inv = xden_inv * isr * xden_sqr
  174. x = 2*s*xden_inv
  175. if negative(x): x = -x
  176. y = ynum * yden_inv
  177. if cls.cofactor==8 and (negative(x*y) or y==0):
  178. raise InvalidEncodingException("x*y is invalid: %d, %d" % (x,y))
  179. return cls(x,y)
  180. @classmethod
  181. def fromJacobiQuartic(cls,s,t,sgn=1):
  182. """Convert point from its Jacobi Quartic representation"""
  183. a,d = cls.a,cls.d
  184. assert s^4 - 2*cls.a*(1-2*d/(d-a))*s^2 + 1 == t^2
  185. x = 2*s*cls.magic / t
  186. if negative(x): x = -x # TODO: doesn't work without resolving x
  187. y = (1+a*s^2) / (1-a*s^2)
  188. return cls(sgn*x,y)
  189. @classmethod
  190. def elligatorSpec(cls,r0):
  191. a,d = cls.a,cls.d
  192. r = cls.qnr * cls.bytesToGf(r0)^2
  193. den = (d*r-a)*(a*r-d)
  194. n1 = cls.a*(r+1)*(a+d)*(d-a)/den
  195. n2 = r*n1
  196. if is_square(n1):
  197. sgn,s,t = 1,xsqrt(n1), -(r-1)*(a+d)^2 / den - 1
  198. else:
  199. sgn,s,t = -1,xsqrt(n2), r*(r-1)*(a+d)^2 / den - 1
  200. return cls.fromJacobiQuartic(s,t,sgn)
  201. @classmethod
  202. @optimized_version_of("elligatorSpec")
  203. def elligator(cls,r0):
  204. a,d = cls.a,cls.d
  205. r0 = cls.bytesToGf(r0)
  206. r = cls.qnr * r0^2
  207. den = (d*r-a)*(a*r-d)
  208. num = cls.a*(r+1)*(a+d)*(d-a)
  209. iss,isri = isqrt_i(num*den)
  210. if iss: sgn,twiddle = 1,1
  211. else: sgn,twiddle = -1,r0*cls.qnr
  212. isri *= twiddle
  213. s = isri*num
  214. t = isri*s*(r-1)*(d+a)^2 + sgn
  215. return cls.fromJacobiQuartic(s,t,sgn)
  216. class Decaf_1_1_Point(QuotientEdwardsPoint):
  217. """Like current decaf but tweaked for simplicity"""
  218. def encodeSpec(self):
  219. """Unoptimized specification for encoding"""
  220. a,d = self.a,self.d
  221. x,y = self
  222. if x==0 or y==0: return(self.gfToBytes(0))
  223. if self.cofactor==8 and negative(x*y*self.isoMagic):
  224. x,y = self.torque()
  225. isr2 = isqrt(a*(y^2-1)) * sqrt(a*d-1)
  226. sr = xsqrt(1-a*x^2)
  227. assert sr in [isr2*x*y,-isr2*x*y]
  228. altx = 1/isr2*self.isoMagic
  229. if negative(altx): s = (1+x*y*isr2)/(a*x)
  230. else: s = (1-x*y*isr2)/(a*x)
  231. return self.gfToBytes(s,mustBePositive=True)
  232. @classmethod
  233. def decodeSpec(cls,s):
  234. """Unoptimized specification for decoding"""
  235. a,d = cls.a,cls.d
  236. s = cls.bytesToGf(s,mustBePositive=True)
  237. if s==0: return cls()
  238. isr = isqrt(s^4 + 2*(a-2*d)*s^2 + 1)
  239. altx = 2*s*isr*cls.isoMagic
  240. if negative(altx): isr = -isr
  241. x = 2*s / (1+a*s^2)
  242. y = (1-a*s^2) * isr
  243. if cls.cofactor==8 and (negative(x*y*cls.isoMagic) or y==0):
  244. raise InvalidEncodingException("x*y is invalid: %d, %d" % (x,y))
  245. return cls(x,y)
  246. @optimized_version_of("encodeSpec")
  247. def encode(self):
  248. """Encode, optimized version"""
  249. a,d = self.a,self.d
  250. x,y,z,t = self.xyzt()
  251. if x==0 or y==0: return(self.gfToBytes(0))
  252. num = (z+y)*(z-y)
  253. den = t*z
  254. tmp = isqrt(num*(a-d)*den^2)
  255. if self.cofactor==8 and negative(tmp^2*den*num*(a-d)*t^2*self.isoMagic):
  256. den,num = num,den
  257. tmp *= sqrt(a-d) # witness that cofactor is 8
  258. yisr = x*sqrt(a)
  259. toggle = (a==1)
  260. else:
  261. yisr = y*(a*d-1)
  262. toggle = False
  263. tiisr = tmp*num
  264. altx = tiisr*t*self.isoMagic
  265. if negative(altx) != toggle: tiisr =- tiisr
  266. s = tmp*den*yisr*(tiisr*z - 1)
  267. return self.gfToBytes(s,mustBePositive=True)
  268. @classmethod
  269. @optimized_version_of("decodeSpec")
  270. def decode(cls,s):
  271. """Decode, optimized version"""
  272. return cls.decodeSpec(s) # TODO
  273. class Ed25519Point(RistrettoPoint):
  274. F = GF(2^255-19)
  275. d = F(-121665/121666)
  276. a = F(-1)
  277. i = sqrt(F(-1))
  278. qnr = i
  279. magic = isqrt(a*d-1)
  280. cofactor = 8
  281. encLen = 32
  282. @classmethod
  283. def base(cls):
  284. y = cls.F(4/5)
  285. x = sqrt((y^2-1)/(cls.d*y^2+1))
  286. if lobit(x): x = -x
  287. return cls(x,y)
  288. class IsoEd448Point(RistrettoPoint):
  289. F = GF(2^448-2^224-1)
  290. d = F(39082/39081)
  291. a = F(1)
  292. qnr = -1
  293. magic = isqrt(a*d-1)
  294. cofactor = 4
  295. encLen = 56
  296. @classmethod
  297. def base(cls):
  298. # = ..., -3/2
  299. return cls.decodeSpec(bytearray(binascii.unhexlify(
  300. "00000000000000000000000000000000000000000000000000000000"+
  301. "fdffffffffffffffffffffffffffffffffffffffffffffffffffffff")))
  302. class TwistedEd448GoldilocksPoint(Decaf_1_1_Point):
  303. F = GF(2^448-2^224-1)
  304. d = F(-39082)
  305. a = F(-1)
  306. qnr = -1
  307. magic = isqrt(a*d-1)
  308. cofactor = 4
  309. encLen = 56
  310. isoMagic = IsoEd448Point.magic
  311. @classmethod
  312. def base(cls):
  313. return cls.decodeSpec(bytearray(binascii.unhexlify(
  314. "00000000000000000000000000000000000000000000000000000000"+
  315. "fdffffffffffffffffffffffffffffffffffffffffffffffffffffff")))
  316. class Ed448GoldilocksPoint(Decaf_1_1_Point):
  317. F = GF(2^448-2^224-1)
  318. d = F(-39081)
  319. a = F(1)
  320. qnr = -1
  321. magic = isqrt(a*d-1)
  322. cofactor = 4
  323. encLen = 56
  324. isoMagic = IsoEd448Point.magic
  325. @classmethod
  326. def base(cls):
  327. return cls.decodeSpec(bytearray(binascii.unhexlify(
  328. "00000000000000000000000000000000000000000000000000000000"+
  329. "fdffffffffffffffffffffffffffffffffffffffffffffffffffffff")))
  330. class IsoEd25519Point(Decaf_1_1_Point):
  331. # TODO: twisted iso too!
  332. # TODO: twisted iso might have to IMAGINE_TWIST or whatever
  333. F = GF(2^255-19)
  334. d = F(-121665)
  335. a = F(1)
  336. i = sqrt(F(-1))
  337. qnr = i
  338. magic = isqrt(a*d-1)
  339. cofactor = 8
  340. encLen = 32
  341. isoMagic = Ed25519Point.magic
  342. isoA = Ed25519Point.a
  343. @classmethod
  344. def base(cls):
  345. return cls.decodeSpec(Ed25519Point.base().encode())
  346. class TestFailedException(Exception): pass
  347. def test(cls,n):
  348. # TODO: test corner cases like 0,1,i
  349. P = cls.base()
  350. Q = cls()
  351. for i in xrange(n):
  352. #print binascii.hexlify(Q.encode())
  353. QQ = cls.decode(Q.encode())
  354. if QQ != Q: raise TestFailedException("Round trip %s != %s" % (str(QQ),str(Q)))
  355. QT = Q
  356. QE = Q.encode()
  357. for h in xrange(cls.cofactor):
  358. QT = QT.torque()
  359. if QT.encode() != QE:
  360. raise TestFailedException("Can't torque %s,%d" % (str(Q),h+1))
  361. Q0 = Q + P
  362. if Q0 == Q: raise TestFailedException("Addition doesn't work")
  363. if Q0-P != Q: raise TestFailedException("Subtraction doesn't work")
  364. r = randint(1,1000)
  365. Q1 = Q0*r
  366. Q2 = Q0*(r+1)
  367. if Q1 + Q0 != Q2: raise TestFailedException("Scalarmul doesn't work")
  368. Q = Q1
  369. test(Ed25519Point,100)
  370. test(IsoEd25519Point,100)
  371. test(IsoEd448Point,100)
  372. test(TwistedEd448GoldilocksPoint,100)
  373. test(Ed448GoldilocksPoint,100)
  374. def gangtest(classes,n):
  375. for i in xrange(n):
  376. rets = [bytes((cls.base()*i).encode()) for cls in classes]
  377. if len(set(rets)) != 1:
  378. print "Divergence at %d" % i
  379. for c,ret in zip(classes,rets):
  380. print c,binascii.hexlify(ret)
  381. print
  382. gangtest([IsoEd448Point,TwistedEd448GoldilocksPoint,Ed448GoldilocksPoint],100)
  383. gangtest([Ed25519Point,IsoEd25519Point],100)
  384. def testElligator(cls,n):
  385. for i in xrange(n):
  386. cls.elligator(randombytes(cls.encLen))
  387. testElligator(Ed25519Point,100)
  388. testElligator(IsoEd448Point,100)
  389. # testElligator(Ed448GoldilocksPoint,100)
  390. # testElligator(TwistedEd448GoldilocksPoint,100)