Kleidos API Search

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.

From the secret to the records. Only a hardened build mixes in the device secret.PIN orpassphrasePBKDF2-SHA256Salt andwork factorHKDF binding(hardened)Device secret(hardened)KEK, wipedafter unlockVerifier,constant timeVault key,in RAMuntil lockWrappedvault keyRecord keys(AES, MAC)Vault recordsAES-256-CBC+ HMACDiagram
From the secret to the records. Only a hardened build mixes in the device secret.

What does what

Function Algorithm For
VaultCrypto::deriveKey() PBKDF2-SHA256 The secret to the KEK
VaultCrypto::encrypt(), VaultCrypto::decrypt() AES-256-CBC with PKCS#7 padding Records and files
VaultCrypto::hmacSha256() HMAC-SHA256 Tags, the keys' derivation, HKDF
VaultCrypto::constantTimeEqual() A compare that takes the same time whatever it finds A verifier or a tag
VaultCrypto::generateRandom() HMAC-DRBG, seeded from the hardware generator Salts, the vault key, tokens, generated passwords
VaultCrypto::secureWipe() 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.

See also
Vault Storage, Keys, Metadata & Rotation, Random Numbers

Files

file src/crypto/admin_crypto_task.h
Services-core (Core 0) crypto worker for the admin portal's heavy KDF.
file src/crypto/crypto_selftest.h
On-device known-answer self-test for the crypto primitives.
file src/crypto/device_secret.h
Binds the vault's key-encryption key to the chip, on the hardened build.
file src/crypto/export_envelope.h
Passphrase-wrapped export envelope: encrypt vault exports at rest.
file src/crypto/kdf_engine.h
The engines a PBKDF2 derivation can finish on, and their names.
file src/crypto/password_generator.h
Cryptographically random password generator (hardware RNG).
file src/crypto/pbkdf2_engine_chain.h
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/crypto/sha256_soft.h
Self-contained software SHA-256 for the PBKDF2 inner loop.
file src/crypto/vault_crypto.h
Vault cryptographic primitives: AES-256-CBC and PBKDF2-SHA256.
file src/crypto/vault_crypto_kdf.cpp
The PBKDF2 back-ends and the VaultCrypto::deriveKey* entry points (part of vault_crypto.h).

Classes

struct kleidos::crypto::selftest::VectorResult
One known-answer test result row. More about kleidos::crypto::selftest::VectorResult
class kleidos::crypto::PepperStore
Persistence port for the NVS-pepper backend (host-testable seam). More about kleidos::crypto::PepperStore
class kleidos::crypto::DeviceSecret
Resolve the device-binding secret for this build/chip. More about kleidos::crypto::DeviceSecret
struct kleidos::crypto::ByteSpan
Non-owning view over a contiguous byte buffer (may be empty: len 0). More about kleidos::crypto::ByteSpan
class kleidos::crypto::ExportEnvelopeWriter
Streaming producer of a passphrase-encrypted export envelope. More about kleidos::crypto::ExportEnvelopeWriter
class kleidos::crypto::ExportEnvelopeReader
Streaming reader for the chunked envelope: verify-before-decrypt, one chunk at a time. More about kleidos::crypto::ExportEnvelopeReader
class kleidos::PasswordGenerator
Stateless random-password generator backed by the hardware RNG. More about kleidos::PasswordGenerator
struct kleidos::crypto::pbkdf2::ChainFault
What a chain run reported. Any flag means the output is not used. More about kleidos::crypto::pbkdf2::ChainFault
struct kleidos::crypto::pbkdf2::LadderState
What the ladder keeps across derivations. More about kleidos::crypto::pbkdf2::LadderState
struct kleidos::crypto::Sha256Ctx
Incremental software SHA-256 state (trivially copyable). More about kleidos::crypto::Sha256Ctx
struct kleidos::VaultAesContext
Opaque AES key-schedule handle for the context-reuse API (PSA backend). More about kleidos::VaultAesContext
class kleidos::VaultCrypto
Stateless collection of the vault's cryptographic primitives. More about kleidos::VaultCrypto
class kleidos::AesCbcEncryptStream
Streaming AES-256-CBC encryptor with PKCS#7 padding. More about kleidos::AesCbcEncryptStream
class kleidos::AesCbcDecryptStream
Streaming AES-256-CBC decryptor with PKCS#7 removal. More about kleidos::AesCbcDecryptStream
class kleidos::HmacSha256Stream
Streaming HMAC-SHA256 with a sign finish and a constant-time verify finish. More about kleidos::HmacSha256Stream

