Encrypt data with AES-CBC mode

In order to encrypt data with AES you should first have a key to use. If you are not familiar with key generation, please check out How to generate an AES key for more information on that.

Note: Please understand that just encrypting data with AES-CBC does not keep the data safe from modification or viewing. If still have to protect the key from others and the integrity of the data. This article only shows you how to use the AES API to encrypt some data with the AES-CBC mode.

In order to start using AES you should add the header file for the module to your file:

#include "mbedtls/aes.h"

Declare the variables needed for AES encryption.

mbedtls_aes_context aes;

unsigned char key[32];
unsigned char iv[16];

unsigned char input [128];
unsigned char output[128];

size_t input_len = 40;
size_t output_len = 0;

We assume you already fill the variable named key with the 32 bytes of the AES key (see "How to generate an AES key") and iv with 16 bytes of random data for use as the Initialization Vector (IV) and that you fill input with 40 bytes of input data and zeroized the rest of input.

The CBC mode for AES assumes that we provide data in blocks of 16 bytes. As we only have 40 bytes of data, we have to extend the input to contain 48 bytes of data instead. There are multiple ways to pad input data. The simplest is to just add zeroes to the end. This is only secure if we also transmit the original length of the input data (40 in this case) securely to the other side as well. For this example we will use padding with zeroes.

First we initialize the AES context with our key and then we encrypt the data (with padding) to the output buffer with our iv.

mbedtls_aes_setkey_enc( &aes, key, 256 );
mbedtls_aes_crypt_cbc( &aes, MBEDTLS_AES_ENCRYPT, 24, iv, input, output );

Now the first 48 bytes of the output buffer contain the encrypted data. This data is only protected for confidentiality purposes. You need to send the length of the input data, the IV and the output buffer to the other side while protecting the integrity of those values. In addition the other side needs the key without anybody ever knowing it. Usually this means making a hash over the length of the input data, the IV and the output buffer and encrypting this hash and the AES key with the public RSA key of the other party using the PKCS#1 encrypt function.

Did this help?