Skip to reference

std.x.crypto.chacha20

wolf-std d58f9e1 · toolchain pin verified against wolf 0.2.41 (0261597). Source signatures and documentation; execution support is stated in each module.

All modules · Plain text · Stability tier: x

Module

std.x.crypto.chacha20 — ChaCha20, Poly1305 and the AEAD_CHACHA20_POLY1305 construction (RFC 8439). Stability tier: x — the D53 crypto ladder's second rung (campaign stdc-crypto, sprint sc17). This is the cipher that needs no tables: add-rotate-xor on public data-flow, no S-boxes, no secret-indexed loads. These are source- level obligations, not a fixed-time certification of generated code or runtime operations. Backend and runtime review at exact pins is separate. AES-GCM (that rung owes a D-question on hardware intrinsics vs bitslicing vs c28-verified masking; named in the sc17 contract, not smuggled here).

The nursery banner (D31). std.x.crypto.chacha20 is not std.crypto: its path, names and behaviour may change or vanish in one sprint; no other std module may depend on it (it may depend on the facade, and does: std.bytes for shared equality); its reason and graduation trigger live in std/x/README.md. Poly1305 lives IN this module rather than beside it because a nursery resident may not depend on another resident — the graduation move splits them.

Implemented from the RFC 8439 DOCUMENT, not ported. Every constant and every round below cites its section of RFC 8439 (June 2018), fetched into the planning repo's refs/specs/rfc8439.txt. The vectors (the RFC's complete set — §2.3.2, §2.4.2, §2.5.2, §2.6.2, §2.8.2, A.1–A.5 — plus the full Wycheproof chacha20_poly1305_test.json) catch transcription errors; the document is the authority.

