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