I have a simple program that encrypts files in a directory. I can iterate through and everything works perfectly. This is using pub/priv key pair. When decrypting one file at a time, it works as it should. However, if there are multiple files in a directory, or even if I put the filenames in a vector and fopen them for reading/writing respectively, it ONLY decrypts the LAST file in the vector/directory. How is this even possible? It fails on everyone of them on OpenFinal(). Here is the function and heart of the program. Everything else is solid. As stated, it works as a standalone program if I just decrypt one file manually or if there is just ONE file in the directory or vector.
Any help would be appreciated. This makes no sense at all. It seems like an implementation issue on their end.
void handleErrors(void)
{
ERR_print_errors_fp(stderr);
abort();
}
int envelope_open(EVP_PKEY *priv_key, unsigned char *ciphertext,
int ciphertext_len, unsigned char *encrypted_key,
int encrypted_key_len, unsigned char *iv,
unsigned char **plaintext, int *plaintext_len)
{
EVP_CIPHER_CTX *ctx;
int len = 0, ret = 0;
unsigned char *tmpptxt = NULL;
if((ctx = EVP_CIPHER_CTX_new()) == NULL)
return 0;
if ((tmpptxt = (unsigned char*)malloc(ciphertext_len)) == NULL)
{
printf("tmptxt error!\n");
handleErrors();
}
if(EVP_OpenInit(ctx, EVP_aes_256_cbc(), encrypted_key, encrypted_key_len,
iv, priv_key) != 1)
{
printf("OpenInit error\n");
handleErrors();
}
if(EVP_OpenUpdate(ctx, tmpptxt, &len, ciphertext, ciphertext_len) != 1)
{
printf("OpenUpdate error\n");
handleErrors();
}
*plaintext_len = len;
if(EVP_OpenFinal(ctx, tmpptxt + len, &len) != 1)
{
printf("OpenFinal error\n");
handleErrors();
}
*plaintext_len += len;
*plaintext = tmpptxt;
tmpptxt = NULL;
ret = 1;
err:
EVP_CIPHER_CTX_free(ctx);
free(tmpptxt);
return ret;
}
What I have tried:
Manually decrypting it in a separate program without a vector and works perfectly so the envelope_open() function does work. It just doesn't work with multiple files for some strange reason.