**The ChaCha word currency is wrapping[u64], masked to 32 bits** (the sha2 discipline, chosen when F-0089 kept the narrowing int as wrapping[u32] off the native rung; that refusal CLOSED at the sc18 pin — s111 / wolf-lang#131 — and the respell is sha2's recorded follow-on, shared by this module, never a bump side-effect). Every value entering a round is 32-bit-clean and every sum or rotation is masked before it is stored. Unlike SHA-2, ChaCha20 is LITTLE-endian at state load and keystream serialization (§2.3) — the word32_le/push_word32_le helpers are this module's own, not sha2's big-endian pair.

**Poly1305 is CHECKED int arithmetic, all the way down** — the sc17 probe delta's finding. Five 26-bit limbs in 64-bit accumulators, carries spelled as literal shifts and masks (>> 26, & 67108863) on limbs the bound proof keeps non-negative, where they are the same numbers / and % were; the §2.5 clamp as masks; and the final conditional subtraction as an arithmetic select. Until sc84 the carries were //%, because a plain-int shift or mask cost the checked lane (F-0026); every lane runs them since wolf 0.2.31, and a default build compiled each //% to a hardware divide of the one-time key and the accumulator (wolf-std#151). The bound proof lives on absorb; because X3's checked arithmetic traps on any overflow, a violated bound would be a trap the vectors catch, not a silent wrap. No wrapping[T] appears anywhere in the MAC.

Lanes, measured at the sc18 pin (wolf 21b129e): ALL THREE run every body. The checked tier's F-0091 operator refusal that kept any path reaching the ChaCha core dark from sc17's first commit closed with s111 (wolf-lang#130) — "the next pin bump flips sha2 and this module in one motion", and it did: all 19 dark chacha20 rows flipped unsupported -> run at the bump, the full Wycheproof parts included (the checked tier's resource budgets that keep sha2's biggest files dark are not reached by 32-vector AEAD parts, measured at the bump). The sc17 nuance stands as history: the refusal was DYNAMIC — per executed path — which is why Poly1305's checked-int arithmetic was three-lane a sprint before the rest of the module.

**Byte sequences are List[byte] (sc35), AND THE INGESTION GUARD IS GONE.** The currency was List[int] with a documented 0..255 element contract (§11's interim, F-0035) and a require_byte that trapped assert on every element breaking it; D72/s135's byte and s136's byte-typed builtins (wolf-lang#231) moved that contract into the type, so the guard was unreachable code and is deleted. What it defended is unchanged: a List[byte] cannot carry a value a wrapping cast would silently key or digest. to_hex is this module's own hex rendering so its tests and doc examples import exactly one module (the sha2 precedent); std.hex.encode is the facade spelling.

Nonces are the CALLER's — seal/open take an explicit 96-bit nonce and this module provides NO random-nonce surface (no entropy story exists yet; the D-question lives with the rung that needs it). Reusing a nonce under one key forfeits both confidentiality and integrity (§4); seal's doc states the contract.

Error rows: exactly one, open's {tag} — a forged, modified or truncated box is the DATA's failure, so it raises (§2's rule). Everything else is total over its documented domain; key/nonce length misuse is a caller contract violation that traps assert (the sc16 spelling); a non-byte element is a TYPE error since sc35 and never reaches a trap.

Constant-time obligations (D53's retrofit clause). c28's compiler-enforced tier does not exist yet; until it does, every pub fn below carries a ct: line. The honest summary: the cipher and the MAC branch and index on PUBLIC quantities only (lengths, block counts, fixed offsets) — and the one recorded exception is RETIRED (sc35). The 0..255 ingestion guard compared every input element, key bytes included, and this header promised "it leaves with F-0035's real byte type". The type arrived and it left, so there is no value-dependent branch anywhere on the cipher or MAC path at source level. Generated instructions and runtime operations are separate review obligations, not certified here. The tag comparison delegates to bytes.is_equal_fixed_work; to_hex is NOT constant-time and says so.

No division (sc84, wolf-std#151). Neither the cipher nor the MAC divides: Poly1305's carries, clamp, limb seams and tag words are shifts and masks, and so are the stream's block positions. At wolf 0.2.39 the default build compiled 76 hardware divides into poly1305, absorb and push_tag_word, on the one-time key and the accumulator. cargo xtask codegen builds this module's default and release objects on the host target and fails on any integer division instruction in them, and runs the RFC 8439 rows in the release tier. It is not a timing measurement (no latency was measured on any CPU), it says nothing about the interpreters, and the compiler that makes the objects is not audited; a target the gate is not run on is not covered by it.

Types and traits

No public declarations in this section.

Functions and methods

block

fn · Source line 391

pub fn block(key: List[byte], counter: int, nonce: List[byte]) -> List[byte]

The ChaCha20 block function (RFC 8439 §2.3): 64 keystream bytes for one (key, counter, nonce) triple. Traps assert on a key that is not 32 bytes, a nonce that is not 12, or a counter outside 0..2^32-1; total otherwise (sc35: a non-byte element is a type error). ct: fixed source-level schedule — the rounds are add-rotate-xor on 32-bit words with literal rotation amounts; every branch is a fixed loop bound and every index is a fixed offset or a loop counter, so no branch and no memory address depends on a secret, and since sc35 there is no recorded exception left.

let key = "wolf sc17: a 32-byte chacha key!".bytes()
let nonce = "twelve bytes".bytes()
chacha20.block(key, 1, nonce).len == 64
chacha20.to_hex(chacha20.block(key, 1, nonce))[0..8] == "4f0949f3"

stream_xor

fn · Source line 414

pub fn stream_xor( key: List[byte], counter: int, nonce: List[byte], data: List[byte], ) -> List[byte]

The ChaCha20 stream cipher (RFC 8439 §2.4): XORs data with the keystream starting at block counter; its own inverse, so one function is both directions. Traps assert on the block-function contract violations, and on a message long enough that the 32-bit block counter would wrap — §2.4's note: the cipher is defined for at most 2^32 blocks from the starting counter (with counter 1 that is ~256 GiB, theoretical; the guard is one comparison). ct: as block — the per-byte XOR touches every element unconditionally, the keystream index is pos % 64 (public), and block boundaries depend on the LENGTH alone.

let key = "wolf sc17: a 32-byte chacha key!".bytes()
let nonce = "twelve bytes".bytes()
let ct = chacha20.stream_xor(key, 1, nonce, "attack at dawn".bytes())
chacha20.to_hex(ct) == "2e7d3d92e359096f5c4660bbeed3"
chacha20.to_hex(chacha20.stream_xor(key, 1, nonce, ct)) == "61747461636b206174206461776e"

poly1305

fn · Source line 543

pub fn poly1305(key: List[byte], msg: List[byte]) -> List[byte]

The Poly1305 one-time authenticator (RFC 8439 §2.5): a 16-byte tag over msg under a 32-byte one-time key (r || s). The r half is clamped with §2.5's exact mask 0x0ffffffc0ffffffc0ffffffc0fffffff — spelled byte-wise as arithmetic, and applied BEFORE the limb split, so no unclamped bit ever enters the schedule. Traps assert on a key that is not 32 bytes; total otherwise (sc35). THE KEY IS ONE-TIME (§2.5): authenticating two messages under one r,s pair forfeits the MAC; the AEAD below derives a fresh key per nonce. ct: the limb schedule is fixed and data-independent — every block runs the same adds, multiplies and shift-and-mask carries; block boundaries depend on the LENGTH alone; the final conditional subtraction of p is an arithmetic select, not a branch — with no recorded exception left since sc35.

let key = "wolf sc17: a 32-byte chacha key!".bytes()
let mac = chacha20.poly1305(key, "a message worth authenticating".bytes())
mac.len == 16
chacha20.to_hex(mac) == "79a8154cdb15d6e6de56665337a5908c"

poly_key

fn · Source line 698

pub fn poly_key(key: List[byte], nonce: List[byte]) -> List[byte]

The per-nonce Poly1305 key (RFC 8439 §2.6): the first 32 bytes of the ChaCha20 block at counter ZERO — which is why the AEAD's encryption starts at counter one. Traps assert on the ChaCha input contract; total otherwise. ct: as block.

let key = "wolf sc17: a 32-byte chacha key!".bytes()
chacha20.poly_key(key, "twelve bytes".bytes()).len == 32

seal

fn · Source line 761

pub fn seal( key: List[byte], nonce: List[byte], aad: List[byte], plaintext: List[byte], ) -> List[byte]

AEAD_CHACHA20_POLY1305 seal (RFC 8439 §2.8): encrypts plaintext under (key, nonce) with the ciphertext starting at block counter 1, authenticates aad and ciphertext per the §2.8 transcript under the §2.6 per-nonce Poly1305 key, and returns ciphertext || 16-byte tag as one sequence. Traps assert on the ChaCha input contract; total otherwise (sc35). THE NONCE IS THE CALLER'S CONTRACT: this module has no entropy surface and never generates one. A nonce must be UNIQUE per key — reuse hands an attacker the XOR of the plaintexts and the Poly1305 key (§4 of the RFC), which forfeits both confidentiality and integrity. Counters and LFSRs are both acceptable per the RFC; whatever the scheme, it is the caller's. ct: the composition of block, stream_xor and poly1305's obligations — public-length control flow only.

let key = "wolf sc17: a 32-byte chacha key!".bytes()
let nonce = "twelve bytes".bytes()
let boxed = chacha20.seal(key, nonce, "hdr".bytes(), "attack at dawn".bytes())
boxed.len == 30
chacha20.to_hex(boxed) == "2e7d3d92e359096f5c4660bbeed3c6e125ca300df002b2a92947a5deded4"

open

fn · Source line 804

pub fn open( key: List[byte], nonce: List[byte], aad: List[byte], boxed: List[byte], ) -> List[byte] ! {tag}

AEAD_CHACHA20_POLY1305 open (RFC 8439 §2.8): verifies the tag over the §2.8 transcript, and ONLY on success decrypts and returns the plaintext. A box that is too short to carry a tag, or whose tag does not match, raises tag — the DATA failed, not the caller (§2's rule) — and NO PLAINTEXT IS COMPUTED on that path: the error row is the entire result, so a forged box can never leak a byte. Traps assert only on the caller's own inputs (key/nonce lengths). ct: bytes.is_equal_fixed_work accumulates every tag-byte difference before the final test: no early exit at source level. Unequal public lengths are rejected structurally. Neither this fold nor the cipher's fixed-looking source certifies instruction latency, runtime behavior or constant time on any tier; inspect generated default/release code at the exact compiler/runtime pins separately. Vector tests establish outputs and rejection, not absence of timing or memory side channels.

let key = "wolf sc17: a 32-byte chacha key!".bytes()
let nonce = "twelve bytes".bytes()
let boxed = chacha20.seal(key, nonce, "hdr".bytes(), "attack at dawn".bytes())
let back = chacha20.open(key, nonce, "hdr".bytes(), boxed) else List[byte]()
chacha20.to_hex(back) == "61747461636b206174206461776e"
let short = chacha20.open(key, nonce, "hdr".bytes(), "not16".bytes()) else List[byte]()
short.len == 0

to_hex

fn · Source line 851

pub fn to_hex(b: List[byte]) -> str

b as lowercase hexadecimal, two digits per byte — this module's own rendering so its tests and examples import exactly one module (the sha2 precedent); std.hex.encode is the facade spelling. Total — the non-byte element it used to trap on is a type error since sc35. ct: NOT constant-time — the alphabet slice is indexed by each byte's VALUE, a secret-dependent memory index. Render public values with it; a constant-time encoder is c28-tier work.

chacha20.to_hex("abc".bytes()) == "616263"
chacha20.to_hex(List[byte]()) == ""

Constants

No public declarations in this section.

Errors and row tags

Tags named by public signatures: tag. Their conditions are documented on the functions that return them.

No public declarations in this section.