diff --git a/README.md b/README.md index 72c5b38..0209cf4 100644 --- a/README.md +++ b/README.md @@ -30,8 +30,10 @@ MSVC), wasip2, wasip3 and Emscripten. and PKCS#8, `formats::pem`, codecs' armor over the DER with its label in its type, each decoded strictly, and an input past a format's bound refused as `codecs::error::input_too_long`. - `webcpp::crypto::public_key_encryption`: NaCl's and libsodium's boxes between two key pairs - (`box`, `box_xchacha20poly1305`), refusing a peer key of small order, and sealed boxes - (`sealed_box`), anonymous encryption to a public key. + (`box`, `box_xchacha20poly1305`), refusing a peer key of small order, sealed boxes + (`sealed_box`), anonymous encryption to a public key, and RFC 9180's HPKE + (`hpke::suite`), composed from X25519 or P-256, webcpp::hash's HKDF and AES-GCM or + ChaCha20-Poly1305, in its four modes, as MLS and Marmot use it. - `webcpp::crypto::key_exchange`: `kx_keypair`, libsodium's `crypto_kx`, a session key for each direction of a client and a server. diff --git a/doc/async.adoc b/doc/async.adoc index d0dcd42..102e6f2 100644 --- a/doc/async.adoc +++ b/doc/async.adoc @@ -179,6 +179,14 @@ include::{examples}/async_sign.cpp[tag=program,indent=0] include::{examples}/async_sign.expected[] ---- +HPKE's setups, single-shot calls, contexts' `seal` and `open` and +`derive_from_seed` have their asynchronous forms too, the synchronous arguments +between the executor and the completion token: `hpke::async_begin_sending(executor, +recipient_public_key, application_info, token)` completes with the sender's +context, and `sender.async_seal(executor, associated_data, plaintext, +ciphertext, token)` with the seal's code (<>). WebCrypto has no +HPKE: on the browser's backend they stop the build. + *The completion's value on an error.* A value that is a keyed object or a secret has no meaning when the call failed, and the completion gives the empty object a move leaves: a `gcm` or a key pair without a key, a `secure::secret<32>` diff --git a/doc/backends.adoc b/doc/backends.adoc index 7399575..a171a07 100644 --- a/doc/backends.adoc +++ b/doc/backends.adoc @@ -227,8 +227,18 @@ One measurement is an open finding, listed under the table with its numbers: libsodium's X25519 `agree` under wasmtime, on wasip2. Its cause is measured: wasmtime does not set DIT, and with DIT set in wasmtime's main thread, an experiment and not the lane, the case passes. The WebAssembly cannot set it, -so the lane prints its value on wasip2 without judging it, and judges -everything else. +so the lane prints its value on wasip2 without judging it. + +On a WASI target the lane prints every case of `dudect_bearssl` (BearSSL's +AEADs and P-256, ctaes, `secure::constant_time_equal` and hash's Base58Check +decode) and judges none of them, by the owner's decision of 2026-12-04: under +wasmtime their timing follows the processor of the runner, not the code +measured. On GitHub's hosted AMD EPYC 9V74, wasip2 runs read |t| 30 to 150 on +`secure::constant_time_equal` and 11 to 12 on AES-GCM's seal and on ctaes, +failing changes that touched none of them, so a verdict there would pass or +fail with the machine drawn. The lane judges everything else: every program +natively, and under wasmtime `dudect_sodium` (X25519's agreement excepted) and +`dudect_secp256k1`. dudect's two classes differ in the secret's bytes and in nothing else: the preparation of each measurement reads both inputs and writes the secret with @@ -247,7 +257,8 @@ program but `dudect_planted` also measures an A/A control case, whose classes are prepared by the same instructions with the same value: it shows what the machine itself does. Valgrind's memcheck and MemorySanitizer, which do not measure time, are judged there; dudect is judged by the program itself -wherever else the lane runs, on a machine of one's own, in one process. +wherever else the lane runs, on a machine of one's own, in one process, except +`dudect_bearssl` on a WASI target, which judges none of its cases. Whether a tag matched, or a shared secret came out all zero, is public by design, since the operation reports it, but it is computed from the secrets: it diff --git a/doc/changelog.adoc b/doc/changelog.adoc index e4a20b9..9abcdfd 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -20,10 +20,10 @@ of every version are on webcpp's index page. * *Breaking change:* Changed the key formats into codecs formats: `codecs::encode`, `codecs::decode` and members replace encode_spki, to_der and their kin, `formats::max_encoded_size` their sizes, and `formats::pem` replaces `crypto::pem` and pem-default. * *Breaking change:* Changed the schemes into `crypto::signing_schemes`; every verification, `recover` and `can_verify` takes a policy after the scheme, `low_s_only`, `any_s` or `canonical` (Ed25519's former `strict`). * *Breaking change:* Changed low S into signatures' `is_low_s()` and `low_s()`, free tweak_xonly, span Schnorr verify and `xonly()` bytes into the typed `xonly_public_key`, and secp256k1's SPKI default to uncompressed. -* Changed PEM: its label is in its type, a PEM result is exactly as long as its longest text, and a hand-built armor over a key format does not build. -* Changed PEM decode: through codecs' over, in place; an input past a format's bound is codecs' `input_too_long` on every path. -* Added crypto, C-backed primitives on webcpp::secure's guard (DIT on arm64): errors 1 to 20, `+[[nodiscard]]+` results, typed signatures, key pair concepts, factories, WEBCPP_CRYPTO_HAS_THREADS, Asio's asynchronous functions. +* Changed PEM: its label is in its type, its result as long as its longest text, its decode in place through codecs' over, and a hand-built armor fails to build. +* Added crypto, C-backed primitives on webcpp::secure's guard (DIT on arm64): errors 1 to 21, `+[[nodiscard]]+` results, typed signatures, key pair concepts, factories, WEBCPP_CRYPTO_HAS_THREADS, Asio's asynchronous functions. * Added random_device, the AES block ciphers, ciphers::gcm, per-target defaults, backends::bearssl (AES-GCM, ChaCha20-Poly1305, curves::p256 keys, low-S ECDSA, agree), backends::openssl and backends::ctaes. * Added curves::secp256k1 (ECDSA, recoverable ECDSA, BIP 340 Schnorr, agree, tweaks, ElligatorSwift, MuSig2, silent payments), and curves::ed25519 and curves::x25519 on libsodium, Ed25519's verification canonical. +* Added public_key_encryption::hpke, RFC 9180's HPKE on X25519 or P-256, HKDF, and AES-GCM or ChaCha20-Poly1305. * Added backends::sodium, ChaCha20-Poly1305 AEADs, secretbox, boxes, sealed boxes, kx_keypair, and the page: chapters per namespace and use case, generated tables, Jamfiles, messages, llms.txt, measurements. // end::unreleased[] diff --git a/doc/errors.adoc b/doc/errors.adoc index 0284841..4d89175 100644 --- a/doc/errors.adoc +++ b/doc/errors.adoc @@ -59,6 +59,8 @@ the format allows. An input longer than the pair's bound is codecs' `input_too_long`, not this. A `raw` or a `der` gives the key's or the signature's own error, and the armor's own faults are codecs' (below). |20 |`invalid_ciphertext_size` |A KEM or RSA ciphertext of another size than the key's. +|21 |`message_limit_reached` |An HPKE context has sealed or opened as many messages as its nonce +allows: its 64-bit sequence number reached 2^64^ - 1 (RFC 9180's `MessageLimitReachedError`). |=== A value that `error` does not define diff --git a/doc/generated/backends-aes_block.adoc b/doc/generated/backends-aes_block.adoc index 653c894..866a636 100644 --- a/doc/generated/backends-aes_block.adoc +++ b/doc/generated/backends-aes_block.adoc @@ -21,12 +21,12 @@ The backends of `+ciphers::aes128+`, `+aes192+`, `+aes256+`, from the test progr |OpenSSL |`+/webcpp/crypto//openssl+` |`++` -|native, wasip2, wasip3 (tested by `+aes_openssl+`, `+agreement_aes+`); not on emscripten: `+/webcpp/crypto//openssl+` stops the build there +|native, wasip2, wasip3 (tested by `+aes_openssl+`, `+agreement_aes+`, `+quic_rfc9001_openssl+`); not on emscripten: `+/webcpp/crypto//openssl+` stops the build there |ctaes |`+/third_party//ctaes+` |`++` -|native, wasip2, wasip3, emscripten (tested by `+aes_ctaes+`, `+agreement_aes+`) +|native, wasip2, wasip3, emscripten (tested by `+aes_ctaes+`, `+agreement_aes+`, `+quic_rfc9001_bearssl+`) |=== `+aes128<>+`, `+aes192<>+` and `+aes256<>+` name the default backend; `+gcm>+` names AES-GCM's. The default per target, whatever the program links, as <> gives it with its reasons and tests: diff --git a/doc/generated/backends-gcm.adoc b/doc/generated/backends-gcm.adoc index 1db54a1..a4be9c3 100644 --- a/doc/generated/backends-gcm.adoc +++ b/doc/generated/backends-gcm.adoc @@ -16,12 +16,12 @@ The backends of `+ciphers::gcm+`, `+aes128_gcm+`, `+aes256_gcm+`, from the test |BearSSL |`+/third_party//bearssl+` |`++` -|native, wasip2, wasip3, emscripten (tested by `+gcm_bearssl+`, `+gcm_wycheproof_bearssl+`, `+agreement_gcm+`, `+agreement_gcm_portable+`) +|native, wasip2, wasip3, emscripten (tested by `+gcm_bearssl+`, `+gcm_wycheproof_bearssl+`, `+agreement_gcm+`, `+agreement_gcm_portable+`, `+quic_rfc9001_bearssl+`) |OpenSSL |`+/webcpp/crypto//openssl+` |`++` -|native, wasip2, wasip3 (tested by `+gcm_openssl+`, `+gcm_wycheproof_openssl+`, `+agreement_gcm+`, `+agreement_gcm_portable+`); not on emscripten: `+/webcpp/crypto//openssl+` stops the build there +|native, wasip2, wasip3 (tested by `+gcm_openssl+`, `+gcm_wycheproof_openssl+`, `+agreement_gcm+`, `+agreement_gcm_portable+`, `+quic_rfc9001_openssl+`); not on emscripten: `+/webcpp/crypto//openssl+` stops the build there |ctaes |`+/third_party//ctaes+` diff --git a/doc/generated/backends-hpke.adoc b/doc/generated/backends-hpke.adoc new file mode 100644 index 0000000..21917e2 --- /dev/null +++ b/doc/generated/backends-hpke.adoc @@ -0,0 +1,25 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, +// the message tests and the Jamfile fixtures: run it again, never edit this file. + +The backends of `+public_key_encryption::hpke::suite+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|BearSSL +|`+/third_party//bearssl+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+hpke_vectors_bearssl+`, `+hpke_async+`, `+hpke_allocation+`, `+timing_coverage_bearssl+`) + +|libsodium +|`+/third_party//sodium+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+hpke_vectors_default+`, `+hpke+`, `+hpke_async+`, `+hpke_allocation+`, `+timing_coverage_sodium+`) +|=== diff --git a/doc/generated/constant-time.adoc b/doc/generated/constant-time.adoc index e181586..32edb66 100644 --- a/doc/generated/constant-time.adoc +++ b/doc/generated/constant-time.adoc @@ -14,7 +14,7 @@ |BearSSL |by design: `+aes_ct64+` and `+ghash_ctmul64+`, or AES-NI and PCLMUL where the CPU has them; on a 32-bit host a 64-bit multiplication may not be constant time, which BearSSL documents; ECDSA signing at webcpp's pin, whose patch submitted upstream closes upstream's leak of the RFC 6979 nonce's bit length (link:https://www.bearssl.org/gitweb/?p=BearSSL;a=blob;f=src/ec/ecdsa_i31_bits.c;hb=7bea48e5e850ab4cafbe68d3765cdaba13a86d6f#l44[BearSSL's ecdsa_i31_bits.c at upstream 7bea48e, lines 44 and 45: the nonce decoded with its actual bit length in the integer's header, then shifted over the words that length needs]; link:https://minerva.crocs.fi.muni.cz/[Minerva: the leak of an ECDSA nonce's bit length through timing, and the lattice that recovers the key (CVE-2019-15809)]; the patch: link:https://github.com/webcpporg/bearssl/commit/ae63032d9f30bf53674db5445875adf71b8626b7[webcpporg/bearssl, commit ae63032 on its branch upstream/ecdsa-bits2int-constant-time, one of the two patches of webcpp's pin f8a2f3d (upstream 7bea48e plus exactly the patches submitted upstream): br_ecdsa_i31_bits2int and br_ecdsa_i15_bits2int setting the integer's header, before the right shift, to the larger of the decoded bit length and the order's, both public; the pin returns to upstream once upstream applies it]); P-256's `+mul+`, which ECDH calls, at webcpp's pin, whose other patch submitted upstream removes the jump on the secret scalar that Clang makes on x86-64 of upstream's scalar check (link:https://www.bearssl.org/gitweb/?p=BearSSL;a=blob;f=src/ec/ec_p256_m62.c;hb=7bea48e5e850ab4cafbe68d3765cdaba13a86d6f#l1623[BearSSL's ec_p256_m62.c at upstream 7bea48e, lines 1623 to 1627: the scalar compared with the order through masks that Clang on x86-64 compiles into a conditional jump on the comparison so far]; the patch: link:https://github.com/webcpporg/bearssl/commit/ec57f886ee0a0783acfca1b465b43ccd62b71046[webcpporg/bearssl, commit ec57f88 on its branch upstream/ec-p256-check-scalar-constant-time, the other patch of webcpp's pin f8a2f3d: check_scalar in ec_p256_m62.c and ec_p256_m64.c computing 0 < k < n as k - 1 < n - 1 with two borrow chains, no select for a compiler to turn into a jump; the pin returns to upstream once upstream applies it]); link:https://www.bearssl.org/constanttime.html[BearSSL, constant-time crypto]; link:https://www.bearssl.org/ctmul.html[BearSSL, constant-time multiplications] |Valgrind's memcheck (Linux): AES-GCM, ChaCha20-Poly1305, P-256 (the key pair's making, `+sign+` of a digest (`+crypto::signing_schemes::prehashed+`), which makes its signature low S without a branch, then `+low_s()+` and `+is_low_s()+` of it, `+agree+` and the private formats, `+pkcs8+`, `+raw+` and `+pem(pkcs8)+` both ways; BearSSL's own branches on its signing's verdicts listed in `+bearssl_verdicts.supp+`; nothing found at webcpp's pin f8a2f3d, whose patches submitted upstream close upstream's leak of the nonce's bit length in `+sign+` that this checker found on 2026-11-21 and the jump on the scalar in P-256's scalar check that it found under `+agree+` on the x86-64 runner on 2026-12-03, `+sign+` with its low-S step included (Valgrind 3.22, arm64 Linux container, 2026-12-02; x86-64, `+ctgrind+` and `+ctgrind_space+`, 2026-12-04)); MemorySanitizer (Linux, clang): AES-GCM, ChaCha20-Poly1305, P-256 (the same paths as memcheck's; the same leak in `+sign+` on 2026-11-21 on upstream's BearSSL, nothing at webcpp's pin ae63032, `+sign+` with its low-S step included (clang 18, arm64 Linux container, 2026-12-02); MemorySanitizer checks the select of P-256's scalar check before the code generator makes it a jump, so the second patch changes nothing it sees); dudect (judged; on a runner GitHub hosts, by two of three runs): AES-GCM, ChaCha20-Poly1305, P-256 (`+sign+` of a digest and `+agree+`, each against the key pair's scalar; `+sign+` with its low-S step judged constant time, \|t\| 1.70 on Linux and 1.63 natively on an Apple M5 Max (release, one run each, 2026-11-22; provisional, measured again in the final quiet pass)) -|dudect (judged; on a runner GitHub hosts, by two of three runs): AES-GCM, ChaCha20-Poly1305, P-256 (`+sign+` of a digest and `+agree+`, each against the key pair's scalar; `+sign+` with its low-S step judged constant time, \|t\| 1.70 on Linux and 1.63 natively on an Apple M5 Max (release, one run each, 2026-11-22; provisional, measured again in the final quiet pass)) +|dudect (printed, not judged: under wasmtime its timing follows the runner's processor): AES-GCM, ChaCha20-Poly1305, P-256 |not measured yet |not measured yet @@ -28,7 +28,7 @@ |ctaes |by design: bitsliced, no table and no branch on secret data; link:https://github.com/bitcoin/bitcoin/tree/master/src/crypto/ctaes[ctaes, constant-time AES] |Valgrind's memcheck (Linux): AES block cipher; MemorySanitizer (Linux, clang): AES block cipher; dudect (judged; on a runner GitHub hosts, by two of three runs): AES block cipher -|dudect (judged; on a runner GitHub hosts, by two of three runs): AES block cipher +|dudect (printed, not judged: under wasmtime its timing follows the runner's processor): AES block cipher |not measured yet |not measured yet @@ -55,8 +55,8 @@ |no backend |webcpp::secure's `+secure::constant_time_equal+`, which crypto's code calls, is constant time in the contents: every byte is read, no branch and no index depends on one -|Valgrind's memcheck (Linux): `+secure::constant_time_equal+`, `+is_all_zero+` and the wipe of `+secure::secret+`; MemorySanitizer (Linux, clang): `+secure::constant_time_equal+`, `+is_all_zero+` and the wipe of `+secure::secret+`; dudect (judged; on a runner GitHub hosts, by two of three runs): `+secure::constant_time_equal+` -|dudect (judged; on a runner GitHub hosts, by two of three runs): `+secure::constant_time_equal+` +|Valgrind's memcheck (Linux): `+secure::constant_time_equal+`, `+is_all_zero+` and the wipe of `+secure::secret+`, HPKE's composition, `+public_key_encryption::hpke+`: its key schedule over webcpp::hash's HKDF, the setups in base and auth_psk mode, seal, open and export, on X25519 with ChaCha20-Poly1305 (libsodium) and P-256 with AES-128-GCM (BearSSL); MemorySanitizer (Linux, clang): `+secure::constant_time_equal+`, `+is_all_zero+` and the wipe of `+secure::secret+`, HPKE's composition, `+public_key_encryption::hpke+`: its key schedule over webcpp::hash's HKDF, the setups in base and auth_psk mode, seal, open and export, on X25519 with ChaCha20-Poly1305 (libsodium) and P-256 with AES-128-GCM (BearSSL); dudect (judged; on a runner GitHub hosts, by two of three runs): `+secure::constant_time_equal+`, HPKE's composition, `+public_key_encryption::hpke+`: its key schedule over webcpp::hash's HKDF, the setups in base and auth_psk mode, seal, open and export, on X25519 with ChaCha20-Poly1305 (libsodium) and P-256 with AES-128-GCM (BearSSL) +|dudect (printed, not judged: under wasmtime its timing follows the runner's processor): `+secure::constant_time_equal+`, HPKE's composition, `+public_key_encryption::hpke+`: its key schedule over webcpp::hash's HKDF, the setups in base and auth_psk mode, seal, open and export, on X25519 with ChaCha20-Poly1305 (libsodium) and P-256 with AES-128-GCM (BearSSL) |not measured yet |not measured yet |=== diff --git a/doc/generated/matrix.adoc b/doc/generated/matrix.adoc index 84570ba..a356d55 100644 --- a/doc/generated/matrix.adoc +++ b/doc/generated/matrix.adoc @@ -59,22 +59,22 @@ |`+ciphers::aes128+`, `+aes192+`, `+aes256+` |OpenSSL |native, wasip2, wasip3; not on emscripten: `+/webcpp/crypto//openssl+` stops the build there -|`+aes_openssl+`, `+agreement_aes+` +|`+aes_openssl+`, `+agreement_aes+`, `+quic_rfc9001_openssl+` |`+ciphers::aes128+`, `+aes192+`, `+aes256+` |ctaes |native, wasip2, wasip3, emscripten -|`+aes_ctaes+`, `+agreement_aes+` +|`+aes_ctaes+`, `+agreement_aes+`, `+quic_rfc9001_bearssl+` |`+ciphers::gcm+`, `+aes128_gcm+`, `+aes256_gcm+` |BearSSL |native, wasip2, wasip3, emscripten -|`+gcm_bearssl+`, `+gcm_wycheproof_bearssl+`, `+agreement_gcm+`, `+agreement_gcm_portable+` +|`+gcm_bearssl+`, `+gcm_wycheproof_bearssl+`, `+agreement_gcm+`, `+agreement_gcm_portable+`, `+quic_rfc9001_bearssl+` |`+ciphers::gcm+`, `+aes128_gcm+`, `+aes256_gcm+` |OpenSSL |native, wasip2, wasip3; not on emscripten: `+/webcpp/crypto//openssl+` stops the build there -|`+gcm_openssl+`, `+gcm_wycheproof_openssl+`, `+agreement_gcm+`, `+agreement_gcm_portable+` +|`+gcm_openssl+`, `+gcm_wycheproof_openssl+`, `+agreement_gcm+`, `+agreement_gcm_portable+`, `+quic_rfc9001_openssl+` |`+ciphers::gcm+`, `+aes128_gcm+`, `+aes256_gcm+` |ctaes @@ -221,6 +221,16 @@ |native, wasip2, wasip3, emscripten |`+box_sodium+`, `+allocation_sodium+` +|`+public_key_encryption::hpke::suite+` +|BearSSL +|native, wasip2, wasip3, emscripten +|`+hpke_vectors_bearssl+`, `+hpke_async+`, `+hpke_allocation+`, `+timing_coverage_bearssl+` + +|`+public_key_encryption::hpke::suite+` +|libsodium +|native, wasip2, wasip3, emscripten +|`+hpke_vectors_default+`, `+hpke+`, `+hpke_async+`, `+hpke_allocation+`, `+timing_coverage_sodium+` + |`+curves::secp256k1::recover+` |libsecp256k1 |native, wasip2, wasip3, emscripten @@ -499,6 +509,12 @@ The same, by target: the backends each operation runs on. |libsodium |libsodium +|`+public_key_encryption::hpke::suite+` +|BearSSL, libsodium +|BearSSL, libsodium +|BearSSL, libsodium +|BearSSL, libsodium + |`+curves::secp256k1::recover+` |libsecp256k1 |libsecp256k1 diff --git a/doc/generated/messages.adoc b/doc/generated/messages.adoc index 28d97be..72b70f7 100644 --- a/doc/generated/messages.adoc +++ b/doc/generated/messages.adoc @@ -475,6 +475,78 @@ The fix: Call the synchronous operation the message names, or build with threads The fix: As `+heavy_without_threads+`. +|`+hpke_async_asynchronous_backend+` +|native, wasip2, wasip3 +|`+webcpp::crypto: WebCrypto has no HPKE; the asynchronous HPKE calls run on a native backend.+` + +The fix: WebCrypto has no HPKE: name a native backend for the suite, as `+hpke::suite<..., backends::sodium>+`, or call the synchronous forms. + +|`+hpke_ciphers_type_as_cipher+` +|native, wasip2, wasip3 +|`+constraints not satisfied for class template 'suite'+` + +The fix: Name the cipher by its HPKE tag, `+hpke::cipher::aes128_gcm+`, which wraps `+ciphers::aes128_gcm+`. + +|`+hpke_context_copied+` +|native, wasip2, wasip3 +|`+call to deleted constructor of+` + +The fix: A context is moved, never copied: a copy would reuse its nonces. Keep one context per stream and `+std::move+` it. + +|`+hpke_context_seal_export_only+` +|native, wasip2, wasip3 +|`+webcpp::crypto: an export-only HPKE suite only exports: it has no seal or open. Call export_secret, or name a cipher that seals (hpke::cipher::aes128_gcm, aes256_gcm or chacha20_poly1305).+` + +The fix: As `+hpke_seal_export_only+`: an export-only suite's contexts only export. + +|`+hpke_export_length+` +|native, wasip2, wasip3 +|`+webcpp::crypto: an HPKE export is 1 to 255 times the key derivation's hash size bytes (Suite::max_export_size).+` + +The fix: An export is 1 to `+Suite::max_export_size+` bytes (255 times the hash size); for a length known at run time, `+export_secret(purpose, output)+`. + +|`+hpke_open_on_sender+` +|native, wasip2, wasip3 +|`+no member named 'open' in+` + +The fix: A sender's context only seals: open with the recipient's context, which `+begin_receiving+` makes from the sender's `+encapsulated_key()+`. + +|`+hpke_p256_key_x25519_suite+` +|native, wasip2, wasip3 +|`+webcpp::crypto: hpke begin_sending takes one of four argument lists, the mode following from them: (recipient_public_key, application_info) for base; (recipient_public_key, application_info, pre_shared_key) for psk; (recipient_public_key, application_info, sender_keypair) for auth; (recipient_public_key, application_info, pre_shared_key, sender_keypair) for auth_psk; each key of the suite's own types, the pre-shared key written hpke::pre_shared_key{key, id}.+` + +The fix: A suite takes the keys of its key encapsulation's curve, `+Suite::public_key_type+`: an X25519 suite takes X25519 keys, and a P-256 suite such as `+p256_hkdf_sha256+` takes P-256 keys. + +|`+hpke_psk_after_sender+` +|native, wasip2, wasip3 +|`+webcpp::crypto: hpke begin_sending takes one of four argument lists, the mode following from them: (recipient_public_key, application_info) for base; (recipient_public_key, application_info, pre_shared_key) for psk; (recipient_public_key, application_info, sender_keypair) for auth; (recipient_public_key, application_info, pre_shared_key, sender_keypair) for auth_psk; each key of the suite's own types, the pre-shared key written hpke::pre_shared_key{key, id}.+` + +The fix: The pre-shared key comes before the sender's key, as RFC 9180's `+SetupAuthPSKS(pkR, info, psk, psk_id, skS)+`. + +|`+hpke_receiving_sender_keypair+` +|native, wasip2, wasip3 +|`+webcpp::crypto: hpke begin_receiving takes one of four argument lists, the mode following from them: (encapsulated_key, recipient_keypair, application_info) for base; (encapsulated_key, recipient_keypair, application_info, pre_shared_key) for psk; (encapsulated_key, recipient_keypair, application_info, sender_public_key) for auth; (encapsulated_key, recipient_keypair, application_info, pre_shared_key, sender_public_key) for auth_psk; each key of the suite's own types, the pre-shared key written hpke::pre_shared_key{key, id}.+` + +The fix: Give the recipient the sender's public key, `+sender_keypair.public_key()+`, never the sender's key pair. + +|`+hpke_seal_export_only+` +|native, wasip2, wasip3 +|`+webcpp::crypto: an export-only HPKE suite only exports: it has no seal or open. Call export_secret, or name a cipher that seals (hpke::cipher::aes128_gcm, aes256_gcm or chacha20_poly1305).+` + +The fix: An export-only suite only exports: call `+begin_sending+` and `+export_secret+`, or name a cipher that seals, `+hpke::cipher::aes128_gcm+`, `+aes256_gcm+` or `+chacha20_poly1305+`. + +|`+hpke_sending_sender_public_key+` +|native, wasip2, wasip3 +|`+webcpp::crypto: hpke begin_sending takes one of four argument lists, the mode following from them: (recipient_public_key, application_info) for base; (recipient_public_key, application_info, pre_shared_key) for psk; (recipient_public_key, application_info, sender_keypair) for auth; (recipient_public_key, application_info, pre_shared_key, sender_keypair) for auth_psk; each key of the suite's own types, the pre-shared key written hpke::pre_shared_key{key, id}.+` + +The fix: Auth mode authenticates the sender by its key pair: pass `+sender_keypair+` to `+begin_sending+`, its public key to `+begin_receiving+`. + +|`+hpke_span_as_pre_shared_key+` +|native, wasip2, wasip3 +|`+webcpp::crypto: hpke begin_sending takes one of four argument lists, the mode following from them: (recipient_public_key, application_info) for base; (recipient_public_key, application_info, pre_shared_key) for psk; (recipient_public_key, application_info, sender_keypair) for auth; (recipient_public_key, application_info, pre_shared_key, sender_keypair) for auth_psk; each key of the suite's own types, the pre-shared key written hpke::pre_shared_key{key, id}.+` + +The fix: Write the pre-shared key with its id, `+hpke::pre_shared_key{key, id}+`. + |`+hybrid_header_removed+` |native, wasip2, wasip3 |`+'webcpp/crypto/hybrid/box.hpp' file not found+` @@ -2154,6 +2226,54 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |As `+heavy_without_threads+`. +|`+hpke_async_asynchronous_backend+` +|the compile +|WebCrypto has no HPKE: name a native backend for the suite, as `+hpke::suite<..., backends::sodium>+`, or call the synchronous forms. + +|`+hpke_ciphers_type_as_cipher+` +|the compile +|Name the cipher by its HPKE tag, `+hpke::cipher::aes128_gcm+`, which wraps `+ciphers::aes128_gcm+`. + +|`+hpke_context_copied+` +|the compile +|A context is moved, never copied: a copy would reuse its nonces. Keep one context per stream and `+std::move+` it. + +|`+hpke_context_seal_export_only+` +|the compile +|As `+hpke_seal_export_only+`: an export-only suite's contexts only export. + +|`+hpke_export_length+` +|the compile +|An export is 1 to `+Suite::max_export_size+` bytes (255 times the hash size); for a length known at run time, `+export_secret(purpose, output)+`. + +|`+hpke_open_on_sender+` +|the compile +|A sender's context only seals: open with the recipient's context, which `+begin_receiving+` makes from the sender's `+encapsulated_key()+`. + +|`+hpke_p256_key_x25519_suite+` +|the compile +|A suite takes the keys of its key encapsulation's curve, `+Suite::public_key_type+`: an X25519 suite takes X25519 keys, and a P-256 suite such as `+p256_hkdf_sha256+` takes P-256 keys. + +|`+hpke_psk_after_sender+` +|the compile +|The pre-shared key comes before the sender's key, as RFC 9180's `+SetupAuthPSKS(pkR, info, psk, psk_id, skS)+`. + +|`+hpke_receiving_sender_keypair+` +|the compile +|Give the recipient the sender's public key, `+sender_keypair.public_key()+`, never the sender's key pair. + +|`+hpke_seal_export_only+` +|the compile +|An export-only suite only exports: call `+begin_sending+` and `+export_secret+`, or name a cipher that seals, `+hpke::cipher::aes128_gcm+`, `+aes256_gcm+` or `+chacha20_poly1305+`. + +|`+hpke_sending_sender_public_key+` +|the compile +|Auth mode authenticates the sender by its key pair: pass `+sender_keypair+` to `+begin_sending+`, its public key to `+begin_receiving+`. + +|`+hpke_span_as_pre_shared_key+` +|the compile +|Write the pre-shared key with its id, `+hpke::pre_shared_key{key, id}+`. + |`+hybrid_header_removed+` |the compile |Include `++` for `+box+` and `+box_xchacha20poly1305+`, `++` for `+sealed_box+`, `++` for `+kx_keypair+`; the old directory is kept free for post-quantum hybrids. diff --git a/doc/generated/namespace-ciphers.adoc b/doc/generated/namespace-ciphers.adoc index ddafec7..18195ae 100644 --- a/doc/generated/namespace-ciphers.adoc +++ b/doc/generated/namespace-ciphers.adoc @@ -41,8 +41,8 @@ |ctaes: yes (link:https://github.com/bitcoin/bitcoin/tree/master/src/crypto/ctaes[ctaes, constant-time AES]); OpenSSL with assembly: yes (link:https://github.com/openssl/openssl/tree/master/crypto/aes/asm[OpenSSL's AES assembly for ARMv8 and x86-64]); OpenSSL no-asm: no (link:https://github.com/openssl/openssl/blob/master/crypto/aes/aes_core.c[OpenSSL's crypto/aes/aes_core.c, OPENSSL_AES_CONST_TIME]) |Constant time, measured -|BearSSL: native, Valgrind's memcheck (Linux), MemorySanitizer (Linux, clang) and dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; wasip2, dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; not measured yet on wasip3, emscripten. OpenSSL (seal alone: its open branches on the verdict inside OpenSSL): native, Valgrind's memcheck (Linux), nothing found; not measured yet on wasip2, wasip3 (<>) -|OpenSSL: not measured yet. ctaes: native, Valgrind's memcheck (Linux), MemorySanitizer (Linux, clang) and dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; wasip2, dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; not measured yet on wasip3, emscripten (<>) +|BearSSL: native, Valgrind's memcheck (Linux), MemorySanitizer (Linux, clang) and dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; wasip2, dudect (printed, not judged: under wasmtime its timing follows the runner's processor); not measured yet on wasip3, emscripten. OpenSSL (seal alone: its open branches on the verdict inside OpenSSL): native, Valgrind's memcheck (Linux), nothing found; not measured yet on wasip2, wasip3 (<>) +|OpenSSL: not measured yet. ctaes: native, Valgrind's memcheck (Linux), MemorySanitizer (Linux, clang) and dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; wasip2, dudect (printed, not judged: under wasmtime its timing follows the runner's processor); not measured yet on wasip3, emscripten (<>) |Standards |link:https://csrc.nist.gov/pubs/sp/800/38/d/final[NIST SP 800-38D, GCM and GMAC] @@ -102,7 +102,7 @@ |libsodium: yes (link:https://doc.libsodium.org/secret-key_cryptography/aead[libsodium's documentation, AEAD constructions: ChaCha20 and timing attacks]) |Constant time, measured -|libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found; not measured yet on wasip2, wasip3, emscripten. BearSSL: native, Valgrind's memcheck (Linux), MemorySanitizer (Linux, clang) and dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; wasip2, dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; not measured yet on wasip3, emscripten. OpenSSL (seal alone: its open branches on the verdict inside OpenSSL): native, Valgrind's memcheck (Linux), nothing found; not measured yet on wasip2, wasip3 (<>) +|libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found; not measured yet on wasip2, wasip3, emscripten. BearSSL: native, Valgrind's memcheck (Linux), MemorySanitizer (Linux, clang) and dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; wasip2, dudect (printed, not judged: under wasmtime its timing follows the runner's processor); not measured yet on wasip3, emscripten. OpenSSL (seal alone: its open branches on the verdict inside OpenSSL): native, Valgrind's memcheck (Linux), nothing found; not measured yet on wasip2, wasip3 (<>) |libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found; not measured yet on wasip2, wasip3, emscripten (<>) |libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found; not measured yet on wasip2, wasip3, emscripten (<>) diff --git a/doc/generated/namespace-curves.adoc b/doc/generated/namespace-curves.adoc index 1095a8a..3e6a7f9 100644 --- a/doc/generated/namespace-curves.adoc +++ b/doc/generated/namespace-curves.adoc @@ -45,7 +45,7 @@ |libsecp256k1: native, Valgrind's memcheck (Linux; libsecp256k1's own `+ctime_tests.c+`, and webcpp's code around it: the key pair's making and `+secret()+`, its signatures and x-only tweak, ECDH in three forms (`+agree+`, `+agree_hashed+` and `+agree_point+`), the secret key's tweaks and negation, and PKCS#8), MemorySanitizer (Linux, clang; the same paths as memcheck's) and dudect (judged; on a runner GitHub hosts, by two of three runs; `+agree+`), nothing found; wasip2, dudect (judged; on a runner GitHub hosts, by two of three runs; `+agree+`), nothing found; not measured yet on wasip3, emscripten (<>) |libsodium: native, Valgrind's memcheck (Linux), MemorySanitizer (Linux, clang) and dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; wasip2, dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; not measured yet on wasip3, emscripten (<>) |libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found, and dudect (judged; on a runner GitHub hosts, by two of three runs): nothing found with arm64's DIT (data-independent timing) bit set, which webcpp sets around every call on 64-bit ARM under macOS, iOS, Linux, Android and Windows where the CPU has it, as Apple requires of constant-time code (link:https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Enable-DIT-for-constant-time-cryptographic-operations[Apple, Writing ARM64 code for Apple platforms: enable DIT for constant-time cryptographic operations]); the lane's dudect sets nothing itself and measures what a program gets: \|t\| 1.8 to 2.8 against the threshold 10 (2026-11-21, five runs), while its `dudect_planted`, an early-exit scan of the secret key run inside the same guard, reads \|t\| 66.72 and 65.53 (2026-11-21): DIT does not hide a leak. Without DIT, dudect times `agree` with an all-zero secret key against random ones at \|t\| 6.7 to 14.5 (2026-11-19) and 4.3 to 7.8 (2026-11-21, three runs): about one nanosecond in 15 µs. Each on an Apple M5 Max, from a release build. libsodium does not set DIT, and webcpp sets nothing on x86 or WebAssembly; wasip2, dudect (judged; on a runner GitHub hosts, by two of three runs): an open finding, its cause measured: dudect times `agree` with an all-zero secret key against random ones at \|t\| 13 to 32 (2026-11-18; a fixed key against another fixed key: 22.9) and 107 to 260 (2026-11-19), and 25.25 in the lane on 2026-11-21, against the threshold 10, under wasmtime 47 on an Apple M5 Max, from a release build. The cause is Apple silicon's DIT (data-independent timing), which wasmtime does not set (link:https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Enable-DIT-for-constant-time-cryptographic-operations[Apple, Writing ARM64 code for Apple platforms: enable DIT for constant-time cryptographic operations]): with DIT set in wasmtime's main thread, an experiment and not the lane, the same case reads \|t\| 1.5 to 2.1; no branch on a secret was found in the WebAssembly or in wasmtime's compiled code. The lane cannot set DIT from inside the WebAssembly, so it prints this value on wasip2 without judging it; the CI's x86-64 run measures it next; not measured yet on wasip3, emscripten (<>) -|BearSSL: native, Valgrind's memcheck (Linux; the key pair's making, `+sign+` of a digest (`+crypto::signing_schemes::prehashed+`), which makes its signature low S without a branch, then `+low_s()+` and `+is_low_s()+` of it, `+agree+` and the private formats, `+pkcs8+`, `+raw+` and `+pem(pkcs8)+` both ways; BearSSL's own branches on its signing's verdicts listed in `+bearssl_verdicts.supp+`; nothing found at webcpp's pin f8a2f3d, whose patches submitted upstream close upstream's leak of the nonce's bit length in `+sign+` that this checker found on 2026-11-21 and the jump on the scalar in P-256's scalar check that it found under `+agree+` on the x86-64 runner on 2026-12-03, `+sign+` with its low-S step included (Valgrind 3.22, arm64 Linux container, 2026-12-02; x86-64, `+ctgrind+` and `+ctgrind_space+`, 2026-12-04)), MemorySanitizer (Linux, clang; the same paths as memcheck's; the same leak in `+sign+` on 2026-11-21 on upstream's BearSSL, nothing at webcpp's pin ae63032, `+sign+` with its low-S step included (clang 18, arm64 Linux container, 2026-12-02); MemorySanitizer checks the select of P-256's scalar check before the code generator makes it a jump, so the second patch changes nothing it sees) and dudect (judged; on a runner GitHub hosts, by two of three runs; `+sign+` of a digest and `+agree+`, each against the key pair's scalar; `+sign+` with its low-S step judged constant time, \|t\| 1.70 on Linux and 1.63 natively on an Apple M5 Max (release, one run each, 2026-11-22; provisional, measured again in the final quiet pass)), nothing found; wasip2, dudect (judged; on a runner GitHub hosts, by two of three runs; `+sign+` of a digest and `+agree+`, each against the key pair's scalar; `+sign+` with its low-S step judged constant time, \|t\| 1.70 on Linux and 1.63 natively on an Apple M5 Max (release, one run each, 2026-11-22; provisional, measured again in the final quiet pass)), nothing found; not measured yet on wasip3, emscripten (<>) +|BearSSL: native, Valgrind's memcheck (Linux; the key pair's making, `+sign+` of a digest (`+crypto::signing_schemes::prehashed+`), which makes its signature low S without a branch, then `+low_s()+` and `+is_low_s()+` of it, `+agree+` and the private formats, `+pkcs8+`, `+raw+` and `+pem(pkcs8)+` both ways; BearSSL's own branches on its signing's verdicts listed in `+bearssl_verdicts.supp+`; nothing found at webcpp's pin f8a2f3d, whose patches submitted upstream close upstream's leak of the nonce's bit length in `+sign+` that this checker found on 2026-11-21 and the jump on the scalar in P-256's scalar check that it found under `+agree+` on the x86-64 runner on 2026-12-03, `+sign+` with its low-S step included (Valgrind 3.22, arm64 Linux container, 2026-12-02; x86-64, `+ctgrind+` and `+ctgrind_space+`, 2026-12-04)), MemorySanitizer (Linux, clang; the same paths as memcheck's; the same leak in `+sign+` on 2026-11-21 on upstream's BearSSL, nothing at webcpp's pin ae63032, `+sign+` with its low-S step included (clang 18, arm64 Linux container, 2026-12-02); MemorySanitizer checks the select of P-256's scalar check before the code generator makes it a jump, so the second patch changes nothing it sees) and dudect (judged; on a runner GitHub hosts, by two of three runs; `+sign+` of a digest and `+agree+`, each against the key pair's scalar; `+sign+` with its low-S step judged constant time, \|t\| 1.70 on Linux and 1.63 natively on an Apple M5 Max (release, one run each, 2026-11-22; provisional, measured again in the final quiet pass)), nothing found; wasip2, dudect (printed, not judged: under wasmtime its timing follows the runner's processor); not measured yet on wasip3, emscripten (<>) |Standards |link:https://www.secg.org/sec2-v2.pdf[SEC 2, Recommended Elliptic Curve Domain Parameters], link:https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki[BIP 340, Schnorr signatures for secp256k1], link:https://www.rfc-editor.org/rfc/rfc6979[RFC 6979, deterministic ECDSA nonces], link:https://github.com/bitcoin/bips/blob/master/bip-0324.mediawiki[BIP 324, version 2 P2P encrypted transport protocol], link:https://github.com/bitcoin/bips/blob/master/bip-0327.mediawiki[BIP 327, MuSig2 for BIP340-compatible multi-signatures], link:https://github.com/bitcoin/bips/blob/master/bip-0352.mediawiki[BIP 352, Silent Payments] diff --git a/doc/generated/namespace-public_key_encryption.adoc b/doc/generated/namespace-public_key_encryption.adoc index 6f6b4a0..6bb7f72 100644 --- a/doc/generated/namespace-public_key_encryption.adoc +++ b/doc/generated/namespace-public_key_encryption.adoc @@ -7,42 +7,49 @@ // Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, // the message tests and the Jamfile fixtures: run it again, never edit this file. -[cols="2h,5,5,5",options="header"] +[cols="2h,5,5,5,5",options="header"] |=== -|Construction |X25519-XSalsa20-Poly1305 |X25519-XChaCha20-Poly1305 |X25519-XSalsa20-Poly1305, anonymous +|Construction |X25519-XSalsa20-Poly1305 |X25519-XChaCha20-Poly1305 |X25519-XSalsa20-Poly1305, anonymous |RFC 9180's HPKE, DHKEM(X25519 or P-256), HKDF-SHA256 or HKDF-SHA512, AES-GCM, ChaCha20-Poly1305 or export-only |Names |`box` |`box_xchacha20poly1305` |`sealed_box` +|`hpke::suite` |What it does |Authenticated encryption between two key pairs: X25519 agrees a key once per pair, then XSalsa20-Poly1305 seals each message; either party can have written it |The same, with XChaCha20-Poly1305 sealing each message |Encryption to a public key alone: a key pair drawn per message, whose public key travels with it; the recipient cannot tell who sealed it, and the sender cannot open it afterwards +|Encryption to a public key by the standard interoperable protocols use (MLS, TLS's Encrypted Client Hello): an ephemeral agreement and a key schedule set up a context that seals messages in order and exports secrets, in four modes (with a pre-shared key, an authenticated sender, or both) |Keys |the own X25519 key pair and the peer's X25519 public key |the same |to seal, the recipient's X25519 public key; to open, the recipient's X25519 key pair +|to seal, the recipient's X25519 or P-256 public key, and in the auth modes the sender's key pair; to open, the recipient's key pair, and in the auth modes the sender's public key |Nonce |24 bytes, safe to draw at random (link:https://cr.yp.to/snuffle/xsalsa-20081128.pdf[D. J. Bernstein, Extending the Salsa20 nonce, 2008]) |24 bytes, safe to draw at random |none: derived from the two public keys +|none: derived from the context's sequence number |Overhead per message |a 16-byte tag |a 16-byte tag |48 bytes: the ephemeral public key and the tag +|the encapsulated key once per context (32 bytes for X25519, 65 for P-256), then a 16-byte tag per message |Standards and sources |link:https://nacl.cr.yp.to/box.html[NaCl, public-key authenticated encryption (crypto_box)], link:https://doc.libsodium.org/public-key_cryptography/authenticated_encryption[libsodium's documentation, public-key authenticated encryption] |link:https://doc.libsodium.org/public-key_cryptography/authenticated_encryption[libsodium's documentation, public-key authenticated encryption] |link:https://doc.libsodium.org/public-key_cryptography/sealed_boxes[libsodium's documentation, sealed boxes] +|link:https://www.rfc-editor.org/rfc/rfc9180[RFC 9180, Hybrid Public Key Encryption], link:https://github.com/cfrg/draft-irtf-cfrg-hpke/blob/5f503c564da00b0687b3de75f1dfbdfc4079ad31/test-vectors.json[RFC 9180's test vectors, cfrg/draft-irtf-cfrg-hpke at 5f503c5], link:https://www.rfc-editor.org/rfc/rfc9420#section-5.1[RFC 9420, the Messaging Layer Security protocol, section 5.1] |Choose it when |two parties who know each other's public keys exchange messages, in NaCl's and libsodium's format; a peer key of small order is refused |the peer uses libsodium's `crypto_box_curve25519xchacha20poly1305`; otherwise `box`, NaCl's format |anyone may write to a recipient who must not learn who wrote: anonymous feedback, a drop box; it proves nothing about the sender +|the peer speaks RFC 9180 (MLS, Marmot, any HPKE library), or one context carries ordered messages and exported keys; a sealed box when the peer is libsodium |=== diff --git a/doc/generated/use-cases.adoc b/doc/generated/use-cases.adoc index df9c0f6..80e1bd3 100644 --- a/doc/generated/use-cases.adoc +++ b/doc/generated/use-cases.adoc @@ -257,6 +257,14 @@ `+/webcpp/crypto//sealed_box-default+` |<> +|Encrypt to a public key as RFC 9180 says, byte for byte, as MLS's Welcome and UpdatePath and Marmot's backups do +|In `+public_key_encryption::hpke+`: `+suite<...>::begin_sending+`, `+begin_receiving+`, `+seal+`, `+open+`, `+derive_from_seed+`; the contexts' `+seal+`, `+open+` and `+export_secret+` +|the defaults of X25519, P-256, AES-GCM and ChaCha20-Poly1305 +|`+/webcpp/crypto//crypto+` + +`+/webcpp/crypto//x25519-default+` + +`+/webcpp/crypto//gcm-default+` +|<> + |Share a file with someone known only by a public key, as a file-sharing app does |`+secret_key_encryption::secretbox<>+` for the file under a key drawn for it, `+public_key_encryption::sealed_box::seal+` for that key |libsodium diff --git a/doc/llms.txt b/doc/llms.txt index 84e8738..957700a 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -281,6 +281,17 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [public_key_encryption::sealed_box](https://webcpporg.github.io/libs/crypto/#crypto-sealed-box): libsodium's sealed boxes, `crypto_box_seal`: anonymous encryption to an X25519 public key under a key pair drawn per message, 48 bytes longer than the message, which only the recipient's X25519 key pair opens. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. Use it to: let anyone send a message that only the recipient can read, without saying who sent it (anonymous feedback, a drop box). - seal: Seals `message_bytes` into `output_bytes`, of `message_bytes.size() + overhead` bytes: the drawn public key, the tag, then the ciphertext. - open: Opens `sealed_bytes` into `output_bytes`, of `sealed_bytes.size() - overhead` bytes, with the recipient's key pair. +- [public_key_encryption::hpke::suite](https://webcpporg.github.io/libs/crypto/#crypto-hpke): RFC 9180's HPKE composed from crypto's X25519 or P-256 agreement, webcpp::hash's HKDF over pieces and crypto's AES-GCM or ChaCha20-Poly1305: suites as types, the mode following from the arguments (base, psk, auth, auth_psk), contexts that seal and open in order and export secrets, single-shot `seal` and `open`, and `derive_from_seed`, RFC 9180's DeriveKeyPair; every RFC 9180 test vector of those suites passes and OpenSSL's HPKE agrees; no backend of its own, no size cap, no allocation. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten; libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Use it to: encrypt to a public key as RFC 9180 says, byte for byte, as MLS's Welcome and UpdatePath and Marmot's backups do. + - begin_sending: Sets up a sender in base mode (RFC 9180's `SetupBaseS`): an ephemeral key pair drawn from the system's generator, its agreement with the recipient's key, then the key schedule. + - begin_receiving: Sets up a recipient in base mode (RFC 9180's `SetupBaseR`): the encapsulated key's agreement with the recipient's key pair, then the key schedule. + - seal: Seals one message to a public key in base mode (RFC 9180's `SealBase`): `begin_sending(recipient_public_key, application_info)`, then one `seal`. + - open: Opens one message in base mode, RFC 9180's `OpenBase`: `begin_receiving` with the encapsulated key, the recipient's key pair and the application info, then one `open`. + - derive_from_seed: Derives a key pair from a seed on the suite's key backend (RFC 9180's `DeriveKeyPair`), as MLS derives every tree key pair: the key encapsulation's `derive_from_seed`. + - async_begin_sending: Sets up a sender, asynchronously: `begin_sending` run with the arguments between the executor and the token when the operation is initiated, its result posted to `completion_executor`; the member form of `hpke::async_begin_sending`. + - async_begin_receiving: Sets up a recipient, asynchronously: `begin_receiving` run with the arguments between the executor and the token when the operation is initiated, its result posted to `completion_executor`; the member form of `hpke::async_begin_receiving`. + - async_seal: Seals one message, asynchronously: the single-shot `seal` run with the arguments between the executor and the token when the operation is initiated, its result posted to `completion_executor`; the member form of `hpke::async_seal`. + - async_open: Opens one message, asynchronously: the single-shot `open` run with the arguments between the executor and the token when the operation is initiated, its result posted to `completion_executor`; the member form of `hpke::async_open`. + - async_derive_from_seed: Derives a key pair from a seed, asynchronously: `derive_from_seed` run when the operation is initiated, its result posted to `completion_executor`; the member form of `hpke::async_derive_from_seed(completion_executor, seed, completion_token)`. ## webcpp::crypto::key_exchange @@ -321,13 +332,13 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp ## Constant time, measured -- AES-GCM: BearSSL: native, Valgrind's memcheck (Linux), MemorySanitizer (Linux, clang) and dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; wasip2, dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; not measured yet on wasip3, emscripten. OpenSSL (seal alone: its open branches on the verdict inside OpenSSL): native, Valgrind's memcheck (Linux), nothing found; not measured yet on wasip2, wasip3. -- AES block cipher: OpenSSL: not measured yet. ctaes: native, Valgrind's memcheck (Linux), MemorySanitizer (Linux, clang) and dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; wasip2, dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; not measured yet on wasip3, emscripten. +- AES-GCM: BearSSL: native, Valgrind's memcheck (Linux), MemorySanitizer (Linux, clang) and dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; wasip2, dudect (printed, not judged: under wasmtime its timing follows the runner's processor); not measured yet on wasip3, emscripten. OpenSSL (seal alone: its open branches on the verdict inside OpenSSL): native, Valgrind's memcheck (Linux), nothing found; not measured yet on wasip2, wasip3. +- AES block cipher: OpenSSL: not measured yet. ctaes: native, Valgrind's memcheck (Linux), MemorySanitizer (Linux, clang) and dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; wasip2, dudect (printed, not judged: under wasmtime its timing follows the runner's processor); not measured yet on wasip3, emscripten. - secp256k1: libsecp256k1: native, Valgrind's memcheck (Linux; libsecp256k1's own `ctime_tests.c`, and webcpp's code around it: the key pair's making and `secret()`, its signatures and x-only tweak, ECDH in three forms (`agree`, `agree_hashed` and `agree_point`), the secret key's tweaks and negation, and PKCS#8), MemorySanitizer (Linux, clang; the same paths as memcheck's) and dudect (judged; on a runner GitHub hosts, by two of three runs; `agree`), nothing found; wasip2, dudect (judged; on a runner GitHub hosts, by two of three runs; `agree`), nothing found; not measured yet on wasip3, emscripten. - Ed25519: libsodium: native, Valgrind's memcheck (Linux), MemorySanitizer (Linux, clang) and dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; wasip2, dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; not measured yet on wasip3, emscripten. - X25519: libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found, and dudect (judged; on a runner GitHub hosts, by two of three runs): nothing found with arm64's DIT (data-independent timing) bit set, which webcpp sets around every call on 64-bit ARM under macOS, iOS, Linux, Android and Windows where the CPU has it, as Apple requires of constant-time code ([Apple, Writing ARM64 code for Apple platforms: enable DIT for constant-time cryptographic operations](https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Enable-DIT-for-constant-time-cryptographic-operations)); the lane's dudect sets nothing itself and measures what a program gets: |t| 1.8 to 2.8 against the threshold 10 (2026-11-21, five runs), while its `dudect_planted`, an early-exit scan of the secret key run inside the same guard, reads |t| 66.72 and 65.53 (2026-11-21): DIT does not hide a leak. Without DIT, dudect times `agree` with an all-zero secret key against random ones at |t| 6.7 to 14.5 (2026-11-19) and 4.3 to 7.8 (2026-11-21, three runs): about one nanosecond in 15 µs. Each on an Apple M5 Max, from a release build. libsodium does not set DIT, and webcpp sets nothing on x86 or WebAssembly; wasip2, dudect (judged; on a runner GitHub hosts, by two of three runs): an open finding, its cause measured: dudect times `agree` with an all-zero secret key against random ones at |t| 13 to 32 (2026-11-18; a fixed key against another fixed key: 22.9) and 107 to 260 (2026-11-19), and 25.25 in the lane on 2026-11-21, against the threshold 10, under wasmtime 47 on an Apple M5 Max, from a release build. The cause is Apple silicon's DIT (data-independent timing), which wasmtime does not set ([Apple, Writing ARM64 code for Apple platforms: enable DIT for constant-time cryptographic operations](https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Enable-DIT-for-constant-time-cryptographic-operations)): with DIT set in wasmtime's main thread, an experiment and not the lane, the same case reads |t| 1.5 to 2.1; no branch on a secret was found in the WebAssembly or in wasmtime's compiled code. The lane cannot set DIT from inside the WebAssembly, so it prints this value on wasip2 without judging it; the CI's x86-64 run measures it next; not measured yet on wasip3, emscripten. - crypto_kx: libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found; not measured yet on wasip2, wasip3, emscripten. -- ChaCha20-Poly1305: libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found; not measured yet on wasip2, wasip3, emscripten. BearSSL: native, Valgrind's memcheck (Linux), MemorySanitizer (Linux, clang) and dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; wasip2, dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; not measured yet on wasip3, emscripten. OpenSSL (seal alone: its open branches on the verdict inside OpenSSL): native, Valgrind's memcheck (Linux), nothing found; not measured yet on wasip2, wasip3. +- ChaCha20-Poly1305: libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found; not measured yet on wasip2, wasip3, emscripten. BearSSL: native, Valgrind's memcheck (Linux), MemorySanitizer (Linux, clang) and dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; wasip2, dudect (printed, not judged: under wasmtime its timing follows the runner's processor); not measured yet on wasip3, emscripten. OpenSSL (seal alone: its open branches on the verdict inside OpenSSL): native, Valgrind's memcheck (Linux), nothing found; not measured yet on wasip2, wasip3. - original ChaCha20-Poly1305: libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found; not measured yet on wasip2, wasip3, emscripten. - XChaCha20-Poly1305: libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found; not measured yet on wasip2, wasip3, emscripten. - XSalsa20-Poly1305 secret box: libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found; not measured yet on wasip2, wasip3, emscripten. @@ -338,7 +349,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - ElligatorSwift: libsecp256k1: native, Valgrind's memcheck (Linux; libsecp256k1's own `ctime_tests.c`, and webcpp's `ellswift_create` and `ellswift_xdh` around it) and MemorySanitizer (Linux, clang; the same paths as memcheck's), nothing found; not measured yet on wasip2, wasip3, emscripten. - MuSig2: libsecp256k1: native, Valgrind's memcheck (Linux; libsecp256k1's own `ctime_tests.c`, and webcpp's `generate_nonce` and `partial_sign` around it) and MemorySanitizer (Linux, clang; the same paths as memcheck's), nothing found; not measured yet on wasip2, wasip3, emscripten. - BIP 352 silent payments: libsecp256k1: native, Valgrind's memcheck (Linux; libsecp256k1's own `ctime_tests.c`, and webcpp's `create_outputs`, `create_label` and `scan_outputs` around it, each workspace's wipe included) and MemorySanitizer (Linux, clang; the same paths as memcheck's), nothing found; not measured yet on wasip2, wasip3, emscripten. -- P-256: BearSSL: native, Valgrind's memcheck (Linux; the key pair's making, `sign` of a digest (`crypto::signing_schemes::prehashed`), which makes its signature low S without a branch, then `low_s()` and `is_low_s()` of it, `agree` and the private formats, `pkcs8`, `raw` and `pem(pkcs8)` both ways; BearSSL's own branches on its signing's verdicts listed in `bearssl_verdicts.supp`; nothing found at webcpp's pin f8a2f3d, whose patches submitted upstream close upstream's leak of the nonce's bit length in `sign` that this checker found on 2026-11-21 and the jump on the scalar in P-256's scalar check that it found under `agree` on the x86-64 runner on 2026-12-03, `sign` with its low-S step included (Valgrind 3.22, arm64 Linux container, 2026-12-02; x86-64, `ctgrind` and `ctgrind_space`, 2026-12-04)), MemorySanitizer (Linux, clang; the same paths as memcheck's; the same leak in `sign` on 2026-11-21 on upstream's BearSSL, nothing at webcpp's pin ae63032, `sign` with its low-S step included (clang 18, arm64 Linux container, 2026-12-02); MemorySanitizer checks the select of P-256's scalar check before the code generator makes it a jump, so the second patch changes nothing it sees) and dudect (judged; on a runner GitHub hosts, by two of three runs; `sign` of a digest and `agree`, each against the key pair's scalar; `sign` with its low-S step judged constant time, |t| 1.70 on Linux and 1.63 natively on an Apple M5 Max (release, one run each, 2026-11-22; provisional, measured again in the final quiet pass)), nothing found; wasip2, dudect (judged; on a runner GitHub hosts, by two of three runs; `sign` of a digest and `agree`, each against the key pair's scalar; `sign` with its low-S step judged constant time, |t| 1.70 on Linux and 1.63 natively on an Apple M5 Max (release, one run each, 2026-11-22; provisional, measured again in the final quiet pass)), nothing found; not measured yet on wasip3, emscripten. +- P-256: BearSSL: native, Valgrind's memcheck (Linux; the key pair's making, `sign` of a digest (`crypto::signing_schemes::prehashed`), which makes its signature low S without a branch, then `low_s()` and `is_low_s()` of it, `agree` and the private formats, `pkcs8`, `raw` and `pem(pkcs8)` both ways; BearSSL's own branches on its signing's verdicts listed in `bearssl_verdicts.supp`; nothing found at webcpp's pin f8a2f3d, whose patches submitted upstream close upstream's leak of the nonce's bit length in `sign` that this checker found on 2026-11-21 and the jump on the scalar in P-256's scalar check that it found under `agree` on the x86-64 runner on 2026-12-03, `sign` with its low-S step included (Valgrind 3.22, arm64 Linux container, 2026-12-02; x86-64, `ctgrind` and `ctgrind_space`, 2026-12-04)), MemorySanitizer (Linux, clang; the same paths as memcheck's; the same leak in `sign` on 2026-11-21 on upstream's BearSSL, nothing at webcpp's pin ae63032, `sign` with its low-S step included (clang 18, arm64 Linux container, 2026-12-02); MemorySanitizer checks the select of P-256's scalar check before the code generator makes it a jump, so the second patch changes nothing it sees) and dudect (judged; on a runner GitHub hosts, by two of three runs; `sign` of a digest and `agree`, each against the key pair's scalar; `sign` with its low-S step judged constant time, |t| 1.70 on Linux and 1.63 natively on an Apple M5 Max (release, one run each, 2026-11-22; provisional, measured again in the final quiet pass)), nothing found; wasip2, dudect (printed, not judged: under wasmtime its timing follows the runner's processor); not measured yet on wasip3, emscripten. ## Rules of use @@ -392,6 +403,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [Encrypt a record or a file under one secret key, each with a random nonce, in libsodium's secret-box format](https://webcpporg.github.io/libs/crypto/#crypto-secretbox): `secretbox<>`, `secretbox_xchacha20poly1305<>`: `from_key`, `seal(nonce, data)`, `open(nonce, data, tag)`; the box forms `seal(box, nonce, data)`, `open(box, nonce, data, tag)` (webcpp::crypto::secret_key_encryption); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//secretbox_xsalsa20poly1305-default. Example: example/file_share.cpp. - [Send messages between two people who know each other's public keys, as NaCl's and libsodium's crypto_box](https://webcpporg.github.io/libs/crypto/#crypto-box): `box::from_keys`, `box::seal`, `box::open` (webcpp::crypto::public_key_encryption); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//box_xsalsa20poly1305-default. Example: example/box_messages.cpp. - [Let anyone send a message that only the recipient can read, without saying who sent it (anonymous feedback, a drop box)](https://webcpporg.github.io/libs/crypto/#crypto-sealed-box): `sealed_box::seal`, `sealed_box::open` (webcpp::crypto::public_key_encryption); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//sealed_box-default. Example: example/file_share.cpp. +- [Encrypt to a public key as RFC 9180 says, byte for byte, as MLS's Welcome and UpdatePath and Marmot's backups do](https://webcpporg.github.io/libs/crypto/#crypto-hpke): `suite<...>::begin_sending`, `begin_receiving`, `seal`, `open`, `derive_from_seed`; the contexts' `seal`, `open` and `export_secret` (webcpp::crypto::public_key_encryption::hpke); backend the defaults of X25519, P-256, AES-GCM and ChaCha20-Poly1305; Jamfile /webcpp/crypto//crypto /webcpp/crypto//x25519-default /webcpp/crypto//gcm-default. Example: example/hpke_base.cpp. - [Share a file with someone known only by a public key, as a file-sharing app does](https://webcpporg.github.io/libs/crypto/#crypto-everyday-files): `secret_key_encryption::secretbox<>` for the file under a key drawn for it, `public_key_encryption::sealed_box::seal` for that key (webcpp::crypto); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//secretbox_xsalsa20poly1305-default /webcpp/crypto//sealed_box-default /webcpp/crypto//x25519-default. Example: example/file_share.cpp. - [Make and keep a P-256 key pair, and import a browser's public key (WebCrypto's raw form), as webcpp::trystero's peers do](https://webcpporg.github.io/libs/crypto/#crypto-p256-keys): `keypair::from_secret`, `keypair::generate`, `keypair::public_key`, `keypair::secret`, `public_key::from_bytes` (webcpp::crypto::curves::p256); backend BearSSL; Jamfile /webcpp/crypto//crypto /webcpp/crypto//p256-default. Example: example/p256_keys.cpp. - [Sign what a browser's WebCrypto verifies and verify what it signs (ECDSA on P-256 with SHA-256), low S where a protocol requires it, as webcpp::trystero's handshakes](https://webcpporg.github.io/libs/crypto/#crypto-p256-ecdsa): `keypair::sign(crypto::signing_schemes::ecdsa_sha256, message)`, `crypto::verify`, `signature.is_low_s()`, `signature.low_s()`; `codecs::encode` and `codecs::decode` with `crypto::formats::der` for X.509 (webcpp::crypto::curves::p256); backend BearSSL; Jamfile /webcpp/crypto//crypto /webcpp/crypto//p256-default. Example: example/p256_sign.cpp. @@ -419,6 +431,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - example/failure_reasons.cpp: Shows the three ways AES-GCM can refuse a message: a tampered ciphertext, a nonce of the wrong size and a tag of the wrong size. A program must tell the first from the others: only authentication_failed means someone changed the data, and open then wipes the plaintext so that no unauthenticated bytes are ever used. - example/file_share.cpp: A file-sharing app shares a file with a recipient it knows only by an X25519 public key: the file is sealed once in a secret box under a key drawn for this file, and that file key is sealed to the recipient's public key in a sealed box. The upload holds both; only the recipient's key pair opens the file key, and the file key opens the file. Prints what the recipient reads, the sizes on the wire, and the refusals of a changed upload and of another key pair. - example/four_forms.cpp: Makes RFC 6979's P-256 key pair (a published scalar, never a real key), signs "sample" with crypto::signing_schemes::ecdsa_sha256 and verifies the signature, each operation in its four forms: the member, its free form, and the asynchronous member and its free form, which complete through an event loop. RFC 6979's nonce makes the four signatures the same bytes, and the four verifications agree. +- example/hpke_base.cpp: HPKE (RFC 9180) in base mode with MLS's suite 0x0001: DHKEM(X25519, HKDF-SHA256), HKDF-SHA256 and AES-128-GCM, on the default backends. The recipient's key pair is derived from a seed, as MLS derives its tree keys; the sender seals two messages to its public key on one context, and sends the encapsulated key with them; the recipient opens them in order. Both contexts export the same secret, as MLS's external join does; a message opened out of its order is refused. Prints what the recipient reads and whether the exports agree. - example/key_formats.cpp: Reads RFC 8410's Ed25519 private key in PEM (section 10.3), as OpenSSL or WebCrypto export it, with codecs::decode, writes its public key as PEM with codecs::encode, which is the RFC's section 10.1 to the character, and signs with it; writes an X25519 key pair's public key the same way, with its member encode; and refuses the RFC's version 2 of the private key, which carries the public key too. Prints the PEM texts and each verdict. - example/key_tweak.cpp: A watch-only wallet: a server that holds the wallet's public key and no secret gives each payment a fresh key, and the signing device, which holds the secret, derives the same keys' secrets. Both add the same tweak, one to the public key and one to the secret key; the device's tweaked key pair signs (BIP 340), and the signature verifies under the server's tweaked public key. The tweak here is an HMAC-SHA-256 of the public key and the payment's number under a chain code both sides share and no one else sees; BIP 32 derives such tweaks its own way, with HMAC-SHA-512, and is a domain library's. - example/kx_session.cpp: A chat app's client and server, each with a crypto_kx key pair made from libsodium's kx test's seeds, exchange public keys and compute their session keys; the client seals a message with its transmit key and the server opens it with its receive key, on ChaCha20-Poly1305; a peer key of low order is refused. Prints the public keys and the client's session keys in hex. diff --git a/doc/overview.adoc b/doc/overview.adoc index 7e8b78b..e18d3de 100644 --- a/doc/overview.adoc +++ b/doc/overview.adoc @@ -98,8 +98,8 @@ and signatures, X25519's key pairs and agreement, and the conversion between them (<>, <>); * `webcpp::crypto::curves::p256`: key pairs, ECDSA, ECDH and the encodings on P-256 (<>); -* `webcpp::crypto::public_key_encryption`: `box`, `box_xchacha20poly1305` and -`sealed_box` (<>); +* `webcpp::crypto::public_key_encryption`: `box`, `box_xchacha20poly1305`, +`sealed_box` and RFC 9180's HPKE, `hpke::suite` (<>); * `webcpp::crypto::key_exchange`: `kx_keypair`, libsodium's `crypto_kx` (<>); * `webcpp::crypto::backends`: the backends (<>). diff --git a/doc/public_key_encryption.adoc b/doc/public_key_encryption.adoc index fbbdddc..fc60274 100644 --- a/doc/public_key_encryption.adoc +++ b/doc/public_key_encryption.adoc @@ -15,13 +15,16 @@ encrypts a message to a contact whose public key it knows; a feedback form encrypts a report to a key whose owner alone may read it. The namespace `webcpp::crypto::public_key_encryption` holds NaCl's and libsodium's constructions in this version: the box, between two key pairs, and the sealed -box, from anyone to a public key. Both agree with X25519 (<>) and -seal with XSalsa20-Poly1305, the secret box's cipher (<>), or, -for `box_xchacha20poly1305`, XChaCha20-Poly1305, on libsodium, their default on -every target. The namespace is named by the problem it solves: the word hybrid -now names the post-quantum hybrids, as X25519MLKEM768 and X-Wing, for which -`webcpp::crypto::hybrid` is kept free, and a later HPKE -(link:https://www.rfc-editor.org/rfc/rfc9180[RFC 9180]) joins the boxes here. +box, from anyone to a public key, both of which agree with X25519 +(<>) and seal with XSalsa20-Poly1305, the secret box's cipher +(<>), or, for `box_xchacha20poly1305`, XChaCha20-Poly1305, on +libsodium, their default on every target; and HPKE +(link:https://www.rfc-editor.org/rfc/rfc9180[RFC 9180]), the standard +encryption to a public key that MLS and TLS's Encrypted Client Hello use, +composed from crypto's own X25519 or P-256 agreement, webcpp::hash's HKDF and +crypto's AES-GCM or ChaCha20-Poly1305 (<>). The namespace is named +by the problem it solves: the word hybrid now names the post-quantum hybrids, as +X25519MLKEM768 and X-Wing, for which `webcpp::crypto::hybrid` is kept free. The namespaces of crypto are named by purpose, as <> lists them: what encrypts under one secret key is in `secret_key_encryption`, what encrypts @@ -33,7 +36,9 @@ contacts. A sealed box when anyone may write and the recipient alone reads: a feedback form, a drop box, a file key sent to a recipient known by a public key (<>). `box_xchacha20poly1305` only when the peer uses libsodium's XChaCha20 form; otherwise `box`, NaCl's format, which libsodium -and its bindings in every language read. Without either, a program that +and its bindings in every language read. HPKE when the peer speaks RFC 9180 +(MLS, Marmot, an HPKE library in another language), or when one setup carries +several ordered messages and exported keys. Without one of them, a program that encrypts to a public key by hand, an agreement and a cipher of its own choosing, risks the mistakes these constructions settle: a shared secret used as a key, a nonce reused, a weak public key accepted. @@ -153,3 +158,244 @@ Parts of this chapter, the boxes' and the sealed boxes' descriptions and pitfalls, are adapted from libsodium's documentation (link:https://github.com/jedisct1/libsodium-doc/tree/6d1ea27b79b853b2a04f09ae9e1a8231c90e3b56[jedisct1/libsodium-doc] at `6d1ea27`, ISC, `LICENSE-LIBSODIUM-DOC.txt`). + +[#crypto-hpke] +=== HPKE (RFC 9180) + +`public_key_encryption::hpke`, in +``, is RFC 9180's Hybrid Public +Key Encryption (link:https://www.rfc-editor.org/rfc/rfc9180[RFC 9180]): the +standard way to encrypt to a public key, which MLS +(link:https://www.rfc-editor.org/rfc/rfc9420#section-5.1[RFC 9420]) uses for every +Welcome and every UpdatePath node secret, and Marmot, MLS over Nostr, for its +backups. The sender draws an ephemeral key pair and agrees a shared secret with +the recipient's public key (the *key encapsulation*); a key schedule over HKDF +turns it, the application's info and the mode's inputs into an AEAD key, a base +nonce and an exporter secret (the *key derivation*); the AEAD seals each message +under the base nonce combined with the message's sequence number (the +*cipher*). The recipient, given the ephemeral public key (the *encapsulated +key*), does the same with its key pair. Each side's *context* seals or opens the +messages in order and exports secrets for other uses, the same on both sides. + +HPKE is composed from crypto's primitives and has no backend of its own: the key +pairs are those of `curves::x25519` (<>) or of `curves::p256` +(<>), HKDF is that of webcpp::hash, over the labeled inputs as pieces with +no copy, and the AEAD is `ciphers::gcm` (<>) or +`ciphers::chacha20_poly1305` (<>). Its values are RFC 9180's +byte for byte: every test vector of the CFRG's file for these suites passes, on +every target, and OpenSSL's HPKE agrees with it in both directions. + +*Suites as types.* A suite is `hpke::suite`, its three parameters tags checked by their concepts +(`key_encapsulation_mechanism`, `key_derivation_function`, `suite_cipher`), in +any of RFC 9180's combinations: + +[cols="2,1,3",options="header"] +|=== +|Tag |RFC 9180 |What it is + +|`key_encapsulation::x25519_hkdf_sha256` |0x0020 |DHKEM(X25519, HKDF-SHA256): 32-byte keys and encapsulated key +|`key_encapsulation::p256_hkdf_sha256` |0x0010 |DHKEM(P-256, HKDF-SHA256): 65-byte uncompressed points +|`key_derivation::hkdf_sha256` |0x0001 |HKDF-SHA256, exports up to 8,160 bytes +|`key_derivation::hkdf_sha512` |0x0003 |HKDF-SHA512, exports up to 16,320 bytes +|`cipher::aes128_gcm` |0x0001 |`ciphers::gcm>` +|`cipher::aes256_gcm` |0x0002 |`ciphers::gcm>` +|`cipher::chacha20_poly1305` |0x0003 |`ciphers::chacha20_poly1305` +|`cipher::export_only` |0xFFFF |no AEAD: the contexts only export +|=== + +MLS's mandatory suite, 0x0001, which Marmot requires, is +`suite`. P-384, P-521, X448, HKDF-SHA384 and the post-quantum key +encapsulations are not offered: crypto has none of those curves. `Backend` is +`hpke::default_backends`, each family's default (X25519 and ChaCha20-Poly1305 on +libsodium, P-256 on BearSSL, AES-GCM on its default per target); one backend +that serves the curve and the cipher both (`backends::bearssl` for a P-256 +suite); or `hpke::backends`, as +`backends` for MLS's suite natively without +OpenSSL. + +*The mode follows from the arguments.* There is no mode tag: the inputs a mode +needs are the arguments it takes, in RFC 9180's order, so that no mode can be +given the wrong ones. + +[cols="1,3,3",options="header"] +|=== +|Mode |Sender |Recipient + +|base |`begin_sending(recipient_public_key, application_info)` |`begin_receiving(encapsulated_key, recipient_keypair, application_info)` +|psk |`begin_sending(recipient_public_key, application_info, pre_shared_key)` |`begin_receiving(encapsulated_key, recipient_keypair, application_info, pre_shared_key)` +|auth |`begin_sending(recipient_public_key, application_info, sender_keypair)` |`begin_receiving(encapsulated_key, recipient_keypair, application_info, sender_public_key)` +|auth_psk |`begin_sending(recipient_public_key, application_info, pre_shared_key, sender_keypair)` |`begin_receiving(encapsulated_key, recipient_keypair, application_info, pre_shared_key, sender_public_key)` +|=== + +The pre-shared key is written `hpke::pre_shared_key{key, id}`; a key of fewer +than 32 bytes is refused, as RFC 9180 requires 32 bytes of entropy, and so is +an empty id. An argument list that is none of the four, a sender's key pair +given to `begin_receiving` for instance, a P-256 key given to an X25519 suite, or +the pre-shared key after the sender's key, stops the build with one message +listing the four. `begin_sending` returns the sender's context, whose +`encapsulated_key()` the recipient needs: send its `bytes()` with the +ciphertexts, and read them back with `encapsulated_key_type::from_bytes`. + +*Contexts.* `sender_context::seal(associated_data, plaintext, ciphertext)` +writes the ciphertext followed by the 16-byte tag, `plaintext.size() + +Suite::tag_size` bytes; `recipient_context::open(associated_data, ciphertext, +plaintext)` checks the tag and writes the plaintext, zeroing it when the tag +does not match. Each uses the nonce of the context's sequence number and +increments it, the recipient's only when the message opened: messages are +opened in the order they were sealed, and a lost message ends the stream (RFC +9180 section 5.2). Both contexts export the same secret for a purpose, +`export_secret(purpose)` returning a `secure::secret`, or +`export_secret(purpose, output)` for a length known at run time. The contexts +are moved and never copied, since a copy would reuse its nonces; moved from, +every member refuses with `invalid_state`; they wipe their secrets. The +sequence number is internal: after `2^64 - 1` messages the context refuses with +`message_limit_reached`. An export-only suite's contexts have no `seal` and no +`open`: the call stops the build. + +*Single-shot calls.* `suite::seal(recipient_public_key, application_info, +associated_data, plaintext, ciphertext[, pre_shared_key][, sender_keypair])` +sets up a sender, seals one message and returns the encapsulated key; +`suite::open(encapsulated_key, recipient_keypair, application_info, +associated_data, ciphertext, plaintext[, pre_shared_key][, sender_public_key])` +opens it. MLS's `SealBase` and `OpenBase` are these, in base mode. + +*Key pairs.* A suite's key pairs are its curve's, `suite::recipient_keypair_type`: +`generate()` draws one, and `suite::derive_from_seed(seed)` is RFC 9180's +`DeriveKeyPair`, as MLS derives every tree key pair from a path secret and +Marmot its recovery key from a BIP-39 entropy (through HKDF, the program's): a +seed of at least 32 bytes. An X25519 key pair derived so keeps its secret key +unclamped, as RFC 9180's test vectors print it; X25519 clamps it where it is +used, and `from_secret(key_pair.secret())` gives the same key pair. + +*No size caps, no allocation.* The application info, the associated data, the +pre-shared key and its id, an export's purpose and a seed are taken at any +length: the labeled HKDF reads them in place as pieces of webcpp::hash's HKDF. +MLS puts the serialized group context, kilobytes for a Welcome, into the +application info; OpenSSL's HPKE caps it at 1,024 bytes, and a pre-shared key, +its id (a C string) and an export's purpose at 66. Nothing is allocated on the +{cpp} heap. + +*The four forms.* Every operation that calls a backend has a member, a free +function in `hpke` (`+hpke::begin_sending(...)+`, `+hpke::seal(...)+`, +`+hpke::seal(sender, ...)+`, `hpke::derive_from_seed(seed)`, ...), and +their asynchronous forms in `` +(`+hpke::async_begin_sending(executor, ..., token)+`, +`+sender.async_seal(executor, ..., token)+`, ...), completing through a post on a +native backend (<>). WebCrypto has no HPKE: on the browser's +backend the asynchronous forms stop the build. `export_secret` calls no +backend and has the synchronous forms alone. + +include::generated/backends-hpke.adoc[] + +[cols="3,1"] +|=== +|Condition |Error + +|a pre-shared key shorter than 32 bytes |`invalid_key_size` +|an empty pre-shared key id; a seed shorter than 32 bytes; an encapsulated key of another size; a `ciphertext` or `plaintext` of the wrong size; an export of no byte or longer than `255 * Nh` |`invalid_input_size` +|an X25519 key of small order, the recipient's, the sender's or the encapsulated key |`weak_public_key` +|a P-256 encapsulated key that is no point of the curve |`invalid_public_key` +|`open`: the message, its associated data, its order, the pre-shared key or the sender differs |`authentication_failed` +|a context that sealed or opened `2^64 - 1` messages |`message_limit_reached` +|a context or a key pair moved from |`invalid_state` +|`begin_sending`: the system's generator fails |`entropy_unavailable` +|=== + +*Example.* MLS's suite in base mode: the recipient's key pair derived from a +seed; two messages sealed on one context and opened in order, a message out of +its order refused; and a secret both contexts export: + +[source,cpp] +---- +include::{examples}/hpke_base.cpp[tag=suite,indent=0] +---- + +[source,cpp] +---- +include::{examples}/hpke_base.cpp[tag=send,indent=0] +---- + +[source,cpp] +---- +include::{examples}/hpke_base.cpp[tag=receive,indent=0] +---- + +[source,cpp] +---- +include::{examples}/hpke_base.cpp[tag=export,indent=0] +---- + +[listing] +---- +include::{examples}/hpke_base.expected[] +---- + +The whole program: + +[source,cpp] +---- +include::{examples}/hpke_base.cpp[tag=program] +---- + +*RFC 9180's names.* crypto names each piece by what it is; this table gives +RFC 9180's name for each: + +[cols="1,2",options="header"] +|=== +|RFC 9180 |crypto + +|KEM, KDF, AEAD |key encapsulation (`key_encapsulation::`), key derivation (`key_derivation::`), cipher (`cipher::`) +|`DHKEM(X25519, HKDF-SHA256)`, `DHKEM(P-256, HKDF-SHA256)` |`key_encapsulation::x25519_hkdf_sha256`, `p256_hkdf_sha256` +|`HKDF-SHA256`, `HKDF-SHA512` |`key_derivation::hkdf_sha256`, `hkdf_sha512` +|`AES-128-GCM`, `AES-256-GCM`, `ChaCha20Poly1305`, `Export-only` |`cipher::aes128_gcm`, `aes256_gcm`, `chacha20_poly1305`, `export_only` +|`kem_id`, `kdf_id`, `aead_id` |`key_encapsulation_type::id`, `key_derivation_type::id`, `cipher_type::id` +|`Nsecret`, `Nenc`, `Npk`, `Nsk` |`shared_secret_size`, `encapsulated_key_size`, `public_key_size`, `secret_key_size` +|`Nh` |`hash_size` +|`Nk`, `Nn`, `Nt` |`key_size`, `nonce_size`, `tag_size` +|`mode_base`, `mode_psk`, `mode_auth`, `mode_auth_psk` |implied by the arguments +|`pkR`, `skR` |`recipient_public_key`, `recipient_keypair` +|`pkS`, `skS` |`sender_public_key`, `sender_keypair` +|`pkE`, `skE` |the ephemeral key pair, internal +|`enc` |`encapsulated_key` (`Suite::encapsulated_key_type`, `sender.encapsulated_key()`) +|`info` |`application_info` +|`aad` |`associated_data` +|`pt`, `ct` |`plaintext`, `ciphertext` +|`psk`, `psk_id` |`pre_shared_key{key, id}` +|`exporter_context`, `L` |`purpose`, `Length` or the output's size +|`GenerateKeyPair()` |`Suite::recipient_keypair_type::generate()` +|`DeriveKeyPair(ikm)` |`Suite::derive_from_seed(seed)`, `KeyEncapsulation::derive_from_seed(seed)` +|`SerializePublicKey`, `DeserializePublicKey` |`public_key.bytes()` (X25519), `uncompressed()` (P-256); `from_bytes` +|`SerializePrivateKey`, `DeserializePrivateKey` |`keypair.secret()`, `from_secret` +|`Encap`, `Decap`, `AuthEncap`, `AuthDecap` |internal, reached through `begin_sending` and `begin_receiving` +|`SetupBaseS`, `SetupPSKS`, `SetupAuthS`, `SetupAuthPSKS` |`+Suite::begin_sending(...)+` +|`SetupBaseR`, `SetupPSKR`, `SetupAuthR`, `SetupAuthPSKR` |`+Suite::begin_receiving(...)+`; `SetupAuthPSKR` is `begin_receiving(encapsulated_key, recipient_keypair, application_info, pre_shared_key, sender_public_key)` +|`Context`, `Context` |`hpke::sender_context`, `hpke::recipient_context` +|`ContextS.Seal(aad, pt)` |`sender.seal(associated_data, plaintext, ciphertext)` +|`ContextR.Open(aad, ct)` |`recipient.open(associated_data, ciphertext, plaintext)` +|`Context.Export(exporter_context, L)` |`context.export_secret(purpose)`, `export_secret(purpose, output)` +|`Seal`, `Open` |`+Suite::seal(...)+`, `+Suite::open(...)+` +|`SendExport`, `ReceiveExport` |`begin_sending` or `begin_receiving`, then `export_secret` +|`seq`, `ComputeNonce`, `IncrementSeq` |internal +|`suite_id`, `LabeledExtract`, `LabeledExpand`, `ExtractAndExpand` |internal +|`ValidationError`, `DeserializeError` |`invalid_public_key` +|`EncapError`, `DecapError` |`weak_public_key` +|`OpenError` |`authentication_failed` +|`MessageLimitReachedError` |`message_limit_reached` +|`DeriveKeyPairError` |`invalid_secret_key` +|=== + +*Pitfalls.* + +* The recipient opens the messages in the order they were sealed: HPKE defines +no wire format and no sequence numbers on the wire (RFC 9180 section 10). A +transport that can reorder or lose messages sets up a context per message, or +numbers them and keeps one context per stream. +* Auth mode authenticates the sender's key pair, nothing more: who the sender is +belongs in the application info (RFC 9180 section 5.1.3). A wrong sender's +public key is found only at `open`, as `authentication_failed`. +* A pre-shared key is a secret of at least 32 bytes of entropy, never a +password: HPKE does not stretch it. +* Exported secrets are compared with `secure::constant_time_equal`, never with +`==`. diff --git a/doc/secret_key_encryption.adoc b/doc/secret_key_encryption.adoc index eb06667..685202e 100644 --- a/doc/secret_key_encryption.adoc +++ b/doc/secret_key_encryption.adoc @@ -42,7 +42,7 @@ free factories (<>) forms `seal` and `open`; `aead`, the AEAD contract over the AEADs of `ciphers` | `crypto::public_key_encryption` -| constructions between key pairs: `box`, `sealed_box` +| constructions between key pairs: `box`, `sealed_box`, HPKE's `hpke::suite` (<>) | `crypto::key_exchange` diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 3771f91..44aaed0 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -1,10 +1,11 @@ { - "comment": "The data of crypto's generated tables and of llms.txt; doc/tables/generate.py reads it with the test Jamfiles, the message tests and the superproject's Jamfile fixtures, and writes doc/generated/, doc/llms.txt, include/webcpp/crypto/detail/capabilities.hpp, include/webcpp/crypto/detail/defaults.hpp and test/capabilities_test.cpp. The capability table is `families`: per family its algorithms, the targets on which each backend has it (each claimed only where a test of the family's operations on that backend runs), constant time per target where it differs from the backend's own `constant_time` (X25519 on wasip2, an open finding, and natively without arm64's DIT, the cause of both), with `constant_time_checker` naming the checker, or the list of checkers, that measured it where that is not every checker of the target, and the default per target, one whatever the program links (design D32), with its reason and the tests that fix it (a row of some of `compilers` restates its target's default for them, with a reason of their own, and each compiler of a target has one row), from which come include/webcpp/crypto/detail/defaults.hpp and the refusal that says what a program whose default is not linked needs; a backend with `targets`, where it is built, is a tag of `backends`. A name in a text is written between backticks, as Markdown writes code: the tables show it as code and llms.txt keeps the backticks. A comparison table's cell {speed:} or {constant_time:} is written from doc/performance.json or from the family's `constant_time`, and each cell of a column a namespace lists in `cited` cites a source or begins with \"none\". Edit this file, then run python3 libs/crypto/doc/tables/generate.py; the doc build runs it with --check.", + "comment": "The data of crypto's generated tables and of llms.txt; doc/tables/generate.py reads it with the test Jamfiles, the message tests and the superproject's Jamfile fixtures, and writes doc/generated/, doc/llms.txt, include/webcpp/crypto/detail/capabilities.hpp, include/webcpp/crypto/detail/defaults.hpp and test/capabilities_test.cpp. The capability table is `families`: per family its algorithms, the targets on which each backend has it (each claimed only where a test of the family's operations on that backend runs), constant time per target where it differs from the backend's own `constant_time` (X25519 on wasip2, an open finding, and natively without arm64's DIT, the cause of both), with `constant_time_checker` naming the checker, or the list of checkers, that measured it where that is not every checker of the target, and the default per target, one whatever the program links (design D32), with its reason and the tests that fix it (a row of some of `compilers` restates its target's default for them, with a reason of their own, and each compiler of a target has one row), from which come include/webcpp/crypto/detail/defaults.hpp and the refusal that says what a program whose default is not linked needs; a backend with `targets`, where it is built, is a tag of `backends`. A name in a text is written between backticks, as Markdown writes code: the tables show it as code and llms.txt keeps the backticks. A comparison table's cell {speed:} or {constant_time:} is written from doc/performance.json or from the family's `constant_time`, and each cell of a column a namespace lists in `cited` cites a source or begins with \"none\". `checkers` names the constant-time lane's checkers; one of `unjudged_checkers` prints what it measures and judges nothing, so a table gives it no result: dudect of the program `dudect_bearssl` (BearSSL, ctaes, `secure::constant_time_equal` and hash's Base58Check) on a WASI target, which judges none of its cases there by the owner's decision of 2026-12-04, as their timing under wasmtime follows the runner's processor. Edit this file, then run python3 libs/crypto/doc/tables/generate.py; the doc build runs it with --check.", "page": "https://webcpporg.github.io/libs/crypto/", "llms": "Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA and recoverable signatures, ECDH, tweaks, ElligatorSwift, MuSig2, silent payments), Ed25519 and Ed25519ph (RFC 8032), X25519 (RFC 7748), their keys in SPKI, PKCS#8 (RFC 8410) and PEM, P-256 key pairs, ECDSA and ECDH on BearSSL, libsodium's crypto_kx, the ChaCha20-Poly1305 AEADs, libsodium's secret boxes, boxes and sealed boxes, a random_device on the system's generator, each over a widely used, reviewed C library (BearSSL, OpenSSL, ctaes, libsecp256k1, libsodium) that the program names in its Jamfile. Hashing and HMAC are Boost.Hash2's; HKDF and password hashing are webcpp::hash's; the constant-time comparison, the erasure of a buffer and secret are webcpp::secure's. Every failure is a boost::system::result value. Protocols (Bitcoin, Ethereum, Nostr) belong to domain libraries built on these primitives.", "targets": ["native", "wasip2", "wasip3", "emscripten"], "compilers": {"clang": "Clang", "gcc": "GCC", "msvc": "MSVC"}, - "checkers": {"memcheck": "Valgrind's memcheck (Linux)", "msan": "MemorySanitizer (Linux, clang)", "dudect": "dudect (judged; on a runner GitHub hosts, by two of three runs)"}, + "checkers": {"memcheck": "Valgrind's memcheck (Linux)", "msan": "MemorySanitizer (Linux, clang)", "dudect": "dudect (judged; on a runner GitHub hosts, by two of three runs)", "dudect_printed": "dudect (printed, not judged: under wasmtime its timing follows the runner's processor)"}, + "unjudged_checkers": ["dudect_printed"], "sources": { "fips197": ["FIPS 197, the Advanced Encryption Standard", "https://csrc.nist.gov/pubs/fips/197/final"], "sp800-38d": ["NIST SP 800-38D, GCM and GMAC", "https://csrc.nist.gov/pubs/sp/800/38/d/final"], @@ -137,7 +138,10 @@ "musig2": ["Nick, Ruffing and Seurin, MuSig2: Simple Two-Round Schnorr Multi-Signatures, CRYPTO 2021", "https://eprint.iacr.org/2020/1261"], "bip352": ["BIP 352, Silent Payments", "https://github.com/bitcoin/bips/blob/master/bip-0352.mediawiki"], "libsecp256k1-silentpayments": ["libsecp256k1's silent payments header at webcpp's pin: the smallest outpoint, the outputs to keep, the labels to create", "https://github.com/bitcoin-core/secp256k1/blob/6e2c8bc4ecdc6e71dbe7a368f360d8d453ce435d/include/secp256k1_silentpayments.h"], - "emscripten-settings": ["Emscripten's compiler settings reference: STACK_SIZE (64 KiB, fixed) and STACK_OVERFLOW_CHECK", "https://emscripten.org/docs/tools_reference/settings_reference.html"] + "emscripten-settings": ["Emscripten's compiler settings reference: STACK_SIZE (64 KiB, fixed) and STACK_OVERFLOW_CHECK", "https://emscripten.org/docs/tools_reference/settings_reference.html"], + "rfc9180": ["RFC 9180, Hybrid Public Key Encryption", "https://www.rfc-editor.org/rfc/rfc9180"], + "rfc9180-vectors": ["RFC 9180's test vectors, cfrg/draft-irtf-cfrg-hpke at 5f503c5", "https://github.com/cfrg/draft-irtf-cfrg-hpke/blob/5f503c564da00b0687b3de75f1dfbdfc4079ad31/test-vectors.json"], + "rfc9420": ["RFC 9420, the Messaging Layer Security protocol, section 5.1", "https://www.rfc-editor.org/rfc/rfc9420#section-5.1"] }, "backends": { "bearssl": { @@ -233,8 +237,9 @@ "constant_time": "webcpp::secure's `secure::constant_time_equal`, which crypto's code calls, is constant time in the contents: every byte is read, no branch and no index depends on one", "constant_time_sources": [], "lane_paths": [ - {"what": "`secure::constant_time_equal`", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect"]}}, - {"what": "`is_all_zero` and the wipe of `secure::secret`", "lane": {"native": ["memcheck", "msan"]}} + {"what": "`secure::constant_time_equal`", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect_printed"]}}, + {"what": "`is_all_zero` and the wipe of `secure::secret`", "lane": {"native": ["memcheck", "msan"]}}, + {"what": "HPKE's composition, `public_key_encryption::hpke`: its key schedule over webcpp::hash's HKDF, the setups in base and auth_psk mode, seal, open and export, on X25519 with ChaCha20-Poly1305 (libsodium) and P-256 with AES-128-GCM (BearSSL)", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect_printed"]}} ] } }, @@ -326,8 +331,8 @@ "section": "crypto-block", "default": "`aes128<>`, `aes192<>` and `aes256<>` name the default backend; `gcm>` names AES-GCM's.", "backends": { - "openssl": {"tests": ["aes_openssl", "agreement_aes"]}, - "ctaes": {"tests": ["aes_ctaes", "agreement_aes"]}, + "openssl": {"tests": ["aes_openssl", "agreement_aes", "quic_rfc9001_openssl"]}, + "ctaes": {"tests": ["aes_ctaes", "agreement_aes", "quic_rfc9001_bearssl"]}, "bearssl": {"refused": "aes_on_bearssl"} } }, @@ -345,9 +350,9 @@ "default": "`aes128_gcm` and `aes256_gcm` name the default backend.", "backends": { "bearssl": {"tests": ["gcm_bearssl", "gcm_wycheproof_bearssl", "agreement_gcm", - "agreement_gcm_portable"]}, + "agreement_gcm_portable", "quic_rfc9001_bearssl"]}, "openssl": {"tests": ["gcm_openssl", "gcm_wycheproof_openssl", "agreement_gcm", - "agreement_gcm_portable"]}, + "agreement_gcm_portable", "quic_rfc9001_openssl"]}, "ctaes": {"refused": "gcm_on_ctaes"} } }, @@ -646,6 +651,17 @@ "default": "`sealed_box` names the default backend.", "backends": {"sodium": {"tests": ["box_sodium", "allocation_sodium"]}} }, + { + "id": "hpke", + "functions": ["suite::begin_sending", "suite::begin_receiving", "suite::seal", "suite::open", "suite::derive_from_seed", "suite::async_begin_sending", "suite::async_begin_receiving", "suite::async_seal", "suite::async_open", "suite::async_derive_from_seed"], + "namespace": "public_key_encryption", + "api": "public_key_encryption::hpke::suite", + "header": "", + "what": "RFC 9180's HPKE composed from crypto's X25519 or P-256 agreement, webcpp::hash's HKDF over pieces and crypto's AES-GCM or ChaCha20-Poly1305: suites as types, the mode following from the arguments (base, psk, auth, auth_psk), contexts that seal and open in order and export secrets, single-shot `seal` and `open`, and `derive_from_seed`, RFC 9180's DeriveKeyPair; every RFC 9180 test vector of those suites passes and OpenSSL's HPKE agrees; no backend of its own, no size cap, no allocation.", + "section": "crypto-hpke", + "default": "A suite that names no backend takes each family's default: the curve's for the key pairs, the cipher's for the AEAD.", + "backends": {"sodium": {"tests": ["hpke_vectors_default", "hpke", "hpke_async", "hpke_allocation", "timing_coverage_sodium"]}, "bearssl": {"tests": ["hpke_vectors_bearssl", "hpke_async", "hpke_allocation", "timing_coverage_bearssl"]}} + }, { "id": "recovery", "family": "secp256k1", @@ -827,7 +843,7 @@ {"targets": ["emscripten"], "backend": "bearssl", "tests": ["default_bearssl", "default_backend_all_linked_emscripten"], "why": "the only AES-GCM backend there: webcpp does not build OpenSSL for Emscripten"} ], "backends": { - "bearssl": {"targets": "all", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect"]}}, + "bearssl": {"targets": "all", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect_printed"]}}, "openssl": {"targets": "all", "lane": {"native": ["memcheck"]}, "lane_note": "seal alone: its open branches on the verdict inside OpenSSL"} } }, @@ -851,7 +867,7 @@ ], "backends": { "openssl": {"targets": "all"}, - "ctaes": {"targets": "all", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect"]}} + "ctaes": {"targets": "all", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect_printed"]}} } }, { @@ -940,7 +956,7 @@ ], "backends": { "sodium": {"targets": "all", "lane": {"native": ["memcheck", "msan"]}}, - "bearssl": {"targets": "all", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect"]}}, + "bearssl": {"targets": "all", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect_printed"]}}, "openssl": {"targets": "all", "lane": {"native": ["memcheck"]}, "lane_note": "seal alone: its open branches on the verdict inside OpenSSL"} } }, @@ -1131,7 +1147,7 @@ {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "bearssl", "tests": ["p256_keys_bearssl", "p256_ecdsa_bearssl", "p256_ecdh_bearssl", "default_backend_none_linked"], "why": "the one backend of the P-curves on all four targets, constant time by design and allocating nothing ({bearssl}); OpenSSL and Botan join in increments 8 and 7"} ], "backends": { - "bearssl": {"targets": "all", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect"]}, "lane_note": {"memcheck": "the key pair's making, `sign` of a digest (`crypto::signing_schemes::prehashed`), which makes its signature low S without a branch, then `low_s()` and `is_low_s()` of it, `agree` and the private formats, `pkcs8`, `raw` and `pem(pkcs8)` both ways; BearSSL's own branches on its signing's verdicts listed in `bearssl_verdicts.supp`; nothing found at webcpp's pin f8a2f3d, whose patches submitted upstream close upstream's leak of the nonce's bit length in `sign` that this checker found on 2026-11-21 and the jump on the scalar in P-256's scalar check that it found under `agree` on the x86-64 runner on 2026-12-03, `sign` with its low-S step included (Valgrind 3.22, arm64 Linux container, 2026-12-02; x86-64, `ctgrind` and `ctgrind_space`, 2026-12-04)", "msan": "the same paths as memcheck's; the same leak in `sign` on 2026-11-21 on upstream's BearSSL, nothing at webcpp's pin ae63032, `sign` with its low-S step included (clang 18, arm64 Linux container, 2026-12-02); MemorySanitizer checks the select of P-256's scalar check before the code generator makes it a jump, so the second patch changes nothing it sees", "dudect": "`sign` of a digest and `agree`, each against the key pair's scalar; `sign` with its low-S step judged constant time, |t| 1.70 on Linux and 1.63 natively on an Apple M5 Max (release, one run each, 2026-11-22; provisional, measured again in the final quiet pass)"}} + "bearssl": {"targets": "all", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect_printed"]}, "lane_note": {"memcheck": "the key pair's making, `sign` of a digest (`crypto::signing_schemes::prehashed`), which makes its signature low S without a branch, then `low_s()` and `is_low_s()` of it, `agree` and the private formats, `pkcs8`, `raw` and `pem(pkcs8)` both ways; BearSSL's own branches on its signing's verdicts listed in `bearssl_verdicts.supp`; nothing found at webcpp's pin f8a2f3d, whose patches submitted upstream close upstream's leak of the nonce's bit length in `sign` that this checker found on 2026-11-21 and the jump on the scalar in P-256's scalar check that it found under `agree` on the x86-64 runner on 2026-12-03, `sign` with its low-S step included (Valgrind 3.22, arm64 Linux container, 2026-12-02; x86-64, `ctgrind` and `ctgrind_space`, 2026-12-04)", "msan": "the same paths as memcheck's; the same leak in `sign` on 2026-11-21 on upstream's BearSSL, nothing at webcpp's pin ae63032, `sign` with its low-S step included (clang 18, arm64 Linux container, 2026-12-02); MemorySanitizer checks the select of P-256's scalar check before the code generator makes it a jump, so the second patch changes nothing it sees", "dudect": "`sign` of a digest and `agree`, each against the key pair's scalar; `sign` with its low-S step judged constant time, |t| 1.70 on Linux and 1.63 natively on an Apple M5 Max (release, one run each, 2026-11-22; provisional, measured again in the final quiet pass)"}} } } ], @@ -1228,7 +1244,8 @@ "rows": [ ["`box`: X25519-XSalsa20-Poly1305", "Authenticated encryption between two key pairs: X25519 agrees a key once per pair, then XSalsa20-Poly1305 seals each message; either party can have written it", "the own X25519 key pair and the peer's X25519 public key", "24 bytes, safe to draw at random ({xsalsa20})", "a 16-byte tag", "{nacl-box}, {libsodium-box}", "two parties who know each other's public keys exchange messages, in NaCl's and libsodium's format; a peer key of small order is refused"], ["`box_xchacha20poly1305`: X25519-XChaCha20-Poly1305", "The same, with XChaCha20-Poly1305 sealing each message", "the same", "24 bytes, safe to draw at random", "a 16-byte tag", "{libsodium-box}", "the peer uses libsodium's `crypto_box_curve25519xchacha20poly1305`; otherwise `box`, NaCl's format"], - ["`sealed_box`: X25519-XSalsa20-Poly1305, anonymous", "Encryption to a public key alone: a key pair drawn per message, whose public key travels with it; the recipient cannot tell who sealed it, and the sender cannot open it afterwards", "to seal, the recipient's X25519 public key; to open, the recipient's X25519 key pair", "none: derived from the two public keys", "48 bytes: the ephemeral public key and the tag", "{libsodium-sealed}", "anyone may write to a recipient who must not learn who wrote: anonymous feedback, a drop box; it proves nothing about the sender"] + ["`sealed_box`: X25519-XSalsa20-Poly1305, anonymous", "Encryption to a public key alone: a key pair drawn per message, whose public key travels with it; the recipient cannot tell who sealed it, and the sender cannot open it afterwards", "to seal, the recipient's X25519 public key; to open, the recipient's X25519 key pair", "none: derived from the two public keys", "48 bytes: the ephemeral public key and the tag", "{libsodium-sealed}", "anyone may write to a recipient who must not learn who wrote: anonymous feedback, a drop box; it proves nothing about the sender"], + ["`hpke::suite`: RFC 9180's HPKE, DHKEM(X25519 or P-256), HKDF-SHA256 or HKDF-SHA512, AES-GCM, ChaCha20-Poly1305 or export-only", "Encryption to a public key by the standard interoperable protocols use (MLS, TLS's Encrypted Client Hello): an ephemeral agreement and a key schedule set up a context that seals messages in order and exports secrets, in four modes (with a pre-shared key, an authenticated sender, or both)", "to seal, the recipient's X25519 or P-256 public key, and in the auth modes the sender's key pair; to open, the recipient's key pair, and in the auth modes the sender's public key", "none: derived from the context's sequence number", "the encapsulated key once per context (32 bytes for X25519, 65 for P-256), then a 16-byte tag per message", "{rfc9180}, {rfc9180-vectors}, {rfc9420}", "the peer speaks RFC 9180 (MLS, Marmot, any HPKE library), or one context carries ordered messages and exported keys; a sealed box when the peer is libsodium"] ] }, "key_exchange": { @@ -1276,6 +1293,7 @@ {"need": "Encrypt a record or a file under one secret key, each with a random nonce, in libsodium's secret-box format", "namespace": "webcpp::crypto::secret_key_encryption", "api": "`secretbox<>`, `secretbox_xchacha20poly1305<>`: `from_key`, `seal(nonce, data)`, `open(nonce, data, tag)`; the box forms `seal(box, nonce, data)`, `open(box, nonce, data, tag)`", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//secretbox_xsalsa20poly1305-default", "example": "file_share", "section": "crypto-secretbox"}, {"need": "Send messages between two people who know each other's public keys, as NaCl's and libsodium's crypto_box", "namespace": "webcpp::crypto::public_key_encryption", "api": "`box::from_keys`, `box::seal`, `box::open`", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//box_xsalsa20poly1305-default", "example": "box_messages", "section": "crypto-box"}, {"need": "Let anyone send a message that only the recipient can read, without saying who sent it (anonymous feedback, a drop box)", "namespace": "webcpp::crypto::public_key_encryption", "api": "`sealed_box::seal`, `sealed_box::open`", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//sealed_box-default", "example": "file_share", "section": "crypto-sealed-box"}, + {"need": "Encrypt to a public key as RFC 9180 says, byte for byte, as MLS's Welcome and UpdatePath and Marmot's backups do", "namespace": "webcpp::crypto::public_key_encryption::hpke", "api": "`suite<...>::begin_sending`, `begin_receiving`, `seal`, `open`, `derive_from_seed`; the contexts' `seal`, `open` and `export_secret`", "backend": "the defaults of X25519, P-256, AES-GCM and ChaCha20-Poly1305", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//x25519-default /webcpp/crypto//gcm-default", "example": "hpke_base", "section": "crypto-hpke"}, {"need": "Share a file with someone known only by a public key, as a file-sharing app does", "namespace": "webcpp::crypto", "api": "`secret_key_encryption::secretbox<>` for the file under a key drawn for it, `public_key_encryption::sealed_box::seal` for that key", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//secretbox_xsalsa20poly1305-default /webcpp/crypto//sealed_box-default /webcpp/crypto//x25519-default", "example": "file_share", "section": "crypto-everyday-files"}, {"need": "Make and keep a P-256 key pair, and import a browser's public key (WebCrypto's raw form), as webcpp::trystero's peers do", "namespace": "webcpp::crypto::curves::p256", "api": "`keypair::from_secret`, `keypair::generate`, `keypair::public_key`, `keypair::secret`, `public_key::from_bytes`", "backend": "BearSSL", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//p256-default", "example": "p256_keys", "section": "crypto-p256-keys"}, {"need": "Sign what a browser's WebCrypto verifies and verify what it signs (ECDSA on P-256 with SHA-256), low S where a protocol requires it, as webcpp::trystero's handshakes", "namespace": "webcpp::crypto::curves::p256", "api": "`keypair::sign(crypto::signing_schemes::ecdsa_sha256, message)`, `crypto::verify`, `signature.is_low_s()`, `signature.low_s()`; `codecs::encode` and `codecs::decode` with `crypto::formats::der` for X.509", "backend": "BearSSL", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//p256-default", "example": "p256_sign", "section": "crypto-p256-ecdsa"}, @@ -1576,7 +1594,19 @@ "chacha_header_not_included_on_emscripten": "As `chacha_header_not_included`.", "chacha_unknown_backend_on_emscripten": "As `chacha_unknown_backend`.", "chacha_openssl_on_emscripten": "Name a backend that has ChaCha20-Poly1305 on Emscripten, as in `chacha20_poly1305`, or its default, `chacha20_poly1305<>`, and link its library.", - "ed25519_unknown_policy_on_emscripten": "As `ed25519_unknown_policy`." + "ed25519_unknown_policy_on_emscripten": "As `ed25519_unknown_policy`.", + "hpke_seal_export_only": "An export-only suite only exports: call `begin_sending` and `export_secret`, or name a cipher that seals, `hpke::cipher::aes128_gcm`, `aes256_gcm` or `chacha20_poly1305`.", + "hpke_context_seal_export_only": "As `hpke_seal_export_only`: an export-only suite's contexts only export.", + "hpke_open_on_sender": "A sender's context only seals: open with the recipient's context, which `begin_receiving` makes from the sender's `encapsulated_key()`.", + "hpke_receiving_sender_keypair": "Give the recipient the sender's public key, `sender_keypair.public_key()`, never the sender's key pair.", + "hpke_sending_sender_public_key": "Auth mode authenticates the sender by its key pair: pass `sender_keypair` to `begin_sending`, its public key to `begin_receiving`.", + "hpke_psk_after_sender": "The pre-shared key comes before the sender's key, as RFC 9180's `SetupAuthPSKS(pkR, info, psk, psk_id, skS)`.", + "hpke_p256_key_x25519_suite": "A suite takes the keys of its key encapsulation's curve, `Suite::public_key_type`: an X25519 suite takes X25519 keys, and a P-256 suite such as `p256_hkdf_sha256` takes P-256 keys.", + "hpke_context_copied": "A context is moved, never copied: a copy would reuse its nonces. Keep one context per stream and `std::move` it.", + "hpke_span_as_pre_shared_key": "Write the pre-shared key with its id, `hpke::pre_shared_key{key, id}`.", + "hpke_export_length": "An export is 1 to `Suite::max_export_size` bytes (255 times the hash size); for a length known at run time, `export_secret(purpose, output)`.", + "hpke_async_asynchronous_backend": "WebCrypto has no HPKE: name a native backend for the suite, as `hpke::suite<..., backends::sodium>`, or call the synchronous forms.", + "hpke_ciphers_type_as_cipher": "Name the cipher by its HPKE tag, `hpke::cipher::aes128_gcm`, which wraps `ciphers::aes128_gcm`." }, "formats": { "comment": "The valid pairs of a format and a type (design D4), the guide's table: `list` is detail::all_formats's formats in its order (generate.py reads formats.hpp's list and refuses a difference), `forms` the point forms of `raw` and `spki`, and each type's `pairs` the formats it has, each with its exact size (`encode` writes it; a size of `der` gives its range), `secret` when its result is codecs' secret one and `encode_only` when it does not decode; a PEM's size is RFC 7468's of its inner pair's, which generate.py computes. test/formats_table_test.cpp reads this section and asserts each type's pairs, and no other, against codecs' encodable and decodable and crypto's check, and each binary size against max_encoded_size.", diff --git a/doc/tables/generate.py b/doc/tables/generate.py index aaaa4af..d85cbe1 100644 --- a/doc/tables/generate.py +++ b/doc/tables/generate.py @@ -628,6 +628,10 @@ def check_families(data: Data, declared: Dict[str, List[str]]) -> None: raise Fault(f'crypto.json: the operation {operation["id"]} names the family ' f'{operation["family"]}, which crypto.json does not list') tags = tags_of(data) + for checker in data.get('unjudged_checkers', []): + if checker not in data.get('checkers', {}): + raise Fault(f'crypto.json: unjudged_checkers names the checker {checker}, which ' + 'checkers does not list') for family in data['families']: name = family['name'] for backend, entry in family['backends'].items(): @@ -1271,11 +1275,13 @@ def lane_text(data: Data, family: Data, cite_with: Any, names_with: Any = None) """What the constant-time lane covers of a family, per backend and target, from crypto.json's `lane` of each backend: the checkers on each target, then nothing found, or the family's measured `constant_time` there, given to the checkers `constant_time_checker` names, the others - nothing found; not measured yet on the targets the lane does not run; a + nothing found; a checker of `unjudged_checkers`, which prints and judges nothing, after them, + with no result of its own; not measured yet on the targets the lane does not run; a backend's `lane_note` beside its name, or, a note of one checker, beside that checker's. Names between backticks are written by names_with, inline code by default; llms.txt keeps the backticks.""" names_with = names_with or marked + printing_only = data.get('unjudged_checkers', []) sentences: List[str] = [] for backend, entry in family['backends'].items(): title = data['backends'][backend]['title'] @@ -1291,16 +1297,25 @@ def titled(names: List[str]) -> str: for name in names]) for target in data['targets']: if target in lane: + # A checker that prints and judges nothing finds nothing: it follows the others, + # and alone it has no result. + unjudged = [name for name in lane[target] if name in printing_only] + judging = [name for name in lane[target] if name not in unjudged] + also = f', and {titled(unjudged)}' if unjudged else '' + if not judging: + result = f': {cite_with(data, found[target])}' if target in found else '' + pieces.append(f'{target}, {titled(unjudged)}{result}') + continue found_by = finders(entry, target) - others = [name for name in lane[target] if name not in (found_by or [])] + others = [name for name in judging if name not in (found_by or [])] if target in found and found_by is not None and others: # A finding of some checkers is theirs: the others found nothing. pieces.append(f'{target}, {titled(others)}, nothing found, and ' - f'{titled(found_by)}: {cite_with(data, found[target])}') + f'{titled(found_by)}: {cite_with(data, found[target])}{also}') continue result = (f': {cite_with(data, found[target])}' if target in found else ', nothing found') - pieces.append(f'{target}, {titled(lane[target])}{result}') + pieces.append(f'{target}, {titled(judging)}{result}{also}') rest = [target for target in cell_targets(data, family, backend) if target not in lane] if rest and pieces: pieces.append(f'not measured yet on {", ".join(rest)}') diff --git a/doc/tables/generate_test.py b/doc/tables/generate_test.py index 723fb12..383e40c 100644 --- a/doc/tables/generate_test.py +++ b/doc/tables/generate_test.py @@ -1704,6 +1704,36 @@ def test_a_lane_note_of_one_checker_is_written_beside_that_checker_alone(_: Path assert text.startswith('libsodium (its own tests): native, memcheck (Linux) and dudect'), text +def test_an_unjudged_checker_is_written_with_no_result(_: Path) -> None: + data = two_ciphers() + data['checkers']['printed'] = 'dudect (printed, not judged)' + data['unjudged_checkers'] = ['printed'] + for backend in data['backends'].values(): + backend.update({'library': 'l', 'constant_time': 'by design', 'constant_time_sources': []}) + entry = data['families'][0]['backends']['sodium'] + del entry['constant_time'] + entry['lane'] = {'native': ['memcheck', 'printed'], 'wasip2': ['printed']} + text = generate.lane_text(data, data['families'][0], generate.cite) + # Alone it has no result; beside a judging checker, nothing found is that checker's alone. + assert text.startswith('libsodium: native, memcheck (Linux), nothing found, and dudect ' + '(printed, not judged); wasip2, dudect (printed, not judged); not ' + 'measured yet on wasip3'), text + page = generate.constant_time_page(data) + assert '|dudect (printed, not judged): ChaCha20-Poly1305\n' in page, page + # A finding stays its own where the only checker prints. + entry['constant_time'] = {'wasip2': 'over the threshold ({rfc8439})'} + text = generate.lane_text(data, data['families'][0], generate.cite) + assert 'wasip2, dudect (printed, not judged): over the threshold' in text, text + + +def test_an_unjudged_checker_must_be_a_checker(_: Path) -> None: + data = small_table() + data['checkers'] = {'dudect': 'dudect'} + data['unjudged_checkers'] = ['printed'] + a_fault(data, {'ed25519': EVERY_TARGET}, + 'unjudged_checkers names the checker printed, which checkers does not list') + + def test_a_lane_note_of_a_checker_the_lane_does_not_run_is_a_fault(_: Path) -> None: data = small_table() data['checkers'] = {'memcheck': 'memcheck (Linux)', 'dudect': 'dudect'} @@ -1913,6 +1943,8 @@ def test_a_namespace_table_is_split_into_its_parts(_: Path) -> None: test_a_finding_s_checker_must_measure_it_there, test_a_lane_note_of_one_checker_is_written_beside_that_checker_alone, test_a_lane_note_of_a_checker_the_lane_does_not_run_is_a_fault, + test_an_unjudged_checker_is_written_with_no_result, + test_an_unjudged_checker_must_be_a_checker, test_llms_gives_no_default_where_the_family_has_none, test_a_cipher_has_its_own_default_apart_from_the_mode_built_on_it, test_a_namespace_table_is_split_into_its_parts, diff --git a/doc/testing.adoc b/doc/testing.adoc index a391f44..24aa67e 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -51,9 +51,11 @@ two fresh processes, failing when two of the three values exceed 10 native lane's command with `libs/crypto/test/constant_time//constant-time` in place of the two directories. Its paths include webcpp::hash's Base58Check, the secret encode and decode of a WIF key's payload, which hash leaves to crypto's -lane; on wasip2 dudect prints that decode's |t| without judging it, an open -finding of codecs' secret base58 conversion under wasmtime, as X25519's -agreement is there (<>). +lane; on wasip2 that decode's |t| is an open finding of codecs' secret base58 +conversion under wasmtime, as X25519's agreement is there. On a WASI target +`dudect_bearssl`, which measures BearSSL, ctaes, `secure::constant_time_equal` +and that decode, prints each case and judges none, as their timing under +wasmtime follows the runner's processor (<>). The own lane `fuzz` runs libFuzzer natively on Linux, with clang, AddressSanitizer and UndefinedBehaviorSanitizer, for 60 seconds a target from a diff --git a/example/Jamfile b/example/Jamfile index 71cf14b..c2ca3ee 100644 --- a/example/Jamfile +++ b/example/Jamfile @@ -189,6 +189,11 @@ webcpp.example file_share.cpp /webcpp/crypto//sealed_box-default /webcpp/crypto//x25519-default ; +# HPKE in base mode with MLS's suite 0x0001 on the defaults: two messages +# sealed to a derived key pair, opened in order, and an exported secret. +webcpp.example hpke_base.cpp + : /webcpp/crypto//x25519-default /webcpp/crypto//gcm-default ; + # Two people's boxes from each other's X25519 public keys, on the defaults. webcpp.example box_messages.cpp : /webcpp/crypto//box_xsalsa20poly1305-default diff --git a/example/hpke_base.cpp b/example/hpke_base.cpp new file mode 100644 index 0000000..02a01ac --- /dev/null +++ b/example/hpke_base.cpp @@ -0,0 +1,120 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// HPKE (RFC 9180) in base mode with MLS's suite 0x0001: DHKEM(X25519, HKDF-SHA256), HKDF-SHA256 +// and AES-128-GCM, on the default backends. The recipient's key pair is derived from a seed, as +// MLS derives its tree keys; the sender seals two messages to its public key on one context, and +// sends the encapsulated key with them; the recipient opens them in order. Both contexts export +// the same secret, as MLS's external join does; a message opened out of its order is refused. +// Prints what the recipient reads and whether the exports agree. +// tag::program[] +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace hpke = webcpp::crypto::public_key_encryption::hpke; + +// tag::suite[] +// MLS's suite 0x0001. +using mls_suite = hpke::suite; +// end::suite[] + +namespace { + +std::vector bytes_of(std::string_view text) { + return {text.begin(), text.end()}; +} + +void read(mls_suite::recipient_context_type& recipient, std::vector const& ciphertext, + std::span associated_data) { + std::vector plaintext(ciphertext.size() - mls_suite::tag_size); + auto const opened = recipient.open(associated_data, ciphertext, plaintext); + if (!opened) { + std::string const reason = opened.error().message(); + std::printf("refused: %s\n", reason.c_str()); + return; + } + std::printf("read: %.*s\n", static_cast(plaintext.size()), + reinterpret_cast(plaintext.data())); +} + +} // namespace + +int main() { + // The recipient's key pair, derived from 32 bytes of entropy (an MLS path secret, say). + std::array seed{}; + seed.fill(0x2a); + auto const recipient_keypair = mls_suite::derive_from_seed(seed); + if (!recipient_keypair) { + return 1; + } + auto const recipient_public_key = recipient_keypair->public_key(); + if (!recipient_public_key) { + return 1; + } + auto const application_info = bytes_of("example group context"); + auto const associated_data = bytes_of("epoch 7"); + + // tag::send[] + // The sender: base mode, to the recipient's public key, bound to the application info. + auto sender = mls_suite::begin_sending(*recipient_public_key, application_info); + if (!sender) { + return 1; + } + std::vector> sent; + for (std::string_view const text : {"first message", "second message"}) { + std::vector ciphertext(text.size() + mls_suite::tag_size); + if (!sender->seal(associated_data, bytes_of(text), ciphertext)) { + return 1; + } + sent.push_back(std::move(ciphertext)); + } + // What travels: sender->encapsulated_key().bytes() and the ciphertexts, in order. + // end::send[] + + // tag::receive[] + auto const encapsulated_key = + mls_suite::encapsulated_key_type::from_bytes(sender->encapsulated_key().bytes()); + if (!encapsulated_key) { + return 1; + } + auto recipient = + mls_suite::begin_receiving(*encapsulated_key, *recipient_keypair, application_info); + if (!recipient) { + return 1; + } + // Out of order: the second message does not open first, and the context still expects the + // first. + read(*recipient, sent[1], associated_data); + read(*recipient, sent[0], associated_data); + read(*recipient, sent[1], associated_data); + // end::receive[] + + // tag::export[] + // Both sides export the same secret for a purpose, without another message. + auto const purpose = bytes_of("response key"); + auto const sender_secret = sender->export_secret<16>(purpose); + auto const recipient_secret = recipient->export_secret<16>(purpose); + if (!sender_secret || !recipient_secret) { + return 1; + } + bool const agree = + webcpp::secure::constant_time_equal(sender_secret->bytes(), recipient_secret->bytes()); + std::printf("exports agree: %s\n", agree ? "yes" : "no"); + // end::export[] + return 0; +} + +// end::program[] diff --git a/example/hpke_base.expected b/example/hpke_base.expected new file mode 100644 index 0000000..f284d1c --- /dev/null +++ b/example/hpke_base.expected @@ -0,0 +1,4 @@ +refused: the authentication tag does not match +read: first message +read: second message +exports agree: yes diff --git a/include/webcpp/crypto.hpp b/include/webcpp/crypto.hpp index 7b5b7bb..da73d39 100644 --- a/include/webcpp/crypto.hpp +++ b/include/webcpp/crypto.hpp @@ -11,8 +11,9 @@ formats, `crypto_kx`, boxes and sealed boxes), `ciphers/aes256_gcm.hpp`, whose `aes128_gcm` and `aes256_gcm` name AES-GCM's default backend, `ciphers/aes_block.hpp`, whose `aes256<>` names the block cipher's, `ciphers/chacha20_poly1305.hpp` and `secret_key_encryption/secretbox.hpp`, whose - AEADs and secret boxes name libsodium, and `curves/p256.hpp` with its key formats, whose key pairs - name BearSSL: a program that does not link the default names another in the type, as + AEADs and secret boxes name libsodium, `curves/p256.hpp` with its key formats, whose key pairs + name BearSSL, and `public_key_encryption/hpke.hpp`, RFC 9180's HPKE, whose suites take each + family's default: a program that does not link the default names another in the type, as `ciphers::gcm>` on WebAssembly or `ciphers::chacha20_poly1305`, or, for the original ChaCha20-Poly1305, XChaCha20-Poly1305 and the secret boxes, which libsodium alone has, links libsodium. @@ -37,6 +38,7 @@ #include #include #include +#include #include // lint-world: the system's entropy, a purpose of crypto #include #include diff --git a/include/webcpp/crypto/async.hpp b/include/webcpp/crypto/async.hpp index 72b3f79..9b24105 100644 --- a/include/webcpp/crypto/async.hpp +++ b/include/webcpp/crypto/async.hpp @@ -118,6 +118,7 @@ #include #include #include +#include #include #include #include @@ -134,8 +135,11 @@ #include #include +#include #include +#include #include +#include #include #include @@ -1731,6 +1735,397 @@ auto curves::p256::basic_public_key::async_verify( } } +namespace detail { + +/** + * The refusal of HPKE's asynchronous forms on a backend that completes by itself (ruling R8): + * WebCrypto has no HPKE, and composing one from its X25519, P-256, HKDF and AES-GCM is part B's. + * + * @tparam Backend The backend that completes by itself. + */ +template +void refuse_hpke_on_asynchronous_backend() noexcept { + static_assert(dependent_false, + "webcpp::crypto: WebCrypto has no HPKE; the asynchronous HPKE calls run on a " + "native backend."); +} + +/** + * Whether a suite's key pairs or AEAD are on a backend that completes by itself. + * + * @tparam Suite The suite. + */ +template +inline constexpr bool hpke_on_asynchronous_backend_v = + asynchronous_backend_v::key_backend> || + asynchronous_backend_v::cipher_backend>; + +/** + * What an HPKE asynchronous call keeps of one argument until it runs the synchronous call: a + * view of bytes as a view (writable where the argument is), a key, an encapsulated key or a + * pre-shared key's views by value, and a key pair, which cannot be copied, by reference; each is + * the caller's until the completion. + * + * @param argument The argument. + * @return What is kept. + */ +template +[[nodiscard]] auto hpke_kept(Argument& argument) noexcept { + using argument_type = std::remove_cv_t; + if constexpr (!std::is_const_v && + std::is_convertible_v>) { + return std::span(argument); + } else if constexpr (std::is_convertible_v>) { + return std::span(argument); + } else if constexpr (std::is_nothrow_copy_constructible_v) { + return argument_type(argument); + } else { + return std::cref(argument); + } +} + +/** + * A kept argument as the synchronous call takes it: a copy of the view or value. + * + * @param kept_argument The kept argument. + * @return A copy. + */ +template +[[nodiscard]] Kept hpke_unwrapped(Kept const& kept_argument) noexcept { + return kept_argument; +} + +/** + * A kept key pair as the synchronous call takes it: the object its reference refers to. + * + * @param kept_argument The kept reference. + * @return The object. + */ +template +[[nodiscard]] Referred& hpke_unwrapped( + std::reference_wrapper const& kept_argument) noexcept { + return kept_argument.get(); +} + +/** + * Initiates an HPKE call whose arguments end with the completion token (design D8): the + * arguments before it kept (`hpke_kept`), then `synchronous_call` run on them when the operation + * is initiated and its result posted to `completion_executor`, as every cheap function's. + * + * @param completion_executor The executor the completion is posted to. + * @param synchronous_call The synchronous call, taking the kept arguments. + * @param arguments_then_token The synchronous call's arguments, then the completion token. + * @return What the completion token's `async_result` gives. + */ +template +auto hpke_complete(Executor const& completion_executor, Call synchronous_call, + Arguments&&... arguments_then_token) { + constexpr std::size_t argument_count = sizeof...(Arguments); + static_assert(argument_count >= 1, + "webcpp::crypto: an asynchronous HPKE call takes its completion token last."); + auto forwarded = std::forward_as_tuple(std::forward(arguments_then_token)...); + auto& completion_token = std::get(forwarded); + return [&](std::index_sequence) { + // Not make_tuple, which would turn a key pair's std::reference_wrapper into a reference. + std::tuple(forwarded)))...> kept{ + hpke_kept(std::get(forwarded))...}; + return complete_by_post( + completion_executor, completion_token, + [kept = std::move(kept), synchronous_call]() mutable noexcept { + return std::apply( + [&synchronous_call](auto const&... kept_arguments) noexcept { + return synchronous_call(hpke_unwrapped(kept_arguments)...); + }, + kept); + }); + }(std::make_index_sequence{}); +} + +} // namespace detail + +namespace public_key_encryption::hpke { + +/** + * Sets up a sender of `Suite`, asynchronously: the free form of `Suite::async_begin_sending`, + * which it calls with the same arguments. + * + * @tparam Suite An `hpke::suite`. + * @tparam Executor The executor's type, an Asio executor. + * @tparam Arguments One of `Suite::begin_sending`'s four argument lists, then the completion + * token's type. + * @param completion_executor The executor the completion is posted to. + * @param arguments_then_token `begin_sending`'s arguments, then the completion token, of + * signature `void(boost::system::error_code, Suite::sender_context_type)`. + * @return What the completion token's `async_result` gives. + */ +template + requires detail::is_hpke_suite_v +auto async_begin_sending(Executor const& completion_executor, Arguments&&... arguments_then_token) { + secure::timing_guard const timing_scope; + return Suite::async_begin_sending(completion_executor, + std::forward(arguments_then_token)...); +} + +/** + * Sets up a recipient of `Suite`, asynchronously: the free form of + * `Suite::async_begin_receiving`. + * + * @tparam Suite An `hpke::suite`. + * @tparam Executor The executor's type, an Asio executor. + * @tparam Arguments One of `Suite::begin_receiving`'s four argument lists, then the completion + * token's type. + * @param completion_executor The executor the completion is posted to. + * @param arguments_then_token `begin_receiving`'s arguments, then the completion token, of + * signature `void(boost::system::error_code, Suite::recipient_context_type)`. + * @return What the completion token's `async_result` gives. + */ +template + requires detail::is_hpke_suite_v +auto async_begin_receiving(Executor const& completion_executor, + Arguments&&... arguments_then_token) { + secure::timing_guard const timing_scope; + return Suite::async_begin_receiving(completion_executor, + std::forward(arguments_then_token)...); +} + +/** + * Seals one message to a public key with `Suite`, asynchronously: the free form of the + * single-shot `Suite::async_seal`. + * + * @tparam Suite An `hpke::suite` that seals. + * @tparam Executor The executor's type, an Asio executor. + * @tparam Arguments One of `Suite::seal`'s four argument lists, then the completion token's type. + * @param completion_executor The executor the completion is posted to. + * @param arguments_then_token `seal`'s arguments, then the completion token, of signature + * `void(boost::system::error_code, Suite::encapsulated_key_type)`. + * @return What the completion token's `async_result` gives. + */ +template + requires detail::is_hpke_suite_v +auto async_seal(Executor const& completion_executor, Arguments&&... arguments_then_token) { + secure::timing_guard const timing_scope; + return Suite::async_seal(completion_executor, std::forward(arguments_then_token)...); +} + +/** + * Opens one message with `Suite`, asynchronously: the free form of the single-shot + * `Suite::async_open`. + * + * @tparam Suite An `hpke::suite` that seals. + * @tparam Executor The executor's type, an Asio executor. + * @tparam Arguments One of `Suite::open`'s four argument lists, then the completion token's type. + * @param completion_executor The executor the completion is posted to. + * @param arguments_then_token `open`'s arguments, then the completion token, of signature + * `void(boost::system::error_code)`. + * @return What the completion token's `async_result` gives. + */ +template + requires detail::is_hpke_suite_v +auto async_open(Executor const& completion_executor, Arguments&&... arguments_then_token) { + secure::timing_guard const timing_scope; + return Suite::async_open(completion_executor, std::forward(arguments_then_token)...); +} + +/** + * Seals the next message on a sender's context, asynchronously: the free form of + * `sender.async_seal`, which it calls with the arguments after `sender`. + * + * @tparam Executor The executor's type, an Asio executor. + * @tparam Suite The context's suite, deduced. + * @tparam CompletionToken Any completion token for the signature `void(boost::system::error_code)`. + * @param completion_executor The executor the completion is posted to. + * @param sender The sender's context, the caller's until the completion. + * @param associated_data Authenticated, not encrypted. + * @param plaintext The message. + * @param ciphertext `plaintext.size() + Suite::tag_size` bytes. + * @param completion_token The completion token, of signature `void(boost::system::error_code)`. + * @return What the completion token's `async_result` gives. + */ +template +auto async_seal(Executor const& completion_executor, sender_context& sender, + std::span associated_data, + std::span plaintext, std::span ciphertext, + CompletionToken&& completion_token) { + secure::timing_guard const timing_scope; + return sender.async_seal(completion_executor, associated_data, plaintext, ciphertext, + std::forward(completion_token)); +} + +/** + * Opens the next message on a recipient's context, asynchronously: the free form of + * `recipient.async_open`, which it calls with the arguments after `recipient`. + * + * @tparam Executor The executor's type, an Asio executor. + * @tparam Suite The context's suite, deduced. + * @tparam CompletionToken Any completion token for the signature `void(boost::system::error_code)`. + * @param completion_executor The executor the completion is posted to. + * @param recipient The recipient's context, the caller's until the completion. + * @param associated_data The associated data of the seal. + * @param ciphertext The ciphertext then the tag. + * @param plaintext `ciphertext.size() - Suite::tag_size` bytes. + * @param completion_token The completion token, of signature `void(boost::system::error_code)`. + * @return What the completion token's `async_result` gives. + */ +template +auto async_open(Executor const& completion_executor, recipient_context& recipient, + std::span associated_data, + std::span ciphertext, std::span plaintext, + CompletionToken&& completion_token) { + secure::timing_guard const timing_scope; + return recipient.async_open(completion_executor, associated_data, ciphertext, plaintext, + std::forward(completion_token)); +} + +/** + * Derives a key pair of `Suite` from a seed, asynchronously: the free form of + * `Suite::async_derive_from_seed`. + * + * @tparam Suite An `hpke::suite`. + * @tparam Executor The executor's type, an Asio executor. + * @tparam CompletionToken Any completion token for the signature `completion_token` states. + * @param completion_executor The executor the completion is posted to. + * @param seed The seed, the caller's until the completion. + * @param completion_token The completion token, of signature + * `void(boost::system::error_code, Suite::recipient_keypair_type)`. + * @return What the completion token's `async_result` gives. + */ +template + requires detail::is_hpke_suite_v +auto async_derive_from_seed(Executor const& completion_executor, std::span seed, + CompletionToken&& completion_token) { + secure::timing_guard const timing_scope; + return Suite::async_derive_from_seed(completion_executor, seed, + std::forward(completion_token)); +} + +} // namespace public_key_encryption::hpke + +template +template +auto public_key_encryption::hpke::suite:: + async_begin_sending(Executor const& completion_executor, Arguments&&... arguments_then_token) { + secure::timing_guard const timing_scope; + if constexpr (detail::hpke_on_asynchronous_backend_v) { + detail::refuse_hpke_on_asynchronous_backend(); + } else { + return detail::hpke_complete( + completion_executor, + [](auto const&... setup_arguments) noexcept { + return suite::begin_sending(setup_arguments...); + }, + std::forward(arguments_then_token)...); + } +} + +template +template +auto public_key_encryption::hpke::suite:: + async_begin_receiving(Executor const& completion_executor, + Arguments&&... arguments_then_token) { + secure::timing_guard const timing_scope; + if constexpr (detail::hpke_on_asynchronous_backend_v) { + detail::refuse_hpke_on_asynchronous_backend(); + } else { + return detail::hpke_complete( + completion_executor, + [](auto const&... setup_arguments) noexcept { + return suite::begin_receiving(setup_arguments...); + }, + std::forward(arguments_then_token)...); + } +} + +template +template +auto public_key_encryption::hpke::suite::async_seal(Executor const& completion_executor, + Arguments&&... arguments_then_token) { + secure::timing_guard const timing_scope; + if constexpr (detail::hpke_on_asynchronous_backend_v) { + detail::refuse_hpke_on_asynchronous_backend(); + } else { + return detail::hpke_complete( + completion_executor, + [](auto const&... seal_arguments) noexcept { return suite::seal(seal_arguments...); }, + std::forward(arguments_then_token)...); + } +} + +template +template +auto public_key_encryption::hpke::suite::async_open(Executor const& completion_executor, + Arguments&&... arguments_then_token) { + secure::timing_guard const timing_scope; + if constexpr (detail::hpke_on_asynchronous_backend_v) { + detail::refuse_hpke_on_asynchronous_backend(); + } else { + return detail::hpke_complete( + completion_executor, + [](auto const&... open_arguments) noexcept { return suite::open(open_arguments...); }, + std::forward(arguments_then_token)...); + } +} + +template +template +auto public_key_encryption::hpke::suite:: + async_derive_from_seed(Executor const& completion_executor, std::span seed, + CompletionToken&& completion_token) { + secure::timing_guard const timing_scope; + if constexpr (detail::hpke_on_asynchronous_backend_v) { + detail::refuse_hpke_on_asynchronous_backend(); + } else { + return detail::complete_by_post(completion_executor, completion_token, [seed]() noexcept { + return suite::derive_from_seed(seed); + }); + } +} + +template +template +auto public_key_encryption::hpke::sender_context::async_seal( + Executor const& completion_executor, std::span associated_data, + std::span plaintext, std::span ciphertext, + CompletionToken&& completion_token) { + secure::timing_guard const timing_scope; + if constexpr (detail::hpke_on_asynchronous_backend_v) { + detail::refuse_hpke_on_asynchronous_backend(); + } else { + return detail::complete_by_post(completion_executor, completion_token, + [this, associated_data, plaintext, ciphertext]() noexcept { + return seal(associated_data, plaintext, ciphertext); + }); + } +} + +template +template +auto public_key_encryption::hpke::recipient_context::async_open( + Executor const& completion_executor, std::span associated_data, + std::span ciphertext, std::span plaintext, + CompletionToken&& completion_token) { + secure::timing_guard const timing_scope; + if constexpr (detail::hpke_on_asynchronous_backend_v) { + detail::refuse_hpke_on_asynchronous_backend(); + } else { + return detail::complete_by_post(completion_executor, completion_token, + [this, associated_data, ciphertext, plaintext]() noexcept { + return open(associated_data, ciphertext, plaintext); + }); + } +} + } // namespace webcpp::crypto #endif // WEBCPP_CRYPTO_ASYNC_HPP diff --git a/include/webcpp/crypto/error.hpp b/include/webcpp/crypto/error.hpp index 4e5381b..b42d4e2 100644 --- a/include/webcpp/crypto/error.hpp +++ b/include/webcpp/crypto/error.hpp @@ -108,6 +108,11 @@ enum class error : int { invalid_encoding = 19, /** A KEM or RSA ciphertext of another size than the key's. */ invalid_ciphertext_size = 20, + /** + * An HPKE context has sealed or opened as many messages as its nonce allows: its 64-bit + * sequence number reached 2^64 - 1 (RFC 9180's `MessageLimitReachedError`). + */ + message_limit_reached = 21, }; namespace detail { @@ -145,6 +150,8 @@ inline const char* message_of(int error_value) noexcept { case error::invalid_padding: return "the padding is not valid"; case error::invalid_encoding: return "the encoding does not decode"; case error::invalid_ciphertext_size: return "the ciphertext is not of the key's size"; + case error::message_limit_reached: + return "the context has sealed or opened as many messages as its nonce allows"; } return "unknown webcpp.crypto error"; } diff --git a/include/webcpp/crypto/public_key_encryption/hpke.hpp b/include/webcpp/crypto/public_key_encryption/hpke.hpp new file mode 100644 index 0000000..f83133c --- /dev/null +++ b/include/webcpp/crypto/public_key_encryption/hpke.hpp @@ -0,0 +1,1320 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + HPKE, RFC 9180's Hybrid Public Key Encryption, composed from crypto's own primitives: + `hpke::suite`, whose `begin_sending` and + `begin_receiving` make the two contexts, whose single-shot `seal` and `open` encrypt one message + to a public key, and whose `derive_from_seed` is RFC 9180's `DeriveKeyPair`; with the free forms + of each in `hpke`. + + The mode follows from the arguments, with no mode tag: `begin_sending(recipient_public_key, + application_info)` is base mode; adding an `hpke::pre_shared_key{key, id}` is psk; adding the + sender's key pair is auth; both, in that order, auth_psk. `begin_receiving` mirrors it with the + sender's public key. An argument list that is none of those stops the build with one message + listing them. No variable-length input has a cap (MLS puts kilobytes into `application_info`); + nothing is allocated. + + It includes its three parts, `hpke/key_derivation.hpp`, `hpke/key_encapsulation.hpp` and + `hpke/context.hpp`; each suite's key pairs and AEAD are their families' on their backends, whose + headers come with the curves' and ciphers' headers when the program links the defaults. + + @code + // exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//x25519-default + // /webcpp/crypto//gcm-default ; + namespace hpke = webcpp::crypto::public_key_encryption::hpke; + // MLS's suite 0x0001: DHKEM(X25519, HKDF-SHA256), HKDF-SHA256, AES-128-GCM. + using mls_suite = hpke::suite; + auto sender = mls_suite::begin_sending(recipient_public_key, application_info); + // sender->encapsulated_key() goes to the recipient with each sender->seal(...)'s output. + @endcode + + @see "HPKE (RFC 9180)", in the guide. +*/ +#ifndef WEBCPP_CRYPTO_PUBLIC_KEY_ENCRYPTION_HPKE_HPP +#define WEBCPP_CRYPTO_PUBLIC_KEY_ENCRYPTION_HPKE_HPP + +#include + +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include + +namespace webcpp::crypto::public_key_encryption::hpke { + +/** + * A pre-shared key and its identifier (RFC 9180's `psk` and `psk_id`), written + * `hpke::pre_shared_key{key, id}` at the call that sets up psk or auth_psk mode. + * + * It views the caller's bytes and owns nothing: the caller keeps the key and erases it with + * `secure::erase_secret`. A key shorter than 32 bytes and an empty id are refused. + */ +struct pre_shared_key { + /** The key, at least 32 bytes of entropy; no upper bound. */ + std::span key{}; + /** The key's identifier, not empty; no upper bound, any bytes. */ + std::span id{}; +}; + +template +struct suite; + +} // namespace webcpp::crypto::public_key_encryption::hpke + +namespace webcpp::crypto::detail { + +/** + * Whether `Type` is an `hpke::suite`. + * + * @tparam Type A type. + */ +template +inline constexpr bool is_hpke_suite_v = false; + +template +inline constexpr bool is_hpke_suite_v< + public_key_encryption::hpke::suite> = true; + +/** + * The types of a call's arguments, which a catch-all's assertion names so that it fails only when + * the catch-all is called. + * + * @tparam Arguments The arguments' types. + */ +template +struct hpke_arguments {}; + +/** + * Whether `Type` is an HPKE context, a sender's or a recipient's. + * + * @tparam Type A type. + */ +template +inline constexpr bool is_hpke_context_v = false; + +template +inline constexpr bool is_hpke_context_v> = true; + +template +inline constexpr bool is_hpke_context_v> = + true; + +/** + * The size of a suite's tag, which a suite that seals names. + * + * @tparam Cipher The cipher. + */ +template +struct hpke_tag_size { + /** The tag's size, `Nt`, by which a ciphertext is longer than its plaintext. */ + static constexpr std::size_t tag_size = Cipher::tag_size; +}; + +/** An export-only suite has no tag. */ +template <> +struct hpke_tag_size {}; + +/** + * The argument lists of the four modes, declared only, which the catch-alls of `begin_sending`, + * `begin_receiving`, `seal` and `open` test a call against (design B2). + * + * @tparam Suite The suite. + */ +template +struct hpke_forms { + /** A view of bytes. */ + using bytes = std::span; + /** A writable view of bytes. */ + using output = std::span; + /** The public key. */ + using public_key = Suite::public_key_type; + /** The key pair. */ + using keypair = Suite::recipient_keypair_type; + /** The encapsulated key. */ + using encapsulated = Suite::encapsulated_key_type; + /** The pre-shared key. */ + using shared = public_key_encryption::hpke::pre_shared_key; + + /** Base. */ + static void sending(public_key const&, bytes); + /** Psk. */ + static void sending(public_key const&, bytes, shared const&); + /** Auth. */ + static void sending(public_key const&, bytes, keypair const&); + /** Auth_psk. */ + static void sending(public_key const&, bytes, shared const&, keypair const&); + /** Base. */ + static void receiving(encapsulated const&, keypair const&, bytes); + /** Psk. */ + static void receiving(encapsulated const&, keypair const&, bytes, shared const&); + /** Auth. */ + static void receiving(encapsulated const&, keypair const&, bytes, public_key const&); + /** Auth_psk. */ + static void receiving(encapsulated const&, keypair const&, bytes, shared const&, + public_key const&); + /** Base. */ + static void sealing(public_key const&, bytes, bytes, bytes, output); + /** Psk. */ + static void sealing(public_key const&, bytes, bytes, bytes, output, shared const&); + /** Auth. */ + static void sealing(public_key const&, bytes, bytes, bytes, output, keypair const&); + /** Auth_psk. */ + static void sealing(public_key const&, bytes, bytes, bytes, output, shared const&, + keypair const&); + /** Base. */ + static void opening(encapsulated const&, keypair const&, bytes, bytes, bytes, output); + /** Psk. */ + static void opening(encapsulated const&, keypair const&, bytes, bytes, bytes, output, + shared const&); + /** Auth. */ + static void opening(encapsulated const&, keypair const&, bytes, bytes, bytes, output, + public_key const&); + /** Auth_psk. */ + static void opening(encapsulated const&, keypair const&, bytes, bytes, bytes, output, + shared const&, public_key const&); +}; + +/** + * Whether `Arguments` are one of `begin_sending`'s four argument lists. + * + * @tparam Suite The suite. + * @tparam Arguments The arguments' types. + */ +template +concept hpke_sending_arguments = requires(Arguments&&... arguments) { + hpke_forms::sending(std::forward(arguments)...); +}; + +/** + * Whether `Arguments` are one of `begin_receiving`'s four argument lists. + * + * @tparam Suite The suite. + * @tparam Arguments The arguments' types. + */ +template +concept hpke_receiving_arguments = requires(Arguments&&... arguments) { + hpke_forms::receiving(std::forward(arguments)...); +}; + +/** + * Whether `Arguments` are one of the single-shot `seal`'s four argument lists. + * + * @tparam Suite The suite. + * @tparam Arguments The arguments' types. + */ +template +concept hpke_sealing_arguments = requires(Arguments&&... arguments) { + hpke_forms::sealing(std::forward(arguments)...); +}; + +/** + * Whether `Arguments` are one of the single-shot `open`'s four argument lists. + * + * @tparam Suite The suite. + * @tparam Arguments The arguments' types. + */ +template +concept hpke_opening_arguments = requires(Arguments&&... arguments) { + hpke_forms::opening(std::forward(arguments)...); +}; + +/** The setups of a suite (defined below). */ +template +struct hpke_setup; + +/** + * The maker of HPKE's contexts and the seam of its tests (ruling R9): the deterministic + * ephemeral key of RFC 9180's test vectors and a context's sequence number. + */ +struct hpke_access { + /** + * Makes a sender's context from its core and its encapsulated key. + * + * @tparam Suite The suite. + * @param made_core The keyed core. + * @param made_key The encapsulated key. + * @return The context. + */ + template + [[nodiscard]] static boost::system::result> + made_sender(hpke_context_core&& made_core, + Suite::encapsulated_key_type const& made_key) noexcept { + public_key_encryption::hpke::sender_context made_context(std::move(made_core), + made_key); + return made_context; + } + + /** + * Makes a recipient's context from its core. + * + * @tparam Suite The suite. + * @param made_core The keyed core. + * @return The context. + */ + template + [[nodiscard]] static boost::system::result< + public_key_encryption::hpke::recipient_context> + made_recipient(hpke_context_core&& made_core) noexcept { + public_key_encryption::hpke::recipient_context made_context(std::move(made_core)); + return made_context; + } + + /** + * The test seam (ruling R9): `begin_sending` with an ephemeral key pair derived from + * `ephemeral_seed`, as RFC 9180's test vectors give it (`ikmE`). A program that uses it reuses + * an ephemeral key at its own peril. + * + * @tparam Suite The suite. + * @param ephemeral_seed `ikmE`. + * @param recipient_public_key `pkR`. + * @param application_info `info`. + * @param pre_shared_key The pre-shared key, or null. + * @param sender_keypair `skS`, or null. + * @return What `begin_sending` returns. + */ + template + [[nodiscard]] static boost::system::result> + begin_sending_with_ephemeral_seed( + std::span ephemeral_seed, + Suite::public_key_type const& recipient_public_key, + std::span application_info, + public_key_encryption::hpke::pre_shared_key const* pre_shared_key, + Suite::sender_keypair_type const* sender_keypair) noexcept { + return hpke_setup::send(recipient_public_key, application_info, pre_shared_key, + sender_keypair, &ephemeral_seed); + } + + /** + * A context's sequence number. + * + * @tparam Context A sender's or a recipient's context. + * @param context The context. + * @return Its sequence number. + */ + template + [[nodiscard]] static std::uint64_t sequence(Context const& context) noexcept { + return context.core_.sequence(); + } + + /** + * Sets a context's sequence number, to check the last message without 2^64 seals. + * + * @tparam Context A sender's or a recipient's context. + * @param context The context. + * @param sequence_number The number. + */ + template + static void set_sequence(Context& context, std::uint64_t sequence_number) noexcept { + context.core_.set_sequence(sequence_number); + } +}; + +/** + * The two setups of a suite (RFC 9180 section 5.1.1 to 5.1.4), every mode in one: a null + * pre-shared key or sender's key leaves the mode without it. + * + * @tparam Suite The suite. + */ +template +struct hpke_setup { + /** The key encapsulation. */ + using key_encapsulation = Suite::key_encapsulation_type; + /** The key pairs' backend. */ + using key_backend = hpke_backends_t::key_backend; + /** The DHKEM on the key backend. */ + using dhkem = hpke_dhkem; + /** The key pair. */ + using keypair_type = Suite::recipient_keypair_type; + /** The public key. */ + using public_key_type = Suite::public_key_type; + /** The pre-shared key. */ + using shared_key = public_key_encryption::hpke::pre_shared_key; + + /** + * RFC 9180's lower bounds of a pre-shared key (ruling R6). + * + * @param pre_shared_key The pre-shared key, or null. + * @return Nothing; `invalid_key_size` for a key shorter than 32 bytes; `invalid_input_size` + * for an empty id. + */ + [[nodiscard]] static boost::system::result checked( + shared_key const* pre_shared_key) noexcept { + if (pre_shared_key == nullptr) { + return {}; + } + if (pre_shared_key->key.size() < 32) { + return error::invalid_key_size; + } + if (pre_shared_key->id.empty()) { + return error::invalid_input_size; + } + return {}; + } + + /** + * The mode of a setup: 0x00 base, 0x01 psk, 0x02 auth, 0x03 auth_psk. + * + * @param with_key Whether a pre-shared key is given. + * @param with_sender Whether the sender is authenticated. + * @return The mode. + */ + [[nodiscard]] static constexpr std::uint8_t mode_of(bool with_key, bool with_sender) noexcept { + return static_cast((with_key ? 1U : 0U) | (with_sender ? 2U : 0U)); + } + + /** + * RFC 9180's `SetupBaseS` to `SetupAuthPSKS`: the key encapsulation with an ephemeral key pair + * drawn by `generate()`, or derived from `ephemeral_seed` for the test seam, then the key + * schedule. + * + * @param recipient_public_key `pkR`. + * @param application_info `info`. + * @param pre_shared_key The pre-shared key, or null. + * @param sender_keypair `skS`, or null. + * @param ephemeral_seed The test seam's `ikmE`, or null. + * @return The sender's context, or the first error. + */ + [[nodiscard]] static boost::system::result> + send(public_key_type const& recipient_public_key, + std::span application_info, shared_key const* pre_shared_key, + keypair_type const* sender_keypair, + std::span const* ephemeral_seed) noexcept { + auto const key_checked = checked(pre_shared_key); + if (!key_checked) { + return key_checked.error(); + } + auto const ephemeral_keypair = + ephemeral_seed != nullptr + ? key_encapsulation::template derive_from_seed(*ephemeral_seed) + : keypair_type::generate(); + if (!ephemeral_keypair) { + return ephemeral_keypair.error(); + } + auto encapsulated = dhkem::encapsulate(recipient_public_key, + ephemeral_keypair.unsafe_value(), sender_keypair); + if (!encapsulated) { + return encapsulated.error(); + } + auto core = keyed_core(mode_of(pre_shared_key != nullptr, sender_keypair != nullptr), + encapsulated.unsafe_value().shared_secret.bytes(), application_info, + pre_shared_key); + if (!core) { + return core.error(); + } + return hpke_access::made_sender(std::move(core).unsafe_value(), + encapsulated.unsafe_value().encapsulated_key); + } + + /** + * RFC 9180's `SetupBaseR` to `SetupAuthPSKR`: the key decapsulation, then the key schedule. + * + * @param encapsulated_key `enc`. + * @param recipient_keypair `skR`. + * @param application_info `info`. + * @param pre_shared_key The pre-shared key, or null. + * @param sender_public_key `pkS`, or null. + * @return The recipient's context, or the first error. + */ + [[nodiscard]] static boost::system::result< + public_key_encryption::hpke::recipient_context> + receive(Suite::encapsulated_key_type const& encapsulated_key, + keypair_type const& recipient_keypair, std::span application_info, + shared_key const* pre_shared_key, public_key_type const* sender_public_key) noexcept { + auto const key_checked = checked(pre_shared_key); + if (!key_checked) { + return key_checked.error(); + } + auto const shared_secret = + dhkem::decapsulate(encapsulated_key, recipient_keypair, sender_public_key); + if (!shared_secret) { + return shared_secret.error(); + } + auto core = + keyed_core(mode_of(pre_shared_key != nullptr, sender_public_key != nullptr), + shared_secret.unsafe_value().bytes(), application_info, pre_shared_key); + if (!core) { + return core.error(); + } + return hpke_access::made_recipient(std::move(core).unsafe_value()); + } + +private: + /** + * The key schedule and the AEAD keyed from it. + * + * @param mode The mode. + * @param shared_secret The key encapsulation's shared secret. + * @param application_info `info`. + * @param pre_shared_key The pre-shared key, or null. + * @return The context's core; the first error. + */ + [[nodiscard]] static boost::system::result> keyed_core( + std::uint8_t mode, std::span shared_secret, + std::span application_info, shared_key const* pre_shared_key) noexcept { + auto schedule = hpke_key_schedule( + mode, shared_secret, application_info, + pre_shared_key != nullptr ? pre_shared_key->key : std::span{}, + pre_shared_key != nullptr ? pre_shared_key->id : std::span{}); + if (!schedule) { + return schedule.error(); + } + return hpke_context_core::from_schedule(schedule.unsafe_value()); + } +}; + +} // namespace webcpp::crypto::detail + +namespace webcpp::crypto::public_key_encryption::hpke { + +/** + * An HPKE suite (RFC 9180): a key encapsulation, a key derivation and a cipher, on their + * backends; its static members set up the two contexts, seal and open one message, and derive a + * key pair from a seed. + * + * Every combination of the parameters is RFC 9180's: `key_encapsulation::x25519_hkdf_sha256` or + * `p256_hkdf_sha256`, `key_derivation::hkdf_sha256` or `hkdf_sha512`, and `cipher::aes128_gcm`, + * `aes256_gcm`, `chacha20_poly1305` or `export_only`. MLS's suite 0x0001 is + * `suite`. It is never instantiated. + * + * The mode follows from the arguments (design D7): + * + * | Mode | Sending | Receiving | + * |---|---|---| + * | base | `begin_sending(recipient_public_key, application_info)` | `begin_receiving(encapsulated_key, recipient_keypair, application_info)` | + * | psk | adds `pre_shared_key` | adds `pre_shared_key` | + * | auth | adds `sender_keypair` | adds `sender_public_key` | + * | auth_psk | adds `pre_shared_key, sender_keypair` | adds `pre_shared_key, sender_public_key` | + * + * @tparam KeyEncapsulation A `key_encapsulation_mechanism`. + * @tparam KeyDerivation A `key_derivation_function`. + * @tparam Cipher A `suite_cipher`. + * @tparam Backend `default_backends`, each family's default; one backend that serves the curve + * and the cipher both (`backends::bearssl` serves P-256 and every cipher); or + * `hpke::backends`. + */ +template +struct suite : detail::hpke_tag_size { +private: + using backends_of = detail::hpke_backends_of; + using setup = detail::hpke_setup; + +public: + /** The key encapsulation. */ + using key_encapsulation_type = KeyEncapsulation; + /** The key derivation of the key schedule and the exports. */ + using key_derivation_type = KeyDerivation; + /** The cipher. */ + using cipher_type = Cipher; + /** The `Backend` argument, as given. */ + using backend_type = Backend; + /** The recipient's key pair, `skR`: the key encapsulation's on the key backend. */ + using recipient_keypair_type = + KeyEncapsulation::template keypair_type; + /** The sender's key pair, `skS`, of auth modes: the same type. */ + using sender_keypair_type = recipient_keypair_type; + /** A public key, `pkR` or `pkS`. */ + using public_key_type = + KeyEncapsulation::template public_key_type; + /** The encapsulated key, `enc`. */ + using encapsulated_key_type = KeyEncapsulation::encapsulated_key; + /** The sender's context. */ + using sender_context_type = sender_context; + /** The recipient's context. */ + using recipient_context_type = recipient_context; + /** The size of the encapsulated key, `Nenc`. */ + static constexpr std::size_t encapsulated_key_size = KeyEncapsulation::encapsulated_key_size; + /** The longest export, `255 * Nh` bytes. */ + static constexpr std::size_t max_export_size = 255 * KeyDerivation::hash_size; + + /** Never instantiated: its members are static. */ + suite() = delete; + + /** + * Sets up a sender in base mode (RFC 9180's `SetupBaseS`): an ephemeral key pair drawn from + * the system's generator, its agreement with the recipient's key, then the key schedule. + * + * @param recipient_public_key The recipient's public key, `pkR`. + * @param application_info `info`: what the messages are for, bound into every key; of any + * length. + * @return The sender's context, whose `encapsulated_key()` goes to the recipient; + * `entropy_unavailable`; `weak_public_key` for an X25519 key of small order; + * `backend_failure`. + */ + [[nodiscard]] static boost::system::result begin_sending( + public_key_type const& recipient_public_key, + std::span application_info) noexcept { + secure::timing_guard const timing_scope; + return setup::send(recipient_public_key, application_info, nullptr, nullptr, nullptr); + } + + /** + * Sets up a sender in psk mode (RFC 9180's `SetupPSKS`): base mode's, with a pre-shared key + * bound into the key schedule. + * + * @param recipient_public_key The recipient's public key, `pkR`. + * @param application_info `info`, of any length. + * @param pre_shared_key `{key, id}`: a key of at least 32 bytes and a non-empty id. + * @return The sender's context; `invalid_key_size` for a key shorter than 32 bytes; + * `invalid_input_size` for an empty id; base mode's errors. + */ + [[nodiscard]] static boost::system::result begin_sending( + public_key_type const& recipient_public_key, std::span application_info, + hpke::pre_shared_key const& pre_shared_key) noexcept { + secure::timing_guard const timing_scope; + return setup::send(recipient_public_key, application_info, &pre_shared_key, nullptr, + nullptr); + } + + /** + * Sets up a sender in auth mode (RFC 9180's `SetupAuthS`): base mode's, with a second + * agreement, of the sender's key pair with the recipient's key, which authenticates the + * sender to a recipient that knows the sender's public key. + * + * @param recipient_public_key The recipient's public key, `pkR`. + * @param application_info `info`, of any length. + * @param sender_keypair The sender's key pair, `skS`. + * @return The sender's context; `invalid_state` for a key pair moved from; base mode's + * errors. + */ + [[nodiscard]] static boost::system::result begin_sending( + public_key_type const& recipient_public_key, std::span application_info, + sender_keypair_type const& sender_keypair) noexcept { + secure::timing_guard const timing_scope; + return setup::send(recipient_public_key, application_info, nullptr, &sender_keypair, + nullptr); + } + + /** + * Sets up a sender in auth_psk mode (RFC 9180's `SetupAuthPSKS`): auth mode's, with a + * pre-shared key. + * + * @param recipient_public_key The recipient's public key, `pkR`. + * @param application_info `info`, of any length. + * @param pre_shared_key `{key, id}`: a key of at least 32 bytes and a non-empty id. + * @param sender_keypair The sender's key pair, `skS`. + * @return The sender's context; psk mode's and auth mode's errors. + */ + [[nodiscard]] static boost::system::result begin_sending( + public_key_type const& recipient_public_key, std::span application_info, + hpke::pre_shared_key const& pre_shared_key, + sender_keypair_type const& sender_keypair) noexcept { + secure::timing_guard const timing_scope; + return setup::send(recipient_public_key, application_info, &pre_shared_key, &sender_keypair, + nullptr); + } + + /** + * An argument list that is none of the four: stops the build with the message that lists + * them (design B2). + * + * @tparam Arguments The arguments' types. + * @return Never: the build stops. + */ + template + requires(!detail::hpke_sending_arguments) + [[nodiscard]] static boost::system::result begin_sending( + Arguments&&... /*arguments*/) noexcept { + static_assert(detail::dependent_false>, + "webcpp::crypto: hpke begin_sending takes one of four argument lists, the " + "mode following from them: (recipient_public_key, application_info) for " + "base; (recipient_public_key, application_info, pre_shared_key) for psk; " + "(recipient_public_key, application_info, sender_keypair) for auth; " + "(recipient_public_key, application_info, pre_shared_key, sender_keypair) " + "for auth_psk; each key of the suite's own types, the pre-shared key " + "written hpke::pre_shared_key{key, id}."); + return error::invalid_state; + } + + /** + * Sets up a sender, asynchronously: `begin_sending` run with the arguments between the + * executor and the token when the operation is initiated, its result posted to + * `completion_executor`; the member form of + * `hpke::async_begin_sending`. + * + * The keys and the bytes the arguments view are the caller's until the completion. Declared + * here and defined in ``, which a program includes to call it, with + * `/webcpp/asio//asio` in its Jamfile. On a backend that completes by itself (the + * browser's) it stops the build: WebCrypto has no HPKE. + * + * @tparam Executor The executor's type, an Asio executor. + * @tparam Arguments One of `begin_sending`'s four argument lists, then the completion + * token's type. + * @param completion_executor The executor the completion is posted to. + * @param arguments_then_token `begin_sending`'s arguments, then the completion token, of + * signature `void(boost::system::error_code, sender_context_type)`; on an error the context + * is empty and refuses every call with `invalid_state`. + * @return What the completion token's `async_result` gives. + */ + template + static auto async_begin_sending(Executor const& completion_executor, + Arguments&&... arguments_then_token); + + /** + * Sets up a recipient in base mode (RFC 9180's `SetupBaseR`): the encapsulated key's + * agreement with the recipient's key pair, then the key schedule. + * + * @param encapsulated_key `enc`, as the sender's context gave it. + * @param recipient_keypair The recipient's key pair, `skR`. + * @param application_info `info`, the sender's. + * @return The recipient's context; `invalid_public_key` for a P-256 encapsulated key that is + * not a point of the curve; `weak_public_key` for an X25519 one of small order; + * `invalid_state` for a key pair moved from; `backend_failure`. + */ + [[nodiscard]] static boost::system::result begin_receiving( + encapsulated_key_type const& encapsulated_key, + recipient_keypair_type const& recipient_keypair, + std::span application_info) noexcept { + secure::timing_guard const timing_scope; + return setup::receive(encapsulated_key, recipient_keypair, application_info, nullptr, + nullptr); + } + + /** + * Sets up a recipient in psk mode (RFC 9180's `SetupPSKR`). + * + * @param encapsulated_key `enc`. + * @param recipient_keypair The recipient's key pair, `skR`. + * @param application_info `info`, the sender's. + * @param pre_shared_key `{key, id}`, the sender's. + * @return The recipient's context; `invalid_key_size` for a key shorter than 32 bytes; + * `invalid_input_size` for an empty id; base mode's errors. A different key or id is found + * at `open`, as `authentication_failed`. + */ + [[nodiscard]] static boost::system::result begin_receiving( + encapsulated_key_type const& encapsulated_key, + recipient_keypair_type const& recipient_keypair, + std::span application_info, + hpke::pre_shared_key const& pre_shared_key) noexcept { + secure::timing_guard const timing_scope; + return setup::receive(encapsulated_key, recipient_keypair, application_info, + &pre_shared_key, nullptr); + } + + /** + * Sets up a recipient in auth mode (RFC 9180's `SetupAuthR`): the messages open only if the + * sender held the key pair of `sender_public_key`. + * + * @param encapsulated_key `enc`. + * @param recipient_keypair The recipient's key pair, `skR`. + * @param application_info `info`, the sender's. + * @param sender_public_key The sender's public key, `pkS`. + * @return The recipient's context; `weak_public_key` for an X25519 sender's key of small + * order; base mode's errors. Another sender is found at `open`, as `authentication_failed`. + */ + [[nodiscard]] static boost::system::result begin_receiving( + encapsulated_key_type const& encapsulated_key, + recipient_keypair_type const& recipient_keypair, + std::span application_info, + public_key_type const& sender_public_key) noexcept { + secure::timing_guard const timing_scope; + return setup::receive(encapsulated_key, recipient_keypair, application_info, nullptr, + &sender_public_key); + } + + /** + * Sets up a recipient in auth_psk mode (RFC 9180's `SetupAuthPSKR`). + * + * @param encapsulated_key `enc`. + * @param recipient_keypair The recipient's key pair, `skR`. + * @param application_info `info`, the sender's. + * @param pre_shared_key `{key, id}`, the sender's. + * @param sender_public_key The sender's public key, `pkS`. + * @return The recipient's context; psk mode's and auth mode's errors. + */ + [[nodiscard]] static boost::system::result begin_receiving( + encapsulated_key_type const& encapsulated_key, + recipient_keypair_type const& recipient_keypair, + std::span application_info, hpke::pre_shared_key const& pre_shared_key, + public_key_type const& sender_public_key) noexcept { + secure::timing_guard const timing_scope; + return setup::receive(encapsulated_key, recipient_keypair, application_info, + &pre_shared_key, &sender_public_key); + } + + /** + * An argument list that is none of the four: stops the build with the message that lists + * them (design B2). + * + * @tparam Arguments The arguments' types. + * @return Never: the build stops. + */ + template + requires(!detail::hpke_receiving_arguments) + [[nodiscard]] static boost::system::result begin_receiving( + Arguments&&... /*arguments*/) noexcept { + static_assert(detail::dependent_false>, + "webcpp::crypto: hpke begin_receiving takes one of four argument lists, " + "the mode following from them: (encapsulated_key, recipient_keypair, " + "application_info) for base; (encapsulated_key, recipient_keypair, " + "application_info, pre_shared_key) for psk; (encapsulated_key, " + "recipient_keypair, application_info, sender_public_key) for auth; " + "(encapsulated_key, recipient_keypair, application_info, pre_shared_key, " + "sender_public_key) for auth_psk; each key of the suite's own types, the " + "pre-shared key written hpke::pre_shared_key{key, id}."); + return error::invalid_state; + } + + /** + * Sets up a recipient, asynchronously: `begin_receiving` run with the arguments between the + * executor and the token when the operation is initiated, its result posted to + * `completion_executor`; the member form of + * `hpke::async_begin_receiving`. + * + * Declared here and defined in ``, as `async_begin_sending` is. + * + * @tparam Executor The executor's type, an Asio executor. + * @tparam Arguments One of `begin_receiving`'s four argument lists, then the completion + * token's type. + * @param completion_executor The executor the completion is posted to. + * @param arguments_then_token `begin_receiving`'s arguments, then the completion token, of + * signature `void(boost::system::error_code, recipient_context_type)`; on an error the + * context is empty. + * @return What the completion token's `async_result` gives. + */ + template + static auto async_begin_receiving(Executor const& completion_executor, + Arguments&&... arguments_then_token); + + /** + * Seals one message to a public key in base mode (RFC 9180's `SealBase`): + * `begin_sending(recipient_public_key, application_info)`, then one `seal`. + * + * `plaintext` may be the first bytes of `ciphertext`; it overlaps it in no other way. + * + * @param recipient_public_key The recipient's public key, `pkR`. + * @param application_info `info`, of any length. + * @param associated_data `aad`, of any length. + * @param plaintext The message. + * @param ciphertext `plaintext.size() + tag_size` bytes. + * @return The encapsulated key, which goes with the ciphertext; `begin_sending`'s and + * `seal`'s errors. + */ + [[nodiscard]] static boost::system::result seal( + public_key_type const& recipient_public_key, std::span application_info, + std::span associated_data, std::span plaintext, + std::span ciphertext) noexcept + requires sealing_cipher + { + secure::timing_guard const timing_scope; + return sealed( + setup::send(recipient_public_key, application_info, nullptr, nullptr, nullptr), + associated_data, plaintext, ciphertext); + } + + /** + * Seals one message in psk mode (RFC 9180's `SealPSK`). + * + * @param recipient_public_key The recipient's public key, `pkR`. + * @param application_info `info`, of any length. + * @param associated_data `aad`, of any length. + * @param plaintext The message. + * @param ciphertext `plaintext.size() + tag_size` bytes. + * @param pre_shared_key `{key, id}`. + * @return The encapsulated key; `begin_sending`'s and `seal`'s errors. + */ + [[nodiscard]] static boost::system::result seal( + public_key_type const& recipient_public_key, std::span application_info, + std::span associated_data, std::span plaintext, + std::span ciphertext, hpke::pre_shared_key const& pre_shared_key) noexcept + requires sealing_cipher + { + secure::timing_guard const timing_scope; + return sealed( + setup::send(recipient_public_key, application_info, &pre_shared_key, nullptr, nullptr), + associated_data, plaintext, ciphertext); + } + + /** + * Seals one message in auth mode (RFC 9180's `SealAuth`). + * + * @param recipient_public_key The recipient's public key, `pkR`. + * @param application_info `info`, of any length. + * @param associated_data `aad`, of any length. + * @param plaintext The message. + * @param ciphertext `plaintext.size() + tag_size` bytes. + * @param sender_keypair The sender's key pair, `skS`. + * @return The encapsulated key; `begin_sending`'s and `seal`'s errors. + */ + [[nodiscard]] static boost::system::result seal( + public_key_type const& recipient_public_key, std::span application_info, + std::span associated_data, std::span plaintext, + std::span ciphertext, sender_keypair_type const& sender_keypair) noexcept + requires sealing_cipher + { + secure::timing_guard const timing_scope; + return sealed( + setup::send(recipient_public_key, application_info, nullptr, &sender_keypair, nullptr), + associated_data, plaintext, ciphertext); + } + + /** + * Seals one message in auth_psk mode (RFC 9180's `SealAuthPSK`). + * + * @param recipient_public_key The recipient's public key, `pkR`. + * @param application_info `info`, of any length. + * @param associated_data `aad`, of any length. + * @param plaintext The message. + * @param ciphertext `plaintext.size() + tag_size` bytes. + * @param pre_shared_key `{key, id}`. + * @param sender_keypair The sender's key pair, `skS`. + * @return The encapsulated key; `begin_sending`'s and `seal`'s errors. + */ + [[nodiscard]] static boost::system::result seal( + public_key_type const& recipient_public_key, std::span application_info, + std::span associated_data, std::span plaintext, + std::span ciphertext, hpke::pre_shared_key const& pre_shared_key, + sender_keypair_type const& sender_keypair) noexcept + requires sealing_cipher + { + secure::timing_guard const timing_scope; + return sealed(setup::send(recipient_public_key, application_info, &pre_shared_key, + &sender_keypair, nullptr), + associated_data, plaintext, ciphertext); + } + + /** + * An argument list that is none of the four, or any call of an export-only suite: stops the + * build with the message that lists the four, or that says an export-only suite only exports + * (design B2, D7). + * + * @tparam Arguments The arguments' types. + * @return Never: the build stops. + */ + template + requires(!sealing_cipher || !detail::hpke_sealing_arguments) + [[nodiscard]] static boost::system::result seal( + Arguments&&... /*arguments*/) noexcept { + if constexpr (!sealing_cipher) { + static_assert(detail::dependent_false>, + "webcpp::crypto: an export-only HPKE suite only exports: it has no seal " + "or open. Call export_secret, or name a cipher that seals " + "(hpke::cipher::aes128_gcm, aes256_gcm or chacha20_poly1305)."); + } else { + static_assert(detail::dependent_false>, + "webcpp::crypto: hpke seal takes one of four argument lists, the mode " + "following from them: (recipient_public_key, application_info, " + "associated_data, plaintext, ciphertext) for base, then " + "pre_shared_key for psk, sender_keypair for auth, or pre_shared_key, " + "sender_keypair for auth_psk; each key of the suite's own types, the " + "pre-shared key written hpke::pre_shared_key{key, id}."); + } + return error::invalid_state; + } + + /** + * Seals one message, asynchronously: the single-shot `seal` run with the arguments between + * the executor and the token when the operation is initiated, its result posted to + * `completion_executor`; the member form of + * `hpke::async_seal`. + * + * Declared here and defined in ``, as `async_begin_sending` is. + * + * @tparam Executor The executor's type, an Asio executor. + * @tparam Arguments One of `seal`'s four argument lists, then the completion token's type. + * @param completion_executor The executor the completion is posted to. + * @param arguments_then_token `seal`'s arguments, then the completion token, of signature + * `void(boost::system::error_code, encapsulated_key_type)`; on an error the key is zero. + * @return What the completion token's `async_result` gives. + */ + template + static auto async_seal(Executor const& completion_executor, + Arguments&&... arguments_then_token); + + /** + * Opens one message in base mode, RFC 9180's `OpenBase`: `begin_receiving` with the + * encapsulated key, the recipient's key pair and the application info, then one `open`. + * + * `plaintext` may be the first bytes of `ciphertext`; it overlaps it in no other way. + * + * @param encapsulated_key `enc`. + * @param recipient_keypair The recipient's key pair, `skR`. + * @param application_info `info`, the sender's. + * @param associated_data `aad`, the sender's. + * @param ciphertext The ciphertext then the tag. + * @param plaintext `ciphertext.size() - tag_size` bytes. + * @return Nothing; `begin_receiving`'s and `open`'s errors. + */ + [[nodiscard]] static boost::system::result open( + encapsulated_key_type const& encapsulated_key, + recipient_keypair_type const& recipient_keypair, + std::span application_info, + std::span associated_data, std::span ciphertext, + std::span plaintext) noexcept + requires sealing_cipher + { + secure::timing_guard const timing_scope; + return opened( + setup::receive(encapsulated_key, recipient_keypair, application_info, nullptr, nullptr), + associated_data, ciphertext, plaintext); + } + + /** + * Opens one message in psk mode (RFC 9180's `OpenPSK`). + * + * @param encapsulated_key `enc`. + * @param recipient_keypair The recipient's key pair, `skR`. + * @param application_info `info`, the sender's. + * @param associated_data `aad`, the sender's. + * @param ciphertext The ciphertext then the tag. + * @param plaintext `ciphertext.size() - tag_size` bytes. + * @param pre_shared_key `{key, id}`, the sender's. + * @return Nothing; `begin_receiving`'s and `open`'s errors. + */ + [[nodiscard]] static boost::system::result open( + encapsulated_key_type const& encapsulated_key, + recipient_keypair_type const& recipient_keypair, + std::span application_info, + std::span associated_data, std::span ciphertext, + std::span plaintext, hpke::pre_shared_key const& pre_shared_key) noexcept + requires sealing_cipher + { + secure::timing_guard const timing_scope; + return opened(setup::receive(encapsulated_key, recipient_keypair, application_info, + &pre_shared_key, nullptr), + associated_data, ciphertext, plaintext); + } + + /** + * Opens one message in auth mode (RFC 9180's `OpenAuth`). + * + * @param encapsulated_key `enc`. + * @param recipient_keypair The recipient's key pair, `skR`. + * @param application_info `info`, the sender's. + * @param associated_data `aad`, the sender's. + * @param ciphertext The ciphertext then the tag. + * @param plaintext `ciphertext.size() - tag_size` bytes. + * @param sender_public_key The sender's public key, `pkS`. + * @return Nothing; `begin_receiving`'s and `open`'s errors. + */ + [[nodiscard]] static boost::system::result open( + encapsulated_key_type const& encapsulated_key, + recipient_keypair_type const& recipient_keypair, + std::span application_info, + std::span associated_data, std::span ciphertext, + std::span plaintext, public_key_type const& sender_public_key) noexcept + requires sealing_cipher + { + secure::timing_guard const timing_scope; + return opened(setup::receive(encapsulated_key, recipient_keypair, application_info, nullptr, + &sender_public_key), + associated_data, ciphertext, plaintext); + } + + /** + * Opens one message in auth_psk mode (RFC 9180's `OpenAuthPSK`). + * + * @param encapsulated_key `enc`. + * @param recipient_keypair The recipient's key pair, `skR`. + * @param application_info `info`, the sender's. + * @param associated_data `aad`, the sender's. + * @param ciphertext The ciphertext then the tag. + * @param plaintext `ciphertext.size() - tag_size` bytes. + * @param pre_shared_key `{key, id}`, the sender's. + * @param sender_public_key The sender's public key, `pkS`. + * @return Nothing; `begin_receiving`'s and `open`'s errors. + */ + [[nodiscard]] static boost::system::result open( + encapsulated_key_type const& encapsulated_key, + recipient_keypair_type const& recipient_keypair, + std::span application_info, + std::span associated_data, std::span ciphertext, + std::span plaintext, hpke::pre_shared_key const& pre_shared_key, + public_key_type const& sender_public_key) noexcept + requires sealing_cipher + { + secure::timing_guard const timing_scope; + return opened(setup::receive(encapsulated_key, recipient_keypair, application_info, + &pre_shared_key, &sender_public_key), + associated_data, ciphertext, plaintext); + } + + /** + * An argument list that is none of the four, or any call of an export-only suite: stops the + * build with the message that lists the four, or that says an export-only suite only exports. + * + * @tparam Arguments The arguments' types. + * @return Never: the build stops. + */ + template + requires(!sealing_cipher || !detail::hpke_opening_arguments) + [[nodiscard]] static boost::system::result open(Arguments&&... /*arguments*/) noexcept { + if constexpr (!sealing_cipher) { + static_assert(detail::dependent_false>, + "webcpp::crypto: an export-only HPKE suite only exports: it has no seal " + "or open. Call export_secret, or name a cipher that seals " + "(hpke::cipher::aes128_gcm, aes256_gcm or chacha20_poly1305)."); + } else { + static_assert(detail::dependent_false>, + "webcpp::crypto: hpke open takes one of four argument lists, the mode " + "following from them: (encapsulated_key, recipient_keypair, " + "application_info, associated_data, ciphertext, plaintext) for base, " + "then pre_shared_key for psk, sender_public_key for auth, or " + "pre_shared_key, sender_public_key for auth_psk; each key of the " + "suite's own types, the pre-shared key written " + "hpke::pre_shared_key{key, id}."); + } + return error::invalid_state; + } + + /** + * Opens one message, asynchronously: the single-shot `open` run with the arguments between + * the executor and the token when the operation is initiated, its result posted to + * `completion_executor`; the member form of + * `hpke::async_open`. + * + * Declared here and defined in ``, as `async_begin_sending` is. + * + * @tparam Executor The executor's type, an Asio executor. + * @tparam Arguments One of `open`'s four argument lists, then the completion token's type. + * @param completion_executor The executor the completion is posted to. + * @param arguments_then_token `open`'s arguments, then the completion token, of signature + * `void(boost::system::error_code)`. + * @return What the completion token's `async_result` gives. + */ + template + static auto async_open(Executor const& completion_executor, + Arguments&&... arguments_then_token); + + /** + * Derives a key pair from a seed on the suite's key backend (RFC 9180's `DeriveKeyPair`), as + * MLS derives every tree key pair: the key encapsulation's `derive_from_seed`. + * + * @param seed At least `KeyEncapsulation::secret_key_size` bytes of entropy; no upper bound. + * @return The key pair; `invalid_input_size` for a shorter seed; `invalid_secret_key` (P-256, + * probability about 2^-8192); `backend_failure`. + */ + [[nodiscard]] static boost::system::result derive_from_seed( + std::span seed) noexcept { + secure::timing_guard const timing_scope; + return KeyEncapsulation::template derive_from_seed(seed); + } + + /** + * Derives a key pair from a seed, asynchronously: `derive_from_seed` run when the operation is + * initiated, its result posted to `completion_executor`; the member form of + * `hpke::async_derive_from_seed(completion_executor, seed, completion_token)`. + * + * Declared here and defined in ``, as `async_begin_sending` is. + * + * @tparam Executor The executor's type, an Asio executor. + * @tparam CompletionToken Any completion token for the signature `completion_token` states. + * @param completion_executor The executor the completion is posted to. + * @param seed The seed, the caller's until the completion. + * @param completion_token The completion token, of signature + * `void(boost::system::error_code, recipient_keypair_type)`; on an error the key pair is + * empty. + * @return What the completion token's `async_result` gives. + */ + template + static auto async_derive_from_seed(Executor const& completion_executor, + std::span seed, + CompletionToken&& completion_token); + +private: + /** One seal on a context just set up, which gives its encapsulated key. */ + [[nodiscard]] static boost::system::result sealed( + boost::system::result&& sender, + std::span associated_data, std::span plaintext, + std::span ciphertext) noexcept { + if (!sender) { + return sender.error(); + } + auto const done = sender.unsafe_value().seal(associated_data, plaintext, ciphertext); + if (!done) { + return done.error(); + } + return sender.unsafe_value().encapsulated_key(); + } + + /** One open on a context just set up. */ + [[nodiscard]] static boost::system::result opened( + boost::system::result&& recipient, + std::span associated_data, std::span ciphertext, + std::span plaintext) noexcept { + if (!recipient) { + return recipient.error(); + } + return recipient.unsafe_value().open(associated_data, ciphertext, plaintext); + } +}; + +/** + * Sets up a sender of `Suite`: the free form of `Suite::begin_sending`, which it calls with the + * same arguments, results and errors. + * + * @tparam Suite An `hpke::suite`. + * @tparam Arguments One of `Suite::begin_sending`'s four argument lists. + * @param arguments `(recipient_public_key, application_info[, pre_shared_key][, + * sender_keypair])`. + * @return What `Suite::begin_sending` returns. + */ +template + requires detail::is_hpke_suite_v +[[nodiscard]] boost::system::result begin_sending( + Arguments&&... arguments) noexcept { + secure::timing_guard const timing_scope; + return Suite::begin_sending(std::forward(arguments)...); +} + +/** + * Sets up a recipient of `Suite`: the free form of `Suite::begin_receiving`. + * + * @tparam Suite An `hpke::suite`. + * @tparam Arguments One of `Suite::begin_receiving`'s four argument lists. + * @param arguments `(encapsulated_key, recipient_keypair, application_info[, pre_shared_key][, + * sender_public_key])`. + * @return What `Suite::begin_receiving` returns. + */ +template + requires detail::is_hpke_suite_v +[[nodiscard]] boost::system::result begin_receiving( + Arguments&&... arguments) noexcept { + secure::timing_guard const timing_scope; + return Suite::begin_receiving(std::forward(arguments)...); +} + +/** + * Seals one message to a public key with `Suite`: the free form of the single-shot + * `Suite::seal`. + * + * @tparam Suite An `hpke::suite` that seals. + * @tparam Arguments One of `Suite::seal`'s four argument lists. + * @param arguments `(recipient_public_key, application_info, associated_data, plaintext, + * ciphertext[, pre_shared_key][, sender_keypair])`. + * @return What `Suite::seal` returns: the encapsulated key. + */ +template + requires detail::is_hpke_suite_v +[[nodiscard]] boost::system::result seal( + Arguments&&... arguments) noexcept { + secure::timing_guard const timing_scope; + return Suite::seal(std::forward(arguments)...); +} + +/** + * Opens one message with `Suite`: the free form of the single-shot `Suite::open`. + * + * @tparam Suite An `hpke::suite` that seals. + * @tparam Arguments One of `Suite::open`'s four argument lists. + * @param arguments `(encapsulated_key, recipient_keypair, application_info, associated_data, + * ciphertext, plaintext[, pre_shared_key][, sender_public_key])`. + * @return What `Suite::open` returns. + */ +template + requires detail::is_hpke_suite_v +[[nodiscard]] boost::system::result open(Arguments&&... arguments) noexcept { + secure::timing_guard const timing_scope; + return Suite::open(std::forward(arguments)...); +} + +/** + * Seals the next message on a sender's context: the free form of `sender.seal`. + * + * @tparam Suite The context's suite, deduced. + * @param sender The sender's context. + * @param associated_data Authenticated, not encrypted. + * @param plaintext The message. + * @param ciphertext `plaintext.size() + Suite::tag_size` bytes. + * @return What `sender.seal` returns. + */ +template +[[nodiscard]] boost::system::result seal(sender_context& sender, + std::span associated_data, + std::span plaintext, + std::span ciphertext) noexcept { + secure::timing_guard const timing_scope; + return sender.seal(associated_data, plaintext, ciphertext); +} + +/** + * Opens the next message on a recipient's context: the free form of `recipient.open`. + * + * @tparam Suite The context's suite, deduced. + * @param recipient The recipient's context. + * @param associated_data The associated data of the seal. + * @param ciphertext The ciphertext then the tag. + * @param plaintext `ciphertext.size() - Suite::tag_size` bytes. + * @return What `recipient.open` returns. + */ +template +[[nodiscard]] boost::system::result open(recipient_context& recipient, + std::span associated_data, + std::span ciphertext, + std::span plaintext) noexcept { + secure::timing_guard const timing_scope; + return recipient.open(associated_data, ciphertext, plaintext); +} + +/** + * Exports a secret of `Length` bytes from a context: the free form of + * `context.export_secret(purpose)`. + * + * @tparam Length 1 to the suite's `max_export_size`. + * @tparam Context A sender's or a recipient's context, deduced. + * @param context The context. + * @param purpose `exporter_context`, of any length. + * @return What `context.export_secret(purpose)` returns. + */ +template + requires detail::is_hpke_context_v +[[nodiscard]] boost::system::result> +export_secret(Context const& context, std::span purpose) noexcept { + secure::timing_guard const timing_scope; + return context.template export_secret(purpose); +} + +/** + * Exports a secret into `output` from a context: the free form of + * `context.export_secret(purpose, output)`. + * + * @tparam Context A sender's or a recipient's context, deduced. + * @param context The context. + * @param purpose `exporter_context`, of any length. + * @param output 1 to the suite's `max_export_size` bytes. + * @return What `context.export_secret(purpose, output)` returns. + */ +template + requires detail::is_hpke_context_v +[[nodiscard]] boost::system::result export_secret(Context const& context, + std::span purpose, + std::span output) noexcept { + secure::timing_guard const timing_scope; + return context.export_secret(purpose, output); +} + +/** + * Derives a key pair of `Suite` from a seed: the free form of `Suite::derive_from_seed`. + * + * @tparam Suite An `hpke::suite`. + * @param seed At least the key encapsulation's `secret_key_size` bytes of entropy. + * @return What `Suite::derive_from_seed` returns. + */ +template + requires detail::is_hpke_suite_v +[[nodiscard]] boost::system::result derive_from_seed( + std::span seed) noexcept { + secure::timing_guard const timing_scope; + return Suite::derive_from_seed(seed); +} + +} // namespace webcpp::crypto::public_key_encryption::hpke + +#endif // WEBCPP_CRYPTO_PUBLIC_KEY_ENCRYPTION_HPKE_HPP diff --git a/include/webcpp/crypto/public_key_encryption/hpke/context.hpp b/include/webcpp/crypto/public_key_encryption/hpke/context.hpp new file mode 100644 index 0000000..fd39722 --- /dev/null +++ b/include/webcpp/crypto/public_key_encryption/hpke/context.hpp @@ -0,0 +1,1039 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + HPKE's ciphers and contexts (RFC 9180 sections 5.1 to 5.3 and 7.3): the tags + `hpke::cipher::aes128_gcm`, `aes256_gcm`, `chacha20_poly1305` and `export_only` with their + concepts `hpke::suite_cipher` and `hpke::sealing_cipher`, and `hpke::sender_context` and + `hpke::recipient_context`, which `begin_sending` and `begin_receiving` make. + + A context holds the AEAD keyed by the key schedule, the base nonce, the exporter secret and a + 64-bit sequence number that no member reads or sets. It is move-only, since a copy would reuse + nonces, and wipes its secrets when it is moved from or destroyed (design D6). + + @see "HPKE (RFC 9180)", in the guide. +*/ +#ifndef WEBCPP_CRYPTO_PUBLIC_KEY_ENCRYPTION_HPKE_CONTEXT_HPP +#define WEBCPP_CRYPTO_PUBLIC_KEY_ENCRYPTION_HPKE_CONTEXT_HPP + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::crypto::public_key_encryption::hpke { + +/** HPKE's ciphers, the third parameter of a suite (RFC 9180 section 7.3). */ +namespace cipher { + +/** AES-128-GCM, RFC 9180's AEAD 0x0001, `ciphers::gcm>`. */ +struct aes128_gcm { + /** The identifier, `aead_id`. */ + static constexpr std::uint16_t id = 0x0001; + /** The size of the key, `Nk`. */ + static constexpr std::size_t key_size = 16; + /** The size of the nonce, `Nn`. */ + static constexpr std::size_t nonce_size = 12; + /** The size of the tag, `Nt`. */ + static constexpr std::size_t tag_size = 16; + /** The AEAD's family, whose default backend a suite's `default_backends` takes. */ + using family_type = families::gcm; + /** + * The AEAD on a backend. + * + * @tparam Backend The backend. + */ + template + using aead_type = ciphers::gcm>; +}; + +/** AES-256-GCM, RFC 9180's AEAD 0x0002, `ciphers::gcm>`. */ +struct aes256_gcm { + /** The identifier, `aead_id`. */ + static constexpr std::uint16_t id = 0x0002; + /** The size of the key, `Nk`. */ + static constexpr std::size_t key_size = 32; + /** The size of the nonce, `Nn`. */ + static constexpr std::size_t nonce_size = 12; + /** The size of the tag, `Nt`. */ + static constexpr std::size_t tag_size = 16; + /** The AEAD's family, whose default backend a suite's `default_backends` takes. */ + using family_type = families::gcm; + /** + * The AEAD on a backend. + * + * @tparam Backend The backend. + */ + template + using aead_type = ciphers::gcm>; +}; + +/** ChaCha20-Poly1305, RFC 9180's AEAD 0x0003, `ciphers::chacha20_poly1305`. */ +struct chacha20_poly1305 { + /** The identifier, `aead_id`. */ + static constexpr std::uint16_t id = 0x0003; + /** The size of the key, `Nk`. */ + static constexpr std::size_t key_size = 32; + /** The size of the nonce, `Nn`. */ + static constexpr std::size_t nonce_size = 12; + /** The size of the tag, `Nt`. */ + static constexpr std::size_t tag_size = 16; + /** The AEAD's family, whose default backend a suite's `default_backends` takes. */ + using family_type = families::chacha20_poly1305; + /** + * The AEAD on a backend. + * + * @tparam Backend The backend. + */ + template + using aead_type = ciphers::chacha20_poly1305; +}; + +/** + * RFC 9180's export-only AEAD, 0xFFFF: a suite that only exports secrets, with no `seal` and no + * `open`. + */ +struct export_only { + /** The identifier, `aead_id`. */ + static constexpr std::uint16_t id = 0xFFFF; +}; + +} // namespace cipher + +/** + * Whether `Cipher` is a cipher of an HPKE suite: `cipher::export_only`, or a tag with `id`, + * `key_size` (`Nk`), `nonce_size` (`Nn`), `tag_size` (`Nt`), a `family_type` and an + * `aead_type` that is a `secret_key_encryption::aead::cipher` of those sizes. + * + * A cipher of `crypto::ciphers` is not one: the suite's parameter wraps it. Only the tags of + * `hpke::cipher` are tested and supported (ruling R11). + * + * @tparam Cipher A tag type. + */ +template +concept suite_cipher = std::same_as || requires { + { Cipher::id } -> std::convertible_to; + { Cipher::key_size } -> std::convertible_to; + { Cipher::nonce_size } -> std::convertible_to; + { Cipher::tag_size } -> std::convertible_to; + typename Cipher::family_type; + typename Cipher::template aead_type; + requires secret_key_encryption::aead::cipher< + typename Cipher::template aead_type>; + requires Cipher::template aead_type::key_size == + Cipher::key_size; + requires Cipher::template aead_type::nonce_size == + Cipher::nonce_size; + requires Cipher::template aead_type::tag_size == + Cipher::tag_size; +}; + +/** + * Whether `Cipher` is a `suite_cipher` that seals and opens: every one but `cipher::export_only`. + * + * @tparam Cipher A tag type. + */ +template +concept sealing_cipher = suite_cipher && !std::same_as; + +static_assert(sealing_cipher); +static_assert(sealing_cipher); +static_assert(sealing_cipher); +static_assert(suite_cipher && !sealing_cipher); + +/** + * The tag of a suite's backends when it names none: each family's default backend, the key + * encapsulation's curve's for the key pairs and the cipher's for the AEAD. + */ +struct default_backends {}; + +/** + * The tag of a suite's backends when the key pairs and the AEAD have different ones, as MLS's + * suite 0x0001 natively without OpenSSL: X25519 on libsodium, AES-128-GCM on BearSSL. + * + * @tparam KeyBackend The key pairs' backend. + * @tparam CipherBackend The AEAD's backend. + */ +template +struct backends {}; + +template +class sender_context; + +template +class recipient_context; + +} // namespace webcpp::crypto::public_key_encryption::hpke + +namespace webcpp::crypto::detail { + +/** + * The key backend and the cipher backend of a suite's `Backend` (design B1): one backend serves + * both. + * + * @tparam Backend The suite's backend argument. + * @tparam KeyEncapsulation The key encapsulation. + * @tparam Cipher The cipher. + */ +template +struct hpke_backends_of { + /** The key pairs' backend. */ + using key_backend = Backend; + /** The AEAD's backend. */ + using cipher_backend = Backend; +}; + +/** + * `default_backends`: each family's default. + * + * @tparam KeyEncapsulation The key encapsulation. + * @tparam Cipher The cipher. + */ +template +struct hpke_backends_of { + /** The curve's default. */ + using key_backend = default_backend_t; + /** The AEAD's default. */ + using cipher_backend = default_backend_t; +}; + +/** + * `default_backends` of an export-only suite: no AEAD, so no cipher backend. + * + * @tparam KeyEncapsulation The key encapsulation. + */ +template +struct hpke_backends_of { + /** The curve's default. */ + using key_backend = default_backend_t; + /** None. */ + using cipher_backend = void; +}; + +/** + * `backends`: one for each. + * + * @tparam KeyBackend The key pairs' backend. + * @tparam CipherBackend The AEAD's backend. + * @tparam KeyEncapsulation The key encapsulation. + * @tparam Cipher The cipher. + */ +template +struct hpke_backends_of, + KeyEncapsulation, Cipher> { + /** `KeyBackend`. */ + using key_backend = KeyBackend; + /** `CipherBackend`. */ + using cipher_backend = CipherBackend; +}; + +/** + * The key backend and the cipher backend of a suite. + * + * @tparam Suite The suite. + */ +template +using hpke_backends_t = + hpke_backends_of; + +/** What an export-only context holds in place of an AEAD: nothing. */ +struct hpke_no_aead {}; + +/** + * The AEAD a suite's contexts hold: its cipher's `aead_type` on the suite's cipher backend, or + * `hpke_no_aead` for an export-only suite. + * + * @tparam Suite The suite. + */ +template +struct hpke_aead_of { + /** The AEAD. */ + using type = + Suite::cipher_type::template aead_type::cipher_backend>; +}; + +/** + * An export-only suite's: none. + * + * @tparam Suite The suite. + */ +template + requires std::same_as +struct hpke_aead_of { + /** None. */ + using type = hpke_no_aead; +}; + +/** + * A suite's identifier, `"HPKE" || I2OSP(kem_id, 2) || I2OSP(kdf_id, 2) || I2OSP(aead_id, 2)` + * (RFC 9180 section 5.1). + * + * @tparam Suite The suite. + */ +template +inline constexpr std::array hpke_suite_identifier{ + 'H', + 'P', + 'K', + 'E', + static_cast(Suite::key_encapsulation_type::id >> 8U), + static_cast(Suite::key_encapsulation_type::id & 0xffU), + static_cast(Suite::key_derivation_type::id >> 8U), + static_cast(Suite::key_derivation_type::id & 0xffU), + static_cast(Suite::cipher_type::id >> 8U), + static_cast(Suite::cipher_type::id & 0xffU), +}; + +/** + * The key and the base nonce of a sealing suite's key schedule. + * + * @tparam Cipher The cipher. + */ +template +struct hpke_aead_material { + /** `key`, `Nk` bytes. */ + secure::secret key; + /** `base_nonce`, `Nn` bytes, wiped by the owner. */ + std::array base_nonce{}; + + /** Wipes the base nonce; the key wipes itself. */ + ~hpke_aead_material() { secure::erase_secret(base_nonce); } + + /** Default-constructible: zeros. */ + hpke_aead_material() noexcept = default; + /** Not copyable: secrets. */ + hpke_aead_material(hpke_aead_material const&) = delete; + /** Not copyable: secrets. */ + hpke_aead_material& operator=(hpke_aead_material const&) = delete; + + /** + * Moves; the source's base nonce is wiped. + * + * @param moved_from The source. + */ + hpke_aead_material(hpke_aead_material&& moved_from) noexcept + : key(std::move(moved_from.key)), base_nonce(moved_from.base_nonce) { + secure::erase_secret(moved_from.base_nonce); + } + + /** Not move-assignable: made once. */ + hpke_aead_material& operator=(hpke_aead_material&&) = delete; +}; + +/** An export-only suite's key schedule computes no key and no base nonce. */ +template <> +struct hpke_aead_material {}; + +/** + * The values of RFC 9180's key schedule (section 5.1): the context, the secret, the key and the + * base nonce (none for an export-only suite), and the exporter secret. + * + * @tparam Suite The suite. + */ +template +struct hpke_schedule { + /** The hash size, `Nh`. */ + static constexpr std::size_t hash_size = Suite::key_derivation_type::hash_size; + /** `key_schedule_context`, `mode || psk_id_hash || info_hash`: public. */ + std::array key_schedule_context{}; + /** `secret`. */ + secure::secret secret; + /** `key` and `base_nonce`. */ + hpke_aead_material aead_material; + /** `exporter_secret`. */ + secure::secret exporter_secret; +}; + +/** + * RFC 9180's `KeySchedule` (section 5.1) with no `VerifyPSKInputs`: the mode follows from the + * overload that was called, and the pre-shared key was checked by it (design D5). + * + * @tparam Suite The suite. + * @param mode 0x00, 0x01, 0x02 or 0x03. + * @param shared_secret The key encapsulation's shared secret. + * @param application_info `info`, of any length. + * @param pre_shared_key `psk`, empty in base and auth modes. + * @param pre_shared_key_id `psk_id`, empty in base and auth modes. + * @return The values; `backend_failure`. + */ +template +[[nodiscard]] boost::system::result> hpke_key_schedule( + std::uint8_t mode, std::span shared_secret, + std::span application_info, std::span pre_shared_key, + std::span pre_shared_key_id) noexcept { + using key_derivation = Suite::key_derivation_type; + constexpr std::size_t hash_size = key_derivation::hash_size; + constexpr auto psk_id_hash_label = hpke_label("psk_id_hash"); + constexpr auto info_hash_label = hpke_label("info_hash"); + constexpr auto secret_label = hpke_label("secret"); + constexpr auto key_label = hpke_label("key"); + constexpr auto base_nonce_label = hpke_label("base_nonce"); + constexpr auto exporter_label = hpke_label("exp"); + auto const& suite_identifier = hpke_suite_identifier; + hpke_schedule schedule; + auto const psk_id_hash = hpke_labeled_extract( + {}, suite_identifier, psk_id_hash_label, pre_shared_key_id); + if (!psk_id_hash) { + return psk_id_hash.error(); + } + auto const info_hash = hpke_labeled_extract({}, suite_identifier, + info_hash_label, application_info); + if (!info_hash) { + return info_hash.error(); + } + schedule.key_schedule_context[0] = mode; + std::ranges::copy(psk_id_hash.unsafe_value().bytes(), + schedule.key_schedule_context.begin() + 1); + std::ranges::copy(info_hash.unsafe_value().bytes(), + schedule.key_schedule_context.begin() + 1 + hash_size); + auto extracted = hpke_labeled_extract(shared_secret, suite_identifier, + secret_label, pre_shared_key); + if (!extracted) { + return extracted.error(); + } + schedule.secret = std::move(extracted).unsafe_value(); + if constexpr (public_key_encryption::hpke::sealing_cipher) { + auto const key_done = hpke_labeled_expand( + schedule.secret.bytes(), suite_identifier, key_label, schedule.key_schedule_context, + schedule.aead_material.key.writable()); + if (!key_done) { + return key_done.error(); + } + auto const nonce_done = hpke_labeled_expand( + schedule.secret.bytes(), suite_identifier, base_nonce_label, + schedule.key_schedule_context, schedule.aead_material.base_nonce); + if (!nonce_done) { + return nonce_done.error(); + } + } + auto const exporter_done = hpke_labeled_expand( + schedule.secret.bytes(), suite_identifier, exporter_label, schedule.key_schedule_context, + schedule.exporter_secret.writable()); + if (!exporter_done) { + return exporter_done.error(); + } + return schedule; +} + +/** + * The secret an export of `Length` bytes returns, `secure::secret`; outside 1 to `Max`, + * whose export the build refuses with its own message, one byte, so that the refusal is alone. + * + * @tparam Length The export's length. + * @tparam Max The suite's longest export. + */ +template +using hpke_export_t = secure::secret<(Length >= 1 && Length <= Max) ? Length : 1>; + +/** + * What both contexts hold and do (design D6, B11): the AEAD, the base nonce, the exporter secret + * and the sequence number; the work of `seal`, `open` and `export_secret` without a guard (the + * public member holds it). + * + * @tparam Suite The suite. + */ +template +class hpke_context_core { +public: + /** The AEAD, or `hpke_no_aead`. */ + using aead_type = hpke_aead_of::type; + /** The cipher tag. */ + using cipher_type = Suite::cipher_type; + /** Whether the suite seals and opens. */ + static constexpr bool sealing = public_key_encryption::hpke::sealing_cipher; + /** The hash size, `Nh`. */ + static constexpr std::size_t hash_size = Suite::key_derivation_type::hash_size; + /** The longest export, `255 * Nh`. */ + static constexpr std::size_t max_export_size = 255 * hash_size; + /** The base nonce's storage: `Nn` bytes, or one unused byte for an export-only suite. */ + static constexpr std::size_t nonce_storage_size = [] { + if constexpr (sealing) { + return cipher_type::nonce_size; + } else { + return std::size_t{1}; + } + }(); + + /** The last sequence number, `2^64 - 1`, at which a context refuses (RFC 9180 section 5.2). */ + static constexpr std::uint64_t last_sequence = ~std::uint64_t{0}; + + /** Empty: every call refuses with `invalid_state`. */ + hpke_context_core() noexcept = default; + + /** + * Keyed from a key schedule's values: the AEAD is made from its key, which the schedule + * wipes; its base nonce and exporter secret are taken. + * + * @param schedule The key schedule's values. + * @return The core; the AEAD's `from_key` error. + */ + [[nodiscard]] static boost::system::result from_schedule( + hpke_schedule& schedule) noexcept { + hpke_context_core made_core; + if constexpr (sealing) { + auto keyed_aead = aead_type::from_key(schedule.aead_material.key.bytes()); + if (!keyed_aead) { + return keyed_aead.error(); + } + made_core.aead_.emplace(std::move(keyed_aead).unsafe_value()); + made_core.base_nonce_ = schedule.aead_material.base_nonce; + } + made_core.exporter_secret_ = std::move(schedule.exporter_secret); + made_core.keyed_ = true; + return made_core; + } + + /** + * Moves; the source is wiped and empty. + * + * @param moved_from The source. + */ + hpke_context_core(hpke_context_core&& moved_from) noexcept + : aead_(std::move(moved_from.aead_)), + base_nonce_(moved_from.base_nonce_), + exporter_secret_(std::move(moved_from.exporter_secret_)), + sequence_(std::exchange(moved_from.sequence_, 0)), + keyed_(std::exchange(moved_from.keyed_, false)) { + moved_from.forget(); + } + + /** + * Moves over this core, wiped first; the source is wiped and empty. + * + * @param moved_from The source. + * @return This core. + */ + hpke_context_core& operator=(hpke_context_core&& moved_from) noexcept { + if (this != &moved_from) { + aead_ = std::move(moved_from.aead_); + base_nonce_ = moved_from.base_nonce_; + exporter_secret_ = std::move(moved_from.exporter_secret_); + sequence_ = std::exchange(moved_from.sequence_, 0); + keyed_ = std::exchange(moved_from.keyed_, false); + moved_from.forget(); + } + return *this; + } + + /** Not copyable: a copy would reuse nonces. */ + hpke_context_core(hpke_context_core const&) = delete; + /** Not copyable: a copy would reuse nonces. */ + hpke_context_core& operator=(hpke_context_core const&) = delete; + + /** Wipes the base nonce; the AEAD and the exporter secret wipe themselves. */ + ~hpke_context_core() { secure::erase_secret(base_nonce_); } + + /** + * RFC 9180's `ContextS.Seal`: seals with the nonce of the sequence number, writes the + * ciphertext then the tag, then increments the sequence number. + * + * @param associated_data `aad`. + * @param plaintext `pt`, which may be the first bytes of `ciphertext`. + * @param ciphertext `plaintext.size() + tag_size` bytes. + * @return Nothing; `invalid_state`; `invalid_input_size`, `ciphertext` untouched; + * `message_limit_reached`, nothing written; the AEAD's errors, `ciphertext` zeroed. + */ + [[nodiscard]] boost::system::result seal(std::span associated_data, + std::span plaintext, + std::span ciphertext) noexcept + requires sealing + { + constexpr std::size_t tag_size = cipher_type::tag_size; + if (!keyed_ || !aead_.has_value()) { + return error::invalid_state; + } + if (plaintext.size() > ~std::size_t{0} - tag_size || + ciphertext.size() != plaintext.size() + tag_size) { + return error::invalid_input_size; + } + if (sequence_ == last_sequence) { + return error::message_limit_reached; + } + auto const message_nonce = nonce(); + auto const sealed_bytes = ciphertext.first(plaintext.size()); + if (plaintext.data() != sealed_bytes.data()) { + std::ranges::copy(plaintext, sealed_bytes.begin()); + } + auto const tag = aead_->seal(message_nonce, associated_data, sealed_bytes); + if (!tag) { + secure::erase_secret(ciphertext); + return tag.error(); + } + std::copy_n(tag.unsafe_value().data(), tag_size, + ciphertext.subspan(plaintext.size()).begin()); + ++sequence_; + return {}; + } + + /** + * RFC 9180's `ContextR.Open`: opens with the nonce of the sequence number and, only when it + * opened, increments the sequence number. + * + * @param associated_data `aad`. + * @param ciphertext `ct`, the ciphertext then the tag. + * @param plaintext `ciphertext.size() - tag_size` bytes, which may be the first bytes of + * `ciphertext`. + * @return Nothing; `invalid_state`; `invalid_input_size`, `plaintext` untouched; + * `message_limit_reached`, nothing written; `authentication_failed` and the AEAD's other + * errors, `plaintext` zeroed and the sequence number unchanged. + */ + [[nodiscard]] boost::system::result open(std::span associated_data, + std::span ciphertext, + std::span plaintext) noexcept + requires sealing + { + constexpr std::size_t tag_size = cipher_type::tag_size; + if (!keyed_ || !aead_.has_value()) { + return error::invalid_state; + } + if (ciphertext.size() < tag_size || plaintext.size() != ciphertext.size() - tag_size) { + return error::invalid_input_size; + } + if (sequence_ == last_sequence) { + return error::message_limit_reached; + } + auto const message_nonce = nonce(); + auto const encrypted_bytes = ciphertext.first(plaintext.size()); + if (encrypted_bytes.data() != plaintext.data()) { + std::ranges::copy(encrypted_bytes, plaintext.begin()); + } + auto const opened = + aead_->open(message_nonce, associated_data, plaintext, ciphertext.last(tag_size)); + if (!opened) { + secure::erase_secret(plaintext); + return opened.error(); + } + ++sequence_; + return {}; + } + + /** + * RFC 9180's `Context.Export(exporter_context, L)`: `LabeledExpand(exporter_secret, "sec", + * purpose, L)`, `L` the output's size. + * + * @param purpose `exporter_context`, of any length. + * @param output 1 to `max_export_size` bytes. + * @return Nothing; `invalid_input_size`, `output` untouched; `invalid_state`; + * `backend_failure`. + */ + [[nodiscard]] boost::system::result export_secret( + std::span purpose, std::span output) const noexcept { + constexpr auto secret_label = hpke_label("sec"); + if (output.empty() || output.size() > max_export_size) { + return error::invalid_input_size; + } + if (!keyed_) { + return error::invalid_state; + } + return hpke_labeled_expand( + exporter_secret_.bytes(), hpke_suite_identifier, secret_label, purpose, output); + } + + /** + * `export_secret` into a secret of `Length` bytes, `Length` checked at compile time: outside + * 1 to `max_export_size`, the build stops with the bounds, and with that error alone. + * + * @param purpose `exporter_context`, of any length. + * @return The secret; `invalid_state`; `backend_failure`. + */ + template + [[nodiscard]] boost::system::result> export_fixed( + std::span purpose) const noexcept { + if constexpr (Length < 1 || Length > max_export_size) { + static_assert(dependent_false>, + "webcpp::crypto: an HPKE export is 1 to 255 times the key derivation's " + "hash size bytes (Suite::max_export_size)."); + return error::invalid_input_size; + } else { + secure::secret exported; + auto const done = export_secret(purpose, exported.writable()); + if (!done) { + return done.error(); + } + return exported; + } + } + + /** + * The sequence number, for the test seam. + * + * @return The number of messages sealed or opened. + */ + [[nodiscard]] std::uint64_t sequence() const noexcept { return sequence_; } + + /** + * Sets the sequence number, for the test seam. + * + * @param sequence_number The number. + */ + void set_sequence(std::uint64_t sequence_number) noexcept { sequence_ = sequence_number; } + +private: + /** The nonce of the sequence number: `base_nonce XOR I2OSP(seq, Nn)`. */ + [[nodiscard]] std::array nonce() const noexcept + requires sealing + { + auto message_nonce = base_nonce_; + for (std::size_t byte_index = 0; byte_index < sizeof(std::uint64_t); ++byte_index) { + message_nonce[nonce_storage_size - 1 - byte_index] ^= + static_cast((sequence_ >> (8U * byte_index)) & 0xffU); + } + return message_nonce; + } + + /** Leaves this core empty: the AEAD dropped, the base nonce wiped. */ + void forget() noexcept { + aead_.reset(); + secure::erase_secret(base_nonce_); + } + + std::optional aead_; + std::array base_nonce_{}; + secure::secret exporter_secret_; + std::uint64_t sequence_ = 0; + bool keyed_ = false; +}; + +} // namespace webcpp::crypto::detail + +namespace webcpp::crypto::public_key_encryption::hpke { + +/** + * The sender's context of a suite (RFC 9180's `Context`), which `begin_sending` makes: it + * seals messages in order, exports secrets, and holds the encapsulated key to send. + * + * It is move-only, since a copy would reuse nonces; moved from, every member refuses with + * `invalid_state`. It wipes its secrets when moved from and destroyed. It is not thread-safe: + * one context serves one ordered stream of messages. + * + * @tparam Suite The suite, a specialisation of `hpke::suite`. + */ +template +class sender_context { + friend struct detail::hpke_access; + // The asynchronous family's error completions make the empty context. + friend struct detail::async_access; + +public: + /** The suite. */ + using suite_type = Suite; + /** The encapsulated key's type. */ + using encapsulated_key_type = Suite::encapsulated_key_type; + /** The longest export, `255 * Nh` bytes. */ + static constexpr std::size_t max_export_size = Suite::max_export_size; + + /** + * Moves the context; the source is wiped and refuses every call. + * + * @param moved_from The context moved from. + */ + sender_context(sender_context&& moved_from) noexcept + : core_(std::move(moved_from.core_)), + encapsulated_key_(std::exchange(moved_from.encapsulated_key_, encapsulated_key_type{})) {} + + /** + * Moves over this context, wiped first; the source is wiped and refuses every call. + * + * @param moved_from The context moved from. + * @return This context. + */ + sender_context& operator=(sender_context&& moved_from) noexcept { + if (this != &moved_from) { + core_ = std::move(moved_from.core_); + encapsulated_key_ = + std::exchange(moved_from.encapsulated_key_, encapsulated_key_type{}); + } + return *this; + } + + /** Not copyable: a copy would reuse nonces. */ + sender_context(sender_context const&) = delete; + /** Not copyable: a copy would reuse nonces. */ + sender_context& operator=(sender_context const&) = delete; + + /** Wipes the key, the base nonce and the exporter secret. */ + ~sender_context() = default; + + /** + * The encapsulated key `begin_sending` produced, which the recipient's `begin_receiving` + * takes: send it with the ciphertexts. + * + * @return The key; its zero value moved from. + */ + [[nodiscard]] encapsulated_key_type const& encapsulated_key() const noexcept { + return encapsulated_key_; + } + + /** + * Seals the next message (RFC 9180's `ContextS.Seal`): writes the ciphertext followed by the + * tag, under the nonce of the context's sequence number, which it then increments. + * + * `plaintext` may be the first bytes of `ciphertext`, sealed in place; it overlaps + * `ciphertext` in no other way. An export-only suite has no `seal`: the call stops the build. + * + * @param associated_data Authenticated, not encrypted; of any length. + * @param plaintext The message, of any length, empty included. + * @param ciphertext `plaintext.size() + Suite::tag_size` bytes. + * @return Nothing; `invalid_state` moved from; `invalid_input_size` for a `ciphertext` of + * another size, untouched; `message_limit_reached` when the context has sealed `2^64 - 1` + * messages, nothing written; `message_too_long` and `backend_failure`, the AEAD's, + * `ciphertext` zeroed. + */ + [[nodiscard]] boost::system::result seal(std::span associated_data, + std::span plaintext, + std::span ciphertext) noexcept { + secure::timing_guard const timing_scope; + if constexpr (!sealing_cipher) { + static_assert(detail::dependent_false, + "webcpp::crypto: an export-only HPKE suite only exports: it has no seal " + "or open. Call export_secret, or name a cipher that seals " + "(hpke::cipher::aes128_gcm, aes256_gcm or chacha20_poly1305)."); + return error::invalid_state; + } else { + return core_.seal(associated_data, plaintext, ciphertext); + } + } + + /** + * Seals the next message, asynchronously: `seal` run when the operation is initiated, its + * result posted to `completion_executor`; the member form of + * `hpke::async_seal(completion_executor, sender, associated_data, plaintext, ciphertext, + * completion_token)`, which calls it. + * + * The context and the spans' bytes are the caller's until the completion. Declared here and + * defined in ``, which a program includes to call it, with + * `/webcpp/asio//asio` in its Jamfile. + * + * @tparam Executor The executor's type, an Asio executor. + * @tparam CompletionToken Any completion token for the signature + * `void(boost::system::error_code)`. + * @param completion_executor The executor the completion is posted to. + * @param associated_data Authenticated, not encrypted. + * @param plaintext The message. + * @param ciphertext `plaintext.size() + Suite::tag_size` bytes. + * @param completion_token The completion token, of signature + * `void(boost::system::error_code)`: `seal`'s error. + * @return What the completion token's `async_result` gives. + */ + template + auto async_seal(Executor const& completion_executor, + std::span associated_data, + std::span plaintext, std::span ciphertext, + CompletionToken&& completion_token); + + /** + * Exports a secret of `Length` bytes (RFC 9180's `Context.Export`), which the recipient's + * context exports too: `LabeledExpand(exporter_secret, "sec", purpose, Length)`. + * + * It changes nothing: the sequence number is untouched. + * + * @tparam Length 1 to `max_export_size`, checked at compile time. + * @param purpose `exporter_context`: what the secret is for, of any length. + * @return The secret; `invalid_state` moved from; `backend_failure`. + */ + template + [[nodiscard]] boost::system::result> + export_secret(std::span purpose) const noexcept { + secure::timing_guard const timing_scope; + return core_.template export_fixed(purpose); + } + + /** + * Exports a secret into `output`, of a length known at run time (RFC 9180's + * `Context.Export`, `L` the output's size). + * + * @param purpose `exporter_context`, of any length. + * @param output 1 to `max_export_size` bytes. + * @return Nothing; `invalid_input_size` for an empty or longer `output`, untouched; + * `invalid_state` moved from; `backend_failure`. + */ + [[nodiscard]] boost::system::result export_secret( + std::span purpose, std::span output) const noexcept { + secure::timing_guard const timing_scope; + return core_.export_secret(purpose, output); + } + +private: + sender_context() noexcept = default; + + sender_context(detail::hpke_context_core&& made_core, + encapsulated_key_type const& made_key) noexcept + : core_(std::move(made_core)), encapsulated_key_(made_key) {} + + detail::hpke_context_core core_; + encapsulated_key_type encapsulated_key_; +}; + +/** + * The recipient's context of a suite (RFC 9180's `Context`), which `begin_receiving` makes: it + * opens messages in the order they were sealed, and exports secrets. + * + * It is move-only; moved from, every member refuses with `invalid_state`. It wipes its secrets + * when moved from and destroyed. It is not thread-safe. A message that does not open leaves the + * sequence number where it was, so the next message is still expected; a lost message ends the + * stream (RFC 9180 section 5.2). + * + * @tparam Suite The suite, a specialisation of `hpke::suite`. + */ +template +class recipient_context { + friend struct detail::hpke_access; + // The asynchronous family's error completions make the empty context. + friend struct detail::async_access; + +public: + /** The suite. */ + using suite_type = Suite; + /** The longest export, `255 * Nh` bytes. */ + static constexpr std::size_t max_export_size = Suite::max_export_size; + + /** + * Moves the context; the source is wiped and refuses every call. + * + * @param moved_from The context moved from. + */ + recipient_context(recipient_context&& moved_from) noexcept = default; + + /** + * Moves over this context, wiped first; the source is wiped and refuses every call. + * + * @param moved_from The context moved from. + * @return This context. + */ + recipient_context& operator=(recipient_context&& moved_from) noexcept = default; + + /** Not copyable: a copy would reuse nonces. */ + recipient_context(recipient_context const&) = delete; + /** Not copyable: a copy would reuse nonces. */ + recipient_context& operator=(recipient_context const&) = delete; + + /** Wipes the key, the base nonce and the exporter secret. */ + ~recipient_context() = default; + + /** + * Opens the next message (RFC 9180's `ContextR.Open`): the ciphertext followed by its tag, + * under the nonce of the context's sequence number, which it increments only when the message + * opened. + * + * `plaintext` may be the first bytes of `ciphertext`, opened in place; it overlaps + * `ciphertext` in no other way. An export-only suite has no `open`: the call stops the build. + * + * @param associated_data The associated data of the seal. + * @param ciphertext The ciphertext then the tag, at least `Suite::tag_size` bytes. + * @param plaintext `ciphertext.size() - Suite::tag_size` bytes. + * @return Nothing; `invalid_state` moved from; `invalid_input_size` for a `ciphertext` + * shorter than the tag or a `plaintext` of another size, untouched; `message_limit_reached`; + * `authentication_failed` when the message, its associated data or its order differs, or + * the context is not the sender's, `plaintext` zeroed and the sequence number unchanged. + */ + [[nodiscard]] boost::system::result open(std::span associated_data, + std::span ciphertext, + std::span plaintext) noexcept { + secure::timing_guard const timing_scope; + if constexpr (!sealing_cipher) { + static_assert(detail::dependent_false, + "webcpp::crypto: an export-only HPKE suite only exports: it has no seal " + "or open. Call export_secret, or name a cipher that seals " + "(hpke::cipher::aes128_gcm, aes256_gcm or chacha20_poly1305)."); + return error::invalid_state; + } else { + return core_.open(associated_data, ciphertext, plaintext); + } + } + + /** + * Opens the next message, asynchronously: `open` run when the operation is initiated, its + * result posted to `completion_executor`; the member form of + * `hpke::async_open(completion_executor, recipient, associated_data, ciphertext, plaintext, + * completion_token)`, which calls it. + * + * The context and the spans' bytes are the caller's until the completion. Declared here and + * defined in ``, which a program includes to call it, with + * `/webcpp/asio//asio` in its Jamfile. + * + * @tparam Executor The executor's type, an Asio executor. + * @tparam CompletionToken Any completion token for the signature + * `void(boost::system::error_code)`. + * @param completion_executor The executor the completion is posted to. + * @param associated_data The associated data of the seal. + * @param ciphertext The ciphertext then the tag. + * @param plaintext `ciphertext.size() - Suite::tag_size` bytes. + * @param completion_token The completion token, of signature + * `void(boost::system::error_code)`: `open`'s error. + * @return What the completion token's `async_result` gives. + */ + template + auto async_open(Executor const& completion_executor, + std::span associated_data, + std::span ciphertext, std::span plaintext, + CompletionToken&& completion_token); + + /** + * Exports a secret of `Length` bytes (RFC 9180's `Context.Export`), the one the sender's + * context exports for the same purpose. + * + * @tparam Length 1 to `max_export_size`, checked at compile time. + * @param purpose `exporter_context`: what the secret is for, of any length. + * @return The secret; `invalid_state` moved from; `backend_failure`. + */ + template + [[nodiscard]] boost::system::result> + export_secret(std::span purpose) const noexcept { + secure::timing_guard const timing_scope; + return core_.template export_fixed(purpose); + } + + /** + * Exports a secret into `output`, of a length known at run time. + * + * @param purpose `exporter_context`, of any length. + * @param output 1 to `max_export_size` bytes. + * @return Nothing; `invalid_input_size` for an empty or longer `output`, untouched; + * `invalid_state` moved from; `backend_failure`. + */ + [[nodiscard]] boost::system::result export_secret( + std::span purpose, std::span output) const noexcept { + secure::timing_guard const timing_scope; + return core_.export_secret(purpose, output); + } + +private: + recipient_context() noexcept = default; + + explicit recipient_context(detail::hpke_context_core&& made_core) noexcept + : core_(std::move(made_core)) {} + + detail::hpke_context_core core_; +}; + +} // namespace webcpp::crypto::public_key_encryption::hpke + +#endif // WEBCPP_CRYPTO_PUBLIC_KEY_ENCRYPTION_HPKE_CONTEXT_HPP diff --git a/include/webcpp/crypto/public_key_encryption/hpke/key_derivation.hpp b/include/webcpp/crypto/public_key_encryption/hpke/key_derivation.hpp new file mode 100644 index 0000000..f06ad39 --- /dev/null +++ b/include/webcpp/crypto/public_key_encryption/hpke/key_derivation.hpp @@ -0,0 +1,176 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + HPKE's key derivations (RFC 9180 section 7.2): `hpke::key_derivation::hkdf_sha256` and + `hkdf_sha512`, the tags a suite names, and their concept `hpke::key_derivation_function`. + + The derivation is webcpp::hash's HKDF over input pieces: RFC 9180's `LabeledExtract` and + `LabeledExpand` give `"HPKE-v1"`, the suite identifier, the label and the input to + `hash::hkdf_extract` and `hash::hkdf_expand` as pieces, so that no input is copied, capped or + allocated (design D4, ruling R1). It calls no backend of crypto's. + + @see "HPKE (RFC 9180)", in the guide. +*/ +#ifndef WEBCPP_CRYPTO_PUBLIC_KEY_ENCRYPTION_HPKE_KEY_DERIVATION_HPP +#define WEBCPP_CRYPTO_PUBLIC_KEY_ENCRYPTION_HPKE_KEY_DERIVATION_HPP + +#include + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +namespace webcpp::crypto::public_key_encryption::hpke { + +/** + * Whether `KeyDerivation` is an HPKE key derivation (RFC 9180's KDF): `KeyDerivation::id`, its + * identifier, `KeyDerivation::hash_size` (`Nh`), and `typename KeyDerivation::hmac_type`, a + * webcpp::hash HMAC whose result is `hash_size` bytes, over which `hash::hkdf_extract` and + * `hash::hkdf_expand` take pieces. + * + * Only `key_derivation::hkdf_sha256` and `hkdf_sha512` are tested and supported (ruling R11). + * + * @tparam KeyDerivation A tag type. + */ +template +concept key_derivation_function = requires { + { KeyDerivation::id } -> std::convertible_to; + { KeyDerivation::hash_size } -> std::convertible_to; + typename KeyDerivation::hmac_type; + requires(typename KeyDerivation::hmac_type::result_type().size() == KeyDerivation::hash_size); +}; + +/** HPKE's key derivations, the second parameter of a suite (RFC 9180 section 7.2). */ +namespace key_derivation { + +/** HKDF-SHA256, RFC 9180's KDF 0x0001. */ +struct hkdf_sha256 { + /** The identifier, `kdf_id`. */ + static constexpr std::uint16_t id = 0x0001; + /** The size of SHA-256's digest, `Nh`. */ + static constexpr std::size_t hash_size = 32; + /** The HMAC webcpp::hash's HKDF runs over. */ + using hmac_type = hash::hmac_sha2_256; +}; + +/** HKDF-SHA512, RFC 9180's KDF 0x0003. */ +struct hkdf_sha512 { + /** The identifier, `kdf_id`. */ + static constexpr std::uint16_t id = 0x0003; + /** The size of SHA-512's digest, `Nh`. */ + static constexpr std::size_t hash_size = 64; + /** The HMAC webcpp::hash's HKDF runs over. */ + using hmac_type = hash::hmac_sha2_512; +}; + +} // namespace key_derivation + +static_assert(key_derivation_function); +static_assert(key_derivation_function); + +} // namespace webcpp::crypto::public_key_encryption::hpke + +namespace webcpp::crypto::detail { + +/** RFC 9180's version label, `"HPKE-v1"`, the first piece of every labeled input. */ +inline constexpr std::array hpke_version_label{'H', 'P', 'K', 'E', '-', 'v', '1'}; + +/** + * A label of RFC 9180, as the bytes of its text without the terminating zero. + * + * @tparam N The size of the text with its terminating zero. + * @param label_text A string literal. + * @return Its bytes. + */ +template +// NOLINTNEXTLINE(modernize-avoid-c-arrays): a string literal's array keeps its length in its type +[[nodiscard]] consteval std::array hpke_label(char const (&label_text)[N]) { + std::array label_bytes{}; + for (std::size_t index = 0; index + 1 < N; ++index) { + label_bytes[index] = static_cast(label_text[index]); + } + return label_bytes; +} + +/** + * RFC 9180's `LabeledExtract(salt, label, ikm)`, `Extract(salt, "HPKE-v1" || suite_id || label || + * ikm)`, by webcpp::hash's HKDF over pieces; the extracted key is copied into a secret and wiped. + * + * @tparam KeyDerivation The key derivation. + * @param salt The salt, empty for RFC 9180's `""`. + * @param suite_identifier The suite identifier. + * @param label The label. + * @param input_key_material The input keying material, of any length. + * @return The pseudorandom key; `backend_failure` when webcpp::hash fails, which it cannot for + * these sizes. + */ +template +[[nodiscard]] boost::system::result> hpke_labeled_extract( + std::span salt, std::span suite_identifier, + std::span label, + std::span input_key_material) noexcept { + auto extracted = hash::hkdf_extract( + salt, {hpke_version_label, suite_identifier, label, input_key_material}); + if (!extracted) { + return error::backend_failure; + } + secure::secret pseudorandom_key; + std::copy_n(extracted.unsafe_value().data(), KeyDerivation::hash_size, + pseudorandom_key.writable().begin()); + secure::erase_secret( + std::span(extracted.unsafe_value().data(), extracted.unsafe_value().size())); + return pseudorandom_key; +} + +/** + * RFC 9180's `LabeledExpand(prk, label, info, L)`, `Expand(prk, I2OSP(L, 2) || "HPKE-v1" || + * suite_id || label || info, L)`, by webcpp::hash's HKDF over pieces, `L` the output's size. + * + * @tparam KeyDerivation The key derivation. + * @param pseudorandom_key `hash_size` bytes. + * @param suite_identifier The suite identifier. + * @param label The label. + * @param application_info The info, of any length. + * @param output_key_material 1 to `255 * hash_size` bytes, which the caller has checked. + * @return Nothing, the output written; `backend_failure` when webcpp::hash fails, which it cannot + * for these sizes, the output zeroed. + */ +template +[[nodiscard]] boost::system::result hpke_labeled_expand( + std::span pseudorandom_key, + std::span suite_identifier, std::span label, + std::span application_info, + std::span output_key_material) noexcept { + // I2OSP(L, 2): the output is at most 255 * 64 bytes, which two bytes hold. Public. + std::array const length_bytes{ + static_cast(output_key_material.size() >> 8U), + static_cast(output_key_material.size() & 0xffU), + }; + auto const expanded = hash::hkdf_expand( + output_key_material, pseudorandom_key, + {length_bytes, hpke_version_label, suite_identifier, label, application_info}); + if (!expanded) { + secure::erase_secret(output_key_material); + return error::backend_failure; + } + return {}; +} + +} // namespace webcpp::crypto::detail + +#endif // WEBCPP_CRYPTO_PUBLIC_KEY_ENCRYPTION_HPKE_KEY_DERIVATION_HPP diff --git a/include/webcpp/crypto/public_key_encryption/hpke/key_encapsulation.hpp b/include/webcpp/crypto/public_key_encryption/hpke/key_encapsulation.hpp new file mode 100644 index 0000000..9fc36c0 --- /dev/null +++ b/include/webcpp/crypto/public_key_encryption/hpke/key_encapsulation.hpp @@ -0,0 +1,572 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + HPKE's key encapsulations (RFC 9180 section 4.1, DHKEM): `hpke::key_encapsulation:: + x25519_hkdf_sha256` and `p256_hkdf_sha256`, the tags a suite names, their encapsulated keys and + their `derive_from_seed` (RFC 9180's `DeriveKeyPair`), and their concept + `hpke::key_encapsulation_mechanism`. + + The encapsulation is an agreement of crypto's typed key pairs, `curves::x25519` and + `curves::p256`, hashed by the key encapsulation's own key derivation (design D3); its validation + is the typed keys': a P-256 point is on the curve when it is made, and an X25519 agreement that + is all zero is `weak_public_key`. + + @see "HPKE (RFC 9180)", in the guide. +*/ +#ifndef WEBCPP_CRYPTO_PUBLIC_KEY_ENCRYPTION_HPKE_KEY_ENCAPSULATION_HPP +#define WEBCPP_CRYPTO_PUBLIC_KEY_ENCRYPTION_HPKE_KEY_ENCAPSULATION_HPP + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::crypto::detail { + +/** The seam of HPKE's tests and the maker of its contexts (`hpke.hpp`). */ +struct hpke_access; + +} // namespace webcpp::crypto::detail + +namespace webcpp::crypto::public_key_encryption::hpke { + +/** + * The encapsulated key of a key encapsulation (RFC 9180's `enc`): the bytes of the sender's + * ephemeral public key, which travel with the ciphertexts. + * + * It is a type of its own per key encapsulation, `KeyEncapsulation::encapsulated_key`, not the + * curve's public key type, so that it cannot be given where a recipient's key is expected (ruling + * R5). `from_bytes` checks its size alone; `begin_receiving` validates it as a public key. It holds + * nothing secret and is copied freely: a regular value type. + * + * @tparam KeyEncapsulation The key encapsulation whose key it is. + */ +template +class basic_encapsulated_key { +public: + /** Its size in bytes, `Nenc`. */ + static constexpr std::size_t size = KeyEncapsulation::encapsulated_key_size; + + /** + * Makes an encapsulated key from its bytes, as they came with the ciphertexts. + * + * @param key_bytes `size` bytes; nothing else is checked here. + * @return The encapsulated key; `invalid_input_size` for another size. + */ + [[nodiscard]] static boost::system::result from_bytes( + std::span key_bytes) noexcept { + if (key_bytes.size() != size) { + return error::invalid_input_size; + } + basic_encapsulated_key made_key; + std::ranges::copy(key_bytes, made_key.bytes_.begin()); + return made_key; + } + + /** + * The bytes to send. + * + * @return `size` bytes. + */ + [[nodiscard]] std::array const& bytes() const noexcept { return bytes_; } + + /** Zero bytes: the value a sender context moved from holds, which no recipient accepts. */ + basic_encapsulated_key() noexcept = default; + + /** + * Compares two encapsulated keys. + * + * @param other_key The other key. + * @return True for the same bytes. + */ + [[nodiscard]] bool operator==(basic_encapsulated_key const& other_key) const noexcept = default; + +private: + std::array bytes_{}; +}; + +/** + * Whether `KeyEncapsulation` is an HPKE key encapsulation (RFC 9180's KEM): its identifier `id`; + * its sizes `shared_secret_size` (`Nsecret`), `encapsulated_key_size` (`Nenc`), `public_key_size` + * (`Npk`) and `secret_key_size` (`Nsk`); its own `key_derivation_type`, a + * `key_derivation_function`; its curve's `family_type`; its `encapsulated_key`; and the templates + * `keypair_type` and `public_key_type`, the key pair a + * `crypto::agreement_keypair` whose `agree` takes the public key. + * + * Only `key_encapsulation::x25519_hkdf_sha256` and `p256_hkdf_sha256` are tested and supported + * (ruling R11). + * + * @tparam KeyEncapsulation A tag type. + */ +template +concept key_encapsulation_mechanism = requires { + { KeyEncapsulation::id } -> std::convertible_to; + { KeyEncapsulation::shared_secret_size } -> std::convertible_to; + { KeyEncapsulation::encapsulated_key_size } -> std::convertible_to; + { KeyEncapsulation::public_key_size } -> std::convertible_to; + { KeyEncapsulation::secret_key_size } -> std::convertible_to; + typename KeyEncapsulation::key_derivation_type; + requires key_derivation_function; + typename KeyEncapsulation::family_type; + typename KeyEncapsulation::encapsulated_key; + typename KeyEncapsulation::template keypair_type< + default_backend_t>; + typename KeyEncapsulation::template public_key_type< + default_backend_t>; + requires agreement_keypair>>; +}; + +} // namespace webcpp::crypto::public_key_encryption::hpke + +namespace webcpp::crypto::detail { + +/** + * A key encapsulation's suite identifier, `"KEM" || I2OSP(kem_id, 2)` (RFC 9180 section 4.1). + * + * @tparam KeyEncapsulation The key encapsulation. + */ +template +inline constexpr std::array hpke_kem_suite_identifier{ + 'K', + 'E', + 'M', + static_cast(KeyEncapsulation::id >> 8U), + static_cast(KeyEncapsulation::id & 0xffU), +}; + +/** + * RFC 9180's `SerializePublicKey`: X25519's 32 bytes, P-256's uncompressed point. + * + * @tparam PublicKey An X25519 or a P-256 public key. + * @param public_key The key. + * @return Its bytes, a copy. + */ +template +[[nodiscard]] auto hpke_serialized(PublicKey const& public_key) noexcept { + if constexpr (requires { public_key.uncompressed(); }) { + return public_key.uncompressed(); + } else { + return public_key.bytes(); + } +} + +/** + * The key pair type of a key encapsulation on a backend. + * + * @tparam KeyEncapsulation The key encapsulation. + * @tparam Backend The key pair's backend. + */ +template +using hpke_keypair_t = KeyEncapsulation::template keypair_type; + +/** + * RFC 9180's DHKEM over a curve's typed key pairs on a backend (design D3): the encapsulation + * and the decapsulation, and their authenticated forms, without a guard of their own (the public + * function that calls them holds it). + * + * @tparam KeyEncapsulation The key encapsulation. + * @tparam Backend The key pairs' backend. + */ +template +struct hpke_dhkem { + /** The key pair's type. */ + using keypair_type = KeyEncapsulation::template keypair_type; + /** The public key's type. */ + using public_key_type = KeyEncapsulation::template public_key_type; + /** The encapsulated key's type. */ + using encapsulated_key_type = KeyEncapsulation::encapsulated_key; + /** The size of the shared secret. */ + static constexpr std::size_t shared_secret_size = KeyEncapsulation::shared_secret_size; + /** The size of one agreement's result, `Ndh`. */ + static constexpr std::size_t agreement_size = + decltype(std::declval().agree( + std::declval()))::value_type::size(); + /** The size of a serialized public key. */ + static constexpr std::size_t public_key_size = KeyEncapsulation::public_key_size; + + /** An encapsulation's results: the shared secret and the key to send. */ + struct encapsulation { + /** The shared secret, `shared_secret`. */ + secure::secret shared_secret; + /** The encapsulated key, `enc`. */ + encapsulated_key_type encapsulated_key; + }; + + /** + * RFC 9180's `ExtractAndExpand(dh, kem_context)`: `LabeledExpand(LabeledExtract("", + * "eae_prk", dh), "shared_secret", kem_context, Nsecret)`, under the key encapsulation's own + * key derivation. + * + * @param agreement_bytes The agreements, one or two. + * @param kem_context The encapsulated key and the serialized public keys. + * @return The shared secret; `backend_failure`. + */ + [[nodiscard]] static boost::system::result> + extract_and_expand(std::span agreement_bytes, + std::span kem_context) noexcept { + using key_derivation = KeyEncapsulation::key_derivation_type; + constexpr auto eae_prk_label = hpke_label("eae_prk"); + constexpr auto shared_secret_label = hpke_label("shared_secret"); + auto const pseudorandom_key = hpke_labeled_extract( + {}, hpke_kem_suite_identifier, eae_prk_label, agreement_bytes); + if (!pseudorandom_key) { + return pseudorandom_key.error(); + } + secure::secret shared_secret; + auto const expanded = hpke_labeled_expand( + pseudorandom_key.unsafe_value().bytes(), hpke_kem_suite_identifier, + shared_secret_label, kem_context, shared_secret.writable()); + if (!expanded) { + return expanded.error(); + } + return shared_secret; + } + + /** + * RFC 9180's `Encap` and, with a sender's key pair, `AuthEncap`, with the ephemeral key pair + * given. + * + * @param recipient_public_key The recipient's public key. + * @param ephemeral_keypair The ephemeral key pair. + * @param sender_keypair The sender's key pair, or null. + * @return The shared secret and the encapsulated key; `weak_public_key` for an X25519 + * recipient's key of small order; `invalid_state` for a key pair moved from; + * `backend_failure`. + */ + [[nodiscard]] static boost::system::result encapsulate( + public_key_type const& recipient_public_key, keypair_type const& ephemeral_keypair, + keypair_type const* sender_keypair) noexcept { + auto const ephemeral_public_key = ephemeral_keypair.public_key(); + if (!ephemeral_public_key) { + return ephemeral_public_key.error(); + } + auto const encapsulated_bytes = hpke_serialized(ephemeral_public_key.unsafe_value()); + auto const made_key = encapsulated_key_type::from_bytes(encapsulated_bytes); + if (!made_key) { + return made_key.error(); + } + std::array, 3> context_parts{encapsulated_bytes, {}, {}}; + auto const recipient_bytes = hpke_serialized(recipient_public_key); + context_parts[1] = recipient_bytes; + std::array sender_bytes{}; + if (sender_keypair != nullptr) { + auto const sender_public_key = sender_keypair->public_key(); + if (!sender_public_key) { + return sender_public_key.error(); + } + sender_bytes = hpke_serialized(sender_public_key.unsafe_value()); + context_parts[2] = sender_bytes; + } + auto shared_secret = agreed(ephemeral_keypair, recipient_public_key, sender_keypair, + &recipient_public_key, context_parts); + if (!shared_secret) { + return shared_secret.error(); + } + return encapsulation{std::move(shared_secret).unsafe_value(), made_key.unsafe_value()}; + } + + /** + * RFC 9180's `Decap` and, with a sender's public key, `AuthDecap`. + * + * @param encapsulated_key The encapsulated key received. + * @param recipient_keypair The recipient's key pair. + * @param sender_public_key The sender's public key, or null. + * @return The shared secret; `invalid_public_key` for a P-256 encapsulated key that is not a + * point of the curve; `weak_public_key` for an X25519 one of small order (or a sender's key); + * `invalid_state` for a key pair moved from; `backend_failure`. + */ + [[nodiscard]] static boost::system::result> decapsulate( + encapsulated_key_type const& encapsulated_key, keypair_type const& recipient_keypair, + public_key_type const* sender_public_key) noexcept { + auto const ephemeral_public_key = public_key_type::from_bytes(encapsulated_key.bytes()); + if (!ephemeral_public_key) { + return ephemeral_public_key.error(); + } + auto const recipient_public_key = recipient_keypair.public_key(); + if (!recipient_public_key) { + return recipient_public_key.error(); + } + auto const recipient_bytes = hpke_serialized(recipient_public_key.unsafe_value()); + std::array, 3> context_parts{ + encapsulated_key.bytes(), + recipient_bytes, + {}, + }; + std::array sender_bytes{}; + if (sender_public_key != nullptr) { + sender_bytes = hpke_serialized(*sender_public_key); + context_parts[2] = sender_bytes; + } + return agreed(recipient_keypair, ephemeral_public_key.unsafe_value(), + sender_public_key != nullptr ? &recipient_keypair : nullptr, + sender_public_key, context_parts); + } + +private: + /** + * The shared secret of one agreement, or of two in the authenticated forms, joined in a + * secret, and of the key encapsulation's context, joined on the stack (public bytes). + * + * @param first_keypair The first agreement's key pair. + * @param first_peer The first agreement's peer. + * @param second_keypair The second agreement's key pair, or null for one agreement. + * @param second_peer The second agreement's peer, read when `second_keypair` is not null. + * @param context_parts `enc`, the recipient's key and, authenticated, the sender's. + * @return The shared secret, or the first error. + */ + [[nodiscard]] static boost::system::result> agreed( + keypair_type const& first_keypair, public_key_type const& first_peer, + keypair_type const* second_keypair, public_key_type const* second_peer, + std::array, 3> const& context_parts) noexcept { + secure::secret<2 * agreement_size> agreement_bytes; + auto const first_agreement = first_keypair.agree(first_peer); + if (!first_agreement) { + return first_agreement.error(); + } + std::ranges::copy(first_agreement.unsafe_value().bytes(), + agreement_bytes.writable().begin()); + std::size_t agreement_length = agreement_size; + if (second_keypair != nullptr) { + auto const second_agreement = second_keypair->agree(*second_peer); + if (!second_agreement) { + return second_agreement.error(); + } + std::ranges::copy(second_agreement.unsafe_value().bytes(), + agreement_bytes.writable().begin() + agreement_size); + agreement_length = 2 * agreement_size; + } + std::array context_bytes{}; + std::size_t context_length = 0; + for (std::span const part : context_parts) { + std::ranges::copy(part, context_bytes.begin() + context_length); + context_length += part.size(); + } + return extract_and_expand( + agreement_bytes.bytes().first(agreement_length), + std::span(context_bytes).first(context_length)); + } +}; + +/** + * RFC 9180's `DeriveKeyPair` for X25519 (section 7.1.3): `dkp_prk = LabeledExtract("", + * "dkp_prk", seed)`, the secret key `LabeledExpand(dkp_prk, "sk", "", 32)`, kept unclamped + * (ruling R7). + * + * @tparam KeyEncapsulation The key encapsulation. + * @tparam Backend The key pair's backend. + * @param seed At least `secret_key_size` bytes, checked by the caller. + * @return The key pair; `backend_failure`. + */ +template +[[nodiscard]] boost::system::result> hpke_derive_x25519( + std::span seed) noexcept { + using key_derivation = KeyEncapsulation::key_derivation_type; + constexpr auto dkp_prk_label = hpke_label("dkp_prk"); + constexpr auto sk_label = hpke_label("sk"); + auto const pseudorandom_key = hpke_labeled_extract( + {}, hpke_kem_suite_identifier, dkp_prk_label, seed); + if (!pseudorandom_key) { + return pseudorandom_key.error(); + } + secure::secret secret_key; + auto const expanded = hpke_labeled_expand( + pseudorandom_key.unsafe_value().bytes(), hpke_kem_suite_identifier, + sk_label, {}, secret_key.writable()); + if (!expanded) { + return expanded.error(); + } + return hpke_keypair_t::from_secret(secret_key.bytes()); +} + +/** + * RFC 9180's `DeriveKeyPair` for P-256 (section 7.1.3): the first of 256 candidates + * `LabeledExpand(dkp_prk, "candidate", I2OSP(counter, 1), 32)` that is neither zero nor at least + * the group order. Whether a candidate is valid is marked public: it reveals only that an event + * of probability 2^-32 happened (design D10). + * + * @tparam KeyEncapsulation The key encapsulation. + * @tparam Backend The key pair's backend. + * @param seed At least `secret_key_size` bytes, checked by the caller. + * @return The key pair; `invalid_secret_key` when no candidate of 256 is valid (RFC 9180's + * `DeriveKeyPairError`); `backend_failure`. + */ +template +[[nodiscard]] boost::system::result> hpke_derive_p256( + std::span seed) noexcept { + using key_derivation = KeyEncapsulation::key_derivation_type; + constexpr auto dkp_prk_label = hpke_label("dkp_prk"); + constexpr auto candidate_label = hpke_label("candidate"); + auto const pseudorandom_key = hpke_labeled_extract( + {}, hpke_kem_suite_identifier, dkp_prk_label, seed); + if (!pseudorandom_key) { + return pseudorandom_key.error(); + } + secure::secret candidate; + for (unsigned counter = 0; counter < 256; ++counter) { + std::array const counter_byte{static_cast(counter)}; + auto const expanded = hpke_labeled_expand( + pseudorandom_key.unsafe_value().bytes(), hpke_kem_suite_identifier, + candidate_label, counter_byte, candidate.writable()); + if (!expanded) { + return expanded.error(); + } + // P-256's bitmask is 0xff: the candidate is used whole. + if (p_curve_scalar_valid(candidate.bytes(), p_curve_traits::order)) { + return hpke_keypair_t::from_secret(candidate.bytes()); + } + } + return error::invalid_secret_key; +} + +} // namespace webcpp::crypto::detail + +namespace webcpp::crypto::public_key_encryption::hpke { + +/** HPKE's key encapsulations, the first parameter of a suite (RFC 9180 section 7.1). */ +namespace key_encapsulation { + +/** + * DHKEM(X25519, HKDF-SHA256), RFC 9180's KEM 0x0020: an X25519 agreement with an ephemeral key + * pair, hashed by HKDF-SHA256. + */ +struct x25519_hkdf_sha256 { + /** The identifier, `kem_id`. */ + static constexpr std::uint16_t id = 0x0020; + /** The size of the shared secret, `Nsecret`. */ + static constexpr std::size_t shared_secret_size = 32; + /** The size of the encapsulated key, `Nenc`. */ + static constexpr std::size_t encapsulated_key_size = 32; + /** The size of a public key, `Npk`. */ + static constexpr std::size_t public_key_size = 32; + /** The size of a secret key, `Nsk`. */ + static constexpr std::size_t secret_key_size = 32; + /** The key encapsulation's own key derivation. */ + using key_derivation_type = key_derivation::hkdf_sha256; + /** The curve's family, whose default backend a suite's `default_backends` takes. */ + using family_type = families::x25519; + /** The encapsulated key, 32 bytes. */ + using encapsulated_key = basic_encapsulated_key; + /** + * The key pair on a backend. + * + * @tparam Backend The backend. + */ + template + using keypair_type = curves::x25519::basic_keypair; + /** + * The public key, the same on every backend. + * + * @tparam Backend The backend. + */ + template + using public_key_type = curves::x25519::public_key; + + /** + * Derives a key pair from a seed (RFC 9180's `DeriveKeyPair`): the secret key is + * `LabeledExpand(LabeledExtract("", "dkp_prk", seed), "sk", "", 32)`, kept unclamped, as + * RFC 9180's test vectors print it; `from_secret(key_pair.secret())` gives the same key pair. + * + * @tparam Backend The key pair's backend; by default X25519's. + * @param seed At least 32 bytes of entropy; no upper bound. + * @return The key pair; `invalid_input_size` for a seed shorter than 32 bytes; + * `backend_failure`. + */ + template > + [[nodiscard]] static boost::system::result> derive_from_seed( + std::span seed) noexcept { + secure::timing_guard const timing_scope; + if (seed.size() < secret_key_size) { + return error::invalid_input_size; + } + return detail::hpke_derive_x25519(seed); + } +}; + +/** + * DHKEM(P-256, HKDF-SHA256), RFC 9180's KEM 0x0010: a P-256 agreement with an ephemeral key + * pair, its raw x coordinate hashed by HKDF-SHA256. + */ +struct p256_hkdf_sha256 { + /** The identifier, `kem_id`. */ + static constexpr std::uint16_t id = 0x0010; + /** The size of the shared secret, `Nsecret`. */ + static constexpr std::size_t shared_secret_size = 32; + /** The size of the encapsulated key, `Nenc`: an uncompressed point. */ + static constexpr std::size_t encapsulated_key_size = 65; + /** The size of a public key, `Npk`: an uncompressed point. */ + static constexpr std::size_t public_key_size = 65; + /** The size of a secret key, `Nsk`. */ + static constexpr std::size_t secret_key_size = 32; + /** The key encapsulation's own key derivation. */ + using key_derivation_type = key_derivation::hkdf_sha256; + /** The curve's family, whose default backend a suite's `default_backends` takes. */ + using family_type = families::p256; + /** The encapsulated key, 65 bytes. */ + using encapsulated_key = basic_encapsulated_key; + /** + * The key pair on a backend. + * + * @tparam Backend The backend. + */ + template + using keypair_type = curves::p256::basic_keypair; + /** + * The public key on a backend. + * + * @tparam Backend The backend. + */ + template + using public_key_type = curves::p256::basic_public_key; + + /** + * Derives a key pair from a seed (RFC 9180's `DeriveKeyPair`): the first of 256 candidates + * `LabeledExpand(LabeledExtract("", "dkp_prk", seed), "candidate", counter, 32)` that is a + * valid scalar. + * + * @tparam Backend The key pair's backend; by default P-256's. + * @param seed At least 32 bytes of entropy; no upper bound. + * @return The key pair; `invalid_input_size` for a seed shorter than 32 bytes; + * `invalid_secret_key` when no candidate of 256 is a valid scalar (probability about + * 2^-8192); `backend_failure`. + */ + template > + [[nodiscard]] static boost::system::result> derive_from_seed( + std::span seed) noexcept { + secure::timing_guard const timing_scope; + if (seed.size() < secret_key_size) { + return error::invalid_input_size; + } + return detail::hpke_derive_p256(seed); + } +}; + +} // namespace key_encapsulation + +static_assert(key_encapsulation_mechanism); +static_assert(key_encapsulation_mechanism); + +} // namespace webcpp::crypto::public_key_encryption::hpke + +#endif // WEBCPP_CRYPTO_PUBLIC_KEY_ENCRYPTION_HPKE_KEY_ENCAPSULATION_HPP diff --git a/test/Jamfile b/test/Jamfile index 94237ae..aefe22a 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -43,7 +43,11 @@ webcpp.headers-alone crypto : ../include : crypto.hpp crypto/config.hpp crypto/factories.hpp crypto/detail/asynchronous.hpp crypto/detail/signature.hpp crypto/detail/curve_of.hpp crypto/detail/format_members.hpp crypto/formats.hpp - crypto/detail/bearssl_i31.hpp ; + crypto/detail/bearssl_i31.hpp + crypto/public_key_encryption/hpke.hpp + crypto/public_key_encryption/hpke/key_derivation.hpp + crypto/public_key_encryption/hpke/key_encapsulation.hpp + crypto/public_key_encryption/hpke/context.hpp ; # detail/heavy.hpp compiles alone only with webcpp::asio, which it includes # where the build has threads; async.hpp, which includes it, only with # webcpp::asio on every target. @@ -175,6 +179,12 @@ crypto-run async_gcm_openssl : async_gcm_test.cpp # never inline, a wrong tag, a refused key. crypto-run async_aead : async_aead_test.cpp : /third_party//sodium /webcpp/asio//asio ; +# HPKE's asynchronous forms on libsodium (X25519, ChaCha20-Poly1305) and on +# BearSSL (P-256, AES-128-GCM), every target: setups, contexts and single-shot +# calls in a coroutine, member and free, never inline, errors. +crypto-run hpke_async : hpke_async_test.cpp + : /third_party//sodium /third_party//bearssl + /webcpp/asio//asio ; # Ed25519's and X25519's asynchronous functions on libsodium, every target: # RFC 8032's and RFC 7748's cases, a changed byte, a generated key pair, a # refused seed, a weak peer key, a coroutine. @@ -842,6 +852,11 @@ crypto-run chacha_wycheproof_sodium : chacha_wycheproof_sodium_test.cpp : /third_party//sodium /third_party//wycheproof /webcpp//boost_json ; crypto-run allocation_sodium : allocation_sodium_test.cpp : /third_party//sodium ; +# HPKE allocates nothing on libsodium and BearSSL, every suite, and caps no +# input: long inputs round-trip and match webcpp::hash's HKDF on the joined +# labeled inputs. +crypto-run hpke_allocation : hpke_allocation_test.cpp + : /third_party//sodium /third_party//bearssl ; # libsodium's boxes, its default on every target: crypto_secretbox and its # XChaCha20 twin, secret_key_encryption's, libsodium's cases, its detached @@ -856,6 +871,33 @@ crypto-run allocation_sodium : allocation_sodium_test.cpp : /third_part crypto-run secretbox_sodium : secretbox_sodium_test.cpp : /third_party//sodium ; crypto-run box_sodium : box_sodium_test.cpp : /third_party//sodium ; +# HPKE (RFC 9180) against the CFRG test vectors, every entry of the suites +# crypto has, on every target: on the default backends of X25519, P-256, +# AES-GCM and ChaCha20-Poly1305, and with BearSSL's AEADs (P-256 wholly on +# BearSSL, X25519 on libsodium beside BearSSL's AEAD). +crypto-run hpke_vectors_default : hpke_vectors_default_test.cpp + : /webcpp/crypto//x25519-default /webcpp/crypto//p256-default + /webcpp/crypto//gcm-default + /webcpp/crypto//chacha20_poly1305-default + /third_party//hpke /webcpp//boost_json ; +crypto-run hpke_vectors_bearssl : hpke_vectors_bearssl_test.cpp + : /third_party//sodium /third_party//bearssl + /third_party//hpke /webcpp//boost_json ; +# HPKE against OpenSSL's OSSL_HPKE_* within OpenSSL's limits, every suite and +# mode, both directions, the same encapsulated key and ciphertexts for the +# same ephemeral seed, where the superproject builds OpenSSL. +crypto-run hpke_openssl : hpke_openssl_test.cpp + : /webcpp/crypto//openssl /third_party//sodium + /third_party//bearssl + : native wasip2 wasip3 ; +# HPKE's four modes, single-shot calls, free forms, refusals, minimum lengths, +# sequence limit and Marmot's recovery key, on the default backends, on every +# target. +crypto-run hpke : hpke_test.cpp + : /webcpp/crypto//x25519-default /webcpp/crypto//p256-default + /webcpp/crypto//gcm-default + /webcpp/crypto//chacha20_poly1305-default ; + # ChaCha20-Poly1305 on BearSSL, on every target, and on OpenSSL, on native, # wasip2 and wasip3: every check of support/aead_checks.hpp against RFC 8439's # cases, natively the message's limit too, and Wycheproof's vectors. @@ -923,6 +965,19 @@ crypto-run agreement_chacha_portable_emscripten : agreement_chacha_portable_test WEBCPP_CRYPTO_DETAIL_BEARSSL_PORTABLE : emscripten ; +# RFC 9001 Appendix A.1 to A.4, QUIC version 1's packet protection +# (support/quic_rfc9001.hpp; the change rfc9001-tests): the Initial keys +# through webcpp::hash's HKDF, both Initial packets protected and unprotected, +# a tampered one refused, the Retry integrity tag. On OpenSSL for AES-128-GCM +# and the header protection's block; on BearSSL, which has no block cipher, +# with ctaes for it; and on the defaults, aes128_gcm and aes128<>. +crypto-run quic_rfc9001_openssl : quic_rfc9001_openssl_test.cpp + : /webcpp/crypto//openssl : native wasip2 wasip3 ; +crypto-run quic_rfc9001_bearssl : quic_rfc9001_bearssl_test.cpp + : /third_party//bearssl /third_party//ctaes ; +crypto-run quic_rfc9001_default : quic_rfc9001_default_test.cpp + : /webcpp/crypto//gcm-default /webcpp/crypto//aes_block-default ; + # before and after every public header (spec sections 2.2 and 8.6), # with every backend linked: on MSVC (the CI's msvc lanes) the headers beside a # bare ; elsewhere the headers alone. diff --git a/test/constant_time/Jamfile b/test/constant_time/Jamfile index 6cdc989..30f5f59 100644 --- a/test/constant_time/Jamfile +++ b/test/constant_time/Jamfile @@ -262,9 +262,9 @@ if [ os.environ RUNNER_ENVIRONMENT ] = github-hosted { DUDECT += WEBCPP_TEST_DUDECT_UNJUDGED ; } -# On wasip2, hash's Base58Check secret decode (base58_decode) is measured and -# printed but not judged: an open finding of codecs' secret base58 conversion -# under wasmtime, which dudect_test.cpp's header describes. +# On a WASI target every case of dudect_bearssl is measured and printed but +# none is judged, by the owner's decision of 2026-12-04: under wasmtime their +# timing follows the runner's processor (dudect_test.cpp, unjudged_here). webcpp.run dudect_bearssl : dudect_test.cpp : /third_party//bearssl /third_party//ctaes /webcpp/hash//base58_with_checksum $(DUDECT) diff --git a/test/constant_time/dudect.hpp b/test/constant_time/dudect.hpp index 981f356..103457f 100644 --- a/test/constant_time/dudect.hpp +++ b/test/constant_time/dudect.hpp @@ -625,21 +625,43 @@ inline std::optional select_case(int argc, char const* const* ar /** * The cases a program measured: each one's lines printed as it is recorded, the human line that - * lists them, and whether every judged one passes. + * lists them, and whether every judged one passes. A program that judges none of its cases on + * the target it runs on says why once, and each of its cases is printed `judged=no`, whatever + * the case's own flag, so that the CI's judge measures none of them again. */ class case_results { public: + /** + * Results that judge each case by its own flag, or none of them. + * @param unjudged Why the program judges no case here, which `print` writes; nullptr, the + * default, where each case's own flag decides. + */ + explicit case_results(char const* unjudged = nullptr) noexcept : unjudged_(unjudged) {} + + /** + * Whether a case counts in the verdict: its own flag, unless the program judges no case here. + * A program measures a case through `measure_case` with this value, so that a case not judged + * runs once. + * @param judged_case The case's own flag. + * @return Whether its |t| counts. + */ + [[nodiscard]] bool judges(bool judged_case) const noexcept { + return judged_case && unjudged_ == nullptr; + } + /** * Prints a case's lines (`report_case`) and adds it to the human line and to the verdict. * @param name The case's name, as `--case` takes it. * @param label Its name in the human line. * @param result Its statistic. - * @param judged_case Whether its |t| counts in the verdict. + * @param judged_case Whether its |t| counts in the verdict, where the program judges its + * cases (`judges`). * @param buffers The buffers it measures: its input, its output and its object. * @param note Printed after its value in the human line. */ void record(char const* name, char const* label, t_statistic const& result, bool judged_case, std::initializer_list
buffers, char const* note = "") { + judged_case = judges(judged_case); report_case(name, result, judged_case, buffers); std::array value{}; static_cast(std::snprintf(value.data(), value.size(), "%s%s %.2f%s", @@ -649,8 +671,16 @@ class case_results { passes_ = passes_ && (!judged_case || printed(result.t) < 10); } - /** Prints the human line: `|t|