Embedded HandbookApps
All sections › III. Peripherals
STM32F407, STM32F437, STM32L4A6, STM32G484 · level intermediate · 19 min read
Open in the interactive handbook

43в. Cryptography basics for embedded: cipher, hash, MAC, signature and key exchange — and which of them STM32 has

Section 43 covers the CRC, RNG, HASH and CRYP hardware blocks, 43а — where to get randomness for keys, 43б — a secure element, 48а — firmware signing, 48г — image encryption. Each section took the piece of cryptography it needed and moved on. Here is the overall map: which protection tasks exist, which primitive solves which, what breaks when it is misused and what each primitive costs on a Cortex-M4F without hardware blocks.

Everything is checked by runs: standard test vectors, ECB on a "picture", nonce reuse, forging a tag by length extension, counting instructions of each operation in QEMU. There is one library for the runs — from the MCUboot package: TinyCrypt 0.2.8 and fiat-crypto (X25519 and Ed25519 verification).

Sources: AES — FIPS 197, SHA-256 — FIPS 180-4, modes — NIST SP 800-38A (ECB, CBC, CTR), SP 800-38B (CMAC), SP 800-38C (CCM), SP 800-38D (GCM); HMAC — RFC 2104 and the RFC 4231 test vectors; HKDF — RFC 5869; X25519 — RFC 7748; Ed25519 — RFC 8032; ECDH on P-256 — RFC 5903. The vectors are taken not from memory but from files on disk: the TinyCrypt tests, test_suite_ecdh.data and test_suite_hkdf.data of Mbed TLS 3.6, test.c of wolfSSL 5.7.0; the answers were recomputed once more with the pyca/cryptography 49.0.0 library. Which blocks a chip has — from the CMSIS headers in the Keil packs and STM32CubeC5.

Terms used in the documentation

Original Meaning
confidentiality, integrity, authenticity secrecy, data unchanged, data from the right party
non-repudiation, freshness the author cannot deny it; not a replay
block cipher, mode of operation block cipher, mode
IV, nonce initialization vector, number used once
AEAD, tag encryption with authentication, tag
MAC, HMAC, CMAC message authentication code and its kinds
length extension extending a message past its hash
KDF, HKDF, extract, expand key derivation, extract step, expand step
key agreement, shared secret key exchange, shared secret
PKA (public key accelerator) public key arithmetic accelerator
SAES (secure AES) secure AES
test vector, known-answer test test vector, check against a known answer

43в.1 Five tasks and what solves them

A device wants one of five things from cryptography:

No primitive gives everything at once:

Primitive Confidentiality Integrity Authenticity Non-repudiation Freshness
AES cipher in CTR or CBC mode yes no no no no
SHA-256 hash no against random damage no no no
MAC: HMAC, CMAC no yes yes, with a shared key no no
AEAD: GCM, CCM yes yes yes, with a shared key no no
ECDSA, Ed25519 signature no yes yes yes no
ECDH, X25519 key exchange gives a shared key for all of the above
counter or nonce under a MAC no no no no yes

Only a signature gives non-repudiation: a MAC can be produced by anyone who knows the shared key — including the verifier itself. No primitive gives freshness: it comes from data under the tag — a number that only grows, or a number issued by the device itself (43.3).

A map in three columns: task, primitive, STM32 block. Confidentiality — AES-CTR or AES-CBC, a 16-byte key, ECB is forbidden — the CRYP blocks of the F417 and F437 and AES of the L4A6, G484, U585, H573, C542. Integrity and confidentiality in one pass — AEAD AES-GCM and AES-CCM, never repeat the nonce — CRYP, AES and SAES, SAES on the U585, H573, C5A3. Integrity — SHA-256, a 32-byte digest — HASH on the F417, F437, L4A6, U585, H5, C5. Authenticity with a shared key — HMAC-SHA-256 and AES-CMAC, not SHA-256 of key and message — HASH in HMAC mode and AES. Non-repudiation — ECDSA P-256 and Ed25519, a 64-byte signature — PKA on the U585, H563, H573, C591, C5A3. A shared key without meeting — ECDH and X25519 plus HKDF, a 32-byte public key — PKA. Freshness and keys — a counter and a nonce, a DRBG generator, entropy from 43а — RNG on all 13 chips. At the bottom the cost on a Cortex-M4F without blocks, TinyCrypt and fiat from MCUboot in QEMU, in instructions: AES-128 5797 per block, SHA-256 71 per byte, X25519 1.16 million, Ed25519 verification 1.34 million, ECDH P-256 10.37 million, ECDSA signature 11.07 million

