Added backend check to hmac primitives
diff --git a/cryptography/hazmat/primitives/hmac.py b/cryptography/hazmat/primitives/hmac.py
index 76d658a..9e1d8d0 100644
--- a/cryptography/hazmat/primitives/hmac.py
+++ b/cryptography/hazmat/primitives/hmac.py
@@ -16,13 +16,20 @@
import six
from cryptography import utils
-from cryptography.exceptions import AlreadyFinalized, InvalidSignature
+from cryptography.exceptions import (
+ AlreadyFinalized, InvalidSignature, UnsupportedInterface)
+
+from cryptography.hazmat.backends.interfaces import HMACBackend
from cryptography.hazmat.primitives import constant_time, interfaces
@utils.register_interface(interfaces.HashContext)
class HMAC(object):
def __init__(self, key, algorithm, backend, ctx=None):
+ if not isinstance(backend, HMACBackend):
+ raise UnsupportedInterface(
+ "Backend object does not implement HMACBackend")
+
if not isinstance(algorithm, interfaces.HashAlgorithm):
raise TypeError("Expected instance of interfaces.HashAlgorithm.")
self.algorithm = algorithm
diff --git a/docs/hazmat/primitives/hmac.rst b/docs/hazmat/primitives/hmac.rst
index 6ca9e16..ce4e880 100644
--- a/docs/hazmat/primitives/hmac.rst
+++ b/docs/hazmat/primitives/hmac.rst
@@ -56,6 +56,10 @@
:class:`~cryptography.hazmat.backends.interfaces.HMACBackend`
provider.
+ :raises cryptography.exceptions.UnsupportedInterface: This is raised if the
+ provided ``backend`` does not implement
+ :class:`~cryptography.hazmat.backends.interfaces.HMACBackend`
+
.. method:: update(msg)
:param bytes msg: The bytes to hash and authenticate.
diff --git a/tests/hazmat/primitives/test_hmac.py b/tests/hazmat/primitives/test_hmac.py
index 88bed52..24988e7 100644
--- a/tests/hazmat/primitives/test_hmac.py
+++ b/tests/hazmat/primitives/test_hmac.py
@@ -21,8 +21,10 @@
from cryptography import utils
from cryptography.exceptions import (
- AlreadyFinalized, UnsupportedHash, InvalidSignature
-)
+ AlreadyFinalized, UnsupportedHash, InvalidSignature,
+ UnsupportedInterface)
+
+from cryptography.hazmat.backends.interfaces import HMACBackend
from cryptography.hazmat.primitives import hashes, hmac, interfaces
from .utils import generate_base_hmac_test
@@ -52,8 +54,11 @@
h.update(six.u("\u00FC"))
def test_copy_backend_object(self):
- pretend_hmac = pretend.stub()
- pretend_backend = pretend.stub(hmacs=pretend_hmac)
+ @utils.register_interface(HMACBackend)
+ class PretendBackend(object):
+ pass
+
+ pretend_backend = PretendBackend()
copied_ctx = pretend.stub()
pretend_ctx = pretend.stub(copy=lambda: copied_ctx)
h = hmac.HMAC(b"key", hashes.SHA1(), backend=pretend_backend,
@@ -104,3 +109,10 @@
def test_unsupported_hash(self, backend):
with pytest.raises(UnsupportedHash):
hmac.HMAC(b"key", UnsupportedDummyHash(), backend)
+
+
+def test_invalid_backend():
+ pretend_backend = object()
+
+ with pytest.raises(UnsupportedInterface):
+ hmac.HMAC(b"key", hashes.SHA1(), pretend_backend)