]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-103256: Fix hmac algorithm to support fallback implementation (gh-103286)
authorDong-hee Na <donghee.na@python.org>
Fri, 7 Apr 2023 01:51:29 +0000 (10:51 +0900)
committerGitHub <noreply@github.com>
Fri, 7 Apr 2023 01:51:29 +0000 (10:51 +0900)
Co-authored-by: Gregory P. Smith <greg@krypto.org>
Lib/test/test_hmac.py
Misc/NEWS.d/next/Library/2023-04-06-17-28-36.gh-issue-103256.1syxfs.rst [new file with mode: 0644]
Modules/_hashopenssl.c

index 7cf99735ca39f00c23a24a71d78da44d8d263af2..a39a2c45ebc2e28e2254b1036d4ebe79dea3ecb5 100644 (file)
@@ -373,6 +373,16 @@ class TestVectorsTestCase(unittest.TestCase):
         with self.assertRaisesRegex(TypeError, r'required.*digestmod'):
             hmac.HMAC(key, msg=data, digestmod='')
 
+    def test_with_fallback(self):
+        cache = getattr(hashlib, '__builtin_constructor_cache')
+        try:
+            cache['foo'] = hashlib.sha256
+            hexdigest = hmac.digest(b'key', b'message', 'foo').hex()
+            expected = '6e9ef29b75fffc5b7abae527d58fdadb2fe42e7219011976917343065f58ed4a'
+            self.assertEqual(hexdigest, expected)
+        finally:
+            cache.pop('foo')
+
 
 class ConstructorTestCase(unittest.TestCase):
 
diff --git a/Misc/NEWS.d/next/Library/2023-04-06-17-28-36.gh-issue-103256.1syxfs.rst b/Misc/NEWS.d/next/Library/2023-04-06-17-28-36.gh-issue-103256.1syxfs.rst
new file mode 100644 (file)
index 0000000..894c046
--- /dev/null
@@ -0,0 +1,6 @@
+Fixed a bug that caused :mod:`hmac` to raise an exception when the requested
+hash algorithm was not available in OpenSSL despite being available
+separately as part of ``hashlib`` itself.  It now falls back properly to the
+built-in. This could happen when, for example, your OpenSSL does not include
+SHA3 support and you want to compute ``hmac.digest(b'K', b'M',
+'sha3_256')``.
index ee8c588020118cc7e9772eb21cea08887fde171e..7476e5dc7dd61e9a1709e1d24513f6787794f15c 100644 (file)
@@ -355,7 +355,7 @@ py_digest_by_name(PyObject *module, const char *name, enum Py_hash_type py_ht)
         }
     }
     if (digest == NULL) {
-        _setException(PyExc_ValueError, "unsupported hash type %s", name);
+        _setException(state->unsupported_digestmod_error, "unsupported hash type %s", name);
         return NULL;
     }
     return digest;