Typedefs

usingkleidos::crypto::AdminCryptoJob
Unit of work marshaled onto the admin-crypto worker.
usingkleidos::crypto::BindFaultFn
usingkleidos::crypto::EnvelopeSink
Destination for envelope bytes as they are produced.
usingkleidos::crypto::pbkdf2::Words
One SHA-256 state or half block, as words.
usingkleidos::crypto::pbkdf2::ResumeChainFn
A chain instantiation, as the driver calls it (an IRAM wrapper on the device).
usingkleidos::crypto::pbkdf2::SliceHook
Called between two slices of a chain: feeds the watchdog of the running task.
usingkleidos::crypto::pbkdf2::RungFn

Enumerations

enum class kleidos::crypto::DeviceSecretBackend : uint8_t { kleidos::crypto::DeviceSecretBackend::None , kleidos::crypto::DeviceSecretBackend::EFuseHmac , kleidos::crypto::DeviceSecretBackend::NvsPepper }
Backend that supplies the device-binding secret. More about kleidos::crypto::DeviceSecretBackend
enum class kleidos::crypto::PepperLoad : uint8_t { kleidos::crypto::PepperLoad::Loaded , kleidos::crypto::PepperLoad::Absent , kleidos::crypto::PepperLoad::Failed }
enum class kleidos::crypto::PepperMint : uint8_t { kleidos::crypto::PepperMint::Refuse , kleidos::crypto::PepperMint::AtProvision }
Whether a computation of the device secret may mint the pepper. More about kleidos::crypto::PepperMint
enum class kleidos::crypto::KdfEngine : uint8_t { kleidos::crypto::KdfEngine::Software , kleidos::crypto::KdfEngine::PortLoop , kleidos::crypto::KdfEngine::LeanResume , kleidos::crypto::KdfEngine::Restart }
The engine a PBKDF2-HMAC-SHA256 derivation finished on. More about kleidos::crypto::KdfEngine
enum class kleidos::PassCharSet : uint8_t { kleidos::PassCharSet::LOWER, kleidos::PassCharSet::UPPER, kleidos::PassCharSet::DIGITS, kleidos::PassCharSet::SYMBOLS, kleidos::PassCharSet::ALL }
Character classes selectable when generating a password (bit mask). More about kleidos::PassCharSet

Functions

