PageRenderTime 32ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/rpython/rlib/rmd5.py

https://bitbucket.org/pypy/pypy/
Python | 386 lines | 365 code | 6 blank | 15 comment | 3 complexity | 3d17d9575dbf5fd3b3a28c0eeeca19be MD5 | raw file
Possible License(s): AGPL-3.0, BSD-3-Clause, Apache-2.0
  1. # -*- coding: iso-8859-1 -*-
  2. """
  3. RPython implementation of MD5 checksums.
  4. See also the pure Python implementation in lib_pypy/md5.py, which might
  5. or might not be faster than this one on top of CPython.
  6. This is an implementation of the MD5 hash function,
  7. as specified by RFC 1321. It was implemented using Bruce Schneier's
  8. excellent book "Applied Cryptography", 2nd ed., 1996.
  9. This module tries to follow the API of the CPython md5 module.
  10. Long history:
  11. By Dinu C. Gherman. BEWARE: this comes with no guarantee whatsoever
  12. about fitness and/or other properties! Specifically, do not use this
  13. in any production code! License is Python License! (Re-licensing
  14. under the MIT would be great, though)
  15. Special thanks to Aurelian Coman who fixed some nasty bugs!
  16. Modernised by J. Hallén and L. Creighton for Pypy.
  17. Converted to RPython by arigo.
  18. """
  19. from rpython.rlib.rarithmetic import r_uint, r_ulonglong
  20. if r_uint.BITS == 32:
  21. def _rotateLeft(x, n):
  22. "Rotate x (32 bit) left n bits circularly."
  23. return (x << n) | (x >> (32-n))
  24. else:
  25. def _rotateLeft_emulator(x, n):
  26. x &= 0xFFFFFFFF
  27. return (x << n) | (x >> (32-n))
  28. # ----- start of custom code, think about something better... -----
  29. from rpython.rtyper.lltypesystem import lltype, rffi
  30. from rpython.translator.tool.cbuild import ExternalCompilationInfo
  31. eci = ExternalCompilationInfo(post_include_bits=["""
  32. static unsigned long pypy__rotateLeft(unsigned long x, long n) {
  33. unsigned int x1 = x; /* arithmetic directly on int */
  34. int n1 = n;
  35. return (x1 << n1) | (x1 >> (32-n1));
  36. }
  37. """])
  38. _rotateLeft = rffi.llexternal(
  39. "pypy__rotateLeft", [lltype.Unsigned, lltype.Signed], lltype.Unsigned,
  40. _callable=_rotateLeft_emulator, compilation_info=eci,
  41. _nowrapper=True, elidable_function=True)
  42. # we expect the function _rotateLeft to be actually inlined
  43. def _state2string(a, b, c, d):
  44. return ''.join([
  45. chr(a&0xFF), chr((a>>8)&0xFF), chr((a>>16)&0xFF), chr((a>>24)&0xFF),
  46. chr(b&0xFF), chr((b>>8)&0xFF), chr((b>>16)&0xFF), chr((b>>24)&0xFF),
  47. chr(c&0xFF), chr((c>>8)&0xFF), chr((c>>16)&0xFF), chr((c>>24)&0xFF),
  48. chr(d&0xFF), chr((d>>8)&0xFF), chr((d>>16)&0xFF), chr((d>>24)&0xFF),
  49. ])
  50. def _state2hexstring(a, b, c, d):
  51. hx = '0123456789abcdef'
  52. return ''.join([
  53. hx[(a>>4)&0xF], hx[a&0xF], hx[(a>>12)&0xF], hx[(a>>8)&0xF],
  54. hx[(a>>20)&0xF], hx[(a>>16)&0xF], hx[(a>>28)&0xF], hx[(a>>24)&0xF],
  55. hx[(b>>4)&0xF], hx[b&0xF], hx[(b>>12)&0xF], hx[(b>>8)&0xF],
  56. hx[(b>>20)&0xF], hx[(b>>16)&0xF], hx[(b>>28)&0xF], hx[(b>>24)&0xF],
  57. hx[(c>>4)&0xF], hx[c&0xF], hx[(c>>12)&0xF], hx[(c>>8)&0xF],
  58. hx[(c>>20)&0xF], hx[(c>>16)&0xF], hx[(c>>28)&0xF], hx[(c>>24)&0xF],
  59. hx[(d>>4)&0xF], hx[d&0xF], hx[(d>>12)&0xF], hx[(d>>8)&0xF],
  60. hx[(d>>20)&0xF], hx[(d>>16)&0xF], hx[(d>>28)&0xF], hx[(d>>24)&0xF],
  61. ])
  62. def _string2uintlist(s, start, count, result):
  63. """Build a list of count r_uint's by unpacking the string
  64. s[start:start+4*count] in little-endian order.
  65. """
  66. for i in range(count):
  67. p = start + i * 4
  68. x = r_uint(ord(s[p]))
  69. x |= r_uint(ord(s[p+1])) << 8
  70. x |= r_uint(ord(s[p+2])) << 16
  71. x |= r_uint(ord(s[p+3])) << 24
  72. result[i] = x
  73. # ======================================================================
  74. # The real MD5 meat...
  75. #
  76. # Implemented after "Applied Cryptography", 2nd ed., 1996,
  77. # pp. 436-441 by Bruce Schneier.
  78. # ======================================================================
  79. # F, G, H and I are basic MD5 functions.
  80. def F(x, y, z):
  81. return (x & y) | ((~x) & z)
  82. def G(x, y, z):
  83. return (x & z) | (y & (~z))
  84. def H(x, y, z):
  85. return x ^ y ^ z
  86. def I(x, y, z):
  87. return y ^ (x | (~z))
  88. def XX(func, a, b, c, d, x, s, ac):
  89. """Wrapper for call distribution to functions F, G, H and I.
  90. This replaces functions FF, GG, HH and II from "Appl. Crypto."
  91. Rotation is separate from addition to prevent recomputation
  92. (now summed-up in one function).
  93. """
  94. res = a + func(b, c, d)
  95. res = res + x
  96. res = res + ac
  97. res = _rotateLeft(res, s)
  98. res = res + b
  99. return res
  100. XX._annspecialcase_ = 'specialize:arg(0)' # performance hint
  101. class RMD5(object):
  102. """RPython-level MD5 object.
  103. """
  104. def __init__(self, initialdata=''):
  105. self._init()
  106. self.update(initialdata)
  107. def _init(self):
  108. """Set this object to an initial empty state.
  109. """
  110. self.count = r_ulonglong(0) # total number of bytes
  111. self.input = "" # pending unprocessed data, < 64 bytes
  112. self.uintbuffer = [r_uint(0)] * 16
  113. # Load magic initialization constants.
  114. self.A = r_uint(0x67452301L)
  115. self.B = r_uint(0xefcdab89L)
  116. self.C = r_uint(0x98badcfeL)
  117. self.D = r_uint(0x10325476L)
  118. def _transform(self, inp):
  119. """Basic MD5 step transforming the digest based on the input.
  120. Note that if the Mysterious Constants are arranged backwards
  121. in little-endian order and decrypted with the DES they produce
  122. OCCULT MESSAGES!
  123. """
  124. # 'inp' is a list of 16 r_uint values.
  125. a, b, c, d = A, B, C, D = self.A, self.B, self.C, self.D
  126. # Round 1.
  127. S11, S12, S13, S14 = 7, 12, 17, 22
  128. a = XX(F, a, b, c, d, inp[ 0], S11, r_uint(0xD76AA478L)) # 1
  129. d = XX(F, d, a, b, c, inp[ 1], S12, r_uint(0xE8C7B756L)) # 2
  130. c = XX(F, c, d, a, b, inp[ 2], S13, r_uint(0x242070DBL)) # 3
  131. b = XX(F, b, c, d, a, inp[ 3], S14, r_uint(0xC1BDCEEEL)) # 4
  132. a = XX(F, a, b, c, d, inp[ 4], S11, r_uint(0xF57C0FAFL)) # 5
  133. d = XX(F, d, a, b, c, inp[ 5], S12, r_uint(0x4787C62AL)) # 6
  134. c = XX(F, c, d, a, b, inp[ 6], S13, r_uint(0xA8304613L)) # 7
  135. b = XX(F, b, c, d, a, inp[ 7], S14, r_uint(0xFD469501L)) # 8
  136. a = XX(F, a, b, c, d, inp[ 8], S11, r_uint(0x698098D8L)) # 9
  137. d = XX(F, d, a, b, c, inp[ 9], S12, r_uint(0x8B44F7AFL)) # 10
  138. c = XX(F, c, d, a, b, inp[10], S13, r_uint(0xFFFF5BB1L)) # 11
  139. b = XX(F, b, c, d, a, inp[11], S14, r_uint(0x895CD7BEL)) # 12
  140. a = XX(F, a, b, c, d, inp[12], S11, r_uint(0x6B901122L)) # 13
  141. d = XX(F, d, a, b, c, inp[13], S12, r_uint(0xFD987193L)) # 14
  142. c = XX(F, c, d, a, b, inp[14], S13, r_uint(0xA679438EL)) # 15
  143. b = XX(F, b, c, d, a, inp[15], S14, r_uint(0x49B40821L)) # 16
  144. # Round 2.
  145. S21, S22, S23, S24 = 5, 9, 14, 20
  146. a = XX(G, a, b, c, d, inp[ 1], S21, r_uint(0xF61E2562L)) # 17
  147. d = XX(G, d, a, b, c, inp[ 6], S22, r_uint(0xC040B340L)) # 18
  148. c = XX(G, c, d, a, b, inp[11], S23, r_uint(0x265E5A51L)) # 19
  149. b = XX(G, b, c, d, a, inp[ 0], S24, r_uint(0xE9B6C7AAL)) # 20
  150. a = XX(G, a, b, c, d, inp[ 5], S21, r_uint(0xD62F105DL)) # 21
  151. d = XX(G, d, a, b, c, inp[10], S22, r_uint(0x02441453L)) # 22
  152. c = XX(G, c, d, a, b, inp[15], S23, r_uint(0xD8A1E681L)) # 23
  153. b = XX(G, b, c, d, a, inp[ 4], S24, r_uint(0xE7D3FBC8L)) # 24
  154. a = XX(G, a, b, c, d, inp[ 9], S21, r_uint(0x21E1CDE6L)) # 25
  155. d = XX(G, d, a, b, c, inp[14], S22, r_uint(0xC33707D6L)) # 26
  156. c = XX(G, c, d, a, b, inp[ 3], S23, r_uint(0xF4D50D87L)) # 27
  157. b = XX(G, b, c, d, a, inp[ 8], S24, r_uint(0x455A14EDL)) # 28
  158. a = XX(G, a, b, c, d, inp[13], S21, r_uint(0xA9E3E905L)) # 29
  159. d = XX(G, d, a, b, c, inp[ 2], S22, r_uint(0xFCEFA3F8L)) # 30
  160. c = XX(G, c, d, a, b, inp[ 7], S23, r_uint(0x676F02D9L)) # 31
  161. b = XX(G, b, c, d, a, inp[12], S24, r_uint(0x8D2A4C8AL)) # 32
  162. # Round 3.
  163. S31, S32, S33, S34 = 4, 11, 16, 23
  164. a = XX(H, a, b, c, d, inp[ 5], S31, r_uint(0xFFFA3942L)) # 33
  165. d = XX(H, d, a, b, c, inp[ 8], S32, r_uint(0x8771F681L)) # 34
  166. c = XX(H, c, d, a, b, inp[11], S33, r_uint(0x6D9D6122L)) # 35
  167. b = XX(H, b, c, d, a, inp[14], S34, r_uint(0xFDE5380CL)) # 36
  168. a = XX(H, a, b, c, d, inp[ 1], S31, r_uint(0xA4BEEA44L)) # 37
  169. d = XX(H, d, a, b, c, inp[ 4], S32, r_uint(0x4BDECFA9L)) # 38
  170. c = XX(H, c, d, a, b, inp[ 7], S33, r_uint(0xF6BB4B60L)) # 39
  171. b = XX(H, b, c, d, a, inp[10], S34, r_uint(0xBEBFBC70L)) # 40
  172. a = XX(H, a, b, c, d, inp[13], S31, r_uint(0x289B7EC6L)) # 41
  173. d = XX(H, d, a, b, c, inp[ 0], S32, r_uint(0xEAA127FAL)) # 42
  174. c = XX(H, c, d, a, b, inp[ 3], S33, r_uint(0xD4EF3085L)) # 43
  175. b = XX(H, b, c, d, a, inp[ 6], S34, r_uint(0x04881D05L)) # 44
  176. a = XX(H, a, b, c, d, inp[ 9], S31, r_uint(0xD9D4D039L)) # 45
  177. d = XX(H, d, a, b, c, inp[12], S32, r_uint(0xE6DB99E5L)) # 46
  178. c = XX(H, c, d, a, b, inp[15], S33, r_uint(0x1FA27CF8L)) # 47
  179. b = XX(H, b, c, d, a, inp[ 2], S34, r_uint(0xC4AC5665L)) # 48
  180. # Round 4.
  181. S41, S42, S43, S44 = 6, 10, 15, 21
  182. a = XX(I, a, b, c, d, inp[ 0], S41, r_uint(0xF4292244L)) # 49
  183. d = XX(I, d, a, b, c, inp[ 7], S42, r_uint(0x432AFF97L)) # 50
  184. c = XX(I, c, d, a, b, inp[14], S43, r_uint(0xAB9423A7L)) # 51
  185. b = XX(I, b, c, d, a, inp[ 5], S44, r_uint(0xFC93A039L)) # 52
  186. a = XX(I, a, b, c, d, inp[12], S41, r_uint(0x655B59C3L)) # 53
  187. d = XX(I, d, a, b, c, inp[ 3], S42, r_uint(0x8F0CCC92L)) # 54
  188. c = XX(I, c, d, a, b, inp[10], S43, r_uint(0xFFEFF47DL)) # 55
  189. b = XX(I, b, c, d, a, inp[ 1], S44, r_uint(0x85845DD1L)) # 56
  190. a = XX(I, a, b, c, d, inp[ 8], S41, r_uint(0x6FA87E4FL)) # 57
  191. d = XX(I, d, a, b, c, inp[15], S42, r_uint(0xFE2CE6E0L)) # 58
  192. c = XX(I, c, d, a, b, inp[ 6], S43, r_uint(0xA3014314L)) # 59
  193. b = XX(I, b, c, d, a, inp[13], S44, r_uint(0x4E0811A1L)) # 60
  194. a = XX(I, a, b, c, d, inp[ 4], S41, r_uint(0xF7537E82L)) # 61
  195. d = XX(I, d, a, b, c, inp[11], S42, r_uint(0xBD3AF235L)) # 62
  196. c = XX(I, c, d, a, b, inp[ 2], S43, r_uint(0x2AD7D2BBL)) # 63
  197. b = XX(I, b, c, d, a, inp[ 9], S44, r_uint(0xEB86D391L)) # 64
  198. A += a
  199. B += b
  200. C += c
  201. D += d
  202. self.A, self.B, self.C, self.D = A, B, C, D
  203. def _finalize(self, digestfunc):
  204. """Logic to add the final padding and extract the digest.
  205. """
  206. # Save the state before adding the padding
  207. count = self.count
  208. input = self.input
  209. A = self.A
  210. B = self.B
  211. C = self.C
  212. D = self.D
  213. index = len(input)
  214. if index < 56:
  215. padLen = 56 - index
  216. else:
  217. padLen = 120 - index
  218. if padLen:
  219. self.update('\200' + '\000' * (padLen-1))
  220. # Append length (before padding).
  221. assert len(self.input) == 56
  222. W = self.uintbuffer
  223. _string2uintlist(self.input, 0, 14, W)
  224. length_in_bits = count << 3
  225. W[14] = r_uint(length_in_bits)
  226. W[15] = r_uint(length_in_bits >> 32)
  227. self._transform(W)
  228. # Store state in digest.
  229. digest = digestfunc(self.A, self.B, self.C, self.D)
  230. # Restore the saved state in case this instance is still used
  231. self.count = count
  232. self.input = input
  233. self.A = A
  234. self.B = B
  235. self.C = C
  236. self.D = D
  237. return digest
  238. # Down from here all methods follow the Python Standard Library
  239. # API of the md5 module.
  240. def update(self, inBuf):
  241. """Add to the current message.
  242. Update the md5 object with the string arg. Repeated calls
  243. are equivalent to a single call with the concatenation of all
  244. the arguments, i.e. m.update(a); m.update(b) is equivalent
  245. to m.update(a+b).
  246. The hash is immediately calculated for all full blocks. The final
  247. calculation is made in digest(). This allows us to keep an
  248. intermediate value for the hash, so that we only need to make
  249. minimal recalculation if we call update() to add moredata to
  250. the hashed string.
  251. """
  252. leninBuf = len(inBuf)
  253. self.count += leninBuf
  254. index = len(self.input)
  255. partLen = 64 - index
  256. assert partLen > 0
  257. if leninBuf >= partLen:
  258. W = self.uintbuffer
  259. self.input = self.input + inBuf[:partLen]
  260. _string2uintlist(self.input, 0, 16, W)
  261. self._transform(W)
  262. i = partLen
  263. while i + 64 <= leninBuf:
  264. _string2uintlist(inBuf, i, 16, W)
  265. self._transform(W)
  266. i = i + 64
  267. else:
  268. self.input = inBuf[i:leninBuf]
  269. else:
  270. self.input = self.input + inBuf
  271. def digest(self):
  272. """Terminate the message-digest computation and return digest.
  273. Return the digest of the strings passed to the update()
  274. method so far. This is a 16-byte string which may contain
  275. non-ASCII characters, including null bytes.
  276. """
  277. return self._finalize(_state2string)
  278. def hexdigest(self):
  279. """Terminate and return digest in HEX form.
  280. Like digest() except the digest is returned as a string of
  281. length 32, containing only hexadecimal digits. This may be
  282. used to exchange the value safely in email or other non-
  283. binary environments.
  284. """
  285. return self._finalize(_state2hexstring)
  286. def copy(self):
  287. """Return a clone object.
  288. Return a copy ('clone') of the md5 object. This can be used
  289. to efficiently compute the digests of strings that share
  290. a common initial substring.
  291. """
  292. clone = RMD5()
  293. clone._copyfrom(self)
  294. return clone
  295. def _copyfrom(self, other):
  296. """Copy all state from 'other' into 'self'.
  297. """
  298. self.count = other.count
  299. self.input = other.input
  300. self.A = other.A
  301. self.B = other.B
  302. self.C = other.C
  303. self.D = other.D
  304. # synonyms to build new RMD5 objects, for compatibility with the
  305. # CPython md5 module interface.
  306. md5 = RMD5
  307. new = RMD5
  308. digest_size = 16