Skip to content

Commit cf0658d

Browse files
[3.14] gh-155426: correctly reject non-bytes keys in hmac.digest (GH-155427) (#159744)
This only affects keys of length smaller than the HMAC blocksize since larger keys are hashed first. (cherry picked from commit 197d332) --------- Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
1 parent 065b5a5 commit cf0658d

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
@@ -255,6 +255,9 @@ def digest(key, msg, digest):
255255

256256

257257
def _compute_digest_fallback(key, msg, digest):
258+
if not isinstance(key, (bytes, bytearray)):
259+
raise TypeError(f"key: expected bytes or bytearray, "
260+
f"but got {type(key).__name__!r}")
258261
digest_cons = _get_digest_constructor(digest)
259262
inner = digest_cons()
260263
outer = digest_cons()

‎Lib/test/test_hmac.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1518,6 +1518,12 @@ def test_with_fallback(self):
15181518
finally:
15191519
cache.pop('foo')
15201520

1521+
@hashlib_helper.requires_hashdigest("md5")
1522+
def test_hmac_digest_reject_memoryview_for_key(self):
1523+
hmac = import_fresh_module("hmac", blocked=["_hashlib", "_hmac"])
1524+
with self.assertRaises(TypeError):
1525+
hmac.digest(memoryview(b"small"), b"world", "md5")
1526+
15211527
@hashlib_helper.requires_openssl_hashdigest("md5")
15221528
@bigmemtest(size=_4G + 5, memuse=2, dry_run=False)
15231529
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` rejects
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)