Skip to main content

m5stack_core/driver/
aes.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! AES accelerator, as a single-block primitive.
3//!
4//! esp-hal's driver covers ECB/CBC/OFB/CTR over buffers. This wraps the one
5//! operation a message-at-a-time consumer needs — one 16-byte block under a
6//! 128-bit key — because that is what short-message crypto is built from: a
7//! CTR keystream for a single block is `encrypt_block(key, nonce)`, and the
8//! caller XORs.
9//!
10//! Why bother, rather than a software cipher: `aes::soft::fixslice` costs
11//! ~3.6 KiB of code on xtensa and re-expands the key schedule for every
12//! message. The accelerator costs neither, and the key never enters a software
13//! key schedule at all.
14//!
15//! The driver owns the peripheral ([`crate::board::SystemResources::aes`]), so
16//! one task holds it. Sharing it between tasks means wrapping it the way any
17//! other single-owner peripheral is wrapped — there is no internal locking
18//! here, deliberately: a lock whose contention nobody measured is worse than
19//! an owner.
20
21use esp_hal::{
22    aes::{Aes, Key},
23    peripherals::AES,
24};
25
26/// One-block AES-128 on the hardware accelerator.
27pub struct Aes128<'d> {
28    aes: Aes<'d>,
29}
30
31impl Aes128<'static> {
32    /// Claim the accelerator.
33    pub fn new(aes: AES<'static>) -> Self {
34        Self { aes: Aes::new(aes) }
35    }
36
37    /// Encrypt `block` in place under `key`.
38    ///
39    /// This is also the CTR keystream for a single block: pass the counter
40    /// block as `block` and XOR the result over the payload.
41    pub fn encrypt_block(&mut self, key: &[u8; 16], block: &mut [u8; 16]) {
42        self.aes.encrypt(block, Key::Key128(*key));
43    }
44
45    /// Decrypt `block` in place under `key` (ECB — the inverse cipher).
46    ///
47    /// Not what CTR or OFB need: those decrypt with [`Self::encrypt_block`].
48    pub fn decrypt_block(&mut self, key: &[u8; 16], block: &mut [u8; 16]) {
49        self.aes.decrypt(block, Key::Key128(*key));
50    }
51}