Skip to content

Cryptography

Digests, message authentication, key derivation, and the one comparison a program cannot write itself.

crypto is a module — import crypto — with four digests, HMAC over the same four, two key-derivation functions, and one constant-time comparison.

The algorithm is in the name

There is no crypto.digest(algorithm, data), and there will not be. A selector a program can compute is how JWT alg confusion works: a document says which algorithm verified it, and the verifier believes the document. Here, changing SHA-256 to SHA-1 is a source edit that shows up in a diff, and never a value that arrived over a wire.

import crypto

fn main() void {
    body := "the payload".to_bytes()
    println(crypto.sha256(body).encode_hex())
}

sha256, sha384, sha512 and sha1 each answer a bytes of the digest’s own width — 32, 48, 64 and 20. sha1 is present because HMAC-SHA-1 is still specified by protocols in use, not because a new program should choose it.

A program that already holds a buffer appends the digest to it instead: crypto.sha256_to(body, &mut out) grows out by 32 bytes and allocates no list for the digest. Every digest has its _to form (sha384_to, sha512_to, sha1_to), and so does every hmac_* (hmac_sha256_to(key, message, &mut out)).

Printing one is bytes.encode_hex(), which is a guest body in stdlib/bytes.at rather than a host call: a nibble is six wasm instructions and a boundary crossing is not.

A message that arrives in pieces

import crypto

fn digest_of_parts(parts []string) bytes ! crypto.Error {
    d := crypto.sha256_stream()?
    for part in parts {
        d.write(part.to_bytes())?
    }
    return d.finish()?
}

fn main() void {
    match digest_of_parts(["a", "b", "c"]) {
        Ok(sum) => println(sum.encode_hex())
        Err(e) => println("no digest")
    }
}

finish spends the digest: a later write or finish answers InvalidHandle rather than a second, different answer. That is why write returns a Result at all — a chunk that went nowhere means the message is shorter than the caller believes, and a digest over a short message is a wrong answer nothing downstream can notice.

A Digest releases its slot when it is dropped, so a program that opens one and returns early leaks nothing.

Prefer the verifier to the signer

Every MAC has a verifier beside it, and the verifier is the one to reach for.

import crypto

fn webhook_is_genuine(secret []byte, body []byte, signature []byte) bool {
    return crypto.hmac_sha256_verify(secret, body, signature)
}

fn main() void {
    secret := "s3cret".to_bytes()
    body := "{}".to_bytes()
    tag := crypto.hmac_sha256(secret, body)
    println("${webhook_is_genuine(secret, body, tag)}")
}

The reason is not convenience. hmac_sha256 followed by == is a timing oracle: == on bytes returns at the first differing byte, and so does every other comparison a program can write. There is no way to state constant time in this language — there is no wasm opcode meaning the optimizer may not observe this, get is bounds-checked, and __compare_to_impl early-exits. Not handing the right answer back is what makes the wrong comparison unspellable.

hmac_sha256_verify answers false for a wrong tag, a tag of the wrong length, an empty tag, and an unsupported algorithm. A failure is never a match.

The streaming form has the same pair: Digest.verify(tag) answers a bool and the digest never crosses back.

import crypto

fn body_matches(body []byte, expected []byte) bool ! crypto.Error {
    d := crypto.sha256_stream()?
    d.write(body)?
    return d.verify(expected)?
}

fn main() void {
    body := "payload".to_bytes()
    match body_matches(body, crypto.sha256(body)) {
        Ok(same) => println("${same}")
        Err(e) => println("no answer")
    }
}

Deriving keys

hkdf_* is RFC 5869 extract-and-expand, for turning one shared secret into several independent keys. An empty salt is the RFC’s absent salt — §2.2 makes that the all-zero string of the hash’s width — so there is one spelling for “no salt” rather than two that differ.

import crypto

fn session_keys(shared []byte, transcript []byte) bytes ! crypto.Error {
    mut no_salt: []byte
    return crypto.hkdf_sha256(shared, no_salt, transcript, 64)?
}

fn main() void {
    match session_keys("shared".to_bytes(), "hello".to_bytes()) {
        Ok(keys) => println("${keys.len()} bytes of key material")
        Err(e) => println("no keys")
    }
}

pbkdf2_* is RFC 8018, for turning a password into a key. It is the one call on this page that suspends: the rounds run on a thread that is allowed to be slow, because a few hundred milliseconds on the reactor thread would stop every other task in the store.

import crypto

