8000 gh-103256: Fix hmac algorithm to support fallback implementation (gh-… · python/cpython@8740fd8 · GitHub
[go: up one dir, main page]

Skip to content

Commit 8740fd8

Browse files
miss-islingtoncorona10gpshead
authored
gh-103256: Fix hmac algorithm to support fallback implementation (gh-103286)
(cherry picked from commit efb0a2c) Co-authored-by: Dong-hee Na <donghee.na@python.org> Co-authored-by: Gregory P. Smith <greg@krypto.org>
1 parent bbe04d9 commit 8740fd8

File tree

3 files changed

+17
-1
lines changed

3 files changed

+17
-1
lines changed

Lib/test/test_hmac.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -373,6 +373,16 @@ def test_with_digestmod_no_default(self):
373373
with self.assertRaisesRegex(TypeError, r'required.*digestmod'):
374374
hmac.HMAC(key, msg=data, digestmod='')
375375

376+
def test_with_fallback(self):
377+
cache = getattr(hashlib, '__builtin_constructor_cache')
378+
try:
379+
cache['foo'] = hashlib.sha256
380+
hexdigest = hmac.digest(b'key', b'message', 'foo').hex()
381+
expected = '6e9ef29b75fffc5b7abae527d58fdadb2fe42e7219011976917343065f58ed4a'
382+
self.assertEqual(hexdigest, expected)
383+
finally:
384+
cache.pop('foo')
385+
376386

377387
class ConstructorTestCase(unittest.TestCase):
378388

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
Fixed a bug that caused :mod:`hmac` to raise an exception when the requested
2+
hash algorithm was not available in OpenSSL despite being available
3+
separately as part of ``hashlib`` itself. It now falls back properly to the
4+
built-in. This could happen when, for example, your OpenSSL does not include
5+
SHA3 support and you want to compute ``hmac.digest(b'K', b'M',
6+
'sha3_256')``.

Modules/_hashopenssl.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -360,7 +360,7 @@ py_digest_by_name(PyObject *module, const char *name, enum Py_hash_type py_ht)
360360
}
361361
}
362362
if (digest == NULL) {
363-
_setException(PyExc_ValueError, "unsupported hash type %s", name);
363+
_setException(state->unsupported_digestmod_error, "unsupported hash type %s", name);
364364
return NULL;
365365
}
366366
return digest;

0 commit comments

Comments
 (0)
0