Michael Papageorge
Michael Papageorge

Reputation: 67

OpenSSL AES_ecb_encrypt padding option?

I have built a C project in Visual Studio that just encrypts input data with AES128 ECB cipher using OpenSSL.

If my input is 16bytes the output is correct by anything shorter than that I get wrong output.

#include <stdio.h>
#include <openssl/ssl.h>
#include <openssl/aes.h>

int main(void)
{
    unsigned char aesKey[] = 
    {
        0x2B, 0x7E, 0x15, 0x16, 0x28, 0xAE, 0xD2, 0xA6, 
        0xAB, 0xF7, 0x15, 0x88, 0x09, 0xCF, 0x4F, 0x3C
    };

    const unsigned char aesData[] = {0x35, 0x31, 0x30, 0x30}; // results in wrong output

    const unsigned char aesDataa[] = // results in correct output
    {
        0x35, 0x31, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 
        0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30 
    }; 

    unsigned char out[32];

    AES_KEY aes_key;
    AES_set_encrypt_key((const unsigned char *)aesKey, 128, &aes_key);
    AES_ecb_encrypt(aesDataa, out, &aes_key, AES_ENCRYPT);

    for (int i = 0; i < 33; i++)
        printf("%x", out[i]);

    return 1;
}

my example:

input hex: 0x35313030

key hex: 0x2B7E151628AED2A6ABF7158809CF4F3C

output hex: 0x2ba87a539758d476bb666bb525d14dbc

this site which is tested against others as well as an implementation in aes hardware accelerated microcontrollers:

output hex: 0xb13278c7f7413d515c549f4042a5de8c

If i put as an input this: 5100510051005100 then they both agree.

Do I have to introduce my own PKCS#7 padding? If so, can someone point me to that implementation?

I am trying to avoid using EVP as I will only be using this specific encryption method and cipher.

thanks

Upvotes: 2

Views: 1217

Answers (1)

dbush
dbush

Reputation: 223689

The AES 128 algorithm expects exactly 16 bytes as input. Your aesData array is only 4 bytes long, so this causes AES_ecb_encrypt to read past the end of the array which triggers undefined behavior.

Make the array 16 bytes wide:

const unsigned char aesData[16] = { 0x35, 0x31, 0x30, 0x30 }; 

This implicitly initializes the remaining elements to 0, so now the result matches what the linked website comes up with.

Also, you have an off-by-one error here:

for (int i = 0;i < 33;i++)
    printf("%x", out[i]);

Which reads past the end of the array. You want:

for (int i = 0;i < 32;i++)
    printf("%x", out[i]);

Also, only 16 bytes of the output array are being written to, so you're reading uninitialized bytes. So initialize out to all zeros:

unsigned char out[32] = {0};

Upvotes: 3

Related Questions