Order of choice: first ask whom we protect against and what they can do (eavesdrop, substitute, replay, break open one device), then pick a task out of the five, then a primitive. Table 43.5 answers the same question for concrete device cases.


43в.2 Symmetric cipher and modes

A block cipher is a permutation on the set of blocks: the key picks one of a huge number of permutations of 16-byte blocks, and without the key one can neither predict it nor invert it. AES (FIPS 197) — a 16-byte block, a 16, 24 or 32-byte key, 10, 12 or 14 rounds. On its own it encrypts exactly one block; anything longer is the job of a mode (the table of modes is in 43.4).

ECB is forbidden — an experiment. A picture of 24 × 7 "pixels", each pixel is a 16-byte block: the background is zeros, the letters are 0xFF bytes. ECB encrypts each block separately, CBC chains a block to the previous one through an initialization vector. The ciphertext blocks are printed like this: the first two distinct ones as a dot and a hash sign, the others as a letter chosen by the first byte:

ecb |........................|
ecb |..#####..#######.#####..|
ecb |.#..........#.........#.|
ecb |..####......#......###..|
ecb |......#.....#.........#.|
ecb |.#####......#....#####..|
ecb |........................|
ecb blocks=168 distinct=2
cbc |.#tkknzvpavefdcqumfrvqbu|
cbc |vxcjlbngabevoydkuxwetthv|
cbc |bukhxysezvkxbdtmmktitdem|
cbc |eolrzieqvraxqgzvqzimnrpl|
cbc |fufgpufegkafnljoyouguplm|
cbc |stbvbfpmehjcigmtjodhongk|
cbc |pinmcjpmdfyrqhmcwuzcfbuf|
cbc blocks=168 distinct=168

ECB honestly encrypted all 168 blocks — and the lettering is readable: identical blocks gave identical ciphertext, there are only 2 distinct ones. Repeated telemetry frames, zeros in a configuration, the 0xFF fill of erased flash "show through" the same way. In CBC all 168 blocks are different.

What is required of the IV and the nonce:

Mode Requirement on the IV or nonce If violated
CBC an unpredictable IV, a new one for every message identical message beginnings are visible
CTR the nonce is never repeated with the same key XOR of ciphertexts = XOR of plaintexts
CCM the same as CTR (SP 800-38C) the same, the text is exposed
GCM the same; 12 bytes is the usual length (SP 800-38D) the text is exposed and the tag can be forged (43.4)

Nonce reuse — an experiment on CCM. CCM is CTR for encryption plus CBC-MAC for the tag, an AEAD mode from the same library. Two device frames, one key, one and the same nonce, an 8-byte tag:

ccm same_nonce xor_c==xor_p 42/42 zero_bytes=30 recovered=42
ccm recovered_text=T=+23.6;U=12.1;DOOR=OPEN;;;PIN=9052;N=0002
ccm other_nonce zero_bytes=0/42

In all 42 bytes the XOR of the two ciphertexts equals the XOR of the two plaintexts. The zeros are in 30 bytes, where the frames coincide: it shows which fields changed. Whoever knows the first frame (for example, guessed it from the format) reads the second one entirely, all 42 bytes, including the code PIN=9052, — without the key. With a different nonce the number of coinciding bytes is 0. The same effect on firmware images is shown in 48г.2. The CCM tag does not help here: it confirms authenticity, but confidentiality is already lost.

Where to get the nonce. A counter saved to flash before use, or 12 random bytes from the RNG (43а). A counter in RAM that starts from zero again after reset is a repeat after every reboot.

AEAD by default. GCM and CCM encrypt and attach a tag in one call, and the order "encrypt first, then the tag" is already right in them. CCM needs only AES (encryption and tag both run on it), GCM adds multiplication in the field GF(2^128); that is why CCM is common in low-power protocols. The cost is in 43в.6.


43в.3 Hash, length extension, HMAC and CMAC

SHA-256 (FIPS 180-4) compresses a message of any length into 32 bytes. A good hash is expected to have three properties: from the digest one cannot find the message, from a message one cannot find a second one with the same digest, one cannot find any pair with the same digest. A hash has no key — so it protects against random damage, but not against someone who substituted the data and recomputed the digest (43.3).

