GitHub

Cryptography and JOSE

Random ids, digests, authenticated encryption, signatures and key formats as services, and signed or encrypted tokens on top of them.

pyfect.crypto gives each family of operations its own service: SecureRandom, Digest, Mac, Kdf, Aead, Cipher, Signature, KeyAgreement and KeyWrap. Nothing is hand-rolled: the primitives come from hashlib, hmac, the cryptography package and PyNaCl, installed with the crypto extra.

uv add "pyfect-dev[crypto]"

Services

Provide native.layer for every family on the host's libraries, or one of its parts (native.layer_aead, native.layer_signature, ...). Each module also has layer_web_crypto, which runs on the WebCrypto reference: swap that reference, with web_crypto.layer(crypto), to run every family on another implementation of the Web Crypto API, as tests do with a fake that fails on purpose.

Keys belong to one algorithm and are typed by it, so a P-256 key cannot reach an operation on P-384 and an AES-GCM key cannot reach HMAC. They display redacted, compare by identity, and refuse to be pickled. A failure is a CryptoError whose reason says what went wrong: InvalidKey, InvalidArgument, DecryptionFailed, NotExtractable or Unsupported. A tampered message, a wrong nonce or the wrong key all give the same DecryptionFailed, and MAC tags are compared in constant time.

services.py
import pyfect as fx
from pyfect.crypto import aead, digest, native, signature
from pyfect.crypto.aead import Aead
from pyfect.crypto.digest import Digest
from pyfect.crypto.secure_random import SecureRandom
from pyfect.crypto.signature import Signature


@fx.fn
def main():
    random = yield from SecureRandom()
    print(len((yield from random.uuid_v7())))

    hashes = yield from Digest()
    print((yield from hashes.digest_hex(digest.sha256, b"abc"))[:16])

    # A fresh nonce for every message under one key.
    sealer = yield from Aead()
    key = yield from sealer.generate_key(aead.aes256_gcm)
    nonce = yield from random.random_bytes(aead.aes256_gcm.nonce_length)
    sealed = yield from sealer.encrypt(key, b"attack at dawn", nonce=nonce, aad=b"v1")
    print((yield from sealer.decrypt(key, sealed, nonce=nonce, aad=b"v1")))
    tampered = sealer.decrypt(key, sealed, nonce=nonce, aad=b"v2")
    print((yield from tampered.flip()).message)

    signer = yield from Signature()
    pair = yield from signer.generate_key_pair(signature.ed25519)
    signed = yield from signer.sign(pair.private_key, b"release 1.2")
    print((yield from signer.verify(pair.public_key, signed, b"release 1.2")))
    print(pair.private_key)


fx.run_main(main().pipe(fx.provide(native.layer)))

AEAD nonces must never repeat under one key. Draw them from SecureRandom for AES-GCM, or use xchacha20_poly1305, whose 24-byte nonces are safe to draw at random for any number of messages. Feed a KeyAgreement shared secret to Kdf (HKDF) before using it as a key, and store passwords with kdf.argon2id().

Envelope encryption

