Skip to content
Systems programming for what’s next.
— Vex

Crypto Namespace ​

The Crypto namespace provides portable semantic cryptographic micro-helpers. The compiler selects a target instruction only when the target capability is proven; otherwise it emits the constant-flow portable lowering.

No import needed. Crypto.* is a builtin namespace available everywhere.

These are building blocks, not full algorithms. For complete crypto implementations (AES-256-GCM, SHA-256, ChaCha20, etc.), see the crypto standard library package.

Fixed-block contract ​

vex
let state: [u8; 16] = [0; 16]
let key: [u8; 16] = getRoundKey()
let encrypted = Crypto.aesEncRound(state, key)

AES round operations currently accept exactly one [u8;16] state and one [u8;16] round key. They do not implicitly map over slices, tensors, [u8;64], or nested arrays. Multi-block algorithms expose parallelism by scheduling multiple exact block operations; aggregate AES-round types require a separate semantic contract and are not inferred from storage shape.

Quick Example ​

This complete program computes the standard CRC-32C check value for the ASCII bytes 123456789:

vex
fn crc32c<const N: usize>(data: &[u8; N]): u32 {
    let! crc: u32 = 0xffffffff;
    let! i: usize = 0;
    while i < N {
        crc = Crypto.crc32c(crc, data[i]);
        i = i + 1;
    }
    return crc ^ 0xffffffff;
}

fn main(): i32 {
    let input: [u8; 9] = [49, 50, 51, 52, 53, 54, 55, 56, 57];
    if crc32c(&input) != (0xe3069283 as u32) { return 1; }
    $println("CRC-32C: PASS");
    return 0;
}

Expected output is CRC-32C: PASS, exit status 0. CRC detects accidental corruption; it is not a message-authentication code.

AES Round Operations ​

Single AES round instructions — the core building block of AES-128/192/256.

FunctionSignatureDescription
Crypto.aesEncRound(state, key)([u8;16], [u8;16]) → [u8;16]SubBytes → ShiftRows → MixColumns → AddRoundKey
Crypto.aesDecRound(state, key)([u8;16], [u8;16]) → [u8;16]Inverse AES round
Crypto.aesEncLast(state, key)([u8;16], [u8;16]) → [u8;16]Final round (no MixColumns)
Crypto.aesDecLast(state, key)([u8;16], [u8;16]) → [u8;16]Final inverse round

Platform Mapping ​

Vex Functionx86 (AES-NI)ARM (Crypto Ext.)
aesEncRoundAESENCAESE + AESMC
aesDecRoundAESDECAESD + AESIMC
aesEncLastAESENCLASTAESE
aesDecLastAESDECLASTAESD

The exact lowering is target-dependent. Inspect emitted assembly and benchmark the complete construction; instruction latency alone is not an algorithm-level performance guarantee.

Usage: AES-256 Encrypt Block ​

This algorithm fragment assumes a correctly expanded 15-round-key schedule and an xorBlocks helper performing bytewise XOR. It is one block-cipher operation, not authenticated encryption or a full key schedule. Use a checked AEAD facade for application records.

vex
fn aes256EncryptHW(block: [u8;16], roundKeys: &[[u8;16]; 15]): [u8;16] {
    // XOR initial round key
    let! state = xorBlocks(block, roundKeys[0]);

    // Rounds 1-13
    let! r = 1;
    while r <= 13 {
        state = Crypto.aesEncRound(state, roundKeys[r]);
        r = r + 1;
    }

    // Final round (no MixColumns)
    state = Crypto.aesEncLast(state, roundKeys[14]);
    return state;
}

SHA-256 Hardware Acceleration ​

These operations have target-independent SHA-256 semantics. The compiler selects native instructions when the exact target proves them and otherwise emits the portable fixed-flow implementation.

FunctionSignatureDescription
Crypto.sha256Rounds4(abcd, efgh, wk)([u32;4], [u32;4], [u32;4]) → [u32;8]Four rounds; returns the complete A..H state
Crypto.sha256Schedule4(w0, w1, w2, w3)([u32;4], [u32;4], [u32;4], [u32;4]) → [u32;4]Produces the next four schedule words
Crypto.sha256H(cdgh, abef, wk)([u32;4], [u32;4], [u32;4]) → [u32;4]Low-level SHA-NI two-round contract
Crypto.sha256Msg0(msg0, msg1)([u32;4], [u32;4]) → [u32;4]Low-level SHA256MSG1 stage
Crypto.sha256Msg1(msg, prev)([u32;4], [u32;4]) → [u32;4]Low-level SHA256MSG2 stage

Platform Mapping ​

Vex FunctionAArch64 with SHA2x86 with SHA-NIPortable fallback
sha256Rounds4SHA256H + SHA256H2fixed-flow loweringfixed-flow lowering
sha256Schedule4SHA256SU0 + SHA256SU1fixed-flow loweringfixed-flow lowering
sha256Hfixed-flow loweringSHA256RNDS2fixed-flow lowering
sha256Msg0fixed-flow loweringSHA256MSG1fixed-flow lowering
sha256Msg1fixed-flow loweringSHA256MSG2fixed-flow lowering

