- C 91%
- OCaml 9%
- C++ <1%
crypto - Cryptographic primitives for OCaml #
Warning. This is a work-in-progress experimental fork of mirage-crypto. Do not use it in production. As the experiments described under Why this fork stabilise, the intent is to upstream them back to
mirage/mirage-cryptoand retire the fork. Until that happens, usemirage-cryptofrom opam directly for anything you care about.
What this fork adds #
- Vendored crypto kernels with explicit provenance. No kernel in
this fork is written in-house:
scripts/import.mlvendors, from pinned upstream commits, BearSSL's constant-time AES/GHASH fallbacks, HACL*'s formally verified vectorized ChaCha20-Poly1305, AWS-LC's ARMv8 AES/GHASH assembly, and libcrux's formally verified ML-DSA-65 and ML-KEM-768/1024. See Provenance and assurance. - Pure-OCaml AES and GHASH backends.
lib/ocaml/aes_pure.mlis a bitsliced AES encryptor andlib/ocaml/ghash_pure.mla constant-time GHASH over bitwise reduction. Both run under js_of_ocaml where no C compiler is available; upstream mirage-crypto requires C stubs. The OCaml GCM path glues these together so AEAD works in the browser. - Packages renamed and Lwt/Miou bindings dropped. Downstream Eio-based services that cannot pull in Lwt or Miou. Upstream leaks those into the dependency graph under some opam resolutions; this fork renames the packages so both can coexist in the same opam switch.
- Post-quantum cryptography.
crypto-pqprovides ML-DSA-65 (FIPS 204) digital signatures and ML-KEM-768/1024 (FIPS 203) key encapsulation with no upstream equivalent, built on libcrux's formally verified implementation.
The rest of the API mirrors the upstream modules with the packages renamed:
| Upstream | This fork |
|---|---|
mirage-crypto |
crypto |
mirage-crypto-rng |
crypto-rng |
mirage-crypto-rng.unix |
crypto-rng.unix |
mirage-crypto-pk |
crypto-pk |
mirage-crypto-ec |
crypto-ec |
| (no upstream equivalent) | crypto-pq |
Installation #
$ opam install nox-crypto nox-crypto-rng nox-crypto-pk nox-crypto-ec nox-crypto-pq
If opam cannot find the packages, they may not yet be released in the public
opam-repository. Add the overlay repository, then install them:
$ opam repo add samoht https://tangled.org/gazagnaire.org/opam-overlay.git
$ opam update
$ opam install nox-crypto nox-crypto-rng nox-crypto-pk nox-crypto-ec nox-crypto-pq
Usage #
Seed the RNG #
Every key-generation or random-dependent operation fails with
Unseeded_generator until a generator is installed. Call use_default ()
once at program start:
let () = Crypto_rng_unix.use_default ()
On Linux this reads from getrandom(2), on BSD/macOS from getentropy(3),
on Windows 10+ from BCryptGenRandom. Older Windows is unsupported.
AEAD: AES-GCM and ChaCha20-Poly1305 #
let aead_roundtrip () =
let key = Crypto.AES.GCM.of_secret (Crypto_rng.generate 32) in
let nonce = Crypto_rng.generate 12 in
let adata = "headers" in
let plaintext = "secret message" in
let ciphertext =
Crypto.AES.GCM.authenticate_encrypt ~key ~nonce ~adata plaintext
in
match
Crypto.AES.GCM.authenticate_decrypt ~key ~nonce ~adata ciphertext
with
| Some recovered -> assert (recovered = plaintext)
| None -> failwith "authentication failed"
Crypto.Chacha20 and Crypto.AES.CCM16 expose the same AEAD signature.
Mismatched nonce/tag or tampered ciphertext return None -- never raise.
Ed25519 signatures #
let sign_and_verify () =
let priv, pub = Crypto_ec.Ed25519.generate () in
let msg = "approved transfer of 42 units" in
let sig_ = Crypto_ec.Ed25519.sign ~key:priv msg in
assert (Crypto_ec.Ed25519.verify ~key:pub sig_ ~msg);
(* Tampering the message invalidates the signature: *)
assert (not (Crypto_ec.Ed25519.verify ~key:pub sig_ ~msg:"changed"))
ML-DSA-65 signatures (post-quantum) #
let mldsa_sign_and_verify () =
let priv, pub = Crypto_pq.Mldsa65.generate () in
let msg = "approved transfer of 42 units" in
let signature = Crypto_pq.Mldsa65.sign ~key:priv msg in
assert (Crypto_pq.Mldsa65.verify ~key:pub ~signature msg);
(* Tampering the message invalidates the signature: *)
assert (not (Crypto_pq.Mldsa65.verify ~key:pub ~signature "changed"))
Signing is hedged by default (32 bytes of fresh randomness per
signature); pass ~randomness explicitly for the deterministic variant.
An optional ~ctx context string (at most 255 bytes) domain-separates
signatures, and of_seed derives a key pair deterministically from a
32-byte seed.
ML-KEM key encapsulation (post-quantum) #
let mlkem_shared () =
let priv, pub = Crypto_pq.Mlkem768.generate () in
(* The encapsulator derives a fresh shared secret from the public key: *)
let ciphertext, shared = Crypto_pq.Mlkem768.encapsulate pub in
(* The key holder recovers it from the ciphertext: *)
match Crypto_pq.Mlkem768.decapsulate priv ciphertext with
| Ok shared' -> assert (shared = shared')
| Error _ -> failwith "malformed ciphertext"
Crypto_pq.Mlkem1024 exposes the same signature at security category 5.
A tampered but well-sized ciphertext does not error: implicit rejection
(FIPS 203) returns a pseudorandom secret that fails the protocol's
subsequent key-confirmation instead of leaking the mismatch here.
X25519 key exchange #
let x25519_shared () =
let a_priv, a_pub = Crypto_ec.X25519.gen_key () in
let b_priv, b_pub = Crypto_ec.X25519.gen_key () in
let a_shared = Crypto_ec.X25519.key_exchange a_priv b_pub in
let b_shared = Crypto_ec.X25519.key_exchange b_priv a_pub in
assert (a_shared = b_shared)
RSA #
let rsa_encrypt_decrypt () =
let priv = Crypto_pk.Rsa.generate ~bits:2048 () in
let pub = Crypto_pk.Rsa.pub_of_priv priv in
let msg = "short message" in
let ct = Crypto_pk.Rsa.PKCS1.encrypt ~key:pub msg in
match Crypto_pk.Rsa.PKCS1.decrypt ~key:priv ct with
| Some pt -> assert (pt = msg)
| None -> failwith "decrypt failed"
Use Rsa.OAEP or Rsa.PSS for new designs; Rsa.PKCS1 is kept for
compatibility with older protocols and is vulnerable to Bleichenbacher-
style oracle attacks if error paths leak timing.
Modules #
| Package | Module | Purpose |
|---|---|---|
crypto |
Crypto.AES |
AES-128/192/256 in ECB/CBC/CTR/GCM/CCM |
crypto |
Crypto.DES |
DES in ECB/CBC/CTR (legacy) |
crypto |
Crypto.Chacha20 |
ChaCha20-Poly1305 AEAD |
crypto |
Crypto.Poly1305 |
Raw Poly1305 MAC |
crypto |
Crypto.ARC4 |
RC4 stream cipher (legacy) |
crypto-rng |
Crypto_rng |
RNG interface, Fortuna, HMAC-DRBG |
crypto-rng.unix |
Crypto_rng_unix |
OS entropy seeders (getrandom, BCrypt) |
crypto-pk |
Crypto_pk.Rsa |
RSA keygen, PKCS1, OAEP, PSS |
crypto-pk |
Crypto_pk.Dsa |
FIPS 186-4 DSA |
crypto-pk |
Crypto_pk.Dh |
Finite-field Diffie-Hellman |
crypto-ec |
Crypto_ec.P256 / P384 / P521 |
NIST curves (ECDH + ECDSA) |
crypto-ec |
Crypto_ec.X25519 |
Curve25519 ECDH |
crypto-ec |
Crypto_ec.Ed25519 |
Curve25519 EdDSA |
crypto-pq |
Crypto_pq.Mldsa65 |
ML-DSA-65 signatures (FIPS 204) |
crypto-pq |
Crypto_pq.Mlkem768 / Mlkem1024 |
ML-KEM key encapsulation (FIPS 203) |
Provenance and assurance #
No cryptographic kernel in this fork is written in-house: kernels are
inherited from upstream mirage-crypto, or vendored verbatim from
formally verified or hardened production code. The import is pinned to
single upstream commits and reproducible byte-for-byte
(scripts/import.ml, with a clean subcommand): every vendored file
carries a provenance stamp, and the importer reads the exact blobs
recorded at the pinned commits, never a working tree.
By kernel family, strongest guarantee first:
- ChaCha20-Poly1305, vectorized (
lib/c/hacl/, from HACL*): C extracted from F* with machine-checked proofs of memory safety, functional correctness against the RFC 8439 specification, and secret independence (no branches or memory accesses on secrets). Compiles to NEON on AArch64 and AVX/AVX2 on x86-64; dispatched automatically,NOX_CRYPTO_NO_SIMDforces the generic path. The generic fallback is mirage-crypto's scalar C (poly1305-donna lineage), unverified. - ML-DSA-65 and ML-KEM-768/1024 (
lib/pq/libcrux_mldsa/andlib/pq/libcrux_mlkem/, from libcrux): code extracted from libcrux's verified Rust implementation through Charon/Eurydice/KaRaMeL, carrying machine-checked proofs of panic freedom and functional correctness against the FIPS 204 and FIPS 203 specifications; the generating tool revisions are recorded in each tree'scode_gen.txt. ML-DSA is portable everywhere with AVX2 on x86-64 under runtime dispatch; ML-KEM uses the portable C extraction (the only pre-generated flavor covering both parameter sets). The test suite enforces NIST ACVP vectors: FIPS 204 key generation, deterministic and hedged signing and tampered-signature rejection; FIPS 203 key generation, encapsulation, decapsulation with implicit rejection, and the Section 7 key checks. - P-256/P-384/P-521 field arithmetic (inherited from upstream): constant-time code generated by fiat-crypto, whose generator carries machine-checked correctness proofs.
- AES/GHASH, ARMv8 (
lib/c/awslc/, from AWS-LC): the OpenSSL-lineage aes_hw / PMULL GHASH assembly as maintained in AWS-LC. Machine- checked verification of these kernels is in progress upstream in s2n-bignum (PMULL model and the gcm_gmult_v8 proof first), so this path is opt-in: it only activates whenNOX_CRYPTO_ARMV8_AESis set in the environment. Until then AArch64 AES-GCM defaults to the constant-time fallback below. The default will flip once the proofs land. - AES/GHASH, x86-64 (inherited from upstream): mirage-crypto's hand-tuned AES-NI and PCLMUL paths; unverified, widely deployed.
- AES/GHASH, constant-time fallback (
lib/c/bearssl/, from BearSSL): the bitslicedaes_ct64andghash_ctmul64implementations -- carefully audited, constant-time by construction, but carrying no formal proof. This is the default on every CPU without the accelerated paths above.
What the tests enforce: the full vector suite (NIST, RFC 8439,
Wycheproof EC) runs on the default dispatch, re-runs with
NOX_CRYPTO_NO_SIMD=1, and re-runs with NOX_CRYPTO_ARMV8_AES=1; and
a differential harness (test/hacl_diff.ml) drives the vectorized and
generic ChaCha20-Poly1305 over stride- and counter-boundary-crossing
inputs and requires byte-identical transcripts.
Side-channel notes #
Inherited from upstream: RSA operations use blinding; AES operations
delegate to AES-NI when available (Crypto.accelerated lists detected
capabilities); P-256/P-384/P-521 point arithmetic uses constant-time code
generated by fiat-crypto. This fork has not been re-audited; if a
side-channel property matters to you, verify against upstream mirage-crypto
and its review history.
ML-DSA-65 and ML-KEM-768/1024 inherit libcrux's analysis: the verified Rust the code is extracted from is written to be secret independent, ML-KEM decapsulation rejects implicitly in constant time, and ML-DSA signing is hedged by default so faults or randomness reuse degrade towards the deterministic variant rather than leaking the key.
Why this fork #
The fork exists so we can explore the design space without churning
upstream. Three pieces of work that mirage-crypto does not ship today:
- A BearSSL-based constant-time AES fallback for platforms without AES-NI or equivalent hardware.
- Pure-OCaml AES and GHASH so AEAD works under js_of_ocaml with no C stubs.
- Post-quantum cryptography (
crypto-pq): ML-DSA-65 signatures and ML-KEM-768/1024 key encapsulation on libcrux's formally verified extraction, with the NIST ACVP vectors enforced in the test suite.
The package-renaming and Lwt/Miou-removal is bookkeeping needed so the
fork can live alongside upstream in the same opam switch while the above
two pieces stabilise. Once they hold up under review and interop testing,
the intent is to propose upstreaming them to mirage/mirage-crypto; if
upstream agrees, this fork stops being a fork and the renamed packages
get deprecated.
No primitive algorithms are modified. Anything this fork gets wrong is upstream's fault, and anything this fork gets right is upstream's credit -- apart from the additions above, which are the point of the fork.
Licence #
ISC. See LICENSE.md for the original mirage-crypto notice and LICENSE.md.mirage-crypto-ec and LICENSE.md.mirage-crypto-rng-mirage for upstream-specific licence text.