PageRenderTime 43ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/Lib/test/test_hmac.py

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