ยปCore Development>Code coverage>Lib/test/test_hashlib.py

Python code coverage for Lib/test/test_hashlib.py

#countcontent
1n/a# Test hashlib module
2n/a#
3n/a# $Id$
4n/a#
5n/a# Copyright (C) 2005-2010 Gregory P. Smith (greg@krypto.org)
6n/a# Licensed to PSF under a Contributor Agreement.
7n/a#
8n/a
9n/aimport array
10n/afrom binascii import unhexlify
11n/aimport hashlib
12n/aimport itertools
13n/aimport os
14n/aimport sys
15n/atry:
16n/a import threading
17n/aexcept ImportError:
18n/a threading = None
19n/aimport unittest
20n/aimport warnings
21n/afrom test import support
22n/afrom test.support import _4G, bigmemtest, import_fresh_module
23n/afrom http.client import HTTPException
24n/a
25n/a# Were we compiled --with-pydebug or with #define Py_DEBUG?
26n/aCOMPILED_WITH_PYDEBUG = hasattr(sys, 'gettotalrefcount')
27n/a
28n/ac_hashlib = import_fresh_module('hashlib', fresh=['_hashlib'])
29n/apy_hashlib = import_fresh_module('hashlib', blocked=['_hashlib'])
30n/a
31n/atry:
32n/a import _blake2
33n/aexcept ImportError:
34n/a _blake2 = None
35n/a
36n/arequires_blake2 = unittest.skipUnless(_blake2, 'requires _blake2')
37n/a
38n/atry:
39n/a import _sha3
40n/aexcept ImportError:
41n/a _sha3 = None
42n/a
43n/arequires_sha3 = unittest.skipUnless(_sha3, 'requires _sha3')
44n/a
45n/a
46n/adef hexstr(s):
47n/a assert isinstance(s, bytes), repr(s)
48n/a h = "0123456789abcdef"
49n/a r = ''
50n/a for i in s:
51n/a r += h[(i >> 4) & 0xF] + h[i & 0xF]
52n/a return r
53n/a
54n/a
55n/aURL = "http://www.pythontest.net/hashlib/{}.txt"
56n/a
57n/adef read_vectors(hash_name):
58n/a url = URL.format(hash_name)
59n/a try:
60n/a testdata = support.open_urlresource(url)
61n/a except (OSError, HTTPException):
62n/a raise unittest.SkipTest("Could not retrieve {}".format(url))
63n/a with testdata:
64n/a for line in testdata:
65n/a line = line.strip()
66n/a if line.startswith('#') or not line:
67n/a continue
68n/a parts = line.split(',')
69n/a parts[0] = bytes.fromhex(parts[0])
70n/a yield parts
71n/a
72n/a
73n/aclass HashLibTestCase(unittest.TestCase):
74n/a supported_hash_names = ( 'md5', 'MD5', 'sha1', 'SHA1',
75n/a 'sha224', 'SHA224', 'sha256', 'SHA256',
76n/a 'sha384', 'SHA384', 'sha512', 'SHA512',
77n/a 'blake2b', 'blake2s',
78n/a 'sha3_224', 'sha3_256', 'sha3_384', 'sha3_512',
79n/a 'shake_128', 'shake_256')
80n/a
81n/a shakes = {'shake_128', 'shake_256'}
82n/a
83n/a # Issue #14693: fallback modules are always compiled under POSIX
84n/a _warn_on_extension_import = os.name == 'posix' or COMPILED_WITH_PYDEBUG
85n/a
86n/a def _conditional_import_module(self, module_name):
87n/a """Import a module and return a reference to it or None on failure."""
88n/a try:
89n/a exec('import '+module_name)
90n/a except ImportError as error:
91n/a if self._warn_on_extension_import:
92n/a warnings.warn('Did a C extension fail to compile? %s' % error)
93n/a return locals().get(module_name)
94n/a
95n/a def __init__(self, *args, **kwargs):
96n/a algorithms = set()
97n/a for algorithm in self.supported_hash_names:
98n/a algorithms.add(algorithm.lower())
99n/a
100n/a _blake2 = self._conditional_import_module('_blake2')
101n/a if _blake2:
102n/a algorithms.update({'blake2b', 'blake2s'})
103n/a
104n/a self.constructors_to_test = {}
105n/a for algorithm in algorithms:
106n/a self.constructors_to_test[algorithm] = set()
107n/a
108n/a # For each algorithm, test the direct constructor and the use
109n/a # of hashlib.new given the algorithm name.
110n/a for algorithm, constructors in self.constructors_to_test.items():
111n/a constructors.add(getattr(hashlib, algorithm))
112n/a def _test_algorithm_via_hashlib_new(data=None, _alg=algorithm, **kwargs):
113n/a if data is None:
114n/a return hashlib.new(_alg, **kwargs)
115n/a return hashlib.new(_alg, data, **kwargs)
116n/a constructors.add(_test_algorithm_via_hashlib_new)
117n/a
118n/a _hashlib = self._conditional_import_module('_hashlib')
119n/a if _hashlib:
120n/a # These two algorithms should always be present when this module
121n/a # is compiled. If not, something was compiled wrong.
122n/a self.assertTrue(hasattr(_hashlib, 'openssl_md5'))
123n/a self.assertTrue(hasattr(_hashlib, 'openssl_sha1'))
124n/a for algorithm, constructors in self.constructors_to_test.items():
125n/a constructor = getattr(_hashlib, 'openssl_'+algorithm, None)
126n/a if constructor:
127n/a constructors.add(constructor)
128n/a
129n/a def add_builtin_constructor(name):
130n/a constructor = getattr(hashlib, "__get_builtin_constructor")(name)
131n/a self.constructors_to_test[name].add(constructor)
132n/a
133n/a _md5 = self._conditional_import_module('_md5')
134n/a if _md5:
135n/a add_builtin_constructor('md5')
136n/a _sha1 = self._conditional_import_module('_sha1')
137n/a if _sha1:
138n/a add_builtin_constructor('sha1')
139n/a _sha256 = self._conditional_import_module('_sha256')
140n/a if _sha256:
141n/a add_builtin_constructor('sha224')
142n/a add_builtin_constructor('sha256')
143n/a _sha512 = self._conditional_import_module('_sha512')
144n/a if _sha512:
145n/a add_builtin_constructor('sha384')
146n/a add_builtin_constructor('sha512')
147n/a if _blake2:
148n/a add_builtin_constructor('blake2s')
149n/a add_builtin_constructor('blake2b')
150n/a
151n/a _sha3 = self._conditional_import_module('_sha3')
152n/a if _sha3:
153n/a add_builtin_constructor('sha3_224')
154n/a add_builtin_constructor('sha3_256')
155n/a add_builtin_constructor('sha3_384')
156n/a add_builtin_constructor('sha3_512')
157n/a add_builtin_constructor('shake_128')
158n/a add_builtin_constructor('shake_256')
159n/a
160n/a super(HashLibTestCase, self).__init__(*args, **kwargs)
161n/a
162n/a @property
163n/a def hash_constructors(self):
164n/a constructors = self.constructors_to_test.values()
165n/a return itertools.chain.from_iterable(constructors)
166n/a
167n/a def test_hash_array(self):
168n/a a = array.array("b", range(10))
169n/a for cons in self.hash_constructors:
170n/a c = cons(a)
171n/a if c.name in self.shakes:
172n/a c.hexdigest(16)
173n/a else:
174n/a c.hexdigest()
175n/a
176n/a def test_algorithms_guaranteed(self):
177n/a self.assertEqual(hashlib.algorithms_guaranteed,
178n/a set(_algo for _algo in self.supported_hash_names
179n/a if _algo.islower()))
180n/a
181n/a def test_algorithms_available(self):
182n/a self.assertTrue(set(hashlib.algorithms_guaranteed).
183n/a issubset(hashlib.algorithms_available))
184n/a
185n/a def test_unknown_hash(self):
186n/a self.assertRaises(ValueError, hashlib.new, 'spam spam spam spam spam')
187n/a self.assertRaises(TypeError, hashlib.new, 1)
188n/a
189n/a def test_get_builtin_constructor(self):
190n/a get_builtin_constructor = getattr(hashlib,
191n/a '__get_builtin_constructor')
192n/a builtin_constructor_cache = getattr(hashlib,
193n/a '__builtin_constructor_cache')
194n/a self.assertRaises(ValueError, get_builtin_constructor, 'test')
195n/a try:
196n/a import _md5
197n/a except ImportError:
198n/a pass
199n/a # This forces an ImportError for "import _md5" statements
200n/a sys.modules['_md5'] = None
201n/a # clear the cache
202n/a builtin_constructor_cache.clear()
203n/a try:
204n/a self.assertRaises(ValueError, get_builtin_constructor, 'md5')
205n/a finally:
206n/a if '_md5' in locals():
207n/a sys.modules['_md5'] = _md5
208n/a else:
209n/a del sys.modules['_md5']
210n/a self.assertRaises(TypeError, get_builtin_constructor, 3)
211n/a constructor = get_builtin_constructor('md5')
212n/a self.assertIs(constructor, _md5.md5)
213n/a self.assertEqual(sorted(builtin_constructor_cache), ['MD5', 'md5'])
214n/a
215n/a def test_hexdigest(self):
216n/a for cons in self.hash_constructors:
217n/a h = cons()
218n/a if h.name in self.shakes:
219n/a self.assertIsInstance(h.digest(16), bytes)
220n/a self.assertEqual(hexstr(h.digest(16)), h.hexdigest(16))
221n/a else:
222n/a self.assertIsInstance(h.digest(), bytes)
223n/a self.assertEqual(hexstr(h.digest()), h.hexdigest())
224n/a
225n/a def test_name_attribute(self):
226n/a for cons in self.hash_constructors:
227n/a h = cons()
228n/a self.assertIsInstance(h.name, str)
229n/a if h.name in self.supported_hash_names:
230n/a self.assertIn(h.name, self.supported_hash_names)
231n/a else:
232n/a self.assertNotIn(h.name, self.supported_hash_names)
233n/a self.assertEqual(h.name, hashlib.new(h.name).name)
234n/a
235n/a def test_large_update(self):
236n/a aas = b'a' * 128
237n/a bees = b'b' * 127
238n/a cees = b'c' * 126
239n/a dees = b'd' * 2048 # HASHLIB_GIL_MINSIZE
240n/a
241n/a for cons in self.hash_constructors:
242n/a m1 = cons()
243n/a m1.update(aas)
244n/a m1.update(bees)
245n/a m1.update(cees)
246n/a m1.update(dees)
247n/a if m1.name in self.shakes:
248n/a args = (16,)
249n/a else:
250n/a args = ()
251n/a
252n/a m2 = cons()
253n/a m2.update(aas + bees + cees + dees)
254n/a self.assertEqual(m1.digest(*args), m2.digest(*args))
255n/a
256n/a m3 = cons(aas + bees + cees + dees)
257n/a self.assertEqual(m1.digest(*args), m3.digest(*args))
258n/a
259n/a # verify copy() doesn't touch original
260n/a m4 = cons(aas + bees + cees)
261n/a m4_digest = m4.digest(*args)
262n/a m4_copy = m4.copy()
263n/a m4_copy.update(dees)
264n/a self.assertEqual(m1.digest(*args), m4_copy.digest(*args))
265n/a self.assertEqual(m4.digest(*args), m4_digest)
266n/a
267n/a def check(self, name, data, hexdigest, shake=False, **kwargs):
268n/a length = len(hexdigest)//2
269n/a hexdigest = hexdigest.lower()
270n/a constructors = self.constructors_to_test[name]
271n/a # 2 is for hashlib.name(...) and hashlib.new(name, ...)
272n/a self.assertGreaterEqual(len(constructors), 2)
273n/a for hash_object_constructor in constructors:
274n/a m = hash_object_constructor(data, **kwargs)
275n/a computed = m.hexdigest() if not shake else m.hexdigest(length)
276n/a self.assertEqual(
277n/a computed, hexdigest,
278n/a "Hash algorithm %s constructed using %s returned hexdigest"
279n/a " %r for %d byte input data that should have hashed to %r."
280n/a % (name, hash_object_constructor,
281n/a computed, len(data), hexdigest))
282n/a computed = m.digest() if not shake else m.digest(length)
283n/a digest = bytes.fromhex(hexdigest)
284n/a self.assertEqual(computed, digest)
285n/a if not shake:
286n/a self.assertEqual(len(digest), m.digest_size)
287n/a
288n/a def check_no_unicode(self, algorithm_name):
289n/a # Unicode objects are not allowed as input.
290n/a constructors = self.constructors_to_test[algorithm_name]
291n/a for hash_object_constructor in constructors:
292n/a self.assertRaises(TypeError, hash_object_constructor, 'spam')
293n/a
294n/a def test_no_unicode(self):
295n/a self.check_no_unicode('md5')
296n/a self.check_no_unicode('sha1')
297n/a self.check_no_unicode('sha224')
298n/a self.check_no_unicode('sha256')
299n/a self.check_no_unicode('sha384')
300n/a self.check_no_unicode('sha512')
301n/a
302n/a @requires_blake2
303n/a def test_no_unicode_blake2(self):
304n/a self.check_no_unicode('blake2b')
305n/a self.check_no_unicode('blake2s')
306n/a
307n/a @requires_sha3
308n/a def test_no_unicode_sha3(self):
309n/a self.check_no_unicode('sha3_224')
310n/a self.check_no_unicode('sha3_256')
311n/a self.check_no_unicode('sha3_384')
312n/a self.check_no_unicode('sha3_512')
313n/a self.check_no_unicode('shake_128')
314n/a self.check_no_unicode('shake_256')
315n/a
316n/a def check_blocksize_name(self, name, block_size=0, digest_size=0,
317n/a digest_length=None):
318n/a constructors = self.constructors_to_test[name]
319n/a for hash_object_constructor in constructors:
320n/a m = hash_object_constructor()
321n/a self.assertEqual(m.block_size, block_size)
322n/a self.assertEqual(m.digest_size, digest_size)
323n/a if digest_length:
324n/a self.assertEqual(len(m.digest(digest_length)),
325n/a digest_length)
326n/a self.assertEqual(len(m.hexdigest(digest_length)),
327n/a 2*digest_length)
328n/a else:
329n/a self.assertEqual(len(m.digest()), digest_size)
330n/a self.assertEqual(len(m.hexdigest()), 2*digest_size)
331n/a self.assertEqual(m.name, name)
332n/a # split for sha3_512 / _sha3.sha3 object
333n/a self.assertIn(name.split("_")[0], repr(m))
334n/a
335n/a def test_blocksize_name(self):
336n/a self.check_blocksize_name('md5', 64, 16)
337n/a self.check_blocksize_name('sha1', 64, 20)
338n/a self.check_blocksize_name('sha224', 64, 28)
339n/a self.check_blocksize_name('sha256', 64, 32)
340n/a self.check_blocksize_name('sha384', 128, 48)
341n/a self.check_blocksize_name('sha512', 128, 64)
342n/a
343n/a @requires_sha3
344n/a def test_blocksize_name_sha3(self):
345n/a self.check_blocksize_name('sha3_224', 144, 28)
346n/a self.check_blocksize_name('sha3_256', 136, 32)
347n/a self.check_blocksize_name('sha3_384', 104, 48)
348n/a self.check_blocksize_name('sha3_512', 72, 64)
349n/a self.check_blocksize_name('shake_128', 168, 0, 32)
350n/a self.check_blocksize_name('shake_256', 136, 0, 64)
351n/a
352n/a def check_sha3(self, name, capacity, rate, suffix):
353n/a constructors = self.constructors_to_test[name]
354n/a for hash_object_constructor in constructors:
355n/a m = hash_object_constructor()
356n/a self.assertEqual(capacity + rate, 1600)
357n/a self.assertEqual(m._capacity_bits, capacity)
358n/a self.assertEqual(m._rate_bits, rate)
359n/a self.assertEqual(m._suffix, suffix)
360n/a
361n/a @requires_sha3
362n/a def test_extra_sha3(self):
363n/a self.check_sha3('sha3_224', 448, 1152, b'\x06')
364n/a self.check_sha3('sha3_256', 512, 1088, b'\x06')
365n/a self.check_sha3('sha3_384', 768, 832, b'\x06')
366n/a self.check_sha3('sha3_512', 1024, 576, b'\x06')
367n/a self.check_sha3('shake_128', 256, 1344, b'\x1f')
368n/a self.check_sha3('shake_256', 512, 1088, b'\x1f')
369n/a
370n/a @requires_blake2
371n/a def test_blocksize_name_blake2(self):
372n/a self.check_blocksize_name('blake2b', 128, 64)
373n/a self.check_blocksize_name('blake2s', 64, 32)
374n/a
375n/a def test_case_md5_0(self):
376n/a self.check('md5', b'', 'd41d8cd98f00b204e9800998ecf8427e')
377n/a
378n/a def test_case_md5_1(self):
379n/a self.check('md5', b'abc', '900150983cd24fb0d6963f7d28e17f72')
380n/a
381n/a def test_case_md5_2(self):
382n/a self.check('md5',
383n/a b'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
384n/a 'd174ab98d277d9f5a5611c2c9f419d9f')
385n/a
386n/a @unittest.skipIf(sys.maxsize < _4G + 5, 'test cannot run on 32-bit systems')
387n/a @bigmemtest(size=_4G + 5, memuse=1, dry_run=False)
388n/a def test_case_md5_huge(self, size):
389n/a self.check('md5', b'A'*size, 'c9af2dff37468ce5dfee8f2cfc0a9c6d')
390n/a
391n/a @unittest.skipIf(sys.maxsize < _4G - 1, 'test cannot run on 32-bit systems')
392n/a @bigmemtest(size=_4G - 1, memuse=1, dry_run=False)
393n/a def test_case_md5_uintmax(self, size):
394n/a self.check('md5', b'A'*size, '28138d306ff1b8281f1a9067e1a1a2b3')
395n/a
396n/a # use the three examples from Federal Information Processing Standards
397n/a # Publication 180-1, Secure Hash Standard, 1995 April 17
398n/a # http://www.itl.nist.gov/div897/pubs/fip180-1.htm
399n/a
400n/a def test_case_sha1_0(self):
401n/a self.check('sha1', b"",
402n/a "da39a3ee5e6b4b0d3255bfef95601890afd80709")
403n/a
404n/a def test_case_sha1_1(self):
405n/a self.check('sha1', b"abc",
406n/a "a9993e364706816aba3e25717850c26c9cd0d89d")
407n/a
408n/a def test_case_sha1_2(self):
409n/a self.check('sha1',
410n/a b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
411n/a "84983e441c3bd26ebaae4aa1f95129e5e54670f1")
412n/a
413n/a def test_case_sha1_3(self):
414n/a self.check('sha1', b"a" * 1000000,
415n/a "34aa973cd4c4daa4f61eeb2bdbad27316534016f")
416n/a
417n/a
418n/a # use the examples from Federal Information Processing Standards
419n/a # Publication 180-2, Secure Hash Standard, 2002 August 1
420n/a # http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf
421n/a
422n/a def test_case_sha224_0(self):
423n/a self.check('sha224', b"",
424n/a "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f")
425n/a
426n/a def test_case_sha224_1(self):
427n/a self.check('sha224', b"abc",
428n/a "23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7")
429n/a
430n/a def test_case_sha224_2(self):
431n/a self.check('sha224',
432n/a b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
433n/a "75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525")
434n/a
435n/a def test_case_sha224_3(self):
436n/a self.check('sha224', b"a" * 1000000,
437n/a "20794655980c91d8bbb4c1ea97618a4bf03f42581948b2ee4ee7ad67")
438n/a
439n/a
440n/a def test_case_sha256_0(self):
441n/a self.check('sha256', b"",
442n/a "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
443n/a
444n/a def test_case_sha256_1(self):
445n/a self.check('sha256', b"abc",
446n/a "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
447n/a
448n/a def test_case_sha256_2(self):
449n/a self.check('sha256',
450n/a b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
451n/a "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1")
452n/a
453n/a def test_case_sha256_3(self):
454n/a self.check('sha256', b"a" * 1000000,
455n/a "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0")
456n/a
457n/a
458n/a def test_case_sha384_0(self):
459n/a self.check('sha384', b"",
460n/a "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da"+
461n/a "274edebfe76f65fbd51ad2f14898b95b")
462n/a
463n/a def test_case_sha384_1(self):
464n/a self.check('sha384', b"abc",
465n/a "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed"+
466n/a "8086072ba1e7cc2358baeca134c825a7")
467n/a
468n/a def test_case_sha384_2(self):
469n/a self.check('sha384',
470n/a b"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn"+
471n/a b"hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
472n/a "09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712"+
473n/a "fcc7c71a557e2db966c3e9fa91746039")
474n/a
475n/a def test_case_sha384_3(self):
476n/a self.check('sha384', b"a" * 1000000,
477n/a "9d0e1809716474cb086e834e310a4a1ced149e9c00f248527972cec5704c2a5b"+
478n/a "07b8b3dc38ecc4ebae97ddd87f3d8985")
479n/a
480n/a
481n/a def test_case_sha512_0(self):
482n/a self.check('sha512', b"",
483n/a "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce"+
484n/a "47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e")
485n/a
486n/a def test_case_sha512_1(self):
487n/a self.check('sha512', b"abc",
488n/a "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a"+
489n/a "2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f")
490n/a
491n/a def test_case_sha512_2(self):
492n/a self.check('sha512',
493n/a b"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn"+
494n/a b"hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
495n/a "8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018"+
496n/a "501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909")
497n/a
498n/a def test_case_sha512_3(self):
499n/a self.check('sha512', b"a" * 1000000,
500n/a "e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973eb"+
501n/a "de0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b")
502n/a
503n/a def check_blake2(self, constructor, salt_size, person_size, key_size,
504n/a digest_size, max_offset):
505n/a self.assertEqual(constructor.SALT_SIZE, salt_size)
506n/a for i in range(salt_size + 1):
507n/a constructor(salt=b'a' * i)
508n/a salt = b'a' * (salt_size + 1)
509n/a self.assertRaises(ValueError, constructor, salt=salt)
510n/a
511n/a self.assertEqual(constructor.PERSON_SIZE, person_size)
512n/a for i in range(person_size+1):
513n/a constructor(person=b'a' * i)
514n/a person = b'a' * (person_size + 1)
515n/a self.assertRaises(ValueError, constructor, person=person)
516n/a
517n/a self.assertEqual(constructor.MAX_DIGEST_SIZE, digest_size)
518n/a for i in range(1, digest_size + 1):
519n/a constructor(digest_size=i)
520n/a self.assertRaises(ValueError, constructor, digest_size=-1)
521n/a self.assertRaises(ValueError, constructor, digest_size=0)
522n/a self.assertRaises(ValueError, constructor, digest_size=digest_size+1)
523n/a
524n/a self.assertEqual(constructor.MAX_KEY_SIZE, key_size)
525n/a for i in range(key_size+1):
526n/a constructor(key=b'a' * i)
527n/a key = b'a' * (key_size + 1)
528n/a self.assertRaises(ValueError, constructor, key=key)
529n/a self.assertEqual(constructor().hexdigest(),
530n/a constructor(key=b'').hexdigest())
531n/a
532n/a for i in range(0, 256):
533n/a constructor(fanout=i)
534n/a self.assertRaises(ValueError, constructor, fanout=-1)
535n/a self.assertRaises(ValueError, constructor, fanout=256)
536n/a
537n/a for i in range(1, 256):
538n/a constructor(depth=i)
539n/a self.assertRaises(ValueError, constructor, depth=-1)
540n/a self.assertRaises(ValueError, constructor, depth=0)
541n/a self.assertRaises(ValueError, constructor, depth=256)
542n/a
543n/a for i in range(0, 256):
544n/a constructor(node_depth=i)
545n/a self.assertRaises(ValueError, constructor, node_depth=-1)
546n/a self.assertRaises(ValueError, constructor, node_depth=256)
547n/a
548n/a for i in range(0, digest_size + 1):
549n/a constructor(inner_size=i)
550n/a self.assertRaises(ValueError, constructor, inner_size=-1)
551n/a self.assertRaises(ValueError, constructor, inner_size=digest_size+1)
552n/a
553n/a constructor(leaf_size=0)
554n/a constructor(leaf_size=(1<<32)-1)
555n/a self.assertRaises(OverflowError, constructor, leaf_size=-1)
556n/a self.assertRaises(OverflowError, constructor, leaf_size=1<<32)
557n/a
558n/a constructor(node_offset=0)
559n/a constructor(node_offset=max_offset)
560n/a self.assertRaises(OverflowError, constructor, node_offset=-1)
561n/a self.assertRaises(OverflowError, constructor, node_offset=max_offset+1)
562n/a
563n/a constructor(
564n/a string=b'',
565n/a key=b'',
566n/a salt=b'',
567n/a person=b'',
568n/a digest_size=17,
569n/a fanout=1,
570n/a depth=1,
571n/a leaf_size=256,
572n/a node_offset=512,
573n/a node_depth=1,
574n/a inner_size=7,
575n/a last_node=True
576n/a )
577n/a
578n/a def blake2_rfc7693(self, constructor, md_len, in_len):
579n/a def selftest_seq(length, seed):
580n/a mask = (1<<32)-1
581n/a a = (0xDEAD4BAD * seed) & mask
582n/a b = 1
583n/a out = bytearray(length)
584n/a for i in range(length):
585n/a t = (a + b) & mask
586n/a a, b = b, t
587n/a out[i] = (t >> 24) & 0xFF
588n/a return out
589n/a outer = constructor(digest_size=32)
590n/a for outlen in md_len:
591n/a for inlen in in_len:
592n/a indata = selftest_seq(inlen, inlen)
593n/a key = selftest_seq(outlen, outlen)
594n/a unkeyed = constructor(indata, digest_size=outlen)
595n/a outer.update(unkeyed.digest())
596n/a keyed = constructor(indata, key=key, digest_size=outlen)
597n/a outer.update(keyed.digest())
598n/a return outer.hexdigest()
599n/a
600n/a @requires_blake2
601n/a def test_blake2b(self):
602n/a self.check_blake2(hashlib.blake2b, 16, 16, 64, 64, (1<<64)-1)
603n/a b2b_md_len = [20, 32, 48, 64]
604n/a b2b_in_len = [0, 3, 128, 129, 255, 1024]
605n/a self.assertEqual(
606n/a self.blake2_rfc7693(hashlib.blake2b, b2b_md_len, b2b_in_len),
607n/a "c23a7800d98123bd10f506c61e29da5603d763b8bbad2e737f5e765a7bccd475")
608n/a
609n/a @requires_blake2
610n/a def test_case_blake2b_0(self):
611n/a self.check('blake2b', b"",
612n/a "786a02f742015903c6c6fd852552d272912f4740e15847618a86e217f71f5419"+
613n/a "d25e1031afee585313896444934eb04b903a685b1448b755d56f701afe9be2ce")
614n/a
615n/a @requires_blake2
616n/a def test_case_blake2b_1(self):
617n/a self.check('blake2b', b"abc",
618n/a "ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d1"+
619n/a "7d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923")
620n/a
621n/a @requires_blake2
622n/a def test_blake2b_vectors(self):
623n/a for msg, key, md in read_vectors('blake2b'):
624n/a key = bytes.fromhex(key)
625n/a self.check('blake2b', msg, md, key=key)
626n/a
627n/a @requires_blake2
628n/a def test_blake2s(self):
629n/a self.check_blake2(hashlib.blake2s, 8, 8, 32, 32, (1<<48)-1)
630n/a b2s_md_len = [16, 20, 28, 32]
631n/a b2s_in_len = [0, 3, 64, 65, 255, 1024]
632n/a self.assertEqual(
633n/a self.blake2_rfc7693(hashlib.blake2s, b2s_md_len, b2s_in_len),
634n/a "6a411f08ce25adcdfb02aba641451cec53c598b24f4fc787fbdc88797f4c1dfe")
635n/a
636n/a @requires_blake2
637n/a def test_case_blake2s_0(self):
638n/a self.check('blake2s', b"",
639n/a "69217a3079908094e11121d042354a7c1f55b6482ca1a51e1b250dfd1ed0eef9")
640n/a
641n/a @requires_blake2
642n/a def test_case_blake2s_1(self):
643n/a self.check('blake2s', b"abc",
644n/a "508c5e8c327c14e2e1a72ba34eeb452f37458b209ed63a294d999b4c86675982")
645n/a
646n/a @requires_blake2
647n/a def test_blake2s_vectors(self):
648n/a for msg, key, md in read_vectors('blake2s'):
649n/a key = bytes.fromhex(key)
650n/a self.check('blake2s', msg, md, key=key)
651n/a
652n/a @requires_sha3
653n/a def test_case_sha3_224_0(self):
654n/a self.check('sha3_224', b"",
655n/a "6b4e03423667dbb73b6e15454f0eb1abd4597f9a1b078e3f5b5a6bc7")
656n/a
657n/a @requires_sha3
658n/a def test_case_sha3_224_vector(self):
659n/a for msg, md in read_vectors('sha3_224'):
660n/a self.check('sha3_224', msg, md)
661n/a
662n/a @requires_sha3
663n/a def test_case_sha3_256_0(self):
664n/a self.check('sha3_256', b"",
665n/a "a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a")
666n/a
667n/a @requires_sha3
668n/a def test_case_sha3_256_vector(self):
669n/a for msg, md in read_vectors('sha3_256'):
670n/a self.check('sha3_256', msg, md)
671n/a
672n/a @requires_sha3
673n/a def test_case_sha3_384_0(self):
674n/a self.check('sha3_384', b"",
675n/a "0c63a75b845e4f7d01107d852e4c2485c51a50aaaa94fc61995e71bbee983a2a"+
676n/a "c3713831264adb47fb6bd1e058d5f004")
677n/a
678n/a @requires_sha3
679n/a def test_case_sha3_384_vector(self):
680n/a for msg, md in read_vectors('sha3_384'):
681n/a self.check('sha3_384', msg, md)
682n/a
683n/a @requires_sha3
684n/a def test_case_sha3_512_0(self):
685n/a self.check('sha3_512', b"",
686n/a "a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a6"+
687n/a "15b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26")
688n/a
689n/a @requires_sha3
690n/a def test_case_sha3_512_vector(self):
691n/a for msg, md in read_vectors('sha3_512'):
692n/a self.check('sha3_512', msg, md)
693n/a
694n/a @requires_sha3
695n/a def test_case_shake_128_0(self):
696n/a self.check('shake_128', b"",
697n/a "7f9c2ba4e88f827d616045507605853ed73b8093f6efbc88eb1a6eacfa66ef26",
698n/a True)
699n/a self.check('shake_128', b"", "7f9c", True)
700n/a
701n/a @requires_sha3
702n/a def test_case_shake128_vector(self):
703n/a for msg, md in read_vectors('shake_128'):
704n/a self.check('shake_128', msg, md, True)
705n/a
706n/a @requires_sha3
707n/a def test_case_shake_256_0(self):
708n/a self.check('shake_256', b"",
709n/a "46b9dd2b0ba88d13233b3feb743eeb243fcd52ea62b81b82b50c27646ed5762f",
710n/a True)
711n/a self.check('shake_256', b"", "46b9", True)
712n/a
713n/a @requires_sha3
714n/a def test_case_shake256_vector(self):
715n/a for msg, md in read_vectors('shake_256'):
716n/a self.check('shake_256', msg, md, True)
717n/a
718n/a def test_gil(self):
719n/a # Check things work fine with an input larger than the size required
720n/a # for multithreaded operation (which is hardwired to 2048).
721n/a gil_minsize = 2048
722n/a
723n/a for cons in self.hash_constructors:
724n/a m = cons()
725n/a m.update(b'1')
726n/a m.update(b'#' * gil_minsize)
727n/a m.update(b'1')
728n/a
729n/a m = cons(b'x' * gil_minsize)
730n/a m.update(b'1')
731n/a
732n/a m = hashlib.md5()
733n/a m.update(b'1')
734n/a m.update(b'#' * gil_minsize)
735n/a m.update(b'1')
736n/a self.assertEqual(m.hexdigest(), 'cb1e1a2cbc80be75e19935d621fb9b21')
737n/a
738n/a m = hashlib.md5(b'x' * gil_minsize)
739n/a self.assertEqual(m.hexdigest(), 'cfb767f225d58469c5de3632a8803958')
740n/a
741n/a @unittest.skipUnless(threading, 'Threading required for this test.')
742n/a @support.reap_threads
743n/a def test_threaded_hashing(self):
744n/a # Updating the same hash object from several threads at once
745n/a # using data chunk sizes containing the same byte sequences.
746n/a #
747n/a # If the internal locks are working to prevent multiple
748n/a # updates on the same object from running at once, the resulting
749n/a # hash will be the same as doing it single threaded upfront.
750n/a hasher = hashlib.sha1()
751n/a num_threads = 5
752n/a smallest_data = b'swineflu'
753n/a data = smallest_data*200000
754n/a expected_hash = hashlib.sha1(data*num_threads).hexdigest()
755n/a
756n/a def hash_in_chunks(chunk_size, event):
757n/a index = 0
758n/a while index < len(data):
759n/a hasher.update(data[index:index+chunk_size])
760n/a index += chunk_size
761n/a event.set()
762n/a
763n/a events = []
764n/a for threadnum in range(num_threads):
765n/a chunk_size = len(data) // (10**threadnum)
766n/a self.assertGreater(chunk_size, 0)
767n/a self.assertEqual(chunk_size % len(smallest_data), 0)
768n/a event = threading.Event()
769n/a events.append(event)
770n/a threading.Thread(target=hash_in_chunks,
771n/a args=(chunk_size, event)).start()
772n/a
773n/a for event in events:
774n/a event.wait()
775n/a
776n/a self.assertEqual(expected_hash, hasher.hexdigest())
777n/a
778n/a
779n/aclass KDFTests(unittest.TestCase):
780n/a
781n/a pbkdf2_test_vectors = [
782n/a (b'password', b'salt', 1, None),
783n/a (b'password', b'salt', 2, None),
784n/a (b'password', b'salt', 4096, None),
785n/a # too slow, it takes over a minute on a fast CPU.
786n/a #(b'password', b'salt', 16777216, None),
787n/a (b'passwordPASSWORDpassword', b'saltSALTsaltSALTsaltSALTsaltSALTsalt',
788n/a 4096, -1),
789n/a (b'pass\0word', b'sa\0lt', 4096, 16),
790n/a ]
791n/a
792n/a scrypt_test_vectors = [
793n/a (b'', b'', 16, 1, 1, unhexlify('77d6576238657b203b19ca42c18a0497f16b4844e3074ae8dfdffa3fede21442fcd0069ded0948f8326a753a0fc81f17e8d3e0fb2e0d3628cf35e20c38d18906')),
794n/a (b'password', b'NaCl', 1024, 8, 16, unhexlify('fdbabe1c9d3472007856e7190d01e9fe7c6ad7cbc8237830e77376634b3731622eaf30d92e22a3886ff109279d9830dac727afb94a83ee6d8360cbdfa2cc0640')),
795n/a (b'pleaseletmein', b'SodiumChloride', 16384, 8, 1, unhexlify('7023bdcb3afd7348461c06cd81fd38ebfda8fbba904f8e3ea9b543f6545da1f2d5432955613f0fcf62d49705242a9af9e61e85dc0d651e40dfcf017b45575887')),
796n/a ]
797n/a
798n/a pbkdf2_results = {
799n/a "sha1": [
800n/a # official test vectors from RFC 6070
801n/a (bytes.fromhex('0c60c80f961f0e71f3a9b524af6012062fe037a6'), None),
802n/a (bytes.fromhex('ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957'), None),
803n/a (bytes.fromhex('4b007901b765489abead49d926f721d065a429c1'), None),
804n/a #(bytes.fromhex('eefe3d61cd4da4e4e9945b3d6ba2158c2634e984'), None),
805n/a (bytes.fromhex('3d2eec4fe41c849b80c8d83662c0e44a8b291a964c'
806n/a 'f2f07038'), 25),
807n/a (bytes.fromhex('56fa6aa75548099dcc37d7f03425e0c3'), None),],
808n/a "sha256": [
809n/a (bytes.fromhex('120fb6cffcf8b32c43e7225256c4f837'
810n/a 'a86548c92ccc35480805987cb70be17b'), None),
811n/a (bytes.fromhex('ae4d0c95af6b46d32d0adff928f06dd0'
812n/a '2a303f8ef3c251dfd6e2d85a95474c43'), None),
813n/a (bytes.fromhex('c5e478d59288c841aa530db6845c4c8d'
814n/a '962893a001ce4e11a4963873aa98134a'), None),
815n/a #(bytes.fromhex('cf81c66fe8cfc04d1f31ecb65dab4089'
816n/a # 'f7f179e89b3b0bcb17ad10e3ac6eba46'), None),
817n/a (bytes.fromhex('348c89dbcbd32b2f32d814b8116e84cf2b17'
818n/a '347ebc1800181c4e2a1fb8dd53e1c635518c7dac47e9'), 40),
819n/a (bytes.fromhex('89b69d0516f829893c696226650a8687'), None),],
820n/a "sha512": [
821n/a (bytes.fromhex('867f70cf1ade02cff3752599a3a53dc4af34c7a669815ae5'
822n/a 'd513554e1c8cf252c02d470a285a0501bad999bfe943c08f'
823n/a '050235d7d68b1da55e63f73b60a57fce'), None),
824n/a (bytes.fromhex('e1d9c16aa681708a45f5c7c4e215ceb66e011a2e9f004071'
825n/a '3f18aefdb866d53cf76cab2868a39b9f7840edce4fef5a82'
826n/a 'be67335c77a6068e04112754f27ccf4e'), None),
827n/a (bytes.fromhex('d197b1b33db0143e018b12f3d1d1479e6cdebdcc97c5c0f8'
828n/a '7f6902e072f457b5143f30602641b3d55cd335988cb36b84'
829n/a '376060ecd532e039b742a239434af2d5'), None),
830n/a (bytes.fromhex('8c0511f4c6e597c6ac6315d8f0362e225f3c501495ba23b8'
831n/a '68c005174dc4ee71115b59f9e60cd9532fa33e0f75aefe30'
832n/a '225c583a186cd82bd4daea9724a3d3b8'), 64),
833n/a (bytes.fromhex('9d9e9c4cd21fe4be24d5b8244c759665'), None),],
834n/a }
835n/a
836n/a def _test_pbkdf2_hmac(self, pbkdf2):
837n/a for digest_name, results in self.pbkdf2_results.items():
838n/a for i, vector in enumerate(self.pbkdf2_test_vectors):
839n/a password, salt, rounds, dklen = vector
840n/a expected, overwrite_dklen = results[i]
841n/a if overwrite_dklen:
842n/a dklen = overwrite_dklen
843n/a out = pbkdf2(digest_name, password, salt, rounds, dklen)
844n/a self.assertEqual(out, expected,
845n/a (digest_name, password, salt, rounds, dklen))
846n/a out = pbkdf2(digest_name, memoryview(password),
847n/a memoryview(salt), rounds, dklen)
848n/a out = pbkdf2(digest_name, bytearray(password),
849n/a bytearray(salt), rounds, dklen)
850n/a self.assertEqual(out, expected)
851n/a if dklen is None:
852n/a out = pbkdf2(digest_name, password, salt, rounds)
853n/a self.assertEqual(out, expected,
854n/a (digest_name, password, salt, rounds))
855n/a
856n/a self.assertRaises(TypeError, pbkdf2, b'sha1', b'pass', b'salt', 1)
857n/a self.assertRaises(TypeError, pbkdf2, 'sha1', 'pass', 'salt', 1)
858n/a self.assertRaises(ValueError, pbkdf2, 'sha1', b'pass', b'salt', 0)
859n/a self.assertRaises(ValueError, pbkdf2, 'sha1', b'pass', b'salt', -1)
860n/a self.assertRaises(ValueError, pbkdf2, 'sha1', b'pass', b'salt', 1, 0)
861n/a self.assertRaises(ValueError, pbkdf2, 'sha1', b'pass', b'salt', 1, -1)
862n/a with self.assertRaisesRegex(ValueError, 'unsupported hash type'):
863n/a pbkdf2('unknown', b'pass', b'salt', 1)
864n/a out = pbkdf2(hash_name='sha1', password=b'password', salt=b'salt',
865n/a iterations=1, dklen=None)
866n/a self.assertEqual(out, self.pbkdf2_results['sha1'][0][0])
867n/a
868n/a def test_pbkdf2_hmac_py(self):
869n/a self._test_pbkdf2_hmac(py_hashlib.pbkdf2_hmac)
870n/a
871n/a @unittest.skipUnless(hasattr(c_hashlib, 'pbkdf2_hmac'),
872n/a ' test requires OpenSSL > 1.0')
873n/a def test_pbkdf2_hmac_c(self):
874n/a self._test_pbkdf2_hmac(c_hashlib.pbkdf2_hmac)
875n/a
876n/a
877n/a @unittest.skipUnless(hasattr(c_hashlib, 'scrypt'),
878n/a ' test requires OpenSSL > 1.1')
879n/a def test_scrypt(self):
880n/a for password, salt, n, r, p, expected in self.scrypt_test_vectors:
881n/a result = hashlib.scrypt(password, salt=salt, n=n, r=r, p=p)
882n/a self.assertEqual(result, expected)
883n/a
884n/a # this values should work
885n/a hashlib.scrypt(b'password', salt=b'salt', n=2, r=8, p=1)
886n/a # password and salt must be bytes-like
887n/a with self.assertRaises(TypeError):
888n/a hashlib.scrypt('password', salt=b'salt', n=2, r=8, p=1)
889n/a with self.assertRaises(TypeError):
890n/a hashlib.scrypt(b'password', salt='salt', n=2, r=8, p=1)
891n/a # require keyword args
892n/a with self.assertRaises(TypeError):
893n/a hashlib.scrypt(b'password')
894n/a with self.assertRaises(TypeError):
895n/a hashlib.scrypt(b'password', b'salt')
896n/a with self.assertRaises(TypeError):
897n/a hashlib.scrypt(b'password', 2, 8, 1, salt=b'salt')
898n/a for n in [-1, 0, 1, None]:
899n/a with self.assertRaises((ValueError, OverflowError, TypeError)):
900n/a hashlib.scrypt(b'password', salt=b'salt', n=n, r=8, p=1)
901n/a for r in [-1, 0, None]:
902n/a with self.assertRaises((ValueError, OverflowError, TypeError)):
903n/a hashlib.scrypt(b'password', salt=b'salt', n=2, r=r, p=1)
904n/a for p in [-1, 0, None]:
905n/a with self.assertRaises((ValueError, OverflowError, TypeError)):
906n/a hashlib.scrypt(b'password', salt=b'salt', n=2, r=8, p=p)
907n/a for maxmem in [-1, None]:
908n/a with self.assertRaises((ValueError, OverflowError, TypeError)):
909n/a hashlib.scrypt(b'password', salt=b'salt', n=2, r=8, p=1,
910n/a maxmem=maxmem)
911n/a for dklen in [-1, None]:
912n/a with self.assertRaises((ValueError, OverflowError, TypeError)):
913n/a hashlib.scrypt(b'password', salt=b'salt', n=2, r=8, p=1,
914n/a dklen=dklen)
915n/a
916n/a
917n/aif __name__ == "__main__":
918n/a unittest.main()