I have the following program in which I encrypt and decrypt a given text using AES_CBC with a key length of 256 bits. I would like to know why I am getting the error in the title when plaintext
, ciphertext
and checktext
are not globals and works fine when they are. Thank you!
#include <stdio.h>
#include <openssl\aes.h>
#include <openssl\rand.h>
#include <conio.h>
#include <openssl\des.h>
#define BIG_TEST_SIZE 1024
char plaintext[BIG_TEST_SIZE];
char ciphertext[BIG_TEST_SIZE];
char checktext[BIG_TEST_SIZE];
AES_KEY key;
char rkey[32+1];
static void hexdump(FILE *f,const char *title,const unsigned char *s,int l)
{
int n=0;
fprintf(f,"%s",title);
for( ; n < l ; ++n)
{
if((n%16) == 0)
fprintf(f,"\n%04x",n);
fprintf(f," %02x",s[n]);
}
fprintf(f,"\n");
}
int main(int argc, char* argv[])
{
//char plaintext[BIG_TEST_SIZE];
//char ciphertext[BIG_TEST_SIZE];
//char checktext[BIG_TEST_SIZE];
char saved_iv[32+1];
int err = 0;
RAND_pseudo_bytes((unsigned char*)rkey, sizeof rkey);
unsigned char iv[32+1]="01234567890123456789012345678901";
memcpy(saved_iv, iv, sizeof saved_iv);
strcpy((char*)plaintext,"aaa");
const size_t encslength = ((strlen(plaintext) + AES_BLOCK_SIZE) / AES_BLOCK_SIZE) * AES_BLOCK_SIZE;
// Straight encrypt
AES_set_encrypt_key((unsigned char*)rkey, 256, &key);
hexdump(stdout, "plaintext", (unsigned char*)plaintext, strlen(plaintext));
AES_cbc_encrypt((unsigned char*)plaintext, (unsigned char*)ciphertext, encslength, &key, (unsigned char*)iv,AES_ENCRYPT);
hexdump(stdout, "ciphertext", (unsigned char*)ciphertext, strlen(plaintext));
// Straight decrypt
AES_set_decrypt_key((unsigned char*)rkey, 256, &key);
memcpy(iv, saved_iv, sizeof iv);
AES_cbc_encrypt((unsigned char*)ciphertext, (unsigned char*)checktext, encslength, &key, (unsigned char*)iv,AES_DECRYPT);
hexdump(stdout, "checktext", (unsigned char*)checktext, strlen(plaintext));
getch();
}
Global and static variable initialize with zero while local variables are not. So when you define plaintext, ciphertext and checktext locally use memset to initialize them with zero. Your string should be null terminated but in your case it is not. ciphertext, checktext is not null terminated. while plaintext become null terminated due to strcpy call.