I wrote a program to encrypt a string with PolarSSL AES-CBC
this is my code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <polarssl/aes.h>
#include <polarssl/havege.h>
int main()
{
char buff[2][64] = {"Who can tell me WHY?", ""};
havege_state hs;
int retval;
unsigned char IV[16];
aes_context enc_ctx;
aes_context dec_ctx;
aes_setkey_enc(&enc_ctx, "password", 256);
aes_setkey_dec(&dec_ctx, "password", 256);
havege_init(&hs);
havege_random(&hs, IV, 16);
//encrypt
aes_crypt_cbc(&enc_ctx, AES_ENCRYPT, 64, IV, buff[0], buff[1]);
havege_random(&hs, IV, 16);
//decrypt
aes_crypt_cbc(&dec_ctx, AES_DECRYPT, 64, IV, buff[1],buff[0]);
printf("After decrypt:%s\n", buff[0]);
return 0;
}
But when I run it, I just got the wrong text after it decrypt.
I don't understand AES algorithm clearly, because my english is very bad, It's too hard for me to read some articles.
-------------------------Added By midCat--------------------------------------------
I followed you advice, and Change me code now I use the same IV and 256-bit key, this is the new code
int main()
{
char buff[2][64] = {"ABCDEFGHIJKLMN", ""};
havege_state hs;
int retval;
unsigned char IV[16];
unsigned char IV2[16];
unsigned char key[32];
aes_context enc_ctx;
aes_context dec_ctx;
havege_init(&hs);
havege_random(&hs, IV, 16);
havege_random(&hs, key, 32);
strncpy(IV, IV2, 16); //copy IV
aes_setkey_enc(&enc_ctx, key, 256);
aes_setkey_dec(&dec_ctx, key, 256);
//encrypt
aes_crypt_cbc(&enc_ctx, AES_ENCRYPT, 64, IV, buff[0], buff[1]);
printf("Before encrypt:%s\n", buff[0]);
//decrypt
aes_crypt_cbc(&dec_ctx, AES_DECRYPT, 64, IV2, buff[1],buff[0]);
printf("After decrypt:%s\n", buff[0]);
return 0;
}
I compiler it, and run for many times, got the same output:
Before encrypt:ABCDEFGHIJKLMN
After decrypt:ABCDEFGHYC
LMN
How to got IV
?