Roc Solid
Markup in Roc · pages on a native server · components in WebAssembly

The platform · crypto

Secrets, and what to do with them

Most apps need unguessable tokens (stored so a leaked table is useless), unforgeable links, and secrets stored encrypted. Secure random bytes, AES-GCM and the elliptic curve P-256 come from the host. The rest is plain Roc in packages/crypto, checked against published test vectors. The secrets come from the app's environment.

The samples are from server/test/app/Samples.roc, compiled and run by the platform's tests. Its header names the crypto package (crypto: "../packages/crypto/main.roc"), and it imports crypto.Hmac and the rest from it.

Tokens, and their digests#

server/test/app/Samples.roc, in part
## A fresh token for a link: 32 random bytes, URL-safe.
token! : {} => Str
token! = |{}| Base64.url_encode(Random.bytes!(32))

## What an app keeps of a token: its digest, never the token, so a leaked table signs no one in.
digest : Str -> Str
digest = |token| Sha256.hex(token.to_utf8())

Random.bytes!(count) is the operating system's secure randomness (through ring). If the system has none, the call crashes rather than make a key from anything weaker. A sign-in link's token is 32 random bytes; the database keeps only its SHA-256 digest, so a copy of the table signs no one in.

Ids: UUIDs#

id = Uuid.v7(Time.now_millis!({}), Random.bytes!(10))   # "019ad2c4-6b1e-7f3a-9c2d-…"
key = Uuid.v4(Random.bytes!(16))                           # random throughout
Uuid.is_uuid(id)                                           # Bool.True

crypto.Uuid writes RFC 9562's UUIDs as text, in lowercase. A version 7 id leads with the time it was made, so ids made later sort after earlier ones, and rows inserted by id go to the end of an index. A version 4 id is random throughout. The module is given its random bytes and the time, so it is plain Roc, and an expect given the same bytes gets the same id.

server/test/app/Samples.roc, in part
## 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 app derives a link-signing key from its APP_SECRET with HKDF, so the key serves this one purpose, then signs the link with HMAC-SHA256. Hmac.verify_sha256 checks a link in constant time, so its timing doesn't tell a forger how much of a signature was right.

Sealed secrets#

server/test/app/Samples.roc, in part
## A secret kept in the database (another service's token), sealed with AES-256-GCM under a key
## derived from `APP_SECRET`, as hex.
seal! : Str => Try(Str, [BadKey])
seal! = |secret| {
	sealed = AesGcm.seal!(sealing_key!({}), secret.to_utf8())?
	Ok(Hex.encode(sealed))
}

## The secret again; `Forged` if what was kept was changed, or sealed under another key.
unseal! : Str => Try(Str, [BadKey, Forged, InvalidHex, BadUtf8])
unseal! = |kept| {
	sealed = Hex.decode(kept)?
	opened = AesGcm.open!(sealing_key!({}), sealed)?
	Str.from_utf8(opened).map_err(|_| BadUtf8)
}

## The key secrets are sealed under, derived for that alone.
sealing_key! : {} => List(U8)
sealing_key! = |{}| Hkdf.sha256(app_secret!({}), [], "sealed".to_utf8(), 32) ?? []

AesGcm.seal!(key, plaintext) encrypts with AES-256-GCM under a 32-byte key (BadKey otherwise), with a fresh random 12-byte nonce each time. It returns the nonce, ciphertext and 16-byte tag, in that order: Web Crypto's output with the nonce in front, so either side can open what the other sealed. AesGcm.open! answers Forged for anything changed or sealed under another key.

P-256: ES256 and ECDH#

server/test/app/Samples.roc, in part
## A JWT signed with ES256, for a service that takes one (Web Push's VAPID token is one): the
## header and the claims, each base64url, then the signature by a P-256 key pair (the private
## key's 32 bytes, the public key's 65), each after a `.`.
es256_token! : Str, List(U8), List(U8) => Try(Str, [BadKey])
es256_token! = |claims, private_key, public_key| {
	header = "{\"typ\":\"JWT\",\"alg\":\"ES256\"}"
	input = "${Base64.url_encode(header.to_utf8())}.${Base64.url_encode(claims.to_utf8())}"
	signature = P256.sign!(private_key, public_key, input.to_utf8())?
	Ok("${input}.${Base64.url_encode(signature)}")
}

P256 is the elliptic curve P-256 (secp256r1), as much as Web Push needs. A public key is an uncompressed 65-byte point (4, then x and y); a private key is its 32-byte scalar. These are the raw forms browsers, Web Crypto and web-push generate-vapid-keys use, in base64url.

The modules#

ModuleWhat
AesGcmseal!, open!: AES-256-GCM, by the host; seal_with_nonce!: AES-128-GCM or AES-256-GCM with the caller's nonce
P256generate!: a new key pair; sign!: ES256 signatures; ecdh!: a shared secret with a key pair made for one call
Randombytes!(count), seed_u64!: the operating system's randomness
crypto.Sha256hash: 32 bytes; hex: 64 hex digits
crypto.Sha1hash: 20 bytes; hex. For authenticator apps' codes (TOTP) alone: never sign with it or keep a digest in it
crypto.Hmacsha256(key, message); verify_sha256(key, message, signature) and equal, in constant time; sha1 and verify_sha1, for TOTP
crypto.Hkdfsha256(key, salt, info, length) (RFC 5869), TooLong past 8160 bytes; extract, expand
crypto.Base64encode, decode; url_encode (unpadded), url_decode; encode_unpadded, url_encode_padded, lines (MIME's)
crypto.Base32encode, encode_unpadded (an otpauth:// secret), decode (either case)
crypto.Hexencode, decode
crypto.Uuidv7(millis, random), v4(random): an id as text; is_uuid

AesGcm, P256 and Random are the platform's, done by the host (ring). The rest are the crypto package's: pure Roc without effects, so they run anywhere, a browser page and expect tests included. They are checked against the test vectors of NIST, RFC 2202, RFC 4231, RFC 4648, RFC 5869 and RFC 9562; Sha256 wraps Roc's builtin Crypto.SHA256. Decoding is strict: only the alphabet, no spaces, padding absent or exact, and the last character's unused bits zero (Hex and Base32 take either case, as people type secrets).