»Core Development>Code coverage>Lib/test/test_hmac.py

Python code coverage for Lib/test/test_hmac.py

#countcontent
1n/aimport functools
2n/aimport hmac
3n/aimport hashlib
4n/aimport unittest
5n/aimport warnings
6n/a
7n/a
8n/adef ignore_warning(func):
9n/a @functools.wraps(func)
10n/a def wrapper(*args, **kwargs):
11n/a with warnings.catch_warnings():
12n/a warnings.filterwarnings("ignore",
13n/a category=PendingDeprecationWarning)
14n/a return func(*args, **kwargs)
15n/a return wrapper
16n/a
17n/a
18n/aclass TestVectorsTestCase(unittest.TestCase):
19n/a
20n/a def test_md5_vectors(self):
21n/a # Test the HMAC module against test vectors from the RFC.
22n/a
23n/a def md5test(key, data, digest):
24n/a h = hmac.HMAC(key, data, digestmod=hashlib.md5)
25n/a self.assertEqual(h.hexdigest().upper(), digest.upper())
26n/a self.assertEqual(h.name, "hmac-md5")
27n/a self.assertEqual(h.digest_size, 16)
28n/a self.assertEqual(h.block_size, 64)
29n/a
30n/a h = hmac.HMAC(key, data, digestmod='md5')
31n/a self.assertEqual(h.hexdigest().upper(), digest.upper())
32n/a self.assertEqual(h.name, "hmac-md5")
33n/a self.assertEqual(h.digest_size, 16)
34n/a self.assertEqual(h.block_size, 64)
35n/a
36n/a
37n/a md5test(b"\x0b" * 16,
38n/a b"Hi There",
39n/a "9294727A3638BB1C13F48EF8158BFC9D")
40n/a
41n/a md5test(b"Jefe",
42n/a b"what do ya want for nothing?",
43n/a "750c783e6ab0b503eaa86e310a5db738")
44n/a
45n/a md5test(b"\xaa" * 16,
46n/a b"\xdd" * 50,
47n/a "56be34521d144c88dbb8c733f0e8b3f6")
48n/a
49n/a md5test(bytes(range(1, 26)),
50n/a b"\xcd" * 50,
51n/a "697eaf0aca3a3aea3a75164746ffaa79")
52n/a
53n/a md5test(b"\x0C" * 16,
54n/a b"Test With Truncation",
55n/a "56461ef2342edc00f9bab995690efd4c")
56n/a
57n/a md5test(b"\xaa" * 80,
58n/a b"Test Using Larger Than Block-Size Key - Hash Key First",
59n/a "6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd")
60n/a
61n/a md5test(b"\xaa" * 80,
62n/a (b"Test Using Larger Than Block-Size Key "
63n/a b"and Larger Than One Block-Size Data"),
64n/a "6f630fad67cda0ee1fb1f562db3aa53e")
65n/a
66n/a def test_sha_vectors(self):
67n/a def shatest(key, data, digest):
68n/a h = hmac.HMAC(key, data, digestmod=hashlib.sha1)
69n/a self.assertEqual(h.hexdigest().upper(), digest.upper())
70n/a self.assertEqual(h.name, "hmac-sha1")
71n/a self.assertEqual(h.digest_size, 20)
72n/a self.assertEqual(h.block_size, 64)
73n/a
74n/a h = hmac.HMAC(key, data, digestmod='sha1')
75n/a self.assertEqual(h.hexdigest().upper(), digest.upper())
76n/a self.assertEqual(h.name, "hmac-sha1")
77n/a self.assertEqual(h.digest_size, 20)
78n/a self.assertEqual(h.block_size, 64)
79n/a
80n/a
81n/a shatest(b"\x0b" * 20,
82n/a b"Hi There",
83n/a "b617318655057264e28bc0b6fb378c8ef146be00")
84n/a
85n/a shatest(b"Jefe",
86n/a b"what do ya want for nothing?",
87n/a "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79")
88n/a
89n/a shatest(b"\xAA" * 20,
90n/a b"\xDD" * 50,
91n/a "125d7342b9ac11cd91a39af48aa17b4f63f175d3")
92n/a
93n/a shatest(bytes(range(1, 26)),
94n/a b"\xCD" * 50,
95n/a "4c9007f4026250c6bc8414f9bf50c86c2d7235da")
96n/a
97n/a shatest(b"\x0C" * 20,
98n/a b"Test With Truncation",
99n/a "4c1a03424b55e07fe7f27be1d58bb9324a9a5a04")
100n/a
101n/a shatest(b"\xAA" * 80,
102n/a b"Test Using Larger Than Block-Size Key - Hash Key First",
103n/a "aa4ae5e15272d00e95705637ce8a3b55ed402112")
104n/a
105n/a shatest(b"\xAA" * 80,
106n/a (b"Test Using Larger Than Block-Size Key "
107n/a b"and Larger Than One Block-Size Data"),
108n/a "e8e99d0f45237d786d6bbaa7965c7808bbff1a91")
109n/a
110n/a def _rfc4231_test_cases(self, hashfunc, hash_name, digest_size, block_size):
111n/a def hmactest(key, data, hexdigests):
112n/a hmac_name = "hmac-" + hash_name
113n/a h = hmac.HMAC(key, data, digestmod=hashfunc)
114n/a self.assertEqual(h.hexdigest().lower(), hexdigests[hashfunc])
115n/a self.assertEqual(h.name, hmac_name)
116n/a self.assertEqual(h.digest_size, digest_size)
117n/a self.assertEqual(h.block_size, block_size)
118n/a
119n/a h = hmac.HMAC(key, data, digestmod=hash_name)
120n/a self.assertEqual(h.hexdigest().lower(), hexdigests[hashfunc])
121n/a self.assertEqual(h.name, hmac_name)
122n/a self.assertEqual(h.digest_size, digest_size)
123n/a self.assertEqual(h.block_size, block_size)
124n/a
125n/a
126n/a # 4.2. Test Case 1
127n/a hmactest(key = b'\x0b'*20,
128n/a data = b'Hi There',
129n/a hexdigests = {
130n/a hashlib.sha224: '896fb1128abbdf196832107cd49df33f'
131n/a '47b4b1169912ba4f53684b22',
132n/a hashlib.sha256: 'b0344c61d8db38535ca8afceaf0bf12b'
133n/a '881dc200c9833da726e9376c2e32cff7',
134n/a hashlib.sha384: 'afd03944d84895626b0825f4ab46907f'
135n/a '15f9dadbe4101ec682aa034c7cebc59c'
136n/a 'faea9ea9076ede7f4af152e8b2fa9cb6',
137n/a hashlib.sha512: '87aa7cdea5ef619d4ff0b4241a1d6cb0'
138n/a '2379f4e2ce4ec2787ad0b30545e17cde'
139n/a 'daa833b7d6b8a702038b274eaea3f4e4'
140n/a 'be9d914eeb61f1702e696c203a126854',
141n/a })
142n/a
143n/a # 4.3. Test Case 2
144n/a hmactest(key = b'Jefe',
145n/a data = b'what do ya want for nothing?',
146n/a hexdigests = {
147n/a hashlib.sha224: 'a30e01098bc6dbbf45690f3a7e9e6d0f'
148n/a '8bbea2a39e6148008fd05e44',
149n/a hashlib.sha256: '5bdcc146bf60754e6a042426089575c7'
150n/a '5a003f089d2739839dec58b964ec3843',
151n/a hashlib.sha384: 'af45d2e376484031617f78d2b58a6b1b'
152n/a '9c7ef464f5a01b47e42ec3736322445e'
153n/a '8e2240ca5e69e2c78b3239ecfab21649',
154n/a hashlib.sha512: '164b7a7bfcf819e2e395fbe73b56e0a3'
155n/a '87bd64222e831fd610270cd7ea250554'
156n/a '9758bf75c05a994a6d034f65f8f0e6fd'
157n/a 'caeab1a34d4a6b4b636e070a38bce737',
158n/a })
159n/a
160n/a # 4.4. Test Case 3
161n/a hmactest(key = b'\xaa'*20,
162n/a data = b'\xdd'*50,
163n/a hexdigests = {
164n/a hashlib.sha224: '7fb3cb3588c6c1f6ffa9694d7d6ad264'
165n/a '9365b0c1f65d69d1ec8333ea',
166n/a hashlib.sha256: '773ea91e36800e46854db8ebd09181a7'
167n/a '2959098b3ef8c122d9635514ced565fe',
168n/a hashlib.sha384: '88062608d3e6ad8a0aa2ace014c8a86f'
169n/a '0aa635d947ac9febe83ef4e55966144b'
170n/a '2a5ab39dc13814b94e3ab6e101a34f27',
171n/a hashlib.sha512: 'fa73b0089d56a284efb0f0756c890be9'
172n/a 'b1b5dbdd8ee81a3655f83e33b2279d39'
173n/a 'bf3e848279a722c806b485a47e67c807'
174n/a 'b946a337bee8942674278859e13292fb',
175n/a })
176n/a
177n/a # 4.5. Test Case 4
178n/a hmactest(key = bytes(x for x in range(0x01, 0x19+1)),
179n/a data = b'\xcd'*50,
180n/a hexdigests = {
181n/a hashlib.sha224: '6c11506874013cac6a2abc1bb382627c'
182n/a 'ec6a90d86efc012de7afec5a',
183n/a hashlib.sha256: '82558a389a443c0ea4cc819899f2083a'
184n/a '85f0faa3e578f8077a2e3ff46729665b',
185n/a hashlib.sha384: '3e8a69b7783c25851933ab6290af6ca7'
186n/a '7a9981480850009cc5577c6e1f573b4e'
187n/a '6801dd23c4a7d679ccf8a386c674cffb',
188n/a hashlib.sha512: 'b0ba465637458c6990e5a8c5f61d4af7'
189n/a 'e576d97ff94b872de76f8050361ee3db'
190n/a 'a91ca5c11aa25eb4d679275cc5788063'
191n/a 'a5f19741120c4f2de2adebeb10a298dd',
192n/a })
193n/a
194n/a # 4.7. Test Case 6
195n/a hmactest(key = b'\xaa'*131,
196n/a data = b'Test Using Larger Than Block-Siz'
197n/a b'e Key - Hash Key First',
198n/a hexdigests = {
199n/a hashlib.sha224: '95e9a0db962095adaebe9b2d6f0dbce2'
200n/a 'd499f112f2d2b7273fa6870e',
201n/a hashlib.sha256: '60e431591ee0b67f0d8a26aacbf5b77f'
202n/a '8e0bc6213728c5140546040f0ee37f54',
203n/a hashlib.sha384: '4ece084485813e9088d2c63a041bc5b4'
204n/a '4f9ef1012a2b588f3cd11f05033ac4c6'
205n/a '0c2ef6ab4030fe8296248df163f44952',
206n/a hashlib.sha512: '80b24263c7c1a3ebb71493c1dd7be8b4'
207n/a '9b46d1f41b4aeec1121b013783f8f352'
208n/a '6b56d037e05f2598bd0fd2215d6a1e52'
209n/a '95e64f73f63f0aec8b915a985d786598',
210n/a })
211n/a
212n/a # 4.8. Test Case 7
213n/a hmactest(key = b'\xaa'*131,
214n/a data = b'This is a test using a larger th'
215n/a b'an block-size key and a larger t'
216n/a b'han block-size data. The key nee'
217n/a b'ds to be hashed before being use'
218n/a b'd by the HMAC algorithm.',
219n/a hexdigests = {
220n/a hashlib.sha224: '3a854166ac5d9f023f54d517d0b39dbd'
221n/a '946770db9c2b95c9f6f565d1',
222n/a hashlib.sha256: '9b09ffa71b942fcb27635fbcd5b0e944'
223n/a 'bfdc63644f0713938a7f51535c3a35e2',
224n/a hashlib.sha384: '6617178e941f020d351e2f254e8fd32c'
225n/a '602420feb0b8fb9adccebb82461e99c5'
226n/a 'a678cc31e799176d3860e6110c46523e',
227n/a hashlib.sha512: 'e37b6a775dc87dbaa4dfa9f96e5e3ffd'
228n/a 'debd71f8867289865df5a32d20cdc944'
229n/a 'b6022cac3c4982b10d5eeb55c3e4de15'
230n/a '134676fb6de0446065c97440fa8c6a58',
231n/a })
232n/a
233n/a def test_sha224_rfc4231(self):
234n/a self._rfc4231_test_cases(hashlib.sha224, 'sha224', 28, 64)
235n/a
236n/a def test_sha256_rfc4231(self):
237n/a self._rfc4231_test_cases(hashlib.sha256, 'sha256', 32, 64)
238n/a
239n/a def test_sha384_rfc4231(self):
240n/a self._rfc4231_test_cases(hashlib.sha384, 'sha384', 48, 128)
241n/a
242n/a def test_sha512_rfc4231(self):
243n/a self._rfc4231_test_cases(hashlib.sha512, 'sha512', 64, 128)
244n/a
245n/a def test_legacy_block_size_warnings(self):
246n/a class MockCrazyHash(object):
247n/a """Ain't no block_size attribute here."""
248n/a def __init__(self, *args):
249n/a self._x = hashlib.sha1(*args)
250n/a self.digest_size = self._x.digest_size
251n/a def update(self, v):
252n/a self._x.update(v)
253n/a def digest(self):
254n/a return self._x.digest()
255n/a
256n/a with warnings.catch_warnings():
257n/a warnings.simplefilter('error', RuntimeWarning)
258n/a with self.assertRaises(RuntimeWarning):
259n/a hmac.HMAC(b'a', b'b', digestmod=MockCrazyHash)
260n/a self.fail('Expected warning about missing block_size')
261n/a
262n/a MockCrazyHash.block_size = 1
263n/a with self.assertRaises(RuntimeWarning):
264n/a hmac.HMAC(b'a', b'b', digestmod=MockCrazyHash)
265n/a self.fail('Expected warning about small block_size')
266n/a
267n/a def test_with_digestmod_warning(self):
268n/a with self.assertWarns(PendingDeprecationWarning):
269n/a key = b"\x0b" * 16
270n/a data = b"Hi There"
271n/a digest = "9294727A3638BB1C13F48EF8158BFC9D"
272n/a h = hmac.HMAC(key, data)
273n/a self.assertEqual(h.hexdigest().upper(), digest)
274n/a
275n/a
276n/aclass ConstructorTestCase(unittest.TestCase):
277n/a
278n/a @ignore_warning
279n/a def test_normal(self):
280n/a # Standard constructor call.
281n/a failed = 0
282n/a try:
283n/a h = hmac.HMAC(b"key")
284n/a except Exception:
285n/a self.fail("Standard constructor call raised exception.")
286n/a
287n/a @ignore_warning
288n/a def test_with_str_key(self):
289n/a # Pass a key of type str, which is an error, because it expects a key
290n/a # of type bytes
291n/a with self.assertRaises(TypeError):
292n/a h = hmac.HMAC("key")
293n/a
294n/a @ignore_warning
295n/a def test_dot_new_with_str_key(self):
296n/a # Pass a key of type str, which is an error, because it expects a key
297n/a # of type bytes
298n/a with self.assertRaises(TypeError):
299n/a h = hmac.new("key")
300n/a
301n/a @ignore_warning
302n/a def test_withtext(self):
303n/a # Constructor call with text.
304n/a try:
305n/a h = hmac.HMAC(b"key", b"hash this!")
306n/a except Exception:
307n/a self.fail("Constructor call with text argument raised exception.")
308n/a self.assertEqual(h.hexdigest(), '34325b639da4cfd95735b381e28cb864')
309n/a
310n/a def test_with_bytearray(self):
311n/a try:
312n/a h = hmac.HMAC(bytearray(b"key"), bytearray(b"hash this!"),
313n/a digestmod="md5")
314n/a except Exception:
315n/a self.fail("Constructor call with bytearray arguments raised exception.")
316n/a self.assertEqual(h.hexdigest(), '34325b639da4cfd95735b381e28cb864')
317n/a
318n/a def test_with_memoryview_msg(self):
319n/a try:
320n/a h = hmac.HMAC(b"key", memoryview(b"hash this!"), digestmod="md5")
321n/a except Exception:
322n/a self.fail("Constructor call with memoryview msg raised exception.")
323n/a self.assertEqual(h.hexdigest(), '34325b639da4cfd95735b381e28cb864')
324n/a
325n/a def test_withmodule(self):
326n/a # Constructor call with text and digest module.
327n/a try:
328n/a h = hmac.HMAC(b"key", b"", hashlib.sha1)
329n/a except Exception:
330n/a self.fail("Constructor call with hashlib.sha1 raised exception.")
331n/a
332n/aclass SanityTestCase(unittest.TestCase):
333n/a
334n/a @ignore_warning
335n/a def test_default_is_md5(self):
336n/a # Testing if HMAC defaults to MD5 algorithm.
337n/a # NOTE: this whitebox test depends on the hmac class internals
338n/a h = hmac.HMAC(b"key")
339n/a self.assertEqual(h.digest_cons, hashlib.md5)
340n/a
341n/a def test_exercise_all_methods(self):
342n/a # Exercising all methods once.
343n/a # This must not raise any exceptions
344n/a try:
345n/a h = hmac.HMAC(b"my secret key", digestmod="md5")
346n/a h.update(b"compute the hash of this text!")
347n/a dig = h.digest()
348n/a dig = h.hexdigest()
349n/a h2 = h.copy()
350n/a except Exception:
351n/a self.fail("Exception raised during normal usage of HMAC class.")
352n/a
353n/aclass CopyTestCase(unittest.TestCase):
354n/a
355n/a def test_attributes(self):
356n/a # Testing if attributes are of same type.
357n/a h1 = hmac.HMAC(b"key", digestmod="md5")
358n/a h2 = h1.copy()
359n/a self.assertTrue(h1.digest_cons == h2.digest_cons,
360n/a "digest constructors don't match.")
361n/a self.assertEqual(type(h1.inner), type(h2.inner),
362n/a "Types of inner don't match.")
363n/a self.assertEqual(type(h1.outer), type(h2.outer),
364n/a "Types of outer don't match.")
365n/a
366n/a def test_realcopy(self):
367n/a # Testing if the copy method created a real copy.
368n/a h1 = hmac.HMAC(b"key", digestmod="md5")
369n/a h2 = h1.copy()
370n/a # Using id() in case somebody has overridden __eq__/__ne__.
371n/a self.assertTrue(id(h1) != id(h2), "No real copy of the HMAC instance.")
372n/a self.assertTrue(id(h1.inner) != id(h2.inner),
373n/a "No real copy of the attribute 'inner'.")
374n/a self.assertTrue(id(h1.outer) != id(h2.outer),
375n/a "No real copy of the attribute 'outer'.")
376n/a
377n/a def test_equality(self):
378n/a # Testing if the copy has the same digests.
379n/a h1 = hmac.HMAC(b"key", digestmod="md5")
380n/a h1.update(b"some random text")
381n/a h2 = h1.copy()
382n/a self.assertEqual(h1.digest(), h2.digest(),
383n/a "Digest of copy doesn't match original digest.")
384n/a self.assertEqual(h1.hexdigest(), h2.hexdigest(),
385n/a "Hexdigest of copy doesn't match original hexdigest.")
386n/a
387n/aclass CompareDigestTestCase(unittest.TestCase):
388n/a
389n/a def test_compare_digest(self):
390n/a # Testing input type exception handling
391n/a a, b = 100, 200
392n/a self.assertRaises(TypeError, hmac.compare_digest, a, b)
393n/a a, b = 100, b"foobar"
394n/a self.assertRaises(TypeError, hmac.compare_digest, a, b)
395n/a a, b = b"foobar", 200
396n/a self.assertRaises(TypeError, hmac.compare_digest, a, b)
397n/a a, b = "foobar", b"foobar"
398n/a self.assertRaises(TypeError, hmac.compare_digest, a, b)
399n/a a, b = b"foobar", "foobar"
400n/a self.assertRaises(TypeError, hmac.compare_digest, a, b)
401n/a
402n/a # Testing bytes of different lengths
403n/a a, b = b"foobar", b"foo"
404n/a self.assertFalse(hmac.compare_digest(a, b))
405n/a a, b = b"\xde\xad\xbe\xef", b"\xde\xad"
406n/a self.assertFalse(hmac.compare_digest(a, b))
407n/a
408n/a # Testing bytes of same lengths, different values
409n/a a, b = b"foobar", b"foobaz"
410n/a self.assertFalse(hmac.compare_digest(a, b))
411n/a a, b = b"\xde\xad\xbe\xef", b"\xab\xad\x1d\xea"
412n/a self.assertFalse(hmac.compare_digest(a, b))
413n/a
414n/a # Testing bytes of same lengths, same values
415n/a a, b = b"foobar", b"foobar"
416n/a self.assertTrue(hmac.compare_digest(a, b))
417n/a a, b = b"\xde\xad\xbe\xef", b"\xde\xad\xbe\xef"
418n/a self.assertTrue(hmac.compare_digest(a, b))
419n/a
420n/a # Testing bytearrays of same lengths, same values
421n/a a, b = bytearray(b"foobar"), bytearray(b"foobar")
422n/a self.assertTrue(hmac.compare_digest(a, b))
423n/a
424n/a # Testing bytearrays of diffeent lengths
425n/a a, b = bytearray(b"foobar"), bytearray(b"foo")
426n/a self.assertFalse(hmac.compare_digest(a, b))
427n/a
428n/a # Testing bytearrays of same lengths, different values
429n/a a, b = bytearray(b"foobar"), bytearray(b"foobaz")
430n/a self.assertFalse(hmac.compare_digest(a, b))
431n/a
432n/a # Testing byte and bytearray of same lengths, same values
433n/a a, b = bytearray(b"foobar"), b"foobar"
434n/a self.assertTrue(hmac.compare_digest(a, b))
435n/a self.assertTrue(hmac.compare_digest(b, a))
436n/a
437n/a # Testing byte bytearray of diffeent lengths
438n/a a, b = bytearray(b"foobar"), b"foo"
439n/a self.assertFalse(hmac.compare_digest(a, b))
440n/a self.assertFalse(hmac.compare_digest(b, a))
441n/a
442n/a # Testing byte and bytearray of same lengths, different values
443n/a a, b = bytearray(b"foobar"), b"foobaz"
444n/a self.assertFalse(hmac.compare_digest(a, b))
445n/a self.assertFalse(hmac.compare_digest(b, a))
446n/a
447n/a # Testing str of same lengths
448n/a a, b = "foobar", "foobar"
449n/a self.assertTrue(hmac.compare_digest(a, b))
450n/a
451n/a # Testing str of diffeent lengths
452n/a a, b = "foo", "foobar"
453n/a self.assertFalse(hmac.compare_digest(a, b))
454n/a
455n/a # Testing bytes of same lengths, different values
456n/a a, b = "foobar", "foobaz"
457n/a self.assertFalse(hmac.compare_digest(a, b))
458n/a
459n/a # Testing error cases
460n/a a, b = "foobar", b"foobar"
461n/a self.assertRaises(TypeError, hmac.compare_digest, a, b)
462n/a a, b = b"foobar", "foobar"
463n/a self.assertRaises(TypeError, hmac.compare_digest, a, b)
464n/a a, b = b"foobar", 1
465n/a self.assertRaises(TypeError, hmac.compare_digest, a, b)
466n/a a, b = 100, 200
467n/a self.assertRaises(TypeError, hmac.compare_digest, a, b)
468n/a a, b = "fooä", "fooä"
469n/a self.assertRaises(TypeError, hmac.compare_digest, a, b)
470n/a
471n/a # subclasses are supported by ignore __eq__
472n/a class mystr(str):
473n/a def __eq__(self, other):
474n/a return False
475n/a
476n/a a, b = mystr("foobar"), mystr("foobar")
477n/a self.assertTrue(hmac.compare_digest(a, b))
478n/a a, b = mystr("foobar"), "foobar"
479n/a self.assertTrue(hmac.compare_digest(a, b))
480n/a a, b = mystr("foobar"), mystr("foobaz")
481n/a self.assertFalse(hmac.compare_digest(a, b))
482n/a
483n/a class mybytes(bytes):
484n/a def __eq__(self, other):
485n/a return False
486n/a
487n/a a, b = mybytes(b"foobar"), mybytes(b"foobar")
488n/a self.assertTrue(hmac.compare_digest(a, b))
489n/a a, b = mybytes(b"foobar"), b"foobar"
490n/a self.assertTrue(hmac.compare_digest(a, b))
491n/a a, b = mybytes(b"foobar"), mybytes(b"foobaz")
492n/a self.assertFalse(hmac.compare_digest(a, b))
493n/a
494n/a
495n/aif __name__ == "__main__":
496n/a unittest.main()