X-Git-Url: https://wagner.pp.ru/gitweb/?a=blobdiff_plain;f=ctypescrypto%2Fcipher.py;h=c2053e988354574d299e0bd1c36e6cf98c7ff701;hb=911a7fb801bfd74cb50b08fa77ae5c50d1890d8d;hp=1ea4f797d7f4d87e88e86832ae438651d18dde68;hpb=8afcf4f352ef2f967adbe84837d4abc5e9b6ee0c;p=oss%2Fctypescrypto.git diff --git a/ctypescrypto/cipher.py b/ctypescrypto/cipher.py index 1ea4f79..c2053e9 100644 --- a/ctypescrypto/cipher.py +++ b/ctypescrypto/cipher.py @@ -1,3 +1,7 @@ +""" +access to symmetric ciphers from libcrypto + +""" from ctypes import create_string_buffer,c_char_p,c_void_p,c_int,c_long,byref,POINTER from ctypescrypto import libcrypto from ctypescrypto.exception import LibCryptoError @@ -101,6 +105,10 @@ class Cipher: """ self._clean_ctx() + # Check key and iv length + if key is None: + raise ValueError("No key specified") + key_ptr = c_char_p(key) iv_ptr = c_char_p(iv) self.ctx = libcrypto.EVP_CIPHER_CTX_new() @@ -111,7 +119,22 @@ class Cipher: enc = 1 else: enc = 0 - result = libcrypto.EVP_CipherInit_ex(self.ctx, cipher_type.cipher, None, key_ptr, iv_ptr, c_int(enc)) + if not iv is None and len(iv) != cipher_type.iv_length(): + raise ValueError("Invalid IV length for this algorithm") + + if len(key) != cipher_type.key_length(): + if (cipher_type.flags() & 8) != 0: + # Variable key length cipher. + result = libcrypto.EVP_CipherInit_ex(self.ctx, cipher_type.cipher, None, None, None, c_int(enc)) + result=libcrypto.EVP_CIPHER_CTX_set_key_length(self.ctx,len(key)) + if result == 0: + self._clean_ctx() + raise CipherError("Unable to set key length") + result = libcrypto.EVP_CipherInit_ex(self.ctx, None, None, key_ptr, iv_ptr, c_int(enc)) + else: + raise ValueError("Invalid key length for this algorithm") + else: + result = libcrypto.EVP_CipherInit_ex(self.ctx, cipher_type.cipher, None, key_ptr, iv_ptr, c_int(enc)) if result == 0: self._clean_ctx() raise CipherError, "Unable to initialize cipher" @@ -170,7 +193,7 @@ class Cipher: raise CipherError, "Cipher operation is already completed" outbuf=create_string_buffer(self.block_size) self.cipher_finalized = True - outlen=c_int() + outlen=c_int(0) result = libcrypto.EVP_CipherFinal_ex(self.ctx,outbuf , byref(outlen)) if result == 0: self._clean_ctx() @@ -208,4 +231,4 @@ libcrypto.EVP_CIPHER_nid.argtypes=(c_void_p,) libcrypto.EVP_CipherUpdate.argtypes=(c_void_p,c_char_p,POINTER(c_int),c_char_p,c_int) libcrypto.EVP_get_cipherbyname.restype=c_void_p libcrypto.EVP_get_cipherbyname.argtypes=(c_char_p,) - +libcrypto.EVP_CIPHER_CTX_set_key_length.argtypes=(c_void_p,c_int)