Encryption (crypto AEAD & Symmetric)
AES-GCM
Authenticated encryption with checked AES-128-GCM and AES-256-GCM facades. The AES-128 facade requires a 16-byte key and the AES-256 facade a 32-byte key; both require a 12-byte nonce and use a 16-byte authentication tag. Backend selection depends on the target and build.
Nonce and key lifecycle
Never repeat a nonce for two encryption operations under the same key, including across processes, machines, crashes, and restores. A valid 12-byte length is not proof of uniqueness. The caller owns this policy: seal checks lengths but does not maintain a nonce registry. Reusing a GCM key/nonce pair can compromise confidentiality and authentication; see RFC 5116 sections 3.1 and 5.1.1.
One deterministic allocation design for a 12-byte nonce is a 4-byte writer identifier followed by an 8-byte counter in a fixed byte order. It requires a durable coordinator, not just an in-memory counter:
- Provision a secret key from an operating-system CSPRNG or a managed key service. Keep it out of records and logs.
Crypto.secureRand()is the target entropy primitive used by Vex's non-cryptographicrandseeding;Rngoutput must not be used for keys or security-sensitive randomness. Check the target implementation and deployment before relying on it. - For each key, assign writer identifiers uniquely across all writers that might ever encrypt under it. Persist those assignments and never reassign an identifier with an old counter state. A randomly chosen writer identifier alone is not a uniqueness guarantee.
- Before encryption, atomically reserve a counter or a disjoint range in durable storage for that key and writer. The durable reservation must commit before any nonce in the range is used. Never return unused values to the pool: burn them after a crash, failed seal, or uncertain outcome. Independent workers must not share a counter without atomic allocation.
- After a restart, resume only from durable allocation state. Treat restored snapshots, cloned machines, storage rollback, failed commits, split brain, and lost allocation state as unsafe: stop encryption until a new key or provably disjoint allocation is installed. Rotate the key before counter exhaustion and before the algorithm's applicable per-key invocation and data limits; a 64-bit counter is not permission to use a key for 2^64 messages.
- Store or transmit the nonce, ciphertext and tag, key identifier, and the exact AAD bytes or an unambiguous way to reconstruct them. Nonces and AAD are not secret; AAD is authenticated but not encrypted. Encode multiple AAD fields unambiguously, for example with fixed widths or length prefixes. The combined
sealresult contains ciphertext followed by the tag; the nonce is managed separately. - On
openfailure, reject the whole record and do not use or expose plaintext. Authentication alone does not prevent replay: add a protocol-specific replay policy if needed. Handle failure without disclosing secrets.
Random 96-bit nonces have collision probability, so randomness is not the deterministic uniqueness policy above. A random-nonce design needs a documented per-key invocation limit and collision-risk analysis across all writers; consult the applicable NIST GCM recommendation.
API fixture (test keys only)
The following complete fixture uses two different fixed test nonces to demonstrate the API and rejection of a modified tag. Fixed keys and fixed nonces must not be copied into an application. It is not an implementation or test of durable allocation, crash recovery, or multi-worker coordination. For a source checkout, put a crypto symlink next to this file pointing to lib/std/crypto, then run vex run aead-example.vx with the tested compiler and library sources.
import { Aes128Gcm, CryptoErrorKind } from "./crypto/src/lib.vx";
fn bytes<const N: usize>(value: &[u8; N]): Span<u8> {
return unsafe { Span.of<u8>(value as Ptr<u8>, N) };
}
fn main(): i32 {
// Test vectors only: real keys and nonces must follow the lifecycle policy above.
let key = [0x19u8; 16];
let nonce1 = [0x27u8; 12];
let nonce2 = [0x28u8; 12];
let aad = [0x35u8; 9];
let plaintext = [0x43u8; 47];
let! first = match Aes128Gcm.seal(bytes(&key), bytes(&nonce1), bytes(&aad), bytes(&plaintext)) {
Ok(value) => value,
Err(_) => { $panic("seal failed"); },
};
let second = match Aes128Gcm.seal(bytes(&key), bytes(&nonce2), bytes(&aad), bytes(&plaintext)) {
Ok(value) => value,
Err(_) => { $panic("seal failed"); },
};
let opened = match Aes128Gcm.open(bytes(&key), bytes(&nonce2), bytes(&aad), second.asSpan()) {
Ok(value) => value,
Err(_) => { $panic("open failed"); },
};
if opened.len() != plaintext.len() { $panic("wrong plaintext length"); }
let! i = 0 as usize;
while i < plaintext.len() {
if opened[i] != plaintext[i] { $panic("wrong plaintext"); }
i = i + 1 as usize;
}
$println(opened.len());
first[first.len() - 1 as usize] = first[first.len() - 1 as usize] ^ 1;
match Aes128Gcm.open(bytes(&key), bytes(&nonce1), bytes(&aad), first.asSpan()) {
Ok(_) => { $panic("tampered tag accepted"); },
Err(failure) => {
match failure.kind {
CryptoErrorKind.AuthenticationFailed => { $println("authentication failed"); },
_ => { $panic("unexpected error"); },
}
},
};
return 0;
}Expected program output is 47 and then authentication failed. A local macOS arm64 development build ran this fixture against the checkout's crypto source; this single run is not a cryptographic audit or evidence for other targets. See rand for the distinction between simulation PRNGs and cryptographic randomness.
ChaCha20-Poly1305
Portable AEAD cipher with checked combined and detached APIs.
import { ChaCha20Poly1305 } from "crypto";
let sealed = ChaCha20Poly1305.seal(key, nonce, aad, plaintext);
let opened = match sealed {
Ok(value) => ChaCha20Poly1305.open(key, nonce, aad, value.asSpan()),
Err(failure) => Err(failure),
};Raw AES
Low-level AES block cipher for custom constructions.
import { aes128EncryptBlock, aes256EncryptBlock } from "crypto";These RawBuf block functions are low-level building blocks. Prefer the checked facades for application data. AEAD open verifies the complete tag before decrypting and clears reusable output on authentication failure.
Raw CTR callers must also respect the complete counter space. Vex validates it before writing: GCM/J0 CTR reserves the pre-incremented counter correctly, and the initial-counter variant accepts a final u32::MAX block once but never a wrapping second block. Raw byte offsets are target-width usize; public protocol lengths remain explicit u64 values until they pass this validation.
Implementation Details
| File | Purpose |
|---|---|
aes.vx | AES key expansion, target-independent round semantics and CTR |
aes_gcm.vx | GCM with reflected four-block GHASH aggregation |
chacha20.vx | ChaCha20 quarter-round stream cipher |
poly1305.vx | Poly1305 MAC with 130-bit accumulator |
aead.vx | Unified AEAD interface combining cipher + MAC |