_md5.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. #!/usr/bin/env python
  2. # -*- coding: iso-8859-1 -*-
  3. # Note that PyPy contains also a built-in module 'md5' which will hide
  4. # this one if compiled in.
  5. """A sample implementation of MD5 in pure Python.
  6. This is an implementation of the MD5 hash function, as specified by
  7. RFC 1321, in pure Python. It was implemented using Bruce Schneier's
  8. excellent book "Applied Cryptography", 2nd ed., 1996.
  9. Surely this is not meant to compete with the existing implementation
  10. of the Python standard library (written in C). Rather, it should be
  11. seen as a Python complement that is more readable than C and can be
  12. used more conveniently for learning and experimenting purposes in
  13. the field of cryptography.
  14. This module tries very hard to follow the API of the existing Python
  15. standard library's "md5" module, but although it seems to work fine,
  16. it has not been extensively tested! (But note that there is a test
  17. module, test_md5py.py, that compares this Python implementation with
  18. the C one of the Python standard library.
  19. BEWARE: this comes with no guarantee whatsoever about fitness and/or
  20. other properties! Specifically, do not use this in any production
  21. code! License is Python License!
  22. Special thanks to Aurelian Coman who fixed some nasty bugs!
  23. Dinu C. Gherman
  24. """
  25. __date__ = '2004-11-17'
  26. __version__ = 0.91 # Modernised by J. Hallén and L. Creighton for Pypy
  27. __metaclass__ = type # or genrpy won't work
  28. import struct, copy
  29. # ======================================================================
  30. # Bit-Manipulation helpers
  31. # ======================================================================
  32. def _bytelist2long(list):
  33. "Transform a list of characters into a list of longs."
  34. imax = len(list) // 4
  35. hl = [0] * imax
  36. j = 0
  37. i = 0
  38. while i < imax:
  39. b0 = list[j]
  40. b1 = list[j+1] << 8
  41. b2 = list[j+2] << 16
  42. b3 = list[j+3] << 24
  43. hl[i] = b0 | b1 |b2 | b3
  44. i = i+1
  45. j = j+4
  46. return hl
  47. def _rotateLeft(x, n):
  48. "Rotate x (32 bit) left n bits circularly."
  49. return (x << n) | (x >> (32-n))
  50. # ======================================================================
  51. # The real MD5 meat...
  52. #
  53. # Implemented after "Applied Cryptography", 2nd ed., 1996,
  54. # pp. 436-441 by Bruce Schneier.
  55. # ======================================================================
  56. # F, G, H and I are basic MD5 functions.
  57. def F(x, y, z):
  58. return (x & y) | ((~x) & z)
  59. def G(x, y, z):
  60. return (x & z) | (y & (~z))
  61. def H(x, y, z):
  62. return x ^ y ^ z
  63. def I(x, y, z):
  64. return y ^ (x | (~z))
  65. def XX(func, a, b, c, d, x, s, ac):
  66. """Wrapper for call distribution to functions F, G, H and I.
  67. This replaces functions FF, GG, HH and II from "Appl. Crypto."
  68. Rotation is separate from addition to prevent recomputation
  69. (now summed-up in one function).
  70. """
  71. res = 0
  72. res = res + a + func(b, c, d)
  73. res = res + x
  74. res = res + ac
  75. res = res & 0xffffffff
  76. res = _rotateLeft(res, s)
  77. res = res & 0xffffffff
  78. res = res + b
  79. return res & 0xffffffff
  80. class md5:
  81. "An implementation of the MD5 hash function in pure Python."
  82. digest_size = digestsize = 16
  83. block_size = 64
  84. def __init__(self, arg=None):
  85. "Initialisation."
  86. # Initial message length in bits(!).
  87. self.length = 0
  88. self.count = [0, 0]
  89. # Initial empty message as a sequence of bytes (8 bit characters).
  90. self.input = []
  91. # Call a separate init function, that can be used repeatedly
  92. # to start from scratch on the same object.
  93. self.init()
  94. if arg:
  95. self.update(arg)
  96. def init(self):
  97. "Initialize the message-digest and set all fields to zero."
  98. self.length = 0
  99. self.count = [0, 0]
  100. self.input = []
  101. # Load magic initialization constants.
  102. self.A = 0x67452301
  103. self.B = 0xefcdab89
  104. self.C = 0x98badcfe
  105. self.D = 0x10325476
  106. def _transform(self, inp):
  107. """Basic MD5 step transforming the digest based on the input.
  108. Note that if the Mysterious Constants are arranged backwards
  109. in little-endian order and decrypted with the DES they produce
  110. OCCULT MESSAGES!
  111. """
  112. a, b, c, d = A, B, C, D = self.A, self.B, self.C, self.D
  113. # Round 1.
  114. S11, S12, S13, S14 = 7, 12, 17, 22
  115. a = XX(F, a, b, c, d, inp[ 0], S11, 0xD76AA478) # 1
  116. d = XX(F, d, a, b, c, inp[ 1], S12, 0xE8C7B756) # 2
  117. c = XX(F, c, d, a, b, inp[ 2], S13, 0x242070DB) # 3
  118. b = XX(F, b, c, d, a, inp[ 3], S14, 0xC1BDCEEE) # 4
  119. a = XX(F, a, b, c, d, inp[ 4], S11, 0xF57C0FAF) # 5
  120. d = XX(F, d, a, b, c, inp[ 5], S12, 0x4787C62A) # 6
  121. c = XX(F, c, d, a, b, inp[ 6], S13, 0xA8304613) # 7
  122. b = XX(F, b, c, d, a, inp[ 7], S14, 0xFD469501) # 8
  123. a = XX(F, a, b, c, d, inp[ 8], S11, 0x698098D8) # 9
  124. d = XX(F, d, a, b, c, inp[ 9], S12, 0x8B44F7AF) # 10
  125. c = XX(F, c, d, a, b, inp[10], S13, 0xFFFF5BB1) # 11
  126. b = XX(F, b, c, d, a, inp[11], S14, 0x895CD7BE) # 12
  127. a = XX(F, a, b, c, d, inp[12], S11, 0x6B901122) # 13
  128. d = XX(F, d, a, b, c, inp[13], S12, 0xFD987193) # 14
  129. c = XX(F, c, d, a, b, inp[14], S13, 0xA679438E) # 15
  130. b = XX(F, b, c, d, a, inp[15], S14, 0x49B40821) # 16
  131. # Round 2.
  132. S21, S22, S23, S24 = 5, 9, 14, 20
  133. a = XX(G, a, b, c, d, inp[ 1], S21, 0xF61E2562) # 17
  134. d = XX(G, d, a, b, c, inp[ 6], S22, 0xC040B340) # 18
  135. c = XX(G, c, d, a, b, inp[11], S23, 0x265E5A51) # 19
  136. b = XX(G, b, c, d, a, inp[ 0], S24, 0xE9B6C7AA) # 20
  137. a = XX(G, a, b, c, d, inp[ 5], S21, 0xD62F105D) # 21
  138. d = XX(G, d, a, b, c, inp[10], S22, 0x02441453) # 22
  139. c = XX(G, c, d, a, b, inp[15], S23, 0xD8A1E681) # 23
  140. b = XX(G, b, c, d, a, inp[ 4], S24, 0xE7D3FBC8) # 24
  141. a = XX(G, a, b, c, d, inp[ 9], S21, 0x21E1CDE6) # 25
  142. d = XX(G, d, a, b, c, inp[14], S22, 0xC33707D6) # 26
  143. c = XX(G, c, d, a, b, inp[ 3], S23, 0xF4D50D87) # 27
  144. b = XX(G, b, c, d, a, inp[ 8], S24, 0x455A14ED) # 28
  145. a = XX(G, a, b, c, d, inp[13], S21, 0xA9E3E905) # 29
  146. d = XX(G, d, a, b, c, inp[ 2], S22, 0xFCEFA3F8) # 30
  147. c = XX(G, c, d, a, b, inp[ 7], S23, 0x676F02D9) # 31
  148. b = XX(G, b, c, d, a, inp[12], S24, 0x8D2A4C8A) # 32
  149. # Round 3.
  150. S31, S32, S33, S34 = 4, 11, 16, 23
  151. a = XX(H, a, b, c, d, inp[ 5], S31, 0xFFFA3942) # 33
  152. d = XX(H, d, a, b, c, inp[ 8], S32, 0x8771F681) # 34
  153. c = XX(H, c, d, a, b, inp[11], S33, 0x6D9D6122) # 35
  154. b = XX(H, b, c, d, a, inp[14], S34, 0xFDE5380C) # 36
  155. a = XX(H, a, b, c, d, inp[ 1], S31, 0xA4BEEA44) # 37
  156. d = XX(H, d, a, b, c, inp[ 4], S32, 0x4BDECFA9) # 38
  157. c = XX(H, c, d, a, b, inp[ 7], S33, 0xF6BB4B60) # 39
  158. b = XX(H, b, c, d, a, inp[10], S34, 0xBEBFBC70) # 40
  159. a = XX(H, a, b, c, d, inp[13], S31, 0x289B7EC6) # 41
  160. d = XX(H, d, a, b, c, inp[ 0], S32, 0xEAA127FA) # 42
  161. c = XX(H, c, d, a, b, inp[ 3], S33, 0xD4EF3085) # 43
  162. b = XX(H, b, c, d, a, inp[ 6], S34, 0x04881D05) # 44
  163. a = XX(H, a, b, c, d, inp[ 9], S31, 0xD9D4D039) # 45
  164. d = XX(H, d, a, b, c, inp[12], S32, 0xE6DB99E5) # 46
  165. c = XX(H, c, d, a, b, inp[15], S33, 0x1FA27CF8) # 47
  166. b = XX(H, b, c, d, a, inp[ 2], S34, 0xC4AC5665) # 48
  167. # Round 4.
  168. S41, S42, S43, S44 = 6, 10, 15, 21
  169. a = XX(I, a, b, c, d, inp[ 0], S41, 0xF4292244) # 49
  170. d = XX(I, d, a, b, c, inp[ 7], S42, 0x432AFF97) # 50
  171. c = XX(I, c, d, a, b, inp[14], S43, 0xAB9423A7) # 51
  172. b = XX(I, b, c, d, a, inp[ 5], S44, 0xFC93A039) # 52
  173. a = XX(I, a, b, c, d, inp[12], S41, 0x655B59C3) # 53
  174. d = XX(I, d, a, b, c, inp[ 3], S42, 0x8F0CCC92) # 54
  175. c = XX(I, c, d, a, b, inp[10], S43, 0xFFEFF47D) # 55
  176. b = XX(I, b, c, d, a, inp[ 1], S44, 0x85845DD1) # 56
  177. a = XX(I, a, b, c, d, inp[ 8], S41, 0x6FA87E4F) # 57
  178. d = XX(I, d, a, b, c, inp[15], S42, 0xFE2CE6E0) # 58
  179. c = XX(I, c, d, a, b, inp[ 6], S43, 0xA3014314) # 59
  180. b = XX(I, b, c, d, a, inp[13], S44, 0x4E0811A1) # 60
  181. a = XX(I, a, b, c, d, inp[ 4], S41, 0xF7537E82) # 61
  182. d = XX(I, d, a, b, c, inp[11], S42, 0xBD3AF235) # 62
  183. c = XX(I, c, d, a, b, inp[ 2], S43, 0x2AD7D2BB) # 63
  184. b = XX(I, b, c, d, a, inp[ 9], S44, 0xEB86D391) # 64
  185. A = (A + a) & 0xffffffff
  186. B = (B + b) & 0xffffffff
  187. C = (C + c) & 0xffffffff
  188. D = (D + d) & 0xffffffff
  189. self.A, self.B, self.C, self.D = A, B, C, D
  190. # Down from here all methods follow the Python Standard Library
  191. # API of the md5 module.
  192. def update(self, inBuf):
  193. """Add to the current message.
  194. Update the md5 object with the string arg. Repeated calls
  195. are equivalent to a single call with the concatenation of all
  196. the arguments, i.e. m.update(a); m.update(b) is equivalent
  197. to m.update(a+b).
  198. The hash is immediately calculated for all full blocks. The final
  199. calculation is made in digest(). This allows us to keep an
  200. intermediate value for the hash, so that we only need to make
  201. minimal recalculation if we call update() to add moredata to
  202. the hashed string.
  203. """
  204. leninBuf = len(inBuf)
  205. # Compute number of bytes mod 64.
  206. index = (self.count[0] >> 3) & 0x3F
  207. # Update number of bits.
  208. self.count[0] = self.count[0] + (leninBuf << 3)
  209. if self.count[0] < (leninBuf << 3):
  210. self.count[1] = self.count[1] + 1
  211. self.count[1] = self.count[1] + (leninBuf >> 29)
  212. partLen = 64 - index
  213. if leninBuf >= partLen:
  214. self.input[index:] = list(inBuf[:partLen])
  215. self._transform(_bytelist2long(self.input))
  216. i = partLen
  217. while i + 63 < leninBuf:
  218. self._transform(_bytelist2long(list(inBuf[i:i+64])))
  219. i = i + 64
  220. else:
  221. self.input = list(inBuf[i:leninBuf])
  222. else:
  223. i = 0
  224. self.input = self.input + list(inBuf)
  225. def digest(self):
  226. """Terminate the message-digest computation and return digest.
  227. Return the digest of the strings passed to the update()
  228. method so far. This is a 16-byte string which may contain
  229. non-ASCII characters, including null bytes.
  230. """
  231. A = self.A
  232. B = self.B
  233. C = self.C
  234. D = self.D
  235. input = [] + self.input
  236. count = [] + self.count
  237. index = (self.count[0] >> 3) & 0x3f
  238. if index < 56:
  239. padLen = 56 - index
  240. else:
  241. padLen = 120 - index
  242. padding = [128] + [0] * 63
  243. self.update(padding[:padLen])
  244. # Append length (before padding).
  245. bits = _bytelist2long(self.input[:56]) + count
  246. self._transform(bits)
  247. # Store state in digest.
  248. digest = struct.pack("<IIII", self.A, self.B, self.C, self.D)
  249. self.A = A
  250. self.B = B
  251. self.C = C
  252. self.D = D
  253. self.input = input
  254. self.count = count
  255. return digest
  256. def hexdigest(self):
  257. """Terminate and return digest in HEX form.
  258. Like digest() except the digest is returned as a string of
  259. length 32, containing only hexadecimal digits. This may be
  260. used to exchange the value safely in email or other non-
  261. binary environments.
  262. """
  263. return ''.join(['%02x' % c for c in self.digest()])
  264. def copy(self):
  265. """Return a clone object.
  266. Return a copy ('clone') of the md5 object. This can be used
  267. to efficiently compute the digests of strings that share
  268. a common initial substring.
  269. """
  270. if 0: # set this to 1 to make the flow space crash
  271. return copy.deepcopy(self)
  272. clone = self.__class__()
  273. clone.length = self.length
  274. clone.count = [] + self.count[:]
  275. clone.input = [] + self.input
  276. clone.A = self.A
  277. clone.B = self.B
  278. clone.C = self.C
  279. clone.D = self.D
  280. return clone