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.
 
 
 
 
 

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