Hi,
I have a problem with the code below. There is a bug that I can't find and
fix.
This is the output when I try to run it:
[root@localhost test]# ./a.out sdcsdsdcd
Entering Encryption Stage:
String to encrypt: sdcsdsdcd
Encryption Successful
Entering Decryption Stage
Error Whilst DecryptFinal
19041:error:06065064:lib(6):func(101):reason(100):evp_enc.c:325:
Here is the source code:
#include
#include
#include
#include
#include
#define input_buf_size 1024
#define output_buf_size 1032
int main(int argc, char *argv[])
{
if (argc !=2)
{
printf("Usage: test1 \n");
exit(1);
}
char *string;
int encoutlen, decoutlen, enctotallen, dectotallen;
unsigned char iv[8];
unsigned char
password[16];
unsigned char enc_outbuf[output_buf_size];
char enc_inbuf[input_buf_size];
unsigned char dec_outbuf[input_buf_size];
char dec_inbuf[output_buf_size];
EVP_CIPHER_CTX ectx;
EVP_CIPHER_CTX dctx;
/*
* Begin the encode - decode
*
* Get our inputs and the random IV
*
*/
string = argv[1];
RAND_bytes(iv, 8);
RAND_bytes(password, 16);
printf("Entering Encryption Stage:\n\n");
printf("String to encrypt: %s\n\n", string);
EVP_CIPHER_CTX_init(&ectx);
EVP_EncryptInit(&ectx, EVP_bf_cbc(), password, iv);
bzero (&enc_inbuf, input_buf_size);
if(!EVP_EncryptUpdate(&ectx, enc_outbuf, &encoutlen, string,
strlen(string)))
{
printf("Error whilst EncryptUpdate\n");
return 0;
}
if(!EVP_EncryptFinal(&ectx, enc_outbuf + encoutlen, &enctotallen))
{
printf("Error Whilst EncryptFinal\n");
return 0;
}
encoutlen += enctotallen;
printf("Encryption Successful\n\n");
printf("Entering Decryption Stage\n\n");
EVP_CIPHER_CTX_init(&dctx);
EVP_DecryptInit(&dctx, EVP_bf_cbc(), password, iv);
bzero (&dec_inbuf, output_buf_size);
bzero (&dec_outbuf, input_buf_size);
if (!(EVP_DecryptUpdate(&dctx, dec_outbuf, &decoutlen, enc_outbuf,
output_buf_size)))
{
printf("Error Whilst DecryptUpdate\n");
return 0;
}
if (!(EVP_DecryptFinal(&dctx, dec_outbuf + decoutlen, &dectotallen)))
{
printf("Error Whilst DecryptFinal\n");
ERR_print_errors_fp(stdout);
return 0;
}
decoutlen += dectotallen;
printf("Decryption Successful\n\n");
printf("Decrypted String is: %s\n", dec_outbuf);
return 0;
}
Any help will be highly appreciated!
Regards
Peter