djbec.py 6.9 KB

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