crypto uses the complete-state four-round API so the source remains identical across targets. Architecture selection is a compiler/backend responsibility.

Carry-Less Multiply ​

64×64→128 bit polynomial multiplication — essential for GCM (GHASH) and CRC computations.

FunctionSignatureDescription
Crypto.clmul(a, b)(u64, u64) → [u64;2]Carry-less multiply, result = [lo, hi]

Platform Mapping ​

x86ARM
PCLMULQDQPMULL

The standard-library GHASH implementation uses this operation with Karatsuba multiplication, reflected register state and four-block aggregation. Targets without PCLMUL/PMULL use the portable constant-flow lowering.

vex
// 64×64 carry-less product; a complete GHASH step also needs field reduction.
let result = Crypto.clmul(a, b);
let lo = result[0];  // Lower 64 bits
let hi = result[1];  // Upper 64 bits

CRC-32 and CRC-32C ​

Crypto.crc32 implements the reflected IEEE polynomial used by Gzip, while Crypto.crc32c implements Castagnoli CRC used by networking and storage. Both operations accept an exact unsigned chunk width, so one semantic source can consume 1, 2, 4 or 8 bytes per update without architecture-specific code.

FunctionSignatureDescription
Crypto.crc32(crc, chunk)(u32, u8|u16|u32|u64) → u32IEEE CRC update
Crypto.crc32c(crc, chunk)(u32, u8|u16|u32|u64) → u32Castagnoli CRC update

Platform Mapping ​

Operationx86AArch64
IEEE CRC-32portable slicing fallbackCRC32B/H/W/X
CRC-32CSSE4.2 where the exact width is legal; otherwise portableCRC32CB/CH/CW/CX

The compiler owns target selection and the constant table fallback. Vex source sees only polynomial and chunk-width semantics. The compress package builds its dependency-broken large-buffer CRC pipeline from this operation.

For chunked input, preserve the running CRC state between chunks and apply the initial/final XOR exactly once for the complete message. Multi-byte chunks must represent the intended byte order; use the package's checked hash/codec APIs when you do not already own a proven raw-buffer range. The byte-at-a-time program above avoids alignment and tail-read assumptions.

Secure Random ​

Cryptographically secure random number generation using the operating system's CSPRNG capability.

FunctionSignatureDescription
Crypto.secureRand()→ u6464-bit CSPRNG value

Platform Mapping ​

PlatformEntropy boundary
LinuxDirect getrandom syscall with EINTR/short-read handling; no libc dependency
macOSSupported libSystem arc4random_buf API
WindowsBCryptGenRandom with the system-preferred provider

The operation fails closed if the OS cannot supply all 64 bits. It never falls back to time, PID, pointer addresses, or a predictable PRNG.

For non-cryptographic randomness (games, simulations), use Math.random() for non-security-sensitive work, or use an explicit rand.Rng stream when replay and distribution control matter.

vex
fn generateKey(): [u8; 32] {
    let! key: [u8; 32] = [0; 32];
    let! wordIndex: usize = 0;
    while wordIndex < 4 {
        let word = Crypto.secureRand();
        let! byteIndex: usize = 0;
        while byteIndex < 8 {
            key[wordIndex * 8 + byteIndex] =
                ((word >> (byteIndex * 8)) & 255 as u64) as u8;
            byteIndex = byteIndex + 1;
        }
        wordIndex = wordIndex + 1;
    }
    return key;
}

This fills the array without an aligned u64 store into byte storage. The caller still owns secure storage, distribution and destruction of the key. Nonce allocation is a separate policy; see AEAD nonce lifecycle.

Hardware Support ​

Instruction-oriented Crypto.* functions select a legal hardware lowering when target features prove support. Operations with a software implementation, such as CRC-32C, remain portable. Crypto.secureRand() uses the OS CSPRNG and does not depend on CPU RDRAND.

Featurex86ARMApple Silicon
AES roundsAES-NI (2010+)ARMv8 CryptoYes M1+
SHA-256 complete-state helpersportable fixed-flow pathSHA2 when enabled for the targetSHA2 when enabled for the target
SHA-NI-style helpersSHA-NI when enabled for the targetportable fixed-flow pathportable fixed-flow path
CLMULPCLMULQDQ (2010+)PMULL (ARMv8)Yes M1+
CRC-32/32CCRC-32C via SSE4.2; IEEE portableCRC32 extensionYes M1+
Secure RNGOS CSPRNGOS CSPRNGOS CSPRNG

Cryptographic algorithms still need portable implementations or explicit target-feature handling where no legal hardware lowering exists.

Next Steps ​

Released under the MIT License.