Skip to content

Commit 0c1bf69

Browse files
committed
gh-155426: correctly accept bytes-like keys in hmac.digest
This only affects keys of length smaller than the HMAC blocksize since larger keys are hashed first.
1 parent 998b890 commit 0c1bf69

3 files changed

Lines changed: 12 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
@@ -1519,6 +1519,12 @@ def test_with_fallback(self):
15191519
finally:
15201520
cache.pop('foo')
15211521

1522+
@hashlib_helper.requires_hashdigest("md5")
1523+
def test_hmac_digest_reject_memoryview_for_key(self):
1524+
hmac = import_fresh_module("hmac", blocked=["_hashlib", "_hmac"])
1525+
with self.assertRaises(TypeError):
1526+
hmac.digest(memoryview(b"small"), b"world", "md5")
1527+
15221528
@hashlib_helper.requires_openssl_hashdigest("md5")
15231529
@bigmemtest(size=_4G + 5, memuse=2, dry_run=False)
15241530
def test_hmac_digest_overflow_error_openssl_only(self, size):
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Make sure that the pure Python fallback of :func:`hmac.digest` reject
2+
keys that are neither :class:`bytes` or :class:`bytearray`. Patch by
3+
Bénédikt Tran.

0 commit comments

Comments
 (0)