Randomness, KDFs, and MACs
Constantine provides small cryptographic building blocks for three related jobs: obtaining unpredictable bytes from the operating system, turning secret input into usable key material, and proving that a message came from a holder of a shared secret. These facilities support protocol code above the hashing and symmetric-primitives layer; they do not by themselves define a complete encryption or key-management protocol.
Cryptographic roles
The components separate three security needs that are easy to confuse. A cryptographically secure pseudo-random number generator (CSPRNG) supplies unpredictable values. A key-derivation function (KDF) gives protocol-specific keys from secret input. A message-authentication code (MAC) gives an authentication tag that a party with the same secret can check.
| Need | Facility | Main result |
|---|---|---|
| Unpredictable bytes | Operating-system CSPRNG | Random bytes for keys, nonces, salts, or challenges |
| Key separation and expansion | HKDF | A pseudorandom key and derived output keying material |
| Message authenticity and integrity | HMAC or Poly1305 | A tag for a message under a shared secret |
The hash-to-field and hash-to-curve flows use hashing to map input into mathematical groups. They solve a different problem from the randomness, KDF, and MAC facilities described here; see Hash to curve and field for that boundary.
Operating-system randomness
The system randomness interface fills a caller-provided buffer with cryptographically secure random data. It delegates to a platform source rather than building a user-space random stream, and it reports success or failure to the caller. The Nim API is sysrand; the C ABI is ctt_csprng_sysrand in include/…/sysrand.h.
The platform source is selected by the host operating system. Linux reads from getrandom and handles partial reads, interruption, and temporary lack of entropy. Windows and Apple platforms use their operating-system random APIs. Unsupported operating systems fail at configuration time instead of silently providing a weak source.
This flow shows how a request becomes random bytes and how the caller receives an explicit result.
flowchart LR
A[Protocol requests bytes] --> B[sysrand interface]
B --> C{Host operating system}
C --> D[Operating-system CSPRNG]
D --> E[Filled buffer]
D --> F[Failure result]
The output is suitable as secret input only when the caller checks the success result and protects the filled buffer. The interface does not decide how many bytes a protocol needs or how the bytes are used.
References: constantine/…/sysrand.nim• L9-18 constantine/…/sysrand.nim• L72-118 constantine/…/sysrand.nim• L120-165 include/…/sysrand.h• L9-19
Key derivation
HKDF is the repository’s HMAC-based key-derivation function. It converts secret input keying material into a fixed-size pseudorandom key, then expands that key into the amount of output keying material a protocol needs. An optional salt helps the extract step, while info carries context for key separation and domain separation.
The normal HKDF flow has two stages. The extract stage makes input of uneven quality or length into a fixed-size pseudorandom key. The expand stage derives one or more outputs from that key and context.
flowchart LR
I[Secret input keying material] --> X[HKDF extract]
S[Optional salt] --> X
X --> P[Pseudorandom key]
P --> E[HKDF expand]
C[Context information] --> E
E --> O[Output keying material]
The one-shot hkdf operation covers both stages. Separate extract and expand operations support protocols that reuse a pseudorandom key or need to append input without making an extra heap allocation. The expand output is bounded by the HKDF construction to 255 hash-output blocks. A context that holds secret material can be cleared after use.
HKDF is not a password-hardening scheme. It is intended for key extraction, key separation, and key expansion from suitable secret input. Password processing needs a password-specific KDF with a deliberate cost model, not raw hashing or an automatic assumption that HKDF makes a weak password strong.
References: constantine/…/kdf_hkdf.nim• L9-22 constantine/…/kdf_hkdf.nim• L24-73 constantine/…/kdf_hkdf.nim• L75-124 constantine/…/kdf_hkdf.nim• L126-210 tests/t_kdf_hkdf.nim• L24-58
Message authentication
A message-authentication code is a keyed digest. The sender computes a tag from a message and a shared secret. The receiver recomputes the tag with the same secret and accepts the message only when the tags match. A MAC provides message integrity and source authentication for parties that already share the key; it does not provide confidentiality, public verification, or non-repudiation.
Constantine exposes two MAC families with different construction goals:
| MAC | Key model | Tag model | Intended role |
|---|---|---|---|
| HMAC over a supported cryptographic hash | Shared secret of suitable strength | Hash-sized tag, with supported truncation | General keyed hashing and protocol authentication |
| Poly1305 | 32-byte unique, non-reused shared key | 16-byte tag | Fast one-time-key message authentication |
Both MACs support incremental message input and a one-shot operation. A context can be cleared after finalization when it contains sensitive key or message state.
References: constantine/…/mac_hmac.nim• L13-25 constantine/…/mac_hmac.nim• L29-40 constantine/…/mac_hmac.nim• L65-105 constantine/…/mac_poly1305.nim• L201-229 constantine/…/mac_poly1305.nim• L281-348
HMAC authentication
HMAC combines a shared secret with a cryptographic hash and produces a tag for the message. It accepts keys up to and beyond the hash block size by applying the HMAC key rules. The HMAC API supports streaming updates, so a caller can authenticate a message without holding the full message in one buffer.
HMAC tags can be truncated by retaining the leftmost output bytes. The implementation guidance calls for a tag of at least half the hash output and at least 80 bits. The protocol, not the primitive, must set the tag length and must compare tags under its own verification rules.
The HMAC implementation is checked against RFC 4231 vectors, including long keys and truncated tags. These checks establish compatibility with the standard construction; they do not choose safe keys or define a message format for a protocol.
References: constantine/…/mac_hmac.nim• L25-80 constantine/…/mac_hmac.nim• L82-105 tests/t_mac_hmac_sha256.nim• L15-42 tests/t_mac_hmac_sha256.nim• L44-114
Poly1305 authentication
Poly1305 authenticates messages with a 32-byte key that must not be reused across independent messages. It produces a 16-byte tag and supports messages supplied in pieces. The unique-key rule is part of the security contract; callers must obtain or derive a fresh key for each authenticated message through the surrounding protocol.
The implementation follows the standard Poly1305 construction and is checked against an RFC 8439 test vector. The finish operation does not clear its context automatically, so secret state requires an explicit clear step or use of the one-shot operation with memory clearing enabled.
References: constantine/…/mac_poly1305.nim• L148-158 constantine/…/mac_poly1305.nim• L201-229 constantine/…/mac_poly1305.nim• L281-348 tests/t_mac_poly1305.nim• L13-31
Secret-state lifecycle
Secret material can remain in a streaming context until the caller clears it. This matters for HKDF, HMAC, and Poly1305 because their contexts retain keying or message state while they process input.
When a protocol finishes with secret-derived state, its normal lifecycle is:
- Initialize the context with suitable secret input.
- Feed message or keying input through the incremental interface.
- Finalize into caller-owned output.
- Clear the context when the secret is no longer needed.
One-shot helpers reduce the lifetime of temporary state and can request memory clearing. They do not clear caller-owned input, output, or other copies held by the surrounding application.
References: constantine/…/kdf_hkdf.nim• L24 constantine/…/kdf_hkdf.nim• L107-108 constantine/…/kdf_hkdf.nim• L168-169 constantine/…/mac_hmac.nim• L82-86 constantine/…/mac_poly1305.nim• L281-288 constantine/…/mac_poly1305.nim• L314-339
Change checklist
When these files or sections are changed, remember to consider these:
- Changes to the operating-system randomness source must preserve the success-or-failure contract across the Nim API and the C header.
- Changes to HKDF hash selection or output sizing must preserve the fixed PRK size and the 255-block expand limit.
- Changes to HKDF context input must preserve
infoas protocol context so that separate uses do not derive the same key by accident. - Changes to HMAC tag handling must keep truncation rules aligned with the protocol that verifies the tag.
- Changes to Poly1305 use must preserve the unique, non-reused key contract for every authenticated message.
- Changes to context clearing must cover both streaming and one-shot paths when secret state is held.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
The caller ignores a failed sysrand result | A buffer can contain unusable or incomplete random data | Stop the protocol when the randomness request fails |
| A Poly1305 key is reused | Authentication security can fail across messages | Generate or derive a fresh 32-byte key per message |
| A weak password is passed directly to a hash or HKDF | The derived key remains exposed to fast guessing | Use a password-hardening design outside this HKDF facility |
Different protocol contexts use the same HKDF info value | Key separation can fail and outputs can be confused | Give each purpose a distinct context value |
| A short HMAC tag is accepted without a protocol limit | Guessing an authentication tag becomes easier | Set and enforce a tag length with adequate strength |
| A secret context is left uncleared | Key or message state can remain in memory | Clear the context after finalization |
Key files
| File | Why to read it |
|---|---|
constantine/csprngs/sysrand.nim | Defines the cross-platform operating-system randomness contract and its failure behavior |
| include/…/sysrand.h | Shows the C-facing randomness entry point |
constantine/kdf/kdf_hkdf.nim | Defines HKDF extraction, expansion, context binding, and clearing |
constantine/mac/mac_hmac.nim | Defines the HMAC key, streaming, tag, and clearing behavior |
constantine/mac/mac_poly1305.nim | Defines the Poly1305 key-uniqueness contract and message lifecycle |
tests/t_kdf_hkdf.nim | Demonstrates standard HKDF extract-and-expand compatibility |
tests/t_mac_hmac_sha256.nim | Demonstrates HMAC compatibility and truncated-tag checks |
tests/t_mac_poly1305.nim | Demonstrates Poly1305 compatibility with a standard vector |