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