Skip to main content

AES MCAL Module

Supported STM32 families: H5
Not supported: F4, F7, G4, H7, L4, U3, U5

This module provides an abstraction layer for the AES hardware accelerator (AES, on some families CRYP) of STM32 MCUs: the encryption and decryption with the 128-bit and 256-bit keys in the ECB, CBC and CTR modes and the authenticated encryption GCM, GMAC and CCM with the tag generation and verification. It offers a one-shot request, an incremental interface (start - update - finish) and the data transfer in DMA, interrupt or polling mode. It is a low-level MCAL module: it owns the AES hardware, the application and the other modules never touch the registers.

The public interface (Aes_Port.h, Aes_Types.h) is identical for all supported families. The implementation for a family lives in its own branch (Dev/<Family> for development, Releases/<Family> for the released versions), so a module or an application written against the interface does not change when the MCU family changes.

This README is the landing page and the specification of the interface (master). The family branches contain their own README with everything that is specific to the family: the instances of the device, their settings and the status of the implementation.

Status: design. No implementation exists yet, the interface below is a proposal. Stories and branches follow.


Intent and purpose​

  • Typical users are the encryption of stored data (a configuration, a log, a file), the authenticated encryption of a communication (an encrypted frame with a tag: a radio, a bootloader, the record layer of a TLS stack) and the decryption of a firmware image during an update, all of them at the speed of the accelerator (a block in tens of cycles) and without the CPU when the DMA is used.
  • The accelerator has no idea of a message: it knows blocks, a phase machine (header, payload, final) and a bunch of registers for the key, the initialization vector, the counter and the tag. The user wants "encrypt this buffer with this key, this IV and this additional data and give me the ciphertext and the tag". The module builds the initial counter blocks (GCM), the header blocks and the counter blocks of CCM, runs the phases in the right order, handles the last incomplete block of the CTR / GCM / CCM payload, reads the tag and, when decrypting, verifies it and reports a mismatch.
  • The keys are the most sensitive data of the system. The module never keeps a key after the request ends, clears the key registers of the hardware at the end of every request, and, where the device has the secure AES (the Saes module), it can use the shared key that was loaded by the Saes module - the key travels on the hardware bus and the CPU never sees it.
  • The module hides the differences between the families: the register layout, the supported modes and key sizes, the suspend / resume registers and the DMA requests differ, the interface stays the same.

What the module is not: it does not protect against the side-channel attacks (the secure AES, Saes module, does), it does not implement the key management (storage, derivation, wrapping - a middleware on the top of the Saes module) and it does not implement the software fall-back of a mode the device does not have.


Concept​

A request is described by the mode, the direction, the key, the initialization data and the buffers:

ItemMeaning
Mode (aes_Mode_t)AES_MODE_ECB, AES_MODE_CBC, AES_MODE_CTR, AES_MODE_GCM, AES_MODE_GMAC (authentication without encryption), AES_MODE_CCM. Only the modes of the device are accepted.
DirectionAES_ENCRYPT, AES_DECRYPT.
Keyaes_KeySource_t: AES_KEY_SOFTWARE (key bytes of 16 or 32 bytes, 24 on the CRYP peripherals) or AES_KEY_SHARED (the key loaded in the Saes module, the CPU does not see it).
Initialization dataIV (CBC), the initial counter block (CTR), the 12-byte IV (GCM), the nonce of 7 ... 13 bytes and the tag length of 4 ... 16 bytes (CCM).
Additional data (AAD)The authenticated, not encrypted header of GCM, GMAC and CCM.
DataThe input and the output buffer (they may be the same buffer), the size in bytes.
TagThe authentication tag: written by the encryption, verified by the decryption.

