Reputation: 55
In implementing AES_128_CBC with OpenSSL, I have been given a key, IV, and some plaintext/cipher text pairs to see if my code is working as it should. Currently, when I decrypt I am getting the expected cipher text result. However, when the code attempts to decrypt cipher text back to plaintext, I am not getting the original plaintext. Instead, I am getting: ���S@�3��6�y�y�.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/aes.h>
#define BUFSIZE 1024
/* AES key for Encryption and Decryption */
const static unsigned char aes_key[]= . {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFF};
unsigned char iv[] = {0x98,0x76,0x54,0x32,0x10,0xFE,0xDC,0xBA,0x98,0x76,0x54,0x32,0x10,0xFE,0xDC,0xBA};
unsigned char tmpIv[sizeof(iv)];
/* Print Encrypted and Decrypted data packets */
void print_data(const char *title, const void* data, int len);
int main( ) {
/* Input data to encrypt */
unsigned char aes_input[BUFSIZE] = {0};
strcpy(aes_input, "Testing");
fprintf(stderr, "%s\n", aes_input);
print_data("Init IV: ", iv, sizeof(iv));
/* Init vector */
memcpy(tmpIv, iv, sizeof(iv));
/* Buffers for Encryption and Decryption */
unsigned char enc_out[sizeof(aes_input)];
unsigned char dec_out[sizeof(aes_input)];
unsigned char *e = enc_out;
/* AES-128 bit CBC Encryption */
AES_KEY enc_key, dec_key;
AES_set_encrypt_key(aes_key, sizeof(aes_key)*8, &enc_key);
AES_cbc_encrypt(aes_input, enc_out, strlen(aes_input), &enc_key, iv, AES_ENCRYPT);
fprintf(stderr, "Encrypted:");
while (*e) printf(" [%02x]", *e++);
printf("\n");
/* AES-128 bit CBC Decryption */
memset(tmpIv, 0x00, sizeof(iv));
memcpy(tmpIv, iv, sizeof(iv));
AES_set_decrypt_key(aes_key, sizeof(aes_key)*8, &dec_key);
AES_cbc_encrypt(enc_out, dec_out, strlen(aes_input), &dec_key, tmpIv, AES_DECRYPT);
fprintf(stderr, "The Plaintext After Decryption is: %s\n", dec_out);
return 0;
}
Upvotes: 1
Views: 484
Reputation: 18410
The problem is, that the iv
is modified in aes_cbc_encrypt()
for the next round of encryption.
Here, you overwrite the iv for decryption with the already modified vector:
/* AES-128 bit CBC Decryption */
memset(tmpIv, 0x00, sizeof(iv));
memcpy(tmpIv, iv, sizeof(iv));
AES_set_decrypt_key(aes_key, sizeof(aes_key)*8, &dec_key);
Since you already copy the correct vector above
/* Init vector */
memcpy(tmpIv, iv, sizeof(iv));
it should suffice to remove the memset()
/memcpy()
below to get a correct result.
Upvotes: 2