hashlib.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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', 'file_digest')
  52. __builtin_constructor_cache = {}
  53. # Prefer our blake2 implementation
  54. # OpenSSL 1.1.0 comes with a limited implementation of blake2b/s. The OpenSSL
  55. # implementations neither support keyed blake2 (blake2 MAC) nor advanced
  56. # features like salt, personalization, or tree hashing. OpenSSL hash-only
  57. # variants are available as 'blake2b512' and 'blake2s256', though.
  58. __block_openssl_constructor = {
  59. 'blake2b', 'blake2s',
  60. }
  61. def __get_builtin_constructor(name):
  62. cache = __builtin_constructor_cache
  63. constructor = cache.get(name)
  64. if constructor is not None:
  65. return constructor
  66. try:
  67. if name in {'SHA1', 'sha1'}:
  68. import _sha1
  69. cache['SHA1'] = cache['sha1'] = _sha1.sha1
  70. elif name in {'MD5', 'md5'}:
  71. import _md5
  72. cache['MD5'] = cache['md5'] = _md5.md5
  73. elif name in {'SHA256', 'sha256', 'SHA224', 'sha224'}:
  74. import _sha2
  75. cache['SHA224'] = cache['sha224'] = _sha2.sha224
  76. cache['SHA256'] = cache['sha256'] = _sha2.sha256
  77. elif name in {'SHA512', 'sha512', 'SHA384', 'sha384'}:
  78. import _sha2
  79. cache['SHA384'] = cache['sha384'] = _sha2.sha384
  80. cache['SHA512'] = cache['sha512'] = _sha2.sha512
  81. elif name in {'blake2b', 'blake2s'}:
  82. import _blake2
  83. cache['blake2b'] = _blake2.blake2b
  84. cache['blake2s'] = _blake2.blake2s
  85. elif name in {'sha3_224', 'sha3_256', 'sha3_384', 'sha3_512'}:
  86. import _sha3
  87. cache['sha3_224'] = _sha3.sha3_224
  88. cache['sha3_256'] = _sha3.sha3_256
  89. cache['sha3_384'] = _sha3.sha3_384
  90. cache['sha3_512'] = _sha3.sha3_512
  91. elif name in {'shake_128', 'shake_256'}:
  92. import _sha3
  93. cache['shake_128'] = _sha3.shake_128
  94. cache['shake_256'] = _sha3.shake_256
  95. except ImportError:
  96. pass # no extension module, this hash is unsupported.
  97. constructor = cache.get(name)
  98. if constructor is not None:
  99. return constructor
  100. raise ValueError('unsupported hash type ' + name)
  101. def __get_openssl_constructor(name):
  102. if name in __block_openssl_constructor:
  103. # Prefer our builtin blake2 implementation.
  104. return __get_builtin_constructor(name)
  105. try:
  106. # MD5, SHA1, and SHA2 are in all supported OpenSSL versions
  107. # SHA3/shake are available in OpenSSL 1.1.1+
  108. f = getattr(_hashlib, 'openssl_' + name)
  109. # Allow the C module to raise ValueError. The function will be
  110. # defined but the hash not actually available. Don't fall back to
  111. # builtin if the current security policy blocks a digest, bpo#40695.
  112. f(usedforsecurity=False)
  113. # Use the C function directly (very fast)
  114. return f
  115. except (AttributeError, ValueError):
  116. return __get_builtin_constructor(name)
  117. def __py_new(name, data=b'', **kwargs):
  118. """new(name, data=b'', **kwargs) - Return a new hashing object using the
  119. named algorithm; optionally initialized with data (which must be
  120. a bytes-like object).
  121. """
  122. return __get_builtin_constructor(name)(data, **kwargs)
  123. def __hash_new(name, data=b'', **kwargs):
  124. """new(name, data=b'') - Return a new hashing object using the named algorithm;
  125. optionally initialized with data (which must be a bytes-like object).
  126. """
  127. if name in __block_openssl_constructor:
  128. # Prefer our builtin blake2 implementation.
  129. return __get_builtin_constructor(name)(data, **kwargs)
  130. try:
  131. return _hashlib.new(name, data, **kwargs)
  132. except ValueError:
  133. # If the _hashlib module (OpenSSL) doesn't support the named
  134. # hash, try using our builtin implementations.
  135. # This allows for SHA224/256 and SHA384/512 support even though
  136. # the OpenSSL library prior to 0.9.8 doesn't provide them.
  137. return __get_builtin_constructor(name)(data)
  138. try:
  139. import _hashlib
  140. new = __hash_new
  141. __get_hash = __get_openssl_constructor
  142. algorithms_available = algorithms_available.union(
  143. _hashlib.openssl_md_meth_names)
  144. except ImportError:
  145. _hashlib = None
  146. new = __py_new
  147. __get_hash = __get_builtin_constructor
  148. try:
  149. # OpenSSL's PKCS5_PBKDF2_HMAC requires OpenSSL 1.0+ with HMAC and SHA
  150. from _hashlib import pbkdf2_hmac
  151. __all__ += ('pbkdf2_hmac',)
  152. except ImportError:
  153. pass
  154. try:
  155. # OpenSSL's scrypt requires OpenSSL 1.1+
  156. from _hashlib import scrypt
  157. except ImportError:
  158. pass
  159. def file_digest(fileobj, digest, /, *, _bufsize=2**18):
  160. """Hash the contents of a file-like object. Returns a digest object.
  161. *fileobj* must be a file-like object opened for reading in binary mode.
  162. It accepts file objects from open(), io.BytesIO(), and SocketIO objects.
  163. The function may bypass Python's I/O and use the file descriptor *fileno*
  164. directly.
  165. *digest* must either be a hash algorithm name as a *str*, a hash
  166. constructor, or a callable that returns a hash object.
  167. """
  168. # On Linux we could use AF_ALG sockets and sendfile() to archive zero-copy
  169. # hashing with hardware acceleration.
  170. if isinstance(digest, str):
  171. digestobj = new(digest)
  172. else:
  173. digestobj = digest()
  174. if hasattr(fileobj, "getbuffer"):
  175. # io.BytesIO object, use zero-copy buffer
  176. digestobj.update(fileobj.getbuffer())
  177. return digestobj
  178. # Only binary files implement readinto().
  179. if not (
  180. hasattr(fileobj, "readinto")
  181. and hasattr(fileobj, "readable")
  182. and fileobj.readable()
  183. ):
  184. raise ValueError(
  185. f"'{fileobj!r}' is not a file-like object in binary reading mode."
  186. )
  187. # binary file, socket.SocketIO object
  188. # Note: socket I/O uses different syscalls than file I/O.
  189. buf = bytearray(_bufsize) # Reusable buffer to reduce allocations.
  190. view = memoryview(buf)
  191. while True:
  192. size = fileobj.readinto(buf)
  193. if size == 0:
  194. break # EOF
  195. digestobj.update(view[:size])
  196. return digestobj
  197. for __func_name in __always_supported:
  198. # try them all, some may not work due to the OpenSSL
  199. # version not supporting that algorithm.
  200. try:
  201. globals()[__func_name] = __get_hash(__func_name)
  202. except ValueError:
  203. import logging
  204. logging.exception('code for hash %s was not found.', __func_name)
  205. # Cleanup locals()
  206. del __always_supported, __func_name, __get_hash
  207. del __py_new, __hash_new, __get_openssl_constructor