diff options
| author | Donald Stufft <donald@stufft.io> | 2013-08-10 14:32:08 -0400 |
|---|---|---|
| committer | Donald Stufft <donald@stufft.io> | 2013-08-10 14:32:08 -0400 |
| commit | b42af172c463f5ac0e5b36c39b9c8c0f328624ce (patch) | |
| tree | 9f6d58b682b0b8e0317423788fc0b13e71f6f4c7 /cryptography | |
| parent | a2e1f54907d880bfe48ac6030dbec52a17b67d1f (diff) | |
| download | cryptography-b42af172c463f5ac0e5b36c39b9c8c0f328624ce.tar.gz cryptography-b42af172c463f5ac0e5b36c39b9c8c0f328624ce.tar.bz2 cryptography-b42af172c463f5ac0e5b36c39b9c8c0f328624ce.zip | |
Ensure that a BlockCipher can only be used for one operation
This prevents trying to call encrypt() and then decrypt() on a
block cipher. It also enables finalize() to know what type of
finalization to call.
Diffstat (limited to 'cryptography')
| -rw-r--r-- | cryptography/primitives/block/base.py | 17 |
1 files changed, 15 insertions, 2 deletions
diff --git a/cryptography/primitives/block/base.py b/cryptography/primitives/block/base.py index 417b1ad8..2a6a5c37 100644 --- a/cryptography/primitives/block/base.py +++ b/cryptography/primitives/block/base.py @@ -21,16 +21,29 @@ class BlockCipher(object): self.cipher = cipher self.mode = mode self._ctx = api.create_block_cipher_context(cipher, mode) + self._operation = None def encrypt(self, plaintext): if self._ctx is None: raise ValueError("BlockCipher was already finalized") + + if self._operation is None: + self._operation = "encrypt" + elif self._operation != "encrypt": + raise ValueError("BlockCipher cannot encrypt when the operation is" + " set to %s" % self._operation) + return api.update_encrypt_context(self._ctx, plaintext) def finalize(self): if self._ctx is None: raise ValueError("BlockCipher was already finalized") - # TODO: this might be a decrypt context - result = api.finalize_encrypt_context(self._ctx) + + if self._operation == "encrypt": + result = api.finalize_encrypt_context(self._ctx) + else: + raise ValueError("BlockCipher cannot finalize the unknown " + "operation %s" % self._operation) + self._ctx = None return result |