Rules:

  1. A request is accepted when the peripheral is idle (Aes_Get_State) and the parameters are valid: a supported mode and key size, non-AES_NULL_PTR buffers, the size a multiple of 16 bytes for ECB and CBC (for the stream modes CTR, GCM and CCM any size), the IV and the tag of the valid length. Otherwise the call returns an error and the hardware is not touched.
  2. Aes_Set_Process is non-blocking in the DMA and ISR mode (the complete callback reports the end) and served by Aes_Task in the POLL mode. The same request and the same callbacks are used in all modes.
  3. The decryption with a tag (GCM, GMAC, CCM) compares the calculated tag with the received one in constant time; a mismatch is reported as AES_XFER_ERROR_TAG_MISMATCH and the output buffer is cleared, so that an unauthenticated plaintext is never released.
  4. The key registers of the hardware are write-only; the module clears them (and the IV registers) at the end of every request and at Aes_Deinit. The application clears its own copy of the key.
  5. The incremental interface keeps the phase of the message: Aes_Set_Start (mode, key, IV, the sizes of the AAD and the payload for the modes that need them), Aes_Set_UpdateAad, Aes_Set_Update (many times), Aes_Set_Finish (the tag). A call in the wrong phase returns an error.
  6. Aes_Get_Context / Aes_Set_Context suspend and resume an incremental message (the hardware suspend registers and the state of the module are saved into a context of the user); a message of a higher priority can use the peripheral in between. The context does not contain the key - it is given again at the resume.

Supported families​

Every family gets its own story, its own tasks and its own branches Dev/<Family> and Releases/<Family> cut from this master.

FamilyBranchPeripheralStatus
STM32H5Dev/STM32H5AES on the lines with the crypto (STM32H533, H553, H573, H5F): 128 / 256-bit keys, ECB, CBC, CTR, GCM, GMAC, CCM, two DMA channels (in, out), shared key with SAES, suspend / resumeplanned (first)
STM32U5Dev/STM32U5AES (and SAES)planned
STM32G4, STM32L4Dev/STM32G4, Dev/STM32L4AES on the lines that have it: 128 / 256-bit keys, ECB, CBC, CTR, GCM, GMAC, CCMplanned
STM32H7Dev/STM32H7CRYP on the crypto lines: 128 / 192 / 256-bit keys, ECB, CBC, CTR, GCM, CCM (and DES / TDES, not in the first version)planned
STM32F4, STM32F7Dev/STM32F4, Dev/STM32F7CRYP on the crypto lines (AES 128 / 192 / 256, DES / TDES not in the first version)planned
STM32U3Dev/STM32U3device dependentplanned

A function without a meaning in a family stays in the interface, returns AES_REQUEST_ERROR and suppresses the unused parameters (for example the shared key on a device without the secure AES, a mode or a key size that the device does not have, the whole module on a device without the peripheral).


Public interface in short (proposal)​

GroupFunctions
Module managementAes_Get_ModuleVersion, Aes_Init, Aes_Deinit, Aes_Task, Aes_Get_DefaultConfig
Capability and stateAes_Get_Capability, Aes_Get_State, Aes_Get_XferError
One-shotAes_Set_Process
IncrementalAes_Set_Start, Aes_Set_UpdateAad, Aes_Set_Update, Aes_Set_Finish, Aes_Set_Abort
Suspend and resumeAes_Get_Context, Aes_Set_Context
KeysAes_Set_KeyClear
InterruptsAes_Set_IrqPriority, Aes_Get_IrqPriority
aes_ModuleVersion_t Aes_Get_ModuleVersion ( void );

aes_RequestState_t Aes_Init ( const aes_Config_t * const aesConfig );
aes_RequestState_t Aes_Deinit ( void );
void Aes_Task ( void );
aes_RequestState_t Aes_Get_DefaultConfig ( aes_Config_t * const aesConfig );

aes_RequestState_t Aes_Get_Capability ( aes_Mode_t mode, aes_KeySize_t keySize, aes_FunctionState_t * const supported );
aes_RequestState_t Aes_Get_State ( aes_State_t * const aesState );
aes_RequestState_t Aes_Get_XferError ( aes_XferError_t * const xferError );

aes_RequestState_t Aes_Set_Process ( const aes_Request_t * const request );