Why SHA-256(key ‖ message) is not a MAC. SHA-256 processes a message in 64-byte blocks, and the digest is simply the internal state after the last block. Whoever knows the digest can continue the computation from that point without knowing the beginning. Experiment len43d.py: the device accepts a command with the tag SHA-256(key ‖ command), a 16-byte key. The attacker has seen one command and its tag and does not know the key:

msg dev=17&cmd=status len 17
glue_bytes 31 forged_len 59
naive_check_accepts True
hmac_accepts False

The attacker appended to the command 31 bytes of SHA-256 padding (the byte 0x80, zeros, the length in bits) and their own tail &cmd=unlock, and computed the tag for the new 59-byte command from the old one — the device accepted it. Against HMAC the same trick does not work. The experiment's own SHA-256 is first checked against hashlib.

HMAC (RFC 2104) hashes twice: H((K ⊕ opad) ‖ H((K ⊕ ipad) ‖ m)). The outer hash hides the internal state, and extension does not work. The cost is two extra compression blocks per message: on 64 bytes HMAC costs 25973 instructions versus 8351 for bare SHA-256, on 1 KB the difference is already small — 90697 versus 73075 (43в.6).

CMAC (SP 800-38B) is a MAC on a block cipher: CBC over the whole message with special handling of the last block. Convenient where there is AES but no hash: the AES block of the G484 or C542 without a software SHA-256 (43в.5). On a Cortex-M4F without blocks it is four times as expensive as HMAC: 384678 instructions per 1 KB versus 90697.

In both cases the tag is compared in constant time — 43.3.


43в.4 Public key: signature, key exchange and key derivation

Symmetric primitives have one shared key for both sides. It has to be delivered somehow, and anyone who knows it can both verify and forge. Asymmetric schemes have two keys: the private one is known only to the owner, the public one can be handed out to everyone. On elliptic curves the public key is a point of the curve obtained by multiplying the base point by the private number; the inverse problem is considered unsolvable in reasonable time.

Signature. The private key signs the digest of a message, the public key verifies. Anyone can verify, only the owner can sign: hence non-repudiation. ECDSA on P-256 is what the ATECC608 (43б) and the bootloaders (48а) can do; Ed25519 (RFC 8032) is a signature on the Edwards curve of the same "25519", deterministic: no random number is needed for signing, and a bad generator will not give away the key. In ECDSA the random number k must be new for every signature: two signatures with the same k reveal the private key.

Key exchange. ECDH and X25519 (RFC 7748): each side multiplies the peer's public key by its own private key, and both obtain the same point — a shared secret that was never sent over the channel. An eavesdropper sees only the public keys. Without a signature the exchange does not know with whom it is: someone who substituted both public keys in the middle will agree with each side separately. That is why the exchange is signed or the public key is checked against one known in advance.

X25519 / Ed25519 ECDH / ECDSA on P-256
private key 32 bytes 32 bytes
public key 32 bytes 64 bytes (X ‖ Y), compressed — 33
signature 64 bytes 64 bytes (r ‖ s)
standard RFC 7748, RFC 8032 FIPS 186, SP 800-56A

Key derivation. The ECDH shared secret is not a key: it is a coordinate of a point, its bits are distributed unevenly, and there is one of it, while several keys are needed — for the cipher, for the MAC, one for each direction. HKDF (RFC 5869) makes any number of independent keys from the secret in two steps on HMAC:

/* HKDF (RFC 5869) поверх HMAC-SHA-256: из общего секрета ikm — ключи нужной длины.
 * Извлечение: prk = HMAC(salt, ikm). Расширение: T(i) = HMAC(prk, T(i-1) ‖ info ‖ i), i = 1, 2, … */
static void hkdf_sha256(uint8_t *okm, unsigned len, const uint8_t *salt, unsigned sl,
                        const uint8_t *ikm, unsigned il, const uint8_t *info, unsigned nl)
{
    uint8_t prk[32], t[32];
    uint8_t i = 0;
    unsigned tl = 0;
    hmac256(prk, salt, sl, ikm, il);
    while (len) {
        i++;
        tc_hmac_set_key(&hm, prk, 32);
        tc_hmac_init(&hm);
        tc_hmac_update(&hm, t, tl);
        tc_hmac_update(&hm, info, nl);
        tc_hmac_update(&hm, &i, 1);
        tc_hmac_final(t, 32, &hm);
        tl = 32;
        unsigned n = len < 32 ? len : 32;
        memcpy(okm, t, n);
        okm += n;
        len -= n;
    }
}

