SHARE
TWEET

Untitled

a guest Sep 6th, 2014 308 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/env python
  2.  
  3. """A sample implementation of MD5 in pure Python.
  4.  
  5. This is an implementation of the MD5 hash function, as specified by
  6. RFC 1321, in pure Python. It was implemented using Bruce Schneier's
  7. excellent book "Applied Cryptography", 2nd ed., 1996.
  8.  
  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.  
  15. This module tries very hard to follow the API of the existing Python
  16. standard library's "md5" module, but although it seems to work fine,
  17. it has not been extensively tested! (But note that there is a test
  18. module, test_md5py.py, that compares this Python implementation with
  19. the C one of the Python standard library.
  20.  
  21. BEWARE: this comes with no guarantee whatsoever about fitness and/or
  22. other properties! Specifically, do not use this in any production
  23. code! License is Python License!
  24.  
  25. Special thanks to Aurelian Coman who fixed some nasty bugs!
  26.  
  27. Dinu C. Gherman
  28. """
  29.  
  30.  
  31. __date__    = '2001-10-1'
  32. __version__ = 0.9
  33.  
  34.  
  35. import struct, string, copy
  36.  
  37.  
  38. # ======================================================================
  39. # Bit-Manipulation helpers
  40. #
  41. #   _long2bytes() was contributed by Barry Warsaw
  42. #   and is reused here with tiny modifications.
  43. # ======================================================================
  44.  
  45. def _long2bytes(n, blocksize=0):
  46.     """Convert a long integer to a byte string.
  47.  
  48.    If optional blocksize is given and greater than zero, pad the front
  49.    of the byte string with binary zeros so that the length is a multiple
  50.    of blocksize.
  51.    """
  52.  
  53.     # After much testing, this algorithm was deemed to be the fastest.
  54.     s = ''
  55.     pack = struct.pack
  56.     while n > 0:
  57.         ### CHANGED FROM '>I' TO '<I'. (DCG)
  58.         s = pack('<I', n & 0xffffffffL) + s
  59.         ### --------------------------
  60.         n = n >> 32
  61.  
  62.     # Strip off leading zeros.
  63.     for i in range(len(s)):
  64.         if s[i] <> '\000':
  65.             break
  66.     else:
  67.         # Only happens when n == 0.
  68.         s = '\000'
  69.         i = 0
  70.  
  71.     s = s[i:]
  72.  
  73.     # Add back some pad bytes. This could be done more efficiently
  74.     # w.r.t. the de-padding being done above, but sigh...
  75.     if blocksize > 0 and len(s) % blocksize:
  76.         s = (blocksize - len(s) % blocksize) * '\000' + s
  77.  
  78.     return s
  79.  
  80.  
  81. def _bytelist2long(list):
  82.     "Transform a list of characters into a list of longs."
  83.  
  84.     imax = len(list)/4
  85.     hl = [0L] * imax
  86.  
  87.     j = 0
  88.     i = 0
  89.     while i < imax:
  90.         b0 = long(ord(list[j]))
  91.         b1 = (long(ord(list[j+1]))) << 8
  92.         b2 = (long(ord(list[j+2]))) << 16
  93.         b3 = (long(ord(list[j+3]))) << 24
  94.         hl[i] = b0 | b1 |b2 | b3
  95.         i = i+1
  96.         j = j+4
  97.  
  98.     return hl
  99.  
  100.  
  101. def _rotateLeft(x, n):
  102.     "Rotate x (32 bit) left n bits circularly."
  103.  
  104.     return (x << n) | (x >> (32-n))
  105.  
  106.  
  107. # ======================================================================
  108. # The real MD5 meat...
  109. #
  110. #   Implemented after "Applied Cryptography", 2nd ed., 1996,
  111. #   pp. 436-441 by Bruce Schneier.
  112. # ======================================================================
  113.  
  114. # F, G, H and I are basic MD5 functions.
  115.  
  116. def F(x, y, z):
  117.     return (x & y) | ((~x) & z)
  118.  
  119. def G(x, y, z):
  120.     return (x & z) | (y & (~z))
  121.  
  122. def H(x, y, z):
  123.     return x ^ y ^ z
  124.  
  125. def I(x, y, z):
  126.     return y ^ (x | (~z))
  127.  
  128.  
  129. def XX(func, a, b, c, d, x, s, ac):
  130.     """Wrapper for call distribution to functions F, G, H and I.
  131.  
  132.    This replaces functions FF, GG, HH and II from "Appl. Crypto.
  133.    Rotation is separate from addition to prevent recomputation
  134.    (now summed-up in one function).
  135.    """
  136.  
  137.     res = 0L
  138.     res = res + a + func(b, c, d)
  139.     res = res + x
  140.     res = res + ac
  141.     res = res & 0xffffffffL
  142.     res = _rotateLeft(res, s)
  143.     res = res & 0xffffffffL
  144.     res = res + b
  145.  
  146.     return res & 0xffffffffL
  147.  
  148.  
  149. class MD5:
  150.     "An implementation of the MD5 hash function in pure Python."
  151.  
  152.     def __init__(self):
  153.         "Initialisation."
  154.        
  155.         # Initial 128 bit message digest (4 times 32 bit).
  156.         self.A = 0L
  157.         self.B = 0L
  158.         self.C = 0L
  159.         self.D = 0L
  160.        
  161.         # Initial message length in bits(!).
  162.         self.length = 0L
  163.         self.count = [0, 0]
  164.  
  165.         # Initial empty message as a sequence of bytes (8 bit characters).
  166.         self.input = []
  167.  
  168.         # Length of the final hash (in bytes).
  169.         self.HASH_LENGTH = 16
  170.          
  171.         # Length of a block (the number of bytes hashed in every transform).
  172.         self.DATA_LENGTH = 64
  173.  
  174.         # Call a separate init function, that can be used repeatedly
  175.         # to start from scratch on the same object.
  176.         self.init()
  177.  
  178.  
  179.     def init(self):
  180.         "Initialize the message-digest and set all fields to zero."
  181.  
  182.         self.length = 0L
  183.         self.input = []
  184.  
  185.         # Load magic initialization constants.
  186.         self.A = 0x67452301L
  187.         self.B = 0xefcdab89L
  188.         self.C = 0x98badcfeL
  189.         self.D = 0x10325476L
  190.  
  191.  
  192.     def _transform(self, inp):
  193.         """Basic MD5 step transforming the digest based on the input.
  194.  
  195.        Note that if the Mysterious Constants are arranged backwards
  196.        in little-endian order and decrypted with the DES they produce
  197.        OCCULT MESSAGES!
  198.        """
  199.  
  200.         a, b, c, d = A, B, C, D = self.A, self.B, self.C, self.D
  201.  
  202.         # Round 1.
  203.  
  204.         S11, S12, S13, S14 = 7, 12, 17, 22
  205.  
  206.         a = XX(F, a, b, c, d, inp[ 0], S11, 0xD76AA478L) # 1
  207.         d = XX(F, d, a, b, c, inp[ 1], S12, 0xE8C7B756L) # 2
  208.         c = XX(F, c, d, a, b, inp[ 2], S13, 0x242070DBL) # 3
  209.         b = XX(F, b, c, d, a, inp[ 3], S14, 0xC1BDCEEEL) # 4
  210.         a = XX(F, a, b, c, d, inp[ 4], S11, 0xF57C0FAFL) # 5
  211.         d = XX(F, d, a, b, c, inp[ 5], S12, 0x4787C62AL) # 6
  212.         c = XX(F, c, d, a, b, inp[ 6], S13, 0xA8304613L) # 7
  213.         b = XX(F, b, c, d, a, inp[ 7], S14, 0xFD469501L) # 8
  214.         a = XX(F, a, b, c, d, inp[ 8], S11, 0x698098D8L) # 9
  215.         d = XX(F, d, a, b, c, inp[ 9], S12, 0x8B44F7AFL) # 10
  216.         c = XX(F, c, d, a, b, inp[10], S13, 0xFFFF5BB1L) # 11
  217.         b = XX(F, b, c, d, a, inp[11], S14, 0x895CD7BEL) # 12
  218.         a = XX(F, a, b, c, d, inp[12], S11, 0x6B901122L) # 13
  219.         d = XX(F, d, a, b, c, inp[13], S12, 0xFD987193L) # 14
  220.         c = XX(F, c, d, a, b, inp[14], S13, 0xA679438EL) # 15
  221.         b = XX(F, b, c, d, a, inp[15], S14, 0x49B40821L) # 16
  222.  
  223.         # Round 2.
  224.  
  225.         S21, S22, S23, S24 = 5, 9, 14, 20
  226.  
  227.         a = XX(G, a, b, c, d, inp[ 1], S21, 0xF61E2562L) # 17
  228.         d = XX(G, d, a, b, c, inp[ 6], S22, 0xC040B340L) # 18
  229.         c = XX(G, c, d, a, b, inp[11], S23, 0x265E5A51L) # 19
  230.         b = XX(G, b, c, d, a, inp[ 0], S24, 0xE9B6C7AAL) # 20
  231.         a = XX(G, a, b, c, d, inp[ 5], S21, 0xD62F105DL) # 21
  232.         d = XX(G, d, a, b, c, inp[10], S22, 0x02441453L) # 22
  233.         c = XX(G, c, d, a, b, inp[15], S23, 0xD8A1E681L) # 23
  234.         b = XX(G, b, c, d, a, inp[ 4], S24, 0xE7D3FBC8L) # 24
  235.         a = XX(G, a, b, c, d, inp[ 9], S21, 0x21E1CDE6L) # 25
  236.         d = XX(G, d, a, b, c, inp[14], S22, 0xC33707D6L) # 26
  237.         c = XX(G, c, d, a, b, inp[ 3], S23, 0xF4D50D87L) # 27
  238.         b = XX(G, b, c, d, a, inp[ 8], S24, 0x455A14EDL) # 28
  239.         a = XX(G, a, b, c, d, inp[13], S21, 0xA9E3E905L) # 29
  240.         d = XX(G, d, a, b, c, inp[ 2], S22, 0xFCEFA3F8L) # 30
  241.         c = XX(G, c, d, a, b, inp[ 7], S23, 0x676F02D9L) # 31
  242.         b = XX(G, b, c, d, a, inp[12], S24, 0x8D2A4C8AL) # 32
  243.  
  244.         # Round 3.
  245.  
  246.         S31, S32, S33, S34 = 4, 11, 16, 23
  247.  
  248.         a = XX(H, a, b, c, d, inp[ 5], S31, 0xFFFA3942L) # 33
  249.         d = XX(H, d, a, b, c, inp[ 8], S32, 0x8771F681L) # 34
  250.         c = XX(H, c, d, a, b, inp[11], S33, 0x6D9D6122L) # 35
  251.         b = XX(H, b, c, d, a, inp[14], S34, 0xFDE5380CL) # 36
  252.         a = XX(H, a, b, c, d, inp[ 1], S31, 0xA4BEEA44L) # 37
  253.         d = XX(H, d, a, b, c, inp[ 4], S32, 0x4BDECFA9L) # 38
  254.         c = XX(H, c, d, a, b, inp[ 7], S33, 0xF6BB4B60L) # 39
  255.         b = XX(H, b, c, d, a, inp[10], S34, 0xBEBFBC70L) # 40
  256.         a = XX(H, a, b, c, d, inp[13], S31, 0x289B7EC6L) # 41
  257.         d = XX(H, d, a, b, c, inp[ 0], S32, 0xEAA127FAL) # 42
  258.         c = XX(H, c, d, a, b, inp[ 3], S33, 0xD4EF3085L) # 43
  259.         b = XX(H, b, c, d, a, inp[ 6], S34, 0x04881D05L) # 44
  260.         a = XX(H, a, b, c, d, inp[ 9], S31, 0xD9D4D039L) # 45
  261.         d = XX(H, d, a, b, c, inp[12], S32, 0xE6DB99E5L) # 46
  262.         c = XX(H, c, d, a, b, inp[15], S33, 0x1FA27CF8L) # 47
  263.         b = XX(H, b, c, d, a, inp[ 2], S34, 0xC4AC5665L) # 48
  264.  
  265.         # Round 4.
  266.  
  267.         S41, S42, S43, S44 = 6, 10, 15, 21
  268.  
  269.         a = XX(I, a, b, c, d, inp[ 0], S41, 0xF4292244L) # 49
  270.         d = XX(I, d, a, b, c, inp[ 7], S42, 0x432AFF97L) # 50
  271.         c = XX(I, c, d, a, b, inp[14], S43, 0xAB9423A7L) # 51
  272.         b = XX(I, b, c, d, a, inp[ 5], S44, 0xFC93A039L) # 52
  273.         a = XX(I, a, b, c, d, inp[12], S41, 0x655B59C3L) # 53
  274.         d = XX(I, d, a, b, c, inp[ 3], S42, 0x8F0CCC92L) # 54
  275.         c = XX(I, c, d, a, b, inp[10], S43, 0xFFEFF47DL) # 55
  276.         b = XX(I, b, c, d, a, inp[ 1], S44, 0x85845DD1L) # 56
  277.         a = XX(I, a, b, c, d, inp[ 8], S41, 0x6FA87E4FL) # 57
  278.         d = XX(I, d, a, b, c, inp[15], S42, 0xFE2CE6E0L) # 58
  279.         c = XX(I, c, d, a, b, inp[ 6], S43, 0xA3014314L) # 59
  280.         b = XX(I, b, c, d, a, inp[13], S44, 0x4E0811A1L) # 60
  281.         a = XX(I, a, b, c, d, inp[ 4], S41, 0xF7537E82L) # 61
  282.         d = XX(I, d, a, b, c, inp[11], S42, 0xBD3AF235L) # 62
  283.         c = XX(I, c, d, a, b, inp[ 2], S43, 0x2AD7D2BBL) # 63
  284.         b = XX(I, b, c, d, a, inp[ 9], S44, 0xEB86D391L) # 64
  285.  
  286.         A = (A + a) & 0xffffffffL
  287.         B = (B + b) & 0xffffffffL
  288.         C = (C + c) & 0xffffffffL
  289.         D = (D + d) & 0xffffffffL
  290.  
  291.         self.A, self.B, self.C, self.D = A, B, C, D
  292.  
  293.  
  294.     # Down from here all methods follow the Python Standard Library
  295.     # API of the md5 module.
  296.  
  297.     def update(self, inBuf):
  298.         """Add to the current message.
  299.  
  300.        Update the md5 object with the string arg. Repeated calls
  301.        are equivalent to a single call with the concatenation of all
  302.        the arguments, i.e. m.update(a); m.update(b) is equivalent
  303.        to m.update(a+b).
  304.        """
  305.  
  306.         leninBuf = long(len(inBuf))
  307.  
  308.         # Compute number of bytes mod 64.
  309.         index = (self.count[0] >> 3) & 0x3FL
  310.  
  311.         # Update number of bits.
  312.         self.count[0] = self.count[0] + (leninBuf << 3)
  313.         if self.count[0] < (leninBuf << 3):
  314.             self.count[1] = self.count[1] + 1
  315.         self.count[1] = self.count[1] + (leninBuf >> 29)
  316.  
  317.         partLen = 64 - index
  318.  
  319.         if leninBuf >= partLen:
  320.             self.input[index:] = map(None, inBuf[:partLen])
  321.             self._transform(_bytelist2long(self.input))
  322.             i = partLen
  323.             while i + 63 < leninBuf:
  324.                 self._transform(_bytelist2long(map(None, inBuf[i:i+64])))
  325.                 i = i + 64
  326.             else:
  327.                 self.input = map(None, inBuf[i:leninBuf])
  328.         else:
  329.             i = 0
  330.             self.input = self.input + map(None, inBuf)
  331.  
  332.  
  333.     def digest(self):
  334.         """Terminate the message-digest computation and return digest.
  335.  
  336.        Return the digest of the strings passed to the update()
  337.        method so far. This is a 16-byte string which may contain
  338.        non-ASCII characters, including null bytes.
  339.        """
  340.  
  341.         A = self.A
  342.         B = self.B
  343.         C = self.C
  344.         D = self.D
  345.         input = [] + self.input
  346.         count = [] + self.count
  347.  
  348.         index = (self.count[0] >> 3) & 0x3fL
  349.  
  350.         if index < 56:
  351.             padLen = 56 - index
  352.         else:
  353.             padLen = 120 - index
  354.  
  355.         padding = ['\200'] + ['\000'] * 63
  356.         self.update(padding[:padLen])
  357.  
  358.         # Append length (before padding).
  359.         bits = _bytelist2long(self.input[:56]) + count
  360.  
  361.         self._transform(bits)
  362.  
  363.         # Store state in digest.
  364.         digest = _long2bytes(self.A << 96, 16)[:4] + \
  365.                  _long2bytes(self.B << 64, 16)[4:8] + \
  366.                  _long2bytes(self.C << 32, 16)[8:12] + \
  367.                  _long2bytes(self.D, 16)[12:]
  368.  
  369.         self.A = A
  370.         self.B = B
  371.         self.C = C
  372.         self.D = D
  373.         self.input = input
  374.         self.count = count
  375.  
  376.         return digest
  377.  
  378.  
  379.     def hexdigest(self):
  380.         """Terminate and return digest in HEX form.
  381.  
  382.        Like digest() except the digest is returned as a string of
  383.        length 32, containing only hexadecimal digits. This may be
  384.        used to exchange the value safely in email or other non-
  385.        binary environments.
  386.        """
  387.  
  388.         d = map(None, self.digest())
  389.         d = map(ord, d)
  390.         d = map(lambda x:"%02x" % x, d)
  391.         d = string.join(d, '')
  392.  
  393.         return d
  394.  
  395.  
  396.     def copy(self):
  397.         """Return a clone object.
  398.  
  399.        Return a copy ('clone') of the md5 object. This can be used
  400.        to efficiently compute the digests of strings that share
  401.        a common initial substring.
  402.        """
  403.  
  404.         return copy.deepcopy(self)
  405.  
  406.  
  407. # ======================================================================
  408. # Mimick Python top-level functions from standard library API
  409. # for consistency with the md5 module of the standard library.
  410. # ======================================================================
  411.  
  412. def new(arg=None):
  413.     """Return a new md5 object.
  414.  
  415.    If arg is present, the method call update(arg) is made.
  416.    """
  417.  
  418.     md5 = MD5()
  419.     if arg:
  420.         md5.update(arg)
  421.  
  422.     return md5
  423.  
  424.  
  425. def md5(arg=None):
  426.     """Same as new().
  427.  
  428.    For backward compatibility reasons, this is an alternative
  429.    name for the new() function.
  430.    """
  431.  
  432.     return new(arg)
RAW Paste Data
Want to get better at Python?
Learn to code Python in 2017
Pastebin PRO Summer Special!
Get 40% OFF on Pastebin PRO accounts!
Top