Crypto, tokens and certificates with Jennifer

Jennifer

Hashes, MACs, ciphers and signatures, passwords, two-factor codes, JWT, OAuth2, ACME certificates and sealed secrets.

November 2026, by @mplx.
Based on Jennifer 0.27.0

Powered by Jennifer's Cantrip - Markdown into slide decks, https://github.com/jennifer-language/cantrip
1 / 20

Four tools, four questions

ToolAnswersKeyJennifer
HashIs this the same data?nonehash.compute("sha256", b)
MACDid someone with our key send it?shared secrethash.hmac("sha256", b, key)
EncryptionCan only key holders read it?shared secretcrypto.encrypt(algo, ...)
SignatureDid the private key's owner write it?key paircrypto.sign(algo, ...)

A hash proves nothing about who; encryption alone proves nothing about what. The algorithm is always the first argument.

2 / 20

Hash, MAC, and a comparison that does not leak

def body as bytes init encoding.encode("utf-8", '{"order":42}');
def key as bytes init
    encoding.encode("utf-8", "PLACEHOLDER-hook-key");
def mac as string init
    encoding.toText("hex", hash.hmac("sha256", $body, $key));
func authentic(body as bytes, sent as string, key as bytes) {
    def want as bytes init hash.hmac("sha256", $body, $key);
    return hash.equal($want, encoding.fromText("hex", $sent));
}
sha256 54985dc3c12fada7a1b1db53...
hmac   d3d0fb779cbe4a0a18d06324...
true false
3 / 20

Encryption is authenticated, signatures are public

def nonce as bytes init crypto.randBytes(24);          # never reuse one
def box as bytes init crypto.encrypt("xchacha20-poly1305", $msg,
    $key, $nonce, $none);
$box[0] = $box[0] ^ 1;                                 # flip one bit
crypto.decrypt("xchacha20-poly1305", $box, $key, $nonce, $none);
def kp as crypto.Keypair init crypto.keypair("ed25519");
def sig as bytes init crypto.sign("ed25519", $msg, $kp.private);
crypto.verify("ed25519", $forged, $sig, $kp.public);
runtime | crypto.decrypt: authentication failed (wrong key,
  nonce or aad, or tampered data)
sig: 64 bytes, ok true
forged: false
4 / 20

Passwords: argon2id, never a digest

def stored as string init
    crypto.hashPassword("argon2id", "correct horse battery");
crypto.verifyPassword("Correct horse battery", $stored);

# on login: an old bcrypt hash that verified is replaced
if (crypto.verifyPassword($pw, $old) and
    strings.startsWith($old, "$2")) {
    $old = crypto.hashPassword("argon2id", $pw);
}
$argon2id$v=19$m=65536,t=3,p=4$xQdPRU0FpHz0P7muZEnyiQ$B+JOjH... (61 ms)
false
now $argon2id$v=19$m=65536,t=3,p=4...
5 / 20

TOTP: enrolment is a URI and a QR code

def secret as string init totp.generateSecret();
def link as string init
    totp.uri("Shelf", "ada@example.org", $secret, $o);
def qr as barcode.Symbol init barcode.encode("qr", $link, $bo);
fs.writeBytes("enrol.png", barcode.png($qr, $bo));

The enrolment QR code

6 / 20

TOTP: a window, and no second use

