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.
 
 
 
 
 

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