Page
Library
Module
Module type
Parameter
Class
Class type
Source
Hybrid Public Key Encryption (RFC 9180) for OCaml. Encrypt to a recipient's public key; decrypt with their private key.
Requires 64-bit OCaml 4.14+ and Dune 3.12+. No release is supported for production use yet. Read the security policy.
In an initialized opam switch:
opam install hpke
mkdir hpke-example
cd hpke-exampleCreate dune-project:
(lang dune 3.12)Create dune:
(executable
(name main)
(libraries hpke mirage-crypto-rng.unix))Create main.ml:
open Hpke
let ( let* ) = Result.bind
let round_trip ~rng =
let suite =
Suite.create ~kem:Kem.X25519 ~kdf:Kdf.Hkdf_sha256
~aead:Aead.Chacha20_poly1305
in
let* private_key, public_key =
generate_key_pair ~rng Kem.X25519
in
let info = "example-v1" and aad = "message-1" in
let* ciphertext =
Rfc9180.seal_base ~rng suite ~recipient:public_key ~info ~aad
~plaintext:"Hello, HPKE."
in
Rfc9180.open_base suite ~recipient:private_key ~info ~aad
~ciphertext
let () =
Mirage_crypto_rng_unix.use_default ();
let rng = Mirage_crypto_rng.default_generator () in
match round_trip ~rng with
| Ok plaintext -> print_endline plaintext
| Error error ->
Format.eprintf "%a@." Error.pp error;
exit 1Run it:
opam exec -- dune exec ./main.exeOutput: Hello, HPKE.
The example keeps both keys in one process. In an application, the sender needs a trusted copy of the recipient's public key; only the recipient needs the private key.
seal_base returns two byte strings: encapsulated_key and ciphertext. Send both; your protocol defines their encoding.info identifies the protocol or purpose. aad is authenticated message metadata. Neither is encrypted or sent by the library; both must match exactly when opening.Need | API |
|---|---|
One independent message |
|
A pre-shared secret |
|
A sender key |
|
Several ordered messages |
|
Derived keys without encryption |
|
The seal, open, setup, and context operations are under Hpke.Rfc9180. Keep context operations serial and messages in order. Single-shot opens report peer-controlled failures as Open_error.
Hpke.Draft_hpke_04 also has SHAKE128 and SHAKE256.ML-KEM and hybrid KEMs support Base and PSK only. Hpke.Draft_hpke_04 implements the successor draft with those two modes; Hpke.Rfc9180 keeps its RFC wire behavior. Hybrid KEMs and Draft_hpke_04 require 0.4.0 or newer; see installation options.
To build this checkout in an initialized opam switch:
opam install . --deps-only --with-test --with-doc
opam exec -- dune build @all @doc
opam exec -- dune runtestISC. Independent implementation; prior OCaml work: FantomeBeignet/ohpke.