boolkleidos::crypto::beginAdminCryptoWorker (kleidos::platform::rtos::Core core=kleidos::platform::rtos::Core::ProCpu, kleidos::platform::rtos::Priority priority=kleidos::platform::rtos::kMinAppPriority)
Spawn the admin-crypto worker task. Idempotent — repeated calls return true without re-spawning.
voidkleidos::crypto::shutdownAdminCryptoWorker ()
Stop the worker and free its queue once it has left.
boolkleidos::crypto::runOnAdminCryptoWorker (AdminCryptoJob job, void *ctx)
Run job on the worker and block the caller until it returns, then propagate the job's success flag.
boolkleidos::crypto::selftest::run (VectorResult *results, size_t cap)
Run every known-answer vector through the production primitives.
boolkleidos::crypto::selftest::runAndReport ()
Run the self-test and print a structured pass/fail report to serial.
boolkleidos::crypto::bindKek (const uint8_t *vaultSalt, size_t vaultSaltLen, uint8_t *kek, size_t kekLen, PepperMint mint)
Mix the device secret into the KEK, the PBKDF2 output (RFC 5869 HKDF-SHA256).
voidkleidos::crypto::setBindFaultForTest (BindFaultFn fault)
Host tests only: run fault on every bindKek, ahead of the backend (which is the identity on the host).
voidkleidos::crypto::setPepperStoreForTest (PepperStore *store)
Host tests only: run the classic hardened build's pepper backend over store.
boolkleidos::crypto::hkdfSha256 (ByteSpan salt, ByteSpan ikm, ByteSpan info, uint8_t *out, size_t outLen)
RFC 5869 HKDF-SHA256 over ikm, keyed by salt, with info.
constexpr size_tkleidos::crypto::exportEnvelopeMaxBytes (size_t plainBytes)
boolkleidos::crypto::wrapExport (const uint8_t *plain, size_t plainLen, const char *passphrase, size_t passLen, std::string &out)
Wrap plaintext in a passphrase-encrypted export envelope.
boolkleidos::crypto::unwrapExport (const uint8_t *env, size_t envLen, const char *passphrase, size_t passLen, std::vector< uint8_t > &out)
Unwrap and decrypt a passphrase-encrypted export envelope.
constexpr const char *kleidos::crypto::kdfEngineName (KdfEngine engine)
The name the unlock trace and diagnostics print for engine.
constexpr size_tkleidos::passgenAcceptBound (size_t poolLen)
The bytes a pool of poolLen characters keeps: those below the largest multiple of poolLen that fits in a byte.
template<size_t... I>
voidkleidos::crypto::pbkdf2::xorWords (uint32_t *acc, const uint32_t *u, std::index_sequence< I... >)
XOR the eight words of u into acc, unrolled.
template<typename Regs, bool KeepTail>
ChainFaultkleidos::crypto::pbkdf2::resumeChain (const uint32_t *ipadState, const uint32_t *opadState, const uint32_t *tail, uint32_t *u, uint32_t *acc, uint32_t more)
PBKDF2's U(i) chain on an engine that loads a midstate.
template<typename Engine, ResumeChainFn Chain>
boolkleidos::crypto::pbkdf2::deriveOnResumeEngine (const uint8_t *pwd, size_t pwdLen, const uint8_t *salt, size_t saltLen, uint32_t iterations, uint8_t *out, size_t outLen, uint32_t sliceIterations, SliceHook onSlice)
PBKDF2-HMAC-SHA256 (RFC 8018 section 5.2) with the chain on a midstate-loading engine.
template<RungFn Rung>
boolkleidos::crypto::pbkdf2::passesSelfTest ()
Whether Rung returns kSelfTestKey.
template<RungFn Lean, RungFn Port, RungFn Soft>
boolkleidos::crypto::pbkdf2::deriveOnLadder (LadderState &state, const uint8_t *pwd, size_t pwdLen, const uint8_t *salt, size_t saltLen, uint32_t iterations, uint8_t *out, size_t outLen)
PBKDF2-HMAC-SHA256 down a ladder of engines: Lean, then Port, then Soft.
template<RungFn Lean, RungFn Port, RungFn Soft>
boolkleidos::crypto::pbkdf2::deriveOffRung (LadderState &state, KdfEngine avoid, const uint8_t *pwd, size_t pwdLen, const uint8_t *salt, size_t saltLen, uint32_t iterations, uint8_t *out, size_t outLen, KdfEngine &used)
PBKDF2-HMAC-SHA256 on a rung other than avoid: the second derivation a mint compares its key with.
voidkleidos::crypto::sha256Init (Sha256Ctx &ctx)
Reset a context to the SHA-256 initial hash value.
voidkleidos::crypto::sha256Update (Sha256Ctx &ctx, const uint8_t *data, size_t len)
Absorb len bytes of data into ctx.
voidkleidos::crypto::sha256Finish (Sha256Ctx &ctx, uint8_t *out)
Finalize ctx and write the digest.
KLEIDOS_IRAM_ATTR voidkleidos::crypto::sha256Transform (const uint32_t *stateIn, const uint32_t *blockWords, uint32_t *stateOut)
One raw SHA-256 compression: stateOut = compress(stateIn, block).

Variables

