Hi all, i'm trying to write a function to encrypt/decrypt binary buffers
using different algorithms.

I'm getting an error when decrypting it, on the EVP_CipherFinal_ex function.
The error basically is WRONG_FINAL_BLOCK_LENGTH and triggers when i try to
decrypt a buffer that is not multiple of the block length (what is almost
always).

I understand that, when encrypting, the last block have to be padded to
encrypt it and so i do, but i dont save to the encrypted file the padded
bytes, because i need the encrypted data to be the same size than original.

What i dont understand is, if i enable padding on decrypt too, why
EVP_CipherFinal_ex fails to pad it? Should i pad it myself before starting
to decrypt?

I attached the function i'm using.

I thank you for any help or even for any hint on what's wrong,

Regards,


   int EVP_sym_crypt( unsigned char *buffer, int buflen, crypt_key_t *key,
const EVP_CIPHER *type, int enc_dec )
{
   int block_size = EVP_CIPHER_block_size( type );
   int key_length = EVP_CIPHER_key_length( type );
   EVP_CIPHER_CTX ctx;
   unsigned char *result = ( unsigned char * ) malloc( ( buflen +
block_size - 1 ) * sizeof( unsigned char ) );
   unsigned char *iv = ( unsigned char * ) malloc( key_length * sizeof(
unsigned char ) );
   int length, count = 0, tmp_count = 0;

   if ( !type )
   {
   Warn( "No algorithm" );
   free( result );
   return -1;
   }

   /* registers the error strings for all libcrypto functions */
   ERR_load_crypto_strings();

   memset(iv,0xaf,16);

   /*length = buflen - ( buflen % block_size );*/

   EVP_CIPHER_CTX_init ( &ctx );
   if (! EVP_CipherInit_ex( &ctx, type, NULL, key->key, iv, enc_dec ) )
   {
   Warn( "Error on EVP_CipherInit_ex" );
   ERR_print_errors_fp( stderr );
   EVP_CIPHER_CTX_cleanup( &ctx );
   free( result );
   return -1;
   }

   EVP_CIPHER_CTX_set_padding( &ctx, 1 );
   if ( !EVP_CipherUpdate( &ctx, result, &count, buffer, buflen ) )
   {
   Warn( "Error on EVP_CipherUpdate" );
   ERR_print_errors_fp( stderr );
   EVP_CIPHER_CTX_cleanup( &ctx );
   free( result );
   return -1;
   }

   /* 15790:error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:
*/
   /* wrong final block length:evp_enc.c:447: */
   if ( !EVP_CipherFinal_ex( &ctx, result + count, &tmp_count ) )
   {
   Warn( "Error on EVP_CipherFinal_ex" );
   ERR_print_errors_fp( stderr );
   EVP_CIPHER_CTX_cleanup( &ctx );
   free( result );
   return -1;
   }

   count += tmp_count;
   EVP_CIPHER_CTX_cleanup( &ctx );
   return 0;

}



--
Jorge Fernandez

Reply via email to