In development. It changes without notice.
Topic
Cryptography
From a PIN or passphrase to the keys that seal the vault, the secret bound to the chip, the seal of a backup and the password generator.
All of it is PSA crypto, with one backend on the device and in the tests on a computer, so a result is the same bytes in both.
The secret is never stored. PBKDF2-SHA256 stretches it, with the vault's random 16-byte salt, into a 32-byte key-encryption key (KEK). The iteration count depends on the chip: 175,000 on the ESP32-S3 and 40,000 on the ESP32. The KEK seals no record: from it come the verifier that checks the secret and the two keys that unwrap and authenticate the vault key, and it is wiped once the unwrap is done.
The vault key is 32 random bytes, kept only wrapped, in the vault's metadata. The keys of the records come from it. An unlocked session holds it in RAM until it locks; the KEK never reaches flash. The scheme is in Keys, Metadata & Rotation.
The records are AES-256-CBC under a fresh random IV each, with an HMAC-SHA256 tag over the ciphertext and its context, checked before anything is decrypted.
The device binding. In a hardened build the KEK is mixed, through HKDF-SHA256, with a secret of the device, so a guess made elsewhere on a copy of the flash also needs that secret. On the ESP32-S3 it is computed by the chip from an eFuse key that software cannot read; on the ESP32 it is a random value in encrypted storage, so there it is as strong as the flash encryption. An open build has no binding, and the PBKDF2 output is the KEK.
What does what
| Function | Algorithm | For |
|---|---|---|
| VaultCrypto:: | PBKDF2-SHA256 | The secret to the KEK |
| VaultCrypto:: | AES-256-CBC with PKCS#7 padding | Records and files |
| VaultCrypto:: | HMAC-SHA256 | Tags, the keys' derivation, HKDF |
| VaultCrypto:: | A compare that takes the same time whatever it finds | A verifier or a tag |
| VaultCrypto:: | HMAC-DRBG, seeded from the hardware generator | Salts, the vault key, tokens, generated passwords |
| VaultCrypto:: | A wipe the compiler cannot drop | Key material after use |
| bindKek() | HKDF-SHA256 | The device binding |
A record's IV does not need to be secret and is drawn from Random Numbers. Two longer jobs of the portal, the seal of a backup and its opening, run on a worker of their own.
Files | |
| file | src/ |
| Services-core (Core 0) crypto worker for the admin portal's heavy KDF. | |
| file | src/ |
| On-device known-answer self-test for the crypto primitives. | |
| file | src/ |
| Binds the vault's key-encryption key to the chip, on the hardened build. | |
| file | src/ |
| Passphrase-wrapped export envelope: encrypt vault exports at rest. | |
| file | src/ |
| The engines a PBKDF2 derivation can finish on, and their names. | |
| file | src/ |
| Cryptographically random password generator (hardware RNG). | |
| file | src/ |
| PBKDF2-HMAC-SHA256 on a SHA engine that loads a midstate: the chain, its driver, and the ladder that never returns a wrong key. | |
| file | src/ |
| Self-contained software SHA-256 for the PBKDF2 inner loop. | |
| file | src/ |
| Vault cryptographic primitives: AES-256-CBC and PBKDF2-SHA256. | |
| file | src/ |
| The PBKDF2 back-ends and the VaultCrypto:: | |
Classes | |
| struct | kleidos:: |
| One known-answer test result row. More about kleidos:: | |
| class | kleidos:: |
| Persistence port for the NVS-pepper backend (host-testable seam). More about kleidos:: | |
| class | kleidos:: |
| Resolve the device-binding secret for this build/chip. More about kleidos:: | |
| struct | kleidos:: |
Non-owning view over a contiguous byte buffer (may be empty: len 0). More about kleidos:: | |
| class | kleidos:: |
| Streaming producer of a passphrase-encrypted export envelope. More about kleidos:: | |
| class | kleidos:: |
| Streaming reader for the chunked envelope: verify-before-decrypt, one chunk at a time. More about kleidos:: | |
| class | kleidos:: |
| Stateless random-password generator backed by the hardware RNG. More about kleidos:: | |
| struct | kleidos:: |
| What a chain run reported. Any flag means the output is not used. More about kleidos:: | |
| struct | kleidos:: |
| What the ladder keeps across derivations. More about kleidos:: | |
| struct | kleidos:: |
| Incremental software SHA-256 state (trivially copyable). More about kleidos:: | |
| struct | kleidos:: |
| Opaque AES key-schedule handle for the context-reuse API (PSA backend). More about kleidos:: | |
| class | kleidos:: |
| Stateless collection of the vault's cryptographic primitives. More about kleidos:: | |
| class | kleidos:: |
| Streaming AES-256-CBC encryptor with PKCS#7 padding. More about kleidos:: | |
| class | kleidos:: |
| Streaming AES-256-CBC decryptor with PKCS#7 removal. More about kleidos:: | |
| class | kleidos:: |
| Streaming HMAC-SHA256 with a sign finish and a constant-time verify finish. More about kleidos:: | |
Typedefs | |
| using | kleidos:: |
| Unit of work marshaled onto the admin-crypto worker. | |
| using | kleidos:: |
| using | kleidos:: |
| Destination for envelope bytes as they are produced. | |
| using | kleidos:: |
| One SHA-256 state or half block, as words. | |
| using | kleidos:: |
| A chain instantiation, as the driver calls it (an IRAM wrapper on the device). | |
| using | kleidos:: |
| Called between two slices of a chain: feeds the watchdog of the running task. | |
| using | kleidos:: |
Functions | |
| bool | kleidos:: |
| Spawn the admin-crypto worker task. Idempotent — repeated calls return true without re-spawning. | |
| void | kleidos:: |
| Stop the worker and free its queue once it has left. | |
| bool | kleidos:: |
Run job on the worker and block the caller until it returns, then propagate the job's success flag. | |
| bool | kleidos:: |
| Run every known-answer vector through the production primitives. | |
| bool | kleidos:: |
| Run the self-test and print a structured pass/fail report to serial. | |
| bool | kleidos:: |
| Mix the device secret into the KEK, the PBKDF2 output (RFC 5869 HKDF-SHA256). | |
| void | kleidos:: |
Host tests only: run fault on every bindKek, ahead of the backend (which is the identity on the host). | |
| void | kleidos:: |
Host tests only: run the classic hardened build's pepper backend over store. | |
| bool | kleidos:: |
RFC 5869 HKDF-SHA256 over ikm, keyed by salt, with info. | |
| constexpr size_t | kleidos:: |
| bool | kleidos:: |
| Wrap plaintext in a passphrase-encrypted export envelope. | |
| bool | kleidos:: |
| Unwrap and decrypt a passphrase-encrypted export envelope. | |
| constexpr const char * | kleidos:: |
The name the unlock trace and diagnostics print for engine. | |
| constexpr size_t | kleidos:: |
The bytes a pool of poolLen characters keeps: those below the largest multiple of poolLen that fits in a byte. | |
| template<size_ | |
| void | kleidos:: |
XOR the eight words of u into acc, unrolled. | |
| template<typename Regs, bool KeepTail> | |
| ChainFault | kleidos:: |
| PBKDF2's U(i) chain on an engine that loads a midstate. | |
| template<typename Engine, ResumeChainFn Chain> | |
| bool | kleidos:: |
| PBKDF2-HMAC-SHA256 (RFC 8018 section 5.2) with the chain on a midstate-loading engine. | |
| template<RungFn Rung> | |
| bool | kleidos:: |
Whether Rung returns kSelfTestKey. | |
| template<RungFn Lean, RungFn Port, RungFn Soft> | |
| bool | kleidos:: |
PBKDF2-HMAC-SHA256 down a ladder of engines: Lean, then Port, then Soft. | |
| template<RungFn Lean, RungFn Port, RungFn Soft> | |
| bool | kleidos:: |
PBKDF2-HMAC-SHA256 on a rung other than avoid: the second derivation a mint compares its key with. | |
| void | kleidos:: |
| Reset a context to the SHA-256 initial hash value. | |
| void | kleidos:: |
Absorb len bytes of data into ctx. | |
| void | kleidos:: |
Finalize ctx and write the digest. | |
| KLEIDOS_ | kleidos:: |
| One raw SHA-256 compression: stateOut = compress(stateIn, block). | |
Variables | |
| constexpr size_t | kleidos:: |
| constexpr size_t | kleidos:: |
| Size of the device-binding secret and the HKDF output, in bytes. | |
| constexpr std::array< uint8_t, 4 > | kleidos:: |
| Envelope magic marker ("KEXP", Kleidos EXPort). Not NUL-terminated on disk. | |
| constexpr uint8_t | kleidos:: |
| Envelope format version byte. | |
| constexpr size_t | kleidos:: |
| PBKDF2 salt size for the export KDF, in bytes. | |
| constexpr uint32_t | kleidos:: |
| Export PBKDF2-SHA256 iteration count. | |
| constexpr uint32_t | kleidos:: |
| Lowest iteration count the reader accepts in an envelope header. | |
| constexpr uint32_t | kleidos:: |
| Highest iteration count the reader accepts in an envelope header. | |
| constexpr size_t | kleidos:: |
| Minimum export passphrase length (bytes). | |
| constexpr size_t | kleidos:: |
| constexpr size_t | kleidos:: |
| constexpr size_t | kleidos:: |
| Chunk framing: ciphertext length (4 bytes, little-endian) + flags (1 byte). | |
| constexpr uint8_t | kleidos:: |
| Flag bit marking the last chunk. A stream that ends without it is truncated. | |
| constexpr size_t | kleidos:: |
| constexpr size_t | kleidos:: |
| Bytes a chunk adds beyond its ciphertext: its framing and its tag. | |
| constexpr size_t | kleidos:: |
| constexpr size_t | kleidos:: |
| Words in a SHA-256 state, and in each half of a message block. | |
| constexpr uint32_t | kleidos:: |
| constexpr Words | kleidos:: |
| constexpr const char * | kleidos:: |
| The self-test's password: RFC 7914 section 11's second input. | |
| constexpr const char * | kleidos:: |
| The self-test's salt. | |
| constexpr uint32_t | kleidos:: |
| The self-test's count: fourteen chain iterations over its two output blocks. | |
| constexpr std::array< uint8_t, 64 > | kleidos:: |
| constexpr size_t | kleidos:: |
| SHA-256 digest size in bytes (FIPS 180-4). | |
| constexpr size_t | kleidos:: |
| SHA-256 compression block size in bytes (FIPS 180-4). | |
| constexpr size_t | kleidos:: |
| SHA-256 state size in 32-bit words (FIPS 180-4). | |
| constexpr size_t | kleidos:: |
| SHA-256 compression block size in 32-bit words (FIPS 180-4). | |
Typedef Documentation
AdminCryptoJob #
Unit of work marshaled onto the admin-crypto worker.
The job runs on the worker (Core 0) and returns its success flag. The caller-owned ctx carries both the inputs and the output buffers, so no data is copied through the queue. A plain function pointer (not std::
- Parameters
-
Name Direction Meaning ctx in, out Caller-owned context: inputs plus output buffers.
- Return values
-
Value Meaning true Job succeeded. false Job failed.
BindFaultFn #
A host test's fault on a binding: the call's index since the fault was set, the KEK in place; false fails the binding as a backend error would.
EnvelopeSink #
Destination for envelope bytes as they are produced.
- Parameters
-
Name Direction Meaning data in Bytes to take. len in Byte count. user in Opaque cookie handed to the writer.
- Return values
-
Value Meaning true Taken. false The sink failed; the writer aborts.
RungFn #
One rung of the ladder: a whole PBKDF2-HMAC-SHA256 derivation; false on a refusal or a fault, with the output wiped.
Enumeration Type Documentation
DeviceSecretBackend #
Backend that supplies the device-binding secret.
KdfEngine #
The engine a PBKDF2-HMAC-SHA256 derivation finished on.
PassCharSet #
PepperLoad #
Outcome of a PepperStore::
The pepper IS the device secret on the NVS-pepper backend: minting a second one derives a different KEK and makes every record already in the vault permanently undecryptable with the correct secret. Only PepperLoad:: — a store that answered, and answered that nothing is there — may authorize minting, and only at a provision (PepperMint::
PepperMint #
Whether a computation of the device secret may mint the pepper.
Only a provision, which writes a vault that does not exist yet, may: the pepper is then made for it. Everything else (an unlock, the proof of a mint, a PIN change, the brute-force guard's tag) finds a pepper or fails, so a lost pepper beside a vault is reported, never replaced by one no record was made under.
Function Documentation
beginAdminCryptoWorker() #
Spawn the admin-crypto worker task. Idempotent — repeated calls return true without re-spawning.
Default placement is PRO_CPU (Core 0) at the lowest application priority, so the radio stacks, the HTTP server and the services workers on that core all preempt it and the UI core stays with the loop task. The queue depth is 1: only one httpd request runs a backup KDF at a time and every caller blocks anyway.
- Parameters
-
Name Direction Meaning core in Target core for the worker (default PRO_CPU). priority in Application priority for the worker (default the lowest).
- Return values
-
Value Meaning true Worker spawned, or already running (idempotent). false Worker creation failed (queue allocation or task-create error), or the worker of a previous session has not left yet (see shutdownAdminCryptoWorker()); jobs then run inline.
- See also
- shutdownAdminCryptoWorker
bindKek() #
Mix the device secret into the KEK, the PBKDF2 output (RFC 5869 HKDF-SHA256).
When binding is disabled (DeviceSecretBackend::) this is a no-op: the kek buffer is left exactly as PBKDF2 produced it, so open builds derive the unbound key byte-for-byte. When binding is enabled, kek is replaced in place by HKDF-Expand(HKDF-Extract(salt = deviceSecret, IKM = kek), "kleidos-device-bind-v1", 32).
The operation is deterministic: the same chip and the same kek / vaultSalt always yield the same bound key, so unlock reproduces what provision stored. Nothing here can tell a wrong device secret from the right one (the eFuse key is unreadable, so there is no known answer to check it against): a mint proves its key by deriving it a second time, binding included, and comparing (VaultMeta::), which catches a fault that does not repeat.
- Parameters
-
Name Direction Meaning vaultSalt in Per-vault KDF salt (selects the eFuse-HMAC secret). vaultSaltLen in Length of vaultSaltin bytes.kek in, out KEK (the PBKDF2 output) in; bound KEK out. kekLen in Length of kekin bytes (expects 32).mint in PepperMint::only for the derivation of a fresh vault's first KEK.AtProvision
- Return values
-
Value Meaning true kekholds the (possibly unbound) KEK to use.false A binding backend error occurred, or the pepper is absent and may not be minted; kekwas wiped.
- Warning
- SECURITY: wipe
kekafter use; never log it.
deriveOffRung() #
PBKDF2-HMAC-SHA256 on a rung other than avoid: the second derivation a mint compares its key with.
After Lean the proof runs on Port, which must pass the self-test first, and on Soft when it does not; after Port, or after Soft, it runs on Soft. A proof that lands on the rung it checks (the software core, the one rung of the classic ESP32 and the host) catches a fault that came and went, not one that stays. Never touches LadderState:: or LadderState:: a proof neither refuses a rung for the boot nor counts as the boot's derivation; it counts in LadderState::.
- Template Parameters
-
Name Meaning Lean The production engine. Port The fallback engine. Soft The software core.
- Parameters
-
Name Direction Meaning state in, out What the ladder keeps across derivations. avoid in The engine the derivation under proof finished on. pwd in Password bytes. pwdLen in Length of pwd.salt in Salt bytes. saltLen in Length of salt.iterations in PBKDF2 count; zero is refused before any rung runs. out out Receives outLenbytes.outLen in Bytes to derive. used out The engine the proof finished on.
- Return values
-
Value Meaning true outholds the key.false A zero count, or the software core refused.
deriveOnLadder() #
PBKDF2-HMAC-SHA256 down a ladder of engines: Lean, then Port, then Soft.
The first rung runs unless it was refused before this boot: it must return kSelfTestKey and then derive the secret with no fault. Otherwise the refusal is recorded (once, for the boot) and the second rung must pass the same check before it derives; when it does not, the software core, the reference the host proves, derives. A refused derivation's output is wiped before the next rung starts from the beginning. Every derivation that does not finish on Lean counts in LadderState::.
What the checks prove, and what they do not: the self-test proves that a rung computes PBKDF2 correctly for its 14 chain iterations, run just before the secret's derivation, and the engine rungs report the three faults their chain can see (a zero state, a lost tail, a wait past its bound). A corruption that raises none of them during the secret's own derivation (hundreds of thousands of compressions after the self-test) is not seen: the rung then returns true with a wrong key. Nothing here can tell that key from the right one, so a caller that commits a record under a fresh key proves it first by deriving it again off the rung that produced it (deriveOffRung, the vault's mint). An unlock does not: a wrong key there fails the record's verifier.
- Template Parameters
-
Name Meaning Lean The production engine. Port The fallback engine. Soft The software core.
- Parameters
-
Name Direction Meaning state in, out What the ladder keeps across derivations. pwd in Password bytes. pwdLen in Length of pwd.salt in Salt bytes. saltLen in Length of salt.iterations in PBKDF2 count; zero is refused before any rung runs. out out Receives outLenbytes.outLen in Bytes to derive.
- Return values
-
Value Meaning true outholds what the rung that finished derived.false A zero count, or the software core refused (it does not for a non-zero count).
deriveOnResumeEngine() #
PBKDF2-HMAC-SHA256 (RFC 8018 section 5.2) with the chain on a midstate-loading engine.
- Template Parameters
-
Name Meaning Engine The engine's lifecycle: static bool acquire(), static void release(), static bool firstBlockState( const uint8_t* block, uint32_t* stateOut ), static void scrub(). Chain The chain instantiation (resumeChain over the engine's registers, or its IRAM wrapper).
- Parameters
-
Name Direction Meaning pwd in Password bytes (nullptr when pwdLenis 0).pwdLen in Length of pwd.salt in Salt bytes (nullptr when saltLenis 0).saltLen in Length of salt.iterations in PBKDF2 count, at least 1. out out Receives outLenbytes; wiped on any failure.outLen in Bytes to derive. sliceIterations in Iterations per chain call (kSliceIterations). onSlice in Called after each slice; nullptr for none.
- Return values
-
Value Meaning true outholds the key, and no fault was seen.false A zero count or slice, an engine that would not start, or a fault.
exportEnvelopeMaxBytes() #
Largest envelope plainBytes bytes of plaintext can produce: one chunk per full plaintext chunk plus the final one that carries the padding.
- Parameters
-
Name Direction Meaning plainBytes in Plaintext the envelope will carry.
- Returns
- The envelope's largest possible size in bytes.
hkdfSha256() #
RFC 5869 HKDF-SHA256 over ikm, keyed by salt, with info.
HKDF-Expand(HKDF-Extract(salt, ikm), info, outLen). Exposed so the binding construction can be verified against the published RFC 5869 known-answer vectors. Built on VaultCrypto::
- Parameters
-
Name Direction Meaning salt in Salt (HKDF-Extract key); may be empty. ikm in Input key material. info in Context/ application info; may be empty. out out Output keying material buffer. outLen in Bytes requested (<= 255 * 32).
- Return values
-
Value Meaning true outholdsoutLenderived bytes.false A primitive failed or outLenis out of range.
kdfEngineName() #
The name the unlock trace and diagnostics print for engine.
- Parameters
-
Name Direction Meaning engine in An engine.
- Returns
- software, port, lean or restart; ? outside the table.
< An engine.
< Its printed name.
passesSelfTest() #
Whether Rung returns kSelfTestKey.
- Template Parameters
-
Name Meaning Rung The rung to check.
- Returns
- True for all 64 bytes of it.
passgenAcceptBound() #
The bytes a pool of poolLen characters keeps: those below the largest multiple of poolLen that fits in a byte.
Below it every residue modulo poolLen occurs equally often, so a kept byte picks every character with the same probability (rejection sampling).
- Parameters
-
Name Direction Meaning poolLen in Characters in the pool, 1 to :: kPassgenByteValues.
- Returns
- The exclusive bound, a multiple of
poolLen.
resumeChain() #
PBKDF2's U(i) chain on an engine that loads a midstate.
- Template Parameters
-
Name Meaning Regs The engine's register moves (loadState, writeLow, writeHigh, run, readState, readHigh). KeepTail Write text words 8 to 15 once per call and check them at its end (true), or before every compression (false).
- Parameters
-
Name Direction Meaning ipadState in Engine state after the key XOR ipad block. opadState in Engine state after the key XOR opad block. tail in Text words 8 to 15 (kEngineTail). u in, out U(k) on entry, U(k + more) on return.acc in, out The running XOR of every U. more in Iterations to run; fewer run after an overrun.
- Returns
- The faults seen.
run() #
Run every known-answer vector through the production primitives.
- Parameters
-
Name Direction Meaning results out Array receiving kVectorCount rows (caller-owned). cap in Capacity of resultsin elements.
- Return values
-
Value Meaning true Every vector matched its expected output byte-for-byte. false At least one vector mismatched, or capwas too small.
runAndReport() #
Run the self-test and print a structured pass/fail report to serial.
Emits one <NAME>=PASS|FAIL line per vector plus a final RESULT=PASS|FAIL passed=<n>/<total> summary line, so a test can parse the outcome.
- Return values
-
Value Meaning true All vectors passed. false One or more vectors failed.
runOnAdminCryptoWorker() #
Run job on the worker and block the caller until it returns, then propagate the job's success flag.
When the worker is running the caller (typically the httpd task) blocks on a task notification while job executes on the worker below every other task of the services core. When the worker is not running the job runs inline on the caller's thread — identical to the pre-offload behavior — so native tests and any worker-down fallback are transparent.
- Parameters
-
Name Direction Meaning job in Work to execute (must not be nullptr).ctx in, out Caller-owned context passed verbatim to job.
- Return values
-
Value Meaning true jobreported success.false jobreported failure, orjobwasnullptr.
- See also
- beginAdminCryptoWorker
setBindFaultForTest() #
Host tests only: run fault on every bindKek, ahead of the backend (which is the identity on the host).
- Parameters
-
Name Direction Meaning fault in The fault, or nullptrto clear it; setting it restarts the index at zero.
setPepperStoreForTest() #
Host tests only: run the classic hardened build's pepper backend over store.
With a store set, DeviceSecret::DeviceSecretBackend::, DeviceSecret::store with the caller's mint, and DeviceSecret::store, so a host suite sees what a classic _secure board sees: which derivation may mint the pepper, and the boot's answer to a pepper lost beside its vault.
- Parameters
-
Name Direction Meaning store in The store (not owned; it outlives its use), or nullptrfor the host's own backend,DeviceSecretBackend::.None
sha256Finish() #
Finalize ctx and write the digest.
- Parameters
-
Name Direction Meaning ctx in, out Active context (left consumed; re-init before reuse). out out Receives :: kSha256DigestSize bytes.
sha256Init() #
Reset a context to the SHA-256 initial hash value.
- Parameters
-
Name Direction Meaning ctx out Context to initialize.
sha256Transform() #
One raw SHA-256 compression: stateOut = compress(stateIn, block).
The low-level seam for the PBKDF2 inner loop: when every message is a single preformed 64-byte block (a 32-byte digest plus fixed padding), the caller can keep midstates and message words in 32-bit word order and skip the byte-buffer and padding machinery of the incremental API entirely. Word order is the logical FIPS 180-4 one: blockWords are the 16 big-endian-loaded message words M0..M15 and the states are H0..H7 (a Sha256Ctx state after absorbing whole blocks is exactly such a state).
- Parameters
-
Name Direction Meaning stateIn in 8-word input chaining state H0..H7. blockWords in 16 message words (big-endian-loaded). stateOut out Receives the 8-word output state; may alias stateIn.
- Warning
- SECURITY: inputs/
outputs are key-derived in PBKDF2 use; callers wipe their buffers with mbedtls_after the loop.platform_ zeroize()
sha256Update() #
Absorb len bytes of data into ctx.
- Parameters
-
Name Direction Meaning ctx in, out Active context. data in Input bytes (may be nullptronly whenlenis 0).len in Number of bytes to absorb.
shutdownAdminCryptoWorker() #
Stop the worker and free its queue once it has left.
Wakes the worker and waits up to 200 ms for it to leave its loop, then deletes the queue. A worker that has not left by then (still running a job, or still waiting for the services core, where every other task outranks it) keeps its queue, since a worker blocked on a deleted queue would wake into freed memory: it leaves by itself, and beginAdminCryptoWorker() refuses to start another until it has.
Safe to call multiple times and when the worker was never started. MUST be paired with beginAdminCryptoWorker() on ADMIN_MODE exit (called from AdminPortal::
- See also
- beginAdminCryptoWorker
unwrapExport() #
Unwrap and decrypt a passphrase-encrypted export envelope.
Parses and bounds-checks env, re-derives the key from passphrase and the envelope salt, verifies the HMAC tag in constant time BEFORE decrypting (verify-before-decrypt), then decrypts. Any parse, authentication, or decryption failure returns false with out cleared (fail closed).
- Parameters
-
Name Direction Meaning env in Envelope bytes. envLen in Length of envin bytes.passphrase in Export passphrase bytes (need not be NUL-terminated). passLen in Length of passphrasein bytes (must be > 0).out out Receives the recovered plaintext; cleared on any failure.
- Return values
-
Value Meaning true Authentication passed and outholds the plaintext.false Malformed envelope, wrong passphrase, tampering, or a backend failure; outis empty.
- Warning
- SECURITY: the caller owns wiping
passphraseand, once consumed, the recovered plaintext inout. Derived keys and scratch are wiped internally.
wrapExport() #
Wrap plaintext in a passphrase-encrypted export envelope.
Derives a fresh high-iteration key from passphrase and a random salt, encrypts plain with AES-256-CBC (fresh random IV), authenticates the header and ciphertext with HMAC-SHA256 (encrypt-then-MAC), and writes the envelope described in the file header into out.
- Parameters
-
Name Direction Meaning plain in Plaintext bytes to protect (may be empty when plainLenis 0).plainLen in Length of plainin bytes.passphrase in Export passphrase bytes (need not be NUL-terminated). passLen in Length of passphrasein bytes (must be > 0).out out Receives the serialized envelope; cleared on entry and on any failure.
- Return values
-
Value Meaning true outholds a complete envelope.false Invalid arguments or a backend failure; outis empty.
- Warning
- SECURITY: the caller owns wiping
passphrase. Derived keys and intermediate buffers are wiped internally before return.
xorWords() #
XOR the eight words of u into acc, unrolled.
- Template Parameters
-
Name Meaning I The words, 0 to 7.
- Parameters
-
Name Direction Meaning acc in, out The running XOR. u in The U just computed.
Variable Documentation
kEngineTail #
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).
kExportChunkCipherMax #
Most ciphertext one chunk may carry: a full plaintext chunk plus the block the cipher may hold back and the padding block of a final chunk.
kExportChunkPlainBytes #
Plaintext carried by one authenticated chunk. The writer cuts its stream here, so a reader holds one chunk's ciphertext and plaintext at a time and never more — the property that lets a full vault restore on a device whose free heap is a fraction of its own backup.
kExportEnvelopeOverhead #
Smallest possible envelope: the header and one final chunk's overhead (its ciphertext is at least the padding block).
kExportHeaderLen #
Authenticated header: magic(4) + ver(1) + kdfIter(4) + salt(16) + iv(16). The chunks start here.
kExportKdfIterations #
Export PBKDF2-SHA256 iteration count.
Independent of the device unlock work factor and intentionally large: an export file is attacked offline with no rate limiting, so the KDF cost is the only brute-force barrier. Set to the OWASP PBKDF2-SHA256 floor (600,000): at 240 MHz, and at the per-iteration costs of kKdfIterationCostNsEsp32S3 and kKdfIterationCostNsEsp32, one derivation takes about 2.9 s on an ESP32-S3 and about 24 s on an ESP32, once per export or import. Over the admin portal an ESP32 derives at 160 MHz (the boost does not change the BBPLL under Wi-Fi), so about half as long again. Envelopes written with older (smaller) counts remain importable: unwrap uses the authenticated header count (bounded by ::
kExportKdfIterationsMax #
Highest iteration count the reader accepts in an envelope header.
Twice what the writer uses: nothing the firmware or the admin page writes is above ::
kExportKdfIterationsMin #
Lowest iteration count the reader accepts in an envelope header.
The admin page re-seals the entries an owner picked from a backup in a one-time transit envelope whose passphrase is 24 random bytes (32 base64url characters, 192 bits) drawn by the page for that one request. A full-entropy key gains nothing from stretching, so that envelope's header states a count of 1, and the page relies on this bound. Such an envelope is transit only: it exists as one request body and is never a download. The header count is authenticated by chunk 0's tag, so nobody can lower the count of a backup a person sealed.
kMinExportPassphraseLen #
Minimum export passphrase length (bytes).
A passphrase shorter than this provides too little entropy to justify the PBKDF2 cost; wrapExport rejects it with false. This floor is a UX and entropy guard at the envelope layer; the caller (admin handler) enforces the same bound before the passphrase reaches this API.
kSelfTestKey #
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.
kSliceIterations #
Iterations of one slice of the chain: 0.08 s on the ESP32-S3 lean loop, 0.13 s on the port loop, 0.64 s on the software core at 240 MHz, under 2 s at 80 MHz, so the watchdog is fed far inside its 5 s on any engine.
kVectorCount #
Number of rows reported by run(): one per primitive plus the vault encrypt/static_assert, so a row added without touching this constant fails the build instead of being dropped from every caller's array.