constexpr size_tkleidos::crypto::selftest::kVectorCount
constexpr size_tkleidos::crypto::kDeviceSecretSize
Size of the device-binding secret and the HKDF output, in bytes.
constexpr std::array< uint8_t, 4 >kleidos::crypto::kExportMagic
Envelope magic marker ("KEXP", Kleidos EXPort). Not NUL-terminated on disk.
constexpr uint8_tkleidos::crypto::kExportEnvelopeVersion
Envelope format version byte.
constexpr size_tkleidos::crypto::kExportSaltSize
PBKDF2 salt size for the export KDF, in bytes.
constexpr uint32_tkleidos::crypto::kExportKdfIterations
Export PBKDF2-SHA256 iteration count.
constexpr uint32_tkleidos::crypto::kExportKdfIterationsMin
Lowest iteration count the reader accepts in an envelope header.
constexpr uint32_tkleidos::crypto::kExportKdfIterationsMax
Highest iteration count the reader accepts in an envelope header.
constexpr size_tkleidos::crypto::kMinExportPassphraseLen
Minimum export passphrase length (bytes).
constexpr size_tkleidos::crypto::kExportHeaderLen
constexpr size_tkleidos::crypto::kExportChunkPlainBytes
constexpr size_tkleidos::crypto::kExportChunkHeaderLen
Chunk framing: ciphertext length (4 bytes, little-endian) + flags (1 byte).
constexpr uint8_tkleidos::crypto::kExportChunkFinal
Flag bit marking the last chunk. A stream that ends without it is truncated.
constexpr size_tkleidos::crypto::kExportChunkCipherMax
constexpr size_tkleidos::crypto::kExportChunkOverhead
Bytes a chunk adds beyond its ciphertext: its framing and its tag.
constexpr size_tkleidos::crypto::kExportEnvelopeOverhead
constexpr size_tkleidos::crypto::pbkdf2::kWords
Words in a SHA-256 state, and in each half of a message block.
constexpr uint32_tkleidos::crypto::pbkdf2::kSliceIterations
constexpr Wordskleidos::crypto::pbkdf2::kEngineTail
constexpr const char *kleidos::crypto::pbkdf2::kSelfTestPassword
The self-test's password: RFC 7914 section 11's second input.
constexpr const char *kleidos::crypto::pbkdf2::kSelfTestSalt
The self-test's salt.
constexpr uint32_tkleidos::crypto::pbkdf2::kSelfTestIterations
The self-test's count: fourteen chain iterations over its two output blocks.
constexpr std::array< uint8_t, 64 >kleidos::crypto::pbkdf2::kSelfTestKey
constexpr size_tkleidos::crypto::kSha256DigestSize
SHA-256 digest size in bytes (FIPS 180-4).
constexpr size_tkleidos::crypto::kSha256BlockSize
SHA-256 compression block size in bytes (FIPS 180-4).
constexpr size_tkleidos::crypto::kSha256StateWords
SHA-256 state size in 32-bit words (FIPS 180-4).
constexpr size_tkleidos::crypto::kSha256BlockWords
SHA-256 compression block size in 32-bit words (FIPS 180-4).

Back to the top

Typedef Documentation

AdminCryptoJob #

using kleidos::crypto::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::function) keeps the request allocation-free.

Parameters
NameDirectionMeaning
ctxin, outCaller-owned context: inputs plus output buffers.
Return values
ValueMeaning
trueJob succeeded.
falseJob failed.

BindFaultFn #

using kleidos::crypto::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 #

using kleidos::crypto::EnvelopeSink

Destination for envelope bytes as they are produced.

Parameters
NameDirectionMeaning
datainBytes to take.
leninByte count.
userinOpaque cookie handed to the writer.
Return values
ValueMeaning
trueTaken.
falseThe sink failed; the writer aborts.

RungFn #

using kleidos::crypto::pbkdf2::RungFn

One rung of the ladder: a whole PBKDF2-HMAC-SHA256 derivation; false on a refusal or a fault, with the output wiped.

Back to the top

Enumeration Type Documentation

DeviceSecretBackend #

enum class kleidos::crypto::DeviceSecretBackend : uint8_t

Backend that supplies the device-binding secret.

Enumerator
None 

No binding (open builds / no capability) — identity mix.

EFuseHmac 

ESP32-S3 HMAC peripheral over an eFuse key (hardened build).

NvsPepper 

Random per-device pepper persisted in NVS (hardened build).

KdfEngine #

enum class kleidos::crypto::KdfEngine : uint8_t

