From fe9b82d1526113f6f08e5de9b8d5e75ab1527bbd Mon Sep 17 00:00:00 2001 From: Paul Kehrer Date: Mon, 9 Sep 2013 22:09:21 -0500 Subject: add ECB support to create_block_cipher_context * This is a basic refactor to support ECB and CBC mode in this method. We can use this as a starting point to discuss a better solution. --- cryptography/bindings/openssl/api.py | 14 +++++++++++++- tests/bindings/test_openssl.py | 6 ++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/cryptography/bindings/openssl/api.py b/cryptography/bindings/openssl/api.py index 54a74d03..17823786 100644 --- a/cryptography/bindings/openssl/api.py +++ b/cryptography/bindings/openssl/api.py @@ -74,9 +74,11 @@ class API(object): assert evp_cipher != self._ffi.NULL # TODO: only use the key and initialization_vector as needed. Sometimes # this needs to be a DecryptInit, when? + iv = self._get_iv(mode) + res = self._lib.EVP_EncryptInit_ex( ctx, evp_cipher, self._ffi.NULL, cipher.key, - mode.initialization_vector + iv ) assert res != 0 @@ -85,6 +87,16 @@ class API(object): self._lib.EVP_CIPHER_CTX_set_padding(ctx, 0) return ctx + def _get_iv(self, mode): + # TODO: refactor this to visitor pattern + klass_name = mode.__class__.__name__ + if klass_name == 'CBC': + return mode.initialization_vector + elif klass_name == 'ECB': + return self._ffi.NULL + else: + raise NotImplementedError + def update_encrypt_context(self, ctx, plaintext): buf = self._ffi.new("unsigned char[]", len(plaintext)) outlen = self._ffi.new("int *") diff --git a/tests/bindings/test_openssl.py b/tests/bindings/test_openssl.py index 1579f002..e4b73460 100644 --- a/tests/bindings/test_openssl.py +++ b/tests/bindings/test_openssl.py @@ -11,6 +11,8 @@ # See the License for the specific language governing permissions and # limitations under the License. +import pytest + from cryptography.bindings.openssl import api @@ -28,3 +30,7 @@ class TestOpenSSL(object): for every OpenSSL. """ assert api.openssl_version_text().startswith("OpenSSL") + + def test_get_iv_invalid_mode(self): + with pytest.raises(NotImplementedError): + api._get_iv(None) -- cgit v1.2.3