_sha1.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. #!/usr/bin/env python
  2. # -*- coding: iso-8859-1 -*-
  3. # Note that PyPy contains also a built-in module 'sha' which will hide
  4. # this one if compiled in.
  5. """A sample implementation of SHA-1 in pure Python.
  6. Framework adapted from Dinu Gherman's MD5 implementation by
  7. J. Hallén and L. Creighton. SHA-1 implementation based directly on
  8. the text of the NIST standard FIPS PUB 180-1.
  9. """
  10. __date__ = '2004-11-17'
  11. __version__ = 0.91 # Modernised by J. Hallén and L. Creighton for Pypy
  12. import struct, copy
  13. # ======================================================================
  14. # Bit-Manipulation helpers
  15. #
  16. # _long2bytes() was contributed by Barry Warsaw
  17. # and is reused here with tiny modifications.
  18. # ======================================================================
  19. def _long2bytesBigEndian(n, blocksize=0):
  20. """Convert a long integer to a byte string.
  21. If optional blocksize is given and greater than zero, pad the front
  22. of the byte string with binary zeros so that the length is a multiple
  23. of blocksize.
  24. """
  25. # After much testing, this algorithm was deemed to be the fastest.
  26. s = b''
  27. pack = struct.pack
  28. while n > 0:
  29. s = pack('>I', n & 0xffffffff) + s
  30. n = n >> 32
  31. # Strip off leading zeros.
  32. for i in range(len(s)):
  33. if s[i] != '\000':
  34. break
  35. else:
  36. # Only happens when n == 0.
  37. s = '\000'
  38. i = 0
  39. s = s[i:]
  40. # Add back some pad bytes. This could be done more efficiently
  41. # w.r.t. the de-padding being done above, but sigh...
  42. if blocksize > 0 and len(s) % blocksize:
  43. s = (blocksize - len(s) % blocksize) * '\000' + s
  44. return s
  45. def _bytelist2longBigEndian(list):
  46. "Transform a list of characters into a list of longs."
  47. imax = len(list) // 4
  48. hl = [0] * imax
  49. j = 0
  50. i = 0
  51. while i < imax:
  52. b0 = list[j] << 24
  53. b1 = list[j+1] << 16
  54. b2 = list[j+2] << 8
  55. b3 = list[j+3]
  56. hl[i] = b0 | b1 | b2 | b3
  57. i = i+1
  58. j = j+4
  59. return hl
  60. def _rotateLeft(x, n):
  61. "Rotate x (32 bit) left n bits circularly."
  62. return (x << n) | (x >> (32-n))
  63. # ======================================================================
  64. # The SHA transformation functions
  65. #
  66. # ======================================================================
  67. def f0_19(B, C, D):
  68. return (B & C) | ((~ B) & D)
  69. def f20_39(B, C, D):
  70. return B ^ C ^ D
  71. def f40_59(B, C, D):
  72. return (B & C) | (B & D) | (C & D)
  73. def f60_79(B, C, D):
  74. return B ^ C ^ D
  75. f = [f0_19, f20_39, f40_59, f60_79]
  76. # Constants to be used
  77. K = [
  78. 0x5A827999, # ( 0 <= t <= 19)
  79. 0x6ED9EBA1, # (20 <= t <= 39)
  80. 0x8F1BBCDC, # (40 <= t <= 59)
  81. 0xCA62C1D6 # (60 <= t <= 79)
  82. ]
  83. class sha:
  84. "An implementation of the SHA hash function in pure Python."
  85. digest_size = digestsize = 20
  86. block_size = 512 // 8
  87. def __init__(self):
  88. "Initialisation."
  89. self.name = 'sha'
  90. # Initial message length in bits(!).
  91. self.length = 0
  92. self.count = [0, 0]
  93. # Initial empty message as a sequence of bytes (8 bit characters).
  94. self.input = []
  95. # Call a separate init function, that can be used repeatedly
  96. # to start from scratch on the same object.
  97. self.init()
  98. def init(self):
  99. "Initialize the message-digest and set all fields to zero."
  100. self.length = 0
  101. self.input = []
  102. # Initial 160 bit message digest (5 times 32 bit).
  103. self.H0 = 0x67452301
  104. self.H1 = 0xEFCDAB89
  105. self.H2 = 0x98BADCFE
  106. self.H3 = 0x10325476
  107. self.H4 = 0xC3D2E1F0
  108. def _transform(self, W):
  109. for t in range(16, 80):
  110. W.append(_rotateLeft(
  111. W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16], 1) & 0xffffffff)
  112. A = self.H0
  113. B = self.H1
  114. C = self.H2
  115. D = self.H3
  116. E = self.H4
  117. """
  118. This loop was unrolled to gain about 10% in speed
  119. for t in range(0, 80):
  120. TEMP = _rotateLeft(A, 5) + f[t/20] + E + W[t] + K[t/20]
  121. E = D
  122. D = C
  123. C = _rotateLeft(B, 30) & 0xffffffff
  124. B = A
  125. A = TEMP & 0xffffffff
  126. """
  127. for t in range(0, 20):
  128. TEMP = _rotateLeft(A, 5) + ((B & C) | ((~ B) & D)) + E + W[t] + K[0]
  129. E = D
  130. D = C
  131. C = _rotateLeft(B, 30) & 0xffffffff
  132. B = A
  133. A = TEMP & 0xffffffff
  134. for t in range(20, 40):
  135. TEMP = _rotateLeft(A, 5) + (B ^ C ^ D) + E + W[t] + K[1]
  136. E = D
  137. D = C
  138. C = _rotateLeft(B, 30) & 0xffffffff
  139. B = A
  140. A = TEMP & 0xffffffff
  141. for t in range(40, 60):
  142. TEMP = _rotateLeft(A, 5) + ((B & C) | (B & D) | (C & D)) + E + W[t] + K[2]
  143. E = D
  144. D = C
  145. C = _rotateLeft(B, 30) & 0xffffffff
  146. B = A
  147. A = TEMP & 0xffffffff
  148. for t in range(60, 80):
  149. TEMP = _rotateLeft(A, 5) + (B ^ C ^ D) + E + W[t] + K[3]
  150. E = D
  151. D = C
  152. C = _rotateLeft(B, 30) & 0xffffffff
  153. B = A
  154. A = TEMP & 0xffffffff
  155. self.H0 = (self.H0 + A) & 0xffffffff
  156. self.H1 = (self.H1 + B) & 0xffffffff
  157. self.H2 = (self.H2 + C) & 0xffffffff
  158. self.H3 = (self.H3 + D) & 0xffffffff
  159. self.H4 = (self.H4 + E) & 0xffffffff
  160. # Down from here all methods follow the Python Standard Library
  161. # API of the sha module.
  162. def update(self, inBuf):
  163. """Add to the current message.
  164. Update the md5 object with the string arg. Repeated calls
  165. are equivalent to a single call with the concatenation of all
  166. the arguments, i.e. m.update(a); m.update(b) is equivalent
  167. to m.update(a+b).
  168. The hash is immediately calculated for all full blocks. The final
  169. calculation is made in digest(). It will calculate 1-2 blocks,
  170. depending on how much padding we have to add. This allows us to
  171. keep an intermediate value for the hash, so that we only need to
  172. make minimal recalculation if we call update() to add more data
  173. to the hashed string.
  174. """
  175. if isinstance(inBuf, str):
  176. raise TypeError("Unicode strings must be encoded before hashing")
  177. leninBuf = len(inBuf)
  178. # Compute number of bytes mod 64.
  179. index = (self.count[1] >> 3) & 0x3F
  180. # Update number of bits.
  181. self.count[1] = self.count[1] + (leninBuf << 3)
  182. if self.count[1] < (leninBuf << 3):
  183. self.count[0] = self.count[0] + 1
  184. self.count[0] = self.count[0] + (leninBuf >> 29)
  185. partLen = 64 - index
  186. if leninBuf >= partLen:
  187. self.input[index:] = list(inBuf[:partLen])
  188. self._transform(_bytelist2longBigEndian(self.input))
  189. i = partLen
  190. while i + 63 < leninBuf:
  191. self._transform(_bytelist2longBigEndian(list(inBuf[i:i+64])))
  192. i = i + 64
  193. else:
  194. self.input = list(inBuf[i:leninBuf])
  195. else:
  196. i = 0
  197. self.input = self.input + list(inBuf)
  198. def digest(self):
  199. """Terminate the message-digest computation and return digest.
  200. Return the digest of the strings passed to the update()
  201. method so far. This is a 16-byte string which may contain
  202. non-ASCII characters, including null bytes.
  203. """
  204. H0 = self.H0
  205. H1 = self.H1
  206. H2 = self.H2
  207. H3 = self.H3
  208. H4 = self.H4
  209. input = [] + self.input
  210. count = [] + self.count
  211. index = (self.count[1] >> 3) & 0x3f
  212. if index < 56:
  213. padLen = 56 - index
  214. else:
  215. padLen = 120 - index
  216. padding = [0o200] + [0] * 63
  217. self.update(padding[:padLen])
  218. # Append length (before padding).
  219. bits = _bytelist2longBigEndian(self.input[:56]) + count
  220. self._transform(bits)
  221. # Store state in digest.
  222. digest = _long2bytesBigEndian(self.H0, 4) + \
  223. _long2bytesBigEndian(self.H1, 4) + \
  224. _long2bytesBigEndian(self.H2, 4) + \
  225. _long2bytesBigEndian(self.H3, 4) + \
  226. _long2bytesBigEndian(self.H4, 4)
  227. self.H0 = H0
  228. self.H1 = H1
  229. self.H2 = H2
  230. self.H3 = H3
  231. self.H4 = H4
  232. self.input = input
  233. self.count = count
  234. return digest
  235. def hexdigest(self):
  236. """Terminate and return digest in HEX form.
  237. Like digest() except the digest is returned as a string of
  238. length 32, containing only hexadecimal digits. This may be
  239. used to exchange the value safely in email or other non-
  240. binary environments.
  241. """
  242. return ''.join(['%02x' % c for c in self.digest()])
  243. def copy(self):
  244. """Return a clone object.
  245. Return a copy ('clone') of the md5 object. This can be used
  246. to efficiently compute the digests of strings that share
  247. a common initial substring.
  248. """
  249. return copy.deepcopy(self)
  250. # ======================================================================
  251. # Mimic Python top-level functions from standard library API
  252. # for consistency with the _sha module of the standard library.
  253. # ======================================================================
  254. # These are mandatory variables in the module. They have constant values
  255. # in the SHA standard.
  256. digest_size = 20
  257. digestsize = 20
  258. blocksize = 1
  259. def sha1(arg=None):
  260. """Return a new sha crypto object.
  261. If arg is present, the method call update(arg) is made.
  262. """
  263. crypto = sha()
  264. crypto.name = 'sha1'
  265. if arg:
  266. crypto.update(arg)
  267. return crypto