The engine a PBKDF2-HMAC-SHA256 derivation finished on.

Enumerator
Software 

The in-house software core (classic ESP32, the host, the last rung).

PortLoop 

The ESP32-S3 engine through ESP-IDF's port calls, all 16 text words per block.

LeanResume 

The ESP32-S3 engine in the lean register loop (eight text words per block).

Restart 

The classic ESP32 engine, restarted per HMAC.

PassCharSet #

enum class kleidos::PassCharSet : uint8_t

Character classes selectable when generating a password (bit mask).

Enumerator
LOWER 

Lowercase letters a–z.

UPPER 

Uppercase letters A–Z.

DIGITS 

Decimal digits 0–9.

SYMBOLS 

ASCII punctuation symbols.

ALL 

All classes above combined.

PepperLoad #

enum class kleidos::crypto::PepperLoad : uint8_t

Outcome of a PepperStore::load, with "never minted" kept apart from "could not be read".

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::Absent — a store that answered, and answered that nothing is there — may authorize minting, and only at a provision (PepperMint::AtProvision). PepperLoad::Failed says the store could not answer, which is a fact about this moment, not about the device.

Enumerator
Loaded 

A pepper was present and copied out.

Absent 

No pepper is stored; this device has never provisioned one.

Failed 

The read failed; whether a pepper exists is unknown.

PepperMint #

enum class kleidos::crypto::PepperMint : uint8_t

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.

Enumerator
Refuse 

An absent pepper fails the computation; nothing is written.

AtProvision 

An absent pepper is minted and stored (a fresh vault only).

Back to the top

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
NameDirectionMeaning
coreinTarget core for the worker (default PRO_CPU).
priorityinApplication priority for the worker (default the lowest).
Return values
ValueMeaning
trueWorker spawned, or already running (idempotent).
falseWorker 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() #

bool kleidos::crypto::bindKek(const uint8_t * vaultSalt, size_t vaultSaltLen, uint8_t * kek, size_t kekLen, PepperMint mint)

Mix the device secret into the KEK, the PBKDF2 output (RFC 5869 HKDF-SHA256).

When binding is disabled (DeviceSecretBackend::None) 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::mintKekHalf), which catches a fault that does not repeat.

Parameters
NameDirectionMeaning
vaultSaltinPer-vault KDF salt (selects the eFuse-HMAC secret).
vaultSaltLeninLength of vaultSalt in bytes.
kekin, outKEK (the PBKDF2 output) in; bound KEK out.
kekLeninLength of kek in bytes (expects 32).
mintinPepperMint::AtProvision only for the derivation of a fresh vault's first KEK.
Return values
ValueMeaning
truekek holds the (possibly unbound) KEK to use.
falseA binding backend error occurred, or the pepper is absent and may not be minted; kek was wiped.
Warning
SECURITY: wipe kek after use; never log it.

deriveOffRung() #

template<RungFn Lean, RungFn Port, RungFn Soft>
bool kleidos::crypto::pbkdf2::deriveOffRung(LadderState & state, KdfEngine avoid, const uint8_t * pwd, size_t pwdLen, const uint8_t * salt, size_t saltLen, uint32_t iterations, uint8_t * out, size_t outLen, KdfEngine & used)

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::leanRefused or LadderState::last: a proof neither refuses a rung for the boot nor counts as the boot's derivation; it counts in LadderState::proofs.

Template Parameters
NameMeaning
LeanThe production engine.
PortThe fallback engine.
SoftThe software core.
Parameters
NameDirectionMeaning
statein, outWhat the ladder keeps across derivations.
avoidinThe engine the derivation under proof finished on.
pwdinPassword bytes.
pwdLeninLength of pwd.
saltinSalt bytes.
saltLeninLength of salt.
iterationsinPBKDF2 count; zero is refused before any rung runs.
outoutReceives outLen bytes.
outLeninBytes to derive.
usedoutThe engine the proof finished on.
Return values
ValueMeaning
trueout holds the key.
falseA zero count, or the software core refused.

deriveOnLadder() #

