Skip to content

Commit 197d332

Browse files
authored
gh-155426: correctly reject non-bytes keys in hmac.digest (#155427)
This only affects keys of length smaller than the HMAC blocksize since larger keys are hashed first.
1 parent a071788 commit 197d332

3 files changed

Lines changed: 13 additions & 0 deletions

File tree

‎Lib/hmac.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,9 @@ def digest(key, msg, digest):
267267

268268

269269
def _compute_digest_fallback(key, msg, digest):
270+
if not isinstance(key, (bytes, bytearray)):
271+
raise TypeError(f"key: expected bytes or bytearray, "
272+
f"but got {type(key).__name__!r}")
270273
digest_cons = _get_digest_constructor(digest)
271274
if _is_shake_constructor(digest_cons):
272275
raise ValueError(f"unsupported hash algorithm {digest}")

‎Lib/test/test_hmac.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1525,6 +1525,12 @@ def test_with_fallback(self):
15251525
finally:
15261526
cache.pop('foo')
15271527

1528+
@hashlib_helper.requires_hashdigest("md5")
1529+
def test_hmac_digest_reject_memoryview_for_key(self):
1530+
hmac = import_fresh_module("hmac", blocked=["_hashlib", "_hmac"])
1531+
with self.assertRaises(TypeError):
1532+
hmac.digest(memoryview(b"small"), b"world", "md5")
1533+
15281534
@hashlib_helper.requires_openssl_hashdigest("md5")
15291535
@bigmemtest(size=_4G + 5, memuse=2, dry_run=False)
15301536
def test_hmac_digest_overflow_error_openssl_only(self, size):
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Make sure that the pure Python fallback of :func:`hmac.digest` reject
2+
keys that are neither :class:`bytes` or :class:`bytearray`. Previously,
3+
an :exc:`AttributeError` was raised instead of :exc:`TypeError`.
4+
Patch by Bénédikt Tran.

0 commit comments

Comments
 (0)