ThomasWest ThomasWest - 19 days ago 5
C Question

Encrypt AES with Multiple Keys

I have a single plain text which is

unsigned char plaintext[] = "Hi, this is trial number one";


For the keys, instead of using something like:

unsigned char key[16] = "azertyuiopqsdfg";


I decided to use tons of them like
"dog", "azkier", "jfieifdragon", ...


My code so far looks like this:

unsigned char *aes_encrypt(unsigned char *plaintext, unsigned char *key)
{
EVP_CIPHER_CTX *ctx;
ctx = EVP_CIPHER_CTX_new();
unsigned char iv[16] = "0000000000000000";

int c_len = strlen(plaintext) + AES_BLOCK_SIZE;
int f_len = 0;
unsigned char *ciphertext = malloc(c_len);

EVP_EncryptInit_ex(ctx, EVP_aes_128_cbc(), NULL, key, iv);

EVP_EncryptUpdate(ctx, ciphertext, &c_len, plaintext, strlen(plaintext));

EVP_EncryptFinal_ex(ctx, ciphertext+c_len, &f_len);

EVP_CIPHER_CTX_free(ctx);

return ciphertext;
}


When I compile and run, the output looks something like this:

the key: dog
the plain: Hi, this is trial number one
ciphertext: 157a320

the key: azkier
the plain: Hi, this is trial number one
ciphertext: 157a320

.....


My questions are:

why I always get the same ciphertext even though I'm using different keys?

Also, why the ciphertext is really short? My plaintext is pretty long tho.

Thanks.

Update --> The way I call the aes_encrypt is like this:

unsigned char plaintext[] = "Hi, this is trial number one";
unsigned char *cipher;
cipher = aes_encrypt(plaintext, "dog");
printf("The cipher is: %x\n", cipher);
free(cipher);

unsigned char *cipher;
cipher = aes_encrypt(plaintext, "azkier");
printf("The cipher is: %x\n", cipher);
free(cipher);

Answer

In your test code:

printf("The cipher is: %x\n", cipher);

Well, of course that doesn't work -- %x prints the address of cipher as hexadecimal, not its contents. If you want a dump of the contents of cipher, you'll need to loop over each byte yourself.

Additionally, the key parameter to EVP_EncryptInit_ex is a fixed-length buffer, whose size is set based on the cipher you're using. It is not a string. Passing a short string may cause unpredictable behavior, as whatever data happens to be stored after the string ends may be used as part of the key.