The info string separates purposes: "cipher key device → server", "MAC key server → device" give different keys from one secret. The same functions on the host computer give the same keys. This function passed test 1 of RFC 5869 (43в.6), 64 bytes of keys cost 66885 instructions. In a similar way — HMAC of the master key and the chip number — the per-device key is derived in 48г.4.


43в.5 Keys, STM32 hardware and libraries

Randomness. Keys, nonces, k in ECDSA — only from a generator with a good entropy source; how to build and test one is in 43а. In this section's experiment ECDSA uses a deterministic generator, and the source says so: it must not be carried over into a product.

Storage. A key in a const array can be read from the firmware (43.4, 11в). Options in increasing strength: a flash area under read and write protection (11в, 48г.4); OTP memory; the secure side of TrustZone, which non-secure code cannot reach (2е); a secure element from which the private key never leaves at all (43б).

Hardware blocks — from the #define <block>_BASE lines in the CMSIS header of each chip (hw43d.py):

Chip RNG HASH CRYP AES SAES PKA
STM32F407 + − − − − −
STM32F417 + + + − − −
STM32F437 + + + − − −
STM32L476 + − − − − −
STM32L4A6 + + − + − −
STM32G474 + − − − − −
STM32G484 + − − + − −
STM32U585 + + − + + +
STM32H563 + + − − − +
STM32H573 + + − + + +
STM32C542 + + − + − −
STM32C591 + + − − − +
STM32C5A3 + + − + + +

The blocks depend on the chip, not on the series: F407 and F437, G474 and G484, H563 and H573 are neighbours in a series with different contents. The last digit often separates "with cryptography" from "without": in G4 and L4 AES is present on the G484 and L4A6. Before choosing a chip, look at the header or the description of the specific part number.

What each block accelerates:

Software libraries — licenses from the files on disk:

Library What it provides License
Mbed TLS 3.6 with PSA Crypto everything: AES and modes, SHA-2, HMAC, HKDF, ECDH, ECDSA, X25519, TLS (37а) Apache-2.0 or GPL-2.0-or-later, your choice
TinyCrypt 0.2.8 AES-128, CBC, CTR, CCM, CMAC, SHA-256, HMAC, ECDH and ECDSA on P-256 BSD, three clauses (Intel)
fiat-crypto curve25519.c from MCUboot X25519 and Ed25519 verification MIT
X-CUBE-CRYPTOLIB the ST library, prebuilt for Keil, IAR and GCC (43.4) terms not checked here

Monocypher — a compact library on 25519 with Ed25519 signing — is not downloaded on this machine, is not used in the section and was not measured.

The PSA Crypto API (include/psa/crypto.h in Mbed TLS 3.6) is a common interface with keys referred to by number, behind which there can be either software or a hardware block: the firmware does not change when the chip changes.


43в.6 Cost on a Cortex-M4F and checking against the standards

Test vectors. Before measuring, the library is checked against the known answers of the standards. The same program cry43d.c was built with gcc on the computer and with arm-none-eabi-gcc for Cortex-M4F; both runs gave the same result:

vec fips197_b_aes128 ok 3925841d02dc09fbdc118597196a0b32
vec fips180_sha256_abc ok ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
vec rfc4231_t1_hmac_sha256 ok b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7
vec sp800_38b_ex1_cmac ok bb1d6929e95937287fa37d129b756746
vec rfc5869_t1_hkdf_sha256 ok 3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865
vec rfc7748_x25519_alice_pub ok 8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a
vec rfc7748_x25519_shared ok 4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742
vec rfc5903_ecdh_p256_shared ok d6840f6b42f6edafd13116e0e12565202fef8e9ece7dce03812464d04b9442de
vec rfc8032_t1_ed25519_verify ok good=1 bitflip=0 othermsg=0

The Ed25519 signature from RFC 8032 is accepted, and with one flipped bit or for another message — rejected. Separately, ref43d.py recomputed all vectors and the ciphertext of the CCM experiment with the pyca/cryptography library — everything matched, and the signature it built from the private key of RFC 8032 test 1 matched the signature in wolfSSL's test.c. A mistake in byte order, in length or in padding shows up here at once — before the device fails to agree with the server.

