Merge pull request #196 from reaperhulk/evp-cipher-set-key-length

Set the key length when initializing an OpenSSL cipher context
diff --git a/cryptography/hazmat/bindings/openssl/backend.py b/cryptography/hazmat/bindings/openssl/backend.py
index 635d6a0..8de37d5 100644
--- a/cryptography/hazmat/bindings/openssl/backend.py
+++ b/cryptography/hazmat/bindings/openssl/backend.py
@@ -138,9 +138,23 @@
             iv_nonce = mode.nonce
         else:
             iv_nonce = self._backend.ffi.NULL
+        # begin init with cipher and operation type
         res = self._backend.lib.EVP_CipherInit_ex(ctx, evp_cipher,
                                                   self._backend.ffi.NULL,
-                                                  cipher.key, iv_nonce,
+                                                  self._backend.ffi.NULL,
+                                                  self._backend.ffi.NULL,
+                                                  operation)
+        assert res != 0
+        # set the key length to handle variable key ciphers
+        res = self._backend.lib.EVP_CIPHER_CTX_set_key_length(
+            ctx, len(cipher.key)
+        )
+        assert res != 0
+        # pass key/iv
+        res = self._backend.lib.EVP_CipherInit_ex(ctx, self._backend.ffi.NULL,
+                                                  self._backend.ffi.NULL,
+                                                  cipher.key,
+                                                  iv_nonce,
                                                   operation)
         assert res != 0
         # We purposely disable padding here as it's handled higher up in the
diff --git a/cryptography/hazmat/bindings/openssl/evp.py b/cryptography/hazmat/bindings/openssl/evp.py
index a5a97a5..4d0fb7f 100644
--- a/cryptography/hazmat/bindings/openssl/evp.py
+++ b/cryptography/hazmat/bindings/openssl/evp.py
@@ -60,6 +60,7 @@
 void EVP_CIPHER_CTX_init(EVP_CIPHER_CTX *);
 EVP_CIPHER_CTX *EVP_CIPHER_CTX_new();
 void EVP_CIPHER_CTX_free(EVP_CIPHER_CTX *);
+int EVP_CIPHER_CTX_set_key_length(EVP_CIPHER_CTX *, int);
 
 EVP_MD_CTX *EVP_MD_CTX_create();
 int EVP_MD_CTX_copy_ex(EVP_MD_CTX *, const EVP_MD_CTX *);