Appearance
std/crypto
From the spec
This page is spec/std/crypto.md, the specification the compiler and the backends are written from. It is rebuilt from the spec with every deploy (how).
Hashes, HMAC, constant-time comparison, random bytes, UUID v7, signatures and JSON Web Tokens: what verifying a webhook (Stripe, GitHub, Slack), issuing or checking a token, or hashing a file needs. It is written in Weft (core/crates/weft-check/src/std/crypto.weft) over std/$crypto, the primitives: on the VM RustCrypto's crates (weft-runtime's crypto.rs), on the JS backend a synchronous SHA-1/SHA-2 and HMAC of its own (src/weft/crypto.ts) with the engine's crypto.getRandomValues. Signatures and keys are the server's: in the browser verify and sign (and the JWT algorithms that use them) panic with "isn't available in the browser". Passwords are std/auth's (argon2id), not this module's. User code (std/sandbox) may import it.
weft
import { hmac, timingSafeEqual, jwt } from "std/crypto"
import * as json from "std/json"
fn fromStripe(payload: string, header: string, secret: string): boolean {
let parts = header.split(",")
let t = (parts.find(p => p.startsWith("t=")) ?? "").slice(2)
let v1 = (parts.find(p => p.startsWith("v1=")) ?? "").slice(3)
return timingSafeEqual(hmac("sha256", secret, `${t}.${payload}`).toHex(), v1)
}
let token = try jwt.sign(try json.parse("{\"sub\":\"u1\"}"), "HS256", "secret", { expiresIn: 3600 })
let claims = try jwt.verify(token, "HS256", "secret")Text given where Bytes | string is taken is its UTF-8.
Hashes and HMAC
Hash | "sha1" | "sha256" | "sha384" | "sha512" |
hash(alg: Hash, input: Bytes | string): Bytes | the digest (FIPS 180-4) |
sha1(input), sha256(input), sha384(input), sha512(input): Bytes | the same, by name |
hmac(alg: Hash, key: Bytes | string, input: Bytes | string): Bytes | RFC 2104 |
timingSafeEqual(a: Bytes | string, b: Bytes | string): boolean | equal, in time that depends only on the lengths (different lengths: false). Compare signatures, tokens and secrets with it, never == |
b.toHex() and b.toBase64() (std.md, Bytes) and std/url's base64url write digests as text.
Random
randomBytes(n: number): Bytes:nbytes (0 to 65,536, else aRangeErrorpanic) from the system's secure generator. Effectful.uuidv7(): string: a version 7 UUID (RFC 9562), lowercase: the clock's milliseconds (the clockstd/time'snow()reads, which test hosts fix), then 74 random bits; UUIDs made later sort after. Effectful. The prelude'suuid()is version 4.
Signatures
Signing | "Ed25519" | "ES256" | "ES384" | "RS256" | "RS384" | "RS512": Ed25519; ECDSA on P-256 with SHA-256 and P-384 with SHA-384; RSA PKCS #1 v1.5 with SHA-256, -384, -512 |
verify(alg: Signing, publicKey: string, input: Bytes | string, signature: Bytes): boolean ! KeyError | whether signature is the key's over input. An ECDSA signature is raw r‖s (as JWTs and WebCrypto write it) or DER |
sign(alg: Signing, privateKey: string, input: Bytes | string): Bytes ! KeyError | the signature (ECDSA: raw r‖s; Ed25519 and RSA PKCS #1 v1.5 are deterministic) |
Keys are text: PEM (a public key as SPKI PUBLIC KEY, or PKCS #1 RSA PUBLIC KEY; a private key as PKCS #8 PRIVATE KEY, PKCS #1 RSA PRIVATE KEY or SEC1 EC PRIVATE KEY), or a JWK's JSON (ktyOKP with crv Ed25519, EC with crv P-256/P-384, RSA with n and e; a private one with d, not for RSA), as a JWKS endpoint gives them. A key that isn't one for alg (the wrong type or curve, a public key to sign, text that isn't a key) fails with KeyError { message }.
JWT
jwt (RFC 7519, the algorithms of RFC 7518) is a namespace:
JwtAlgorithm | "HS256" | "HS384" | "HS512" | "EdDSA" | "ES256" | "ES384" | "RS256" | "RS384" | "RS512"; never none |
jwt.sign(claims: json, alg: JwtAlgorithm, key: Bytes | string, options?: JwtSignOptions): string ! JwtError | KeyError | the compact token: header {"alg","typ":"JWT"} (and kid), the claims with iat (now, in seconds) and what options adds, each only where the claims don't have it: expiresIn → exp, notBefore → nbf (seconds from now), issuer → iss, audience → aud, subject → sub; keyId → the header's kid. HS* take the secret; the others a private key, as sign |
jwt.verify(token: string, alg: JwtAlgorithm, key: Bytes | string, options?: JwtVerifyOptions): json ! JwtError | KeyError | the claims, once the token holds: its header's alg is alg (the verifier chooses the algorithm, never the token), the signature is key's (HS* compared in constant time), exp hasn't passed and nbf has (leeway seconds of skew, 0 by default; now in seconds overrides the clock), and iss, sub and aud (equal to, or a list holding, audience) are what options asks for |
jwt.decode(token: string): Jwt ! JwtError | { header, claims } unverified: to read kid before choosing a key |
A token that doesn't hold fails with JwtError { reason, message }, reason one of "malformed" (not three base64url parts of JSON objects, or an exp/nbf that isn't a number), "algorithm", "signature", "expired", "notYetValid", "issuer", "audience", "subject". A key alg can't use fails with KeyError.
The errors are std/crypto's variants (language.md, Errors): KeyError { message }, JwtError { reason: JwtReason, message }; import their types by name to write or match them.
std/$crypto
The primitives, positions none: digest(alg, data), hmac(alg, key, data), equal(a, b) (constant time), random(n) (effectful), keyProblem(alg, key, private) (why the key can't be used, or null), verify(alg, key, data, signature), sign(alg, key, data). A bad algorithm name or key panics (TypeError) everywhere but keyProblem; the JS backend has the first four.