Back to Blog
55 min Copy as Markdown
Part 6 / 6 · Kleidos firmware: six decisions under hard constraints

PBKDF2 on the ESP32-S3 SHA engine: what does an iteration cost?

One PBKDF2 iteration on the ESP32-S3 fell from about 102 µs on the stock PSA path to 4.73 µs on a register loop that relies on engine behavior Espressif does not document, so every derivation first proves the engine with a self-test; and for nine weeks the count every release build derived was a 600,000 nobody had chosen.

Cover image for PBKDF2 on the ESP32-S3 SHA engine: what does an iteration cost?

The third post in this series argued that no PBKDF2 iteration count can protect a four-digit PIN once someone has copied the flash: a single GPU runs through every PIN faster than the device runs one derivation, and only a per-chip secret mixed in after PBKDF2 stops that attack. That argument is still right. It also leaves the iterations themselves exactly where they were. Every unlock on a hardware password manager I’m building (not yet released) still runs 175,000 of them on an ESP32-S3 and 40,000 on a classic ESP32, and the person holding the device waits for every one.

So this post is about the other half of the key derivation: what one iteration costs on this silicon, how it got from about 102 µs to 4.73 µs, how the firmware decides to trust a fast engine whose behavior Espressif does not fully document, and how the count those iterations multiply was, for nine weeks, a number no build had chosen. My thesis has two parts. The work factor is a number the build must prove it applied. The speed is a property of the engine, and an undocumented engine is only usable behind a check that turns its failure into lost time, never a wrong key.

As in the previous posts, I’ve kept the evidence labels from the bench. A figure is measured when it came off a board, and I give the board, the image and the date. It is computed when I derived it from measured figures, estimated when it is a comment’s or a document’s projection, and not measured when nobody has run it. Some engines are bench-only: they exist in a debug console command and nowhere in a production path. Some checks are host-tested: they run on a model of the engine on a PC, not on silicon. Unless I say otherwise, the November figures come from _stress images, which are debug-console builds that keep the production work factor, flashed onto each board after a full erase.

TL;DR: PBKDF2 on the ESP32-S3's SHA engine

6 key points
  • One PBKDF2-HMAC-SHA256 iteration is two SHA-256 compressions once the HMAC pad states are precomputed. The stock PSA_ALG_PBKDF2_HMAC path of Mbed TLS 4 recomputes them every iteration, so it pays four, plus a MAC operation’s setup: about 102 µs per iteration on the S3 (measured, July 2026). Production Kleidos does not use it.
  • The ESP32-S3 engine can resume from a supplied state. A batched loop over ESP-IDF’s internal SHA calls reached 8.12 µs; a lean register loop, writing only eight text words per compression, reaches 4.73 µs: 827.8 ms at 175,000 on four S3 boards (measured, November 2026).
  • The lean loop relies on behavior Espressif does not document: that the engine keeps text words 8 to 15 across a block. It re-reads them every batch, bounds every wait, and before every derivation runs a self-test, PBKDF2(“Password”, “NaCl”, 8, 64), the inputs of RFC 7914 §11 at 8 iterations (not a published vector). A failure drops to a slower engine from scratch: lost time, never a wrong key.
  • The saving was cashed as time, not iterations: the S3 stays at 175,000, though about 293,000 would fit the old derivation time. The export envelope stays at 600,000, now 2.84 s on the S3 (measured).
  • From 2026-06-17 to 2026-08-21 every base, _release and _secure build derived at 600,000, whatever the board’s header said; an M5StickC Plus2 measured a 34.41 s unlock. Today the count is one build flag per chip family, a build without it does not compile, and a guard checks every environment.
  • Nothing here has been measured on a hardened board, and the classic ESP32’s faster engine path (3.97x) is a bench measurement only.
