From d8cd024ea504633cc801b53a759ff0730fe56f17 Mon Sep 17 00:00:00 2001 From: R Date: Fri, 4 Dec 2026 00:36:24 -0300 Subject: [PATCH 1/7] crypto: RFC 9001 Appendix A.1 to A.4, QUIC version 1's packet protection, as tests on OpenSSL, on BearSSL with ctaes for the block and on the defaults, with no QUIC API; the capability table names them --- doc/generated/backends-aes_block.adoc | 4 +- doc/generated/backends-gcm.adoc | 4 +- doc/generated/matrix.adoc | 8 +- doc/tables/crypto.json | 8 +- test/Jamfile | 13 + test/quic_rfc9001_bearssl_test.cpp | 28 ++ test/quic_rfc9001_default_test.cpp | 23 ++ test/quic_rfc9001_openssl_test.cpp | 25 ++ test/support/quic_rfc9001.hpp | 403 ++++++++++++++++++++++++++ test/support/quic_rfc9001_vectors.hpp | 178 ++++++++++++ 10 files changed, 682 insertions(+), 12 deletions(-) create mode 100644 test/quic_rfc9001_bearssl_test.cpp create mode 100644 test/quic_rfc9001_default_test.cpp create mode 100644 test/quic_rfc9001_openssl_test.cpp create mode 100644 test/support/quic_rfc9001.hpp create mode 100644 test/support/quic_rfc9001_vectors.hpp diff --git a/doc/generated/backends-aes_block.adoc b/doc/generated/backends-aes_block.adoc index 653c8940..866a6361 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 1db54a1c..a4be9c35 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/matrix.adoc b/doc/generated/matrix.adoc index 84570baf..847de06b 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 diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 9d9ba46f..64597f84 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -324,8 +324,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"} } }, @@ -343,9 +343,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"} } }, diff --git a/test/Jamfile b/test/Jamfile index 94237ae5..eebc86fe 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -923,6 +923,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/quic_rfc9001_bearssl_test.cpp b/test/quic_rfc9001_bearssl_test.cpp new file mode 100644 index 00000000..08a2cbe8 --- /dev/null +++ b/test/quic_rfc9001_bearssl_test.cpp @@ -0,0 +1,28 @@ +// 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) + +// RFC 9001 Appendix A.1 to A.4 (QUIC version 1 packet protection) on BearSSL: AES-128-GCM on +// backends::bearssl, which has no block cipher, and the header protection's AES-128 block on +// backends::ctaes, the pair the defaults make on WebAssembly (support/quic_rfc9001.hpp). + +#include +#include +#include +#include +#include + +#include "support/quic_rfc9001.hpp" + +#include + +int main() { + namespace ciphers = webcpp::crypto::ciphers; + using webcpp::crypto::backends::bearssl; + using webcpp::crypto::backends::ctaes; + webcpp::test::quic_rfc9001::check_appendix_a>, + ciphers::aes128>(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/quic_rfc9001_default_test.cpp b/test/quic_rfc9001_default_test.cpp new file mode 100644 index 00000000..3c0d6e8a --- /dev/null +++ b/test/quic_rfc9001_default_test.cpp @@ -0,0 +1,23 @@ +// 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) + +// RFC 9001 Appendix A.1 to A.4 (QUIC version 1 packet protection) on the defaults a program +// writes, aes128_gcm and aes128<>: natively OpenSSL for both, on wasip2, wasip3 and Emscripten +// BearSSL and ctaes (support/quic_rfc9001.hpp). + +#include +#include +#include + +#include "support/quic_rfc9001.hpp" + +#include + +int main() { + namespace ciphers = webcpp::crypto::ciphers; + webcpp::test::quic_rfc9001::check_appendix_a>(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/quic_rfc9001_openssl_test.cpp b/test/quic_rfc9001_openssl_test.cpp new file mode 100644 index 00000000..09acb3bd --- /dev/null +++ b/test/quic_rfc9001_openssl_test.cpp @@ -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) + +// RFC 9001 Appendix A.1 to A.4 (QUIC version 1 packet protection) on OpenSSL: AES-128-GCM and +// the header protection's AES-128 block both on backends::openssl (support/quic_rfc9001.hpp). + +#include +#include +#include +#include + +#include "support/quic_rfc9001.hpp" + +#include + +int main() { + namespace ciphers = webcpp::crypto::ciphers; + using webcpp::crypto::backends::openssl; + webcpp::test::quic_rfc9001::check_appendix_a>, + ciphers::aes128>(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/support/quic_rfc9001.hpp b/test/support/quic_rfc9001.hpp new file mode 100644 index 00000000..91c467b7 --- /dev/null +++ b/test/support/quic_rfc9001.hpp @@ -0,0 +1,403 @@ +// 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) + +// QUIC version 1's packet protection (RFC 9001 sections 5.1 to 5.4 and 5.8) written with crypto's +// public API, and the checks of Appendix A.1 to A.4 over it (support/quic_rfc9001_vectors.hpp): +// the change rfc9001-tests. Each check is a template over the AEAD, a `gcm>`, and the +// header protection's block cipher, an `aes128`, so that each backend's program +// (quic_rfc9001__test.cpp) runs them all. Nothing here is crypto's API: TLS 1.3's +// HKDF-Expand-Label and QUIC's header parsing belong to the test (ruling R1). + +#ifndef WEBCPP_TEST_CRYPTO_SUPPORT_QUIC_RFC9001_HPP +#define WEBCPP_TEST_CRYPTO_SUPPORT_QUIC_RFC9001_HPP + +#include +#include +#include + +#include "../require.hpp" +#include "hex.hpp" +#include "quic_rfc9001_vectors.hpp" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::test::quic_rfc9001 { + +/** A text's bytes, viewed. */ +inline std::span bytes_of(std::string_view text) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): a text's bytes, viewed + return {reinterpret_cast(text.data()), text.size()}; +} + +/** RFC 8446 section 7.1: the prefix of every HkdfLabel's label. */ +inline constexpr std::string_view tls13_prefix = "tls13 "; +/** Section 5.2: the client's Initial secret's label. */ +inline constexpr std::string_view client_in = "client in"; +/** Section 5.2: the server's Initial secret's label. */ +inline constexpr std::string_view server_in = "server in"; +/** Section 5.1: the AEAD key's label. */ +inline constexpr std::string_view quic_key = "quic key"; +/** Section 5.1: the IV's label. */ +inline constexpr std::string_view quic_iv = "quic iv"; +/** Section 5.1: the header protection key's label. */ +inline constexpr std::string_view quic_hp = "quic hp"; + +/** + * RFC 8446 section 7.1's HkdfLabel with an empty context, as five pieces that HKDF-Expand reads + * one after another: the output's length (2 bytes), the label's length (1 byte), "tls13 ", the + * label, the context's length (0). + */ +class hkdf_label { +public: + /** + * @param output_length The output's length, at most 255 bytes here. + * @param label The label, without "tls13 ". + */ + hkdf_label(std::size_t output_length, std::string_view label) + : output_length_{ + static_cast(output_length >> 8U), + static_cast(output_length & 0xffU), + }, + label_length_{static_cast(tls13_prefix.size() + label.size())}, + label_(bytes_of(label)) {} + + /** The pieces, pointing into this object and the label. */ + [[nodiscard]] std::array, 5> pieces() const { + return {output_length_, label_length_, bytes_of(tls13_prefix), label_, context_length_}; + } + + /** The pieces joined: the HkdfLabel's bytes. */ + [[nodiscard]] std::vector bytes() const { + std::vector joined; + for (std::span const piece : pieces()) { + joined.insert(joined.end(), piece.begin(), piece.end()); + } + return joined; + } + +private: + std::array output_length_; + std::array label_length_; + std::span label_; + std::array context_length_{}; +}; + +/** + * HKDF-Expand-Label(secret, label, "", N) over SHA-256 (RFC 8446 section 7.1), through + * webcpp::hash's HKDF-Expand over pieces, on hash's default backend (ruling R4). + */ +template +std::array expand_label(std::span secret, + std::string_view label) { + hkdf_label const info(N, label); + auto const info_pieces = info.pieces(); + std::array output{}; + auto const expanded = + webcpp::hash::hkdf_expand(output, secret, info_pieces); + require(BOOST_TEST(expanded.has_value())); + return output; +} + +/** The keys of one direction of a connection, as section 5.1 derives them from its secret. */ +struct packet_keys { + /** AES-128-GCM's key. */ + std::array key; + /** The nonce's base. */ + std::array iv; + /** The header protection's AES-128 key. */ + std::array hp; +}; + +/** Section 5.1: "quic key", "quic iv" and "quic hp" of `secret`. */ +inline packet_keys derive_packet_keys(std::span secret) { + return { + .key = expand_label<16>(secret, quic_key), + .iv = expand_label<12>(secret, quic_iv), + .hp = expand_label<16>(secret, quic_hp), + }; +} + +/** Section 5.3: the nonce, the IV with the packet number XORed into its last 8 bytes. */ +inline std::array packet_nonce(std::array const& iv, + std::uint64_t packet_number) { + std::array nonce = iv; + for (std::size_t i = 0; i < 8; ++i) { + nonce[11 - i] ^= static_cast(packet_number >> (8U * i)); + } + return nonce; +} + +/** Section 5.4.3: the first 5 bytes of AES-ECB(hp, sample), on the block cipher `Block`. */ +template +std::array header_protection_mask(std::span hp, + std::span sample) { + auto cipher = Block::from_key(hp); + require(BOOST_TEST(cipher.has_value())); + std::array block{}; + std::copy_n(sample.begin(), block.size(), block.begin()); + require(BOOST_TEST(cipher->encrypt(block).has_value())); + std::array mask{}; + std::copy_n(block.begin(), mask.size(), mask.begin()); + return mask; +} + +/** RFC 9000 section 16: the length of the variable-length integer at `bytes`, and its value. */ +inline std::size_t read_varint(std::span bytes, std::uint64_t& value) { + std::size_t const length = std::size_t{1} << (static_cast(bytes[0]) >> 6U); + value = bytes[0] & 0x3fU; + for (std::size_t i = 1; i < length; ++i) { + value = (value << 8U) | bytes[i]; + } + return length; +} + +/** + * RFC 9000 section 17.2.2: the offset of an Initial packet's Packet Number field, past the first + * byte, the version, both connection IDs, the token and the length. + */ +inline std::size_t initial_packet_number_offset(std::span packet) { + std::size_t offset = 1 + 4; + offset += 1 + packet[offset]; // the Destination Connection ID + offset += 1 + packet[offset]; // the Source Connection ID + std::uint64_t token_length = 0; + offset += read_varint(packet.subspan(offset), token_length); + offset += static_cast(token_length); + std::uint64_t length = 0; + offset += read_varint(packet.subspan(offset), length); + return offset; +} + +/** Section 5.4.1: the bits of the first byte header protection masks, by the header's form. */ +inline unsigned first_byte_mask(std::uint8_t first_byte) { + return (first_byte & 0x80U) != 0 ? 0x0fU : 0x1fU; +} + +/** + * Sections 5.3 and 5.4: protects an Initial packet, `header` (unprotected, ending with its packet + * number) followed by `payload`: seals the payload with the header as associated data, then + * masks the first byte and the packet number with the sample at 4 bytes past its start. + */ +template +std::vector protect(packet_keys const& keys, std::span header, + std::uint64_t packet_number, + std::span payload) { + std::vector packet(header.begin(), header.end()); + packet.insert(packet.end(), payload.begin(), payload.end()); + auto aead = Aead::from_key(keys.key); + require(BOOST_TEST(aead.has_value())); + auto const nonce = packet_nonce(keys.iv, packet_number); + auto const tag = + aead->seal(nonce, header, std::span(packet).subspan(header.size(), payload.size())); + require(BOOST_TEST(tag.has_value())); + packet.insert(packet.end(), tag->begin(), tag->end()); + + std::size_t const packet_number_length = (header[0] & 0x03U) + 1U; + std::size_t const packet_number_offset = header.size() - packet_number_length; + auto const mask = header_protection_mask( + keys.hp, std::span(packet).subspan(packet_number_offset + 4, 16)); + packet[0] ^= static_cast(mask[0] & first_byte_mask(packet[0])); + for (std::size_t i = 0; i < packet_number_length; ++i) { + packet[packet_number_offset + i] ^= mask[1 + i]; + } + return packet; +} + +/** What `unprotect` gives back. */ +struct unprotected_packet { + /** The header, its first byte and packet number unmasked. */ + std::vector header; + /** The payload, opened in place; zeroed when the open failed. */ + std::vector payload; + /** The packet number as the packet carries it (RFC 9001's examples need no reconstruction). */ + std::uint64_t packet_number = 0; + /** The open's result. */ + boost::system::result opened; +}; + +/** + * Sections 5.3 and 5.4, as a receiver: removes an Initial packet's header protection, the packet + * number's length read from the unmasked first byte, then opens the payload. + */ +template +unprotected_packet unprotect(packet_keys const& keys, std::span packet) { + std::size_t const packet_number_offset = initial_packet_number_offset(packet); + auto const mask = + header_protection_mask(keys.hp, packet.subspan(packet_number_offset + 4, 16)); + auto const first_byte = static_cast(static_cast(packet[0]) ^ + (mask[0] & first_byte_mask(packet[0]))); + std::size_t const packet_number_length = (first_byte & 0x03U) + 1U; + std::size_t const header_size = packet_number_offset + packet_number_length; + + unprotected_packet result{ + .header = {packet.begin(), packet.begin() + header_size}, + .payload = {packet.begin() + header_size, packet.end() - 16}, + .opened = {}, + }; + result.header[0] = first_byte; + for (std::size_t i = 0; i < packet_number_length; ++i) { + result.header[packet_number_offset + i] ^= mask[1 + i]; + result.packet_number = + (result.packet_number << 8U) | result.header[packet_number_offset + i]; + } + auto aead = Aead::from_key(keys.key); + require(BOOST_TEST(aead.has_value())); + auto const nonce = packet_nonce(keys.iv, result.packet_number); + result.opened = aead->open(nonce, result.header, result.payload, packet.last(16)); + return result; +} + +/** A.2's payload: the CRYPTO frame, then PADDING frames (zero bytes) to 1,162 bytes. */ +inline std::vector client_payload() { + std::vector payload = from_hex(client_crypto_frame); + payload.resize(client_payload_size, 0); + return payload; +} + +/** A.1: the HkdfLabels, the initial secret and both directions' secrets, keys, IVs and hp. */ +inline void check_keys() { + BOOST_TEST_EQ(to_hex(hkdf_label(32, client_in).bytes()), to_hex(label_client_in)); + BOOST_TEST_EQ(to_hex(hkdf_label(32, server_in).bytes()), to_hex(label_server_in)); + BOOST_TEST_EQ(to_hex(hkdf_label(16, quic_key).bytes()), to_hex(label_quic_key)); + BOOST_TEST_EQ(to_hex(hkdf_label(12, quic_iv).bytes()), to_hex(label_quic_iv)); + BOOST_TEST_EQ(to_hex(hkdf_label(16, quic_hp).bytes()), to_hex(label_quic_hp)); + + auto const extracted = webcpp::hash::hkdf_extract( + initial_salt, client_destination_connection_id); + if (!BOOST_TEST(extracted.has_value())) { + return; + } + BOOST_TEST_EQ(to_hex(*extracted), to_hex(initial_secret)); + + for (auto const& [label, expected] : { + std::pair{client_in, &client_keys}, + std::pair{server_in, &server_keys}, + }) { + auto const secret = expand_label<32>(initial_secret, label); + BOOST_TEST_EQ(to_hex(secret), to_hex(expected->secret)); + auto const keys = derive_packet_keys(secret); + BOOST_TEST_EQ(to_hex(keys.key), to_hex(expected->key)); + BOOST_TEST_EQ(to_hex(keys.iv), to_hex(expected->iv)); + BOOST_TEST_EQ(to_hex(keys.hp), to_hex(expected->hp)); + } +} + +/** A.1's keys of one direction, as `protect` and `unprotect` take them. */ +inline packet_keys keys_of(initial_keys const& keys) { + return {.key = keys.key, .iv = keys.iv, .hp = keys.hp}; +} + +/** A.2: the client's Initial, its sample and mask, protected and unprotected. */ +template +void check_client_initial() { + auto const keys = keys_of(client_keys); + BOOST_TEST_EQ(to_hex(header_protection_mask(keys.hp, client_sample)), + to_hex(client_mask)); + auto const header = from_hex(client_header); + auto const payload = client_payload(); + auto const packet = protect(keys, header, client_packet_number, payload); + BOOST_TEST_EQ(to_hex(packet), std::string(client_packet)); + + auto const expected_packet = from_hex(client_packet); + auto const opened = unprotect(keys, expected_packet); + BOOST_TEST(opened.opened.has_value()); + BOOST_TEST_EQ(opened.packet_number, client_packet_number); + BOOST_TEST_EQ(to_hex(opened.header), std::string(client_header)); + BOOST_TEST_EQ(to_hex(opened.payload), to_hex(payload)); +} + +/** A.3: the server's Initial, its sample and mask, protected and unprotected. */ +template +void check_server_initial() { + auto const keys = keys_of(server_keys); + BOOST_TEST_EQ(to_hex(header_protection_mask(keys.hp, server_sample)), + to_hex(server_mask)); + auto const header = from_hex(server_header); + auto const payload = from_hex(server_payload); + auto const packet = protect(keys, header, server_packet_number, payload); + BOOST_TEST_EQ(to_hex(packet), std::string(server_packet)); + + auto const expected_packet = from_hex(server_packet); + auto const opened = unprotect(keys, expected_packet); + BOOST_TEST(opened.opened.has_value()); + BOOST_TEST_EQ(opened.packet_number, server_packet_number); + BOOST_TEST_EQ(to_hex(opened.header), std::string(server_header)); + BOOST_TEST_EQ(to_hex(opened.payload), std::string(server_payload)); +} + +/** A.2's packet with one bit of its protected payload flipped: refused, the payload zeroed. */ +template +void check_tampered_initial() { + auto packet = from_hex(client_packet); + packet[100] ^= 0x01U; + auto const opened = unprotect(keys_of(client_keys), packet); + BOOST_TEST(opened.opened.error() == webcpp::crypto::error::authentication_failed); + BOOST_TEST(std::ranges::all_of(opened.payload, [](std::uint8_t b) { return b == 0; })); +} + +/** + * Section 5.8's Retry pseudo-packet: the original Destination Connection ID's length and bytes, + * then the Retry packet without its integrity tag. + */ +inline std::vector retry_pseudo_packet( + std::span original_destination_connection_id) { + auto const retry = from_hex(retry_packet); + std::vector pseudo_packet{ + static_cast(original_destination_connection_id.size()), + }; + pseudo_packet.insert(pseudo_packet.end(), original_destination_connection_id.begin(), + original_destination_connection_id.end()); + pseudo_packet.insert(pseudo_packet.end(), retry.begin(), retry.end() - 16); + return pseudo_packet; +} + +/** A.4: the Retry integrity tag sealed, opened, and refused for another connection ID. */ +template +void check_retry() { + auto aead = Aead::from_key(retry_key); + if (!BOOST_TEST(aead.has_value())) { + return; + } + auto const retry = from_hex(retry_packet); + auto const expected_tag = std::span(retry).last(16); + auto const pseudo_packet = retry_pseudo_packet(client_destination_connection_id); + auto const tag = aead->seal(retry_nonce, pseudo_packet, std::span{}); + if (BOOST_TEST(tag.has_value())) { + BOOST_TEST_EQ(to_hex(*tag), to_hex(expected_tag)); + } + BOOST_TEST(aead->open(retry_nonce, pseudo_packet, std::span{}, expected_tag) + .has_value()); + + auto other_connection_id = client_destination_connection_id; + other_connection_id[0] ^= 0x01U; + BOOST_TEST(aead->open(retry_nonce, retry_pseudo_packet(other_connection_id), + std::span{}, expected_tag) + .error() == webcpp::crypto::error::authentication_failed); +} + +/** Every check of A.1 to A.4 on the AEAD `Aead` and the header protection's block `Block`. */ +template +void check_appendix_a() { + check_keys(); + check_client_initial(); + check_server_initial(); + check_tampered_initial(); + check_retry(); +} + +} // namespace webcpp::test::quic_rfc9001 + +#endif // WEBCPP_TEST_CRYPTO_SUPPORT_QUIC_RFC9001_HPP diff --git a/test/support/quic_rfc9001_vectors.hpp b/test/support/quic_rfc9001_vectors.hpp new file mode 100644 index 00000000..a52248c4 --- /dev/null +++ b/test/support/quic_rfc9001_vectors.hpp @@ -0,0 +1,178 @@ +// 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) + +// RFC 9001 (Using TLS to Secure QUIC) Appendix A's sample packet protection, copied from the RFC +// Editor's text (https://www.rfc-editor.org/rfc/rfc9001.txt): section 5.2's initial salt, section +// 5.8's Retry key and nonce, and Appendix A.1 to A.4, each value named by its section. A.5 +// (ChaCha20-Poly1305) is not here: its header protection needs raw ChaCha20, which crypto does not +// expose (the change rfc9001-tests, ruling R7). + +#ifndef WEBCPP_TEST_CRYPTO_SUPPORT_QUIC_RFC9001_VECTORS_HPP +#define WEBCPP_TEST_CRYPTO_SUPPORT_QUIC_RFC9001_VECTORS_HPP + +#include "hex.hpp" + +#include +#include +#include +#include + +namespace webcpp::test::quic_rfc9001 { + +/** Section 5.2: the salt of QUIC version 1's initial secret. */ +inline constexpr auto initial_salt = hex<20>("38762cf7f55934b34d179ae6a4c80cadccbb7f0a"); + +/** Appendix A: the client's chosen Destination Connection ID. */ +inline constexpr auto client_destination_connection_id = hex<8>("8394c8f03e515708"); + +/** A.1: the HkdfLabel of "client in", 32 bytes, an empty context. */ +inline constexpr auto label_client_in = hex<19>("00200f746c73313320636c69656e7420696e00"); +/** A.1: the HkdfLabel of "server in", 32 bytes, an empty context. */ +inline constexpr auto label_server_in = hex<19>("00200f746c7331332073657276657220696e00"); +/** A.1: the HkdfLabel of "quic key", 16 bytes, an empty context. */ +inline constexpr auto label_quic_key = hex<18>("00100e746c7331332071756963206b657900"); +/** A.1: the HkdfLabel of "quic iv", 12 bytes, an empty context. */ +inline constexpr auto label_quic_iv = hex<17>("000c0d746c733133207175696320697600"); +/** A.1: the HkdfLabel of "quic hp", 16 bytes, an empty context. */ +inline constexpr auto label_quic_hp = hex<17>("00100d746c733133207175696320687000"); + +/** A.1: HKDF-Extract(initial_salt, client_destination_connection_id). */ +inline constexpr auto initial_secret = + hex<32>("7db5df06e7a69e432496adedb00851923595221596ae2ae9fb8115c1e9ed0a44"); + +/** The keys of one direction of A.1. */ +struct initial_keys { + /** HKDF-Expand-Label(initial_secret, "client in" or "server in", "", 32). */ + std::array secret; + /** HKDF-Expand-Label(secret, "quic key", "", 16), AES-128-GCM's key. */ + std::array key; + /** HKDF-Expand-Label(secret, "quic iv", "", 12), the nonce's base. */ + std::array iv; + /** HKDF-Expand-Label(secret, "quic hp", "", 16), the header protection's AES-128 key. */ + std::array hp; +}; + +/** A.1: the client's Initial keys. */ +inline constexpr initial_keys client_keys{ + .secret = hex<32>("c00cf151ca5be075ed0ebfb5c80323c42d6b7db67881289af4008f1f6c357aea"), + .key = hex<16>("1f369613dd76d5467730efcbe3b1a22d"), + .iv = hex<12>("fa044b2f42a3fd3b46fb255c"), + .hp = hex<16>("9f50449e04a0e810283a1e9933adedd2"), +}; + +/** A.1: the server's Initial keys. */ +inline constexpr initial_keys server_keys{ + .secret = hex<32>("3c199828fd139efd216c155ad844cc81fb82fa8d7446fa7d78be803acdda951b"), + .key = hex<16>("cf3a5331653c364c88f0f379b6067e37"), + .iv = hex<12>("0ac1493ca1905853b0bba03e"), + .hp = hex<16>("c206b8d9b9f0f37644430b490eeaa314"), +}; + +/** A.2: the client's payload, its CRYPTO frame and PADDING frames, 1,162 bytes. */ +inline constexpr std::size_t client_payload_size = 1162; +/** A.2: the client's packet number. */ +inline constexpr std::uint64_t client_packet_number = 2; +/** A.2: the header protection's sample, the first 16 bytes of the protected payload. */ +inline constexpr auto client_sample = hex<16>("d1b1c98dd7689fb8ec11d242b123dc9b"); +/** A.2: the first 5 bytes of AES-ECB(hp, sample). */ +inline constexpr auto client_mask = hex<5>("437b9aec36"); + +/** A.3: the server's packet number. */ +inline constexpr std::uint64_t server_packet_number = 1; +/** A.3: the header protection's sample, from the third protected byte. */ +inline constexpr auto server_sample = hex<16>("2cd0991cd25b0aac406a5816b6394100"); +/** A.3: the first 5 bytes of AES-ECB(hp, sample). */ +inline constexpr auto server_mask = hex<5>("2ec0d8356a"); + +/** Section 5.8: the Retry integrity tag's AES-128-GCM key. */ +inline constexpr auto retry_key = hex<16>("be0c690b9f66575a1d766b54e368c84e"); +/** Section 5.8: the Retry integrity tag's nonce. */ +inline constexpr auto retry_nonce = hex<12>("461599d35d632bf2239825bb"); + +/** + * A.2: the client's CRYPTO frame, which PADDING frames (zero bytes) follow up to + * `client_payload_size`. + */ +inline constexpr std::string_view client_crypto_frame = + "060040f1010000ed0303ebf8fa56f12939b9584a3896472ec40bb863cfd3e868" + "04fe3a47f06a2b69484c00000413011302010000c000000010000e00000b6578" + "616d706c652e636f6dff01000100000a00080006001d00170018001000070005" + "04616c706e000500050100000000003300260024001d00209370b2c9caa47fba" + "baf4559fedba753de171fa71f50f1ce15d43e994ec74d748002b000302030400" + "0d0010000e0403050306030203080408050806002d00020101001c0002400100" + "3900320408ffffffffffffffff05048000ffff07048000ffff08011001048000" + "75300901100f088394c8f03e51570806048000ffff"; + +/** A.2: the client's unprotected header, packet number 2 on 4 bytes. */ +inline constexpr std::string_view client_header = "c300000001088394c8f03e5157080000449e00000002"; + +/** A.2: the client's protected packet, 1,200 bytes. */ +inline constexpr std::string_view client_packet = + "c000000001088394c8f03e5157080000449e7b9aec34d1b1c98dd7689fb8ec11" + "d242b123dc9bd8bab936b47d92ec356c0bab7df5976d27cd449f63300099f399" + "1c260ec4c60d17b31f8429157bb35a1282a643a8d2262cad67500cadb8e7378c" + "8eb7539ec4d4905fed1bee1fc8aafba17c750e2c7ace01e6005f80fcb7df6212" + "30c83711b39343fa028cea7f7fb5ff89eac2308249a02252155e2347b63d58c5" + "457afd84d05dfffdb20392844ae812154682e9cf012f9021a6f0be17ddd0c208" + "4dce25ff9b06cde535d0f920a2db1bf362c23e596d11a4f5a6cf3948838a3aec" + "4e15daf8500a6ef69ec4e3feb6b1d98e610ac8b7ec3faf6ad760b7bad1db4ba3" + "485e8a94dc250ae3fdb41ed15fb6a8e5eba0fc3dd60bc8e30c5c4287e53805db" + "059ae0648db2f64264ed5e39be2e20d82df566da8dd5998ccabdae053060ae6c" + "7b4378e846d29f37ed7b4ea9ec5d82e7961b7f25a9323851f681d582363aa5f8" + "9937f5a67258bf63ad6f1a0b1d96dbd4faddfcefc5266ba6611722395c906556" + "be52afe3f565636ad1b17d508b73d8743eeb524be22b3dcbc2c7468d54119c74" + "68449a13d8e3b95811a198f3491de3e7fe942b330407abf82a4ed7c1b311663a" + "c69890f4157015853d91e923037c227a33cdd5ec281ca3f79c44546b9d90ca00" + "f064c99e3dd97911d39fe9c5d0b23a229a234cb36186c4819e8b9c5927726632" + "291d6a418211cc2962e20fe47feb3edf330f2c603a9d48c0fcb5699dbfe58964" + "25c5bac4aee82e57a85aaf4e2513e4f05796b07ba2ee47d80506f8d2c25e50fd" + "14de71e6c418559302f939b0e1abd576f279c4b2e0feb85c1f28ff18f58891ff" + "ef132eef2fa09346aee33c28eb130ff28f5b766953334113211996d20011a198" + "e3fc433f9f2541010ae17c1bf202580f6047472fb36857fe843b19f5984009dd" + "c324044e847a4f4a0ab34f719595de37252d6235365e9b84392b061085349d73" + "203a4a13e96f5432ec0fd4a1ee65accdd5e3904df54c1da510b0ff20dcc0c77f" + "cb2c0e0eb605cb0504db87632cf3d8b4dae6e705769d1de354270123cb11450e" + "fc60ac47683d7b8d0f811365565fd98c4c8eb936bcab8d069fc33bd801b03ade" + "a2e1fbc5aa463d08ca19896d2bf59a071b851e6c239052172f296bfb5e724047" + "90a2181014f3b94a4e97d117b438130368cc39dbb2d198065ae3986547926cd2" + "162f40a29f0c3c8745c0f50fba3852e566d44575c29d39a03f0cda721984b6f4" + "40591f355e12d439ff150aab7613499dbd49adabc8676eef023b15b65bfc5ca0" + "6948109f23f350db82123535eb8a7433bdabcb909271a6ecbcb58b936a88cd4e" + "8f2e6ff5800175f113253d8fa9ca8885c2f552e657dc603f252e1a8e308f76f0" + "be79e2fb8f5d5fbbe2e30ecadd220723c8c0aea8078cdfcb3868263ff8f09400" + "54da48781893a7e49ad5aff4af300cd804a6b6279ab3ff3afb64491c85194aab" + "760d58a606654f9f4400e8b38591356fbf6425aca26dc85244259ff2b19c41b9" + "f96f3ca9ec1dde434da7d2d392b905ddf3d1f9af93d1af5950bd493f5aa731b4" + "056df31bd267b6b90a079831aaf579be0a39013137aac6d404f518cfd4684064" + "7e78bfe706ca4cf5e9c5453e9f7cfd2b8b4c8d169a44e55c88d4a9a7f9474241" + "e221af44860018ab0856972e194cd934"; + +/** A.3: the server's payload, an ACK frame and a CRYPTO frame. */ +inline constexpr std::string_view server_payload = + "02000000000600405a020000560303eefce7f7b37ba1d1632e96677825ddf739" + "88cfc79825df566dc5430b9a045a1200130100002e00330024001d00209d3c94" + "0d89690b84d08a60993c144eca684d1081287c834d5311bcf32bb9da1a002b00" + "020304"; + +/** A.3: the server's unprotected header, packet number 1 on 2 bytes. */ +inline constexpr std::string_view server_header = "c1000000010008f067a5502a4262b50040750001"; + +/** A.3: the server's protected packet. */ +inline constexpr std::string_view server_packet = + "cf000000010008f067a5502a4262b5004075c0d95a482cd0991cd25b0aac406a" + "5816b6394100f37a1c69797554780bb38cc5a99f5ede4cf73c3ec2493a1839b3" + "dbcba3f6ea46c5b7684df3548e7ddeb9c3bf9c73cc3f3bded74b562bfb19fb84" + "022f8ef4cdd93795d77d06edbb7aaf2f58891850abbdca3d20398c276456cbc4" + "2158407dd074ee"; + +/** A.4: the Retry packet, its integrity tag the last 16 bytes. */ +inline constexpr std::string_view retry_packet = + "ff000000010008f067a5502a4262b5746f6b656e04a265ba2eff4d829058fb3f" + "0f2496ba"; + +} // namespace webcpp::test::quic_rfc9001 + +#endif // WEBCPP_TEST_CRYPTO_SUPPORT_QUIC_RFC9001_VECTORS_HPP From 0fb1dc62448fd95fc8e0395560ca999994dcb2aa Mon Sep 17 00:00:00 2001 From: R Date: Fri, 4 Dec 2026 04:42:59 -0300 Subject: [PATCH 2/7] crypto: HPKE (RFC 9180) in public_key_encryption::hpke, composed from X25519 or P-256, webcpp::hash's HKDF over pieces and AES-GCM or ChaCha20-Poly1305 The change hpke of webcpporg/proposals (libraries/crypto/openspec/changes/hpke, rulings R1 to R24): RFC 9180's Hybrid Public Key Encryption with no backend of its own. - hpke::suite over key_encapsulation::x25519_hkdf_sha256 and p256_hkdf_sha256, key_derivation::hkdf_sha256 and hkdf_sha512, cipher::aes128_gcm, aes256_gcm, chacha20_poly1305 and export_only, each checked by its concept; Backend default_backends, one backend, or backends. - The mode follows from the arguments: begin_sending and begin_receiving in base, psk, auth and auth_psk mode, the single-shot seal and open, and a catch-all per name whose one message lists the four argument lists; derive_from_seed (RFC 9180's DeriveKeyPair, X25519's secret kept unclamped); sender_context and recipient_context, move-only and wiped, sealing and opening in order on an internal 64-bit sequence number, exporting with export_secret and export_secret(purpose, output); the free forms in hpke and the asynchronous forms in async.hpp, refused on the browser's backend. - The labeled HKDF passes "HPKE-v1", the suite identifier, the label and the input as pieces to webcpp::hash's HKDF: no input is copied, capped or allocated. A pre-shared key under 32 bytes, an empty id and a seed under 32 bytes are refused. - error::message_limit_reached, the value 21. Tests: every CFRG vector of these suites (64 entries, four modes, 12,336 encryptions in order, the exports) on the defaults and with BearSSL's AEADs, on every target; the four modes, refusals, minimums, the sequence's limit through the seam, and Marmot's recovery-key vectors; OpenSSL's OSSL_HPKE_* in both directions within its limits, with the same encapsulated key and ciphertexts for the same ephemeral seed; no allocation, and long inputs (1 MiB info, 64 KiB associated data, id and purpose) against webcpp::hash's HKDF on the joined labeled inputs; the asynchronous forms; twelve message tests and their MSVC twins; the timing coverage on libsodium and BearSSL; two constant-time paths and dudect's key schedule with its A/A control. The guide's HPKE section with the table of RFC 9180's names, the example hpke_base, crypto.json's rows and the generated files, the changelog. --- README.md | 6 +- doc/async.adoc | 8 + doc/changelog.adoc | 6 +- doc/errors.adoc | 2 + doc/generated/backends-hpke.adoc | 25 + doc/generated/constant-time.adoc | 4 +- doc/generated/matrix.adoc | 16 + doc/generated/messages.adoc | 120 ++ .../namespace-public_key_encryption.adoc | 11 +- doc/generated/use-cases.adoc | 8 + doc/llms.txt | 13 + doc/overview.adoc | 4 +- doc/public_key_encryption.adoc | 262 +++- doc/secret_key_encryption.adoc | 2 +- doc/tables/crypto.json | 37 +- example/Jamfile | 5 + example/hpke_base.cpp | 120 ++ example/hpke_base.expected | 4 + include/webcpp/crypto.hpp | 6 +- include/webcpp/crypto/async.hpp | 395 +++++ include/webcpp/crypto/error.hpp | 7 + .../crypto/public_key_encryption/hpke.hpp | 1324 +++++++++++++++++ .../public_key_encryption/hpke/context.hpp | 1039 +++++++++++++ .../hpke/key_derivation.hpp | 176 +++ .../hpke/key_encapsulation.hpp | 572 +++++++ test/Jamfile | 44 +- test/constant_time/dudect_test.cpp | 63 +- test/constant_time/paths.hpp | 108 +- test/error_test.cpp | 7 +- test/hpke_allocation_test.cpp | 318 ++++ test/hpke_async_test.cpp | 312 ++++ test/hpke_openssl_test.cpp | 329 ++++ test/hpke_test.cpp | 646 ++++++++ test/hpke_vectors_bearssl_test.cpp | 47 + test/hpke_vectors_default_test.cpp | 33 + test/messages/Jamfile | 12 + .../hpke_async_asynchronous_backend/Jamfile | 14 + .../hpke_async_asynchronous_backend.cpp | 57 + .../hpke_ciphers_type_as_cipher/Jamfile | 14 + .../hpke_ciphers_type_as_cipher.cpp | 25 + test/messages/hpke_context_copied/Jamfile | 14 + .../hpke_context_copied.cpp | 38 + .../hpke_context_seal_export_only/Jamfile | 14 + .../hpke_context_seal_export_only.cpp | 40 + test/messages/hpke_export_length/Jamfile | 14 + .../hpke_export_length/hpke_export_length.cpp | 41 + test/messages/hpke_open_on_sender/Jamfile | 14 + .../hpke_open_on_sender.cpp | 36 + .../hpke_p256_key_x25519_suite/Jamfile | 14 + .../hpke_p256_key_x25519_suite.cpp | 42 + test/messages/hpke_psk_after_sender/Jamfile | 14 + .../hpke_psk_after_sender.cpp | 42 + .../hpke_receiving_sender_keypair/Jamfile | 14 + .../hpke_receiving_sender_keypair.cpp | 43 + test/messages/hpke_seal_export_only/Jamfile | 14 + .../hpke_seal_export_only.cpp | 43 + .../hpke_sending_sender_public_key/Jamfile | 14 + .../hpke_sending_sender_public_key.cpp | 42 + .../hpke_span_as_pre_shared_key/Jamfile | 14 + .../hpke_span_as_pre_shared_key.cpp | 43 + test/msvc/Jamfile | 12 + .../hpke_async_asynchronous_backend/Jamfile | 10 + .../hpke_async_asynchronous_backend/app.cpp | 53 + test/msvc/hpke_ciphers_type_as_cipher/Jamfile | 10 + test/msvc/hpke_ciphers_type_as_cipher/app.cpp | 25 + test/msvc/hpke_context_copied/Jamfile | 10 + test/msvc/hpke_context_copied/app.cpp | 34 + .../hpke_context_seal_export_only/Jamfile | 10 + .../hpke_context_seal_export_only/app.cpp | 37 + test/msvc/hpke_export_length/Jamfile | 10 + test/msvc/hpke_export_length/app.cpp | 37 + test/msvc/hpke_open_on_sender/Jamfile | 10 + test/msvc/hpke_open_on_sender/app.cpp | 36 + test/msvc/hpke_p256_key_x25519_suite/Jamfile | 10 + test/msvc/hpke_p256_key_x25519_suite/app.cpp | 39 + test/msvc/hpke_psk_after_sender/Jamfile | 10 + test/msvc/hpke_psk_after_sender/app.cpp | 38 + .../hpke_receiving_sender_keypair/Jamfile | 10 + .../hpke_receiving_sender_keypair/app.cpp | 39 + test/msvc/hpke_seal_export_only/Jamfile | 10 + test/msvc/hpke_seal_export_only/app.cpp | 39 + .../hpke_sending_sender_public_key/Jamfile | 10 + .../hpke_sending_sender_public_key/app.cpp | 38 + test/msvc/hpke_span_as_pre_shared_key/Jamfile | 10 + test/msvc/hpke_span_as_pre_shared_key/app.cpp | 40 + test/support/hpke_coverage.hpp | 489 ++++++ test/support/hpke_vectors.hpp | 378 +++++ test/timing_coverage_bearssl_test.cpp | 10 + test/timing_coverage_sodium_test.cpp | 10 + test/user_globals_test.cpp | 4 + test/windows_h_after_test.cpp | 1 + test/windows_h_before_test.cpp | 1 + 92 files changed, 8200 insertions(+), 31 deletions(-) create mode 100644 doc/generated/backends-hpke.adoc create mode 100644 example/hpke_base.cpp create mode 100644 example/hpke_base.expected create mode 100644 include/webcpp/crypto/public_key_encryption/hpke.hpp create mode 100644 include/webcpp/crypto/public_key_encryption/hpke/context.hpp create mode 100644 include/webcpp/crypto/public_key_encryption/hpke/key_derivation.hpp create mode 100644 include/webcpp/crypto/public_key_encryption/hpke/key_encapsulation.hpp create mode 100644 test/hpke_allocation_test.cpp create mode 100644 test/hpke_async_test.cpp create mode 100644 test/hpke_openssl_test.cpp create mode 100644 test/hpke_test.cpp create mode 100644 test/hpke_vectors_bearssl_test.cpp create mode 100644 test/hpke_vectors_default_test.cpp create mode 100644 test/messages/hpke_async_asynchronous_backend/Jamfile create mode 100644 test/messages/hpke_async_asynchronous_backend/hpke_async_asynchronous_backend.cpp create mode 100644 test/messages/hpke_ciphers_type_as_cipher/Jamfile create mode 100644 test/messages/hpke_ciphers_type_as_cipher/hpke_ciphers_type_as_cipher.cpp create mode 100644 test/messages/hpke_context_copied/Jamfile create mode 100644 test/messages/hpke_context_copied/hpke_context_copied.cpp create mode 100644 test/messages/hpke_context_seal_export_only/Jamfile create mode 100644 test/messages/hpke_context_seal_export_only/hpke_context_seal_export_only.cpp create mode 100644 test/messages/hpke_export_length/Jamfile create mode 100644 test/messages/hpke_export_length/hpke_export_length.cpp create mode 100644 test/messages/hpke_open_on_sender/Jamfile create mode 100644 test/messages/hpke_open_on_sender/hpke_open_on_sender.cpp create mode 100644 test/messages/hpke_p256_key_x25519_suite/Jamfile create mode 100644 test/messages/hpke_p256_key_x25519_suite/hpke_p256_key_x25519_suite.cpp create mode 100644 test/messages/hpke_psk_after_sender/Jamfile create mode 100644 test/messages/hpke_psk_after_sender/hpke_psk_after_sender.cpp create mode 100644 test/messages/hpke_receiving_sender_keypair/Jamfile create mode 100644 test/messages/hpke_receiving_sender_keypair/hpke_receiving_sender_keypair.cpp create mode 100644 test/messages/hpke_seal_export_only/Jamfile create mode 100644 test/messages/hpke_seal_export_only/hpke_seal_export_only.cpp create mode 100644 test/messages/hpke_sending_sender_public_key/Jamfile create mode 100644 test/messages/hpke_sending_sender_public_key/hpke_sending_sender_public_key.cpp create mode 100644 test/messages/hpke_span_as_pre_shared_key/Jamfile create mode 100644 test/messages/hpke_span_as_pre_shared_key/hpke_span_as_pre_shared_key.cpp create mode 100644 test/msvc/hpke_async_asynchronous_backend/Jamfile create mode 100644 test/msvc/hpke_async_asynchronous_backend/app.cpp create mode 100644 test/msvc/hpke_ciphers_type_as_cipher/Jamfile create mode 100644 test/msvc/hpke_ciphers_type_as_cipher/app.cpp create mode 100644 test/msvc/hpke_context_copied/Jamfile create mode 100644 test/msvc/hpke_context_copied/app.cpp create mode 100644 test/msvc/hpke_context_seal_export_only/Jamfile create mode 100644 test/msvc/hpke_context_seal_export_only/app.cpp create mode 100644 test/msvc/hpke_export_length/Jamfile create mode 100644 test/msvc/hpke_export_length/app.cpp create mode 100644 test/msvc/hpke_open_on_sender/Jamfile create mode 100644 test/msvc/hpke_open_on_sender/app.cpp create mode 100644 test/msvc/hpke_p256_key_x25519_suite/Jamfile create mode 100644 test/msvc/hpke_p256_key_x25519_suite/app.cpp create mode 100644 test/msvc/hpke_psk_after_sender/Jamfile create mode 100644 test/msvc/hpke_psk_after_sender/app.cpp create mode 100644 test/msvc/hpke_receiving_sender_keypair/Jamfile create mode 100644 test/msvc/hpke_receiving_sender_keypair/app.cpp create mode 100644 test/msvc/hpke_seal_export_only/Jamfile create mode 100644 test/msvc/hpke_seal_export_only/app.cpp create mode 100644 test/msvc/hpke_sending_sender_public_key/Jamfile create mode 100644 test/msvc/hpke_sending_sender_public_key/app.cpp create mode 100644 test/msvc/hpke_span_as_pre_shared_key/Jamfile create mode 100644 test/msvc/hpke_span_as_pre_shared_key/app.cpp create mode 100644 test/support/hpke_coverage.hpp create mode 100644 test/support/hpke_vectors.hpp diff --git a/README.md b/README.md index 72c5b38e..0209cf40 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 d0dcd425..102e6f26 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/changelog.adoc b/doc/changelog.adoc index e4a20b9d..9abcdfd7 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 02848417..4d891751 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-hpke.adoc b/doc/generated/backends-hpke.adoc new file mode 100644 index 00000000..21917e22 --- /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 0fd9a274..4a542825 100644 --- a/doc/generated/constant-time.adoc +++ b/doc/generated/constant-time.adoc @@ -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 (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) |not measured yet |not measured yet |=== diff --git a/doc/generated/matrix.adoc b/doc/generated/matrix.adoc index 84570baf..c463a7d4 100644 --- a/doc/generated/matrix.adoc +++ b/doc/generated/matrix.adoc @@ -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 8f7353d9..c01d0515 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 X25519 keys, `+p256_hkdf_sha256+`'s 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 X25519 keys, `+p256_hkdf_sha256+`'s 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-public_key_encryption.adoc b/doc/generated/namespace-public_key_encryption.adoc index 6f6b4a0e..47adfdfe 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 df9c0f6a..80e1bd32 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 856359df..94e43538 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(encapsulated_key, recipient_keypair, 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(completion_executor, ..., completion_token)`. + - 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(completion_executor, ..., completion_token)`. + - 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(completion_executor, ..., completion_token)`. + - 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(completion_executor, ..., completion_token)`. + - 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 @@ -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 7e8b78b0..e18d3deb 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 fbbdddcc..78ab220f 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 `curves::x25519`'s (<>) or `curves::p256`'s +(<>), HKDF is webcpp::hash's, 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 +C++ 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 eb066676..685202ec 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 9d9ba46f..d5437e37 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -135,7 +135,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": { @@ -232,7 +235,8 @@ "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": "`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"]}} ] } }, @@ -644,6 +648,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", @@ -1226,7 +1241,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": { @@ -1274,6 +1290,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"}, @@ -1574,7 +1591,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 X25519 keys, `p256_hkdf_sha256`'s 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/example/Jamfile b/example/Jamfile index 71cf14be..c2ca3ee0 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 00000000..02a01ac8 --- /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 00000000..f284d1c0 --- /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 7b5b7bb9..da73d39f 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 72b3f79e..9b241054 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 4e5381b9..b42d4e22 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 00000000..9bc0d59f --- /dev/null +++ b/include/webcpp/crypto/public_key_encryption/hpke.hpp @@ -0,0 +1,1324 @@ +// 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", 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. + * @param arguments The arguments. + * @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(completion_executor, ..., completion_token)`. + * + * 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. + * @param arguments The arguments. + * @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(completion_executor, ..., completion_token)`. + * + * 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. + * @param arguments The arguments. + * @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(completion_executor, ..., completion_token)`. + * + * 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(encapsulated_key, + * recipient_keypair, 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. + * @param arguments The arguments. + * @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(completion_executor, ..., completion_token)`. + * + * 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 00000000..d05b7811 --- /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", 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, `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, `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 00000000..21229c74 --- /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", 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 00000000..16a7bf82 --- /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", 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 94237ae5..ec47c8fd 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. diff --git a/test/constant_time/dudect_test.cpp b/test/constant_time/dudect_test.cpp index aa3298a3..1bcca3ff 100644 --- a/test/constant_time/dudect_test.cpp +++ b/test/constant_time/dudect_test.cpp @@ -16,7 +16,13 @@ // hash's design D4) is measured against its text: two fixed texts of one length, two compressed // WIF keys of Bitcoin Core's key_io_valid.json, decoded into a codecs::secret_bytes, codecs' // constant-time conversion, with its A/A control (base58_decode_aa); on wasip2 the decode is -// printed and not judged, an open finding. `--case ` measures one case alone. +// printed and not judged, an open finding. HPKE's key schedule (case hpke_key_schedule, design +// B6), the composition HPKE adds to its curves and AEADs, which their own cases measure: RFC +// 9180's KeySchedule of a P-256, HKDF-SHA256 and AES-128-GCM suite on BearSSL in auth_psk mode, +// its labeled HKDF over pieces (webcpp::hash's) and the AEAD keyed from it, against the shared +// secret (all zero, against random ones), the pre-shared key and the info fixed; with its A/A +// control (hpke_key_schedule_aa), both classes the all-zero secret. `--case ` measures one +// case alone. #include "dudect.hpp" @@ -26,6 +32,7 @@ #include #include #include +#include #include #include #include @@ -178,6 +185,56 @@ bool measure_p256(test::case_results& results, test::case_selection const& selec return true; } +/** + * Times HPKE's key schedule against its shared secret (case hpke_key_schedule): all zero, against + * random ones, the info, the pre-shared key and its id fixed; and its A/A control + * (hpke_key_schedule_aa), both classes the all-zero secret, prepared by the same instructions. The + * schedule computes two labeled extracts of public inputs, the secret's extract under the shared + * secret, three labeled expands under it, and keys the AEAD. + * @param results Where each case measured is recorded. + * @param selection The cases to measure. + */ +void measure_hpke(test::case_results& results, test::case_selection const& selection) { + namespace hpke = webcpp::crypto::public_key_encryption::hpke; + using suite = + hpke::suite; + // A schedule takes about 20 microseconds natively: a tenth of the AEADs' measurements. + constexpr std::size_t hpke_count = count / 10; + std::array const zero{}; + std::array shared_secret{}; + std::array psk_key{}; + psk_key.fill(0x55); + std::array const psk_id{'p', 's', 'k', '1'}; + std::array const info{'i', 'n', 'f', 'o'}; + auto const schedule = [&] { + auto values = webcpp::crypto::detail::hpke_key_schedule(0x03, shared_secret, info, + psk_key, psk_id); + auto const core = webcpp::crypto::detail::hpke_context_core::from_schedule(*values); + static_cast(core); + }; + if (selection.runs("hpke_key_schedule")) { + auto const schedule_t = test::twice( + hpke_count, + [&](int which, auto& generator) { + test::choose(which, generator, zero, shared_secret); + }, + schedule); + results.record("hpke_key_schedule", "HPKE key schedule", schedule_t, true, + {{"shared_secret", shared_secret.data()}, {"psk", psk_key.data()}}); + } + if (selection.runs("hpke_key_schedule_aa")) { + auto const control_t = test::twice( + hpke_count, + [&](int which, auto& generator) { + test::choose(which, generator, zero, shared_secret); + }, + schedule); + results.record("hpke_key_schedule_aa", "HPKE key schedule A/A", control_t, true, + {{"shared_secret", shared_secret.data()}, {"psk", psk_key.data()}}); + } +} + /** * Times hash's Base58Check's secret decode of a WIF key's text into a codecs::secret_bytes (case * base58_decode), the two classes two fixed texts of one length, both valid: two compressed WIF @@ -271,6 +328,8 @@ int main(int argc, char** argv) { "p256_ecdh_x", "base58_decode", "base58_decode_aa", + "hpke_key_schedule", + "hpke_key_schedule_aa", }); if (!selection) { return 2; @@ -326,6 +385,8 @@ int main(int argc, char** argv) { return 1; } + measure_hpke(results, *selection); + results.print(); return test::verdict(results.passes()); } diff --git a/test/constant_time/paths.hpp b/test/constant_time/paths.hpp index 44b7b122..c140bf32 100644 --- a/test/constant_time/paths.hpp +++ b/test/constant_time/paths.hpp @@ -51,6 +51,7 @@ #include #include #include +#include #include #include #include @@ -1107,6 +1108,110 @@ int base58_with_checksum_path() { traced_and_equal(decoded->view(), plain_payload, "Base58Check's secret decode"); } +/** + * HPKE (RFC 9180) on one suite (design B6), in base and auth_psk mode: the recipient's and the + * sender's key pairs made from secret bytes, their public keys marked public (they are + * published); the pre-shared key, the plaintext and the ephemeral seed secret (the sender is set up + * through the test seam, so that the ephemeral key pair is derived from a secret seed rather than + * drawn from the system's generator, which the checker does not mark). The ciphertext and the + * export are traced; the encapsulated key, which travels in clear, is marked public before the + * recipient reads it; the setups' verdicts and the open's must be public: the library marks the + * one verdict HPKE adds, P-256's candidate scalar's, and the curves and the AEAD theirs. + * + * @tparam Suite The suite: X25519 with ChaCha20-Poly1305 on libsodium, or P-256 with AES-128-GCM + * on BearSSL. + */ +template +int hpke_path(char const* what) { + namespace hpke = crypto::public_key_encryption::hpke; + using access = crypto::detail::hpke_access; + std::array recipient_secret{}; + std::array sender_secret{}; + std::array psk_key{}; + std::array ephemeral_seed{}; + std::array plaintext{}; + recipient_secret.fill(0x42); + sender_secret.fill(0x24); + psk_key.fill(0x55); + ephemeral_seed.fill(0x66); + plaintext.fill(0x17); + Checker::mark_secret(recipient_secret); + Checker::mark_secret(sender_secret); + Checker::mark_secret(psk_key); + Checker::mark_secret(ephemeral_seed); + Checker::mark_secret(plaintext); + std::array const psk_id{'p', 's', 'k', '1'}; + std::array const info{'i', 'n', 'f', 'o'}; + hpke::pre_shared_key const pre_shared_key{.key = psk_key, .id = psk_id}; + auto const recipient = Suite::recipient_keypair_type::from_secret(recipient_secret); + auto const sender = Suite::sender_keypair_type::from_secret(sender_secret); + // Not const: the mark changes the object in the checker's shadow, so it is read again. + bool made = recipient.has_value() && sender.has_value(); // NOLINT(misc-const-correctness) + Checker::verdict(made); + if (!made) { + return check(false, what); + } + // The public keys are published. + auto recipient_public_key = recipient->public_key(); + auto sender_public_key = sender->public_key(); + if (!recipient_public_key || !sender_public_key) { + return check(false, what); + } + Checker::mark_public(bytes_of(*recipient_public_key)); + Checker::mark_public(bytes_of(*sender_public_key)); + int failures = 0; + for (bool const authenticated : {false, true}) { + auto sending = access::begin_sending_with_ephemeral_seed( + ephemeral_seed, *recipient_public_key, info, authenticated ? &pre_shared_key : nullptr, + authenticated ? &*sender : nullptr); + // Not const: the mark changes the object in the checker's shadow, so it is read again. + bool sent = sending.has_value(); // NOLINT(misc-const-correctness) + Checker::verdict(sent); + if (!sent) { + return failures + check(false, what); + } + std::array ciphertext{}; + bool const sealed = sending->seal(info, plaintext, ciphertext).has_value(); + auto const exported = sending->template export_secret<32>(info); + failures += check(sealed && carries_mark(ciphertext) && exported.has_value() && + carries_mark(exported->bytes()), + what); + // The encapsulated key travels in clear. + auto const encapsulated_key = sending->encapsulated_key(); + Checker::mark_public(bytes_of(encapsulated_key)); + auto receiving = authenticated ? Suite::begin_receiving(encapsulated_key, *recipient, info, + pre_shared_key, *sender_public_key) + : Suite::begin_receiving(encapsulated_key, *recipient, info); + // Not const: the mark changes the object in the checker's shadow, so it is read again. + bool received = receiving.has_value(); // NOLINT(misc-const-correctness) + Checker::verdict(received); + if (!received) { + return failures + check(false, what); + } + std::array opened{}; + // Not const: the mark changes the object in the checker's shadow, so it is read again. + bool opened_verdict = // NOLINT(misc-const-correctness) + receiving->open(info, ciphertext, opened).has_value(); + Checker::verdict(opened_verdict); + failures += check(opened_verdict && carries_mark(opened), what); + } + return failures; +} + +/** HPKE's two paths, one per key encapsulation (design B6). */ +template +int hpke_paths() { + namespace hpke = crypto::public_key_encryption::hpke; + return hpke_path>( + "HPKE, X25519 and ChaCha20-Poly1305 on libsodium") + + hpke_path>( + "HPKE, P-256 and AES-128-GCM on BearSSL"); +} + /** Every path above, on the checker: the number of failed checks. */ template int common_paths() { @@ -1136,7 +1241,8 @@ int common_paths() { crypto::families::box_xchacha20poly1305, sodium>>( "box_xchacha20poly1305 on libsodium") + sodium_sealed_box() + sodium_kx() + secp256k1_paths() + - bearssl_p256_paths() + base58_with_checksum_path(); + bearssl_p256_paths() + base58_with_checksum_path() + + hpke_paths(); } } // namespace webcpp::test::constant_time diff --git a/test/error_test.cpp b/test/error_test.cpp index 6c12c710..e7ca0189 100644 --- a/test/error_test.cpp +++ b/test/error_test.cpp @@ -43,6 +43,7 @@ int main() { BOOST_TEST_EQ(static_cast(error::invalid_padding), 18); BOOST_TEST_EQ(static_cast(error::invalid_encoding), 19); BOOST_TEST_EQ(static_cast(error::invalid_ciphertext_size), 20); + BOOST_TEST_EQ(static_cast(error::message_limit_reached), 21); boost::system::error_code const code = error::authentication_failed; BOOST_TEST_EQ(std::string_view(code.category().name()), "webcpp.crypto"); @@ -89,16 +90,18 @@ int main() { "the encoding does not decode"); BOOST_TEST_EQ(crypto::make_error_code(error::invalid_ciphertext_size).message(), "the ciphertext is not of the key's size"); + BOOST_TEST_EQ(crypto::make_error_code(error::message_limit_reached).message(), + "the context has sealed or opened as many messages as its nonce allows"); // Every defined value has its own message, never the unknown one. std::set messages; - for (int value = 1; value <= 20; ++value) { + for (int value = 1; value <= 21; ++value) { std::string const text = crypto::error_category().message(value); BOOST_TEST(!text.empty()); BOOST_TEST_NE(text, "unknown webcpp.crypto error"); messages.insert(text); } - BOOST_TEST_EQ(messages.size(), 20u); + BOOST_TEST_EQ(messages.size(), 21u); // The guards of the buffer form: a null buffer or a size of 0 writes nothing, a size of 1 // writes the terminating zero alone, and a message longer than the buffer is cut with one. diff --git a/test/hpke_allocation_test.cpp b/test/hpke_allocation_test.cpp new file mode 100644 index 00000000..8f99a990 --- /dev/null +++ b/test/hpke_allocation_test.cpp @@ -0,0 +1,318 @@ +// 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 allocates nothing (design D10) and caps no input (owner decision 6, design D4), on the +// backends that allocate nothing: X25519 on libsodium with each AEAD on BearSSL +// (hpke::backends) and ChaCha20-Poly1305 on libsodium, and P-256 wholly on +// BearSSL. OpenSSL's AES-GCM, natively AES-GCM's default, allocates its own context on the C heap, +// as its page says, and is left out. +// - For every suite of the 32 (two key encapsulations by two key derivations by four ciphers): +// derive_from_seed, both setups in base and auth_psk mode, a seal, an open, a refused open and +// both exports make no call of operator new, nor of the C library's allocator where the target +// lets a program count it; a control proves the counter moves. +// - Long inputs: an application_info of 4 KiB, 64 KiB and 1 MiB, an associated data, a +// pre-shared key id and an export purpose of 64 KiB round-trip with no allocation, and the key +// schedule's values and the exported secret equal a second computation that joins each labeled +// input on the heap and calls webcpp::hash's single-buffer hkdf_extract and hkdf_expand (its +// pieces form on the one joined piece, for an expand info beyond the single-buffer form's cap), +// which pins the labels and their order. + +#include +#include +#include +#include +#include +#include + +#include "support/counting.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace crypto = webcpp::crypto; +namespace hpke = crypto::public_key_encryption::hpke; +using access = crypto::detail::hpke_access; + +/** P-256 wholly on BearSSL; X25519 on libsodium beside BearSSL's AEADs. */ +template +using counted_backends = std::conditional_t< + std::is_same_v, + crypto::backends::bearssl, + std::conditional_t, + crypto::backends::sodium, + hpke::backends>>; + +template +using counted_suite = hpke::suite>; + +/** The plaintext's size. */ +constexpr std::size_t plaintext_size = 1000; + +/** The inputs of one round trip, allocated before the counted window. */ +struct inputs { + std::vector info; + std::vector associated_data; + std::vector psk_key = std::vector(32, 0x42); + std::vector psk_id = std::vector(7, 0x49); + std::vector purpose; + std::vector plaintext = std::vector(plaintext_size, 0x50); +}; + +/** Bytes of a length, each its index's low byte. */ +std::vector counting_bytes(std::size_t length) { + std::vector made(length); + for (std::size_t index = 0; index < length; ++index) { + made[index] = static_cast(index); + } + return made; +} + +/** + * Both setups, base or auth_psk, a seal, an open, a refused open and both exports, which the + * caller counts. + */ +template +void round_trip(inputs const& in, bool authenticated, + typename Suite::recipient_keypair_type const& recipient, + typename Suite::sender_keypair_type const& sender_keypair) { + auto const recipient_public_key = recipient.public_key(); + auto const sender_public_key = sender_keypair.public_key(); + if (!BOOST_TEST(recipient_public_key.has_value() && sender_public_key.has_value())) { + return; + } + hpke::pre_shared_key const pre_shared_key{.key = in.psk_key, .id = in.psk_id}; + auto sender = authenticated ? Suite::begin_sending(*recipient_public_key, in.info, + pre_shared_key, sender_keypair) + : Suite::begin_sending(*recipient_public_key, in.info); + if (!BOOST_TEST(sender.has_value())) { + return; + } + auto receiver = authenticated + ? Suite::begin_receiving(sender->encapsulated_key(), recipient, in.info, + pre_shared_key, *sender_public_key) + : Suite::begin_receiving(sender->encapsulated_key(), recipient, in.info); + if (!BOOST_TEST(receiver.has_value())) { + return; + } + if constexpr (hpke::sealing_cipher) { + // On the stack: the window counts every allocation. + std::array ciphertext{}; + std::array opened{}; + BOOST_TEST(sender->seal(in.associated_data, in.plaintext, ciphertext).has_value()); + BOOST_TEST(receiver->open(in.associated_data, ciphertext, opened).has_value()); + BOOST_TEST(std::ranges::equal(opened, in.plaintext)); + BOOST_TEST(receiver->open(in.associated_data, ciphertext, opened).error() == + crypto::error::authentication_failed); + } + auto const sent = sender->template export_secret<64>(in.purpose); + std::array received{}; + BOOST_TEST(receiver->export_secret(in.purpose, received).has_value()); + BOOST_TEST(sent.has_value() && std::ranges::equal(sent->bytes(), received)); + auto const moved = std::move(*receiver); + BOOST_TEST(moved.export_secret(in.purpose, received).has_value()); +} + +/** + * A round trip with no allocation: derived key pairs, both setups in base and auth_psk mode, a + * seal, an open, a refused open and both exports. + */ +template +void expect_no_allocation(inputs const& in) { + std::array const recipient_seed{1}; + std::array const sender_seed{2}; + std::size_t const before = webcpp::test::allocations(); + { + auto const recipient = Suite::derive_from_seed(recipient_seed); + auto const sender_keypair = Suite::derive_from_seed(sender_seed); + if (!BOOST_TEST(recipient.has_value() && sender_keypair.has_value())) { + return; + } + for (bool const authenticated : {false, true}) { + round_trip(in, authenticated, *recipient, *sender_keypair); + } + } + BOOST_TEST_EQ(webcpp::test::allocations(), before); +} + +/** The joined labeled input of RFC 9180's LabeledExtract, on the heap. */ +template +std::vector joined_extract_input(std::string_view label, + std::span input) { + auto const& suite_identifier = crypto::detail::hpke_suite_identifier; + std::vector joined{'H', 'P', 'K', 'E', '-', 'v', '1'}; + joined.insert(joined.end(), suite_identifier.begin(), suite_identifier.end()); + joined.insert(joined.end(), label.begin(), label.end()); + joined.insert(joined.end(), input.begin(), input.end()); + return joined; +} + +/** The joined labeled info of RFC 9180's LabeledExpand, on the heap. */ +template +std::vector joined_expand_info(std::size_t length, std::string_view label, + std::span info) { + std::vector joined{ + static_cast(length >> 8U), + static_cast(length & 0xffU), + }; + auto const rest = joined_extract_input(label, info); + joined.insert(joined.end(), rest.begin(), rest.end()); + return joined; +} + +/** HKDF-Extract on the joined input, by the single-buffer form. */ +template +std::vector joined_extract(std::span salt, std::string_view label, + std::span input) { + using hmac = Suite::key_derivation_type::hmac_type; + auto const joined = joined_extract_input(label, input); + auto const extracted = + webcpp::hash::hkdf_extract(salt, std::span(joined)); + if (!BOOST_TEST(extracted.has_value())) { + return {}; + } + return {extracted->begin(), extracted->end()}; +} + +/** + * HKDF-Expand on the joined info: the single-buffer form within its cap, the pieces form on the + * one joined piece beyond it. + */ +template +std::vector joined_expand(std::span pseudorandom_key, + std::string_view label, std::span info, + std::size_t length) { + using hmac = Suite::key_derivation_type::hmac_type; + auto const joined = joined_expand_info(length, label, info); + std::vector output(length); + if (joined.size() <= webcpp::hash::hkdf_max_application_info_size) { + BOOST_TEST(webcpp::hash::hkdf_expand(output, pseudorandom_key, + std::span(joined)) + .has_value()); + } else { + BOOST_TEST(webcpp::hash::hkdf_expand(output, pseudorandom_key, + webcpp::hash::byte_pieces{joined}) + .has_value()); + } + return output; +} + +/** The key schedule and an export of long inputs, against the joined computation. */ +template +void check_long_inputs(inputs const& in) { + constexpr std::size_t hash_size = Suite::key_derivation_type::hash_size; + std::array const recipient_seed{3}; + std::array const ephemeral_seed{4}; + auto const recipient = Suite::derive_from_seed(recipient_seed); + if (!BOOST_TEST(recipient.has_value())) { + return; + } + hpke::pre_shared_key const pre_shared_key{.key = in.psk_key, .id = in.psk_id}; + auto sender = access::begin_sending_with_ephemeral_seed( + ephemeral_seed, *recipient->public_key(), in.info, &pre_shared_key, nullptr); + if (!BOOST_TEST(sender.has_value())) { + return; + } + auto const shared_secret = crypto::detail::hpke_setup::dhkem::decapsulate( + sender->encapsulated_key(), *recipient, nullptr); + if (!BOOST_TEST(shared_secret.has_value())) { + return; + } + auto const schedule = crypto::detail::hpke_key_schedule(0x01, shared_secret->bytes(), + in.info, in.psk_key, in.psk_id); + if (!BOOST_TEST(schedule.has_value())) { + return; + } + std::vector context{0x01}; + auto const psk_id_hash = joined_extract({}, "psk_id_hash", in.psk_id); + auto const info_hash = joined_extract({}, "info_hash", in.info); + context.insert(context.end(), psk_id_hash.begin(), psk_id_hash.end()); + context.insert(context.end(), info_hash.begin(), info_hash.end()); + BOOST_TEST(std::ranges::equal(schedule->key_schedule_context, context)); + auto const secret = joined_extract(shared_secret->bytes(), "secret", in.psk_key); + BOOST_TEST(std::ranges::equal(schedule->secret.bytes(), secret)); + auto const exporter_secret = joined_expand(secret, "exp", context, hash_size); + BOOST_TEST(std::ranges::equal(schedule->exporter_secret.bytes(), exporter_secret)); + if constexpr (hpke::sealing_cipher) { + BOOST_TEST(std::ranges::equal( + schedule->aead_material.key.bytes(), + joined_expand(secret, "key", context, Suite::cipher_type::key_size))); + BOOST_TEST(std::ranges::equal( + schedule->aead_material.base_nonce, + joined_expand(secret, "base_nonce", context, Suite::cipher_type::nonce_size))); + } + auto const exported = sender->template export_secret<48>(in.purpose); + if (BOOST_TEST(exported.has_value())) { + BOOST_TEST(std::ranges::equal( + exported->bytes(), joined_expand(exporter_secret, "sec", in.purpose, 48))); + } +} + +/** Every check of one suite, with short inputs and with long ones. */ +template +void check_suite(std::vector const& every_input) { + for (inputs const& in : every_input) { + expect_no_allocation(in); + check_long_inputs(in); + } +} + +template +void check_ciphers(std::vector const& every_input) { + check_suite>( + every_input); + check_suite>( + every_input); + check_suite>( + every_input); + check_suite>( + every_input); +} + +} // namespace + +int main() { + namespace kem = hpke::key_encapsulation; + namespace kdf = hpke::key_derivation; + // The control: the counter moves. + std::size_t const before = webcpp::test::allocations(); + { + std::vector const counted(1); + BOOST_TEST_EQ(counted.size(), 1U); + } + BOOST_TEST_GT(webcpp::test::allocations(), before); + + constexpr std::size_t kibibyte = 1024; + std::vector every_input; + every_input.push_back({ + .info = counting_bytes(20), + .associated_data = counting_bytes(7), + .purpose = counting_bytes(11), + }); + for (std::size_t const info_size : {4 * kibibyte, 64 * kibibyte, 1024 * kibibyte}) { + every_input.push_back({ + .info = counting_bytes(info_size), + .associated_data = counting_bytes(64 * kibibyte), + .psk_id = counting_bytes(64 * kibibyte), + .purpose = counting_bytes(64 * kibibyte), + }); + } + check_ciphers(every_input); + check_ciphers(every_input); + check_ciphers(every_input); + check_ciphers(every_input); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/hpke_async_test.cpp b/test/hpke_async_test.cpp new file mode 100644 index 00000000..a8bbf3ec --- /dev/null +++ b/test/hpke_async_test.cpp @@ -0,0 +1,312 @@ +// 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 asynchronous forms (design D8) on synchronous backends: X25519 with ChaCha20-Poly1305 on +// libsodium, and P-256 with AES-128-GCM on BearSSL. Each runs the synchronous call when the +// operation is initiated and completes through a post, never inside the call. +// - In a coroutine (the specification's case): hpke::async_begin_sending, then the sender's +// async_seal, then hpke::async_begin_receiving and the recipient's async_open, member and free; +// the single-shot async_seal and async_open, member and free, in every mode; and +// async_derive_from_seed, member and free, gives derive_from_seed's key pair. +// - The asynchronous seal on a context set up through the test seam with an ephemeral seed gives +// the ciphertext the synchronous seal gives on a second context with the same seed. +// - never_inline: a callback's flag is unset when the asynchronous call returns and set after the +// context runs, for a setup, a context's seal and a single-shot open. +// - Errors: a short seed completes with invalid_input_size and an empty key pair; a changed +// ciphertext with authentication_failed; a setup with a short pre-shared key with +// invalid_key_size and an empty context, which refuses with invalid_state. + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace asio = webcpp::asio; +namespace crypto = webcpp::crypto; +namespace hpke = crypto::public_key_encryption::hpke; +using access = crypto::detail::hpke_access; + +/** X25519 with ChaCha20-Poly1305, wholly on libsodium. */ +using sodium_suite = + hpke::suite; +/** P-256 with AES-128-GCM, wholly on BearSSL. */ +using bearssl_suite = + hpke::suite; + +/** + * The bytes of a text, at compile time. + * + * @param text A string literal. + * @return Its bytes without the terminating zero. + */ +template +// NOLINTNEXTLINE(modernize-avoid-c-arrays): a string literal's array keeps its length in its type +consteval std::array text_bytes(char const (&text)[N]) { + std::array bytes{}; + for (std::size_t index = 0; index + 1 < N; ++index) { + bytes[index] = static_cast(text[index]); + } + return bytes; +} + +/** 32 bytes of one value, at compile time. */ +consteval std::array filled(std::uint8_t value) { + std::array bytes{}; + bytes.fill(value); + return bytes; +} + +constexpr auto test_info = text_bytes("asynchronous HPKE"); +constexpr auto test_associated_data = text_bytes("associated"); +constexpr auto test_plaintext = text_bytes("a message sealed asynchronously"); +constexpr auto test_psk_key = filled(0x24); +constexpr auto test_psk_id = text_bytes("id"); +constexpr auto test_recipient_seed = filled(0x11); +constexpr auto test_sender_seed = filled(0x22); + +/** The contexts, set up, sealed and opened in a coroutine, member and free. */ +template +asio::awaitable contexts_round_trip() { + auto const executor = co_await asio::this_coro::executor; + auto const recipient = co_await hpke::async_derive_from_seed( + executor, test_recipient_seed, asio::use_awaitable); + auto const derived = Suite::derive_from_seed(test_recipient_seed); + BOOST_TEST(derived.has_value() && *recipient.public_key() == *derived->public_key()); + auto const member_derived = + co_await Suite::async_derive_from_seed(executor, test_recipient_seed, asio::use_awaitable); + BOOST_TEST(*member_derived.public_key() == *derived->public_key()); + auto const recipient_public_key = *recipient.public_key(); + + auto sender = co_await hpke::async_begin_sending(executor, recipient_public_key, + test_info, asio::use_awaitable); + std::vector ciphertext(test_plaintext.size() + Suite::tag_size); + co_await sender.async_seal(executor, test_associated_data, test_plaintext, ciphertext, + asio::use_awaitable); + std::vector second(test_plaintext.size() + Suite::tag_size); + co_await hpke::async_seal(executor, sender, test_associated_data, test_plaintext, second, + asio::use_awaitable); + auto receiver = co_await Suite::async_begin_receiving( + executor, sender.encapsulated_key(), recipient, test_info, asio::use_awaitable); + std::vector opened(test_plaintext.size()); + co_await receiver.async_open(executor, test_associated_data, ciphertext, opened, + asio::use_awaitable); + BOOST_TEST(std::ranges::equal(opened, test_plaintext)); + co_await hpke::async_open(executor, receiver, test_associated_data, second, opened, + asio::use_awaitable); + BOOST_TEST(std::ranges::equal(opened, test_plaintext)); + auto const sent_secret = sender.template export_secret<32>(test_info); + auto const received_secret = receiver.template export_secret<32>(test_info); + BOOST_TEST(sent_secret.has_value() && received_secret.has_value() && + std::ranges::equal(sent_secret->bytes(), received_secret->bytes())); +} + +/** The single-shot calls in every mode, member and free. */ +template +asio::awaitable single_shot_round_trip() { + auto const executor = co_await asio::this_coro::executor; + auto const recipient = Suite::derive_from_seed(test_recipient_seed); + auto const sender = Suite::derive_from_seed(test_sender_seed); + if (!BOOST_TEST(recipient.has_value() && sender.has_value())) { + co_return; + } + auto const recipient_public_key = *recipient->public_key(); + auto const sender_public_key = *sender->public_key(); + hpke::pre_shared_key const pre_shared_key{.key = test_psk_key, .id = test_psk_id}; + std::vector ciphertext(test_plaintext.size() + Suite::tag_size); + std::vector opened(test_plaintext.size()); + + auto key = co_await hpke::async_seal(executor, recipient_public_key, test_info, + test_associated_data, test_plaintext, ciphertext, + asio::use_awaitable); + co_await hpke::async_open(executor, key, *recipient, test_info, test_associated_data, + ciphertext, opened, asio::use_awaitable); + BOOST_TEST(std::ranges::equal(opened, test_plaintext)); + + key = + co_await Suite::async_seal(executor, recipient_public_key, test_info, test_associated_data, + test_plaintext, ciphertext, pre_shared_key, asio::use_awaitable); + co_await Suite::async_open(executor, key, *recipient, test_info, test_associated_data, + ciphertext, opened, pre_shared_key, asio::use_awaitable); + BOOST_TEST(std::ranges::equal(opened, test_plaintext)); + + key = + co_await Suite::async_seal(executor, recipient_public_key, test_info, test_associated_data, + test_plaintext, ciphertext, *sender, asio::use_awaitable); + co_await Suite::async_open(executor, key, *recipient, test_info, test_associated_data, + ciphertext, opened, sender_public_key, asio::use_awaitable); + BOOST_TEST(std::ranges::equal(opened, test_plaintext)); + + key = co_await hpke::async_seal(executor, recipient_public_key, test_info, + test_associated_data, test_plaintext, ciphertext, + pre_shared_key, *sender, asio::use_awaitable); + co_await hpke::async_open(executor, key, *recipient, test_info, test_associated_data, + ciphertext, opened, pre_shared_key, sender_public_key, + asio::use_awaitable); + BOOST_TEST(std::ranges::equal(opened, test_plaintext)); + + // The receiving setup in auth_psk mode, then a changed ciphertext refused. + auto receiver = co_await hpke::async_begin_receiving( + executor, key, *recipient, test_info, pre_shared_key, sender_public_key, + asio::use_awaitable); + ciphertext.back() ^= 0x01U; + auto const [code] = co_await receiver.async_open(executor, test_associated_data, ciphertext, + opened, asio::as_tuple(asio::use_awaitable)); + BOOST_TEST(code == crypto::error::authentication_failed); +} + +/** Runs a coroutine to its end on the context, which it must reach without an exception. */ +void run_coroutine(asio::io_context& context, asio::awaitable coroutine) { + bool finished = false; + asio::co_spawn(context, std::move(coroutine), [&finished](std::exception_ptr const& failure) { + BOOST_TEST(!failure); + finished = true; + }); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST(finished); +} + +/** The asynchronous seal gives the synchronous seal's ciphertext for the same ephemeral seed. */ +template +void same_as_synchronous(asio::io_context& context) { + auto const recipient = Suite::derive_from_seed(test_recipient_seed); + if (!BOOST_TEST(recipient.has_value())) { + return; + } + std::vector const ephemeral_seed(32, 0x33); + auto asynchronous_sender = access::begin_sending_with_ephemeral_seed( + ephemeral_seed, *recipient->public_key(), test_info, nullptr, nullptr); + auto synchronous_sender = access::begin_sending_with_ephemeral_seed( + ephemeral_seed, *recipient->public_key(), test_info, nullptr, nullptr); + if (!BOOST_TEST(asynchronous_sender.has_value() && synchronous_sender.has_value())) { + return; + } + std::vector asynchronous_ciphertext(test_plaintext.size() + Suite::tag_size); + std::vector synchronous_ciphertext(test_plaintext.size() + Suite::tag_size); + boost::system::error_code completed = crypto::error::invalid_state; + asynchronous_sender->async_seal( + context.get_executor(), test_associated_data, test_plaintext, asynchronous_ciphertext, + [&completed](boost::system::error_code code) { completed = code; }); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST(!completed); + BOOST_TEST( + synchronous_sender->seal(test_associated_data, test_plaintext, synchronous_ciphertext) + .has_value()); + BOOST_TEST(asynchronous_ciphertext == synchronous_ciphertext); +} + +/** A flag a callback sets: unset when the initiating call returns, set once the context runs. */ +template +void check_never_inline(asio::io_context& context, Start start) { + bool called = false; + start([&called](auto&&...) { called = true; }); + BOOST_TEST(!called); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST(called); +} + +template +void never_inline(asio::io_context& context) { + auto const executor = context.get_executor(); + auto const recipient = Suite::derive_from_seed(test_recipient_seed); + if (!BOOST_TEST(recipient.has_value())) { + return; + } + auto const recipient_public_key = *recipient->public_key(); + check_never_inline(context, [&](auto handler) { + Suite::async_begin_sending(executor, recipient_public_key, test_info, handler); + }); + auto sender = Suite::begin_sending(recipient_public_key, test_info); + if (!BOOST_TEST(sender.has_value())) { + return; + } + std::vector ciphertext(test_plaintext.size() + Suite::tag_size); + check_never_inline(context, [&](auto handler) { + sender->async_seal(executor, test_associated_data, test_plaintext, ciphertext, handler); + }); + std::vector opened(test_plaintext.size()); + check_never_inline(context, [&](auto handler) { + hpke::async_open(executor, sender->encapsulated_key(), *recipient, test_info, + test_associated_data, ciphertext, opened, handler); + }); + BOOST_TEST(std::ranges::equal(opened, test_plaintext)); +} + +/** Errors complete with their code and the empty value. */ +template +void errors(asio::io_context& context) { + auto const executor = context.get_executor(); + std::vector const short_seed(31); + boost::system::error_code seed_code; + Suite::async_derive_from_seed( + executor, short_seed, + [&seed_code](boost::system::error_code code, Suite::recipient_keypair_type key_pair) { + seed_code = code; + BOOST_TEST(key_pair.public_key().error() == crypto::error::invalid_state); + }); + auto const recipient = Suite::derive_from_seed(test_recipient_seed); + if (!BOOST_TEST(recipient.has_value())) { + return; + } + std::vector const short_key(31); + boost::system::error_code setup_code; + hpke::async_begin_sending( + executor, *recipient->public_key(), test_info, + hpke::pre_shared_key{.key = short_key, .id = test_psk_id}, + [&setup_code](boost::system::error_code code, Suite::sender_context_type sender) { + setup_code = code; + BOOST_TEST(sender.template export_secret<32>({}).error() == + crypto::error::invalid_state); + }); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST(seed_code == crypto::error::invalid_input_size); + BOOST_TEST(setup_code == crypto::error::invalid_key_size); +} + +template +void suite_cases(asio::io_context& context) { + run_coroutine(context, contexts_round_trip()); + run_coroutine(context, single_shot_round_trip()); + same_as_synchronous(context); + never_inline(context); + errors(context); +} + +} // namespace + +int main() { + asio::io_context context; + suite_cases(context); + suite_cases(context); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/hpke_openssl_test.cpp b/test/hpke_openssl_test.cpp new file mode 100644 index 00000000..84b20a91 --- /dev/null +++ b/test/hpke_openssl_test.cpp @@ -0,0 +1,329 @@ +// 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 against OpenSSL's (OSSL_HPKE_*, OpenSSL 3.5) as a cross-check, within OpenSSL's limits +// (design D11): an application_info of at most 1024 bytes; a pre-shared key, its id and an +// export purpose of 32 to 66 bytes, the id with no zero byte; a plaintext of at least one byte +// (OSSL_HPKE_seal refuses an empty one, which RFC 9180 allows). crypto runs on libsodium and +// BearSSL (X25519 on libsodium beside BearSSL's AEADs, P-256 wholly on BearSSL), so that OpenSSL +// is the other side alone. For each of the 32 suites (two key encapsulations by two key +// derivations by four ciphers) and each mode, on inputs drawn at random: +// - derive_from_seed and OSSL_HPKE_keygen, given the same seed, give the same public key; +// - with the same ephemeral seed (OSSL_HPKE_CTX_set1_ikme and the test seam), both senders give +// the same encapsulated key and the same ciphertexts, three in order, and the same exports; +// - crypto seals and OpenSSL opens, OpenSSL seals and crypto opens, three messages each; +// - both sides export the same secrets; an export-only suite exports only. +// The specification's case is among them: OpenSSL seals to a key pair crypto's derive_from_seed +// made, in auth_psk mode, with an info of 1024 bytes, and crypto opens it and exports the same +// secret. + +#include +#include +#include +#include +#include +#include + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace crypto = webcpp::crypto; +namespace hpke = crypto::public_key_encryption::hpke; +using access = crypto::detail::hpke_access; + +/** P-256 wholly on BearSSL; X25519 on libsodium beside BearSSL's AEADs. */ +template +using crypto_backends = + std::conditional_t, + crypto::backends::bearssl, + hpke::backends>; + +/** An OpenSSL context, freed. */ +struct context_deleter { + void operator()(OSSL_HPKE_CTX* context) const noexcept { OSSL_HPKE_CTX_free(context); } +}; + +using openssl_context = std::unique_ptr; + +/** An OpenSSL key, freed. */ +struct key_deleter { + void operator()(EVP_PKEY* key) const noexcept { EVP_PKEY_free(key); } +}; + +using openssl_key = std::unique_ptr; + +/** Random bytes of a length, none of them zero when `no_zero` (OpenSSL's id is a C string). */ +std::vector random_bytes(std::size_t length, bool no_zero = false) { + std::vector drawn(length); + BOOST_TEST(crypto::random_device().fill(drawn).has_value()); + if (no_zero) { + std::ranges::replace(drawn, std::uint8_t{0}, std::uint8_t{1}); + } + return drawn; +} + +/** A key pair OpenSSL derives from a seed, and its public key's bytes. */ +struct openssl_keypair { + openssl_key private_key; + std::vector public_bytes; +}; + +openssl_keypair openssl_derived(OSSL_HPKE_SUITE suite, std::span seed) { + openssl_keypair made{.private_key = nullptr, .public_bytes = std::vector(133)}; + std::size_t public_size = made.public_bytes.size(); + EVP_PKEY* private_key = nullptr; + BOOST_TEST_EQ(OSSL_HPKE_keygen(suite, made.public_bytes.data(), &public_size, &private_key, + seed.data(), seed.size(), nullptr, nullptr), + 1); + made.private_key.reset(private_key); + made.public_bytes.resize(public_size); + return made; +} + +/** The inputs of one mode's cross-check, within OpenSSL's limits. */ +struct inputs { + int mode = OSSL_HPKE_MODE_BASE; + std::vector info = random_bytes(1024); + std::vector psk_key = random_bytes(66); + std::vector psk_id = random_bytes(48, true); + std::vector purpose = random_bytes(32); + std::vector ephemeral_seed = random_bytes(32); + std::vector recipient_seed = random_bytes(32); + std::vector sender_seed = random_bytes(64); + std::array, 3> plaintexts{ + random_bytes(1), + random_bytes(17), + random_bytes(300), + }; + std::vector associated_data = random_bytes(40); +}; + +/** Whether a mode takes the pre-shared key, and whether it authenticates the sender. */ +bool keyed(int mode) { + return mode == OSSL_HPKE_MODE_PSK || mode == OSSL_HPKE_MODE_PSKAUTH; +} + +bool authenticated(int mode) { + return mode == OSSL_HPKE_MODE_AUTH || mode == OSSL_HPKE_MODE_PSKAUTH; +} + +/** An OpenSSL context of a role, given the mode's inputs. */ +openssl_context openssl_made(OSSL_HPKE_SUITE suite, inputs const& in, int role, + openssl_keypair const& sender) { + openssl_context made(OSSL_HPKE_CTX_new(in.mode, suite, role, nullptr, nullptr)); + if (!BOOST_TEST(made != nullptr)) { + return made; + } + if (keyed(in.mode)) { + std::string const id(in.psk_id.begin(), in.psk_id.end()); + BOOST_TEST_EQ( + OSSL_HPKE_CTX_set1_psk(made.get(), id.c_str(), in.psk_key.data(), in.psk_key.size()), + 1); + } + if (authenticated(in.mode)) { + if (role == OSSL_HPKE_ROLE_SENDER) { + BOOST_TEST_EQ(OSSL_HPKE_CTX_set1_authpriv(made.get(), sender.private_key.get()), 1); + } else { + BOOST_TEST_EQ(OSSL_HPKE_CTX_set1_authpub(made.get(), sender.public_bytes.data(), + sender.public_bytes.size()), + 1); + } + } + return made; +} + +/** crypto's recipient of a mode, from the encapsulated key crypto's sender gave. */ +template +boost::system::result crypto_received( + inputs const& in, typename Suite::encapsulated_key_type const& key, + typename Suite::recipient_keypair_type const& recipient, + hpke::pre_shared_key const& pre_shared_key, + typename Suite::public_key_type const& sender_public_key) { + if (keyed(in.mode) && authenticated(in.mode)) { + return Suite::begin_receiving(key, recipient, in.info, pre_shared_key, sender_public_key); + } + if (keyed(in.mode)) { + return Suite::begin_receiving(key, recipient, in.info, pre_shared_key); + } + if (authenticated(in.mode)) { + return Suite::begin_receiving(key, recipient, in.info, sender_public_key); + } + return Suite::begin_receiving(key, recipient, in.info); +} + +/** The messages: both senders give the same ciphertexts, and each recipient opens the other's. */ +template +void check_messages(inputs const& in, typename Suite::sender_context_type& crypto_sender, + typename Suite::recipient_context_type& crypto_recipient, + OSSL_HPKE_CTX* openssl_sender, OSSL_HPKE_CTX* openssl_recipient) { + for (auto const& plaintext : in.plaintexts) { + std::vector sealed(plaintext.size() + Suite::tag_size); + BOOST_TEST(crypto_sender.seal(in.associated_data, plaintext, sealed).has_value()); + std::vector openssl_sealed(plaintext.size() + Suite::tag_size); + std::size_t sealed_size = openssl_sealed.size(); + BOOST_TEST_EQ(OSSL_HPKE_seal(openssl_sender, openssl_sealed.data(), &sealed_size, + in.associated_data.data(), in.associated_data.size(), + plaintext.data(), plaintext.size()), + 1); + BOOST_TEST(sealed == openssl_sealed); + // OpenSSL opens crypto's; crypto opens OpenSSL's. + std::vector openssl_opened(plaintext.size() + 1); + std::size_t opened_size = openssl_opened.size(); + BOOST_TEST_EQ(OSSL_HPKE_open(openssl_recipient, openssl_opened.data(), &opened_size, + in.associated_data.data(), in.associated_data.size(), + sealed.data(), sealed.size()), + 1); + openssl_opened.resize(opened_size); + BOOST_TEST(openssl_opened == plaintext); + std::vector opened(plaintext.size()); + BOOST_TEST(crypto_recipient.open(in.associated_data, openssl_sealed, opened).has_value()); + BOOST_TEST(opened == plaintext); + } +} + +/** Every side exports the same secret. */ +template +void check_exports(inputs const& in, typename Suite::sender_context_type const& crypto_sender, + typename Suite::recipient_context_type const& crypto_recipient, + OSSL_HPKE_CTX* openssl_sender, OSSL_HPKE_CTX* openssl_recipient) { + std::array openssl_sent{}; + std::array openssl_received{}; + BOOST_TEST_EQ(OSSL_HPKE_export(openssl_sender, openssl_sent.data(), openssl_sent.size(), + in.purpose.data(), in.purpose.size()), + 1); + BOOST_TEST_EQ(OSSL_HPKE_export(openssl_recipient, openssl_received.data(), + openssl_received.size(), in.purpose.data(), in.purpose.size()), + 1); + auto const sent = crypto_sender.template export_secret<48>(in.purpose); + auto const received = crypto_recipient.template export_secret<48>(in.purpose); + if (BOOST_TEST(sent.has_value() && received.has_value())) { + BOOST_TEST(std::ranges::equal(sent->bytes(), openssl_sent)); + BOOST_TEST(std::ranges::equal(received->bytes(), openssl_received)); + } +} + +/** One mode of one suite, both directions. */ +template +void check_mode(inputs const& in) { + OSSL_HPKE_SUITE const suite{ + Suite::key_encapsulation_type::id, + Suite::key_derivation_type::id, + Suite::cipher_type::id, + }; + // The key pairs, derived by both from the same seeds. + auto const recipient = Suite::derive_from_seed(in.recipient_seed); + auto const sender_keypair = Suite::derive_from_seed(in.sender_seed); + if (!BOOST_TEST(recipient.has_value() && sender_keypair.has_value())) { + return; + } + auto const recipient_public_key = *recipient->public_key(); + auto const sender_public_key = *sender_keypair->public_key(); + auto const openssl_recipient = openssl_derived(suite, in.recipient_seed); + auto const openssl_sender = openssl_derived(suite, in.sender_seed); + auto const recipient_bytes = crypto::detail::hpke_serialized(recipient_public_key); + BOOST_TEST(std::ranges::equal(recipient_bytes, openssl_recipient.public_bytes)); + BOOST_TEST(std::ranges::equal(crypto::detail::hpke_serialized(sender_public_key), + openssl_sender.public_bytes)); + + hpke::pre_shared_key const pre_shared_key{.key = in.psk_key, .id = in.psk_id}; + auto const* key_given = keyed(in.mode) ? &pre_shared_key : nullptr; + auto const* sender_given = authenticated(in.mode) ? &*sender_keypair : nullptr; + + // The same ephemeral seed on both senders: the same encapsulated key and ciphertexts. + auto crypto_sender = access::begin_sending_with_ephemeral_seed( + in.ephemeral_seed, recipient_public_key, in.info, key_given, sender_given); + auto const openssl_sender_context = + openssl_made(suite, in, OSSL_HPKE_ROLE_SENDER, openssl_sender); + if (!BOOST_TEST(crypto_sender.has_value() && openssl_sender_context != nullptr)) { + return; + } + BOOST_TEST_EQ(OSSL_HPKE_CTX_set1_ikme(openssl_sender_context.get(), in.ephemeral_seed.data(), + in.ephemeral_seed.size()), + 1); + std::array openssl_encapsulated{}; + std::size_t encapsulated_size = openssl_encapsulated.size(); + BOOST_TEST_EQ(OSSL_HPKE_encap(openssl_sender_context.get(), openssl_encapsulated.data(), + &encapsulated_size, recipient_bytes.data(), + recipient_bytes.size(), in.info.data(), in.info.size()), + 1); + BOOST_TEST(std::ranges::equal(crypto_sender->encapsulated_key().bytes(), + std::span(openssl_encapsulated).first(encapsulated_size))); + + // Both recipients: OpenSSL's for crypto's messages, crypto's for OpenSSL's. + auto const openssl_recipient_context = + openssl_made(suite, in, OSSL_HPKE_ROLE_RECEIVER, openssl_sender); + auto const& encapsulated = crypto_sender->encapsulated_key().bytes(); + if (!BOOST_TEST(openssl_recipient_context != nullptr)) { + return; + } + BOOST_TEST_EQ( + OSSL_HPKE_decap(openssl_recipient_context.get(), encapsulated.data(), encapsulated.size(), + openssl_recipient.private_key.get(), in.info.data(), in.info.size()), + 1); + auto crypto_recipient = crypto_received(in, crypto_sender->encapsulated_key(), + *recipient, pre_shared_key, sender_public_key); + if (!BOOST_TEST(crypto_recipient.has_value())) { + return; + } + if constexpr (hpke::sealing_cipher) { + check_messages(in, *crypto_sender, *crypto_recipient, openssl_sender_context.get(), + openssl_recipient_context.get()); + } + check_exports(in, *crypto_sender, *crypto_recipient, openssl_sender_context.get(), + openssl_recipient_context.get()); +} + +template +void check_suite() { + for (int const mode : + {OSSL_HPKE_MODE_BASE, OSSL_HPKE_MODE_PSK, OSSL_HPKE_MODE_AUTH, OSSL_HPKE_MODE_PSKAUTH}) { + inputs in; + in.mode = mode; + check_mode(in); + // The shortest of OpenSSL's limits too: 32-byte key, id and purpose, an empty info. + in.info.clear(); + in.psk_key = random_bytes(32); + in.psk_id = random_bytes(32, true); + in.purpose = random_bytes(32); + check_mode(in); + } +} + +template +void check_ciphers() { + using backend = crypto_backends; + check_suite>(); + check_suite>(); + check_suite< + hpke::suite>(); + check_suite>(); +} + +} // namespace + +int main() { + namespace kem = hpke::key_encapsulation; + namespace kdf = hpke::key_derivation; + check_ciphers(); + check_ciphers(); + check_ciphers(); + check_ciphers(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/hpke_test.cpp b/test/hpke_test.cpp new file mode 100644 index 00000000..f3a6fd9f --- /dev/null +++ b/test/hpke_test.cpp @@ -0,0 +1,646 @@ +// 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) through its public calls, on the default backends, for every suite crypto has +// (two key encapsulations by two key derivations by four ciphers, design D11): +// - the four modes round-trip through begin_sending and begin_receiving, three messages in order +// on one context each, in place too, an empty message's ciphertext the tag alone; through the +// single-shot seal and open; through the free forms of hpke; both contexts export the same +// secrets by both forms of export_secret, the free forms too, for an empty purpose as for one; +// - the refusals: a wrong sender's public key, a wrong pre-shared key or id, a changed associated +// data, a changed ciphertext and another encapsulated key each fail with +// authentication_failed, the output zeroed and the sequence number unchanged, the unchanged +// message opening afterwards; the sizes (invalid_input_size, the output untouched); a context +// moved from (invalid_state, its encapsulated key zero); an export of no byte or longer than +// 255 * Nh; +// - an X25519 key of small order, as the recipient's key or as the encapsulated key, is +// weak_public_key; a P-256 encapsulated key off the curve is invalid_public_key; +// - the minimum lengths (ruling R6): a pre-shared key of 31 bytes is invalid_key_size, an empty id +// invalid_input_size, a seed of 31 bytes invalid_input_size; an encapsulated key of another size +// invalid_input_size; +// - the sequence number through the test seam: a sender at 2^64 - 2 seals once, then refuses with +// message_limit_reached, its output untouched; a recipient there opens once, then refuses; +// - an export-only suite sets up and exports in every mode; +// - Marmot's recovery key (marmot-protocol/marmot @ 36757fe, features/account-sync.md, "Recovery +// key"): its two vectors, the entropy through HKDF-SHA256 with its salt and info, then +// derive_from_seed, give the document's ikm, sk and pk (ruling B4). + +#include +#include +#include +#include +#include +#include + +#include "support/hex.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace crypto = webcpp::crypto; +namespace hpke = crypto::public_key_encryption::hpke; +using crypto::error; +using access = crypto::detail::hpke_access; + +/** The bytes of a text. */ +std::vector bytes_of(std::string_view text) { + return {text.begin(), text.end()}; +} + +/** Whether every byte is zero. */ +bool all_zero(std::span checked_bytes) { + return std::ranges::all_of(checked_bytes, [](std::uint8_t byte) { return byte == 0; }); +} + +/** The four modes. */ +enum class mode { base, psk, auth, auth_psk }; + +constexpr std::array every_mode{mode::base, mode::psk, mode::auth, mode::auth_psk}; + +/** Whether a mode takes the pre-shared key. */ +constexpr bool keyed(mode checked_mode) { + return checked_mode == mode::psk || checked_mode == mode::auth_psk; +} + +/** Whether a mode authenticates the sender. */ +constexpr bool authenticated(mode checked_mode) { + return checked_mode == mode::auth || checked_mode == mode::auth_psk; +} + +/** The parties and inputs of a suite's checks. */ +template +struct parties { + Suite::recipient_keypair_type recipient; + Suite::sender_keypair_type sender; + Suite::public_key_type recipient_public_key; + Suite::public_key_type sender_public_key; + std::vector info = bytes_of("an HPKE test of webcpp::crypto"); + std::vector psk_key = std::vector(32, 0x42); + std::vector psk_id = bytes_of("the pre-shared key's id"); +}; + +/** Two fresh key pairs of a suite and their public keys. */ +template +std::optional> made_parties() { + auto recipient = Suite::recipient_keypair_type::generate(); + auto sender = Suite::sender_keypair_type::generate(); + if (!BOOST_TEST(recipient.has_value() && sender.has_value())) { + return std::nullopt; + } + auto recipient_public_key = recipient->public_key(); + auto sender_public_key = sender->public_key(); + if (!BOOST_TEST(recipient_public_key.has_value() && sender_public_key.has_value())) { + return std::nullopt; + } + return parties{ + std::move(*recipient), + std::move(*sender), + *recipient_public_key, + *sender_public_key, + }; +} + +/** A sender set up in a mode. */ +template +boost::system::result sending( + mode setup_mode, parties const& party, hpke::pre_shared_key const& pre_shared_key) { + switch (setup_mode) { + case mode::base: return Suite::begin_sending(party.recipient_public_key, party.info); + case mode::psk: + return Suite::begin_sending(party.recipient_public_key, party.info, pre_shared_key); + case mode::auth: + return Suite::begin_sending(party.recipient_public_key, party.info, party.sender); + case mode::auth_psk: + return Suite::begin_sending(party.recipient_public_key, party.info, pre_shared_key, + party.sender); + } + return error::invalid_state; +} + +/** A recipient set up in a mode, with the sender's public key given. */ +template +boost::system::result receiving( + mode setup_mode, parties const& party, + typename Suite::encapsulated_key_type const& encapsulated_key, + hpke::pre_shared_key const& pre_shared_key, + typename Suite::public_key_type const& sender_public_key) { + switch (setup_mode) { + case mode::base: + return Suite::begin_receiving(encapsulated_key, party.recipient, party.info); + case mode::psk: + return Suite::begin_receiving(encapsulated_key, party.recipient, party.info, + pre_shared_key); + case mode::auth: + return Suite::begin_receiving(encapsulated_key, party.recipient, party.info, + sender_public_key); + case mode::auth_psk: + return Suite::begin_receiving(encapsulated_key, party.recipient, party.info, + pre_shared_key, sender_public_key); + } + return error::invalid_state; +} + +/** Both contexts export the same secrets, by every form. */ +template +void check_exports(typename Suite::sender_context_type const& sender, + typename Suite::recipient_context_type const& recipient) { + for (auto const& purpose : {std::vector{}, bytes_of("response key")}) { + auto const sent = sender.template export_secret<32>(purpose); + auto const received = recipient.template export_secret<32>(purpose); + std::array sent_bytes{}; + std::array received_bytes{}; + BOOST_TEST(sender.export_secret(purpose, sent_bytes).has_value()); + BOOST_TEST(hpke::export_secret(recipient, purpose, received_bytes).has_value()); + auto const free_form = hpke::export_secret<32>(sender, purpose); + if (!BOOST_TEST(sent.has_value() && received.has_value() && free_form.has_value())) { + continue; + } + BOOST_TEST(webcpp::secure::constant_time_equal(sent->bytes(), received->bytes())); + BOOST_TEST(std::ranges::equal(sent->bytes(), sent_bytes)); + BOOST_TEST(std::ranges::equal(sent->bytes(), received_bytes)); + BOOST_TEST(std::ranges::equal(sent->bytes(), free_form->bytes())); + } + // The longest export, and one byte more (refused, untouched), and none. + std::vector longest(Suite::max_export_size); + BOOST_TEST(sender.export_secret({}, longest).has_value()); + std::vector too_long(Suite::max_export_size + 1, 0x5a); + BOOST_TEST(sender.export_secret({}, too_long).error() == error::invalid_input_size); + BOOST_TEST(std::ranges::all_of(too_long, [](std::uint8_t byte) { return byte == 0x5a; })); + BOOST_TEST(recipient.export_secret({}, std::span{}).error() == + error::invalid_input_size); +} + +/** Three messages, the first empty and the last sealed and opened in place, in order. */ +template +void check_messages(typename Suite::sender_context_type& sender, + typename Suite::recipient_context_type& recipient) { + auto const associated_data = bytes_of("Count-0"); + for (std::size_t const length : {std::size_t{0}, std::size_t{29}, std::size_t{100}}) { + std::vector plaintext(length); + for (std::size_t index = 0; index < length; ++index) { + plaintext[index] = static_cast(index * 7U); + } + std::vector ciphertext(length + Suite::tag_size); + if (length == 100) { + std::ranges::copy(plaintext, ciphertext.begin()); + BOOST_TEST(hpke::seal(sender, associated_data, + std::span(ciphertext).first(length), + ciphertext) + .has_value()); + BOOST_TEST(hpke::open(recipient, associated_data, ciphertext, + std::span(ciphertext).first(length)) + .has_value()); + BOOST_TEST(std::ranges::equal(std::span(ciphertext).first(length), plaintext)); + continue; + } + BOOST_TEST(sender.seal(associated_data, plaintext, ciphertext).has_value()); + std::vector opened(length); + BOOST_TEST(recipient.open(associated_data, ciphertext, opened).has_value()); + BOOST_TEST(opened == plaintext); + } + BOOST_TEST_EQ(access::sequence(sender), 3U); + BOOST_TEST_EQ(access::sequence(recipient), 3U); +} + +/** One mode's round trip, through the contexts and through the single-shot calls. */ +template +void check_round_trip(mode setup_mode, parties const& party) { + hpke::pre_shared_key const pre_shared_key{.key = party.psk_key, .id = party.psk_id}; + auto sender = sending(setup_mode, party, pre_shared_key); + if (!BOOST_TEST(sender.has_value())) { + return; + } + auto recipient = receiving(setup_mode, party, sender->encapsulated_key(), pre_shared_key, + party.sender_public_key); + if (!BOOST_TEST(recipient.has_value())) { + return; + } + check_exports(*sender, *recipient); + if constexpr (hpke::sealing_cipher) { + check_messages(*sender, *recipient); + // The single-shot calls, by mode. + auto const associated_data = bytes_of("single shot"); + auto const plaintext = bytes_of("one message to a public key"); + std::vector ciphertext(plaintext.size() + Suite::tag_size); + std::vector opened(plaintext.size()); + auto const pkr = party.recipient_public_key; + boost::system::result sealed = error::invalid_state; + boost::system::result unsealed = error::invalid_state; + switch (setup_mode) { + case mode::base: + sealed = hpke::seal(pkr, party.info, associated_data, plaintext, ciphertext); + if (sealed) { + unsealed = hpke::open(*sealed, party.recipient, party.info, + associated_data, ciphertext, opened); + } + break; + case mode::psk: + sealed = Suite::seal(pkr, party.info, associated_data, plaintext, ciphertext, + pre_shared_key); + if (sealed) { + unsealed = Suite::open(*sealed, party.recipient, party.info, associated_data, + ciphertext, opened, pre_shared_key); + } + break; + case mode::auth: + sealed = Suite::seal(pkr, party.info, associated_data, plaintext, ciphertext, + party.sender); + if (sealed) { + unsealed = Suite::open(*sealed, party.recipient, party.info, associated_data, + ciphertext, opened, party.sender_public_key); + } + break; + case mode::auth_psk: + sealed = Suite::seal(pkr, party.info, associated_data, plaintext, ciphertext, + pre_shared_key, party.sender); + if (sealed) { + unsealed = + Suite::open(*sealed, party.recipient, party.info, associated_data, + ciphertext, opened, pre_shared_key, party.sender_public_key); + } + break; + } + BOOST_TEST(sealed.has_value()); + BOOST_TEST(unsealed.has_value()); + BOOST_TEST(opened == plaintext); + } +} + +/** + * A message that does not open: authentication_failed, the output zeroed, the sequence number + * unchanged; then the unchanged message opens, when `then_opens`. + */ +template +void check_refused(typename Suite::recipient_context_type& recipient, + std::span associated_data, + std::span ciphertext, bool then_opens, + std::span good_associated_data, + std::span good_ciphertext) { + auto const before = access::sequence(recipient); + std::vector opened(ciphertext.size() - Suite::tag_size, 0x5a); + auto const refused = recipient.open(associated_data, ciphertext, opened); + BOOST_TEST(!refused.has_value() && refused.error() == error::authentication_failed); + BOOST_TEST(all_zero(opened)); + BOOST_TEST_EQ(access::sequence(recipient), before); + if (then_opens) { + BOOST_TEST(recipient.open(good_associated_data, good_ciphertext, opened).has_value()); + BOOST_TEST_EQ(access::sequence(recipient), before + 1); + } +} + +/** A recipient set up with one input other than the sender's: its open is refused. */ +template +void check_wrong_setup(mode setup_mode, parties const& party, + typename Suite::encapsulated_key_type const& encapsulated_key, + hpke::pre_shared_key const& pre_shared_key, + typename Suite::public_key_type const& sender_public_key, + std::span associated_data, + std::span ciphertext) { + auto wrong = receiving(setup_mode, party, encapsulated_key, pre_shared_key, sender_public_key); + if (BOOST_TEST(wrong.has_value())) { + check_refused(*wrong, associated_data, ciphertext, false, {}, {}); + } +} + +/** The refusals of a sealing suite in one mode. */ +template +void check_refusals_in(mode setup_mode, parties const& party) { + hpke::pre_shared_key const pre_shared_key{.key = party.psk_key, .id = party.psk_id}; + auto const associated_data = bytes_of("associated"); + auto const plaintext = bytes_of("a message"); + auto sender = sending(setup_mode, party, pre_shared_key); + auto other_sender = sending(setup_mode, party, pre_shared_key); + if (!BOOST_TEST(sender.has_value() && other_sender.has_value())) { + return; + } + std::vector ciphertext(plaintext.size() + Suite::tag_size); + BOOST_TEST(sender->seal(associated_data, plaintext, ciphertext).has_value()); + auto recipient = receiving(setup_mode, party, sender->encapsulated_key(), pre_shared_key, + party.sender_public_key); + if (!BOOST_TEST(recipient.has_value())) { + return; + } + // A changed associated data, then a changed last byte, then the message itself. + check_refused(*recipient, bytes_of("associateD"), ciphertext, false, {}, {}); + auto changed = ciphertext; + changed.back() ^= 0x01U; + check_refused(*recipient, associated_data, changed, true, associated_data, ciphertext); + // Another encapsulated key: a context of another sender. + check_wrong_setup(setup_mode, party, other_sender->encapsulated_key(), pre_shared_key, + party.sender_public_key, associated_data, ciphertext); + if (authenticated(setup_mode)) { + // The recipient's own public key is not the sender's. + check_wrong_setup(setup_mode, party, sender->encapsulated_key(), pre_shared_key, + party.recipient_public_key, associated_data, ciphertext); + } + if (keyed(setup_mode)) { + auto other_key = party.psk_key; + other_key[0] ^= 0x01U; + auto other_id = party.psk_id; + other_id.push_back(0); + check_wrong_setup(setup_mode, party, sender->encapsulated_key(), + hpke::pre_shared_key{.key = other_key, .id = party.psk_id}, + party.sender_public_key, associated_data, ciphertext); + check_wrong_setup(setup_mode, party, sender->encapsulated_key(), + hpke::pre_shared_key{.key = party.psk_key, .id = other_id}, + party.sender_public_key, associated_data, ciphertext); + } +} + +/** The refusals of a sealing suite, in the modes they apply to. */ +template +void check_refusals(parties const& party) { + for (mode const setup_mode : every_mode) { + check_refusals_in(setup_mode, party); + } +} + +/** The size refusals of a context, which leave the output untouched. */ +template +void check_sizes(parties const& party) { + auto sender = Suite::begin_sending(party.recipient_public_key, party.info); + if (!BOOST_TEST(sender.has_value())) { + return; + } + auto recipient = + Suite::begin_receiving(sender->encapsulated_key(), party.recipient, party.info); + if (!BOOST_TEST(recipient.has_value())) { + return; + } + auto const plaintext = bytes_of("sized"); + for (std::size_t const wrong : + {plaintext.size() + Suite::tag_size - 1, plaintext.size() + Suite::tag_size + 1}) { + std::vector ciphertext(wrong, 0x5a); + BOOST_TEST(sender->seal({}, plaintext, ciphertext).error() == error::invalid_input_size); + BOOST_TEST(std::ranges::all_of(ciphertext, [](std::uint8_t byte) { return byte == 0x5a; })); + } + BOOST_TEST_EQ(access::sequence(*sender), 0U); + std::vector short_ciphertext(Suite::tag_size - 1); + std::vector none; + BOOST_TEST(recipient->open({}, short_ciphertext, none).error() == error::invalid_input_size); + std::vector ciphertext(plaintext.size() + Suite::tag_size); + std::vector wrong_plaintext(plaintext.size() + 1, 0x5a); + BOOST_TEST(recipient->open({}, ciphertext, wrong_plaintext).error() == + error::invalid_input_size); + BOOST_TEST( + std::ranges::all_of(wrong_plaintext, [](std::uint8_t byte) { return byte == 0x5a; })); +} + +/** The last message of a context, through the seam. */ +template +void check_sequence_limit(parties const& party) { + constexpr std::uint64_t last = std::numeric_limits::max() - 1; + auto sender = Suite::begin_sending(party.recipient_public_key, party.info); + if (!BOOST_TEST(sender.has_value())) { + return; + } + auto recipient = + Suite::begin_receiving(sender->encapsulated_key(), party.recipient, party.info); + if (!BOOST_TEST(recipient.has_value())) { + return; + } + access::set_sequence(*sender, last); + access::set_sequence(*recipient, last); + auto const plaintext = bytes_of("the last message"); + std::vector ciphertext(plaintext.size() + Suite::tag_size); + BOOST_TEST(sender->seal({}, plaintext, ciphertext).has_value()); + std::vector untouched(plaintext.size() + Suite::tag_size, 0x5a); + BOOST_TEST(sender->seal({}, plaintext, untouched).error() == error::message_limit_reached); + BOOST_TEST(std::ranges::all_of(untouched, [](std::uint8_t byte) { return byte == 0x5a; })); + std::vector opened(plaintext.size()); + // A failed open does not advance: the message still opens after it. + auto changed = ciphertext; + changed.front() ^= 0x80U; + BOOST_TEST(recipient->open({}, changed, opened).error() == error::authentication_failed); + BOOST_TEST(recipient->open({}, ciphertext, opened).has_value()); + BOOST_TEST(opened == plaintext); + BOOST_TEST(recipient->open({}, ciphertext, opened).error() == error::message_limit_reached); + // Exports go on: they do not touch the sequence number. + BOOST_TEST(sender->template export_secret<16>({}).has_value()); +} + +/** A context moved from refuses every call; its encapsulated key is zero. */ +template +void check_moved(parties const& party) { + auto sender = Suite::begin_sending(party.recipient_public_key, party.info); + if (!BOOST_TEST(sender.has_value())) { + return; + } + auto const sent_key = sender->encapsulated_key(); + auto recipient = Suite::begin_receiving(sent_key, party.recipient, party.info); + if (!BOOST_TEST(recipient.has_value())) { + return; + } + auto moved_sender = std::move(*sender); + auto moved_recipient = std::move(*recipient); + BOOST_TEST(moved_sender.encapsulated_key() == sent_key); + BOOST_TEST(sender->encapsulated_key() == typename Suite::encapsulated_key_type{}); + BOOST_TEST(sender->template export_secret<32>({}).error() == error::invalid_state); + std::array output{}; + BOOST_TEST(recipient->export_secret({}, output).error() == error::invalid_state); + if constexpr (hpke::sealing_cipher) { + std::vector ciphertext(Suite::tag_size); + BOOST_TEST(sender->seal({}, {}, ciphertext).error() == error::invalid_state); + BOOST_TEST(recipient->open({}, ciphertext, std::span{}).error() == + error::invalid_state); + } + // Moved back by assignment, the contexts work again; the sources refuse. + *sender = std::move(moved_sender); + *recipient = std::move(moved_recipient); + BOOST_TEST(sender->encapsulated_key() == sent_key); + // NOLINTNEXTLINE(bugprone-use-after-move,clang-analyzer-cplusplus.Move): the empty context + BOOST_TEST(moved_sender.template export_secret<32>({}).error() == error::invalid_state); + BOOST_TEST(recipient->export_secret({}, output).has_value()); + if constexpr (hpke::sealing_cipher) { + std::vector ciphertext(Suite::tag_size); + BOOST_TEST(sender->seal({}, {}, ciphertext).has_value()); + BOOST_TEST(recipient->open({}, ciphertext, std::span{}).has_value()); + } +} + +/** The minimum lengths and the encapsulated key's size (ruling R6). */ +template +void check_minimums(parties const& party) { + std::vector const short_key(31, 0x42); + std::vector const empty_id; + auto const short_psk = + Suite::begin_sending(party.recipient_public_key, party.info, + hpke::pre_shared_key{.key = short_key, .id = party.psk_id}); + BOOST_TEST(short_psk.error() == error::invalid_key_size); + auto const no_id = Suite::begin_sending( + party.recipient_public_key, party.info, + hpke::pre_shared_key{.key = party.psk_key, .id = empty_id}, party.sender); + BOOST_TEST(no_id.error() == error::invalid_input_size); + std::vector const short_seed(31, 0x01); + BOOST_TEST(Suite::derive_from_seed(short_seed).error() == error::invalid_input_size); + BOOST_TEST(hpke::derive_from_seed(std::vector(32, 0x01)).has_value()); + // A seed has no upper bound. + BOOST_TEST(Suite::derive_from_seed(std::vector(4096, 0x02)).has_value()); + std::vector const wrong_size(Suite::encapsulated_key_size + 1); + BOOST_TEST(Suite::encapsulated_key_type::from_bytes(wrong_size).error() == + error::invalid_input_size); + BOOST_TEST(crypto::from_bytes( + std::vector(Suite::encapsulated_key_size)) + .has_value()); +} + +/** Every check of one suite. */ +template +void check_suite() { + auto party = made_parties(); + if (!party) { + return; + } + for (mode const setup_mode : every_mode) { + check_round_trip(setup_mode, *party); + } + check_moved(*party); + check_minimums(*party); + if constexpr (hpke::sealing_cipher) { + check_refusals(*party); + check_sizes(*party); + check_sequence_limit(*party); + } +} + +/** The suites of a key encapsulation and a key derivation, every cipher. */ +template +void check_ciphers() { + check_suite>(); + check_suite>(); + check_suite>(); + check_suite>(); +} + +/** X25519 keys of small order: refused as the recipient's key and as the encapsulated key. */ +void check_x25519_small_order() { + using suite = hpke::suite; + std::array const zero_point{}; + auto const weak_key = suite::public_key_type::from_bytes(zero_point); + if (!BOOST_TEST(weak_key.has_value())) { + return; + } + auto const info = bytes_of("info"); + BOOST_TEST(suite::begin_sending(*weak_key, info).error() == crypto::error::weak_public_key); + auto const recipient = suite::recipient_keypair_type::generate(); + auto const weak_encapsulated = suite::encapsulated_key_type::from_bytes(zero_point); + if (!BOOST_TEST(recipient.has_value() && weak_encapsulated.has_value())) { + return; + } + BOOST_TEST(suite::begin_receiving(*weak_encapsulated, *recipient, info).error() == + crypto::error::weak_public_key); + // A sender's public key of small order, in auth mode. + auto const good = suite::begin_sending(*recipient->public_key(), info); + if (BOOST_TEST(good.has_value())) { + BOOST_TEST( + suite::begin_receiving(good->encapsulated_key(), *recipient, info, *weak_key).error() == + crypto::error::weak_public_key); + } +} + +/** A P-256 encapsulated key off the curve: invalid_public_key. */ +void check_p256_off_curve() { + using suite = hpke::suite; + std::array off_curve{0x04}; + off_curve[32] = 1; + off_curve[64] = 1; + auto const encapsulated_key = suite::encapsulated_key_type::from_bytes(off_curve); + auto const recipient = suite::recipient_keypair_type::generate(); + if (!BOOST_TEST(encapsulated_key.has_value() && recipient.has_value())) { + return; + } + BOOST_TEST(suite::begin_receiving(*encapsulated_key, *recipient, {}).error() == + crypto::error::invalid_public_key); + // The zero value of a moved-from context is no point either. + BOOST_TEST(suite::begin_receiving(suite::encapsulated_key_type{}, *recipient, {}).error() == + crypto::error::invalid_public_key); +} + +/** Marmot's recovery key: entropy, HKDF-SHA256 to an ikm, then DeriveKeyPair. */ +void check_marmot_recovery_key() { + using kem = hpke::key_encapsulation::x25519_hkdf_sha256; + + struct vector { + std::array entropy; + std::array ikm; + std::array secret_key; + std::array public_key; + }; + + // marmot-protocol/marmot @ 36757fe, features/account-sync.md, "Recovery key", its two test + // vectors. + constexpr std::array vectors{ + { + { + .entropy = webcpp::test::hex<16>("00000000000000000000000000000000"), + .ikm = webcpp::test::hex<32>( + "f2b851179e27ff0fa2a197b538c8e525aac11fcf3d8570bc8afb3e5dd48aea28"), + .secret_key = webcpp::test::hex<32>( + "f99da3bd75751479570bd7d7a807bebb49c8da68aed12e813862cccdff5a577d"), + .public_key = webcpp::test::hex<32>( + "aed5608fc1960f7992decafb36786d19508dce48e02288785cf24e557d58a368"), + }, + { + .entropy = webcpp::test::hex<16>("7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f"), + .ikm = webcpp::test::hex<32>( + "20d2dc269edddf61ef7859324c9459eb96ae0d34ffbace54b404d63862bba855"), + .secret_key = webcpp::test::hex<32>( + "8570ead0cc10c1ae63c6357959fdb15996475dabe3b781c4ebecdacb2015ef83"), + .public_key = webcpp::test::hex<32>( + "9076c238afd9311184e7dda595f7d42f5c73b48bff561e88482c4435d5cb5f10"), + }, + }, + }; + auto const salt = bytes_of("marmot recovery key v1"); + auto const info = bytes_of("marmot recovery key pair"); + for (vector const& marmot : vectors) { + std::array ikm{}; + BOOST_TEST(webcpp::hash::hkdf( + ikm, salt, std::span(marmot.entropy), + std::span(info)) + .has_value()); + BOOST_TEST(ikm == marmot.ikm); + auto const key_pair = kem::derive_from_seed(ikm); + if (!BOOST_TEST(key_pair.has_value())) { + continue; + } + auto const secret_key = key_pair->secret(); + auto const public_key = key_pair->public_key(); + if (BOOST_TEST(secret_key.has_value() && public_key.has_value())) { + BOOST_TEST(std::ranges::equal(secret_key->bytes(), marmot.secret_key)); + BOOST_TEST(public_key->bytes() == marmot.public_key); + } + } +} + +} // namespace + +int main() { + namespace kem = hpke::key_encapsulation; + namespace kdf = hpke::key_derivation; + check_ciphers(); + check_ciphers(); + check_ciphers(); + check_ciphers(); + check_x25519_small_order(); + check_p256_off_curve(); + check_marmot_recovery_key(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/hpke_vectors_bearssl_test.cpp b/test/hpke_vectors_bearssl_test.cpp new file mode 100644 index 00000000..7d892e53 --- /dev/null +++ b/test/hpke_vectors_bearssl_test.cpp @@ -0,0 +1,47 @@ +// 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) against the CFRG test vectors with BearSSL's ciphers +// (support/hpke_vectors.hpp): the P-256 suites wholly on BearSSL, one backend for the key pairs +// and the AEAD, and the X25519 suites on hpke::backends, X25519 on libsodium and +// the AEAD on BearSSL, as MLS's suite 0x0001 runs natively without OpenSSL. All 64 entries of the +// suites crypto has, every mode, every encryption in order and every export. + +#include +#include +#include +#include + +#include "support/hpke_vectors.hpp" + +#include + +#include + +namespace { + +namespace crypto = webcpp::crypto; +namespace hpke = crypto::public_key_encryption::hpke; + +/** P-256 wholly on BearSSL; X25519 on libsodium with BearSSL's AEAD. */ +template +using bearssl_backends = + std::conditional_t, + crypto::backends::bearssl, + hpke::backends>; + +/** A suite whose AEAD is BearSSL's. */ +template +using bearssl_suite = + hpke::suite>; + +} // namespace + +int main() { + namespace vectors = webcpp::test::hpke_vectors; + vectors::check_counts(vectors::check_file()); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/hpke_vectors_default_test.cpp b/test/hpke_vectors_default_test.cpp new file mode 100644 index 00000000..20a4b5a9 --- /dev/null +++ b/test/hpke_vectors_default_test.cpp @@ -0,0 +1,33 @@ +// 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) against the CFRG test vectors on the default backends of every family it uses +// (support/hpke_vectors.hpp): X25519 and ChaCha20-Poly1305 on libsodium, P-256 on BearSSL, and +// AES-GCM on its default, natively OpenSSL and on WebAssembly BearSSL. All 64 entries of the +// suites crypto has, every mode, every encryption in order and every export. + +#include +#include + +#include "support/hpke_vectors.hpp" + +#include + +namespace { + +namespace hpke = webcpp::crypto::public_key_encryption::hpke; + +/** A suite on the default backends. */ +template +using default_suite = hpke::suite; + +} // namespace + +int main() { + namespace vectors = webcpp::test::hpke_vectors; + vectors::check_counts(vectors::check_file()); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/messages/Jamfile b/test/messages/Jamfile index 03be8e51..e327509d 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -196,3 +196,15 @@ build-project pem_other_armor ; build-project pem_other_basic_armor ; build-project member_der_on_ed25519 ; build-project foreign_format_on_key ; +build-project hpke_seal_export_only ; +build-project hpke_context_seal_export_only ; +build-project hpke_open_on_sender ; +build-project hpke_receiving_sender_keypair ; +build-project hpke_sending_sender_public_key ; +build-project hpke_psk_after_sender ; +build-project hpke_p256_key_x25519_suite ; +build-project hpke_context_copied ; +build-project hpke_span_as_pre_shared_key ; +build-project hpke_export_length ; +build-project hpke_async_asynchronous_backend ; +build-project hpke_ciphers_type_as_cipher ; diff --git a/test/messages/hpke_async_asynchronous_backend/Jamfile b/test/messages/hpke_async_asynchronous_backend/Jamfile new file mode 100644 index 00000000..d73e7e2b --- /dev/null +++ b/test/messages/hpke_async_asynchronous_backend/Jamfile @@ -0,0 +1,14 @@ +# 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) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic hpke_async_asynchronous_backend : hpke_async_asynchronous_backend.cpp : /webcpp/asio//asio + : native wasip2 wasip3 : alone ; diff --git a/test/messages/hpke_async_asynchronous_backend/hpke_async_asynchronous_backend.cpp b/test/messages/hpke_async_asynchronous_backend/hpke_async_asynchronous_backend.cpp new file mode 100644 index 00000000..7b226590 --- /dev/null +++ b/test/messages/hpke_async_asynchronous_backend/hpke_async_asynchronous_backend.cpp @@ -0,0 +1,57 @@ +// 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::async_begin_sending on a suite whose backend completes by itself (a stand-in whose +// detail::asynchronous_backend_v is true, as part B's browser backend will) stops the build with +// the refusal that says WebCrypto has no HPKE (ruling R8), and with that error alone: no engine is +// reached. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/async.hpp:* {{webcpp::crypto: WebCrypto has no HPKE; the asynchronous HPKE calls run on a native backend.}} +// clang-format on +#include +#include + +#include + +#include + +#include +#include + +namespace { + +/** A backend that completes by itself, as part B's browser backend will. */ +struct stand_in_browser {}; + +} // namespace + +template <> +inline constexpr bool webcpp::crypto::detail::asynchronous_backend_v = true; + +namespace { + +namespace hpke = webcpp::crypto::public_key_encryption::hpke; +using suite = + hpke::suite; + +/** Sets up a sender asynchronously. */ +void sent(webcpp::crypto::curves::x25519::public_key const& recipient_public_key) { + webcpp::asio::io_context context; + hpke::async_begin_sending(context.get_executor(), recipient_public_key, + std::span{}, + [](boost::system::error_code, suite::sender_context_type) {}); +} + +} // namespace + +int main() { + static_cast(&sent); + return 0; +} diff --git a/test/messages/hpke_ciphers_type_as_cipher/Jamfile b/test/messages/hpke_ciphers_type_as_cipher/Jamfile new file mode 100644 index 00000000..d956637c --- /dev/null +++ b/test/messages/hpke_ciphers_type_as_cipher/Jamfile @@ -0,0 +1,14 @@ +# 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) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic hpke_ciphers_type_as_cipher : hpke_ciphers_type_as_cipher.cpp : /third_party//sodium + : native wasip2 wasip3 : alone ; diff --git a/test/messages/hpke_ciphers_type_as_cipher/hpke_ciphers_type_as_cipher.cpp b/test/messages/hpke_ciphers_type_as_cipher/hpke_ciphers_type_as_cipher.cpp new file mode 100644 index 00000000..4ab0d3de --- /dev/null +++ b/test/messages/hpke_ciphers_type_as_cipher/hpke_ciphers_type_as_cipher.cpp @@ -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) + +// A cipher of crypto::ciphers named as an HPKE suite's cipher: the suite's parameter is an +// hpke::cipher tag, which wraps it, so the build stops at the concept suite_cipher (design D2), and +// with that error alone. + +#include +#include +#include + +namespace hpke = webcpp::crypto::public_key_encryption::hpke; + +/** The suite, its cipher a cipher of crypto::ciphers. */ +using wrong_suite = + // expected-error@+1 {{constraints not satisfied for class template 'suite'}} + hpke::suite; + +int main() { + return 0; +} diff --git a/test/messages/hpke_context_copied/Jamfile b/test/messages/hpke_context_copied/Jamfile new file mode 100644 index 00000000..e1c6c0a1 --- /dev/null +++ b/test/messages/hpke_context_copied/Jamfile @@ -0,0 +1,14 @@ +# 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) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic hpke_context_copied : hpke_context_copied.cpp : /third_party//sodium + : native wasip2 wasip3 : alone ; diff --git a/test/messages/hpke_context_copied/hpke_context_copied.cpp b/test/messages/hpke_context_copied/hpke_context_copied.cpp new file mode 100644 index 00000000..4c7dbca2 --- /dev/null +++ b/test/messages/hpke_context_copied/hpke_context_copied.cpp @@ -0,0 +1,38 @@ +// 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) + +// A sender's HPKE context is move-only: a copy would seal two messages under one nonce (design +// D6). The copy stops the build at its line, with that error alone. + +#include +#include + +#include +#include + +namespace hpke = webcpp::crypto::public_key_encryption::hpke; +using suite = hpke::suite; + +namespace { + +/** Copies a sender's context. */ +void copied(suite::sender_context_type const& sender) { + // expected-error@+1 {{call to deleted constructor of}} + suite::sender_context_type const copy = sender; + static_cast(copy); +} + +} // namespace + +int main() { + static_cast(&copied); + return 0; +} + +// clang-format off +// expected-note@webcpp/crypto/public_key_encryption/hpke/context.hpp:* {{'sender_context' has been explicitly marked deleted here}} +// clang-format on diff --git a/test/messages/hpke_context_seal_export_only/Jamfile b/test/messages/hpke_context_seal_export_only/Jamfile new file mode 100644 index 00000000..66af12aa --- /dev/null +++ b/test/messages/hpke_context_seal_export_only/Jamfile @@ -0,0 +1,14 @@ +# 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) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic hpke_context_seal_export_only : hpke_context_seal_export_only.cpp : /third_party//sodium + : native wasip2 wasip3 : alone ; diff --git a/test/messages/hpke_context_seal_export_only/hpke_context_seal_export_only.cpp b/test/messages/hpke_context_seal_export_only/hpke_context_seal_export_only.cpp new file mode 100644 index 00000000..f5a9c7f6 --- /dev/null +++ b/test/messages/hpke_context_seal_export_only/hpke_context_seal_export_only.cpp @@ -0,0 +1,40 @@ +// 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) + +// seal on the sender's context of an export-only HPKE suite stops the build with the message that +// says an export-only suite only exports (design D7), and with that error alone. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/public_key_encryption/hpke/context.hpp:* {{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).}} +// clang-format on +#include +#include + +#include +#include + +namespace hpke = webcpp::crypto::public_key_encryption::hpke; +using suite = hpke::suite; + +namespace { + +/** Seals on an export-only sender's context. */ +void sealed(suite::sender_context_type& sender) { + std::array const plaintext{}; + std::array ciphertext{}; + auto const done = sender.seal({}, plaintext, ciphertext); + static_cast(done); +} + +} // namespace + +int main() { + static_cast(&sealed); + return 0; +} diff --git a/test/messages/hpke_export_length/Jamfile b/test/messages/hpke_export_length/Jamfile new file mode 100644 index 00000000..d6a7546b --- /dev/null +++ b/test/messages/hpke_export_length/Jamfile @@ -0,0 +1,14 @@ +# 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) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic hpke_export_length : hpke_export_length.cpp : /third_party//sodium + : native wasip2 wasip3 : alone ; diff --git a/test/messages/hpke_export_length/hpke_export_length.cpp b/test/messages/hpke_export_length/hpke_export_length.cpp new file mode 100644 index 00000000..f9c7d849 --- /dev/null +++ b/test/messages/hpke_export_length/hpke_export_length.cpp @@ -0,0 +1,41 @@ +// 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) + +// export_secret<0> and export_secret<8161> on an HKDF-SHA256 suite's context, whose longest export +// is 255 * 32 = 8160 bytes (HKDF-SHA512's, 16320), stop the build with the message that gives the +// bounds (design D6), once each, and with those errors alone. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/public_key_encryption/hpke/context.hpp:* 2 {{webcpp::crypto: an HPKE export is 1 to 255 times the key derivation's hash size bytes (Suite::max_export_size).}} +// clang-format on +#include +#include + +#include +#include + +namespace hpke = webcpp::crypto::public_key_encryption::hpke; +using suite = hpke::suite; + +namespace { + +/** Exports nothing, then too much. */ +void exported(suite::recipient_context_type const& recipient) { + auto const none = recipient.export_secret<0>({}); + auto const too_long = recipient.export_secret({}); + static_cast(none); + static_cast(too_long); +} + +} // namespace + +int main() { + static_cast(&exported); + return 0; +} diff --git a/test/messages/hpke_open_on_sender/Jamfile b/test/messages/hpke_open_on_sender/Jamfile new file mode 100644 index 00000000..6cb1e340 --- /dev/null +++ b/test/messages/hpke_open_on_sender/Jamfile @@ -0,0 +1,14 @@ +# 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) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic hpke_open_on_sender : hpke_open_on_sender.cpp : /third_party//sodium + : native wasip2 wasip3 : alone ; diff --git a/test/messages/hpke_open_on_sender/hpke_open_on_sender.cpp b/test/messages/hpke_open_on_sender/hpke_open_on_sender.cpp new file mode 100644 index 00000000..dfe186ed --- /dev/null +++ b/test/messages/hpke_open_on_sender/hpke_open_on_sender.cpp @@ -0,0 +1,36 @@ +// 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) + +// A sender's HPKE context has no open (RFC 9180 section 5.2: a sender context MUST NOT decrypt): +// the call stops the build at its line, with that error alone. + +#include +#include + +#include +#include + +namespace hpke = webcpp::crypto::public_key_encryption::hpke; +using suite = hpke::suite; + +namespace { + +/** Opens on a sender's context. */ +void opened(suite::sender_context_type& sender) { + std::array const ciphertext{}; + std::array plaintext{}; + // expected-error@+1 {{no member named 'open' in}} + auto const done = sender.open({}, ciphertext, plaintext); + static_cast(done); +} + +} // namespace + +int main() { + static_cast(&opened); + return 0; +} diff --git a/test/messages/hpke_p256_key_x25519_suite/Jamfile b/test/messages/hpke_p256_key_x25519_suite/Jamfile new file mode 100644 index 00000000..6b6f9d58 --- /dev/null +++ b/test/messages/hpke_p256_key_x25519_suite/Jamfile @@ -0,0 +1,14 @@ +# 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) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic hpke_p256_key_x25519_suite : hpke_p256_key_x25519_suite.cpp : /third_party//sodium /third_party//bearssl + : native wasip2 wasip3 : alone ; diff --git a/test/messages/hpke_p256_key_x25519_suite/hpke_p256_key_x25519_suite.cpp b/test/messages/hpke_p256_key_x25519_suite/hpke_p256_key_x25519_suite.cpp new file mode 100644 index 00000000..02f5a4a0 --- /dev/null +++ b/test/messages/hpke_p256_key_x25519_suite/hpke_p256_key_x25519_suite.cpp @@ -0,0 +1,42 @@ +// 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) + +// A P-256 public key given to an X25519 suite's begin_sending finds none of its four argument +// lists: the build stops with the message listing them (design B2), and with that error alone. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/public_key_encryption/hpke.hpp:* {{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}.}} +// clang-format on +#include +#include +#include +#include + +#include +#include +#include + +namespace hpke = webcpp::crypto::public_key_encryption::hpke; +using suite = hpke::suite; + +namespace { + +/** Sets up an X25519 sender with a P-256 key. */ +void sent(webcpp::crypto::curves::p256::public_key const& recipient_public_key) { + std::span const info{}; + auto const context = suite::begin_sending(recipient_public_key, info); + static_cast(context); +} + +} // namespace + +int main() { + static_cast(&sent); + return 0; +} diff --git a/test/messages/hpke_psk_after_sender/Jamfile b/test/messages/hpke_psk_after_sender/Jamfile new file mode 100644 index 00000000..b8346f37 --- /dev/null +++ b/test/messages/hpke_psk_after_sender/Jamfile @@ -0,0 +1,14 @@ +# 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) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic hpke_psk_after_sender : hpke_psk_after_sender.cpp : /third_party//sodium + : native wasip2 wasip3 : alone ; diff --git a/test/messages/hpke_psk_after_sender/hpke_psk_after_sender.cpp b/test/messages/hpke_psk_after_sender/hpke_psk_after_sender.cpp new file mode 100644 index 00000000..0f170ec4 --- /dev/null +++ b/test/messages/hpke_psk_after_sender/hpke_psk_after_sender.cpp @@ -0,0 +1,42 @@ +// 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) + +// begin_sending in auth_psk mode with the pre-shared key after the sender's key pair: RFC 9180's +// order (SetupAuthPSKS(pkR, info, psk, psk_id, skS)) is the only one, so the build stops with the +// message listing the four argument lists (design B2), and with that error alone. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/public_key_encryption/hpke.hpp:* {{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}.}} +// clang-format on +#include +#include + +#include +#include +#include + +namespace hpke = webcpp::crypto::public_key_encryption::hpke; +using suite = hpke::suite; + +namespace { + +/** Sets up a sender with its arguments out of order. */ +void sent(suite::public_key_type const& recipient_public_key, + suite::sender_keypair_type const& sender, hpke::pre_shared_key const& pre_shared_key) { + std::span const info{}; + auto const context = suite::begin_sending(recipient_public_key, info, sender, pre_shared_key); + static_cast(context); +} + +} // namespace + +int main() { + static_cast(&sent); + return 0; +} diff --git a/test/messages/hpke_receiving_sender_keypair/Jamfile b/test/messages/hpke_receiving_sender_keypair/Jamfile new file mode 100644 index 00000000..f0227dd8 --- /dev/null +++ b/test/messages/hpke_receiving_sender_keypair/Jamfile @@ -0,0 +1,14 @@ +# 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) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic hpke_receiving_sender_keypair : hpke_receiving_sender_keypair.cpp : /third_party//sodium + : native wasip2 wasip3 : alone ; diff --git a/test/messages/hpke_receiving_sender_keypair/hpke_receiving_sender_keypair.cpp b/test/messages/hpke_receiving_sender_keypair/hpke_receiving_sender_keypair.cpp new file mode 100644 index 00000000..1145f649 --- /dev/null +++ b/test/messages/hpke_receiving_sender_keypair/hpke_receiving_sender_keypair.cpp @@ -0,0 +1,43 @@ +// 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) + +// begin_receiving given the sender's key pair, where auth mode takes the sender's public key, finds +// none of its four argument lists: the build stops with the message listing them (design B2), and +// with that error alone. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/public_key_encryption/hpke.hpp:* {{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}.}} +// clang-format on +#include +#include + +#include +#include +#include + +namespace hpke = webcpp::crypto::public_key_encryption::hpke; +using suite = hpke::suite; + +namespace { + +/** Sets up a recipient with the sender's key pair. */ +void received(suite::encapsulated_key_type const& encapsulated_key, + suite::recipient_keypair_type const& recipient, + suite::sender_keypair_type const& sender) { + std::span const info{}; + auto const context = suite::begin_receiving(encapsulated_key, recipient, info, sender); + static_cast(context); +} + +} // namespace + +int main() { + static_cast(&received); + return 0; +} diff --git a/test/messages/hpke_seal_export_only/Jamfile b/test/messages/hpke_seal_export_only/Jamfile new file mode 100644 index 00000000..172dbd98 --- /dev/null +++ b/test/messages/hpke_seal_export_only/Jamfile @@ -0,0 +1,14 @@ +# 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) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic hpke_seal_export_only : hpke_seal_export_only.cpp : /third_party//sodium + : native wasip2 wasip3 : alone ; diff --git a/test/messages/hpke_seal_export_only/hpke_seal_export_only.cpp b/test/messages/hpke_seal_export_only/hpke_seal_export_only.cpp new file mode 100644 index 00000000..284449bc --- /dev/null +++ b/test/messages/hpke_seal_export_only/hpke_seal_export_only.cpp @@ -0,0 +1,43 @@ +// 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) + +// The single-shot seal of an export-only HPKE suite stops the build with the message that says an +// export-only suite only exports (design D7), and with that error alone. The call is in a function +// that is compiled, never run. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/public_key_encryption/hpke.hpp:* {{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).}} +// clang-format on +#include +#include + +#include +#include +#include + +namespace hpke = webcpp::crypto::public_key_encryption::hpke; +using suite = hpke::suite; + +namespace { + +/** Seals with an export-only suite. */ +void sealed(suite::public_key_type const& recipient_public_key) { + std::span const info{}; + std::array const plaintext{}; + std::array ciphertext{}; + auto const key = suite::seal(recipient_public_key, info, info, plaintext, ciphertext); + static_cast(key); +} + +} // namespace + +int main() { + static_cast(&sealed); + return 0; +} diff --git a/test/messages/hpke_sending_sender_public_key/Jamfile b/test/messages/hpke_sending_sender_public_key/Jamfile new file mode 100644 index 00000000..3f6c6cf7 --- /dev/null +++ b/test/messages/hpke_sending_sender_public_key/Jamfile @@ -0,0 +1,14 @@ +# 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) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic hpke_sending_sender_public_key : hpke_sending_sender_public_key.cpp : /third_party//sodium + : native wasip2 wasip3 : alone ; diff --git a/test/messages/hpke_sending_sender_public_key/hpke_sending_sender_public_key.cpp b/test/messages/hpke_sending_sender_public_key/hpke_sending_sender_public_key.cpp new file mode 100644 index 00000000..3106048c --- /dev/null +++ b/test/messages/hpke_sending_sender_public_key/hpke_sending_sender_public_key.cpp @@ -0,0 +1,42 @@ +// 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) + +// begin_sending given a public key where auth mode takes the sender's key pair finds none of its +// four argument lists: the build stops with the message listing them (design B2), and with that +// error alone. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/public_key_encryption/hpke.hpp:* {{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}.}} +// clang-format on +#include +#include + +#include +#include +#include + +namespace hpke = webcpp::crypto::public_key_encryption::hpke; +using suite = hpke::suite; + +namespace { + +/** Sets up a sender with a public key as the sender's key. */ +void sent(suite::public_key_type const& recipient_public_key, + suite::public_key_type const& sender_public_key) { + std::span const info{}; + auto const context = suite::begin_sending(recipient_public_key, info, sender_public_key); + static_cast(context); +} + +} // namespace + +int main() { + static_cast(&sent); + return 0; +} diff --git a/test/messages/hpke_span_as_pre_shared_key/Jamfile b/test/messages/hpke_span_as_pre_shared_key/Jamfile new file mode 100644 index 00000000..ac2c1b07 --- /dev/null +++ b/test/messages/hpke_span_as_pre_shared_key/Jamfile @@ -0,0 +1,14 @@ +# 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) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic hpke_span_as_pre_shared_key : hpke_span_as_pre_shared_key.cpp : /third_party//sodium + : native wasip2 wasip3 : alone ; diff --git a/test/messages/hpke_span_as_pre_shared_key/hpke_span_as_pre_shared_key.cpp b/test/messages/hpke_span_as_pre_shared_key/hpke_span_as_pre_shared_key.cpp new file mode 100644 index 00000000..cb14f78d --- /dev/null +++ b/test/messages/hpke_span_as_pre_shared_key/hpke_span_as_pre_shared_key.cpp @@ -0,0 +1,43 @@ +// 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) + +// A single span where psk mode takes the pre-shared key and its id: the span does not convert to +// hpke::pre_shared_key, so begin_sending finds none of its four argument lists and the build stops +// with the message listing them (design B2), and with that error alone. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/public_key_encryption/hpke.hpp:* {{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}.}} +// clang-format on +#include +#include + +#include +#include +#include + +namespace hpke = webcpp::crypto::public_key_encryption::hpke; +using suite = hpke::suite; + +namespace { + +/** Sets up a sender with a bare key. */ +void sent(suite::public_key_type const& recipient_public_key) { + std::span const info{}; + std::array const key{}; + auto const context = + suite::begin_sending(recipient_public_key, info, std::span(key)); + static_cast(context); +} + +} // namespace + +int main() { + static_cast(&sent); + return 0; +} diff --git a/test/msvc/Jamfile b/test/msvc/Jamfile index 51b22431..cc9d18ee 100644 --- a/test/msvc/Jamfile +++ b/test/msvc/Jamfile @@ -213,3 +213,15 @@ build-project wipe_removed ; build-project x25519_asynchronous_backend ; build-project x25519_constructions_other_backend ; build-project x25519_free_functions_removed ; +build-project hpke_async_asynchronous_backend ; +build-project hpke_ciphers_type_as_cipher ; +build-project hpke_context_copied ; +build-project hpke_context_seal_export_only ; +build-project hpke_export_length ; +build-project hpke_open_on_sender ; +build-project hpke_p256_key_x25519_suite ; +build-project hpke_psk_after_sender ; +build-project hpke_receiving_sender_keypair ; +build-project hpke_seal_export_only ; +build-project hpke_sending_sender_public_key ; +build-project hpke_span_as_pre_shared_key ; diff --git a/test/msvc/hpke_async_asynchronous_backend/Jamfile b/test/msvc/hpke_async_asynchronous_backend/Jamfile new file mode 100644 index 00000000..2ca0f59a --- /dev/null +++ b/test/msvc/hpke_async_asynchronous_backend/Jamfile @@ -0,0 +1,10 @@ +# 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) + +import webcpp ; + +webcpp.compile-fail hpke_async_asynchronous_backend : app.cpp + : /webcpp/crypto//crypto /webcpp/asio//asio : native ; diff --git a/test/msvc/hpke_async_asynchronous_backend/app.cpp b/test/msvc/hpke_async_asynchronous_backend/app.cpp new file mode 100644 index 00000000..a1a778c2 --- /dev/null +++ b/test/msvc/hpke_async_asynchronous_backend/app.cpp @@ -0,0 +1,53 @@ +// 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::async_begin_sending on a suite whose backend completes by itself (a stand-in whose +// detail::asynchronous_backend_v is true, as part B's browser backend will) stops the build with +// the refusal that says WebCrypto has no HPKE (ruling R8): no engine is reached. +// On MSVC the compile fails; the text is checked on clang, in +// test/messages/hpke_async_asynchronous_backend. + +#include +#include + +#include + +#include + +#include +#include + +namespace { + +/** A backend that completes by itself, as part B's browser backend will. */ +struct stand_in_browser {}; + +} // namespace + +template <> +inline constexpr bool webcpp::crypto::detail::asynchronous_backend_v = true; + +namespace { + +namespace hpke = webcpp::crypto::public_key_encryption::hpke; +using suite = + hpke::suite; + +/** Sets up a sender asynchronously. */ +void sent(webcpp::crypto::curves::x25519::public_key const& recipient_public_key) { + webcpp::asio::io_context context; + hpke::async_begin_sending(context.get_executor(), recipient_public_key, + std::span{}, + [](boost::system::error_code, suite::sender_context_type) {}); +} + +} // namespace + +int main() { + static_cast(&sent); + return 0; +} diff --git a/test/msvc/hpke_ciphers_type_as_cipher/Jamfile b/test/msvc/hpke_ciphers_type_as_cipher/Jamfile new file mode 100644 index 00000000..9151da3f --- /dev/null +++ b/test/msvc/hpke_ciphers_type_as_cipher/Jamfile @@ -0,0 +1,10 @@ +# 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) + +import webcpp ; + +webcpp.compile-fail hpke_ciphers_type_as_cipher : app.cpp + : /webcpp/crypto//crypto /third_party//sodium : native ; diff --git a/test/msvc/hpke_ciphers_type_as_cipher/app.cpp b/test/msvc/hpke_ciphers_type_as_cipher/app.cpp new file mode 100644 index 00000000..e8e354b9 --- /dev/null +++ b/test/msvc/hpke_ciphers_type_as_cipher/app.cpp @@ -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) + +// A cipher of crypto::ciphers named as an HPKE suite's cipher: the suite's parameter is an +// hpke::cipher tag, which wraps it, so the build stops at the concept suite_cipher (design D2). +// On MSVC the compile fails; the text is checked on clang, in +// test/messages/hpke_ciphers_type_as_cipher. + +#include +#include +#include + +namespace hpke = webcpp::crypto::public_key_encryption::hpke; + +/** The suite, its cipher a cipher of crypto::ciphers. */ +using wrong_suite = + hpke::suite; + +int main() { + return 0; +} diff --git a/test/msvc/hpke_context_copied/Jamfile b/test/msvc/hpke_context_copied/Jamfile new file mode 100644 index 00000000..265cb517 --- /dev/null +++ b/test/msvc/hpke_context_copied/Jamfile @@ -0,0 +1,10 @@ +# 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) + +import webcpp ; + +webcpp.compile-fail hpke_context_copied : app.cpp + : /webcpp/crypto//crypto /third_party//sodium : native ; diff --git a/test/msvc/hpke_context_copied/app.cpp b/test/msvc/hpke_context_copied/app.cpp new file mode 100644 index 00000000..9b9e6067 --- /dev/null +++ b/test/msvc/hpke_context_copied/app.cpp @@ -0,0 +1,34 @@ +// 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) + +// A sender's HPKE context is move-only: a copy would seal two messages under one nonce (design +// D6). The copy stops the build at its line. +// On MSVC the compile fails; the text is checked on clang, in test/messages/hpke_context_copied. + +#include +#include + +#include +#include + +namespace hpke = webcpp::crypto::public_key_encryption::hpke; +using suite = hpke::suite; + +namespace { + +/** Copies a sender's context. */ +void copied(suite::sender_context_type const& sender) { + suite::sender_context_type const copy = sender; + static_cast(copy); +} + +} // namespace + +int main() { + static_cast(&copied); + return 0; +} diff --git a/test/msvc/hpke_context_seal_export_only/Jamfile b/test/msvc/hpke_context_seal_export_only/Jamfile new file mode 100644 index 00000000..5b1701ba --- /dev/null +++ b/test/msvc/hpke_context_seal_export_only/Jamfile @@ -0,0 +1,10 @@ +# 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) + +import webcpp ; + +webcpp.compile-fail hpke_context_seal_export_only : app.cpp + : /webcpp/crypto//crypto /third_party//sodium : native ; diff --git a/test/msvc/hpke_context_seal_export_only/app.cpp b/test/msvc/hpke_context_seal_export_only/app.cpp new file mode 100644 index 00000000..f7848830 --- /dev/null +++ b/test/msvc/hpke_context_seal_export_only/app.cpp @@ -0,0 +1,37 @@ +// 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) + +// seal on the sender's context of an export-only HPKE suite stops the build with the message that +// says an export-only suite only exports (design D7). +// On MSVC the compile fails; the text is checked on clang, in +// test/messages/hpke_context_seal_export_only. + +#include +#include + +#include +#include + +namespace hpke = webcpp::crypto::public_key_encryption::hpke; +using suite = hpke::suite; + +namespace { + +/** Seals on an export-only sender's context. */ +void sealed(suite::sender_context_type& sender) { + std::array const plaintext{}; + std::array ciphertext{}; + auto const done = sender.seal({}, plaintext, ciphertext); + static_cast(done); +} + +} // namespace + +int main() { + static_cast(&sealed); + return 0; +} diff --git a/test/msvc/hpke_export_length/Jamfile b/test/msvc/hpke_export_length/Jamfile new file mode 100644 index 00000000..8e4502d9 --- /dev/null +++ b/test/msvc/hpke_export_length/Jamfile @@ -0,0 +1,10 @@ +# 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) + +import webcpp ; + +webcpp.compile-fail hpke_export_length : app.cpp + : /webcpp/crypto//crypto /third_party//sodium : native ; diff --git a/test/msvc/hpke_export_length/app.cpp b/test/msvc/hpke_export_length/app.cpp new file mode 100644 index 00000000..3a434175 --- /dev/null +++ b/test/msvc/hpke_export_length/app.cpp @@ -0,0 +1,37 @@ +// 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) + +// export_secret<0> and export_secret<8161> on an HKDF-SHA256 suite's context, whose longest export +// is 255 * 32 = 8160 bytes (HKDF-SHA512's, 16320), stop the build with the message that gives the +// bounds (design D6), once each. +// On MSVC the compile fails; the text is checked on clang, in test/messages/hpke_export_length. + +#include +#include + +#include +#include + +namespace hpke = webcpp::crypto::public_key_encryption::hpke; +using suite = hpke::suite; + +namespace { + +/** Exports nothing, then too much. */ +void exported(suite::recipient_context_type const& recipient) { + auto const none = recipient.export_secret<0>({}); + auto const too_long = recipient.export_secret({}); + static_cast(none); + static_cast(too_long); +} + +} // namespace + +int main() { + static_cast(&exported); + return 0; +} diff --git a/test/msvc/hpke_open_on_sender/Jamfile b/test/msvc/hpke_open_on_sender/Jamfile new file mode 100644 index 00000000..d9e2bec6 --- /dev/null +++ b/test/msvc/hpke_open_on_sender/Jamfile @@ -0,0 +1,10 @@ +# 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) + +import webcpp ; + +webcpp.compile-fail hpke_open_on_sender : app.cpp + : /webcpp/crypto//crypto /third_party//sodium : native ; diff --git a/test/msvc/hpke_open_on_sender/app.cpp b/test/msvc/hpke_open_on_sender/app.cpp new file mode 100644 index 00000000..b7c8060a --- /dev/null +++ b/test/msvc/hpke_open_on_sender/app.cpp @@ -0,0 +1,36 @@ +// 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) + +// A sender's HPKE context has no open (RFC 9180 section 5.2: a sender context MUST NOT decrypt): +// the call stops the build at its line. +// On MSVC the compile fails; the text is checked on clang, in test/messages/hpke_open_on_sender. + +#include +#include + +#include +#include + +namespace hpke = webcpp::crypto::public_key_encryption::hpke; +using suite = hpke::suite; + +namespace { + +/** Opens on a sender's context. */ +void opened(suite::sender_context_type& sender) { + std::array const ciphertext{}; + std::array plaintext{}; + auto const done = sender.open({}, ciphertext, plaintext); + static_cast(done); +} + +} // namespace + +int main() { + static_cast(&opened); + return 0; +} diff --git a/test/msvc/hpke_p256_key_x25519_suite/Jamfile b/test/msvc/hpke_p256_key_x25519_suite/Jamfile new file mode 100644 index 00000000..ff67653d --- /dev/null +++ b/test/msvc/hpke_p256_key_x25519_suite/Jamfile @@ -0,0 +1,10 @@ +# 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) + +import webcpp ; + +webcpp.compile-fail hpke_p256_key_x25519_suite : app.cpp + : /webcpp/crypto//crypto /third_party//sodium /third_party//bearssl : native ; diff --git a/test/msvc/hpke_p256_key_x25519_suite/app.cpp b/test/msvc/hpke_p256_key_x25519_suite/app.cpp new file mode 100644 index 00000000..e930cb81 --- /dev/null +++ b/test/msvc/hpke_p256_key_x25519_suite/app.cpp @@ -0,0 +1,39 @@ +// 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) + +// A P-256 public key given to an X25519 suite's begin_sending finds none of its four argument +// lists: the build stops with the message listing them (design B2). +// On MSVC the compile fails; the text is checked on clang, in +// test/messages/hpke_p256_key_x25519_suite. + +#include +#include +#include +#include + +#include +#include +#include + +namespace hpke = webcpp::crypto::public_key_encryption::hpke; +using suite = hpke::suite; + +namespace { + +/** Sets up an X25519 sender with a P-256 key. */ +void sent(webcpp::crypto::curves::p256::public_key const& recipient_public_key) { + std::span const info{}; + auto const context = suite::begin_sending(recipient_public_key, info); + static_cast(context); +} + +} // namespace + +int main() { + static_cast(&sent); + return 0; +} diff --git a/test/msvc/hpke_psk_after_sender/Jamfile b/test/msvc/hpke_psk_after_sender/Jamfile new file mode 100644 index 00000000..7c60fe4e --- /dev/null +++ b/test/msvc/hpke_psk_after_sender/Jamfile @@ -0,0 +1,10 @@ +# 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) + +import webcpp ; + +webcpp.compile-fail hpke_psk_after_sender : app.cpp + : /webcpp/crypto//crypto /third_party//sodium : native ; diff --git a/test/msvc/hpke_psk_after_sender/app.cpp b/test/msvc/hpke_psk_after_sender/app.cpp new file mode 100644 index 00000000..87e2dd3e --- /dev/null +++ b/test/msvc/hpke_psk_after_sender/app.cpp @@ -0,0 +1,38 @@ +// 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) + +// begin_sending in auth_psk mode with the pre-shared key after the sender's key pair: RFC 9180's +// order (SetupAuthPSKS(pkR, info, psk, psk_id, skS)) is the only one, so the build stops with the +// message listing the four argument lists (design B2). +// On MSVC the compile fails; the text is checked on clang, in test/messages/hpke_psk_after_sender. + +#include +#include + +#include +#include +#include + +namespace hpke = webcpp::crypto::public_key_encryption::hpke; +using suite = hpke::suite; + +namespace { + +/** Sets up a sender with its arguments out of order. */ +void sent(suite::public_key_type const& recipient_public_key, + suite::sender_keypair_type const& sender, hpke::pre_shared_key const& pre_shared_key) { + std::span const info{}; + auto const context = suite::begin_sending(recipient_public_key, info, sender, pre_shared_key); + static_cast(context); +} + +} // namespace + +int main() { + static_cast(&sent); + return 0; +} diff --git a/test/msvc/hpke_receiving_sender_keypair/Jamfile b/test/msvc/hpke_receiving_sender_keypair/Jamfile new file mode 100644 index 00000000..b62a18e3 --- /dev/null +++ b/test/msvc/hpke_receiving_sender_keypair/Jamfile @@ -0,0 +1,10 @@ +# 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) + +import webcpp ; + +webcpp.compile-fail hpke_receiving_sender_keypair : app.cpp + : /webcpp/crypto//crypto /third_party//sodium : native ; diff --git a/test/msvc/hpke_receiving_sender_keypair/app.cpp b/test/msvc/hpke_receiving_sender_keypair/app.cpp new file mode 100644 index 00000000..e8f696a4 --- /dev/null +++ b/test/msvc/hpke_receiving_sender_keypair/app.cpp @@ -0,0 +1,39 @@ +// 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) + +// begin_receiving given the sender's key pair, where auth mode takes the sender's public key, finds +// none of its four argument lists: the build stops with the message listing them (design B2). +// On MSVC the compile fails; the text is checked on clang, in +// test/messages/hpke_receiving_sender_keypair. + +#include +#include + +#include +#include +#include + +namespace hpke = webcpp::crypto::public_key_encryption::hpke; +using suite = hpke::suite; + +namespace { + +/** Sets up a recipient with the sender's key pair. */ +void received(suite::encapsulated_key_type const& encapsulated_key, + suite::recipient_keypair_type const& recipient, + suite::sender_keypair_type const& sender) { + std::span const info{}; + auto const context = suite::begin_receiving(encapsulated_key, recipient, info, sender); + static_cast(context); +} + +} // namespace + +int main() { + static_cast(&received); + return 0; +} diff --git a/test/msvc/hpke_seal_export_only/Jamfile b/test/msvc/hpke_seal_export_only/Jamfile new file mode 100644 index 00000000..0d7b4289 --- /dev/null +++ b/test/msvc/hpke_seal_export_only/Jamfile @@ -0,0 +1,10 @@ +# 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) + +import webcpp ; + +webcpp.compile-fail hpke_seal_export_only : app.cpp + : /webcpp/crypto//crypto /third_party//sodium : native ; diff --git a/test/msvc/hpke_seal_export_only/app.cpp b/test/msvc/hpke_seal_export_only/app.cpp new file mode 100644 index 00000000..5825817a --- /dev/null +++ b/test/msvc/hpke_seal_export_only/app.cpp @@ -0,0 +1,39 @@ +// 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) + +// The single-shot seal of an export-only HPKE suite stops the build with the message that says an +// export-only suite only exports (design D7). The call is in a function that is compiled, never +// run. +// On MSVC the compile fails; the text is checked on clang, in test/messages/hpke_seal_export_only. + +#include +#include + +#include +#include +#include + +namespace hpke = webcpp::crypto::public_key_encryption::hpke; +using suite = hpke::suite; + +namespace { + +/** Seals with an export-only suite. */ +void sealed(suite::public_key_type const& recipient_public_key) { + std::span const info{}; + std::array const plaintext{}; + std::array ciphertext{}; + auto const key = suite::seal(recipient_public_key, info, info, plaintext, ciphertext); + static_cast(key); +} + +} // namespace + +int main() { + static_cast(&sealed); + return 0; +} diff --git a/test/msvc/hpke_sending_sender_public_key/Jamfile b/test/msvc/hpke_sending_sender_public_key/Jamfile new file mode 100644 index 00000000..56a8ff6e --- /dev/null +++ b/test/msvc/hpke_sending_sender_public_key/Jamfile @@ -0,0 +1,10 @@ +# 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) + +import webcpp ; + +webcpp.compile-fail hpke_sending_sender_public_key : app.cpp + : /webcpp/crypto//crypto /third_party//sodium : native ; diff --git a/test/msvc/hpke_sending_sender_public_key/app.cpp b/test/msvc/hpke_sending_sender_public_key/app.cpp new file mode 100644 index 00000000..48f31c1c --- /dev/null +++ b/test/msvc/hpke_sending_sender_public_key/app.cpp @@ -0,0 +1,38 @@ +// 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) + +// begin_sending given a public key where auth mode takes the sender's key pair finds none of its +// four argument lists: the build stops with the message listing them (design B2). +// On MSVC the compile fails; the text is checked on clang, in +// test/messages/hpke_sending_sender_public_key. + +#include +#include + +#include +#include +#include + +namespace hpke = webcpp::crypto::public_key_encryption::hpke; +using suite = hpke::suite; + +namespace { + +/** Sets up a sender with a public key as the sender's key. */ +void sent(suite::public_key_type const& recipient_public_key, + suite::public_key_type const& sender_public_key) { + std::span const info{}; + auto const context = suite::begin_sending(recipient_public_key, info, sender_public_key); + static_cast(context); +} + +} // namespace + +int main() { + static_cast(&sent); + return 0; +} diff --git a/test/msvc/hpke_span_as_pre_shared_key/Jamfile b/test/msvc/hpke_span_as_pre_shared_key/Jamfile new file mode 100644 index 00000000..68c84092 --- /dev/null +++ b/test/msvc/hpke_span_as_pre_shared_key/Jamfile @@ -0,0 +1,10 @@ +# 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) + +import webcpp ; + +webcpp.compile-fail hpke_span_as_pre_shared_key : app.cpp + : /webcpp/crypto//crypto /third_party//sodium : native ; diff --git a/test/msvc/hpke_span_as_pre_shared_key/app.cpp b/test/msvc/hpke_span_as_pre_shared_key/app.cpp new file mode 100644 index 00000000..f471f4e8 --- /dev/null +++ b/test/msvc/hpke_span_as_pre_shared_key/app.cpp @@ -0,0 +1,40 @@ +// 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) + +// A single span where psk mode takes the pre-shared key and its id: the span does not convert to +// hpke::pre_shared_key, so begin_sending finds none of its four argument lists and the build stops +// with the message listing them (design B2). +// On MSVC the compile fails; the text is checked on clang, in +// test/messages/hpke_span_as_pre_shared_key. + +#include +#include + +#include +#include +#include + +namespace hpke = webcpp::crypto::public_key_encryption::hpke; +using suite = hpke::suite; + +namespace { + +/** Sets up a sender with a bare key. */ +void sent(suite::public_key_type const& recipient_public_key) { + std::span const info{}; + std::array const key{}; + auto const context = + suite::begin_sending(recipient_public_key, info, std::span(key)); + static_cast(context); +} + +} // namespace + +int main() { + static_cast(&sent); + return 0; +} diff --git a/test/support/hpke_coverage.hpp b/test/support/hpke_coverage.hpp new file mode 100644 index 00000000..fb5b772e --- /dev/null +++ b/test/support/hpke_coverage.hpp @@ -0,0 +1,489 @@ +// 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) + +// The timing coverage of HPKE's public functions on a suite's backends (design D10, B6): each +// enters its own webcpp::secure::timing_guard first and leaves the thread's DIT as it found it, +// with valid input and with input refused before the backend: the suite's begin_sending and +// begin_receiving in every mode, seal and open in every mode, derive_from_seed (the suite's and +// the key encapsulation's), the contexts' seal, open and both export_secret forms, the free forms +// of hpke, and the asynchronous forms, member and free. A program that includes it includes +// support/timing_seam.hpp before any webcpp header, then support/timing_coverage.hpp. + +#ifndef WEBCPP_TEST_CRYPTO_SUPPORT_HPKE_COVERAGE_HPP +#define WEBCPP_TEST_CRYPTO_SUPPORT_HPKE_COVERAGE_HPP + +#include "timing_coverage.hpp" + +#include +#include +#include + +#include + +#include +#include + +#include +#include +#include +#include +#include + +namespace webcpp::test { + +/** + * A completion handler that counts its calls: a class, never a lambda, whose name in a function's + * template arguments would hide the function from `names_function`. + */ +struct hpke_completion_counter { + /** The count, incremented by each completion. */ + int* completions = nullptr; + + /** Counts a completion, whatever its arguments. */ + template + void operator()(Arguments&&... /*arguments*/) const { + ++*completions; + } +}; + +/** + * The inputs and buffers every HPKE check of a suite shares. + * + * @tparam Suite The suite. + */ +template +struct hpke_coverage_data { + /** The recipient's seed. */ + std::array recipient_seed{1}; + /** The sender's seed. */ + std::array sender_seed{2}; + /** A seed one byte short. */ + std::span short_seed = std::span(recipient_seed).first(31); + /** The application info. */ + std::vector info{'i', 'n', 'f', 'o'}; + /** The pre-shared key. */ + std::vector psk_key = std::vector(32, 0x42); + /** Its id. */ + std::vector psk_id{'i', 'd'}; + /** Both. */ + webcpp::crypto::public_key_encryption::hpke::pre_shared_key pre_shared_key{ + .key = psk_key, + .id = psk_id, + }; + /** A key one byte short. */ + webcpp::crypto::public_key_encryption::hpke::pre_shared_key short_psk{ + .key = std::span(psk_key).first(31), + .id = psk_id, + }; + /** The message. */ + std::vector plaintext{'p', 't'}; + /** Its ciphertext. */ + std::vector ciphertext = + std::vector(plaintext.size() + Suite::tag_size); + /** The message opened. */ + std::vector opened = std::vector(plaintext.size()); + /** An export. */ + std::array exported{}; +}; + +/** + * `derive_from_seed`: the suite's, the key encapsulation's and the free form. + * + * @tparam Suite The suite. + * @param data The shared inputs and buffers. + * @param on ` on `, which ends each name. + */ +template +void cover_hpke_keys(hpke_coverage_data& data, std::string const& on) { + namespace hpke = webcpp::crypto::public_key_encryption::hpke; + using kem = Suite::key_encapsulation_type; + covered("hpke derive_from_seed" + on, "suite::derive_from_seed", + [&] { BOOST_TEST(Suite::derive_from_seed(data.recipient_seed).has_value()); }); + covered("hpke derive_from_seed of a short seed" + on, "suite::derive_from_seed", [&] { + BOOST_TEST(Suite::derive_from_seed(data.short_seed).error() == + webcpp::crypto::error::invalid_input_size); + }); + std::string const kem_name = kem::id == 0x0020 ? "x25519_hkdf_sha256" : "p256_hkdf_sha256"; + covered("hpke key encapsulation's derive_from_seed" + on, kem_name + "::derive_from_seed", [&] { + BOOST_TEST( + kem::template derive_from_seed( + data.recipient_seed) + .has_value()); + }); + covered("hpke::derive_from_seed" + on, "hpke::derive_from_seed", + [&] { BOOST_TEST(hpke::derive_from_seed(data.recipient_seed).has_value()); }); +} + +/** + * `begin_receiving` in every mode, and its free form. + * + * @tparam Suite The suite. + * @param data The shared inputs and buffers. + * @param recipient The recipient's key pair. + * @param sender_keypair The sender's key pair. + * @param sender_public_key The sender's public key. + * @param on ` on `, which ends each name. + */ +template +void cover_hpke_receiving(hpke_coverage_data& data, + typename Suite::recipient_keypair_type const& recipient, + typename Suite::sender_keypair_type const& sender_keypair, + typename Suite::public_key_type const& sender_public_key, + std::string const& on) { + namespace hpke = webcpp::crypto::public_key_encryption::hpke; + auto const recipient_public_key = recipient.public_key(); + if (!BOOST_TEST(recipient_public_key.has_value())) { + return; + } + auto const sender = + Suite::begin_sending(*recipient_public_key, data.info, data.pre_shared_key, sender_keypair); + if (!BOOST_TEST(sender.has_value())) { + return; + } + auto const encapsulated_key = sender->encapsulated_key(); + covered("hpke begin_receiving, base" + on, "suite::begin_receiving", [&] { + BOOST_TEST(Suite::begin_receiving(encapsulated_key, recipient, data.info).has_value()); + }); + covered("hpke begin_receiving, psk" + on, "suite::begin_receiving", [&] { + BOOST_TEST( + Suite::begin_receiving(encapsulated_key, recipient, data.info, data.pre_shared_key) + .has_value()); + }); + covered("hpke begin_receiving, auth" + on, "suite::begin_receiving", [&] { + BOOST_TEST(Suite::begin_receiving(encapsulated_key, recipient, data.info, sender_public_key) + .has_value()); + }); + covered("hpke begin_receiving, auth_psk" + on, "suite::begin_receiving", [&] { + BOOST_TEST(Suite::begin_receiving(encapsulated_key, recipient, data.info, + data.pre_shared_key, sender_public_key) + .has_value()); + }); + covered("hpke begin_receiving with a short pre-shared key" + on, "suite::begin_receiving", [&] { + BOOST_TEST(Suite::begin_receiving(encapsulated_key, recipient, data.info, data.short_psk) + .error() == webcpp::crypto::error::invalid_key_size); + }); + covered("hpke::begin_receiving" + on, "hpke::begin_receiving", [&] { + BOOST_TEST( + hpke::begin_receiving(encapsulated_key, recipient, data.info).has_value()); + }); +} + +/** + * `begin_sending` in every mode and its free form, then `begin_receiving`'s. + * + * @tparam Suite The suite. + * @param data The shared inputs and buffers. + * @param recipient The recipient's key pair. + * @param sender_keypair The sender's key pair. + * @param recipient_public_key Its public key. + * @param sender_public_key The sender's public key. + * @param on ` on `, which ends each name. + */ +template +void cover_hpke_setups(hpke_coverage_data& data, + typename Suite::recipient_keypair_type const& recipient, + typename Suite::sender_keypair_type const& sender_keypair, + typename Suite::public_key_type const& recipient_public_key, + typename Suite::public_key_type const& sender_public_key, + std::string const& on) { + namespace hpke = webcpp::crypto::public_key_encryption::hpke; + covered("hpke begin_sending, base" + on, "suite::begin_sending", + [&] { BOOST_TEST(Suite::begin_sending(recipient_public_key, data.info).has_value()); }); + covered("hpke begin_sending, psk" + on, "suite::begin_sending", [&] { + BOOST_TEST( + Suite::begin_sending(recipient_public_key, data.info, data.pre_shared_key).has_value()); + }); + covered("hpke begin_sending, auth" + on, "suite::begin_sending", [&] { + BOOST_TEST( + Suite::begin_sending(recipient_public_key, data.info, sender_keypair).has_value()); + }); + covered("hpke begin_sending, auth_psk" + on, "suite::begin_sending", [&] { + BOOST_TEST(Suite::begin_sending(recipient_public_key, data.info, data.pre_shared_key, + sender_keypair) + .has_value()); + }); + covered("hpke begin_sending with a short pre-shared key" + on, "suite::begin_sending", [&] { + BOOST_TEST(Suite::begin_sending(recipient_public_key, data.info, data.short_psk).error() == + webcpp::crypto::error::invalid_key_size); + }); + covered("hpke::begin_sending" + on, "hpke::begin_sending", [&] { + BOOST_TEST(hpke::begin_sending(recipient_public_key, data.info).has_value()); + }); + cover_hpke_receiving(data, recipient, sender_keypair, sender_public_key, on); +} + +/** + * The contexts' `seal`, `open` and `export_secret`, and their free forms. + * + * @tparam Suite The suite. + * @param data The shared inputs and buffers. + * @param sender A sender's context. + * @param receiver Its recipient's context. + * @param on ` on `, which ends each name. + */ +template +void cover_hpke_contexts(hpke_coverage_data& data, + typename Suite::sender_context_type& sender, + typename Suite::recipient_context_type& receiver, std::string const& on) { + namespace hpke = webcpp::crypto::public_key_encryption::hpke; + covered("hpke sender_context::seal" + on, "sender_context::seal", [&] { + BOOST_TEST(sender.seal(data.info, data.plaintext, data.ciphertext).has_value()); + }); + covered("hpke recipient_context::open" + on, "recipient_context::open", [&] { + BOOST_TEST(receiver.open(data.info, data.ciphertext, data.opened).has_value()); + }); + covered("hpke sender_context::seal into a short output" + on, "sender_context::seal", [&] { + BOOST_TEST( + sender.seal(data.info, data.plaintext, std::span(data.ciphertext).first(1)).error() == + webcpp::crypto::error::invalid_input_size); + }); + covered( + "hpke recipient_context::open of a short data.ciphertext" + on, "recipient_context::open", + [&] { + BOOST_TEST(receiver.open(data.info, std::span(data.ciphertext).first(1), data.opened) + .error() == webcpp::crypto::error::invalid_input_size); + }); + covered("hpke::seal of a context" + on, "hpke::seal", [&] { + BOOST_TEST(hpke::seal(sender, data.info, data.plaintext, data.ciphertext).has_value()); + }); + covered("hpke::open of a context" + on, "hpke::open", [&] { + BOOST_TEST(hpke::open(receiver, data.info, data.ciphertext, data.opened).has_value()); + }); + covered("hpke sender_context::export_secret<32>" + on, "sender_context::export_secret", + [&] { BOOST_TEST(sender.template export_secret<32>(data.info).has_value()); }); + covered("hpke recipient_context::export_secret<32>" + on, "recipient_context::export_secret", + [&] { BOOST_TEST(receiver.template export_secret<32>(data.info).has_value()); }); + covered("hpke sender_context::export_secret into a span" + on, "sender_context::export_secret", + [&] { BOOST_TEST(sender.export_secret(data.info, data.exported).has_value()); }); + covered("hpke recipient_context::export_secret into an empty span" + on, + "recipient_context::export_secret", [&] { + BOOST_TEST(receiver.export_secret(data.info, std::span{}).error() == + webcpp::crypto::error::invalid_input_size); + }); + covered("hpke::export_secret<32>" + on, "hpke::export_secret", + [&] { BOOST_TEST(hpke::export_secret<32>(sender, data.info).has_value()); }); + covered("hpke::export_secret into a span" + on, "hpke::export_secret", [&] { + BOOST_TEST(hpke::export_secret(receiver, data.info, data.exported).has_value()); + }); +} + +/** + * The single-shot `seal` and `open` in every mode, and their free forms. + * + * @tparam Suite The suite. + * @param data The shared inputs and buffers. + * @param recipient The recipient's key pair. + * @param sender_keypair The sender's key pair. + * @param recipient_public_key Its public key. + * @param sender_public_key The sender's public key. + * @param encapsulated_key An auth_psk sender's encapsulated key. + * @param on ` on `, which ends each name. + */ +template +void cover_hpke_single_shot(hpke_coverage_data& data, + typename Suite::recipient_keypair_type const& recipient, + typename Suite::sender_keypair_type const& sender_keypair, + typename Suite::public_key_type const& recipient_public_key, + typename Suite::public_key_type const& sender_public_key, + typename Suite::encapsulated_key_type const& encapsulated_key, + std::string const& on) { + namespace hpke = webcpp::crypto::public_key_encryption::hpke; + auto sealed_key = encapsulated_key; + covered("hpke seal, base" + on, "suite::seal", [&] { + auto const sealed = Suite::seal(recipient_public_key, data.info, data.info, data.plaintext, + data.ciphertext); + if (BOOST_TEST(sealed.has_value())) { + sealed_key = *sealed; + } + }); + covered("hpke open, base" + on, "suite::open", [&] { + BOOST_TEST( + Suite::open(sealed_key, recipient, data.info, data.info, data.ciphertext, data.opened) + .has_value()); + }); + covered("hpke seal, psk" + on, "suite::seal", [&] { + BOOST_TEST(Suite::seal(recipient_public_key, data.info, data.info, data.plaintext, + data.ciphertext, data.pre_shared_key) + .has_value()); + }); + covered("hpke seal, auth" + on, "suite::seal", [&] { + BOOST_TEST(Suite::seal(recipient_public_key, data.info, data.info, data.plaintext, + data.ciphertext, sender_keypair) + .has_value()); + }); + covered("hpke seal, auth_psk" + on, "suite::seal", [&] { + BOOST_TEST(Suite::seal(recipient_public_key, data.info, data.info, data.plaintext, + data.ciphertext, data.pre_shared_key, sender_keypair) + .has_value()); + }); + covered("hpke open, auth_psk" + on, "suite::open", [&] { + BOOST_TEST(Suite::open(encapsulated_key, recipient, data.info, data.info, data.ciphertext, + data.opened, data.pre_shared_key, sender_public_key) + .error() == webcpp::crypto::error::authentication_failed); + }); + covered("hpke open, psk, short pre-shared key" + on, "suite::open", [&] { + BOOST_TEST(Suite::open(encapsulated_key, recipient, data.info, data.info, data.ciphertext, + data.opened, data.short_psk) + .error() == webcpp::crypto::error::invalid_key_size); + }); + covered("hpke open, auth" + on, "suite::open", [&] { + BOOST_TEST(Suite::open(encapsulated_key, recipient, data.info, data.info, data.ciphertext, + data.opened, sender_public_key) + .error() == webcpp::crypto::error::authentication_failed); + }); + covered("hpke::seal" + on, "hpke::seal", [&] { + BOOST_TEST(hpke::seal(recipient_public_key, data.info, data.info, data.plaintext, + data.ciphertext) + .has_value()); + }); + covered("hpke::open" + on, "hpke::open", [&] { + BOOST_TEST(hpke::open(encapsulated_key, recipient, data.info, data.info, + data.ciphertext, data.opened) + .error() == webcpp::crypto::error::authentication_failed); + }); +} + +/** + * The asynchronous forms, member and free. + * + * @tparam Suite The suite. + * @param data The shared inputs and buffers. + * @param recipient The recipient's key pair. + * @param sender_keypair The sender's key pair. + * @param recipient_public_key Its public key. + * @param sender_public_key The sender's public key. + * @param encapsulated_key An auth_psk sender's encapsulated key. + * @param sender A sender's context. + * @param receiver Its recipient's context. + * @param on ` on `, which ends each name. + */ +template +void cover_hpke_asynchronous(hpke_coverage_data& data, + typename Suite::recipient_keypair_type const& recipient, + typename Suite::sender_keypair_type const& sender_keypair, + typename Suite::public_key_type const& recipient_public_key, + typename Suite::public_key_type const& sender_public_key, + typename Suite::encapsulated_key_type const& encapsulated_key, + typename Suite::sender_context_type& sender, + typename Suite::recipient_context_type& receiver, + std::string const& on) { + namespace hpke = webcpp::crypto::public_key_encryption::hpke; + webcpp::asio::io_context context; + auto const executor = context.get_executor(); + int completions = 0; + auto const deliver = [&context] { + context.restart(); + context.run(); // lint-run: the test's event loop + }; + hpke_completion_counter const counted{.completions = &completions}; + covered("hpke async_begin_sending" + on, "suite::async_begin_sending", [&] { + Suite::async_begin_sending(executor, recipient_public_key, data.info, counted); + deliver(); + }); + covered("hpke::async_begin_sending" + on, "hpke::async_begin_sending", [&] { + hpke::async_begin_sending(executor, recipient_public_key, data.info, data.short_psk, + counted); + deliver(); + }); + covered("hpke async_begin_receiving" + on, "suite::async_begin_receiving", [&] { + Suite::async_begin_receiving(executor, encapsulated_key, recipient, data.info, counted); + deliver(); + }); + covered("hpke::async_begin_receiving" + on, "hpke::async_begin_receiving", [&] { + hpke::async_begin_receiving(executor, encapsulated_key, recipient, data.info, + data.pre_shared_key, sender_public_key, counted); + deliver(); + }); + covered("hpke async_seal" + on, "suite::async_seal", [&] { + Suite::async_seal(executor, recipient_public_key, data.info, data.info, data.plaintext, + data.ciphertext, counted); + deliver(); + }); + covered("hpke::async_seal" + on, "hpke::async_seal", [&] { + hpke::async_seal(executor, recipient_public_key, data.info, data.info, + data.plaintext, data.ciphertext, sender_keypair, counted); + deliver(); + }); + covered("hpke async_open" + on, "suite::async_open", [&] { + Suite::async_open(executor, encapsulated_key, recipient, data.info, data.info, + data.ciphertext, data.opened, counted); + deliver(); + }); + covered("hpke::async_open" + on, "hpke::async_open", [&] { + hpke::async_open(executor, encapsulated_key, recipient, data.info, data.info, + data.ciphertext, data.opened, data.pre_shared_key, counted); + deliver(); + }); + covered("hpke async_derive_from_seed" + on, "suite::async_derive_from_seed", [&] { + Suite::async_derive_from_seed(executor, data.recipient_seed, counted); + deliver(); + }); + covered("hpke::async_derive_from_seed" + on, "hpke::async_derive_from_seed", [&] { + hpke::async_derive_from_seed(executor, data.short_seed, counted); + deliver(); + }); + covered("hpke sender_context::async_seal" + on, "sender_context::async_seal", [&] { + sender.async_seal(executor, data.info, data.plaintext, data.ciphertext, counted); + deliver(); + }); + covered("hpke::async_seal of a context" + on, "hpke::async_seal", [&] { + hpke::async_seal(executor, sender, data.info, data.plaintext, data.ciphertext, counted); + deliver(); + }); + covered("hpke recipient_context::async_open" + on, "recipient_context::async_open", [&] { + receiver.async_open(executor, data.info, data.ciphertext, data.opened, counted); + deliver(); + }); + covered("hpke::async_open of a context" + on, "hpke::async_open", [&] { + hpke::async_open(executor, receiver, data.info, data.ciphertext, data.opened, counted); + deliver(); + }); + BOOST_TEST_EQ(completions, 14); +} + +/** + * Every HPKE function of `Suite`, covered. + * + * @tparam Suite An `hpke::suite` that seals, on the backend under test. + * @param on ` on `, which ends each name. + */ +template +void cover_hpke(std::string const& on) { + hpke_coverage_data data; + cover_hpke_keys(data, on); + auto const recipient = Suite::derive_from_seed(data.recipient_seed); + auto const sender_keypair = Suite::derive_from_seed(data.sender_seed); + if (!BOOST_TEST(recipient.has_value() && sender_keypair.has_value())) { + return; + } + auto const recipient_public_key = recipient->public_key(); + auto const sender_public_key = sender_keypair->public_key(); + if (!BOOST_TEST(recipient_public_key.has_value() && sender_public_key.has_value())) { + return; + } + cover_hpke_setups(data, *recipient, *sender_keypair, *recipient_public_key, + *sender_public_key, on); + auto sender = Suite::begin_sending(*recipient_public_key, data.info, data.pre_shared_key, + *sender_keypair); + if (!BOOST_TEST(sender.has_value())) { + return; + } + auto receiver = Suite::begin_receiving(sender->encapsulated_key(), *recipient, data.info, + data.pre_shared_key, *sender_public_key); + if (!BOOST_TEST(receiver.has_value())) { + return; + } + cover_hpke_contexts(data, *sender, *receiver, on); + cover_hpke_single_shot(data, *recipient, *sender_keypair, *recipient_public_key, + *sender_public_key, sender->encapsulated_key(), on); + cover_hpke_asynchronous(data, *recipient, *sender_keypair, *recipient_public_key, + *sender_public_key, sender->encapsulated_key(), *sender, + *receiver, on); +} + +} // namespace webcpp::test + +#endif // WEBCPP_TEST_CRYPTO_SUPPORT_HPKE_COVERAGE_HPP diff --git a/test/support/hpke_vectors.hpp b/test/support/hpke_vectors.hpp new file mode 100644 index 00000000..ef6ac5fd --- /dev/null +++ b/test/support/hpke_vectors.hpp @@ -0,0 +1,378 @@ +// 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) + +// RFC 9180's test vectors (cfrg/draft-irtf-cfrg-hpke at 5f503c5, test-vectors.json, read at run +// time from third_party/libs/hpke), the 64 entries of the suites crypto has: KEM 0x0010 or 0x0020, +// KDF 0x0001 or 0x0003, any AEAD, the four modes. A program that includes this header is built +// with WEBCPP_TEST_HPKE, the submodule's directory, and links Boost.JSON. +// +// Each entry is checked through every path (design D11): +// - derive_from_seed(ikmR), and ikmS and ikmE, give pkRm, pkSm and pkEm, and their secret() +// gives skRm, skSm and skEm byte for byte (X25519's unclamped, ruling R7; their clamped forms +// are equal too, and from_secret(secret()) gives the same key pair); +// - the key encapsulation with the ephemeral key pair gives shared_secret and enc, and the +// decapsulation the same shared secret; +// - the key schedule gives key_schedule_context, secret, key, base_nonce and exporter_secret; +// - the sender set up through the test seam with ikmE gives enc, and seals the entry's +// encryptions in order on one context, each giving its ct; the recipient set up through the +// public begin_receiving opens them in order, each giving its pt; +// - the three exports give exported_value from both contexts, by both forms of export_secret. + +#ifndef WEBCPP_TEST_CRYPTO_SUPPORT_HPKE_VECTORS_HPP +#define WEBCPP_TEST_CRYPTO_SUPPORT_HPKE_VECTORS_HPP + +#include + +#include "hex.hpp" +#include "test_data.hpp" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::test::hpke_vectors { + +namespace hpke = webcpp::crypto::public_key_encryption::hpke; + +/** What the checks counted, which the program compares with the file's known numbers. */ +struct counts { + /** Entries checked. */ + std::size_t entries = 0; + /** Entries per mode, 0 to 3. */ + std::array modes{}; + /** Encryptions sealed and opened. */ + std::size_t encryptions = 0; + /** Exports checked, on both contexts. */ + std::size_t exports = 0; + /** Export-only entries. */ + std::size_t export_only = 0; +}; + +/** The bytes of a hex field of an entry; an absent field is empty. */ +inline std::vector field(boost::json::object const& entry, std::string_view name) { + auto const* value = entry.if_contains(name); + if (value == nullptr) { + return {}; + } + return from_hex(std::string_view(value->as_string())); +} + +/** Whether two byte ranges are equal. */ +template +bool same_bytes(First const& first, Second const& second) { + return std::ranges::equal(std::span(first), + std::span(second)); +} + +/** RFC 7748's clamping of an X25519 secret key. */ +inline std::vector clamped(std::span secret_key) { + std::vector clamped_key(secret_key.begin(), secret_key.end()); + clamped_key[0] = static_cast(clamped_key[0] & 248U); + clamped_key[31] = static_cast((clamped_key[31] & 127U) | 64U); + return clamped_key; +} + +/** The serialized public key of a key pair. */ +template +std::vector public_bytes(Keypair const& key_pair) { + auto const public_key = key_pair.public_key(); + if (!BOOST_TEST(public_key.has_value())) { + return {}; + } + auto const serialized = webcpp::crypto::detail::hpke_serialized(*public_key); + return {serialized.begin(), serialized.end()}; +} + +/** + * A key pair derived from an entry's seed, checked against its public and secret keys; empty when + * it fails, the failure counted. + */ +template +boost::system::result derived( + boost::json::object const& entry, std::string_view seed_name, std::string_view public_name, + std::string_view secret_name) { + using key_encapsulation = Suite::key_encapsulation_type; + auto const seed = field(entry, seed_name); + auto key_pair = Suite::derive_from_seed(seed); + if (!BOOST_TEST(key_pair.has_value())) { + return key_pair; + } + BOOST_TEST(same_bytes(public_bytes(*key_pair), field(entry, public_name))); + auto const secret_key = key_pair->secret(); + if (!BOOST_TEST(secret_key.has_value())) { + return key_pair; + } + auto const expected_secret = field(entry, secret_name); + BOOST_TEST(same_bytes(secret_key->bytes(), expected_secret)); + if constexpr (key_encapsulation::id == 0x0020) { + BOOST_TEST(same_bytes(clamped(secret_key->bytes()), clamped(expected_secret))); + } + // from_secret(secret()) gives the same key pair (ruling R7). + auto const again = Suite::recipient_keypair_type::from_secret(secret_key->bytes()); + if (BOOST_TEST(again.has_value())) { + BOOST_TEST(same_bytes(public_bytes(*again), field(entry, public_name))); + } + return key_pair; +} + +/** The key schedule's values, computed again from the shared secret, against the entry's. */ +template +void check_schedule(boost::json::object const& entry, std::uint8_t mode, + std::span shared_secret) { + auto const info = field(entry, "info"); + auto const psk = field(entry, "psk"); + auto const psk_id = field(entry, "psk_id"); + auto const schedule = + webcpp::crypto::detail::hpke_key_schedule(mode, shared_secret, info, psk, psk_id); + if (!BOOST_TEST(schedule.has_value())) { + return; + } + BOOST_TEST(same_bytes(schedule->key_schedule_context, field(entry, "key_schedule_context"))); + BOOST_TEST(same_bytes(schedule->secret.bytes(), field(entry, "secret"))); + BOOST_TEST(same_bytes(schedule->exporter_secret.bytes(), field(entry, "exporter_secret"))); + if constexpr (hpke::sealing_cipher) { + BOOST_TEST(same_bytes(schedule->aead_material.key.bytes(), field(entry, "key"))); + BOOST_TEST(same_bytes(schedule->aead_material.base_nonce, field(entry, "base_nonce"))); + } else { + BOOST_TEST(field(entry, "key").empty()); + BOOST_TEST(field(entry, "base_nonce").empty()); + } +} + +/** The entry's encryptions, sealed and opened in order on one context each. */ +template +void check_encryptions(boost::json::object const& entry, + typename Suite::sender_context_type& sender, + typename Suite::recipient_context_type& recipient, counts& counted) { + for (auto const& encryption_value : entry.at("encryptions").as_array()) { + auto const& encryption = encryption_value.as_object(); + auto const associated_data = field(encryption, "aad"); + auto const plaintext = field(encryption, "pt"); + auto const ciphertext = field(encryption, "ct"); + std::vector sealed(plaintext.size() + Suite::tag_size); + BOOST_TEST(sender.seal(associated_data, plaintext, sealed).has_value()); + BOOST_TEST(same_bytes(sealed, ciphertext)); + std::vector opened(ciphertext.size() - Suite::tag_size); + BOOST_TEST(recipient.open(associated_data, ciphertext, opened).has_value()); + BOOST_TEST(same_bytes(opened, plaintext)); + ++counted.encryptions; + } +} + +/** The entry's exports, from both contexts, by both forms. */ +template +void check_exports(boost::json::object const& entry, + typename Suite::sender_context_type const& sender, + typename Suite::recipient_context_type const& recipient, counts& counted) { + for (auto const& export_value : entry.at("exports").as_array()) { + auto const& exported = export_value.as_object(); + auto const purpose = field(exported, "exporter_context"); + auto const expected = field(exported, "exported_value"); + auto const length = static_cast(exported.at("L").as_int64()); + for (int side = 0; side < 2; ++side) { + std::vector output(length); + auto const done = side == 0 ? sender.export_secret(purpose, output) + : recipient.export_secret(purpose, output); + BOOST_TEST(done.has_value()); + BOOST_TEST(same_bytes(output, expected)); + ++counted.exports; + } + if (length == 32) { + auto const fixed = hpke::export_secret<32>(recipient, purpose); + if (BOOST_TEST(fixed.has_value())) { + BOOST_TEST(same_bytes(fixed->bytes(), expected)); + } + } + } +} + +/** The key encapsulation of an entry, both ways: its shared secret and its encapsulated key. */ +template +void check_encapsulation(boost::json::object const& entry, + typename Suite::recipient_keypair_type const& recipient_keypair, + typename Suite::recipient_keypair_type const& ephemeral_keypair, + typename Suite::sender_keypair_type const* sender_keypair, + typename Suite::public_key_type const& recipient_public_key, + typename Suite::public_key_type const* sender_public_key) { + using dhkem = webcpp::crypto::detail::hpke_setup::dhkem; + auto const encapsulated = + dhkem::encapsulate(recipient_public_key, ephemeral_keypair, sender_keypair); + if (!BOOST_TEST(encapsulated.has_value())) { + return; + } + auto const shared_secret = field(entry, "shared_secret"); + BOOST_TEST(same_bytes(encapsulated->shared_secret.bytes(), shared_secret)); + BOOST_TEST(same_bytes(encapsulated->encapsulated_key.bytes(), field(entry, "enc"))); + auto const decapsulated = + dhkem::decapsulate(encapsulated->encapsulated_key, recipient_keypair, sender_public_key); + if (BOOST_TEST(decapsulated.has_value())) { + BOOST_TEST(same_bytes(decapsulated->bytes(), shared_secret)); + } +} + +/** The recipient's context of an entry, set up through the public call of its mode. */ +template +boost::system::result received( + boost::json::object const& entry, std::uint8_t mode, + typename Suite::recipient_keypair_type const& recipient_keypair, + hpke::pre_shared_key const& pre_shared_key, + typename Suite::public_key_type const& sender_public_key) { + auto const info = field(entry, "info"); + auto const encapsulated_key = Suite::encapsulated_key_type::from_bytes(field(entry, "enc")); + if (!BOOST_TEST(encapsulated_key.has_value())) { + return encapsulated_key.error(); + } + switch (mode) { + case 1: + return Suite::begin_receiving(*encapsulated_key, recipient_keypair, info, + pre_shared_key); + case 2: + return Suite::begin_receiving(*encapsulated_key, recipient_keypair, info, + sender_public_key); + case 3: + return Suite::begin_receiving(*encapsulated_key, recipient_keypair, info, + pre_shared_key, sender_public_key); + default: return Suite::begin_receiving(*encapsulated_key, recipient_keypair, info); + } +} + +/** One entry of a suite, through every path. */ +template +void check_entry(boost::json::object const& entry, counts& counted) { + using access = webcpp::crypto::detail::hpke_access; + auto const mode = static_cast(entry.at("mode").as_int64()); + bool const with_key = (mode & 1U) != 0; + bool const with_sender = (mode & 2U) != 0; + auto const recipient_keypair = derived(entry, "ikmR", "pkRm", "skRm"); + auto const ephemeral_keypair = derived(entry, "ikmE", "pkEm", "skEm"); + auto const sender_keypair = with_sender ? derived(entry, "ikmS", "pkSm", "skSm") + : Suite::derive_from_seed(field(entry, "ikmR")); + if (!recipient_keypair || !ephemeral_keypair || !sender_keypair) { + return; + } + auto const recipient_public_key = recipient_keypair->public_key(); + auto const sender_public_key = sender_keypair->public_key(); + if (!BOOST_TEST(recipient_public_key.has_value() && sender_public_key.has_value())) { + return; + } + check_encapsulation(entry, *recipient_keypair, *ephemeral_keypair, + with_sender ? &*sender_keypair : nullptr, *recipient_public_key, + with_sender ? &*sender_public_key : nullptr); + check_schedule(entry, mode, field(entry, "shared_secret")); + // The contexts: the sender through the seam, the recipient through the public call. + auto const psk = field(entry, "psk"); + auto const psk_id = field(entry, "psk_id"); + hpke::pre_shared_key const pre_shared_key{.key = psk, .id = psk_id}; + auto sender = access::begin_sending_with_ephemeral_seed( + field(entry, "ikmE"), *recipient_public_key, field(entry, "info"), + with_key ? &pre_shared_key : nullptr, with_sender ? &*sender_keypair : nullptr); + auto recipient = + received(entry, mode, *recipient_keypair, pre_shared_key, *sender_public_key); + if (!BOOST_TEST(sender.has_value() && recipient.has_value())) { + return; + } + BOOST_TEST(same_bytes(sender->encapsulated_key().bytes(), field(entry, "enc"))); + if constexpr (hpke::sealing_cipher) { + check_encryptions(entry, *sender, *recipient, counted); + } else { + auto const& encryptions = entry.at("encryptions").as_array(); + BOOST_TEST(encryptions.empty()); + ++counted.export_only; + } + check_exports(entry, *sender, *recipient, counted); + ++counted.entries; + ++counted.modes[mode]; +} + +/** + * The suite of an entry's identifiers, by the program's choice of backends: `SuiteOf`. + */ +template