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.
 
 
 
 
 

481 lines
15 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. try: spec_ans = getattr(self,spec,spec)(*args,**kwargs),None
  16. except Exception as e: spec_ans = None,e
  17. try: opt_ans = f(self,*args,**kwargs),None
  18. except Exception as e: opt_ans = None,e
  19. if spec_ans[1] is None and opt_ans[1] is not None:
  20. raise
  21. #raise SpecException("Mismatch in %s: spec returned %s but opt threw %s"
  22. # % (f.__name__,str(spec_ans[0]),str(opt_ans[1])))
  23. if spec_ans[1] is not None and opt_ans[1] is None:
  24. raise
  25. #raise SpecException("Mismatch in %s: spec threw %s but opt returned %s"
  26. # % (f.__name__,str(spec_ans[1]),str(opt_ans[0])))
  27. if spec_ans[0] != opt_ans[0]:
  28. raise SpecException("Mismatch in %s: %s != %s"
  29. % (f.__name__,str(spec_ans[0]),str(opt_ans[0])))
  30. if opt_ans[1] is not None: raise
  31. else: return opt_ans[0]
  32. wrapper.__name__ = f.__name__
  33. return wrapper
  34. return decorator
  35. def xsqrt(x,exn=InvalidEncodingException("Not on curve")):
  36. """Return sqrt(x)"""
  37. if not is_square(x): raise exn
  38. s = sqrt(x)
  39. if negative(s): s=-s
  40. return s
  41. def isqrt(x,exn=InvalidEncodingException("Not on curve")):
  42. """Return 1/sqrt(x)"""
  43. if x==0: return 0
  44. if not is_square(x): raise exn
  45. return 1/sqrt(x)
  46. def isqrt_i(x):
  47. """Return 1/sqrt(x) or 1/sqrt(zeta * x)"""
  48. if x==0: return 0
  49. gen = x.parent(-1)
  50. while is_square(gen): gen = sqrt(gen)
  51. if is_square(x): return True,1/sqrt(x)
  52. else: return False,1/sqrt(x*gen)
  53. class QuotientEdwardsPoint(object):
  54. """Abstract class for point an a quotiented Edwards curve; needs F,a,d,cofactor to work"""
  55. def __init__(self,x=0,y=1):
  56. x = self.x = self.F(x)
  57. y = self.y = self.F(y)
  58. if y^2 + self.a*x^2 != 1 + self.d*x^2*y^2:
  59. raise NotOnCurveException(str(self))
  60. def __repr__(self):
  61. return "%s(0x%x,0x%x)" % (self.__class__.__name__, self.x, self.y)
  62. def __iter__(self):
  63. yield self.x
  64. yield self.y
  65. def __add__(self,other):
  66. x,y = self
  67. X,Y = other
  68. a,d = self.a,self.d
  69. return self.__class__(
  70. (x*Y+y*X)/(1+d*x*y*X*Y),
  71. (y*Y-a*x*X)/(1-d*x*y*X*Y)
  72. )
  73. def __neg__(self): return self.__class__(-self.x,self.y)
  74. def __sub__(self,other): return self + (-other)
  75. def __rmul__(self,other): return self*other
  76. def __eq__(self,other):
  77. """NB: this is the only method that is different from the usual one"""
  78. x,y = self
  79. X,Y = other
  80. return x*Y == X*y or (self.cofactor==8 and -self.a*x*X == y*Y)
  81. def __ne__(self,other): return not (self==other)
  82. def __mul__(self,exp):
  83. exp = int(exp)
  84. if exp < 0: exp,self = -exp,-self
  85. total = self.__class__()
  86. work = self
  87. while exp != 0:
  88. if exp & 1: total += work
  89. work += work
  90. exp >>= 1
  91. return total
  92. def xyzt(self):
  93. x,y = self
  94. z = self.F.random_element()
  95. return x*z,y*z,z,x*y*z
  96. def torque(self):
  97. """Apply cofactor group, except keeping the point even"""
  98. if self.cofactor == 8:
  99. if self.a == -1: return self.__class__(self.y*self.i, self.x*self.i)
  100. if self.a == 1: return self.__class__(-self.y, self.x)
  101. else:
  102. return self.__class__(-self.x, -self.y)
  103. # Utility functions
  104. @classmethod
  105. def bytesToGf(cls,bytes,mustBeProper=True,mustBePositive=False):
  106. """Convert little-endian bytes to field element, sanity check length"""
  107. if len(bytes) != cls.encLen:
  108. raise InvalidEncodingException("wrong length %d" % len(bytes))
  109. s = dec_le(bytes)
  110. if mustBeProper and s >= cls.F.modulus():
  111. raise InvalidEncodingException("%d out of range!" % s)
  112. s = cls.F(s)
  113. if mustBePositive and negative(s):
  114. raise InvalidEncodingException("%d is negative!" % s)
  115. return s
  116. @classmethod
  117. def gfToBytes(cls,x,mustBePositive=False):
  118. """Convert little-endian bytes to field element, sanity check length"""
  119. if negative(x) and mustBePositive: x = -x
  120. return enc_le(x,cls.encLen)
  121. class RistrettoPoint(QuotientEdwardsPoint):
  122. """The new Ristretto group"""
  123. def encodeSpec(self):
  124. """Unoptimized specification for encoding"""
  125. x,y = self
  126. if self.cofactor==8 and (negative(x*y) or y==0): (x,y) = self.torque()
  127. if y == -1: y = 1 # Avoid divide by 0; doesn't affect impl
  128. if negative(x): x,y = -x,-y
  129. s = xsqrt(self.a*(y-1)/(y+1),exn=Exception("Unimplemented: point is odd: " + str(self)))
  130. return self.gfToBytes(s)
  131. @classmethod
  132. def decodeSpec(cls,s):
  133. """Unoptimized specification for decoding"""
  134. s = cls.bytesToGf(s,mustBePositive=True)
  135. a,d = cls.a,cls.d
  136. x = xsqrt(4*s^2 / (a*d*(1+a*s^2)^2 - (1-a*s^2)^2))
  137. y = (1+a*s^2) / (1-a*s^2)
  138. if cls.cofactor==8 and (negative(x*y) or y==0):
  139. raise InvalidEncodingException("x*y has high bit")
  140. return cls(x,y)
  141. @optimized_version_of("encodeSpec")
  142. def encode(self):
  143. """Encode, optimized version"""
  144. a,d = self.a,self.d
  145. x,y,z,t = self.xyzt()
  146. if self.cofactor==8:
  147. u1 = a*(y+z)*(y-z)
  148. u2 = x*y # = t*z
  149. isr = isqrt(u1*u2^2)
  150. i1 = isr*u1
  151. i2 = isr*u2
  152. z_inv = i1*i2*t
  153. if negative(t*z_inv):
  154. if a==-1: x,y = y*self.i,x*self.i
  155. else: x,y = -y,x # TODO: test
  156. den_inv = self.magic * i1
  157. else:
  158. den_inv = i2
  159. if negative(x*z_inv): y = -y
  160. s = (z-y) * den_inv
  161. else:
  162. num = a*(y+z)*(y-z)
  163. isr = isqrt(num*y^2)
  164. if negative(isr^2*num*y*t): y = -y
  165. s = isr*y*(z-y)
  166. return self.gfToBytes(s,mustBePositive=True)
  167. @classmethod
  168. @optimized_version_of("decodeSpec")
  169. def decode(cls,s):
  170. """Decode, optimized version"""
  171. s = cls.bytesToGf(s,mustBePositive=True)
  172. a,d = cls.a,cls.d
  173. yden = 1-a*s^2
  174. ynum = 1+a*s^2
  175. yden_sqr = yden^2
  176. xden_sqr = a*d*ynum^2 - yden_sqr
  177. isr = isqrt(xden_sqr * yden_sqr)
  178. xden_inv = isr * yden
  179. yden_inv = xden_inv * isr * xden_sqr
  180. x = 2*s*xden_inv
  181. if negative(x): x = -x
  182. y = ynum * yden_inv
  183. if cls.cofactor==8 and (negative(x*y) or y==0):
  184. raise InvalidEncodingException("x*y is invalid: %d, %d" % (x,y))
  185. return cls(x,y)
  186. @classmethod
  187. def fromJacobiQuartic(cls,s,t,sgn=1):
  188. """Convert point from its Jacobi Quartic representation"""
  189. a,d = cls.a,cls.d
  190. assert s^4 - 2*cls.a*(1-2*d/(d-a))*s^2 + 1 == t^2
  191. x = 2*s*cls.magic / t
  192. if negative(x): x = -x # TODO: doesn't work without resolving x
  193. y = (1+a*s^2) / (1-a*s^2)
  194. return cls(sgn*x,y)
  195. @classmethod
  196. def elligatorSpec(cls,r0):
  197. a,d = cls.a,cls.d
  198. r = cls.qnr * cls.bytesToGf(r0)^2
  199. den = (d*r-a)*(a*r-d)
  200. n1 = cls.a*(r+1)*(a+d)*(d-a)/den
  201. n2 = r*n1
  202. if is_square(n1):
  203. sgn,s,t = 1,xsqrt(n1), -(r-1)*(a+d)^2 / den - 1
  204. else:
  205. sgn,s,t = -1,xsqrt(n2), r*(r-1)*(a+d)^2 / den - 1
  206. return cls.fromJacobiQuartic(s,t,sgn)
  207. @classmethod
  208. @optimized_version_of("elligatorSpec")
  209. def elligator(cls,r0):
  210. a,d = cls.a,cls.d
  211. r0 = cls.bytesToGf(r0)
  212. r = cls.qnr * r0^2
  213. den = (d*r-a)*(a*r-d)
  214. num = cls.a*(r+1)*(a+d)*(d-a)
  215. iss,isri = isqrt_i(num*den)
  216. if iss: sgn,twiddle = 1,1
  217. else: sgn,twiddle = -1,r0*cls.qnr
  218. isri *= twiddle
  219. s = isri*num
  220. t = isri*s*(r-1)*(d+a)^2 + sgn
  221. return cls.fromJacobiQuartic(s,t,sgn)
  222. class Decaf_1_1_Point(QuotientEdwardsPoint):
  223. """Like current decaf but tweaked for simplicity"""
  224. def encodeSpec(self):
  225. """Unoptimized specification for encoding"""
  226. a,d = self.a,self.d
  227. x,y = self
  228. if x==0 or y==0: return(self.gfToBytes(0))
  229. if self.cofactor==8 and negative(x*y*self.isoMagic):
  230. x,y = self.torque()
  231. isr2 = isqrt(a*(y^2-1)) * sqrt(a*d-1)
  232. sr = xsqrt(1-a*x^2)
  233. assert sr in [isr2*x*y,-isr2*x*y]
  234. altx = 1/isr2*self.isoMagic
  235. if negative(altx): s = (1+x*y*isr2)/(a*x)
  236. else: s = (1-x*y*isr2)/(a*x)
  237. return self.gfToBytes(s,mustBePositive=True)
  238. @classmethod
  239. def decodeSpec(cls,s):
  240. """Unoptimized specification for decoding"""
  241. a,d = cls.a,cls.d
  242. s = cls.bytesToGf(s,mustBePositive=True)
  243. if s==0: return cls()
  244. isr = isqrt(s^4 + 2*(a-2*d)*s^2 + 1)
  245. altx = 2*s*isr*cls.isoMagic
  246. if negative(altx): isr = -isr
  247. x = 2*s / (1+a*s^2)
  248. y = (1-a*s^2) * isr
  249. if cls.cofactor==8 and (negative(x*y*cls.isoMagic) or y==0):
  250. raise InvalidEncodingException("x*y is invalid: %d, %d" % (x,y))
  251. return cls(x,y)
  252. @optimized_version_of("encodeSpec")
  253. def encode(self):
  254. """Encode, optimized version"""
  255. a,d = self.a,self.d
  256. x,y,z,t = self.xyzt()
  257. if self.cofactor == 8:
  258. num = (z+y)*(z-y)
  259. den = x*y
  260. tmp = isqrt(num*(a-d)*den^2)
  261. if negative(tmp^2*den*num*(a-d)*t^2*self.isoMagic):
  262. den,num = num,den
  263. tmp *= sqrt(a-d) # witness that cofactor is 8
  264. yisr = x*sqrt(a)
  265. toggle = (a==1)
  266. else:
  267. yisr = y*(a*d-1)
  268. toggle = False
  269. tiisr = tmp*num
  270. altx = tiisr*t*self.isoMagic
  271. if negative(altx) != toggle: tiisr =- tiisr
  272. s = tmp*den*yisr*(tiisr*z - 1)
  273. else:
  274. num = (x+t)*(x-t)
  275. isr = isqrt(num*(a-d)*x^2)
  276. ratio = isr*num
  277. if negative(ratio*self.isoMagic): ratio=-ratio
  278. s = (a-d)*isr*x*(ratio*z - t)
  279. return self.gfToBytes(s,mustBePositive=True)
  280. @classmethod
  281. @optimized_version_of("decodeSpec")
  282. def decode(cls,s):
  283. """Decode, optimized version"""
  284. return cls.decodeSpec(s) # TODO
  285. class Ed25519Point(RistrettoPoint):
  286. F = GF(2^255-19)
  287. d = F(-121665/121666)
  288. a = F(-1)
  289. i = sqrt(F(-1))
  290. qnr = i
  291. magic = isqrt(a*d-1)
  292. cofactor = 8
  293. encLen = 32
  294. @classmethod
  295. def base(cls):
  296. y = cls.F(4/5)
  297. x = sqrt((y^2-1)/(cls.d*y^2+1))
  298. if lobit(x): x = -x
  299. return cls(x,y)
  300. class IsoEd448Point(RistrettoPoint):
  301. F = GF(2^448-2^224-1)
  302. d = F(39082/39081)
  303. a = F(1)
  304. qnr = -1
  305. magic = isqrt(a*d-1)
  306. cofactor = 4
  307. encLen = 56
  308. @classmethod
  309. def base(cls):
  310. # = ..., -3/2
  311. return cls.decodeSpec(bytearray(binascii.unhexlify(
  312. "00000000000000000000000000000000000000000000000000000000"+
  313. "fdffffffffffffffffffffffffffffffffffffffffffffffffffffff")))
  314. class TwistedEd448GoldilocksPoint(Decaf_1_1_Point):
  315. F = GF(2^448-2^224-1)
  316. d = F(-39082)
  317. a = F(-1)
  318. qnr = -1
  319. magic = isqrt(a*d-1)
  320. cofactor = 4
  321. encLen = 56
  322. isoMagic = IsoEd448Point.magic
  323. @classmethod
  324. def base(cls):
  325. return cls.decodeSpec(bytearray(binascii.unhexlify(
  326. "00000000000000000000000000000000000000000000000000000000"+
  327. "fdffffffffffffffffffffffffffffffffffffffffffffffffffffff")))
  328. class Ed448GoldilocksPoint(Decaf_1_1_Point):
  329. F = GF(2^448-2^224-1)
  330. d = F(-39081)
  331. a = F(1)
  332. qnr = -1
  333. magic = isqrt(a*d-1)
  334. cofactor = 4
  335. encLen = 56
  336. isoMagic = IsoEd448Point.magic
  337. @classmethod
  338. def base(cls):
  339. return cls.decodeSpec(bytearray(binascii.unhexlify(
  340. "00000000000000000000000000000000000000000000000000000000"+
  341. "fdffffffffffffffffffffffffffffffffffffffffffffffffffffff")))
  342. class IsoEd25519Point(Decaf_1_1_Point):
  343. # TODO: twisted iso too!
  344. # TODO: twisted iso might have to IMAGINE_TWIST or whatever
  345. F = GF(2^255-19)
  346. d = F(-121665)
  347. a = F(1)
  348. i = sqrt(F(-1))
  349. qnr = i
  350. magic = isqrt(a*d-1)
  351. cofactor = 8
  352. encLen = 32
  353. isoMagic = Ed25519Point.magic
  354. isoA = Ed25519Point.a
  355. @classmethod
  356. def base(cls):
  357. return cls.decodeSpec(Ed25519Point.base().encode())
  358. class TestFailedException(Exception): pass
  359. def test(cls,n):
  360. # TODO: test corner cases like 0,1,i
  361. P = cls.base()
  362. Q = cls()
  363. for i in xrange(n):
  364. #print binascii.hexlify(Q.encode())
  365. QQ = cls.decode(Q.encode())
  366. if QQ != Q: raise TestFailedException("Round trip %s != %s" % (str(QQ),str(Q)))
  367. QT = Q
  368. QE = Q.encode()
  369. for h in xrange(cls.cofactor):
  370. QT = QT.torque()
  371. if QT.encode() != QE:
  372. raise TestFailedException("Can't torque %s,%d" % (str(Q),h+1))
  373. Q0 = Q + P
  374. if Q0 == Q: raise TestFailedException("Addition doesn't work")
  375. if Q0-P != Q: raise TestFailedException("Subtraction doesn't work")
  376. r = randint(1,1000)
  377. Q1 = Q0*r
  378. Q2 = Q0*(r+1)
  379. if Q1 + Q0 != Q2: raise TestFailedException("Scalarmul doesn't work")
  380. Q = Q1
  381. test(Ed25519Point,100)
  382. test(IsoEd25519Point,100)
  383. test(IsoEd448Point,100)
  384. test(TwistedEd448GoldilocksPoint,100)
  385. test(Ed448GoldilocksPoint,100)
  386. def gangtest(classes,n):
  387. for i in xrange(n):
  388. rets = [bytes((cls.base()*i).encode()) for cls in classes]
  389. if len(set(rets)) != 1:
  390. print "Divergence at %d" % i
  391. for c,ret in zip(classes,rets):
  392. print c,binascii.hexlify(ret)
  393. print
  394. gangtest([IsoEd448Point,TwistedEd448GoldilocksPoint,Ed448GoldilocksPoint],100)
  395. gangtest([Ed25519Point,IsoEd25519Point],100)
  396. def testElligator(cls,n):
  397. for i in xrange(n):
  398. cls.elligator(randombytes(cls.encLen))
  399. testElligator(Ed25519Point,100)
  400. testElligator(IsoEd448Point,100)
  401. # testElligator(Ed448GoldilocksPoint,100)
  402. # testElligator(TwistedEd448GoldilocksPoint,100)