hashlib.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. #. Copyright (C) 2005-2010 Gregory P. Smith (greg@krypto.org)
  2. # Licensed to PSF under a Contributor Agreement.
  3. #
  4. __doc__ = """hashlib module - A common interface to many hash functions.
  5. new(name, data=b'', **kwargs) - returns a new hash object implementing the
  6. given hash function; initializing the hash
  7. using the given binary data.
  8. Named constructor functions are also available, these are faster
  9. than using new(name):
  10. md5(), sha1(), sha224(), sha256(), sha384(), sha512(), blake2b(), blake2s(),
  11. sha3_224, sha3_256, sha3_384, sha3_512, shake_128, and shake_256.
  12. More algorithms may be available on your platform but the above are guaranteed
  13. to exist. See the algorithms_guaranteed and algorithms_available attributes
  14. to find out what algorithm names can be passed to new().
  15. NOTE: If you want the adler32 or crc32 hash functions they are available in
  16. the zlib module.
  17. Choose your hash function wisely. Some have known collision weaknesses.
  18. sha384 and sha512 will be slow on 32 bit platforms.
  19. Hash objects have these methods:
  20. - update(data): Update the hash object with the bytes in data. Repeated calls
  21. are equivalent to a single call with the concatenation of all
  22. the arguments.
  23. - digest(): Return the digest of the bytes passed to the update() method
  24. so far as a bytes object.
  25. - hexdigest(): Like digest() except the digest is returned as a string
  26. of double length, containing only hexadecimal digits.
  27. - copy(): Return a copy (clone) of the hash object. This can be used to
  28. efficiently compute the digests of datas that share a common
  29. initial substring.
  30. For example, to obtain the digest of the byte string 'Nobody inspects the
  31. spammish repetition':
  32. >>> import hashlib
  33. >>> m = hashlib.md5()
  34. >>> m.update(b"Nobody inspects")
  35. >>> m.update(b" the spammish repetition")
  36. >>> m.digest()
  37. b'\\xbbd\\x9c\\x83\\xdd\\x1e\\xa5\\xc9\\xd9\\xde\\xc9\\xa1\\x8d\\xf0\\xff\\xe9'
  38. More condensed:
  39. >>> hashlib.sha224(b"Nobody inspects the spammish repetition").hexdigest()
  40. 'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2'
  41. """
  42. # This tuple and __get_builtin_constructor() must be modified if a new
  43. # always available algorithm is added.
  44. __always_supported = ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512',
  45. 'blake2b', 'blake2s',
  46. 'sha3_224', 'sha3_256', 'sha3_384', 'sha3_512',
  47. 'shake_128', 'shake_256')
  48. algorithms_guaranteed = set(__always_supported)
  49. algorithms_available = set(__always_supported)
  50. __all__ = __always_supported + ('new', 'algorithms_guaranteed',
  51. 'algorithms_available', 'pbkdf2_hmac')
  52. __builtin_constructor_cache = {}
  53. __block_openssl_constructor = {
  54. 'sha3_224', 'sha3_256', 'sha3_384', 'sha3_512',
  55. 'shake_128', 'shake_256',
  56. 'blake2b', 'blake2s',
  57. }
  58. def __get_builtin_constructor(name):
  59. cache = __builtin_constructor_cache
  60. constructor = cache.get(name)
  61. if constructor is not None:
  62. return constructor
  63. try:
  64. if name in {'SHA1', 'sha1'}:
  65. import _sha1
  66. cache['SHA1'] = cache['sha1'] = _sha1.sha1
  67. elif name in {'MD5', 'md5'}:
  68. import _md5
  69. cache['MD5'] = cache['md5'] = _md5.md5
  70. elif name in {'SHA256', 'sha256', 'SHA224', 'sha224'}:
  71. import _sha256
  72. cache['SHA224'] = cache['sha224'] = _sha256.sha224
  73. cache['SHA256'] = cache['sha256'] = _sha256.sha256
  74. elif name in {'SHA512', 'sha512', 'SHA384', 'sha384'}:
  75. import _sha512
  76. cache['SHA384'] = cache['sha384'] = _sha512.sha384
  77. cache['SHA512'] = cache['sha512'] = _sha512.sha512
  78. elif name in {'blake2b', 'blake2s'}:
  79. import _blake2
  80. cache['blake2b'] = _blake2.blake2b
  81. cache['blake2s'] = _blake2.blake2s
  82. elif name in {'sha3_224', 'sha3_256', 'sha3_384', 'sha3_512'}:
  83. import _sha3
  84. cache['sha3_224'] = _sha3.sha3_224
  85. cache['sha3_256'] = _sha3.sha3_256
  86. cache['sha3_384'] = _sha3.sha3_384
  87. cache['sha3_512'] = _sha3.sha3_512
  88. elif name in {'shake_128', 'shake_256'}:
  89. import _sha3
  90. cache['shake_128'] = _sha3.shake_128
  91. cache['shake_256'] = _sha3.shake_256
  92. except ImportError:
  93. pass # no extension module, this hash is unsupported.
  94. constructor = cache.get(name)
  95. if constructor is not None:
  96. return constructor
  97. raise ValueError('unsupported hash type ' + name)
  98. def __get_openssl_constructor(name):
  99. if name in __block_openssl_constructor:
  100. # Prefer our blake2 and sha3 implementation.
  101. return __get_builtin_constructor(name)
  102. try:
  103. f = getattr(_hashlib, 'openssl_' + name)
  104. # Allow the C module to raise ValueError. The function will be
  105. # defined but the hash not actually available thanks to OpenSSL.
  106. f()
  107. # Use the C function directly (very fast)
  108. return f
  109. except (AttributeError, ValueError):
  110. return __get_builtin_constructor(name)
  111. def __py_new(name, data=b'', **kwargs):
  112. """new(name, data=b'', **kwargs) - Return a new hashing object using the
  113. named algorithm; optionally initialized with data (which must be
  114. a bytes-like object).
  115. """
  116. return __get_builtin_constructor(name)(data, **kwargs)
  117. def __hash_new(name, data=b'', **kwargs):
  118. """new(name, data=b'') - Return a new hashing object using the named algorithm;
  119. optionally initialized with data (which must be a bytes-like object).
  120. """
  121. if name in __block_openssl_constructor:
  122. # Prefer our blake2 and sha3 implementation
  123. # OpenSSL 1.1.0 comes with a limited implementation of blake2b/s.
  124. # It does neither support keyed blake2 nor advanced features like
  125. # salt, personal, tree hashing or SSE.
  126. return __get_builtin_constructor(name)(data, **kwargs)
  127. try:
  128. return _hashlib.new(name, data)
  129. except ValueError:
  130. # If the _hashlib module (OpenSSL) doesn't support the named
  131. # hash, try using our builtin implementations.
  132. # This allows for SHA224/256 and SHA384/512 support even though
  133. # the OpenSSL library prior to 0.9.8 doesn't provide them.
  134. return __get_builtin_constructor(name)(data)
  135. try:
  136. import _hashlib
  137. new = __hash_new
  138. __get_hash = __get_openssl_constructor
  139. algorithms_available = algorithms_available.union(
  140. _hashlib.openssl_md_meth_names)
  141. except ImportError:
  142. new = __py_new
  143. __get_hash = __get_builtin_constructor
  144. try:
  145. # OpenSSL's PKCS5_PBKDF2_HMAC requires OpenSSL 1.0+ with HMAC and SHA
  146. from _hashlib import pbkdf2_hmac
  147. except ImportError:
  148. _trans_5C = bytes((x ^ 0x5C) for x in range(256))
  149. _trans_36 = bytes((x ^ 0x36) for x in range(256))
  150. def pbkdf2_hmac(hash_name, password, salt, iterations, dklen=None):
  151. """Password based key derivation function 2 (PKCS #5 v2.0)
  152. This Python implementations based on the hmac module about as fast
  153. as OpenSSL's PKCS5_PBKDF2_HMAC for short passwords and much faster
  154. for long passwords.
  155. """
  156. if not isinstance(hash_name, str):
  157. raise TypeError(hash_name)
  158. if not isinstance(password, (bytes, bytearray)):
  159. password = bytes(memoryview(password))
  160. if not isinstance(salt, (bytes, bytearray)):
  161. salt = bytes(memoryview(salt))
  162. # Fast inline HMAC implementation
  163. inner = new(hash_name)
  164. outer = new(hash_name)
  165. blocksize = getattr(inner, 'block_size', 64)
  166. if len(password) > blocksize:
  167. password = new(hash_name, password).digest()
  168. password = password + b'\x00' * (blocksize - len(password))
  169. inner.update(password.translate(_trans_36))
  170. outer.update(password.translate(_trans_5C))
  171. def prf(msg, inner=inner, outer=outer):
  172. # PBKDF2_HMAC uses the password as key. We can re-use the same
  173. # digest objects and just update copies to skip initialization.
  174. icpy = inner.copy()
  175. ocpy = outer.copy()
  176. icpy.update(msg)
  177. ocpy.update(icpy.digest())
  178. return ocpy.digest()
  179. if iterations < 1:
  180. raise ValueError(iterations)
  181. if dklen is None:
  182. dklen = outer.digest_size
  183. if dklen < 1:
  184. raise ValueError(dklen)
  185. dkey = b''
  186. loop = 1
  187. from_bytes = int.from_bytes
  188. while len(dkey) < dklen:
  189. prev = prf(salt + loop.to_bytes(4, 'big'))
  190. # endianness doesn't matter here as long to / from use the same
  191. rkey = int.from_bytes(prev, 'big')
  192. for i in range(iterations - 1):
  193. prev = prf(prev)
  194. # rkey = rkey ^ prev
  195. rkey ^= from_bytes(prev, 'big')
  196. loop += 1
  197. dkey += rkey.to_bytes(inner.digest_size, 'big')
  198. return dkey[:dklen]
  199. try:
  200. # OpenSSL's scrypt requires OpenSSL 1.1+
  201. from _hashlib import scrypt
  202. except ImportError:
  203. pass
  204. for __func_name in __always_supported:
  205. # try them all, some may not work due to the OpenSSL
  206. # version not supporting that algorithm.
  207. try:
  208. globals()[__func_name] = __get_hash(__func_name)
  209. except ValueError:
  210. import logging
  211. logging.exception('code for hash %s was not found.', __func_name)
  212. # Cleanup locals()
  213. del __always_supported, __func_name, __get_hash
  214. del __py_new, __hash_new, __get_openssl_constructor