|
3 | 3 | import hashlib |
4 | 4 | import os |
5 | 5 | import sys |
6 | | -from contextlib import suppress |
| 6 | +from hashlib import file_digest |
7 | 7 | from pathlib import Path |
8 | 8 | from typing import Any |
9 | 9 |
|
|
13 | 13 | _WINDOWS_DRIVE_PREFIX_LENGTH = 3 |
14 | 14 |
|
15 | 15 |
|
16 | | -if sys.version_info >= (3, 11): # pragma: no cover |
17 | | - from hashlib import file_digest |
18 | | -else: # pragma: no cover |
19 | | - # This tuple and __get_builtin_constructor() must be modified if a new |
20 | | - # always available algorithm is added. |
21 | | - __always_supported = ( |
22 | | - "md5", |
23 | | - "sha1", |
24 | | - "sha224", |
25 | | - "sha256", |
26 | | - "sha384", |
27 | | - "sha512", |
28 | | - "blake2b", |
29 | | - "blake2s", |
30 | | - "sha3_224", |
31 | | - "sha3_256", |
32 | | - "sha3_384", |
33 | | - "sha3_512", |
34 | | - "shake_128", |
35 | | - "shake_256", |
36 | | - ) |
37 | | - |
38 | | - algorithms_guaranteed = set(__always_supported) |
39 | | - algorithms_available = set(__always_supported) |
40 | | - |
41 | | - __all__ = __always_supported + ( |
42 | | - "new", |
43 | | - "algorithms_guaranteed", |
44 | | - "algorithms_available", |
45 | | - "file_digest", |
46 | | - ) |
47 | | - |
48 | | - __builtin_constructor_cache = {} |
49 | | - |
50 | | - # Prefer our blake2 implementation |
51 | | - # OpenSSL 1.1.0 comes with a limited implementation of blake2b/s. The OpenSSL |
52 | | - # implementations neither support keyed blake2 (blake2 MAC) nor advanced |
53 | | - # features like salt, personalization, or tree hashing. OpenSSL hash-only |
54 | | - # variants are available as 'blake2b512' and 'blake2s256', though. |
55 | | - __block_openssl_constructor = { |
56 | | - "blake2b", |
57 | | - "blake2s", |
58 | | - } |
59 | | - |
60 | | - def __get_builtin_constructor(name): |
61 | | - cache = __builtin_constructor_cache |
62 | | - constructor = cache.get(name) |
63 | | - if constructor is not None: |
64 | | - return constructor |
65 | | - |
66 | | - with suppress(ImportError): |
67 | | - if name in {"SHA1", "sha1"}: |
68 | | - import _sha1 |
69 | | - |
70 | | - cache["SHA1"] = cache["sha1"] = _sha1.sha1 |
71 | | - elif name in {"MD5", "md5"}: |
72 | | - import _md5 |
73 | | - |
74 | | - cache["MD5"] = cache["md5"] = _md5.md5 |
75 | | - elif name in {"SHA256", "sha256", "SHA224", "sha224"}: |
76 | | - try: |
77 | | - import _sha2 |
78 | | - except ImportError: |
79 | | - import _sha256 as _sha2 |
80 | | - cache["SHA224"] = cache["sha224"] = _sha2.sha224 |
81 | | - cache["SHA256"] = cache["sha256"] = _sha2.sha256 |
82 | | - elif name in {"SHA512", "sha512", "SHA384", "sha384"}: |
83 | | - try: |
84 | | - import _sha2 |
85 | | - except ImportError: |
86 | | - import _sha256 as _sha2 |
87 | | - cache["SHA384"] = cache["sha384"] = _sha2.sha384 |
88 | | - cache["SHA512"] = cache["sha512"] = _sha2.sha512 |
89 | | - elif name in {"blake2b", "blake2s"}: |
90 | | - import _blake2 |
91 | | - |
92 | | - cache["blake2b"] = _blake2.blake2b |
93 | | - cache["blake2s"] = _blake2.blake2s |
94 | | - elif name in {"sha3_224", "sha3_256", "sha3_384", "sha3_512"}: |
95 | | - import _sha3 |
96 | | - |
97 | | - cache["sha3_224"] = _sha3.sha3_224 |
98 | | - cache["sha3_256"] = _sha3.sha3_256 |
99 | | - cache["sha3_384"] = _sha3.sha3_384 |
100 | | - cache["sha3_512"] = _sha3.sha3_512 |
101 | | - elif name in {"shake_128", "shake_256"}: |
102 | | - import _sha3 |
103 | | - |
104 | | - cache["shake_128"] = _sha3.shake_128 |
105 | | - cache["shake_256"] = _sha3.shake_256 |
106 | | - |
107 | | - constructor = cache.get(name) |
108 | | - if constructor is not None: |
109 | | - return constructor |
110 | | - |
111 | | - raise ValueError("unsupported hash type " + name) |
112 | | - |
113 | | - def __get_openssl_constructor(name): |
114 | | - if name in __block_openssl_constructor: |
115 | | - # Prefer our builtin blake2 implementation. |
116 | | - return __get_builtin_constructor(name) |
117 | | - try: |
118 | | - # MD5, SHA1, and SHA2 are in all supported OpenSSL versions |
119 | | - # SHA3/shake are available in OpenSSL 1.1.1+ |
120 | | - f = getattr(_hashlib, "openssl_" + name) |
121 | | - # Allow the C module to raise ValueError. The function will be |
122 | | - # defined but the hash not actually available. Don't fall back to |
123 | | - # builtin if the current security policy blocks a digest, bpo#40695. |
124 | | - f(usedforsecurity=False) |
125 | | - # Use the C function directly (very fast) |
126 | | - return f |
127 | | - except (AttributeError, ValueError): |
128 | | - return __get_builtin_constructor(name) |
129 | | - |
130 | | - def __py_new(name, data=b"", **kwargs): |
131 | | - """new(name, data=b'', **kwargs) - Return a new hashing object using the |
132 | | - named algorithm; optionally initialized with data (which must be |
133 | | - a bytes-like object). |
134 | | - """ |
135 | | - return __get_builtin_constructor(name)(data, **kwargs) |
136 | | - |
137 | | - def __hash_new(name, data=b"", **kwargs): |
138 | | - """new(name, data=b'') - Return a new hashing object using the named algorithm; |
139 | | - optionally initialized with data (which must be a bytes-like object). |
140 | | - """ |
141 | | - if name in __block_openssl_constructor: |
142 | | - # Prefer our builtin blake2 implementation. |
143 | | - return __get_builtin_constructor(name)(data, **kwargs) |
144 | | - try: |
145 | | - return _hashlib.new(name, data, **kwargs) |
146 | | - except ValueError: |
147 | | - # If the _hashlib module (OpenSSL) doesn't support the named |
148 | | - # hash, try using our builtin implementations. |
149 | | - # This allows for SHA224/256 and SHA384/512 support even though |
150 | | - # the OpenSSL library prior to 0.9.8 doesn't provide them. |
151 | | - return __get_builtin_constructor(name)(data) |
152 | | - |
153 | | - try: |
154 | | - import _hashlib |
155 | | - |
156 | | - new = __hash_new |
157 | | - __get_hash = __get_openssl_constructor |
158 | | - algorithms_available = algorithms_available.union( |
159 | | - _hashlib.openssl_md_meth_names |
160 | | - ) |
161 | | - except ImportError: |
162 | | - _hashlib = None |
163 | | - new = __py_new |
164 | | - __get_hash = __get_builtin_constructor |
165 | | - |
166 | | - with suppress(ImportError): |
167 | | - # OpenSSL's PKCS5_PBKDF2_HMAC requires OpenSSL 1.0+ with HMAC and SHA |
168 | | - from _hashlib import pbkdf2_hmac |
169 | | - |
170 | | - __all__ += ("pbkdf2_hmac",) |
171 | | - |
172 | | - with suppress(ImportError): |
173 | | - # OpenSSL's scrypt requires OpenSSL 1.1+ |
174 | | - from _hashlib import scrypt |
175 | | - |
176 | | - def file_digest(fileobj, digest, /, *, _bufsize=2**18): |
177 | | - """Hash the contents of a file-like object. Returns a digest object. |
178 | | - |
179 | | - *fileobj* must be a file-like object opened for reading in binary mode. |
180 | | - It accepts file objects from open(), io.BytesIO(), and SocketIO objects. |
181 | | - The function may bypass Python's I/O and use the file descriptor *fileno* |
182 | | - directly. |
183 | | - |
184 | | - *digest* must either be a hash algorithm name as a *str*, a hash |
185 | | - constructor, or a callable that returns a hash object. |
186 | | - """ |
187 | | - # On Linux we could use AF_ALG sockets and sendfile() to archive zero-copy |
188 | | - # hashing with hardware acceleration. |
189 | | - if isinstance(digest, str): |
190 | | - digestobj = new(digest) |
191 | | - else: |
192 | | - digestobj = digest() |
193 | | - |
194 | | - if hasattr(fileobj, "getbuffer"): |
195 | | - # io.BytesIO object, use zero-copy buffer |
196 | | - digestobj.update(fileobj.getbuffer()) |
197 | | - return digestobj |
198 | | - |
199 | | - # Only binary files implement readinto(). |
200 | | - if not ( |
201 | | - hasattr(fileobj, "readinto") |
202 | | - and hasattr(fileobj, "readable") |
203 | | - and fileobj.readable() |
204 | | - ): |
205 | | - raise ValueError( |
206 | | - f"'{fileobj!r}' is not a file-like object in binary reading mode." |
207 | | - ) |
208 | | - |
209 | | - # binary file, socket.SocketIO object |
210 | | - # Note: socket I/O uses different syscalls than file I/O. |
211 | | - buf = bytearray(_bufsize) # Reusable buffer to reduce allocations. |
212 | | - view = memoryview(buf) |
213 | | - while True: |
214 | | - size = fileobj.readinto(buf) |
215 | | - if size == 0: |
216 | | - break # EOF |
217 | | - digestobj.update(view[:size]) |
218 | | - |
219 | | - return digestobj |
220 | | - |
221 | | - |
222 | 16 | def hash_value(value: Any) -> int | str: |
223 | 17 | """Hash values. |
224 | 18 |
|
|
0 commit comments