Quick glossary (if SHA engines aren't your background)
  • PBKDF2 · iteration · work factor: the password-based key derivation of RFC 8018. It repeats an HMAC a chosen number of times (the iteration count, or work factor) so that each guess costs that many HMACs.
  • SHA-256 compression: the core step of SHA-256. It mixes one 64-byte block into an eight-word (32-byte) state. Hashing a message means one compression per 64-byte block.
  • Midstate: the eight-word state after some blocks have been compressed. Saving it lets you skip recompressing those blocks.
  • ipad · opad: HMAC’s inner and outer pads. The key XORed with each fills a full first block, so the state after that block (a midstate) depends only on the key.
  • SHA engine · registers: the ESP32-S3’s SHA-256 hardware. Software talks to it through memory-mapped registers: SHA_H holds the state, SHA_TEXT the 16 words of the block, SHA_CONTINUE starts a compression, SHA_BUSY says it is running.
  • PSA Crypto · TF-PSA-Crypto: the cryptography API that Mbed TLS 4 exposes, and the library that implements it.
  • IRAM: the ESP32’s internal instruction RAM. Code there runs without waiting on the flash cache.
  • Watchdog: a timer that resets the chip if a task stops feeding it. Kleidos’s must be fed at least every 5 s.
  • Open build · _secure build: Kleidos’s builds without and with the hardening of the previous two posts.

What does one PBKDF2 iteration actually compute?

PBKDF2 is defined in RFC 8018, section 5.2. For each 32-byte block of output, it computes a chain of HMACs keyed by the password: U_1 = PRF(P, S || INT(i)), then U_j = PRF(P, U_{j-1}) for each following iteration, and XORs every U into the output. The PRF here is HMAC-SHA256. Each link of the chain needs the previous one, so the chain cannot be split across the two cores of an ESP32: each derivation in Kleidos asks for 32 bytes, one output block, and cutting its iterations in two halves would compute a different and weaker function.

An HMAC is two hashes. The inner hash runs over the key XORed with the inner pad, a full 64-byte block, followed by the message; the outer hash runs over the key XORed with the outer pad followed by the inner digest. In PBKDF2 the key (the password) never changes, so the state after each pad block never changes either. Compute those two midstates once per derivation, and every iteration reduces to two compressions: the inner hash resumes from the ipad midstate and compresses one block holding the previous U; the outer hash resumes from the opad midstate and compresses one block holding the inner digest.

Both of those blocks have the same shape. The message is 96 bytes (the 64-byte pad block already absorbed, plus 32 bytes of digest), so the second block holds 32 bytes of data, then the padding byte 0x80, then 29 zero bytes, then the message length, 768 bits, as 0x03 0x00. Half of every block is the same in every iteration of every derivation. That fact is the whole of the fast loop later in this post.

How many iterations to run is a choice, and the standards are candid that it is a choice about the user’s patience. NIST SP 800-132 says the count “shall be selected as large as possible, as long as the time required to generate the key using the entered password is acceptable for the users”, and it names the range of machines that sentence has to cover: “from a smart card to high-end workstations or servers”. The OWASP Password Storage Cheat Sheet recommends 600,000 iterations of PBKDF2-HMAC-SHA256. On a microcontroller, the iteration count is what you can afford, and what you can afford is a property of how cheap each iteration is. So the first engineering question is how close to two compressions per iteration a given code path actually gets.


Why is the stock PSA path four compressions per iteration?

Kleidos moved to ESP-IDF 6.0.1 and Mbed TLS 4 on 2026-06-18, which put its cryptography behind the PSA API. PSA has a PBKDF2: psa_key_derivation_* with PSA_ALG_PBKDF2_HMAC. For a few hours that day it was the production derivation. Why it no longer is shows in the library’s own loop. This is TF-PSA-Crypto 1.1.1, the version Kleidos builds with on ESP-IDF 6.0.3, generating one output block:

core/psa_crypto.c, TF-PSA-Crypto v1.1.1 (the iteration loop; arguments reflowed) c
for (i = 1; i < pbkdf2->input_cost; i++) {
    /* We are passing prf_output_length as mac_size because the driver
     * function directly sets mac_output_length as mac_size upon success.
     * See https://github.com/Mbed-TLS/mbedtls/issues/7801 */
    status = psa_driver_wrapper_mac_compute(
        attributes,
        pbkdf2->password, pbkdf2->password_length,
        prf_alg, U_i, prf_output_length,
        U_i, prf_output_length,
        &mac_output_length);
    if (status != PSA_SUCCESS) {
        goto cleanup;
    }

    mbedtls_xor(U_accumulator, U_accumulator, U_i, prf_output_length);
}

Every iteration is a complete, one-shot HMAC from the password (source). It derives the ipad and opad blocks from the password again, compresses them again, and only then compresses the message: four SHA-256 compressions per iteration instead of two. On ESP-IDF each of those calls also sets up a fresh transparent HMAC operation, which means allocating, freeing and zeroizing contexts. Nothing in the API lets you do better from the outside:

  • PSA has no PBKDF2 driver entry point that a platform could accelerate: Mbed-TLS/mbedtls#4004, “PBKDF2 PSA driver dispatch implementation”, has been open since January 2021.
  • It has no way to keep a keyed HMAC context, or to export a hash midstate. Public getters for the hash contexts were declined (#5198, closed as not planned in November 2022), and psa_hash_suspend/psa_hash_resume are specified but not implemented (#3274, open since 2020).
  • A September 2025 issue, TF-PSA-Crypto#456, describes why per-key precomputation is lost in general: a PSA key slot has no room to store it. That issue is about RSA and GCM; the obstacle is the same one.

Hardware SHA through PSA loses

The obvious next step is to let ESP-IDF’s PSA driver use the SHA hardware. Measured on both chips, it loses. With 64-byte blocks, more than 95% of the roughly 84 µs per iteration on that path went to the mutex, the clock gate and the dispatch around each block, and the S3 driver also allocates and frees memory on every clone and finish of a hash operation. Espressif’s own configuration help says as much: “SHA hardware acceleration is faster than software in some situations but slower in others. You should benchmark to find the best setting for you” (components/mbedtls/Kconfig, v6.0.3). Isolated on the bench at 160 MHz, one 64-byte HMAC-SHA256 through psa_mac_compute took 387 µs on a StickS3 and 495 µs on a Core2, against 163 and 176 µs computing the pads directly: the PSA layer alone cost 2.4x and 2.8x (measured).

There was a subtler mistake in the same period, wrong from the start. Mbed TLS 4 removed the *_ALT hooks through which a platform used to replace mbedtls_sha256_* with hardware, so those functions are now always the portable C of the built-in library. The S3 backend that the July baseline called “HW SHA” was therefore software: the configuration, the linker map (mbedtls_sha256_update in libmbed-builtin.a(sha256.c.o)) and the arithmetic (about 5,800 cycles per compression at 160 MHz) all say so. Its 15% gain came from removing the PSA dispatch; performance and correctness were unaffected, but the comments of the time credited the wrong mechanism.


How fast is each engine, and on which chip?

Kleidos has had seven ways of computing PBKDF2-HMAC-SHA256 since June. Six of them were production on some chip at some point; one never was. Here they are on the ESP32-S3, at 240 MHz, with the evidence behind each bar:

The first three are ways of calling a library. The PSA hash-clone precompute, production from 2026-06-18 to 2026-07-06, computed the pad states once and cloned them through the PSA hash API, which already halved the cost. “Mbed TLS direct” called the library’s SHA-256 functions directly, skipping PSA, and was the S3’s production path for one day, 2026-07-06. The software core is Kleidos’s own SHA-256, written for the classic ESP32 and used on the S3 only as the last rung of a fallback ladder you’ll meet below. The last two drive the SHA engine.

The classic ESP32 has a different engine and a different story:

Classic ESP32: the engines and where they run
EnginePer iterationStatus
Stock PSA PBKDF2≈167 µsBench only
PSA hash-clone≈77.7 µsRetired 2026-07-06
Software core (IRAM)37.4 to 39.0 µsProduction
Engine, start and continue9.83 µsBench only

All four classic figures are measured at 240 MHz: stock PSA as 4,187 ms at 25,000 on a Core2 in July, the hash-clone figure from June, the software core at 40,000 on five classic boards in November, and the engine figure as 393 ms at 40,000 on a Core2 v1.3 on 2026-11-14. That last row is the classic chip’s fastest path, and nothing in production runs it; a later section explains why.


What did the batched port loop buy?

The ESP32-S3’s SHA engine can do something the classic ESP32’s cannot: start a compression from a state that software supplies. ESP-IDF declares it as a capability of the chip, with a one-line comment: “The SHA engine is able to resume hashing from a user supplied context” (SOC_SHA_SUPPORT_RESUME in the S3’s soc_caps.h, v6.0.3). The classic ESP32’s capability list has no such entry. That one capability is what makes the pad midstates expressible in hardware.

The first engine loop, production on the S3 since 2026-07-07, takes the engine once per derivation instead of once per block. pbkdf2HmacSha256HwResume acquires the hardware with esp_sha_acquire_hardware(), absorbs the two pad blocks, and then for every compression calls three functions from ESP-IDF’s internal SHA header (sha/sha_core.h): esp_sha_write_digest_state() to load the midstate, esp_sha_block() to pass one 64-byte block, and esp_sha_read_digest_state() to read the result back. No lock, no clock gate and no driver dispatch per block. It runs in batches, feeding the watchdog between them, and clears the engine before releasing it.

Measured on 2026-11-14 on the four S3 boards (Cardputer ADV, CoreS3 SE, T-Deck and an open StickS3), it derives 175,000 iterations in 1,421 to 1,423 ms: 8.12 µs per iteration. In July, at 160 MHz and 35,000 iterations, the StickS3 had measured 11.8 µs per iteration, 4.6 times the software core.

That speed is what the July counts were sized to. On 2026-07-07 the declared counts rose from 35,000 to 175,000 on the S3 (about 1.54 s of derivation on that engine) and from 25,000 to 40,000 on the classic chip (about 1.57 s on its software core): the same budget of roughly 2 s for an unlock on an open build, spent on a cheaper iteration. Hold on to the word “declared”. It matters later.

The port loop had two accepted costs. It uses ESP-IDF’s internal SHA API, which has to be re-verified at every platform bump. And it holds the fleet-wide SHA and AES lock for the whole derivation. Today it is the second rung of the ladder: it runs only when the lean loop has been refused, and it passes the same self-test first.


How does the lean loop reach 4.73 µs per iteration?

The port loop still writes a full block for every compression: sixteen words into the text registers, eight of which are the same padding every time. The lean register loop, in production on the S3 since 2026-11-21, stops doing that. Per HMAC it does five things, in this order:

The register names are Espressif’s (hwcrypto_reg.h, v6.0.3); the sequence is resumeChain in src/crypto/pbkdf2_engine_chain.h, with the register moves in ResumeRegs in src/platform/peripherals/sha_engine.h. Words stay in the engine’s order end to end: the state read back is, as it stands, the first eight words of the next block, so no byte swapping happens inside the loop. This is the heart of the chain, as it is in the firmware:

pbkdf2_engine_chain.h: the chain (indent reduced; two branches and a comment trimmed) cpp
Regs::writeHigh( tail );
for ( uint32_t i = 0; i < more; ++i ) {
    Regs::loadState( ipadState );
    Regs::writeLow( u );
    if ( !Regs::run() ) [[unlikely]] {
        overrun = true;
        break;
    }
    zero |= ( Regs::readState( inner.data() ) == 0U ) ? 1U : 0U;

    Regs::loadState( opadState );
    Regs::writeLow( inner.data() );
    if ( !Regs::run() ) [[unlikely]] {
        overrun = true;
        break;
    }
    zero |= ( Regs::readState( u ) == 0U ) ? 1U : 0U;
    xorWords( acc, u, std::make_index_sequence<kWords>{} );
}

The first line is the one the speed comes from. writeHigh( tail ) writes text words 8 to 15 once, before the batch, and nothing inside the loop writes them again. The tail is a constant:

pbkdf2_engine_chain.h: the fixed padding (reflowed) cpp
/// Text words 8 to 15 of every steady-state block,
/// in engine order: the bytes 0x80, 29 zero bytes,
/// then 0x03 0x00 (a 96-byte message is 768 bits).
inline constexpr Words kEngineTail = {
    0x00000080U, 0U, 0U, 0U,
    0U, 0U, 0U, 0x00030000U };

How the loop was found

It was not the first idea. On 2026-11-14 I timed four ways of driving the engine against the port loop, at 175,000 iterations, on the four S3 boards. The plan said a candidate had to beat production by 1.5x to be worth its risk:

Engine loops at 175,000 iterations, 240 MHz (measured, 2026-11-14)
Bench modeTimevs port loop
Port loop (production then)1,421 to 1,423 ms1.00x
hwraw1,506 to 1,508 ms0.94x
hwll, 16 text words1,033 to 1,034 ms1.375x
hwll8, 8 text words848 to 849 ms1.674x

Driving the registers directly but writing all sixteen text words (hwll) gave 1.375x, and the bench notes called it “a dead end”. Writing only the eight words that change (hwll8) gave 1.674x, and it was eligible only if the tail survived on all four S3 boards. It did; the next section is about that condition.

Timing the same mode at 240 and 160 MHz splits each iteration into the part that scales with the CPU clock and the part that does not: about 3.0 µs outside the CPU clock (the engine’s compression and the register traffic over the peripheral bus) and about 1.8 µs inside it. Writing eight fewer words per compression saved 1.06 µs per iteration, about 66 ns per register write, which means the register traffic is now most of each iteration. The bench notes conclude, fairly, that “no further loop work is in sight”.

Bounding the wait without paying for it

The first production version of the chain took 898 ms, 1.58x. Its wait loop decremented a counter on every read of the busy flag, and that counter sat on the CPU side of every compression: 48 ms of the derivation at 240 MHz, 25 ms at 160. Reading the flag four times per count, and unrolling the XOR, brought it to 827 ms, 22 ms under the unbounded hwll8 that the bench had timed:

sha_engine.h: the bounded wait (indent reduced; comments trimmed) cpp
[[gnu::always_inline]] static bool waitIdle() {
    constexpr uint32_t             kUnroll = 4U;
    const volatile uint32_t* const busy    = reg( SHA_BUSY_REG );
    for ( uint32_t n = kBusyPollLimit / kUnroll; n != 0U; --n ) {
        if ( idleWithin( busy, std::make_index_sequence<kUnroll>{} ) ) {
            return true;
        }
    }
    return false;
}

[[gnu::always_inline]] static bool run() {
    store( *reg( SHA_CONTINUE_REG ), 1U );
    return waitIdle();
}

kBusyPollLimit is 10,000, so the loop counts 2,500 times and reads the flag at most 10,000 times. A wait that runs out returns false, and the chain stops. Three versions of that stop were built and timed on the StickS3 at 175,000: accumulating faults and finishing every iteration (828.3 ms), testing one flag per iteration (834.7 ms), and leaving at the first overrun (826.3 ms). The last is both the cheapest and the safest, because a hung engine then costs one bounded wait instead of one per remaining compression of the batch. It has been the production version since 2026-11-21.

The production figures

Measured through the production entry point, VaultCrypto::deriveKey(), self-test included, on 2026-11-14 and 15:

At 175,000 the CoreS3 SE and the Cardputer ADV measured 827.8 ms and the T-Deck 828.4 ms, three runs each within 0.01 ms: 4.73 µs per iteration, 1.717 times the 14 November baseline. The self-test inside that figure costs about 0.2 ms. On 2026-11-21, on the restructured tree, the open StickS3 went from 1,423.23 to 1,423.27 ms (port loop, five runs) to 826.32 to 826.37 ms (lean loop, five runs). The firmware’s own cost model rounds 4.73 µs up to 4,800 ns (kKdfIterationCostNs), which matters for a ceiling we’ll get to.

The loop is its own function, leanChainKeepTail, placed in IRAM with KLEIDOS_IRAM_ATTR. It cannot be inline: an inline function can’t carry the IRAM section attribute, its literal pool would land outside it, and the Xtensa linker rejects that. The cost, read from the Cardputer’s ELF with nm -S, is 787 bytes of IRAM and 16 bytes of static RAM for the ladder’s state.


What if the engine stops keeping the tail?

Writing the padding once per batch only works if the engine leaves text words 8 to 15 as written across a compression. Espressif does not document that it does. Nothing in the ESP-IDF API or the register descriptions promises that SHA_TEXT survives a block; the fast loop relies on an observation, not a guarantee.

What I have instead is a measurement and a set of runtime checks. The bench reads the tail back after a run: text_kept=1 in 5 of 5 reads on each of the Cardputer ADV, CoreS3 SE, StickS3 and T-Deck on 2026-11-14, and again on the T-Deck on 2026-11-15. That covers the four S3 boards in the fleet. It covers no other revision of the silicon, and no future ESP-IDF that might change how the engine is clocked or reset between blocks. So the loop treats the tail as something to check, not something to trust, and reports three kinds of fault (ChainFault), never trusting a result that carries one:

  • Lost tail (tailLost): at the end of every batch, the chain re-reads SHA_TEXT[8..15] and compares it with kEngineTail. If the engine didn’t keep it, every block of that batch was compressed with the wrong padding.
  • Zero state (zeroState): a state read that is all zeros means the engine did not run. The chain ORs that test into a flag on every read, as the excerpt above shows.
  • Overrun (overrun): a wait that ran out of its 10,000 reads. The chain leaves at the first one.

Why not use ESP-IDF’s own functions for the wait and the read, as the port loop does? Because of what they do when the engine misbehaves. In ESP-IDF 6.0.3, esp_sha_read_digest_state() calls sha_hal_read_digest(), which waits in while (sha_ll_busy()) {} with no limit, and calls abort() if the state it reads is all zeros, with the comment “SHA peripheral returned all zero state, probably due to fault injection” (sha_hal.c, v6.0.3). Both are reasonable defaults for a general library. For a fallback ladder they are the wrong ones: a stuck engine should cost a bounded wait and a slower path, not hang the unlock or reboot the device.

The engine is scrubbed on every exit

After a chain, the engine’s state registers hold the last U and its text registers the last inner digest. With a public salt and a public count, either one is enough to test PIN guesses against. So the driver, deriveOnResumeEngine, scrubs the engine before releasing it, on every exit path, success or fault:

sha_engine.cpp: scrub() cpp
void scrub() {
    // A hung engine is left as it is: nothing it holds is trusted, and the
    // zeros are written either way.
    static_cast<void>( ResumeRegs::waitIdle() );
    constexpr std::array<uint32_t, kStateWords> kZero{};
    ResumeRegs::loadState( kZero.data() );
    ResumeRegs::writeLow( kZero.data() );
    ResumeRegs::writeHigh( kZero.data() );
}

The port loop does the same scrub. The driver also computes the pad blocks and each output block’s U_1 in software (firstU), so the engine loop itself places no limit on the length of the password, the salt or the output.

Batches and the watchdog

Both engine loops and the software core run in batches of 16,384 iterations (kSliceIterations), feeding the watchdog between batches. A batch takes about 0.08 s on the lean loop, 0.13 s on the port loop and 0.64 s on the software core at 240 MHz, and under 2 s on any engine at 80 MHz, so the watchdog is fed far inside its 5 s whichever engine runs.


How does the firmware decide to trust the engine on this boot?

Runtime checks inside the loop catch an engine that fails visibly. They don’t catch one that computes a wrong value cleanly. For that, every derivation starts with a known answer, and every engine rung has to return it before it is allowed near the secret.

The self-test is PBKDF2-HMAC-SHA256(“Password”, “NaCl”, 8, 64), all 64 bytes compared, without an early exit. The password and salt are the inputs of the second vector in RFC 7914, section 11. The count is not: the RFC’s vector uses 80,000 iterations, and this test uses 8. The expected key is therefore not a published test vector. It was computed on the host by OpenSSL’s PBKDF2 (through Python’s hashlib, Node’s crypto and openssl kdf) and by a loop written from RFC 8018 section 5.2 over hashlib.sha256 alone, and they agree:

pbkdf2_engine_chain.h: the self-test's inputs (comments reflowed; the 64-byte key follows) cpp
/// The self-test's password:
/// RFC 7914 section 11's second input.
inline constexpr const char* kSelfTestPassword = "Password";

/// The self-test's salt.
inline constexpr const char* kSelfTestSalt = "NaCl";

/// The self-test's count: fourteen chain
/// iterations over its two output blocks.
inline constexpr uint32_t kSelfTestIterations = 8U;

/// PBKDF2-HMAC-SHA256( "Password", "NaCl", 8, 64 ).
/// Computed on the host by OpenSSL's PBKDF2
/// (Python hashlib, Node crypto, `openssl kdf`)
/// and by a loop written from RFC 8018 section 5.2
/// over hashlib.sha256 alone; they agree.

You can reproduce the key in one line. I recomputed it with hashlib for this post, and it matches the firmware’s kSelfTestKey byte for byte:

The self-test key, recomputed on a PC python
>>> import hashlib
>>> hashlib.pbkdf2_hmac(
...     "sha256", b"Password", b"NaCl", 8, 64
... ).hex()
'd0f2d6162ab7d5877734ba70d16a31e7'
'7727596742088f88a8b0c9def9735b78'
'1fc721ca55430b1ee77b8851f4ad4c2b'
'f350610e8d30fb36b8b84896fac63a37'

(Python prints the 128 hex digits on one line; I’ve split them into four lines of 32.) Why 8 iterations and 64 bytes? Because the test runs before every derivation and must be nearly free (about 0.2 ms), and because a 64-byte output needs two output blocks, each with its own chain of 7 engine iterations after its software U_1: 14 chain iterations that exercise the multi-block path, which a 32-byte unlock never uses. What it does not exercise is the batch boundary, which starts at 16,384 iterations; the tail re-read covers that.

The ladder: lean, then port loop, then software

The self-test is one half of the trust decision. The other half is what happens when a rung fails. deriveOnLadder (in pbkdf2_engine_chain.h, instantiated in pbkdf2HmacSha256Selected in src/crypto/vault_crypto_kdf.cpp) tries three engines, and each engine rung must pass the self-test and then derive the secret without a fault:

no fault

fails: wipe,
refuse until reboot

no fault

fails: wipe

Lean loop
self-test, then the secret

Key from
the lean loop

Port loop
self-test, then the secret

Key from
the port loop

Software core
derives from scratch

The derivation ladder on the ESP32-S3. A refused rung's output is wiped and the next rung derives from scratch, so no partial result crosses a rung. The lean loop, once refused, stays refused until the next boot: later derivations start at the port loop.
pbkdf2_engine_chain.h: the ladder (indent reduced; one condition reflowed) cpp
++state.derivations;
if ( !state.leanRefused ) {
    if ( passesSelfTest<Lean>()
         && Lean( pwd, pwdLen, salt, saltLen, iterations, out, outLen ) ) {
        state.last = KdfEngine::LeanResume;
        return true;
    }
    state.leanRefused = true;
    util::secureZero( out, outLen );
}
++state.fallbacks;
if ( passesSelfTest<Port>()
     && Port( pwd, pwdLen, salt, saltLen, iterations, out, outLen ) ) {
    state.last = KdfEngine::PortLoop;
    return true;
}
util::secureZero( out, outLen );
state.last = KdfEngine::Software;
return Soft( pwd, pwdLen, salt, saltLen, iterations, out, outLen );

This is the thesis in code. If the engine stops keeping the tail after some future ESP-IDF update, the lean loop fails its self-test or reports tailLost, is refused for the rest of the boot, and the unlock takes about 1.42 s on the port loop instead of 0.83 s. The firmware logs it once: SHA engine: lean loop refused, using the port loop. If the port loop also fails, the software core takes about 6.2 s (6,211 ms at 175,000 on the S3, measured on the 14 November baseline). What it never does is hand a key from a misbehaving engine to the vault.

There is one honest gap in that picture. The port loop still calls ESP-IDF’s own wait and read, so a stuck engine or an all-zero state there is an unbounded wait or an abort(), exactly as it was before the lean loop existed. On a device, the software rung is therefore reached only when both engine rungs return a wrong but non-zero self-test. The lean loop is the better-behaved of the two engine rungs.

Counting what the ladder did

The ladder counts its own behavior in a small LadderState, kept under the crypto hardware lock: derivations, fallbacks (derivations that did not finish on the first rung), whether the lean loop was refused, and which engine ran last. Debug builds print it with a console command:

Console output format (debug builds) text
KDFSTAT derivations=<n> fallbacks=0 last_engine=lean lean_refused=0
kdf: 600000 iterations: 2841 ms @ 240 MHz engine=lean

The second line is the unlock trace, compiled in only with KLEIDOS_UNLOCK_TRACE, which is on by default only in debug builds; production logs Key derived (%u iterations). Neither line carries a secret. In every measurement campaign cited in this post, KDFSTAT? read fallbacks=0 lean_refused=0 before and after.


How do you know the fast key is the right key?

A self-test of 8 iterations proves the engine computes PBKDF2 correctly on one input. It doesn’t prove that the batching, the tail handling and the exits produce the same key as a standard implementation for every input the vault will use. Four independent checks cover that, and they are worth separating, because each one is weaker or stronger in a different way.

Against the firmware’s own software core, on the device. A debug console command, KDFDIFF, pits the production derivation (VaultCrypto::deriveKey(), wherever the ladder lands) against the software core on random inputs from the chip’s RNG: 480 cases in the shapes the host tests use (counts 1, 2, 3 and 1,000; outputs of 16, 32, 64 and 100 bytes; salts of 0, 16, 32, 55, 56 and 100 bytes; passwords of 0, 8, 64, 65 and 100 bytes), plus the build’s own count at 32 and 64 bytes. It compares in constant time and prints neither input nor key:

KDFDIFF result (measured, CoreS3 SE, Cardputer ADV and T-Deck, 2026-11-14/15) text
KDFDIFF OK cases=482 mismatches=0 engine=lean

The same result held after merging main, and on 2026-11-21 on the StickS3 (engine=lean) and on the classic StickC Plus2 (engine=software).

Against an implementation that shares no code with the firmware. The bench command KDFBENCH prints a short fingerprint of the derived key (the first 4 bytes of its SHA-256), which I compared with Python’s hashlib.pbkdf2_hmac at counts of 1, 2, 4,096, 40,000 and 175,000, on two inputs: a fixed bench PIN with 16 zero salt bytes and a 32-byte output, and the RFC 7914 inputs with two output blocks. 50 of 50 matched on the StickS3 across five modes and 25 of 25 on the Plus2, plus 35 more with main images. The engine bench modes (hwll, hwll8, swfix, hw4 and port) print no time at all unless they first return the published RFC 7914 vector at 80,000 iterations, so a fast wrong engine can’t even produce a benchmark figure.

On the host, against a model of the engine. Nineteen cases run the chain on a fake SHA engine (test/support/fake_sha_engine.h): the RFC 7914 vectors, the inputs of RFC 6070 (published for HMAC-SHA1) under SHA-256, the self-test, a lost tail, a zero state, an engine that hangs mid-derivation, and a ladder that falls all the way to software. Two test names state the property directly: no fake fault ever returns a wrong key, and the engine holds no word of the last state after a derivation. These are host-tested: they prove the logic against a model, not the silicon.

On a real vault, off the device. On the CoreS3 SE, the Cardputer ADV and the T-Deck (2026-11-14 and 15), I provisioned a full vault, read the flash with esptool read-flash, and opened it on a PC with qa/tools/offline_unlock.py, which derives with stock PBKDF2: it opened with the bench PIN and rejected a wrong one. The keys the lean loop derives are the ones a host derives. Note what that test needs: it worked because those were open builds, with no device binding. On a hardened build, opening the vault off the device is exactly what the device-bound key of post 012 exists to prevent, so this check can only ever run on an open build.


Who chose the 600,000 iterations?

Nobody did, and that is the second half of the thesis.

From 2026-06-17 to 2026-08-21, every base, _release and _secure build of the firmware derived its unlock key at 600,000 iterations, whatever the board’s configuration said. During those nine weeks, each board’s count lived in its variants/<v>/variant.h, behind an #ifndef. The file that derives, src/crypto/vault_crypto.h, did not include variant.h, and nothing forced it to, so in the translation unit that actually called PBKDF2 the macro was undefined, and it fell to vault_crypto.h’s own fallback. On 2026-06-17 that fallback had been raised from 100,000 to 600,000, with a commit titled “raise default PBKDF2 to 600k iterations (OWASP 2025)”. Meanwhile the version command, VER?, printed pbkdf2_iters=40000 on a classic board, because the console code does include variant.h. The derivation and the report about the derivation read two different numbers.

included

not included

variant.h
#ifndef: 40,000

Console code

VER? prints
pbkdf2_iters=40000

vault_crypto.h
macro undefined

vault_crypto.h fallback
600,000

Unlock key derived
at 600,000

A classic board's build between 2026-06-17 and 2026-08-21: one macro, two translation units, two answers. The console code included variant.h; the deriving code did not.

The reason nobody noticed is the most instructive part. Only two kinds of build passed the count on the compiler’s command line: _debug builds, which set it to 1 so that development unlocks are instant, and the native host tests, which use 2,048. Those are exactly the builds used every day. The builds that derived at 600,000 were the ones you flash when you want to see the real thing, and the real thing just looked slow.

It was not the first time the header had been invisible. Before 2026-06-17 the fallback was 100,000 and the variant headers already said 100,000 on the S3 and 10,000 on the classic chip; the classic boards were deriving ten times their declared count. On 2026-06-18 a commit set the declared counts to about 2 s of work (30,000 on the S3, 20,000 on classic) and stated that the 600,000 fallback was “never reached because every variant.h overrides it”. It was the only value ever reached.

  1. Until 2026-06-17
    Fallback 100,000

    variant.h declares 100,000 (S3) and 10,000 (classic); the derivation never sees it.

  2. Fallback raised to 600,000

    From here every non-debug build derives at 600,000.

  3. ESP-IDF 6.0.1 and PSA

    Declared counts 30,000/20,000, then 35,000/25,000 the same evening; still invisible.

  4. Engines per architecture

    ESP-IDF 6.0.2. Mbed TLS direct on the S3; the IRAM software core on classic.

  5. Port loop on the S3

    Declared counts raised to 175,000/40,000; still invisible.

  6. Lockout reproduced

    A vault made at 600,000 rejects the correct PIN on a 40,000 build.

  7. The count becomes a build flag Milestone

    [kdf] anchor, #error with no fallback, a variant guard. Plus2: 34.41 s to 2.49 s.

  8. ESP-IDF 6.0.3

    Mbed TLS 4.1.1, TF-PSA-Crypto 1.1.1.

  9. Clock boost moves inside deriveKey
  10. Eight-board baseline

    hwll8 at 1.674x; the classic engine at 3.94x to 3.97x (bench).

  11. Lean loop with the ladder on main

    KDFDIFF, KDFSTAT?, exit at the first overrun, stored-count ceiling.

  12. Unlock measured on seven boards

What 600,000 cost, chip by chip

It’s tempting to summarize the bug as “unlocks took 30 seconds”. That is true only for part of the period and part of the fleet:

  • The S3 in June: on the PSA hash-clone path, the June comment in variant.h computed “600k ≈ 32 s”. That is an estimate; nobody measured a 600,000 unlock on the S3 that month.
  • The S3 from 2026-07-07: the port loop derived 600,000 in about 4.9 s. That figure comes from later measurements of the port loop at 600,000 (4,856 to 4,880 ms), so for that window it is computed from measurements, not a recorded unlock.
  • The classic ESP32 throughout: much longer. On an M5StickC Plus2 in August, the unlock took 34.41 s, with the log line Crypto: Key derived (600000 iterations) (measured; the image was not recorded). After the fix, the same board logged Key derived (40000 iterations) in 2.49 s; the record doesn’t say whether that is the derivation or the whole unlock.

So every count stated for these builds during those nine weeks, in the repository or anywhere else, described what was intended, not what the firmware derived.

What a count change broke

At the time, a vault did not record its own count, so a build that derived with a different count than the one the vault was created with simply produced a different key and rejected the right PIN. The July raise, from 35,000/25,000 to 175,000/40,000, predates the stored count, and it locked out vaults provisioned with the old figures. In August a board reproduced the failure twice: a vault provisioned at 600,000 rejected the correct PIN on a 40,000 build. Vaults that predate the stored count are reprovisioned with a full erase. At this stage that touches only development and personal devices, which is the only reason it was an inconvenience rather than data loss.


How does the build prove the count it applied?

The fix of 2026-08-21 does not add a better default. It removes the default. The count is defined in exactly one place, a [kdf] section of platformio.ini, as one anchor per chip family:

platformio.ini: the single definition site ini
[kdf]
iterations_esp32s3 = -DCRYPTO_PBKDF2_ITERATIONS=175000
iterations_esp32 = -DCRYPTO_PBKDF2_ITERATIONS=40000

Each variant adds its family’s anchor to the flag block that all its targets share: base, _debug, _release, _secure, _secure_dev, _stress and the host harness. _debug removes it with build_unflags and sets 1. _stress replaces that list and removes the 1, so the production count comes back without being defined twice; a second -D would be a macro redefinition, and with -Werror that is fatal:

platformio.ini: how _stress gets the production count back ini
[stress]
build_unflags =
    -DCORE_DEBUG_LEVEL=1
    -DCRYPTO_PBKDF2_ITERATIONS=1

The header that derives has no fallback at all. A build that forgot the anchor does not compile:

vault_crypto.h (a Doxygen comment omitted before the constant; padding before the backslash removed) cpp
#ifndef CRYPTO_PBKDF2_ITERATIONS
    #error \
        "CRYPTO_PBKDF2_ITERATIONS is not defined: add this SoC family's anchor from platformio.ini [kdf] to the environment build_flags"
#endif  // CRYPTO_PBKDF2_ITERATIONS
static constexpr uint32_t kPbkdF2Iterations = CRYPTO_PBKDF2_ITERATIONS;

The comment next to it says why in one sentence: “a fallback would let the vault derive keys at a work factor no diagnostic reports and no build ever chose”. The #ifndef is gone from the eight variant.h files, and VER? and the portal’s security posture now read kPbkdF2Iterations, the same constant deriveKey() uses; the version token is build_pbkdf2_iters. A report and the thing it reports can no longer read different numbers.

A compile error catches a missing count. It does not catch a wrong one. That is the job of invariant 22 of scripts/check_variants.py: no variants/*/variant.h may define the macro; every environment must resolve, through extends and build_unflags, to exactly one definition; and that definition must be its family’s figure, except _debug (and _jtag, which extends it), which must be 1. The expected figures are written into the guard itself:

scripts/check_variants.py (reflowed) python
KDF_ITERATIONS_BY_FAMILY = {
    "esp32s3": 175000,
    "esp32": 40000,
}

The duplication is deliberate. In the guard’s own words, “a guard that read the number back from the file it guards would ratify any edit”. Changing the work factor now takes two edits in two files, and a reviewer sees both.

Why per chip family and not per board? Because the cost of an iteration depends on the engine, and the engine depends on the family: the S3 can load a midstate into its SHA engine and the classic ESP32 cannot. Both counts were sized to an unlock of about 2 s on an open build, with the engines of July.


What does each vault remember about its own count?

The build’s count decides only what a new vault gets. Each vault stores its own count in meta.bin as kdfIterations: a 32-bit little-endian field at offset 19 of the record, covered by the record’s authentication tag (wrapTag, from the vault-envelope post). The unlock derives with that stored count, never with the build’s. That is what the July raise lacked, and it changes what raising the count means: a new build can raise it without locking out existing vaults, and only a change of secret, which re-keys the vault, moves an old vault to the new figure.

A count read from flash is attacker-controlled input until its tag is checked, and the tag can only be checked after the derivation. So the parser bounds it first. The accepted window is relative to the build that reads it (src/vault/vault_meta.h):

  • The minimum is the build’s count divided by 8 (kMetaKdfWeakeningSlack), so that a production image will not open a 1-iteration vault that a debug build created.
  • The maximum is whatever fits a 6 s derivation at the family’s cost per iteration, capped at 600,000:
vault_meta.h: the stored-count ceiling (reflowed) cpp
inline constexpr uint32_t kKdfDerivationBudgetMs = 6'000;

constexpr uint32_t metaMaxKdfIterations( uint32_t costNs ) {
    const uint64_t fits =
        uint64_t{ kKdfDerivationBudgetMs } * 1'000'000U / costNs;
    return fits < kKdfIterationsPolicyMax
               ? static_cast<uint32_t>( fits )
               : kKdfIterationsPolicyMax;
}

At 4,800 ns per iteration the S3’s ceiling is the 600,000 cap; at the classic chip’s 39,400 ns it is 152,284. The 6 s budget is a denial-of-service limit, not a security level: a tampered meta.bin makes the device derive before it can know the record is tampered, so the ceiling bounds how long a forged count can make the device work. A static_assert fails the build if a family’s own count falls outside its window, and a count outside the window, including the zero of a missing field, is a malformed record: the unlock fails closed, and the count is never replaced by a default.

The window also bounds what a raise can do to old vaults. A vault opens under a new build only if its count is at least an eighth of the new build’s and under the family’s ceiling. So raising the S3 from 175,000 to 600,000, 3.4x, would leave every existing S3 vault openable.


Why was the lean saving spent on time, not iterations?

When the lean loop landed, there were two ways to spend it. Keep the count and shorten the unlock, or keep the derivation time and raise the count. At the port loop’s 1.42 s, the lean loop would fit about 293,000 iterations. The S3 stayed at 175,000, before and after: the work factor did not change, so the unlock got shorter.

The reason is in the numbers that post 012 already set out. The reference attacker is one RTX 5090 Founders Edition running hashcat mode 10900 (PBKDF2-HMAC-SHA256) at 11,157.2 kH/s at 999 iterations, from a published hashcat benchmark; about 1.115 × 1010 iterations per second, scaled linearly to each count. It is the fastest consumer GPU with a published figure for this mode, chosen because a slower card would describe a slower attacker:

One RTX 5090, offline, by work factor (computed)
IterationsGuesses/sAll 4-digit PINs
40,000 (classic)≈278,700≈0.036 s
175,000 (S3)≈63,700≈0.16 s
600,000 (OWASP)≈18,600≈0.54 s

At 175,000, the same card exhausts six digits in about 16 s and eight in about 26 minutes. Raising the S3 to 293,000 would slow it by the same 1.67x the lean loop gained. Two more PIN digits slow it by 100x. Offline, the defenses that matter are the length of the secret and the passphrase option on an open build, and the per-chip binding on a hardened one; online, against someone at the keypad, it is the escalating lockout that wipes the vault at ten failures. The repository’s own conclusion is the one this post started from: the iteration count is a supporting multiplier, not a barrier. A 1.67x multiplier was worth less than giving every unlock back 0.6 s.

That 0.6 s is real at the user’s end. On the open StickS3, from the last dialed digit to the first frame of the home list (30 credentials and 10 notes in the vault), the unlock went from 2,678 ms on the port loop to 2,036 ms on the lean loop (measured, 2026-11-21); the classic Plus2, which runs the software core either way, measured 2,736 and 2,742 ms. On 2026-11-27, the same kind of vault unlocked in 1.8 to 2.4 s on the four S3 boards and 2.8 to 4.8 s on the three classic ones (the table in post 012 has each board). The derivation is no longer the largest cost of an unlock: in July it was estimated at more than 85% of one, and by November loading the credential list and the PIN screen’s fixed feedback of about 0.8 s weighed more.


Why does the export envelope stay at 600,000?

The vault’s encrypted export is a different threat. Once written to an SD card or downloaded, the file is attacked offline with unlimited tries, its key comes from a person’s passphrase, and nothing on the device can rate-limit it. There the KDF is the only barrier, so it uses the full OWASP figure: kExportKdfIterations = 600000 in src/crypto/export_envelope.h, guarded by static_assert( kExportKdfIterations >= 600000, "the export writer derives from a human passphrase: keep its work factor" ). It is independent of the unlock count.

The reader derives with the count in the envelope’s authenticated header, bounded between 1 and 10,000,000, so older envelopes stay importable; the minimum of 1 exists only for the portal’s transit envelope, whose passphrase is a random 192-bit key.

The lean loop changed this path more than the unlock. KDFBENCH at 600,000 measured 2,836 to 2,838 ms on the CoreS3 SE, Cardputer ADV and T-Deck on the lean loop, against 4,856 to 4,858 ms on the port loop (2026-11-14 and 15). Three exports of the T-Deck’s full test vault to its SD card, each a 191,060-byte envelope, traced kdf: 600000 iterations: 2841 ms @ 240 MHz engine=lean and took 14.55 to 14.56 s from the first byte to the file on the card; on the port loop that would be about 16.6 s (computed from the two derivation times, not measured). On the classic chip, 600,000 is a long wait: the Plus2’s portal export measured 34.7 s at 160 MHz on 2026-10-12. That is the price of a backup an attacker can’t cheaply test, and the unlock could not pay it: about 2.9 s of derivation on the S3 and about 22.5 s on classic (estimated).


What does the classic ESP32 run instead?

The classic ESP32’s SHA engine can only start a hash from SHA-256’s initial value. It has no way to load a midstate, so the pad precompute that both S3 engine loops depend on can’t be expressed on it. Production on the classic chip is a software core, pbkdf2HmacSha256Software in vault_crypto_kdf.cpp: the same two compressions per iteration over a preformed block, with the padding written once and byte order converted only at the edges. The compression (src/crypto/sha256_soft.cpp) keeps its transform in IRAM and its round constants in DRAM, so the loop never waits on a flash cache miss.

It replaced the library because the library was slower and not even consistent across boards: at 160 MHz on a Core2 (ESP-IDF 6.0.2, medians of three, 2026-07-06), the core did 17,053 iterations per second against 12,500 for Mbed TLS direct and 7,810 through PSA, and Mbed TLS’s core measured 13,843 per second on a Plus2 but 10,412 on a Gray, where Kleidos’s core stayed above 17,000 on all of them. At 40,000 iterations and 240 MHz in November it takes 1,560 ms on the Core2 v1.3 (39.0 µs per iteration), 1,497 to 1,498 ms on the Plus SE, Plus 1.1 and CoreInk, and 1,496.31 to 1,496.46 ms on the StickC Plus2 (37.4 µs). With Wi-Fi or Bluetooth running, a classic ESP32 stays at 160 MHz, because 240 MHz needs a different BBPLL setting, so a derivation from the portal takes 240/160 times as long, about 2.4 s.

A specialized compression for the fixed block (swfix: 64 unrolled rounds in IRAM) measured 1.225x to 1.253x the core. The adoption threshold was 1.2x, and it cleared it “by a hair”; it was not adopted.

The classic engine: 3.97x on the bench, nowhere in production

There is a faster path on the classic chip. PBKDF2 doesn’t actually need a loadable midstate if you’re willing to pay for the pad block again: use the engine’s start operation on the pad block, its continue operation on the message block, and its load operation to read the result, four compressions per iteration with the text memory held per HMAC. Measured on 2026-11-14 at 40,000 iterations, this hw4 mode took 393 ms on the Core2 v1.3 (9.83 µs per iteration, 3.97x the software core; 568 ms at 160 MHz) and 380 ms on the Plus SE (3.94x), the Plus 1.1 and the CoreInk: 2.46 µs per compression. It passes its known answer on revision-1 PICO-D4 chips too, where a read erratum of the DPORT bus applies and every engine read goes through esp_dport_access_reg_read or esp_dport_access_read_buffer. Unlike the software core, it barely scales with the CPU clock: 1.45x from 160 to 240 MHz, against 1.50x.

It would buy a classic unlock about 1.1 s shorter at 40,000, or about 158,000 iterations in today’s time. Nothing in production runs it: it is a measurement. Its first version held a critical section for the whole derivation and tripped the interrupt watchdog. On main it exists only in the debug bench, src/debug/debug_crypto_bench.cpp, compiled only with DEBUG_SERIAL_BUTTONS. The name KdfEngine::Restart (“The classic ESP32 engine, restarted per HMAC”) exists in kdf_engine.h and in the KDFSTAT? vocabulary, but no production path selects it: on a classic chip, pbkdf2HmacSha256Selected goes straight to the software core. There is no dated plan to bring it to production.


Why does the clock matter as much as the engine?

Every number above is at 240 MHz, and that is not the clock the device idles at. Every state of the firmware’s state machine runs at an 80 MHz base clock, and an unboosted derivation runs about three times slower: a console PIN on the Plus2 at 40,000 iterations measured 4,548 ms at 80 MHz, and a PIN change, which pays two derivations, was estimated at about 9.6 s on the S3. The same console in July, at 80 MHz, had measured 5.4 to 5.8 s.

Since 2026-10-12 the boost lives inside VaultCrypto::deriveKey() itself, so every derivation runs at 240 MHz (160 MHz on a classic with Wi-Fi), whoever calls it:

vault_crypto_kdf.cpp: the production entry (comments omitted) cpp
const kleidos::platform::crypto_hw::ScopedLock hwLock;
const kleidos::platform::CpuBoostGuard cpuBoost;

CpuBoostGuard (src/platform/power/cpu_boost.h) is a scoped guard: it raises the clock to 240 MHz only if it is lower, and restores it on destruction. It is taken inside the hardware lock, so two derivations can never stack a boost and a restore; a caller that already boosted keeps its boost. Measured on 2026-10-12 and 13, the Plus2 then derived in 1,499 ms from the PIN screen and every other caller landed within 5% of that, and the StickS3 in 1,423 to 1,424 ms on the port loop, with the clock back at 80 MHz after each.

The lock around it, crypto_hw::ScopedLock, serializes the derivation against the audio path. On the boards with an ES8311 audio codec, its I2S traffic can corrupt the shared AES and SHA engines (espressif/esp-idf#18640), and on the S3 the whole derivation drives the engine directly, so it runs inside the lock from start to end. One failure mode of that issue, stale DMA registers after a channel is torn down, is covered by no mutex; Kleidos doesn’t reach it today because its I2S code never deletes a channel while the codec is running. And if it ever did, the self-test turns a corrupted engine into lost time, not a wrong key.


What has been measured, and on what?

The figures in this post come from different kinds of evidence, and the difference matters more than the figures. Here they are, by label:

Evidence, by label
  • Measured: the lean loop, the tail check and KDFDIFF on the four S3 boards (_stress images, 240 MHz, 2026-11-14 to 21); the export at 600,000 on the T-Deck; the software core on five classic boards; the 34.41 s unlock on the Plus2 in August (image not recorded).
  • Host-tested: nineteen engine cases on a model of the engine, including lost tail, zero state, hang and fallback; the self-test key recomputed by a QA test with hashlib.
  • Computed: the about 4.9 s an S3 derived at 600,000 between July and August; the about 16.6 s export on the port loop; the attacker rates; the about 293,000 iterations the old time would fit.
  • Estimated: the about 32 s at 600,000 on the S3 in June (a comment in variant.h); the about 22.5 s and 24 s at 600,000 on the classic chip; the about 9.6 s PIN change at 80 MHz; the July share of the unlock spent in PBKDF2.
  • Bench only: the stock PSA path, hwmd, hwll, swfix and the classic engine path, hw4, at 3.94x to 3.97x.
  • Not measured: the lean loop on a hardened board (below); the lean loop on any S3 silicon outside the fleet’s four boards; the tail on any ESP-IDF later than 6.0.3.

The hardened case deserves its own sentence. The hardened bench StickS3 does have encrypted-vault unlock figures from November, 3,025 to 4,329 ms after a reset (from a console PIN to the first frame of the list, debug image at the production count, vaults from 30 credentials and 10 notes to 250 and 40), but those were taken on the port loop (1,423 to 1,424 ms of derivation) with the old unmapped vault read, and all of them are over the 2 s budget. None of the lean loop’s figures here should be read as hardened figures.


The honest costs and limits

What you accept with this design
  • The lean loop depends on undocumented engine behavior. Nothing re-verifies it on an ESP-IDF bump except its own runtime checks: the batch re-read, the per-derivation self-test and the ladder.
  • The port loop uses ESP-IDF’s internal SHA API (sha/sha_core.h), which must be re-verified at each platform bump, and it leaves one honest gap in the ladder.
  • The Mbed TLS version gate must move for 4.2. The firmware’s private-API use is gated by a static_assert that MBEDTLS_VERSION_NUMBER lies in [4.0.0, 4.2.0).
  • The classic ESP32 has no engine path in production (hw4 is bench only); classic unlocks pay the software core.
  • The saving went to time, not iterations (why).
  • No hardened figures for the lean loop (what has been measured).
  • PBKDF2 was kept over memory-hard KDFs. In the comparison of alternatives, Argon2id in SRAM bought a factor of 1 to 8 over PBKDF2, unreliably; in PSRAM about 5, but S3-only, would split the fleet (the Plus1 and CoreInk have no PSRAM), and would leave derived state in probeable PSRAM on open builds; scrypt in SRAM 0.4, a loss. The decision is reopened only if adversaries with custom silicon enter the open-build-with-passphrase threat model.
  • A misbehaving engine costs time, never the key (the ladder).
  • The count a build derives with is the count it reports, and a build without one doesn’t compile.

Wrap: a number the build proves, an engine behind a check

Two different things went wrong with this key derivation in 2026, and they needed two different kinds of fix.

The speed was a property of the engine. The PSA path paid four compressions and a MAC setup per iteration; the port loop paid two compressions and a full block of register writes; the lean loop pays two compressions and half a block. Each step down came from knowing what the silicon could do, and the last step came from relying on something the silicon does without being documented to do it. That is acceptable for one reason only: every derivation proves the engine first, every batch re-reads what it relied on, and any failure falls to a slower engine from scratch. If the tail ever stops surviving, an unlock gets 0.6 s slower, and the vault never sees a key computed from the wrong padding.

The work factor was a number nobody checked. For nine weeks, every build anyone would ship derived at a count no one had chosen, while the diagnostics confidently reported the one that had been. The fix isn’t a better default; it is no default. The count is defined once per chip family, a build that lacks it fails to compile, a guard with its own copy of the expected figures checks every environment, the diagnostics read the same constant the derivation does, and each vault carries its own count inside its authenticated record. The number is still only a supporting multiplier against a short PIN, as post 012 argued, but now it is a number the build can prove it applied.

Kleidos PBKDF2, as built on the ESP32-S3

One iteration in 4.73 µs on the S3's SHA engine, behind a 64-byte self-test on every derivation, bounded waits, a tail re-read every batch, an engine scrub on every exit and a ladder that falls back from scratch; a work factor that is one build flag per family, with no fallback, a guard, and a per-vault authenticated count bounded before use. Held back by what is not proven: the fast loop relies on undocumented engine behavior checked only at runtime and on four boards, nothing has been measured on a hardened board, the classic ESP32 has no engine path in production, and the count itself is a supporting multiplier, not the defence against a short PIN.

Frequently asked questions

How fast is PBKDF2-HMAC-SHA256 on an ESP32-S3?

In Kleidos's production derivation, which drives the SHA engine's registers directly, 4.73 µs per iteration at 240 MHz: 175,000 iterations in about 828 ms, measured on four ESP32-S3 boards in November 2026 with ESP-IDF 6.0.3. The stock PSA path of Mbed TLS 4 measured about 102 µs per iteration.

Why is PSA_ALG_PBKDF2_HMAC slow on a microcontroller?

TF-PSA-Crypto computes each iteration as a fresh HMAC from the password, so it recomputes the inner and outer pad states every time: four SHA-256 compressions per iteration instead of two, plus a MAC operation's setup. PSA has no API to reuse a keyed HMAC state, and on the ESP32 its hardware SHA driver adds a lock, a clock gate and a dispatch per 64-byte block that cost more than the compression.

Is it safe to rely on undocumented behavior of the ESP32-S3 SHA engine?

Only behind checks that turn its failure into lost time. Kleidos's register loop writes the padding words of the SHA text registers once per batch and relies on the engine keeping them, which Espressif does not document. It re-reads them every batch, runs a self-test before every derivation, bounds every wait, and on any fault wipes the output and derives again on a slower engine: a changed engine costs time, never a wrong key.

What is the Kleidos PBKDF2 self-test?

PBKDF2-HMAC-SHA256 with password "Password", salt "NaCl", 8 iterations and a 64-byte output, all 64 bytes compared without early exit. Those are the inputs of RFC 7914 section 11's second vector, but at 8 iterations instead of 80,000, so the expected key is not a published vector: it was computed on the host with OpenSSL's PBKDF2 and with a loop written from RFC 8018, and they agree. Its two output blocks exercise the multi-block path, and it costs about 0.2 ms.

Why did the Kleidos firmware derive keys at 600,000 iterations by mistake?

Each board's count was a #define in its variant.h, which the deriving code never included, so it fell back to a 600,000 default while the version command, which did include variant.h, reported the board's figure. Debug builds and host tests passed the count on the command line, so nobody noticed. From 2026-06-17 to 2026-08-21 every base, release and secure build derived at 600,000; an M5StickC Plus2 measured a 34.41 s unlock. The count is now one build flag per chip family, with no fallback.

Why does Kleidos not raise its PBKDF2 count to OWASP's 600,000?

For the unlock, 600,000 does not fit the roughly 2 s budget: it takes 2.84 s of derivation on the ESP32-S3 (measured) and about 22.5 s on the classic ESP32 (estimated), and against a short PIN the count is a supporting multiplier, not the barrier. The encrypted export, which an attacker can test offline without limit, does use 600,000, and a static_assert keeps it there.