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.
 
 
 
 
 

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