Back to index

python3.2  3.2.2
test_hmac.py
Go to the documentation of this file.
00001 import hmac
00002 import hashlib
00003 import unittest
00004 import warnings
00005 from test import support
00006 
00007 class TestVectorsTestCase(unittest.TestCase):
00008 
00009     def test_md5_vectors(self):
00010         # Test the HMAC module against test vectors from the RFC.
00011 
00012         def md5test(key, data, digest):
00013             h = hmac.HMAC(key, data)
00014             self.assertEqual(h.hexdigest().upper(), digest.upper())
00015 
00016         md5test(b"\x0b" * 16,
00017                 b"Hi There",
00018                 "9294727A3638BB1C13F48EF8158BFC9D")
00019 
00020         md5test(b"Jefe",
00021                 b"what do ya want for nothing?",
00022                 "750c783e6ab0b503eaa86e310a5db738")
00023 
00024         md5test(b"\xaa" * 16,
00025                 b"\xdd" * 50,
00026                 "56be34521d144c88dbb8c733f0e8b3f6")
00027 
00028         md5test(bytes(range(1, 26)),
00029                 b"\xcd" * 50,
00030                 "697eaf0aca3a3aea3a75164746ffaa79")
00031 
00032         md5test(b"\x0C" * 16,
00033                 b"Test With Truncation",
00034                 "56461ef2342edc00f9bab995690efd4c")
00035 
00036         md5test(b"\xaa" * 80,
00037                 b"Test Using Larger Than Block-Size Key - Hash Key First",
00038                 "6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd")
00039 
00040         md5test(b"\xaa" * 80,
00041                 (b"Test Using Larger Than Block-Size Key "
00042                  b"and Larger Than One Block-Size Data"),
00043                 "6f630fad67cda0ee1fb1f562db3aa53e")
00044 
00045     def test_sha_vectors(self):
00046         def shatest(key, data, digest):
00047             h = hmac.HMAC(key, data, digestmod=hashlib.sha1)
00048             self.assertEqual(h.hexdigest().upper(), digest.upper())
00049 
00050         shatest(b"\x0b" * 20,
00051                 b"Hi There",
00052                 "b617318655057264e28bc0b6fb378c8ef146be00")
00053 
00054         shatest(b"Jefe",
00055                 b"what do ya want for nothing?",
00056                 "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79")
00057 
00058         shatest(b"\xAA" * 20,
00059                 b"\xDD" * 50,
00060                 "125d7342b9ac11cd91a39af48aa17b4f63f175d3")
00061 
00062         shatest(bytes(range(1, 26)),
00063                 b"\xCD" * 50,
00064                 "4c9007f4026250c6bc8414f9bf50c86c2d7235da")
00065 
00066         shatest(b"\x0C" * 20,
00067                 b"Test With Truncation",
00068                 "4c1a03424b55e07fe7f27be1d58bb9324a9a5a04")
00069 
00070         shatest(b"\xAA" * 80,
00071                 b"Test Using Larger Than Block-Size Key - Hash Key First",
00072                 "aa4ae5e15272d00e95705637ce8a3b55ed402112")
00073 
00074         shatest(b"\xAA" * 80,
00075                 (b"Test Using Larger Than Block-Size Key "
00076                  b"and Larger Than One Block-Size Data"),
00077                 "e8e99d0f45237d786d6bbaa7965c7808bbff1a91")
00078 
00079     def _rfc4231_test_cases(self, hashfunc):
00080         def hmactest(key, data, hexdigests):
00081             h = hmac.HMAC(key, data, digestmod=hashfunc)
00082             self.assertEqual(h.hexdigest().lower(), hexdigests[hashfunc])
00083 
00084         # 4.2.  Test Case 1
00085         hmactest(key = b'\x0b'*20,
00086                  data = b'Hi There',
00087                  hexdigests = {
00088                    hashlib.sha224: '896fb1128abbdf196832107cd49df33f'
00089                                    '47b4b1169912ba4f53684b22',
00090                    hashlib.sha256: 'b0344c61d8db38535ca8afceaf0bf12b'
00091                                    '881dc200c9833da726e9376c2e32cff7',
00092                    hashlib.sha384: 'afd03944d84895626b0825f4ab46907f'
00093                                    '15f9dadbe4101ec682aa034c7cebc59c'
00094                                    'faea9ea9076ede7f4af152e8b2fa9cb6',
00095                    hashlib.sha512: '87aa7cdea5ef619d4ff0b4241a1d6cb0'
00096                                    '2379f4e2ce4ec2787ad0b30545e17cde'
00097                                    'daa833b7d6b8a702038b274eaea3f4e4'
00098                                    'be9d914eeb61f1702e696c203a126854',
00099                  })
00100 
00101         # 4.3.  Test Case 2
00102         hmactest(key = b'Jefe',
00103                  data = b'what do ya want for nothing?',
00104                  hexdigests = {
00105                    hashlib.sha224: 'a30e01098bc6dbbf45690f3a7e9e6d0f'
00106                                    '8bbea2a39e6148008fd05e44',
00107                    hashlib.sha256: '5bdcc146bf60754e6a042426089575c7'
00108                                    '5a003f089d2739839dec58b964ec3843',
00109                    hashlib.sha384: 'af45d2e376484031617f78d2b58a6b1b'
00110                                    '9c7ef464f5a01b47e42ec3736322445e'
00111                                    '8e2240ca5e69e2c78b3239ecfab21649',
00112                    hashlib.sha512: '164b7a7bfcf819e2e395fbe73b56e0a3'
00113                                    '87bd64222e831fd610270cd7ea250554'
00114                                    '9758bf75c05a994a6d034f65f8f0e6fd'
00115                                    'caeab1a34d4a6b4b636e070a38bce737',
00116                  })
00117 
00118         # 4.4.  Test Case 3
00119         hmactest(key = b'\xaa'*20,
00120                  data = b'\xdd'*50,
00121                  hexdigests = {
00122                    hashlib.sha224: '7fb3cb3588c6c1f6ffa9694d7d6ad264'
00123                                    '9365b0c1f65d69d1ec8333ea',
00124                    hashlib.sha256: '773ea91e36800e46854db8ebd09181a7'
00125                                    '2959098b3ef8c122d9635514ced565fe',
00126                    hashlib.sha384: '88062608d3e6ad8a0aa2ace014c8a86f'
00127                                    '0aa635d947ac9febe83ef4e55966144b'
00128                                    '2a5ab39dc13814b94e3ab6e101a34f27',
00129                    hashlib.sha512: 'fa73b0089d56a284efb0f0756c890be9'
00130                                    'b1b5dbdd8ee81a3655f83e33b2279d39'
00131                                    'bf3e848279a722c806b485a47e67c807'
00132                                    'b946a337bee8942674278859e13292fb',
00133                  })
00134 
00135         # 4.5.  Test Case 4
00136         hmactest(key = bytes(x for x in range(0x01, 0x19+1)),
00137                  data = b'\xcd'*50,
00138                  hexdigests = {
00139                    hashlib.sha224: '6c11506874013cac6a2abc1bb382627c'
00140                                    'ec6a90d86efc012de7afec5a',
00141                    hashlib.sha256: '82558a389a443c0ea4cc819899f2083a'
00142                                    '85f0faa3e578f8077a2e3ff46729665b',
00143                    hashlib.sha384: '3e8a69b7783c25851933ab6290af6ca7'
00144                                    '7a9981480850009cc5577c6e1f573b4e'
00145                                    '6801dd23c4a7d679ccf8a386c674cffb',
00146                    hashlib.sha512: 'b0ba465637458c6990e5a8c5f61d4af7'
00147                                    'e576d97ff94b872de76f8050361ee3db'
00148                                    'a91ca5c11aa25eb4d679275cc5788063'
00149                                    'a5f19741120c4f2de2adebeb10a298dd',
00150                  })
00151 
00152         # 4.7.  Test Case 6
00153         hmactest(key = b'\xaa'*131,
00154                  data = b'Test Using Larger Than Block-Siz'
00155                         b'e Key - Hash Key First',
00156                  hexdigests = {
00157                    hashlib.sha224: '95e9a0db962095adaebe9b2d6f0dbce2'
00158                                    'd499f112f2d2b7273fa6870e',
00159                    hashlib.sha256: '60e431591ee0b67f0d8a26aacbf5b77f'
00160                                    '8e0bc6213728c5140546040f0ee37f54',
00161                    hashlib.sha384: '4ece084485813e9088d2c63a041bc5b4'
00162                                    '4f9ef1012a2b588f3cd11f05033ac4c6'
00163                                    '0c2ef6ab4030fe8296248df163f44952',
00164                    hashlib.sha512: '80b24263c7c1a3ebb71493c1dd7be8b4'
00165                                    '9b46d1f41b4aeec1121b013783f8f352'
00166                                    '6b56d037e05f2598bd0fd2215d6a1e52'
00167                                    '95e64f73f63f0aec8b915a985d786598',
00168                  })
00169 
00170         # 4.8.  Test Case 7
00171         hmactest(key = b'\xaa'*131,
00172                  data = b'This is a test using a larger th'
00173                         b'an block-size key and a larger t'
00174                         b'han block-size data. The key nee'
00175                         b'ds to be hashed before being use'
00176                         b'd by the HMAC algorithm.',
00177                  hexdigests = {
00178                    hashlib.sha224: '3a854166ac5d9f023f54d517d0b39dbd'
00179                                    '946770db9c2b95c9f6f565d1',
00180                    hashlib.sha256: '9b09ffa71b942fcb27635fbcd5b0e944'
00181                                    'bfdc63644f0713938a7f51535c3a35e2',
00182                    hashlib.sha384: '6617178e941f020d351e2f254e8fd32c'
00183                                    '602420feb0b8fb9adccebb82461e99c5'
00184                                    'a678cc31e799176d3860e6110c46523e',
00185                    hashlib.sha512: 'e37b6a775dc87dbaa4dfa9f96e5e3ffd'
00186                                    'debd71f8867289865df5a32d20cdc944'
00187                                    'b6022cac3c4982b10d5eeb55c3e4de15'
00188                                    '134676fb6de0446065c97440fa8c6a58',
00189                  })
00190 
00191     def test_sha224_rfc4231(self):
00192         self._rfc4231_test_cases(hashlib.sha224)
00193 
00194     def test_sha256_rfc4231(self):
00195         self._rfc4231_test_cases(hashlib.sha256)
00196 
00197     def test_sha384_rfc4231(self):
00198         self._rfc4231_test_cases(hashlib.sha384)
00199 
00200     def test_sha512_rfc4231(self):
00201         self._rfc4231_test_cases(hashlib.sha512)
00202 
00203     def test_legacy_block_size_warnings(self):
00204         class MockCrazyHash(object):
00205             """Ain't no block_size attribute here."""
00206             def __init__(self, *args):
00207                 self._x = hashlib.sha1(*args)
00208                 self.digest_size = self._x.digest_size
00209             def update(self, v):
00210                 self._x.update(v)
00211             def digest(self):
00212                 return self._x.digest()
00213 
00214         with warnings.catch_warnings():
00215             warnings.simplefilter('error', RuntimeWarning)
00216             with self.assertRaises(RuntimeWarning):
00217                 hmac.HMAC(b'a', b'b', digestmod=MockCrazyHash)
00218                 self.fail('Expected warning about missing block_size')
00219 
00220             MockCrazyHash.block_size = 1
00221             with self.assertRaises(RuntimeWarning):
00222                 hmac.HMAC(b'a', b'b', digestmod=MockCrazyHash)
00223                 self.fail('Expected warning about small block_size')
00224 
00225 
00226 
00227 class ConstructorTestCase(unittest.TestCase):
00228 
00229     def test_normal(self):
00230         # Standard constructor call.
00231         failed = 0
00232         try:
00233             h = hmac.HMAC(b"key")
00234         except:
00235             self.fail("Standard constructor call raised exception.")
00236 
00237     def test_withtext(self):
00238         # Constructor call with text.
00239         try:
00240             h = hmac.HMAC(b"key", b"hash this!")
00241         except:
00242             self.fail("Constructor call with text argument raised exception.")
00243 
00244     def test_withmodule(self):
00245         # Constructor call with text and digest module.
00246         try:
00247             h = hmac.HMAC(b"key", b"", hashlib.sha1)
00248         except:
00249             self.fail("Constructor call with hashlib.sha1 raised exception.")
00250 
00251 class SanityTestCase(unittest.TestCase):
00252 
00253     def test_default_is_md5(self):
00254         # Testing if HMAC defaults to MD5 algorithm.
00255         # NOTE: this whitebox test depends on the hmac class internals
00256         h = hmac.HMAC(b"key")
00257         self.assertEqual(h.digest_cons, hashlib.md5)
00258 
00259     def test_exercise_all_methods(self):
00260         # Exercising all methods once.
00261         # This must not raise any exceptions
00262         try:
00263             h = hmac.HMAC(b"my secret key")
00264             h.update(b"compute the hash of this text!")
00265             dig = h.digest()
00266             dig = h.hexdigest()
00267             h2 = h.copy()
00268         except:
00269             self.fail("Exception raised during normal usage of HMAC class.")
00270 
00271 class CopyTestCase(unittest.TestCase):
00272 
00273     def test_attributes(self):
00274         # Testing if attributes are of same type.
00275         h1 = hmac.HMAC(b"key")
00276         h2 = h1.copy()
00277         self.assertTrue(h1.digest_cons == h2.digest_cons,
00278             "digest constructors don't match.")
00279         self.assertEqual(type(h1.inner), type(h2.inner),
00280             "Types of inner don't match.")
00281         self.assertEqual(type(h1.outer), type(h2.outer),
00282             "Types of outer don't match.")
00283 
00284     def test_realcopy(self):
00285         # Testing if the copy method created a real copy.
00286         h1 = hmac.HMAC(b"key")
00287         h2 = h1.copy()
00288         # Using id() in case somebody has overridden __eq__/__ne__.
00289         self.assertTrue(id(h1) != id(h2), "No real copy of the HMAC instance.")
00290         self.assertTrue(id(h1.inner) != id(h2.inner),
00291             "No real copy of the attribute 'inner'.")
00292         self.assertTrue(id(h1.outer) != id(h2.outer),
00293             "No real copy of the attribute 'outer'.")
00294 
00295     def test_equality(self):
00296         # Testing if the copy has the same digests.
00297         h1 = hmac.HMAC(b"key")
00298         h1.update(b"some random text")
00299         h2 = h1.copy()
00300         self.assertEqual(h1.digest(), h2.digest(),
00301             "Digest of copy doesn't match original digest.")
00302         self.assertEqual(h1.hexdigest(), h2.hexdigest(),
00303             "Hexdigest of copy doesn't match original hexdigest.")
00304 
00305 def test_main():
00306     support.run_unittest(
00307         TestVectorsTestCase,
00308         ConstructorTestCase,
00309         SanityTestCase,
00310         CopyTestCase
00311     )
00312 
00313 if __name__ == "__main__":
00314     test_main()