Hi I'm working on C on Linux.
I have a query related to symmetric key decryption.
I have generated an symmetric key using the below command.
openssl rand base64 512 > sym.key
Using this key (sym.key) I have encrypted a file with below command.
openssl enc -aes-256-cbc -in temp.txt -out temp.enc -kfile sym.key
It has generated an encrypted file temp.enc.
Now, I have to use the same key (sym.key) with EVP Decrypt API's and have to decrypt this encrypted file.
Could any one suggest me a better approach for this.
Here is the code
unsigned char* decode (unsigned char *key, int len)
{
BIO *b64, *bmem;
char *buffer = (char *)malloc(len);
memset (buffer, 0, len);
b64 = BIO_new(BIO_f_base64());
bmem = BIO_new_mem_buf(key, len);
bmem = BIO_push(b64, bmem);
BIO_read(bmem, buffer, len);
BIO_free_all(bmem);
return buffer;
}
void decrypt(char *file_name, char *key_file)
{
unsigned char *inbuff = NULL, *outbuff = NULL, *ckey = NULL;
char *buff = NULL;
unsigned int flen = 0, outlen2 = 0, outlen1 = 0, klen = 0;
FILE *fp = NULL, *kfp = NULL;
unsigned char iv[16] = {};
fp = fopen (file_name, "r");
if (NULL == fp)
{
printf ("Cannot open file : %s\n", file_name);
exit(1);
}
fseek (fp, 0, SEEK_END);
flen = ftell (fp);
rewind (fp);
kfp = fopen (key_file, "r");
if (NULL == kfp)
{
printf ("Cannot open file : %s\n", key_file);
exit(1);
}
fseek (kfp, 0, SEEK_END);
klen = ftell (kfp);
rewind (kfp);
inbuff = (unsigned char *)malloc(flen);
outbuff = (unsigned char *)malloc(flen * 2);
ckey = (unsigned char *)malloc(klen);
buff = (char *)malloc(klen);
fread (inbuff, sizeof(char), flen, fp);
fread (buff, sizeof(char), klen, kfp);
ckey = decode(buff, klen);
EVP_CIPHER_CTX ctx;
#if 1
if (! EVP_DecryptInit (&ctx, EVP_aes_256_cbc(), ckey, iv))
{
ERR_print_errors_fp(stderr);
EVP_CIPHER_CTX_cleanup(&ctx);
printf ("Error in Init\n");
exit(1);
}
if (! EVP_DecryptUpdate (&ctx, outbuff, &outlen1, inbuff, flen))
{
ERR_print_errors_fp(stderr);
EVP_CIPHER_CTX_cleanup(&ctx);
printf ("Error in Init\n");
exit(1);
}
if (! EVP_DecryptFinal (&ctx, outbuff + outlen1, &outlen2))
{
ERR_print_errors_fp(stderr);
EVP_CIPHER_CTX_cleanup(&ctx);
printf ("Error in Init\n");
exit(1);
}
EVP_CIPHER_CTX_cleanup(&ctx);
#endif
free (inbuff);
free (outbuff);
free (ckey);
fclose (fp);
fclose (kfp);
printf ("Outbuff:\n %s\n", outbuff);
}
Thank you.