1 # Test the hashlib module.
2 #
3 # Copyright (C) 2005-2010 Gregory P. Smith (greg@krypto.org)
4 # Licensed to PSF under a Contributor Agreement.
5 #
6
7 import array
8 from binascii import unhexlify
9 import hashlib
10 import importlib
11 import io
12 import itertools
13 import os
14 import sys
15 import sysconfig
16 import threading
17 import unittest
18 import warnings
19 from test import support
20 from test.support import _4G, bigmemtest
21 from test.support.import_helper import import_fresh_module
22 from test.support import os_helper
23 from test.support import requires_resource
24 from test.support import threading_helper
25 from http.client import HTTPException
26
27
28 default_builtin_hashes = {'md5', 'sha1', 'sha256', 'sha512', 'sha3', 'blake2'}
29 # --with-builtin-hashlib-hashes override
30 builtin_hashes = sysconfig.get_config_var("PY_BUILTIN_HASHLIB_HASHES")
31 if builtin_hashes is None:
32 builtin_hashes = default_builtin_hashes
33 else:
34 builtin_hashes = {
35 m.strip() for m in builtin_hashes.strip('"').lower().split(",")
36 }
37
38 # hashlib with and without OpenSSL backend for PBKDF2
39 # only import builtin_hashlib when all builtin hashes are available.
40 # Otherwise import prints noise on stderr
41 openssl_hashlib = import_fresh_module('hashlib', fresh=['_hashlib'])
42 if builtin_hashes == default_builtin_hashes:
43 builtin_hashlib = import_fresh_module('hashlib', blocked=['_hashlib'])
44 else:
45 builtin_hashlib = None
46
47 try:
48 from _hashlib import HASH, HASHXOF, openssl_md_meth_names, get_fips_mode
49 except ImportError:
50 HASH = None
51 HASHXOF = None
52 openssl_md_meth_names = frozenset()
53
54 def get_fips_mode():
55 return 0
56
57 try:
58 import _blake2
59 except ImportError:
60 _blake2 = None
61
62 requires_blake2 = unittest.skipUnless(_blake2, 'requires _blake2')
63
64 # bpo-46913: Don't test the _sha3 extension on a Python UBSAN build
65 # TODO(gh-99108): Revisit this after _sha3 uses HACL*.
66 SKIP_SHA3 = support.check_sanitizer(ub=True)
67 requires_sha3 = unittest.skipUnless(not SKIP_SHA3, 'requires _sha3')
68
69
70 def hexstr(s):
71 assert isinstance(s, bytes), repr(s)
72 h = "0123456789abcdef"
73 r = ''
74 for i in s:
75 r += h[(i >> 4) & 0xF] + h[i & 0xF]
76 return r
77
78
79 URL = "http://www.pythontest.net/hashlib/{}.txt"
80
81 def read_vectors(hash_name):
82 url = URL.format(hash_name)
83 try:
84 testdata = support.open_urlresource(url, encoding="utf-8")
85 except (OSError, HTTPException):
86 raise unittest.SkipTest("Could not retrieve {}".format(url))
87 with testdata:
88 for line in testdata:
89 line = line.strip()
90 if line.startswith('#') or not line:
91 continue
92 parts = line.split(',')
93 parts[0] = bytes.fromhex(parts[0])
94 yield parts
95
96
97 class ESC[4;38;5;81mHashLibTestCase(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
98 supported_hash_names = ( 'md5', 'MD5', 'sha1', 'SHA1',
99 'sha224', 'SHA224', 'sha256', 'SHA256',
100 'sha384', 'SHA384', 'sha512', 'SHA512',
101 'blake2b', 'blake2s',
102 'sha3_224', 'sha3_256', 'sha3_384', 'sha3_512',
103 'shake_128', 'shake_256')
104
105 shakes = {'shake_128', 'shake_256'}
106
107 # gh-58898: Fallback modules are always compiled under POSIX.
108 _warn_on_extension_import = (os.name == 'posix' or support.Py_DEBUG)
109
110 def _conditional_import_module(self, module_name):
111 """Import a module and return a reference to it or None on failure."""
112 try:
113 return importlib.import_module(module_name)
114 except ModuleNotFoundError as error:
115 if self._warn_on_extension_import and module_name in builtin_hashes:
116 warnings.warn(f'Did a C extension fail to compile? {error}')
117 return None
118
119 def __init__(self, *args, **kwargs):
120 algorithms = set()
121 for algorithm in self.supported_hash_names:
122 algorithms.add(algorithm.lower())
123
124 _blake2 = self._conditional_import_module('_blake2')
125 if _blake2:
126 algorithms.update({'blake2b', 'blake2s'})
127
128 self.constructors_to_test = {}
129 for algorithm in algorithms:
130 if SKIP_SHA3 and algorithm.startswith('sha3_'):
131 continue
132 self.constructors_to_test[algorithm] = set()
133
134 # For each algorithm, test the direct constructor and the use
135 # of hashlib.new given the algorithm name.
136 for algorithm, constructors in self.constructors_to_test.items():
137 constructors.add(getattr(hashlib, algorithm))
138 def _test_algorithm_via_hashlib_new(data=None, _alg=algorithm, **kwargs):
139 if data is None:
140 return hashlib.new(_alg, **kwargs)
141 return hashlib.new(_alg, data, **kwargs)
142 constructors.add(_test_algorithm_via_hashlib_new)
143
144 _hashlib = self._conditional_import_module('_hashlib')
145 self._hashlib = _hashlib
146 if _hashlib:
147 # These algorithms should always be present when this module
148 # is compiled. If not, something was compiled wrong.
149 self.assertTrue(hasattr(_hashlib, 'openssl_md5'))
150 self.assertTrue(hasattr(_hashlib, 'openssl_sha1'))
151 for algorithm, constructors in self.constructors_to_test.items():
152 constructor = getattr(_hashlib, 'openssl_'+algorithm, None)
153 if constructor:
154 try:
155 constructor()
156 except ValueError:
157 # default constructor blocked by crypto policy
158 pass
159 else:
160 constructors.add(constructor)
161
162 def add_builtin_constructor(name):
163 constructor = getattr(hashlib, "__get_builtin_constructor")(name)
164 self.constructors_to_test[name].add(constructor)
165
166 _md5 = self._conditional_import_module('_md5')
167 if _md5:
168 add_builtin_constructor('md5')
169 _sha1 = self._conditional_import_module('_sha1')
170 if _sha1:
171 add_builtin_constructor('sha1')
172 _sha2 = self._conditional_import_module('_sha2')
173 if _sha2:
174 add_builtin_constructor('sha224')
175 add_builtin_constructor('sha256')
176 add_builtin_constructor('sha384')
177 add_builtin_constructor('sha512')
178 if _blake2:
179 add_builtin_constructor('blake2s')
180 add_builtin_constructor('blake2b')
181
182 if not SKIP_SHA3:
183 _sha3 = self._conditional_import_module('_sha3')
184 if _sha3:
185 add_builtin_constructor('sha3_224')
186 add_builtin_constructor('sha3_256')
187 add_builtin_constructor('sha3_384')
188 add_builtin_constructor('sha3_512')
189 add_builtin_constructor('shake_128')
190 add_builtin_constructor('shake_256')
191
192 super(HashLibTestCase, self).__init__(*args, **kwargs)
193
194 @property
195 def hash_constructors(self):
196 constructors = self.constructors_to_test.values()
197 return itertools.chain.from_iterable(constructors)
198
199 @property
200 def is_fips_mode(self):
201 return get_fips_mode()
202
203 def test_hash_array(self):
204 a = array.array("b", range(10))
205 for cons in self.hash_constructors:
206 c = cons(a, usedforsecurity=False)
207 if c.name in self.shakes:
208 c.hexdigest(16)
209 else:
210 c.hexdigest()
211
212 def test_algorithms_guaranteed(self):
213 self.assertEqual(hashlib.algorithms_guaranteed,
214 set(_algo for _algo in self.supported_hash_names
215 if _algo.islower()))
216
217 def test_algorithms_available(self):
218 self.assertTrue(set(hashlib.algorithms_guaranteed).
219 issubset(hashlib.algorithms_available))
220 # all available algorithms must be loadable, bpo-47101
221 self.assertNotIn("undefined", hashlib.algorithms_available)
222 for name in hashlib.algorithms_available:
223 digest = hashlib.new(name, usedforsecurity=False)
224
225 def test_usedforsecurity_true(self):
226 hashlib.new("sha256", usedforsecurity=True)
227 if self.is_fips_mode:
228 self.skipTest("skip in FIPS mode")
229 for cons in self.hash_constructors:
230 cons(usedforsecurity=True)
231 cons(b'', usedforsecurity=True)
232 hashlib.new("md5", usedforsecurity=True)
233 hashlib.md5(usedforsecurity=True)
234 if self._hashlib is not None:
235 self._hashlib.new("md5", usedforsecurity=True)
236 self._hashlib.openssl_md5(usedforsecurity=True)
237
238 def test_usedforsecurity_false(self):
239 hashlib.new("sha256", usedforsecurity=False)
240 for cons in self.hash_constructors:
241 cons(usedforsecurity=False)
242 cons(b'', usedforsecurity=False)
243 hashlib.new("md5", usedforsecurity=False)
244 hashlib.md5(usedforsecurity=False)
245 if self._hashlib is not None:
246 self._hashlib.new("md5", usedforsecurity=False)
247 self._hashlib.openssl_md5(usedforsecurity=False)
248
249 def test_unknown_hash(self):
250 self.assertRaises(ValueError, hashlib.new, 'spam spam spam spam spam')
251 self.assertRaises(TypeError, hashlib.new, 1)
252
253 def test_new_upper_to_lower(self):
254 self.assertEqual(hashlib.new("SHA256").name, "sha256")
255
256 def test_get_builtin_constructor(self):
257 get_builtin_constructor = getattr(hashlib,
258 '__get_builtin_constructor')
259 builtin_constructor_cache = getattr(hashlib,
260 '__builtin_constructor_cache')
261 self.assertRaises(ValueError, get_builtin_constructor, 'test')
262 try:
263 import _md5
264 except ImportError:
265 self.skipTest("_md5 module not available")
266 # This forces an ImportError for "import _md5" statements
267 sys.modules['_md5'] = None
268 # clear the cache
269 builtin_constructor_cache.clear()
270 try:
271 self.assertRaises(ValueError, get_builtin_constructor, 'md5')
272 finally:
273 if '_md5' in locals():
274 sys.modules['_md5'] = _md5
275 else:
276 del sys.modules['_md5']
277 self.assertRaises(TypeError, get_builtin_constructor, 3)
278 constructor = get_builtin_constructor('md5')
279 self.assertIs(constructor, _md5.md5)
280 self.assertEqual(sorted(builtin_constructor_cache), ['MD5', 'md5'])
281
282 def test_hexdigest(self):
283 for cons in self.hash_constructors:
284 h = cons(usedforsecurity=False)
285 if h.name in self.shakes:
286 self.assertIsInstance(h.digest(16), bytes)
287 self.assertEqual(hexstr(h.digest(16)), h.hexdigest(16))
288 else:
289 self.assertIsInstance(h.digest(), bytes)
290 self.assertEqual(hexstr(h.digest()), h.hexdigest())
291
292 def test_digest_length_overflow(self):
293 # See issue #34922
294 large_sizes = (2**29, 2**32-10, 2**32+10, 2**61, 2**64-10, 2**64+10)
295 for cons in self.hash_constructors:
296 h = cons(usedforsecurity=False)
297 if h.name not in self.shakes:
298 continue
299 if HASH is not None and isinstance(h, HASH):
300 # _hashopenssl's take a size_t
301 continue
302 for digest in h.digest, h.hexdigest:
303 self.assertRaises(ValueError, digest, -10)
304 for length in large_sizes:
305 with self.assertRaises((ValueError, OverflowError)):
306 digest(length)
307
308 def test_name_attribute(self):
309 for cons in self.hash_constructors:
310 h = cons(usedforsecurity=False)
311 self.assertIsInstance(h.name, str)
312 if h.name in self.supported_hash_names:
313 self.assertIn(h.name, self.supported_hash_names)
314 else:
315 self.assertNotIn(h.name, self.supported_hash_names)
316 self.assertEqual(
317 h.name,
318 hashlib.new(h.name, usedforsecurity=False).name
319 )
320
321 def test_large_update(self):
322 aas = b'a' * 128
323 bees = b'b' * 127
324 cees = b'c' * 126
325 dees = b'd' * 2048 # HASHLIB_GIL_MINSIZE
326
327 for cons in self.hash_constructors:
328 m1 = cons(usedforsecurity=False)
329 m1.update(aas)
330 m1.update(bees)
331 m1.update(cees)
332 m1.update(dees)
333 if m1.name in self.shakes:
334 args = (16,)
335 else:
336 args = ()
337
338 m2 = cons(usedforsecurity=False)
339 m2.update(aas + bees + cees + dees)
340 self.assertEqual(m1.digest(*args), m2.digest(*args))
341
342 m3 = cons(aas + bees + cees + dees, usedforsecurity=False)
343 self.assertEqual(m1.digest(*args), m3.digest(*args))
344
345 # verify copy() doesn't touch original
346 m4 = cons(aas + bees + cees, usedforsecurity=False)
347 m4_digest = m4.digest(*args)
348 m4_copy = m4.copy()
349 m4_copy.update(dees)
350 self.assertEqual(m1.digest(*args), m4_copy.digest(*args))
351 self.assertEqual(m4.digest(*args), m4_digest)
352
353 @requires_resource('cpu')
354 def test_sha256_update_over_4gb(self):
355 zero_1mb = b"\0" * 1024 * 1024
356 h = hashlib.sha256()
357 for i in range(0, 4096):
358 h.update(zero_1mb)
359 h.update(b"hello world")
360 self.assertEqual(h.hexdigest(), "a5364f7a52ebe2e25f1838a4ca715a893b6fd7a23f2a0d9e9762120da8b1bf53")
361
362 @requires_resource('cpu')
363 def test_sha3_256_update_over_4gb(self):
364 zero_1mb = b"\0" * 1024 * 1024
365 h = hashlib.sha3_256()
366 for i in range(0, 4096):
367 h.update(zero_1mb)
368 h.update(b"hello world")
369 self.assertEqual(h.hexdigest(), "e2d4535e3b613135c14f2fe4e026d7ad8d569db44901740beffa30d430acb038")
370
371 def check(self, name, data, hexdigest, shake=False, **kwargs):
372 length = len(hexdigest)//2
373 hexdigest = hexdigest.lower()
374 constructors = self.constructors_to_test[name]
375 # 2 is for hashlib.name(...) and hashlib.new(name, ...)
376 self.assertGreaterEqual(len(constructors), 2)
377 for hash_object_constructor in constructors:
378 m = hash_object_constructor(data, **kwargs)
379 computed = m.hexdigest() if not shake else m.hexdigest(length)
380 self.assertEqual(
381 computed, hexdigest,
382 "Hash algorithm %s constructed using %s returned hexdigest"
383 " %r for %d byte input data that should have hashed to %r."
384 % (name, hash_object_constructor,
385 computed, len(data), hexdigest))
386 computed = m.digest() if not shake else m.digest(length)
387 digest = bytes.fromhex(hexdigest)
388 self.assertEqual(computed, digest)
389 if not shake:
390 self.assertEqual(len(digest), m.digest_size)
391
392 if not shake and kwargs.get("key") is None:
393 # skip shake and blake2 extended parameter tests
394 self.check_file_digest(name, data, hexdigest)
395
396 def check_file_digest(self, name, data, hexdigest):
397 hexdigest = hexdigest.lower()
398 try:
399 hashlib.new(name)
400 except ValueError:
401 # skip, algorithm is blocked by security policy.
402 return
403 digests = [name]
404 digests.extend(self.constructors_to_test[name])
405
406 with open(os_helper.TESTFN, "wb") as f:
407 f.write(data)
408
409 try:
410 for digest in digests:
411 buf = io.BytesIO(data)
412 buf.seek(0)
413 self.assertEqual(
414 hashlib.file_digest(buf, digest).hexdigest(), hexdigest
415 )
416 with open(os_helper.TESTFN, "rb") as f:
417 digestobj = hashlib.file_digest(f, digest)
418 self.assertEqual(digestobj.hexdigest(), hexdigest)
419 finally:
420 os.unlink(os_helper.TESTFN)
421
422 def check_no_unicode(self, algorithm_name):
423 # Unicode objects are not allowed as input.
424 constructors = self.constructors_to_test[algorithm_name]
425 for hash_object_constructor in constructors:
426 self.assertRaises(TypeError, hash_object_constructor, 'spam')
427
428 def test_no_unicode(self):
429 self.check_no_unicode('md5')
430 self.check_no_unicode('sha1')
431 self.check_no_unicode('sha224')
432 self.check_no_unicode('sha256')
433 self.check_no_unicode('sha384')
434 self.check_no_unicode('sha512')
435
436 @requires_blake2
437 def test_no_unicode_blake2(self):
438 self.check_no_unicode('blake2b')
439 self.check_no_unicode('blake2s')
440
441 @requires_sha3
442 def test_no_unicode_sha3(self):
443 self.check_no_unicode('sha3_224')
444 self.check_no_unicode('sha3_256')
445 self.check_no_unicode('sha3_384')
446 self.check_no_unicode('sha3_512')
447 self.check_no_unicode('shake_128')
448 self.check_no_unicode('shake_256')
449
450 def check_blocksize_name(self, name, block_size=0, digest_size=0,
451 digest_length=None):
452 constructors = self.constructors_to_test[name]
453 for hash_object_constructor in constructors:
454 m = hash_object_constructor(usedforsecurity=False)
455 self.assertEqual(m.block_size, block_size)
456 self.assertEqual(m.digest_size, digest_size)
457 if digest_length:
458 self.assertEqual(len(m.digest(digest_length)),
459 digest_length)
460 self.assertEqual(len(m.hexdigest(digest_length)),
461 2*digest_length)
462 else:
463 self.assertEqual(len(m.digest()), digest_size)
464 self.assertEqual(len(m.hexdigest()), 2*digest_size)
465 self.assertEqual(m.name, name)
466 # split for sha3_512 / _sha3.sha3 object
467 self.assertIn(name.split("_")[0], repr(m).lower())
468
469 def test_blocksize_and_name(self):
470 self.check_blocksize_name('md5', 64, 16)
471 self.check_blocksize_name('sha1', 64, 20)
472 self.check_blocksize_name('sha224', 64, 28)
473 self.check_blocksize_name('sha256', 64, 32)
474 self.check_blocksize_name('sha384', 128, 48)
475 self.check_blocksize_name('sha512', 128, 64)
476
477 @requires_sha3
478 def test_blocksize_name_sha3(self):
479 self.check_blocksize_name('sha3_224', 144, 28)
480 self.check_blocksize_name('sha3_256', 136, 32)
481 self.check_blocksize_name('sha3_384', 104, 48)
482 self.check_blocksize_name('sha3_512', 72, 64)
483 self.check_blocksize_name('shake_128', 168, 0, 32)
484 self.check_blocksize_name('shake_256', 136, 0, 64)
485
486 def check_sha3(self, name, capacity, rate, suffix):
487 constructors = self.constructors_to_test[name]
488 for hash_object_constructor in constructors:
489 m = hash_object_constructor()
490 if HASH is not None and isinstance(m, HASH):
491 # _hashopenssl's variant does not have extra SHA3 attributes
492 continue
493 self.assertEqual(capacity + rate, 1600)
494 self.assertEqual(m._capacity_bits, capacity)
495 self.assertEqual(m._rate_bits, rate)
496 self.assertEqual(m._suffix, suffix)
497
498 @requires_sha3
499 def test_extra_sha3(self):
500 self.check_sha3('sha3_224', 448, 1152, b'\x06')
501 self.check_sha3('sha3_256', 512, 1088, b'\x06')
502 self.check_sha3('sha3_384', 768, 832, b'\x06')
503 self.check_sha3('sha3_512', 1024, 576, b'\x06')
504 self.check_sha3('shake_128', 256, 1344, b'\x1f')
505 self.check_sha3('shake_256', 512, 1088, b'\x1f')
506
507 @requires_blake2
508 def test_blocksize_name_blake2(self):
509 self.check_blocksize_name('blake2b', 128, 64)
510 self.check_blocksize_name('blake2s', 64, 32)
511
512 def test_case_md5_0(self):
513 self.check(
514 'md5', b'', 'd41d8cd98f00b204e9800998ecf8427e',
515 usedforsecurity=False
516 )
517
518 def test_case_md5_1(self):
519 self.check(
520 'md5', b'abc', '900150983cd24fb0d6963f7d28e17f72',
521 usedforsecurity=False
522 )
523
524 def test_case_md5_2(self):
525 self.check(
526 'md5',
527 b'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
528 'd174ab98d277d9f5a5611c2c9f419d9f',
529 usedforsecurity=False
530 )
531
532 @unittest.skipIf(sys.maxsize < _4G + 5, 'test cannot run on 32-bit systems')
533 @bigmemtest(size=_4G + 5, memuse=1, dry_run=False)
534 def test_case_md5_huge(self, size):
535 self.check('md5', b'A'*size, 'c9af2dff37468ce5dfee8f2cfc0a9c6d')
536
537 @unittest.skipIf(sys.maxsize < _4G - 1, 'test cannot run on 32-bit systems')
538 @bigmemtest(size=_4G - 1, memuse=1, dry_run=False)
539 def test_case_md5_uintmax(self, size):
540 self.check('md5', b'A'*size, '28138d306ff1b8281f1a9067e1a1a2b3')
541
542 # use the three examples from Federal Information Processing Standards
543 # Publication 180-1, Secure Hash Standard, 1995 April 17
544 # http://www.itl.nist.gov/div897/pubs/fip180-1.htm
545
546 def test_case_sha1_0(self):
547 self.check('sha1', b"",
548 "da39a3ee5e6b4b0d3255bfef95601890afd80709")
549
550 def test_case_sha1_1(self):
551 self.check('sha1', b"abc",
552 "a9993e364706816aba3e25717850c26c9cd0d89d")
553
554 def test_case_sha1_2(self):
555 self.check('sha1',
556 b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
557 "84983e441c3bd26ebaae4aa1f95129e5e54670f1")
558
559 def test_case_sha1_3(self):
560 self.check('sha1', b"a" * 1000000,
561 "34aa973cd4c4daa4f61eeb2bdbad27316534016f")
562
563
564 # use the examples from Federal Information Processing Standards
565 # Publication 180-2, Secure Hash Standard, 2002 August 1
566 # http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf
567
568 def test_case_sha224_0(self):
569 self.check('sha224', b"",
570 "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f")
571
572 def test_case_sha224_1(self):
573 self.check('sha224', b"abc",
574 "23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7")
575
576 def test_case_sha224_2(self):
577 self.check('sha224',
578 b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
579 "75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525")
580
581 def test_case_sha224_3(self):
582 self.check('sha224', b"a" * 1000000,
583 "20794655980c91d8bbb4c1ea97618a4bf03f42581948b2ee4ee7ad67")
584
585
586 def test_case_sha256_0(self):
587 self.check('sha256', b"",
588 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
589
590 def test_case_sha256_1(self):
591 self.check('sha256', b"abc",
592 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
593
594 def test_case_sha256_2(self):
595 self.check('sha256',
596 b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
597 "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1")
598
599 def test_case_sha256_3(self):
600 self.check('sha256', b"a" * 1000000,
601 "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0")
602
603
604 def test_case_sha384_0(self):
605 self.check('sha384', b"",
606 "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da"+
607 "274edebfe76f65fbd51ad2f14898b95b")
608
609 def test_case_sha384_1(self):
610 self.check('sha384', b"abc",
611 "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed"+
612 "8086072ba1e7cc2358baeca134c825a7")
613
614 def test_case_sha384_2(self):
615 self.check('sha384',
616 b"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn"+
617 b"hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
618 "09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712"+
619 "fcc7c71a557e2db966c3e9fa91746039")
620
621 def test_case_sha384_3(self):
622 self.check('sha384', b"a" * 1000000,
623 "9d0e1809716474cb086e834e310a4a1ced149e9c00f248527972cec5704c2a5b"+
624 "07b8b3dc38ecc4ebae97ddd87f3d8985")
625
626
627 def test_case_sha512_0(self):
628 self.check('sha512', b"",
629 "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce"+
630 "47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e")
631
632 def test_case_sha512_1(self):
633 self.check('sha512', b"abc",
634 "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a"+
635 "2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f")
636
637 def test_case_sha512_2(self):
638 self.check('sha512',
639 b"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn"+
640 b"hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
641 "8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018"+
642 "501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909")
643
644 def test_case_sha512_3(self):
645 self.check('sha512', b"a" * 1000000,
646 "e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973eb"+
647 "de0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b")
648
649 def check_blake2(self, constructor, salt_size, person_size, key_size,
650 digest_size, max_offset):
651 self.assertEqual(constructor.SALT_SIZE, salt_size)
652 for i in range(salt_size + 1):
653 constructor(salt=b'a' * i)
654 salt = b'a' * (salt_size + 1)
655 self.assertRaises(ValueError, constructor, salt=salt)
656
657 self.assertEqual(constructor.PERSON_SIZE, person_size)
658 for i in range(person_size+1):
659 constructor(person=b'a' * i)
660 person = b'a' * (person_size + 1)
661 self.assertRaises(ValueError, constructor, person=person)
662
663 self.assertEqual(constructor.MAX_DIGEST_SIZE, digest_size)
664 for i in range(1, digest_size + 1):
665 constructor(digest_size=i)
666 self.assertRaises(ValueError, constructor, digest_size=-1)
667 self.assertRaises(ValueError, constructor, digest_size=0)
668 self.assertRaises(ValueError, constructor, digest_size=digest_size+1)
669
670 self.assertEqual(constructor.MAX_KEY_SIZE, key_size)
671 for i in range(key_size+1):
672 constructor(key=b'a' * i)
673 key = b'a' * (key_size + 1)
674 self.assertRaises(ValueError, constructor, key=key)
675 self.assertEqual(constructor().hexdigest(),
676 constructor(key=b'').hexdigest())
677
678 for i in range(0, 256):
679 constructor(fanout=i)
680 self.assertRaises(ValueError, constructor, fanout=-1)
681 self.assertRaises(ValueError, constructor, fanout=256)
682
683 for i in range(1, 256):
684 constructor(depth=i)
685 self.assertRaises(ValueError, constructor, depth=-1)
686 self.assertRaises(ValueError, constructor, depth=0)
687 self.assertRaises(ValueError, constructor, depth=256)
688
689 for i in range(0, 256):
690 constructor(node_depth=i)
691 self.assertRaises(ValueError, constructor, node_depth=-1)
692 self.assertRaises(ValueError, constructor, node_depth=256)
693
694 for i in range(0, digest_size + 1):
695 constructor(inner_size=i)
696 self.assertRaises(ValueError, constructor, inner_size=-1)
697 self.assertRaises(ValueError, constructor, inner_size=digest_size+1)
698
699 constructor(leaf_size=0)
700 constructor(leaf_size=(1<<32)-1)
701 self.assertRaises(ValueError, constructor, leaf_size=-1)
702 self.assertRaises(OverflowError, constructor, leaf_size=1<<32)
703
704 constructor(node_offset=0)
705 constructor(node_offset=max_offset)
706 self.assertRaises(ValueError, constructor, node_offset=-1)
707 self.assertRaises(OverflowError, constructor, node_offset=max_offset+1)
708
709 self.assertRaises(TypeError, constructor, data=b'')
710 self.assertRaises(TypeError, constructor, string=b'')
711 self.assertRaises(TypeError, constructor, '')
712
713 constructor(
714 b'',
715 key=b'',
716 salt=b'',
717 person=b'',
718 digest_size=17,
719 fanout=1,
720 depth=1,
721 leaf_size=256,
722 node_offset=512,
723 node_depth=1,
724 inner_size=7,
725 last_node=True
726 )
727
728 def blake2_rfc7693(self, constructor, md_len, in_len):
729 def selftest_seq(length, seed):
730 mask = (1<<32)-1
731 a = (0xDEAD4BAD * seed) & mask
732 b = 1
733 out = bytearray(length)
734 for i in range(length):
735 t = (a + b) & mask
736 a, b = b, t
737 out[i] = (t >> 24) & 0xFF
738 return out
739 outer = constructor(digest_size=32)
740 for outlen in md_len:
741 for inlen in in_len:
742 indata = selftest_seq(inlen, inlen)
743 key = selftest_seq(outlen, outlen)
744 unkeyed = constructor(indata, digest_size=outlen)
745 outer.update(unkeyed.digest())
746 keyed = constructor(indata, key=key, digest_size=outlen)
747 outer.update(keyed.digest())
748 return outer.hexdigest()
749
750 @requires_blake2
751 def test_blake2b(self):
752 self.check_blake2(hashlib.blake2b, 16, 16, 64, 64, (1<<64)-1)
753 b2b_md_len = [20, 32, 48, 64]
754 b2b_in_len = [0, 3, 128, 129, 255, 1024]
755 self.assertEqual(
756 self.blake2_rfc7693(hashlib.blake2b, b2b_md_len, b2b_in_len),
757 "c23a7800d98123bd10f506c61e29da5603d763b8bbad2e737f5e765a7bccd475")
758
759 @requires_blake2
760 def test_case_blake2b_0(self):
761 self.check('blake2b', b"",
762 "786a02f742015903c6c6fd852552d272912f4740e15847618a86e217f71f5419"+
763 "d25e1031afee585313896444934eb04b903a685b1448b755d56f701afe9be2ce")
764
765 @requires_blake2
766 def test_case_blake2b_1(self):
767 self.check('blake2b', b"abc",
768 "ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d1"+
769 "7d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923")
770
771 @requires_blake2
772 def test_case_blake2b_all_parameters(self):
773 # This checks that all the parameters work in general, and also that
774 # parameter byte order doesn't get confused on big endian platforms.
775 self.check('blake2b', b"foo",
776 "920568b0c5873b2f0ab67bedb6cf1b2b",
777 digest_size=16,
778 key=b"bar",
779 salt=b"baz",
780 person=b"bing",
781 fanout=2,
782 depth=3,
783 leaf_size=4,
784 node_offset=5,
785 node_depth=6,
786 inner_size=7,
787 last_node=True)
788
789 @requires_blake2
790 def test_blake2b_vectors(self):
791 for msg, key, md in read_vectors('blake2b'):
792 key = bytes.fromhex(key)
793 self.check('blake2b', msg, md, key=key)
794
795 @requires_blake2
796 def test_blake2s(self):
797 self.check_blake2(hashlib.blake2s, 8, 8, 32, 32, (1<<48)-1)
798 b2s_md_len = [16, 20, 28, 32]
799 b2s_in_len = [0, 3, 64, 65, 255, 1024]
800 self.assertEqual(
801 self.blake2_rfc7693(hashlib.blake2s, b2s_md_len, b2s_in_len),
802 "6a411f08ce25adcdfb02aba641451cec53c598b24f4fc787fbdc88797f4c1dfe")
803
804 @requires_blake2
805 def test_case_blake2s_0(self):
806 self.check('blake2s', b"",
807 "69217a3079908094e11121d042354a7c1f55b6482ca1a51e1b250dfd1ed0eef9")
808
809 @requires_blake2
810 def test_case_blake2s_1(self):
811 self.check('blake2s', b"abc",
812 "508c5e8c327c14e2e1a72ba34eeb452f37458b209ed63a294d999b4c86675982")
813
814 @requires_blake2
815 def test_case_blake2s_all_parameters(self):
816 # This checks that all the parameters work in general, and also that
817 # parameter byte order doesn't get confused on big endian platforms.
818 self.check('blake2s', b"foo",
819 "bf2a8f7fe3c555012a6f8046e646bc75",
820 digest_size=16,
821 key=b"bar",
822 salt=b"baz",
823 person=b"bing",
824 fanout=2,
825 depth=3,
826 leaf_size=4,
827 node_offset=5,
828 node_depth=6,
829 inner_size=7,
830 last_node=True)
831
832 @requires_blake2
833 def test_blake2s_vectors(self):
834 for msg, key, md in read_vectors('blake2s'):
835 key = bytes.fromhex(key)
836 self.check('blake2s', msg, md, key=key)
837
838 @requires_sha3
839 def test_case_sha3_224_0(self):
840 self.check('sha3_224', b"",
841 "6b4e03423667dbb73b6e15454f0eb1abd4597f9a1b078e3f5b5a6bc7")
842
843 @requires_sha3
844 def test_case_sha3_224_vector(self):
845 for msg, md in read_vectors('sha3_224'):
846 self.check('sha3_224', msg, md)
847
848 @requires_sha3
849 def test_case_sha3_256_0(self):
850 self.check('sha3_256', b"",
851 "a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a")
852
853 @requires_sha3
854 def test_case_sha3_256_vector(self):
855 for msg, md in read_vectors('sha3_256'):
856 self.check('sha3_256', msg, md)
857
858 @requires_sha3
859 def test_case_sha3_384_0(self):
860 self.check('sha3_384', b"",
861 "0c63a75b845e4f7d01107d852e4c2485c51a50aaaa94fc61995e71bbee983a2a"+
862 "c3713831264adb47fb6bd1e058d5f004")
863
864 @requires_sha3
865 def test_case_sha3_384_vector(self):
866 for msg, md in read_vectors('sha3_384'):
867 self.check('sha3_384', msg, md)
868
869 @requires_sha3
870 def test_case_sha3_512_0(self):
871 self.check('sha3_512', b"",
872 "a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a6"+
873 "15b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26")
874
875 @requires_sha3
876 def test_case_sha3_512_vector(self):
877 for msg, md in read_vectors('sha3_512'):
878 self.check('sha3_512', msg, md)
879
880 def test_case_shake_128_0(self):
881 self.check('shake_128', b"",
882 "7f9c2ba4e88f827d616045507605853ed73b8093f6efbc88eb1a6eacfa66ef26",
883 True)
884 self.check('shake_128', b"", "7f9c", True)
885
886 def test_case_shake128_vector(self):
887 for msg, md in read_vectors('shake_128'):
888 self.check('shake_128', msg, md, True)
889
890 def test_case_shake_256_0(self):
891 self.check('shake_256', b"",
892 "46b9dd2b0ba88d13233b3feb743eeb243fcd52ea62b81b82b50c27646ed5762f",
893 True)
894 self.check('shake_256', b"", "46b9", True)
895
896 def test_case_shake256_vector(self):
897 for msg, md in read_vectors('shake_256'):
898 self.check('shake_256', msg, md, True)
899
900 def test_gil(self):
901 # Check things work fine with an input larger than the size required
902 # for multithreaded operation (which is hardwired to 2048).
903 gil_minsize = 2048
904
905 for cons in self.hash_constructors:
906 m = cons(usedforsecurity=False)
907 m.update(b'1')
908 m.update(b'#' * gil_minsize)
909 m.update(b'1')
910
911 m = cons(b'x' * gil_minsize, usedforsecurity=False)
912 m.update(b'1')
913
914 m = hashlib.sha256()
915 m.update(b'1')
916 m.update(b'#' * gil_minsize)
917 m.update(b'1')
918 self.assertEqual(
919 m.hexdigest(),
920 '1cfceca95989f51f658e3f3ffe7f1cd43726c9e088c13ee10b46f57cef135b94'
921 )
922
923 m = hashlib.sha256(b'1' + b'#' * gil_minsize + b'1')
924 self.assertEqual(
925 m.hexdigest(),
926 '1cfceca95989f51f658e3f3ffe7f1cd43726c9e088c13ee10b46f57cef135b94'
927 )
928
929 @threading_helper.reap_threads
930 @threading_helper.requires_working_threading()
931 def test_threaded_hashing(self):
932 # Updating the same hash object from several threads at once
933 # using data chunk sizes containing the same byte sequences.
934 #
935 # If the internal locks are working to prevent multiple
936 # updates on the same object from running at once, the resulting
937 # hash will be the same as doing it single threaded upfront.
938 hasher = hashlib.sha1()
939 num_threads = 5
940 smallest_data = b'swineflu'
941 data = smallest_data * 200000
942 expected_hash = hashlib.sha1(data*num_threads).hexdigest()
943
944 def hash_in_chunks(chunk_size):
945 index = 0
946 while index < len(data):
947 hasher.update(data[index:index + chunk_size])
948 index += chunk_size
949
950 threads = []
951 for threadnum in range(num_threads):
952 chunk_size = len(data) // (10 ** threadnum)
953 self.assertGreater(chunk_size, 0)
954 self.assertEqual(chunk_size % len(smallest_data), 0)
955 thread = threading.Thread(target=hash_in_chunks,
956 args=(chunk_size,))
957 threads.append(thread)
958
959 for thread in threads:
960 thread.start()
961 for thread in threads:
962 thread.join()
963
964 self.assertEqual(expected_hash, hasher.hexdigest())
965
966 def test_get_fips_mode(self):
967 fips_mode = self.is_fips_mode
968 if fips_mode is not None:
969 self.assertIsInstance(fips_mode, int)
970
971 @support.cpython_only
972 def test_disallow_instantiation(self):
973 for algorithm, constructors in self.constructors_to_test.items():
974 if algorithm.startswith(("sha3_", "shake", "blake")):
975 # _sha3 and _blake types can be instantiated
976 continue
977 # all other types have DISALLOW_INSTANTIATION
978 for constructor in constructors:
979 # In FIPS mode some algorithms are not available raising ValueError
980 try:
981 h = constructor()
982 except ValueError:
983 continue
984 with self.subTest(constructor=constructor):
985 support.check_disallow_instantiation(self, type(h))
986
987 @unittest.skipUnless(HASH is not None, 'need _hashlib')
988 def test_hash_disallow_instantiation(self):
989 # internal types like _hashlib.HASH are not constructable
990 support.check_disallow_instantiation(self, HASH)
991 support.check_disallow_instantiation(self, HASHXOF)
992
993 def test_readonly_types(self):
994 for algorithm, constructors in self.constructors_to_test.items():
995 # all other types have DISALLOW_INSTANTIATION
996 for constructor in constructors:
997 # In FIPS mode some algorithms are not available raising ValueError
998 try:
999 hash_type = type(constructor())
1000 except ValueError:
1001 continue
1002 with self.subTest(hash_type=hash_type):
1003 with self.assertRaisesRegex(TypeError, "immutable type"):
1004 hash_type.value = False
1005
1006
1007 class ESC[4;38;5;81mKDFTests(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
1008
1009 pbkdf2_test_vectors = [
1010 (b'password', b'salt', 1, None),
1011 (b'password', b'salt', 2, None),
1012 (b'password', b'salt', 4096, None),
1013 # too slow, it takes over a minute on a fast CPU.
1014 #(b'password', b'salt', 16777216, None),
1015 (b'passwordPASSWORDpassword', b'saltSALTsaltSALTsaltSALTsaltSALTsalt',
1016 4096, -1),
1017 (b'pass\0word', b'sa\0lt', 4096, 16),
1018 ]
1019
1020 scrypt_test_vectors = [
1021 (b'', b'', 16, 1, 1, unhexlify('77d6576238657b203b19ca42c18a0497f16b4844e3074ae8dfdffa3fede21442fcd0069ded0948f8326a753a0fc81f17e8d3e0fb2e0d3628cf35e20c38d18906')),
1022 (b'password', b'NaCl', 1024, 8, 16, unhexlify('fdbabe1c9d3472007856e7190d01e9fe7c6ad7cbc8237830e77376634b3731622eaf30d92e22a3886ff109279d9830dac727afb94a83ee6d8360cbdfa2cc0640')),
1023 (b'pleaseletmein', b'SodiumChloride', 16384, 8, 1, unhexlify('7023bdcb3afd7348461c06cd81fd38ebfda8fbba904f8e3ea9b543f6545da1f2d5432955613f0fcf62d49705242a9af9e61e85dc0d651e40dfcf017b45575887')),
1024 ]
1025
1026 pbkdf2_results = {
1027 "sha1": [
1028 # official test vectors from RFC 6070
1029 (bytes.fromhex('0c60c80f961f0e71f3a9b524af6012062fe037a6'), None),
1030 (bytes.fromhex('ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957'), None),
1031 (bytes.fromhex('4b007901b765489abead49d926f721d065a429c1'), None),
1032 #(bytes.fromhex('eefe3d61cd4da4e4e9945b3d6ba2158c2634e984'), None),
1033 (bytes.fromhex('3d2eec4fe41c849b80c8d83662c0e44a8b291a964c'
1034 'f2f07038'), 25),
1035 (bytes.fromhex('56fa6aa75548099dcc37d7f03425e0c3'), None),],
1036 "sha256": [
1037 (bytes.fromhex('120fb6cffcf8b32c43e7225256c4f837'
1038 'a86548c92ccc35480805987cb70be17b'), None),
1039 (bytes.fromhex('ae4d0c95af6b46d32d0adff928f06dd0'
1040 '2a303f8ef3c251dfd6e2d85a95474c43'), None),
1041 (bytes.fromhex('c5e478d59288c841aa530db6845c4c8d'
1042 '962893a001ce4e11a4963873aa98134a'), None),
1043 #(bytes.fromhex('cf81c66fe8cfc04d1f31ecb65dab4089'
1044 # 'f7f179e89b3b0bcb17ad10e3ac6eba46'), None),
1045 (bytes.fromhex('348c89dbcbd32b2f32d814b8116e84cf2b17'
1046 '347ebc1800181c4e2a1fb8dd53e1c635518c7dac47e9'), 40),
1047 (bytes.fromhex('89b69d0516f829893c696226650a8687'), None),],
1048 "sha512": [
1049 (bytes.fromhex('867f70cf1ade02cff3752599a3a53dc4af34c7a669815ae5'
1050 'd513554e1c8cf252c02d470a285a0501bad999bfe943c08f'
1051 '050235d7d68b1da55e63f73b60a57fce'), None),
1052 (bytes.fromhex('e1d9c16aa681708a45f5c7c4e215ceb66e011a2e9f004071'
1053 '3f18aefdb866d53cf76cab2868a39b9f7840edce4fef5a82'
1054 'be67335c77a6068e04112754f27ccf4e'), None),
1055 (bytes.fromhex('d197b1b33db0143e018b12f3d1d1479e6cdebdcc97c5c0f8'
1056 '7f6902e072f457b5143f30602641b3d55cd335988cb36b84'
1057 '376060ecd532e039b742a239434af2d5'), None),
1058 (bytes.fromhex('8c0511f4c6e597c6ac6315d8f0362e225f3c501495ba23b8'
1059 '68c005174dc4ee71115b59f9e60cd9532fa33e0f75aefe30'
1060 '225c583a186cd82bd4daea9724a3d3b8'), 64),
1061 (bytes.fromhex('9d9e9c4cd21fe4be24d5b8244c759665'), None),],
1062 }
1063
1064 def _test_pbkdf2_hmac(self, pbkdf2, supported):
1065 for digest_name, results in self.pbkdf2_results.items():
1066 if digest_name not in supported:
1067 continue
1068 for i, vector in enumerate(self.pbkdf2_test_vectors):
1069 password, salt, rounds, dklen = vector
1070 expected, overwrite_dklen = results[i]
1071 if overwrite_dklen:
1072 dklen = overwrite_dklen
1073 out = pbkdf2(digest_name, password, salt, rounds, dklen)
1074 self.assertEqual(out, expected,
1075 (digest_name, password, salt, rounds, dklen))
1076 out = pbkdf2(digest_name, memoryview(password),
1077 memoryview(salt), rounds, dklen)
1078 self.assertEqual(out, expected)
1079 out = pbkdf2(digest_name, bytearray(password),
1080 bytearray(salt), rounds, dklen)
1081 self.assertEqual(out, expected)
1082 if dklen is None:
1083 out = pbkdf2(digest_name, password, salt, rounds)
1084 self.assertEqual(out, expected,
1085 (digest_name, password, salt, rounds))
1086
1087 with self.assertRaisesRegex(ValueError, '.*unsupported.*'):
1088 pbkdf2('unknown', b'pass', b'salt', 1)
1089
1090 if 'sha1' in supported:
1091 self.assertRaises(
1092 TypeError, pbkdf2, b'sha1', b'pass', b'salt', 1
1093 )
1094 self.assertRaises(
1095 TypeError, pbkdf2, 'sha1', 'pass', 'salt', 1
1096 )
1097 self.assertRaises(
1098 ValueError, pbkdf2, 'sha1', b'pass', b'salt', 0
1099 )
1100 self.assertRaises(
1101 ValueError, pbkdf2, 'sha1', b'pass', b'salt', -1
1102 )
1103 self.assertRaises(
1104 ValueError, pbkdf2, 'sha1', b'pass', b'salt', 1, 0
1105 )
1106 self.assertRaises(
1107 ValueError, pbkdf2, 'sha1', b'pass', b'salt', 1, -1
1108 )
1109 out = pbkdf2(hash_name='sha1', password=b'password', salt=b'salt',
1110 iterations=1, dklen=None)
1111 self.assertEqual(out, self.pbkdf2_results['sha1'][0][0])
1112
1113 @unittest.skipIf(openssl_hashlib is None, "requires OpenSSL bindings")
1114 def test_pbkdf2_hmac_c(self):
1115 self._test_pbkdf2_hmac(openssl_hashlib.pbkdf2_hmac, openssl_md_meth_names)
1116
1117 @unittest.skipUnless(hasattr(hashlib, 'scrypt'),
1118 ' test requires OpenSSL > 1.1')
1119 @unittest.skipIf(get_fips_mode(), reason="scrypt is blocked in FIPS mode")
1120 def test_scrypt(self):
1121 for password, salt, n, r, p, expected in self.scrypt_test_vectors:
1122 result = hashlib.scrypt(password, salt=salt, n=n, r=r, p=p)
1123 self.assertEqual(result, expected)
1124
1125 # this values should work
1126 hashlib.scrypt(b'password', salt=b'salt', n=2, r=8, p=1)
1127 # password and salt must be bytes-like
1128 with self.assertRaises(TypeError):
1129 hashlib.scrypt('password', salt=b'salt', n=2, r=8, p=1)
1130 with self.assertRaises(TypeError):
1131 hashlib.scrypt(b'password', salt='salt', n=2, r=8, p=1)
1132 # require keyword args
1133 with self.assertRaises(TypeError):
1134 hashlib.scrypt(b'password')
1135 with self.assertRaises(TypeError):
1136 hashlib.scrypt(b'password', b'salt')
1137 with self.assertRaises(TypeError):
1138 hashlib.scrypt(b'password', 2, 8, 1, salt=b'salt')
1139 for n in [-1, 0, 1, None]:
1140 with self.assertRaises((ValueError, OverflowError, TypeError)):
1141 hashlib.scrypt(b'password', salt=b'salt', n=n, r=8, p=1)
1142 for r in [-1, 0, None]:
1143 with self.assertRaises((ValueError, OverflowError, TypeError)):
1144 hashlib.scrypt(b'password', salt=b'salt', n=2, r=r, p=1)
1145 for p in [-1, 0, None]:
1146 with self.assertRaises((ValueError, OverflowError, TypeError)):
1147 hashlib.scrypt(b'password', salt=b'salt', n=2, r=8, p=p)
1148 for maxmem in [-1, None]:
1149 with self.assertRaises((ValueError, OverflowError, TypeError)):
1150 hashlib.scrypt(b'password', salt=b'salt', n=2, r=8, p=1,
1151 maxmem=maxmem)
1152 for dklen in [-1, None]:
1153 with self.assertRaises((ValueError, OverflowError, TypeError)):
1154 hashlib.scrypt(b'password', salt=b'salt', n=2, r=8, p=1,
1155 dklen=dklen)
1156
1157 def test_normalized_name(self):
1158 self.assertNotIn("blake2b512", hashlib.algorithms_available)
1159 self.assertNotIn("sha3-512", hashlib.algorithms_available)
1160
1161 def test_file_digest(self):
1162 data = b'a' * 65536
1163 d1 = hashlib.sha256()
1164 self.addCleanup(os.unlink, os_helper.TESTFN)
1165 with open(os_helper.TESTFN, "wb") as f:
1166 for _ in range(10):
1167 d1.update(data)
1168 f.write(data)
1169
1170 with open(os_helper.TESTFN, "rb") as f:
1171 d2 = hashlib.file_digest(f, hashlib.sha256)
1172
1173 self.assertEqual(d1.hexdigest(), d2.hexdigest())
1174 self.assertEqual(d1.name, d2.name)
1175 self.assertIs(type(d1), type(d2))
1176
1177 with self.assertRaises(ValueError):
1178 hashlib.file_digest(None, "sha256")
1179
1180 with self.assertRaises(ValueError):
1181 with open(os_helper.TESTFN, "r") as f:
1182 hashlib.file_digest(f, "sha256")
1183
1184 with self.assertRaises(ValueError):
1185 with open(os_helper.TESTFN, "wb") as f:
1186 hashlib.file_digest(f, "sha256")
1187
1188
1189 if __name__ == "__main__":
1190 unittest.main()