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,
Here, you have already figured out the steps. So, it will be
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:
EVP_CIPHER_CTX_new
to create a contextEVP_EncryptInit_ex
with the contextEVP_CIPHER_CTX_set_padding
on the contextEVP_EncryptUpdate_ex
to encrypt the dataEVP_EncryptFinal_ex
to retrieve the cipher textAlso see EVP Symmetric Encryption and Decryption on the OpenSSL wiki.