hashlib.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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(arg): Update the hash object with the bytes in arg. 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.
  25. - hexdigest(): Like digest() except the digest is returned as a unicode
  26. object 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 strings that share a common
  29. initial substring.
  30. For example, to obtain the digest of the 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. def __get_builtin_constructor(name):
  54. cache = __builtin_constructor_cache
  55. constructor = cache.get(name)
  56. if constructor is not None:
  57. return constructor
  58. try:
  59. if name in ('SHA1', 'sha1'):
  60. import _sha1
  61. cache['SHA1'] = cache['sha1'] = _sha1.sha1
  62. elif name in ('MD5', 'md5'):
  63. import _md5
  64. cache['MD5'] = cache['md5'] = _md5.md5
  65. elif name in ('SHA256', 'sha256', 'SHA224', 'sha224'):
  66. import _sha256
  67. cache['SHA224'] = cache['sha224'] = _sha256.sha224
  68. cache['SHA256'] = cache['sha256'] = _sha256.sha256
  69. elif name in ('SHA512', 'sha512', 'SHA384', 'sha384'):
  70. import _sha512
  71. cache['SHA384'] = cache['sha384'] = _sha512.sha384
  72. cache['SHA512'] = cache['sha512'] = _sha512.sha512
  73. elif name in ('blake2b', 'blake2s'):
  74. import _blake2
  75. cache['blake2b'] = _blake2.blake2b
  76. cache['blake2s'] = _blake2.blake2s
  77. elif name in {'sha3_224', 'sha3_256', 'sha3_384', 'sha3_512'}:
  78. #'shake_128', 'shake_256'}:
  79. import _sha3
  80. cache['sha3_224'] = _sha3.sha3_224
  81. cache['sha3_256'] = _sha3.sha3_256
  82. cache['sha3_384'] = _sha3.sha3_384
  83. cache['sha3_512'] = _sha3.sha3_512
  84. #cache['shake_128'] = _sha3.shake_128
  85. #cache['shake_256'] = _sha3.shake_256
  86. except ImportError:
  87. pass # no extension module, this hash is unsupported.
  88. constructor = cache.get(name)
  89. if constructor is not None:
  90. return constructor
  91. raise ValueError('unsupported hash type ' + name)
  92. def __get_openssl_constructor(name):
  93. if name in {'blake2b', 'blake2s'}:
  94. # Prefer our blake2 implementation.
  95. return __get_builtin_constructor(name)
  96. try:
  97. f = getattr(_hashlib, 'openssl_' + name)
  98. # Allow the C module to raise ValueError. The function will be
  99. # defined but the hash not actually available thanks to OpenSSL.
  100. f()
  101. # Use the C function directly (very fast)
  102. return f
  103. except (AttributeError, ValueError):
  104. return __get_builtin_constructor(name)
  105. def __py_new(name, data=b'', **kwargs):
  106. """new(name, data=b'', **kwargs) - Return a new hashing object using the
  107. named algorithm; optionally initialized with data (which must be bytes).
  108. """
  109. return __get_builtin_constructor(name)(data, **kwargs)
  110. def __hash_new(name, data=b'', **kwargs):
  111. """new(name, data=b'') - Return a new hashing object using the named algorithm;
  112. optionally initialized with data (which must be bytes).
  113. """
  114. if name in {'blake2b', 'blake2s'}:
  115. # Prefer our blake2 implementation.
  116. # OpenSSL 1.1.0 comes with a limited implementation of blake2b/s.
  117. # It does neither support keyed blake2 nor advanced features like
  118. # salt, personal, tree hashing or SSE.
  119. return __get_builtin_constructor(name)(data, **kwargs)
  120. try:
  121. return _hashlib.new(name, data)
  122. except ValueError:
  123. # If the _hashlib module (OpenSSL) doesn't support the named
  124. # hash, try using our builtin implementations.
  125. # This allows for SHA224/256 and SHA384/512 support even though
  126. # the OpenSSL library prior to 0.9.8 doesn't provide them.
  127. return __get_builtin_constructor(name)(data)
  128. try:
  129. import _hashlib
  130. new = __hash_new
  131. __get_hash = __get_openssl_constructor
  132. algorithms_available = algorithms_available.union(
  133. _hashlib.openssl_md_meth_names)
  134. except ImportError:
  135. new = __py_new
  136. __get_hash = __get_builtin_constructor
  137. try:
  138. # OpenSSL's PKCS5_PBKDF2_HMAC requires OpenSSL 1.0+ with HMAC and SHA
  139. from _hashlib import pbkdf2_hmac
  140. except ImportError:
  141. _trans_5C = bytes((x ^ 0x5C) for x in range(256))
  142. _trans_36 = bytes((x ^ 0x36) for x in range(256))
  143. def pbkdf2_hmac(hash_name, password, salt, iterations, dklen=None):
  144. """Password based key derivation function 2 (PKCS #5 v2.0)
  145. This Python implementations based on the hmac module about as fast
  146. as OpenSSL's PKCS5_PBKDF2_HMAC for short passwords and much faster
  147. for long passwords.
  148. """
  149. if not isinstance(hash_name, str):
  150. raise TypeError(hash_name)
  151. if not isinstance(password, (bytes, bytearray)):
  152. password = bytes(memoryview(password))
  153. if not isinstance(salt, (bytes, bytearray)):
  154. salt = bytes(memoryview(salt))
  155. # Fast inline HMAC implementation
  156. inner = new(hash_name)
  157. outer = new(hash_name)
  158. blocksize = getattr(inner, 'block_size', 64)
  159. if len(password) > blocksize:
  160. password = new(hash_name, password).digest()
  161. password = password + b'\x00' * (blocksize - len(password))
  162. inner.update(password.translate(_trans_36))
  163. outer.update(password.translate(_trans_5C))
  164. def prf(msg, inner=inner, outer=outer):
  165. # PBKDF2_HMAC uses the password as key. We can re-use the same
  166. # digest objects and just update copies to skip initialization.
  167. icpy = inner.copy()
  168. ocpy = outer.copy()
  169. icpy.update(msg)
  170. ocpy.update(icpy.digest())
  171. return ocpy.digest()
  172. if iterations < 1:
  173. raise ValueError(iterations)
  174. if dklen is None:
  175. dklen = outer.digest_size
  176. if dklen < 1:
  177. raise ValueError(dklen)
  178. dkey = b''
  179. loop = 1
  180. from_bytes = int.from_bytes
  181. while len(dkey) < dklen:
  182. prev = prf(salt + loop.to_bytes(4, 'big'))
  183. # endianess doesn't matter here as long to / from use the same
  184. rkey = int.from_bytes(prev, 'big')
  185. for i in range(iterations - 1):
  186. prev = prf(prev)
  187. # rkey = rkey ^ prev
  188. rkey ^= from_bytes(prev, 'big')
  189. loop += 1
  190. dkey += rkey.to_bytes(inner.digest_size, 'big')
  191. return dkey[:dklen]
  192. try:
  193. # OpenSSL's scrypt requires OpenSSL 1.1+
  194. from _hashlib import scrypt
  195. except ImportError:
  196. pass
  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