djbec.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. # Ed25519 digital signatures
  2. # Based on http://ed25519.cr.yp.to/python/ed25519.py
  3. # See also http://ed25519.cr.yp.to/software.html
  4. # Adapted by Ron Garret
  5. # Sped up considerably using coordinate transforms found on:
  6. # http://www.hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
  7. # Specifically add-2008-hwcd-4 and dbl-2008-hwcd
  8. try: # pragma nocover
  9. unicode
  10. PY3 = False
  11. def asbytes(b):
  12. """Convert array of integers to byte string"""
  13. return ''.join(chr(x) for x in b)
  14. def joinbytes(b):
  15. """Convert array of bytes to byte string"""
  16. return ''.join(b)
  17. def bit(h, i):
  18. """Return i'th bit of bytestring h"""
  19. return (ord(h[i//8]) >> (i%8)) & 1
  20. except NameError: # pragma nocover
  21. PY3 = True
  22. asbytes = bytes
  23. joinbytes = bytes
  24. def bit(h, i):
  25. return (h[i//8] >> (i%8)) & 1
  26. import hashlib
  27. b = 256
  28. q = 2**255 - 19
  29. l = 2**252 + 27742317777372353535851937790883648493
  30. def H(m):
  31. return hashlib.sha512(m).digest()
  32. def expmod(b, e, m):
  33. if e == 0: return 1
  34. t = expmod(b, e // 2, m) ** 2 % m
  35. if e & 1: t = (t * b) % m
  36. return t
  37. # Can probably get some extra speedup here by replacing this with
  38. # an extended-euclidean, but performance seems OK without that
  39. def inv(x):
  40. return expmod(x, q-2, q)
  41. d = -121665 * inv(121666)
  42. I = expmod(2,(q-1)//4,q)
  43. def xrecover(y):
  44. xx = (y*y-1) * inv(d*y*y+1)
  45. x = expmod(xx,(q+3)//8,q)
  46. if (x*x - xx) % q != 0: x = (x*I) % q
  47. if x % 2 != 0: x = q-x
  48. return x
  49. By = 4 * inv(5)
  50. Bx = xrecover(By)
  51. B = [Bx % q,By % q]
  52. #def edwards(P,Q):
  53. # x1 = P[0]
  54. # y1 = P[1]
  55. # x2 = Q[0]
  56. # y2 = Q[1]
  57. # x3 = (x1*y2+x2*y1) * inv(1+d*x1*x2*y1*y2)
  58. # y3 = (y1*y2+x1*x2) * inv(1-d*x1*x2*y1*y2)
  59. # return (x3 % q,y3 % q)
  60. #def scalarmult(P,e):
  61. # if e == 0: return [0,1]
  62. # Q = scalarmult(P,e/2)
  63. # Q = edwards(Q,Q)
  64. # if e & 1: Q = edwards(Q,P)
  65. # return Q
  66. # Faster (!) version based on:
  67. # http://www.hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
  68. def xpt_add(pt1, pt2):
  69. (X1, Y1, Z1, T1) = pt1
  70. (X2, Y2, Z2, T2) = pt2
  71. A = ((Y1-X1)*(Y2+X2)) % q
  72. B = ((Y1+X1)*(Y2-X2)) % q
  73. C = (Z1*2*T2) % q
  74. D = (T1*2*Z2) % q
  75. E = (D+C) % q
  76. F = (B-A) % q
  77. G = (B+A) % q
  78. H = (D-C) % q
  79. X3 = (E*F) % q
  80. Y3 = (G*H) % q
  81. Z3 = (F*G) % q
  82. T3 = (E*H) % q
  83. return (X3, Y3, Z3, T3)
  84. def xpt_double (pt):
  85. (X1, Y1, Z1, _) = pt
  86. A = (X1*X1)
  87. B = (Y1*Y1)
  88. C = (2*Z1*Z1)
  89. D = (-A) % q
  90. J = (X1+Y1) % q
  91. E = (J*J-A-B) % q
  92. G = (D+B) % q
  93. F = (G-C) % q
  94. H = (D-B) % q
  95. X3 = (E*F) % q
  96. Y3 = (G*H) % q
  97. Z3 = (F*G) % q
  98. T3 = (E*H) % q
  99. return (X3, Y3, Z3, T3)
  100. def pt_xform (pt):
  101. (x, y) = pt
  102. return (x, y, 1, (x*y)%q)
  103. def pt_unxform (pt):
  104. (x, y, z, _) = pt
  105. return ((x*inv(z))%q, (y*inv(z))%q)
  106. def xpt_mult (pt, n):
  107. if n==0: return pt_xform((0,1))
  108. _ = xpt_double(xpt_mult(pt, n>>1))
  109. return xpt_add(_, pt) if n&1 else _
  110. def scalarmult(pt, e):
  111. return pt_unxform(xpt_mult(pt_xform(pt), e))
  112. def encodeint(y):
  113. bits = [(y >> i) & 1 for i in range(b)]
  114. e = [(sum([bits[i * 8 + j] << j for j in range(8)]))
  115. for i in range(b//8)]
  116. return asbytes(e)
  117. def encodepoint(P):
  118. x = P[0]
  119. y = P[1]
  120. bits = [(y >> i) & 1 for i in range(b - 1)] + [x & 1]
  121. e = [(sum([bits[i * 8 + j] << j for j in range(8)]))
  122. for i in range(b//8)]
  123. return asbytes(e)
  124. def publickey(sk):
  125. h = H(sk)
  126. a = 2**(b-2) + sum(2**i * bit(h,i) for i in range(3,b-2))
  127. A = scalarmult(B,a)
  128. return encodepoint(A)
  129. def Hint(m):
  130. h = H(m)
  131. return sum(2**i * bit(h,i) for i in range(2*b))
  132. def signature(m,sk,pk):
  133. h = H(sk)
  134. a = 2**(b-2) + sum(2**i * bit(h,i) for i in range(3,b-2))
  135. inter = joinbytes([h[i] for i in range(b//8,b//4)])
  136. r = Hint(inter + m)
  137. R = scalarmult(B,r)
  138. S = (r + Hint(encodepoint(R) + pk + m) * a) % l
  139. return encodepoint(R) + encodeint(S)
  140. def isoncurve(P):
  141. x = P[0]
  142. y = P[1]
  143. return (-x*x + y*y - 1 - d*x*x*y*y) % q == 0
  144. def decodeint(s):
  145. return sum(2**i * bit(s,i) for i in range(0,b))
  146. def decodepoint(s):
  147. y = sum(2**i * bit(s,i) for i in range(0,b-1))
  148. x = xrecover(y)
  149. if x & 1 != bit(s,b-1): x = q-x
  150. P = [x,y]
  151. if not isoncurve(P): raise Exception("decoding point that is not on curve")
  152. return P
  153. def checkvalid(s, m, pk):
  154. if len(s) != b//4: raise Exception("signature length is wrong")
  155. if len(pk) != b//8: raise Exception("public-key length is wrong")
  156. R = decodepoint(s[0:b//8])
  157. A = decodepoint(pk)
  158. S = decodeint(s[b//8:b//4])
  159. h = Hint(encodepoint(R) + pk + m)
  160. v1 = scalarmult(B,S)
  161. # v2 = edwards(R,scalarmult(A,h))
  162. v2 = pt_unxform(xpt_add(pt_xform(R), pt_xform(scalarmult(A, h))))
  163. return v1==v2
  164. ##########################################################
  165. #
  166. # Curve25519 reference implementation by Matthew Dempsky, from:
  167. # http://cr.yp.to/highspeed/naclcrypto-20090310.pdf
  168. # P = 2 ** 255 - 19
  169. P = q
  170. A = 486662
  171. #def expmod(b, e, m):
  172. # if e == 0: return 1
  173. # t = expmod(b, e / 2, m) ** 2 % m
  174. # if e & 1: t = (t * b) % m
  175. # return t
  176. # def inv(x): return expmod(x, P - 2, P)
  177. def add(n, m, d):
  178. (xn, zn) = n
  179. (xm, zm) = m
  180. (xd, zd) = d
  181. x = 4 * (xm * xn - zm * zn) ** 2 * zd
  182. z = 4 * (xm * zn - zm * xn) ** 2 * xd
  183. return (x % P, z % P)
  184. def double(n):
  185. (xn, zn) = n
  186. x = (xn ** 2 - zn ** 2) ** 2
  187. z = 4 * xn * zn * (xn ** 2 + A * xn * zn + zn ** 2)
  188. return (x % P, z % P)
  189. def curve25519(n, base=9):
  190. one = (base,1)
  191. two = double(one)
  192. # f(m) evaluates to a tuple
  193. # containing the mth multiple and the
  194. # (m+1)th multiple of base.
  195. def f(m):
  196. if m == 1: return (one, two)
  197. (pm, pm1) = f(m // 2)
  198. if (m & 1):
  199. return (add(pm, pm1, one), double(pm1))
  200. return (double(pm), add(pm, pm1, one))
  201. ((x,z), _) = f(n)
  202. return (x * inv(z)) % P
  203. import random
  204. def genkey(n=0):
  205. n = n or random.randint(0,P)
  206. n &= ~7
  207. n &= ~(128 << 8 * 31)
  208. n |= 64 << 8 * 31
  209. return n
  210. #def str2int(s):
  211. # return int(hexlify(s), 16)
  212. # # return sum(ord(s[i]) << (8 * i) for i in range(32))
  213. #
  214. #def int2str(n):
  215. # return unhexlify("%x" % n)
  216. # # return ''.join([chr((n >> (8 * i)) & 255) for i in range(32)])
  217. #################################################
  218. def dsa_test():
  219. import os
  220. msg = str(random.randint(q,q+q)).encode('utf-8')
  221. sk = os.urandom(32)
  222. pk = publickey(sk)
  223. sig = signature(msg, sk, pk)
  224. return checkvalid(sig, msg, pk)
  225. def dh_test():
  226. sk1 = genkey()
  227. sk2 = genkey()
  228. return curve25519(sk1, curve25519(sk2)) == curve25519(sk2, curve25519(sk1))