aes_RequestState_t Aes_Set_Start ( const aes_StartConfig_t * const startConfig );
aes_RequestState_t Aes_Set_UpdateAad ( const aes_Data_t * const aad, aes_DataCnt_t aadSize );
aes_RequestState_t Aes_Set_Update ( const aes_Data_t * const input, aes_Data_t * const output, aes_DataCnt_t dataSize );
aes_RequestState_t Aes_Set_Finish ( aes_Data_t * const tag, aes_DataCnt_t tagSize );
aes_RequestState_t Aes_Set_Abort ( void );

aes_RequestState_t Aes_Get_Context ( aes_Context_t * const context );
aes_RequestState_t Aes_Set_Context ( const aes_Context_t * const context, const aes_Key_t * const key );

aes_RequestState_t Aes_Set_KeyClear ( void );

Every function returns AES_REQUEST_OK / AES_REQUEST_ERROR and checks its parameters and the state of the module before it touches a register.

TypeMeaning
aes_Config_tTransfer mode (AES_XFER_MODE_POLL / ISR / DMA), DMA channels and priorities (input, output), interrupt priority, callbacks (complete, error)
aes_Request_tMode, direction, key (source, bytes, size), IV / nonce and its size, AAD and its size, input, output, data size, tag and its size
aes_StartConfig_tThe part of the request without the data (for the incremental interface), including the total AAD and payload sizes for GCM and CCM
aes_Context_tOpaque storage of a suspended message, AES_CONTEXT_SIZE bytes, without the key
aes_XferError_tBit mask: tag mismatch, DMA error, read / write error of the hardware, request in the wrong phase

Usage​

Authenticated encryption (AES-256-GCM) of a frame​

#include "Aes_Port.h"

static aes_Data_t cipherText[ 128u ];
static aes_Data_t tag[ 16u ];

static void App_AesDone( void ) { /* cipherText and tag are ready */ }

aes_Config_t aesConfig;

(void)Aes_Get_DefaultConfig( &aesConfig );
aesConfig.XferMode = AES_XFER_MODE_DMA;
aesConfig.CompleteCallback = App_AesDone;
(void)Aes_Init( &aesConfig );

const aes_Request_t encrypt =
{
.Mode = AES_MODE_GCM,
.Direction = AES_ENCRYPT,
.KeySource = AES_KEY_SOFTWARE,
.Key = key256,
.KeySize = AES_KEY_SIZE_256,
.Iv = iv96,
.IvSize = 12u,
.Aad = header,
.AadSize = headerSize,
.Input = plainText,
.Output = cipherText,
.DataSize = 128u,
.Tag = tag,
.TagSize = 16u,
};

(void)Aes_Set_Process( &encrypt );

Decryption with the verification of the tag​

The same request with .Direction = AES_DECRYPT and the received tag in .Tag. If the tag does not match, the error callback reports AES_XFER_ERROR_TAG_MISMATCH and .Output is cleared.

Decryption with a shared key (no key in the CPU)​

/* the Saes module has loaded or unwrapped the key and shares it with the AES */
request.KeySource = AES_KEY_SHARED;
request.Key = AES_NULL_PTR;
(void)Aes_Set_Process( &request );

Behaviour and limits​

  • Block alignment. ECB and CBC work with whole 16-byte blocks (the padding is the task of the protocol above); CTR, GCM and CCM accept any size. A buffer for the DMA must be aligned to words.
  • The IV and the counter. Never reuse an IV with the same key in CTR, GCM and CCM - it destroys the confidentiality and the authenticity. The module cannot check it; the generation of the IV (a counter, or the Rng module) is the task of the application / the protocol.
  • Throughput. The accelerator needs tens of clock cycles per block; the DMA mode needs no CPU, the polling mode waits. The DMA moves single words (no bursts) on the devices where the hardware has only the single requests.
  • Cache and DMA. The buffers of the DMA must be visible to the DMA (a non-cacheable region or a cache maintenance by the application).
  • Side channels. The accelerator has no protection against the differential power analysis; use the Saes module for the operations with the keys that must be protected.
  • Not part of the first version: DES / TDES of the CRYP peripherals, the key sizes and the modes beyond those of the table, the software fall-back, the XTS and CMAC modes, the key derivation.

