This should be a simple question, but I can't find any examples or figure out the answer from the openssl docs.
I want to encrypt exactly 128 bits, which should fit in one encryption block.
So I call EVP_EncyptInit_ex
, and then what?
Do I call EVP_EncryptUpdate_ex
(to encrypt the 128 bit block) and EVP_EncryptFinal_ex
(even though there is nothing more left to encrypt)?
Or only EVP_EncryptUpdate_ex
?
Or only EVP_EncryptFinal_ex
?
Here, you have already figured out the steps.
So, it will be
- EVP_encryptInit_ex
- EVP_EncryptUpdate_ex
- EVP_EncryptFinal_ex
EVP_EncryptFinal_ex
also take care of the fact that data is not in multiple of block lengths.
In my opinion, if you have only to use AES with no padding (EVP_ interfaces takes care of padding), then go for AES_encrypt
.
They are fairly easy to use.
//Step 1: Set encrypt key.
AES_KEY aeskey;
AES_set_encrypt_key(key, bits, &aeskey);
//Step2: Encrypt exactly 128 bits.
AES_encrypt(data, dataout, &aeskey);
AES encryption of 16 bytes without padding
Use the EVP_*
interfaces and disable padding on the block.
Use the EVP_*
interface because it supports engines and hardware acceleration, like AES-NI. The AES_encrypt
functions are software based and do not support alternate implementations. Also, its not readily apparent, but AES_encrypt
is not portable - some platforms suffer endianess issues.
You need to call EVP_CIPHER_CTX_set_padding
to ensure no padding is added. From the EVP_CIPHER_CTX_set_padding(3)
man page:
EVP_CIPHER_CTX_set_padding() enables or disables padding. By default
encryption operations are padded using standard block padding and the
padding is checked and removed when decrypting. If the pad parameter
is zero then no padding is performed, the total amount of data
encrypted or decrypted must then be a multiple of the block size or an
error will occur.
This function should be called after the context is set up for
encryption or decryption with EVP_EncryptInit_ex().
So your steps are:
- Call
EVP_CIPHER_CTX_new
to create a context
- Call
EVP_EncryptInit_ex
with the context
- Call
EVP_CIPHER_CTX_set_padding
on the context
- Call
EVP_EncryptUpdate_ex
to encrypt the data
- Call
EVP_EncryptFinal_ex
to retrieve the cipher text
Also see EVP Symmetric Encryption and Decryption on the OpenSSL wiki.