Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

hashlib.py 9.3 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
  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', '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
  108. a bytes-like object).
  109. """
  110. return __get_builtin_constructor(name)(data, **kwargs)
  111. def __hash_new(name, data=b'', **kwargs):
  112. """new(name, data=b'') - Return a new hashing object using the named algorithm;
  113. optionally initialized with data (which must be a bytes-like object).
  114. """
  115. if name in {'blake2b', 'blake2s'}:
  116. # Prefer our blake2 implementation.
  117. # OpenSSL 1.1.0 comes with a limited implementation of blake2b/s.
  118. # It does neither support keyed blake2 nor advanced features like
  119. # salt, personal, tree hashing or SSE.
  120. return __get_builtin_constructor(name)(data, **kwargs)
  121. try:
  122. return _hashlib.new(name, data)
  123. except ValueError:
  124. # If the _hashlib module (OpenSSL) doesn't support the named
  125. # hash, try using our builtin implementations.
  126. # This allows for SHA224/256 and SHA384/512 support even though
  127. # the OpenSSL library prior to 0.9.8 doesn't provide them.
  128. return __get_builtin_constructor(name)(data)
  129. try:
  130. import _hashlib
  131. new = __hash_new
  132. __get_hash = __get_openssl_constructor
  133. algorithms_available = algorithms_available.union(
  134. _hashlib.openssl_md_meth_names)
  135. except ImportError:
  136. new = __py_new
  137. __get_hash = __get_builtin_constructor
  138. try:
  139. # OpenSSL's PKCS5_PBKDF2_HMAC requires OpenSSL 1.0+ with HMAC and SHA
  140. from _hashlib import pbkdf2_hmac
  141. except ImportError:
  142. _trans_5C = bytes((x ^ 0x5C) for x in range(256))
  143. _trans_36 = bytes((x ^ 0x36) for x in range(256))
  144. def pbkdf2_hmac(hash_name, password, salt, iterations, dklen=None):
  145. """Password based key derivation function 2 (PKCS #5 v2.0)
  146. This Python implementations based on the hmac module about as fast
  147. as OpenSSL's PKCS5_PBKDF2_HMAC for short passwords and much faster
  148. for long passwords.
  149. """
  150. if not isinstance(hash_name, str):
  151. raise TypeError(hash_name)
  152. if not isinstance(password, (bytes, bytearray)):
  153. password = bytes(memoryview(password))
  154. if not isinstance(salt, (bytes, bytearray)):
  155. salt = bytes(memoryview(salt))
  156. # Fast inline HMAC implementation
  157. inner = new(hash_name)
  158. outer = new(hash_name)
  159. blocksize = getattr(inner, 'block_size', 64)
  160. if len(password) > blocksize:
  161. password = new(hash_name, password).digest()
  162. password = password + b'\x00' * (blocksize - len(password))
  163. inner.update(password.translate(_trans_36))
  164. outer.update(password.translate(_trans_5C))
  165. def prf(msg, inner=inner, outer=outer):
  166. # PBKDF2_HMAC uses the password as key. We can re-use the same
  167. # digest objects and just update copies to skip initialization.
  168. icpy = inner.copy()
  169. ocpy = outer.copy()
  170. icpy.update(msg)
  171. ocpy.update(icpy.digest())
  172. return ocpy.digest()
  173. if iterations < 1:
  174. raise ValueError(iterations)
  175. if dklen is None:
  176. dklen = outer.digest_size
  177. if dklen < 1:
  178. raise ValueError(dklen)
  179. dkey = b''
  180. loop = 1
  181. from_bytes = int.from_bytes
  182. while len(dkey) < dklen:
  183. prev = prf(salt + loop.to_bytes(4, 'big'))
  184. # endianness doesn't matter here as long to / from use the same
  185. rkey = int.from_bytes(prev, 'big')
  186. for i in range(iterations - 1):
  187. prev = prf(prev)
  188. # rkey = rkey ^ prev
  189. rkey ^= from_bytes(prev, 'big')
  190. loop += 1
  191. dkey += rkey.to_bytes(inner.digest_size, 'big')
  192. return dkey[:dklen]
  193. try:
  194. # OpenSSL's scrypt requires OpenSSL 1.1+
  195. from _hashlib import scrypt
  196. except ImportError:
  197. pass
  198. for __func_name in __always_supported:
  199. # try them all, some may not work due to the OpenSSL
  200. # version not supporting that algorithm.
  201. try:
  202. globals()[__func_name] = __get_hash(__func_name)
  203. except ValueError:
  204. import logging
  205. logging.exception('code for hash %s was not found.', __func_name)
  206. # Cleanup locals()
  207. del __always_supported, __func_name, __get_hash
  208. del __py_new, __hash_new, __get_openssl_constructor
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...