raise TypeError if you attempt to get the tag attribute on a decrypt
* To support this the _AEADCipherContext in base.py now needs to be
aware of whether it is encrypting/decrypting
diff --git a/cryptography/hazmat/primitives/ciphers/base.py b/cryptography/hazmat/primitives/ciphers/base.py
index 3f6ca0f..252a9fe 100644
--- a/cryptography/hazmat/primitives/ciphers/base.py
+++ b/cryptography/hazmat/primitives/ciphers/base.py
@@ -33,17 +33,17 @@
ctx = self._backend.create_symmetric_encryption_ctx(
self.algorithm, self.mode
)
- return self._wrap_ctx(ctx)
+ return self._wrap_ctx(ctx, True)
def decryptor(self):
ctx = self._backend.create_symmetric_decryption_ctx(
self.algorithm, self.mode
)
- return self._wrap_ctx(ctx)
+ return self._wrap_ctx(ctx, False)
- def _wrap_ctx(self, ctx):
+ def _wrap_ctx(self, ctx, encrypt):
if isinstance(self.mode, interfaces.ModeWithAAD):
- return _AEADCipherContext(ctx)
+ return _AEADCipherContext(ctx, encrypt)
else:
return _CipherContext(ctx)
@@ -69,10 +69,11 @@
@utils.register_interface(interfaces.AEADCipherContext)
@utils.register_interface(interfaces.CipherContext)
class _AEADCipherContext(object):
- def __init__(self, ctx):
+ def __init__(self, ctx, encrypt):
self._ctx = ctx
self._tag = None
self._updated = False
+ self._encrypt = encrypt
def update(self, data):
if self._ctx is None:
@@ -97,6 +98,9 @@
@property
def tag(self):
+ if not self._encrypt:
+ raise TypeError("The tag attribute is unavailable on a "
+ "decryption context")
if self._ctx is not None:
raise NotYetFinalized("You must finalize encryption before "
"getting the tag")
diff --git a/docs/hazmat/primitives/symmetric-encryption.rst b/docs/hazmat/primitives/symmetric-encryption.rst
index d123d15..f35357d 100644
--- a/docs/hazmat/primitives/symmetric-encryption.rst
+++ b/docs/hazmat/primitives/symmetric-encryption.rst
@@ -139,6 +139,7 @@
:return bytes: Returns the tag value as bytes.
:raises: :class:`~cryptography.exceptions.NotYetFinalized` if called
before the context is finalized.
+ :raises TypeError: If called on a decryption context.
.. _symmetric-encryption-algorithms:
diff --git a/tests/hazmat/primitives/utils.py b/tests/hazmat/primitives/utils.py
index b6f9e0f..58b9a91 100644
--- a/tests/hazmat/primitives/utils.py
+++ b/tests/hazmat/primitives/utils.py
@@ -344,3 +344,12 @@
encryptor.update(b"b" * 16)
with pytest.raises(AlreadyFinalized):
encryptor.finalize()
+ cipher = Cipher(
+ cipher_factory(binascii.unhexlify(b"0" * 32)),
+ mode_factory(binascii.unhexlify(b"0" * 24), b"0" * 16),
+ backend
+ )
+ decryptor = cipher.decryptor()
+ decryptor.update(b"a" * 16)
+ with pytest.raises(TypeError):
+ decryptor.tag