Dependencies​

  • Rcc - peripheral clock and reset
  • Nvic - interrupt of the peripheral
  • Gpdma - DMA transfers of the input and the output data
  • Saes - the shared key (on the devices that have both peripherals)
  • RAL (Register Abstraction Layer) - used internally to access the registers

All mandatory RCC, NVIC and DMA configurations are handled internally.


Testing​

  • Unit tests (host, Unity + CMock + RegMem): the construction of the initial blocks of GCM and CCM (the known vectors of the standards), the phase machine and the rejected calls in the wrong phase, the handling of the last incomplete block, the tag verification (match, mismatch, clearing of the output), the clearing of the key registers, the context suspend / resume, the DMA / ISR / POLL flow with the callbacks, the abort.
  • Integration tests (target, probe-rs): the NIST / RFC test vectors for every mode and key size of the device (including the 0-byte and the 1-byte payloads and the AAD only), the DMA transfer of a large buffer compared with a software reference, the shared key with the Saes module.

Interface conventions​

The module follows the common rules of the MCAL layer, so that it behaves like the other modules:

  • Lists instead of free members. Everything that the hardware restricts (the pins, the kernel clock sources, the DMA channels, the triggers and the other selectable sources) is a typedef enum list with exactly the items that are valid for the device line; a pin is an item AES_<SIGNAL>_PIN_<INSTANCE>_P<port><pin> and there is an *_UNUSED item. A choice that is not in the list cannot be written.
  • Own peripheral only. The module calls only the registers / LL functions of its own peripheral. The clocks, the interrupts, the pins, the DMA and the EXTI lines go through the API of the Rcc, Nvic, Gpio, Gpdma and Exti modules; a missing function is added to that module, it is not bypassed.
  • Init verifies itself. Aes_Init checks the result at the end; when it is not as required, the module is deinitialized and an error is returned. The waiting for the hardware is a loop on the register state with a timeout, never a blind delay.
  • Transfer modes. Where the module moves data, the POLL (served by Aes_Task), ISR and DMA modes have the same configuration structure, the same request and the same callbacks (error, half transfer, transfer complete).
  • Flags and states are enums of the module (aes_FunctionState_t, aes_FlagState_t), the limits and the constants are named, there are no magic numbers in the interface.
  • Unsupported functions stay. A function without a meaning in a family keeps its signature, suppresses the unused parameters and returns AES_REQUEST_ERROR.
  • Documentation. Every function and type has a Doxygen description, the main header has the \defgroup.

Repository layout and branches​

The master holds this README and the license. The family branches (Dev/<Family>, Releases/<Family>) hold:

PathContent
README.mdREADME of the family: the instances of the device, specifics, errata, status
Aes_Port.h, Aes_Types.hPublic interface (identical in all families)
Aes*.c, Aes.hImplementation of the family
CMakeLists.txtLibrary Aes_Lib of the EmBi platform
Tests/UnitTestsUnit tests (Unity + CMock + RegMem)
Tests/IntegrationTestsIntegration tests on the target (probe-rs)

A change of the public interface is made in all families.


CMake integration​

target_link_libraries( User_Lib PRIVATE Aes_Lib )
  1. Link Aes_Lib to your CMake library.
  2. Include Aes_Port.h in your project.
  3. Configure the module as needed for your hardware.

License​

This project is licensed under the Creative Commons Attribution-NonCommercial 4.0 International (CC BY-NC 4.0).

You are free to use, modify, and share this work for non-commercial purposes, provided appropriate credit is given.

See LICENSE.md for full terms or visit creativecommons.org/licenses/by-nc/4.0.


Authors​

Contributions are welcome! Please open a pull request.