761 lines
25 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. # Utility functions
  110. @classmethod
  111. def bytesToGf(cls,bytes,mustBeProper=True,mustBePositive=False):
  112. """Convert little-endian bytes to field element, sanity check length"""
  113. if len(bytes) != cls.encLen:
  114. raise InvalidEncodingException("wrong length %d" % len(bytes))
  115. s = dec_le(bytes)
  116. if mustBeProper and s >= cls.F.modulus():
  117. raise InvalidEncodingException("%d out of range!" % s)
  118. s = cls.F(s)
  119. if mustBePositive and negative(s):
  120. raise InvalidEncodingException("%d is negative!" % s)
  121. return s
  122. @classmethod
  123. def gfToBytes(cls,x,mustBePositive=False):
  124. """Convert little-endian bytes to field element, sanity check length"""
  125. if negative(x) and mustBePositive: x = -x
  126. return enc_le(x,cls.encLen)
  127. class RistrettoPoint(QuotientEdwardsPoint):
  128. """The new Ristretto group"""
  129. def encodeSpec(self):
  130. """Unoptimized specification for encoding"""
  131. x,y = self
  132. if self.cofactor==8 and (negative(x*y) or y==0): (x,y) = self.torque()
  133. if y == -1: y = 1 # Avoid divide by 0; doesn't affect impl
  134. if negative(x): x,y = -x,-y
  135. s = xsqrt(self.mneg*(1-y)/(1+y),exn=Exception("Unimplemented: point is odd: " + str(self)))
  136. return self.gfToBytes(s)
  137. @classmethod
  138. def decodeSpec(cls,s):
  139. """Unoptimized specification for decoding"""
  140. s = cls.bytesToGf(s,mustBePositive=True)
  141. a,d = cls.a,cls.d
  142. x = xsqrt(4*s^2 / (a*d*(1+a*s^2)^2 - (1-a*s^2)^2))
  143. y = (1+a*s^2) / (1-a*s^2)
  144. if cls.cofactor==8 and (negative(x*y) or y==0):
  145. raise InvalidEncodingException("x*y has high bit")
  146. return cls(x,y)
  147. @optimized_version_of("encodeSpec")
  148. def encode(self):
  149. """Encode, optimized version"""
  150. a,d,mneg = self.a,self.d,self.mneg
  151. x,y,z,t = self.xyzt()
  152. if self.cofactor==8:
  153. u1 = mneg*(z+y)*(z-y)
  154. u2 = x*y # = t*z
  155. isr = isqrt(u1*u2^2)
  156. i1 = isr*u1 # sqrt(mneg*(z+y)*(z-y))/(x*y)
  157. i2 = isr*u2 # 1/sqrt(a*(y+z)*(y-z))
  158. z_inv = i1*i2*t # 1/z
  159. if negative(t*z_inv):
  160. if a==-1:
  161. x,y = y*self.i,x*self.i
  162. den_inv = self.magic * i1
  163. else:
  164. x,y = -y,x
  165. den_inv = self.i * self.magic * i1
  166. else:
  167. den_inv = i2
  168. if negative(x*z_inv): y = -y
  169. s = (z-y) * den_inv
  170. else:
  171. num = mneg*(z+y)*(z-y)
  172. isr = isqrt(num*y^2)
  173. if negative(isr^2*num*y*t): y = -y
  174. s = isr*y*(z-y)
  175. return self.gfToBytes(s,mustBePositive=True)
  176. @classmethod
  177. @optimized_version_of("decodeSpec")
  178. def decode(cls,s):
  179. """Decode, optimized version"""
  180. s = cls.bytesToGf(s,mustBePositive=True)
  181. a,d = cls.a,cls.d
  182. yden = 1-a*s^2
  183. ynum = 1+a*s^2
  184. yden_sqr = yden^2
  185. xden_sqr = a*d*ynum^2 - yden_sqr
  186. isr = isqrt(xden_sqr * yden_sqr)
  187. xden_inv = isr * yden
  188. yden_inv = xden_inv * isr * xden_sqr
  189. x = 2*s*xden_inv
  190. if negative(x): x = -x
  191. y = ynum * yden_inv
  192. if cls.cofactor==8 and (negative(x*y) or y==0):
  193. raise InvalidEncodingException("x*y is invalid: %d, %d" % (x,y))
  194. return cls(x,y)
  195. @classmethod
  196. def fromJacobiQuartic(cls,s,t,sgn=1):
  197. """Convert point from its Jacobi Quartic representation"""
  198. a,d = cls.a,cls.d
  199. assert s^4 - 2*cls.a*(1-2*d/(d-a))*s^2 + 1 == t^2
  200. x = 2*s*cls.magic / t
  201. y = (1+a*s^2) / (1-a*s^2)
  202. return cls(sgn*x,y)
  203. @classmethod
  204. def elligatorSpec(cls,r0):
  205. a,d = cls.a,cls.d
  206. r = cls.qnr * cls.bytesToGf(r0)^2
  207. den = (d*r-a)*(a*r-d)
  208. if den == 0: return cls()
  209. n1 = cls.a*(r+1)*(a+d)*(d-a)/den
  210. n2 = r*n1
  211. if is_square(n1):
  212. sgn,s,t = 1, xsqrt(n1), -(r-1)*(a+d)^2 / den - 1
  213. else:
  214. sgn,s,t = -1,-xsqrt(n2), r*(r-1)*(a+d)^2 / den - 1
  215. return cls.fromJacobiQuartic(s,t)
  216. @classmethod
  217. @optimized_version_of("elligatorSpec")
  218. def elligator(cls,r0):
  219. a,d = cls.a,cls.d
  220. r0 = cls.bytesToGf(r0)
  221. r = cls.qnr * r0^2
  222. den = (d*r-a)*(a*r-d)
  223. num = cls.a*(r+1)*(a+d)*(d-a)
  224. iss,isri = isqrt_i(num*den)
  225. if iss: sgn,twiddle = 1,1
  226. else: sgn,twiddle = -1,r0*cls.qnr
  227. isri *= twiddle
  228. s = isri*num
  229. t = -sgn*isri*s*(r-1)*(d+a)^2 - 1
  230. if negative(s) == iss: s = -s
  231. return cls.fromJacobiQuartic(s,t)
  232. class Decaf_1_1_Point(QuotientEdwardsPoint):
  233. """Like current decaf but tweaked for simplicity"""
  234. def encodeSpec(self):
  235. """Unoptimized specification for encoding"""
  236. a,d = self.a,self.d
  237. x,y = self
  238. if x==0 or y==0: return(self.gfToBytes(0))
  239. if self.cofactor==8 and negative(x*y*self.isoMagic):
  240. x,y = self.torque()
  241. sr = xsqrt(1-a*x^2)
  242. altx = x*y*self.isoMagic / sr
  243. if negative(altx): s = (1+sr)/x
  244. else: s = (1-sr)/x
  245. return self.gfToBytes(s,mustBePositive=True)
  246. @classmethod
  247. def decodeSpec(cls,s):
  248. """Unoptimized specification for decoding"""
  249. a,d = cls.a,cls.d
  250. s = cls.bytesToGf(s,mustBePositive=True)
  251. if s==0: return cls()
  252. t = xsqrt(s^4 + 2*(a-2*d)*s^2 + 1)
  253. altx = 2*s*cls.isoMagic/t
  254. if negative(altx): t = -t
  255. x = 2*s / (1+a*s^2)
  256. y = (1-a*s^2) / t
  257. if cls.cofactor==8 and (negative(x*y*cls.isoMagic) or y==0):
  258. raise InvalidEncodingException("x*y is invalid: %d, %d" % (x,y))
  259. return cls(x,y)
  260. def toJacobiQuartic(self,toggle_rotation=False,toggle_altx=False,toggle_s=False):
  261. "Return s,t on jacobi curve"
  262. a,d = self.a,self.d
  263. x,y,z,t = self.xyzt()
  264. if self.cofactor == 8:
  265. # Cofactor 8 version
  266. # Simulate IMAGINE_TWIST because that's how libdecaf does it
  267. x = self.i*x
  268. t = self.i*t
  269. a = -a
  270. d = -d
  271. # OK, the actual libdecaf code should be here
  272. num = (z+y)*(z-y)
  273. den = x*y
  274. isr = isqrt(num*(a-d)*den^2)
  275. iden = isr * den * self.isoMagic # 1/sqrt((z+y)(z-y)) = 1/sqrt(1-Y^2) / z
  276. inum = isr * num # sqrt(1-Y^2) * z / xysqrt(a-d) ~ 1/sqrt(1-ax^2)/z
  277. if negative(iden*inum*self.i*t^2*(d-a)) != toggle_rotation:
  278. iden,inum = inum,iden
  279. fac = x*sqrt(a)
  280. toggle=(a==-1)
  281. else:
  282. fac = y
  283. toggle=False
  284. imi = self.isoMagic * self.i
  285. altx = inum*t*imi
  286. neg_altx = negative(altx) != toggle_altx
  287. if neg_altx != toggle: inum =- inum
  288. tmp = fac*(inum*z + 1)
  289. s = iden*tmp*imi
  290. negm1 = (negative(s) != toggle_s) != neg_altx
  291. if negm1: m1 = a*fac + z
  292. else: m1 = a*fac - z
  293. swap = toggle_s
  294. else:
  295. # Much simpler cofactor 4 version
  296. num = (x+t)*(x-t)
  297. isr = isqrt(num*(a-d)*x^2)
  298. ratio = isr*num
  299. altx = ratio*self.isoMagic
  300. neg_altx = negative(altx) != toggle_altx
  301. if neg_altx: ratio =- ratio
  302. tmp = ratio*z - t
  303. s = (a-d)*isr*x*tmp
  304. negx = (negative(s) != toggle_s) != neg_altx
  305. if negx: m1 = -a*t + x
  306. else: m1 = -a*t - x
  307. swap = toggle_s
  308. if negative(s): s = -s
  309. return s,m1,a*tmp,swap
  310. def invertElligator(self,toggle_r=False,*args,**kwargs):
  311. "Produce preimage of self under elligator, or None"
  312. a,d = self.a,self.d
  313. rets = []
  314. tr = [False,True] if self.cofactor == 8 else [False]
  315. for toggle_rotation in tr:
  316. for toggle_altx in [False,True]:
  317. for toggle_s in [False,True]:
  318. for toggle_r in [False,True]:
  319. s,m1,m12,swap = self.toJacobiQuartic(toggle_rotation,toggle_altx,toggle_s)
  320. #print
  321. #print toggle_rotation,toggle_altx,toggle_s
  322. #print m1
  323. #print m12
  324. if self == self.__class__():
  325. if self.cofactor == 4:
  326. # Hacks for identity!
  327. if toggle_altx: m12 = 1
  328. elif toggle_s: m1 = 1
  329. elif toggle_r: continue
  330. ## BOTH???
  331. else:
  332. m12 = 1
  333. imi = self.isoMagic * self.i
  334. if toggle_rotation:
  335. if toggle_altx: m1 = -imi
  336. else: m1 = +imi
  337. else:
  338. if toggle_altx: m1 = 0
  339. else: m1 = a-d
  340. rnum = (d*a*m12-m1)
  341. rden = ((d*a-1)*m12+m1)
  342. if swap: rnum,rden = rden,rnum
  343. ok,sr = isqrt_i(rnum*rden*self.qnr)
  344. if not ok: continue
  345. sr *= rnum
  346. #print "Works! %d %x" % (swap,sr)
  347. if negative(sr) != toggle_r: sr = -sr
  348. ret = self.gfToBytes(sr)
  349. if self.elligator(ret) != self and self.elligator(ret) != -self:
  350. print "WRONG!",[toggle_rotation,toggle_altx,toggle_s]
  351. if self.elligator(ret) == -self and self != -self: print "Negated!",[toggle_rotation,toggle_altx,toggle_s]
  352. rets.append(bytes(ret))
  353. return rets
  354. @optimized_version_of("encodeSpec")
  355. def encode(self):
  356. """Encode, optimized version"""
  357. return self.gfToBytes(self.toJacobiQuartic()[0])
  358. @classmethod
  359. @optimized_version_of("decodeSpec")
  360. def decode(cls,s):
  361. """Decode, optimized version"""
  362. a,d = cls.a,cls.d
  363. s = cls.bytesToGf(s,mustBePositive=True)
  364. #if s==0: return cls()
  365. s2 = s^2
  366. den = 1+a*s2
  367. num = den^2 - 4*d*s2
  368. isr = isqrt(num*den^2)
  369. altx = 2*s*isr*den*cls.isoMagic
  370. if negative(altx): isr = -isr
  371. x = 2*s *isr^2*den*num
  372. y = (1-a*s^2) * isr*den
  373. if cls.cofactor==8 and (negative(x*y*cls.isoMagic) or y==0):
  374. raise InvalidEncodingException("x*y is invalid: %d, %d" % (x,y))
  375. return cls(x,y)
  376. @classmethod
  377. def fromJacobiQuartic(cls,s,t,sgn=1):
  378. """Convert point from its Jacobi Quartic representation"""
  379. a,d = cls.a,cls.d
  380. if s==0: return cls()
  381. x = 2*s / (1+a*s^2)
  382. y = (1-a*s^2) / t
  383. return cls(x,sgn*y)
  384. @classmethod
  385. def elligatorSpec(cls,r0,fromR=False):
  386. a,d = cls.a,cls.d
  387. if fromR: r = r0
  388. else: r = cls.qnr * cls.bytesToGf(r0)^2
  389. den = (d*r-(d-a))*((d-a)*r-d)
  390. if den == 0: return cls()
  391. n1 = (r+1)*(a-2*d)/den
  392. n2 = r*n1
  393. if is_square(n1):
  394. sgn,s,t = 1, xsqrt(n1), -(r-1)*(a-2*d)^2 / den - 1
  395. else:
  396. sgn,s,t = -1, -xsqrt(n2), r*(r-1)*(a-2*d)^2 / den - 1
  397. return cls.fromJacobiQuartic(s,t)
  398. @classmethod
  399. @optimized_version_of("elligatorSpec")
  400. def elligator(cls,r0):
  401. a,d = cls.a,cls.d
  402. r0 = cls.bytesToGf(r0)
  403. r = cls.qnr * r0^2
  404. den = (d*r-(d-a))*((d-a)*r-d)
  405. num = (r+1)*(a-2*d)
  406. iss,isri = isqrt_i(num*den)
  407. if iss: sgn,twiddle = 1,1
  408. else: sgn,twiddle = -1,r0*cls.qnr
  409. isri *= twiddle
  410. s = isri*num
  411. t = -sgn*isri*s*(r-1)*(a-2*d)^2 - 1
  412. if negative(s) == iss: s = -s
  413. return cls.fromJacobiQuartic(s,t)
  414. def elligatorInverseBruteForce(self):
  415. """Invert Elligator using SAGE's polynomial solver"""
  416. a,d = self.a,self.d
  417. R.<r0> = self.F[]
  418. r = self.qnr * r0^2
  419. den = (d*r-(d-a))*((d-a)*r-d)
  420. n1 = (r+1)*(a-2*d)/den
  421. n2 = r*n1
  422. ret = set()
  423. for s2,t in [(n1, -(r-1)*(a-2*d)^2 / den - 1),
  424. (n2,r*(r-1)*(a-2*d)^2 / den - 1)]:
  425. x2 = 4*s2/(1+a*s2)^2
  426. y = (1-a*s2) / t
  427. selfT = self
  428. for i in xrange(self.cofactor/2):
  429. xT,yT = selfT
  430. polyX = xT^2-x2
  431. polyY = yT-y
  432. sx = set(r for r,_ in polyX.numerator().roots())
  433. sy = set(r for r,_ in polyY.numerator().roots())
  434. ret = ret.union(sx.intersection(sy))
  435. selfT = selfT.torque()
  436. ret = [self.gfToBytes(r) for r in ret]
  437. for r in ret:
  438. assert self.elligator(r) in [self,-self]
  439. ret = [r for r in ret if self.elligator(r) == self]
  440. return ret
  441. class Ed25519Point(RistrettoPoint):
  442. F = GF(2^255-19)
  443. d = F(-121665/121666)
  444. a = F(-1)
  445. i = sqrt(F(-1))
  446. mneg = F(1)
  447. qnr = i
  448. magic = isqrt(a*d-1)
  449. cofactor = 8
  450. encLen = 32
  451. @classmethod
  452. def base(cls):
  453. return cls( 15112221349535400772501151409588531511454012693041857206046113283949847762202, 46316835694926478169428394003475163141307993866256225615783033603165251855960
  454. )
  455. class NegEd25519Point(RistrettoPoint):
  456. F = GF(2^255-19)
  457. d = F(121665/121666)
  458. a = F(1)
  459. i = sqrt(F(-1))
  460. mneg = F(-1) # TODO checkme vs 1-ad or whatever
  461. qnr = i
  462. magic = isqrt(a*d-1)
  463. cofactor = 8
  464. encLen = 32
  465. @classmethod
  466. def base(cls):
  467. y = cls.F(4/5)
  468. x = sqrt((y^2-1)/(cls.d*y^2-cls.a))
  469. if negative(x): x = -x
  470. return cls(x,y)
  471. class IsoEd448Point(RistrettoPoint):
  472. F = GF(2^448-2^224-1)
  473. d = F(39082/39081)
  474. a = F(1)
  475. mneg = F(-1)
  476. qnr = -1
  477. magic = isqrt(a*d-1)
  478. cofactor = 4
  479. encLen = 56
  480. @classmethod
  481. def base(cls):
  482. return cls( # RFC has it wrong
  483. 345397493039729516374008604150537410266655260075183290216406970281645695073672344430481787759340633221708391583424041788924124567700732,
  484. -363419362147803445274661903944002267176820680343659030140745099590306164083365386343198191849338272965044442230921818680526749009182718
  485. )
  486. class TwistedEd448GoldilocksPoint(Decaf_1_1_Point):
  487. F = GF(2^448-2^224-1)
  488. d = F(-39082)
  489. a = F(-1)
  490. qnr = -1
  491. cofactor = 4
  492. encLen = 56
  493. isoMagic = IsoEd448Point.magic
  494. @classmethod
  495. def base(cls):
  496. return cls.decodeSpec(Ed448GoldilocksPoint.base().encodeSpec())
  497. class Ed448GoldilocksPoint(Decaf_1_1_Point):
  498. F = GF(2^448-2^224-1)
  499. d = F(-39081)
  500. a = F(1)
  501. qnr = -1
  502. cofactor = 4
  503. encLen = 56
  504. isoMagic = IsoEd448Point.magic
  505. @classmethod
  506. def base(cls):
  507. return 2*cls(
  508. 224580040295924300187604334099896036246789641632564134246125461686950415467406032909029192869357953282578032075146446173674602635247710, 298819210078481492676017930443930673437544040154080242095928241372331506189835876003536878655418784733982303233503462500531545062832660
  509. )
  510. class IsoEd25519Point(Decaf_1_1_Point):
  511. # TODO: twisted iso too!
  512. # TODO: twisted iso might have to IMAGINE_TWIST or whatever
  513. F = GF(2^255-19)
  514. d = F(-121665)
  515. a = F(1)
  516. i = sqrt(F(-1))
  517. qnr = i
  518. magic = isqrt(a*d-1)
  519. cofactor = 8
  520. encLen = 32
  521. isoMagic = Ed25519Point.magic
  522. isoA = Ed25519Point.a
  523. @classmethod
  524. def base(cls):
  525. return cls.decodeSpec(Ed25519Point.base().encode())
  526. class TestFailedException(Exception): pass
  527. def test(cls,n):
  528. print "Testing curve %s" % cls.__name__
  529. specials = [1]
  530. ii = cls.F(-1)
  531. while is_square(ii):
  532. specials.append(ii)
  533. ii = sqrt(ii)
  534. specials.append(ii)
  535. for i in specials:
  536. if negative(cls.F(i)): i = -i
  537. i = enc_le(i,cls.encLen)
  538. try:
  539. Q = cls.decode(i)
  540. QE = Q.encode()
  541. if QE != i:
  542. raise TestFailedException("Round trip special %s != %s" %
  543. (binascii.hexlify(QE),binascii.hexlify(i)))
  544. except NotOnCurveException: pass
  545. except InvalidEncodingException: pass
  546. P = cls.base()
  547. Q = cls()
  548. for i in xrange(n):
  549. #print binascii.hexlify(Q.encode())
  550. QE = Q.encode()
  551. QQ = cls.decode(QE)
  552. if QQ != Q: raise TestFailedException("Round trip %s != %s" % (str(QQ),str(Q)))
  553. # Testing s -> 1/s: encodes -point on cofactor
  554. s = cls.bytesToGf(QE)
  555. if s != 0:
  556. ss = cls.gfToBytes(1/s,mustBePositive=True)
  557. try:
  558. QN = cls.decode(ss)
  559. if cls.cofactor == 8:
  560. raise TestFailedException("1/s shouldnt work for cofactor 8")
  561. if QN != -Q:
  562. raise TestFailedException("s -> 1/s should negate point for cofactor 4")
  563. except InvalidEncodingException as e:
  564. # Should be raised iff cofactor==8
  565. if cls.cofactor == 4:
  566. raise TestFailedException("s -> 1/s should work for cofactor 4")
  567. QT = Q
  568. for h in xrange(cls.cofactor):
  569. QT = QT.torque()
  570. if QT.encode() != QE:
  571. raise TestFailedException("Can't torque %s,%d" % (str(Q),h+1))
  572. Q0 = Q + P
  573. if Q0 == Q: raise TestFailedException("Addition doesn't work")
  574. if Q0-P != Q: raise TestFailedException("Subtraction doesn't work")
  575. r = randint(1,1000)
  576. Q1 = Q0*r
  577. Q2 = Q0*(r+1)
  578. if Q1 + Q0 != Q2: raise TestFailedException("Scalarmul doesn't work")
  579. Q = Q1
  580. #test(Ed25519Point,100)
  581. #test(NegEd25519Point,100)
  582. #test(IsoEd25519Point,100)
  583. #test(IsoEd448Point,100)
  584. #test(TwistedEd448GoldilocksPoint,100)
  585. #test(Ed448GoldilocksPoint,100)
  586. def testElligator(cls,n):
  587. print "Testing elligator on %s" % cls.__name__
  588. for i in xrange(n):
  589. r = randombytes(cls.encLen)
  590. P = cls.elligator(r)
  591. if hasattr(P,"invertElligator"):
  592. iv = P.invertElligator()
  593. modr = bytes(cls.gfToBytes(cls.bytesToGf(r)))
  594. iv2 = P.torque().invertElligator()
  595. if modr not in iv: print "Failed to invert Elligator!"
  596. if len(iv) != len(set(iv)):
  597. print "Elligator inverses not unique!", len(set(iv)), len(iv)
  598. if iv != iv2:
  599. print "Elligator is untorqueable!"
  600. #print [binascii.hexlify(j) for j in iv]
  601. #print [binascii.hexlify(j) for j in iv2]
  602. #break
  603. else:
  604. pass # TODO
  605. #testElligator(Ed25519Point,100)
  606. #testElligator(NegEd25519Point,100)
  607. #testElligator(IsoEd25519Point,100)
  608. #testElligator(IsoEd448Point,100)
  609. #testElligator(Ed448GoldilocksPoint,100)
  610. #testElligator(TwistedEd448GoldilocksPoint,100)
  611. def gangtest(classes,n):
  612. print "Gang test",[cls.__name__ for cls in classes]
  613. specials = [1]
  614. ii = classes[0].F(-1)
  615. while is_square(ii):
  616. specials.append(ii)
  617. ii = sqrt(ii)
  618. specials.append(ii)
  619. for i in xrange(n):
  620. rets = [bytes((cls.base()*i).encode()) for cls in classes]
  621. if len(set(rets)) != 1:
  622. print "Divergence in encode at %d" % i
  623. for c,ret in zip(classes,rets):
  624. print c,binascii.hexlify(ret)
  625. print
  626. if i < len(specials): r0 = enc_le(specials[i],classes[0].encLen)
  627. else: r0 = randombytes(classes[0].encLen)
  628. rets = [bytes((cls.elligator(r0)*i).encode()) for cls in classes]
  629. if len(set(rets)) != 1:
  630. print "Divergence in elligator at %d" % i
  631. for c,ret in zip(classes,rets):
  632. print c,binascii.hexlify(ret)
  633. print
  634. #gangtest([IsoEd448Point,TwistedEd448GoldilocksPoint,Ed448GoldilocksPoint],100)
  635. #gangtest([Ed25519Point,IsoEd25519Point],100)