Tern

crypto

The crypto module has the pieces a web service needs to handle secrets: SHA-256 and SHA-512, HMAC signatures, password hashing with Argon2id, PBKDF2, secure random bytes and numbers, constant-time comparison, hex and base64, and UUIDs (v4 random, v7 time-ordered). It is self-contained C inside the Tern runtime (no OpenSSL), works on every target including WebAssembly, and is compiled into a program only when it imports crypto.

import crypto

fn main():
    print(crypto.hex(crypto.sha256("hello")))
    token = crypto.base64url(crypto.random_bytes(32))
    print(len(token))
    h = crypto.hash_password("hunter2")
    print(crypto.verify_password("hunter2", h), crypto.verify_password("hunter3", h))
Output
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
43
true false

Bytes in strings

Hashes, MACs, keys and random bytes are raw bytes, returned in a str (Tern strings hold any bytes, including zeros). Printing one shows unreadable characters; turn it into text with crypto.hex or crypto.base64 first, and back with crypto.unhex or crypto.base64_decode. len(s) is the number of bytes.

Hashes and MACs

fn sha256(data: str) str                     32 bytes
fn sha512(data: str) str                     64 bytes
fn hmac_sha256(key: str, msg: str) str       32 bytes
fn hmac_sha512(key: str, msg: str) str       64 bytes
fn sha1(data: str) str                       20 bytes
fn hmac_sha1(key: str, msg: str) str         20 bytes

SHA-1 is broken for collision resistance: don't use it for signatures or content addressing. HMAC-SHA1 is still sound, and it's what TOTP codes (RFC 6238, every authenticator app) and some older protocols require.

SHA-256 uses the CPU's SHA instructions where it has them (Apple silicon and other ARMv8 chips). To check a signature someone sent you, compute the expected MAC and compare with crypto.equal, never ==: == stops at the first differing byte, which leaks through timing how much of a forged signature was right.

import crypto

fn sign(secret: str, body: str) str:
    return crypto.hex(crypto.hmac_sha256(secret, body))

fn verify(secret: str, body: str, sig: str) bool:
    return crypto.equal(sign(secret, body), sig)

fn main():
    s = sign("key", "The quick brown fox jumps over the lazy dog")
    print(s)
    print(verify("key", "The quick brown fox jumps over the lazy dog", s))
    print(verify("key", "The quick brown fox jumps over the lazy cat", s))
Output
f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8
true
false

Passwords

fn hash_password(pw: str) str
fn verify_password(pw: str, hash: str) bool

hash_password hashes with Argon2id (RFC 9106), the algorithm OWASP recommends, using a fresh 16-byte random salt and OWASP's cost settings (19 MiB of memory, 2 passes, 1 lane). The result is a PHC string that records the algorithm, the cost and the salt, so it is all you need to store:

$argon2id$v=19$m=19456,t=2,p=1$<salt in base64>$<hash in base64>