The run:

M=.../bootloader/mcuboot/ext        # TinyCrypt, tinycrypt-sha512, fiat
docker run --rm -v "$PWD/cry43d:/v:ro" -v "$M:/m:ro" stm-sys:1 sh /v/run43d.sh host
docker run --rm -v "$PWD/cry43d:/v:ro" -v "$M:/m:ro" stm-arm:1 sh /v/run43d.sh qemu
docker run --rm -v "$PWD/cry43d:/v:ro" -v "$M:/m:ro" stm-arm:1 sh /v/run43d.sh size

Cost. QEMU netduinoplus2 (STM32F405, Cortex-M4F) with -icount, build -O2; these are instructions, not cycles, and the time at 168 MHz is a lower bound:

Operation Instructions Per byte At 168 MHz, at least
AES-128: key schedule 769
AES-128: one 16-byte block 5797 362 0.03 ms
AES-128-CTR, 1 KB 382606 374 2.28 ms
AES-128-CCM, 1 KB, 8-byte tag 776468 758 4.62 ms
AES-CMAC, 1 KB 384678 376 2.29 ms
SHA-256, 64 bytes 8351 130 0.05 ms
SHA-256, 1 KB 73075 71 0.43 ms
HMAC-SHA-256, 64 bytes 25973 406 0.15 ms
HMAC-SHA-256, 1 KB 90697 89 0.54 ms
HKDF-SHA-256, 64 bytes of keys 66885 0.40 ms
X25519, one multiplication 1156653 6.88 ms
Ed25519, signature verification 1342558 7.99 ms
ECDH P-256, shared secret 10367426 61.71 ms
P-256, key generation 10469122 62.32 ms
ECDSA P-256, signing 11066136 65.87 ms
ECDSA P-256, verification 12220588 72.74 ms

What follows from this:

Code size (-Os, Cortex-M4F, whole object file, bytes):

Part Bytes
AES-128 encryption (aes_encrypt) 1044
+ CTR / CCM / CMAC / CBC 176 / 844 / 507 / 268
SHA-256 + HMAC 1060 + 318
P-256: arithmetic, ECDH, ECDSA 4140 + 430 + 1304
X25519 and Ed25519 verification (fiat, with tables) 12568
SHA-512 for Ed25519 2300

The whole symmetric set — AES, CTR, CCM, CMAC, SHA-256, HMAC — is 3949 bytes. P-256 is 5874 bytes, 25519 with SHA-512 is 14868: fiat keeps tables of precomputed points and is faster thanks to them.


43в.7 Pitfalls

The test vector does not match, yet "on hardware it seems to encrypt". Most often it is byte order: the key or the block are fed as words in a different order (43.3, the DATATYPE register), the P-256 public key is passed with the 04 prefix or without it, X25519 expects bytes least significant first. First the known answer of the standard, then the exchange with the other side.

"Encrypted", but the contents can be guessed. ECB mode: identical blocks give identical ciphertext (43в.2, 168 blocks — 2 distinct). Some wrappers around a hardware block choose it by default.

Nonce repeated after reset. A counter in RAM or a constant in the code: the very first frame after a reboot repeats the number, and the XOR of two ciphertexts yields the XOR of the texts (43в.2, 42 of 42 bytes exposed).

A home-made MAC SHA-256(key ‖ data). It is forged by extension without the key (43в.3). Only HMAC or CMAC.

The signature is verified, but with the wrong key. Verifying a signature with a public key that arrived in the same message proves nothing: whoever substituted the message will substitute the key as well. The public key must be in the device in advance (48а.5) or signed by someone the device already trusts.

The ECDH shared secret is used as the AES key. The first 16 bytes of the secret instead of HKDF: one key for both directions and for both the cipher and the MAC. Keys are derived separately, with different info strings (43в.4).

The test generator got into the product. Examples use a deterministic generator, as in this section; with it ECDSA produces a predictable k, and hence the private key. In a product — the RNG and the checks from 43а.


43в.8 Summary

Next: section 43г "A do-it-yourself secure channel between a device and a computer: key exchange, frame encryption, replay protection" — an X25519 handshake signed by the device, per-direction keys from HKDF, AES-CCM frames with a counter and a replay window — and five experiments with the device in QEMU and the host on the computer.

Open in the interactive handbook