Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

8 byte missing on EVP_DecryptFinal

Tags:

c

openssl

this is my first question so please tell me if I do something wrong :).

My problem is I use

EVP_DecryptInit(&ctx1, EVP_des_ecb(), tmpkey, NULL);
EVP_DecryptUpdate(&ctx1, keysigout, &outlu ,keysigin, keysigfilelength);
EVP_DecryptFinal(&ctx1, keysigout, &outlf);
printf("DECLEN:%i",outlu + outlf);

to decrypt a binary file. The file is 248 bytes long but the printf only tells me EVP decrypted 240 bytes. keysigfilelength is 248 and should tell the update that 248 bytes need to be decrypted.

I dont understand why this doesnt work and would be happy if you can enlighten me.

Edit: I just encrypted a file manually with the command

openssl enc -e -des-ecb -in test.txt -out test.bin -K 00a82b209cbeaf00

and it grew by 8 bytes :O. I still don't know where they come from but I don't think the general error I have in my program is caused by this.

The context of this whole problem is an information security course at my university. We got similar Tasks with different algorithms, but even someone who has done his program successfully couldnt figure out where the problem in my program is.

Is it ok to post my whole program for you?

like image 584
outsmartin Avatar asked Jan 06 '12 22:01

outsmartin


1 Answers

I hope its fine to answer my own question.

EVP_DecryptUpdate(&ctx1, keysigout, &outlu ,keysigin, keysigfilelength);
EVP_DecryptFinal(&ctx1, keysigout + outlu, &outlf);

The problem was the missing outlu, DecryptFinal tried to decrypt the whole block again. When i added the outlu i got 7 byte in outlf, and it worked. For future reference i add the whole function below. It expects the key and iv to be one block of data.

int decrypt(const EVP_CIPHER *cipher,unsigned char *key, unsigned char *encryptedData, int encryptedLength,unsigned int * length, unsigned char ** decryptedData)
{
  int decryptedLength = 0, lastDecryptLength = 0, ret;
  unsigned char * iv = NULL;
  EVP_CIPHER_CTX *cryptCtx = EVP_CIPHER_CTX_new();
  EVP_CIPHER_CTX_init(cryptCtx);
  *decryptedData = malloc (encryptedLength * sizeof(char));

  if(cipher->iv_len != 0) iv = key + cipher->key_len;

  EVP_DecryptInit_ex(cryptCtx, cipher, NULL, key, iv);
  EVP_DecryptUpdate(cryptCtx, *decryptedData, &decryptedLength, encryptedData, encryptedLength);
  ret = EVP_DecryptFinal_ex(cryptCtx, *decryptedData + decryptedLength, &lastDecryptLength);

  *length = decryptedLength + lastDecryptLength;

  EVP_CIPHER_CTX_free(cryptCtx);
  EVP_cleanup();
  return ret;
}
like image 57
outsmartin Avatar answered Oct 15 '22 08:10

outsmartin