CTR-AES256 Encrypt does not match OpenSSL -aes-256-ctr <-- this post did not help
I tried the following C implementation of Openssl EVP function for AES-128-CTR encryption but the results I am getting are incorrect compared to the command line OpenSSL result.
The odd part is that when I try with a larger size of Plaintext (600 bytes or more), only last 600 bytes of cipher is different between C code and Command line. If required I can paste that result here as well.
C code implementation of AES-128-CTR
static const unsigned char key[16] = {
0x00, 0x01, 0x02, 0x03,
0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b,
0x0c, 0x0d, 0x0e, 0x0f,
};
static const unsigned char iv[16] = {
0x01, 0x23, 0x45, 0x67,
0x89, 0xab, 0xcd, 0xef,
0x88, 0x88, 0x88, 0x88,
0xC0, 0x00, 0x00, 0x00,
};
FILE *fp_output = fopen("cipherCode.bin", "wb");
// Encrypt Plaintext
EVP_CIPHER_CTX *ctx;
int outlen;
unsigned char cipher[size];
if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();
if(!(EVP_EncryptInit_ex(ctx, EVP_aes_128_ctr(), NULL, key, iv))) handleErrors();
if(!(EVP_EncryptUpdate(ctx, cipher, &outlen, plaintext, size))) handleErrors();
if(!(EVP_EncryptFinal_ex(ctx, cipher + outlen, &outlen))) handleErrors();
/*---Edit----
// EVP_CIPHER_CTX_set_padding(ctx, 0); <-- removed this as it isnt necessary
-----------*/
EVP_CIPHER_CTX_free(ctx);
// Write result cipher into output file
fwrite((unsigned char *)&cipher[0], outlen, 1, fp_output);
fclose(fp_output);
OpenSSL command line:
openssl enc -aes-128-ctr -in plaintext.bin -out cipherCL.bin -K 000102030405060708090a0b0c0d0e0f -iv 0123456789abcdef88888888c0000000 -p -nopad
Same Plaintext, key and IV used for both.
Input:
Plaintext:
0000000 ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
Ouput:
Hexdiff (shortened for clarity):
Visuel HexDiff v 0.0.53 by tTh 2007 dec 7bits
0 00 00 00 00 00 00 00 00 10 90 66 01 00 00 00 00 f
** cipherCode.bin 16 0 0%
0 1e a4 43 3f d8 4c 8c b7 1a e7 f0 af 85 0c d2 c2 C? L
** cipherCL.bin 16 0 0%
I found the issue in my program. I was not defining the cipher variable as static. Now that I define it static, the correct cipher data is written to the file.
Why static worked? I called a ciphering function to calculate the cipher and then return the cipher. Since the cipher was not declared as static, it lost its value after exiting the function, thus the data returned was not the same as the data in the cipher. After declaring cipher as static, the value of cipher retained after function call and wrote correct information in the file.