Hashing and symmetric primitives
This area provides the byte-level cryptographic building blocks used by Constantine. It turns messages into fixed digests or field and curve values, derives keys from secret input, authenticates data, encrypts data with a stream cipher, and obtains fresh random bytes from the operating system. Higher-level signing and proof systems use these services as shared primitives.
Primitive roles
The primitives serve different security goals. A hash gives a digest, a message authentication code (MAC) proves that a party with a shared key created the message, a key derivation function (KDF) makes separate keys from secret input, and a stream cipher protects message content. Random bytes supply the unpredictable input needed by key and nonce generation.
| Primitive role | Main result | Typical use |
|---|---|---|
| Hash | Fixed-size digest | Data fingerprints and protocol input |
| Hash-to-field or hash-to-curve | Field elements or curve points | Pairing-based protocols |
| KDF | Pseudorandom output keying material | Session and sub-key generation |
| MAC | Authentication tag | Message integrity and origin checks |
| Stream cipher | Encrypted or decrypted bytes | Confidentiality |
| System random source | Unpredictable bytes | Keys, nonces, and random protocol values |
Shared data flow
The facilities form a layered path. Hashes provide the common digest interface, HMAC uses that interface for both MAC and HKDF, and hash-to-curve uses a hash to create values that can become curve points.
This diagram shows how raw message or secret input moves through the main services.
flowchart LR
R[System random bytes] --> K[Keys and nonces]
M[Message] --> H[Hash]
M --> A[Hash-to-field]
A --> C[Hash-to-curve point]
S[Secret input] --> KDF[HKDF]
H --> HMAC[HMAC]
KDF --> HMAC
K --> HMAC
K --> P[Poly1305]
K --> X[ChaCha20]
M --> HMAC
M --> P
M --> X
References: constantine/hashes.nim• L17-61 constantine/…/hash_to_curve.nim• L209-249 constantine/…/kdf_hkdf.nim• L14-20 constantine/…/mac_hmac.nim• L13-25 constantine/…/chacha20.nim• L13-24 constantine/…/sysrand.nim• L9-18
Hash functions
The hash service gives each supported hash a common context model. A caller can hash a complete message in one call or initialize a context, add message parts, finish into a fixed-size digest, and clear the context when secret data was used.
Supported hash families
The public CryptoHash concept defines the contract shared by the hash families. The current exports include SHA-256, Keccak-256, SHA3-256, and RIPEMD-160. Keccak-256 and SHA3-256 are distinct choices because they use different sponge delimiters even though they have the same digest size.
| Hash | Digest size | High-level distinction |
|---|---|---|
| SHA-256 | 32 bytes | SHA-2 hash used by many protocols |
| Keccak-256 | 32 bytes | Keccak sponge form used by Ethereum-style protocols |
| SHA3-256 | 32 bytes | SHA-3 standardized padding form |
| RIPEMD-160 | 20 bytes | Older hash used where a shorter digest is part of a protocol contract |
The generic hash entry point is defined in the fully qualified path constantine/hashes.nim. The individual algorithms expose the same lifecycle so callers can change the hash type when a protocol permits it. The tests compare the algorithms with known vectors and external results. They also check that chunked input gives the same result as one-pass input.
References: constantine/hashes.nim• L17-80 constantine/…/h_sha256.nim• L83-94 constantine/…/h_keccak.nim• L76-127 constantine/…/h_ripemd160.nim• L28-57 tests/t_hash_sha256_vs_openssl.nim• L20-85 tests/t_hash_keccak_sha3_vs_openssl.nim• L48-102 tests/t_hash_ripemd160_vs_openssl.nim• L23-89
Hash context use
The one-shot hash call is the normal choice for a complete message. The context form is useful when data arrives in parts or when a caller must avoid joining secret buffers. A finished context still holds internal state until it is cleared, so secret input needs a deliberate clear step.
Raw hashing is not a password KDF. Passwords and secret keys need a KDF such as HKDF so that the protocol can include salt and context information and request the required output length.
References: constantine/hashes.nim• L18-61 constantine/…/h_sha256.nim• L131-143 constantine/…/h_sha256.nim• L172-210 constantine/…/h_keccak.nim• L262-289 constantine/…/h_ripemd160.nim• L59-83
Hash-to-curve support
Hash-to-curve turns a message into a point in a selected elliptic-curve subgroup. It first expands the message into uniform bytes, maps those bytes into field elements, maps the elements to the curve, and clears the cofactor so the result is in the intended subgroup.
Field expansion
The hash-to-field layer follows the hash-to-curve message expansion model. It uses a domain separation tag (DST) to keep protocol domains distinct and accepts an optional augmentation that is prepended before hashing. Oversized DST values are reduced to a short tag before expansion.
The expansion produces enough uniform bytes for the requested field elements. Each element is interpreted from big-endian bytes and reduced into the selected base field or quadratic extension field. The security parameter k controls how much extra input is requested for the target security level.
References: constantine/…/h2c_hash_to_field.nim• L41-148 constantine/…/h2c_hash_to_field.nim• L166-239 tests/t_hash_to_field.nim• L17-40 tests/t_hash_to_field.nim• L146-181
Curve point mapping
The curve layer maps two field values into a point by using the mapping suite selected for the curve. BLS12-381 uses the SSWU path in the public dispatcher. BN254 Snarks uses the SVDW path. The final cofactor step makes the point suitable for subgroup-based protocols.
The public call accepts the hash type, security parameter, message, optional augmentation, and DST. It can return an affine, projective, or Jacobian point. The repository checks both official vectors and randomized points on the curve and in the correct subgroup.
For the focused explanation of field expansion, mapping suites, and subgroup rules, see Hash-to-curve and field.
References: constantine/…/hash_to_curve.nim• L212-249 constantine/…/hash_to_curve.nim• L251-323 constantine/…/zoo_hash_to_curve.nim• L9-33 tests/t_hash_to_curve.nim• L104-172 tests/t_hash_to_curve_random.nim• L32-58
Key derivation and message authentication
Key derivation and message authentication use keyed hashing to protect secret material and message boundaries. HKDF converts input keying material into pseudorandom keys. HMAC authenticates a message with a shared secret. Poly1305 provides a separate fixed-key MAC for protocols that use its tag format.
HKDF key derivation
HKDF follows RFC 5869 in two stages. Extract turns optional salt and input keying material into a fixed-size pseudorandom key (PRK). Expand uses the PRK, optional context information, and an optional appended value to produce output keying material (OKM) of the requested size.
The hash choice sets the PRK size and the size of each expansion chunk. Expansion is limited to 255 hash-sized chunks by the RFC. The context information should identify the protocol or key purpose so that outputs for different uses do not overlap.
For the focused explanation of HKDF, HMAC, Poly1305, and related random input, see Randomness, KDF, and MAC.
References: constantine/…/kdf_hkdf.nim• L14-20 constantine/…/kdf_hkdf.nim• L27-73 constantine/…/kdf_hkdf.nim• L75-190 constantine/…/kdf_hkdf.nim• L192-210 tests/t_kdf_hkdf.nim• L24-117
HMAC authentication
HMAC makes a tag from a message and a shared secret key. It supports incremental input and returns a tag with the selected hash size. A caller may use a left-truncated tag when the protocol defines one, but both sides must agree on the tag length.
HMAC needs a secret key that is random or derived from strong secret material. It authenticates data but does not hide it. Encryption and authentication therefore remain separate concerns unless a higher-level protocol combines them.
References: constantine/…/mac_hmac.nim• L13-25 constantine/…/mac_hmac.nim• L29-106 tests/t_mac_hmac_sha256.nim• L15-42 tests/t_mac_hmac_sha256.nim• L44-114
Poly1305 authentication
Poly1305 creates a 16-byte tag from a message and a unique 32-byte one-time key. It supports incremental input and keeps a partial message tail until it can finish the tag. The key must not be reused for different messages.
Poly1305 is a MAC, not an encryption service. A protocol that needs confidentiality must pair it with an approved encryption design and must define how keys, nonces, and tags are managed.
References: constantine/…/mac_poly1305.nim• L201-229 constantine/…/mac_poly1305.nim• L281-348 tests/t_mac_poly1305.nim• L13-31
Stream cipher
ChaCha20 provides confidentiality by XORing data with a pseudorandom byte stream. The operation is symmetric: applying it again with the same key, counter, and nonce restores the original data. It changes the caller’s buffer in place and returns the next block counter.
ChaCha20 inputs
The IETF ChaCha20 interface uses a 32-byte key, a 12-byte nonce, and a counter. The nonce must be unique for each use of a key. The counter must advance as encryption consumes blocks so that the same key and nonce do not generate the same stream block twice.
ChaCha20 by itself does not detect changes to the ciphertext. A higher-level design must add authentication, such as a suitable authenticated-encryption construction or a separately specified MAC arrangement. The repository tests the cipher against the RFC 8439 vector and checks that the same operation decrypts the result.
References: constantine/…/chacha20.nim• L13-24 constantine/…/chacha20.nim• L91-131 tests/t_cipher_chacha20.nim• L13-43
Random-number generation
The random service fills caller-provided memory with cryptographically secure random bytes from the host operating system. It presents one sysrand operation across supported platforms and returns a Boolean success result instead of silently returning weak or incomplete data.
Operating-system random source
On Linux, the service reads from the system getrandom facility and handles partial reads, interruption, and temporary lack of entropy. On Windows and Apple platforms, it calls the platform secure random API. Unsupported operating systems fail at build time rather than appearing to provide a random source.
The service is a source of fresh random bytes. It is not a general-purpose seeded pseudo-random generator, and it does not replace protocol-specific nonce rules. Callers must check the success result before using the output as a key, nonce, or secret value.
For the focused explanation of system randomness and its use with key derivation and MAC services, see Randomness, KDF, and MAC.
References: constantine/csprngs.nim• L9-10 constantine/…/sysrand.nim• L9-18 constantine/…/sysrand.nim• L72-118 constantine/…/sysrand.nim• L120-165 tests/t_csprngs.nim• L9-27
Change checklist
When these files or sections are changed, remember to consider these:
- A change to the
CryptoHashcontract can affect direct hashing, HMAC, HKDF, and hash-to-field expansion at the same time. - A change to a hash digest size or block size must stay aligned with fixed-size HMAC keys, HKDF PRKs, and hash-to-curve expansion limits.
- A change to hash-to-curve DST or augmentation handling must be checked against protocol test vectors and every caller that defines a suite domain.
- A change to the curve dispatcher or its supported groups must keep the matching curve constants and subgroup clearing rules aligned.
- A change to ChaCha20 key, nonce, or counter handling must preserve the caller’s uniqueness contract and the returned counter meaning.
- A change to the system random source must preserve the failure result across each supported operating system and the public library bindings.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| Reuse of a ChaCha20 nonce with one key | The same stream can expose relationships between plaintexts | Generate a unique nonce per key and advance the counter |
| Use of ChaCha20 without authentication | An attacker can alter ciphertext without detection | Use a defined authenticated-encryption or MAC design |
| Reuse of a Poly1305 one-time key | Message tags can reveal the authentication key | Allocate a fresh 32-byte key for every message |
| Use of raw SHA-256 for a password or secret-key derivation | The result lacks KDF salt and context separation | Use HKDF or a protocol-specific password KDF |
| Wrong hash-to-curve DST or augmentation | The point differs from the protocol suite or another domain | Treat both values as part of the suite contract and verify vectors |
Ignoring a false sysrand result | A key or nonce may contain incomplete or invalid randomness | Stop the operation and report random-source failure |
Calling Keccak finish before update | The context does not follow the required absorb-to-squeeze transition | Call update, including for an empty message |
Key files
| File | Why to read it |
|---|---|
constantine/hashes.nim | Defines the common hash contract and one-shot digest entry points |
constantine/hashes/h_sha256.nim | Shows the SHA-256 public lifecycle and secret-buffer guidance |
constantine/hashes/h_keccak.nim | Shows the Keccak and SHA-3 variants and sponge lifecycle |
constantine/hash_to_curve/h2c_hash_to_field.nim | Explains message expansion, DST handling, and field output |
constantine/hash_to_curve/hash_to_curve.nim | Connects hash output to supported curve mappings and subgroup points |
constantine/kdf/kdf_hkdf.nim | Defines extract and expand key derivation |
constantine/mac/mac_hmac.nim | Defines hash-based message authentication |
constantine/mac/mac_poly1305.nim | Defines the one-time-key MAC service |
constantine/ciphers/chacha20.nim | Defines in-place stream encryption and counter behavior |
constantine/csprngs/sysrand.nim | Defines the operating-system random-byte contract |
bindings/lib_constantine.nim | Shows which core services are assembled into the library surface |
tests/t_hash_to_curve.nim | Shows validation against official hash-to-curve vectors |
tests/t_cipher_chacha20.nim | Shows the ChaCha20 interoperability check and round-trip behavior |