template<RungFn Lean, RungFn Port, RungFn Soft>
bool kleidos::crypto::pbkdf2::deriveOnLadder(LadderState & state, const uint8_t * pwd, size_t pwdLen, const uint8_t * salt, size_t saltLen, uint32_t iterations, uint8_t * out, size_t outLen)

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::fallbacks.

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
NameMeaning
LeanThe production engine.
PortThe fallback engine.
SoftThe software core.
Parameters
NameDirectionMeaning
statein, outWhat the ladder keeps across derivations.
pwdinPassword bytes.
pwdLeninLength of pwd.
saltinSalt bytes.
saltLeninLength of salt.
iterationsinPBKDF2 count; zero is refused before any rung runs.
outoutReceives outLen bytes.
outLeninBytes to derive.
Return values
ValueMeaning
trueout holds what the rung that finished derived.
falseA zero count, or the software core refused (it does not for a non-zero count).

deriveOnResumeEngine() #

template<typename Engine, ResumeChainFn Chain>
bool kleidos::crypto::pbkdf2::deriveOnResumeEngine(const uint8_t * pwd, size_t pwdLen, const uint8_t * salt, size_t saltLen, uint32_t iterations, uint8_t * out, size_t outLen, uint32_t sliceIterations, SliceHook onSlice)

PBKDF2-HMAC-SHA256 (RFC 8018 section 5.2) with the chain on a midstate-loading engine.

