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