The ecosystem · packages/crypto
Hashes, signatures and keys, in Roc
SHA-256, HMAC, HKDF, Base64 and hex: store a token as its digest, sign a link so nobody can forge it, derive separate keys from one secret, make a row's id. SHA-1 and Base32 are here too, for authenticator apps' codes. The package is plain Roc on no platform, so the server, a page in the browser and an expect run the same code.
Installing it#
Name the package in your app's header, beside the platform:
app [program] { crypto: "../packages/crypto/main.roc", pf: platform "../server/platform/main.roc" }Then import the modules you use: import crypto.Hmac, import crypto.Base64, and so on. The platform's crypto page uses them with the server platform's encryption and random bytes, for tokens and sealed secrets.
A signed link#
A link that carries who it is for and when it expires, signed so that changing either breaks it. From the server platform's test app:
## A link for a member, until a moment (ms), signed with a key of its own derived from the app's
## `APP_SECRET`.
signed_link! : Str, U64 => Str
signed_link! = |member, until| {
said = "${member}.${until.to_str()}"
"${said}.${Base64.url_encode(Hmac.sha256(link_key!({}), said.to_utf8()))}"
}
## Whom a signed link is for, if its signature holds and it hasn't run out by `now` (ms).
link_member! : Str, U64 => Try(Str, [BadLink, Expired])
link_member! = |link, now|
match link.split_on(".") {
[member, until, signature] => {
said = "${member}.${until}"
signed = Base64.url_decode(signature) ?? []
if (!Hmac.verify_sha256(link_key!({}), said.to_utf8(), signed)) {
Err(BadLink)
} else if ((U64.from_str(until) ?? 0) < now) {
Err(Expired)
} else {
Ok(member)
}
}
_ => Err(BadLink)
}
## The links' key: derived from the app's secret, for links alone, so no other use of the secret
## signs one.
link_key! : {} => List(U8)
link_key! = |{}| Hkdf.sha256(app_secret!({}), [], "links".to_utf8(), 32) ?? []
## The app's secret, from its environment (a development one without).
app_secret! : {} => List(U8)
app_secret! = |{}| (Env.var!("APP_SECRET") ?? "a development secret, not for production").to_utf8()The signing key comes from the app's APP_SECRET through HKDF, with "links" as its purpose, so it signs links and nothing else. The link's text is signed with HMAC-SHA256, and the signature is written in Base64's URL alphabet, which needs no escaping in a URL. Hmac.verify_sha256 compares signatures in constant time, so the time it takes doesn't tell a forger how much of a signature was right.
The modules#
| Module | What it has |
|---|---|
Sha256 | hash (the 32-byte digest), hex (the digest as 64 lowercase hex digits), chunks (the digest of several pieces, without joining them first) |
Sha1 | hash (the 20-byte digest) and hex: for authenticator apps' codes alone (below) |
Hmac | sha256(key, message); verify_sha256(key, message, signature); sha1 and verify_sha1, the same over SHA-1; equal, a constant-time comparison of two byte lists |
Hkdf | sha256(key, salt, info, length), which fails with TooLong past 8160 bytes; its two steps, extract and expand |
Base64 | encode and decode (standard alphabet, padded); url_encode (URL alphabet, unpadded) and url_decode; encode_unpadded, url_encode_padded; lines (76-character lines, as MIME wants) |
Base32 | encode (padded), encode_unpadded, decode (either case, padded or not): how an authenticator app's secret is written |
Hex | encode (lowercase), decode (either case) |
Uuid | v7(millis, random), a version 7 UUID that leads with its time; v4(random), all random; is_uuid, whether text is one |
Rsa | verify_pkcs1_sha256(key, message, signature): whether an RSA signature (PKCS#1 v1.5 with SHA-256, 2048 to 8192 bits) is the message's under the public key |
Jwt | verify_rs256(token, keys): a JSON Web Token's claims, if one of a JSON Web Key Set's keys (keys, from its JSON) signed it with RS256; parse, its parts unchecked |
Decoding is strict, so each value has exactly one text: only the alphabet asked for, no spaces or line breaks, padding either left out or exactly right, and the last character's unused bits zero. Anything else is an error (InvalidBase64, InvalidBase32, InvalidHex). The package's README.md (packages/crypto/) lists every function's type.
A row's id: Uuid.v7(Time.now_millis!({}), Random.bytes!(10)), the time and random bytes from the server platform, as the module is plain Roc. A version 7 id leads with when it was made, so rows added by id go to the end of an index, and sorting by id sorts by time; it also tells whoever sees it when that was, which a version 4 id doesn't. Both are 36 characters of text, the same in SQLite and Postgres. The auth package's users get version 7 ids.
SHA-1, HMAC-SHA1 and Base32 serve one job: an authenticator app's six-digit codes (TOTP, RFC 6238), which the auth package's two-factor sign-in checks. SHA-1 is broken for collisions, so don't sign with it or store a token's digest in it. HMAC-SHA1 doesn't rest on collisions, but use HMAC-SHA256 for anything new.
Rsa and Jwt check what an OpenID Connect provider signs: an ID token Google gives a phone's account sheet, which the auth package checks against Google's keys. They only check: no signing, and a token is taken only if its header says RS256 (never none or HS256). What its claims must say (issuer, audience, expiry, nonce) is the caller's to check.
How it is tested#
Each module's expects check it against published test vectors: NIST's SHA-256 and SHA-1 examples, every test case of RFC 4231 (HMAC-SHA256) and RFC 2202 (HMAC-SHA1), RFC 5869's SHA-256 cases (HKDF), RFC 4648's (Base64, Base32 and hex), RFC 9562's UUID examples, and RFC 7515's RS256 example (Rsa, Jwt), with keys of the tests' own whose signatures Node made. Sha256 wraps Roc's builtin Crypto.SHA256; Sha1 is the package's own Roc. The server platform's tests also compare SHA-256, HMAC, HKDF, Base64 and hex with Node's crypto through a running server, and the auth package's tests compare authenticator codes with Node's.
What isn't here#
- Encryption and random bytes, which need the operating system: they are the server platform's
AesGcmandRandom. - Password hashing (bcrypt, scrypt, Argon2): not yet. SHA-256 and HKDF are too fast to protect passwords.
- Public-key cryptography: the server platform's
P256has what Web Push needs (ES256 signatures, ECDH with a key pair made for one call, and a new key pair); here, RSA signatures checked. RSA signing, PSS, ES256 tokens checked and other curves: not yet.