test_hmac.py 25 KB

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