AES
- C course
- Advanced
- Lesson 58/83
- 5 min
Learn symmetric encryption with AES.
What is AES?
AES is a symmetric block cipher. The same key is used for encryption and decryption. The block size is 16 bytes; the key can be 128, 192 or 256 bits. EVP_aes_256_cbc() selects a 256-bit key and CBC mode.
The OpenSSL EVP flow: EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();, EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv), EVP_EncryptUpdate(ctx, out, &outl, in, inl), EVP_EncryptFinal_ex(ctx, out + outl, &fl), EVP_CIPHER_CTX_free(ctx). key is 32 bytes, iv is 16 bytes. For testing, a done message is enough.
The encryption pattern
The flow: EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();, EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv);, EVP_EncryptUpdate(ctx, out, &outl, in, inl);, EVP_EncryptFinal_ex(ctx, out + outl, &fl);, EVP_CIPHER_CTX_free(ctx);.
The key and IV must have fixed lengths: key 32 bytes, IV 16 bytes. For testing, printf("aes done\n") is printed; rather than printing the ciphertext byte values, a fixed output is preferred. Decryption is done with EVP_DecryptInit_ex, EVP_DecryptUpdate, EVP_DecryptFinal_ex; the same key and IV are used.
Practice Encrypt with AES
Create a context with EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();. Initialize with EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, (const unsigned char *)"01234567890123456789012345678901", (const unsigned char *)"0123456789012345");. unsigned char out[64]; int outl = 0; EVP_EncryptUpdate(ctx, out, &outl, (const unsigned char *)"hello", 5);. int fl = 0; EVP_EncryptFinal_ex(ctx, out + outl, &fl);. EVP_CIPHER_CTX_free(ctx);. printf("aes done\n");.
Starter code
#include <stdio.h>
#include <openssl/evp.h>
// Create AES encryption context
// Initialize, update and finalize
// Print done
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
#include <openssl/evp.h>
int main(void) {
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, (const unsigned char *)"01234567890123456789012345678901", (const unsigned char *)"0123456789012345");
unsigned char out[64];
int outl = 0;
EVP_EncryptUpdate(ctx, out, &outl, (const unsigned char *)"hello", 5);
int fl = 0;
EVP_EncryptFinal_ex(ctx, out + outl, &fl);
EVP_CIPHER_CTX_free(ctx);
printf("aes done\n");
return 0;
}Expected output
aes done
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How many bits is the AES-256 key?
- 128 bits
- 256 bits Correct answer
- 64 bits
- 192 bits
Explanation: AES-256 uses a 256-bit key.
2 Match AES parts
| Term | Meaning |
|---|---|
EVP_aes_256_cbc |
Algorithm |
EVP_EncryptInit_ex |
Initialize |
EVP_EncryptUpdate |
Encrypt data |
EVP_EncryptFinal_ex |
Finalize |
3 EVP_EncryptInit_ex
EVP_EncryptInit_ex(ctx, ____, NULL, key, iv);
EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv);
Explanation: EVP_aes_256_cbc() selects the AES-256 CBC algorithm.