// OWASP's 2023 floor for PBKDF2-HMAC-SHA-256. Anything below six figures is a
// number chosen by nobody.
const ROUNDS: int = 600000

fn stored_form(password string, salt []byte) bytes ! crypto.Error {
    return crypto.pbkdf2_sha256(password.to_bytes(), salt, ROUNDS, 32)?
}

fn main() void {
    match stored_form("hunter2", "per-user-salt".to_bytes()) {
        Ok(k) => println("${k.len()} bytes stored")
        Err(e) => println("no key")
    }
}

The iteration count is the caller’s because the right number changes with hardware, and a library that chose one would be wrong within a year.

The comparison of last resort

For a tag this module did not compute — a signature out of a wire format, a token out of a database — crypto.equal compares in time that does not depend on where two runs differ.

import crypto

fn token_matches(presented string, stored string) bool {
    return crypto.equal(presented.to_bytes(), stored.to_bytes())
}

fn main() void {
    println("${token_matches("abc", "abc")} ${token_matches("abc", "abd")}")
}

Two runs of different lengths answer false at once, and that is deliberate: a length is not a secret in any protocol this serves, and hiding it would mean hashing both sides in order to compare them.

Randomness

Entropy is not in this module — it is module random, random.bytes(n) and random.below(bound), so a program needing a random number does not have to import a cryptography module for one; List.shuffled needs no import at all. Both draw from the same source: one host declaration, std.next_u64, over an OS-seeded thread-local CSPRNG.

import crypto
import random

fn salted(password string) bytes ! crypto.Error {
    salt := random.bytes(16)
    return crypto.pbkdf2_sha256(password.to_bytes(), salt, 600000, 32)?
}

fn main() void {
    println("${random.bytes(16).len()} bytes of salt")
    println("${random.below(6.to_usize()) < 6.to_usize()}")
}

random.below(bound) is unbiased — it rejects and redraws rather than taking a modulo, which would favour the low residues whenever bound does not divide 2^64; a bound of zero has no answer and stops the program with a trap. random.bytes(n) answers n bytes, and none when n is not positive. Bulk entropy is a guest body over the same word source rather than a declaration of its own: a 32-byte token is four crossings at about 1.6 ns each, which is less than the block the answer is written into.

Errors

import crypto

fn describe(e crypto.Error) string {
    match e {
        Unsupported => return "no such algorithm here"
        InvalidHandle => return "the digest was already spent"
        InvalidArgument => return "a length or a round count the host will not take"
        TooManyDigests => return "too many digests open at once"
        Other => return "failed"
    }
}

fn main() void {
    mut nothing: []byte
    match crypto.hkdf_sha256(nothing, nothing, nothing, 0) {
        Ok(k) => println("derived")
        Err(e) => println(describe(e))
    }
}

The one-shot digests and MACs answer a bytes rather than a Result. The only way the host refuses one is a span the program does not own, which a []byte cannot be, so there is no failure to handle; if one is ever answered the program stops, and never goes on with an empty digest. A digest in progress, HKDF and PBKDF2 answer a Result, because a caller can cause their failures: a digest that has answered, a length past the bound, no iterations.

What is not here

Encryption. Nothing in this tree encrypts yet, and an AEAD surface with no caller would be a set of shapes nobody has run. When it lands, seal will draw its own nonce and write it as the first twelve bytes of the answer — there is no nonce argument in either direction, because a reused nonce is the one mistake AES-GCM does not survive.

A way to read a key back. A key crosses as []byte per call and nothing here answers one.

X.509, JWT, TOTP, Argon2. All formats built over this surface rather than primitives. What a program usually wants after mutual TLS is the verified peer identity of a connection the host already authenticated — which is Conn.peer_names() on the TCP page, not a second certificate parser.

Hex and base64. Those are bytes.encode_hex() and its neighbours on the Bytes page. They are guest bodies for the same reason these are hosts: a host exists where there is a machine instruction no sequence of wasm instructions reaches, and there is no base64 instruction.

Availability

Everything on this page compiles and runs against atoll_hosts::all().

Surface Status
sha256 / sha384 / sha512 / sha1 answers
*_stream → write / finish / verify / close answers
sha*_to and hmac_*_to, which append to a buffer answers
hmac_* and hmac_*_verify answers
hkdf_sha256 / hkdf_sha384 / hkdf_sha512 answers
pbkdf2_* answers, and suspends
equal answers
AEAD, signatures, X.509 not declared

Type to search…

↑↓ navigate↵ selectEsc close