OpenSSL: An example from the command line

This first post is going to be based on the “test_AES.c” file available here AES OpenSSL Code Sample. I wrote this short example when I was first learning and navigating my way through OpenSSL land.

At that time I couldn’t find any strong examples that demonstrated how to use OpenSSL in a general form from the command line without sockets.  My end goal was to create a Matlab Toolbox (which I completed, but more on that another time) that I could use to test various algorithms and modes.  I ended up stumbling on the EVP interface which provides a nice interface providing access to all supported algorithms (DES, AES, Blowfish, etc…),  key lengths, and mode.  More on the supported ciphers here.  In the coming weeks I plan to give a better explanation on modes, but a good introduction is already available.

Most of the examples I found had issues either in the encryption and the decryption for a few reasons.   This encryption example works:

EVP_EncryptInit(&ctx, EVP_aes_128_cbc(), (unsigned char *)mykey, (unsigned char *)iv);

EVP_EncryptUpdate(&ctx, (unsigned char *)ciphertext, &out_len, (unsigned char *)plaintext, in_len); //Call when needed

tmp_len += out_len; //Need to keep track of how much data has been encrypted

EVP_EncryptFinal(&ctx, (unsigned char *) &ciphertext[out_len], &out_len);  //Only call once – when done with encryption

tmp_len += out_len;

The problems were hidden by not zeroing out the plaintext buffer and reinitializing the variables needed to decrypt before reading the data back into it:


in_len = tmp_len;

out_len = tmp_len = 0;

So with that said, feel to take a look at the code, it scales up .  It builds under Windows and UNIX .

This command line example shows the code building under widows with Visual C++ Express:

cl test_AES.c /IC:\openssl\include /linkC:\openssl\lib\libeay32.lib

This example moves on to building on UNIX – I’m using gcc with OS X:

gcc test_AES.c -L/usr/local/ssl/lib/ -lssl -lcrypto

With all of that said, what example could possible be complete without output:

No encrypt: Hello World? – this is a test of AES! of which I’m curious to see if it really is working.
Encrypted: ;|?|??`A ??)?????#?’??7E??/
Decrypted: Hello World? – this is a test of AES! of which I’m curious to see if it really is working.


It should go with out saying this code is not industrial strength and is really just a fun example to have fun with.

OpenSSL can be downloaded here for: Windows & UNIX

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s