https://github.com/python/cpython/commit/e0685b7ae5db24ce98a7237f68c74cf54e2ebcb4
commit: e0685b7ae5db24ce98a7237f68c74cf54e2ebcb4
branch: 3.15
author: Miss Islington (bot) <[email protected]>
committer: picnixz <[email protected]>
date: 2026-10-19T20:18:18Z
summary:

[3.15] gh-155426: correctly reject non-bytes keys in `hmac.digest` (GH-155427) 
(#159743)

This only affects keys of length smaller than the HMAC blocksize
since larger keys are hashed first.

(cherry picked from commit 197d33218f755af0758c83add3956e0bd7ef8657)

---------

Co-authored-by: Bénédikt Tran <[email protected]>

files:
A Misc/NEWS.d/next/Library/2026-08-09-14-06-27.gh-issue-155426.zZVPMd.rst
M Lib/hmac.py
M Lib/test/test_hmac.py

diff --git a/Lib/hmac.py b/Lib/hmac.py
index e0c040bcd5fe3d..61e0823e68be21 100644
--- a/Lib/hmac.py
+++ b/Lib/hmac.py
@@ -267,6 +267,9 @@ def digest(key, msg, digest):
 
 
 def _compute_digest_fallback(key, msg, digest):
+    if not isinstance(key, (bytes, bytearray)):
+        raise TypeError(f"key: expected bytes or bytearray, "
+                        f"but got {type(key).__name__!r}")
     digest_cons = _get_digest_constructor(digest)
     if _is_shake_constructor(digest_cons):
         raise ValueError(f"unsupported hash algorithm {digest}")
diff --git a/Lib/test/test_hmac.py b/Lib/test/test_hmac.py
index c43188cc333e88..e44113edf3f422 100644
--- a/Lib/test/test_hmac.py
+++ b/Lib/test/test_hmac.py
@@ -1525,6 +1525,12 @@ def test_with_fallback(self):
         finally:
             cache.pop('foo')
 
+    @hashlib_helper.requires_hashdigest("md5")
+    def test_hmac_digest_reject_memoryview_for_key(self):
+        hmac = import_fresh_module("hmac", blocked=["_hashlib", "_hmac"])
+        with self.assertRaises(TypeError):
+            hmac.digest(memoryview(b"small"), b"world", "md5")
+
     @hashlib_helper.requires_openssl_hashdigest("md5")
     @bigmemtest(size=_4G + 5, memuse=2, dry_run=False)
     def test_hmac_digest_overflow_error_openssl_only(self, size):
diff --git 
a/Misc/NEWS.d/next/Library/2026-08-09-14-06-27.gh-issue-155426.zZVPMd.rst 
b/Misc/NEWS.d/next/Library/2026-08-09-14-06-27.gh-issue-155426.zZVPMd.rst
new file mode 100644
index 00000000000000..b7424a76ce26ea
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-08-09-14-06-27.gh-issue-155426.zZVPMd.rst
@@ -0,0 +1,4 @@
+Make sure that the pure Python fallback of :func:`hmac.digest` rejects
+keys that are neither :class:`bytes` or :class:`bytearray`. Previously,
+an :exc:`AttributeError` was raised instead of :exc:`TypeError`.
+Patch by Bénédikt Tran.

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]

Reply via email to