It is the same format the argon2 libraries of other languages use (Rust's argon2, Go's alexedwards/argon2id, Python's argon2-cffi), so hashes move between them. verify_password reads the cost from the string, so hashes made with other settings still verify; it returns false for a wrong password and for a string it can't parse.

Hashing a password takes about 20-40 ms of CPU on purpose. Called from a task (a web handler, say), the work runs on the blocking-thread pool like task.blocking, so the other tasks on that core keep serving requests meanwhile.

import crypto

fn main():
    stored = crypto.hash_password("correct horse battery staple")
    print(stored.starts_with("$argon2id$v=19$m=19456,t=2,p=1$"))
    print(crypto.verify_password("correct horse battery staple", stored))
    print(crypto.verify_password("Tr0ub4dor&3", stored))
    print(crypto.hash_password("same") != crypto.hash_password("same"))
Output
true
true
false
true

Key derivation

fn argon2id(pw: str, salt: str, t: int, m_kib: int, p: int, length: int) str
fn pbkdf2_sha256(pw: str, salt: str, iterations: int, length: int) str

The raw functions, for deriving encryption keys or talking to a protocol that fixes the parameters (PostgreSQL's SCRAM login uses PBKDF2). argon2id needs a salt of at least 8 bytes, t >= 1 passes, m_kib KiB of memory (at least 8 * p), and p lanes; the result has length bytes. Bad parameters are a runtime error.

import crypto

fn main():
    print(crypto.hex(crypto.pbkdf2_sha256("password", "salt", 4096, 32)))
    print(crypto.hex(crypto.argon2id("password", "somesalt", 2, 65536, 1, 32)))
Output
c5e478d59288c841aa530db6845c4c8d962893a001ce4e11a4963873aa98134a
09316115d5cf24ed5a15a31a3ba326e5cf32edc24702987c02b6566f61913cf7

Random numbers

fn random_bytes(n: int) str
fn random_int(lo: int, hi: int) int          lo..hi, both included

From the operating system's secure generator (arc4random_buf on macOS, iOS, Android and the BSDs, getrandom on Linux, WASI random_get on WebAssembly). Use these, not the random module, for tokens, keys, salts and anything an attacker must not guess. random_int has no modulo bias.

import crypto

fn main():
    session = crypto.hex(crypto.random_bytes(16))
    print(len(session))
    code = crypto.random_int(100000, 999999)      # a 6-digit one-time code
    print(code >= 100000 and code <= 999999)
Output
32
true

UUIDs

fn uuid4() str        random
fn uuid7() str        Unix milliseconds, then random bits (RFC 9562)

Both return the 36-character text form. Version 7 UUIDs sort in the order they were made (within one millisecond, a thread's UUIDs count up), so they make good database keys: new rows land at the end of the index instead of all over it.

import crypto

fn main():
    a = crypto.uuid7()
    b = crypto.uuid7()
    print(len(a), a[14], a < b)
    print(crypto.uuid4()[14])
Output
36 7 true
4

Encryption

seal encrypts with ChaCha20-Poly1305 (RFC 8439), which is authenticated: unseal fails if a single byte of the sealed data was changed, or if the key is wrong, instead of returning garbage. The key is 32 random bytes; keep it outside the data it protects (an environment variable, a secrets manager, a file readable only by the service).

import crypto

fn main():
    key = crypto.random_bytes(32)
    sealed = crypto.seal(key, "sk-ant-api03-secret")
    print(len(sealed), crypto.unseal(key, sealed))
    tampered = sealed[..20] + "!" + sealed[21..]
    print(crypto.unseal(key, tampered) == "", crypto.error())
    print(crypto.try_unseal(crypto.random_bytes(32), sealed).is_err())
Output
47 sk-ant-api03-secret
true crypto: open: the data was changed, or the key is wrong
true
fn seal(key: str, plaintext: str) str          a random 12-byte nonce + ciphertext + 16-byte tag
fn unseal(key: str, sealed: str) str           "" and crypto.error() if it doesn't check out
fn try_unseal(key: str, sealed: str) Result[str, str]
fn chacha20_poly1305(key: str, nonce: str, aad: str, plaintext: str) str      ciphertext + tag
fn chacha20_poly1305_open(key: str, nonce: str, aad: str, sealed: str) str

The raw forms take your own 12-byte nonce, which must never repeat under the same key (a counter works; seal's random nonces are safe for billions of messages per key), and additional data that is authenticated but not encrypted (a record id, so a sealed value can't be moved to another record).

Signatures

rsa_verify_sha256 checks an RSA signature made with PKCS#1 v1.5 and SHA-256: JWT's RS256, what Google, Apple and most OpenID Connect providers sign ID tokens with. The key is the modulus and exponent as big-endian bytes, which is what a JWK's "n" and "e" are after base64url_decode. It builds the block the signature must decode to and compares the whole of it, rather than parsing the signature's padding.

fn rsa_verify_sha256(n: str, e: str, msg: str, sig: str) bool     1024- to 8192-bit keys, e up to 8 bytes

A JWT's signature covers header.payload (the first two parts as sent, dots included):

parts = token.split(".")
ok = crypto.rsa_verify_sha256(crypto.base64url_decode(jwk_n), crypto.base64url_decode(jwk_e),
    parts[0] + "." + parts[1], crypto.base64url_decode(parts[2]))

It's written in Tern (about 12 ms for a 2048-bit key), so importing crypto links nothing more. It only verifies: there's no RSA signing or encryption.

Comparing secrets

fn equal(a: str, b: str) bool

True when a and b are the same bytes. It takes the same time wherever they differ (only the lengths can be learned from timing), so use it for MACs, tokens and API keys.

Hex and base64

fn hex(data: str) str                 lowercase
fn unhex(s: str) str                  either case
fn base64(data: str) str              standard alphabet, with = padding
fn base64_decode(s: str) str          padding optional; spaces and newlines skipped
fn base64url(data: str) str           - and _ instead of + and /, no padding (URLs, JWTs)
fn base64url_decode(s: str) str
fn error() str

A decoder given bad input returns "" and crypto.error() says why; after a successful call crypto.error() is "" (so you can tell a bad input from an empty one).

import crypto

fn main():
    print(crypto.base64("hello?"), crypto.base64url("hello?"))
    print(crypto.base64_decode("aGVsbG8/"))
    print(crypto.hex("AZ"), crypto.unhex("415a"))
    bad = crypto.unhex("xyz")
    print(bad == "", crypto.error())
Output
aGVsbG8/ aGVsbG8_
hello?
415a AZ
true crypto.unhex: odd number of hex digits

With Result

try_unhex(s), try_base64_decode(s) and try_base64url_decode(s) return Result[str, str]: key = crypto.try_base64_decode(env_key)?, with errors like "crypto: base64_decode: not base64".

Performance

Single core, Apple M-series, against Rust (sha2, hmac, argon2 crates) and Go (crypto/sha256, golang.org/x/crypto/argon2); the programs are in bench/std/:

TernGoRust
SHA-256, 64 MiB1937 MB/s2042 MB/s1930 MB/s
HMAC-SHA256 of 64 bytes140 ns416 ns140 ns
Argon2id, m=19 MiB t=2 p=1 (hash_password)20.7 ms40.5 ms21.6 ms
PBKDF2-SHA256, 600,000 iterations38.1 ms68.2 ms47.2 ms
ChaCha20-Poly1305, 1 MiB messages678 MB/s1238 MB/s (assembly)713 MB/s (chacha20poly1305)
Source: docs/std/crypto.md. Every example on this page is compiled and run by tern x test docs.