Seal each message under its own data key and store only that key wrapped under a key-encryption key: KeyWrap with aes256_kw (RFC 3394) wraps any secret key and unwrap gives it back as a key of the algorithm you name, so changing the outer key rewraps a few bytes and leaves the ciphertext alone. Here the outer key comes from a passphrase through Kdf with kdf.argon2id() (RFC 9106's second recommended setting, which needs native.layer); a wrong passphrase fails to unwrap with DecryptionFailed.

envelope.py
import pyfect as fx
from pyfect.crypto import aead, kdf, key_wrap, native
from pyfect.crypto.aead import Aead
from pyfect.crypto.kdf import Kdf
from pyfect.crypto.key_wrap import KeyWrap
from pyfect.crypto.secure_random import SecureRandom


@fx.fn
def main():
    random = yield from SecureRandom()
    sealer = yield from Aead()
    wrapper = yield from KeyWrap()
    derive = yield from Kdf()

    # One data key per message; only its wrapped form is stored.
    data_key = yield from sealer.generate_key(aead.xchacha20_poly1305)
    nonce = yield from random.random_bytes(aead.xchacha20_poly1305.nonce_length)
    sealed = yield from sealer.encrypt(data_key, b"the launch code", nonce=nonce, aad=b"msg-1")

    # The key-encryption key comes from a passphrase, through Argon2id.
    salt = yield from random.random_bytes(16)
    stretched = yield from derive.derive(kdf.argon2id(), b"correct horse", salt=salt, length=32)
    kek = yield from key_wrap.key(key_wrap.aes256_kw, stretched)
    wrapped = yield from wrapper.wrap(kek, data_key)
    print(len(wrapped))

    # A new passphrase only rewraps the data key; the sealed message stays as it is.
    restored = yield from wrapper.unwrap(kek, aead.xchacha20_poly1305, wrapped)
    print((yield from sealer.decrypt(restored, sealed, nonce=nonce, aad=b"msg-1")))

    wrong = yield from derive.derive(kdf.argon2id(), b"wrong horse", salt=salt, length=32)
    wrong_kek = yield from key_wrap.key(key_wrap.aes256_kw, wrong)
    refused = wrapper.unwrap(wrong_kek, aead.xchacha20_poly1305, wrapped)
    print((yield from refused.flip()).reason.tag)


fx.run_main(main().pipe(fx.provide(native.layer)))

Sealing to a public key

To encrypt for someone who holds an X25519 key pair, agree on a secret with a fresh pair of your own and send its public half along. derive_shared_secret gives raw bytes, which go through HKDF (kdf.hkdf_sha256, with an info naming the purpose) before they become an aead.key; the recipient repeats the agreement with their private key and gets the same key.

sealing.py
import pyfect as fx
from pyfect.crypto import aead, kdf, key_agreement, native
from pyfect.crypto.aead import Aead
from pyfect.crypto.kdf import Kdf
from pyfect.crypto.key_agreement import KeyAgreement
from pyfect.crypto.secure_random import SecureRandom

INFO = b"example sealed box v1"


@fx.fn
def main():
    random = yield from SecureRandom()
    agreement = yield from KeyAgreement()
    derive = yield from Kdf()
    sealer = yield from Aead()

    recipient = yield from agreement.generate_key_pair(key_agreement.x25519)

    # The sender agrees on a secret with a fresh pair, then stretches it with HKDF:
    # a raw X25519 secret is never a key by itself.
    ephemeral = yield from agreement.generate_key_pair(key_agreement.x25519)
    shared = yield from agreement.derive_shared_secret(ephemeral.private_key, recipient.public_key)
    salt = yield from key_agreement.to_bytes(ephemeral.public_key)
    okm = yield from derive.derive(kdf.hkdf_sha256, shared, salt=salt, info=INFO, length=32)
    key = yield from aead.key(aead.xchacha20_poly1305, okm)
    nonce = yield from random.random_bytes(aead.xchacha20_poly1305.nonce_length)
    box = yield from sealer.encrypt(key, b"for your eyes only", nonce=nonce)

    # The recipient derives the same key from the sender's public key.
    sender_public = yield from key_agreement.public_key(key_agreement.x25519, salt)
    secret = yield from agreement.derive_shared_secret(recipient.private_key, sender_public)
    okm = yield from derive.derive(kdf.hkdf_sha256, secret, salt=salt, info=INFO, length=32)
    opened = yield from aead.key(aead.xchacha20_poly1305, okm)
    print((yield from sealer.decrypt(opened, box, nonce=nonce)))


fx.run_main(main().pipe(fx.provide(native.layer)))

Wrapping to a public key

To send a data key to someone who publishes an RSA public key, wrap it with RSA-OAEP: key_wrap.rsa_oaep_sha256 is JWE's RSA-OAEP-256 (OAEP with SHA-256) and key_wrap.rsa_oaep_sha1 is JWE's RSA-OAEP (OAEP with SHA-1, for protocols that require it). Both generate 3072-bit keys. A public key that arrives as a JWK becomes a key with key_format.decode_public(key_format.jwk, algorithm, JsonWebKey(...)), where JsonWebKey comes from pyfect.crypto.key_format. The algorithm, not the JWK, picks the hash, and a key wrapped with one hash does not unwrap with the other: it fails with DecryptionFailed.

wrapping.py
import json

import pyfect as fx
from pyfect.crypto import aead, key_format, key_wrap, native
from pyfect.crypto.key_format import JsonWebKey
from pyfect.crypto.key_wrap import KeyWrap


@fx.fn
def main():
    wrapper = yield from KeyWrap()

    # The recipient keeps the private key and publishes the public one as a JWK.
    pair = yield from wrapper.generate_key_pair(key_wrap.rsa_oaep_sha256)
    published = json.dumps((yield from key_format.encode(key_format.jwk, pair.public_key)))

    # The sender reads the JWK it was sent as a key of the algorithm it names.
    received: dict[str, str] = json.loads(published)
    jwk = JsonWebKey(kty="RSA", n=received["n"], e=received["e"])
    public_key = yield from key_format.decode_public(key_format.jwk, key_wrap.rsa_oaep_sha256, jwk)
    data_key = yield from (yield from aead.Aead()).generate_key(aead.aes256_gcm)
    wrapped = yield from wrapper.wrap(public_key, data_key)
    print(len(wrapped))  # the modulus length: 3072 bits

    restored = yield from wrapper.unwrap(pair.private_key, aead.aes256_gcm, wrapped)
    print(restored.algorithm.name)

    # The same RSA key with the other hash wraps differently, and does not unwrap.
    sha1_key = yield from key_format.decode_public(key_format.jwk, key_wrap.rsa_oaep_sha1, jwk)
    other = yield from wrapper.wrap(sha1_key, data_key)
    error = yield from wrapper.unwrap(pair.private_key, aead.aes256_gcm, other).flip()
    print(error.reason.tag)


fx.run_main(main().pipe(fx.provide(native.layer)))

Key formats and schemas

key_format reads and writes keys as SPKI, PKCS#8, PKCS#1, SEC1, JWK and PEM. The format's type says which keys it holds and which way it goes: pkcs1 and sec1 only read, and PEM formats take text where DER formats take bytes. pyfect.crypto.schema turns keys into schemas: CS.MacKeyFromBytes(mac.hmac_sha256) reads raw bytes (base64 under config.schema), and CS.SignaturePublicKeyFromFormat(format, algorithm) reads a format. Secret and private keys are written back only with allow_encode=True, and keys never have a JSON form.

keys.py
import pyfect as fx
from pyfect import config
from pyfect import config_provider as cp
from pyfect import schema as S
from pyfect.crypto import key_format, mac, native, signature
from pyfect.crypto import schema as CS
from pyfect.crypto.mac import Mac
from pyfect.crypto.signature import Signature

# An HMAC key from base64 in the environment.
hmac_key = config.schema(CS.MacKeyFromBytes(mac.hmac_sha256), "WEBHOOK_KEY")
provider = cp.from_env({"WEBHOOK_KEY": "c2VjcmV0LWtleS1mb3Itd2ViaG9va3MtMDAwMDAwMDA="})

# A public key from PEM; FromFormat schemas decode only as effects.
PublicKeyPem = CS.SignaturePublicKeyFromFormat(key_format.pem(key_format.spki), signature.ed25519)


@fx.fn
def main():
    key = yield from hmac_key.parse(provider)
    tag = yield from (yield from Mac()).sign(key, b"payload")
    print(tag.hex()[:16])

    pair = yield from (yield from Signature()).generate_key_pair(signature.ed25519)
    pem = yield from key_format.encode(key_format.pem(key_format.spki), pair.public_key)
    print(pem.splitlines()[0])
    decoded = yield from S.decode_effect(PublicKeyPem)(pem)
    print(decoded.algorithm.name)

    # Private keys are written back only when asked to.
    error = yield from S.encode_effect(
        CS.SignaturePrivateKeyFromFormat(key_format.pkcs8, signature.ed25519)
    )(pair.private_key).flip()
    print(error)


fx.run_main(main().pipe(fx.provide(native.layer)))

Tokens

pyfect.jose builds JSON Web Signatures, Encryption and Tokens on these services. jwk generates, imports and exports keys and computes thumbprints; jws signs with HS*, RS*, PS*, ES* and EdDSA; jwe encrypts with a shared key; jwt signs or encrypts claims described by a schema and checks them against a policy (subject, issuer, audience, clock tolerance, ...). jwks.layer_remote(url) resolves a token's key from an issuer's key set, cached and refreshed once for an unknown kid. Every failure is a JoseError, and tokens are Redacted.

tokens.py
from typing import TypedDict

import pyfect as fx
from pyfect import redacted
from pyfect import schema as S
from pyfect.crypto import native
from pyfect.jose import JoseError, jwk, jwt


class Claims(TypedDict):
    sub: str
    role: str


ClaimsSchema = S.Struct(Claims)


@fx.fn
def main():
    secret = yield from jwk.generate_secret("HS256", kid="2026-11")
    key = yield from jwk.import_hmac(secret, "HS256")
    token = yield from jwt.sign(ClaimsSchema, {"sub": "ada", "role": "admin"}, key)
    verified = yield from jwt.verify(ClaimsSchema, token, key, subject="ada")
    print(verified.claims, verified.protected_header.get("kid"))

    head, _, signed = redacted.value(token).rpartition(".")
    forged = f"{head}.{'A' * len(signed)}"
    error = yield from jwt.verify(ClaimsSchema, forged, key).flip()
    print(error.reason.tag if isinstance(error, JoseError) else error)


fx.run_main(main().pipe(fx.provide(native.layer)))

Expiring tokens

jwt.sign signs exactly the claims you give it, so an expiring token carries iat and exp itself, as NumericDates in whole seconds, and its claims schema lists them. verify always checks exp and nbf against the Clock; required_claims=["iat", "exp"] also refuses a token without them. To use RFC 7638's thumbprint as the kid, compute it from the generated public JWK and set it on the imported keys with dataclasses.replace (they are frozen dataclasses): sign puts it in the header, and jwk.export_public writes it into the JWK you serve.

expiring_tokens.py
from dataclasses import replace
from typing import TypedDict

import pyfect as fx
from pyfect import clock
from pyfect import schema as S
from pyfect.crypto import native
from pyfect.jose import JoseError, jwk, jwt


class Claims(TypedDict):
    sub: str
    iat: int
    exp: int


ClaimsSchema = S.Struct(Claims)


@fx.fn
def issue(key: jwk.PrivateKey, subject: str, lifetime_seconds: int):
    # `iat` and `exp` are NumericDates, whole seconds, which the claims carry themselves.
    now = int((yield from clock.current_time_millis()) // 1000)
    claims: Claims = {"sub": subject, "iat": now, "exp": now + lifetime_seconds}
    return (yield from jwt.sign(ClaimsSchema, claims, key))


@fx.fn
def main():
    pair = yield from jwk.generate_key_pair("EdDSA")
    # The RFC 7638 thumbprint as `kid`: the imported keys are dataclasses, so
    # `replace` sets it, and `export_public` writes it into the served JWK.
    kid = yield from jwk.thumbprint(pair.public_key)
    signing = replace((yield from jwk.import_private(pair.private_key, "EdDSA")), kid=kid)
    verifying = replace((yield from jwk.import_public(pair.public_key, "EdDSA")), kid=kid)
    print((yield from jwk.export_public(verifying)).get("kid") == kid)

    token = yield from issue(signing, "ada", 3600)
    verified = yield from jwt.verify(
        ClaimsSchema, token, verifying, subject="ada", required_claims=["iat", "exp"]
    )
    print(verified.claims["sub"], verified.protected_header.get("kid") == kid)

    expired = yield from issue(signing, "ada", -60)
    error = yield from jwt.verify(ClaimsSchema, expired, verifying).flip()
    print(error.reason.message if isinstance(error, JoseError) else error)


fx.run_main(main().pipe(fx.provide(native.layer)))

Encrypted tokens

jwt.encrypt seals claims into a compact JWE that only holders of the shared key can read, as for a session token the issuing service opens again itself; jwt.decrypt opens it and checks the claims against the same policy options as verify. jwe.encrypt and jwe.decrypt do the same for any bytes. As in Effect, one algorithm pair is supported: alg dir (the key is used directly, so the token's encrypted-key segment is empty) with enc A256GCM. The key is a 32-byte jwk.DirKey, from jwk.import_dir of a JWK made with jwk.generate_secret("dir"). A token with any other alg or enc, such as A128GCM (RFC 7520 §5.6), or with a zip or crit header, is refused with InvalidToken; a wrong key or a tampered token gives DecryptionFailed.

sessions.py
import base64
import json
from typing import TypedDict

import pyfect as fx
from pyfect import redacted
from pyfect import schema as S
from pyfect.crypto import native
from pyfect.jose import JoseError, jwk, jwt


class Session(TypedDict):
    sub: str
    scope: str


SessionSchema = S.Struct(Session)


def segment(data: dict[str, str]) -> str:
    return base64.urlsafe_b64encode(json.dumps(data).encode()).rstrip(b"=").decode()


@fx.fn
def main():
    # A dir key is 32 random bytes, shared by whoever seals and opens the tokens.
    secret = yield from jwk.generate_secret("dir", kid="sessions-1")
    key = yield from jwk.import_dir(secret)

    token = yield from jwt.encrypt(SessionSchema, {"sub": "ada", "scope": "read"}, key)
    # Five segments; with dir there is no encrypted key, so the second is empty.
    parts = redacted.value(token).split(".")
    print(len(parts), parts[1] == "")
    opened = yield from jwt.decrypt(SessionSchema, token, key)
    print(opened.claims, opened.protected_header)

    # Only dir with A256GCM is supported: any other alg or enc is refused.
    other = ".".join([segment({"alg": "dir", "enc": "A128GCM"}), *parts[1:]])
    error = yield from jwt.decrypt(SessionSchema, other, key).flip()
    print(error.reason.tag if isinstance(error, JoseError) else error)


fx.run_main(main().pipe(fx.provide(native.layer)))

Key sets that change

jwks.layer_local(key_set) reads its key set once. When keys are added or revoked while the app runs, build the service for each request with jwks.make_local(key_set), or write your own JwksService(resolve=...): resolve gets the token's Selection (algorithm, kid, header) and returns the key or fails, here with KeyNotFound for a revoked kid.

key_sets.py
from typing import TypedDict

import pyfect as fx
from pyfect import schema as S
from pyfect.crypto import native
from pyfect.jose import JoseError, jwk, jwks, jwt
from pyfect.jose.jose_error import KeyNotFound
from pyfect.jose.jwks import Jwks, JwksService, Selection


class Claims(TypedDict):
    sub: str


ClaimsSchema = S.Struct(Claims)

# The app's key store: the served public keys, and the kids revoked since.
served: list[jwk.PublicJwk] = []
revoked: set[str] = set()


@fx.fn
def new_key(kid: str):
    pair = yield from jwk.generate_key_pair("EdDSA", kid=kid)
    served.append(pair.public_key)
    return (yield from jwk.import_private(pair.private_key, "EdDSA"))


@fx.fn
def verify(token: fx.Redacted[str]):
    # A key set read for each request sees the keys as they are now.
    key_set = yield from jwks.make_local({"keys": list(served)})

    # A custom resolver refuses a revoked kid before the key set looks.
    def resolve(selection: Selection) -> fx.Effect[jwk.PublicKey, JoseError]:
        if selection.kid in revoked:
            return fx.fail(JoseError(KeyNotFound()))
        return key_set.resolve(selection)

    verifying = jwt.verify_with_key_set(ClaimsSchema, token, algorithms=["EdDSA"])
    verified = yield from verifying.pipe(fx.provide_service(Jwks, JwksService(resolve=resolve)))
    return verified.claims["sub"]


@fx.fn
def main():
    old = yield from new_key("2026-10")
    token = yield from jwt.sign(ClaimsSchema, {"sub": "ada"}, old)
    print((yield from verify(token)))

    rotated = yield from new_key("2026-11")
    print((yield from verify((yield from jwt.sign(ClaimsSchema, {"sub": "bob"}, rotated)))))

    revoked.add("2026-10")
    error = yield from verify(token).flip()
    print(error.reason.tag if isinstance(error, JoseError) else error)


fx.run_main(main().pipe(fx.provide(native.layer)))