Template Parameters
NameMeaning
EngineThe engine's lifecycle: static bool acquire(), static void release(), static bool firstBlockState( const uint8_t* block, uint32_t* stateOut ), static void scrub().
ChainThe chain instantiation (resumeChain over the engine's registers, or its IRAM wrapper).
Parameters
NameDirectionMeaning
pwdinPassword bytes (nullptr when pwdLen is 0).
pwdLeninLength of pwd.
saltinSalt bytes (nullptr when saltLen is 0).
saltLeninLength of salt.
iterationsinPBKDF2 count, at least 1.
outoutReceives outLen bytes; wiped on any failure.
outLeninBytes to derive.
sliceIterationsinIterations per chain call (kSliceIterations).
onSliceinCalled after each slice; nullptr for none.
Return values
ValueMeaning
trueout holds the key, and no fault was seen.
falseA zero count or slice, an engine that would not start, or a fault.

exportEnvelopeMaxBytes() #

size_t kleidos::crypto::exportEnvelopeMaxBytes(size_t plainBytes)
constexpr

Largest envelope plainBytes bytes of plaintext can produce: one chunk per full plaintext chunk plus the final one that carries the padding.

Parameters
NameDirectionMeaning
plainBytesinPlaintext the envelope will carry.
Returns
The envelope's largest possible size in bytes.

hkdfSha256() #

bool kleidos::crypto::hkdfSha256(ByteSpan salt, ByteSpan ikm, ByteSpan info, uint8_t * out, size_t outLen)

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::hmacSha256 — the single PSA-native backend shared by device and host — so native tests match firmware byte-for-byte.

Parameters
NameDirectionMeaning
saltinSalt (HKDF-Extract key); may be empty.
ikminInput key material.
infoinContext/application info; may be empty.
outoutOutput keying material buffer.
outLeninBytes requested (<= 255 * 32).
Return values
ValueMeaning
trueout holds outLen derived bytes.
falseA primitive failed or outLen is out of range.

kdfEngineName() #

const char * kleidos::crypto::kdfEngineName(KdfEngine engine)
constexpr

The name the unlock trace and diagnostics print for engine.

Parameters
NameDirectionMeaning
engineinAn engine.
Returns
software, port, lean or restart; ? outside the table.

< An engine.

< Its printed name.

passesSelfTest() #

template<RungFn Rung>
bool kleidos::crypto::pbkdf2::passesSelfTest()

Whether Rung returns kSelfTestKey.

Template Parameters
NameMeaning
RungThe rung to check.
Returns
True for all 64 bytes of it.

passgenAcceptBound() #

size_t kleidos::passgenAcceptBound(size_t poolLen)
constexpr

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
NameDirectionMeaning
poolLeninCharacters in the pool, 1 to ::kPassgenByteValues.
Returns
The exclusive bound, a multiple of poolLen.

resumeChain() #

template<typename Regs, bool KeepTail>
ChainFault kleidos::crypto::pbkdf2::resumeChain(const uint32_t * ipadState, const uint32_t * opadState, const uint32_t * tail, uint32_t * u, uint32_t * acc, uint32_t more)
inline

PBKDF2's U(i) chain on an engine that loads a midstate.

Template Parameters
NameMeaning
RegsThe engine's register moves (loadState, writeLow, writeHigh, run, readState, readHigh).
KeepTailWrite text words 8 to 15 once per call and check them at its end (true), or before every compression (false).
Parameters
NameDirectionMeaning
ipadStateinEngine state after the key XOR ipad block.
opadStateinEngine state after the key XOR opad block.
tailinText words 8 to 15 (kEngineTail).
uin, outU(k) on entry, U(k + more) on return.
accin, outThe running XOR of every U.
moreinIterations to run; fewer run after an overrun.
Returns
The faults seen.

run() #

bool kleidos::crypto::selftest::run(VectorResult * results, size_t cap)

Run every known-answer vector through the production primitives.

Parameters
NameDirectionMeaning
resultsoutArray receiving kVectorCount rows (caller-owned).
capinCapacity of results in elements.
Return values
ValueMeaning
trueEvery vector matched its expected output byte-for-byte.
falseAt least one vector mismatched, or cap was too small.

runAndReport() #

bool kleidos::crypto::selftest::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
ValueMeaning
trueAll vectors passed.
falseOne or more vectors failed.

runOnAdminCryptoWorker() #

bool kleidos::crypto::runOnAdminCryptoWorker(AdminCryptoJob job, void * ctx)

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
NameDirectionMeaning
jobinWork to execute (must not be nullptr).
ctxin, outCaller-owned context passed verbatim to job.
Return values
ValueMeaning
truejob reported success.
falsejob reported failure, or job was nullptr.
See also
beginAdminCryptoWorker

setBindFaultForTest() #

void kleidos::crypto::setBindFaultForTest(BindFaultFn fault)

Host tests only: run fault on every bindKek, ahead of the backend (which is the identity on the host).

Parameters
NameDirectionMeaning
faultinThe fault, or nullptr to clear it; setting it restarts the index at zero.

setPepperStoreForTest() #

void kleidos::crypto::setPepperStoreForTest(PepperStore * store)

Host tests only: run the classic hardened build's pepper backend over store.

With a store set, DeviceSecret::activeBackend answers DeviceSecretBackend::NvsPepper, DeviceSecret::compute goes through DeviceSecret::computePepper on store with the caller's mint, and DeviceSecret::pepperAbsent asks 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
NameDirectionMeaning
storeinThe store (not owned; it outlives its use), or nullptr for the host's own backend, DeviceSecretBackend::None.

sha256Finish() #

void kleidos::crypto::sha256Finish(Sha256Ctx & ctx, uint8_t * out)

Finalize ctx and write the digest.

Parameters
NameDirectionMeaning
ctxin, outActive context (left consumed; re-init before reuse).
outoutReceives ::kSha256DigestSize bytes.

sha256Init() #

void kleidos::crypto::sha256Init(Sha256Ctx & ctx)

Reset a context to the SHA-256 initial hash value.

Parameters
NameDirectionMeaning
ctxoutContext to initialize.

sha256Transform() #

void kleidos::crypto::sha256Transform(const uint32_t * stateIn, const uint32_t * blockWords, uint32_t * stateOut)

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
NameDirectionMeaning
stateInin8-word input chaining state H0..H7.
blockWordsin16 message words (big-endian-loaded).
stateOutoutReceives the 8-word output state; may alias stateIn.
Warning
SECURITY: inputs/outputs are key-derived in PBKDF2 use; callers wipe their buffers with mbedtls_platform_zeroize() after the loop.

sha256Update() #

void kleidos::crypto::sha256Update(Sha256Ctx & ctx, const uint8_t * data, size_t len)

Absorb len bytes of data into ctx.

Parameters
NameDirectionMeaning
ctxin, outActive context.
datainInput bytes (may be nullptr only when len is 0).
leninNumber of bytes to absorb.

shutdownAdminCryptoWorker() #

void kleidos::crypto::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::end(), which is itself on the deep-sleep teardown path) so no idle worker task survives into deep sleep.

