test_hmac.py 17 KB

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