func stepOf(code as string, now as int, o as totp.Options) {
    def found as int init -1;
    for (def d in -1..2) { # -1, 0, 1: half-open, one step each side
        def at as int init $now + $d * 30;
        def want as string init totp.generateAt(SECRET, $at, $o);
        if (hash.equal(utf8($want), utf8($code))) { $found = $at // 30; }
    }
    return $found;
}
verify true, old code false
985187 ok, step 59836375
985187 refused
7 / 20

JWT: sign, then verify against a policy

def claims as json.Value init json.decode('{"sub":"ada",' +
    '"iss":"https://shelf.example.org","aud":"shelf-api"}');
$claims = json.set($claims, "/exp", $now + 900);
def token as string init jwt.sign("EdDSA", $claims, $kp.private);
def policy as jwt.Policy init jwt.Policy{
    iss: "https://shelf.example.org",
    aud: "shelf-api", requireExp: true, leeway: 30};
def back as json.Value init
    jwt.verifyWith("EdDSA", $token, $kp.public, $policy);
eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhZGEiLCJpc3M...
sub=ada
8 / 20

JWT: what verifyWith refuses

attempt("none", b64('{"alg":"none"}') + "." + $body + ".",
    $kp.public, $p);
attempt("confused", jwt.sign("HS256", $c, $kp.public), $kp.public, $p);
attempt("tampered", $parts[0] + "." + $evil + "." + $parts[2],
    $kp.public, $p);
attempt("expired", jwt.sign("EdDSA", $c, $kp.private), $kp.public, $p);
none: jwt.verify: token algorithm does not match the expected EdDSA
confused: jwt.verify: token algorithm does not match the expected EdDSA
tampered: jwt.verify: signature verification failed
expired: jwt.verify: token has expired
9 / 20

OAuth2: a service as itself

def cfg as oauth.Config;
$cfg.tokenUrl = "http://127.0.0.1:9400/token";
$cfg.clientId = "shelf-worker";
$cfg.clientSecret = os.getEnv("SHELF_CLIENT_SECRET");
def tok as oauth.Token init oauth.clientCredentials($cfg);
$cfg.clientSecret = "wrong";
try { oauth.clientCredentials($cfg); } catch (e) {
    if ($e.kind != "oauth") { throw $e; }
    io.printf("%s %d | %s\n", $e.errorCode, $e.status, $e.message);
}
Bearer at-jwX..., expires 1795094904, expired false
invalid_client 400 | invalid_client: bad client secret
10 / 20

OAuth2: authorization code with PKCE

def srv as httpd.Server init httpd.listen("127.0.0.1:0");
def req as oauth.AuthRequest init oauth.authorize($cfg,
    "http://" + httpd.address($srv) + "/callback");
def waiter as task of string init
    spawn { return oauth.awaitCode($req, $srv); };
# ... the user signs in; the browser lands on /callback
def code as string init task.wait($waiter);
httpd.shutdown($srv);
def tok as oauth.Token init oauth.exchangeCode($cfg, $req, $code);
browser: 200 Signed in. You can close this window.
access at-Dg-..., refresh rt-AKV...
11 / 20

OAuth2: refresh, rotation, and the token file

def old as string init $tok.refreshToken;
$tok = oauth.refresh($cfg, $tok.refreshToken);
try {
    oauth.refresh($cfg, $old);
} catch (e) {
    if ($e.kind != "oauth") { throw $e; }
    io.printf("reuse: %s (%s)\n", $e.errorCode, $e.description);
}
oauth.save("token.json", $tok);
refreshed: refresh rt-2Ql...
reuse: invalid_grant (refresh token revoked or reused)
$ stat -c '%a %n' token.json
600 token.json
12 / 20

ACME: account, order, challenge

def c as acme.Client init acme.connect(CA, accountKey("account.pem"));
$c = acme.register($c, "ops@example.org");
def o as acme.Order init acme.order($c, [DOMAIN]);
def az as acme.Authorization init
    acme.authorization($c, $o.authorizations[0]);
def ch as acme.Challenge init acme.challenge("http-01", $az);
def srv as httpd.Server init httpd.listen("127.0.0.1:5002");
def answer as string init acme.keyAuthorization($c, $ch.token);
def web as task of null init
    spawn { serveChallenge($srv, $ch.token, $answer); };
account https://127.0.0.1:14000/my-account/57766b11a0899f75
order pending, 1 authorization(s)
13 / 20

ACME: prove it, check it, finalize

acme.accept($c, $ch.url);
def done as acme.Authorization init
    acme.pollAuthorization($c, $o.authorizations[0], 1000, 30);
stopServer($srv, $web);
if ($done.status != "valid") { notValidated($done); }
def certKey as crypto.Keypair init crypto.keypair("p256");
def csr as bytes init crypto.csr($certKey.private, [DOMAIN]);
$o = acme.finalize($c, $o, $csr, 1000, 30);
def pem as string init acme.downloadCertificate($c, $o);
order valid, 2063 bytes of PEM
# the same program, serving a wrong answer:
shelf.example.test: authorization invalid
14 / 20

When to renew

def cert as asn1.Value init
    asn1.decode(encoding.fromText("base64", $b64));
def s as string init encoding.decode("utf-8",
    asn1.asBytes($cert, "/0/4/{$which}"));   # notBefore, notAfter
# ...
def life as int init time.unix($ends) - time.unix($from);
def left as int init time.unix($ends) - time.unix(time.now());
if ($left < $life // 3) {
    io.printf("renew now\n");
}
expires 2027-02-17, 89 of 89 days left
15 / 20

Sealed secrets with @deckyard/sealbox

import "@deckyard/sealbox/" as sealbox;

def key as bytes init sealbox.newKey();
def id as bytes init encoding.encode("utf-8", "row 17");
def box as bytes init sealbox.sealWith($plain, $key, $id);
def other as bytes init encoding.encode("utf-8", "row 18");
sealbox.openWith($box, $key, $other);
def tok as string init sealbox.fernetEncrypt($plain, $fkey);
box 52 bytes for 24
sealbox | sealbox: cannot open (wrong key, or the data was changed)
fernet gAAAAABq_uraUoQ5EljskIId...
16 / 20

Keys: owner-only files, ids, rotation

func keyFile(path as string) {
    if (fs.stat($path).mode & 0o077 != 0) {
        throw Error{kind: "config",
            message: $path + " is readable by others"};
    }
    return fs.readString($path);
}
def old as string init jwt.signWithKid("HS256", $c,
    encoding.encode("utf-8", $keys["2026-10"]), "2026-10");
def back as json.Value init jwt.verifyWithKeys("HS256", $t, $keys);
config | run/jwt-2026-11 is readable by others
kid 2026-10: sub=ada
kid 2026-11: sub=ada
17 / 20

Errors and their kinds

WhereKindCarries
crypto.decrypt"runtime"one vague message
totp, jwt"totp", "value"a message
oauth"oauth": OAuthErrorerrorCode, status
acme"acme": AcmeErrorproblemType, retryAfter
@deckyard/sealbox"sealbox"one vague message
http underneathnet, timeout, limit, closedpassed on
18 / 20

Checklist

19 / 20

Read more

Based on Jennifer 0.27.0, November 2026.

20 / 20