See also
beginAdminCryptoWorker

unwrapExport() #

bool kleidos::crypto::unwrapExport(const uint8_t * env, size_t envLen, const char * passphrase, size_t passLen, std::vector< uint8_t > & out)

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
NameDirectionMeaning
envinEnvelope bytes.
envLeninLength of env in bytes.
passphraseinExport passphrase bytes (need not be NUL-terminated).
passLeninLength of passphrase in bytes (must be > 0).
outoutReceives the recovered plaintext; cleared on any failure.
Return values
ValueMeaning
trueAuthentication passed and out holds the plaintext.
falseMalformed envelope, wrong passphrase, tampering, or a backend failure; out is empty.
Warning
SECURITY: the caller owns wiping passphrase and, once consumed, the recovered plaintext in out. Derived keys and scratch are wiped internally.

wrapExport() #

bool kleidos::crypto::wrapExport(const uint8_t * plain, size_t plainLen, const char * passphrase, size_t passLen, std::string & out)

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
NameDirectionMeaning
plaininPlaintext bytes to protect (may be empty when plainLen is 0).
plainLeninLength of plain in bytes.
passphraseinExport passphrase bytes (need not be NUL-terminated).
passLeninLength of passphrase in bytes (must be > 0).
outoutReceives the serialized envelope; cleared on entry and on any failure.
Return values
ValueMeaning
trueout holds a complete envelope.
falseInvalid arguments or a backend failure; out is empty.
Warning
SECURITY: the caller owns wiping passphrase. Derived keys and intermediate buffers are wiped internally before return.

xorWords() #

template<size_t... I>
void kleidos::crypto::pbkdf2::xorWords(uint32_t * acc, const uint32_t * u, std::index_sequence< I... >)
inline

XOR the eight words of u into acc, unrolled.

Template Parameters
NameMeaning
IThe words, 0 to 7.
Parameters
NameDirectionMeaning
accin, outThe running XOR.
uinThe U just computed.

Back to the top

Variable Documentation

kEngineTail #

Words kleidos::crypto::pbkdf2::kEngineTail
inlineconstexpr

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 #

size_t kleidos::crypto::kExportChunkCipherMax
inlineconstexpr

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 #

size_t kleidos::crypto::kExportChunkPlainBytes
inlineconstexpr

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 #

size_t kleidos::crypto::kExportEnvelopeOverhead
inlineconstexpr

Smallest possible envelope: the header and one final chunk's overhead (its ciphertext is at least the padding block).

kExportHeaderLen #

size_t kleidos::crypto::kExportHeaderLen
inlineconstexpr

Authenticated header: magic(4) + ver(1) + kdfIter(4) + salt(16) + iv(16). The chunks start here.

kExportKdfIterations #

uint32_t kleidos::crypto::kExportKdfIterations
inlineconstexpr

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).

kExportKdfIterationsMax #

uint32_t kleidos::crypto::kExportKdfIterationsMax
inlineconstexpr

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 ::kExportKdfIterations, and the margin lets a later release raise the writer's count without a reader of this one refusing its files. The count is read before any tag can fail, so this is the most a damaged or hostile file can make the owner wait: about 5.8 s on an ESP32-S3 and 48 s on an ESP32 at their per-iteration costs.

kExportKdfIterationsMin #

uint32_t kleidos::crypto::kExportKdfIterationsMin
inlineconstexpr

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 #

size_t kleidos::crypto::kMinExportPassphraseLen
inlineconstexpr

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 #

std::array<uint8_t, 64> kleidos::crypto::pbkdf2::kSelfTestKey
inlineconstexpr

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 #

uint32_t kleidos::crypto::pbkdf2::kSliceIterations
inlineconstexpr

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 #

size_t kleidos::crypto::selftest::kVectorCount
inlineconstexpr

Number of rows reported by run(): one per primitive plus the vault encrypt/decrypt envelope round-trip. The suite's own table is checked against this with a static_assert, so a row added without touching this constant fails the build instead of being dropped from every caller's array.

Back to the top