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.
 
 
 
 
 

865 lines
28 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. def pr(x):
  16. if isinstance(x,bytearray): return binascii.hexlify(x)
  17. else: return str(x)
  18. try: spec_ans = getattr(self,spec,spec)(*args,**kwargs),None
  19. except Exception as e: spec_ans = None,e
  20. try: opt_ans = f(self,*args,**kwargs),None
  21. except Exception as e: opt_ans = None,e
  22. if spec_ans[1] is None and opt_ans[1] is not None:
  23. raise
  24. #raise SpecException("Mismatch in %s: spec returned %s but opt threw %s"
  25. # % (f.__name__,str(spec_ans[0]),str(opt_ans[1])))
  26. if spec_ans[1] is not None and opt_ans[1] is None:
  27. raise
  28. #raise SpecException("Mismatch in %s: spec threw %s but opt returned %s"
  29. # % (f.__name__,str(spec_ans[1]),str(opt_ans[0])))
  30. if spec_ans[0] != opt_ans[0]:
  31. raise SpecException("Mismatch in %s: %s != %s"
  32. % (f.__name__,pr(spec_ans[0]),pr(opt_ans[0])))
  33. if opt_ans[1] is not None: raise
  34. else: return opt_ans[0]
  35. wrapper.__name__ = f.__name__
  36. return wrapper
  37. return decorator
  38. def xsqrt(x,exn=InvalidEncodingException("Not on curve")):
  39. """Return sqrt(x)"""
  40. if not is_square(x): raise exn
  41. s = sqrt(x)
  42. if negative(s): s=-s
  43. return s
  44. def isqrt(x,exn=InvalidEncodingException("Not on curve")):
  45. """Return 1/sqrt(x)"""
  46. if x==0: return 0
  47. if not is_square(x): raise exn
  48. s = sqrt(x)
  49. #if negative(s): s=-s
  50. return 1/s
  51. def inv0(x): return 1/x if x != 0 else 0
  52. def isqrt_i(x):
  53. """Return 1/sqrt(x) or 1/sqrt(zeta * x)"""
  54. if x==0: return True,0
  55. gen = x.parent(-1)
  56. while is_square(gen): gen = sqrt(gen)
  57. if is_square(x): return True,1/sqrt(x)
  58. else: return False,1/sqrt(x*gen)
  59. class QuotientEdwardsPoint(object):
  60. """Abstract class for point an a quotiented Edwards curve; needs F,a,d,cofactor to work"""
  61. def __init__(self,x=0,y=1):
  62. x = self.x = self.F(x)
  63. y = self.y = self.F(y)
  64. if y^2 + self.a*x^2 != 1 + self.d*x^2*y^2:
  65. raise NotOnCurveException(str(self))
  66. def __repr__(self):
  67. return "%s(0x%x,0x%x)" % (self.__class__.__name__, self.x, self.y)
  68. def __iter__(self):
  69. yield self.x
  70. yield self.y
  71. def __add__(self,other):
  72. x,y = self
  73. X,Y = other
  74. a,d = self.a,self.d
  75. return self.__class__(
  76. (x*Y+y*X)/(1+d*x*y*X*Y),
  77. (y*Y-a*x*X)/(1-d*x*y*X*Y)
  78. )
  79. def __neg__(self): return self.__class__(-self.x,self.y)
  80. def __sub__(self,other): return self + (-other)
  81. def __rmul__(self,other): return self*other
  82. def __eq__(self,other):
  83. """NB: this is the only method that is different from the usual one"""
  84. x,y = self
  85. X,Y = other
  86. return x*Y == X*y or (self.cofactor==8 and -self.a*x*X == y*Y)
  87. def __ne__(self,other): return not (self==other)
  88. def __mul__(self,exp):
  89. exp = int(exp)
  90. if exp < 0: exp,self = -exp,-self
  91. total = self.__class__()
  92. work = self
  93. while exp != 0:
  94. if exp & 1: total += work
  95. work += work
  96. exp >>= 1
  97. return total
  98. def xyzt(self):
  99. x,y = self
  100. z = self.F.random_element()
  101. return x*z,y*z,z,x*y*z
  102. def torque(self):
  103. """Apply cofactor group, except keeping the point even"""
  104. if self.cofactor == 8:
  105. if self.a == -1: return self.__class__(self.y*self.i, self.x*self.i)
  106. if self.a == 1: return self.__class__(-self.y, self.x)
  107. else:
  108. return self.__class__(-self.x, -self.y)
  109. def doubleAndEncodeSpec(self):
  110. return (self+self).encode()
  111. # Utility functions
  112. @classmethod
  113. def bytesToGf(cls,bytes,mustBeProper=True,mustBePositive=False,maskHiBits=False):
  114. """Convert little-endian bytes to field element, sanity check length"""
  115. if len(bytes) != cls.encLen:
  116. raise InvalidEncodingException("wrong length %d" % len(bytes))
  117. s = dec_le(bytes)
  118. if mustBeProper and s >= cls.F.order():
  119. raise InvalidEncodingException("%d out of range!" % s)
  120. bitlen = int(ceil(log(cls.F.order())/log(2)))
  121. if maskHiBits: s &= 2^bitlen-1
  122. s = cls.F(s)
  123. if mustBePositive and negative(s):
  124. raise InvalidEncodingException("%d is negative!" % s)
  125. return s
  126. @classmethod
  127. def gfToBytes(cls,x,mustBePositive=False):
  128. """Convert little-endian bytes to field element, sanity check length"""
  129. if negative(x) and mustBePositive: x = -x
  130. return enc_le(x,cls.encLen)
  131. class RistrettoPoint(QuotientEdwardsPoint):
  132. """The new Ristretto group"""
  133. def encodeSpec(self):
  134. """Unoptimized specification for encoding"""
  135. x,y = self
  136. if self.cofactor==8 and (negative(x*y) or y==0): (x,y) = self.torque()
  137. if y == -1: y = 1 # Avoid divide by 0; doesn't affect impl
  138. if negative(x): x,y = -x,-y
  139. s = xsqrt(self.mneg*(1-y)/(1+y),exn=Exception("Unimplemented: point is odd: " + str(self)))
  140. return self.gfToBytes(s)
  141. @classmethod
  142. def decodeSpec(cls,s):
  143. """Unoptimized specification for decoding"""
  144. s = cls.bytesToGf(s,mustBePositive=True)
  145. a,d = cls.a,cls.d
  146. x = xsqrt(4*s^2 / (a*d*(1+a*s^2)^2 - (1-a*s^2)^2))
  147. y = (1+a*s^2) / (1-a*s^2)
  148. if cls.cofactor==8 and (negative(x*y) or y==0):
  149. raise InvalidEncodingException("x*y has high bit")
  150. return cls(x,y)
  151. @optimized_version_of("encodeSpec")
  152. def encode(self):
  153. """Encode, optimized version"""
  154. a,d,mneg = self.a,self.d,self.mneg
  155. x,y,z,t = self.xyzt()
  156. if self.cofactor==8:
  157. u1 = mneg*(z+y)*(z-y)
  158. u2 = x*y # = t*z
  159. isr = isqrt(u1*u2^2)
  160. i1 = isr*u1 # sqrt(mneg*(z+y)*(z-y))/(x*y)
  161. i2 = isr*u2 # 1/sqrt(a*(y+z)*(y-z))
  162. z_inv = i1*i2*t # 1/z
  163. if negative(t*z_inv):
  164. if a==-1:
  165. x,y = y*self.i,x*self.i
  166. den_inv = self.magic * i1
  167. else:
  168. x,y = -y,x
  169. den_inv = self.i * self.magic * i1
  170. else:
  171. den_inv = i2
  172. if negative(x*z_inv): y = -y
  173. s = (z-y) * den_inv
  174. else:
  175. num = mneg*(z+y)*(z-y)
  176. isr = isqrt(num*y^2)
  177. if negative(isr^2*num*y*t): y = -y
  178. s = isr*y*(z-y)
  179. return self.gfToBytes(s,mustBePositive=True)
  180. @optimized_version_of("doubleAndEncodeSpec")
  181. def doubleAndEncode(self):
  182. X,Y,Z,T = self.xyzt()
  183. a,d,mneg = self.a,self.d,self.mneg
  184. if self.cofactor==8:
  185. e = 2*X*Y
  186. f = Z^2+d*T^2
  187. g = Y^2-a*X^2
  188. h = Z^2-d*T^2
  189. inv1 = inv0(e*f*g*h)
  190. z_inv = inv1*e*g # 1 / (f*h)
  191. t_inv = inv1*f*h
  192. if negative(e*g*z_inv):
  193. if a==-1: sqrta = self.i
  194. else: sqrta = -1
  195. e,f,g,h = g,h,-e,f*sqrta
  196. factor = self.i
  197. else:
  198. factor = self.magic
  199. if negative(h*e*z_inv): g=-g
  200. s = (h-g)*factor*g*t_inv
  201. else:
  202. foo = Y^2+a*X^2
  203. bar = X*Y
  204. den = inv0(foo*bar)
  205. if negative(2*bar^2*den): tmp = a*X^2
  206. else: tmp = Y^2
  207. s = self.magic*(Z^2-tmp)*foo*den
  208. return self.gfToBytes(s,mustBePositive=True)
  209. @classmethod
  210. @optimized_version_of("decodeSpec")
  211. def decode(cls,s):
  212. """Decode, optimized version"""
  213. s = cls.bytesToGf(s,mustBePositive=True)
  214. a,d = cls.a,cls.d
  215. yden = 1-a*s^2
  216. ynum = 1+a*s^2
  217. yden_sqr = yden^2
  218. xden_sqr = a*d*ynum^2 - yden_sqr
  219. isr = isqrt(xden_sqr * yden_sqr)
  220. xden_inv = isr * yden
  221. yden_inv = xden_inv * isr * xden_sqr
  222. x = 2*s*xden_inv
  223. if negative(x): x = -x
  224. y = ynum * yden_inv
  225. if cls.cofactor==8 and (negative(x*y) or y==0):
  226. raise InvalidEncodingException("x*y is invalid: %d, %d" % (x,y))
  227. return cls(x,y)
  228. @classmethod
  229. def fromJacobiQuartic(cls,s,t,sgn=1):
  230. """Convert point from its Jacobi Quartic representation"""
  231. a,d = cls.a,cls.d
  232. assert s^4 - 2*cls.a*(1-2*d/(d-a))*s^2 + 1 == t^2
  233. x = 2*s*cls.magic / t
  234. y = (1+a*s^2) / (1-a*s^2)
  235. return cls(sgn*x,y)
  236. @classmethod
  237. def elligatorSpec(cls,r0):
  238. a,d = cls.a,cls.d
  239. r = cls.qnr * cls.bytesToGf(r0,mustBeProper=False,maskHiBits=True)^2
  240. den = (d*r-a)*(a*r-d)
  241. if den == 0: return cls()
  242. n1 = cls.a*(r+1)*(a+d)*(d-a)/den
  243. n2 = r*n1
  244. if is_square(n1):
  245. sgn,s,t = 1, xsqrt(n1), -(r-1)*(a+d)^2 / den - 1
  246. else:
  247. sgn,s,t = -1,-xsqrt(n2), r*(r-1)*(a+d)^2 / den - 1
  248. return cls.fromJacobiQuartic(s,t)
  249. @classmethod
  250. @optimized_version_of("elligatorSpec")
  251. def elligator(cls,r0):
  252. a,d = cls.a,cls.d
  253. r0 = cls.bytesToGf(r0,mustBeProper=False,maskHiBits=True)
  254. r = cls.qnr * r0^2
  255. den = (d*r-a)*(a*r-d)
  256. num = cls.a*(r+1)*(a+d)*(d-a)
  257. iss,isri = isqrt_i(num*den)
  258. if iss: sgn,twiddle = 1,1
  259. else: sgn,twiddle = -1,r0*cls.qnr
  260. isri *= twiddle
  261. s = isri*num
  262. t = -sgn*isri*s*(r-1)*(d+a)^2 - 1
  263. if negative(s) == iss: s = -s
  264. return cls.fromJacobiQuartic(s,t)
  265. class Decaf_1_1_Point(QuotientEdwardsPoint):
  266. """Like current decaf but tweaked for simplicity"""
  267. def encodeSpec(self):
  268. """Unoptimized specification for encoding"""
  269. a,d = self.a,self.d
  270. x,y = self
  271. if x==0 or y==0: return(self.gfToBytes(0))
  272. if self.cofactor==8 and negative(x*y*self.isoMagic):
  273. x,y = self.torque()
  274. sr = xsqrt(1-a*x^2)
  275. altx = x*y*self.isoMagic / sr
  276. if negative(altx): s = (1+sr)/x
  277. else: s = (1-sr)/x
  278. return self.gfToBytes(s,mustBePositive=True)
  279. @classmethod
  280. def decodeSpec(cls,s):
  281. """Unoptimized specification for decoding"""
  282. a,d = cls.a,cls.d
  283. s = cls.bytesToGf(s,mustBePositive=True)
  284. if s==0: return cls()
  285. t = xsqrt(s^4 + 2*(a-2*d)*s^2 + 1)
  286. altx = 2*s*cls.isoMagic/t
  287. if negative(altx): t = -t
  288. x = 2*s / (1+a*s^2)
  289. y = (1-a*s^2) / t
  290. if cls.cofactor==8 and (negative(x*y*cls.isoMagic) or y==0):
  291. raise InvalidEncodingException("x*y is invalid: %d, %d" % (x,y))
  292. return cls(x,y)
  293. def toJacobiQuartic(self,toggle_rotation=False,toggle_altx=False,toggle_s=False):
  294. "Return s,t on jacobi curve"
  295. a,d = self.a,self.d
  296. x,y,z,t = self.xyzt()
  297. if self.cofactor == 8:
  298. # Cofactor 8 version
  299. # Simulate IMAGINE_TWIST because that's how libdecaf does it
  300. x = self.i*x
  301. t = self.i*t
  302. a = -a
  303. d = -d
  304. # OK, the actual libdecaf code should be here
  305. num = (z+y)*(z-y)
  306. den = x*y
  307. isr = isqrt(num*(a-d)*den^2)
  308. iden = isr * den * self.isoMagic # 1/sqrt((z+y)(z-y)) = 1/sqrt(1-Y^2) / z
  309. inum = isr * num # sqrt(1-Y^2) * z / xysqrt(a-d) ~ 1/sqrt(1-ax^2)/z
  310. if negative(iden*inum*self.i*t^2*(d-a)) != toggle_rotation:
  311. iden,inum = inum,iden
  312. fac = x*sqrt(a)
  313. toggle=(a==-1)
  314. else:
  315. fac = y
  316. toggle=False
  317. imi = self.isoMagic * self.i
  318. altx = inum*t*imi
  319. neg_altx = negative(altx) != toggle_altx
  320. if neg_altx != toggle: inum =- inum
  321. tmp = fac*(inum*z + 1)
  322. s = iden*tmp*imi
  323. negm1 = (negative(s) != toggle_s) != neg_altx
  324. if negm1: m1 = a*fac + z
  325. else: m1 = a*fac - z
  326. swap = toggle_s
  327. else:
  328. # Much simpler cofactor 4 version
  329. num = (x+t)*(x-t)
  330. isr = isqrt(num*(a-d)*x^2)
  331. ratio = isr*num
  332. altx = ratio*self.isoMagic
  333. neg_altx = negative(altx) != toggle_altx
  334. if neg_altx: ratio =- ratio
  335. tmp = ratio*z - t
  336. s = (a-d)*isr*x*tmp
  337. negx = (negative(s) != toggle_s) != neg_altx
  338. if negx: m1 = -a*t + x
  339. else: m1 = -a*t - x
  340. swap = toggle_s
  341. if negative(s): s = -s
  342. return s,m1,a*tmp,swap
  343. def invertElligator(self,toggle_r=False,*args,**kwargs):
  344. "Produce preimage of self under elligator, or None"
  345. a,d = self.a,self.d
  346. rets = []
  347. tr = [False,True] if self.cofactor == 8 else [False]
  348. for toggle_rotation in tr:
  349. for toggle_altx in [False,True]:
  350. for toggle_s in [False,True]:
  351. for toggle_r in [False,True]:
  352. s,m1,m12,swap = self.toJacobiQuartic(toggle_rotation,toggle_altx,toggle_s)
  353. #print
  354. #print toggle_rotation,toggle_altx,toggle_s
  355. #print m1
  356. #print m12
  357. if self == self.__class__():
  358. if self.cofactor == 4:
  359. # Hacks for identity!
  360. if toggle_altx: m12 = 1
  361. elif toggle_s: m1 = 1
  362. elif toggle_r: continue
  363. ## BOTH???
  364. else:
  365. m12 = 1
  366. imi = self.isoMagic * self.i
  367. if toggle_rotation:
  368. if toggle_altx: m1 = -imi
  369. else: m1 = +imi
  370. else:
  371. if toggle_altx: m1 = 0
  372. else: m1 = a-d
  373. rnum = (d*a*m12-m1)
  374. rden = ((d*a-1)*m12+m1)
  375. if swap: rnum,rden = rden,rnum
  376. ok,sr = isqrt_i(rnum*rden*self.qnr)
  377. if not ok: continue
  378. sr *= rnum
  379. #print "Works! %d %x" % (swap,sr)
  380. if negative(sr) != toggle_r: sr = -sr
  381. ret = self.gfToBytes(sr)
  382. if self.elligator(ret) != self and self.elligator(ret) != -self:
  383. print "WRONG!",[toggle_rotation,toggle_altx,toggle_s]
  384. if self.elligator(ret) == -self and self != -self: print "Negated!",[toggle_rotation,toggle_altx,toggle_s]
  385. rets.append(bytes(ret))
  386. return rets
  387. @optimized_version_of("encodeSpec")
  388. def encode(self):
  389. """Encode, optimized version"""
  390. return self.gfToBytes(self.toJacobiQuartic()[0])
  391. @classmethod
  392. @optimized_version_of("decodeSpec")
  393. def decode(cls,s):
  394. """Decode, optimized version"""
  395. a,d = cls.a,cls.d
  396. s = cls.bytesToGf(s,mustBePositive=True)
  397. #if s==0: return cls()
  398. s2 = s^2
  399. den = 1+a*s2
  400. num = den^2 - 4*d*s2
  401. isr = isqrt(num*den^2)
  402. altx = 2*s*isr*den*cls.isoMagic
  403. if negative(altx): isr = -isr
  404. x = 2*s *isr^2*den*num
  405. y = (1-a*s^2) * isr*den
  406. if cls.cofactor==8 and (negative(x*y*cls.isoMagic) or y==0):
  407. raise InvalidEncodingException("x*y is invalid: %d, %d" % (x,y))
  408. return cls(x,y)
  409. @classmethod
  410. def fromJacobiQuartic(cls,s,t,sgn=1):
  411. """Convert point from its Jacobi Quartic representation"""
  412. a,d = cls.a,cls.d
  413. if s==0: return cls()
  414. x = 2*s / (1+a*s^2)
  415. y = (1-a*s^2) / t
  416. return cls(x,sgn*y)
  417. @optimized_version_of("doubleAndEncodeSpec")
  418. def doubleAndEncode(self):
  419. X,Y,Z,T = self.xyzt()
  420. a,d = self.a,self.d
  421. if self.cofactor == 8:
  422. # Cofactor 8 version
  423. # Simulate IMAGINE_TWIST because that's how libdecaf does it
  424. X = self.i*X
  425. T = self.i*T
  426. a = -a
  427. d = -d
  428. # TODO: This is only being called for a=-1, so could
  429. # be wrong for a=1
  430. e = 2*X*Y
  431. f = Y^2+a*X^2
  432. g = Y^2-a*X^2
  433. h = Z^2-d*T^2
  434. eim = e*self.isoMagic
  435. inv = inv0(eim*g*f*h)
  436. fh_inv = eim*g*inv*self.i
  437. if negative(eim*g*fh_inv):
  438. idf = g*self.isoMagic*self.i
  439. bar = f
  440. foo = g
  441. test = eim*f
  442. else:
  443. idf = eim
  444. bar = h
  445. foo = -eim
  446. test = g*h
  447. if negative(test*fh_inv): bar =- bar
  448. s = idf*(foo+bar)*inv*f*h
  449. else:
  450. xy = X*Y
  451. h = Z^2-d*T^2
  452. inv = inv0(xy*h)
  453. if negative(inv*2*xy^2*self.isoMagic): tmp = Y
  454. else: tmp = X
  455. s = tmp^2*h*inv # = X/Y or Y/X, interestingly
  456. return self.gfToBytes(s,mustBePositive=True)
  457. @classmethod
  458. def elligatorSpec(cls,r0,fromR=False):
  459. a,d = cls.a,cls.d
  460. if fromR: r = r0
  461. else: r = cls.qnr * cls.bytesToGf(r0,mustBeProper=False,maskHiBits=True)^2
  462. den = (d*r-(d-a))*((d-a)*r-d)
  463. if den == 0: return cls()
  464. n1 = (r+1)*(a-2*d)/den
  465. n2 = r*n1
  466. if is_square(n1):
  467. sgn,s,t = 1, xsqrt(n1), -(r-1)*(a-2*d)^2 / den - 1
  468. else:
  469. sgn,s,t = -1, -xsqrt(n2), r*(r-1)*(a-2*d)^2 / den - 1
  470. return cls.fromJacobiQuartic(s,t)
  471. @classmethod
  472. @optimized_version_of("elligatorSpec")
  473. def elligator(cls,r0):
  474. a,d = cls.a,cls.d
  475. r0 = cls.bytesToGf(r0,mustBeProper=False,maskHiBits=True)
  476. r = cls.qnr * r0^2
  477. den = (d*r-(d-a))*((d-a)*r-d)
  478. num = (r+1)*(a-2*d)
  479. iss,isri = isqrt_i(num*den)
  480. if iss: sgn,twiddle = 1,1
  481. else: sgn,twiddle = -1,r0*cls.qnr
  482. isri *= twiddle
  483. s = isri*num
  484. t = -sgn*isri*s*(r-1)*(a-2*d)^2 - 1
  485. if negative(s) == iss: s = -s
  486. return cls.fromJacobiQuartic(s,t)
  487. def elligatorInverseBruteForce(self):
  488. """Invert Elligator using SAGE's polynomial solver"""
  489. a,d = self.a,self.d
  490. R.<r0> = self.F[]
  491. r = self.qnr * r0^2
  492. den = (d*r-(d-a))*((d-a)*r-d)
  493. n1 = (r+1)*(a-2*d)/den
  494. n2 = r*n1
  495. ret = set()
  496. for s2,t in [(n1, -(r-1)*(a-2*d)^2 / den - 1),
  497. (n2,r*(r-1)*(a-2*d)^2 / den - 1)]:
  498. x2 = 4*s2/(1+a*s2)^2
  499. y = (1-a*s2) / t
  500. selfT = self
  501. for i in xrange(self.cofactor/2):
  502. xT,yT = selfT
  503. polyX = xT^2-x2
  504. polyY = yT-y
  505. sx = set(r for r,_ in polyX.numerator().roots())
  506. sy = set(r for r,_ in polyY.numerator().roots())
  507. ret = ret.union(sx.intersection(sy))
  508. selfT = selfT.torque()
  509. ret = [self.gfToBytes(r) for r in ret]
  510. for r in ret:
  511. assert self.elligator(r) in [self,-self]
  512. ret = [r for r in ret if self.elligator(r) == self]
  513. return ret
  514. class Ed25519Point(RistrettoPoint):
  515. F = GF(2^255-19)
  516. d = F(-121665/121666)
  517. a = F(-1)
  518. i = sqrt(F(-1))
  519. mneg = F(1)
  520. qnr = i
  521. magic = isqrt(a*d-1)
  522. cofactor = 8
  523. encLen = 32
  524. @classmethod
  525. def base(cls):
  526. return cls( 15112221349535400772501151409588531511454012693041857206046113283949847762202, 46316835694926478169428394003475163141307993866256225615783033603165251855960
  527. )
  528. class NegEd25519Point(RistrettoPoint):
  529. F = GF(2^255-19)
  530. d = F(121665/121666)
  531. a = F(1)
  532. i = sqrt(F(-1))
  533. mneg = F(-1) # TODO checkme vs 1-ad or whatever
  534. qnr = i
  535. magic = isqrt(a*d-1)
  536. cofactor = 8
  537. encLen = 32
  538. @classmethod
  539. def base(cls):
  540. y = cls.F(4/5)
  541. x = sqrt((y^2-1)/(cls.d*y^2-cls.a))
  542. if negative(x): x = -x
  543. return cls(x,y)
  544. class IsoEd448Point(RistrettoPoint):
  545. F = GF(2^448-2^224-1)
  546. d = F(39082/39081)
  547. a = F(1)
  548. mneg = F(-1)
  549. qnr = -1
  550. magic = isqrt(a*d-1)
  551. cofactor = 4
  552. encLen = 56
  553. @classmethod
  554. def base(cls):
  555. return cls( # RFC has it wrong
  556. 345397493039729516374008604150537410266655260075183290216406970281645695073672344430481787759340633221708391583424041788924124567700732,
  557. -363419362147803445274661903944002267176820680343659030140745099590306164083365386343198191849338272965044442230921818680526749009182718
  558. )
  559. class TwistedEd448GoldilocksPoint(Decaf_1_1_Point):
  560. F = GF(2^448-2^224-1)
  561. d = F(-39082)
  562. a = F(-1)
  563. qnr = -1
  564. cofactor = 4
  565. encLen = 56
  566. isoMagic = IsoEd448Point.magic
  567. @classmethod
  568. def base(cls):
  569. return cls.decodeSpec(Ed448GoldilocksPoint.base().encodeSpec())
  570. class Ed448GoldilocksPoint(Decaf_1_1_Point):
  571. F = GF(2^448-2^224-1)
  572. d = F(-39081)
  573. a = F(1)
  574. qnr = -1
  575. cofactor = 4
  576. encLen = 56
  577. isoMagic = IsoEd448Point.magic
  578. @classmethod
  579. def base(cls):
  580. return 2*cls(
  581. 224580040295924300187604334099896036246789641632564134246125461686950415467406032909029192869357953282578032075146446173674602635247710, 298819210078481492676017930443930673437544040154080242095928241372331506189835876003536878655418784733982303233503462500531545062832660
  582. )
  583. class IsoEd25519Point(Decaf_1_1_Point):
  584. # TODO: twisted iso too!
  585. # TODO: twisted iso might have to IMAGINE_TWIST or whatever
  586. F = GF(2^255-19)
  587. d = F(-121665)
  588. a = F(1)
  589. i = sqrt(F(-1))
  590. qnr = i
  591. magic = isqrt(a*d-1)
  592. cofactor = 8
  593. encLen = 32
  594. isoMagic = Ed25519Point.magic
  595. isoA = Ed25519Point.a
  596. @classmethod
  597. def base(cls):
  598. return cls.decodeSpec(Ed25519Point.base().encode())
  599. class TestFailedException(Exception): pass
  600. def test(cls,n):
  601. print "Testing curve %s" % cls.__name__
  602. specials = [1]
  603. ii = cls.F(-1)
  604. while is_square(ii):
  605. specials.append(ii)
  606. ii = sqrt(ii)
  607. specials.append(ii)
  608. for i in specials:
  609. if negative(cls.F(i)): i = -i
  610. i = enc_le(i,cls.encLen)
  611. try:
  612. Q = cls.decode(i)
  613. QE = Q.encode()
  614. if QE != i:
  615. raise TestFailedException("Round trip special %s != %s" %
  616. (binascii.hexlify(QE),binascii.hexlify(i)))
  617. except NotOnCurveException: pass
  618. except InvalidEncodingException: pass
  619. P = cls.base()
  620. Q = cls()
  621. for i in xrange(n):
  622. #print binascii.hexlify(Q.encode())
  623. QE = Q.encode()
  624. QQ = cls.decode(QE)
  625. if QQ != Q: raise TestFailedException("Round trip %s != %s" % (str(QQ),str(Q)))
  626. # Testing s -> 1/s: encodes -point on cofactor
  627. s = cls.bytesToGf(QE)
  628. if s != 0:
  629. ss = cls.gfToBytes(1/s,mustBePositive=True)
  630. try:
  631. QN = cls.decode(ss)
  632. if cls.cofactor == 8:
  633. raise TestFailedException("1/s shouldnt work for cofactor 8")
  634. if QN != -Q:
  635. raise TestFailedException("s -> 1/s should negate point for cofactor 4")
  636. except InvalidEncodingException as e:
  637. # Should be raised iff cofactor==8
  638. if cls.cofactor == 4:
  639. raise TestFailedException("s -> 1/s should work for cofactor 4")
  640. QT = Q
  641. for h in xrange(cls.cofactor):
  642. QT = QT.torque()
  643. if QT.encode() != QE:
  644. raise TestFailedException("Can't torque %s,%d" % (str(Q),h+1))
  645. Q0 = Q + P
  646. if Q0 == Q: raise TestFailedException("Addition doesn't work")
  647. if Q0-P != Q: raise TestFailedException("Subtraction doesn't work")
  648. r = randint(1,1000)
  649. Q1 = Q0*r
  650. Q2 = Q0*(r+1)
  651. if Q1 + Q0 != Q2: raise TestFailedException("Scalarmul doesn't work")
  652. Q = Q1
  653. def testElligator(cls,n):
  654. print "Testing elligator on %s" % cls.__name__
  655. for i in xrange(n):
  656. r = randombytes(cls.encLen)
  657. P = cls.elligator(r)
  658. if hasattr(P,"invertElligator"):
  659. iv = P.invertElligator()
  660. modr = bytes(cls.gfToBytes(cls.bytesToGf(r,mustBeProper=False,maskHiBits=True)))
  661. iv2 = P.torque().invertElligator()
  662. if modr not in iv: print "Failed to invert Elligator!"
  663. if len(iv) != len(set(iv)):
  664. print "Elligator inverses not unique!", len(set(iv)), len(iv)
  665. if iv != iv2:
  666. print "Elligator is untorqueable!"
  667. #print [binascii.hexlify(j) for j in iv]
  668. #print [binascii.hexlify(j) for j in iv2]
  669. #break
  670. else:
  671. pass # TODO
  672. def gangtest(classes,n):
  673. print "Gang test",[cls.__name__ for cls in classes]
  674. specials = [1]
  675. ii = classes[0].F(-1)
  676. while is_square(ii):
  677. specials.append(ii)
  678. ii = sqrt(ii)
  679. specials.append(ii)
  680. for i in xrange(n):
  681. rets = [bytes((cls.base()*i).encode()) for cls in classes]
  682. if len(set(rets)) != 1:
  683. print "Divergence in encode at %d" % i
  684. for c,ret in zip(classes,rets):
  685. print c,binascii.hexlify(ret)
  686. print
  687. if i < len(specials): r0 = enc_le(specials[i],classes[0].encLen)
  688. else: r0 = randombytes(classes[0].encLen)
  689. rets = [bytes((cls.elligator(r0)*i).encode()) for cls in classes]
  690. if len(set(rets)) != 1:
  691. print "Divergence in elligator at %d" % i
  692. for c,ret in zip(classes,rets):
  693. print c,binascii.hexlify(ret)
  694. print
  695. def testDoubleAndEncode(cls,n):
  696. print "Testing doubleAndEncode on %s" % cls.__name__
  697. P = cls()
  698. for i in xrange(cls.cofactor):
  699. Q = P.torque()
  700. assert P.doubleAndEncode() == Q.doubleAndEncode()
  701. P = Q
  702. for i in xrange(n):
  703. r1 = randombytes(cls.encLen)
  704. r2 = randombytes(cls.encLen)
  705. u = cls.elligator(r1) + cls.elligator(r2)
  706. assert u.doubleAndEncode() == u.torque().doubleAndEncode()
  707. testDoubleAndEncode(Ed25519Point,100)
  708. testDoubleAndEncode(NegEd25519Point,100)
  709. testDoubleAndEncode(IsoEd25519Point,100)
  710. testDoubleAndEncode(IsoEd448Point,100)
  711. testDoubleAndEncode(TwistedEd448GoldilocksPoint,100)
  712. #test(Ed25519Point,100)
  713. #test(NegEd25519Point,100)
  714. #test(IsoEd25519Point,100)
  715. #test(IsoEd448Point,100)
  716. #test(TwistedEd448GoldilocksPoint,100)
  717. #test(Ed448GoldilocksPoint,100)
  718. #testElligator(Ed25519Point,100)
  719. #testElligator(NegEd25519Point,100)
  720. #testElligator(IsoEd25519Point,100)
  721. #testElligator(IsoEd448Point,100)
  722. #testElligator(Ed448GoldilocksPoint,100)
  723. #testElligator(TwistedEd448GoldilocksPoint,100)
  724. #gangtest([IsoEd448Point,TwistedEd448GoldilocksPoint,Ed448GoldilocksPoint],100)
  725. #gangtest([Ed25519Point,IsoEd25519Point],100)