ยปCore Development>Code coverage>Lib/hashlib.py

Python code coverage for Lib/hashlib.py

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