Sp800 208 Lms ESP32
An ESP32 development project.
Parts and sourceBefore you start
Confirm board compatibility and supported firmware targets in the upstream documentation.
Upstream README
sp800-208-lms-esp32
Stateful hash-based post-quantum digital signatures for ESP32: LMS (Leighton-Micali Signatures) and its multi-level variant HSS, as specified in RFC 8554, RFC 9858 and approved by NIST in SP 800-208. Supports all SP 800-208 parameter sets: SHA-256, SHA-256/192, SHAKE256/256 and SHAKE256/192; tree heights 5-25; Winternitz parameters 1, 2, 4 and 8; HSS with 1-8 levels.
The library manages the private key state for you: the one-time key index is written to NVS before each signature is computed, interrupted operations never lead to a one-time key being used twice, and the tree caches make signing fast. It joins fips203-mlkem-esp32 (ML-KEM, FIPS 203), fips204-mldsa-esp32 (ML-DSA, FIPS 204) and fips205-slhdsa-esp32 (SLH-DSA, FIPS 205), and follows the same structure.
Features
- SP 800-208 parameter sets: 20 LMS and 16 LM-OTS types (RFC 8554 + RFC 9858), LMS and HSS public key / signature formats
- Verified against the RFC 8554 and RFC 9858 test cases (keys and signatures regenerated bit-exactly from the published seeds) and all 87 NIST ACVP LMS vectors, on the host and on the device; interoperability with Cisco's hash-sigs reference implementation in both directions
- Crash-safe state handling: write-ahead counter updates, abandoned (never re-signed) HSS trees after an interrupted tree creation, refusal of inconsistent state. Tested with thousands of simulated power losses at every possible storage write: no one-time key was ever used twice
- Fast signing: Merkle tree caches (a few KB of RAM), the next subtree is computed a leaf at a time while signing, so signing time stays nearly constant (2.6-7.4 ms with SHA hardware for a height-10 tree)
- Optional SHA hardware acceleration (
LMS_ESP32_HW_SHA, off by default): the LM-OTS hash chains run on the ESP32's SHA accelerator, 4.4× faster key generation, signing and verification for the SHA-256 sets - NVS storage (
LMS_NVS.h) with atomic, committed updates; any other storage via a 3-function interface - Hardware RNG for I, SEED and the randomizers C (SP 800-208 Section 6.1), one fresh I/SEED pair per tree
- Watchdog-safe long key generation (cooperative yields), small stack (the benchmark task peaks at 2.7 KB, including
printf) - Arduino-friendly C++ classes
LMSKey/HSSKey, plus a plain C API
About LMS and HSS
How it works
An LM-OTS one-time signature is built from Winternitz hash chains: the private key is a set of random strings, the public key is the end of each chain, and a signature reveals intermediate chain values determined by the message digest. One LM-OTS key must sign only one message; two signatures with the same one-time key let an attacker forge.
An LMS tree authenticates 2^h one-time keys with a Merkle tree of height h. The public key is the tree root (56 bytes for n = 32). A signature contains the leaf index q, the LM-OTS signature and the authentication path.
HSS stacks LMS trees: the top tree signs the public keys of lower trees, the bottom tree signs messages. Two levels of height 10 give 2^20 signatures while only two 1024-leaf trees have to be computed at a time.
Security relies only on the hash function (second-preimage resistance), like SLH-DSA. Compared with SLH-DSA, the signatures are much smaller (1-9 KB instead of 8-50 KB) and signing is much faster, at the price of state: the signer must never reuse a one-time key.
Stateful signatures: the rules
NIST SP 800-208 describes LMS/XMSS as suitable for cases where the number of signatures is bounded and the signer can manage state reliably, for example firmware signing. The library takes care of the state in the device, but a few rules are the application's responsibility:
- Never copy, clone or restore a private key. Restoring an NVS backup, flashing the same NVS image to two devices or running the same key on two devices reuses one-time keys. The library cannot detect this.
- Storage writes must be durable.
LMSNvsStoragecommits each update before returning; a custom storage must do the same. - The number of signatures is limited (2^h for LMS, 2^(h1+h2+...) for HSS).
remaining()tells how many are left; when it reaches 0, sign() returnsLMS_ERR_EXHAUSTED. - Some one-time keys are skipped (not reused) after a reset: the reserved ones (
reserve()), and the remainder of a lower HSS tree whose creation was interrupted. This is by design.
SP 800-208 further requires key generation and signing to happen in a FIPS 140 level 3 hardware module with non-exportable keys. An ESP32 is not such a module; this library is for experimentation, education and prototyping. Verification has no such restriction.
Parameter sets
Sizes for LMS (one tree). An HSS signature with L levels is the sum of the L LMS signatures + (L-1) × public key + 4 bytes.
| LM-OTS (n = 32) | p | Signature, h = 5 / 10 / 15 | LM-OTS (n = 24) | p | Signature, h = 5 / 10 / 15 | |
|---|---|---|---|---|---|---|
| W1 | 265 | 8,684 / 8,844 / 9,004 | W1 | 200 | 4,956 / 5,076 / 5,196 | |
| W2 | 133 | 4,460 / 4,620 / 4,780 | W2 | 101 | 2,580 / 2,700 / 2,820 | |
| W4 | 67 | 2,348 / 2,508 / 2,668 | W4 | 51 | 1,380 / 1,500 / 1,620 | |
| W8 | 34 | 1,292 / 1,452 / 1,612 | W8 | 26 | 780 / 900 / 1,020 |
- n = 32:
LMS_SHA256_M32_H*/LMS_SHAKE_M32_H*withLMOTS_SHA256_N32_W*/LMOTS_SHAKE_N32_W*(256-bit hash output, public key 56 B) - n = 24:
LMS_SHA256_M24_H*/LMS_SHAKE_M24_H*withLMOTS_SHA256_N24_W*/LMOTS_SHAKE_N24_W*(192-bit output, smaller signatures, public key 48 B) - W trades signature size for time: each step from W4 to W8 halves the signature but makes key generation and signing ~6-8× slower.
- The LMS and LM-OTS type of a level must use the same hash function and output size. In HSS, every level can use different types.
Recommendations on the ESP32: LMS_SHA256_M32_H10 + LMOTS_SHA256_N32_W4 for up to 1024 signatures (2.5 KB signatures; 24 s key generation, 5.5 s with SHA hardware), or HSS with two such levels for up to 2^20. Use the n = 24 sets for smaller signatures. The SHAKE sets are ~5× slower in software and have no hardware support.
Requirements
- An ESP32-family board (ESP32, ESP32-S2, ESP32-S3, ESP32-C3, ESP32-C6, ...)
- Arduino-ESP32 core 3.x (tested: 3.3.11), via the Arduino IDE,
arduino-clior PlatformIO - RAM for the tree caches: 1 KB (h = 5) to ~32 KB (h = 15) per level; signature buffer 1-9 KB per level
- NVS space for the state: ~0.4 KB for an LMS key (h ≤ 10: + 2 KB tree cache), + ~2.5-9 KB per lower HSS level
Installation
Arduino IDE
Copy the sp800-208-lms-esp32 folder into your Arduino libraries folder (or Sketch → Include Library → Add .ZIP Library), then open File → Examples → sp800-208-lms-esp32.
arduino-cli
arduino-cli compile -b esp32:esp32:esp32 --library path/to/sp800-208-lms-esp32 path/to/sp800-208-lms-esp32/examples/lms_simple
PlatformIO
[env:esp32]
platform = espressif32
framework = arduino
lib_deps = file://path/to/sp800-208-lms-esp32
; build_flags = -DLMS_ESP32_HW_SHA ; optional SHA hardware acceleration
Quick Start
#include <LMS.h>
#include <LMS_NVS.h>
LMSNvsStorage storage;
LMSKey key;
uint8_t pk[56], sig[2508];
void setup() {
Serial.begin(115200);
storage.begin("lms"); // NVS namespace
if (key.load(storage) != LMS_OK) { // first boot: new key
key.generate(storage, LMS_SHA256_M32_H10, LMOTS_SHA256_N32_W4);
}
size_t pkLen = sizeof(pk);
key.publicKey(pk, &pkLen);
const char *msg = "firmware v1.2.3";
size_t sigLen = sizeof(sig);
if (key.sign((const uint8_t *)msg, strlen(msg), sig, &sigLen) == LMS_OK) {
bool ok = LMSKey::verify(pk, pkLen, (const uint8_t *)msg, strlen(msg), sig, sigLen) == 0;
Serial.printf("signed with one-time key %u, %s, %llu left\n", (unsigned)lms_get32(sig),
ok ? "valid" : "INVALID", (unsigned long long)key.remaining());
}
}
void loop() {}
API Reference
LMSKey (one tree) and HSSKey (1-8 levels)
#include <LMS.h>
LMSKey key;
int generate(LMSStorage &storage, uint32_t lmsType, uint32_t otsType);
HSSKey hss;
int generate(LMSStorage &storage, unsigned levels, const LMSLevel *lv); // lv[0] = top
int generate(LMSStorage &storage, const LMSLevel (&lv)[N]); // array overload
int load(LMSStorage &storage); // LMS_ERR_NOKEY if none, LMS_ERR_STATE if inconsistent
int sign(const uint8_t *msg, size_t msgLen, uint8_t *sig, size_t *sigLen); // *sigLen: in = capacity
int publicKey(uint8_t *pk, size_t *pkLen) const;
int reserve(uint64_t n); // reserve n signatures now (fewer flash writes later)
void setAutoReserve(uint32_t n); // reserve n extra whenever the state is written
uint64_t remaining() const, nextIndex() const, totalSignatures() const;
size_t publicKeySize() const, signatureSize() const, cacheSize() const;
unsigned levels() const; uint32_t lmsType(unsigned level), otsType(unsigned level);
void end(); // free the RAM copy (the stored state stays)
static int LMSKey::verify(pk, pkLen, msg, msgLen, sig, sigLen); // 0 = valid (LMS format)
static int HSSKey::verify(pk, pkLen, msg, msgLen, sig, sigLen); // 0 = valid (HSS format)
static size_t LMSKey::signatureSize(lmsType, otsType), LMSKey::publicKeySize(lmsType);
static size_t HSSKey::signatureSize(levels, lv), HSSKey::publicKeySize(topLmsType);
static int LMSKeyBase::erase(LMSStorage &storage); // delete a stored key
static const char *LMSKeyBase::errorString(int rc);
All functions return LMS_OK (0) or a negative LMS_ERR_* code: PARAM, NOMEM, STORE (storage write failed; no signature was produced), EXHAUSTED, RNG, STATE (stored state inconsistent, key refused), BUFFER, NOKEY, INTERNAL.
LMSKey and HSSKey use different public key and signature formats (an HSS key with one level is not an LMS key): LMSKey::load refuses an HSS key and vice versa.
Storage
#include <LMS_NVS.h>
LMSNvsStorage storage; storage.begin("namespace"); // one key per namespace
LMSRamStorage ram; // RAM only, for tests and benchmarks (state lost on reset!)
class MyStorage : public LMSStorage { // anything else: FRAM, secure element, file, ...
int read(const char *name, uint8_t *buf, size_t cap, size_t *len) override; // 0, 1 = missing, <0
int write(const char *name, const uint8_t *buf, size_t len) override; // 0 = durable
int erase(const char *name) override;
};
Records: hdr (parameters), ctr (next unused index, 8 bytes, written on every signature unless reserved), lv0..lv7 (per level: I, SEED, root, and the stored signature of the level's public key), ax0..ax7 (tree caches, public; recomputed if missing or damaged).
C API
src/lms_esp32.h: lms_key_generate, lms_key_load, lms_key_sign, lms_key_reserve, lms_key_public_key, lms_key_free, ... with an lms_store struct of three callbacks. src/lms_core.h: lms_verify, hss_verify, parameter tables, and the deterministic building blocks (lmots_sign, lms_tree_root, lms_sign_internal) used by the test vectors.
Examples
| Example | Description |
|---|---|
| lms_simple | Minimal key generation + sign + verify (RAM state) |
| lms_nvs_storage | Key with persistent state in NVS: the one-time key index continues across resets (r reserve, e erase) |
| hss_demo | Two-level HSS: signs a 64 KB "firmware image", prints the signature structure, shows the new bottom tree every 32 signatures |
| lms_test_vectors | RFC 8554 / RFC 9858 test cases (regenerated from the seeds), NIST ACVP LMS vectors, stateful round trips for all four hash functions |
| lms_benchmark | Key generation / signing / verification times, signature and cache sizes, hash primitive speed; CSV output |
| m5stickc-plus2 | Live demo on the M5StickC PLUS2 display: the key stays in NVS, the one-time key index q continues after a power cycle; button B switches the parameter set (requires M5Unified) |

m5stickc-plus2 example (framebuffer captured from the device, SHA hardware enabled): same layout as the ML-KEM, ML-DSA and SLH-DSA demos. The line below the cards shows the one-time key index q of the latest signature out of 2^h. Button A runs a tamper test on the latest signature, button B switches between LMS H5/W4, H10/W4, SHA-256/192 H5/W8, SHAKE H5/W4 and HSS H5+H5/W4 (a new key is generated; only one key is kept in NVS).
Performance
Measured with examples/lms_benchmark on an M5StickC PLUS2 (ESP32-PICO-V3-02 @ 240 MHz, Arduino-ESP32 3.3.11, RAM storage, 32-byte messages). Signing is the average over the signatures made (32 for h = 5, 256 for h = 10: steady state, including the precomputation of the next subtree); with LMSNvsStorage each signature adds the NVS write (typically 3-5 ms).
| Parameter set | KeyGen SW | KeyGen HW | Sign SW | Sign HW | Verify SW | Verify HW | Signature |
|---|---|---|---|---|---|---|---|
| LMS SHA256 H5 W1 | 512 ms | 221 ms | 18.0 ms | 6.6 ms | 8.1 ms | 5.8 ms | 8,684 B |
| LMS SHA256 H5 W2 | 437 ms | 145 ms | 14.7 ms | 4.4 ms | 7.0 ms | 3.6 ms | 4,460 B |
| LMS SHA256 H5 W4 | 763 ms | 173 ms | 24.3 ms | 5.4 ms | 12.2 ms | 3.6 ms | 2,348 B |
| LMS SHA256 H5 W8 | 5.87 s | 1.08 s | 180 ms | 33.2 ms | 95.2 ms | 17.9 ms | 1,292 B |
| LMS SHA256/192 H5 W4 | 572 ms | 122 ms | 18.0 ms | 3.8 ms | 9.3 ms | 2.5 ms | 1,380 B |
| LMS SHAKE H5 W4 | 4.34 s | - | 137 ms | - | 66.8 ms | - | 2,348 B |
| LMS SHAKE/192 H5 W4 | 3.26 s | - | 104 ms | - | 50.1 ms | - | 1,380 B |
| LMS SHA256 H10 W4 | 24.4 s | 5.54 s | 33.2 ms | 7.4 ms | 12.6 ms | 3.9 ms | 2,508 B |
| HSS SHA256 H10+H10 W4 | 48.8 s | 11.1 s | 33.3 ms | 7.4 ms | 25.2 ms | 7.6 ms | 5,076 B |
| HSS SHA256 H5+H5 W8 | 11.8 s | 2.17 s | 178 ms | 32.7 ms | 194 ms | 37.7 ms | 2,644 B |
(SW: software SHA-256; HW: LMS_ESP32_HW_SHA. SHAKE sets: no hardware support, same time in both builds.)
Observations:
- Key generation is the expensive part: it computes all 2^h one-time public keys (each 67 hash chains of 15 steps for W4). A height-10 tree takes 24 s in software, 5.5 s with SHA hardware; a height-15 tree would take ~13 min / ~3 min (extrapolated, 32× height 10). Use HSS for more signatures.
- HSS lower-level trees are generated when the previous one is used up: every 2^h_bottom signatures, one sign call also takes as long as generating one tree (e.g. 0.2-0.8 s for h = 5, see
hss_demo). - After a reset, the first signature recomputes the current subtree (up to 0.8 s for h = 10 in software); the tree caches themselves are stored in NVS, so loading takes milliseconds.
- Signing is fast compared with SLH-DSA (2.6 s for SHA2-128f in software) and ML-DSA (~80 ms), and the signatures are small.
- Hash primitives: SHA-256 compression 21.0 µs in software (compiled with
-O3: 21% less time than with the default-Os), 2.9 µs on the hardware accelerator (session held); Keccak-f[1600] 113.5 µs (fastest with-Os).
SHA hardware acceleration
Every hash inside an LM-OTS chain — 97-99% of the work of key generation, signing and verification — is SHA-256 of one 55-byte (n = 32) or 47-byte (n = 24) message: exactly one padded block, hashed from the initial state. That is the one thing the original ESP32's SHA accelerator does well (it cannot resume from a midstate), so with LMS_ESP32_HW_SHA those blocks go to the hardware. Off by default.
Enabling it:
- PlatformIO:
build_flags = -DLMS_ESP32_HW_SHA - arduino-cli:
--build-property "compiler.c.extra_flags=-DLMS_ESP32_HW_SHA" --build-property "compiler.cpp.extra_flags=-DLMS_ESP32_HW_SHA" - Arduino IDE: uncomment
#define LMS_ESP32_HW_SHAinsrc/lms_esp32_config.h
Keys and signatures are identical with and without it (the KAT suite passes in both modes: 266/266 on the device). lms_hw_sha_active() reports whether the hardware is in use. Speed-up: 4.4× (key generation and steady-state signing), 3.2× (verification, which also hashes the message and the tree path in software).
How it works: the chain block is kept as 16 big-endian words; each step writes it to the accelerator's text registers, starts the engine, reads the digest back and shifts it into place for the next step (no byte conversion: unaligned byte accesses alone cost more than the hash on the Xtensa core). Per block: ~650 CPU cycles of register traffic (write, run, read back), 2.9 µs including the call, vs. 21 µs in software.
Sharing the accelerator, self-test and chip support are the same as in fips205-slhdsa-esp32:
- On the original ESP32 all SHA engines (SHA-1, SHA-256, SHA-384/512) are held for one LM-OTS operation and released every 256 blocks; mbedTLS tries the engines and falls back to software meanwhile,
esp_sha()waits at most until the next release. - A self-test compares hardware and software results on 12 messages before the first use (and detects the register byte order); if it fails, the software implementation is used.
- ESP32 (original): tested on hardware. ESP32-S2/S3/C3/C6: compile-tested only (ESP-IDF 5 SHA driver, engine held for 64 blocks at a time).
Memory usage
- Stack: the benchmark task (all operations, including
Serial.printf) peaks at 2.7 KB;printfalone accounts for 2.5 KB of that. Records and temporary buffers live on the heap. The examples use the default 8 KBloop()stack or a 12-16 KB task. - Heap (per key): the tree caches, 2^(h-k+1) + 2^(k+1) (+ 2^k for the bottom level) nodes of n bytes with k = ⌈h/2⌉: 1,024 B (h = 5), 5,120 B (h = 10), ~32 KB (h = 15) for n = 32.
cacheSize()reports it. Plus temporary buffers for the storage records. - Signature buffer: see the parameter table; keep it static for W1/W2.
Conformance testing
- RFC 8554 Appendix F (HSS, 2 levels, SHA-256 H5/W8 and H10/W4): verification; for test case 2 both trees are regenerated from the published SEED/I and every byte of the public key and signature matches.
- RFC 9858 Appendix A (SHA-256/192, SHAKE256/192, SHAKE256/256 and SHA-256/192 W4 with h = 20): key and signature regenerated bit-exactly from the published seed (h = 20: LM-OTS signature regenerated, path verified).
- NIST ACVP LMS (keyGen 9, sigGen 62, sigVer 16 cases; revisions 1.0 and SP800-208): all pass. ACVP sigGen expected signatures depend on the signer's random C, so they are checked as valid signatures; signing is covered by the RFC cases.
- Every valid signature is also checked with a flipped bit and a modified message.
- Device:
examples/lms_test_vectors: 266 passed, 0 failed (300 s in software, 196 s with SHA hardware; the SHAKE cases dominate). - Host: the same
kat_runner.hunder AddressSanitizer/UBSan; a state-machine test with random simulated power losses at every storage write (with the write lost or completed), reloads, auto-reservation, 1-3 HSS levels and mixed hash functions: every produced signature verified, no one-time key used twice across 6,666 signatures, 416 simulated crashes and 787 reloads. - Interoperability with Cisco hash-sigs (SHA-256 sets, LMS and 2-3 level HSS): our signatures verify with hash-sigs and hash-sigs signatures verify with this library.
- Regenerate the vectors with
scripts/gen_test_vectors.py --download --out examples/lms_test_vectors/lms_vectors.h.
Important Notes
- State is everything — see the rules. Keep the NVS partition healthy: when it is nearly full, every write triggers NVS garbage collection (we measured 110 ms per signature instead of 5 ms on a full 20 KB partition) and eventually writes fail;
sign()then returnsLMS_ERR_STOREwithout producing a signature. Use a larger NVS partition orsetAutoReserve()for frequent signing. - Flash wear: each signature writes 8 bytes to NVS (wear-levelled across the partition). For very frequent signing, reserve signatures (
setAutoReserve(n)): one write per n+1 signatures, at the cost of losing up to n signatures per reset. - NVS is not encrypted unless NVS/flash encryption is enabled; the seeds can be read with physical access.
- Entropy:
esp_fill_random()is truly random only while Wi-Fi/Bluetooth runs orbootloader_random_enable()is active. Generate keys with an entropy source running. - Watchdog: key generation yields for one tick every 500 ms, so the 5 s task watchdog of core 0 is fed even during minutes-long key generation.
- Not thread-safe: use one key object from one task at a time (verification is thread-safe).
Implementation details
| File | Purpose |
|---|---|
src/lms_core.c/.h |
Parameter tables, LM-OTS (chains as one-block hashes on 32-bit words), LMS tree nodes, LMS/HSS verification, deterministic signing for tests |
src/lms_key.c, src/lms_esp32.h |
Stateful key: records, write-ahead counter, HSS tree creation, tree caches (upper nodes + current subtree + next-subtree leaves) |
src/lms_hash.c/.h, src/lms_keccak.c |
SHA-256, SHAKE256 (Keccak permutation from slhdsa-c) |
src/lms_hwsha.c/.h |
Optional SHA-256 hardware backend |
src/lms_esp32_platform.c |
Hardware RNG, cooperative yield |
src/LMS.h, src/LMS_NVS.h |
C++ classes, NVS storage |
scripts/gen_test_vectors.py, scripts/parse_rfc_vectors.py |
RFC + ACVP vectors → lms_vectors.h |
State machine (global index g over all levels; level i uses tree number g >> (h_i + ... + h_{L-1}) and its root is signed by leaf (tree number mod 2^h_{i-1}) of level i-1):
- If a lower-level tree is used up: write a pending record with fresh random I/SEED → compute the tree → sign its public key with the parent's next one-time key → store the tree cache and the record with the signature. A pending record found after a reset means the parent's one-time key may already have been used: the whole tree is skipped, its signature never recomputed (SP 800-208 footnote 9).
- Write
ctr = g + 1(or more with reservation) and only then compute the signature with leaf g. - A stored state that is inconsistent (counter behind the stored trees, missing records) is refused with
LMS_ERR_STATErather than repaired.
License
Licensed under the Apache License, Version 2.0. The Keccak permutation (src/lms_keccak.c) is taken from slhdsa-c (Apache-2.0 OR ISC OR MIT). The test vectors come from RFC 8554, RFC 9858 and NIST ACVP.