The Quantum Physicist
The Quantum Physicist

Reputation: 26256

How can I create OpenSSL output that compares to OpenSSL C++ output to generate unit tests?

I'm using a C++ wrapper for OpenSSL's AES-256-CBC encryption that follows the recipe from OpenSSL docs. It's meant to take some data to encrypt, a key and an initialization vector, and return encrypted bytes.

Now on the relative sense, encryption and decryption works fine. I can encrypt anything and decrypt it and retrieve the original data. However, I'd like to test it in the absolute sense. So, I'm using OpenSSL in command line/terminal to create encrypted data, and then inject it in my tests. But the outputs are not matching, and I'm not sure where to start or how to systematically tackle this.

To produce the hex data:

printf '%s' 'Hello world!' | xxd -ps

which returns 48656c6c6f20776f726c6421.

Then, to encrypt it with OpenSSL:

printf '%s' '48656c6c6f20776f726c6421' | xxd -r -ps | openssl aes-256-cbc -iv 00000000000000000000000000000000 -k 0000000000000000000000000000000000000000000000000000000000000000 -nosalt | xxd -ps

which gives f1b486ded0fd22dad9dbdab2205f61c2.

xxd -r converts hex to bytes, and xxd does the opposite. I tried also with plain Hello world! without xxd in the beginning, but also is wrong. The result always doesn't match what I get in the C++ OpenSSL code. What am I missing here?

Find a minimal, verifiable, complete example here of my code that demonstrates the result.

Upvotes: 3

Views: 437

Answers (1)

The Quantum Physicist
The Quantum Physicist

Reputation: 26256

I figured it out. The problem was that I'm using the wrong command line parameter. It should be -K for the key, not -k. This is the correct format:

printf '%s' '48656c6c6f20776f726c6421' | xxd -r -ps | openssl aes-256-cbc -iv 00000000000000000000000000000000 -K 0000000000000000000000000000000000000000000000000000000000000000 -nosalt | xxd -ps

and this gives the exact same result as OpenSSL in C++.

Upvotes: 3

Related Questions