Debian Codegraph @

Lib/test/test_hmac.py

raw
1 """Test suite for HMAC.
2
3 Python provides three different implementations of HMAC:
4
5 - OpenSSL HMAC using OpenSSL hash functions.
6 - HACL* HMAC using HACL* hash functions.
7 - Generic Python HMAC using user-defined hash functions.
8
9 The generic Python HMAC implementation is able to use OpenSSL
10 callables or names, HACL* named hash functions or arbitrary
11 objects implementing PEP 247 interface.
12
13 In the two first cases, Python HMAC wraps a C HMAC object (either OpenSSL
14 or HACL*-based). As a last resort, HMAC is re-implemented in pure Python.
15 It is however interesting to test the pure Python implementation against
16 the OpenSSL and HACL* hash functions.
17 """
18
19 import binascii
20 import functools
21 import hmac
22 import hashlib
23 import random
24 import types
25 import unittest
26 import warnings
27 from _operator import _compare_digest as operator_compare_digest
28 from test.support import _4G, bigmemtest
29 from test.support import check_disallow_instantiation
30 from test.support import hashlib_helper, import_helper
31 from test.support.hashlib_helper import (
32 BuiltinHashFunctionsTrait,
33 HashFunctionsTrait,
34 NamedHashFunctionsTrait,
35 OpenSSLHashFunctionsTrait,
36 )
37 from test.support.import_helper import import_fresh_module
38 from unittest.mock import patch
39
40 try:
41 import _hashlib
42 from _hashlib import compare_digest as openssl_compare_digest
43 except ImportError:
44 _hashlib = None
45 openssl_compare_digest = None
46
47 try:
48 import _sha2 as sha2
49 except ImportError:
50 sha2 = None
51
52
53 def requires_builtin_sha2():
54 return unittest.skipIf(sha2 is None, "requires _sha2")
55
56
57 class ModuleMixin:
58 """Mixin with a HMAC module implementation."""
59
60 hmac = None
61
62
63 class PyModuleMixin(ModuleMixin):
64 """Pure Python implementation of HMAC.
65
66 The underlying hash functions may be OpenSSL-based or HACL* based,
67 depending on whether OpenSSL is present or not.
68 """
69
70 @classmethod
71 def setUpClass(cls):
72 super().setUpClass()
73 cls.hmac = import_fresh_module('hmac', blocked=['_hashlib', '_hmac'])
74
75
76 @hashlib_helper.requires_builtin_hmac()
77 class BuiltinModuleMixin(ModuleMixin):
78 """Built-in HACL* implementation of HMAC."""
79
80 @classmethod
81 def setUpClass(cls):
82 super().setUpClass()
83 cls.hmac = import_fresh_module('_hmac')
84
85
86 # Sentinel object used to detect whether a digestmod is given or not.
87 DIGESTMOD_SENTINEL = object()
88
89
90 class CreatorMixin:
91 """Mixin exposing a method creating a HMAC object."""
92
93 def hmac_new(self, key, msg=None, digestmod=DIGESTMOD_SENTINEL):
94 """Create a new HMAC object.
95
96 Implementations should accept arbitrary 'digestmod' as this
97 method can be used to test which exceptions are being raised.
98 """
99 raise NotImplementedError
100
101 def bind_hmac_new(self, digestmod):
102 """Return a specialization of hmac_new() with a bound digestmod."""
103 return functools.partial(self.hmac_new, digestmod=digestmod)
104
105
106 class DigestMixin:
107 """Mixin exposing a method computing a HMAC digest."""
108
109 def hmac_digest(self, key, msg=None, digestmod=DIGESTMOD_SENTINEL):
110 """Compute a HMAC digest.
111
112 Implementations should accept arbitrary 'digestmod' as this
113 method can be used to test which exceptions are being raised.
114 """
115 raise NotImplementedError
116
117 def bind_hmac_digest(self, digestmod):
118 """Return a specialization of hmac_digest() with a bound digestmod."""
119 return functools.partial(self.hmac_digest, digestmod=digestmod)
120
121
122 def _call_newobj_func(new_func, key, msg, digestmod):
123 if digestmod is DIGESTMOD_SENTINEL: # to test when digestmod is missing
124 return new_func(key, msg) # expected to raise
125 # functions creating HMAC objects take a 'digestmod' keyword argument
126 return new_func(key, msg, digestmod=digestmod)
127
128
129 def _call_digest_func(digest_func, key, msg, digestmod):
130 if digestmod is DIGESTMOD_SENTINEL: # to test when digestmod is missing
131 return digest_func(key, msg) # expected to raise
132 # functions directly computing digests take a 'digest' keyword argument
133 return digest_func(key, msg, digest=digestmod)
134
135
136 class ThroughObjectMixin(ModuleMixin, CreatorMixin, DigestMixin):
137 """Mixin delegating to <module>.HMAC() and <module>.HMAC(...).digest().
138
139 Both the C implementation and the Python implementation of HMAC should
140 expose a HMAC class with the same functionalities.
141 """
142
143 def hmac_new(self, key, msg=None, digestmod=DIGESTMOD_SENTINEL):
144 """Create a HMAC object via a module-level class constructor."""
145 return _call_newobj_func(self.hmac.HMAC, key, msg, digestmod)
146
147 def hmac_digest(self, key, msg=None, digestmod=DIGESTMOD_SENTINEL):
148 """Call the digest() method on a HMAC object obtained by hmac_new()."""
149 return _call_newobj_func(self.hmac_new, key, msg, digestmod).digest()
150
151
152 class ThroughModuleAPIMixin(ModuleMixin, CreatorMixin, DigestMixin):
153 """Mixin delegating to <module>.new() and <module>.digest()."""
154
155 def hmac_new(self, key, msg=None, digestmod=DIGESTMOD_SENTINEL):
156 """Create a HMAC object via a module-level function."""
157 return _call_newobj_func(self.hmac.new, key, msg, digestmod)
158
159 def hmac_digest(self, key, msg=None, digestmod=DIGESTMOD_SENTINEL):
160 """One-shot HMAC digest computation."""
161 return _call_digest_func(self.hmac.digest, key, msg, digestmod)
162
163
164 @hashlib_helper.requires_hashlib()
165 class ThroughOpenSSLAPIMixin(CreatorMixin, DigestMixin):
166 """Mixin delegating to _hashlib.hmac_new() and _hashlib.hmac_digest()."""
167
168 def hmac_new(self, key, msg=None, digestmod=DIGESTMOD_SENTINEL):
169 return _call_newobj_func(_hashlib.hmac_new, key, msg, digestmod)
170
171 def hmac_digest(self, key, msg=None, digestmod=DIGESTMOD_SENTINEL):
172 return _call_digest_func(_hashlib.hmac_digest, key, msg, digestmod)
173
174
175 class ThroughBuiltinAPIMixin(BuiltinModuleMixin, CreatorMixin, DigestMixin):
176 """Mixin delegating to _hmac.new() and _hmac.compute_digest()."""
177
178 def hmac_new(self, key, msg=None, digestmod=DIGESTMOD_SENTINEL):
179 return _call_newobj_func(self.hmac.new, key, msg, digestmod)
180
181 def hmac_digest(self, key, msg=None, digestmod=DIGESTMOD_SENTINEL):
182 return _call_digest_func(self.hmac.compute_digest, key, msg, digestmod)
183
184
185 class ObjectCheckerMixin:
186 """Mixin for checking HMAC objects (pure Python, OpenSSL or built-in)."""
187
188 def check_object(self, h, hexdigest, hashname, digest_size, block_size):
189 """Check a HMAC object 'h' against the given values."""
190 self.check_internals(h, hashname, digest_size, block_size)
191 self.check_hexdigest(h, hexdigest, digest_size)
192
193 def check_internals(self, h, hashname, digest_size, block_size):
194 """Check the constant attributes of a HMAC object."""
195 self.assertEqual(h.name, f"hmac-{hashname}")
196 self.assertEqual(h.digest_size, digest_size)
197 self.assertEqual(h.block_size, block_size)
198
199 def check_hexdigest(self, h, hexdigest, digest_size):
200 """Check the HMAC digest of 'h' and its size."""
201 self.assertEqual(len(h.digest()), digest_size)
202 self.assertEqual(h.digest(), binascii.unhexlify(hexdigest))
203 self.assertEqual(h.hexdigest().upper(), hexdigest.upper())
204
205
206 class AssertersMixin(CreatorMixin, DigestMixin, ObjectCheckerMixin):
207 """Mixin class for common tests."""
208
209 def hmac_new_by_name(self, key, msg=None, *, hashname):
210 """Alternative implementation of hmac_new().
211
212 This is typically useful when one needs to test against an HMAC
213 implementation which only recognizes underlying hash functions
214 by their name (all HMAC implementations must at least recognize
215 hash functions by their names but some may use aliases such as
216 `hashlib.sha1` instead of "sha1").
217
218 Unlike hmac_new(), this method may assert the type of 'hashname'
219 as it should only be used in tests that are expected to create
220 a HMAC object.
221 """
222 self.assertIsInstance(hashname, str)
223 return self.hmac_new(key, msg, digestmod=hashname)
224
225 def hmac_digest_by_name(self, key, msg=None, *, hashname):
226 """Alternative implementation of hmac_digest().
227
228 Unlike hmac_digest(), this method may assert the type of 'hashname'
229 as it should only be used in tests that are expected to compute a
230 HMAC digest.
231 """
232 self.assertIsInstance(hashname, str)
233 return self.hmac_digest(key, msg, digestmod=hashname)
234
235 def assert_hmac(
236 self, key, msg, hexdigest, hashfunc, hashname, digest_size, block_size
237 ):
238 """Check that HMAC(key, msg) == digest.
239
240 The 'hashfunc' and 'hashname' are used as 'digestmod' values,
241 thereby allowing to test the underlying dispatching mechanism.
242
243 Note that 'hashfunc' may be a string, a callable, or a PEP-257
244 module. Note that not all HMAC implementations may recognize the
245 same set of types for 'hashfunc', but they should always accept
246 a hash function by its name.
247 """
248 if hashfunc == hashname:
249 choices = [hashname]
250 else:
251 choices = [hashfunc, hashname]
252
253 for digestmod in choices:
254 with self.subTest(digestmod=digestmod):
255 self.assert_hmac_new(
256 key, msg, hexdigest, digestmod,
257 hashname, digest_size, block_size
258 )
259 self.assert_hmac_hexdigest(
260 key, msg, hexdigest, digestmod, digest_size
261 )
262 self.assert_hmac_common_cases(
263 key, msg, hexdigest, digestmod,
264 hashname, digest_size, block_size
265 )
266 self.assert_hmac_extra_cases(
267 key, msg, hexdigest, digestmod,
268 hashname, digest_size, block_size
269 )
270
271 self.assert_hmac_new_by_name(
272 key, msg, hexdigest, hashname, digest_size, block_size
273 )
274 self.assert_hmac_hexdigest_by_name(
275 key, msg, hexdigest, hashname, digest_size
276 )
277
278 def assert_hmac_new(
279 self, key, msg, hexdigest, digestmod, hashname, digest_size, block_size
280 ):
281 """Check that HMAC(key, msg) == digest.
282
283 This test uses the `hmac_new()` method to create HMAC objects.
284 """
285 self.check_hmac_new(
286 key, msg, hexdigest, hashname, digest_size, block_size,
287 hmac_new_func=self.hmac_new,
288 hmac_new_kwds={'digestmod': digestmod},
289 )
290
291 def assert_hmac_new_by_name(
292 self, key, msg, hexdigest, hashname, digest_size, block_size
293 ):
294 """Check that HMAC(key, msg) == digest.
295
296 This test uses the `hmac_new_by_name()` method to create HMAC objects.
297 """
298 self.check_hmac_new(
299 key, msg, hexdigest, hashname, digest_size, block_size,
300 hmac_new_func=self.hmac_new_by_name,
301 hmac_new_kwds={'hashname': hashname},
302 )
303
304 def check_hmac_new(
305 self, key, msg, hexdigest, hashname, digest_size, block_size,
306 hmac_new_func, hmac_new_kwds=types.MappingProxyType({}),
307 ):
308 """Check that HMAC(key, msg) == digest.
309
310 This also tests that using an empty/None initial message and
311 then calling `h.update(msg)` produces the same result, namely
312 that HMAC(key, msg) is equivalent to HMAC(key).update(msg).
313 """
314 h = hmac_new_func(key, msg, **hmac_new_kwds)
315 self.check_object(h, hexdigest, hashname, digest_size, block_size)
316
317 def hmac_new_feed(*args):
318 h = hmac_new_func(key, *args, **hmac_new_kwds)
319 h.update(msg)
320 self.check_hexdigest(h, hexdigest, digest_size)
321
322 with self.subTest('no initial message'):
323 hmac_new_feed()
324 with self.subTest('initial message is empty'):
325 hmac_new_feed(b'')
326 with self.subTest('initial message is None'):
327 hmac_new_feed(None)
328
329 def assert_hmac_hexdigest(
330 self, key, msg, hexdigest, digestmod, digest_size,
331 ):
332 """Check a HMAC digest computed by hmac_digest()."""
333 self.check_hmac_hexdigest(
334 key, msg, hexdigest, digest_size,
335 hmac_digest_func=self.hmac_digest,
336 hmac_digest_kwds={'digestmod': digestmod},
337 )
338
339 def assert_hmac_hexdigest_by_name(
340 self, key, msg, hexdigest, hashname, digest_size
341 ):
342 """Check a HMAC digest computed by hmac_digest_by_name()."""
343 self.assertIsInstance(hashname, str)
344 self.check_hmac_hexdigest(
345 key, msg, hexdigest, digest_size,
346 hmac_digest_func=self.hmac_digest_by_name,
347 hmac_digest_kwds={'hashname': hashname},
348 )
349
350 def check_hmac_hexdigest(
351 self, key, msg, hexdigest, digest_size,
352 hmac_digest_func, hmac_digest_kwds=types.MappingProxyType({}),
353 ):
354 """Check and return a HMAC digest computed by hmac_digest_func().
355
356 This HMAC digest is computed by:
357
358 hmac_digest_func(key, msg, **hmac_digest_kwds)
359
360 This is typically useful for checking one-shot HMAC functions.
361 """
362 d = hmac_digest_func(key, msg, **hmac_digest_kwds)
363 self.assertEqual(len(d), digest_size)
364 self.assertEqual(d, binascii.unhexlify(hexdigest))
365 return d
366
367 def assert_hmac_common_cases(
368 self, key, msg, hexdigest, digestmod, hashname, digest_size, block_size
369 ):
370 """Common tests executed by all subclasses."""
371 h1 = self.hmac_new_by_name(key, hashname=hashname)
372 h2 = h1.copy()
373 h2.update(b"test update should not affect original")
374 h1.update(msg)
375 self.check_object(h1, hexdigest, hashname, digest_size, block_size)
376
377 def assert_hmac_extra_cases(
378 self, key, msg, hexdigest, digestmod, hashname, digest_size, block_size
379 ):
380 """Extra tests that can be added in subclasses."""
381
382
383 class PyAssertersMixin(PyModuleMixin, AssertersMixin):
384
385 def assert_hmac_extra_cases(
386 self, key, msg, hexdigest, digestmod, hashname, digest_size, block_size
387 ):
388 h = self.hmac.HMAC.__new__(self.hmac.HMAC)
389 h._init_old(key, msg, digestmod=digestmod)
390 self.check_object(h, hexdigest, hashname, digest_size, block_size)
391
392
393 class OpenSSLAssertersMixin(ThroughOpenSSLAPIMixin, AssertersMixin):
394
395 def hmac_new_by_name(self, key, msg=None, *, hashname):
396 self.assertIsInstance(hashname, str)
397 openssl_func = getattr(_hashlib, f"openssl_{hashname}")
398 return self.hmac_new(key, msg, digestmod=openssl_func)
399
400 def hmac_digest_by_name(self, key, msg=None, *, hashname):
401 self.assertIsInstance(hashname, str)
402 openssl_func = getattr(_hashlib, f"openssl_{hashname}")
403 return self.hmac_digest(key, msg, digestmod=openssl_func)
404
405
406 class BuiltinAssertersMixin(ThroughBuiltinAPIMixin, AssertersMixin):
407 pass
408
409
410 class RFCTestCaseMixin(HashFunctionsTrait, AssertersMixin):
411 """Test HMAC implementations against RFC 2202/4231 and NIST test vectors.
412
413 - Test vectors for MD5 and SHA-1 are taken from RFC 2202.
414 - Test vectors for SHA-2 are taken from RFC 4231.
415 - Test vectors for SHA-3 are NIST's test vectors [1].
416
417 [1] https://csrc.nist.gov/projects/message-authentication-codes
418 """
419
420 def test_md5_rfc2202(self):
421 def md5test(key, msg, hexdigest):
422 self.assert_hmac(key, msg, hexdigest, self.md5, "md5", 16, 64)
423
424 md5test(b"\x0b" * 16,
425 b"Hi There",
426 "9294727a3638bb1c13f48ef8158bfc9d")
427
428 md5test(b"Jefe",
429 b"what do ya want for nothing?",
430 "750c783e6ab0b503eaa86e310a5db738")
431
432 md5test(b"\xaa" * 16,
433 b"\xdd" * 50,
434 "56be34521d144c88dbb8c733f0e8b3f6")
435
436 md5test(bytes(range(1, 26)),
437 b"\xcd" * 50,
438 "697eaf0aca3a3aea3a75164746ffaa79")
439
440 md5test(b"\x0C" * 16,
441 b"Test With Truncation",
442 "56461ef2342edc00f9bab995690efd4c")
443
444 md5test(b"\xaa" * 80,
445 b"Test Using Larger Than Block-Size Key - Hash Key First",
446 "6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd")
447
448 md5test(b"\xaa" * 80,
449 (b"Test Using Larger Than Block-Size Key "
450 b"and Larger Than One Block-Size Data"),
451 "6f630fad67cda0ee1fb1f562db3aa53e")
452
453 def test_sha1_rfc2202(self):
454 def shatest(key, msg, hexdigest):
455 self.assert_hmac(key, msg, hexdigest, self.sha1, "sha1", 20, 64)
456
457 shatest(b"\x0b" * 20,
458 b"Hi There",
459 "b617318655057264e28bc0b6fb378c8ef146be00")
460
461 shatest(b"Jefe",
462 b"what do ya want for nothing?",
463 "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79")
464
465 shatest(b"\xAA" * 20,
466 b"\xDD" * 50,
467 "125d7342b9ac11cd91a39af48aa17b4f63f175d3")
468
469 shatest(bytes(range(1, 26)),
470 b"\xCD" * 50,
471 "4c9007f4026250c6bc8414f9bf50c86c2d7235da")
472
473 shatest(b"\x0C" * 20,
474 b"Test With Truncation",
475 "4c1a03424b55e07fe7f27be1d58bb9324a9a5a04")
476
477 shatest(b"\xAA" * 80,
478 b"Test Using Larger Than Block-Size Key - Hash Key First",
479 "aa4ae5e15272d00e95705637ce8a3b55ed402112")
480
481 shatest(b"\xAA" * 80,
482 (b"Test Using Larger Than Block-Size Key "
483 b"and Larger Than One Block-Size Data"),
484 "e8e99d0f45237d786d6bbaa7965c7808bbff1a91")
485
486 def test_sha2_224_rfc4231(self):
487 self._test_sha2_rfc4231(self.sha224, 'sha224', 28, 64)
488
489 def test_sha2_256_rfc4231(self):
490 self._test_sha2_rfc4231(self.sha256, 'sha256', 32, 64)
491
492 def test_sha2_384_rfc4231(self):
493 self._test_sha2_rfc4231(self.sha384, 'sha384', 48, 128)
494
495 def test_sha2_512_rfc4231(self):
496 self._test_sha2_rfc4231(self.sha512, 'sha512', 64, 128)
497
498 def _test_sha2_rfc4231(self, hashfunc, hashname, digest_size, block_size):
499 def hmactest(key, msg, hexdigests):
500 hexdigest = hexdigests[hashname]
501
502 self.assert_hmac(
503 key, msg, hexdigest,
504 hashfunc=hashfunc,
505 hashname=hashname,
506 digest_size=digest_size,
507 block_size=block_size
508 )
509
510 # 4.2. Test Case 1
511 hmactest(key=b'\x0b' * 20,
512 msg=b'Hi There',
513 hexdigests={
514 'sha224': '896fb1128abbdf196832107cd49df33f'
515 '47b4b1169912ba4f53684b22',
516 'sha256': 'b0344c61d8db38535ca8afceaf0bf12b'
517 '881dc200c9833da726e9376c2e32cff7',
518 'sha384': 'afd03944d84895626b0825f4ab46907f'
519 '15f9dadbe4101ec682aa034c7cebc59c'
520 'faea9ea9076ede7f4af152e8b2fa9cb6',
521 'sha512': '87aa7cdea5ef619d4ff0b4241a1d6cb0'
522 '2379f4e2ce4ec2787ad0b30545e17cde'
523 'daa833b7d6b8a702038b274eaea3f4e4'
524 'be9d914eeb61f1702e696c203a126854',
525 })
526
527 # 4.3. Test Case 2
528 hmactest(key=b'Jefe',
529 msg=b'what do ya want for nothing?',
530 hexdigests={
531 'sha224': 'a30e01098bc6dbbf45690f3a7e9e6d0f'
532 '8bbea2a39e6148008fd05e44',
533 'sha256': '5bdcc146bf60754e6a042426089575c7'
534 '5a003f089d2739839dec58b964ec3843',
535 'sha384': 'af45d2e376484031617f78d2b58a6b1b'
536 '9c7ef464f5a01b47e42ec3736322445e'
537 '8e2240ca5e69e2c78b3239ecfab21649',
538 'sha512': '164b7a7bfcf819e2e395fbe73b56e0a3'
539 '87bd64222e831fd610270cd7ea250554'
540 '9758bf75c05a994a6d034f65f8f0e6fd'
541 'caeab1a34d4a6b4b636e070a38bce737',
542 })
543
544 # 4.4. Test Case 3
545 hmactest(key=b'\xaa' * 20,
546 msg=b'\xdd' * 50,
547 hexdigests={
548 'sha224': '7fb3cb3588c6c1f6ffa9694d7d6ad264'
549 '9365b0c1f65d69d1ec8333ea',
550 'sha256': '773ea91e36800e46854db8ebd09181a7'
551 '2959098b3ef8c122d9635514ced565fe',
552 'sha384': '88062608d3e6ad8a0aa2ace014c8a86f'
553 '0aa635d947ac9febe83ef4e55966144b'
554 '2a5ab39dc13814b94e3ab6e101a34f27',
555 'sha512': 'fa73b0089d56a284efb0f0756c890be9'
556 'b1b5dbdd8ee81a3655f83e33b2279d39'
557 'bf3e848279a722c806b485a47e67c807'
558 'b946a337bee8942674278859e13292fb',
559 })
560
561 # 4.5. Test Case 4
562 hmactest(key=bytes(x for x in range(0x01, 0x19 + 1)),
563 msg=b'\xcd' * 50,
564 hexdigests={
565 'sha224': '6c11506874013cac6a2abc1bb382627c'
566 'ec6a90d86efc012de7afec5a',
567 'sha256': '82558a389a443c0ea4cc819899f2083a'
568 '85f0faa3e578f8077a2e3ff46729665b',
569 'sha384': '3e8a69b7783c25851933ab6290af6ca7'
570 '7a9981480850009cc5577c6e1f573b4e'
571 '6801dd23c4a7d679ccf8a386c674cffb',
572 'sha512': 'b0ba465637458c6990e5a8c5f61d4af7'
573 'e576d97ff94b872de76f8050361ee3db'
574 'a91ca5c11aa25eb4d679275cc5788063'
575 'a5f19741120c4f2de2adebeb10a298dd',
576 })
577
578 # 4.7. Test Case 6
579 hmactest(key=b'\xaa' * 131,
580 msg=b'Test Using Larger Than Block-Siz'
581 b'e Key - Hash Key First',
582 hexdigests={
583 'sha224': '95e9a0db962095adaebe9b2d6f0dbce2'
584 'd499f112f2d2b7273fa6870e',
585 'sha256': '60e431591ee0b67f0d8a26aacbf5b77f'
586 '8e0bc6213728c5140546040f0ee37f54',
587 'sha384': '4ece084485813e9088d2c63a041bc5b4'
588 '4f9ef1012a2b588f3cd11f05033ac4c6'
589 '0c2ef6ab4030fe8296248df163f44952',
590 'sha512': '80b24263c7c1a3ebb71493c1dd7be8b4'
591 '9b46d1f41b4aeec1121b013783f8f352'
592 '6b56d037e05f2598bd0fd2215d6a1e52'
593 '95e64f73f63f0aec8b915a985d786598',
594 })
595
596 # 4.8. Test Case 7
597 hmactest(key=b'\xaa' * 131,
598 msg=b'This is a test using a larger th'
599 b'an block-size key and a larger t'
600 b'han block-size data. The key nee'
601 b'ds to be hashed before being use'
602 b'd by the HMAC algorithm.',
603 hexdigests={
604 'sha224': '3a854166ac5d9f023f54d517d0b39dbd'
605 '946770db9c2b95c9f6f565d1',
606 'sha256': '9b09ffa71b942fcb27635fbcd5b0e944'
607 'bfdc63644f0713938a7f51535c3a35e2',
608 'sha384': '6617178e941f020d351e2f254e8fd32c'
609 '602420feb0b8fb9adccebb82461e99c5'
610 'a678cc31e799176d3860e6110c46523e',
611 'sha512': 'e37b6a775dc87dbaa4dfa9f96e5e3ffd'
612 'debd71f8867289865df5a32d20cdc944'
613 'b6022cac3c4982b10d5eeb55c3e4de15'
614 '134676fb6de0446065c97440fa8c6a58',
615 })
616
617 def test_sha3_224_nist(self):
618 for key, msg, hexdigest in [
619 (
620 bytes(range(28)),
621 b'Sample message for keylen<blocklen',
622 '332cfd59347fdb8e576e77260be4aba2d6dc53117b3bfb52c6d18c04'
623 ), (
624 bytes(range(144)),
625 b'Sample message for keylen=blocklen',
626 'd8b733bcf66c644a12323d564e24dcf3fc75f231f3b67968359100c7'
627 ), (
628 bytes(range(172)),
629 b'Sample message for keylen>blocklen',
630 '078695eecc227c636ad31d063a15dd05a7e819a66ec6d8de1e193e59'
631 )
632 ]:
633 self.assert_hmac(
634 key, msg, hexdigest,
635 hashfunc=self.sha3_224, hashname='sha3_224',
636 digest_size=28, block_size=144
637 )
638
639 def test_sha3_256_nist(self):
640 for key, msg, hexdigest in [
641 (
642 bytes(range(32)),
643 b'Sample message for keylen<blocklen',
644 '4fe8e202c4f058e8dddc23d8c34e4673'
645 '43e23555e24fc2f025d598f558f67205'
646 ), (
647 bytes(range(136)),
648 b'Sample message for keylen=blocklen',
649 '68b94e2e538a9be4103bebb5aa016d47'
650 '961d4d1aa906061313b557f8af2c3faa'
651 ), (
652 bytes(range(168)),
653 b'Sample message for keylen>blocklen',
654 '9bcf2c238e235c3ce88404e813bd2f3a'
655 '97185ac6f238c63d6229a00b07974258'
656 )
657 ]:
658 self.assert_hmac(
659 key, msg, hexdigest,
660 hashfunc=self.sha3_256, hashname='sha3_256',
661 digest_size=32, block_size=136
662 )
663
664 def test_sha3_384_nist(self):
665 for key, msg, hexdigest in [
666 (
667 bytes(range(48)),
668 b'Sample message for keylen<blocklen',
669 'd588a3c51f3f2d906e8298c1199aa8ff'
670 '6296218127f6b38a90b6afe2c5617725'
671 'bc99987f79b22a557b6520db710b7f42'
672 ), (
673 bytes(range(104)),
674 b'Sample message for keylen=blocklen',
675 'a27d24b592e8c8cbf6d4ce6fc5bf62d8'
676 'fc98bf2d486640d9eb8099e24047837f'
677 '5f3bffbe92dcce90b4ed5b1e7e44fa90'
678 ), (
679 bytes(range(152)),
680 b'Sample message for keylen>blocklen',
681 'e5ae4c739f455279368ebf36d4f5354c'
682 '95aa184c899d3870e460ebc288ef1f94'
683 '70053f73f7c6da2a71bcaec38ce7d6ac'
684 )
685 ]:
686 self.assert_hmac(
687 key, msg, hexdigest,
688 hashfunc=self.sha3_384, hashname='sha3_384',
689 digest_size=48, block_size=104
690 )
691
692 def test_sha3_512_nist(self):
693 for key, msg, hexdigest in [
694 (
695 bytes(range(64)),
696 b'Sample message for keylen<blocklen',
697 '4efd629d6c71bf86162658f29943b1c3'
698 '08ce27cdfa6db0d9c3ce81763f9cbce5'
699 'f7ebe9868031db1a8f8eb7b6b95e5c5e'
700 '3f657a8996c86a2f6527e307f0213196'
701 ), (
702 bytes(range(72)),
703 b'Sample message for keylen=blocklen',
704 '544e257ea2a3e5ea19a590e6a24b724c'
705 'e6327757723fe2751b75bf007d80f6b3'
706 '60744bf1b7a88ea585f9765b47911976'
707 'd3191cf83c039f5ffab0d29cc9d9b6da'
708 ), (
709 bytes(range(136)),
710 b'Sample message for keylen>blocklen',
711 '5f464f5e5b7848e3885e49b2c385f069'
712 '4985d0e38966242dc4a5fe3fea4b37d4'
713 '6b65ceced5dcf59438dd840bab22269f'
714 '0ba7febdb9fcf74602a35666b2a32915'
715 )
716 ]:
717 self.assert_hmac(
718 key, msg, hexdigest,
719 hashfunc=self.sha3_512, hashname='sha3_512',
720 digest_size=64, block_size=72
721 )
722
723
724 class PurePythonInitHMAC(PyModuleMixin, HashFunctionsTrait):
725
726 @classmethod
727 def setUpClass(cls):
728 super().setUpClass()
729 for meth in ['_init_openssl_hmac', '_init_builtin_hmac']:
730 fn = getattr(cls.hmac.HMAC, meth)
731 cm = patch.object(cls.hmac.HMAC, meth, autospec=True, wraps=fn)
732 cls.enterClassContext(cm)
733
734 @classmethod
735 def tearDownClass(cls):
736 cls.hmac.HMAC._init_openssl_hmac.assert_not_called()
737 cls.hmac.HMAC._init_builtin_hmac.assert_not_called()
738 # Do not assert that HMAC._init_old() has been called as it's tricky
739 # to determine whether a test for a specific hash function has been
740 # executed or not. On regular builds, it will be called but if a
741 # hash function is not available, it's hard to detect for which
742 # test we should checj HMAC._init_old() or not.
743 super().tearDownClass()
744
745
746 class PyRFCOpenSSLTestCase(ThroughObjectMixin,
747 PyAssertersMixin,
748 OpenSSLHashFunctionsTrait,
749 RFCTestCaseMixin,
750 PurePythonInitHMAC,
751 unittest.TestCase):
752 """Python implementation of HMAC using hmac.HMAC().
753
754 The underlying hash functions are OpenSSL-based but
755 _init_old() is used instead of _init_openssl_hmac().
756 """
757
758
759 class PyRFCBuiltinTestCase(ThroughObjectMixin,
760 PyAssertersMixin,
761 BuiltinHashFunctionsTrait,
762 RFCTestCaseMixin,
763 PurePythonInitHMAC,
764 unittest.TestCase):
765 """Python implementation of HMAC using hmac.HMAC().
766
767 The underlying hash functions are HACL*-based but
768 _init_old() is used instead of _init_builtin_hmac().
769 """
770
771
772 class PyDotNewOpenSSLRFCTestCase(ThroughModuleAPIMixin,
773 PyAssertersMixin,
774 OpenSSLHashFunctionsTrait,
775 RFCTestCaseMixin,
776 PurePythonInitHMAC,
777 unittest.TestCase):
778 """Python implementation of HMAC using hmac.new().
779
780 The underlying hash functions are OpenSSL-based but
781 _init_old() is used instead of _init_openssl_hmac().
782 """
783
784
785 class PyDotNewBuiltinRFCTestCase(ThroughModuleAPIMixin,
786 PyAssertersMixin,
787 BuiltinHashFunctionsTrait,
788 RFCTestCaseMixin,
789 PurePythonInitHMAC,
790 unittest.TestCase):
791 """Python implementation of HMAC using hmac.new().
792
793 The underlying hash functions are HACL-based but
794 _init_old() is used instead of _init_openssl_hmac().
795 """
796
797
798 class OpenSSLRFCTestCase(OpenSSLAssertersMixin,
799 OpenSSLHashFunctionsTrait,
800 RFCTestCaseMixin,
801 unittest.TestCase):
802 """OpenSSL implementation of HMAC.
803
804 The underlying hash functions are also OpenSSL-based.
805 """
806
807
808 class BuiltinRFCTestCase(BuiltinAssertersMixin,
809 NamedHashFunctionsTrait,
810 RFCTestCaseMixin,
811 unittest.TestCase):
812 """Built-in HACL* implementation of HMAC.
813
814 The underlying hash functions are also HACL*-based.
815 """
816
817 def assert_hmac_extra_cases(
818 self, key, msg, hexdigest, digestmod, hashname, digest_size, block_size
819 ):
820 # assert one-shot HMAC at the same time
821 with self.subTest(key=key, msg=msg, hashname=hashname):
822 func = getattr(self.hmac, f'compute_{hashname}')
823 self.assertTrue(callable(func))
824 self.check_hmac_hexdigest(key, msg, hexdigest, digest_size, func)
825
826
827 class DigestModTestCaseMixin(CreatorMixin, DigestMixin):
828 """Tests for the 'digestmod' parameter for hmac_new() and hmac_digest()."""
829
830 def assert_raises_missing_digestmod(self):
831 """A context manager catching errors when a digestmod is missing."""
832 return self.assertRaisesRegex(TypeError,
833 "[M|m]issing.*required.*digestmod")
834
835 def assert_raises_unknown_digestmod(self):
836 """A context manager catching errors when a digestmod is unknown."""
837 return self.assertRaisesRegex(ValueError, "[Uu]nsupported.*")
838
839 def test_constructor_missing_digestmod(self):
840 catcher = self.assert_raises_missing_digestmod
841 self.do_test_constructor_missing_digestmod(catcher)
842
843 def test_constructor_unknown_digestmod(self):
844 catcher = self.assert_raises_unknown_digestmod
845 self.do_test_constructor_unknown_digestmod(catcher)
846
847 def do_test_constructor_missing_digestmod(self, catcher):
848 for func, args, kwds in self.cases_missing_digestmod_in_constructor():
849 with self.subTest(args=args, kwds=kwds), catcher():
850 func(*args, **kwds)
851
852 def do_test_constructor_unknown_digestmod(self, catcher):
853 for func, args, kwds in self.cases_unknown_digestmod_in_constructor():
854 with self.subTest(args=args, kwds=kwds), catcher():
855 func(*args, **kwds)
856
857 def cases_missing_digestmod_in_constructor(self):
858 raise NotImplementedError
859
860 def make_missing_digestmod_cases(self, func, missing_like=()):
861 """Generate cases for missing digestmod tests.
862
863 Only the Python implementation should consider "falsey" 'digestmod'
864 values as being equivalent to a missing one.
865 """
866 key, msg = b'unused key', b'unused msg'
867 choices = [DIGESTMOD_SENTINEL, *missing_like]
868 return self._invalid_digestmod_cases(func, key, msg, choices)
869
870 def cases_unknown_digestmod_in_constructor(self):
871 raise NotImplementedError
872
873 def make_unknown_digestmod_cases(self, func, bad_digestmods):
874 """Generate cases for unknown digestmod tests."""
875 key, msg = b'unused key', b'unused msg'
876 return self._invalid_digestmod_cases(func, key, msg, bad_digestmods)
877
878 def _invalid_digestmod_cases(self, func, key, msg, choices):
879 cases = []
880 for digestmod in choices:
881 kwargs = {'digestmod': digestmod}
882 cases.append((func, (key,), kwargs))
883 cases.append((func, (key, msg), kwargs))
884 cases.append((func, (key,), kwargs | {'msg': msg}))
885 return cases
886
887
888 class ConstructorTestCaseMixin(CreatorMixin, DigestMixin, ObjectCheckerMixin):
889 """HMAC constructor tests based on HMAC-SHA-2/256."""
890
891 key = b"key"
892 msg = b"hash this!"
893 res = "6c845b47f52b3b47f6590c502db7825aad757bf4fadc8fa972f7cd2e76a5bdeb"
894
895 def do_test_constructor(self, hmac_on_key_and_msg):
896 self.do_test_constructor_invalid_types(hmac_on_key_and_msg)
897 self.do_test_constructor_supported_types(hmac_on_key_and_msg)
898
899 def do_test_constructor_invalid_types(self, hmac_on_key_and_msg):
900 self.assertRaises(TypeError, hmac_on_key_and_msg, 1)
901 self.assertRaises(TypeError, hmac_on_key_and_msg, "key")
902
903 self.assertRaises(TypeError, hmac_on_key_and_msg, b"key", 1)
904 self.assertRaises(TypeError, hmac_on_key_and_msg, b"key", "msg")
905
906 def do_test_constructor_supported_types(self, hmac_on_key_and_msg):
907 for tp_key in [bytes, bytearray]:
908 for tp_msg in [bytes, bytearray, memoryview]:
909 with self.subTest(tp_key=tp_key, tp_msg=tp_msg):
910 h = hmac_on_key_and_msg(tp_key(self.key), tp_msg(self.msg))
911 self.assertEqual(h.name, "hmac-sha256")
912 self.assertEqual(h.hexdigest(), self.res)
913
914 @hashlib_helper.requires_hashdigest("sha256")
915 def test_constructor(self):
916 self.do_test_constructor(self.bind_hmac_new("sha256"))
917
918 @hashlib_helper.requires_hashdigest("sha256")
919 def test_digest(self):
920 digest = self.hmac_digest(self.key, self.msg, "sha256")
921 self.assertEqual(digest, binascii.unhexlify(self.res))
922
923
924 class PyConstructorBaseMixin(PyModuleMixin,
925 DigestModTestCaseMixin,
926 ConstructorTestCaseMixin):
927
928 def cases_missing_digestmod_in_constructor(self):
929 func, choices = self.hmac_new, ['', None, False]
930 return self.make_missing_digestmod_cases(func, choices)
931
932 def cases_unknown_digestmod_in_constructor(self):
933 func, choices = self.hmac_new, ['unknown']
934 return self.make_unknown_digestmod_cases(func, choices)
935
936 @requires_builtin_sha2()
937 def test_constructor_with_module(self):
938 self.do_test_constructor(self.bind_hmac_new(sha2.sha256))
939
940 @requires_builtin_sha2()
941 def test_digest_with_module(self):
942 digest = self.hmac_digest(self.key, self.msg, sha2.sha256)
943 self.assertEqual(digest, binascii.unhexlify(self.res))
944
945
946 class PyConstructorTestCase(ThroughObjectMixin, PyConstructorBaseMixin,
947 unittest.TestCase):
948 """Test the hmac.HMAC() pure Python constructor."""
949
950
951 class PyModuleConstructorTestCase(ThroughModuleAPIMixin, PyConstructorBaseMixin,
952 unittest.TestCase):
953 """Test the hmac.new() and hmac.digest() functions.
954
955 Note that "self.hmac" is imported by blocking "_hashlib" and "_hmac".
956 For testing functions in "hmac", extend PyMiscellaneousTests instead.
957 """
958
959 def test_hmac_digest_digestmod_parameter(self):
960 func = self.hmac_digest
961
962 def raiser():
963 raise RuntimeError("custom exception")
964
965 with self.assertRaisesRegex(RuntimeError, "custom exception"):
966 func(b'key', b'msg', raiser)
967
968 with self.assertRaisesRegex(ValueError, 'hash type'):
969 func(b'key', b'msg', 'unknown')
970
971 with self.assertRaisesRegex(AttributeError, 'new'):
972 func(b'key', b'msg', 1234)
973 with self.assertRaisesRegex(AttributeError, 'new'):
974 func(b'key', b'msg', None)
975
976
977 class ExtensionConstructorTestCaseMixin(DigestModTestCaseMixin,
978 ConstructorTestCaseMixin):
979
980 @property
981 def obj_type(self):
982 """The underlying (non-instantiable) C class."""
983 raise NotImplementedError
984
985 @property
986 def exc_type(self):
987 """The exact exception class raised upon invalid 'digestmod' values."""
988 raise NotImplementedError
989
990 def test_internal_types(self):
991 # internal C types are immutable and cannot be instantiated
992 check_disallow_instantiation(self, self.obj_type)
993 with self.assertRaisesRegex(TypeError, "immutable type"):
994 self.obj_type.value = None
995
996 def assert_raises_unknown_digestmod(self):
997 self.assertIsSubclass(self.exc_type, ValueError)
998 return self.assertRaises(self.exc_type)
999
1000 def cases_missing_digestmod_in_constructor(self):
1001 return self.make_missing_digestmod_cases(self.hmac_new)
1002
1003 def cases_unknown_digestmod_in_constructor(self):
1004 func, choices = self.hmac_new, ['unknown', 1234]
1005 return self.make_unknown_digestmod_cases(func, choices)
1006
1007
1008 class OpenSSLConstructorTestCase(ThroughOpenSSLAPIMixin,
1009 ExtensionConstructorTestCaseMixin,
1010 unittest.TestCase):
1011
1012 @property
1013 def obj_type(self):
1014 return _hashlib.HMAC
1015
1016 @property
1017 def exc_type(self):
1018 return _hashlib.UnsupportedDigestmodError
1019
1020 def test_hmac_digest_digestmod_parameter(self):
1021 for value in [object, 'unknown', 1234, None]:
1022 with (
1023 self.subTest(value=value),
1024 self.assert_raises_unknown_digestmod(),
1025 ):
1026 self.hmac_digest(b'key', b'msg', value)
1027
1028
1029 class BuiltinConstructorTestCase(ThroughBuiltinAPIMixin,
1030 ExtensionConstructorTestCaseMixin,
1031 unittest.TestCase):
1032
1033 @property
1034 def obj_type(self):
1035 return self.hmac.HMAC
1036
1037 @property
1038 def exc_type(self):
1039 return self.hmac.UnknownHashError
1040
1041 def test_hmac_digest_digestmod_parameter(self):
1042 for value in [object, 'unknown', 1234, None]:
1043 with (
1044 self.subTest(value=value),
1045 self.assert_raises_unknown_digestmod(),
1046 ):
1047 self.hmac_digest(b'key', b'msg', value)
1048
1049
1050 class SanityTestCaseMixin(CreatorMixin):
1051 """Sanity checks for HMAC objects and their object interface.
1052
1053 The tests here use a common digestname and do not check all supported
1054 hash functions.
1055 """
1056
1057 # The underlying HMAC class to test. May be in C or in Python.
1058 hmac_class: type
1059 # The underlying hash function name (should be accepted by the HMAC class).
1060 digestname: str
1061 # The expected digest and block sizes (must be hardcoded).
1062 digest_size: int
1063 block_size: int
1064
1065 def test_methods(self):
1066 h = self.hmac_new(b"my secret key", digestmod=self.digestname)
1067 self.assertIsInstance(h, self.hmac_class)
1068 self.assertIsNone(h.update(b"compute the hash of this text!"))
1069 self.assertIsInstance(h.digest(), bytes)
1070 self.assertIsInstance(h.hexdigest(), str)
1071 self.assertIsInstance(h.copy(), self.hmac_class)
1072
1073 def test_properties(self):
1074 h = self.hmac_new(b"my secret key", digestmod=self.digestname)
1075 self.assertEqual(h.name, f"hmac-{self.digestname}")
1076 self.assertEqual(h.digest_size, self.digest_size)
1077 self.assertEqual(h.block_size, self.block_size)
1078
1079 def test_copy(self):
1080 # Test a generic copy() and the attributes it exposes.
1081 # See https://github.com/python/cpython/issues/142451.
1082 h1 = self.hmac_new(b"my secret key", digestmod=self.digestname)
1083 h2 = h1.copy()
1084 self.assertEqual(h1.name, h2.name)
1085 self.assertEqual(h1.digest_size, h2.digest_size)
1086 self.assertEqual(h1.block_size, h2.block_size)
1087
1088 def test_repr(self):
1089 # HMAC object representation may differ across implementations
1090 raise NotImplementedError
1091
1092
1093 @hashlib_helper.requires_hashdigest('sha256')
1094 class PySanityTestCase(ThroughObjectMixin, PyModuleMixin, SanityTestCaseMixin,
1095 unittest.TestCase):
1096
1097 @classmethod
1098 def setUpClass(cls):
1099 super().setUpClass()
1100 cls.hmac_class = cls.hmac.HMAC
1101 cls.digestname = 'sha256'
1102 cls.digest_size = 32
1103 cls.block_size = 64
1104
1105 def test_repr(self):
1106 h = self.hmac_new(b"my secret key", digestmod=self.digestname)
1107 self.assertStartsWith(repr(h), "<hmac.HMAC object at")
1108
1109
1110 @hashlib_helper.requires_openssl_hashdigest('sha256')
1111 class OpenSSLSanityTestCase(ThroughOpenSSLAPIMixin, SanityTestCaseMixin,
1112 unittest.TestCase):
1113
1114 @classmethod
1115 def setUpClass(cls):
1116 super().setUpClass()
1117 cls.hmac_class = _hashlib.HMAC
1118 cls.digestname = 'sha256'
1119 cls.digest_size = 32
1120 cls.block_size = 64
1121
1122 def test_repr(self):
1123 h = self.hmac_new(b"my secret key", digestmod=self.digestname)
1124 self.assertStartsWith(repr(h), f"<{self.digestname} HMAC object @")
1125
1126
1127 class BuiltinSanityTestCase(ThroughBuiltinAPIMixin, SanityTestCaseMixin,
1128 unittest.TestCase):
1129
1130 @classmethod
1131 def setUpClass(cls):
1132 super().setUpClass()
1133 cls.hmac_class = cls.hmac.HMAC
1134 cls.digestname = 'sha256'
1135 cls.digest_size = 32
1136 cls.block_size = 64
1137
1138 def test_repr(self):
1139 h = self.hmac_new(b"my secret key", digestmod=self.digestname)
1140 self.assertStartsWith(repr(h), f"<{self.digestname} HMAC object @")
1141
1142
1143 class UpdateTestCaseMixin:
1144 """Tests for the update() method (streaming HMAC)."""
1145
1146 def HMAC(self, key, msg=None):
1147 """Create a HMAC object."""
1148 raise NotImplementedError
1149
1150 @property
1151 def gil_minsize(self):
1152 """Get the maximal input length for the GIL to be held."""
1153 raise NotImplementedError
1154
1155 def check_update(self, key, chunks):
1156 chunks = list(chunks)
1157 msg = b''.join(chunks)
1158 h1 = self.HMAC(key, msg)
1159
1160 h2 = self.HMAC(key)
1161 for chunk in chunks:
1162 h2.update(chunk)
1163
1164 self.assertEqual(h1.digest(), h2.digest())
1165 self.assertEqual(h1.hexdigest(), h2.hexdigest())
1166
1167 def test_update(self):
1168 key, msg = random.randbytes(16), random.randbytes(16)
1169 with self.subTest(key=key, msg=msg):
1170 self.check_update(key, [msg])
1171
1172 def test_update_large(self):
1173 gil_minsize = self.gil_minsize
1174 key = random.randbytes(16)
1175 top = random.randbytes(gil_minsize + 1)
1176 bot = random.randbytes(gil_minsize + 1)
1177 self.check_update(key, [top, bot])
1178
1179 def test_update_exceptions(self):
1180 h = self.HMAC(b"key")
1181 for msg in ['invalid msg', 123, (), []]:
1182 with self.subTest(msg=msg):
1183 self.assertRaises(TypeError, h.update, msg)
1184
1185
1186 @requires_builtin_sha2()
1187 class PyUpdateTestCase(PyModuleMixin, UpdateTestCaseMixin, unittest.TestCase):
1188
1189 def HMAC(self, key, msg=None):
1190 return self.hmac.HMAC(key, msg, digestmod='sha256')
1191
1192 @property
1193 def gil_minsize(self):
1194 return sha2._GIL_MINSIZE
1195
1196
1197 @hashlib_helper.requires_openssl_hashdigest('sha256')
1198 class OpenSSLUpdateTestCase(UpdateTestCaseMixin, unittest.TestCase):
1199
1200 def HMAC(self, key, msg=None):
1201 return _hashlib.hmac_new(key, msg, digestmod='sha256')
1202
1203 @property
1204 def gil_minsize(self):
1205 return _hashlib._GIL_MINSIZE
1206
1207
1208 class BuiltinUpdateTestCase(BuiltinModuleMixin,
1209 UpdateTestCaseMixin, unittest.TestCase):
1210
1211 def HMAC(self, key, msg=None):
1212 # Even if Python does not build '_sha2', the HACL* sources
1213 # are still built, making it possible to use SHA-2 hashes.
1214 return self.hmac.new(key, msg, digestmod='sha256')
1215
1216 @property
1217 def gil_minsize(self):
1218 return self.hmac._GIL_MINSIZE
1219
1220
1221 class CopyBaseTestCase:
1222
1223 def test_attributes(self):
1224 raise NotImplementedError
1225
1226 def test_realcopy(self):
1227 raise NotImplementedError
1228
1229
1230 @hashlib_helper.requires_hashdigest('sha256')
1231 class PythonCopyTestCase(CopyBaseTestCase, unittest.TestCase):
1232
1233 def test_attributes(self):
1234 # Testing if attributes are of same type.
1235 h1 = hmac.HMAC.__new__(hmac.HMAC)
1236 h1._init_old(b"key", b"msg", digestmod="sha256")
1237 self.assertIsNone(h1._hmac)
1238 self.assertIsNotNone(h1._inner)
1239 self.assertIsNotNone(h1._outer)
1240
1241 h2 = h1.copy()
1242 self.assertIsNone(h2._hmac)
1243 self.assertIsNotNone(h2._inner)
1244 self.assertIsNotNone(h2._outer)
1245 self.assertEqual(type(h1._inner), type(h2._inner))
1246 self.assertEqual(type(h1._outer), type(h2._outer))
1247
1248 def test_realcopy(self):
1249 # Testing if the copy method created a real copy.
1250 h1 = hmac.HMAC.__new__(hmac.HMAC)
1251 h1._init_old(b"key", b"msg", digestmod="sha256")
1252 h2 = h1.copy()
1253 # Using id() in case somebody has overridden __eq__/__ne__.
1254 self.assertNotEqual(id(h1), id(h2))
1255 self.assertNotEqual(id(h1._inner), id(h2._inner))
1256 self.assertNotEqual(id(h1._outer), id(h2._outer))
1257
1258 def test_equality(self):
1259 # Testing if the copy has the same digests.
1260 h1 = hmac.HMAC(b"key", digestmod="sha256")
1261 h1.update(b"some random text")
1262 h2 = h1.copy()
1263 self.assertEqual(h1.digest(), h2.digest())
1264 self.assertEqual(h1.hexdigest(), h2.hexdigest())
1265
1266 def test_equality_new(self):
1267 # Testing if the copy has the same digests with hmac.new().
1268 h1 = hmac.new(b"key", digestmod="sha256")
1269 h1.update(b"some random text")
1270 h2 = h1.copy()
1271 # Using id() in case somebody has overridden __eq__/__ne__.
1272 self.assertNotEqual(id(h1), id(h2))
1273 self.assertEqual(h1.digest(), h2.digest())
1274 self.assertEqual(h1.hexdigest(), h2.hexdigest())
1275
1276
1277 class ExtensionCopyTestCase(CopyBaseTestCase):
1278
1279 def init(self, h):
1280 """Call the dedicate init() method to test."""
1281 raise NotImplementedError
1282
1283 def test_attributes(self):
1284 # Testing if attributes are of same type.
1285 h1 = hmac.HMAC.__new__(hmac.HMAC)
1286
1287 self.init(h1)
1288 self.assertIsNotNone(h1._hmac)
1289 self.assertIsNone(h1._inner)
1290 self.assertIsNone(h1._outer)
1291
1292 h2 = h1.copy()
1293 self.assertIsNotNone(h2._hmac)
1294 self.assertIsNone(h2._inner)
1295 self.assertIsNone(h2._outer)
1296
1297 def test_realcopy(self):
1298 h1 = hmac.HMAC.__new__(hmac.HMAC)
1299 self.init(h1)
1300 h2 = h1.copy()
1301 # Using id() in case somebody has overridden __eq__/__ne__.
1302 self.assertNotEqual(id(h1._hmac), id(h2._hmac))
1303
1304
1305 @hashlib_helper.requires_openssl_hashdigest('sha256')
1306 class OpenSSLCopyTestCase(ExtensionCopyTestCase, unittest.TestCase):
1307
1308 def init(self, h):
1309 h._init_openssl_hmac(b"key", b"msg", digestmod="sha256")
1310
1311
1312 @hashlib_helper.requires_builtin_hmac()
1313 class BuiltinCopyTestCase(ExtensionCopyTestCase, unittest.TestCase):
1314
1315 def init(self, h):
1316 # Even if Python does not build '_sha2', the HACL* sources
1317 # are still built, making it possible to use SHA-2 hashes.
1318 h._init_builtin_hmac(b"key", b"msg", digestmod="sha256")
1319
1320
1321 class CompareDigestMixin:
1322
1323 @staticmethod
1324 def compare_digest(a, b):
1325 """Implementation of 'a == b' to test."""
1326 raise NotImplementedError
1327
1328 def assert_digest_equal(self, a, b):
1329 with self.subTest(a=a, b=b):
1330 self.assertTrue(self.compare_digest(a, b))
1331 with self.subTest(a=b, b=a):
1332 self.assertTrue(self.compare_digest(b, a))
1333
1334 def assert_digest_not_equal(self, a, b):
1335 with self.subTest(a=a, b=b):
1336 self.assertFalse(self.compare_digest(a, b))
1337 with self.subTest(a=b, b=a):
1338 self.assertFalse(self.compare_digest(b, a))
1339
1340 def test_exceptions(self):
1341 for a, b in [
1342 # Testing input type exception handling
1343 (100, 200), (100, b"foobar"), ("foobar", b"foobar"),
1344 # non-ASCII strings
1345 ("fooä", "fooä")
1346 ]:
1347 self.assertRaises(TypeError, self.compare_digest, a, b)
1348 self.assertRaises(TypeError, self.compare_digest, b, a)
1349
1350 def test_bytes(self):
1351 # Testing bytes of different lengths
1352 a, b = b"foobar", b"foo"
1353 self.assert_digest_not_equal(a, b)
1354 a, b = b"\xde\xad\xbe\xef", b"\xde\xad"
1355 self.assert_digest_not_equal(a, b)
1356
1357 # Testing bytes of same lengths, different values
1358 a, b = b"foobar", b"foobaz"
1359 self.assert_digest_not_equal(a, b)
1360 a, b = b"\xde\xad\xbe\xef", b"\xab\xad\x1d\xea"
1361 self.assert_digest_not_equal(a, b)
1362
1363 # Testing bytes of same lengths, same values
1364 a, b = b"foobar", b"foobar"
1365 self.assert_digest_equal(a, b)
1366 a, b = b"\xde\xad\xbe\xef", b"\xde\xad\xbe\xef"
1367 self.assert_digest_equal(a, b)
1368
1369 def test_bytearray(self):
1370 # Testing bytearrays of same lengths, same values
1371 a, b = bytearray(b"foobar"), bytearray(b"foobar")
1372 self.assert_digest_equal(a, b)
1373
1374 # Testing bytearrays of different lengths
1375 a, b = bytearray(b"foobar"), bytearray(b"foo")
1376 self.assert_digest_not_equal(a, b)
1377
1378 # Testing bytearrays of same lengths, different values
1379 a, b = bytearray(b"foobar"), bytearray(b"foobaz")
1380 self.assert_digest_not_equal(a, b)
1381
1382 def test_mixed_types(self):
1383 # Testing byte and bytearray of same lengths, same values
1384 a, b = bytearray(b"foobar"), b"foobar"
1385 self.assert_digest_equal(a, b)
1386
1387 # Testing byte bytearray of different lengths
1388 a, b = bytearray(b"foobar"), b"foo"
1389 self.assert_digest_not_equal(a, b)
1390
1391 # Testing byte and bytearray of same lengths, different values
1392 a, b = bytearray(b"foobar"), b"foobaz"
1393 self.assert_digest_not_equal(a, b)
1394
1395 def test_string(self):
1396 # Testing str of same lengths
1397 a, b = "foobar", "foobar"
1398 self.assert_digest_equal(a, b)
1399
1400 # Testing str of different lengths
1401 a, b = "foo", "foobar"
1402 self.assert_digest_not_equal(a, b)
1403
1404 # Testing str of same lengths, different values
1405 a, b = "foobar", "foobaz"
1406 self.assert_digest_not_equal(a, b)
1407
1408 def test_string_subclass(self):
1409 class S(str):
1410 def __eq__(self, other):
1411 raise ValueError("should not be called")
1412
1413 a, b = S("foobar"), S("foobar")
1414 self.assert_digest_equal(a, b)
1415 a, b = S("foobar"), "foobar"
1416 self.assert_digest_equal(a, b)
1417 a, b = S("foobar"), S("foobaz")
1418 self.assert_digest_not_equal(a, b)
1419
1420 def test_bytes_subclass(self):
1421 class B(bytes):
1422 def __eq__(self, other):
1423 raise ValueError("should not be called")
1424
1425 a, b = B(b"foobar"), B(b"foobar")
1426 self.assert_digest_equal(a, b)
1427 a, b = B(b"foobar"), b"foobar"
1428 self.assert_digest_equal(a, b)
1429 a, b = B(b"foobar"), B(b"foobaz")
1430 self.assert_digest_not_equal(a, b)
1431
1432
1433 class HMACCompareDigestTestCase(CompareDigestMixin, unittest.TestCase):
1434 compare_digest = hmac.compare_digest
1435
1436 def test_compare_digest_func(self):
1437 if openssl_compare_digest is not None:
1438 self.assertIs(self.compare_digest, openssl_compare_digest)
1439 else:
1440 self.assertIs(self.compare_digest, operator_compare_digest)
1441
1442
1443 @hashlib_helper.requires_hashlib()
1444 class OpenSSLCompareDigestTestCase(CompareDigestMixin, unittest.TestCase):
1445 compare_digest = openssl_compare_digest
1446
1447
1448 class OperatorCompareDigestTestCase(CompareDigestMixin, unittest.TestCase):
1449 compare_digest = operator_compare_digest
1450
1451
1452 class PyMiscellaneousTests(unittest.TestCase):
1453 """Miscellaneous tests for the pure Python HMAC module."""
1454
1455 @hashlib_helper.requires_builtin_hmac()
1456 def test_hmac_constructor_uses_builtin(self):
1457 # Block the OpenSSL implementation and check that
1458 # HMAC() uses the built-in implementation instead.
1459 hmac = import_fresh_module("hmac", blocked=["_hashlib"])
1460
1461 def watch_method(cls, name):
1462 wraps = getattr(cls, name)
1463 return patch.object(cls, name, autospec=True, wraps=wraps)
1464
1465 with (
1466 watch_method(hmac.HMAC, '_init_openssl_hmac') as f,
1467 watch_method(hmac.HMAC, '_init_builtin_hmac') as g,
1468 ):
1469 _ = hmac.HMAC(b'key', b'msg', digestmod="sha256")
1470 f.assert_not_called()
1471 g.assert_called_once()
1472
1473 @hashlib_helper.requires_hashdigest('sha256')
1474 def test_hmac_delegated_properties(self):
1475 h = hmac.HMAC(b'key', b'msg', digestmod="sha256")
1476 self.assertEqual(h.name, "hmac-sha256")
1477 self.assertEqual(h.digest_size, 32)
1478 self.assertEqual(h.block_size, 64)
1479
1480 @hashlib_helper.requires_hashdigest('sha256')
1481 def test_legacy_block_size_warnings(self):
1482 class MockCrazyHash(object):
1483 """Ain't no block_size attribute here."""
1484 def __init__(self, *args):
1485 self._x = hashlib.sha256(*args)
1486 self.digest_size = self._x.digest_size
1487 def update(self, v):
1488 self._x.update(v)
1489 def digest(self):
1490 return self._x.digest()
1491
1492 with warnings.catch_warnings():
1493 warnings.simplefilter('error', RuntimeWarning)
1494 with self.assertRaises(RuntimeWarning):
1495 hmac.HMAC(b'a', b'b', digestmod=MockCrazyHash)
1496 self.fail('Expected warning about missing block_size')
1497
1498 MockCrazyHash.block_size = 1
1499 with self.assertRaises(RuntimeWarning):
1500 hmac.HMAC(b'a', b'b', digestmod=MockCrazyHash)
1501 self.fail('Expected warning about small block_size')
1502
1503 @hashlib_helper.requires_hashdigest('sha256')
1504 def test_with_fallback(self):
1505 cache = getattr(hashlib, '__builtin_constructor_cache')
1506 try:
1507 cache['foo'] = hashlib.sha256
1508 hexdigest = hmac.digest(b'key', b'message', 'foo').hex()
1509 expected = ('6e9ef29b75fffc5b7abae527d58fdadb'
1510 '2fe42e7219011976917343065f58ed4a')
1511 self.assertEqual(hexdigest, expected)
1512 finally:
1513 cache.pop('foo')
1514
1515 @hashlib_helper.requires_openssl_hashdigest("md5")
1516 @bigmemtest(size=_4G + 5, memuse=2, dry_run=False)
1517 def test_hmac_digest_overflow_error_openssl_only(self, size):
1518 hmac = import_fresh_module("hmac", blocked=["_hmac"])
1519 self.do_test_hmac_digest_overflow_error_switch_to_slow(hmac, size)
1520
1521 @hashlib_helper.requires_builtin_hashdigest("_md5", "md5")
1522 @bigmemtest(size=_4G + 5, memuse=2, dry_run=False)
1523 def test_hmac_digest_overflow_error_builtin_only(self, size):
1524 hmac = import_fresh_module("hmac", blocked=["_hashlib"])
1525 self.do_test_hmac_digest_overflow_error_switch_to_slow(hmac, size)
1526
1527 def do_test_hmac_digest_overflow_error_switch_to_slow(self, hmac, size):
1528 """Check that hmac.digest() falls back to pure Python.
1529
1530 The *hmac* argument implements the HMAC module interface.
1531 The *size* argument is a large key size or message size that would
1532 trigger an OverflowError in the C implementation(s) of hmac.digest().
1533 """
1534
1535 bigkey = b'K' * size
1536 bigmsg = b'M' * size
1537
1538 with patch.object(hmac, "_compute_digest_fallback") as slow:
1539 hmac.digest(bigkey, b'm', "md5")
1540 slow.assert_called_once()
1541
1542 with patch.object(hmac, "_compute_digest_fallback") as slow:
1543 hmac.digest(b'k', bigmsg, "md5")
1544 slow.assert_called_once()
1545
1546 @hashlib_helper.requires_hashdigest("md5", openssl=True)
1547 @bigmemtest(size=_4G + 5, memuse=2, dry_run=False)
1548 def test_hmac_digest_no_overflow_error_in_fallback(self, size):
1549 hmac = import_fresh_module("hmac", blocked=["_hashlib", "_hmac"])
1550
1551 for key, msg in [(b'K' * size, b'm'), (b'k', b'M' * size)]:
1552 with self.subTest(keysize=len(key), msgsize=len(msg)):
1553 with patch.object(hmac, "_compute_digest_fallback") as slow:
1554 hmac.digest(key, msg, "md5")
1555 slow.assert_called_once()
1556
1557
1558 class BuiltinMiscellaneousTests(BuiltinModuleMixin, unittest.TestCase):
1559 """HMAC-BLAKE2 is not standardized as BLAKE2 is a keyed hash function.
1560
1561 In particular, there is no official test vectors for HMAC-BLAKE2.
1562 However, we can test that the HACL* interface is correctly used by
1563 checking against the pure Python implementation output.
1564 """
1565
1566 @classmethod
1567 def setUpClass(cls):
1568 super().setUpClass()
1569 cls.blake2 = import_helper.import_module("_blake2")
1570 cls.blake2b = cls.blake2.blake2b
1571 cls.blake2s = cls.blake2.blake2s
1572
1573 def assert_hmac_blake_correctness(self, digest, key, msg, hashfunc):
1574 self.assertIsInstance(digest, bytes)
1575 expect = hmac._compute_digest_fallback(key, msg, hashfunc)
1576 self.assertEqual(digest, expect)
1577
1578 def test_compute_blake2b_32(self):
1579 key, msg = random.randbytes(8), random.randbytes(16)
1580 digest = self.hmac.compute_blake2b_32(key, msg)
1581 self.assert_hmac_blake_correctness(digest, key, msg, self.blake2b)
1582
1583 def test_compute_blake2s_32(self):
1584 key, msg = random.randbytes(8), random.randbytes(16)
1585 digest = self.hmac.compute_blake2s_32(key, msg)
1586 self.assert_hmac_blake_correctness(digest, key, msg, self.blake2s)
1587
1588
1589 if __name__ == "__main__":
1590 unittest.main()