Debian Codegraph @

Lib/test/test_hashlib.py

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