Skip to content

Commit 43408f0

Browse files
committed
ensure that hmac.digest does not raise OverflowError`
1 parent 74239be commit 43408f0

File tree

2 files changed

+14
-11
lines changed

2 files changed

+14
-11
lines changed

Lib/hmac.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -241,19 +241,22 @@ def digest(key, msg, digest):
241241
if _hashopenssl and isinstance(digest, (str, _functype)):
242242
try:
243243
return _hashopenssl.hmac_digest(key, msg, digest)
244-
except OverflowError as exc:
245-
if (not _hmac and isinstance(digest, str)) or callable(digest):
246-
# Without re-raising now, slow HMAC will be used as
247-
# HACL* HMAC only identifies digests by their name.
248-
raise exc
244+
except OverflowError:
245+
try:
246+
return _hashopenssl.hmac_new(key, msg, digest).digest()
247+
except _hashopenssl.UnsupportedDigestmodError:
248+
pass
249249
except _hashopenssl.UnsupportedDigestmodError:
250250
pass
251251

252252
if _hmac and isinstance(digest, str):
253253
try:
254-
# The following call may raise an OverflowError
255-
# but we do not want to fallback to slow HMAC.
256254
return _hmac.compute_digest(key, msg, digest)
255+
except OverflowError:
256+
try:
257+
return _hmac.new(key, msg, digest).digest()
258+
except _hmac.UnknownHashError:
259+
pass
257260
except _hmac.UnknownHashError:
258261
pass
259262

Lib/test/test_hmac.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1513,8 +1513,8 @@ def test_hmac_digest_overflow_error_no_openssl(self, size):
15131513
bigmsg = b'M' * size
15141514

15151515
with unittest.mock.patch.object(hmac, "_compute_digest_fallback") as f:
1516-
self.assertRaises(OverflowError, hmac.digest, bigkey, b'm', "md5")
1517-
self.assertRaises(OverflowError, hmac.digest, b'k', bigmsg, "md5")
1516+
self.assertIsInstance(hmac.digest(bigkey, b'msg', "md5"), bytes)
1517+
self.assertIsInstance(hmac.digest(b'key', bigmsg, "md5"), bytes)
15181518
f.assert_not_called()
15191519

15201520
@hashlib_helper.requires_openssl_hashdigest("md5")
@@ -1528,8 +1528,8 @@ def test_hmac_digest_overflow_error_no_builtin(self, size):
15281528
bigmsg = b'M' * size
15291529

15301530
with unittest.mock.patch.object(hmac, "_compute_digest_fallback") as f:
1531-
self.assertRaises(OverflowError, hmac.digest, bigkey, b'm', "md5")
1532-
self.assertRaises(OverflowError, hmac.digest, b'k', bigmsg, "md5")
1531+
self.assertIsInstance(hmac.digest(bigkey, b'msg', "md5"), bytes)
1532+
self.assertIsInstance(hmac.digest(b'key', bigmsg, "md5"), bytes)
15331533
f.assert_not_called()
15341534

15351535
@hashlib_helper.requires_hashdigest("md5", openssl=True)

0 commit comments

Comments
 (0)