Introducing a new way to review your PRs.

Read the announcement

mratsim / constantine

Constantine: modular, high-performance, zero-dependency cryptography stack for verifiable computation, proof systems and blockchain protocols.

View on GitHub

19 documents · Updated Nov 13, 2026

docs / randomness-kdf-and-mac

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.

NeedFacilityMain result
Unpredictable bytesOperating-system CSPRNGRandom bytes for keys, nonces, salts, or challenges
Key separation and expansionHKDFA pseudorandom key and derived output keying material
Message authenticity and integrityHMAC or Poly1305A 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:

MACKey modelTag modelIntended role
HMAC over a supported cryptographic hashShared secret of suitable strengthHash-sized tag, with supported truncationGeneral keyed hashing and protocol authentication
Poly130532-byte unique, non-reused shared key16-byte tagFast 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:

  1. Initialize the context with suitable secret input.
  2. Feed message or keying input through the incremental interface.
  3. Finalize into caller-owned output.
  4. 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 info as 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

TriggerConsequenceGuard
The caller ignores a failed sysrand resultA buffer can contain unusable or incomplete random dataStop the protocol when the randomness request fails
A Poly1305 key is reusedAuthentication security can fail across messagesGenerate or derive a fresh 32-byte key per message
A weak password is passed directly to a hash or HKDFThe derived key remains exposed to fast guessingUse a password-hardening design outside this HKDF facility
Different protocol contexts use the same HKDF info valueKey separation can fail and outputs can be confusedGive each purpose a distinct context value
A short HMAC tag is accepted without a protocol limitGuessing an authentication tag becomes easierSet and enforce a tag length with adequate strength
A secret context is left unclearedKey or message state can remain in memoryClear the context after finalization

Key files

FileWhy to read it
constantine/csprngs/sysrand.nimDefines the cross-platform operating-system randomness contract and its failure behavior
include/…/sysrand.hShows the C-facing randomness entry point
constantine/kdf/kdf_hkdf.nimDefines HKDF extraction, expansion, context binding, and clearing
constantine/mac/mac_hmac.nimDefines the HMAC key, streaming, tag, and clearing behavior
constantine/mac/mac_poly1305.nimDefines the Poly1305 key-uniqueness contract and message lifecycle
tests/t_kdf_hkdf.nimDemonstrates standard HKDF extract-and-expand compatibility
tests/t_mac_hmac_sha256.nimDemonstrates HMAC compatibility and truncated-tag checks
tests/t_mac_poly1305.nimDemonstrates Poly1305 compatibility with a standard vector