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.
 
 
 
 
 

604 lines
19 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. n1 = cls.a*(r+1)*(a+d)*(d-a)/den
  206. n2 = r*n1
  207. if is_square(n1):
  208. sgn,s,t = 1, xsqrt(n1), -(r-1)*(a+d)^2 / den - 1
  209. else:
  210. sgn,s,t = -1,-xsqrt(n2), r*(r-1)*(a+d)^2 / den - 1
  211. return cls.fromJacobiQuartic(s,t)
  212. @classmethod
  213. @optimized_version_of("elligatorSpec")
  214. def elligator(cls,r0):
  215. a,d = cls.a,cls.d
  216. r0 = cls.bytesToGf(r0)
  217. r = cls.qnr * r0^2
  218. den = (d*r-a)*(a*r-d)
  219. num = cls.a*(r+1)*(a+d)*(d-a)
  220. iss,isri = isqrt_i(num*den)
  221. if iss: sgn,twiddle = 1,1
  222. else: sgn,twiddle = -1,r0*cls.qnr
  223. isri *= twiddle
  224. s = isri*num
  225. t = -sgn*isri*s*(r-1)*(d+a)^2 - 1
  226. if negative(s) == iss: s = -s
  227. return cls.fromJacobiQuartic(s,t)
  228. class Decaf_1_1_Point(QuotientEdwardsPoint):
  229. """Like current decaf but tweaked for simplicity"""
  230. def encodeSpec(self):
  231. """Unoptimized specification for encoding"""
  232. a,d = self.a,self.d
  233. x,y = self
  234. if x==0 or y==0: return(self.gfToBytes(0))
  235. if self.cofactor==8 and negative(x*y*self.isoMagic):
  236. x,y = self.torque()
  237. isr2 = isqrt(a*(y^2-1)) * sqrt(a*d-1)
  238. sr = xsqrt(1-a*x^2)
  239. assert sr in [isr2*x*y,-isr2*x*y]
  240. altx = 1/isr2*self.isoMagic
  241. if negative(altx): s = (1+x*y*isr2)/(a*x)
  242. else: s = (1-x*y*isr2)/(a*x)
  243. return self.gfToBytes(s,mustBePositive=True)
  244. @classmethod
  245. def decodeSpec(cls,s):
  246. """Unoptimized specification for decoding"""
  247. a,d = cls.a,cls.d
  248. s = cls.bytesToGf(s,mustBePositive=True)
  249. if s==0: return cls()
  250. isr = isqrt(s^4 + 2*(a-2*d)*s^2 + 1)
  251. altx = 2*s*isr*cls.isoMagic
  252. if negative(altx): isr = -isr
  253. x = 2*s / (1+a*s^2)
  254. y = (1-a*s^2) * isr
  255. if cls.cofactor==8 and (negative(x*y*cls.isoMagic) or y==0):
  256. raise InvalidEncodingException("x*y is invalid: %d, %d" % (x,y))
  257. return cls(x,y)
  258. @optimized_version_of("encodeSpec")
  259. def encode(self):
  260. """Encode, optimized version"""
  261. a,d = self.a,self.d
  262. x,y,z,t = self.xyzt()
  263. if self.cofactor == 8:
  264. # Cofactor 8 version
  265. num = (z+y)*(z-y)
  266. den = x*y
  267. tmp = isqrt(num*(a-d)*den^2)
  268. if negative(tmp^2*den*num*(a-d)*t^2*self.isoMagic):
  269. den,num = num,den
  270. tmp *= sqrt(a-d) # witness that cofactor is 8
  271. yisr = x*sqrt(a)
  272. toggle = (a==1)
  273. else:
  274. yisr = y*(a*d-1)
  275. toggle = False
  276. tiisr = tmp*num
  277. altx = tiisr*t*self.isoMagic
  278. if negative(altx) != toggle: tiisr =- tiisr
  279. s = tmp*den*yisr*(tiisr*z - 1)
  280. else:
  281. # Much simpler cofactor 4 version
  282. num = (x+t)*(x-t)
  283. isr = isqrt(num*(a-d)*x^2)
  284. ratio = isr*num
  285. if negative(ratio*self.isoMagic): ratio=-ratio
  286. s = (a-d)*isr*x*(ratio*z - t)
  287. return self.gfToBytes(s,mustBePositive=True)
  288. @classmethod
  289. @optimized_version_of("decodeSpec")
  290. def decode(cls,s):
  291. """Decode, optimized version"""
  292. a,d = cls.a,cls.d
  293. s = cls.bytesToGf(s,mustBePositive=True)
  294. if s==0: return cls()
  295. s2 = s^2
  296. den = 1+a*s2
  297. num = den^2 - 4*d*s2
  298. isr = isqrt(num*den^2)
  299. altx = 2*s*isr*den*cls.isoMagic
  300. if negative(altx): isr = -isr
  301. x = 2*s *isr^2*den*num
  302. y = (1-a*s^2) * isr*den
  303. if cls.cofactor==8 and (negative(x*y*cls.isoMagic) or y==0):
  304. raise InvalidEncodingException("x*y is invalid: %d, %d" % (x,y))
  305. return cls(x,y)
  306. @classmethod
  307. def fromJacobiQuartic(cls,s,t,sgn=1):
  308. """Convert point from its Jacobi Quartic representation"""
  309. a,d = cls.a,cls.d
  310. if s==0: return cls()
  311. x = 2*s / (1+a*s^2)
  312. y = (1-a*s^2) / t
  313. return cls(x,sgn*y)
  314. @classmethod
  315. def elligatorSpec(cls,r0):
  316. a,d = cls.a,cls.d
  317. r = cls.qnr * cls.bytesToGf(r0)^2
  318. den = (d*r-(d-a))*((d-a)*r-d)
  319. n1 = (r+1)*(a-2*d)/den
  320. n2 = r*n1
  321. if is_square(n1):
  322. sgn,s,t = 1, xsqrt(n1), -(r-1)*(a-2*d)^2 / den - 1
  323. else:
  324. sgn,s,t = -1, -xsqrt(n2), r*(r-1)*(a-2*d)^2 / den - 1
  325. return cls.fromJacobiQuartic(s,t)
  326. @classmethod
  327. @optimized_version_of("elligatorSpec")
  328. def elligator(cls,r0):
  329. a,d = cls.a,cls.d
  330. r0 = cls.bytesToGf(r0)
  331. r = cls.qnr * r0^2
  332. den = (d*r-(d-a))*((d-a)*r-d)
  333. num = (r+1)*(a-2*d)
  334. iss,isri = isqrt_i(num*den)
  335. if iss: sgn,twiddle = 1,1
  336. else: sgn,twiddle = -1,r0*cls.qnr
  337. isri *= twiddle
  338. s = isri*num
  339. t = -sgn*isri*s*(r-1)*(a-2*d)^2 - 1
  340. if negative(s) == iss: s = -s
  341. return cls.fromJacobiQuartic(s,t)
  342. class Ed25519Point(RistrettoPoint):
  343. F = GF(2^255-19)
  344. d = F(-121665/121666)
  345. a = F(-1)
  346. i = sqrt(F(-1))
  347. mneg = F(1)
  348. qnr = i
  349. magic = isqrt(a*d-1)
  350. cofactor = 8
  351. encLen = 32
  352. @classmethod
  353. def base(cls):
  354. return cls( 15112221349535400772501151409588531511454012693041857206046113283949847762202, 46316835694926478169428394003475163141307993866256225615783033603165251855960
  355. )
  356. class NegEd25519Point(RistrettoPoint):
  357. F = GF(2^255-19)
  358. d = F(121665/121666)
  359. a = F(1)
  360. i = sqrt(F(-1))
  361. mneg = F(-1) # TODO checkme vs 1-ad or whatever
  362. qnr = i
  363. magic = isqrt(a*d-1)
  364. cofactor = 8
  365. encLen = 32
  366. @classmethod
  367. def base(cls):
  368. y = cls.F(4/5)
  369. x = sqrt((y^2-1)/(cls.d*y^2-cls.a))
  370. if negative(x): x = -x
  371. return cls(x,y)
  372. class IsoEd448Point(RistrettoPoint):
  373. F = GF(2^448-2^224-1)
  374. d = F(39082/39081)
  375. a = F(1)
  376. mneg = F(-1)
  377. qnr = -1
  378. magic = isqrt(a*d-1)
  379. cofactor = 4
  380. encLen = 56
  381. @classmethod
  382. def base(cls):
  383. return cls( # RFC has it wrong
  384. -345397493039729516374008604150537410266655260075183290216406970281645695073672344430481787759340633221708391583424041788924124567700732,
  385. -363419362147803445274661903944002267176820680343659030140745099590306164083365386343198191849338272965044442230921818680526749009182718
  386. )
  387. class TwistedEd448GoldilocksPoint(Decaf_1_1_Point):
  388. F = GF(2^448-2^224-1)
  389. d = F(-39082)
  390. a = F(-1)
  391. qnr = -1
  392. magic = isqrt(a*d-1)
  393. cofactor = 4
  394. encLen = 56
  395. isoMagic = IsoEd448Point.magic
  396. @classmethod
  397. def base(cls):
  398. return cls.decodeSpec(Ed448GoldilocksPoint.base().encodeSpec())
  399. class Ed448GoldilocksPoint(Decaf_1_1_Point):
  400. F = GF(2^448-2^224-1)
  401. d = F(-39081)
  402. a = F(1)
  403. qnr = -1
  404. magic = isqrt(a*d-1)
  405. cofactor = 4
  406. encLen = 56
  407. isoMagic = IsoEd448Point.magic
  408. @classmethod
  409. def base(cls):
  410. return -2*cls( # FIXME: make not negative
  411. 224580040295924300187604334099896036246789641632564134246125461686950415467406032909029192869357953282578032075146446173674602635247710, 298819210078481492676017930443930673437544040154080242095928241372331506189835876003536878655418784733982303233503462500531545062832660
  412. )
  413. class IsoEd25519Point(Decaf_1_1_Point):
  414. # TODO: twisted iso too!
  415. # TODO: twisted iso might have to IMAGINE_TWIST or whatever
  416. F = GF(2^255-19)
  417. d = F(-121665)
  418. a = F(1)
  419. i = sqrt(F(-1))
  420. qnr = i
  421. magic = isqrt(a*d-1)
  422. cofactor = 8
  423. encLen = 32
  424. isoMagic = Ed25519Point.magic
  425. isoA = Ed25519Point.a
  426. @classmethod
  427. def base(cls):
  428. return cls.decodeSpec(Ed25519Point.base().encode())
  429. class TestFailedException(Exception): pass
  430. def test(cls,n):
  431. print "Testing curve %s" % cls.__name__
  432. specials = [1]
  433. ii = cls.F(-1)
  434. while is_square(ii):
  435. specials.append(ii)
  436. ii = sqrt(ii)
  437. specials.append(ii)
  438. for i in specials:
  439. if negative(cls.F(i)): i = -i
  440. i = enc_le(i,cls.encLen)
  441. try:
  442. Q = cls.decode(i)
  443. QE = Q.encode()
  444. if QE != i:
  445. raise TestFailedException("Round trip special %s != %s" %
  446. (binascii.hexlify(QE),binascii.hexlify(i)))
  447. except NotOnCurveException: pass
  448. except InvalidEncodingException: pass
  449. P = cls.base()
  450. Q = cls()
  451. for i in xrange(n):
  452. #print binascii.hexlify(Q.encode())
  453. QQ = cls.decode(Q.encode())
  454. if QQ != Q: raise TestFailedException("Round trip %s != %s" % (str(QQ),str(Q)))
  455. QT = Q
  456. QE = Q.encode()
  457. for h in xrange(cls.cofactor):
  458. QT = QT.torque()
  459. if QT.encode() != QE:
  460. raise TestFailedException("Can't torque %s,%d" % (str(Q),h+1))
  461. Q0 = Q + P
  462. if Q0 == Q: raise TestFailedException("Addition doesn't work")
  463. if Q0-P != Q: raise TestFailedException("Subtraction doesn't work")
  464. r = randint(1,1000)
  465. Q1 = Q0*r
  466. Q2 = Q0*(r+1)
  467. if Q1 + Q0 != Q2: raise TestFailedException("Scalarmul doesn't work")
  468. Q = Q1
  469. test(Ed25519Point,100)
  470. test(NegEd25519Point,100)
  471. test(IsoEd25519Point,100)
  472. test(IsoEd448Point,100)
  473. test(TwistedEd448GoldilocksPoint,100)
  474. test(Ed448GoldilocksPoint,100)
  475. def testElligator(cls,n):
  476. print "Testing elligator on %s" % cls.__name__
  477. for i in xrange(n):
  478. cls.elligator(randombytes(cls.encLen))
  479. testElligator(Ed25519Point,100)
  480. testElligator(NegEd25519Point,100)
  481. testElligator(IsoEd448Point,100)
  482. testElligator(Ed448GoldilocksPoint,100)
  483. testElligator(TwistedEd448GoldilocksPoint,100)
  484. def gangtest(classes,n):
  485. print "Gang test",[cls.__name__ for cls in classes]
  486. specials = [1]
  487. ii = classes[0].F(-1)
  488. while is_square(ii):
  489. specials.append(ii)
  490. ii = sqrt(ii)
  491. specials.append(ii)
  492. for i in xrange(n):
  493. rets = [bytes((cls.base()*i).encode()) for cls in classes]
  494. if len(set(rets)) != 1:
  495. print "Divergence in encode at %d" % i
  496. for c,ret in zip(classes,rets):
  497. print c,binascii.hexlify(ret)
  498. print
  499. if i < len(specials): r0 = enc_le(specials[i],classes[0].encLen)
  500. else: r0 = randombytes(classes[0].encLen)
  501. rets = [bytes((cls.elligator(r0)*i).encode()) for cls in classes]
  502. if len(set(rets)) != 1:
  503. print "Divergence in elligator at %d" % i
  504. for c,ret in zip(classes,rets):
  505. print c,binascii.hexlify(ret)
  506. print
  507. gangtest([IsoEd448Point,TwistedEd448GoldilocksPoint,Ed448GoldilocksPoint],100)
  508. gangtest([Ed25519Point,IsoEd25519Point],100)