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:
- confidentiality — an outsider cannot read the data;
- integrity — the data has not changed;
- authenticity — the data was composed by someone we trust;
- non-repudiation — the author cannot say "it was not me", and a third party can see that;
- freshness — this is not an old message recorded and replayed.
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).
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:
- CRYP (F4) and AES (L4, G4, U5, H5, C5) — the block cipher and modes; CRYP also has DES and triple DES (43.4).
- SAES — AES whose key can be taken from the chip's hardware unique
key (DHUK), invisible to software: that is how
CRYP_KEYSEL_HWis described in the U5 HAL; on the U585 SAES works together with TrustZone (2е). - HASH — SHA-256, on F4 and L4 also SHA-1 and MD5, HMAC mode (43.3).
- PKA — public key arithmetic: in the U5 HAL these are modes for curve point multiplication, ECDSA signing and verification, modular exponentiation for RSA. That is exactly what a TLS handshake spends its time on (37а.6); how much faster PKA is than software is not measured in this section — QEMU does not model the blocks.
- RNG — a true generator, present on all 13 chips of the table (43а).
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:
- Symmetric is cheap. A 64-byte telemetry frame with HMAC is 25973 instructions, a fraction of a millisecond. AES without a block costs about 370 instructions per byte — 5 times more than SHA-256; a stream of hundreds of kilobytes is already noticeable, and here a hardware AES pays off.
- Public key is thousands of times more expensive. One X25519 is like 200 AES blocks. That is why the public key is used once per session (exchange and signature), and after that a symmetric key from HKDF does the work.
- 25519 is almost 9 times cheaper than P-256 here: X25519 — 1.16 million instructions versus 10.37 million for ECDH on P-256 in TinyCrypt. This compares two different libraries, not the curves in general; but Mbed TLS in 37а on P-256 also spent 13.88 million instructions on the one-time key of TLS 1.3.
- Ed25519 signing is not measured: the MCUboot package has only verification.
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
- There are five tasks: confidentiality, integrity, authenticity, non-repudiation, freshness. A cipher gives only confidentiality, a MAC — integrity and authenticity with a shared key, a signature — non-repudiation as well, freshness — a number under the tag.
- ECB exposes the picture: of the picture's 168 blocks — 2 distinct ciphertexts, in CBC — 168. A nonce repeated in CCM exposed the second frame entirely, 42 bytes of 42.
SHA-256(key ‖ data)is forged without the key: 31 bytes of padding and one's own tail — the tag is accepted; HMAC cannot be fooled like that.- Keys are derived from the ECDH shared secret with HKDF (RFC 5869): 64 bytes of keys — 66885 instructions.
- Blocks by the CMSIS headers: RNG — on all 13 chips of the table, AES — on the L4A6, G484, U585, H573, C542, C5A3, SAES and PKA — on the U585, H573, C5A3, PKA without AES — on the H563 and C591. The contents depend on the part number, not on the series.
- Cost on a Cortex-M4F without blocks: AES-128 — 5797 instructions per block, SHA-256 — 71 per byte, HMAC of 64 bytes — 25973, X25519 — 1.16 million, Ed25519 verification — 1.34 million, ECDH on P-256 — 10.37 million, ECDSA signature — 11.07 million.
- The test vectors of FIPS 197, FIPS 180-4, RFC 4231, SP 800-38B, RFC 5869, RFC 7748, RFC 8032 and RFC 5903 matched on the computer and in QEMU and were recomputed by a second library.
- The next sections of the series: 43г — a do-it-yourself secure channel between the device and a computer on these primitives, 43д — typical cryptography mistakes in firmware.
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.