From cfb544fffe7ce8685562e969eb45cb0e950df321 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 10:16:31 -0300 Subject: [PATCH 001/110] crypto: the backend libsodium, its canary and its three layers --- LICENSE-LIBSODIUM.txt | 18 +++++ README.md | 3 +- doc/changelog.adoc | 1 + doc/generated/messages.adoc | 56 ++++++++++++++ doc/tables/crypto.json | 7 +- include/webcpp/crypto.hpp | 4 + include/webcpp/crypto/backends/sodium.hpp | 74 +++++++++++++++++++ include/webcpp/crypto/config.hpp | 15 ++++ include/webcpp/crypto/detail/canary.h | 6 ++ src/canary_sodium.c | 31 ++++++++ test/Jamfile | 6 ++ test/convenience_header_test.cpp | 3 +- test/messages/Jamfile | 1 + test/messages/sodium_not_linked/Jamfile | 11 +++ .../sodium_not_linked/sodium_not_linked.cpp | 17 +++++ test/msvc/Jamfile | 2 + test/msvc/canary_sodium_other_commit/Jamfile | 11 +++ test/msvc/canary_sodium_other_commit/app.cpp | 13 ++++ test/msvc/sodium_not_linked/Jamfile | 9 +++ test/msvc/sodium_not_linked/app.cpp | 14 ++++ test/sodium_backend_test.cpp | 20 +++++ 21 files changed, 319 insertions(+), 3 deletions(-) create mode 100644 LICENSE-LIBSODIUM.txt create mode 100644 include/webcpp/crypto/backends/sodium.hpp create mode 100644 src/canary_sodium.c create mode 100644 test/messages/sodium_not_linked/Jamfile create mode 100644 test/messages/sodium_not_linked/sodium_not_linked.cpp create mode 100644 test/msvc/canary_sodium_other_commit/Jamfile create mode 100644 test/msvc/canary_sodium_other_commit/app.cpp create mode 100644 test/msvc/sodium_not_linked/Jamfile create mode 100644 test/msvc/sodium_not_linked/app.cpp create mode 100644 test/sodium_backend_test.cpp diff --git a/LICENSE-LIBSODIUM.txt b/LICENSE-LIBSODIUM.txt new file mode 100644 index 00000000..95c22fba --- /dev/null +++ b/LICENSE-LIBSODIUM.txt @@ -0,0 +1,18 @@ +/* + * ISC License + * + * Copyright (c) 2013-2026 + * Frank Denis + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/README.md b/README.md index 2e1d1cc2..eb83a678 100644 --- a/README.md +++ b/README.md @@ -46,4 +46,5 @@ from `doc/tables/crypto.json` and the tests; `b2 libs/crypto/doc` checks them. crypto is under the Boost Software License, Version 1.0 (`LICENSE_1_0.txt`). The backends keep their own: BearSSL is MIT (`LICENSE-BEARSSL.txt`), ctaes is MIT (`LICENSE-CTAES.txt`), -libsecp256k1 is MIT (`LICENSE-SECP256K1.txt`) and OpenSSL is Apache-2.0. +libsecp256k1 is MIT (`LICENSE-SECP256K1.txt`), libsodium is ISC (`LICENSE-LIBSODIUM.txt`) and +OpenSSL is Apache-2.0. diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 41ea58b2..68a94641 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -25,5 +25,6 @@ of every version are on webcpp's index page. * Added backends::ctaes, the AES block cipher alone on every target; ciphers::gcm refuses it. * Added curves::secp256k1: key pairs, BIP340 and ECDSA signatures, ECDH, strict DER, low-S and the x-only tweak. * Added the link-time canaries of BearSSL, ctaes and libsecp256k1, and their own suites on webcpp's build. +* Added backends::sodium and its link-time canary on /third_party//sodium, which webcpp::hash shares, and libsodium's initialisation every engine calls first. * Added the page: a chapter per namespace and use case, the memory option's guide and example, tables generated from the tests, every Jamfile and message, and llms.txt. // end::unreleased[] diff --git a/doc/generated/messages.adoc b/doc/generated/messages.adoc index 61d1bcd8..9b2f7da4 100644 --- a/doc/generated/messages.adoc +++ b/doc/generated/messages.adoc @@ -91,6 +91,12 @@ The fix: Add `+/third_party//secp256k1+`. The fix: Name `+backends::secp256k1+`, or leave the backend out: `+curves::secp256k1::keypair+`. +|`+sodium_not_linked+` +|native, wasip2, wasip3 +|`+webcpp::crypto: the backend libsodium is used and not linked. In the program's Jamfile, add /third_party//sodium beside /webcpp/crypto//crypto, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)+` + +The fix: Add `+/third_party//sodium+`. + |`+two_defaults+` |native |`+webcpp::crypto: both WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL and WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL are defined. Keep one.+` @@ -268,6 +274,34 @@ On each target, the build's output contains: ** `+undefined symbol: webcpp_crypto_secp256k1_6e2c8bc_w2c2x5__add_third_party_secp256k1_to_your_link+` ** `pass:[em++: error:]` +`+canary_sodium_other_commit+`:: A libsodium of another commit than the headers'. The fix: Build the library at the commit of webcpp's submodule, or link it through b2. ++ +Its Jamfile: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/canary_sodium_other_commit/Jamfile[tag=jamfile] +---- ++ +On each target, the build's output contains: ++ +* native, macOS: +** `+Undefined symbols for architecture+` +** `+_webcpp_crypto_sodium_0000000_portable__add_third_party_sodium_to_your_link+` +* native, Linux: +** `+webcpp_crypto_sodium_0000000_portable__add_third_party_sodium_to_your_link+` +** `pass:[undefined reference to `webcpp_crypto_sodium_0000000_portable__add_third_party_sodium_to_your_link']` +* wasip2: +** `+wasm-ld: error:+` +** `+undefined symbol: webcpp_crypto_sodium_0000000_portable__add_third_party_sodium_to_your_link+` +* wasip3: +** `+wasm-ld: error:+` +** `+undefined symbol: webcpp_crypto_sodium_0000000_portable__add_third_party_sodium_to_your_link+` +* emscripten: +** `+wasm-ld: error:+` +** `+undefined symbol: webcpp_crypto_sodium_0000000_portable__add_third_party_sodium_to_your_link+` +** `pass:[em++: error:]` + `+canary_without+`:: A BearSSL built from its sources without webcpp's `+src/canary_bearssl.c+`. The fix: Compile webcpp's `+src/canary_bearssl.c+` with the library, or link it through b2. + Its Jamfile: @@ -400,6 +434,20 @@ On each target, the build's output contains: * emscripten: ** `+webcpp::crypto: /webcpp/crypto//openssl is named in a build for Emscripten, where webcpp does not build OpenSSL.+` +`+sodium_not_linked_on_emscripten+`:: A program for Emscripten that names libsodium and links none. The fix: Add `+/third_party//sodium+` to the program's sources. ++ +Its Jamfile: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/sodium_not_linked_on_emscripten/Jamfile[tag=jamfile] +---- ++ +On each target, the build's output contains: ++ +* emscripten: +** `+webcpp::crypto: the backend libsodium is used and not linked. In the program's Jamfile, add /third_party//sodium beside /webcpp/crypto//crypto, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)+` + On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at link time; its text is MSVC's own, the same instruction in MSVC's words, and two files compiled with different settings stop the link with LNK2038. [cols="1,1,4",options="header"] @@ -442,6 +490,10 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the link |Compile every file of the program with the same backend settings. +|`+canary_sodium_other_commit+` +|the link +|Build the library at the commit of webcpp's submodule, or link it through b2. + |`+canary_two_files+` |the link |Compile every file of the program with the same backend settings. @@ -494,6 +546,10 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |Name `+backends::secp256k1+`, or leave the backend out: `+curves::secp256k1::keypair+`. +|`+sodium_not_linked+` +|the compile +|Add `+/third_party//sodium+`. + |`+two_defaults+` |the compile |Keep one of the two defines. diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 0708a798..5babe0f9 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -350,7 +350,9 @@ "memory_missing_definition_make": "The memory option set in the program's project, a `make` on OpenSSL, and `openssl_memory_resource()` not defined.", "memory_two_files": "Two files of one program, one compiled with the memory option and one without.", "memory_option": "OpenSSL's allocations in the program's own resource: the define and OpenSSL in the requirements of the program's project, the resource defined once, the install first in `main`.", - "no_backend_on_emscripten": "A program for Emscripten that uses the default backend and links none." + "no_backend_on_emscripten": "A program for Emscripten that uses the default backend and links none.", + "canary_sodium_other_commit": "A libsodium of another commit than the headers'.", + "sodium_not_linked_on_emscripten": "A program for Emscripten that names libsodium and links none." }, "fixes": { "no_backend_native": "Add `/webcpp/crypto//openssl` or `/third_party//bearssl` to the program's sources.", @@ -360,6 +362,9 @@ "openssl_not_linked": "Add `/webcpp/crypto//openssl`.", "openssl_old": "Name `/webcpp/crypto//openssl`, which builds OpenSSL 3.5.9; without b2, put OpenSSL 3's `include/` first.", "ctaes_not_linked": "Add `/third_party//ctaes`.", + "sodium_not_linked": "Add `/third_party//sodium`.", + "sodium_not_linked_on_emscripten": "Add `/third_party//sodium` to the program's sources.", + "canary_sodium_other_commit": "Build the library at the commit of webcpp's submodule, or link it through b2.", "secp256k1_not_linked": "Add `/third_party//secp256k1`.", "gcm_on_ctaes": "Use `aes256_gcm` with BearSSL or OpenSSL linked.", "secp256k1_other_backend": "Name `backends::secp256k1`, or leave the backend out: `curves::secp256k1::keypair`.", diff --git a/include/webcpp/crypto.hpp b/include/webcpp/crypto.hpp index d4faaa4b..2c68ce59 100644 --- a/include/webcpp/crypto.hpp +++ b/include/webcpp/crypto.hpp @@ -37,6 +37,10 @@ #include #endif +#ifdef WEBCPP_CRYPTO_HAS_SODIUM +#include +#endif + #ifdef WEBCPP_CRYPTO_HAS_SECP256K1 #include #endif diff --git a/include/webcpp/crypto/backends/sodium.hpp b/include/webcpp/crypto/backends/sodium.hpp new file mode 100644 index 00000000..418010f6 --- /dev/null +++ b/include/webcpp/crypto/backends/sodium.hpp @@ -0,0 +1,74 @@ +// 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 backend libsodium: libsodium 1.0.22's own C code, built from its sources by + `/third_party//sodium`, the one copy webcpp::hash and webcpp::crypto share. + + @see "The backends", in the guide. +*/ +#ifndef WEBCPP_CRYPTO_BACKENDS_SODIUM_HPP +#define WEBCPP_CRYPTO_BACKENDS_SODIUM_HPP + +#include + +#ifndef WEBCPP_CRYPTO_HAS_SODIUM +// clang-format off +#error "webcpp::crypto: the backend libsodium is used and not linked. In the program's Jamfile, add /third_party//sodium beside /webcpp/crypto//crypto, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)" +// clang-format on +#else + +#include +#include +#include + +#include // through /third_party//sodium, as webcpp::hash's header does +#include + +#include + +/** The canary's name, which every libsodium function of webcpp::crypto reads. */ +#define WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY \ + WEBCPP_CRYPTO_DETAIL_CANARY(sodium, WEBCPP_CRYPTO_SODIUM_COMMIT, portable) + +#ifdef _MSC_VER +#pragma detect_mismatch( \ + "webcpp_crypto_backend_sodium", \ + WEBCPP_CRYPTO_DETAIL_MISMATCH_VALUE(sodium, WEBCPP_CRYPTO_SODIUM_COMMIT, portable)) +#endif + +extern "C" const char WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY; + +namespace webcpp::crypto::backends { + +/** The backend libsodium (design D7). */ +struct sodium { + /** The backend's name, which the examples print. */ + static constexpr std::string_view name = "sodium"; +}; + +} // namespace webcpp::crypto::backends + +namespace webcpp::crypto::detail { + +/** + Reads libsodium's canary and initialises libsodium, which every engine calls first. + `sodium_init` is idempotent and takes libsodium's own lock; its state is libsodium's. + + @return Nothing; `backend_failure` when `sodium_init` returns -1. +*/ +inline boost::system::result sodium_ready() noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); + if (sodium_init() < 0) { + return error::backend_failure; + } + return {}; +} + +} // namespace webcpp::crypto::detail + +#endif // WEBCPP_CRYPTO_HAS_SODIUM +#endif // WEBCPP_CRYPTO_BACKENDS_SODIUM_HPP diff --git a/include/webcpp/crypto/config.hpp b/include/webcpp/crypto/config.hpp index 558e0a3d..b4cc6ba9 100644 --- a/include/webcpp/crypto/config.hpp +++ b/include/webcpp/crypto/config.hpp @@ -78,6 +78,19 @@ #undef WEBCPP_CRYPTO_HAS_CTAES #endif #undef WEBCPP_CRYPTO_DETAIL_REFERENCE_LINKS_CTAES +#ifdef WEBCPP_CRYPTO_HAS_SODIUM +/** Defined while config.hpp reads a reference's build that links libsodium (doc/Jamfile). */ +#define WEBCPP_CRYPTO_DETAIL_REFERENCE_LINKS_SODIUM +#endif +/** + Defined by `/third_party//sodium` when the program links libsodium; a program built without + b2 defines it to 1 itself, and links libsodium built with webcpp's `src/canary_sodium.c`. +*/ +#define WEBCPP_CRYPTO_HAS_SODIUM 1 +#ifndef WEBCPP_CRYPTO_DETAIL_REFERENCE_LINKS_SODIUM +#undef WEBCPP_CRYPTO_HAS_SODIUM +#endif +#undef WEBCPP_CRYPTO_DETAIL_REFERENCE_LINKS_SODIUM #ifdef WEBCPP_CRYPTO_HAS_SECP256K1 /** Defined while config.hpp reads a reference's build that links libsecp256k1 (doc/Jamfile). */ #define WEBCPP_CRYPTO_DETAIL_REFERENCE_LINKS_SECP256K1 @@ -196,6 +209,8 @@ struct openssl; struct ctaes; /** libsecp256k1, built from its sources by `/third_party//secp256k1`. */ struct secp256k1; +/** libsodium 1.0.22, built from its sources by `/third_party//sodium`. */ +struct sodium; } // namespace webcpp::crypto::backends diff --git a/include/webcpp/crypto/detail/canary.h b/include/webcpp/crypto/detail/canary.h index 61c29ca2..a085d1c9 100644 --- a/include/webcpp/crypto/detail/canary.h +++ b/include/webcpp/crypto/detail/canary.h @@ -36,6 +36,12 @@ #define WEBCPP_CRYPTO_CTAES_COMMIT 9be056a #endif +#ifdef WEBCPP_CRYPTO_SODIUM_CANARY_COMMIT +#define WEBCPP_CRYPTO_SODIUM_COMMIT WEBCPP_CRYPTO_SODIUM_CANARY_COMMIT +#else +#define WEBCPP_CRYPTO_SODIUM_COMMIT 77e1ce5 +#endif + #define WEBCPP_CRYPTO_DETAIL_CANARY_I(name, commit, configuration) \ webcpp_crypto_##name##_##commit##_##configuration##__add_third_party_##name##_to_your_link #define WEBCPP_CRYPTO_DETAIL_CANARY(name, commit, configuration) \ diff --git a/src/canary_sodium.c b/src/canary_sodium.c new file mode 100644 index 00000000..c79e05ec --- /dev/null +++ b/src/canary_sodium.c @@ -0,0 +1,31 @@ +/* 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 canary of the backend libsodium, compiled into /third_party//sodium with libsodium's + * own defines. Its configuration is portable exactly when those defines are the ones + * third_party/Jamfile derives from libsodium's configure: CONFIGURED, SODIUM_STATIC and + * NATIVE_LITTLE_ENDIAN each 1, and libsodium's assembly off (no HAVE_AMD64_ASM), so that every + * function is its C code (design D7); and unconfigured for any other build, which no header + * expects. */ +#include + +#if defined(CONFIGURED) && CONFIGURED == 1 && defined(SODIUM_STATIC) && SODIUM_STATIC == 1 && \ + defined(NATIVE_LITTLE_ENDIAN) && NATIVE_LITTLE_ENDIAN == 1 && !defined(HAVE_AMD64_ASM) +#define WEBCPP_CRYPTO_SODIUM_BUILT portable +#else +#define WEBCPP_CRYPTO_SODIUM_BUILT unconfigured +#endif + +#if defined(_MSC_VER) +#pragma detect_mismatch("webcpp_crypto_backend_sodium", \ + WEBCPP_CRYPTO_DETAIL_MISMATCH_VALUE(sodium, WEBCPP_CRYPTO_SODIUM_COMMIT, \ + WEBCPP_CRYPTO_SODIUM_BUILT)) +#endif + +extern const char WEBCPP_CRYPTO_DETAIL_CANARY(sodium, WEBCPP_CRYPTO_SODIUM_COMMIT, + WEBCPP_CRYPTO_SODIUM_BUILT); +const char WEBCPP_CRYPTO_DETAIL_CANARY(sodium, WEBCPP_CRYPTO_SODIUM_COMMIT, + WEBCPP_CRYPTO_SODIUM_BUILT) = 0; diff --git a/test/Jamfile b/test/Jamfile index 37fd1037..dbd8ff73 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -43,6 +43,9 @@ webcpp.headers-alone crypto : ../include : crypto/backends/openssl.hpp # The backend ctaes's header alone, with ctaes linked, on every target. webcpp.headers-alone crypto : ../include : crypto/backends/ctaes.hpp : /third_party//ctaes ; +# The backend libsodium's header alone, with libsodium linked, on every target. +webcpp.headers-alone crypto : ../include : crypto/backends/sodium.hpp + : /third_party//sodium ; # libsecp256k1's headers compile alone only with its library, which defines # WEBCPP_CRYPTO_HAS_SECP256K1 (without it, each stops with its message). webcpp.headers-alone crypto : ../include @@ -251,6 +254,9 @@ crypto-run default_both_wasm : default_both_wasm_test.cpp # (ruling R5). crypto-run aes_ctaes : aes_ctaes_test.cpp : /third_party//ctaes ; +# The backend libsodium: its canary, its initialisation and its three layers. +crypto-run sodium_backend : sodium_backend_test.cpp : /third_party//sodium ; + # ctaes against OpenSSL on 10,000 random keys of each size (spec section 8.2), # on native, wasip2 and wasip3 (on WASI OpenSSL runs its portable C code). crypto-run agreement_aes : agreement_aes_test.cpp diff --git a/test/convenience_header_test.cpp b/test/convenience_header_test.cpp index cc042bcd..025f7872 100644 --- a/test/convenience_header_test.cpp +++ b/test/convenience_header_test.cpp @@ -17,7 +17,8 @@ #include #if defined(WEBCPP_CRYPTO_HAS_BEARSSL) || defined(WEBCPP_CRYPTO_HAS_OPENSSL) || \ - defined(WEBCPP_CRYPTO_HAS_CTAES) || defined(WEBCPP_CRYPTO_HAS_SECP256K1) + defined(WEBCPP_CRYPTO_HAS_CTAES) || defined(WEBCPP_CRYPTO_HAS_SECP256K1) || \ + defined(WEBCPP_CRYPTO_HAS_SODIUM) #error "this program links no backend: its project must not name one" #endif diff --git a/test/messages/Jamfile b/test/messages/Jamfile index 16690c6a..3f1b778d 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -23,3 +23,4 @@ build-project aes_on_bearssl ; build-project secp256k1_other_backend ; build-project openssl_memory_on_webassembly ; build-project openssl_memory_not_linked ; +build-project sodium_not_linked ; diff --git a/test/messages/sodium_not_linked/Jamfile b/test/messages/sodium_not_linked/Jamfile new file mode 100644 index 00000000..a3d76440 --- /dev/null +++ b/test/messages/sodium_not_linked/Jamfile @@ -0,0 +1,11 @@ +# 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 ; + +webcpp.compile-diagnostic sodium_not_linked : sodium_not_linked.cpp : : native wasip2 wasip3 ; diff --git a/test/messages/sodium_not_linked/sodium_not_linked.cpp b/test/messages/sodium_not_linked/sodium_not_linked.cpp new file mode 100644 index 00000000..4f0a3fbe --- /dev/null +++ b/test/messages/sodium_not_linked/sodium_not_linked.cpp @@ -0,0 +1,17 @@ +// 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 program that names libsodium and does not link it stops with the instruction to add +// /third_party//sodium. + +// clang-format off +// expected-error@webcpp/crypto/backends/sodium.hpp:* {{webcpp::crypto: the backend libsodium is used and not linked. In the program's Jamfile, add /third_party//sodium beside /webcpp/crypto//crypto, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)}} +// clang-format on +#include + +int main() { + return 0; +} diff --git a/test/msvc/Jamfile b/test/msvc/Jamfile index 1521c91d..e2fa6462 100644 --- a/test/msvc/Jamfile +++ b/test/msvc/Jamfile @@ -42,3 +42,5 @@ build-project openssl_memory_not_linked ; build-project memory_missing_definition_install ; build-project memory_missing_definition_make ; build-project memory_two_files ; +build-project sodium_not_linked ; +build-project canary_sodium_other_commit ; diff --git a/test/msvc/canary_sodium_other_commit/Jamfile b/test/msvc/canary_sodium_other_commit/Jamfile new file mode 100644 index 00000000..97cd6936 --- /dev/null +++ b/test/msvc/canary_sodium_other_commit/Jamfile @@ -0,0 +1,11 @@ +# 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.link-fail canary_sodium_other_commit : app.cpp + : /webcpp/crypto//crypto /third_party//sodium WEBCPP_CRYPTO_SODIUM_CANARY_COMMIT=0000000 + : native ; diff --git a/test/msvc/canary_sodium_other_commit/app.cpp b/test/msvc/canary_sodium_other_commit/app.cpp new file mode 100644 index 00000000..b3970970 --- /dev/null +++ b/test/msvc/canary_sodium_other_commit/app.cpp @@ -0,0 +1,13 @@ +// 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) + +// Initialises libsodium through the backend's header, which reads libsodium's canary, built for +// another commit than this program names: the link fails (LNK2038 on MSVC). +#include + +int main() { + return webcpp::crypto::detail::sodium_ready() ? 0 : 1; +} diff --git a/test/msvc/sodium_not_linked/Jamfile b/test/msvc/sodium_not_linked/Jamfile new file mode 100644 index 00000000..3aeca0ac --- /dev/null +++ b/test/msvc/sodium_not_linked/Jamfile @@ -0,0 +1,9 @@ +# 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 sodium_not_linked : app.cpp : /webcpp/crypto//crypto : native ; diff --git a/test/msvc/sodium_not_linked/app.cpp b/test/msvc/sodium_not_linked/app.cpp new file mode 100644 index 00000000..d232d008 --- /dev/null +++ b/test/msvc/sodium_not_linked/app.cpp @@ -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) + +// A program that names libsodium and does not link it stops at backends/sodium.hpp's instruction +// to add /third_party//sodium: on MSVC the compile fails. The text is checked on clang, in +// test/messages/sodium_not_linked. +#include + +int main() { + return 0; +} diff --git a/test/sodium_backend_test.cpp b/test/sodium_backend_test.cpp new file mode 100644 index 00000000..2d5c2d54 --- /dev/null +++ b/test/sodium_backend_test.cpp @@ -0,0 +1,20 @@ +// 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) + +#include + +#include +#include + +namespace crypto = webcpp::crypto; + +int main() { + BOOST_TEST_EQ(crypto::backends::sodium::name, "sodium"); + BOOST_TEST(crypto::detail::sodium_ready().has_value()); + // A second call is libsodium's no-op (sodium_init returns 1), still a success. + BOOST_TEST(crypto::detail::sodium_ready().has_value()); + return webcpp::test::exit_status(boost::report_errors()); +} From 01c1c9b4de8531741ca789f47811ab23e48e8edf Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 10:53:55 -0300 Subject: [PATCH 002/110] crypto: the reference links libsodium, so backends/sodium.hpp compiles in it --- doc/Jamfile | 2 +- doc/changelog.adoc | 1 + doc/errors.adoc | 8 +++ include/webcpp/crypto.hpp | 1 + include/webcpp/crypto/error.hpp | 22 ++++++ include/webcpp/crypto/secret.hpp | 82 ++++++++++++++++++++++ test/Jamfile | 4 +- test/error_test.cpp | 23 ++++++- test/secret_test.cpp | 114 +++++++++++++++++++++++++++++++ 9 files changed, 253 insertions(+), 4 deletions(-) create mode 100644 include/webcpp/crypto/secret.hpp create mode 100644 test/secret_test.cpp diff --git a/doc/Jamfile b/doc/Jamfile index 2d91948a..04dc2184 100644 --- a/doc/Jamfile +++ b/doc/Jamfile @@ -11,7 +11,7 @@ webcpp.doc crypto : crypto.adoc ; # link their library: it links every backend, OpenSSL natively the default # whose header ciphers/aes256_gcm.hpp includes. webcpp.reference crypto : /webcpp/crypto//openssl /third_party//bearssl - /third_party//ctaes /third_party//secp256k1 ; + /third_party//ctaes /third_party//secp256k1 /third_party//sodium ; # The generated tables and llms.txt are what doc/tables/generate.py writes # from doc/tables/crypto.json and the tests: the build fails when they are diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 68a94641..00273c36 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -27,4 +27,5 @@ of every version are on webcpp's index page. * Added the link-time canaries of BearSSL, ctaes and libsecp256k1, and their own suites on webcpp's build. * Added backends::sodium and its link-time canary on /third_party//sodium, which webcpp::hash shares, and libsodium's initialisation every engine calls first. * Added the page: a chapter per namespace and use case, the memory option's guide and example, tables generated from the tests, every Jamfile and message, and llms.txt. +* Added secret, a self-wiping array that is copied only by clone, and the errors 15 to 20: weak_public_key, invalid_point, invalid_scalar, invalid_padding, invalid_encoding and invalid_ciphertext_size. // end::unreleased[] diff --git a/doc/errors.adoc b/doc/errors.adoc index d74d7c61..c4bedad8 100644 --- a/doc/errors.adoc +++ b/doc/errors.adoc @@ -46,6 +46,14 @@ already allocated, or another party installed its own. From `backends::openssl:: with `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE`. |14 |`memory_functions_not_installed` |OpenSSL's memory functions are not webcpp::crypto's. From every `make` of the OpenSSL backend, with `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE`. +|15 |`weak_public_key` |A public key of small order, or one that gives an all-zero shared secret. +|16 |`invalid_point` |An encoding that is not a canonical element of the group. +|17 |`invalid_scalar` |A scalar that is not reduced, or zero where zero is refused. +|18 |`invalid_padding` |Padding that cannot be removed, whatever the cause: one value for every +cause, so that no padding oracle is built from it. +|19 |`invalid_encoding` |Hexadecimal, base64, PEM, or a key's DER form that does not decode, or is +not the one encoding the format allows. +|20 |`invalid_ciphertext_size` |A KEM or RSA ciphertext of another size than the key's. |=== A value that `error` does not define diff --git a/include/webcpp/crypto.hpp b/include/webcpp/crypto.hpp index 2c68ce59..b152c2e1 100644 --- a/include/webcpp/crypto.hpp +++ b/include/webcpp/crypto.hpp @@ -21,6 +21,7 @@ #include #include #include // lint-world: the system's entropy, a purpose of crypto +#include #ifdef WEBCPP_CRYPTO_HAS_BEARSSL #include diff --git a/include/webcpp/crypto/error.hpp b/include/webcpp/crypto/error.hpp index 408997f7..56bc3db6 100644 --- a/include/webcpp/crypto/error.hpp +++ b/include/webcpp/crypto/error.hpp @@ -79,6 +79,21 @@ enum class error : int { * refuses to run, with `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE`. */ memory_functions_not_installed = 14, + /** A public key of small order, or one that gives an all-zero shared secret. */ + weak_public_key = 15, + /** An encoding that is not a canonical element of the group. */ + invalid_point = 16, + /** A scalar that is not reduced, or zero where zero is refused. */ + invalid_scalar = 17, + /** Padding that cannot be removed, whatever the cause. */ + invalid_padding = 18, + /** + * Hexadecimal, base64, PEM, or a key's DER form that does not decode, or is not the one + * encoding the format allows. + */ + invalid_encoding = 19, + /** A KEM or RSA ciphertext of another size than the key's. */ + invalid_ciphertext_size = 20, }; namespace detail { @@ -109,6 +124,13 @@ inline const char* message_of(int error_value) noexcept { return "OpenSSL's memory functions are not webcpp::crypto's. Call " "backends::openssl::install_memory_functions() as the first statement of " "main, and let nothing else call CRYPTO_set_mem_functions."; + case error::weak_public_key: + return "the public key is weak: of small order, or the shared secret is zero"; + case error::invalid_point: return "the encoding is not a canonical element of the group"; + case error::invalid_scalar: return "the scalar is not reduced, or is zero"; + 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"; } return "unknown webcpp.crypto error"; } diff --git a/include/webcpp/crypto/secret.hpp b/include/webcpp/crypto/secret.hpp new file mode 100644 index 00000000..cddf8d8e --- /dev/null +++ b/include/webcpp/crypto/secret.hpp @@ -0,0 +1,82 @@ +// 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 secret output of webcpp::crypto, which wipes itself (design D9). */ +#ifndef WEBCPP_CRYPTO_SECRET_HPP +#define WEBCPP_CRYPTO_SECRET_HPP + +#include + +#include + +#include +#include +#include +#include + +namespace webcpp::crypto { + +/** + `N` secret bytes: a shared secret, a session key, a converted secret key. They are wiped by + volatile stores when the object is destroyed or moved from; a copy is made only by `clone`. + + @tparam N The number of bytes. +*/ +template +class secret { +public: + /** The number of bytes. */ + static constexpr std::size_t size_bytes = N; + + /** Zero bytes. */ + secret() noexcept = default; + + /** Takes the bytes of `other`, which is wiped. */ + secret(secret&& other) noexcept : bytes_(other.bytes_) { detail::wipe_object(other.bytes_); } + + /** Takes the bytes of `other` over these, which are wiped first; `other` is wiped. */ + secret& operator=(secret&& other) noexcept { + if (this != &other) { + bytes_ = other.bytes_; + detail::wipe_object(other.bytes_); + } + return *this; + } + + /** Not copyable: a copy is asked for by name, with `clone`. */ + secret(secret const&) = delete; + /** Not copyable: a copy is asked for by name, with `clone`. */ + secret& operator=(secret const&) = delete; + + /** Wipes the bytes. */ + ~secret() { detail::wipe_object(bytes_); } + + /** A copy of the bytes, which the caller then owns. */ + [[nodiscard]] secret clone() const noexcept { + secret copy; + copy.bytes_ = bytes_; + return copy; + } + + /** The bytes, to read. */ + [[nodiscard]] std::span bytes() const noexcept { return bytes_; } + + /** The bytes, for the library's engines to write. */ + [[nodiscard]] std::span writable() noexcept { return bytes_; } + + /** The bytes, as a span of fixed size. */ + operator std::span() const noexcept { return bytes_; } + + /** The number of bytes. */ + static constexpr std::size_t size() noexcept { return N; } + +private: + std::array bytes_{}; +}; + +} // namespace webcpp::crypto + +#endif // WEBCPP_CRYPTO_SECRET_HPP diff --git a/test/Jamfile b/test/Jamfile index dbd8ff73..606fb3c7 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -24,7 +24,7 @@ webcpp.headers-alone crypto : ../include : crypto.hpp crypto/config.hpp crypto/equal.hpp crypto/error.hpp crypto/ciphers/aes.hpp crypto/ciphers/gcm.hpp crypto/random_device.hpp crypto/detail/declassify.hpp crypto/detail/engines.hpp crypto/detail/entropy.hpp crypto/detail/limits.hpp crypto/detail/windows.hpp - crypto/detail/wipe.hpp ; + crypto/detail/wipe.hpp crypto/secret.hpp ; # The backend BearSSL's header and the default backend's, with BearSSL linked, # on every target. @@ -67,6 +67,8 @@ crypto-run equal : equal_test.cpp ; # alone, with no backend linked, compiles, links and runs. crypto-run convenience_header : convenience_header_test.cpp ; crypto-run wipe : wipe_test.cpp ; +# secret is not copyable, moves wipe the source, and the destructor wipes the storage, at -O2. +crypto-run secret : secret_test.cpp : speed ; # A destroyed or moved-from key schedule is zero in its storage, read at -O2 # where a dropped store would show: one program per keyed type, one source. diff --git a/test/error_test.cpp b/test/error_test.cpp index b56beef1..472b2f4b 100644 --- a/test/error_test.cpp +++ b/test/error_test.cpp @@ -37,6 +37,12 @@ int main() { BOOST_TEST_EQ(static_cast(error::backend_failure), 12); BOOST_TEST_EQ(static_cast(error::memory_functions_refused), 13); BOOST_TEST_EQ(static_cast(error::memory_functions_not_installed), 14); + BOOST_TEST_EQ(static_cast(error::weak_public_key), 15); + BOOST_TEST_EQ(static_cast(error::invalid_point), 16); + BOOST_TEST_EQ(static_cast(error::invalid_scalar), 17); + 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::system::error_code const code = error::authentication_failed; BOOST_TEST_EQ(std::string_view(code.category().name()), "webcpp.crypto"); @@ -69,15 +75,28 @@ int main() { "the authentication tag does not match"); BOOST_TEST_EQ(std::string_view(buffer.data()), "the aut"); + BOOST_TEST_EQ(crypto::make_error_code(error::weak_public_key).message(), + "the public key is weak: of small order, or the shared secret is zero"); + BOOST_TEST_EQ(crypto::make_error_code(error::invalid_point).message(), + "the encoding is not a canonical element of the group"); + BOOST_TEST_EQ(crypto::make_error_code(error::invalid_scalar).message(), + "the scalar is not reduced, or is zero"); + BOOST_TEST_EQ(crypto::make_error_code(error::invalid_padding).message(), + "the padding is not valid"); + BOOST_TEST_EQ(crypto::make_error_code(error::invalid_encoding).message(), + "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"); + // Every defined value has its own message, never the unknown one. std::set messages; - for (int value = 1; value <= 14; ++value) { + for (int value = 1; value <= 20; ++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(), 14u); + BOOST_TEST_EQ(messages.size(), 20u); // 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/secret_test.cpp b/test/secret_test.cpp new file mode 100644 index 00000000..b0831351 --- /dev/null +++ b/test/secret_test.cpp @@ -0,0 +1,114 @@ +// 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) + +// secret is not copyable, clone copies by name, a move leaves the source zero, it converts to +// a span of fixed size, and its storage is zero after its destructor, read at -O2 (the Jamfile's +// speed), where a store the optimiser may drop is the case. + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace crypto = webcpp::crypto; + +using key = crypto::secret<32>; + +static_assert(!std::is_copy_constructible_v); +static_assert(!std::is_copy_assignable_v); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_move_assignable_v); +static_assert(std::is_convertible_v>); +static_assert(key::size() == 32 && key::size_bytes == 32); +static_assert(sizeof(key) == 32); + +void fill(key& target, std::uint8_t first) { + auto const bytes = target.writable(); + for (std::size_t i = 0; i < bytes.size(); ++i) { + bytes[i] = static_cast(first + i); + } +} + +bool is_zero(key const& source) { + for (std::uint8_t const byte : source.bytes()) { + if (byte != 0) { + return false; + } + } + return true; +} + +// Whether any byte of the storage is not zero, read through a volatile pointer. +bool any_set(std::array const& storage) { + auto const* const bytes = reinterpret_cast(storage.data()); + for (std::size_t i = 0; i < storage.size(); ++i) { + if (bytes[i] != 0) { + return true; + } + } + return false; +} + +} // namespace + +int main() { + // A new secret is zero. + key const zero; + BOOST_TEST(is_zero(zero)); + + // clone copies, and the two are then independent. + key original; + fill(original, 1); + key copy = original.clone(); + BOOST_TEST(!is_zero(original)); + BOOST_TEST(std::equal(copy.bytes().begin(), copy.bytes().end(), original.bytes().begin())); + copy.writable()[0] = 0xee; + BOOST_TEST_EQ(original.bytes()[0], 1); + + // A move construction leaves the source zero and the destination with the bytes. + key from; + fill(from, 7); + key const expected = from.clone(); + key to(std::move(from)); + BOOST_TEST(is_zero(from)); + BOOST_TEST(std::equal(to.bytes().begin(), to.bytes().end(), expected.bytes().begin())); + + // A move assignment does too, over the destination's own bytes. + key assigned; + fill(assigned, 100); + key source; + fill(source, 7); + assigned = std::move(source); + BOOST_TEST(is_zero(source)); + BOOST_TEST( + std::equal(assigned.bytes().begin(), assigned.bytes().end(), expected.bytes().begin())); + + // The conversion to a span of fixed size views the same bytes. + std::span const view = expected; + BOOST_TEST(view.data() == expected.bytes().data()); + BOOST_TEST_EQ(view.size(), 32u); + + // After the destructor, the storage is zero. + alignas(key) std::array storage{}; + auto* const placed = new (storage.data()) key; + fill(*placed, 1); + BOOST_TEST(any_set(storage)); + std::destroy_at(placed); + BOOST_TEST(!any_set(storage)); + + return webcpp::test::exit_status(boost::report_errors()); +} From 5eb91131a260c26126e4ae356cdb983aec0e9151 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 10:53:56 -0300 Subject: [PATCH 003/110] crypto: secret, and the errors 15 to 20 --- include/webcpp/crypto/secret.hpp | 49 ++++++++++++++++++++++++++------ 1 file changed, 40 insertions(+), 9 deletions(-) diff --git a/include/webcpp/crypto/secret.hpp b/include/webcpp/crypto/secret.hpp index cddf8d8e..1252144d 100644 --- a/include/webcpp/crypto/secret.hpp +++ b/include/webcpp/crypto/secret.hpp @@ -20,8 +20,10 @@ namespace webcpp::crypto { /** - `N` secret bytes: a shared secret, a session key, a converted secret key. They are wiped by - volatile stores when the object is destroyed or moved from; a copy is made only by `clone`. + `N` secret bytes: a shared secret, a session key, a converted secret key. + + They are wiped by volatile stores when the object is destroyed or moved from; a copy is made + only by `clone`. @tparam N The number of bytes. */ @@ -34,10 +36,19 @@ class secret { /** Zero bytes. */ secret() noexcept = default; - /** Takes the bytes of `other`, which is wiped. */ + /** + Takes the bytes of `other`, which is wiped. + + @param other The secret to take the bytes of. + */ secret(secret&& other) noexcept : bytes_(other.bytes_) { detail::wipe_object(other.bytes_); } - /** Takes the bytes of `other` over these, which are wiped first; `other` is wiped. */ + /** + Takes the bytes of `other` over these, which are wiped first; `other` is wiped. + + @param other The secret to take the bytes of. + @return This secret. + */ secret& operator=(secret&& other) noexcept { if (this != &other) { bytes_ = other.bytes_; @@ -54,23 +65,43 @@ class secret { /** Wipes the bytes. */ ~secret() { detail::wipe_object(bytes_); } - /** A copy of the bytes, which the caller then owns. */ + /** + A copy of the bytes, which the caller then owns. + + @return A secret of the same bytes. + */ [[nodiscard]] secret clone() const noexcept { secret copy; copy.bytes_ = bytes_; return copy; } - /** The bytes, to read. */ + /** + The bytes, to read. + + @return A view of the bytes. + */ [[nodiscard]] std::span bytes() const noexcept { return bytes_; } - /** The bytes, for the library's engines to write. */ + /** + The bytes, for the library's engines to write. + + @return A writable view of the bytes. + */ [[nodiscard]] std::span writable() noexcept { return bytes_; } - /** The bytes, as a span of fixed size. */ + /** + The bytes, as a span of fixed size. + + @return A view of the bytes. + */ operator std::span() const noexcept { return bytes_; } - /** The number of bytes. */ + /** + The number of bytes. + + @return `N`. + */ static constexpr std::size_t size() noexcept { return N; } private: From 5d759c42cb225982359fe0da7347b1e863f245d8 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 11:04:37 -0300 Subject: [PATCH 004/110] crypto: secret's tests catch a dead-store wipe; no views of a dying secret; the wipe's reach is documented --- include/webcpp/crypto/secret.hpp | 36 ++++++++++++-- test/Jamfile | 2 +- test/secret_test.cpp | 84 ++++++++++++++++++++++++++++++-- 3 files changed, 114 insertions(+), 8 deletions(-) diff --git a/include/webcpp/crypto/secret.hpp b/include/webcpp/crypto/secret.hpp index 1252144d..52108d6f 100644 --- a/include/webcpp/crypto/secret.hpp +++ b/include/webcpp/crypto/secret.hpp @@ -25,10 +25,15 @@ namespace webcpp::crypto { They are wiped by volatile stores when the object is destroyed or moved from; a copy is made only by `clone`. + The wipe covers the object's own storage only: a move or a `clone` may leave copies of the bytes in + registers or temporaries, which the library does not reach. + @tparam N The number of bytes. */ template class secret { + static_assert(N > 0, "a secret of no bytes holds nothing"); + public: /** The number of bytes. */ static constexpr std::size_t size_bytes = N; @@ -44,13 +49,15 @@ class secret { secret(secret&& other) noexcept : bytes_(other.bytes_) { detail::wipe_object(other.bytes_); } /** - Takes the bytes of `other` over these, which are wiped first; `other` is wiped. + Wipes these bytes, then takes the bytes of `other`, which is wiped; a move to itself changes + nothing. @param other The secret to take the bytes of. @return This secret. */ secret& operator=(secret&& other) noexcept { if (this != &other) { + detail::wipe_object(bytes_); bytes_ = other.bytes_; detail::wipe_object(other.bytes_); } @@ -81,21 +88,42 @@ class secret { @return A view of the bytes. */ - [[nodiscard]] std::span bytes() const noexcept { return bytes_; } + [[nodiscard]] std::span bytes() const& noexcept { return bytes_; } + + /** + Not available on a secret that is about to be destroyed: the view would dangle. + + @return Nothing. + */ + std::span bytes() const&& = delete; /** The bytes, for the library's engines to write. @return A writable view of the bytes. */ - [[nodiscard]] std::span writable() noexcept { return bytes_; } + [[nodiscard]] std::span writable() & noexcept { return bytes_; } + + /** + Not available on a secret that is about to be destroyed: the view would dangle. + + @return Nothing. + */ + std::span writable() && = delete; /** The bytes, as a span of fixed size. @return A view of the bytes. */ - operator std::span() const noexcept { return bytes_; } + operator std::span() const& noexcept { return bytes_; } + + /** + Not available on a secret that is about to be destroyed: the view would dangle. + + @return Nothing. + */ + operator std::span() const&& = delete; /** The number of bytes. diff --git a/test/Jamfile b/test/Jamfile index 606fb3c7..d46bdbf5 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -68,7 +68,7 @@ crypto-run equal : equal_test.cpp ; crypto-run convenience_header : convenience_header_test.cpp ; crypto-run wipe : wipe_test.cpp ; # secret is not copyable, moves wipe the source, and the destructor wipes the storage, at -O2. -crypto-run secret : secret_test.cpp : speed ; +crypto-run secret : secret_test.cpp : speed full ; # A destroyed or moved-from key schedule is zero in its storage, read at -O2 # where a dropped store would show: one program per keyed type, one source. diff --git a/test/secret_test.cpp b/test/secret_test.cpp index b0831351..894bffe5 100644 --- a/test/secret_test.cpp +++ b/test/secret_test.cpp @@ -13,6 +13,7 @@ #include +#include #include #include #include @@ -36,6 +37,27 @@ static_assert(std::is_convertible_v +concept views_lvalue = requires(T& k) { k.bytes(); } && requires(T& k) { k.writable(); }; +template +concept views_const_lvalue = requires(T const& k) { k.bytes(); }; +template +concept writes_const_lvalue = requires(T const& k) { k.writable(); }; +template +concept views_rvalue_bytes = requires { T{}.bytes(); }; +template +concept views_rvalue_writable = requires { T{}.writable(); }; +template +concept spans_rvalue = std::is_convertible_v>; + +static_assert(views_lvalue); +static_assert(views_const_lvalue); +static_assert(!writes_const_lvalue); +static_assert(!views_rvalue_bytes); +static_assert(!views_rvalue_writable); +static_assert(!spans_rvalue); + void fill(key& target, std::uint8_t first) { auto const bytes = target.writable(); for (std::size_t i = 0; i < bytes.size(); ++i) { @@ -43,15 +65,51 @@ void fill(key& target, std::uint8_t first) { } } -bool is_zero(key const& source) { - for (std::uint8_t const byte : source.bytes()) { - if (byte != 0) { +// A function the optimiser cannot see into, so that what it is handed is read from memory. +#if defined(_MSC_VER) && !defined(__clang__) +#define WEBCPP_TEST_NOINLINE __declspec(noinline) +#else +#define WEBCPP_TEST_NOINLINE __attribute__((noinline)) +#endif + +// Whether every byte at `where` is zero, read through a volatile pointer in a function that is +// never inlined: a store that was dropped before the call is found here. It may be handed the +// address of an object that is gone (the point of the destructor's check), so it is exempt from +// the sanitizers that would stop that read. +#if defined(__clang__) || defined(__GNUC__) +__attribute__((no_sanitize("address"))) +#endif +WEBCPP_TEST_NOINLINE bool memory_is_zero(std::uint8_t const* where, std::size_t count) { + auto const volatile* const bytes = where; + for (std::size_t i = 0; i < count; ++i) { + if (bytes[i] != 0) { return false; } } return true; } +// The same, for a secret that is alive. +bool is_zero(key const& source) { + return memory_is_zero(source.bytes().data(), source.bytes().size()); +} + +// A secret in a scope of its own, which a call the optimiser cannot see into is handed, is +// destroyed; its storage, in this frame, is read after the scope. A wipe that is a dead store +// (a plain write to an object about to die) is dropped by the optimiser and the bytes remain. +WEBCPP_TEST_NOINLINE bool destruction_leaves_zero() { + std::uint8_t const* where = nullptr; + { + key local; + fill(local, 1); + where = local.bytes().data(); + if (memory_is_zero(where, key::size())) { + return false; + } + } + return memory_is_zero(where, key::size()); +} + // Whether any byte of the storage is not zero, read through a volatile pointer. bool any_set(std::array const& storage) { auto const* const bytes = reinterpret_cast(storage.data()); @@ -70,6 +128,9 @@ int main() { key const zero; BOOST_TEST(is_zero(zero)); + // A secret that is destroyed in an ordinary scope leaves zero behind, at -O2. + BOOST_TEST(destruction_leaves_zero()); + // clone copies, and the two are then independent. key original; fill(original, 1); @@ -97,6 +158,23 @@ int main() { BOOST_TEST( std::equal(assigned.bytes().begin(), assigned.bytes().end(), expected.bytes().begin())); + // A move assignment to itself keeps the bytes; clone of a moved-from secret is zero. + { + key self; + fill(self, 9); + key& alias = self; + self = std::move(alias); + BOOST_TEST(!is_zero(self)); + BOOST_TEST_EQ(self.bytes()[0], 9); + + key gone; + fill(gone, 5); + key taker(std::move(gone)); + key const empty = gone.clone(); + BOOST_TEST(is_zero(empty)); + BOOST_TEST(!is_zero(taker)); + } + // The conversion to a span of fixed size views the same bytes. std::span const view = expected; BOOST_TEST(view.data() == expected.bytes().data()); From a3eac7586f55150bde6abf0593dab6c675d10357 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 11:31:18 -0300 Subject: [PATCH 005/110] crypto: the changelog's Unreleased holds ten lines at most, as the lint's changelog form asks: the lines of related changes are one --- doc/changelog.adoc | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 00273c36..338a88e4 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -17,15 +17,12 @@ of every version are on webcpp's index page. // tag::unreleased[] * Added crypto, primitives over C backends: ciphers, curves and randomness, with errors of fixed values in webcpp.crypto, every result `+[[nodiscard]]+`. -* Added equal and random_device, and ciphers::aes128, aes192 and aes256, the AES block cipher. -* Added ciphers::gcm, AES-GCM in place with an incremental seal, whose failed open zeroes the data. +* Added equal, random_device, ciphers::aes128, aes192 and aes256, the AES block cipher, and ciphers::gcm, AES-GCM in place with an incremental seal whose failed open zeroes the data. * Added the default backend, ciphers::aes128_gcm and aes256_gcm, and the refusals of backends that conflict. -* Added backends::bearssl: AES-GCM on every target allocating nothing, the block cipher refused, and the Jamfile line a program lacks without it. -* Added backends::openssl, /webcpp/crypto//openssl on native and WASI, allocating nothing after make; WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE: OpenSSL's allocations in the program's resource, refused on WebAssembly (WASI included) and without OpenSSL: openssl_memory_resource, install_memory_functions, memory_functions_refused, memory_functions_not_installed. -* Added backends::ctaes, the AES block cipher alone on every target; ciphers::gcm refuses it. +* Added backends::bearssl on every target, backends::openssl with /webcpp/crypto//openssl on native and WASI, and backends::ctaes: AES-GCM allocating nothing per message, the block cipher on OpenSSL and ctaes. +* Added WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE: OpenSSL's allocations in the program's resource, refused on WebAssembly (WASI included) and without OpenSSL: openssl_memory_resource, install_memory_functions, memory_functions_refused, memory_functions_not_installed. * Added curves::secp256k1: key pairs, BIP340 and ECDSA signatures, ECDH, strict DER, low-S and the x-only tweak. -* Added the link-time canaries of BearSSL, ctaes and libsecp256k1, and their own suites on webcpp's build. -* Added backends::sodium and its link-time canary on /third_party//sodium, which webcpp::hash shares, and libsodium's initialisation every engine calls first. +* Added backends::sodium on /third_party//sodium, which webcpp::hash shares, and every backend's link-time canary, with the C libraries' own suites on webcpp's build. * Added the page: a chapter per namespace and use case, the memory option's guide and example, tables generated from the tests, every Jamfile and message, and llms.txt. * Added secret, a self-wiping array that is copied only by clone, and the errors 15 to 20: weak_public_key, invalid_point, invalid_scalar, invalid_padding, invalid_encoding and invalid_ciphertext_size. // end::unreleased[] From a07da77c748b685a4c6673e409a31c27fe2ad1be Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 11:31:32 -0300 Subject: [PATCH 006/110] crypto: sodium_ready's result is [[nodiscard]], as the lint's rule asks of every result --- include/webcpp/crypto/backends/sodium.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/webcpp/crypto/backends/sodium.hpp b/include/webcpp/crypto/backends/sodium.hpp index 418010f6..288cd585 100644 --- a/include/webcpp/crypto/backends/sodium.hpp +++ b/include/webcpp/crypto/backends/sodium.hpp @@ -60,7 +60,7 @@ namespace webcpp::crypto::detail { @return Nothing; `backend_failure` when `sodium_init` returns -1. */ -inline boost::system::result sodium_ready() noexcept { +[[nodiscard]] inline boost::system::result sodium_ready() noexcept { read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); if (sodium_init() < 0) { return error::backend_failure; From 47438a48925bbb809f28501457c8a8be980d6a6e Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 11:41:01 -0300 Subject: [PATCH 007/110] crypto: the aggregate's headers-alone line links libsodium, so that every public header, backends/sodium.hpp included, compiles in the lint's aggregate --- test/Jamfile | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/Jamfile b/test/Jamfile index d46bdbf5..b6214677 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -31,14 +31,14 @@ webcpp.headers-alone crypto : ../include : crypto.hpp crypto/config.hpp webcpp.headers-alone crypto : ../include : crypto/ciphers/aes256_gcm.hpp crypto/backends/bearssl.hpp : /third_party//bearssl ; -# The backend OpenSSL's header, with OpenSSL linked and selected; BearSSL, ctaes -# and libsecp256k1 are linked too, so that every public header compiles with -# these options (the lint's aggregate translation unit, +# The backend OpenSSL's header, with OpenSSL linked and selected; BearSSL, +# ctaes, libsecp256k1 and libsodium are linked too, so that every public +# header compiles with these options (the lint's aggregate translation unit, # tools/lint/compile_commands.py). webcpp.headers-alone crypto : ../include : crypto/backends/openssl.hpp : /webcpp/crypto//openssl /third_party//bearssl /third_party//ctaes /third_party//secp256k1 - WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL + /third_party//sodium WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL : native wasip2 wasip3 ; # The backend ctaes's header alone, with ctaes linked, on every target. webcpp.headers-alone crypto : ../include : crypto/backends/ctaes.hpp From beabd27da5db833e0626e1390bb270a4899068ed Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 11:48:57 -0300 Subject: [PATCH 008/110] crypto: secret's conversion to its span stays implicit, as the spec asks, and clang-tidy's misc-explicit-constructor is silenced for it --- include/webcpp/crypto/secret.hpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/include/webcpp/crypto/secret.hpp b/include/webcpp/crypto/secret.hpp index 52108d6f..dcc665fc 100644 --- a/include/webcpp/crypto/secret.hpp +++ b/include/webcpp/crypto/secret.hpp @@ -116,6 +116,9 @@ class secret { @return A view of the bytes. */ + // Implicit, as the spec asks, so that a secret is passed where a function takes the span of + // its bytes: misc-explicit-constructor is silenced for it. + // NOLINTNEXTLINE(misc-explicit-constructor) operator std::span() const& noexcept { return bytes_; } /** From e3aad772971b0eeebc4e4ae7afdc79ac22e0ba3f Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 12:04:14 -0300 Subject: [PATCH 009/110] crypto: the capability table, supports_v and the generated refusals doc/tables/crypto.json gains its families (gcm, aes_block, secp256k1): per family its algorithms, per backend the targets on which it has them, each claimed only where a test of the family's operations runs, constant time where it is not the backend's design, and the default per target with its reason. generate.py checks them and writes from them include/webcpp/crypto/detail/capabilities.hpp (the family and algorithm tags, detail::supported per cell and target, each family's refusal macro naming the backends that have it) and test/capabilities_test.cpp, which asserts every cell and makes every present one on each target. supports_v reads the table; ciphers::gcm, the AES block cipher and secp256k1's key pair name their family_type and name_type. --- doc/backends.adoc | 8 + doc/changelog.adoc | 1 + doc/tables/crypto.json | 86 +++++- doc/tables/generate.py | 291 +++++++++++++++++- doc/tables/generate_test.py | 169 +++++++++- include/webcpp/crypto.hpp | 1 + include/webcpp/crypto/ciphers/aes.hpp | 8 + include/webcpp/crypto/ciphers/gcm.hpp | 11 + include/webcpp/crypto/config.hpp | 3 + include/webcpp/crypto/curves/secp256k1.hpp | 5 + include/webcpp/crypto/detail/capabilities.hpp | 169 ++++++++++ include/webcpp/crypto/detail/engines.hpp | 4 + include/webcpp/crypto/supports.hpp | 40 +++ test/Jamfile | 20 +- test/capabilities_test.cpp | 226 ++++++++++++++ test/support/capabilities.hpp | 53 ++++ 16 files changed, 1079 insertions(+), 16 deletions(-) create mode 100644 include/webcpp/crypto/detail/capabilities.hpp create mode 100644 include/webcpp/crypto/supports.hpp create mode 100644 test/capabilities_test.cpp create mode 100644 test/support/capabilities.hpp diff --git a/doc/backends.adoc b/doc/backends.adoc index 49e9377b..62646971 100644 --- a/doc/backends.adoc +++ b/doc/backends.adoc @@ -16,6 +16,14 @@ that target, and refused where a message test stops it. The data and the tables are regenerated, and checked by the documentation's build, at every change of a test or a pin. +A program asks the same table in {cpp}: `supports_v`, in +``, is `true` exactly where the table says that +the backend has the algorithm on the target being compiled, and needs neither +the backend's header nor its library, so that generic code can choose a +backend at compile time. Each algorithm's type names its family and its +algorithm for it (`family_type` and `name_type`, tags of `families` and +`tags`); the test that asserts every cell is generated from the same data. + [#crypto-backends-matrix] === Operations, backends and targets diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 338a88e4..456cced2 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -24,5 +24,6 @@ of every version are on webcpp's index page. * Added curves::secp256k1: key pairs, BIP340 and ECDSA signatures, ECDH, strict DER, low-S and the x-only tweak. * Added backends::sodium on /third_party//sodium, which webcpp::hash shares, and every backend's link-time canary, with the C libraries' own suites on webcpp's build. * Added the page: a chapter per namespace and use case, the memory option's guide and example, tables generated from the tests, every Jamfile and message, and llms.txt. +* Added supports_v, the capability table on the target being compiled, and the tags of its families and algorithms, which ciphers::gcm, the AES block cipher and secp256k1's key pair name. * Added secret, a self-wiping array that is copied only by clone, and the errors 15 to 20: weak_public_key, invalid_point, invalid_scalar, invalid_padding, invalid_encoding and invalid_ciphertext_size. // end::unreleased[] diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 5babe0f9..d70426e9 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -1,5 +1,5 @@ { - "comment": "The data of crypto's generated tables and of llms.txt; doc/tables/generate.py reads it with the test Jamfiles, the message tests and the superproject's Jamfile fixtures, and writes doc/generated/ and doc/llms.txt. A name in a text is written between backticks, as Markdown writes code: the tables show it as code and llms.txt keeps the backticks. Edit this file, then run python3 libs/crypto/doc/tables/generate.py; the doc build runs it with --check.", + "comment": "The data of crypto's generated tables and of llms.txt; doc/tables/generate.py reads it with the test Jamfiles, the message tests and the superproject's Jamfile fixtures, and writes doc/generated/, doc/llms.txt, include/webcpp/crypto/detail/capabilities.hpp and test/capabilities_test.cpp. The capability table is `families`: per family its algorithms, the targets on which each backend has it (each claimed only where a test of the family's operations on that backend runs), constant time where it is not by the backend's design, and the default per target with its reason; a backend with `targets`, where it is built, is a tag of `backends`. A name in a text is written between backticks, as Markdown writes code: the tables show it as code and llms.txt keeps the backticks. Edit this file, then run python3 libs/crypto/doc/tables/generate.py; the doc build runs it with --check.", "page": "https://webcpporg.github.io/libs/crypto/", "targets": ["native", "wasip2", "wasip3", "emscripten"], "sources": { @@ -66,6 +66,7 @@ "bearssl": { "title": "BearSSL", "jamfile": "/third_party//bearssl", + "targets": ["native", "wasip2", "wasip3", "emscripten"], "header": "", "library": "BearSSL, commit 7bea48e5 of the mirror webcpporg/bearssl, built from source", "licence": "MIT", @@ -77,6 +78,7 @@ "openssl": { "title": "OpenSSL", "jamfile": "/webcpp/crypto//openssl", + "targets": ["native", "wasip2", "wasip3"], "header": "", "library": "OpenSSL 3.5.9's libcrypto, built from source and static", "licence": "Apache-2.0", @@ -88,6 +90,7 @@ "ctaes": { "title": "ctaes", "jamfile": "/third_party//ctaes", + "targets": ["native", "wasip2", "wasip3", "emscripten"], "header": "", "library": "ctaes as Bitcoin Core v31.1 ships it (`src/crypto/ctaes`), built from source", "licence": "MIT", @@ -99,6 +102,7 @@ "secp256k1": { "title": "libsecp256k1", "jamfile": "/third_party//secp256k1", + "targets": ["native", "wasip2", "wasip3", "emscripten"], "header": "", "library": "libsecp256k1 v0.8.0, built from source with every module on", "licence": "MIT", @@ -107,6 +111,14 @@ "constant_time": "by design: signing and key generation are constant time and constant memory access", "constant_time_sources": ["libsecp256k1"] }, + "sodium": { + "title": "libsodium", + "jamfile": "/third_party//sodium", + "targets": ["native", "wasip2", "wasip3", "emscripten"], + "header": "", + "library": "libsodium 1.0.22, built from source", + "licence": "ISC" + }, "system": { "title": "the system's generator", "jamfile": "/webcpp/crypto//crypto", @@ -163,6 +175,7 @@ }, { "id": "aes_block", + "family": "aes_block", "functions": ["make", "encrypt", "decrypt"], "namespace": "ciphers", "api": "ciphers::aes128, aes192, aes256", @@ -178,6 +191,7 @@ }, { "id": "gcm", + "family": "gcm", "functions": ["make", "seal", "open", "begin_seal", "update", "result"], "namespace": "ciphers", "api": "ciphers::gcm, aes128_gcm, aes256_gcm", @@ -195,6 +209,7 @@ }, { "id": "keypair", + "family": "secp256k1", "functions": ["make", "xonly_public_key", "public_key", "sign_schnorr", "sign_ecdsa", "ecdh", "tweak_xonly"], "namespace": "curves", "api": "curves::secp256k1::keypair", @@ -205,6 +220,7 @@ }, { "id": "verify", + "family": "secp256k1", "functions": ["verify_schnorr", "verify_ecdsa"], "namespace": "curves", "api": "curves::secp256k1::verify_schnorr, verify_ecdsa", @@ -215,6 +231,7 @@ }, { "id": "encodings", + "family": "secp256k1", "functions": ["to_der", "from_der", "normalize_ecdsa"], "namespace": "curves", "api": "curves::secp256k1::to_der, from_der, normalize_ecdsa", @@ -225,6 +242,7 @@ }, { "id": "tweak", + "family": "secp256k1", "free": true, "functions": ["tweak_xonly"], "namespace": "curves", @@ -245,6 +263,72 @@ "backends": {"openssl": {"tests": ["adapter", "everything", "late", "foreign", "fresh_install", "forgotten", "replaced", "second_install", "fail_second", "fail_init", "fail_init_threads", "neighbours", "handshake"], "elsewhere": "memory"}} } ], + "families": [ + { + "name": "gcm", + "title": "AES-GCM", + "group": "ciphers", + "since": "0.1", + "header": "", + "names": [ + {"name": "aes128_gcm", "title": "AES-128-GCM", "type": "ciphers::gcm>"}, + {"name": "aes192_gcm", "title": "AES-192-GCM", "type": "ciphers::gcm>"}, + {"name": "aes256_gcm", "title": "AES-256-GCM", "type": "ciphers::gcm>"} + ], + "default": [ + {"targets": ["native"], "backend": "openssl", "why": "OpenSSL's assembly uses the CPU's AES and carry-less multiplication instructions on x86-64 and ARMv8 ({openssl-armv8}; {openssl-ghash-asm}); BearSSL has them on x86 only ({bearssl-aes})"}, + {"targets": ["wasip2", "wasip3"], "backend": "bearssl", "why": "constant time by design ({bearssl-ct}), where OpenSSL is built no-asm and its AES and GHASH are table-based ({openssl-install})"}, + {"targets": ["emscripten"], "backend": "bearssl", "why": "the only backend there: webcpp does not build OpenSSL for Emscripten; constant time by design ({bearssl-ct})"} + ], + "backends": { + "bearssl": {"targets": "all"}, + "openssl": {"targets": "all", "constant_time": { + "native": "with assembly (Clang and GCC), AES-NI and carry-less multiplication where the CPU has them; built no-asm on MSVC, table-based AES and 4-bit GHASH, neither constant time ({openssl-install})", + "wasip2": "not constant time: built no-asm, table-based AES and 4-bit GHASH ({openssl-install}; {openssl-aes-core})", + "wasip3": "not constant time: built no-asm, table-based AES and 4-bit GHASH ({openssl-install}; {openssl-aes-core})" + }} + } + }, + { + "name": "aes_block", + "title": "AES block cipher", + "group": "ciphers", + "since": "0.1", + "header": "", + "names": [ + {"name": "aes128", "title": "AES-128", "type": "ciphers::aes128<{backend}>"}, + {"name": "aes192", "title": "AES-192", "type": "ciphers::aes192<{backend}>"}, + {"name": "aes256", "title": "AES-256", "type": "ciphers::aes256<{backend}>"} + ], + "default": [ + {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": null, "why": "none: a raw block cipher is a building block a program chooses deliberately, naming its backend; `aes256<>` takes AES-GCM's default as its argument, and its `make` does not compile where that is BearSSL"} + ], + "backends": { + "openssl": {"targets": "all", "constant_time": { + "native": "with assembly (Clang and GCC), AES-NI where the CPU has it; built no-asm on MSVC, table-based AES, not constant time ({openssl-install})", + "wasip2": "not constant time: built no-asm, table-based AES ({openssl-install}; {openssl-aes-core})", + "wasip3": "not constant time: built no-asm, table-based AES ({openssl-install}; {openssl-aes-core})" + }}, + "ctaes": {"targets": "all"} + } + }, + { + "name": "secp256k1", + "title": "secp256k1", + "group": "curves::secp256k1", + "since": "0.1", + "header": "", + "names": [ + {"name": "secp256k1", "title": "secp256k1", "type": "curves::secp256k1::basic_keypair<{backend}>"} + ], + "default": [ + {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "secp256k1", "why": "the only backend ({libsecp256k1})"} + ], + "backends": { + "secp256k1": {"targets": "all"} + } + } + ], "rules": [ {"title": "Never reuse an IV under one key", "section": "crypto-gcm-rules", "text": "two AES-GCM messages under one key and one IV reveal the XOR of their plaintexts and let an attacker forge tags for every later message ({joux}; {nonce-reuse}); draw a random 12-byte IV per message, or use a counter that never repeats, a restart included."}, {"title": "The usage limit", "section": "crypto-gcm-rules", "text": "with random IVs, at most 2^32 messages under one key ({sp800-38d}, section 8.3); rotate the key before."}, diff --git a/doc/tables/generate.py b/doc/tables/generate.py index 2a24e7a9..5558c02d 100644 --- a/doc/tables/generate.py +++ b/doc/tables/generate.py @@ -5,7 +5,9 @@ # accompanying file LICENSE_1_0.txt or copy at # https://www.boost.org/LICENSE_1_0.txt) -"""Writes crypto's generated tables, doc/generated/*.adoc, and its index for LLMs, doc/llms.txt. +"""Writes crypto's generated tables, doc/generated/*.adoc, its index for LLMs, doc/llms.txt, and +the capability table's C++: include/webcpp/crypto/detail/capabilities.hpp and its test, +test/capabilities_test.cpp. Nothing in them is typed by hand. What crypto supports, on which backend and which target, comes from the programs the test Jamfiles declare: an operation's backend is supported on the targets of @@ -17,6 +19,13 @@ message and the description of each fixture. A measurement no lane takes yet (size, throughput, constant time measured) is written as not measured yet. +The capability table is crypto.json's families: each family's algorithms and, per backend, the +targets on which it has them, which the tests of the family's operations must run on (a cell is +claimed only where a named test runs), and its default per target with the reason. From it come +the family and algorithm tags, `detail::supported`, which `supports_v` reads, the refusal of a +backend without the family, which names the backends that have it, and the test that asserts each +cell and makes each present one. + Each fact is checked against the tree: a test, a message case, a fixture or an example that crypto.json names and the tree does not hold is a fault, and so is a fixture or a message case of the tree that crypto.json does not describe. @@ -32,6 +41,7 @@ import json import re import sys +import textwrap from pathlib import Path from typing import Any, Dict, List, Optional, Tuple @@ -45,7 +55,7 @@ '// Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles,\n' '// the message tests and the Jamfile fixtures: run it again, never edit this file.\n\n') FIXTURES = 'tools/test/fixtures/crypto_jamfiles' -BACKEND_ORDER = ('bearssl', 'openssl', 'ctaes', 'secp256k1', 'system', 'none') +BACKEND_ORDER = ('bearssl', 'openssl', 'ctaes', 'secp256k1', 'sodium', 'system', 'none') NAMESPACE_TITLES = {'root': 'webcpp::crypto', 'ciphers': 'webcpp::crypto::ciphers', 'curves': 'webcpp::crypto::curves'} RUN_RULES = ('crypto-run', 'memory-run', 'webcpp.run', 'webcpp.compile', @@ -54,6 +64,12 @@ EXPECTED_ERROR = re.compile(r'expected-error@\S+ \{\{(.*)\}\}') SOURCE = re.compile(r'\{([a-z0-9-]+)\}') NOT_MEASURED = 'not measured yet' +# The macro defined on each target, in the C++ written here: config.hpp defines the first where +# no WebAssembly target is defined. +TARGET_MACROS = {'native': 'WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE', 'wasip2': 'WEBCPP_TARGET_WASIP2', + 'wasip3': 'WEBCPP_TARGET_WASIP3', 'emscripten': 'WEBCPP_TARGET_EMSCRIPTEN'} +CAPABILITIES = Path('include/webcpp/crypto/detail/capabilities.hpp') +CAPABILITIES_TEST = Path('test/capabilities_test.cpp') Data = Dict[str, Any] @@ -370,6 +386,265 @@ def describe(self, operation: str, backend: str) -> str: return text + rest +def tags_of(data: Data) -> List[str]: + """The backends that are tags of `backends`, in crypto.json's order: those built for targets + of their own, where the rest (the system's generator, no backend at all) are not.""" + return [name for name, facts in data['backends'].items() if 'targets' in facts] + + +def cell_targets(data: Data, family: Data, backend: str) -> List[str]: + """The targets on which a backend has a family, in crypto.json's order of targets: "all" is + every target the backend is built for.""" + wanted = family['backends'][backend]['targets'] + if wanted == 'all': + wanted = data['backends'][backend]['targets'] + return [target for target in data['targets'] if target in wanted] + + +def check_families(data: Data, declared: Dict[str, List[str]]) -> None: + """Checks crypto.json's families against its backends, its operations and the tests: a cell is + claimed only for a tag of `backends`, on a target it is built for and where a test of the + family's operations on it runs; each target has one default, a backend that has the family + there, or none.""" + names = {family['name'] for family in data['families']} + for operation in data['operations']: + if 'family' in operation and operation['family'] not in names: + raise Fault(f'crypto.json: the operation {operation["id"]} names the family ' + f'{operation["family"]}, which crypto.json does not list') + tags = tags_of(data) + for family in data['families']: + name = family['name'] + for backend, entry in family['backends'].items(): + if backend not in tags: + raise Fault(f'crypto.json: the family {name} names the backend {backend}, which ' + 'is no tag of backends') + built = data['backends'][backend]['targets'] + claimed = built if entry['targets'] == 'all' else entry['targets'] + tested: List[str] = [] + for operation in data['operations']: + if operation.get('family') == name: + for test in operation['backends'].get(backend, {}).get('tests', []): + tested += declared.get(test, []) + for target in claimed: + if target not in built: + raise Fault(f'crypto.json: the family {name} claims {backend} on {target}, ' + f'where {backend} is not built') + if target not in tested: + raise Fault(f'crypto.json: the family {name} claims {backend} on {target}, ' + f'where no test of its operations on {backend} runs') + for target, why in entry.get('constant_time', {}).items(): + if target not in claimed: + raise Fault(f'crypto.json: the family {name} states constant time for ' + f'{backend} on {target}, where it does not claim it') + cite(data, why) + defaults: Dict[str, Optional[str]] = {} + for entry in family['default']: + cite(data, entry['why']) + for target in entry['targets']: + if target in defaults: + raise Fault(f'crypto.json: the family {name} has two defaults on {target}') + defaults[target] = entry['backend'] + backend = entry['backend'] + if backend is not None and (backend not in family['backends'] or + target not in cell_targets(data, family, backend)): + raise Fault(f'crypto.json: the family {name} defaults to {backend} on ' + f'{target}, which does not have it there') + missing = [target for target in data['targets'] if target not in defaults] + if missing: + raise Fault(f'crypto.json: the family {name} has no default on {", ".join(missing)}') + + +def have_list(data: Data, family: Data) -> str: + """The backends that have a family, each with its targets, as a refusal names them.""" + parts: List[str] = [] + for backend, entry in family['backends'].items(): + late = ', at run time' if entry.get('runtime') else '' + parts.append(f'{backend} ({", ".join(cell_targets(data, family, backend))}{late})') + return ', '.join(parts) + + +def refusal(data: Data, family: Data, backend: str) -> str: + """The refusal of a backend without a family (spec, "a backend without a function + refuses").""" + return (f'webcpp::crypto: {backend} has no {family["title"]}. The backends that have it: ' + f'{have_list(data, family)}.') + + +def tag_of(family: Data, name: str) -> str: + """The tag of an algorithm: a family of one algorithm of its own name is its own tag.""" + return f'families::{name}' if name == family['name'] else f'tags::{name}' + + +def doc_comment(text: str) -> List[str]: + """A Doc Comment's lines, as clang-format leaves them: on one line where it fits in 100 + columns, else broken between words.""" + if len(text) + 7 <= 100: + return [f'/** {text} */'] + return ['/**'] + [f' * {line}' for line in textwrap.wrap(text, 97)] + [' */'] + + +# A qualified name of crypto.json's types, which are written from webcpp::crypto. +QUALIFIED = re.compile(r'(? str: + """The preprocessor's condition that holds on the targets.""" + return ' || '.join(f'defined({TARGET_MACROS[target]})' for target in targets) + + +def capabilities_header(data: Data) -> str: + """include/webcpp/crypto/detail/capabilities.hpp: the family and algorithm tags, each cell of + `detail::supported` on its targets, and the refusals of each family's primary engine.""" + out = ['#ifndef WEBCPP_CRYPTO_DETAIL_CAPABILITIES_HPP', + '#define WEBCPP_CRYPTO_DETAIL_CAPABILITIES_HPP', '', + '#include ', '', + '#include ', '', + '#include ', '', + 'namespace webcpp::crypto::families {', ''] + named: List[Tuple[Data, Data]] = [] + for family in data['families']: + algorithms = [entry['name'] for entry in family['names']] + listed = ', '.join(f'`{tag_of(family, name)}`' for name in algorithms) + if algorithms == [family['name']]: + text = (f'The family {family["title"]}, of `{family["group"]}`, also the tag of its ' + 'one algorithm.') + else: + text = (f'The family {family["title"]}, of `{family["group"]}`; its algorithms: ' + f'{listed}.') + out += doc_comment(text) + [f'struct {family["name"]};', ''] + named += [(family, entry) for entry in family['names'] if entry['name'] != family['name']] + out += ['} // namespace webcpp::crypto::families', ''] + if named: + out += ['namespace webcpp::crypto::tags {', ''] + for family, entry in named: + out += doc_comment(f'{entry["title"]}, of the family ' + f'`families::{family["name"]}`.') + [f'struct {entry["name"]};', + ''] + out += ['} // namespace webcpp::crypto::tags', ''] + out += ['namespace webcpp::crypto::detail {', '', + '/**', + ' * One cell of the capability table, doc/tables/crypto.json, on the target being', + ' * compiled: whether `Backend` has the algorithm `Name` of the family `Family`. False', + ' * but where a specialisation below makes it true.', + ' *', + ' * @tparam Family A family tag of `families`.', + ' * @tparam Name An algorithm\'s tag of `tags`, or the family\'s own tag for a', + ' * family of one algorithm.', + ' * @tparam Backend A backend tag of `backends`.', + ' */', + 'template ', + 'inline constexpr bool supported = false;', '', + '// Each cell on its targets, as long as the table\'s names make its line.', + '// clang-format off'] + for family in data['families']: + for backend in family['backends']: + targets = cell_targets(data, family, backend) + out.append(f'// {family["title"]} on {backend}: {", ".join(targets)}.') + for entry in family['names']: + out += [f'#if {condition(targets)}', 'template <>', + f'inline constexpr bool supported = true;', + '#endif'] + out += ['// clang-format on', '', '} // namespace webcpp::crypto::detail', '', + '// The body of each family\'s primary engine, which a backend reaches where its', + '// header does not specialise the engine: a backend without the family is refused,', + '// naming those that have it; a backend that has it, whose header the program did', + '// not include, is told to include it; any other type is no backend of the family.', + '// clang-format off'] + tags = tags_of(data) + for family in data['families']: + have = have_list(data, family) + lines: List[str] = [] + for backend in tags: + if backend in family['backends']: + facts = data['backends'][backend] + text = (f'webcpp::crypto: {backend}\'s {family["title"]} is in ' + f'{facts["header"]}, which the program does not include. Include it, and ' + f'add {facts["jamfile"]} to the program\'s Jamfile.') + else: + text = refusal(data, family, backend) + lines.append(f'static_assert(!std::is_same_v, "{text}")') + lines.append(f'static_assert(::webcpp::crypto::detail::dependent_false, ' + f'"webcpp::crypto: {family["title"]} has no backend of that name. The ' + f'backends that have it: {have}.")') + out += doc_comment(f'The refusals of the family {family["title"]}\'s primary engine for ' + '`Backend`.') + [ + f'#define WEBCPP_CRYPTO_DETAIL_REFUSE_{family["name"].upper()}(Backend) \\'] + out += [f' {line}; \\' for line in lines[:-1]] + [f' {lines[-1]}'] + out += ['// clang-format on', '', '#endif // WEBCPP_CRYPTO_DETAIL_CAPABILITIES_HPP', ''] + return '\n'.join(out) + + +def capabilities_test(data: Data) -> str: + """test/capabilities_test.cpp: `supports_v` of every cell on the target being compiled, each + present cell made through its family's own type where its backend is linked, and each + family's refusal parsed.""" + tags = tags_of(data) + headers = sorted({family['header'] for family in data['families']} + | {'', ''}) + out = ['// What doc/tables/crypto.json says of each cell of the capability table, on the', + '// target being compiled: supports_v of each algorithm on each backend, true on the', + '// cell\'s targets alone; each present cell made, where its backend is linked, through', + '// the type a program names, which names its family and its algorithm as the table', + '// does; and each family\'s refusal, parsed.', ''] + out += [f'#include {header}' for header in headers] + [''] + for backend in tags: + out += [f'#ifdef WEBCPP_CRYPTO_HAS_{backend.upper()}', + f'#include {data["backends"][backend]["header"]}', '#endif'] + out += ['', '#include "support/capabilities.hpp"', '', + '#include ', '', + 'namespace {', '', + 'namespace crypto = webcpp::crypto;', + 'namespace backends = webcpp::crypto::backends;', + 'namespace families = webcpp::crypto::families;'] + if any(entry['name'] != family['name'] for family in data['families'] + for entry in family['names']): + out.append('namespace tags = webcpp::crypto::tags;') + out += ['', '/** An algorithm of `Family` named `Name`, as `supports_v` reads one. */', + 'template ', 'struct algorithm {', + ' /** The family. */', ' using family_type = Family;', + ' /** The algorithm. */', ' using name_type = Name;', '};'] + for family in data['families']: + out += ['', f'/** The refusals of {family["title"]}, parsed: nothing instantiates it. */', + 'template ', f'struct refuses_{family["name"]} {{', + f' WEBCPP_CRYPTO_DETAIL_REFUSE_{family["name"].upper()}(Backend);', '};'] + out += ['', '} // namespace', '', '// clang-format off'] + made: List[str] = [] + for family in data['families']: + for backend in tags: + present = backend in family['backends'] + targets = cell_targets(data, family, backend) if present else [] + out.append(f'// {family["title"]} on {backend}: {", ".join(targets) or "none"}.') + for entry in family['names']: + tag = tag_of(family, entry['name']) + trait = (f'crypto::supports_v, ' + f'backends::{backend}>') + if not present: + out.append(f'static_assert(!{trait});') + continue + out += [f'#if {condition(targets)}', f'static_assert({trait});', '#else', + f'static_assert(!{trait});', '#endif'] + algorithm = QUALIFIED.sub(r'crypto::\1', entry['type']).format( + backend=f'backends::{backend}') + made += [f'#if ({condition(targets)}) && defined(WEBCPP_CRYPTO_HAS_' + f'{backend.upper()})', + f' BOOST_TEST((webcpp::test::made<{algorithm}, ' + f'families::{family["name"]}, {tag}, backends::{backend}>()));', + '#endif'] + out += ['// clang-format on', '', 'int main() {', ' // clang-format off'] + out += made + out += [' // clang-format on', + ' return webcpp::test::exit_status(boost::report_errors());', '}', ''] + return '\n'.join(out) + + +def stale(files: Dict[Path, str]) -> List[Path]: + """The files that differ from what generate.py writes, or that do not exist.""" + return sorted(path for path, text in files.items() + if not path.is_file() or path.read_text(encoding='utf-8') != text) + + # A namespace table's column named by its names of code, then its plain name. NAMED_COLUMN = re.compile(r'^((?:`[^`]+`(?:, )?)+): (.+)$') @@ -763,6 +1038,7 @@ def generate(root: Path, library: Path) -> Dict[Path, str]: if name not in cases: raise Fault(f'crypto.json describes the fixture {name}, which the tree does not hold') matrix = Matrix(data, declared, refusals) + check_families(data, declared) generated = DOC / 'generated' files: Dict[Path, str] = {} for namespace in NAMESPACE_TITLES: @@ -779,6 +1055,8 @@ def generate(root: Path, library: Path) -> Dict[Path, str]: files[generated / 'messages.adoc'] = messages_page(data, refusals, cases, msvc_cases(library)) files[generated / 'use-cases.adoc'] = use_cases_page(data, library) + files[library / CAPABILITIES] = capabilities_header(data) + files[library / CAPABILITIES_TEST] = capabilities_test(data) for path in list(files): files[path] = NOTICE + files[path] files[DOC / 'llms.txt'] = llms(data, matrix, library) @@ -795,18 +1073,17 @@ def main() -> int: except Fault as fault: print(f'generate.py: {fault}', file=sys.stderr) return 1 - stale = sorted(path for path, text in files.items() - if not path.is_file() or path.read_text(encoding='utf-8') != text) + differing = stale(files) extra = sorted(path for path in (DOC / 'generated').glob('*.adoc') if path not in files) if arguments.check: - for path in stale: + for path in differing: print(f'generate.py: {path.relative_to(LIBRARY)} is not what crypto.json and the ' 'tree give: run python3 libs/crypto/doc/tables/generate.py', file=sys.stderr) for path in extra: print(f'generate.py: {path.relative_to(LIBRARY)} is generated by nothing: remove it', file=sys.stderr) - return 1 if stale or extra else 0 - for path in stale: + return 1 if differing or extra else 0 + for path in differing: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(files[path], encoding='utf-8') for path in extra: diff --git a/doc/tables/generate_test.py b/doc/tables/generate_test.py index 9990c895..53831525 100644 --- a/doc/tables/generate_test.py +++ b/doc/tables/generate_test.py @@ -8,12 +8,14 @@ """Checks generate.py's readers and writers on small fixtures of their own: the Jamfile reader (a program inside an `if`, a rule's body, the targets a program inherits, the memory option's tests, a name declared twice), a backend's reason for the targets an operation misses (OpenSSL's alone), the -outcome reader (each directive and section), the Doc Comment reader (a line reference left out), -and the writers whose output a reader of the page sees (inline code that holds a `+` or a backtick, -a failing fixture's output per target, a comparison table's names of code, the decision table's -Jamfile column). generate.py --check proves only that the committed tables are what generate.py -writes now: a reader that regresses and is regenerated in the same change would pass it, and fails -here. +outcome reader (each directive and section), the Doc Comment reader (a line reference left out), the +writers whose output a reader of the page sees (inline code that holds a `+` or a backtick, a +failing fixture's output per target, a comparison table's names of code, the decision table's +Jamfile column), and the capability table's: its checks of crypto.json's families, the refusals and +cells of include/webcpp/crypto/detail/capabilities.hpp, the cells test/capabilities_test.cpp +asserts, and the comparison --check makes. +generate.py --check proves only that the committed tables are what generate.py writes now: a reader +that regresses and is regenerated in the same change would pass it, and fails here. Usage: generate_test.py [...]. The doc build runs it before generate.py --check (doc/Jamfile). Exit 0, or 1 at the first failing case. @@ -229,6 +231,153 @@ def test_the_decision_table_writes_no_jamfile_as_prose(scratch: Path) -> None: assert '\n|<>\n' in page, page +EVERY_TARGET = ['native', 'wasip2', 'wasip3', 'emscripten'] + + +def small_table() -> generate.Data: + """A capability table of one family, Ed25519, on libsodium alone, beside BearSSL and a + backend that is no tag of `backends` (the operating system's generator).""" + def backend(title: str, name: str, jamfile: str) -> generate.Data: + return {'title': title, 'jamfile': jamfile, + 'header': f'', 'targets': EVERY_TARGET} + return { + 'targets': EVERY_TARGET, 'sources': {'rfc8032': ['RFC 8032', 'https://example.org']}, + 'backends': {'bearssl': backend('BearSSL', 'bearssl', '/third_party//bearssl'), + 'sodium': backend('libsodium', 'sodium', '/third_party//sodium'), + 'system': {'title': 'The system'}}, + 'operations': [{'id': 'sign', 'family': 'ed25519', + 'backends': {'sodium': {'tests': ['ed25519']}}}], + 'families': [{ + 'name': 'ed25519', 'title': 'Ed25519', 'group': 'curves::ed25519', 'since': '0.2', + 'header': '', + 'names': [{'name': 'ed25519', 'title': 'Ed25519', + 'type': 'curves::ed25519::basic_keypair<{backend}>'}], + 'default': [{'targets': EVERY_TARGET, 'backend': 'sodium', + 'why': 'the only backend ({rfc8032})'}], + 'backends': {'sodium': {'targets': 'all'}}}]} + + +def a_fault(data: generate.Data, declared: dict[str, list[str]], wanted: str) -> None: + """Checks that the families of data are refused with a fault that says wanted.""" + try: + generate.check_families(data, declared) + except generate.Fault as fault: + assert wanted in str(fault), fault + else: + raise AssertionError(f'no fault saying {wanted}') + + +def test_a_backend_without_a_family_is_refused_naming_those_that_have_it(_: Path) -> None: + header = generate.capabilities_header(small_table()) + assert ('static_assert(!std::is_same_v, ' + '"webcpp::crypto: bearssl has no Ed25519. The backends that have it: sodium ' + '(native, wasip2, wasip3, emscripten).")') in header, header + # A backend that has the family, whose header the program did not include, is told so; a + # backend that is no tag of backends:: is never named; any other type is the last refusal. + assert ('static_assert(!std::is_same_v, ' + '"webcpp::crypto: sodium\'s Ed25519 is in , ' + 'which the program does not include. Include it, and add /third_party//sodium to the ' + 'program\'s Jamfile.")') in header, header + assert 'system' not in header, header + assert ('static_assert(::webcpp::crypto::detail::dependent_false, ' + '"webcpp::crypto: Ed25519 has no backend of that name. The backends that have it: ' + 'sodium (native, wasip2, wasip3, emscripten).")\n') in header, header + assert '#define WEBCPP_CRYPTO_DETAIL_REFUSE_ED25519(Backend)' in header, header + + +def test_a_cell_decided_at_run_time_says_so(_: Path) -> None: + data = small_table() + data['families'][0]['backends']['sodium'] = {'targets': ['native'], 'runtime': True} + assert generate.refusal(data, data['families'][0], 'bearssl') == ( + 'webcpp::crypto: bearssl has no Ed25519. The backends that have it: sodium (native, at ' + 'run time).') + + +def test_each_cell_is_true_on_its_targets_alone(_: Path) -> None: + data = small_table() + data['families'][0]['backends']['sodium']['targets'] = ['native', 'wasip3'] + header = generate.capabilities_header(data) + assert ('#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP3)\n' + 'template <>\n' + 'inline constexpr bool supported = true;\n#endif\n') in header, header + # A family of one name is its own name: no tag of tags:: is declared for it. + assert 'struct ed25519;' in header and 'namespace webcpp::crypto::tags' not in header, header + assert header.startswith('#ifndef WEBCPP_CRYPTO_DETAIL_CAPABILITIES_HPP\n'), header + + +def test_the_generated_test_asserts_every_cell(_: Path) -> None: + test = generate.capabilities_test(small_table()) + present = ('crypto::supports_v, ' + 'backends::sodium>') + assert (f'#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) ' + f'|| defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN)\n' + f'static_assert({present});\n#else\nstatic_assert(!{present});\n#endif\n') in test, test + assert ('static_assert(!crypto::supports_v, ' + 'backends::bearssl>);\n') in test, test + # Each present cell is made, where its backend is linked, through the family's own type. + assert ('defined(WEBCPP_CRYPTO_HAS_SODIUM)\n BOOST_TEST((webcpp::test::made<' + 'crypto::curves::ed25519::basic_keypair, families::ed25519, ' + 'families::ed25519, backends::sodium>()));\n') in test, test + assert '#include \n' in test, test + assert '#ifdef WEBCPP_CRYPTO_HAS_SODIUM\n#include \n' in ( + test), test + # The refusal macro is parsed, in a template no one instantiates. + assert 'WEBCPP_CRYPTO_DETAIL_REFUSE_ED25519(Backend);' in test, test + + +def test_a_family_that_names_an_unknown_backend_is_a_fault(_: Path) -> None: + data = small_table() + data['families'][0]['backends']['botan'] = {'targets': 'all'} + a_fault(data, {'ed25519': EVERY_TARGET}, + 'the family ed25519 names the backend botan, which is no tag of backends') + data = small_table() + data['families'][0]['backends']['system'] = {'targets': 'all'} + a_fault(data, {'ed25519': EVERY_TARGET}, + 'the family ed25519 names the backend system, which is no tag of backends') + + +def test_a_cell_claimed_where_no_test_runs_is_a_fault(_: Path) -> None: + a_fault(small_table(), {'ed25519': ['native', 'wasip2', 'wasip3']}, + 'the family ed25519 claims sodium on emscripten, where no test of its operations ' + 'on sodium runs') + data = small_table() + data['backends']['sodium']['targets'] = ['native'] + data['families'][0]['backends']['sodium']['targets'] = ['native', 'wasip2'] + a_fault(data, {'ed25519': EVERY_TARGET}, + 'the family ed25519 claims sodium on wasip2, where sodium is not built') + + +def test_a_default_is_one_backend_of_the_family_per_target(_: Path) -> None: + data = small_table() + data['families'][0]['default'] = [{'targets': ['native'], 'backend': 'sodium', 'why': 'w'}] + a_fault(data, {'ed25519': EVERY_TARGET}, + 'the family ed25519 has no default on wasip2, wasip3, emscripten') + data['families'][0]['default'] = [{'targets': EVERY_TARGET, 'backend': 'bearssl', + 'why': 'w'}] + a_fault(data, {'ed25519': EVERY_TARGET}, + 'the family ed25519 defaults to bearssl on native, which does not have it there') + data['families'][0]['default'] = [{'targets': EVERY_TARGET, 'backend': 'sodium', 'why': 'w'}, + {'targets': ['native'], 'backend': None, 'why': 'w'}] + a_fault(data, {'ed25519': EVERY_TARGET}, 'the family ed25519 has two defaults on native') + data = small_table() + data['operations'][0]['family'] = 'ed448' + a_fault(data, {'ed25519': EVERY_TARGET}, + 'the operation sign names the family ed448, which crypto.json does not list') + + +def test_the_check_names_a_file_that_differs(scratch: Path) -> None: + files = {scratch / 'include/a.hpp': 'one\n', scratch / 'test/b.cpp': 'two\n'} + for path, text in files.items(): + written(path.parent, path.name, text) + assert generate.stale(files) == [], generate.stale(files) + written(scratch / 'test', 'b.cpp', 'twO\n') + assert generate.stale(files) == [scratch / 'test/b.cpp'], generate.stale(files) + (scratch / 'include/a.hpp').unlink() + assert generate.stale(files) == [scratch / 'include/a.hpp', scratch / 'test/b.cpp'], ( + generate.stale(files)) + + CASES: list[Callable[[Path], None]] = [ test_a_rule_body_declares_nothing, test_a_program_inside_an_if_is_a_fault, @@ -242,6 +391,14 @@ def test_the_decision_table_writes_no_jamfile_as_prose(scratch: Path) -> None: test_a_fixture_that_builds_and_runs_nothing_is_a_record, test_a_comparison_column_is_headed_by_its_plain_name, test_the_decision_table_writes_no_jamfile_as_prose, + test_a_backend_without_a_family_is_refused_naming_those_that_have_it, + test_a_cell_decided_at_run_time_says_so, + test_each_cell_is_true_on_its_targets_alone, + test_the_generated_test_asserts_every_cell, + test_a_family_that_names_an_unknown_backend_is_a_fault, + test_a_cell_claimed_where_no_test_runs_is_a_fault, + test_a_default_is_one_backend_of_the_family_per_target, + test_the_check_names_a_file_that_differs, ] diff --git a/include/webcpp/crypto.hpp b/include/webcpp/crypto.hpp index b152c2e1..d15b6cd6 100644 --- a/include/webcpp/crypto.hpp +++ b/include/webcpp/crypto.hpp @@ -22,6 +22,7 @@ #include #include // lint-world: the system's entropy, a purpose of crypto #include +#include #ifdef WEBCPP_CRYPTO_HAS_BEARSSL #include diff --git a/include/webcpp/crypto/ciphers/aes.hpp b/include/webcpp/crypto/ciphers/aes.hpp index 1335f965..dc285c9e 100644 --- a/include/webcpp/crypto/ciphers/aes.hpp +++ b/include/webcpp/crypto/ciphers/aes.hpp @@ -15,6 +15,7 @@ #include +#include #include #include @@ -23,6 +24,7 @@ #include #include #include +#include #include namespace webcpp::crypto::detail { @@ -42,6 +44,12 @@ class basic_aes { public: /** The backend. */ using backend_type = Backend; + /** The family of the capability table, `families::aes_block`, which `supports_v` reads. */ + using family_type = families::aes_block; + /** The algorithm of the capability table: `tags::aes128`, `tags::aes192` or `tags::aes256`. */ + using name_type = + std::conditional_t>; /** The key's size in bytes. */ static constexpr std::size_t key_size = KeySize; /** AES's block, 16 bytes. */ diff --git a/include/webcpp/crypto/ciphers/gcm.hpp b/include/webcpp/crypto/ciphers/gcm.hpp index 80d23149..c3509770 100644 --- a/include/webcpp/crypto/ciphers/gcm.hpp +++ b/include/webcpp/crypto/ciphers/gcm.hpp @@ -14,6 +14,7 @@ #include +#include #include #include #include @@ -27,6 +28,7 @@ #include #include #include +#include #include namespace webcpp::crypto::ciphers { @@ -52,6 +54,15 @@ class gcm { using cipher_type = Cipher; /** The backend. */ using backend_type = backend; + /** The family of the capability table, `families::gcm`, which `supports_v` reads. */ + using family_type = families::gcm; + /** + * The algorithm of the capability table: `tags::aes128_gcm`, `tags::aes192_gcm` or + * `tags::aes256_gcm`, by the key's size. + */ + using name_type = std::conditional_t< + Cipher::key_size == 16, tags::aes128_gcm, + std::conditional_t>; /** The tag, Boost.Hash2's digest of 16 bytes. */ using result_type = boost::hash2::digest<16>; /** The key's size in bytes. */ diff --git a/include/webcpp/crypto/config.hpp b/include/webcpp/crypto/config.hpp index b4cc6ba9..6784b257 100644 --- a/include/webcpp/crypto/config.hpp +++ b/include/webcpp/crypto/config.hpp @@ -152,6 +152,9 @@ #if defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || \ defined(WEBCPP_TARGET_EMSCRIPTEN) #define WEBCPP_CRYPTO_WEBASSEMBLY 1 +#else +/** Defined on the native target, where no WebAssembly target is: the capability table's name. */ +#define WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE 1 #endif // The refusals of impossible combinations. Clang and gcc go on after an diff --git a/include/webcpp/crypto/curves/secp256k1.hpp b/include/webcpp/crypto/curves/secp256k1.hpp index 724cae92..c883d9a3 100644 --- a/include/webcpp/crypto/curves/secp256k1.hpp +++ b/include/webcpp/crypto/curves/secp256k1.hpp @@ -16,6 +16,7 @@ #include #include +#include #include #include #include // lint-world: the context's randomisation, its purpose @@ -170,6 +171,10 @@ class basic_keypair { public: /** The backend. */ using backend_type = Backend; + /** The family of the capability table, `families::secp256k1`, which `supports_v` reads. */ + using family_type = families::secp256k1; + /** The algorithm of the capability table: the family's own tag, its one algorithm. */ + using name_type = families::secp256k1; /** * Makes a key pair from a secret key. diff --git a/include/webcpp/crypto/detail/capabilities.hpp b/include/webcpp/crypto/detail/capabilities.hpp new file mode 100644 index 00000000..d2611419 --- /dev/null +++ b/include/webcpp/crypto/detail/capabilities.hpp @@ -0,0 +1,169 @@ +// 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. + +#ifndef WEBCPP_CRYPTO_DETAIL_CAPABILITIES_HPP +#define WEBCPP_CRYPTO_DETAIL_CAPABILITIES_HPP + +#include + +#include + +#include + +namespace webcpp::crypto::families { + +/** + * The family AES-GCM, of `ciphers`; its algorithms: `tags::aes128_gcm`, `tags::aes192_gcm`, + * `tags::aes256_gcm`. + */ +struct gcm; + +/** + * The family AES block cipher, of `ciphers`; its algorithms: `tags::aes128`, `tags::aes192`, + * `tags::aes256`. + */ +struct aes_block; + +/** The family secp256k1, of `curves::secp256k1`, also the tag of its one algorithm. */ +struct secp256k1; + +} // namespace webcpp::crypto::families + +namespace webcpp::crypto::tags { + +/** AES-128-GCM, of the family `families::gcm`. */ +struct aes128_gcm; + +/** AES-192-GCM, of the family `families::gcm`. */ +struct aes192_gcm; + +/** AES-256-GCM, of the family `families::gcm`. */ +struct aes256_gcm; + +/** AES-128, of the family `families::aes_block`. */ +struct aes128; + +/** AES-192, of the family `families::aes_block`. */ +struct aes192; + +/** AES-256, of the family `families::aes_block`. */ +struct aes256; + +} // namespace webcpp::crypto::tags + +namespace webcpp::crypto::detail { + +/** + * One cell of the capability table, doc/tables/crypto.json, on the target being + * compiled: whether `Backend` has the algorithm `Name` of the family `Family`. False + * but where a specialisation below makes it true. + * + * @tparam Family A family tag of `families`. + * @tparam Name An algorithm's tag of `tags`, or the family's own tag for a + * family of one algorithm. + * @tparam Backend A backend tag of `backends`. + */ +template +inline constexpr bool supported = false; + +// Each cell on its targets, as long as the table's names make its line. +// clang-format off +// AES-GCM on bearssl: native, wasip2, wasip3, emscripten. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool supported = true; +#endif +// AES-GCM on openssl: native, wasip2, wasip3. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) +template <> +inline constexpr bool supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) +template <> +inline constexpr bool supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) +template <> +inline constexpr bool supported = true; +#endif +// AES block cipher on openssl: native, wasip2, wasip3. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) +template <> +inline constexpr bool supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) +template <> +inline constexpr bool supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) +template <> +inline constexpr bool supported = true; +#endif +// AES block cipher on ctaes: native, wasip2, wasip3, emscripten. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool supported = true; +#endif +// secp256k1 on secp256k1: native, wasip2, wasip3, emscripten. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool supported = true; +#endif +// clang-format on + +} // namespace webcpp::crypto::detail + +// The body of each family's primary engine, which a backend reaches where its +// header does not specialise the engine: a backend without the family is refused, +// naming those that have it; a backend that has it, whose header the program did +// not include, is told to include it; any other type is no backend of the family. +// clang-format off +/** The refusals of the family AES-GCM's primary engine for `Backend`. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_GCM(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl's AES-GCM is in , which the program does not include. Include it, and add /third_party//bearssl to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl's AES-GCM is in , which the program does not include. Include it, and add /webcpp/crypto//openssl to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no AES-GCM. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no AES-GCM. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: sodium has no AES-GCM. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(::webcpp::crypto::detail::dependent_false, "webcpp::crypto: AES-GCM has no backend of that name. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).") +/** The refusals of the family AES block cipher's primary engine for `Backend`. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_AES_BLOCK(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no AES block cipher. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl's AES block cipher is in , which the program does not include. Include it, and add /webcpp/crypto//openssl to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes's AES block cipher is in , which the program does not include. Include it, and add /third_party//ctaes to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no AES block cipher. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: sodium has no AES block cipher. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten)."); \ + static_assert(::webcpp::crypto::detail::dependent_false, "webcpp::crypto: AES block cipher has no backend of that name. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten).") +/** The refusals of the family secp256k1's primary engine for `Backend`. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_SECP256K1(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1's secp256k1 is in , which the program does not include. Include it, and add /third_party//secp256k1 to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: sodium has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ + static_assert(::webcpp::crypto::detail::dependent_false, "webcpp::crypto: secp256k1 has no backend of that name. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten).") +// clang-format on + +#endif // WEBCPP_CRYPTO_DETAIL_CAPABILITIES_HPP diff --git a/include/webcpp/crypto/detail/engines.hpp b/include/webcpp/crypto/detail/engines.hpp index 78f12cce..c64efe05 100644 --- a/include/webcpp/crypto/detail/engines.hpp +++ b/include/webcpp/crypto/detail/engines.hpp @@ -13,6 +13,10 @@ namespace webcpp::crypto::detail { +/** False for every `T`: a `static_assert` on it fires only where its template is instantiated. */ +template +inline constexpr bool dependent_false = false; + /** * What a backend's header specialises, per algorithm: a state, which an object stores and * which never refuses, and an engine, used only inside the algorithm's member functions, diff --git a/include/webcpp/crypto/supports.hpp b/include/webcpp/crypto/supports.hpp new file mode 100644 index 00000000..e0d3ae04 --- /dev/null +++ b/include/webcpp/crypto/supports.hpp @@ -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) + +/** + Whether a backend has an algorithm on the target being compiled, as the capability table, + `doc/tables/crypto.json`, says. + + @see "The backends", in the guide. +*/ +#ifndef WEBCPP_CRYPTO_SUPPORTS_HPP +#define WEBCPP_CRYPTO_SUPPORTS_HPP + +#include + +#include + +namespace webcpp::crypto { + +/** + * `true` exactly where the capability table says that `Backend` has `Algorithm` on the target + * being compiled. + * + * A cell decided at run time is `true` too: its `make` then reports `not_supported` on a + * machine that lacks it. It needs no backend's header and no library: a program asks it of a + * backend it does not link. + * + * @tparam Algorithm An algorithm's type, which names its `family_type` and its `name_type`, as + * `ciphers::aes256_gcm` does. + * @tparam Backend A backend tag of `backends`. + */ +template +inline constexpr bool supports_v = + detail::supported; + +} // namespace webcpp::crypto + +#endif // WEBCPP_CRYPTO_SUPPORTS_HPP diff --git a/test/Jamfile b/test/Jamfile index b6214677..5b584143 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -24,7 +24,8 @@ webcpp.headers-alone crypto : ../include : crypto.hpp crypto/config.hpp crypto/equal.hpp crypto/error.hpp crypto/ciphers/aes.hpp crypto/ciphers/gcm.hpp crypto/random_device.hpp crypto/detail/declassify.hpp crypto/detail/engines.hpp crypto/detail/entropy.hpp crypto/detail/limits.hpp crypto/detail/windows.hpp - crypto/detail/wipe.hpp crypto/secret.hpp ; + crypto/detail/wipe.hpp crypto/secret.hpp crypto/supports.hpp + crypto/detail/capabilities.hpp ; # The backend BearSSL's header and the default backend's, with BearSSL linked, # on every target. @@ -67,7 +68,9 @@ crypto-run equal : equal_test.cpp ; # alone, with no backend linked, compiles, links and runs. crypto-run convenience_header : convenience_header_test.cpp ; crypto-run wipe : wipe_test.cpp ; -# secret is not copyable, moves wipe the source, and the destructor wipes the storage, at -O2. +# secret is not copyable, moves wipe the source, and the destructor wipes +# the storage: at -O2 with every call inlined (full), where a wipe +# the compiler could drop as a dead store would be dropped. crypto-run secret : secret_test.cpp : speed full ; # A destroyed or moved-from key schedule is zero in its storage, read at -O2 @@ -259,6 +262,19 @@ crypto-run aes_ctaes : aes_ctaes_test.cpp : /third_party//ctaes ; # The backend libsodium: its canary, its initialisation and its three layers. crypto-run sodium_backend : sodium_backend_test.cpp : /third_party//sodium ; +# The capability table of doc/tables/crypto.json, which generate.py writes +# this test from: supports_v of every cell on the target, and each present +# cell made, with every backend the target builds linked. +crypto-run capabilities : capabilities_test.cpp + : /third_party//bearssl /webcpp/crypto//openssl + /third_party//ctaes /third_party//secp256k1 + /third_party//sodium + : native wasip2 wasip3 ; +crypto-run capabilities_emscripten : capabilities_test.cpp + : /third_party//bearssl /third_party//ctaes + /third_party//secp256k1 /third_party//sodium + : emscripten ; + # ctaes against OpenSSL on 10,000 random keys of each size (spec section 8.2), # on native, wasip2 and wasip3 (on WASI OpenSSL runs its portable C code). crypto-run agreement_aes : agreement_aes_test.cpp diff --git a/test/capabilities_test.cpp b/test/capabilities_test.cpp new file mode 100644 index 00000000..7d3fe38f --- /dev/null +++ b/test/capabilities_test.cpp @@ -0,0 +1,226 @@ +// 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. + +// What doc/tables/crypto.json says of each cell of the capability table, on the +// target being compiled: supports_v of each algorithm on each backend, true on the +// cell's targets alone; each present cell made, where its backend is linked, through +// the type a program names, which names its family and its algorithm as the table +// does; and each family's refusal, parsed. + +#include +#include +#include +#include +#include + +#ifdef WEBCPP_CRYPTO_HAS_BEARSSL +#include +#endif +#ifdef WEBCPP_CRYPTO_HAS_OPENSSL +#include +#endif +#ifdef WEBCPP_CRYPTO_HAS_CTAES +#include +#endif +#ifdef WEBCPP_CRYPTO_HAS_SECP256K1 +#include +#endif +#ifdef WEBCPP_CRYPTO_HAS_SODIUM +#include +#endif + +#include "support/capabilities.hpp" + +#include + +namespace { + +namespace crypto = webcpp::crypto; +namespace backends = webcpp::crypto::backends; +namespace families = webcpp::crypto::families; +namespace tags = webcpp::crypto::tags; + +/** An algorithm of `Family` named `Name`, as `supports_v` reads one. */ +template +struct algorithm { + /** The family. */ + using family_type = Family; + /** The algorithm. */ + using name_type = Name; +}; + +/** The refusals of AES-GCM, parsed: nothing instantiates it. */ +template +struct refuses_gcm { + WEBCPP_CRYPTO_DETAIL_REFUSE_GCM(Backend); +}; + +/** The refusals of AES block cipher, parsed: nothing instantiates it. */ +template +struct refuses_aes_block { + WEBCPP_CRYPTO_DETAIL_REFUSE_AES_BLOCK(Backend); +}; + +/** The refusals of secp256k1, parsed: nothing instantiates it. */ +template +struct refuses_secp256k1 { + WEBCPP_CRYPTO_DETAIL_REFUSE_SECP256K1(Backend); +}; + +} // namespace + +// clang-format off +// AES-GCM on bearssl: native, wasip2, wasip3, emscripten. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_v, backends::bearssl>); +#else +static_assert(!crypto::supports_v, backends::bearssl>); +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_v, backends::bearssl>); +#else +static_assert(!crypto::supports_v, backends::bearssl>); +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_v, backends::bearssl>); +#else +static_assert(!crypto::supports_v, backends::bearssl>); +#endif +// AES-GCM on openssl: native, wasip2, wasip3. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) +static_assert(crypto::supports_v, backends::openssl>); +#else +static_assert(!crypto::supports_v, backends::openssl>); +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) +static_assert(crypto::supports_v, backends::openssl>); +#else +static_assert(!crypto::supports_v, backends::openssl>); +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) +static_assert(crypto::supports_v, backends::openssl>); +#else +static_assert(!crypto::supports_v, backends::openssl>); +#endif +// AES-GCM on ctaes: none. +static_assert(!crypto::supports_v, backends::ctaes>); +static_assert(!crypto::supports_v, backends::ctaes>); +static_assert(!crypto::supports_v, backends::ctaes>); +// AES-GCM on secp256k1: none. +static_assert(!crypto::supports_v, backends::secp256k1>); +static_assert(!crypto::supports_v, backends::secp256k1>); +static_assert(!crypto::supports_v, backends::secp256k1>); +// AES-GCM on sodium: none. +static_assert(!crypto::supports_v, backends::sodium>); +static_assert(!crypto::supports_v, backends::sodium>); +static_assert(!crypto::supports_v, backends::sodium>); +// AES block cipher on bearssl: none. +static_assert(!crypto::supports_v, backends::bearssl>); +static_assert(!crypto::supports_v, backends::bearssl>); +static_assert(!crypto::supports_v, backends::bearssl>); +// AES block cipher on openssl: native, wasip2, wasip3. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) +static_assert(crypto::supports_v, backends::openssl>); +#else +static_assert(!crypto::supports_v, backends::openssl>); +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) +static_assert(crypto::supports_v, backends::openssl>); +#else +static_assert(!crypto::supports_v, backends::openssl>); +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) +static_assert(crypto::supports_v, backends::openssl>); +#else +static_assert(!crypto::supports_v, backends::openssl>); +#endif +// AES block cipher on ctaes: native, wasip2, wasip3, emscripten. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_v, backends::ctaes>); +#else +static_assert(!crypto::supports_v, backends::ctaes>); +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_v, backends::ctaes>); +#else +static_assert(!crypto::supports_v, backends::ctaes>); +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_v, backends::ctaes>); +#else +static_assert(!crypto::supports_v, backends::ctaes>); +#endif +// AES block cipher on secp256k1: none. +static_assert(!crypto::supports_v, backends::secp256k1>); +static_assert(!crypto::supports_v, backends::secp256k1>); +static_assert(!crypto::supports_v, backends::secp256k1>); +// AES block cipher on sodium: none. +static_assert(!crypto::supports_v, backends::sodium>); +static_assert(!crypto::supports_v, backends::sodium>); +static_assert(!crypto::supports_v, backends::sodium>); +// secp256k1 on bearssl: none. +static_assert(!crypto::supports_v, backends::bearssl>); +// secp256k1 on openssl: none. +static_assert(!crypto::supports_v, backends::openssl>); +// secp256k1 on ctaes: none. +static_assert(!crypto::supports_v, backends::ctaes>); +// secp256k1 on secp256k1: native, wasip2, wasip3, emscripten. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_v, backends::secp256k1>); +#else +static_assert(!crypto::supports_v, backends::secp256k1>); +#endif +// secp256k1 on sodium: none. +static_assert(!crypto::supports_v, backends::sodium>); +// clang-format on + +int main() { + // clang-format off +#if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN)) && defined(WEBCPP_CRYPTO_HAS_BEARSSL) + BOOST_TEST((webcpp::test::made>, families::gcm, tags::aes128_gcm, backends::bearssl>())); +#endif +#if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN)) && defined(WEBCPP_CRYPTO_HAS_BEARSSL) + BOOST_TEST((webcpp::test::made>, families::gcm, tags::aes192_gcm, backends::bearssl>())); +#endif +#if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN)) && defined(WEBCPP_CRYPTO_HAS_BEARSSL) + BOOST_TEST((webcpp::test::made>, families::gcm, tags::aes256_gcm, backends::bearssl>())); +#endif +#if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3)) && defined(WEBCPP_CRYPTO_HAS_OPENSSL) + BOOST_TEST((webcpp::test::made>, families::gcm, tags::aes128_gcm, backends::openssl>())); +#endif +#if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3)) && defined(WEBCPP_CRYPTO_HAS_OPENSSL) + BOOST_TEST((webcpp::test::made>, families::gcm, tags::aes192_gcm, backends::openssl>())); +#endif +#if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3)) && defined(WEBCPP_CRYPTO_HAS_OPENSSL) + BOOST_TEST((webcpp::test::made>, families::gcm, tags::aes256_gcm, backends::openssl>())); +#endif +#if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3)) && defined(WEBCPP_CRYPTO_HAS_OPENSSL) + BOOST_TEST((webcpp::test::made, families::aes_block, tags::aes128, backends::openssl>())); +#endif +#if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3)) && defined(WEBCPP_CRYPTO_HAS_OPENSSL) + BOOST_TEST((webcpp::test::made, families::aes_block, tags::aes192, backends::openssl>())); +#endif +#if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3)) && defined(WEBCPP_CRYPTO_HAS_OPENSSL) + BOOST_TEST((webcpp::test::made, families::aes_block, tags::aes256, backends::openssl>())); +#endif +#if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN)) && defined(WEBCPP_CRYPTO_HAS_CTAES) + BOOST_TEST((webcpp::test::made, families::aes_block, tags::aes128, backends::ctaes>())); +#endif +#if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN)) && defined(WEBCPP_CRYPTO_HAS_CTAES) + BOOST_TEST((webcpp::test::made, families::aes_block, tags::aes192, backends::ctaes>())); +#endif +#if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN)) && defined(WEBCPP_CRYPTO_HAS_CTAES) + BOOST_TEST((webcpp::test::made, families::aes_block, tags::aes256, backends::ctaes>())); +#endif +#if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN)) && defined(WEBCPP_CRYPTO_HAS_SECP256K1) + BOOST_TEST((webcpp::test::made, families::secp256k1, families::secp256k1, backends::secp256k1>())); +#endif + // clang-format on + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/support/capabilities.hpp b/test/support/capabilities.hpp new file mode 100644 index 00000000..2a77e2c8 --- /dev/null +++ b/test/support/capabilities.hpp @@ -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) + +#ifndef WEBCPP_TEST_CRYPTO_SUPPORT_CAPABILITIES_HPP +#define WEBCPP_TEST_CRYPTO_SUPPORT_CAPABILITIES_HPP + +#include + +#include +#include +#include +#include + +namespace webcpp::test { + +/** The size of the key an algorithm's `make` takes: its `key_size`, else a secret key's 32. */ +template +constexpr std::size_t key_size_of() { + if constexpr (requires { Algorithm::key_size; }) { + return Algorithm::key_size; + } else { + return 32; + } +} + +/** + * Makes an algorithm, through the type a program names, from a key whose bytes are all 1: a + * cell the capability table marks present whose engine is missing fails to compile here. The + * type names its family and its algorithm as the table does, and `supports_v` says that the + * backend has it. + * + * @tparam Algorithm The type a program names, on `Backend`. + * @tparam Family Its family's tag. + * @tparam Name Its algorithm's tag. + * @tparam Backend Its backend. + * @return Whether `make` succeeded. + */ +template +[[nodiscard]] bool made() { + static_assert(std::is_same_v); + static_assert(std::is_same_v); + static_assert(webcpp::crypto::supports_v); + std::array()> key_bytes{}; + key_bytes.fill(1); + return Algorithm::make(key_bytes).has_value(); +} + +} // namespace webcpp::test + +#endif // WEBCPP_TEST_CRYPTO_SUPPORT_CAPABILITIES_HPP From 7f227c0711fb3fa4821973fe26db9301a28184bb Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 12:13:21 -0300 Subject: [PATCH 010/110] crypto: the families' defaults are the one source of the defaults page, and each refusal holds on its target crypto.json's old defaults list moves into families[].default, which states the defaults the code has now, each row claimed only where a test that fixes it runs; the defaults page, the backends pages and llms.txt read it. The refusal macros are written per target, so that a backend without the family on that target is refused rather than told to include a header. --check's printing is tested through checked(), a type keeps std:: as it is, the per-family constant time no longer restates the backend's, and the changelog's merged lines keep their facts. --- doc/backends.adoc | 5 +- doc/changelog.adoc | 6 +- doc/generated/defaults.adoc | 25 ++- doc/llms.txt | 20 ++- doc/tables/crypto.json | 38 ++-- doc/tables/generate.py | 164 +++++++++++------- doc/tables/generate_test.py | 89 ++++++++-- include/webcpp/crypto/detail/capabilities.hpp | 100 ++++++++++- 8 files changed, 329 insertions(+), 118 deletions(-) diff --git a/doc/backends.adoc b/doc/backends.adoc index 62646971..208a76d0 100644 --- a/doc/backends.adoc +++ b/doc/backends.adoc @@ -40,8 +40,9 @@ rule is the same, but OpenSSL is built without assembly there: the default is then table-based and not constant time, and a program that timing attacks threaten defines `WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL`. Sizes and speeds are not measured yet. -It applies to `aes128_gcm`, `aes256_gcm` and `aes256<>`; libsecp256k1 and ctaes -are the only backends of what they implement. +The table gives the default of each family: AES-GCM's applies to `aes128_gcm`, +`aes256_gcm` and `aes256<>`; the AES block cipher has none of its own, and +libsecp256k1 is the only backend of secp256k1. include::generated/defaults.adoc[] diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 456cced2..2eba8c06 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -18,11 +18,11 @@ of every version are on webcpp's index page. // tag::unreleased[] * Added crypto, primitives over C backends: ciphers, curves and randomness, with errors of fixed values in webcpp.crypto, every result `+[[nodiscard]]+`. * Added equal, random_device, ciphers::aes128, aes192 and aes256, the AES block cipher, and ciphers::gcm, AES-GCM in place with an incremental seal whose failed open zeroes the data. -* Added the default backend, ciphers::aes128_gcm and aes256_gcm, and the refusals of backends that conflict. -* Added backends::bearssl on every target, backends::openssl with /webcpp/crypto//openssl on native and WASI, and backends::ctaes: AES-GCM allocating nothing per message, the block cipher on OpenSSL and ctaes. +* Added the default backend, ciphers::aes128_gcm and aes256_gcm, and refusals of conflicting or missing backends that name the Jamfile line to add. +* Added backends::bearssl (AES-GCM allocating nothing, no block cipher), backends::openssl through /webcpp/crypto//openssl on native and WASI (allocating at make only), and backends::ctaes (block cipher alone). * Added WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE: OpenSSL's allocations in the program's resource, refused on WebAssembly (WASI included) and without OpenSSL: openssl_memory_resource, install_memory_functions, memory_functions_refused, memory_functions_not_installed. * Added curves::secp256k1: key pairs, BIP340 and ECDSA signatures, ECDH, strict DER, low-S and the x-only tweak. -* Added backends::sodium on /third_party//sodium, which webcpp::hash shares, and every backend's link-time canary, with the C libraries' own suites on webcpp's build. +* Added backends::sodium on /third_party//sodium, shared with webcpp::hash and initialised before every engine, and every backend's link-time canary and C suite. * Added the page: a chapter per namespace and use case, the memory option's guide and example, tables generated from the tests, every Jamfile and message, and llms.txt. * Added supports_v, the capability table on the target being compiled, and the tags of its families and algorithms, which ciphers::gcm, the AES block cipher and secp256k1's key pair name. * Added secret, a self-wiping array that is copied only by clone, and the errors 15 to 20: weak_public_key, invalid_point, invalid_scalar, invalid_padding, invalid_encoding and invalid_ciphertext_size. diff --git a/doc/generated/defaults.adoc b/doc/generated/defaults.adoc index 1ecef013..e22bcd1a 100644 --- a/doc/generated/defaults.adoc +++ b/doc/generated/defaults.adoc @@ -7,49 +7,70 @@ // 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. -[.wrap-names,cols="2,4,2,5,3",options="header"] +[.wrap-names,cols="2,2,4,2,5,3",options="header"] |=== -|Target |Linked |Default |Why |Tested by +|Family |Target |Linked |Default |Why |Tested by +|AES-GCM |emscripten |BearSSL |BearSSL |the only AEAD backend there: webcpp does not build OpenSSL for Emscripten; size and speed not measured yet |`+default_bearssl+` +|AES-GCM |wasip2, wasip3 |BearSSL, with or without OpenSSL |BearSSL |constant time by design (link:https://www.bearssl.org/constanttime.html[BearSSL, constant-time crypto]), where OpenSSL is built no-asm and its AES and GHASH are table-based (link:https://github.com/openssl/openssl/blob/master/INSTALL.md[OpenSSL's INSTALL.md, no-asm]) |`+default_bearssl+`, `+default_both_wasm+` +|AES-GCM |wasip2, wasip3 |BearSSL and OpenSSL, with `+WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL+` |OpenSSL |the program's choice |`+default_openssl_wasm+` +|AES-GCM |native, Clang and GCC |OpenSSL, with or without BearSSL |OpenSSL |OpenSSL's assembly uses the CPU's AES and carry-less multiplication instructions on x86-64 and ARMv8 (link:https://github.com/openssl/openssl/tree/master/crypto/aes/asm[OpenSSL's AES assembly for ARMv8 and x86-64]; link:https://github.com/openssl/openssl/tree/master/crypto/modes/asm[OpenSSL's GHASH and AES-GCM assembly]); BearSSL has them on x86 only (link:https://www.bearssl.org/support.html[BearSSL, the AES implementations it selects]); speed not measured yet |`+default_both+` +|AES-GCM |native, MSVC |OpenSSL, with or without BearSSL |OpenSSL |the same rule as with Clang and GCC, but here OpenSSL is built no-asm: table-based AES and 4-bit GHASH, no AES-NI, not constant time (link:https://github.com/openssl/openssl/blob/master/INSTALL.md[OpenSSL's INSTALL.md, no-asm]); where timing attacks matter, link BearSSL and define `WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL` |`+default_both+` +|AES-GCM |native |BearSSL and OpenSSL, with `+WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL+` |BearSSL |the program's choice, constant time by design (link:https://www.bearssl.org/constanttime.html[BearSSL, constant-time crypto]): on MSVC, where OpenSSL is built no-asm, the choice for code that timing attacks threaten |`+default_selected+` +|AES-GCM |native |BearSSL alone |BearSSL |the backend that is linked |`+default_bearssl+` + +|AES block cipher +|native, wasip2, wasip3, emscripten +|any backend +|none +|a raw block cipher is a building block a program chooses deliberately, naming its backend; `aes256<>` takes AES-GCM's default as its argument, and its `make` does not compile where that is BearSSL +|`+default_selection_bearssl+` + +|secp256k1 +|native, wasip2, wasip3, emscripten +|libsecp256k1 +|libsecp256k1 +|the only backend (link:https://github.com/bitcoin-core/secp256k1#readme[libsecp256k1's README]) +|`+secp256k1+` |=== diff --git a/doc/llms.txt b/doc/llms.txt index d9137d3b..321083ce 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -56,15 +56,17 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [curves::secp256k1::tweak_xonly](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1): Tweaks an x-only public key by a 32-byte tweak a protocol computes. Header . Backends: libsecp256k1 (/third_party//secp256k1) on native, wasip2, wasip3, emscripten. - tweak_xonly: Tweaks an x-only public key by a 32-byte tweak t: P + t*G, with libsecp256k1's static context, which allocates nothing (`secp256k1_xonly_pubkey_tweak_add`). -## Default backend of aes128_gcm, aes256_gcm and aes256<> - -- emscripten, linked BearSSL: BearSSL; the only AEAD backend there: webcpp does not build OpenSSL for Emscripten; size and speed not measured yet. -- wasip2, wasip3, linked BearSSL, with or without OpenSSL: BearSSL; constant time by design ([BearSSL, constant-time crypto](https://www.bearssl.org/constanttime.html)), where OpenSSL is built no-asm and its AES and GHASH are table-based ([OpenSSL's INSTALL.md, no-asm](https://github.com/openssl/openssl/blob/master/INSTALL.md)). -- wasip2, wasip3, linked BearSSL and OpenSSL, with `WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL`: OpenSSL; the program's choice. -- native, Clang and GCC, linked OpenSSL, with or without BearSSL: OpenSSL; OpenSSL's assembly uses the CPU's AES and carry-less multiplication instructions on x86-64 and ARMv8 ([OpenSSL's AES assembly for ARMv8 and x86-64](https://github.com/openssl/openssl/tree/master/crypto/aes/asm); [OpenSSL's GHASH and AES-GCM assembly](https://github.com/openssl/openssl/tree/master/crypto/modes/asm)); BearSSL has them on x86 only ([BearSSL, the AES implementations it selects](https://www.bearssl.org/support.html)); speed not measured yet. -- native, MSVC, linked OpenSSL, with or without BearSSL: OpenSSL; the same rule as with Clang and GCC, but here OpenSSL is built no-asm: table-based AES and 4-bit GHASH, no AES-NI, not constant time ([OpenSSL's INSTALL.md, no-asm](https://github.com/openssl/openssl/blob/master/INSTALL.md)); where timing attacks matter, link BearSSL and define `WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL`. -- native, linked BearSSL and OpenSSL, with `WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL`: BearSSL; the program's choice, constant time by design ([BearSSL, constant-time crypto](https://www.bearssl.org/constanttime.html)): on MSVC, where OpenSSL is built no-asm, the choice for code that timing attacks threaten. -- native, linked BearSSL alone: BearSSL; the backend that is linked. +## Default backend per family + +- AES-GCM, emscripten, linked BearSSL: BearSSL; the only AEAD backend there: webcpp does not build OpenSSL for Emscripten; size and speed not measured yet. +- AES-GCM, wasip2, wasip3, linked BearSSL, with or without OpenSSL: BearSSL; constant time by design ([BearSSL, constant-time crypto](https://www.bearssl.org/constanttime.html)), where OpenSSL is built no-asm and its AES and GHASH are table-based ([OpenSSL's INSTALL.md, no-asm](https://github.com/openssl/openssl/blob/master/INSTALL.md)). +- AES-GCM, wasip2, wasip3, linked BearSSL and OpenSSL, with `WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL`: OpenSSL; the program's choice. +- AES-GCM, native, Clang and GCC, linked OpenSSL, with or without BearSSL: OpenSSL; OpenSSL's assembly uses the CPU's AES and carry-less multiplication instructions on x86-64 and ARMv8 ([OpenSSL's AES assembly for ARMv8 and x86-64](https://github.com/openssl/openssl/tree/master/crypto/aes/asm); [OpenSSL's GHASH and AES-GCM assembly](https://github.com/openssl/openssl/tree/master/crypto/modes/asm)); BearSSL has them on x86 only ([BearSSL, the AES implementations it selects](https://www.bearssl.org/support.html)); speed not measured yet. +- AES-GCM, native, MSVC, linked OpenSSL, with or without BearSSL: OpenSSL; the same rule as with Clang and GCC, but here OpenSSL is built no-asm: table-based AES and 4-bit GHASH, no AES-NI, not constant time ([OpenSSL's INSTALL.md, no-asm](https://github.com/openssl/openssl/blob/master/INSTALL.md)); where timing attacks matter, link BearSSL and define `WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL`. +- AES-GCM, native, linked BearSSL and OpenSSL, with `WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL`: BearSSL; the program's choice, constant time by design ([BearSSL, constant-time crypto](https://www.bearssl.org/constanttime.html)): on MSVC, where OpenSSL is built no-asm, the choice for code that timing attacks threaten. +- AES-GCM, native, linked BearSSL alone: BearSSL; the backend that is linked. +- AES block cipher, native, wasip2, wasip3, emscripten, linked any backend: none; a raw block cipher is a building block a program chooses deliberately, naming its backend; `aes256<>` takes AES-GCM's default as its argument, and its `make` does not compile where that is BearSSL. +- secp256k1, native, wasip2, wasip3, emscripten, linked libsecp256k1: libsecp256k1; the only backend ([libsecp256k1's README](https://github.com/bitcoin-core/secp256k1#readme)). ## Rules of use diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index d70426e9..eb5398fd 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -1,5 +1,5 @@ { - "comment": "The data of crypto's generated tables and of llms.txt; doc/tables/generate.py reads it with the test Jamfiles, the message tests and the superproject's Jamfile fixtures, and writes doc/generated/, doc/llms.txt, include/webcpp/crypto/detail/capabilities.hpp and test/capabilities_test.cpp. The capability table is `families`: per family its algorithms, the targets on which each backend has it (each claimed only where a test of the family's operations on that backend runs), constant time where it is not by the backend's design, and the default per target with its reason; a backend with `targets`, where it is built, is a tag of `backends`. A name in a text is written between backticks, as Markdown writes code: the tables show it as code and llms.txt keeps the backticks. Edit this file, then run python3 libs/crypto/doc/tables/generate.py; the doc build runs it with --check.", + "comment": "The data of crypto's generated tables and of llms.txt; doc/tables/generate.py reads it with the test Jamfiles, the message tests and the superproject's Jamfile fixtures, and writes doc/generated/, doc/llms.txt, include/webcpp/crypto/detail/capabilities.hpp and test/capabilities_test.cpp. The capability table is `families`: per family its algorithms, the targets on which each backend has it (each claimed only where a test of the family's operations on that backend runs), constant time per target where it differs from the backend's own `constant_time` (none yet), and the default per target and what the program links, as the code has it now, with its reason and the tests that fix it; a backend with `targets`, where it is built, is a tag of `backends`. A name in a text is written between backticks, as Markdown writes code: the tables show it as code and llms.txt keeps the backticks. Edit this file, then run python3 libs/crypto/doc/tables/generate.py; the doc build runs it with --check.", "page": "https://webcpporg.github.io/libs/crypto/", "targets": ["native", "wasip2", "wasip3", "emscripten"], "sources": { @@ -176,6 +176,7 @@ { "id": "aes_block", "family": "aes_block", + "default_of": "gcm", "functions": ["make", "encrypt", "decrypt"], "namespace": "ciphers", "api": "ciphers::aes128, aes192, aes256", @@ -276,17 +277,17 @@ {"name": "aes256_gcm", "title": "AES-256-GCM", "type": "ciphers::gcm>"} ], "default": [ - {"targets": ["native"], "backend": "openssl", "why": "OpenSSL's assembly uses the CPU's AES and carry-less multiplication instructions on x86-64 and ARMv8 ({openssl-armv8}; {openssl-ghash-asm}); BearSSL has them on x86 only ({bearssl-aes})"}, - {"targets": ["wasip2", "wasip3"], "backend": "bearssl", "why": "constant time by design ({bearssl-ct}), where OpenSSL is built no-asm and its AES and GHASH are table-based ({openssl-install})"}, - {"targets": ["emscripten"], "backend": "bearssl", "why": "the only backend there: webcpp does not build OpenSSL for Emscripten; constant time by design ({bearssl-ct})"} + {"targets": ["emscripten"], "linked": "BearSSL", "backend": "bearssl", "tests": ["default_bearssl"], "why": "the only AEAD backend there: webcpp does not build OpenSSL for Emscripten; size and speed not measured yet"}, + {"targets": ["wasip2", "wasip3"], "linked": "BearSSL, with or without OpenSSL", "backend": "bearssl", "tests": ["default_bearssl", "default_both_wasm"], "why": "constant time by design ({bearssl-ct}), where OpenSSL is built no-asm and its AES and GHASH are table-based ({openssl-install})"}, + {"targets": ["wasip2", "wasip3"], "linked": "BearSSL and OpenSSL, with `WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL`", "backend": "openssl", "tests": ["default_openssl_wasm"], "why": "the program's choice"}, + {"targets": ["native"], "where": "Clang and GCC", "linked": "OpenSSL, with or without BearSSL", "backend": "openssl", "tests": ["default_both"], "why": "OpenSSL's assembly uses the CPU's AES and carry-less multiplication instructions on x86-64 and ARMv8 ({openssl-armv8}; {openssl-ghash-asm}); BearSSL has them on x86 only ({bearssl-aes}); speed not measured yet"}, + {"targets": ["native"], "where": "MSVC", "linked": "OpenSSL, with or without BearSSL", "backend": "openssl", "tests": ["default_both"], "why": "the same rule as with Clang and GCC, but here OpenSSL is built no-asm: table-based AES and 4-bit GHASH, no AES-NI, not constant time ({openssl-install}); where timing attacks matter, link BearSSL and define `WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL`"}, + {"targets": ["native"], "linked": "BearSSL and OpenSSL, with `WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL`", "backend": "bearssl", "tests": ["default_selected"], "why": "the program's choice, constant time by design ({bearssl-ct}): on MSVC, where OpenSSL is built no-asm, the choice for code that timing attacks threaten"}, + {"targets": ["native"], "linked": "BearSSL alone", "backend": "bearssl", "tests": ["default_bearssl"], "why": "the backend that is linked"} ], "backends": { "bearssl": {"targets": "all"}, - "openssl": {"targets": "all", "constant_time": { - "native": "with assembly (Clang and GCC), AES-NI and carry-less multiplication where the CPU has them; built no-asm on MSVC, table-based AES and 4-bit GHASH, neither constant time ({openssl-install})", - "wasip2": "not constant time: built no-asm, table-based AES and 4-bit GHASH ({openssl-install}; {openssl-aes-core})", - "wasip3": "not constant time: built no-asm, table-based AES and 4-bit GHASH ({openssl-install}; {openssl-aes-core})" - }} + "openssl": {"targets": "all"} } }, { @@ -301,14 +302,10 @@ {"name": "aes256", "title": "AES-256", "type": "ciphers::aes256<{backend}>"} ], "default": [ - {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": null, "why": "none: a raw block cipher is a building block a program chooses deliberately, naming its backend; `aes256<>` takes AES-GCM's default as its argument, and its `make` does not compile where that is BearSSL"} + {"targets": ["native", "wasip2", "wasip3", "emscripten"], "linked": "any backend", "backend": null, "tests": ["default_selection_bearssl"], "why": "a raw block cipher is a building block a program chooses deliberately, naming its backend; `aes256<>` takes AES-GCM's default as its argument, and its `make` does not compile where that is BearSSL"} ], "backends": { - "openssl": {"targets": "all", "constant_time": { - "native": "with assembly (Clang and GCC), AES-NI where the CPU has it; built no-asm on MSVC, table-based AES, not constant time ({openssl-install})", - "wasip2": "not constant time: built no-asm, table-based AES ({openssl-install}; {openssl-aes-core})", - "wasip3": "not constant time: built no-asm, table-based AES ({openssl-install}; {openssl-aes-core})" - }}, + "openssl": {"targets": "all"}, "ctaes": {"targets": "all"} } }, @@ -322,7 +319,7 @@ {"name": "secp256k1", "title": "secp256k1", "type": "curves::secp256k1::basic_keypair<{backend}>"} ], "default": [ - {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "secp256k1", "why": "the only backend ({libsecp256k1})"} + {"targets": ["native", "wasip2", "wasip3", "emscripten"], "linked": "libsecp256k1", "backend": "secp256k1", "tests": ["secp256k1"], "why": "the only backend ({libsecp256k1})"} ], "backends": { "secp256k1": {"targets": "all"} @@ -354,15 +351,6 @@ "openssl": "`/webcpp/crypto//openssl` stops the build there", "refused": "refused at compile time" }, - "defaults": [ - {"target": "emscripten", "linked": "BearSSL", "default": "bearssl", "tests": ["default_bearssl"], "why": "the only AEAD backend there: webcpp does not build OpenSSL for Emscripten; size and speed not measured yet"}, - {"target": "wasip2, wasip3", "linked": "BearSSL, with or without OpenSSL", "default": "bearssl", "tests": ["default_bearssl", "default_both_wasm"], "why": "constant time by design ({bearssl-ct}), where OpenSSL is built no-asm and its AES and GHASH are table-based ({openssl-install})"}, - {"target": "wasip2, wasip3", "linked": "BearSSL and OpenSSL, with `WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL`", "default": "openssl", "tests": ["default_openssl_wasm"], "why": "the program's choice"}, - {"target": "native, Clang and GCC", "linked": "OpenSSL, with or without BearSSL", "default": "openssl", "tests": ["default_both"], "why": "OpenSSL's assembly uses the CPU's AES and carry-less multiplication instructions on x86-64 and ARMv8 ({openssl-armv8}; {openssl-ghash-asm}); BearSSL has them on x86 only ({bearssl-aes}); speed not measured yet"}, - {"target": "native, MSVC", "linked": "OpenSSL, with or without BearSSL", "default": "openssl", "tests": ["default_both"], "why": "the same rule as with Clang and GCC, but here OpenSSL is built no-asm: table-based AES and 4-bit GHASH, no AES-NI, not constant time ({openssl-install}); where timing attacks matter, link BearSSL and define `WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL`"}, - {"target": "native", "linked": "BearSSL and OpenSSL, with `WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL`", "default": "bearssl", "tests": ["default_selected"], "why": "the program's choice, constant time by design ({bearssl-ct}): on MSVC, where OpenSSL is built no-asm, the choice for code that timing attacks threaten"}, - {"target": "native", "linked": "BearSSL alone", "default": "bearssl", "tests": ["default_bearssl"], "why": "the backend that is linked"} - ], "namespaces": { "root": { "title": "webcpp::crypto", diff --git a/doc/tables/generate.py b/doc/tables/generate.py index 5558c02d..743bef0b 100644 --- a/doc/tables/generate.py +++ b/doc/tables/generate.py @@ -437,19 +437,28 @@ def check_families(data: Data, declared: Dict[str, List[str]]) -> None: raise Fault(f'crypto.json: the family {name} states constant time for ' f'{backend} on {target}, where it does not claim it') cite(data, why) - defaults: Dict[str, Optional[str]] = {} + # A default per target and what the program links (and, natively, the compiler), each + # claimed only where a test that fixes it runs. + defaults: List[Tuple[str, str, str]] = [] for entry in family['default']: cite(data, entry['why']) for target in entry['targets']: - if target in defaults: - raise Fault(f'crypto.json: the family {name} has two defaults on {target}') - defaults[target] = entry['backend'] + key = (target, entry.get('where', ''), entry['linked']) + if key in defaults: + raise Fault(f'crypto.json: the family {name} has two defaults on {target}, ' + f'linked {entry["linked"]}') + defaults.append(key) backend = entry['backend'] if backend is not None and (backend not in family['backends'] or target not in cell_targets(data, family, backend)): raise Fault(f'crypto.json: the family {name} defaults to {backend} on ' f'{target}, which does not have it there') - missing = [target for target in data['targets'] if target not in defaults] + for test in entry['tests']: + if target not in declared.get(test, []): + raise Fault(f'crypto.json: the family {name}\'s default on {target} ' + f'names the test {test}, which does not run there') + covered = {target for target, _, _ in defaults} + missing = [target for target in data['targets'] if target not in covered] if missing: raise Fault(f'crypto.json: the family {name} has no default on {", ".join(missing)}') @@ -483,8 +492,14 @@ def doc_comment(text: str) -> List[str]: return ['/**'] + [f' * {line}' for line in textwrap.wrap(text, 97)] + [' */'] -# A qualified name of crypto.json's types, which are written from webcpp::crypto. -QUALIFIED = re.compile(r'(? str: + """A type of crypto.json, written from webcpp::crypto, as the generated test names it: each + of crypto's namespaces that starts a name is reached through `crypto::`, and `{backend}` is + the backend's tag. Any other namespace, std:: among them, is left as it is.""" + namespaces = ({name for name in data.get('namespaces', {}) if name != 'root'} + | {family['group'].split('::')[0] for family in data['families']}) + qualified = re.compile(rf'(? str: @@ -547,31 +562,38 @@ def capabilities_header(data: Data) -> str: '#endif'] out += ['// clang-format on', '', '} // namespace webcpp::crypto::detail', '', '// The body of each family\'s primary engine, which a backend reaches where its', - '// header does not specialise the engine: a backend without the family is refused,', - '// naming those that have it; a backend that has it, whose header the program did', - '// not include, is told to include it; any other type is no backend of the family.', + '// header does not specialise the engine, per target: a backend without the family', + '// there is refused, naming those that have it; a backend that has it there, whose', + '// header the program did not include, is told to include it; any other type is no', + '// backend of the family.', '// clang-format off'] tags = tags_of(data) for family in data['families']: have = have_list(data, family) - lines: List[str] = [] - for backend in tags: - if backend in family['backends']: - facts = data['backends'][backend] - text = (f'webcpp::crypto: {backend}\'s {family["title"]} is in ' - f'{facts["header"]}, which the program does not include. Include it, and ' - f'add {facts["jamfile"]} to the program\'s Jamfile.') - else: - text = refusal(data, family, backend) - lines.append(f'static_assert(!std::is_same_v, "{text}")') - lines.append(f'static_assert(::webcpp::crypto::detail::dependent_false, ' - f'"webcpp::crypto: {family["title"]} has no backend of that name. The ' - f'backends that have it: {have}.")') - out += doc_comment(f'The refusals of the family {family["title"]}\'s primary engine for ' - '`Backend`.') + [ - f'#define WEBCPP_CRYPTO_DETAIL_REFUSE_{family["name"].upper()}(Backend) \\'] - out += [f' {line}; \\' for line in lines[:-1]] + [f' {lines[-1]}'] + for index, target in enumerate(data['targets']): + lines: List[str] = [] + for backend in tags: + if backend not in family['backends']: + text = refusal(data, family, backend) + elif target in cell_targets(data, family, backend): + facts = data['backends'][backend] + text = (f'webcpp::crypto: {backend}\'s {family["title"]} is in ' + f'{facts["header"]}, which the program does not include. Include ' + f'it, and add {facts["jamfile"]} to the program\'s Jamfile.') + else: + text = (f'webcpp::crypto: {backend} has no {family["title"]} on {target}. ' + f'The backends that have it: {have}.') + lines.append(f'static_assert(!std::is_same_v, "{text}")') + lines.append(f'static_assert(::webcpp::crypto::detail::dependent_false, ' + f'"webcpp::crypto: {family["title"]} has no backend of that name. The ' + f'backends that have it: {have}.")') + out.append(f'#{"if" if index == 0 else "elif"} defined({TARGET_MACROS[target]})') + out += doc_comment(f'The refusals of the family {family["title"]}\'s primary engine ' + f'for `Backend`, on {target}.') + [ + f'#define WEBCPP_CRYPTO_DETAIL_REFUSE_{family["name"].upper()}(Backend) \\'] + out += [f' {line}; \\' for line in lines[:-1]] + [f' {lines[-1]}'] + out.append('#endif') out += ['// clang-format on', '', '#endif // WEBCPP_CRYPTO_DETAIL_CAPABILITIES_HPP', ''] return '\n'.join(out) @@ -625,8 +647,7 @@ def capabilities_test(data: Data) -> str: continue out += [f'#if {condition(targets)}', f'static_assert({trait});', '#else', f'static_assert(!{trait});', '#endif'] - algorithm = QUALIFIED.sub(r'crypto::\1', entry['type']).format( - backend=f'backends::{backend}') + algorithm = program_type(data, entry['type'], backend) made += [f'#if ({condition(targets)}) && defined(WEBCPP_CRYPTO_HAS_' f'{backend.upper()})', f' BOOST_TEST((webcpp::test::made<{algorithm}, ' @@ -682,8 +703,10 @@ def api_backends(data: Data, matrix: Matrix, operation: Data) -> str: text = (f'The backends of {names(operation["api"])}, from the test programs that run it:\n\n' + table(['Backend', 'Jamfile', 'Header', 'Targets'], rows, 'cols="1,2,2,4",')) if 'default' in operation: - defaults = [[entry['target'], marked(entry['linked']), - data['backends'][entry['default']]['title']] for entry in data['defaults']] + # The block cipher's default argument is AES-GCM's default: its table is AES-GCM's. + family = family_of(data, operation.get('default_of', operation['family'])) + defaults = [[target_label(entry), marked(entry['linked']), default_title(data, entry)] + for entry in family['default']] text += (f'\n{marked(operation["default"])} The default per target and what the program ' 'links, as <> gives it with its reasons and tests:\n\n' + table(['Target', 'Linked', 'Default'], defaults, '.wrap-names,cols="2,4,2",')) @@ -730,22 +753,39 @@ def facts_page(data: Data, matrix: Matrix) -> str: rows, 'cols="1,2,1,2,3",')) -def defaults_page(data: Data, declared: Dict[str, List[str]]) -> str: - """The default backend per target and what is linked, each with the tests that fix it.""" +def family_of(data: Data, name: str) -> Data: + """The family of crypto.json named name.""" + for family in data['families']: + if family['name'] == name: + return family + raise Fault(f'crypto.json names the family {name}, which it does not list') + + +def target_label(entry: Data) -> str: + """The targets of a default, and the compiler where it is one compiler's.""" + where = f', {entry["where"]}' if entry.get('where') else '' + return ', '.join(entry['targets']) + where + + +def default_title(data: Data, entry: Data) -> str: + """The default backend's title, or none.""" + return data['backends'][entry['backend']]['title'] if entry['backend'] else 'none' + + +def defaults_page(data: Data) -> str: + """The default backend of each family per target and what is linked, each with the tests + that fix it (check_families has checked that they run there).""" rows: List[List[str]] = [] - for entry in data['defaults']: - for name in entry['tests']: - if name not in declared: - raise Fault(f'crypto.json: the default on {entry["target"]} names the test ' - f'{name}, which no test Jamfile declares') - rows.append([entry['target'], marked(entry['linked']), - data['backends'][entry['default']]['title'], cite(data, entry['why']), - ', '.join(code(name) for name in entry['tests'])]) + for family in data['families']: + for entry in family['default']: + rows.append([family['title'], target_label(entry), marked(entry['linked']), + default_title(data, entry), cite(data, entry['why']), + ', '.join(code(name) for name in entry['tests'])]) # wrap-names: a header in "Linked" breaks after its / at every width; a define of 37 # characters breaks between its parts where the table does not fit otherwise, rather than # take the width "Why" needs (tools/doc/docinfo.html). - return table(['Target', 'Linked', 'Default', 'Why', 'Tested by'], rows, - '.wrap-names,cols="2,4,2,5,3",') + return table(['Family', 'Target', 'Linked', 'Default', 'Why', 'Tested by'], rows, + '.wrap-names,cols="2,2,4,2,5,3",') def constant_time_page(data: Data) -> str: @@ -1000,11 +1040,11 @@ def llms(data: Data, matrix: Matrix, library: Path) -> str: out.append(f' - {function}: ' f'{declared_brief(library, operation, function)}') out.append('') - out += ['## Default backend of aes128_gcm, aes256_gcm and aes256<>', ''] - for entry in data['defaults']: - out.append(f'- {entry["target"]}, linked {entry["linked"]}: ' - f'{data["backends"][entry["default"]]["title"]}; ' - f'{cite_markdown(data, entry["why"])}.') + out += ['## Default backend per family', ''] + for family in data['families']: + for entry in family['default']: + out.append(f'- {family["title"]}, {target_label(entry)}, linked {entry["linked"]}: ' + f'{default_title(data, entry)}; {cite_markdown(data, entry["why"])}.') out += ['', '## Rules of use', ''] for rule in data['rules']: out.append(f'- [{rule["title"]}]({page}#{rule["section"]}): ' @@ -1048,7 +1088,7 @@ def generate(root: Path, library: Path) -> Dict[Path, str]: operation) files[generated / 'matrix.adoc'] = matrix_page(data, matrix) files[generated / 'backend-facts.adoc'] = facts_page(data, matrix) - files[generated / 'defaults.adoc'] = defaults_page(data, declared) + files[generated / 'defaults.adoc'] = defaults_page(data) files[generated / 'constant-time.adoc'] = constant_time_page(data) files[generated / 'sizes.adoc'] = sizes_page(data) files[generated / 'jamfiles.adoc'] = jamfiles_page(data, cases) @@ -1063,6 +1103,20 @@ def generate(root: Path, library: Path) -> Dict[Path, str]: return files +def checked(files: Dict[Path, str], library: Path, generated: Path) -> int: + """--check: prints each file that differs from what generate.py writes, and each page of + generated that it does not write, by its path in library. 1 when there is one, else 0.""" + differing = stale(files) + extra = sorted(path for path in generated.glob('*.adoc') if path not in files) + for path in differing: + print(f'generate.py: {path.relative_to(library)} is not what crypto.json and the tree ' + 'give: run python3 libs/crypto/doc/tables/generate.py', file=sys.stderr) + for path in extra: + print(f'generate.py: {path.relative_to(library)} is generated by nothing: remove it', + file=sys.stderr) + return 1 if differing or extra else 0 + + def main() -> int: parser = argparse.ArgumentParser(description=(__doc__ or '').split('\n', 1)[0]) parser.add_argument('--check', action='store_true') @@ -1073,16 +1127,10 @@ def main() -> int: except Fault as fault: print(f'generate.py: {fault}', file=sys.stderr) return 1 + if arguments.check: + return checked(files, LIBRARY, DOC / 'generated') differing = stale(files) extra = sorted(path for path in (DOC / 'generated').glob('*.adoc') if path not in files) - if arguments.check: - for path in differing: - print(f'generate.py: {path.relative_to(LIBRARY)} is not what crypto.json and the ' - 'tree give: run python3 libs/crypto/doc/tables/generate.py', file=sys.stderr) - for path in extra: - print(f'generate.py: {path.relative_to(LIBRARY)} is generated by nothing: remove it', - file=sys.stderr) - return 1 if differing or extra else 0 for path in differing: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(files[path], encoding='utf-8') diff --git a/doc/tables/generate_test.py b/doc/tables/generate_test.py index 53831525..70492835 100644 --- a/doc/tables/generate_test.py +++ b/doc/tables/generate_test.py @@ -23,10 +23,13 @@ from __future__ import annotations +import io import sys import tempfile +from contextlib import redirect_stderr from collections.abc import Callable from pathlib import Path +from typing import Optional HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE)) @@ -252,8 +255,8 @@ def backend(title: str, name: str, jamfile: str) -> generate.Data: 'header': '', 'names': [{'name': 'ed25519', 'title': 'Ed25519', 'type': 'curves::ed25519::basic_keypair<{backend}>'}], - 'default': [{'targets': EVERY_TARGET, 'backend': 'sodium', - 'why': 'the only backend ({rfc8032})'}], + 'default': [{'targets': EVERY_TARGET, 'linked': 'libsodium', 'backend': 'sodium', + 'tests': ['ed25519'], 'why': 'the only backend ({rfc8032})'}], 'backends': {'sodium': {'targets': 'all'}}}]} @@ -348,24 +351,81 @@ def test_a_cell_claimed_where_no_test_runs_is_a_fault(_: Path) -> None: 'the family ed25519 claims sodium on wasip2, where sodium is not built') -def test_a_default_is_one_backend_of_the_family_per_target(_: Path) -> None: +def test_a_default_is_a_backend_of_the_family_its_tests_run_on(_: Path) -> None: + def default(targets: list[str], backend: Optional[str], linked: str = 'libsodium', + tests: Optional[list[str]] = None) -> generate.Data: + return {'targets': targets, 'linked': linked, 'backend': backend, + 'tests': ['ed25519'] if tests is None else tests, 'why': 'w'} data = small_table() - data['families'][0]['default'] = [{'targets': ['native'], 'backend': 'sodium', 'why': 'w'}] - a_fault(data, {'ed25519': EVERY_TARGET}, - 'the family ed25519 has no default on wasip2, wasip3, emscripten') - data['families'][0]['default'] = [{'targets': EVERY_TARGET, 'backend': 'bearssl', - 'why': 'w'}] - a_fault(data, {'ed25519': EVERY_TARGET}, + every = {'ed25519': EVERY_TARGET, 'ed25519_native': ['native']} + data['families'][0]['default'] = [default(['native'], 'sodium')] + a_fault(data, every, 'the family ed25519 has no default on wasip2, wasip3, emscripten') + data['families'][0]['default'] = [default(EVERY_TARGET, 'bearssl')] + a_fault(data, every, 'the family ed25519 defaults to bearssl on native, which does not have it there') - data['families'][0]['default'] = [{'targets': EVERY_TARGET, 'backend': 'sodium', 'why': 'w'}, - {'targets': ['native'], 'backend': None, 'why': 'w'}] - a_fault(data, {'ed25519': EVERY_TARGET}, 'the family ed25519 has two defaults on native') + data['families'][0]['default'] = [default(EVERY_TARGET, 'sodium'), + default(['native'], None)] + a_fault(data, every, 'the family ed25519 has two defaults on native, linked libsodium') + # What the program links tells two defaults of one target apart. + data['families'][0]['default'] = [default(EVERY_TARGET, 'sodium'), + default(['native'], None, 'nothing')] + generate.check_families(data, every) + # A default is claimed only where a test that fixes it runs. + data['families'][0]['default'] = [default(EVERY_TARGET, 'sodium', tests=['ed25519_native'])] + a_fault(data, every, 'the family ed25519\'s default on wasip2 names the test ed25519_native, ' + 'which does not run there') + data['families'][0]['default'] = [default(EVERY_TARGET, 'sodium', tests=['absent'])] + a_fault(data, every, 'the family ed25519\'s default on native names the test absent, which ' + 'does not run there') data = small_table() data['operations'][0]['family'] = 'ed448' a_fault(data, {'ed25519': EVERY_TARGET}, 'the operation sign names the family ed448, which crypto.json does not list') +def test_a_refusal_holds_on_its_target(_: Path) -> None: + data = small_table() + data['families'][0]['backends']['sodium']['targets'] = ['native'] + header = generate.capabilities_header(data) + native, rest = header.split('#elif defined(WEBCPP_TARGET_WASIP2)\n', 1) + wasip2 = rest.split('#elif', 1)[0] + # Natively sodium has Ed25519: a primary engine reached means its header is not included. + assert 'sodium\'s Ed25519 is in ' in native, native + # On wasip2 it has none, and is never told to include a header that would not give it. + assert ('"webcpp::crypto: sodium has no Ed25519 on wasip2. The backends that have it: sodium ' + '(native).")') in wasip2, wasip2 + assert 'is in ' not in wasip2, wasip2 + assert '#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE)\n' in native, native + assert header.count('#define WEBCPP_CRYPTO_DETAIL_REFUSE_ED25519(Backend)') == 4, header + + +def test_a_type_names_only_crypto_s_namespaces_from_the_root(_: Path) -> None: + data = small_table() + data['families'][0]['names'][0]['type'] = 'curves::ed25519::basic' + test = generate.capabilities_test(data) + assert 'crypto::curves::ed25519::basic' in test, test + + +def test_the_check_prints_each_file_that_differs(scratch: Path) -> None: + files = {scratch / 'include/a.hpp': 'one\n', scratch / 'test/b.cpp': 'two\n'} + generated = scratch / 'doc/generated' + for path, text in files.items(): + written(path.parent, path.name, text) + printed = io.StringIO() + with redirect_stderr(printed): + assert generate.checked(files, scratch, generated) == 0 + assert printed.getvalue() == '', printed.getvalue() + written(scratch / 'test', 'b.cpp', 'twO\n') + written(generated, 'old.adoc', '') + with redirect_stderr(printed): + assert generate.checked(files, scratch, generated) == 1 + assert printed.getvalue() == ( + 'generate.py: test/b.cpp is not what crypto.json and the tree give: run python3 ' + 'libs/crypto/doc/tables/generate.py\n' + 'generate.py: doc/generated/old.adoc is generated by nothing: remove it\n'), ( + printed.getvalue()) + + def test_the_check_names_a_file_that_differs(scratch: Path) -> None: files = {scratch / 'include/a.hpp': 'one\n', scratch / 'test/b.cpp': 'two\n'} for path, text in files.items(): @@ -397,7 +457,10 @@ def test_the_check_names_a_file_that_differs(scratch: Path) -> None: test_the_generated_test_asserts_every_cell, test_a_family_that_names_an_unknown_backend_is_a_fault, test_a_cell_claimed_where_no_test_runs_is_a_fault, - test_a_default_is_one_backend_of_the_family_per_target, + test_a_default_is_a_backend_of_the_family_its_tests_run_on, + test_a_refusal_holds_on_its_target, + test_a_type_names_only_crypto_s_namespaces_from_the_root, + test_the_check_prints_each_file_that_differs, test_the_check_names_a_file_that_differs, ] diff --git a/include/webcpp/crypto/detail/capabilities.hpp b/include/webcpp/crypto/detail/capabilities.hpp index d2611419..e87fba44 100644 --- a/include/webcpp/crypto/detail/capabilities.hpp +++ b/include/webcpp/crypto/detail/capabilities.hpp @@ -136,11 +136,13 @@ inline constexpr bool supported, "webcpp::crypto: bearssl's AES-GCM is in , which the program does not include. Include it, and add /third_party//bearssl to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: openssl's AES-GCM is in , which the program does not include. Include it, and add /webcpp/crypto//openssl to the program's Jamfile."); \ @@ -148,7 +150,54 @@ inline constexpr bool supported, "webcpp::crypto: secp256k1 has no AES-GCM. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ static_assert(!std::is_same_v, "webcpp::crypto: sodium has no AES-GCM. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ static_assert(::webcpp::crypto::detail::dependent_false, "webcpp::crypto: AES-GCM has no backend of that name. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).") -/** The refusals of the family AES block cipher's primary engine for `Backend`. */ +#elif defined(WEBCPP_TARGET_WASIP2) +/** The refusals of the family AES-GCM's primary engine for `Backend`, on wasip2. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_GCM(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl's AES-GCM is in , which the program does not include. Include it, and add /third_party//bearssl to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl's AES-GCM is in , which the program does not include. Include it, and add /webcpp/crypto//openssl to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no AES-GCM. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no AES-GCM. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: sodium has no AES-GCM. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(::webcpp::crypto::detail::dependent_false, "webcpp::crypto: AES-GCM has no backend of that name. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).") +#elif defined(WEBCPP_TARGET_WASIP3) +/** The refusals of the family AES-GCM's primary engine for `Backend`, on wasip3. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_GCM(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl's AES-GCM is in , which the program does not include. Include it, and add /third_party//bearssl to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl's AES-GCM is in , which the program does not include. Include it, and add /webcpp/crypto//openssl to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no AES-GCM. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no AES-GCM. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: sodium has no AES-GCM. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(::webcpp::crypto::detail::dependent_false, "webcpp::crypto: AES-GCM has no backend of that name. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).") +#elif defined(WEBCPP_TARGET_EMSCRIPTEN) +/** The refusals of the family AES-GCM's primary engine for `Backend`, on emscripten. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_GCM(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl's AES-GCM is in , which the program does not include. Include it, and add /third_party//bearssl to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no AES-GCM on emscripten. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no AES-GCM. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no AES-GCM. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: sodium has no AES-GCM. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(::webcpp::crypto::detail::dependent_false, "webcpp::crypto: AES-GCM has no backend of that name. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).") +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) +/** The refusals of the family AES block cipher's primary engine for `Backend`, on native. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_AES_BLOCK(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no AES block cipher. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl's AES block cipher is in , which the program does not include. Include it, and add /webcpp/crypto//openssl to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes's AES block cipher is in , which the program does not include. Include it, and add /third_party//ctaes to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no AES block cipher. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: sodium has no AES block cipher. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten)."); \ + static_assert(::webcpp::crypto::detail::dependent_false, "webcpp::crypto: AES block cipher has no backend of that name. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_WASIP2) +/** The refusals of the family AES block cipher's primary engine for `Backend`, on wasip2. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_AES_BLOCK(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no AES block cipher. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl's AES block cipher is in , which the program does not include. Include it, and add /webcpp/crypto//openssl to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes's AES block cipher is in , which the program does not include. Include it, and add /third_party//ctaes to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no AES block cipher. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: sodium has no AES block cipher. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten)."); \ + static_assert(::webcpp::crypto::detail::dependent_false, "webcpp::crypto: AES block cipher has no backend of that name. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_WASIP3) +/** The refusals of the family AES block cipher's primary engine for `Backend`, on wasip3. */ #define WEBCPP_CRYPTO_DETAIL_REFUSE_AES_BLOCK(Backend) \ static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no AES block cipher. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: openssl's AES block cipher is in , which the program does not include. Include it, and add /webcpp/crypto//openssl to the program's Jamfile."); \ @@ -156,7 +205,36 @@ inline constexpr bool supported, "webcpp::crypto: secp256k1 has no AES block cipher. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: sodium has no AES block cipher. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten)."); \ static_assert(::webcpp::crypto::detail::dependent_false, "webcpp::crypto: AES block cipher has no backend of that name. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten).") -/** The refusals of the family secp256k1's primary engine for `Backend`. */ +#elif defined(WEBCPP_TARGET_EMSCRIPTEN) +/** The refusals of the family AES block cipher's primary engine for `Backend`, on emscripten. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_AES_BLOCK(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no AES block cipher. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no AES block cipher on emscripten. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes's AES block cipher is in , which the program does not include. Include it, and add /third_party//ctaes to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no AES block cipher. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: sodium has no AES block cipher. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten)."); \ + static_assert(::webcpp::crypto::detail::dependent_false, "webcpp::crypto: AES block cipher has no backend of that name. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten).") +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) +/** The refusals of the family secp256k1's primary engine for `Backend`, on native. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_SECP256K1(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1's secp256k1 is in , which the program does not include. Include it, and add /third_party//secp256k1 to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: sodium has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ + static_assert(::webcpp::crypto::detail::dependent_false, "webcpp::crypto: secp256k1 has no backend of that name. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_WASIP2) +/** The refusals of the family secp256k1's primary engine for `Backend`, on wasip2. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_SECP256K1(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1's secp256k1 is in , which the program does not include. Include it, and add /third_party//secp256k1 to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: sodium has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ + static_assert(::webcpp::crypto::detail::dependent_false, "webcpp::crypto: secp256k1 has no backend of that name. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_WASIP3) +/** The refusals of the family secp256k1's primary engine for `Backend`, on wasip3. */ #define WEBCPP_CRYPTO_DETAIL_REFUSE_SECP256K1(Backend) \ static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: openssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ @@ -164,6 +242,16 @@ inline constexpr bool supported, "webcpp::crypto: secp256k1's secp256k1 is in , which the program does not include. Include it, and add /third_party//secp256k1 to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: sodium has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ static_assert(::webcpp::crypto::detail::dependent_false, "webcpp::crypto: secp256k1 has no backend of that name. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_EMSCRIPTEN) +/** The refusals of the family secp256k1's primary engine for `Backend`, on emscripten. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_SECP256K1(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1's secp256k1 is in , which the program does not include. Include it, and add /third_party//secp256k1 to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: sodium has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ + static_assert(::webcpp::crypto::detail::dependent_false, "webcpp::crypto: secp256k1 has no backend of that name. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten).") +#endif // clang-format on #endif // WEBCPP_CRYPTO_DETAIL_CAPABILITIES_HPP From 52104c3e95d45f73421a416ac07524087dc30703 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 13:19:45 -0300 Subject: [PATCH 011/110] crypto: one default per family and target, by a stated reason (design D32) Each family's default backend is chosen by WEBCPP_TARGET_* alone, whatever the program links, for the reason doc/tables/crypto.json gives (the owner's answers Q1 to Q4). generate.py writes detail/defaults.hpp from families[].default: default_backend_of with one specialisation per family that has a default, default_backend_t, and default_backend, AES-GCM's. AES-GCM's default is OpenSSL natively and BearSSL on WebAssembly; secp256k1's is libsecp256k1; the AES block cipher has none. config.hpp no longer chooses a default: WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL and _OPENSSL stop the build with the type to write (Q3). aes256_gcm.hpp includes its default's header only when it is linked; the family's primary engine, defined in gcm.hpp and aes.hpp with an empty primary state, is the generated refusal, which for the default not linked names the Jamfile line that links it and the type that names another backend. The refusal of an unknown backend now fires for an unknown type alone, and a one-target block opens with #ifdef. The default tests assert the fixed defaults with every backend linked, none, each alone and the plan's retired defines; default_selected and default_openssl_wasm become message tests of Q3's text, default_bearssl natively becomes gcm_default_openssl_not_linked, each with its MSVC case; two_defaults, no_backend_native, MSVC no_backend and default_two_files (its detect_mismatch) are gone. The examples that link BearSSL alone name it in the type. --- doc/aead.adoc | 16 +- doc/backends.adoc | 27 ++- doc/block.adoc | 6 +- doc/changelog.adoc | 2 +- doc/generated/backends-aes_block.adoc | 26 +- doc/generated/backends-gcm.adoc | 26 +- doc/generated/defaults.adoc | 53 +--- doc/generated/jamfiles.adoc | 14 +- doc/generated/messages.adoc | 86 ++++--- doc/generated/use-cases.adoc | 8 +- doc/jamfile.adoc | 41 ++-- doc/llms.txt | 21 +- doc/tables/crypto.json | 50 ++-- doc/tables/generate.py | 228 ++++++++++++++---- doc/tables/generate_test.py | 134 ++++++++-- doc/testing.adoc | 5 +- example/ecdh_session.cpp | 12 +- example/failure_reasons.cpp | 8 +- example/store_token.cpp | 8 +- example/wallet_key.cpp | 9 +- include/webcpp/crypto.hpp | 14 +- include/webcpp/crypto/backends/bearssl.hpp | 8 +- include/webcpp/crypto/ciphers/aes.hpp | 47 ++++ include/webcpp/crypto/ciphers/aes256_gcm.hpp | 30 +-- include/webcpp/crypto/ciphers/gcm.hpp | 64 +++++ include/webcpp/crypto/config.hpp | 72 +----- include/webcpp/crypto/curves/secp256k1.hpp | 15 +- include/webcpp/crypto/detail/capabilities.hpp | 89 +++++-- include/webcpp/crypto/detail/defaults.hpp | 83 +++++++ include/webcpp/crypto/detail/engines.hpp | 10 +- test/Jamfile | 106 ++++---- test/crypto_openssl_alone_test.cpp | 8 +- test/default_backend_test.cpp | 61 +++-- test/default_bearssl_test.cpp | 3 +- test/default_both_test.cpp | 3 +- test/default_both_wasm_test.cpp | 2 +- test/default_openssl_wasm_test.cpp | 20 -- test/default_selected_test.cpp | 20 -- test/default_selection_test.cpp | 17 +- test/messages/Jamfile | 5 +- test/messages/bearssl_not_linked/Jamfile | 3 +- .../bearssl_not_linked/bearssl_not_linked.cpp | 11 +- .../Jamfile | 5 +- .../default_openssl_wasm.cpp | 18 ++ test/messages/default_selected/Jamfile | 12 + .../default_selected/default_selected.cpp | 18 ++ .../Jamfile | 3 +- .../gcm_default_openssl_not_linked.cpp | 23 ++ .../no_backend_native/no_backend_native.cpp | 17 -- .../no_backend_wasm/no_backend_wasm.cpp | 16 +- test/messages/openssl_not_linked/Jamfile | 3 +- .../openssl_not_linked/openssl_not_linked.cpp | 9 +- test/messages/openssl_on_wasi/Jamfile | 5 +- .../openssl_on_wasi/openssl_on_wasi.cpp | 20 +- .../openssl_only_on_wasi.cpp | 17 +- test/messages/two_defaults/two_defaults.cpp | 17 -- test/msvc/Jamfile | 6 +- test/msvc/bearssl_not_linked/Jamfile | 2 +- test/msvc/bearssl_not_linked/app.cpp | 2 +- .../Jamfile | 4 +- test/msvc/default_openssl_wasm/app.cpp | 14 ++ .../{no_backend => default_selected}/Jamfile | 4 +- .../app.cpp | 6 +- test/msvc/default_two_files/main.cpp | 24 -- test/msvc/default_two_files/with.cpp | 22 -- .../Jamfile | 4 +- .../gcm_default_openssl_not_linked/app.cpp | 19 ++ test/msvc/no_backend/app.cpp | 14 -- test/msvc/openssl_not_linked/Jamfile | 2 +- test/msvc/openssl_not_linked/app.cpp | 2 +- 70 files changed, 1080 insertions(+), 699 deletions(-) create mode 100644 include/webcpp/crypto/detail/defaults.hpp delete mode 100644 test/default_openssl_wasm_test.cpp delete mode 100644 test/default_selected_test.cpp rename test/messages/{two_defaults => default_openssl_wasm}/Jamfile (61%) create mode 100644 test/messages/default_openssl_wasm/default_openssl_wasm.cpp create mode 100644 test/messages/default_selected/Jamfile create mode 100644 test/messages/default_selected/default_selected.cpp rename test/messages/{no_backend_native => gcm_default_openssl_not_linked}/Jamfile (65%) create mode 100644 test/messages/gcm_default_openssl_not_linked/gcm_default_openssl_not_linked.cpp delete mode 100644 test/messages/no_backend_native/no_backend_native.cpp delete mode 100644 test/messages/two_defaults/two_defaults.cpp rename test/msvc/{two_defaults => default_openssl_wasm}/Jamfile (56%) create mode 100644 test/msvc/default_openssl_wasm/app.cpp rename test/msvc/{no_backend => default_selected}/Jamfile (62%) rename test/msvc/{two_defaults => default_selected}/app.cpp (51%) delete mode 100644 test/msvc/default_two_files/main.cpp delete mode 100644 test/msvc/default_two_files/with.cpp rename test/msvc/{default_two_files => gcm_default_openssl_not_linked}/Jamfile (75%) create mode 100644 test/msvc/gcm_default_openssl_not_linked/app.cpp delete mode 100644 test/msvc/no_backend/app.cpp diff --git a/doc/aead.adoc b/doc/aead.adoc index fc8746e4..ee5010b4 100644 --- a/doc/aead.adoc +++ b/doc/aead.adoc @@ -25,7 +25,8 @@ and the AEAD of browsers' WebCrypto `gcm`, in ``, is AES-GCM with the key size of `Cipher`, on the backend of `Cipher`, which must export GCM over its own AES: BearSSL or OpenSSL. `aes128_gcm` and `aes256_gcm`, in -``, name it on the default backend. It is +``, name it on the default backend, +OpenSSL natively and BearSSL on WebAssembly. It is made with `make(key_bytes)`, and works in place: * `seal(iv_bytes, additional_data_bytes, data_bytes)` encrypts `data_bytes` @@ -57,8 +58,9 @@ include::{examples}/store_token.cpp[tag=open,indent=0] include::{examples}/store_token.expected[] ---- -The same, with the backend named rather than the default: AES-256-GCM on -BearSSL against the GCM specification's test case 14. +The examples name BearSSL in the type, `aead_type`, so that one Jamfile line +serves every target. The whole of one: AES-256-GCM on BearSSL against the GCM +specification's test case 14. [source,cpp] ---- @@ -145,15 +147,15 @@ summed over `update`, or additional data longer than 2^61^ - 1 bytes (NIST SP [#crypto-gcm-arm] ==== A warning for ARM servers -Natively without OpenSSL, the default is BearSSL, which has AES-NI code for x86 -but none for ARM's AES instructions +Natively the default is OpenSSL. A program that names BearSSL there gets +AES-NI code for x86 but none for ARM's AES instructions (link:https://www.bearssl.org/support.html[BearSSL]): on an ARM server it runs its portable constant-time code, while OpenSSL's assembly uses ARMv8's AES and polynomial multiplication instructions (link:https://github.com/openssl/openssl/tree/master/crypto/aes/asm[OpenSSL's AES]; link:https://github.com/openssl/openssl/tree/master/crypto/modes/asm[OpenSSL's GHASH]). -How much slower is not measured yet. A server on ARM names -`/webcpp/crypto//openssl` (<>). +How much slower is not measured yet. A server on ARM keeps the default and +links `/webcpp/crypto//openssl` (<>). [#crypto-gcm-incremental] ==== Encrypting what does not fit in memory diff --git a/doc/backends.adoc b/doc/backends.adoc index 208a76d0..37009fb5 100644 --- a/doc/backends.adoc +++ b/doc/backends.adoc @@ -32,17 +32,22 @@ include::generated/matrix.adoc[] [#crypto-backends-defaults] === The default backend per target -The rule, and its reasons, are in the table: on WebAssembly BearSSL, the only -AEAD backend on Emscripten and constant time by design where OpenSSL is built -without assembly; natively OpenSSL when it is linked, whose assembly uses the -CPU's AES instructions on x86-64 and ARMv8 with Clang and GCC. On MSVC the -rule is the same, but OpenSSL is built without assembly there: the default is -then table-based and not constant time, and a program that timing attacks -threaten defines `WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL`. Sizes and speeds are -not measured yet. -The table gives the default of each family: AES-GCM's applies to `aes128_gcm`, -`aes256_gcm` and `aes256<>`; the AES block cipher has none of its own, and -libsecp256k1 is the only backend of secp256k1. +Each family has one default backend per target, for the reason the table +gives, whatever the program links; no define changes it, and every other +backend is reached by naming it in the type. AES-GCM's is OpenSSL natively, +whose assembly uses the CPU's AES instructions on x86-64 and ARMv8 with Clang +and GCC, and BearSSL on WebAssembly, the only AEAD backend on Emscripten and +constant time by design where OpenSSL is built without assembly. On MSVC +OpenSSL is built without assembly too: the default is then table-based and not +constant time, and a program that timing attacks threaten names +`ciphers::gcm>`. A program that uses a +default it does not link stops where it calls it, with the Jamfile line that +links it and the type that names another backend +(<>). +AES-GCM's default applies to `aes128_gcm`, `aes256_gcm` and `aes256<>`; the +AES block cipher has none of its own, and libsecp256k1 is the only backend of +secp256k1. In {cpp}, `default_backend_t` names a family's default on +the target being compiled, and `default_backend` AES-GCM's. include::generated/defaults.adoc[] diff --git a/doc/block.adoc b/doc/block.adoc index 5ec3fbc7..d4911726 100644 --- a/doc/block.adoc +++ b/doc/block.adoc @@ -29,9 +29,9 @@ BearSSL exports AES only inside its modes, with no single-block class, so `aes256` is a complete type, which `gcm` needs to name its cipher, but its `make` does not compile, and a `static_assert` says which backends to use (<>). `aes256<>` is the cipher of -`aes256_gcm`, so it follows the default backend, BearSSL on WebAssembly and -natively without OpenSSL, where `aes256<>::make` does not compile either: a -program that wants the block cipher there names +`aes256_gcm`, so it follows AES-GCM's default backend, OpenSSL natively and +BearSSL on WebAssembly, where `aes256<>::make` does not compile: a program that +wants the block cipher there names `aes256` and includes ``. ctaes is a constant-time bitsliced AES, the one Bitcoin Core ships (link:https://github.com/bitcoin/bitcoin/tree/master/src/crypto/ctaes[ctaes]): diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 2eba8c06..135d2c78 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -18,7 +18,7 @@ of every version are on webcpp's index page. // tag::unreleased[] * Added crypto, primitives over C backends: ciphers, curves and randomness, with errors of fixed values in webcpp.crypto, every result `+[[nodiscard]]+`. * Added equal, random_device, ciphers::aes128, aes192 and aes256, the AES block cipher, and ciphers::gcm, AES-GCM in place with an incremental seal whose failed open zeroes the data. -* Added the default backend, ciphers::aes128_gcm and aes256_gcm, and refusals of conflicting or missing backends that name the Jamfile line to add. +* Added default_backend_t, one default backend per family and target whatever is linked, ciphers::aes128_gcm and aes256_gcm, and refusals of missing backends naming the Jamfile line and another backend's type. * Added backends::bearssl (AES-GCM allocating nothing, no block cipher), backends::openssl through /webcpp/crypto//openssl on native and WASI (allocating at make only), and backends::ctaes (block cipher alone). * Added WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE: OpenSSL's allocations in the program's resource, refused on WebAssembly (WASI included) and without OpenSSL: openssl_memory_resource, install_memory_functions, memory_functions_refused, memory_functions_not_installed. * Added curves::secp256k1: key pairs, BIP340 and ECDSA signatures, ECDH, strict DER, low-S and the x-only tweak. diff --git a/doc/generated/backends-aes_block.adoc b/doc/generated/backends-aes_block.adoc index 68a78568..24e25341 100644 --- a/doc/generated/backends-aes_block.adoc +++ b/doc/generated/backends-aes_block.adoc @@ -29,37 +29,21 @@ The backends of `+ciphers::aes128+`, `+aes192+`, `+aes256+`, from the test progr |native, wasip2, wasip3, emscripten (tested by `+aes_ctaes+`, `+agreement_aes+`) |=== -`+aes256<>+` names the default backend; where that is BearSSL, its `+make+` does not compile, and the program names `+aes256+`. The default per target and what the program links, as <> gives it with its reasons and tests: +`+aes256<>+` names the default backend; where that is BearSSL, its `+make+` does not compile, and the program names `+aes256+`. The default per target, whatever the program links, as <> gives it with its reasons and tests: -[.wrap-names,cols="2,4,2",options="header"] +[cols="1,1",options="header"] |=== -|Target |Linked |Default - -|emscripten -|BearSSL -|BearSSL - -|wasip2, wasip3 -|BearSSL, with or without OpenSSL -|BearSSL - -|wasip2, wasip3 -|BearSSL and OpenSSL, with `+WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL+` -|OpenSSL +|Target |Default |native, Clang and GCC -|OpenSSL, with or without BearSSL |OpenSSL |native, MSVC -|OpenSSL, with or without BearSSL |OpenSSL -|native -|BearSSL and OpenSSL, with `+WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL+` +|wasip2, wasip3 |BearSSL -|native -|BearSSL alone +|emscripten |BearSSL |=== diff --git a/doc/generated/backends-gcm.adoc b/doc/generated/backends-gcm.adoc index d529e895..1db54a1c 100644 --- a/doc/generated/backends-gcm.adoc +++ b/doc/generated/backends-gcm.adoc @@ -29,37 +29,21 @@ The backends of `+ciphers::gcm+`, `+aes128_gcm+`, `+aes256_gcm+`, from the test |refused at compile time (`+gcm_on_ctaes+`) |=== -`+aes128_gcm+` and `+aes256_gcm+` name the default backend. The default per target and what the program links, as <> gives it with its reasons and tests: +`+aes128_gcm+` and `+aes256_gcm+` name the default backend. The default per target, whatever the program links, as <> gives it with its reasons and tests: -[.wrap-names,cols="2,4,2",options="header"] +[cols="1,1",options="header"] |=== -|Target |Linked |Default - -|emscripten -|BearSSL -|BearSSL - -|wasip2, wasip3 -|BearSSL, with or without OpenSSL -|BearSSL - -|wasip2, wasip3 -|BearSSL and OpenSSL, with `+WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL+` -|OpenSSL +|Target |Default |native, Clang and GCC -|OpenSSL, with or without BearSSL |OpenSSL |native, MSVC -|OpenSSL, with or without BearSSL |OpenSSL -|native -|BearSSL and OpenSSL, with `+WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL+` +|wasip2, wasip3 |BearSSL -|native -|BearSSL alone +|emscripten |BearSSL |=== diff --git a/doc/generated/defaults.adoc b/doc/generated/defaults.adoc index e22bcd1a..c62fcb88 100644 --- a/doc/generated/defaults.adoc +++ b/doc/generated/defaults.adoc @@ -7,70 +7,43 @@ // 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. -[.wrap-names,cols="2,2,4,2,5,3",options="header"] +[cols="2,2,2,6,3",options="header"] |=== -|Family |Target |Linked |Default |Why |Tested by - -|AES-GCM -|emscripten -|BearSSL -|BearSSL -|the only AEAD backend there: webcpp does not build OpenSSL for Emscripten; size and speed not measured yet -|`+default_bearssl+` - -|AES-GCM -|wasip2, wasip3 -|BearSSL, with or without OpenSSL -|BearSSL -|constant time by design (link:https://www.bearssl.org/constanttime.html[BearSSL, constant-time crypto]), where OpenSSL is built no-asm and its AES and GHASH are table-based (link:https://github.com/openssl/openssl/blob/master/INSTALL.md[OpenSSL's INSTALL.md, no-asm]) -|`+default_bearssl+`, `+default_both_wasm+` - -|AES-GCM -|wasip2, wasip3 -|BearSSL and OpenSSL, with `+WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL+` -|OpenSSL -|the program's choice -|`+default_openssl_wasm+` +|Family |Target |Default |Why |Tested by |AES-GCM |native, Clang and GCC -|OpenSSL, with or without BearSSL |OpenSSL -|OpenSSL's assembly uses the CPU's AES and carry-less multiplication instructions on x86-64 and ARMv8 (link:https://github.com/openssl/openssl/tree/master/crypto/aes/asm[OpenSSL's AES assembly for ARMv8 and x86-64]; link:https://github.com/openssl/openssl/tree/master/crypto/modes/asm[OpenSSL's GHASH and AES-GCM assembly]); BearSSL has them on x86 only (link:https://www.bearssl.org/support.html[BearSSL, the AES implementations it selects]); speed not measured yet -|`+default_both+` +|OpenSSL's assembly uses the CPU's AES and carry-less multiplication instructions on x86-64 and ARMv8 (link:https://github.com/openssl/openssl/tree/master/crypto/aes/asm[OpenSSL's AES assembly for ARMv8 and x86-64]; link:https://github.com/openssl/openssl/tree/master/crypto/modes/asm[OpenSSL's GHASH and AES-GCM assembly]); BearSSL has them on x86 only (link:https://www.bearssl.org/support.html[BearSSL, the AES implementations it selects]). OpenSSL whatever the program links: a program that links BearSSL alone names `gcm>` +|`+default_both+`, `+default_backend_all_linked+` |AES-GCM |native, MSVC -|OpenSSL, with or without BearSSL |OpenSSL -|the same rule as with Clang and GCC, but here OpenSSL is built no-asm: table-based AES and 4-bit GHASH, no AES-NI, not constant time (link:https://github.com/openssl/openssl/blob/master/INSTALL.md[OpenSSL's INSTALL.md, no-asm]); where timing attacks matter, link BearSSL and define `WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL` +|the same rule as with Clang and GCC, but here OpenSSL is built no-asm: table-based AES and 4-bit GHASH, no AES-NI, not constant time (link:https://github.com/openssl/openssl/blob/master/INSTALL.md[OpenSSL's INSTALL.md, no-asm]); where timing attacks matter, link BearSSL and name `gcm>` |`+default_both+` |AES-GCM -|native -|BearSSL and OpenSSL, with `+WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL+` +|wasip2, wasip3 |BearSSL -|the program's choice, constant time by design (link:https://www.bearssl.org/constanttime.html[BearSSL, constant-time crypto]): on MSVC, where OpenSSL is built no-asm, the choice for code that timing attacks threaten -|`+default_selected+` +|constant time by design (link:https://www.bearssl.org/constanttime.html[BearSSL, constant-time crypto]), where OpenSSL is built no-asm and its AES and GHASH are table-based (link:https://github.com/openssl/openssl/blob/master/INSTALL.md[OpenSSL's INSTALL.md, no-asm]). BearSSL whatever the program links: a program that links OpenSSL alone names `gcm>` +|`+default_bearssl+`, `+default_both_wasm+`, `+default_backend_all_linked+` |AES-GCM -|native -|BearSSL alone +|emscripten |BearSSL -|the backend that is linked -|`+default_bearssl+` +|the only AEAD backend there: webcpp does not build OpenSSL for Emscripten +|`+default_bearssl+`, `+default_backend_all_linked_emscripten+` |AES block cipher |native, wasip2, wasip3, emscripten -|any backend |none |a raw block cipher is a building block a program chooses deliberately, naming its backend; `aes256<>` takes AES-GCM's default as its argument, and its `make` does not compile where that is BearSSL -|`+default_selection_bearssl+` +|`+default_backend_none_linked+`, `+default_selection_bearssl+` |secp256k1 |native, wasip2, wasip3, emscripten |libsecp256k1 -|libsecp256k1 |the only backend (link:https://github.com/bitcoin-core/secp256k1#readme[libsecp256k1's README]) -|`+secp256k1+` +|`+secp256k1+`, `+default_backend_none_linked+` |=== diff --git a/doc/generated/jamfiles.adoc b/doc/generated/jamfiles.adoc index 5e406cf8..11fd9b5d 100644 --- a/doc/generated/jamfiles.adoc +++ b/doc/generated/jamfiles.adoc @@ -23,23 +23,23 @@ It prints: include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/block/block.outcome[tag=output] ---- -`+both_bearssl_default+`:: Both backends linked, BearSSL chosen as the default with a define; the same program. +`+both_bearssl_named+`:: Both backends linked, and BearSSL named in the type where the default is OpenSSL. + Its Jamfile, built and run on native, wasip2, wasip3: + [listing] ---- -include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/both_bearssl_default/Jamfile[tag=jamfile] +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/both_bearssl_named/Jamfile[tag=jamfile] ---- + It prints: + [listing] ---- -include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/both_bearssl_default/both_bearssl_default.outcome[tag=output] +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/both_bearssl_named/both_bearssl_named.outcome[tag=output] ---- -`+encrypt_and_sign+`:: Two backends in one program: AES-256-GCM on the default backend and a BIP 340 signature. +`+encrypt_and_sign+`:: Two backends in one program: AES-256-GCM on BearSSL, named in the type so that one Jamfile serves every target, and a BIP 340 signature. + Its Jamfile, built and run on native, wasip2, wasip3, emscripten: + @@ -87,7 +87,7 @@ It prints: include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/openssl_linked/openssl_linked.outcome[tag=output] ---- -`+server+`:: A server, natively: the same program with OpenSSL, the default natively when linked. +`+server+`:: A server, natively: the same program with OpenSSL, the default natively. + Its Jamfile, built and run on native: + @@ -135,9 +135,9 @@ It prints: include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/sign_small/sign_small.outcome[tag=output] ---- -`+web+`:: A web application: AES-256-GCM on BearSSL, the default on every target. +`+web+`:: A web application: AES-256-GCM on BearSSL, the default on WebAssembly. + -Its Jamfile, built and run on native, wasip2, wasip3, emscripten: +Its Jamfile, built and run on wasip2, wasip3, emscripten: + [listing] ---- diff --git a/doc/generated/messages.adoc b/doc/generated/messages.adoc index 9b2f7da4..4a885b2a 100644 --- a/doc/generated/messages.adoc +++ b/doc/generated/messages.adoc @@ -21,9 +21,9 @@ The fix: Name `+ciphers::aes256+`, include `+WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL. (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)+` +|`+webcpp::crypto: the backend BearSSL is used and not linked. In the program's Jamfile, add /third_party//bearssl beside /webcpp/crypto//crypto. (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)+` -The fix: Add `+/third_party//bearssl+`, or, with OpenSSL linked, define `+WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL+`. +The fix: Add `+/third_party//bearssl+`. |`+ctaes_not_linked+` |native, wasip2, wasip3 @@ -31,21 +31,33 @@ The fix: Add `+/third_party//bearssl+`, or, with OpenSSL linked, define `+WEBCPP The fix: Add `+/third_party//ctaes+`. -|`+gcm_on_ctaes+` +|`+default_openssl_wasm+` |native, wasip2, wasip3 -|`+webcpp::crypto: ciphers::gcm>: ctaes exports the AES block cipher alone, and webcpp builds no GCM on another library's AES. Use a backend that exports GCM: ciphers::gcm> or ciphers::gcm>.+` +|`+webcpp::crypto: WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL no longer chooses a default. Write the backend in the type where the program wants it, as in ciphers::gcm>.+` + +The fix: Remove the define, and name `+gcm>+` where the program wants OpenSSL. + +|`+default_selected+` +|native, wasip2, wasip3 +|`+webcpp::crypto: WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL no longer chooses a default. Write the backend in the type where the program wants it, as in ciphers::gcm>.+` -The fix: Use `+aes256_gcm+` with BearSSL or OpenSSL linked. +The fix: Remove the define, and name `+gcm>+` where the program wants BearSSL. -|`+no_backend_native+` +|`+gcm_default_openssl_not_linked+` |native -|`+webcpp::crypto: no backend is linked. In the program's Jamfile, add /webcpp/crypto//openssl (OpenSSL built from source) or /third_party//bearssl (built from source) beside /webcpp/crypto//crypto, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//openssl ; (without b2: define WEBCPP_CRYPTO_HAS_OPENSSL=1 and link libcrypto, or define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)+` +|`+webcpp::crypto: AES-GCM's default backend on this target is OpenSSL, which is not linked. Add /webcpp/crypto//openssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//openssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).+` -The fix: Add `+/webcpp/crypto//openssl+` or `+/third_party//bearssl+` to the program's sources. +The fix: Natively the default is OpenSSL: add `+/webcpp/crypto//openssl+`, or name BearSSL in the type, as in `+gcm>+`. + +|`+gcm_on_ctaes+` +|native, wasip2, wasip3 +|`+webcpp::crypto: ciphers::gcm>: ctaes exports the AES block cipher alone, and webcpp builds no GCM on another library's AES. Use a backend that exports GCM: ciphers::gcm> or ciphers::gcm>.+` + +The fix: Name `+gcm>+` or `+gcm>+`, or use `+aes256_gcm+` with its default linked. |`+no_backend_wasm+` |wasip2, wasip3 -|`+webcpp::crypto: no backend is linked. On WebAssembly the backend is BearSSL: in the program's Jamfile, add /third_party//bearssl beside /webcpp/crypto//crypto, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ; (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)+` +|`+webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked. Add /third_party//bearssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).+` The fix: Add `+/third_party//bearssl+` to the program's sources. @@ -75,9 +87,9 @@ The fix: Name `+/webcpp/crypto//openssl+`, which builds OpenSSL 3.5.9; without b |`+openssl_only_on_wasi+` |wasip2, wasip3 -|`+webcpp::crypto: the backend BearSSL is used and not linked. In the program's Jamfile, add /third_party//bearssl beside /webcpp/crypto//crypto, or, with /webcpp/crypto//openssl linked, select OpenSSL with WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL. (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)+` +|`+webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked. Add /third_party//bearssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).+` -The fix: On WASI the default is BearSSL: add `+/third_party//bearssl+`, or define `+WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL+`. +The fix: On WASI the default is BearSSL: add `+/third_party//bearssl+`, or name OpenSSL in the type, as in `+gcm>+`. |`+secp256k1_not_linked+` |native, wasip2 @@ -96,12 +108,6 @@ The fix: Name `+backends::secp256k1+`, or leave the backend out: `+curves::secp2 |`+webcpp::crypto: the backend libsodium is used and not linked. In the program's Jamfile, add /third_party//sodium beside /webcpp/crypto//crypto, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)+` The fix: Add `+/third_party//sodium+`. - -|`+two_defaults+` -|native -|`+webcpp::crypto: both WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL and WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL are defined. Keep one.+` - -The fix: Keep one of the two defines. |=== At build and link time, from the fixtures of the user's Jamfiles, each built on a scratch superproject: the texts the build's output contains, per target and linker, as each fixture checks them. @@ -330,7 +336,21 @@ On each target, the build's output contains: ** `+undefined symbol: webcpp_crypto_bearssl_7bea48e_getentropy__add_third_party_bearssl_to_your_link+` ** `pass:[em++: error:]` -`+default_openssl_on_emscripten+`:: OpenSSL selected as the default in a build for Emscripten. The fix: Remove the define, or make it `+WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL+`. +`+default_bearssl_on_emscripten+`:: Version 0.1's define that chose BearSSL as the default, in a build for Emscripten. The fix: Remove the define: on Emscripten the default is BearSSL. ++ +Its Jamfile: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/default_bearssl_on_emscripten/Jamfile[tag=jamfile] +---- ++ +On each target, the build's output contains: ++ +* emscripten: +** `+webcpp::crypto: WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL no longer chooses a default. Write the backend in the type where the program wants it, as in ciphers::gcm>.+` + +`+default_openssl_on_emscripten+`:: Version 0.1's define that chose OpenSSL as the default, in a build for Emscripten. The fix: Remove the define: on Emscripten the default is BearSSL, and OpenSSL is not built. + Its Jamfile: + @@ -342,7 +362,7 @@ include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/default_openssl_on_em On each target, the build's output contains: + * emscripten: -** `+webcpp::crypto: WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL selects OpenSSL, which is not built for Emscripten. Remove that define, or make it WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL.+` +** `+webcpp::crypto: WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL no longer chooses a default. Write the backend in the type where the program wants it, as in ciphers::gcm>.+` `+has_openssl_on_emscripten+`:: OpenSSL declared linked, without b2, in a build for Emscripten. The fix: Replace `+/webcpp/crypto//openssl+` with `+/third_party//bearssl+`. + @@ -404,7 +424,7 @@ include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/no_backend_on_emscrip On each target, the build's output contains: + * emscripten: -** `+webcpp::crypto: no backend is linked. On WebAssembly the backend is BearSSL: in the program's Jamfile, add /third_party//bearssl beside /webcpp/crypto//crypto, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ; (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)+` +** `+webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked, and the one backend that has it there. Add /third_party//bearssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ;+` `+openssl_memory_on_emscripten+`:: The memory option of the OpenSSL backend set in a build for Emscripten. The fix: Remove `+WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE+` from the WebAssembly build: give that build a project of its own, without the define and OpenSSL, naming `+/third_party//bearssl+`. On WebAssembly the backend is BearSSL, which allocates nothing. + @@ -460,7 +480,7 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |`+bearssl_not_linked+` |the compile -|Add `+/third_party//bearssl+`, or, with OpenSSL linked, define `+WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL+`. +|Add `+/third_party//bearssl+`. |`+canary_ctaes_missing+` |the link @@ -502,13 +522,21 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |Add `+/third_party//ctaes+`. -|`+default_two_files+` -|the link -|Give `+WEBCPP_CRYPTO_DEFAULT_BACKEND_*+` in the requirements of the program's project, so that every file gets it. +|`+default_openssl_wasm+` +|the compile +|Remove the define, and name `+gcm>+` where the program wants OpenSSL. + +|`+default_selected+` +|the compile +|Remove the define, and name `+gcm>+` where the program wants BearSSL. + +|`+gcm_default_openssl_not_linked+` +|the compile +|Natively the default is OpenSSL: add `+/webcpp/crypto//openssl+`, or name BearSSL in the type, as in `+gcm>+`. |`+gcm_on_ctaes+` |the compile -|Use `+aes256_gcm+` with BearSSL or OpenSSL linked. +|Name `+gcm>+` or `+gcm>+`, or use `+aes256_gcm+` with its default linked. |`+memory_missing_definition_install+` |the link @@ -522,10 +550,6 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the link |Give the define in the requirements of the program's project, with OpenSSL beside it, `+project app : requirements WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE /webcpp/crypto//openssl ;+`, so that every target of the program gets both. -|`+no_backend+` -|the compile -|As `+no_backend_native+`. - |`+openssl_memory_not_linked+` |the compile |A target has the define and not OpenSSL: put `+/webcpp/crypto//openssl+` in the same project requirements as the define, or remove the define. @@ -549,10 +573,6 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |`+sodium_not_linked+` |the compile |Add `+/third_party//sodium+`. - -|`+two_defaults+` -|the compile -|Keep one of the two defines. |=== Elsewhere than MSVC these mistakes build, and nothing stops them; the fixtures record it: diff --git a/doc/generated/use-cases.adoc b/doc/generated/use-cases.adoc index 0878b2da..96069c87 100644 --- a/doc/generated/use-cases.adoc +++ b/doc/generated/use-cases.adoc @@ -30,15 +30,15 @@ |<> |Encrypt a database field, a cookie or a token at rest -|In `+ciphers+`: `+aes256_gcm+` -|default: BearSSL on WebAssembly, OpenSSL natively when linked +|In `+ciphers+`: `+gcm>+`, or `+aes256_gcm+` on the default +|BearSSL, named: one Jamfile line on every target; the default is OpenSSL natively, BearSSL on WebAssembly |`+/webcpp/crypto//crypto+` + `+/third_party//bearssl+` |<> |Encrypt a large file or a stream -|In `+ciphers+`: `+aes256_gcm+`: records, or `+begin_seal+`, `+update+` and `+result+` -|default +|In `+ciphers+`: `+gcm>+`: records, or `+begin_seal+`, `+update+` and `+result+` +|BearSSL, named |`+/webcpp/crypto//crypto+` + `+/third_party//bearssl+` |<> diff --git a/doc/jamfile.adoc b/doc/jamfile.adoc index 31a2f83b..0fda5044 100644 --- a/doc/jamfile.adoc +++ b/doc/jamfile.adoc @@ -29,24 +29,27 @@ In {cpp}, a program names a backend by including its header, `.hpp>`, and using its tag type, `backends::`, as a template argument: `ciphers::gcm>`. The default backend needs no -include of its own: `` brings it. +include of its own: `` brings it when it is +linked. [#crypto-jamfile-default] === The default backend, and choosing another -`aes128_gcm`, `aes256_gcm` and `aes256<>` name the default backend: BearSSL on -WebAssembly; natively OpenSSL when it is linked, else BearSSL. A program -chooses with a define in its Jamfile's requirements, -`WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL` or -`WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL`, or names the backend at any -use. <> gives every combination with the test that -fixes it. +`aes128_gcm`, `aes256_gcm` and `aes256<>` name AES-GCM's default backend: +natively OpenSSL, on WebAssembly BearSSL, whatever else the program links +(<>). A program that wants another backend names it +in the type, as `ciphers::gcm>`, and links +it; no define chooses a default. A native program that links BearSSL alone and +uses `aes256_gcm` stops where it calls it, with the line that links OpenSSL +and the type that names BearSSL. Version 0.1's +`WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL` and +`WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL` stop the build with the type to write +(<>). The source-built OpenSSL is compiled without assembly (`no-asm`) on MSVC, wasip2 and wasip3: its AES is table-based and its GHASH 4-bit, neither constant -time, and there is no AES-NI. A program for which timing attacks matter there -defines `WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL`, or names -`ciphers::gcm>`. +time, and there is no AES-NI. A program for which timing attacks matter on +MSVC names `ciphers::gcm>`. [#crypto-jamfile-memory] === OpenSSL's memory option @@ -87,14 +90,14 @@ include::generated/jamfiles.adoc[] A user builds a case from its directory with `b2` natively, `b2 toolset=emscripten` for the browser, and `b2 toolset=clang-wasip2` or `b2 toolset=clang-wasip3` for WASI, and runs the program as each target runs one: -`./app`, `node app.js`, or a WASI runtime such as wasmtime. The cases `web`, -`server` and `both_bearssl_default` are one program, byte for byte (the test -checks the copies), whose output names the backend that ran: BearSSL wherever -it is the default, OpenSSL natively when the program names it, and BearSSL -again when a define chooses it with both linked. On WASI the default is BearSSL -even when OpenSSL is linked (<>), so `server` is a -native case; a WASI program that wants OpenSSL names the backend in the type, -as `openssl_linked` does, or defines `WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL`. +`./app`, `node app.js`, or a WASI runtime such as wasmtime. The cases `web` and +`server` are one program, byte for byte (the test checks the copy), whose +output names the backend that ran: BearSSL, the default on WebAssembly, and +OpenSSL, the default natively. `both_bearssl_named` links both and names +BearSSL in the type where OpenSSL is the default. On WASI the default is +BearSSL even when OpenSSL is linked (<>), so `server` +is a native case; a WASI program that wants OpenSSL names the backend in the +type, as `openssl_linked` does. The examples of this page are built the same way: `example/Jamfile` names `/webcpp/crypto//crypto` in its project's requirements, and each example the diff --git a/doc/llms.txt b/doc/llms.txt index 321083ce..3ff1dbf8 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -58,15 +58,12 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp ## Default backend per family -- AES-GCM, emscripten, linked BearSSL: BearSSL; the only AEAD backend there: webcpp does not build OpenSSL for Emscripten; size and speed not measured yet. -- AES-GCM, wasip2, wasip3, linked BearSSL, with or without OpenSSL: BearSSL; constant time by design ([BearSSL, constant-time crypto](https://www.bearssl.org/constanttime.html)), where OpenSSL is built no-asm and its AES and GHASH are table-based ([OpenSSL's INSTALL.md, no-asm](https://github.com/openssl/openssl/blob/master/INSTALL.md)). -- AES-GCM, wasip2, wasip3, linked BearSSL and OpenSSL, with `WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL`: OpenSSL; the program's choice. -- AES-GCM, native, Clang and GCC, linked OpenSSL, with or without BearSSL: OpenSSL; OpenSSL's assembly uses the CPU's AES and carry-less multiplication instructions on x86-64 and ARMv8 ([OpenSSL's AES assembly for ARMv8 and x86-64](https://github.com/openssl/openssl/tree/master/crypto/aes/asm); [OpenSSL's GHASH and AES-GCM assembly](https://github.com/openssl/openssl/tree/master/crypto/modes/asm)); BearSSL has them on x86 only ([BearSSL, the AES implementations it selects](https://www.bearssl.org/support.html)); speed not measured yet. -- AES-GCM, native, MSVC, linked OpenSSL, with or without BearSSL: OpenSSL; the same rule as with Clang and GCC, but here OpenSSL is built no-asm: table-based AES and 4-bit GHASH, no AES-NI, not constant time ([OpenSSL's INSTALL.md, no-asm](https://github.com/openssl/openssl/blob/master/INSTALL.md)); where timing attacks matter, link BearSSL and define `WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL`. -- AES-GCM, native, linked BearSSL and OpenSSL, with `WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL`: BearSSL; the program's choice, constant time by design ([BearSSL, constant-time crypto](https://www.bearssl.org/constanttime.html)): on MSVC, where OpenSSL is built no-asm, the choice for code that timing attacks threaten. -- AES-GCM, native, linked BearSSL alone: BearSSL; the backend that is linked. -- AES block cipher, native, wasip2, wasip3, emscripten, linked any backend: none; a raw block cipher is a building block a program chooses deliberately, naming its backend; `aes256<>` takes AES-GCM's default as its argument, and its `make` does not compile where that is BearSSL. -- secp256k1, native, wasip2, wasip3, emscripten, linked libsecp256k1: libsecp256k1; the only backend ([libsecp256k1's README](https://github.com/bitcoin-core/secp256k1#readme)). +- AES-GCM, native, Clang and GCC: OpenSSL; OpenSSL's assembly uses the CPU's AES and carry-less multiplication instructions on x86-64 and ARMv8 ([OpenSSL's AES assembly for ARMv8 and x86-64](https://github.com/openssl/openssl/tree/master/crypto/aes/asm); [OpenSSL's GHASH and AES-GCM assembly](https://github.com/openssl/openssl/tree/master/crypto/modes/asm)); BearSSL has them on x86 only ([BearSSL, the AES implementations it selects](https://www.bearssl.org/support.html)). OpenSSL whatever the program links: a program that links BearSSL alone names `gcm>`. +- AES-GCM, native, MSVC: OpenSSL; the same rule as with Clang and GCC, but here OpenSSL is built no-asm: table-based AES and 4-bit GHASH, no AES-NI, not constant time ([OpenSSL's INSTALL.md, no-asm](https://github.com/openssl/openssl/blob/master/INSTALL.md)); where timing attacks matter, link BearSSL and name `gcm>`. +- AES-GCM, wasip2, wasip3: BearSSL; constant time by design ([BearSSL, constant-time crypto](https://www.bearssl.org/constanttime.html)), where OpenSSL is built no-asm and its AES and GHASH are table-based ([OpenSSL's INSTALL.md, no-asm](https://github.com/openssl/openssl/blob/master/INSTALL.md)). BearSSL whatever the program links: a program that links OpenSSL alone names `gcm>`. +- AES-GCM, emscripten: BearSSL; the only AEAD backend there: webcpp does not build OpenSSL for Emscripten. +- AES block cipher, native, wasip2, wasip3, emscripten: none; a raw block cipher is a building block a program chooses deliberately, naming its backend; `aes256<>` takes AES-GCM's default as its argument, and its `make` does not compile where that is BearSSL. +- secp256k1, native, wasip2, wasip3, emscripten: libsecp256k1; the only backend ([libsecp256k1's README](https://github.com/bitcoin-core/secp256k1#readme)). ## Rules of use @@ -79,15 +76,15 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [Ethereum](https://webcpporg.github.io/libs/crypto/#crypto-curves): this version verifies Ethereum's ECDSA signatures with a known key but has no recoverable signature (no recovery id `v`, no public key recovery) and no uncompressed public key output, so it cannot sign Ethereum transactions or derive addresses. - [Compare secrets in constant time](https://webcpporg.github.io/libs/crypto/#crypto-equal): compare a tag, a MAC or a token with `equal`, never `==` or `memcmp` ([CWE-208, observable timing discrepancy](https://cwe.mitre.org/data/definitions/208.html)). - [Secrets come from random_device](https://webcpporg.github.io/libs/crypto/#crypto-entropy): keys, IVs and tokens are drawn from `random_device`, never `std::mt19937` or `rand` ([CWE-338, a weak generator used for security](https://cwe.mitre.org/data/definitions/338.html)). -- [The default on MSVC is not constant time](https://webcpporg.github.io/libs/crypto/#crypto-backends-defaults): natively with OpenSSL linked the default is OpenSSL, which MSVC builds no-asm, table-based ([OpenSSL's INSTALL.md, no-asm](https://github.com/openssl/openssl/blob/master/INSTALL.md)); where timing attacks matter, link BearSSL and define `WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL`. +- [The default on MSVC is not constant time](https://webcpporg.github.io/libs/crypto/#crypto-backends-defaults): natively the default is OpenSSL, which MSVC builds no-asm, table-based ([OpenSSL's INSTALL.md, no-asm](https://github.com/openssl/openssl/blob/master/INSTALL.md)); where timing attacks matter, link BearSSL and name `gcm>`. ## Choose by use case - [Generate a session token, a password-reset link or an API key](https://webcpporg.github.io/libs/crypto/#crypto-entropy): `random_device::fill` (webcpp::crypto); backend the system's generator; Jamfile /webcpp/crypto//crypto. Example: example/reset_token.cpp. - [Draw an unbiased number in a range, such as a six-digit code](https://webcpporg.github.io/libs/crypto/#crypto-entropy): `random_device` with `std::uniform_int_distribution` (webcpp::crypto); backend the system's generator; Jamfile /webcpp/crypto//crypto. Example: example/reset_token.cpp. - [Check a webhook's or an API's HMAC signature](https://webcpporg.github.io/libs/crypto/#crypto-equal): `equal`, with Boost.Hash2's `hmac` (webcpp::crypto); backend none; Jamfile /webcpp/crypto//crypto. Example: example/equal_hmac.cpp. -- [Encrypt a database field, a cookie or a token at rest](https://webcpporg.github.io/libs/crypto/#crypto-gcm): `aes256_gcm` (webcpp::crypto::ciphers); backend default: BearSSL on WebAssembly, OpenSSL natively when linked; Jamfile /webcpp/crypto//crypto /third_party//bearssl. Example: example/store_token.cpp. -- [Encrypt a large file or a stream](https://webcpporg.github.io/libs/crypto/#crypto-gcm-incremental): `aes256_gcm`: records, or `begin_seal`, `update` and `result` (webcpp::crypto::ciphers); backend default; Jamfile /webcpp/crypto//crypto /third_party//bearssl. Example: example/sealed_records.cpp. +- [Encrypt a database field, a cookie or a token at rest](https://webcpporg.github.io/libs/crypto/#crypto-gcm): `gcm>`, or `aes256_gcm` on the default (webcpp::crypto::ciphers); backend BearSSL, named: one Jamfile line on every target; the default is OpenSSL natively, BearSSL on WebAssembly; Jamfile /webcpp/crypto//crypto /third_party//bearssl. Example: example/store_token.cpp. +- [Encrypt a large file or a stream](https://webcpporg.github.io/libs/crypto/#crypto-gcm-incremental): `gcm>`: records, or `begin_seal`, `update` and `result` (webcpp::crypto::ciphers); backend BearSSL, named; Jamfile /webcpp/crypto//crypto /third_party//bearssl. Example: example/sealed_records.cpp. - [Tell a forged message from a malformed one](https://webcpporg.github.io/libs/crypto/#crypto-errors): `error` (webcpp::crypto); backend any; Jamfile /webcpp/crypto//crypto. Example: example/failure_reasons.cpp. - [Turn a sequential id into an opaque reference](https://webcpporg.github.io/libs/crypto/#crypto-block): `aes256` (webcpp::crypto::ciphers); backend ctaes, or OpenSSL natively and on WASI; Jamfile /webcpp/crypto//crypto /third_party//ctaes. Example: example/order_reference.cpp. - [Prove who wrote a message posted to a relay](https://webcpporg.github.io/libs/crypto/#crypto-p2p-signed): `keypair::sign_schnorr`, `verify_schnorr` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/signed_message.cpp. diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index eb5398fd..291aefa0 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -1,5 +1,5 @@ { - "comment": "The data of crypto's generated tables and of llms.txt; doc/tables/generate.py reads it with the test Jamfiles, the message tests and the superproject's Jamfile fixtures, and writes doc/generated/, doc/llms.txt, include/webcpp/crypto/detail/capabilities.hpp and test/capabilities_test.cpp. The capability table is `families`: per family its algorithms, the targets on which each backend has it (each claimed only where a test of the family's operations on that backend runs), constant time per target where it differs from the backend's own `constant_time` (none yet), and the default per target and what the program links, as the code has it now, with its reason and the tests that fix it; a backend with `targets`, where it is built, is a tag of `backends`. A name in a text is written between backticks, as Markdown writes code: the tables show it as code and llms.txt keeps the backticks. Edit this file, then run python3 libs/crypto/doc/tables/generate.py; the doc build runs it with --check.", + "comment": "The data of crypto's generated tables and of llms.txt; doc/tables/generate.py reads it with the test Jamfiles, the message tests and the superproject's Jamfile fixtures, and writes doc/generated/, doc/llms.txt, include/webcpp/crypto/detail/capabilities.hpp, include/webcpp/crypto/detail/defaults.hpp and test/capabilities_test.cpp. The capability table is `families`: per family its algorithms, the targets on which each backend has it (each claimed only where a test of the family's operations on that backend runs), constant time per target where it differs from the backend's own `constant_time` (none yet), and the default per target, one whatever the program links (design D32), with its reason and the tests that fix it, from which come include/webcpp/crypto/detail/defaults.hpp and the refusal that says what a program whose default is not linked needs; a backend with `targets`, where it is built, is a tag of `backends`. A name in a text is written between backticks, as Markdown writes code: the tables show it as code and llms.txt keeps the backticks. Edit this file, then run python3 libs/crypto/doc/tables/generate.py; the doc build runs it with --check.", "page": "https://webcpporg.github.io/libs/crypto/", "targets": ["native", "wasip2", "wasip3", "emscripten"], "sources": { @@ -277,13 +277,10 @@ {"name": "aes256_gcm", "title": "AES-256-GCM", "type": "ciphers::gcm>"} ], "default": [ - {"targets": ["emscripten"], "linked": "BearSSL", "backend": "bearssl", "tests": ["default_bearssl"], "why": "the only AEAD backend there: webcpp does not build OpenSSL for Emscripten; size and speed not measured yet"}, - {"targets": ["wasip2", "wasip3"], "linked": "BearSSL, with or without OpenSSL", "backend": "bearssl", "tests": ["default_bearssl", "default_both_wasm"], "why": "constant time by design ({bearssl-ct}), where OpenSSL is built no-asm and its AES and GHASH are table-based ({openssl-install})"}, - {"targets": ["wasip2", "wasip3"], "linked": "BearSSL and OpenSSL, with `WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL`", "backend": "openssl", "tests": ["default_openssl_wasm"], "why": "the program's choice"}, - {"targets": ["native"], "where": "Clang and GCC", "linked": "OpenSSL, with or without BearSSL", "backend": "openssl", "tests": ["default_both"], "why": "OpenSSL's assembly uses the CPU's AES and carry-less multiplication instructions on x86-64 and ARMv8 ({openssl-armv8}; {openssl-ghash-asm}); BearSSL has them on x86 only ({bearssl-aes}); speed not measured yet"}, - {"targets": ["native"], "where": "MSVC", "linked": "OpenSSL, with or without BearSSL", "backend": "openssl", "tests": ["default_both"], "why": "the same rule as with Clang and GCC, but here OpenSSL is built no-asm: table-based AES and 4-bit GHASH, no AES-NI, not constant time ({openssl-install}); where timing attacks matter, link BearSSL and define `WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL`"}, - {"targets": ["native"], "linked": "BearSSL and OpenSSL, with `WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL`", "backend": "bearssl", "tests": ["default_selected"], "why": "the program's choice, constant time by design ({bearssl-ct}): on MSVC, where OpenSSL is built no-asm, the choice for code that timing attacks threaten"}, - {"targets": ["native"], "linked": "BearSSL alone", "backend": "bearssl", "tests": ["default_bearssl"], "why": "the backend that is linked"} + {"targets": ["native"], "where": "Clang and GCC", "backend": "openssl", "tests": ["default_both", "default_backend_all_linked"], "why": "OpenSSL's assembly uses the CPU's AES and carry-less multiplication instructions on x86-64 and ARMv8 ({openssl-armv8}; {openssl-ghash-asm}); BearSSL has them on x86 only ({bearssl-aes}). OpenSSL whatever the program links: a program that links BearSSL alone names `gcm>`"}, + {"targets": ["native"], "where": "MSVC", "backend": "openssl", "tests": ["default_both"], "why": "the same rule as with Clang and GCC, but here OpenSSL is built no-asm: table-based AES and 4-bit GHASH, no AES-NI, not constant time ({openssl-install}); where timing attacks matter, link BearSSL and name `gcm>`"}, + {"targets": ["wasip2", "wasip3"], "backend": "bearssl", "tests": ["default_bearssl", "default_both_wasm", "default_backend_all_linked"], "why": "constant time by design ({bearssl-ct}), where OpenSSL is built no-asm and its AES and GHASH are table-based ({openssl-install}). BearSSL whatever the program links: a program that links OpenSSL alone names `gcm>`"}, + {"targets": ["emscripten"], "backend": "bearssl", "tests": ["default_bearssl", "default_backend_all_linked_emscripten"], "why": "the only AEAD backend there: webcpp does not build OpenSSL for Emscripten"} ], "backends": { "bearssl": {"targets": "all"}, @@ -302,7 +299,7 @@ {"name": "aes256", "title": "AES-256", "type": "ciphers::aes256<{backend}>"} ], "default": [ - {"targets": ["native", "wasip2", "wasip3", "emscripten"], "linked": "any backend", "backend": null, "tests": ["default_selection_bearssl"], "why": "a raw block cipher is a building block a program chooses deliberately, naming its backend; `aes256<>` takes AES-GCM's default as its argument, and its `make` does not compile where that is BearSSL"} + {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": null, "tests": ["default_backend_none_linked", "default_selection_bearssl"], "why": "a raw block cipher is a building block a program chooses deliberately, naming its backend; `aes256<>` takes AES-GCM's default as its argument, and its `make` does not compile where that is BearSSL"} ], "backends": { "openssl": {"targets": "all"}, @@ -319,7 +316,7 @@ {"name": "secp256k1", "title": "secp256k1", "type": "curves::secp256k1::basic_keypair<{backend}>"} ], "default": [ - {"targets": ["native", "wasip2", "wasip3", "emscripten"], "linked": "libsecp256k1", "backend": "secp256k1", "tests": ["secp256k1"], "why": "the only backend ({libsecp256k1})"} + {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "secp256k1", "tests": ["secp256k1", "default_backend_none_linked"], "why": "the only backend ({libsecp256k1})"} ], "backends": { "secp256k1": {"targets": "all"} @@ -336,7 +333,7 @@ {"title": "Ethereum", "section": "crypto-curves", "text": "this version verifies Ethereum's ECDSA signatures with a known key but has no recoverable signature (no recovery id `v`, no public key recovery) and no uncompressed public key output, so it cannot sign Ethereum transactions or derive addresses."}, {"title": "Compare secrets in constant time", "section": "crypto-equal", "text": "compare a tag, a MAC or a token with `equal`, never `==` or `memcmp` ({cwe208})."}, {"title": "Secrets come from random_device", "section": "crypto-entropy", "text": "keys, IVs and tokens are drawn from `random_device`, never `std::mt19937` or `rand` ({cwe338})."}, - {"title": "The default on MSVC is not constant time", "section": "crypto-backends-defaults", "text": "natively with OpenSSL linked the default is OpenSSL, which MSVC builds no-asm, table-based ({openssl-install}); where timing attacks matter, link BearSSL and define `WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL`."} + {"title": "The default on MSVC is not constant time", "section": "crypto-backends-defaults", "text": "natively the default is OpenSSL, which MSVC builds no-asm, table-based ({openssl-install}); where timing attacks matter, link BearSSL and name `gcm>`."} ], "outcome_sections": { "all": "every target", @@ -382,8 +379,8 @@ {"need": "Generate a session token, a password-reset link or an API key", "namespace": "webcpp::crypto", "api": "`random_device::fill`", "backend": "the system's generator", "jamfile": "/webcpp/crypto//crypto", "example": "reset_token", "section": "crypto-entropy"}, {"need": "Draw an unbiased number in a range, such as a six-digit code", "namespace": "webcpp::crypto", "api": "`random_device` with `std::uniform_int_distribution`", "backend": "the system's generator", "jamfile": "/webcpp/crypto//crypto", "example": "reset_token", "section": "crypto-entropy"}, {"need": "Check a webhook's or an API's HMAC signature", "namespace": "webcpp::crypto", "api": "`equal`, with Boost.Hash2's `hmac`", "backend": "none", "jamfile": "/webcpp/crypto//crypto", "example": "equal_hmac", "section": "crypto-equal"}, - {"need": "Encrypt a database field, a cookie or a token at rest", "namespace": "webcpp::crypto::ciphers", "api": "`aes256_gcm`", "backend": "default: BearSSL on WebAssembly, OpenSSL natively when linked", "jamfile": "/webcpp/crypto//crypto /third_party//bearssl", "example": "store_token", "section": "crypto-gcm"}, - {"need": "Encrypt a large file or a stream", "namespace": "webcpp::crypto::ciphers", "api": "`aes256_gcm`: records, or `begin_seal`, `update` and `result`", "backend": "default", "jamfile": "/webcpp/crypto//crypto /third_party//bearssl", "example": "sealed_records", "section": "crypto-gcm-incremental"}, + {"need": "Encrypt a database field, a cookie or a token at rest", "namespace": "webcpp::crypto::ciphers", "api": "`gcm>`, or `aes256_gcm` on the default", "backend": "BearSSL, named: one Jamfile line on every target; the default is OpenSSL natively, BearSSL on WebAssembly", "jamfile": "/webcpp/crypto//crypto /third_party//bearssl", "example": "store_token", "section": "crypto-gcm"}, + {"need": "Encrypt a large file or a stream", "namespace": "webcpp::crypto::ciphers", "api": "`gcm>`: records, or `begin_seal`, `update` and `result`", "backend": "BearSSL, named", "jamfile": "/webcpp/crypto//crypto /third_party//bearssl", "example": "sealed_records", "section": "crypto-gcm-incremental"}, {"need": "Tell a forged message from a malformed one", "namespace": "webcpp::crypto", "api": "`error`", "backend": "any", "jamfile": "/webcpp/crypto//crypto", "example": "failure_reasons", "section": "crypto-errors"}, {"need": "Turn a sequential id into an opaque reference", "namespace": "webcpp::crypto::ciphers", "api": "`aes256`", "backend": "ctaes, or OpenSSL natively and on WASI", "jamfile": "/webcpp/crypto//crypto /third_party//ctaes", "example": "order_reference", "section": "crypto-block"}, {"need": "Prove who wrote a message posted to a relay", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::sign_schnorr`, `verify_schnorr`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "signed_message", "section": "crypto-p2p-signed"}, @@ -399,11 +396,11 @@ {"need": "Use P-256 (passkeys, JWT's ES256), Ed25519 or X25519", "namespace": "none in this version", "api": "secp256k1 keys and signatures do not interoperate with these curves", "backend": "none", "jamfile": "none", "example": "", "section": "crypto-curves"} ], "fixtures": { - "web": "A web application: AES-256-GCM on BearSSL, the default on every target.", - "server": "A server, natively: the same program with OpenSSL, the default natively when linked.", - "both_bearssl_default": "Both backends linked, BearSSL chosen as the default with a define; the same program.", + "web": "A web application: AES-256-GCM on BearSSL, the default on WebAssembly.", + "server": "A server, natively: the same program with OpenSSL, the default natively.", + "both_bearssl_named": "Both backends linked, and BearSSL named in the type where the default is OpenSSL.", "block": "The AES block cipher on ctaes: the FIPS 197 block encrypted and decrypted again.", - "encrypt_and_sign": "Two backends in one program: AES-256-GCM on the default backend and a BIP 340 signature.", + "encrypt_and_sign": "Two backends in one program: AES-256-GCM on BearSSL, named in the type so that one Jamfile serves every target, and a BIP 340 signature.", "openssl_linked": "OpenSSL, built from source, named in the type: natively and on WASI.", "sign": "A BIP 340 signature with libsecp256k1's default tables.", "sign_small": "The same program with libsecp256k1's small tables, which libsecp256k1 documents as smaller and slower to verify ({secp256k1-configure}); not measured here yet.", @@ -414,7 +411,8 @@ "canary_ctaes_missing": "ctaes's headers used without its library.", "canary_secp256k1_missing": "libsecp256k1's headers used without its library.", "canary_secp256k1_small": "A program compiled for other tables than its libsecp256k1 was built with.", - "default_openssl_on_emscripten": "OpenSSL selected as the default in a build for Emscripten.", + "default_openssl_on_emscripten": "Version 0.1's define that chose OpenSSL as the default, in a build for Emscripten.", + "default_bearssl_on_emscripten": "Version 0.1's define that chose BearSSL as the default, in a build for Emscripten.", "has_openssl_on_emscripten": "OpenSSL declared linked, without b2, in a build for Emscripten.", "openssl_on_emscripten": "`/webcpp/crypto//openssl` named in a build for Emscripten.", "openssl_memory_on_emscripten": "The memory option of the OpenSSL backend set in a build for Emscripten.", @@ -427,10 +425,10 @@ "sodium_not_linked_on_emscripten": "A program for Emscripten that names libsodium and links none." }, "fixes": { - "no_backend_native": "Add `/webcpp/crypto//openssl` or `/third_party//bearssl` to the program's sources.", + "gcm_default_openssl_not_linked": "Natively the default is OpenSSL: add `/webcpp/crypto//openssl`, or name BearSSL in the type, as in `gcm>`.", "no_backend_wasm": "Add `/third_party//bearssl` to the program's sources.", - "bearssl_not_linked": "Add `/third_party//bearssl`, or, with OpenSSL linked, define `WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL`.", - "openssl_only_on_wasi": "On WASI the default is BearSSL: add `/third_party//bearssl`, or define `WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL`.", + "bearssl_not_linked": "Add `/third_party//bearssl`.", + "openssl_only_on_wasi": "On WASI the default is BearSSL: add `/third_party//bearssl`, or name OpenSSL in the type, as in `gcm>`.", "openssl_not_linked": "Add `/webcpp/crypto//openssl`.", "openssl_old": "Name `/webcpp/crypto//openssl`, which builds OpenSSL 3.5.9; without b2, put OpenSSL 3's `include/` first.", "ctaes_not_linked": "Add `/third_party//ctaes`.", @@ -438,11 +436,13 @@ "sodium_not_linked_on_emscripten": "Add `/third_party//sodium` to the program's sources.", "canary_sodium_other_commit": "Build the library at the commit of webcpp's submodule, or link it through b2.", "secp256k1_not_linked": "Add `/third_party//secp256k1`.", - "gcm_on_ctaes": "Use `aes256_gcm` with BearSSL or OpenSSL linked.", + "gcm_on_ctaes": "Name `gcm>` or `gcm>`, or use `aes256_gcm` with its default linked.", "secp256k1_other_backend": "Name `backends::secp256k1`, or leave the backend out: `curves::secp256k1::keypair`.", "aes_on_bearssl": "Name `ciphers::aes256`, include `` and add `/third_party//ctaes`.", - "two_defaults": "Keep one of the two defines.", - "default_openssl_on_emscripten": "Remove the define, or make it `WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL`.", + "default_selected": "Remove the define, and name `gcm>` where the program wants BearSSL.", + "default_openssl_wasm": "Remove the define, and name `gcm>` where the program wants OpenSSL.", + "default_openssl_on_emscripten": "Remove the define: on Emscripten the default is BearSSL, and OpenSSL is not built.", + "default_bearssl_on_emscripten": "Remove the define: on Emscripten the default is BearSSL.", "has_openssl_on_emscripten": "Replace `/webcpp/crypto//openssl` with `/third_party//bearssl`.", "openssl_on_emscripten": "Name `/third_party//bearssl` in its place for the Emscripten build.", "openssl_memory_on_emscripten": "Remove `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE` from the WebAssembly build: give that build a project of its own, without the define and OpenSSL, naming `/third_party//bearssl`. On WebAssembly the backend is BearSSL, which allocates nothing.", @@ -461,8 +461,6 @@ "no_backend_on_emscripten": "Add `/third_party//bearssl` to the program's sources.", "canary_secp256k1_two_files": "Compile every file of the program with the same backend settings.", "canary_two_files": "Compile every file of the program with the same backend settings.", - "default_two_files": "Give `WEBCPP_CRYPTO_DEFAULT_BACKEND_*` in the requirements of the program's project, so that every file gets it.", - "no_backend": "As `no_backend_native`.", "openssl_not_linked_msvc": "As `openssl_not_linked`." } } diff --git a/doc/tables/generate.py b/doc/tables/generate.py index 743bef0b..50b24023 100644 --- a/doc/tables/generate.py +++ b/doc/tables/generate.py @@ -70,6 +70,7 @@ 'wasip3': 'WEBCPP_TARGET_WASIP3', 'emscripten': 'WEBCPP_TARGET_EMSCRIPTEN'} CAPABILITIES = Path('include/webcpp/crypto/detail/capabilities.hpp') CAPABILITIES_TEST = Path('test/capabilities_test.cpp') +DEFAULTS = Path('include/webcpp/crypto/detail/defaults.hpp') Data = Dict[str, Any] @@ -437,18 +438,24 @@ def check_families(data: Data, declared: Dict[str, List[str]]) -> None: raise Fault(f'crypto.json: the family {name} states constant time for ' f'{backend} on {target}, where it does not claim it') cite(data, why) - # A default per target and what the program links (and, natively, the compiler), each - # claimed only where a test that fixes it runs. - defaults: List[Tuple[str, str, str]] = [] + # One default per target, chosen by the target alone (design D32): a row of one compiler + # restates it with a reason of its own. Each is claimed only where a test that fixes it + # runs. + rows: List[Tuple[str, str]] = [] for entry in family['default']: cite(data, entry['why']) + backend = entry['backend'] for target in entry['targets']: - key = (target, entry.get('where', ''), entry['linked']) - if key in defaults: - raise Fault(f'crypto.json: the family {name} has two defaults on {target}, ' - f'linked {entry["linked"]}') - defaults.append(key) - backend = entry['backend'] + where = entry.get('where', '') + if (target, where) in rows: + raise Fault(f'crypto.json: the family {name} has two defaults on {target}' + + (f', {where}' if where else '')) + rows.append((target, where)) + chosen = default_on(family, target) + if chosen != backend: + raise Fault(f'crypto.json: the family {name} has two default backends on ' + f'{target}, {chosen or "none"} and {backend or "none"}: the ' + 'target alone chooses it') if backend is not None and (backend not in family['backends'] or target not in cell_targets(data, family, backend)): raise Fault(f'crypto.json: the family {name} defaults to {backend} on ' @@ -457,12 +464,21 @@ def check_families(data: Data, declared: Dict[str, List[str]]) -> None: if target not in declared.get(test, []): raise Fault(f'crypto.json: the family {name}\'s default on {target} ' f'names the test {test}, which does not run there') - covered = {target for target, _, _ in defaults} + covered = {target for target, _ in rows} missing = [target for target in data['targets'] if target not in covered] if missing: raise Fault(f'crypto.json: the family {name} has no default on {", ".join(missing)}') +def default_on(family: Data, target: str) -> Optional[str]: + """A family's default backend on a target, or None: its first row there (check_families + faults a row that names another).""" + for entry in family['default']: + if target in entry['targets']: + return entry['backend'] + return None + + def have_list(data: Data, family: Data) -> str: """The backends that have a family, each with its targets, as a refusal names them.""" parts: List[str] = [] @@ -507,6 +523,17 @@ def condition(targets: List[str]) -> str: return ' || '.join(f'defined({TARGET_MACROS[target]})' for target in targets) +def opening(targets: List[str], first: bool = True) -> str: + """The directive that opens, or with first false continues, a block that holds on the + targets: #ifdef for one target where it opens one, as clang-tidy's + readability-use-concise-preprocessor-directives asks.""" + if not first: + return f'#elif {condition(targets)}' + if len(targets) == 1: + return f'#ifdef {TARGET_MACROS[targets[0]]}' + return f'#if {condition(targets)}' + + def capabilities_header(data: Data) -> str: """include/webcpp/crypto/detail/capabilities.hpp: the family and algorithm tags, each cell of `detail::supported` on its targets, and the refusals of each family's primary engine.""" @@ -556,39 +583,62 @@ def capabilities_header(data: Data) -> str: targets = cell_targets(data, family, backend) out.append(f'// {family["title"]} on {backend}: {", ".join(targets)}.') for entry in family['names']: - out += [f'#if {condition(targets)}', 'template <>', + out += [opening(targets), 'template <>', f'inline constexpr bool supported = true;', '#endif'] - out += ['// clang-format on', '', '} // namespace webcpp::crypto::detail', '', + out += ['// clang-format on', '', + '/**', + ' * Whether `Backend`\'s library is linked: its `WEBCPP_CRYPTO_HAS_` is defined.', + ' *', + ' * @tparam Backend A backend tag of `backends`.', + ' */', + 'template ', 'inline constexpr bool linked = false;'] + for backend in tags_of(data): + out += [f'#ifdef WEBCPP_CRYPTO_HAS_{backend.upper()}', 'template <>', + f'inline constexpr bool linked = true;', '#endif'] + out += ['', '} // namespace webcpp::crypto::detail', '', '// The body of each family\'s primary engine, which a backend reaches where its', '// header does not specialise the engine, per target: a backend without the family', - '// there is refused, naming those that have it; a backend that has it there, whose', - '// header the program did not include, is told to include it; any other type is no', - '// backend of the family.', + '// there is refused, naming those that have it; the default there, not linked, says', + '// the Jamfile line that links it and the type that names another backend; a backend', + '// that has it there, whose header the program did not include, is told to include', + '// it; any other type is no backend of the family.', '// clang-format off'] tags = tags_of(data) for family in data['families']: have = have_list(data, family) + known = ' || '.join(f'std::is_same_v' + for backend in tags) for index, target in enumerate(data['targets']): lines: List[str] = [] for backend in tags: + tag = f'::webcpp::crypto::backends::{backend}' if backend not in family['backends']: - text = refusal(data, family, backend) - elif target in cell_targets(data, family, backend): - facts = data['backends'][backend] - text = (f'webcpp::crypto: {backend}\'s {family["title"]} is in ' - f'{facts["header"]}, which the program does not include. Include ' - f'it, and add {facts["jamfile"]} to the program\'s Jamfile.') - else: - text = (f'webcpp::crypto: {backend} has no {family["title"]} on {target}. ' - f'The backends that have it: {have}.') - lines.append(f'static_assert(!std::is_same_v, "{text}")') - lines.append(f'static_assert(::webcpp::crypto::detail::dependent_false, ' - f'"webcpp::crypto: {family["title"]} has no backend of that name. The ' - f'backends that have it: {have}.")') - out.append(f'#{"if" if index == 0 else "elif"} defined({TARGET_MACROS[target]})') + lines.append(f'static_assert(!std::is_same_v, ' + f'"{refusal(data, family, backend)}")') + continue + if target not in cell_targets(data, family, backend): + lines.append(f'static_assert(!std::is_same_v, ' + f'"webcpp::crypto: {backend} has no {family["title"]} on ' + f'{target}. The backends that have it: {have}.")') + continue + facts = data['backends'][backend] + include = (f'webcpp::crypto: {backend}\'s {family["title"]} is in ' + f'{facts["header"]}, which the program does not include. Include ' + f'it, and add {facts["jamfile"]} to the program\'s Jamfile.') + if backend != default_on(family, target): + lines.append(f'static_assert(!std::is_same_v, "{include}")') + continue + # The default: not linked, what the program needs; linked, its header. + linked = f'::webcpp::crypto::detail::linked<{tag}>' + lines += [f'static_assert(!std::is_same_v || {linked}, ' + f'"{needs(data, family, target, backend)}")', + f'static_assert(!std::is_same_v || !{linked}, ' + f'"{include}")'] + lines.append(f'static_assert({known}, "webcpp::crypto: {family["title"]} has no ' + f'backend of that name. The backends that have it: {have}.")') + out.append(opening([target], index == 0)) out += doc_comment(f'The refusals of the family {family["title"]}\'s primary engine ' f'for `Backend`, on {target}.') + [ f'#define WEBCPP_CRYPTO_DETAIL_REFUSE_{family["name"].upper()}(Backend) \\'] @@ -598,6 +648,98 @@ def capabilities_header(data: Data) -> str: return '\n'.join(out) +def needs(data: Data, family: Data, target: str, backend: str) -> str: + """What a program that uses a family's default without linking it needs (design D32): the + Jamfile line that links it and, where another backend has the family on the target, the type + that names it. The text holds on every target where the default is that backend, so that + one message test checks it on each.""" + facts = data['backends'][backend] + head = (f'webcpp::crypto: {family["title"]}\'s default backend on this target is ' + f'{facts["title"]}, which is not linked') + add = (f'Add {facts["jamfile"]} to the program\'s Jamfile, as in: exe app : app.cpp ' + f'/webcpp/crypto//crypto {facts["jamfile"]} ;') + others = [other for other in family['backends'] + if other != backend and target in cell_targets(data, family, other)] + if not others: + return f'{head}, and the one backend that has it there. {add}' + named = family['names'][-1]['type'].replace('{backend}', f'backends::{others[0]}') + return (f'{head}. {add} or name another backend in the type, as in {named}. The backends ' + f'that have it: {have_list(data, family)}.') + + +def defaults_header(data: Data) -> str: + """include/webcpp/crypto/detail/defaults.hpp: each family's default backend per target, + chosen by the target alone (design D32), and the macro that tells the family's header which + backend's header to include.""" + out = ['#ifndef WEBCPP_CRYPTO_DETAIL_DEFAULTS_HPP', '#define WEBCPP_CRYPTO_DETAIL_DEFAULTS_HPP', + '', '#include ', '', + '#include ', '', + 'namespace webcpp::crypto {', '', + '/**', + ' * The default backend of `Family` on the target being compiled, as its `type`.', + ' *', + ' * One per family and target, chosen by the target alone whatever the program links,', + ' * for the reason doc/tables/crypto.json gives (the guide\'s "The default backend per', + ' * target"). A family without a default has no `type`; a program names any other', + ' * backend in the type.', + ' *', + ' * @tparam Family A family tag of `families`.', + ' */', + 'template ', 'struct default_backend_of {};', '', + '// Each family\'s default, on the targets where it is that backend.', + '// clang-format off'] + for family in data['families']: + groups: List[Tuple[str, List[str]]] = [] + for target in data['targets']: + backend = default_on(family, target) + if backend is None: + continue + for chosen, targets in groups: + if chosen == backend: + targets.append(target) + break + else: + groups.append((backend, [target])) + if not groups: + continue + conditional = len(groups) > 1 or len(groups[0][1]) < len(data['targets']) + for index, (backend, targets) in enumerate(groups): + title = data['backends'][backend]['title'] + if conditional: + out.append(opening(targets, index == 0)) + out += doc_comment(f'Defined where {title} is the default of {family["title"]}.') + out.append(f'#define WEBCPP_CRYPTO_DETAIL_DEFAULT_{family["name"].upper()}_' + f'{backend.upper()} 1') + out += doc_comment(f'The default of {family["title"]} on {", ".join(targets)}: ' + f'{title}.') + out += ['template <>', f'struct default_backend_of {{', + f' /** `backends::{backend}`. */', f' using type = backends::{backend};', + '};'] + if conditional: + out.append('#endif') + out += ['// clang-format on', '', + '/**', + ' * The default backend of `Family` on the target being compiled (see', + ' * @ref default_backend_of).', + ' *', + ' * @tparam Family A family tag of `families` that has a default.', + ' */', + 'template ', + 'using default_backend_t = default_backend_of::type;', ''] + if any(family['name'] == 'gcm' for family in data['families']): + out += ['/**', + ' * The default backend of AES-GCM, version 0.1\'s name, which `aes128_gcm`,', + ' * `aes256_gcm` and the AES block cipher\'s `aes256<>` take: natively OpenSSL, on', + ' * WebAssembly BearSSL.', + ' *', + ' * @see "The default backend per target", in the guide.', + ' */', + 'using default_backend = default_backend_t;', ''] + out += ['} // namespace webcpp::crypto', '', + '#endif // WEBCPP_CRYPTO_DETAIL_DEFAULTS_HPP', ''] + return '\n'.join(out) + + def capabilities_test(data: Data) -> str: """test/capabilities_test.cpp: `supports_v` of every cell on the target being compiled, each present cell made through its family's own type where its backend is linked, and each @@ -645,7 +787,7 @@ def capabilities_test(data: Data) -> str: if not present: out.append(f'static_assert(!{trait});') continue - out += [f'#if {condition(targets)}', f'static_assert({trait});', '#else', + out += [opening(targets), f'static_assert({trait});', '#else', f'static_assert(!{trait});', '#endif'] algorithm = program_type(data, entry['type'], backend) made += [f'#if ({condition(targets)}) && defined(WEBCPP_CRYPTO_HAS_' @@ -705,11 +847,11 @@ def api_backends(data: Data, matrix: Matrix, operation: Data) -> str: if 'default' in operation: # The block cipher's default argument is AES-GCM's default: its table is AES-GCM's. family = family_of(data, operation.get('default_of', operation['family'])) - defaults = [[target_label(entry), marked(entry['linked']), default_title(data, entry)] + defaults = [[target_label(entry), default_title(data, entry)] for entry in family['default']] - text += (f'\n{marked(operation["default"])} The default per target and what the program ' + text += (f'\n{marked(operation["default"])} The default per target, whatever the program ' 'links, as <> gives it with its reasons and tests:\n\n' - + table(['Target', 'Linked', 'Default'], defaults, '.wrap-names,cols="2,4,2",')) + + table(['Target', 'Default'], defaults, 'cols="1,1",')) return text @@ -773,19 +915,16 @@ def default_title(data: Data, entry: Data) -> str: def defaults_page(data: Data) -> str: - """The default backend of each family per target and what is linked, each with the tests - that fix it (check_families has checked that they run there).""" + """The default backend of each family per target, whatever the program links, each with its + reason and the tests that fix it (check_families has checked that they run there).""" rows: List[List[str]] = [] for family in data['families']: for entry in family['default']: - rows.append([family['title'], target_label(entry), marked(entry['linked']), - default_title(data, entry), cite(data, entry['why']), + rows.append([family['title'], target_label(entry), default_title(data, entry), + cite(data, entry['why']), ', '.join(code(name) for name in entry['tests'])]) - # wrap-names: a header in "Linked" breaks after its / at every width; a define of 37 - # characters breaks between its parts where the table does not fit otherwise, rather than - # take the width "Why" needs (tools/doc/docinfo.html). - return table(['Family', 'Target', 'Linked', 'Default', 'Why', 'Tested by'], rows, - '.wrap-names,cols="2,2,4,2,5,3",') + return table(['Family', 'Target', 'Default', 'Why', 'Tested by'], rows, + 'cols="2,2,2,6,3",') def constant_time_page(data: Data) -> str: @@ -1043,7 +1182,7 @@ def llms(data: Data, matrix: Matrix, library: Path) -> str: out += ['## Default backend per family', ''] for family in data['families']: for entry in family['default']: - out.append(f'- {family["title"]}, {target_label(entry)}, linked {entry["linked"]}: ' + out.append(f'- {family["title"]}, {target_label(entry)}: ' f'{default_title(data, entry)}; {cite_markdown(data, entry["why"])}.') out += ['', '## Rules of use', ''] for rule in data['rules']: @@ -1097,6 +1236,7 @@ def generate(root: Path, library: Path) -> Dict[Path, str]: files[generated / 'use-cases.adoc'] = use_cases_page(data, library) files[library / CAPABILITIES] = capabilities_header(data) files[library / CAPABILITIES_TEST] = capabilities_test(data) + files[library / DEFAULTS] = defaults_header(data) for path in list(files): files[path] = NOTICE + files[path] files[DOC / 'llms.txt'] = llms(data, matrix, library) diff --git a/doc/tables/generate_test.py b/doc/tables/generate_test.py index 70492835..d15ca7da 100644 --- a/doc/tables/generate_test.py +++ b/doc/tables/generate_test.py @@ -255,8 +255,8 @@ def backend(title: str, name: str, jamfile: str) -> generate.Data: 'header': '', 'names': [{'name': 'ed25519', 'title': 'Ed25519', 'type': 'curves::ed25519::basic_keypair<{backend}>'}], - 'default': [{'targets': EVERY_TARGET, 'linked': 'libsodium', 'backend': 'sodium', - 'tests': ['ed25519'], 'why': 'the only backend ({rfc8032})'}], + 'default': [{'targets': EVERY_TARGET, 'backend': 'sodium', 'tests': ['ed25519'], + 'why': 'the only backend ({rfc8032})'}], 'backends': {'sodium': {'targets': 'all'}}}]} @@ -277,12 +277,13 @@ def test_a_backend_without_a_family_is_refused_naming_those_that_have_it(_: Path '(native, wasip2, wasip3, emscripten).")') in header, header # A backend that has the family, whose header the program did not include, is told so; a # backend that is no tag of backends:: is never named; any other type is the last refusal. - assert ('static_assert(!std::is_same_v, ' + assert ('!::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, ' '"webcpp::crypto: sodium\'s Ed25519 is in , ' 'which the program does not include. Include it, and add /third_party//sodium to the ' 'program\'s Jamfile.")') in header, header assert 'system' not in header, header - assert ('static_assert(::webcpp::crypto::detail::dependent_false, ' + assert ('static_assert(std::is_same_v || ' + 'std::is_same_v, ' '"webcpp::crypto: Ed25519 has no backend of that name. The backends that have it: ' 'sodium (native, wasip2, wasip3, emscripten).")\n') in header, header assert '#define WEBCPP_CRYPTO_DETAIL_REFUSE_ED25519(Backend)' in header, header @@ -351,30 +352,42 @@ def test_a_cell_claimed_where_no_test_runs_is_a_fault(_: Path) -> None: 'the family ed25519 claims sodium on wasip2, where sodium is not built') +def a_default(targets: list[str], backend: Optional[str], where: str = '', + tests: Optional[list[str]] = None) -> generate.Data: + """A row of a family's defaults, on targets, for one compiler where where names it.""" + row: generate.Data = {'targets': targets, 'backend': backend, + 'tests': ['ed25519'] if tests is None else tests, 'why': 'w'} + if where: + row['where'] = where + return row + + def test_a_default_is_a_backend_of_the_family_its_tests_run_on(_: Path) -> None: - def default(targets: list[str], backend: Optional[str], linked: str = 'libsodium', - tests: Optional[list[str]] = None) -> generate.Data: - return {'targets': targets, 'linked': linked, 'backend': backend, - 'tests': ['ed25519'] if tests is None else tests, 'why': 'w'} data = small_table() every = {'ed25519': EVERY_TARGET, 'ed25519_native': ['native']} - data['families'][0]['default'] = [default(['native'], 'sodium')] + data['families'][0]['default'] = [a_default(['native'], 'sodium')] a_fault(data, every, 'the family ed25519 has no default on wasip2, wasip3, emscripten') - data['families'][0]['default'] = [default(EVERY_TARGET, 'bearssl')] + data['families'][0]['default'] = [a_default(EVERY_TARGET, 'bearssl')] a_fault(data, every, 'the family ed25519 defaults to bearssl on native, which does not have it there') - data['families'][0]['default'] = [default(EVERY_TARGET, 'sodium'), - default(['native'], None)] - a_fault(data, every, 'the family ed25519 has two defaults on native, linked libsodium') - # What the program links tells two defaults of one target apart. - data['families'][0]['default'] = [default(EVERY_TARGET, 'sodium'), - default(['native'], None, 'nothing')] + data['families'][0]['default'] = [a_default(EVERY_TARGET, 'sodium'), + a_default(['native'], 'sodium')] + a_fault(data, every, 'the family ed25519 has two defaults on native') + # A compiler's row restates its target's default with a reason of its own; it never changes + # the backend, which the target alone chooses. + data['families'][0]['default'] = [a_default(EVERY_TARGET, 'sodium'), + a_default(['native'], 'sodium', 'MSVC')] generate.check_families(data, every) + data['families'][0]['default'] = [a_default(EVERY_TARGET, 'sodium'), + a_default(['native'], None, 'MSVC')] + a_fault(data, every, 'the family ed25519 has two default backends on native, sodium and ' + 'none: the target alone chooses it') # A default is claimed only where a test that fixes it runs. - data['families'][0]['default'] = [default(EVERY_TARGET, 'sodium', tests=['ed25519_native'])] + data['families'][0]['default'] = [a_default(EVERY_TARGET, 'sodium', + tests=['ed25519_native'])] a_fault(data, every, 'the family ed25519\'s default on wasip2 names the test ed25519_native, ' 'which does not run there') - data['families'][0]['default'] = [default(EVERY_TARGET, 'sodium', tests=['absent'])] + data['families'][0]['default'] = [a_default(EVERY_TARGET, 'sodium', tests=['absent'])] a_fault(data, every, 'the family ed25519\'s default on native names the test absent, which ' 'does not run there') data = small_table() @@ -383,6 +396,86 @@ def default(targets: list[str], backend: Optional[str], linked: str = 'libsodium 'the operation sign names the family ed448, which crypto.json does not list') +def two_backends() -> generate.Data: + """small_table with BearSSL's Ed25519 on every target, and libsodium the default natively + alone, BearSSL elsewhere.""" + data = small_table() + family = data['families'][0] + family['backends']['bearssl'] = {'targets': 'all'} + family['default'] = [a_default(['native'], 'sodium'), + a_default(['wasip2', 'wasip3', 'emscripten'], 'bearssl')] + return data + + +def test_the_defaults_header_chooses_by_the_target_alone(_: Path) -> None: + header = generate.defaults_header(two_backends()) + assert header.startswith('#ifndef WEBCPP_CRYPTO_DETAIL_DEFAULTS_HPP\n'), header + assert '#include \n' in header, header + assert ('template \nstruct default_backend_of {};\n') in header, header + assert ('#ifdef WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE\n' + '/** Defined where libsodium is the default of Ed25519. */\n' + '#define WEBCPP_CRYPTO_DETAIL_DEFAULT_ED25519_SODIUM 1\n' + '/** The default of Ed25519 on native: libsodium. */\n' + 'template <>\nstruct default_backend_of {\n' + ' /** `backends::sodium`. */\n using type = backends::sodium;\n};\n' + '#elif defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || ' + 'defined(WEBCPP_TARGET_EMSCRIPTEN)\n') in header, header + assert 'using type = backends::bearssl;\n};\n#endif\n' in header, header + assert ('template \n' + 'using default_backend_t = default_backend_of::type;\n') in header, header + # AES-GCM's default keeps version 0.1's name, default_backend; a table without it has none. + assert 'using default_backend =' not in header, header + # A family whose default is the same on every target needs no condition. + one = generate.defaults_header(small_table()) + assert ('#define WEBCPP_CRYPTO_DETAIL_DEFAULT_ED25519_SODIUM 1\n/** The default of Ed25519 ' + 'on native, wasip2, wasip3, emscripten: libsodium. */\n') in one, one + assert '#if' not in one.split('struct default_backend_of {};', 1)[1], one + + +def test_a_family_without_a_default_has_no_type(_: Path) -> None: + data = small_table() + data['families'][0]['default'] = [a_default(EVERY_TARGET, None)] + header = generate.defaults_header(data) + assert 'default_backend_of' not in header, header + assert 'WEBCPP_CRYPTO_DETAIL_DEFAULT_ED25519' not in header, header + + +def test_the_default_s_refusal_says_what_the_program_needs(_: Path) -> None: + header = generate.capabilities_header(two_backends()) + native, rest = header.split('#elif defined(WEBCPP_TARGET_WASIP2)\n', 1) + emscripten = rest.split('#elif defined(WEBCPP_TARGET_EMSCRIPTEN)\n', 1)[1].split('#endif')[0] + sodium = '::webcpp::crypto::backends::sodium' + # The default, not linked: what to add, and the type that names another backend. + assert (f'static_assert(!std::is_same_v || ' + f'::webcpp::crypto::detail::linked<{sodium}>, "webcpp::crypto: Ed25519\'s default ' + 'backend on this target is libsodium, which is not linked. Add /third_party//sodium to ' + 'the program\'s Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto ' + '/third_party//sodium ; or name another backend in the type, as in ' + 'curves::ed25519::basic_keypair. The backends that have it: ' + 'sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, ' + 'emscripten).")') in native, native + # The default, linked, whose header the program did not include. + assert (f'static_assert(!std::is_same_v || ' + f'!::webcpp::crypto::detail::linked<{sodium}>, "webcpp::crypto: sodium\'s Ed25519 ' + 'is in ') in native, native + # Where no other backend has the family, there is no other type to name. + data = small_table() + alone = generate.capabilities_header(data).split('#elif defined(WEBCPP_TARGET_EMSCRIPTEN)\n', + 1)[1] + assert ('"webcpp::crypto: Ed25519\'s default backend on this target is libsodium, which is ' + 'not linked, and the one backend that has it there. Add /third_party//sodium to the ' + 'program\'s Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto ' + '/third_party//sodium ;")') in alone, alone + assert 'default backend on this target is BearSSL' in emscripten, emscripten + # Any other type is refused as no backend of the family, and nothing else is. + assert ('static_assert(std::is_same_v || ' + f'std::is_same_v, "webcpp::crypto: Ed25519 has no backend of that ' + 'name.') in native, native + assert ('template \ninline constexpr bool linked = false;\n' + '#ifdef WEBCPP_CRYPTO_HAS_BEARSSL\ntemplate <>\n' + 'inline constexpr bool linked = true;\n#endif\n') in header, header + + def test_a_refusal_holds_on_its_target(_: Path) -> None: data = small_table() data['families'][0]['backends']['sodium']['targets'] = ['native'] @@ -395,7 +488,7 @@ def test_a_refusal_holds_on_its_target(_: Path) -> None: assert ('"webcpp::crypto: sodium has no Ed25519 on wasip2. The backends that have it: sodium ' '(native).")') in wasip2, wasip2 assert 'is in ' not in wasip2, wasip2 - assert '#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE)\n' in native, native + assert '#ifdef WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE\n' in native, native assert header.count('#define WEBCPP_CRYPTO_DETAIL_REFUSE_ED25519(Backend)') == 4, header @@ -458,6 +551,9 @@ def test_the_check_names_a_file_that_differs(scratch: Path) -> None: test_a_family_that_names_an_unknown_backend_is_a_fault, test_a_cell_claimed_where_no_test_runs_is_a_fault, test_a_default_is_a_backend_of_the_family_its_tests_run_on, + test_the_defaults_header_chooses_by_the_target_alone, + test_a_family_without_a_default_has_no_type, + test_the_default_s_refusal_says_what_the_program_needs, test_a_refusal_holds_on_its_target, test_a_type_names_only_crypto_s_namespaces_from_the_root, test_the_check_prints_each_file_that_differs, diff --git a/doc/testing.adoc b/doc/testing.adoc index b7178ba9..6568a1e0 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -55,8 +55,9 @@ continuous integration's MSVC lanes. backend's test runs as well, and the limits natively. * *Allocation:* every `operator new` and the C library's allocator counted around each operation. -* *The default backend,* for each combination of linked and selected backends -on the targets where its answer holds (<>). +* *The default backend* of every family on every target, the same with every +backend linked, with none, with each alone and with the defines that no longer +choose one (<>). * *Every message,* word for word, by a message test with clang on the targets it names; on MSVC, each case proven to stop the build (<>). diff --git a/example/ecdh_session.cpp b/example/ecdh_session.cpp index be3f3304..dd60343c 100644 --- a/example/ecdh_session.cpp +++ b/example/ecdh_session.cpp @@ -8,7 +8,9 @@ // and talk over AES-256-GCM. The raw ECDH output is not a key: HKDF turns it into one and ties // it to this application with a context string. // tag::program[] -#include +#include +#include +#include #include #include #include @@ -27,6 +29,9 @@ #include namespace crypto = webcpp::crypto; +// AES-256-GCM on BearSSL, named in the type: one Jamfile line serves every target, where +// aes256_gcm's default is OpenSSL natively. +using aead_type = crypto::ciphers::gcm>; namespace secp256k1 = webcpp::crypto::curves::secp256k1; namespace hash2 = boost::hash2; @@ -127,10 +132,9 @@ boost::system::result generate_key() { } // Both sides derive their session key the same way. -boost::system::result session_cipher( - std::array const& shared) { +boost::system::result session_cipher(std::array const& shared) { auto key = hkdf_sha256<32>(shared, {}, bytes_of("example chat v1 session key")); - auto cipher = crypto::ciphers::aes256_gcm::make(key); + auto cipher = aead_type::make(key); // The cipher keeps its own copy of the key, which it wipes; this one goes now. wipe(std::as_writable_bytes(std::span(key))); return cipher; diff --git a/example/failure_reasons.cpp b/example/failure_reasons.cpp index 044789e7..7847eedc 100644 --- a/example/failure_reasons.cpp +++ b/example/failure_reasons.cpp @@ -9,7 +9,9 @@ // authentication_failed means someone changed the data, and open then wipes the plaintext so // that no unauthenticated bytes are ever used. // tag::program[] -#include +#include +#include +#include #include #include @@ -22,7 +24,9 @@ #include namespace crypto = webcpp::crypto; -using aead_type = crypto::ciphers::aes256_gcm; +// AES-256-GCM on BearSSL, named in the type: one Jamfile line serves every target, where +// aes256_gcm's default is OpenSSL natively. +using aead_type = crypto::ciphers::gcm>; namespace { diff --git a/example/store_token.cpp b/example/store_token.cpp index 90520a76..27d29ee5 100644 --- a/example/store_token.cpp +++ b/example/store_token.cpp @@ -8,7 +8,9 @@ // additional data: authenticated but not encrypted, so a row copied to another user's record // no longer opens. Without that binding a database writer could swap the rows of two users. // tag::program[] -#include +#include +#include +#include #include #include @@ -22,7 +24,9 @@ #include namespace crypto = webcpp::crypto; -using aead_type = crypto::ciphers::aes256_gcm; +// AES-256-GCM on BearSSL, named in the type: one Jamfile line serves every target, where +// aes256_gcm's default is OpenSSL natively. +using aead_type = crypto::ciphers::gcm>; namespace { diff --git a/example/wallet_key.cpp b/example/wallet_key.cpp index 180a6ba1..f576adac 100644 --- a/example/wallet_key.cpp +++ b/example/wallet_key.cpp @@ -8,7 +8,9 @@ // and restores it. A secret that sits unencrypted on disk, or lingers in memory after use, is // the first thing an attacker looks for, so the copies are wiped as soon as they are not needed. // tag::program[] -#include +#include +#include +#include #include #include #include @@ -24,6 +26,9 @@ #include namespace crypto = webcpp::crypto; +// AES-256-GCM on BearSSL, named in the type: one Jamfile line serves every target, where +// aes256_gcm's default is OpenSSL natively. +using aead_type = crypto::ciphers::gcm>; namespace secp256k1 = webcpp::crypto::curves::secp256k1; namespace { @@ -86,7 +91,7 @@ int main() { if (!device.fill(device_key) || !device.fill(iv)) { return 1; } - auto aead = crypto::ciphers::aes256_gcm::make(device_key); + auto aead = aead_type::make(device_key); wipe(std::as_writable_bytes(std::span(device_key))); if (!aead) { return 1; diff --git a/include/webcpp/crypto.hpp b/include/webcpp/crypto.hpp index d15b6cd6..2f8a8b21 100644 --- a/include/webcpp/crypto.hpp +++ b/include/webcpp/crypto.hpp @@ -5,11 +5,10 @@ // https://www.boost.org/LICENSE_1_0.txt) /** - Every header of webcpp::crypto that needs no backend, and the header of each - backend the build links. `ciphers/aes256_gcm.hpp`, `aes128_gcm` and `aes256_gcm`, is - included when the default backend is linked: a program that links OpenSSL alone where - BearSSL is the default (WebAssembly, or `WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL`) names - `ciphers::gcm>`. + Every header of webcpp::crypto that needs no backend, the header of each backend the build + links, and `ciphers/aes256_gcm.hpp`, whose `aes128_gcm` and `aes256_gcm` name AES-GCM's default + backend: a program that does not link the default names another in the type, as + `ciphers::gcm>` on WebAssembly. */ #ifndef WEBCPP_CRYPTO_HPP #define WEBCPP_CRYPTO_HPP @@ -17,6 +16,7 @@ #include #include +#include #include #include #include @@ -30,10 +30,6 @@ #ifdef WEBCPP_CRYPTO_HAS_OPENSSL #include #endif -#if (defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_OPENSSL) && defined(WEBCPP_CRYPTO_HAS_OPENSSL)) || \ - (defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_BEARSSL) && defined(WEBCPP_CRYPTO_HAS_BEARSSL)) -#include -#endif #ifdef WEBCPP_CRYPTO_HAS_CTAES #include diff --git a/include/webcpp/crypto/backends/bearssl.hpp b/include/webcpp/crypto/backends/bearssl.hpp index b2adedc1..9dfdd5c0 100644 --- a/include/webcpp/crypto/backends/bearssl.hpp +++ b/include/webcpp/crypto/backends/bearssl.hpp @@ -20,13 +20,7 @@ // without linking it stops here, with the line to write. #ifndef WEBCPP_CRYPTO_HAS_BEARSSL // clang-format off -#if defined(WEBCPP_CRYPTO_DETAIL_NONE_LINKED) && defined(WEBCPP_CRYPTO_WEBASSEMBLY) -#error "webcpp::crypto: no backend is linked. On WebAssembly the backend is BearSSL: in the program's Jamfile, add /third_party//bearssl beside /webcpp/crypto//crypto, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ; (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)" -#elif defined(WEBCPP_CRYPTO_DETAIL_NONE_LINKED) -#error "webcpp::crypto: no backend is linked. In the program's Jamfile, add /webcpp/crypto//openssl (OpenSSL built from source) or /third_party//bearssl (built from source) beside /webcpp/crypto//crypto, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//openssl ; (without b2: define WEBCPP_CRYPTO_HAS_OPENSSL=1 and link libcrypto, or define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)" -#else -#error "webcpp::crypto: the backend BearSSL is used and not linked. In the program's Jamfile, add /third_party//bearssl beside /webcpp/crypto//crypto, or, with /webcpp/crypto//openssl linked, select OpenSSL with WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL. (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)" -#endif +#error "webcpp::crypto: the backend BearSSL is used and not linked. In the program's Jamfile, add /third_party//bearssl beside /webcpp/crypto//crypto. (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)" // clang-format on #else diff --git a/include/webcpp/crypto/ciphers/aes.hpp b/include/webcpp/crypto/ciphers/aes.hpp index dc285c9e..0181901a 100644 --- a/include/webcpp/crypto/ciphers/aes.hpp +++ b/include/webcpp/crypto/ciphers/aes.hpp @@ -16,6 +16,7 @@ #include #include +#include #include #include @@ -29,6 +30,52 @@ namespace webcpp::crypto::detail { +/** + * What the AES block cipher stores on a backend whose header does not specialise it: nothing, + * since its engine refuses the backend where the cipher is called. + */ +template +struct block_state {}; + +/** + * The block cipher's engine on a backend whose header does not specialise it: the family's + * refusal (`detail/capabilities.hpp`). Its functions are never called: the refusal stops the + * build where the class is instantiated, and they keep the compiler from adding errors of their + * own after it. + */ +template +struct block_engine { + WEBCPP_CRYPTO_DETAIL_REFUSE_AES_BLOCK(Backend); + + /** Never called. */ + template + [[nodiscard]] static boost::system::result init(Arguments&&... /*arguments*/) noexcept { + return {}; + } + + /** Never called. */ + template + [[nodiscard]] static boost::system::result encrypt( + Arguments&&... /*arguments*/) noexcept { + return {}; + } + + /** Never called. */ + template + [[nodiscard]] static boost::system::result decrypt( + Arguments&&... /*arguments*/) noexcept { + return {}; + } + + /** Never called. */ + template + static void move(Arguments&&... /*arguments*/) noexcept {} + + /** Never called. */ + template + static void reset(Arguments&&... /*arguments*/) noexcept {} +}; + /** * The AES block cipher with keys of `KeySize` bytes on `Backend`, of which `aes128`, `aes192` * and `aes256` are the named forms. diff --git a/include/webcpp/crypto/ciphers/aes256_gcm.hpp b/include/webcpp/crypto/ciphers/aes256_gcm.hpp index 2106c6a1..b1fe98f2 100644 --- a/include/webcpp/crypto/ciphers/aes256_gcm.hpp +++ b/include/webcpp/crypto/ciphers/aes256_gcm.hpp @@ -5,19 +5,16 @@ // https://www.boost.org/LICENSE_1_0.txt) /** - `aes128_gcm` and `aes256_gcm` on the default backend, whose header it includes: natively - OpenSSL when it is linked, else BearSSL; on WebAssembly BearSSL, unless - `WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL` selects OpenSSL on wasip2 or wasip3. + `aes128_gcm` and `aes256_gcm` on AES-GCM's default backend, whose header it includes when the + program links it: natively OpenSSL, on wasip2, wasip3 and Emscripten BearSSL, whatever else the + program links (`default_backend_t`). A program that uses them without linking + the default stops where it calls them, with the Jamfile line that links it and the type that + names another backend, as `gcm>`. On MSVC, wasip2 and wasip3 the source-built OpenSSL is compiled without assembly: AES is table-driven, GHASH is 4-bit tables, there is no AES-NI, and none of it is constant time. - On MSVC the default is OpenSSL all the same, so a program that links OpenSSL there - gets that build. A program that wants BearSSL on those targets defines - `WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL`, or names `gcm>`. - - The MSVC link-time net (`detect_mismatch`) covers the translation units that include this - header; a program that names `aes256<>` through `ciphers/aes.hpp` gets the same choice from - `config.hpp` but no link-time net. + On MSVC the default is OpenSSL all the same, so a program that wants BearSSL there names + `gcm>`. @see "Using webcpp::crypto in your Jamfile", in the guide. */ @@ -28,21 +25,14 @@ #include #include +#include -#ifdef WEBCPP_CRYPTO_DETAIL_DEFAULT_OPENSSL +#if defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_GCM_OPENSSL) && defined(WEBCPP_CRYPTO_HAS_OPENSSL) #include -#else +#elif defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_GCM_BEARSSL) && defined(WEBCPP_CRYPTO_HAS_BEARSSL) #include #endif -// Two files of one program that choose different defaults name two types aes256_gcm: on -// MSVC the link then fails with LNK2038 on this key. -#if defined(_MSC_VER) && defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_OPENSSL) -#pragma detect_mismatch("webcpp_crypto_default_backend", "openssl") -#elif defined(_MSC_VER) -#pragma detect_mismatch("webcpp_crypto_default_backend", "bearssl") -#endif - namespace webcpp::crypto::ciphers { /** AES-128-GCM on the default backend. */ diff --git a/include/webcpp/crypto/ciphers/gcm.hpp b/include/webcpp/crypto/ciphers/gcm.hpp index c3509770..3749d8aa 100644 --- a/include/webcpp/crypto/ciphers/gcm.hpp +++ b/include/webcpp/crypto/ciphers/gcm.hpp @@ -31,6 +31,70 @@ #include #include +namespace webcpp::crypto::detail { + +/** + * What a `ciphers::gcm` stores on a backend whose header does not specialise it: nothing, since + * its engine refuses the backend where the family is called. + */ +template +struct gcm_state {}; + +/** + * GCM's engine on a backend whose header does not specialise it: the family's refusal, which + * names what the program needs (`detail/capabilities.hpp`). Its functions are never called: the + * refusal stops the build where the class is instantiated, and they keep the compiler from + * adding errors of their own after it. + */ +template +struct gcm_engine { + WEBCPP_CRYPTO_DETAIL_REFUSE_GCM(Backend); + + /** Never called. */ + template + [[nodiscard]] static boost::system::result init(Arguments&&... /*arguments*/) noexcept { + return {}; + } + + /** Never called. */ + template + [[nodiscard]] static boost::system::result start(Arguments&&... /*arguments*/) noexcept { + return {}; + } + + /** Never called. */ + template + [[nodiscard]] static boost::system::result run(Arguments&&... /*arguments*/) noexcept { + return {}; + } + + /** Never called. */ + template + [[nodiscard]] static boost::system::result tag(Arguments&&... /*arguments*/) noexcept { + return {}; + } + + /** Never called. */ + template + [[nodiscard]] static boost::system::result check(Arguments&&... /*arguments*/) noexcept { + return {}; + } + + /** Never called. */ + template + static void move(Arguments&&... /*arguments*/) noexcept {} + + /** Never called. */ + template + static void abandon(Arguments&&... /*arguments*/) noexcept {} + + /** Never called. */ + template + static void reset(Arguments&&... /*arguments*/) noexcept {} +}; + +} // namespace webcpp::crypto::detail + namespace webcpp::crypto::ciphers { /** diff --git a/include/webcpp/crypto/config.hpp b/include/webcpp/crypto/config.hpp index 6784b257..d0585364 100644 --- a/include/webcpp/crypto/config.hpp +++ b/include/webcpp/crypto/config.hpp @@ -7,7 +7,8 @@ /** The configuration of webcpp::crypto, which each of its headers includes first: whether it is built without exceptions, whether the target is WebAssembly, the - backends the build links and the default backend. + backends the build links, and the refusal of version 0.1's defines that chose the + default backend, which the target alone now chooses (`detail/defaults.hpp`). @see "Using webcpp::crypto in your Jamfile", in the guide. */ @@ -120,19 +121,6 @@ #undef WEBCPP_CRYPTO_SECP256K1_SMALL_TABLES #endif #undef WEBCPP_CRYPTO_DETAIL_REFERENCE_SMALL_TABLES -/** - Defined by a program to make BearSSL the default backend, on every target, when OpenSSL - is linked as well. -*/ -#define WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL -#undef WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL -/** - Defined by a program to make OpenSSL the default backend, which on wasip2 and wasip3 it is - not without it. Refused on Emscripten, and together with - `WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL`. -*/ -#define WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL -#undef WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL /** Defined by a native program, in its project's requirements beside `/webcpp/crypto//openssl`, to send every allocation of OpenSSL's in the process to a resource of the program's: the program @@ -165,11 +153,13 @@ #if defined(WEBCPP_TARGET_EMSCRIPTEN) && defined(WEBCPP_CRYPTO_HAS_OPENSSL) #error "webcpp::crypto: OpenSSL is not built for Emscripten. In the program's Jamfile, replace /webcpp/crypto//openssl with /third_party//bearssl." #endif -#if defined(WEBCPP_TARGET_EMSCRIPTEN) && defined(WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL) -#error "webcpp::crypto: WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL selects OpenSSL, which is not built for Emscripten. Remove that define, or make it WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL." +// Version 0.1's two defines chose the default backend; the target alone chooses it now +// (design D32), and a define the build ignored would change which code a program runs. +#ifdef WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL +#error "webcpp::crypto: WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL no longer chooses a default. Write the backend in the type where the program wants it, as in ciphers::gcm>." #endif -#if defined(WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL) && defined(WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL) -#error "webcpp::crypto: both WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL and WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL are defined. Keep one." +#ifdef WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL +#error "webcpp::crypto: WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL no longer chooses a default. Write the backend in the type where the program wants it, as in ciphers::gcm>." #endif #if defined(WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE) && defined(WEBCPP_CRYPTO_WEBASSEMBLY) #error "webcpp::crypto: WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE is an option of native programs, and this program is built for WebAssembly. Remove that define from the program's Jamfile." @@ -180,28 +170,6 @@ #endif // clang-format on -// The default backend of the AEADs: the one the program selects; else -// natively the first linked of OpenSSL, BearSSL; else BearSSL, whose header then says that -// no backend is linked when neither is, and that BearSSL is not linked when OpenSSL alone is -// (on WebAssembly, where the program selects OpenSSL with its define). -#ifdef WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL -/** Defined when OpenSSL is the default backend: the program selects it. */ -#define WEBCPP_CRYPTO_DETAIL_DEFAULT_OPENSSL 1 -#elif defined(WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL) -/** Defined when BearSSL is the default backend: the program selects it. */ -#define WEBCPP_CRYPTO_DETAIL_DEFAULT_BEARSSL 1 -#elif !defined(WEBCPP_CRYPTO_WEBASSEMBLY) && defined(WEBCPP_CRYPTO_HAS_OPENSSL) -/** Defined when OpenSSL is the default backend: natively, when it is linked. */ -#define WEBCPP_CRYPTO_DETAIL_DEFAULT_OPENSSL 1 -#else -/** Defined when BearSSL is the default backend: on WebAssembly, or natively without OpenSSL. */ -#define WEBCPP_CRYPTO_DETAIL_DEFAULT_BEARSSL 1 -#if !defined(WEBCPP_CRYPTO_HAS_BEARSSL) && !defined(WEBCPP_CRYPTO_HAS_OPENSSL) -/** Defined when no backend is linked, which BearSSL's header then says. */ -#define WEBCPP_CRYPTO_DETAIL_NONE_LINKED 1 -#endif -#endif - namespace webcpp::crypto::backends { /** BearSSL, built from its sources by `/third_party//bearssl`. */ @@ -217,28 +185,4 @@ struct sodium; } // namespace webcpp::crypto::backends -namespace webcpp::crypto { - -#ifdef WEBCPP_CRYPTO_DETAIL_DEFAULT_OPENSSL -/** - * The default backend, of `ciphers::aes256<>`, `ciphers::gcm>` and - * `ciphers::aes256_gcm`: the one the program selects; else natively OpenSSL when it is linked; - * else BearSSL. - * - * @see "The default backend, and choosing another", in the guide. - */ -using default_backend = backends::openssl; -#else -/** - * The default backend, of `ciphers::aes256<>`, `ciphers::gcm>` and - * `ciphers::aes256_gcm`: the one the program selects; else natively OpenSSL when it is linked; - * else BearSSL. - * - * @see "The default backend, and choosing another", in the guide. - */ -using default_backend = backends::bearssl; -#endif - -} // namespace webcpp::crypto - #endif // WEBCPP_CRYPTO_CONFIG_HPP diff --git a/include/webcpp/crypto/curves/secp256k1.hpp b/include/webcpp/crypto/curves/secp256k1.hpp index c883d9a3..bd674187 100644 --- a/include/webcpp/crypto/curves/secp256k1.hpp +++ b/include/webcpp/crypto/curves/secp256k1.hpp @@ -17,6 +17,7 @@ #include #include +#include #include #include #include // lint-world: the context's randomisation, its purpose @@ -163,7 +164,7 @@ struct tweaked_xonly_key { * * @tparam Backend `backends::secp256k1`, its only backend. */ -template +template > class basic_keypair { static_assert(webcpp::crypto::detail::secp256k1_backend, WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); @@ -441,7 +442,7 @@ using keypair = basic_keypair<>; * @param xonly_key_bytes 32 bytes. * @return Nothing; `invalid_public_key`; `invalid_signature`. */ -template +template > [[nodiscard]] boost::system::result verify_schnorr( std::span signature_bytes, std::span message_bytes, std::span xonly_key_bytes) noexcept { @@ -471,7 +472,7 @@ template * @param public_key_bytes SEC1: 33 bytes, prefix 02 or 03, or 65, prefix 04. * @return Nothing; `invalid_public_key`; `invalid_signature`. */ -template +template > [[nodiscard]] boost::system::result verify_ecdsa( std::span signature_bytes, std::span message_hash, @@ -505,7 +506,7 @@ template * `output_bytes` is shorter than `max_der_size`; `invalid_signature` when r or s is zero or not * below the group order. */ -template +template > [[nodiscard]] boost::system::result to_der( std::span compact_signature, std::span output_bytes) noexcept { @@ -538,7 +539,7 @@ template * @return 64 bytes, r then s; `invalid_signature` for anything that is not strict DER, and for * an r or an s that is zero or not below the group order. */ -template +template > [[nodiscard]] boost::system::result> from_der( std::span der_signature) noexcept { static_assert(webcpp::crypto::detail::secp256k1_backend, @@ -570,7 +571,7 @@ template * @return 64 bytes, r then n - s when s was above half the group order; * `invalid_signature` when r or s is zero or not below the group order. */ -template +template > [[nodiscard]] boost::system::result> normalize_ecdsa( std::span compact_signature) noexcept { static_assert(webcpp::crypto::detail::secp256k1_backend, @@ -601,7 +602,7 @@ template * point's x; `invalid_secret_key` for a tweak not below the group order, or one that gives * no valid key (negligible, but checked). */ -template +template > [[nodiscard]] boost::system::result tweak_xonly( std::span xonly_key_bytes, std::span tweak_bytes) noexcept { diff --git a/include/webcpp/crypto/detail/capabilities.hpp b/include/webcpp/crypto/detail/capabilities.hpp index e87fba44..dad5099f 100644 --- a/include/webcpp/crypto/detail/capabilities.hpp +++ b/include/webcpp/crypto/detail/capabilities.hpp @@ -133,52 +133,85 @@ inline constexpr bool supported` is defined. + * + * @tparam Backend A backend tag of `backends`. + */ +template +inline constexpr bool linked = false; +#ifdef WEBCPP_CRYPTO_HAS_BEARSSL +template <> +inline constexpr bool linked = true; +#endif +#ifdef WEBCPP_CRYPTO_HAS_OPENSSL +template <> +inline constexpr bool linked = true; +#endif +#ifdef WEBCPP_CRYPTO_HAS_CTAES +template <> +inline constexpr bool linked = true; +#endif +#ifdef WEBCPP_CRYPTO_HAS_SECP256K1 +template <> +inline constexpr bool linked = true; +#endif +#ifdef WEBCPP_CRYPTO_HAS_SODIUM +template <> +inline constexpr bool linked = true; +#endif + } // namespace webcpp::crypto::detail // The body of each family's primary engine, which a backend reaches where its // header does not specialise the engine, per target: a backend without the family -// there is refused, naming those that have it; a backend that has it there, whose -// header the program did not include, is told to include it; any other type is no -// backend of the family. +// there is refused, naming those that have it; the default there, not linked, says +// the Jamfile line that links it and the type that names another backend; a backend +// that has it there, whose header the program did not include, is told to include +// it; any other type is no backend of the family. // clang-format off -#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) +#ifdef WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE /** The refusals of the family AES-GCM's primary engine for `Backend`, on native. */ #define WEBCPP_CRYPTO_DETAIL_REFUSE_GCM(Backend) \ static_assert(!std::is_same_v, "webcpp::crypto: bearssl's AES-GCM is in , which the program does not include. Include it, and add /third_party//bearssl to the program's Jamfile."); \ - static_assert(!std::is_same_v, "webcpp::crypto: openssl's AES-GCM is in , which the program does not include. Include it, and add /webcpp/crypto//openssl to the program's Jamfile."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::openssl>, "webcpp::crypto: AES-GCM's default backend on this target is OpenSSL, which is not linked. Add /webcpp/crypto//openssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//openssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::openssl>, "webcpp::crypto: openssl's AES-GCM is in , which the program does not include. Include it, and add /webcpp/crypto//openssl to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no AES-GCM. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no AES-GCM. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ static_assert(!std::is_same_v, "webcpp::crypto: sodium has no AES-GCM. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ - static_assert(::webcpp::crypto::detail::dependent_false, "webcpp::crypto: AES-GCM has no backend of that name. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).") + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: AES-GCM has no backend of that name. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).") #elif defined(WEBCPP_TARGET_WASIP2) /** The refusals of the family AES-GCM's primary engine for `Backend`, on wasip2. */ #define WEBCPP_CRYPTO_DETAIL_REFUSE_GCM(Backend) \ - static_assert(!std::is_same_v, "webcpp::crypto: bearssl's AES-GCM is in , which the program does not include. Include it, and add /third_party//bearssl to the program's Jamfile."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::bearssl>, "webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked. Add /third_party//bearssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::bearssl>, "webcpp::crypto: bearssl's AES-GCM is in , which the program does not include. Include it, and add /third_party//bearssl to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: openssl's AES-GCM is in , which the program does not include. Include it, and add /webcpp/crypto//openssl to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no AES-GCM. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no AES-GCM. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ static_assert(!std::is_same_v, "webcpp::crypto: sodium has no AES-GCM. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ - static_assert(::webcpp::crypto::detail::dependent_false, "webcpp::crypto: AES-GCM has no backend of that name. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).") + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: AES-GCM has no backend of that name. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).") #elif defined(WEBCPP_TARGET_WASIP3) /** The refusals of the family AES-GCM's primary engine for `Backend`, on wasip3. */ #define WEBCPP_CRYPTO_DETAIL_REFUSE_GCM(Backend) \ - static_assert(!std::is_same_v, "webcpp::crypto: bearssl's AES-GCM is in , which the program does not include. Include it, and add /third_party//bearssl to the program's Jamfile."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::bearssl>, "webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked. Add /third_party//bearssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::bearssl>, "webcpp::crypto: bearssl's AES-GCM is in , which the program does not include. Include it, and add /third_party//bearssl to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: openssl's AES-GCM is in , which the program does not include. Include it, and add /webcpp/crypto//openssl to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no AES-GCM. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no AES-GCM. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ static_assert(!std::is_same_v, "webcpp::crypto: sodium has no AES-GCM. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ - static_assert(::webcpp::crypto::detail::dependent_false, "webcpp::crypto: AES-GCM has no backend of that name. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).") + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: AES-GCM has no backend of that name. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).") #elif defined(WEBCPP_TARGET_EMSCRIPTEN) /** The refusals of the family AES-GCM's primary engine for `Backend`, on emscripten. */ #define WEBCPP_CRYPTO_DETAIL_REFUSE_GCM(Backend) \ - static_assert(!std::is_same_v, "webcpp::crypto: bearssl's AES-GCM is in , which the program does not include. Include it, and add /third_party//bearssl to the program's Jamfile."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::bearssl>, "webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked, and the one backend that has it there. Add /third_party//bearssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ;"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::bearssl>, "webcpp::crypto: bearssl's AES-GCM is in , which the program does not include. Include it, and add /third_party//bearssl to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: openssl has no AES-GCM on emscripten. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no AES-GCM. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no AES-GCM. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ static_assert(!std::is_same_v, "webcpp::crypto: sodium has no AES-GCM. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ - static_assert(::webcpp::crypto::detail::dependent_false, "webcpp::crypto: AES-GCM has no backend of that name. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).") + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: AES-GCM has no backend of that name. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).") #endif -#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) +#ifdef WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE /** The refusals of the family AES block cipher's primary engine for `Backend`, on native. */ #define WEBCPP_CRYPTO_DETAIL_REFUSE_AES_BLOCK(Backend) \ static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no AES block cipher. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten)."); \ @@ -186,7 +219,7 @@ inline constexpr bool supported, "webcpp::crypto: ctaes's AES block cipher is in , which the program does not include. Include it, and add /third_party//ctaes to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no AES block cipher. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: sodium has no AES block cipher. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten)."); \ - static_assert(::webcpp::crypto::detail::dependent_false, "webcpp::crypto: AES block cipher has no backend of that name. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten).") + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: AES block cipher has no backend of that name. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten).") #elif defined(WEBCPP_TARGET_WASIP2) /** The refusals of the family AES block cipher's primary engine for `Backend`, on wasip2. */ #define WEBCPP_CRYPTO_DETAIL_REFUSE_AES_BLOCK(Backend) \ @@ -195,7 +228,7 @@ inline constexpr bool supported, "webcpp::crypto: ctaes's AES block cipher is in , which the program does not include. Include it, and add /third_party//ctaes to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no AES block cipher. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: sodium has no AES block cipher. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten)."); \ - static_assert(::webcpp::crypto::detail::dependent_false, "webcpp::crypto: AES block cipher has no backend of that name. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten).") + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: AES block cipher has no backend of that name. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten).") #elif defined(WEBCPP_TARGET_WASIP3) /** The refusals of the family AES block cipher's primary engine for `Backend`, on wasip3. */ #define WEBCPP_CRYPTO_DETAIL_REFUSE_AES_BLOCK(Backend) \ @@ -204,7 +237,7 @@ inline constexpr bool supported, "webcpp::crypto: ctaes's AES block cipher is in , which the program does not include. Include it, and add /third_party//ctaes to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no AES block cipher. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: sodium has no AES block cipher. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten)."); \ - static_assert(::webcpp::crypto::detail::dependent_false, "webcpp::crypto: AES block cipher has no backend of that name. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten).") + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: AES block cipher has no backend of that name. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten).") #elif defined(WEBCPP_TARGET_EMSCRIPTEN) /** The refusals of the family AES block cipher's primary engine for `Backend`, on emscripten. */ #define WEBCPP_CRYPTO_DETAIL_REFUSE_AES_BLOCK(Backend) \ @@ -213,44 +246,48 @@ inline constexpr bool supported, "webcpp::crypto: ctaes's AES block cipher is in , which the program does not include. Include it, and add /third_party//ctaes to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no AES block cipher. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: sodium has no AES block cipher. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten)."); \ - static_assert(::webcpp::crypto::detail::dependent_false, "webcpp::crypto: AES block cipher has no backend of that name. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten).") + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: AES block cipher has no backend of that name. The backends that have it: openssl (native, wasip2, wasip3), ctaes (native, wasip2, wasip3, emscripten).") #endif -#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) +#ifdef WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE /** The refusals of the family secp256k1's primary engine for `Backend`, on native. */ #define WEBCPP_CRYPTO_DETAIL_REFUSE_SECP256K1(Backend) \ static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: openssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v, "webcpp::crypto: secp256k1's secp256k1 is in , which the program does not include. Include it, and add /third_party//secp256k1 to the program's Jamfile."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::secp256k1>, "webcpp::crypto: secp256k1's default backend on this target is libsecp256k1, which is not linked, and the one backend that has it there. Add /third_party//secp256k1 to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//secp256k1 ;"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::secp256k1>, "webcpp::crypto: secp256k1's secp256k1 is in , which the program does not include. Include it, and add /third_party//secp256k1 to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: sodium has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ - static_assert(::webcpp::crypto::detail::dependent_false, "webcpp::crypto: secp256k1 has no backend of that name. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten).") + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: secp256k1 has no backend of that name. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten).") #elif defined(WEBCPP_TARGET_WASIP2) /** The refusals of the family secp256k1's primary engine for `Backend`, on wasip2. */ #define WEBCPP_CRYPTO_DETAIL_REFUSE_SECP256K1(Backend) \ static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: openssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v, "webcpp::crypto: secp256k1's secp256k1 is in , which the program does not include. Include it, and add /third_party//secp256k1 to the program's Jamfile."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::secp256k1>, "webcpp::crypto: secp256k1's default backend on this target is libsecp256k1, which is not linked, and the one backend that has it there. Add /third_party//secp256k1 to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//secp256k1 ;"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::secp256k1>, "webcpp::crypto: secp256k1's secp256k1 is in , which the program does not include. Include it, and add /third_party//secp256k1 to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: sodium has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ - static_assert(::webcpp::crypto::detail::dependent_false, "webcpp::crypto: secp256k1 has no backend of that name. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten).") + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: secp256k1 has no backend of that name. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten).") #elif defined(WEBCPP_TARGET_WASIP3) /** The refusals of the family secp256k1's primary engine for `Backend`, on wasip3. */ #define WEBCPP_CRYPTO_DETAIL_REFUSE_SECP256K1(Backend) \ static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: openssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v, "webcpp::crypto: secp256k1's secp256k1 is in , which the program does not include. Include it, and add /third_party//secp256k1 to the program's Jamfile."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::secp256k1>, "webcpp::crypto: secp256k1's default backend on this target is libsecp256k1, which is not linked, and the one backend that has it there. Add /third_party//secp256k1 to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//secp256k1 ;"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::secp256k1>, "webcpp::crypto: secp256k1's secp256k1 is in , which the program does not include. Include it, and add /third_party//secp256k1 to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: sodium has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ - static_assert(::webcpp::crypto::detail::dependent_false, "webcpp::crypto: secp256k1 has no backend of that name. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten).") + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: secp256k1 has no backend of that name. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten).") #elif defined(WEBCPP_TARGET_EMSCRIPTEN) /** The refusals of the family secp256k1's primary engine for `Backend`, on emscripten. */ #define WEBCPP_CRYPTO_DETAIL_REFUSE_SECP256K1(Backend) \ static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: openssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v, "webcpp::crypto: secp256k1's secp256k1 is in , which the program does not include. Include it, and add /third_party//secp256k1 to the program's Jamfile."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::secp256k1>, "webcpp::crypto: secp256k1's default backend on this target is libsecp256k1, which is not linked, and the one backend that has it there. Add /third_party//secp256k1 to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//secp256k1 ;"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::secp256k1>, "webcpp::crypto: secp256k1's secp256k1 is in , which the program does not include. Include it, and add /third_party//secp256k1 to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: sodium has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ - static_assert(::webcpp::crypto::detail::dependent_false, "webcpp::crypto: secp256k1 has no backend of that name. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten).") + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: secp256k1 has no backend of that name. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten).") #endif // clang-format on diff --git a/include/webcpp/crypto/detail/defaults.hpp b/include/webcpp/crypto/detail/defaults.hpp new file mode 100644 index 00000000..965af4da --- /dev/null +++ b/include/webcpp/crypto/detail/defaults.hpp @@ -0,0 +1,83 @@ +// 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. + +#ifndef WEBCPP_CRYPTO_DETAIL_DEFAULTS_HPP +#define WEBCPP_CRYPTO_DETAIL_DEFAULTS_HPP + +#include + +#include + +namespace webcpp::crypto { + +/** + * The default backend of `Family` on the target being compiled, as its `type`. + * + * One per family and target, chosen by the target alone whatever the program links, + * for the reason doc/tables/crypto.json gives (the guide's "The default backend per + * target"). A family without a default has no `type`; a program names any other + * backend in the type. + * + * @tparam Family A family tag of `families`. + */ +template +struct default_backend_of {}; + +// Each family's default, on the targets where it is that backend. +// clang-format off +#ifdef WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE +/** Defined where OpenSSL is the default of AES-GCM. */ +#define WEBCPP_CRYPTO_DETAIL_DEFAULT_GCM_OPENSSL 1 +/** The default of AES-GCM on native: OpenSSL. */ +template <> +struct default_backend_of { + /** `backends::openssl`. */ + using type = backends::openssl; +}; +#elif defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +/** Defined where BearSSL is the default of AES-GCM. */ +#define WEBCPP_CRYPTO_DETAIL_DEFAULT_GCM_BEARSSL 1 +/** The default of AES-GCM on wasip2, wasip3, emscripten: BearSSL. */ +template <> +struct default_backend_of { + /** `backends::bearssl`. */ + using type = backends::bearssl; +}; +#endif +/** Defined where libsecp256k1 is the default of secp256k1. */ +#define WEBCPP_CRYPTO_DETAIL_DEFAULT_SECP256K1_SECP256K1 1 +/** The default of secp256k1 on native, wasip2, wasip3, emscripten: libsecp256k1. */ +template <> +struct default_backend_of { + /** `backends::secp256k1`. */ + using type = backends::secp256k1; +}; +// clang-format on + +/** + * The default backend of `Family` on the target being compiled (see + * @ref default_backend_of). + * + * @tparam Family A family tag of `families` that has a default. + */ +template +using default_backend_t = default_backend_of::type; + +/** + * The default backend of AES-GCM, version 0.1's name, which `aes128_gcm`, + * `aes256_gcm` and the AES block cipher's `aes256<>` take: natively OpenSSL, on + * WebAssembly BearSSL. + * + * @see "The default backend per target", in the guide. + */ +using default_backend = default_backend_t; + +} // namespace webcpp::crypto + +#endif // WEBCPP_CRYPTO_DETAIL_DEFAULTS_HPP diff --git a/include/webcpp/crypto/detail/engines.hpp b/include/webcpp/crypto/detail/engines.hpp index c64efe05..71b286f2 100644 --- a/include/webcpp/crypto/detail/engines.hpp +++ b/include/webcpp/crypto/detail/engines.hpp @@ -19,10 +19,12 @@ inline constexpr bool dependent_false = false; /** * What a backend's header specialises, per algorithm: a state, which an object stores and - * which never refuses, and an engine, used only inside the algorithm's member functions, - * whose specialisation for a backend without the algorithm holds the `static_assert` that - * names the backends that have it. A backend whose header is not included leaves both - * undefined, and the compiler names the specialisation it lacks. + * which never refuses, and an engine, used only inside the algorithm's member functions. The + * family's header defines both primaries: an empty state, and an engine whose body is the + * family's generated refusal (`detail/capabilities.hpp`), which a backend reaches where its + * header does not specialise the engine: one without the algorithm is refused, naming the + * backends that have it; the default, not linked, says the Jamfile line that links it and the + * type that names another backend; one whose header is not included is told to include it. * * Tip: `ciphers::gcm>` reads * `ciphers::aes256::key_size`, which instantiates the class and its members' diff --git a/test/Jamfile b/test/Jamfile index 5b584143..b0cc32cb 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -25,21 +25,21 @@ webcpp.headers-alone crypto : ../include : crypto.hpp crypto/config.hpp crypto/random_device.hpp crypto/detail/declassify.hpp crypto/detail/engines.hpp crypto/detail/entropy.hpp crypto/detail/limits.hpp crypto/detail/windows.hpp crypto/detail/wipe.hpp crypto/secret.hpp crypto/supports.hpp - crypto/detail/capabilities.hpp ; + crypto/detail/capabilities.hpp crypto/detail/defaults.hpp ; # The backend BearSSL's header and the default backend's, with BearSSL linked, # on every target. webcpp.headers-alone crypto : ../include : crypto/ciphers/aes256_gcm.hpp crypto/backends/bearssl.hpp : /third_party//bearssl ; -# The backend OpenSSL's header, with OpenSSL linked and selected; BearSSL, +# The backend OpenSSL's header, with OpenSSL linked; BearSSL, # ctaes, libsecp256k1 and libsodium are linked too, so that every public # header compiles with these options (the lint's aggregate translation unit, # tools/lint/compile_commands.py). webcpp.headers-alone crypto : ../include : crypto/backends/openssl.hpp : /webcpp/crypto//openssl /third_party//bearssl /third_party//ctaes /third_party//secp256k1 - /third_party//sodium WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL + /third_party//sodium : native wasip2 wasip3 ; # The backend ctaes's header alone, with ctaes linked, on every target. webcpp.headers-alone crypto : ../include : crypto/backends/ctaes.hpp @@ -113,59 +113,53 @@ webcpp.compile-fail openssl_named_c_on_emscripten : openssl_named_c_test.c build-project msvc ; build-project openssl_memory ; -# The default backend (spec section 5), one combination of linked and selected -# backends per program, each on the targets where its answer holds. -webcpp.compile default_backend_none : default_backend_test.cpp - : WEBCPP_TEST_CRYPTO_EXPECT_NONE_LINKED ; -webcpp.compile default_backend_bearssl_linked : default_backend_test.cpp +# Every family's default backend per target (design D32), the same whatever +# the program links and defines: every backend of the target linked, none, +# each alone, and the defines of the profiles and overrides of the plan's +# first draft, which change nothing. +webcpp.compile default_backend_all_linked : default_backend_test.cpp + : WEBCPP_CRYPTO_HAS_BEARSSL=1 WEBCPP_CRYPTO_HAS_OPENSSL=1 + WEBCPP_CRYPTO_HAS_CTAES=1 WEBCPP_CRYPTO_HAS_SECP256K1=1 + WEBCPP_CRYPTO_HAS_SODIUM=1 + : native wasip2 wasip3 ; +webcpp.compile default_backend_all_linked_emscripten : default_backend_test.cpp + : WEBCPP_CRYPTO_HAS_BEARSSL=1 WEBCPP_CRYPTO_HAS_CTAES=1 + WEBCPP_CRYPTO_HAS_SECP256K1=1 WEBCPP_CRYPTO_HAS_SODIUM=1 + : emscripten ; +webcpp.compile default_backend_none_linked : default_backend_test.cpp ; +webcpp.compile default_backend_bearssl_alone : default_backend_test.cpp : WEBCPP_CRYPTO_HAS_BEARSSL=1 ; -webcpp.compile default_backend_bearssl_selected : default_backend_test.cpp - : WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL ; -webcpp.compile default_backend_openssl_linked : default_backend_test.cpp - : WEBCPP_CRYPTO_HAS_OPENSSL=1 WEBCPP_TEST_CRYPTO_EXPECT_OPENSSL : native ; -webcpp.compile default_backend_openssl_linked_wasi : default_backend_test.cpp - : WEBCPP_CRYPTO_HAS_OPENSSL=1 : wasip2 wasip3 ; -webcpp.compile default_backend_both_linked : default_backend_test.cpp - : WEBCPP_CRYPTO_HAS_OPENSSL=1 WEBCPP_CRYPTO_HAS_BEARSSL=1 - WEBCPP_TEST_CRYPTO_EXPECT_OPENSSL : native ; -webcpp.compile default_backend_both_linked_wasi : default_backend_test.cpp - : WEBCPP_CRYPTO_HAS_OPENSSL=1 WEBCPP_CRYPTO_HAS_BEARSSL=1 : wasip2 wasip3 ; -webcpp.compile default_backend_both_bearssl_selected : default_backend_test.cpp +webcpp.compile default_backend_openssl_alone : default_backend_test.cpp + : WEBCPP_CRYPTO_HAS_OPENSSL=1 : native wasip2 wasip3 ; +webcpp.compile default_backend_ctaes_alone : default_backend_test.cpp + : WEBCPP_CRYPTO_HAS_CTAES=1 ; +webcpp.compile default_backend_secp256k1_alone : default_backend_test.cpp + : WEBCPP_CRYPTO_HAS_SECP256K1=1 ; +webcpp.compile default_backend_sodium_alone : default_backend_test.cpp + : WEBCPP_CRYPTO_HAS_SODIUM=1 ; +webcpp.compile default_backend_former_defines : default_backend_test.cpp + : WEBCPP_CRYPTO_HAS_BEARSSL=1 WEBCPP_CRYPTO_PROFILE_FASTEST + WEBCPP_PROFILE_SMALLEST WEBCPP_CRYPTO_DEFAULT_BACKEND_GCM_BEARSSL ; + +# aes128_gcm, aes256_gcm and aes256<> name AES-GCM's default backend, OpenSSL +# natively and BearSSL on WebAssembly, whatever is linked: checked against +# stand-ins for the backends' headers (support/fake_backends), which the test +# includes first, under the real headers' guards. +webcpp.compile default_selection_both : default_selection_test.cpp : WEBCPP_CRYPTO_HAS_OPENSSL=1 WEBCPP_CRYPTO_HAS_BEARSSL=1 - WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL : native ; -webcpp.compile default_backend_openssl_selected : default_backend_test.cpp - : WEBCPP_CRYPTO_HAS_OPENSSL=1 WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL - WEBCPP_TEST_CRYPTO_EXPECT_OPENSSL : native wasip2 wasip3 ; - -# aes128_gcm, aes256_gcm and aes256<> name the default backend (spec section 5), -# checked from the defines alone against stand-ins for the backends' headers -# (support/fake_backends), which the test includes first, under the real -# headers' guards. -webcpp.compile default_selection_openssl : default_selection_test.cpp - : WEBCPP_CRYPTO_HAS_OPENSSL=1 WEBCPP_CRYPTO_HAS_BEARSSL=1 - WEBCPP_TEST_CRYPTO_EXPECT_OPENSSL : native ; + : native wasip2 wasip3 ; webcpp.compile default_selection_openssl_alone : default_selection_test.cpp - : WEBCPP_CRYPTO_HAS_OPENSSL=1 WEBCPP_TEST_CRYPTO_EXPECT_OPENSSL : native ; -webcpp.compile default_selection_both_wasm : default_selection_test.cpp - : WEBCPP_CRYPTO_HAS_OPENSSL=1 WEBCPP_CRYPTO_HAS_BEARSSL=1 : wasip2 wasip3 ; + : WEBCPP_CRYPTO_HAS_OPENSSL=1 : native wasip2 wasip3 ; webcpp.compile default_selection_bearssl : default_selection_test.cpp : WEBCPP_CRYPTO_HAS_BEARSSL=1 ; -webcpp.compile default_selection_bearssl_selected : default_selection_test.cpp - : WEBCPP_CRYPTO_HAS_OPENSSL=1 WEBCPP_CRYPTO_HAS_BEARSSL=1 - WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL : native wasip2 wasip3 ; -webcpp.compile default_selection_openssl_selected : default_selection_test.cpp - : WEBCPP_CRYPTO_HAS_OPENSSL=1 WEBCPP_CRYPTO_HAS_BEARSSL=1 - WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL WEBCPP_TEST_CRYPTO_EXPECT_OPENSSL - : native wasip2 wasip3 ; # crypto.hpp's branch for libsecp256k1, which headers-alone, without the # library, leaves out. webcpp.compile crypto_secp256k1 : crypto_secp256k1_test.cpp : /third_party//secp256k1 ; -# crypto.hpp with OpenSSL alone linked and BearSSL the default: no -# aes256_gcm.hpp. +# crypto.hpp with OpenSSL alone linked, where on WASI BearSSL stays the +# default: the program names OpenSSL in the type. crypto-run crypto_openssl_alone : crypto_openssl_alone_test.cpp - : /webcpp/crypto//openssl WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL - : native wasip2 wasip3 ; + : /webcpp/crypto//openssl : native wasip2 wasip3 ; crypto-run secp256k1 : secp256k1_test.cpp : /third_party//secp256k1 ; crypto-run secp256k1_allocation : secp256k1_allocation_test.cpp : /third_party//secp256k1 ; @@ -240,17 +234,12 @@ crypto-run openssl_error_queue : openssl_error_queue_test.cpp crypto-run gcm_openssl_threads : gcm_openssl_threads_test.cpp : /webcpp/crypto//openssl multi : native ; -# The default backend with the real backends. +# AES-GCM's default with the real backends, whatever else is linked: natively +# OpenSSL, on MSVC too; on WebAssembly BearSSL. crypto-run default_both : default_both_test.cpp : /third_party//bearssl /webcpp/crypto//openssl : native ; -crypto-run default_openssl_wasm : default_openssl_wasm_test.cpp - : /third_party//bearssl /webcpp/crypto//openssl - WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL : wasip2 wasip3 ; -crypto-run default_selected : default_selected_test.cpp - : /third_party//bearssl /webcpp/crypto//openssl - WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL : native wasip2 wasip3 ; crypto-run default_bearssl : default_bearssl_test.cpp - : /third_party//bearssl ; + : /third_party//bearssl : wasip2 wasip3 emscripten ; crypto-run default_both_wasm : default_both_wasm_test.cpp : /third_party//bearssl /webcpp/crypto//openssl : wasip2 wasip3 ; @@ -311,14 +300,13 @@ crypto-run windows_h_after : windows_h_after_test.cpp # so that the ordinary lanes and clang-tidy read the documentation's code; the # fixtures that must fail are left to that test. webcpp.compile doc_web_app : ../../../tools/test/fixtures/crypto_jamfiles/web/app.cpp - : /third_party//bearssl ; + : /third_party//bearssl : wasip2 wasip3 emscripten ; webcpp.compile doc_server_app : ../../../tools/test/fixtures/crypto_jamfiles/server/app.cpp : /webcpp/crypto//openssl : native ; -webcpp.compile doc_both_bearssl_default_app - : ../../../tools/test/fixtures/crypto_jamfiles/both_bearssl_default/app.cpp - : /webcpp/crypto//openssl /third_party//bearssl - WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL : native wasip2 wasip3 ; +webcpp.compile doc_both_bearssl_named_app + : ../../../tools/test/fixtures/crypto_jamfiles/both_bearssl_named/app.cpp + : /webcpp/crypto//openssl /third_party//bearssl : native wasip2 wasip3 ; webcpp.compile doc_block : ../../../tools/test/fixtures/crypto_jamfiles/block/block.cpp : /third_party//ctaes ; webcpp.compile doc_encrypt_and_sign diff --git a/test/crypto_openssl_alone_test.cpp b/test/crypto_openssl_alone_test.cpp index 412952f6..10cc9dc9 100644 --- a/test/crypto_openssl_alone_test.cpp +++ b/test/crypto_openssl_alone_test.cpp @@ -4,10 +4,10 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// in a program that links OpenSSL alone while BearSSL is the default (here -// selected by WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL, as WebAssembly's default is): the header -// leaves out aes256_gcm.hpp, whose default backend is not linked, and the program seals with -// the type that names OpenSSL. +// in a program that links OpenSSL alone: the header compiles on every +// target that builds OpenSSL, aes256_gcm.hpp included, whose default on WASI, BearSSL, is not +// linked and refuses only where it is called, and the program seals with the type that names +// OpenSSL. #include #include diff --git a/test/default_backend_test.cpp b/test/default_backend_test.cpp index 17f3cc91..4fceab44 100644 --- a/test/default_backend_test.cpp +++ b/test/default_backend_test.cpp @@ -4,37 +4,54 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// chooses the default backend as spec section 5 does: the one -// the program selects; else natively the first linked of OpenSSL and BearSSL; else -// BearSSL, with WEBCPP_CRYPTO_DETAIL_NONE_LINKED when neither is linked. test/Jamfile -// builds this file once per combination, each on the targets where its answer holds, and -// tells it the answer through WEBCPP_TEST_CRYPTO_EXPECT_OPENSSL (else BearSSL) and -// WEBCPP_TEST_CRYPTO_EXPECT_NONE_LINKED. +// Every family's default backend on the target being compiled (design D32): one per family and +// target, whatever the program links and whatever it defines. test/Jamfile builds this file with +// every backend of the target linked, with none, with each alone, and with the defines of the +// profiles and of a per-family override, which version 0.2 does not have; every build asserts +// the same defaults. -#include +#include #include namespace crypto = webcpp::crypto; +namespace backends = webcpp::crypto::backends; +namespace families = webcpp::crypto::families; -#if defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_OPENSSL) == defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_BEARSSL) -#error "exactly one of WEBCPP_CRYPTO_DETAIL_DEFAULT_OPENSSL and _BEARSSL is defined" -#endif +namespace { + +/** Whether `Family` has a default: `default_backend_t` names a type. */ +template +inline constexpr bool has_default = false; + +/** A family with a default. */ +template +inline constexpr bool has_default>> = true; -#ifdef WEBCPP_TEST_CRYPTO_EXPECT_OPENSSL -#ifndef WEBCPP_CRYPTO_DETAIL_DEFAULT_OPENSSL -#error "the default backend is not OpenSSL" +} // namespace + +// AES-GCM: natively OpenSSL, whatever is linked (the owner's answer Q2); on WebAssembly BearSSL. +#ifdef WEBCPP_CRYPTO_WEBASSEMBLY +using gcm_default = backends::bearssl; +#if !defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_GCM_BEARSSL) || \ + defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_GCM_OPENSSL) +#error "aes256_gcm.hpp is told to include another header than BearSSL's" #endif -static_assert(std::is_same_v, - "default_backend is not OpenSSL"); #else -#ifndef WEBCPP_CRYPTO_DETAIL_DEFAULT_BEARSSL -#error "the default backend is not BearSSL" +using gcm_default = backends::openssl; +#if !defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_GCM_OPENSSL) || \ + defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_GCM_BEARSSL) +#error "aes256_gcm.hpp is told to include another header than OpenSSL's" #endif -static_assert(std::is_same_v, - "default_backend is not BearSSL"); #endif +static_assert(std::is_same_v, gcm_default>); +static_assert(std::is_same_v); +static_assert(crypto::detail::supported); -#if defined(WEBCPP_TEST_CRYPTO_EXPECT_NONE_LINKED) != defined(WEBCPP_CRYPTO_DETAIL_NONE_LINKED) -#error "WEBCPP_CRYPTO_DETAIL_NONE_LINKED is not defined exactly when no backend is linked" -#endif +// The AES block cipher: none (its aes256<> takes AES-GCM's as its argument). +static_assert(!has_default); + +// secp256k1: libsecp256k1, the only backend, on every target. +static_assert(std::is_same_v, backends::secp256k1>); +static_assert(crypto::detail::supported>); diff --git a/test/default_bearssl_test.cpp b/test/default_bearssl_test.cpp index bd791d7d..659667ba 100644 --- a/test/default_bearssl_test.cpp +++ b/test/default_bearssl_test.cpp @@ -4,7 +4,8 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// With BearSSL alone, BearSSL is the default, on every target. +// On WebAssembly, with BearSSL alone, BearSSL is AES-GCM's default (design D32); natively +// OpenSSL is, and test/messages/gcm_default_openssl_not_linked stops the same program. #include #include diff --git a/test/default_both_test.cpp b/test/default_both_test.cpp index f7f9e7fd..a0bc1ba8 100644 --- a/test/default_both_test.cpp +++ b/test/default_both_test.cpp @@ -4,8 +4,7 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// Natively, with OpenSSL and BearSSL linked, OpenSSL is the default (spec section 5), on MSVC -// too. +// Natively, with OpenSSL and BearSSL linked, OpenSSL is the default (design D32), on MSVC too. #include #include diff --git a/test/default_both_wasm_test.cpp b/test/default_both_wasm_test.cpp index 47d354cb..f586f37d 100644 --- a/test/default_both_wasm_test.cpp +++ b/test/default_both_wasm_test.cpp @@ -5,7 +5,7 @@ // https://www.boost.org/LICENSE_1_0.txt) // On wasip2 and wasip3, with OpenSSL and BearSSL linked, BearSSL is the default: OpenSSL is -// never the default on WebAssembly unless selected (spec section 5). +// never the default on WebAssembly (design D32). #include #include diff --git a/test/default_openssl_wasm_test.cpp b/test/default_openssl_wasm_test.cpp deleted file mode 100644 index 54820de5..00000000 --- a/test/default_openssl_wasm_test.cpp +++ /dev/null @@ -1,20 +0,0 @@ -// 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) - -// On wasip2 and wasip3, with both linked and WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL defined, -// OpenSSL is the default. - -#include -#include - -#include - -int main() { - BOOST_TEST_EQ(webcpp::crypto::ciphers::aes256_gcm::backend_type::name, "openssl"); - BOOST_TEST_EQ(webcpp::crypto::ciphers::aes128_gcm::backend_type::name, "openssl"); - BOOST_TEST_EQ(webcpp::crypto::ciphers::aes256<>::backend_type::name, "openssl"); - return webcpp::test::exit_status(boost::report_errors()); -} diff --git a/test/default_selected_test.cpp b/test/default_selected_test.cpp deleted file mode 100644 index 4436a2cc..00000000 --- a/test/default_selected_test.cpp +++ /dev/null @@ -1,20 +0,0 @@ -// 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) - -// With OpenSSL and BearSSL linked and WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL defined, BearSSL is -// the default, on every target. - -#include -#include - -#include - -int main() { - BOOST_TEST_EQ(webcpp::crypto::ciphers::aes256_gcm::backend_type::name, "bearssl"); - BOOST_TEST_EQ(webcpp::crypto::ciphers::aes128_gcm::backend_type::name, "bearssl"); - BOOST_TEST_EQ(webcpp::crypto::ciphers::aes256<>::backend_type::name, "bearssl"); - return webcpp::test::exit_status(boost::report_errors()); -} diff --git a/test/default_selection_test.cpp b/test/default_selection_test.cpp index 7d5a57c7..73f34700 100644 --- a/test/default_selection_test.cpp +++ b/test/default_selection_test.cpp @@ -4,12 +4,11 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// The types aes128_gcm, aes256_gcm and aes256<> name, from the defines alone (spec section 5): -// test/Jamfile builds this file once per combination of linked and selected backends, and -// tells it the answer through WEBCPP_TEST_CRYPTO_EXPECT_OPENSSL (else BearSSL). The backends' -// headers are stand-ins from test/support/fake_backends, included first under the real -// headers' guards, so nothing here needs a real backend, and nothing is instantiated: the -// aliases are only named. +// The types aes128_gcm, aes256_gcm and aes256<> name: AES-GCM's default backend, natively +// OpenSSL and on WebAssembly BearSSL, whatever is linked (design D32). test/Jamfile builds this +// file once per combination of linked backends. The backends' headers are stand-ins from +// test/support/fake_backends, included first under the real headers' guards, so nothing here +// needs a real backend, and nothing is instantiated: the aliases are only named. // clang-format off #include "support/fake_backends/webcpp/crypto/backends/bearssl.hpp" @@ -26,10 +25,10 @@ namespace crypto = webcpp::crypto; -#ifdef WEBCPP_TEST_CRYPTO_EXPECT_OPENSSL -using expected = crypto::backends::openssl; -#else +#ifdef WEBCPP_CRYPTO_WEBASSEMBLY using expected = crypto::backends::bearssl; +#else +using expected = crypto::backends::openssl; #endif static_assert(std::is_same_v); diff --git a/test/messages/Jamfile b/test/messages/Jamfile index 3f1b778d..7783c628 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -8,7 +8,8 @@ # directory's Jamfile gives its case the requirements that raise the message, # and nothing else. -build-project two_defaults ; +build-project default_selected ; +build-project default_openssl_wasm ; build-project openssl_on_wasi ; build-project openssl_not_linked ; build-project openssl_old ; @@ -16,7 +17,7 @@ build-project ctaes_not_linked ; build-project gcm_on_ctaes ; build-project secp256k1_not_linked ; build-project no_backend_wasm ; -build-project no_backend_native ; +build-project gcm_default_openssl_not_linked ; build-project bearssl_not_linked ; build-project openssl_only_on_wasi ; build-project aes_on_bearssl ; diff --git a/test/messages/bearssl_not_linked/Jamfile b/test/messages/bearssl_not_linked/Jamfile index d61c560a..814f3902 100644 --- a/test/messages/bearssl_not_linked/Jamfile +++ b/test/messages/bearssl_not_linked/Jamfile @@ -8,5 +8,4 @@ project : requirements /webcpp/crypto//crypto ; import webcpp ; -webcpp.compile-diagnostic bearssl_not_linked : bearssl_not_linked.cpp - : WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL : native wasip2 ; +webcpp.compile-diagnostic bearssl_not_linked : bearssl_not_linked.cpp : : native wasip2 ; diff --git a/test/messages/bearssl_not_linked/bearssl_not_linked.cpp b/test/messages/bearssl_not_linked/bearssl_not_linked.cpp index 4822d8fd..526752f7 100644 --- a/test/messages/bearssl_not_linked/bearssl_not_linked.cpp +++ b/test/messages/bearssl_not_linked/bearssl_not_linked.cpp @@ -4,13 +4,18 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// A program that selects BearSSL without linking it stops with the instruction to add it -// (spec section 4.3). +// A program that names BearSSL in the type and does not link it stops at the backend's header +// with the instruction to add it (spec section 4.3). // clang-format off -// expected-error@webcpp/crypto/backends/bearssl.hpp:* {{webcpp::crypto: the backend BearSSL is used and not linked. In the program's Jamfile, add /third_party//bearssl beside /webcpp/crypto//crypto, or, with /webcpp/crypto//openssl linked, select OpenSSL with WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL. (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)}} +// expected-error@webcpp/crypto/backends/bearssl.hpp:* {{webcpp::crypto: the backend BearSSL is used and not linked. In the program's Jamfile, add /third_party//bearssl beside /webcpp/crypto//crypto. (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)}} // clang-format on #include +#include +#include + +webcpp::crypto::ciphers::gcm>* + unused = nullptr; int main() { return 0; diff --git a/test/messages/two_defaults/Jamfile b/test/messages/default_openssl_wasm/Jamfile similarity index 61% rename from test/messages/two_defaults/Jamfile rename to test/messages/default_openssl_wasm/Jamfile index ec1cdc49..7c0e86b3 100644 --- a/test/messages/two_defaults/Jamfile +++ b/test/messages/default_openssl_wasm/Jamfile @@ -8,6 +8,5 @@ project : requirements /webcpp/crypto//crypto ; import webcpp ; -webcpp.compile-diagnostic two_defaults : two_defaults.cpp - : WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL - : native ; +webcpp.compile-diagnostic default_openssl_wasm : default_openssl_wasm.cpp + : WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL : native wasip2 wasip3 ; diff --git a/test/messages/default_openssl_wasm/default_openssl_wasm.cpp b/test/messages/default_openssl_wasm/default_openssl_wasm.cpp new file mode 100644 index 00000000..0e76d52c --- /dev/null +++ b/test/messages/default_openssl_wasm/default_openssl_wasm.cpp @@ -0,0 +1,18 @@ +// 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) + +// Version 0.1's WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL chose the default backend; the target alone +// chooses it now (design D32), so the define stops the build with the type to write, rather than +// change silently which code the program runs (the owner's answer Q3), on every target. + +// clang-format off +// expected-error@webcpp/crypto/config.hpp:* {{webcpp::crypto: WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL no longer chooses a default. Write the backend in the type where the program wants it, as in ciphers::gcm>.}} +// clang-format on +#include + +int main() { + return 0; +} diff --git a/test/messages/default_selected/Jamfile b/test/messages/default_selected/Jamfile new file mode 100644 index 00000000..f6055c7b --- /dev/null +++ b/test/messages/default_selected/Jamfile @@ -0,0 +1,12 @@ +# 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 ; + +webcpp.compile-diagnostic default_selected : default_selected.cpp + : WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL : native wasip2 wasip3 ; diff --git a/test/messages/default_selected/default_selected.cpp b/test/messages/default_selected/default_selected.cpp new file mode 100644 index 00000000..3ddd57c4 --- /dev/null +++ b/test/messages/default_selected/default_selected.cpp @@ -0,0 +1,18 @@ +// 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) + +// Version 0.1's WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL chose the default backend; the target alone +// chooses it now (design D32), so the define stops the build with the type to write, rather than +// change silently which code the program runs (the owner's answer Q3), on every target. + +// clang-format off +// expected-error@webcpp/crypto/config.hpp:* {{webcpp::crypto: WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL no longer chooses a default. Write the backend in the type where the program wants it, as in ciphers::gcm>.}} +// clang-format on +#include + +int main() { + return 0; +} diff --git a/test/messages/no_backend_native/Jamfile b/test/messages/gcm_default_openssl_not_linked/Jamfile similarity index 65% rename from test/messages/no_backend_native/Jamfile rename to test/messages/gcm_default_openssl_not_linked/Jamfile index d9a4db02..73abfe9d 100644 --- a/test/messages/no_backend_native/Jamfile +++ b/test/messages/gcm_default_openssl_not_linked/Jamfile @@ -8,4 +8,5 @@ project : requirements /webcpp/crypto//crypto ; import webcpp ; -webcpp.compile-diagnostic no_backend_native : no_backend_native.cpp : : native ; +webcpp.compile-diagnostic gcm_default_openssl_not_linked : gcm_default_openssl_not_linked.cpp + : /third_party//bearssl : native ; diff --git a/test/messages/gcm_default_openssl_not_linked/gcm_default_openssl_not_linked.cpp b/test/messages/gcm_default_openssl_not_linked/gcm_default_openssl_not_linked.cpp new file mode 100644 index 00000000..57378b53 --- /dev/null +++ b/test/messages/gcm_default_openssl_not_linked/gcm_default_openssl_not_linked.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) + +// A native program that links BearSSL alone and calls aes256_gcm, whose default backend natively +// is OpenSSL whatever is linked (design D32, the owner's answer Q2), stops where it calls it, +// with the line that links OpenSSL and the type that names BearSSL. + +// clang-format off +// expected-error@webcpp/crypto/ciphers/gcm.hpp:* {{webcpp::crypto: AES-GCM's default backend on this target is OpenSSL, which is not linked. Add /webcpp/crypto//openssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//openssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).}} +// clang-format on + +#include + +#include +#include + +int main() { + std::array const key{}; + return webcpp::crypto::ciphers::aes256_gcm::make(key) ? 0 : 1; +} diff --git a/test/messages/no_backend_native/no_backend_native.cpp b/test/messages/no_backend_native/no_backend_native.cpp deleted file mode 100644 index 3746bfae..00000000 --- a/test/messages/no_backend_native/no_backend_native.cpp +++ /dev/null @@ -1,17 +0,0 @@ -// 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 native program that links no backend and uses the default's header stops with the -// instruction to add OpenSSL or BearSSL (spec section 4.3, the second row). - -// clang-format off -// expected-error@webcpp/crypto/backends/bearssl.hpp:* {{webcpp::crypto: no backend is linked. In the program's Jamfile, add /webcpp/crypto//openssl (OpenSSL built from source) or /third_party//bearssl (built from source) beside /webcpp/crypto//crypto, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//openssl ; (without b2: define WEBCPP_CRYPTO_HAS_OPENSSL=1 and link libcrypto, or define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)}} -// clang-format on -#include - -int main() { - return 0; -} diff --git a/test/messages/no_backend_wasm/no_backend_wasm.cpp b/test/messages/no_backend_wasm/no_backend_wasm.cpp index 88f60e7c..f40d86cb 100644 --- a/test/messages/no_backend_wasm/no_backend_wasm.cpp +++ b/test/messages/no_backend_wasm/no_backend_wasm.cpp @@ -4,14 +4,20 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// A program for WebAssembly that links no backend and uses the default's header stops -// with the instruction to add BearSSL (spec section 4.3, the first row). +// A program for wasip2 or wasip3 that links no backend and calls aes256_gcm, whose default +// backend on WebAssembly is BearSSL, stops where it calls it with the line that links BearSSL +// (design D32). // clang-format off -// expected-error@webcpp/crypto/backends/bearssl.hpp:* {{webcpp::crypto: no backend is linked. On WebAssembly the backend is BearSSL: in the program's Jamfile, add /third_party//bearssl beside /webcpp/crypto//crypto, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ; (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)}} +// expected-error@webcpp/crypto/ciphers/gcm.hpp:* {{webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked. Add /third_party//bearssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).}} // clang-format on -#include + +#include + +#include +#include int main() { - return 0; + std::array const key{}; + return webcpp::crypto::ciphers::aes256_gcm::make(key) ? 0 : 1; } diff --git a/test/messages/openssl_not_linked/Jamfile b/test/messages/openssl_not_linked/Jamfile index f56a2722..b6b84b09 100644 --- a/test/messages/openssl_not_linked/Jamfile +++ b/test/messages/openssl_not_linked/Jamfile @@ -8,5 +8,4 @@ project : requirements /webcpp/crypto//crypto ; import webcpp ; -webcpp.compile-diagnostic openssl_not_linked : openssl_not_linked.cpp - : WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL : native wasip2 ; +webcpp.compile-diagnostic openssl_not_linked : openssl_not_linked.cpp : : native wasip2 ; diff --git a/test/messages/openssl_not_linked/openssl_not_linked.cpp b/test/messages/openssl_not_linked/openssl_not_linked.cpp index c6814abd..dcb54918 100644 --- a/test/messages/openssl_not_linked/openssl_not_linked.cpp +++ b/test/messages/openssl_not_linked/openssl_not_linked.cpp @@ -4,13 +4,18 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// A program that selects OpenSSL and does not link it stops with the instruction to add -// /webcpp/crypto//openssl (spec section 4.3). +// A program that names OpenSSL in the type and does not link it stops at the backend's header +// with the instruction to add /webcpp/crypto//openssl (spec section 4.3). // clang-format off // expected-error@webcpp/crypto/backends/openssl.hpp:* {{webcpp::crypto: the backend OpenSSL is used and not linked. In the program's Jamfile, add /webcpp/crypto//openssl beside /webcpp/crypto//crypto. (without b2: define WEBCPP_CRYPTO_HAS_OPENSSL=1 and link libcrypto)}} // clang-format on #include +#include +#include + +webcpp::crypto::ciphers::gcm>* + unused = nullptr; int main() { return 0; diff --git a/test/messages/openssl_on_wasi/Jamfile b/test/messages/openssl_on_wasi/Jamfile index e036363a..f7bf4e4e 100644 --- a/test/messages/openssl_on_wasi/Jamfile +++ b/test/messages/openssl_on_wasi/Jamfile @@ -9,7 +9,6 @@ project : requirements /webcpp/crypto//crypto ; import webcpp ; # OpenSSL is a backend on wasip2 and wasip3, where the provider builds it: -# config.hpp refuses it on Emscripten alone. +# config.hpp refuses it on Emscripten alone. BearSSL stays the default. webcpp.compile openssl_on_wasi : openssl_on_wasi.cpp - : WEBCPP_CRYPTO_HAS_OPENSSL=1 WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL - : wasip2 wasip3 ; + : WEBCPP_CRYPTO_HAS_OPENSSL=1 : wasip2 wasip3 ; diff --git a/test/messages/openssl_on_wasi/openssl_on_wasi.cpp b/test/messages/openssl_on_wasi/openssl_on_wasi.cpp index d2100daa..e52cadb3 100644 --- a/test/messages/openssl_on_wasi/openssl_on_wasi.cpp +++ b/test/messages/openssl_on_wasi/openssl_on_wasi.cpp @@ -4,15 +4,25 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// A program for wasip2 or wasip3 that links OpenSSL and selects it compiles: OpenSSL is -// refused on Emscripten alone, and the program's selection is the default backend. +// A program for wasip2 or wasip3 that links OpenSSL compiles, and names it in the type: OpenSSL +// is refused on Emscripten alone, and AES-GCM's default there stays BearSSL (design D32). -#include +#include +#include +#include +#include #include -static_assert(std::is_same_v, - "the program's selection is the default backend"); +namespace crypto = webcpp::crypto; + +static_assert( + crypto::supports_v>, + crypto::backends::openssl>, + "OpenSSL has AES-GCM on WASI"); +static_assert( + std::is_same_v, crypto::backends::bearssl>, + "linking OpenSSL leaves BearSSL the default"); int main() { return 0; diff --git a/test/messages/openssl_only_on_wasi/openssl_only_on_wasi.cpp b/test/messages/openssl_only_on_wasi/openssl_only_on_wasi.cpp index b74822c4..80c2c8ad 100644 --- a/test/messages/openssl_only_on_wasi/openssl_only_on_wasi.cpp +++ b/test/messages/openssl_only_on_wasi/openssl_only_on_wasi.cpp @@ -4,15 +4,20 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// A program for wasip2 or wasip3 that links OpenSSL alone and uses BearSSL, WebAssembly's -// default, stops with the instruction to add BearSSL or to select OpenSSL with its define -// (spec section 4.3). +// A program for wasip2 or wasip3 that links OpenSSL alone and calls aes256_gcm, whose default +// backend on WebAssembly is BearSSL whatever is linked (design D32), stops where it calls it, +// with the line that links BearSSL and the type that names OpenSSL. // clang-format off -// expected-error@webcpp/crypto/backends/bearssl.hpp:* {{webcpp::crypto: the backend BearSSL is used and not linked. In the program's Jamfile, add /third_party//bearssl beside /webcpp/crypto//crypto, or, with /webcpp/crypto//openssl linked, select OpenSSL with WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL. (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)}} +// expected-error@webcpp/crypto/ciphers/gcm.hpp:* {{webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked. Add /third_party//bearssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).}} // clang-format on -#include + +#include + +#include +#include int main() { - return 0; + std::array const key{}; + return webcpp::crypto::ciphers::aes256_gcm::make(key) ? 0 : 1; } diff --git a/test/messages/two_defaults/two_defaults.cpp b/test/messages/two_defaults/two_defaults.cpp deleted file mode 100644 index 84d9f0f9..00000000 --- a/test/messages/two_defaults/two_defaults.cpp +++ /dev/null @@ -1,17 +0,0 @@ -// 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 program that selects both default backends stops with the instruction to keep one -// (spec section 4.3, the ninth row). - -// clang-format off -// expected-error@webcpp/crypto/config.hpp:* {{webcpp::crypto: both WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL and WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL are defined. Keep one.}} -// clang-format on -#include - -int main() { - return 0; -} diff --git a/test/msvc/Jamfile b/test/msvc/Jamfile index e2fa6462..77d6aaa4 100644 --- a/test/msvc/Jamfile +++ b/test/msvc/Jamfile @@ -20,12 +20,13 @@ rule msvc-only ( properties * ) project : requirements @msvc-only ; build-project openssl_not_linked ; -build-project two_defaults ; +build-project default_selected ; +build-project default_openssl_wasm ; build-project canary_secp256k1_missing ; build-project canary_secp256k1_small ; build-project canary_ctaes_missing ; build-project gcm_on_ctaes ; -build-project no_backend ; +build-project gcm_default_openssl_not_linked ; build-project bearssl_not_linked ; build-project aes_on_bearssl ; build-project canary_missing ; @@ -33,7 +34,6 @@ build-project canary_other_commit ; build-project canary_other_configuration ; build-project canary_two_files ; build-project canary_secp256k1_two_files ; -build-project default_two_files ; build-project ctaes_not_linked ; build-project secp256k1_not_linked ; build-project openssl_old ; diff --git a/test/msvc/bearssl_not_linked/Jamfile b/test/msvc/bearssl_not_linked/Jamfile index 1d030fb7..d5b23481 100644 --- a/test/msvc/bearssl_not_linked/Jamfile +++ b/test/msvc/bearssl_not_linked/Jamfile @@ -7,5 +7,5 @@ import webcpp ; webcpp.compile-fail bearssl_not_linked : app.cpp - : WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL /webcpp/crypto//crypto + : /webcpp/crypto//crypto : native ; diff --git a/test/msvc/bearssl_not_linked/app.cpp b/test/msvc/bearssl_not_linked/app.cpp index e2f9b139..8dbb05ce 100644 --- a/test/msvc/bearssl_not_linked/app.cpp +++ b/test/msvc/bearssl_not_linked/app.cpp @@ -4,7 +4,7 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// A program that selects BearSSL and does not link it stops at backends/bearssl.hpp's +// A program that includes BearSSL's header and does not link it stops at backends/bearssl.hpp's // instruction to add /third_party//bearssl (spec section 4.3): on MSVC the compile fails. The // text is checked on clang, in test/messages/bearssl_not_linked. #include diff --git a/test/msvc/two_defaults/Jamfile b/test/msvc/default_openssl_wasm/Jamfile similarity index 56% rename from test/msvc/two_defaults/Jamfile rename to test/msvc/default_openssl_wasm/Jamfile index 80afa36f..b8dff4b0 100644 --- a/test/msvc/two_defaults/Jamfile +++ b/test/msvc/default_openssl_wasm/Jamfile @@ -6,6 +6,6 @@ import webcpp ; -webcpp.compile-fail two_defaults : app.cpp - : WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL /webcpp/crypto//crypto +webcpp.compile-fail default_openssl_wasm : app.cpp + : WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL /webcpp/crypto//crypto : native ; diff --git a/test/msvc/default_openssl_wasm/app.cpp b/test/msvc/default_openssl_wasm/app.cpp new file mode 100644 index 00000000..1908869c --- /dev/null +++ b/test/msvc/default_openssl_wasm/app.cpp @@ -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) + +// Version 0.1's WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL stops the build at config.hpp, with the type +// to write, on every target (the owner's answer Q3): on MSVC the compile fails. The text is +// checked on clang, in test/messages/default_openssl_wasm. +#include + +int main() { + return 0; +} diff --git a/test/msvc/no_backend/Jamfile b/test/msvc/default_selected/Jamfile similarity index 62% rename from test/msvc/no_backend/Jamfile rename to test/msvc/default_selected/Jamfile index 8e4ff8a3..9b8730f1 100644 --- a/test/msvc/no_backend/Jamfile +++ b/test/msvc/default_selected/Jamfile @@ -6,6 +6,6 @@ import webcpp ; -webcpp.compile-fail no_backend : app.cpp - : /webcpp/crypto//crypto +webcpp.compile-fail default_selected : app.cpp + : WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL /webcpp/crypto//crypto : native ; diff --git a/test/msvc/two_defaults/app.cpp b/test/msvc/default_selected/app.cpp similarity index 51% rename from test/msvc/two_defaults/app.cpp rename to test/msvc/default_selected/app.cpp index 5b06a0e8..0c8cd690 100644 --- a/test/msvc/two_defaults/app.cpp +++ b/test/msvc/default_selected/app.cpp @@ -4,9 +4,9 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// A program that selects both default backends stops at config.hpp's instruction to keep one -// (spec section 4.3): on MSVC the compile fails. The text is checked on clang, in -// test/messages/two_defaults. +// Version 0.1's WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL stops the build at config.hpp, with the type +// to write, on every target (the owner's answer Q3): on MSVC the compile fails. The text is +// checked on clang, in test/messages/default_selected. #include int main() { diff --git a/test/msvc/default_two_files/main.cpp b/test/msvc/default_two_files/main.cpp deleted file mode 100644 index 2592dcbf..00000000 --- a/test/msvc/default_two_files/main.cpp +++ /dev/null @@ -1,24 +0,0 @@ -// 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) - -// Two translation units whose default backends differ: main.cpp keeps the default (OpenSSL, -// natively), with.cpp selects BearSSL. MSVC's linker compares the values of aes256_gcm.hpp's -// #pragma detect_mismatch and fails with LNK2038 (spec section 5). Elsewhere the program links; -// it is MSVC's case alone. -#include - -#include -#include - -bool seal_with_bearssl(); - -int main() { - std::array const key{}; - std::array const iv{}; - std::array data{}; - auto aead = webcpp::crypto::ciphers::aes256_gcm::make(key); - return aead && aead->seal(iv, {}, data) && seal_with_bearssl() ? 0 : 1; -} diff --git a/test/msvc/default_two_files/with.cpp b/test/msvc/default_two_files/with.cpp deleted file mode 100644 index 03c5ce8a..00000000 --- a/test/msvc/default_two_files/with.cpp +++ /dev/null @@ -1,22 +0,0 @@ -// 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 second translation unit of default_two_files: it selects BearSSL as the default backend -// before its includes, so its detect_mismatch value differs from main.cpp's. -#define WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL - -#include - -#include -#include - -bool seal_with_bearssl() { - std::array const key{}; - std::array const iv{}; - std::array data{}; - auto aead = webcpp::crypto::ciphers::aes256_gcm::make(key); - return aead && aead->seal(iv, {}, data); -} diff --git a/test/msvc/default_two_files/Jamfile b/test/msvc/gcm_default_openssl_not_linked/Jamfile similarity index 75% rename from test/msvc/default_two_files/Jamfile rename to test/msvc/gcm_default_openssl_not_linked/Jamfile index 93e0df48..73c8a0cd 100644 --- a/test/msvc/default_two_files/Jamfile +++ b/test/msvc/gcm_default_openssl_not_linked/Jamfile @@ -6,6 +6,6 @@ import webcpp ; -webcpp.link-fail default_two_files : main.cpp with.cpp - : /webcpp/crypto//crypto /third_party//bearssl /webcpp/crypto//openssl +webcpp.compile-fail gcm_default_openssl_not_linked : app.cpp + : /webcpp/crypto//crypto /third_party//bearssl : native ; diff --git a/test/msvc/gcm_default_openssl_not_linked/app.cpp b/test/msvc/gcm_default_openssl_not_linked/app.cpp new file mode 100644 index 00000000..1e408251 --- /dev/null +++ b/test/msvc/gcm_default_openssl_not_linked/app.cpp @@ -0,0 +1,19 @@ +// 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 native program that links BearSSL alone and calls aes256_gcm, whose default is OpenSSL +// natively whatever is linked, stops where it calls it with the line that links OpenSSL (design +// D32): on MSVC the compile fails. The text is checked on clang, in +// test/messages/gcm_default_openssl_not_linked. +#include + +#include +#include + +int main() { + std::array const key{}; + return webcpp::crypto::ciphers::aes256_gcm::make(key) ? 0 : 1; +} diff --git a/test/msvc/no_backend/app.cpp b/test/msvc/no_backend/app.cpp deleted file mode 100644 index de7f5996..00000000 --- a/test/msvc/no_backend/app.cpp +++ /dev/null @@ -1,14 +0,0 @@ -// 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 native program that links no backend and uses the default's header stops at -// backends/bearssl.hpp's instruction to add OpenSSL or BearSSL (spec section 4.3): on MSVC the -// compile fails. The text is checked on clang, in test/messages/no_backend_native. -#include - -int main() { - return 0; -} diff --git a/test/msvc/openssl_not_linked/Jamfile b/test/msvc/openssl_not_linked/Jamfile index fba47bd5..f1749e77 100644 --- a/test/msvc/openssl_not_linked/Jamfile +++ b/test/msvc/openssl_not_linked/Jamfile @@ -7,5 +7,5 @@ import webcpp ; webcpp.compile-fail openssl_not_linked : app.cpp - : WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL /webcpp/crypto//crypto + : /webcpp/crypto//crypto : native ; diff --git a/test/msvc/openssl_not_linked/app.cpp b/test/msvc/openssl_not_linked/app.cpp index b7c4892e..719f90f0 100644 --- a/test/msvc/openssl_not_linked/app.cpp +++ b/test/msvc/openssl_not_linked/app.cpp @@ -4,7 +4,7 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// A program that selects OpenSSL and does not link it stops at backends/openssl.hpp's +// A program that includes OpenSSL's header and does not link it stops at backends/openssl.hpp's // instruction to add /webcpp/crypto//openssl (spec section 4.3): on MSVC the compile fails. // The text is checked on clang, in test/messages/openssl_not_linked. #include From 954b0f580e744d6f0774364b2bbf7e88a5a4bb24 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 13:19:51 -0300 Subject: [PATCH 012/110] crypto: a default row of some compilers names them from crypto.json's compilers, each compiler of a target once The check of two defaults on one target keyed on the free-text where (and before it linked), so one compiler written in two ways passed, and nothing checked that the rows of a target covered each compiler. A row now lists compilers by their names in crypto.json's compilers; check_families faults an unknown name, a compiler of a target in two rows, and one in none. The pages are unchanged. --- doc/tables/crypto.json | 7 +++--- doc/tables/generate.py | 38 +++++++++++++++++----------- doc/tables/generate_test.py | 50 +++++++++++++++++++++++++++++++------ 3 files changed, 70 insertions(+), 25 deletions(-) diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 291aefa0..21ed301c 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -1,7 +1,8 @@ { - "comment": "The data of crypto's generated tables and of llms.txt; doc/tables/generate.py reads it with the test Jamfiles, the message tests and the superproject's Jamfile fixtures, and writes doc/generated/, doc/llms.txt, include/webcpp/crypto/detail/capabilities.hpp, include/webcpp/crypto/detail/defaults.hpp and test/capabilities_test.cpp. The capability table is `families`: per family its algorithms, the targets on which each backend has it (each claimed only where a test of the family's operations on that backend runs), constant time per target where it differs from the backend's own `constant_time` (none yet), and the default per target, one whatever the program links (design D32), with its reason and the tests that fix it, from which come include/webcpp/crypto/detail/defaults.hpp and the refusal that says what a program whose default is not linked needs; a backend with `targets`, where it is built, is a tag of `backends`. A name in a text is written between backticks, as Markdown writes code: the tables show it as code and llms.txt keeps the backticks. Edit this file, then run python3 libs/crypto/doc/tables/generate.py; the doc build runs it with --check.", + "comment": "The data of crypto's generated tables and of llms.txt; doc/tables/generate.py reads it with the test Jamfiles, the message tests and the superproject's Jamfile fixtures, and writes doc/generated/, doc/llms.txt, include/webcpp/crypto/detail/capabilities.hpp, include/webcpp/crypto/detail/defaults.hpp and test/capabilities_test.cpp. The capability table is `families`: per family its algorithms, the targets on which each backend has it (each claimed only where a test of the family's operations on that backend runs), constant time per target where it differs from the backend's own `constant_time` (none yet), and the default per target, one whatever the program links (design D32), with its reason and the tests that fix it (a row of some of `compilers` restates its target's default for them, with a reason of their own, and each compiler of a target has one row), from which come include/webcpp/crypto/detail/defaults.hpp and the refusal that says what a program whose default is not linked needs; a backend with `targets`, where it is built, is a tag of `backends`. A name in a text is written between backticks, as Markdown writes code: the tables show it as code and llms.txt keeps the backticks. Edit this file, then run python3 libs/crypto/doc/tables/generate.py; the doc build runs it with --check.", "page": "https://webcpporg.github.io/libs/crypto/", "targets": ["native", "wasip2", "wasip3", "emscripten"], + "compilers": {"clang": "Clang", "gcc": "GCC", "msvc": "MSVC"}, "sources": { "fips197": ["FIPS 197, the Advanced Encryption Standard", "https://csrc.nist.gov/pubs/fips/197/final"], "sp800-38d": ["NIST SP 800-38D, GCM and GMAC", "https://csrc.nist.gov/pubs/sp/800/38/d/final"], @@ -277,8 +278,8 @@ {"name": "aes256_gcm", "title": "AES-256-GCM", "type": "ciphers::gcm>"} ], "default": [ - {"targets": ["native"], "where": "Clang and GCC", "backend": "openssl", "tests": ["default_both", "default_backend_all_linked"], "why": "OpenSSL's assembly uses the CPU's AES and carry-less multiplication instructions on x86-64 and ARMv8 ({openssl-armv8}; {openssl-ghash-asm}); BearSSL has them on x86 only ({bearssl-aes}). OpenSSL whatever the program links: a program that links BearSSL alone names `gcm>`"}, - {"targets": ["native"], "where": "MSVC", "backend": "openssl", "tests": ["default_both"], "why": "the same rule as with Clang and GCC, but here OpenSSL is built no-asm: table-based AES and 4-bit GHASH, no AES-NI, not constant time ({openssl-install}); where timing attacks matter, link BearSSL and name `gcm>`"}, + {"targets": ["native"], "compilers": ["clang", "gcc"], "backend": "openssl", "tests": ["default_both", "default_backend_all_linked"], "why": "OpenSSL's assembly uses the CPU's AES and carry-less multiplication instructions on x86-64 and ARMv8 ({openssl-armv8}; {openssl-ghash-asm}); BearSSL has them on x86 only ({bearssl-aes}). OpenSSL whatever the program links: a program that links BearSSL alone names `gcm>`"}, + {"targets": ["native"], "compilers": ["msvc"], "backend": "openssl", "tests": ["default_both"], "why": "the same rule as with Clang and GCC, but here OpenSSL is built no-asm: table-based AES and 4-bit GHASH, no AES-NI, not constant time ({openssl-install}); where timing attacks matter, link BearSSL and name `gcm>`"}, {"targets": ["wasip2", "wasip3"], "backend": "bearssl", "tests": ["default_bearssl", "default_both_wasm", "default_backend_all_linked"], "why": "constant time by design ({bearssl-ct}), where OpenSSL is built no-asm and its AES and GHASH are table-based ({openssl-install}). BearSSL whatever the program links: a program that links OpenSSL alone names `gcm>`"}, {"targets": ["emscripten"], "backend": "bearssl", "tests": ["default_bearssl", "default_backend_all_linked_emscripten"], "why": "the only AEAD backend there: webcpp does not build OpenSSL for Emscripten"} ], diff --git a/doc/tables/generate.py b/doc/tables/generate.py index 50b24023..af38e576 100644 --- a/doc/tables/generate.py +++ b/doc/tables/generate.py @@ -438,19 +438,24 @@ def check_families(data: Data, declared: Dict[str, List[str]]) -> None: raise Fault(f'crypto.json: the family {name} states constant time for ' f'{backend} on {target}, where it does not claim it') cite(data, why) - # One default per target, chosen by the target alone (design D32): a row of one compiler - # restates it with a reason of its own. Each is claimed only where a test that fixes it + # One default per target, chosen by the target alone (design D32): a row of some + # compilers, named from crypto.json's compilers, restates it with a reason of its own, and + # each compiler of a target has one row. Each is claimed only where a test that fixes it # runs. rows: List[Tuple[str, str]] = [] for entry in family['default']: cite(data, entry['why']) backend = entry['backend'] for target in entry['targets']: - where = entry.get('where', '') - if (target, where) in rows: - raise Fault(f'crypto.json: the family {name} has two defaults on {target}' - + (f', {where}' if where else '')) - rows.append((target, where)) + for compiler in entry.get('compilers', data['compilers']): + if compiler not in data['compilers']: + raise Fault(f'crypto.json: the family {name}\'s default on {target} ' + f'names the compiler {compiler}, which crypto.json\'s ' + 'compilers does not list') + if (target, compiler) in rows: + raise Fault(f'crypto.json: the family {name} has two defaults on ' + f'{target} with {compiler}') + rows.append((target, compiler)) chosen = default_on(family, target) if chosen != backend: raise Fault(f'crypto.json: the family {name} has two default backends on ' @@ -468,6 +473,11 @@ def check_families(data: Data, declared: Dict[str, List[str]]) -> None: missing = [target for target in data['targets'] if target not in covered] if missing: raise Fault(f'crypto.json: the family {name} has no default on {", ".join(missing)}') + for target in data['targets']: + for compiler in data['compilers']: + if (target, compiler) not in rows: + raise Fault(f'crypto.json: the family {name} has no default on {target} ' + f'with {compiler}') def default_on(family: Data, target: str) -> Optional[str]: @@ -847,7 +857,7 @@ def api_backends(data: Data, matrix: Matrix, operation: Data) -> str: if 'default' in operation: # The block cipher's default argument is AES-GCM's default: its table is AES-GCM's. family = family_of(data, operation.get('default_of', operation['family'])) - defaults = [[target_label(entry), default_title(data, entry)] + defaults = [[target_label(data, entry), default_title(data, entry)] for entry in family['default']] text += (f'\n{marked(operation["default"])} The default per target, whatever the program ' 'links, as <> gives it with its reasons and tests:\n\n' @@ -903,10 +913,10 @@ def family_of(data: Data, name: str) -> Data: raise Fault(f'crypto.json names the family {name}, which it does not list') -def target_label(entry: Data) -> str: - """The targets of a default, and the compiler where it is one compiler's.""" - where = f', {entry["where"]}' if entry.get('where') else '' - return ', '.join(entry['targets']) + where +def target_label(data: Data, entry: Data) -> str: + """The targets of a default, and its compilers where it is some compilers' alone.""" + compilers = ' and '.join(data['compilers'][name] for name in entry.get('compilers', [])) + return ', '.join(entry['targets']) + (f', {compilers}' if compilers else '') def default_title(data: Data, entry: Data) -> str: @@ -920,7 +930,7 @@ def defaults_page(data: Data) -> str: rows: List[List[str]] = [] for family in data['families']: for entry in family['default']: - rows.append([family['title'], target_label(entry), default_title(data, entry), + rows.append([family['title'], target_label(data, entry), default_title(data, entry), cite(data, entry['why']), ', '.join(code(name) for name in entry['tests'])]) return table(['Family', 'Target', 'Default', 'Why', 'Tested by'], rows, @@ -1182,7 +1192,7 @@ def llms(data: Data, matrix: Matrix, library: Path) -> str: out += ['## Default backend per family', ''] for family in data['families']: for entry in family['default']: - out.append(f'- {family["title"]}, {target_label(entry)}: ' + out.append(f'- {family["title"]}, {target_label(data, entry)}: ' f'{default_title(data, entry)}; {cite_markdown(data, entry["why"])}.') out += ['', '## Rules of use', ''] for rule in data['rules']: diff --git a/doc/tables/generate_test.py b/doc/tables/generate_test.py index d15ca7da..936aee0d 100644 --- a/doc/tables/generate_test.py +++ b/doc/tables/generate_test.py @@ -245,6 +245,7 @@ def backend(title: str, name: str, jamfile: str) -> generate.Data: 'header': f'', 'targets': EVERY_TARGET} return { 'targets': EVERY_TARGET, 'sources': {'rfc8032': ['RFC 8032', 'https://example.org']}, + 'compilers': {'clang': 'Clang', 'gcc': 'GCC', 'msvc': 'MSVC'}, 'backends': {'bearssl': backend('BearSSL', 'bearssl', '/third_party//bearssl'), 'sodium': backend('libsodium', 'sodium', '/third_party//sodium'), 'system': {'title': 'The system'}}, @@ -352,13 +353,14 @@ def test_a_cell_claimed_where_no_test_runs_is_a_fault(_: Path) -> None: 'the family ed25519 claims sodium on wasip2, where sodium is not built') -def a_default(targets: list[str], backend: Optional[str], where: str = '', +def a_default(targets: list[str], backend: Optional[str], + compilers: Optional[list[str]] = None, tests: Optional[list[str]] = None) -> generate.Data: - """A row of a family's defaults, on targets, for one compiler where where names it.""" + """A row of a family's defaults, on targets, for the compilers named, else for every one.""" row: generate.Data = {'targets': targets, 'backend': backend, 'tests': ['ed25519'] if tests is None else tests, 'why': 'w'} - if where: - row['where'] = where + if compilers is not None: + row['compilers'] = compilers return row @@ -375,13 +377,34 @@ def test_a_default_is_a_backend_of_the_family_its_tests_run_on(_: Path) -> None: a_fault(data, every, 'the family ed25519 has two defaults on native') # A compiler's row restates its target's default with a reason of its own; it never changes # the backend, which the target alone chooses. - data['families'][0]['default'] = [a_default(EVERY_TARGET, 'sodium'), - a_default(['native'], 'sodium', 'MSVC')] + wasm = ['wasip2', 'wasip3', 'emscripten'] + data['families'][0]['default'] = [a_default(wasm, 'sodium'), + a_default(['native'], 'sodium', ['clang', 'gcc']), + a_default(['native'], 'sodium', ['msvc'])] generate.check_families(data, every) - data['families'][0]['default'] = [a_default(EVERY_TARGET, 'sodium'), - a_default(['native'], None, 'MSVC')] + data['families'][0]['default'] = [a_default(wasm, 'sodium'), + a_default(['native'], 'sodium', ['clang', 'gcc']), + a_default(['native'], None, ['msvc'])] a_fault(data, every, 'the family ed25519 has two default backends on native, sodium and ' 'none: the target alone chooses it') + # The compilers are names of crypto.json's compilers, so that two rows cannot name one + # compiler in two spellings: each compiler of a target has one row. + data['families'][0]['default'] = [a_default(wasm, 'sodium'), + a_default(['native'], 'sodium', ['Clang and GCC']), + a_default(['native'], 'sodium', ['msvc'])] + a_fault(data, every, 'the family ed25519\'s default on native names the compiler Clang and ' + 'GCC, which crypto.json\'s compilers does not list') + data['families'][0]['default'] = [a_default(wasm, 'sodium'), + a_default(['native'], 'sodium', ['clang', 'gcc']), + a_default(['native'], 'sodium', ['gcc', 'msvc'])] + a_fault(data, every, 'the family ed25519 has two defaults on native with gcc') + data['families'][0]['default'] = [a_default(EVERY_TARGET, 'sodium'), + a_default(['native'], 'sodium', ['msvc'])] + a_fault(data, every, 'the family ed25519 has two defaults on native with msvc') + data['families'][0]['default'] = [a_default(wasm, 'sodium'), + a_default(['native'], 'sodium', ['clang']), + a_default(['native'], 'sodium', ['msvc'])] + a_fault(data, every, 'the family ed25519 has no default on native with gcc') # A default is claimed only where a test that fixes it runs. data['families'][0]['default'] = [a_default(EVERY_TARGET, 'sodium', tests=['ed25519_native'])] @@ -432,6 +455,16 @@ def test_the_defaults_header_chooses_by_the_target_alone(_: Path) -> None: assert '#if' not in one.split('struct default_backend_of {};', 1)[1], one +def test_a_row_of_some_compilers_is_labelled_with_their_names(_: Path) -> None: + data = small_table() + assert generate.target_label(data, a_default(['native'], 'sodium', ['clang', 'gcc'])) == ( + 'native, Clang and GCC') + assert generate.target_label(data, a_default(['native'], 'sodium', ['msvc'])) == ( + 'native, MSVC') + assert generate.target_label(data, a_default(['wasip2', 'wasip3'], 'sodium')) == ( + 'wasip2, wasip3') + + def test_a_family_without_a_default_has_no_type(_: Path) -> None: data = small_table() data['families'][0]['default'] = [a_default(EVERY_TARGET, None)] @@ -552,6 +585,7 @@ def test_the_check_names_a_file_that_differs(scratch: Path) -> None: test_a_cell_claimed_where_no_test_runs_is_a_fault, test_a_default_is_a_backend_of_the_family_its_tests_run_on, test_the_defaults_header_chooses_by_the_target_alone, + test_a_row_of_some_compilers_is_labelled_with_their_names, test_a_family_without_a_default_has_no_type, test_the_default_s_refusal_says_what_the_program_needs, test_a_refusal_holds_on_its_target, From f746e5bfda81ae6be4063ab425e9ee72101e2a14 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 13:19:56 -0300 Subject: [PATCH 013/110] crypto: the optimised tests link on Emscripten without debug information, so em++ runs its whole post-link optimisation secret, canary_read, canary_read_absent and wipe_objects_* were built at speed in the debug variant, whose -g made em++ warn -Wlimited-postlink-optimizations ten times a lane: DWARF keeps binaryen to its limited passes. They read what an optimiser leaves, so on Emscripten they now drop the debug information (emscripten:off) and wasm-opt runs in full, the stricter test; elsewhere nothing changes. --- test/Jamfile | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/test/Jamfile b/test/Jamfile index b0cc32cb..35da824a 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -20,6 +20,12 @@ rule crypto-run ( name : sources + : requirements * : targets * ) : $(requirements) off : $(targets) ; } +# The requirements of a test that reads what an optimiser leaves: -O2, and on +# Emscripten no debug information, whose DWARF would hold back em++'s +# post-link optimisation, the wasm-opt a release build runs +# (-Wlimited-postlink-optimizations). +OPTIMISED = speed emscripten:off ; + webcpp.headers-alone crypto : ../include : crypto.hpp crypto/config.hpp crypto/equal.hpp crypto/error.hpp crypto/ciphers/aes.hpp crypto/ciphers/gcm.hpp crypto/random_device.hpp crypto/detail/declassify.hpp crypto/detail/engines.hpp @@ -69,20 +75,20 @@ crypto-run equal : equal_test.cpp ; crypto-run convenience_header : convenience_header_test.cpp ; crypto-run wipe : wipe_test.cpp ; # secret is not copyable, moves wipe the source, and the destructor wipes -# the storage: at -O2 with every call inlined (full), where a wipe -# the compiler could drop as a dead store would be dropped. -crypto-run secret : secret_test.cpp : speed full ; +# the storage: optimised, with every call inlined (full), where a +# wipe the compiler could drop as a dead store would be dropped. +crypto-run secret : secret_test.cpp : $(OPTIMISED) full ; # A destroyed or moved-from key schedule is zero in its storage, read at -O2 # where a dropped store would show: one program per keyed type, one source. crypto-run wipe_objects_bearssl : wipe_objects_test.cpp - : /third_party//bearssl WEBCPP_TEST_WIPE_BEARSSL speed ; + : /third_party//bearssl WEBCPP_TEST_WIPE_BEARSSL $(OPTIMISED) ; crypto-run wipe_objects_ctaes : wipe_objects_test.cpp - : /third_party//ctaes WEBCPP_TEST_WIPE_CTAES speed ; + : /third_party//ctaes WEBCPP_TEST_WIPE_CTAES $(OPTIMISED) ; crypto-run wipe_objects_secp256k1 : wipe_objects_test.cpp - : /third_party//secp256k1 WEBCPP_TEST_WIPE_SECP256K1 speed ; + : /third_party//secp256k1 WEBCPP_TEST_WIPE_SECP256K1 $(OPTIMISED) ; crypto-run wipe_objects_openssl : wipe_objects_test.cpp - : /webcpp/crypto//openssl WEBCPP_TEST_WIPE_OPENSSL speed + : /webcpp/crypto//openssl WEBCPP_TEST_WIPE_OPENSSL $(OPTIMISED) : native wasip2 wasip3 ; # The counter itself: counts each allocation as it documents, on the first @@ -198,9 +204,9 @@ crypto-run gcm_wycheproof_bearssl : gcm_wycheproof_bearssl_test.cpp # read_canary's load survives optimisation: without the canary the program does # not link, on every compiler; with it, it links and runs. -webcpp.link-fail canary_read_absent : canary_read_test.cpp : speed ; +webcpp.link-fail canary_read_absent : canary_read_test.cpp : $(OPTIMISED) ; crypto-run canary_read : canary_read_test.cpp - : speed WEBCPP_TEST_CRYPTO_DEFINE_CANARY ; + : $(OPTIMISED) WEBCPP_TEST_CRYPTO_DEFINE_CANARY ; # random_device: the system's generator, and a planted failing source. crypto-run random_device : random_device_test.cpp ; From 9f7253ab6a68624d0e4ee008443876866772d0e1 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 13:54:44 -0300 Subject: [PATCH 014/110] crypto: the examples and the use cases teach AES-GCM's default, and the default's refusal says what a build without b2 links Review of Task 5', fix round 1. The use cases and five examples named BearSSL in the type, which natively steers a server on ARM to BearSSL's portable AES, the case OpenSSL's native default exists to avoid. They name aes256_gcm again and link its default on each target, OpenSSL natively and BearSSL on WebAssembly, through a rule of example/Jamfile that the guide shows; the guide states the cost of naming BearSSL natively where it shows that form. The never-called member functions of the primary engines return backend_failure, so a path the refusal missed fails closed. The needs message ends with what a build without b2 defines and links, from each backend's without_b2 in crypto.json. The other backend it names is the first of crypto.json's backends that has the family on the target when the program is built, never one decided at run time, in the family's shown name, which check_families requires where there is another backend. The fixes of no_backend_wasm and openssl_only_on_wasi match their message. --- doc/aead.adoc | 8 ++-- doc/generated/jamfiles.adoc | 4 +- doc/generated/messages.adoc | 12 +++--- doc/generated/use-cases.adoc | 26 +++++-------- doc/jamfile.adoc | 9 +++++ doc/llms.txt | 8 ++-- doc/tables/crypto.json | 20 ++++++---- doc/tables/generate.py | 38 +++++++++++++++---- doc/tables/generate_test.py | 36 ++++++++++++++++-- example/Jamfile | 25 +++++++++--- example/ecdh_session.cpp | 12 ++---- example/failure_reasons.cpp | 8 +--- example/sealed_records.cpp | 6 +-- example/store_token.cpp | 8 +--- example/wallet_key.cpp | 9 +---- include/webcpp/crypto/ciphers/aes.hpp | 15 ++++---- include/webcpp/crypto/ciphers/gcm.hpp | 23 +++++------ include/webcpp/crypto/detail/capabilities.hpp | 16 ++++---- test/Jamfile | 3 +- .../gcm_default_openssl_not_linked.cpp | 2 +- .../no_backend_wasm/no_backend_wasm.cpp | 2 +- .../openssl_only_on_wasi.cpp | 2 +- 22 files changed, 177 insertions(+), 115 deletions(-) diff --git a/doc/aead.adoc b/doc/aead.adoc index ee5010b4..45d27ef0 100644 --- a/doc/aead.adoc +++ b/doc/aead.adoc @@ -58,9 +58,11 @@ include::{examples}/store_token.cpp[tag=open,indent=0] include::{examples}/store_token.expected[] ---- -The examples name BearSSL in the type, `aead_type`, so that one Jamfile line -serves every target. The whole of one: AES-256-GCM on BearSSL against the GCM -specification's test case 14. +The same, with the backend named rather than the default: AES-256-GCM on +BearSSL against the GCM specification's test case 14. Naming BearSSL lets one +Jamfile line serve every target, at a cost natively: on an ARM server BearSSL +runs its portable AES, where the default, OpenSSL, uses the CPU's +(<>). [source,cpp] ---- diff --git a/doc/generated/jamfiles.adoc b/doc/generated/jamfiles.adoc index 11fd9b5d..5d6325f8 100644 --- a/doc/generated/jamfiles.adoc +++ b/doc/generated/jamfiles.adoc @@ -39,9 +39,9 @@ It prints: include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/both_bearssl_named/both_bearssl_named.outcome[tag=output] ---- -`+encrypt_and_sign+`:: Two backends in one program: AES-256-GCM on BearSSL, named in the type so that one Jamfile serves every target, and a BIP 340 signature. +`+encrypt_and_sign+`:: Two backends in one program on WebAssembly: AES-256-GCM on its default, BearSSL, and a BIP 340 signature. + -Its Jamfile, built and run on native, wasip2, wasip3, emscripten: +Its Jamfile, built and run on wasip2, wasip3, emscripten: + [listing] ---- diff --git a/doc/generated/messages.adoc b/doc/generated/messages.adoc index 4a885b2a..80912ea6 100644 --- a/doc/generated/messages.adoc +++ b/doc/generated/messages.adoc @@ -45,7 +45,7 @@ The fix: Remove the define, and name `+gcm>+` where th |`+gcm_default_openssl_not_linked+` |native -|`+webcpp::crypto: AES-GCM's default backend on this target is OpenSSL, which is not linked. Add /webcpp/crypto//openssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//openssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).+` +|`+webcpp::crypto: AES-GCM's default backend on this target is OpenSSL, which is not linked. Add /webcpp/crypto//openssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//openssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_OPENSSL=1 and link libcrypto)+` The fix: Natively the default is OpenSSL: add `+/webcpp/crypto//openssl+`, or name BearSSL in the type, as in `+gcm>+`. @@ -57,9 +57,9 @@ The fix: Name `+gcm>+` or `+gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).+` +|`+webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked. Add /third_party//bearssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)+` -The fix: Add `+/third_party//bearssl+` to the program's sources. +The fix: On WASI the default is BearSSL: add `+/third_party//bearssl+`, or, with OpenSSL linked, name it in the type, as in `+gcm>+`. |`+openssl_memory_not_linked+` |native @@ -87,9 +87,9 @@ The fix: Name `+/webcpp/crypto//openssl+`, which builds OpenSSL 3.5.9; without b |`+openssl_only_on_wasi+` |wasip2, wasip3 -|`+webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked. Add /third_party//bearssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).+` +|`+webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked. Add /third_party//bearssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)+` -The fix: On WASI the default is BearSSL: add `+/third_party//bearssl+`, or name OpenSSL in the type, as in `+gcm>+`. +The fix: On WASI the default is BearSSL: add `+/third_party//bearssl+`, or, with OpenSSL linked, name it in the type, as in `+gcm>+`. |`+secp256k1_not_linked+` |native, wasip2 @@ -424,7 +424,7 @@ include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/no_backend_on_emscrip On each target, the build's output contains: + * emscripten: -** `+webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked, and the one backend that has it there. Add /third_party//bearssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ;+` +** `+webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked, and the one backend that has it there. Add /third_party//bearssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ; (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)+` `+openssl_memory_on_emscripten+`:: The memory option of the OpenSSL backend set in a build for Emscripten. The fix: Remove `+WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE+` from the WebAssembly build: give that build a project of its own, without the define and OpenSSL, naming `+/third_party//bearssl+`. On WebAssembly the backend is BearSSL, which allocates nothing. + diff --git a/doc/generated/use-cases.adoc b/doc/generated/use-cases.adoc index 96069c87..90af5b92 100644 --- a/doc/generated/use-cases.adoc +++ b/doc/generated/use-cases.adoc @@ -30,17 +30,15 @@ |<> |Encrypt a database field, a cookie or a token at rest -|In `+ciphers+`: `+gcm>+`, or `+aes256_gcm+` on the default -|BearSSL, named: one Jamfile line on every target; the default is OpenSSL natively, BearSSL on WebAssembly -|`+/webcpp/crypto//crypto+` + -`+/third_party//bearssl+` +|In `+ciphers+`: `+aes256_gcm+` +|the default: OpenSSL natively, BearSSL on WebAssembly +|`+/webcpp/crypto//crypto+`; natively `+/webcpp/crypto//openssl+`, on WebAssembly `+/third_party//bearssl+` |<> |Encrypt a large file or a stream -|In `+ciphers+`: `+gcm>+`: records, or `+begin_seal+`, `+update+` and `+result+` -|BearSSL, named -|`+/webcpp/crypto//crypto+` + -`+/third_party//bearssl+` +|In `+ciphers+`: `+aes256_gcm+`: records, or `+begin_seal+`, `+update+` and `+result+` +|the default +|`+/webcpp/crypto//crypto+`; natively `+/webcpp/crypto//openssl+`, on WebAssembly `+/third_party//bearssl+` |<> |Tell a forged message from a malformed one @@ -72,18 +70,14 @@ |Agree on a key with a peer through a relay that sees everything |In `+curves::secp256k1+`: `+keypair::ecdh+` (SHA-256 of the shared point: not NIP-44's raw x coordinate), then HKDF on Boost.Hash2 and `+aes256_gcm+` -|libsecp256k1 and BearSSL -|`+/webcpp/crypto//crypto+` + -`+/third_party//secp256k1+` + -`+/third_party//bearssl+` +|libsecp256k1, and AES-GCM's default +|`+/webcpp/crypto//crypto+` `+/third_party//secp256k1+`; natively `+/webcpp/crypto//openssl+`, on WebAssembly `+/third_party//bearssl+` |<> |Make and keep a wallet's key |In `+curves::secp256k1+`: `+keypair::make+`, `+xonly_public_key+`, `+public_key+`; `+aes256_gcm+` at rest -|libsecp256k1 and BearSSL -|`+/webcpp/crypto//crypto+` + -`+/third_party//secp256k1+` + -`+/third_party//bearssl+` +|libsecp256k1, and AES-GCM's default +|`+/webcpp/crypto//crypto+` `+/third_party//secp256k1+`; natively `+/webcpp/crypto//openssl+`, on WebAssembly `+/third_party//bearssl+` |<> |Sign a Bitcoin SegWit v0 input (a domain library's job) diff --git a/doc/jamfile.adoc b/doc/jamfile.adoc index 0fda5044..3c1a5f45 100644 --- a/doc/jamfile.adoc +++ b/doc/jamfile.adoc @@ -46,6 +46,15 @@ and the type that names BearSSL. Version 0.1's `WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL` stop the build with the type to write (<>). +A program built for every target links its default's library on each, as +the examples of this page do: a rule of its Jamfile gives the library by +target, and the program names `aes256_gcm`: + +[listing] +---- +include::{library-root}/example/Jamfile[tag=default_aead] +---- + The source-built OpenSSL is compiled without assembly (`no-asm`) on MSVC, wasip2 and wasip3: its AES is table-based and its GHASH 4-bit, neither constant time, and there is no AES-NI. A program for which timing attacks matter on diff --git a/doc/llms.txt b/doc/llms.txt index 3ff1dbf8..e08d72b3 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -83,14 +83,14 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [Generate a session token, a password-reset link or an API key](https://webcpporg.github.io/libs/crypto/#crypto-entropy): `random_device::fill` (webcpp::crypto); backend the system's generator; Jamfile /webcpp/crypto//crypto. Example: example/reset_token.cpp. - [Draw an unbiased number in a range, such as a six-digit code](https://webcpporg.github.io/libs/crypto/#crypto-entropy): `random_device` with `std::uniform_int_distribution` (webcpp::crypto); backend the system's generator; Jamfile /webcpp/crypto//crypto. Example: example/reset_token.cpp. - [Check a webhook's or an API's HMAC signature](https://webcpporg.github.io/libs/crypto/#crypto-equal): `equal`, with Boost.Hash2's `hmac` (webcpp::crypto); backend none; Jamfile /webcpp/crypto//crypto. Example: example/equal_hmac.cpp. -- [Encrypt a database field, a cookie or a token at rest](https://webcpporg.github.io/libs/crypto/#crypto-gcm): `gcm>`, or `aes256_gcm` on the default (webcpp::crypto::ciphers); backend BearSSL, named: one Jamfile line on every target; the default is OpenSSL natively, BearSSL on WebAssembly; Jamfile /webcpp/crypto//crypto /third_party//bearssl. Example: example/store_token.cpp. -- [Encrypt a large file or a stream](https://webcpporg.github.io/libs/crypto/#crypto-gcm-incremental): `gcm>`: records, or `begin_seal`, `update` and `result` (webcpp::crypto::ciphers); backend BearSSL, named; Jamfile /webcpp/crypto//crypto /third_party//bearssl. Example: example/sealed_records.cpp. +- [Encrypt a database field, a cookie or a token at rest](https://webcpporg.github.io/libs/crypto/#crypto-gcm): `aes256_gcm` (webcpp::crypto::ciphers); backend the default: OpenSSL natively, BearSSL on WebAssembly; Jamfile `/webcpp/crypto//crypto`; natively `/webcpp/crypto//openssl`, on WebAssembly `/third_party//bearssl`. Example: example/store_token.cpp. +- [Encrypt a large file or a stream](https://webcpporg.github.io/libs/crypto/#crypto-gcm-incremental): `aes256_gcm`: records, or `begin_seal`, `update` and `result` (webcpp::crypto::ciphers); backend the default; Jamfile `/webcpp/crypto//crypto`; natively `/webcpp/crypto//openssl`, on WebAssembly `/third_party//bearssl`. Example: example/sealed_records.cpp. - [Tell a forged message from a malformed one](https://webcpporg.github.io/libs/crypto/#crypto-errors): `error` (webcpp::crypto); backend any; Jamfile /webcpp/crypto//crypto. Example: example/failure_reasons.cpp. - [Turn a sequential id into an opaque reference](https://webcpporg.github.io/libs/crypto/#crypto-block): `aes256` (webcpp::crypto::ciphers); backend ctaes, or OpenSSL natively and on WASI; Jamfile /webcpp/crypto//crypto /third_party//ctaes. Example: example/order_reference.cpp. - [Prove who wrote a message posted to a relay](https://webcpporg.github.io/libs/crypto/#crypto-p2p-signed): `keypair::sign_schnorr`, `verify_schnorr` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/signed_message.cpp. - [Check a software update or a licence file](https://webcpporg.github.io/libs/crypto/#crypto-everyday-update): `keypair::sign_ecdsa`, `verify_ecdsa` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/signed_update.cpp. -- [Agree on a key with a peer through a relay that sees everything](https://webcpporg.github.io/libs/crypto/#crypto-p2p-session): `keypair::ecdh` (SHA-256 of the shared point: not NIP-44's raw x coordinate), then HKDF on Boost.Hash2 and `aes256_gcm` (webcpp::crypto::curves::secp256k1); backend libsecp256k1 and BearSSL; Jamfile /webcpp/crypto//crypto /third_party//secp256k1 /third_party//bearssl. Example: example/ecdh_session.cpp. -- [Make and keep a wallet's key](https://webcpporg.github.io/libs/crypto/#crypto-wallets-key): `keypair::make`, `xonly_public_key`, `public_key`; `aes256_gcm` at rest (webcpp::crypto::curves::secp256k1); backend libsecp256k1 and BearSSL; Jamfile /webcpp/crypto//crypto /third_party//secp256k1 /third_party//bearssl. Example: example/wallet_key.cpp. +- [Agree on a key with a peer through a relay that sees everything](https://webcpporg.github.io/libs/crypto/#crypto-p2p-session): `keypair::ecdh` (SHA-256 of the shared point: not NIP-44's raw x coordinate), then HKDF on Boost.Hash2 and `aes256_gcm` (webcpp::crypto::curves::secp256k1); backend libsecp256k1, and AES-GCM's default; Jamfile `/webcpp/crypto//crypto` `/third_party//secp256k1`; natively `/webcpp/crypto//openssl`, on WebAssembly `/third_party//bearssl`. Example: example/ecdh_session.cpp. +- [Make and keep a wallet's key](https://webcpporg.github.io/libs/crypto/#crypto-wallets-key): `keypair::make`, `xonly_public_key`, `public_key`; `aes256_gcm` at rest (webcpp::crypto::curves::secp256k1); backend libsecp256k1, and AES-GCM's default; Jamfile `/webcpp/crypto//crypto` `/third_party//secp256k1`; natively `/webcpp/crypto//openssl`, on WebAssembly `/third_party//bearssl`. Example: example/wallet_key.cpp. - [Sign a Bitcoin SegWit v0 input (a domain library's job)](https://webcpporg.github.io/libs/crypto/#crypto-wallets-der): `sign_ecdsa`, `to_der`, `normalize_ecdsa` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/ecdsa_der.cpp. - [Derive a Bitcoin Taproot output key and spend by key path (a domain library's job)](https://webcpporg.github.io/libs/crypto/#crypto-wallets-taproot): `tweak_xonly`, `keypair::tweak_xonly` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/taproot_tweak.cpp. - [Sign where allocation is restricted to the program's arena](https://webcpporg.github.io/libs/crypto/#crypto-memory): `keypair::make(secret, resource)` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/arena_signer.cpp. diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 21ed301c..0258d3ff 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -65,6 +65,7 @@ }, "backends": { "bearssl": { + "without_b2": "link BearSSL built with webcpp's src/canary_bearssl.c", "title": "BearSSL", "jamfile": "/third_party//bearssl", "targets": ["native", "wasip2", "wasip3", "emscripten"], @@ -77,6 +78,7 @@ "constant_time_sources": ["bearssl-ct", "bearssl-ctmul"] }, "openssl": { + "without_b2": "link libcrypto", "title": "OpenSSL", "jamfile": "/webcpp/crypto//openssl", "targets": ["native", "wasip2", "wasip3"], @@ -89,6 +91,7 @@ "constant_time_sources": ["openssl-install", "openssl-aes-core"] }, "ctaes": { + "without_b2": "link ctaes.c with webcpp's src/canary_ctaes.c", "title": "ctaes", "jamfile": "/third_party//ctaes", "targets": ["native", "wasip2", "wasip3", "emscripten"], @@ -101,6 +104,7 @@ "constant_time_sources": ["ctaes"] }, "secp256k1": { + "without_b2": "link libsecp256k1 built with webcpp's src/canary_secp256k1.c", "title": "libsecp256k1", "jamfile": "/third_party//secp256k1", "targets": ["native", "wasip2", "wasip3", "emscripten"], @@ -113,6 +117,7 @@ "constant_time_sources": ["libsecp256k1"] }, "sodium": { + "without_b2": "link libsodium built with webcpp's src/canary_sodium.c", "title": "libsodium", "jamfile": "/third_party//sodium", "targets": ["native", "wasip2", "wasip3", "emscripten"], @@ -272,6 +277,7 @@ "group": "ciphers", "since": "0.1", "header": "", + "shown": "aes256_gcm", "names": [ {"name": "aes128_gcm", "title": "AES-128-GCM", "type": "ciphers::gcm>"}, {"name": "aes192_gcm", "title": "AES-192-GCM", "type": "ciphers::gcm>"}, @@ -380,14 +386,14 @@ {"need": "Generate a session token, a password-reset link or an API key", "namespace": "webcpp::crypto", "api": "`random_device::fill`", "backend": "the system's generator", "jamfile": "/webcpp/crypto//crypto", "example": "reset_token", "section": "crypto-entropy"}, {"need": "Draw an unbiased number in a range, such as a six-digit code", "namespace": "webcpp::crypto", "api": "`random_device` with `std::uniform_int_distribution`", "backend": "the system's generator", "jamfile": "/webcpp/crypto//crypto", "example": "reset_token", "section": "crypto-entropy"}, {"need": "Check a webhook's or an API's HMAC signature", "namespace": "webcpp::crypto", "api": "`equal`, with Boost.Hash2's `hmac`", "backend": "none", "jamfile": "/webcpp/crypto//crypto", "example": "equal_hmac", "section": "crypto-equal"}, - {"need": "Encrypt a database field, a cookie or a token at rest", "namespace": "webcpp::crypto::ciphers", "api": "`gcm>`, or `aes256_gcm` on the default", "backend": "BearSSL, named: one Jamfile line on every target; the default is OpenSSL natively, BearSSL on WebAssembly", "jamfile": "/webcpp/crypto//crypto /third_party//bearssl", "example": "store_token", "section": "crypto-gcm"}, - {"need": "Encrypt a large file or a stream", "namespace": "webcpp::crypto::ciphers", "api": "`gcm>`: records, or `begin_seal`, `update` and `result`", "backend": "BearSSL, named", "jamfile": "/webcpp/crypto//crypto /third_party//bearssl", "example": "sealed_records", "section": "crypto-gcm-incremental"}, + {"need": "Encrypt a database field, a cookie or a token at rest", "namespace": "webcpp::crypto::ciphers", "api": "`aes256_gcm`", "backend": "the default: OpenSSL natively, BearSSL on WebAssembly", "jamfile": "`/webcpp/crypto//crypto`; natively `/webcpp/crypto//openssl`, on WebAssembly `/third_party//bearssl`", "example": "store_token", "section": "crypto-gcm"}, + {"need": "Encrypt a large file or a stream", "namespace": "webcpp::crypto::ciphers", "api": "`aes256_gcm`: records, or `begin_seal`, `update` and `result`", "backend": "the default", "jamfile": "`/webcpp/crypto//crypto`; natively `/webcpp/crypto//openssl`, on WebAssembly `/third_party//bearssl`", "example": "sealed_records", "section": "crypto-gcm-incremental"}, {"need": "Tell a forged message from a malformed one", "namespace": "webcpp::crypto", "api": "`error`", "backend": "any", "jamfile": "/webcpp/crypto//crypto", "example": "failure_reasons", "section": "crypto-errors"}, {"need": "Turn a sequential id into an opaque reference", "namespace": "webcpp::crypto::ciphers", "api": "`aes256`", "backend": "ctaes, or OpenSSL natively and on WASI", "jamfile": "/webcpp/crypto//crypto /third_party//ctaes", "example": "order_reference", "section": "crypto-block"}, {"need": "Prove who wrote a message posted to a relay", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::sign_schnorr`, `verify_schnorr`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "signed_message", "section": "crypto-p2p-signed"}, {"need": "Check a software update or a licence file", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::sign_ecdsa`, `verify_ecdsa`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "signed_update", "section": "crypto-everyday-update"}, - {"need": "Agree on a key with a peer through a relay that sees everything", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::ecdh` (SHA-256 of the shared point: not NIP-44's raw x coordinate), then HKDF on Boost.Hash2 and `aes256_gcm`", "backend": "libsecp256k1 and BearSSL", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1 /third_party//bearssl", "example": "ecdh_session", "section": "crypto-p2p-session"}, - {"need": "Make and keep a wallet's key", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::make`, `xonly_public_key`, `public_key`; `aes256_gcm` at rest", "backend": "libsecp256k1 and BearSSL", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1 /third_party//bearssl", "example": "wallet_key", "section": "crypto-wallets-key"}, + {"need": "Agree on a key with a peer through a relay that sees everything", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::ecdh` (SHA-256 of the shared point: not NIP-44's raw x coordinate), then HKDF on Boost.Hash2 and `aes256_gcm`", "backend": "libsecp256k1, and AES-GCM's default", "jamfile": "`/webcpp/crypto//crypto` `/third_party//secp256k1`; natively `/webcpp/crypto//openssl`, on WebAssembly `/third_party//bearssl`", "example": "ecdh_session", "section": "crypto-p2p-session"}, + {"need": "Make and keep a wallet's key", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::make`, `xonly_public_key`, `public_key`; `aes256_gcm` at rest", "backend": "libsecp256k1, and AES-GCM's default", "jamfile": "`/webcpp/crypto//crypto` `/third_party//secp256k1`; natively `/webcpp/crypto//openssl`, on WebAssembly `/third_party//bearssl`", "example": "wallet_key", "section": "crypto-wallets-key"}, {"need": "Sign a Bitcoin SegWit v0 input (a domain library's job)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`sign_ecdsa`, `to_der`, `normalize_ecdsa`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "ecdsa_der", "section": "crypto-wallets-der"}, {"need": "Derive a Bitcoin Taproot output key and spend by key path (a domain library's job)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`tweak_xonly`, `keypair::tweak_xonly`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "taproot_tweak", "section": "crypto-wallets-taproot"}, {"need": "Sign where allocation is restricted to the program's arena", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::make(secret, resource)`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "arena_signer", "section": "crypto-memory"}, @@ -401,7 +407,7 @@ "server": "A server, natively: the same program with OpenSSL, the default natively.", "both_bearssl_named": "Both backends linked, and BearSSL named in the type where the default is OpenSSL.", "block": "The AES block cipher on ctaes: the FIPS 197 block encrypted and decrypted again.", - "encrypt_and_sign": "Two backends in one program: AES-256-GCM on BearSSL, named in the type so that one Jamfile serves every target, and a BIP 340 signature.", + "encrypt_and_sign": "Two backends in one program on WebAssembly: AES-256-GCM on its default, BearSSL, and a BIP 340 signature.", "openssl_linked": "OpenSSL, built from source, named in the type: natively and on WASI.", "sign": "A BIP 340 signature with libsecp256k1's default tables.", "sign_small": "The same program with libsecp256k1's small tables, which libsecp256k1 documents as smaller and slower to verify ({secp256k1-configure}); not measured here yet.", @@ -427,9 +433,9 @@ }, "fixes": { "gcm_default_openssl_not_linked": "Natively the default is OpenSSL: add `/webcpp/crypto//openssl`, or name BearSSL in the type, as in `gcm>`.", - "no_backend_wasm": "Add `/third_party//bearssl` to the program's sources.", + "no_backend_wasm": "On WASI the default is BearSSL: add `/third_party//bearssl`, or, with OpenSSL linked, name it in the type, as in `gcm>`.", "bearssl_not_linked": "Add `/third_party//bearssl`.", - "openssl_only_on_wasi": "On WASI the default is BearSSL: add `/third_party//bearssl`, or name OpenSSL in the type, as in `gcm>`.", + "openssl_only_on_wasi": "On WASI the default is BearSSL: add `/third_party//bearssl`, or, with OpenSSL linked, name it in the type, as in `gcm>`.", "openssl_not_linked": "Add `/webcpp/crypto//openssl`.", "openssl_old": "Name `/webcpp/crypto//openssl`, which builds OpenSSL 3.5.9; without b2, put OpenSSL 3's `include/` first.", "ctaes_not_linked": "Add `/third_party//ctaes`.", diff --git a/doc/tables/generate.py b/doc/tables/generate.py index af38e576..1fd6765b 100644 --- a/doc/tables/generate.py +++ b/doc/tables/generate.py @@ -469,6 +469,15 @@ def check_families(data: Data, declared: Dict[str, List[str]]) -> None: if target not in declared.get(test, []): raise Fault(f'crypto.json: the family {name}\'s default on {target} ' f'names the test {test}, which does not run there') + if any(default_on(family, target) and + others_of(data, family, target, default_on(family, target) or '') + for target in data['targets']): + if 'shown' not in family: + raise Fault(f'crypto.json: the family {name} has no shown name, which its ' + 'default\'s refusal names with another backend') + if family['shown'] not in [entry['name'] for entry in family['names']]: + raise Fault(f'crypto.json: the family {name} shows {family["shown"]}, which is ' + 'none of its names') covered = {target for target, _ in rows} missing = [target for target in data['targets'] if target not in covered] if missing: @@ -658,23 +667,36 @@ def capabilities_header(data: Data) -> str: return '\n'.join(out) +def others_of(data: Data, family: Data, target: str, backend: str) -> List[str]: + """The backends other than backend that have a family on a target when the program is built, + in crypto.json's order of backends: a cell decided at run time is not one a program can be + sure to get.""" + return [other for other in tags_of(data) + if other != backend and other in family['backends'] + and not family['backends'][other].get('runtime') + and target in cell_targets(data, family, other)] + + def needs(data: Data, family: Data, target: str, backend: str) -> str: """What a program that uses a family's default without linking it needs (design D32): the - Jamfile line that links it and, where another backend has the family on the target, the type - that names it. The text holds on every target where the default is that backend, so that - one message test checks it on each.""" + Jamfile line that links it, and, where another backend has the family on the target, the type + that names the first of them (others_of) in the family's shown name; then, as every message + of a backend not linked, what a build without b2 defines and links. The text holds on every + target where the default is that backend, so that one message test checks it on each.""" facts = data['backends'][backend] head = (f'webcpp::crypto: {family["title"]}\'s default backend on this target is ' f'{facts["title"]}, which is not linked') add = (f'Add {facts["jamfile"]} to the program\'s Jamfile, as in: exe app : app.cpp ' f'/webcpp/crypto//crypto {facts["jamfile"]} ;') - others = [other for other in family['backends'] - if other != backend and target in cell_targets(data, family, other)] + without = (f'(without b2: define WEBCPP_CRYPTO_HAS_{backend.upper()}=1 and ' + f'{facts["without_b2"]})') + others = others_of(data, family, target, backend) if not others: - return f'{head}, and the one backend that has it there. {add}' - named = family['names'][-1]['type'].replace('{backend}', f'backends::{others[0]}') + return f'{head}, and the one backend that has it there. {add} {without}' + shown = next(entry for entry in family['names'] if entry['name'] == family['shown']) + named = shown['type'].replace('{backend}', f'backends::{others[0]}') return (f'{head}. {add} or name another backend in the type, as in {named}. The backends ' - f'that have it: {have_list(data, family)}.') + f'that have it: {have_list(data, family)}. {without}') def defaults_header(data: Data) -> str: diff --git a/doc/tables/generate_test.py b/doc/tables/generate_test.py index 936aee0d..9bf63fd1 100644 --- a/doc/tables/generate_test.py +++ b/doc/tables/generate_test.py @@ -241,7 +241,7 @@ def small_table() -> generate.Data: """A capability table of one family, Ed25519, on libsodium alone, beside BearSSL and a backend that is no tag of `backends` (the operating system's generator).""" def backend(title: str, name: str, jamfile: str) -> generate.Data: - return {'title': title, 'jamfile': jamfile, + return {'title': title, 'jamfile': jamfile, 'without_b2': f'link {title}', 'header': f'', 'targets': EVERY_TARGET} return { 'targets': EVERY_TARGET, 'sources': {'rfc8032': ['RFC 8032', 'https://example.org']}, @@ -425,6 +425,7 @@ def two_backends() -> generate.Data: data = small_table() family = data['families'][0] family['backends']['bearssl'] = {'targets': 'all'} + family['shown'] = 'ed25519' family['default'] = [a_default(['native'], 'sodium'), a_default(['wasip2', 'wasip3', 'emscripten'], 'bearssl')] return data @@ -455,6 +456,32 @@ def test_the_defaults_header_chooses_by_the_target_alone(_: Path) -> None: assert '#if' not in one.split('struct default_backend_of {};', 1)[1], one +def test_the_other_backend_a_refusal_names_is_chosen_as_stated(_: Path) -> None: + # The other backend is the first of crypto.json's backends, not of the family's, that has + # the family on the target when the program is built; the type is the family's shown name. + data = two_backends() + family = data['families'][0] + family['backends'] = {'sodium': {'targets': 'all'}, 'bearssl': {'targets': 'all'}} + family['names'].append({'name': 'ed25519ph', 'title': 'Ed25519ph', + 'type': 'curves::ed25519ph::keypair<{backend}>'}) + text = generate.needs(data, family, 'native', 'sodium') + assert 'as in curves::ed25519::basic_keypair.' in text, text + # A backend that has the family only at run time is never offered in its place. + family['backends']['bearssl'] = {'targets': 'all', 'runtime': True} + text = generate.needs(data, family, 'native', 'sodium') + assert 'and the one backend that has it there' in text, text + assert 'name another backend' not in text, text + # A family whose default has another backend must say which name its refusal shows. + family['backends']['bearssl'] = {'targets': 'all'} + data['operations'][0]['backends']['bearssl'] = {'tests': ['ed25519']} + del family['shown'] + a_fault(data, {'ed25519': EVERY_TARGET}, 'the family ed25519 has no shown name, which its ' + 'default\'s refusal names with another backend') + family['shown'] = 'ed448' + a_fault(data, {'ed25519': EVERY_TARGET}, 'the family ed25519 shows ed448, which is none of ' + 'its names') + + def test_a_row_of_some_compilers_is_labelled_with_their_names(_: Path) -> None: data = small_table() assert generate.target_label(data, a_default(['native'], 'sodium', ['clang', 'gcc'])) == ( @@ -486,7 +513,8 @@ def test_the_default_s_refusal_says_what_the_program_needs(_: Path) -> None: '/third_party//sodium ; or name another backend in the type, as in ' 'curves::ed25519::basic_keypair. The backends that have it: ' 'sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, ' - 'emscripten).")') in native, native + 'emscripten). (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link ' + 'libsodium)")') in native, native # The default, linked, whose header the program did not include. assert (f'static_assert(!std::is_same_v || ' f'!::webcpp::crypto::detail::linked<{sodium}>, "webcpp::crypto: sodium\'s Ed25519 ' @@ -498,7 +526,8 @@ def test_the_default_s_refusal_says_what_the_program_needs(_: Path) -> None: assert ('"webcpp::crypto: Ed25519\'s default backend on this target is libsodium, which is ' 'not linked, and the one backend that has it there. Add /third_party//sodium to the ' 'program\'s Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto ' - '/third_party//sodium ;")') in alone, alone + '/third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link ' + 'libsodium)")') in alone, alone assert 'default backend on this target is BearSSL' in emscripten, emscripten # Any other type is refused as no backend of the family, and nothing else is. assert ('static_assert(std::is_same_v || ' @@ -586,6 +615,7 @@ def test_the_check_names_a_file_that_differs(scratch: Path) -> None: test_a_default_is_a_backend_of_the_family_its_tests_run_on, test_the_defaults_header_chooses_by_the_target_alone, test_a_row_of_some_compilers_is_labelled_with_their_names, + test_the_other_backend_a_refusal_names_is_chosen_as_stated, test_a_family_without_a_default_has_no_type, test_the_default_s_refusal_says_what_the_program_needs, test_a_refusal_holds_on_its_target, diff --git a/example/Jamfile b/example/Jamfile index d124518c..7bb28dd8 100644 --- a/example/Jamfile +++ b/example/Jamfile @@ -7,9 +7,24 @@ project : requirements /webcpp/crypto//crypto ; import webcpp ; +import webcpp-target ; webcpp.targets native wasip2 wasip3 emscripten ; +# The library of AES-GCM's default backend, which aes128_gcm and aes256_gcm +# name: OpenSSL natively, BearSSL on WebAssembly (the guide's "The default +# backend per target"). +# tag::default_aead[] +rule default-aead ( properties * ) +{ + if [ webcpp-target.target-of $(properties) ] = native + { + return /webcpp/crypto//openssl ; + } + return /third_party//bearssl ; +} +# end::default_aead[] + # The guide's secp256k1 program: BIP340's first vector signed and verified, then # the key pair tweaked and used again. webcpp.example schnorr_sign.cpp : /third_party//secp256k1 ; @@ -26,16 +41,16 @@ webcpp.example equal_hmac.cpp ; webcpp.example bearssl_prng.cpp : /third_party//bearssl ; # The three ways AES-GCM refuses a message, on the default backend. -webcpp.example failure_reasons.cpp : /third_party//bearssl ; +webcpp.example failure_reasons.cpp : @default-aead ; # A reset token and a one-time code from random_device; no backend. webcpp.example reset_token.cpp ; # An API token stored in a row, bound to the user id as additional data. -webcpp.example store_token.cpp : /third_party//bearssl ; +webcpp.example store_token.cpp : @default-aead ; # The incremental seal, and records bound to their numbers. -webcpp.example sealed_records.cpp : /third_party//bearssl ; +webcpp.example sealed_records.cpp : @default-aead ; # An order id turned into an opaque reference with the raw AES block cipher. webcpp.example order_reference.cpp : /third_party//ctaes ; @@ -47,10 +62,10 @@ webcpp.example signed_message.cpp : /third_party//secp256k1 ; webcpp.example signed_update.cpp : /third_party//secp256k1 ; # ECDH, HKDF-SHA-256 and AES-256-GCM between two peers. -webcpp.example ecdh_session.cpp : /third_party//secp256k1 /third_party//bearssl ; +webcpp.example ecdh_session.cpp : /third_party//secp256k1 @default-aead ; # A wallet's key pair, its secret sealed at rest and restored. -webcpp.example wallet_key.cpp : /third_party//secp256k1 /third_party//bearssl ; +webcpp.example wallet_key.cpp : /third_party//secp256k1 @default-aead ; # ECDSA with DER encoding and the low-S rule, as a domain library uses them. webcpp.example ecdsa_der.cpp : /third_party//secp256k1 ; diff --git a/example/ecdh_session.cpp b/example/ecdh_session.cpp index dd60343c..be3f3304 100644 --- a/example/ecdh_session.cpp +++ b/example/ecdh_session.cpp @@ -8,9 +8,7 @@ // and talk over AES-256-GCM. The raw ECDH output is not a key: HKDF turns it into one and ties // it to this application with a context string. // tag::program[] -#include -#include -#include +#include #include #include #include @@ -29,9 +27,6 @@ #include namespace crypto = webcpp::crypto; -// AES-256-GCM on BearSSL, named in the type: one Jamfile line serves every target, where -// aes256_gcm's default is OpenSSL natively. -using aead_type = crypto::ciphers::gcm>; namespace secp256k1 = webcpp::crypto::curves::secp256k1; namespace hash2 = boost::hash2; @@ -132,9 +127,10 @@ boost::system::result generate_key() { } // Both sides derive their session key the same way. -boost::system::result session_cipher(std::array const& shared) { +boost::system::result session_cipher( + std::array const& shared) { auto key = hkdf_sha256<32>(shared, {}, bytes_of("example chat v1 session key")); - auto cipher = aead_type::make(key); + auto cipher = crypto::ciphers::aes256_gcm::make(key); // The cipher keeps its own copy of the key, which it wipes; this one goes now. wipe(std::as_writable_bytes(std::span(key))); return cipher; diff --git a/example/failure_reasons.cpp b/example/failure_reasons.cpp index 7847eedc..044789e7 100644 --- a/example/failure_reasons.cpp +++ b/example/failure_reasons.cpp @@ -9,9 +9,7 @@ // authentication_failed means someone changed the data, and open then wipes the plaintext so // that no unauthenticated bytes are ever used. // tag::program[] -#include -#include -#include +#include #include #include @@ -24,9 +22,7 @@ #include namespace crypto = webcpp::crypto; -// AES-256-GCM on BearSSL, named in the type: one Jamfile line serves every target, where -// aes256_gcm's default is OpenSSL natively. -using aead_type = crypto::ciphers::gcm>; +using aead_type = crypto::ciphers::aes256_gcm; namespace { diff --git a/example/sealed_records.cpp b/example/sealed_records.cpp index ae7bb473..83c51311 100644 --- a/example/sealed_records.cpp +++ b/example/sealed_records.cpp @@ -11,9 +11,7 @@ // a key of its own, drawn when the stream starts: the counter IVs 0, 1, 2 of one stream are safe // only because no other stream seals under its key. // tag::program[] -#include -#include -#include +#include #include #include @@ -30,7 +28,7 @@ #include namespace crypto = webcpp::crypto; -using aead_type = crypto::ciphers::gcm>; +using aead_type = crypto::ciphers::aes256_gcm; namespace { diff --git a/example/store_token.cpp b/example/store_token.cpp index 27d29ee5..90520a76 100644 --- a/example/store_token.cpp +++ b/example/store_token.cpp @@ -8,9 +8,7 @@ // additional data: authenticated but not encrypted, so a row copied to another user's record // no longer opens. Without that binding a database writer could swap the rows of two users. // tag::program[] -#include -#include -#include +#include #include #include @@ -24,9 +22,7 @@ #include namespace crypto = webcpp::crypto; -// AES-256-GCM on BearSSL, named in the type: one Jamfile line serves every target, where -// aes256_gcm's default is OpenSSL natively. -using aead_type = crypto::ciphers::gcm>; +using aead_type = crypto::ciphers::aes256_gcm; namespace { diff --git a/example/wallet_key.cpp b/example/wallet_key.cpp index f576adac..180a6ba1 100644 --- a/example/wallet_key.cpp +++ b/example/wallet_key.cpp @@ -8,9 +8,7 @@ // and restores it. A secret that sits unencrypted on disk, or lingers in memory after use, is // the first thing an attacker looks for, so the copies are wiped as soon as they are not needed. // tag::program[] -#include -#include -#include +#include #include #include #include @@ -26,9 +24,6 @@ #include namespace crypto = webcpp::crypto; -// AES-256-GCM on BearSSL, named in the type: one Jamfile line serves every target, where -// aes256_gcm's default is OpenSSL natively. -using aead_type = crypto::ciphers::gcm>; namespace secp256k1 = webcpp::crypto::curves::secp256k1; namespace { @@ -91,7 +86,7 @@ int main() { if (!device.fill(device_key) || !device.fill(iv)) { return 1; } - auto aead = aead_type::make(device_key); + auto aead = crypto::ciphers::aes256_gcm::make(device_key); wipe(std::as_writable_bytes(std::span(device_key))); if (!aead) { return 1; diff --git a/include/webcpp/crypto/ciphers/aes.hpp b/include/webcpp/crypto/ciphers/aes.hpp index 0181901a..7553e99f 100644 --- a/include/webcpp/crypto/ciphers/aes.hpp +++ b/include/webcpp/crypto/ciphers/aes.hpp @@ -41,30 +41,31 @@ struct block_state {}; * The block cipher's engine on a backend whose header does not specialise it: the family's * refusal (`detail/capabilities.hpp`). Its functions are never called: the refusal stops the * build where the class is instantiated, and they keep the compiler from adding errors of their - * own after it. + * own after it; those that return report `backend_failure`, so that a path the refusal missed + * fails closed. */ template struct block_engine { WEBCPP_CRYPTO_DETAIL_REFUSE_AES_BLOCK(Backend); - /** Never called. */ + /** Never called; fails closed. */ template [[nodiscard]] static boost::system::result init(Arguments&&... /*arguments*/) noexcept { - return {}; + return error::backend_failure; } - /** Never called. */ + /** Never called; fails closed. */ template [[nodiscard]] static boost::system::result encrypt( Arguments&&... /*arguments*/) noexcept { - return {}; + return error::backend_failure; } - /** Never called. */ + /** Never called; fails closed. */ template [[nodiscard]] static boost::system::result decrypt( Arguments&&... /*arguments*/) noexcept { - return {}; + return error::backend_failure; } /** Never called. */ diff --git a/include/webcpp/crypto/ciphers/gcm.hpp b/include/webcpp/crypto/ciphers/gcm.hpp index 3749d8aa..d7b613e8 100644 --- a/include/webcpp/crypto/ciphers/gcm.hpp +++ b/include/webcpp/crypto/ciphers/gcm.hpp @@ -44,40 +44,41 @@ struct gcm_state {}; * GCM's engine on a backend whose header does not specialise it: the family's refusal, which * names what the program needs (`detail/capabilities.hpp`). Its functions are never called: the * refusal stops the build where the class is instantiated, and they keep the compiler from - * adding errors of their own after it. + * adding errors of their own after it; those that return report `backend_failure`, so that a + * path the refusal missed fails closed. */ template struct gcm_engine { WEBCPP_CRYPTO_DETAIL_REFUSE_GCM(Backend); - /** Never called. */ + /** Never called; fails closed. */ template [[nodiscard]] static boost::system::result init(Arguments&&... /*arguments*/) noexcept { - return {}; + return error::backend_failure; } - /** Never called. */ + /** Never called; fails closed. */ template [[nodiscard]] static boost::system::result start(Arguments&&... /*arguments*/) noexcept { - return {}; + return error::backend_failure; } - /** Never called. */ + /** Never called; fails closed. */ template [[nodiscard]] static boost::system::result run(Arguments&&... /*arguments*/) noexcept { - return {}; + return error::backend_failure; } - /** Never called. */ + /** Never called; fails closed. */ template [[nodiscard]] static boost::system::result tag(Arguments&&... /*arguments*/) noexcept { - return {}; + return error::backend_failure; } - /** Never called. */ + /** Never called; fails closed. */ template [[nodiscard]] static boost::system::result check(Arguments&&... /*arguments*/) noexcept { - return {}; + return error::backend_failure; } /** Never called. */ diff --git a/include/webcpp/crypto/detail/capabilities.hpp b/include/webcpp/crypto/detail/capabilities.hpp index dad5099f..d5593b11 100644 --- a/include/webcpp/crypto/detail/capabilities.hpp +++ b/include/webcpp/crypto/detail/capabilities.hpp @@ -174,7 +174,7 @@ inline constexpr bool linked = true; /** The refusals of the family AES-GCM's primary engine for `Backend`, on native. */ #define WEBCPP_CRYPTO_DETAIL_REFUSE_GCM(Backend) \ static_assert(!std::is_same_v, "webcpp::crypto: bearssl's AES-GCM is in , which the program does not include. Include it, and add /third_party//bearssl to the program's Jamfile."); \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::openssl>, "webcpp::crypto: AES-GCM's default backend on this target is OpenSSL, which is not linked. Add /webcpp/crypto//openssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//openssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::openssl>, "webcpp::crypto: AES-GCM's default backend on this target is OpenSSL, which is not linked. Add /webcpp/crypto//openssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//openssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_OPENSSL=1 and link libcrypto)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::openssl>, "webcpp::crypto: openssl's AES-GCM is in , which the program does not include. Include it, and add /webcpp/crypto//openssl to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no AES-GCM. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no AES-GCM. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ @@ -183,7 +183,7 @@ inline constexpr bool linked = true; #elif defined(WEBCPP_TARGET_WASIP2) /** The refusals of the family AES-GCM's primary engine for `Backend`, on wasip2. */ #define WEBCPP_CRYPTO_DETAIL_REFUSE_GCM(Backend) \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::bearssl>, "webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked. Add /third_party//bearssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::bearssl>, "webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked. Add /third_party//bearssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::bearssl>, "webcpp::crypto: bearssl's AES-GCM is in , which the program does not include. Include it, and add /third_party//bearssl to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: openssl's AES-GCM is in , which the program does not include. Include it, and add /webcpp/crypto//openssl to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no AES-GCM. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ @@ -193,7 +193,7 @@ inline constexpr bool linked = true; #elif defined(WEBCPP_TARGET_WASIP3) /** The refusals of the family AES-GCM's primary engine for `Backend`, on wasip3. */ #define WEBCPP_CRYPTO_DETAIL_REFUSE_GCM(Backend) \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::bearssl>, "webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked. Add /third_party//bearssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::bearssl>, "webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked. Add /third_party//bearssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::bearssl>, "webcpp::crypto: bearssl's AES-GCM is in , which the program does not include. Include it, and add /third_party//bearssl to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: openssl's AES-GCM is in , which the program does not include. Include it, and add /webcpp/crypto//openssl to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no AES-GCM. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ @@ -203,7 +203,7 @@ inline constexpr bool linked = true; #elif defined(WEBCPP_TARGET_EMSCRIPTEN) /** The refusals of the family AES-GCM's primary engine for `Backend`, on emscripten. */ #define WEBCPP_CRYPTO_DETAIL_REFUSE_GCM(Backend) \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::bearssl>, "webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked, and the one backend that has it there. Add /third_party//bearssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ;"); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::bearssl>, "webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked, and the one backend that has it there. Add /third_party//bearssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ; (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::bearssl>, "webcpp::crypto: bearssl's AES-GCM is in , which the program does not include. Include it, and add /third_party//bearssl to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: openssl has no AES-GCM on emscripten. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no AES-GCM. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ @@ -254,7 +254,7 @@ inline constexpr bool linked = true; static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: openssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::secp256k1>, "webcpp::crypto: secp256k1's default backend on this target is libsecp256k1, which is not linked, and the one backend that has it there. Add /third_party//secp256k1 to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//secp256k1 ;"); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::secp256k1>, "webcpp::crypto: secp256k1's default backend on this target is libsecp256k1, which is not linked, and the one backend that has it there. Add /third_party//secp256k1 to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//secp256k1 ; (without b2: define WEBCPP_CRYPTO_HAS_SECP256K1=1 and link libsecp256k1 built with webcpp's src/canary_secp256k1.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::secp256k1>, "webcpp::crypto: secp256k1's secp256k1 is in , which the program does not include. Include it, and add /third_party//secp256k1 to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: sodium has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: secp256k1 has no backend of that name. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten).") @@ -264,7 +264,7 @@ inline constexpr bool linked = true; static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: openssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::secp256k1>, "webcpp::crypto: secp256k1's default backend on this target is libsecp256k1, which is not linked, and the one backend that has it there. Add /third_party//secp256k1 to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//secp256k1 ;"); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::secp256k1>, "webcpp::crypto: secp256k1's default backend on this target is libsecp256k1, which is not linked, and the one backend that has it there. Add /third_party//secp256k1 to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//secp256k1 ; (without b2: define WEBCPP_CRYPTO_HAS_SECP256K1=1 and link libsecp256k1 built with webcpp's src/canary_secp256k1.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::secp256k1>, "webcpp::crypto: secp256k1's secp256k1 is in , which the program does not include. Include it, and add /third_party//secp256k1 to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: sodium has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: secp256k1 has no backend of that name. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten).") @@ -274,7 +274,7 @@ inline constexpr bool linked = true; static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: openssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::secp256k1>, "webcpp::crypto: secp256k1's default backend on this target is libsecp256k1, which is not linked, and the one backend that has it there. Add /third_party//secp256k1 to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//secp256k1 ;"); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::secp256k1>, "webcpp::crypto: secp256k1's default backend on this target is libsecp256k1, which is not linked, and the one backend that has it there. Add /third_party//secp256k1 to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//secp256k1 ; (without b2: define WEBCPP_CRYPTO_HAS_SECP256K1=1 and link libsecp256k1 built with webcpp's src/canary_secp256k1.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::secp256k1>, "webcpp::crypto: secp256k1's secp256k1 is in , which the program does not include. Include it, and add /third_party//secp256k1 to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: sodium has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: secp256k1 has no backend of that name. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten).") @@ -284,7 +284,7 @@ inline constexpr bool linked = true; static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: openssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::secp256k1>, "webcpp::crypto: secp256k1's default backend on this target is libsecp256k1, which is not linked, and the one backend that has it there. Add /third_party//secp256k1 to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//secp256k1 ;"); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::secp256k1>, "webcpp::crypto: secp256k1's default backend on this target is libsecp256k1, which is not linked, and the one backend that has it there. Add /third_party//secp256k1 to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//secp256k1 ; (without b2: define WEBCPP_CRYPTO_HAS_SECP256K1=1 and link libsecp256k1 built with webcpp's src/canary_secp256k1.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::secp256k1>, "webcpp::crypto: secp256k1's secp256k1 is in , which the program does not include. Include it, and add /third_party//secp256k1 to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: sodium has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: secp256k1 has no backend of that name. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten).") diff --git a/test/Jamfile b/test/Jamfile index 35da824a..97946170 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -317,7 +317,8 @@ webcpp.compile doc_block : ../../../tools/test/fixtures/crypto_jamfiles/block/bl : /third_party//ctaes ; webcpp.compile doc_encrypt_and_sign : ../../../tools/test/fixtures/crypto_jamfiles/encrypt_and_sign/app.cpp - : /third_party//bearssl /third_party//secp256k1 ; + : /third_party//bearssl /third_party//secp256k1 + : wasip2 wasip3 emscripten ; webcpp.compile doc_openssl_linked : ../../../tools/test/fixtures/crypto_jamfiles/openssl_linked/app.cpp : /webcpp/crypto//openssl : native wasip2 wasip3 ; diff --git a/test/messages/gcm_default_openssl_not_linked/gcm_default_openssl_not_linked.cpp b/test/messages/gcm_default_openssl_not_linked/gcm_default_openssl_not_linked.cpp index 57378b53..5120110e 100644 --- a/test/messages/gcm_default_openssl_not_linked/gcm_default_openssl_not_linked.cpp +++ b/test/messages/gcm_default_openssl_not_linked/gcm_default_openssl_not_linked.cpp @@ -9,7 +9,7 @@ // with the line that links OpenSSL and the type that names BearSSL. // clang-format off -// expected-error@webcpp/crypto/ciphers/gcm.hpp:* {{webcpp::crypto: AES-GCM's default backend on this target is OpenSSL, which is not linked. Add /webcpp/crypto//openssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//openssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).}} +// expected-error@webcpp/crypto/ciphers/gcm.hpp:* {{webcpp::crypto: AES-GCM's default backend on this target is OpenSSL, which is not linked. Add /webcpp/crypto//openssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//openssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_OPENSSL=1 and link libcrypto)}} // clang-format on #include diff --git a/test/messages/no_backend_wasm/no_backend_wasm.cpp b/test/messages/no_backend_wasm/no_backend_wasm.cpp index f40d86cb..72f704dd 100644 --- a/test/messages/no_backend_wasm/no_backend_wasm.cpp +++ b/test/messages/no_backend_wasm/no_backend_wasm.cpp @@ -9,7 +9,7 @@ // (design D32). // clang-format off -// expected-error@webcpp/crypto/ciphers/gcm.hpp:* {{webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked. Add /third_party//bearssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).}} +// expected-error@webcpp/crypto/ciphers/gcm.hpp:* {{webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked. Add /third_party//bearssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)}} // clang-format on #include diff --git a/test/messages/openssl_only_on_wasi/openssl_only_on_wasi.cpp b/test/messages/openssl_only_on_wasi/openssl_only_on_wasi.cpp index 80c2c8ad..f2264419 100644 --- a/test/messages/openssl_only_on_wasi/openssl_only_on_wasi.cpp +++ b/test/messages/openssl_only_on_wasi/openssl_only_on_wasi.cpp @@ -9,7 +9,7 @@ // with the line that links BearSSL and the type that names OpenSSL. // clang-format off -// expected-error@webcpp/crypto/ciphers/gcm.hpp:* {{webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked. Add /third_party//bearssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).}} +// expected-error@webcpp/crypto/ciphers/gcm.hpp:* {{webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked. Add /third_party//bearssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)}} // clang-format on #include From 4da310c5c25002c6487b24d2992ad71b0cc5fb1b Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 14:05:47 -0300 Subject: [PATCH 015/110] crypto: /webcpp/crypto//gcm-default links AES-GCM's default on every target, generated with the defaults Review of Task 5', fix round 2. The guide taught a rule of the examples' Jamfile that called the internal webcpp-target module and could not be copied. generate.py now writes a block of build.jam, from families[].default as detail/defaults.hpp is, that gives each family with a default the alias /webcpp/crypto//-default: its usage requirements link the default's library on each target, OpenSSL natively and BearSSL on WebAssembly for gcm-default. --check keeps the two from drifting. The examples link gcm-default; jamfile.adoc shows the Jamfile of the new fixture gcm_default, which builds and runs on all four targets, and the use cases name the line. --- build.jam | 34 +++++++++++++++++++++++++++-- doc/changelog.adoc | 2 +- doc/generated/jamfiles.adoc | 20 +++++++++++++++-- doc/generated/use-cases.adoc | 14 ++++++++---- doc/jamfile.adoc | 23 +++++++++++++------- doc/llms.txt | 8 +++---- doc/tables/crypto.json | 11 +++++----- doc/tables/generate.py | 42 ++++++++++++++++++++++++++++++++++++ doc/tables/generate_test.py | 29 +++++++++++++++++++++++++ example/Jamfile | 25 +++++---------------- test/Jamfile | 6 ++++-- 11 files changed, 166 insertions(+), 48 deletions(-) diff --git a/build.jam b/build.jam index fe0f6f06..f43a5ffd 100644 --- a/build.jam +++ b/build.jam @@ -7,9 +7,10 @@ # crypto: authenticated encryption, randomness and secp256k1 over C backends. # A program names /webcpp/crypto//crypto and the library of each backend it # uses, /third_party// (third_party/Jamfile), or, for OpenSSL, -# /webcpp/crypto//openssl: +# /webcpp/crypto//openssl; or, for a family's default backend on every +# target, /webcpp/crypto//-default (the block at the end): # -# exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ; +# exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//gcm-default ; import webcpp-target ; @@ -45,3 +46,32 @@ alias openssl : : : : @openssl-linked emscripten:"-include \"$(WEBCPP_CRYPTO_ROOT)/src/openssl_on_emscripten.hpp\"" emscripten:"-include \"$(WEBCPP_CRYPTO_ROOT)/src/openssl_on_emscripten.hpp\"" ; # end::openssl[] + +# generate.py: begin the defaults' aliases +# Generated by doc/tables/generate.py from doc/tables/crypto.json: run it +# again, never edit this block. Each family with a default backend has the +# alias /webcpp/crypto//-default, which links the library of its +# default on each target, the backend detail/defaults.hpp chooses there. +rule gcm-default-linked ( properties * ) +{ + switch [ webcpp-target.target-of $(properties) ] + { + case native : return /webcpp/crypto//openssl ; + case wasip2 : return /third_party//bearssl ; + case wasip3 : return /third_party//bearssl ; + case emscripten : return /third_party//bearssl ; + } +} +alias gcm-default : : : : @gcm-default-linked ; +rule secp256k1-default-linked ( properties * ) +{ + switch [ webcpp-target.target-of $(properties) ] + { + case native : return /third_party//secp256k1 ; + case wasip2 : return /third_party//secp256k1 ; + case wasip3 : return /third_party//secp256k1 ; + case emscripten : return /third_party//secp256k1 ; + } +} +alias secp256k1-default : : : : @secp256k1-default-linked ; +# generate.py: end the defaults' aliases diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 135d2c78..b9a8da85 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -18,7 +18,7 @@ of every version are on webcpp's index page. // tag::unreleased[] * Added crypto, primitives over C backends: ciphers, curves and randomness, with errors of fixed values in webcpp.crypto, every result `+[[nodiscard]]+`. * Added equal, random_device, ciphers::aes128, aes192 and aes256, the AES block cipher, and ciphers::gcm, AES-GCM in place with an incremental seal whose failed open zeroes the data. -* Added default_backend_t, one default backend per family and target whatever is linked, ciphers::aes128_gcm and aes256_gcm, and refusals of missing backends naming the Jamfile line and another backend's type. +* Added default_backend_t and /webcpp/crypto//-default, one default backend per family and target whatever is linked, ciphers::aes128_gcm and aes256_gcm, and refusals naming the Jamfile line and another backend's type. * Added backends::bearssl (AES-GCM allocating nothing, no block cipher), backends::openssl through /webcpp/crypto//openssl on native and WASI (allocating at make only), and backends::ctaes (block cipher alone). * Added WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE: OpenSSL's allocations in the program's resource, refused on WebAssembly (WASI included) and without OpenSSL: openssl_memory_resource, install_memory_functions, memory_functions_refused, memory_functions_not_installed. * Added curves::secp256k1: key pairs, BIP340 and ECDSA signatures, ECDH, strict DER, low-S and the x-only tweak. diff --git a/doc/generated/jamfiles.adoc b/doc/generated/jamfiles.adoc index 5d6325f8..333dfd27 100644 --- a/doc/generated/jamfiles.adoc +++ b/doc/generated/jamfiles.adoc @@ -39,9 +39,9 @@ It prints: include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/both_bearssl_named/both_bearssl_named.outcome[tag=output] ---- -`+encrypt_and_sign+`:: Two backends in one program on WebAssembly: AES-256-GCM on its default, BearSSL, and a BIP 340 signature. +`+encrypt_and_sign+`:: Two backends in one program on every target: AES-256-GCM on its default, through `+/webcpp/crypto//gcm-default+`, and a BIP 340 signature. + -Its Jamfile, built and run on wasip2, wasip3, emscripten: +Its Jamfile, built and run on native, wasip2, wasip3, emscripten: + [listing] ---- @@ -55,6 +55,22 @@ It prints: include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/encrypt_and_sign/encrypt_and_sign.outcome[tag=output] ---- +`+gcm_default+`:: AES-256-GCM on its default on every target, with the one line `+/webcpp/crypto//gcm-default+`, which links OpenSSL natively and BearSSL on WebAssembly; the same program as `+web+`. ++ +Its Jamfile, built and run on native, wasip2, wasip3, emscripten: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/gcm_default/Jamfile[tag=jamfile] +---- ++ +It prints: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/gcm_default/gcm_default.outcome[tag=output] +---- + `+memory_option+`:: OpenSSL's allocations in the program's own resource: the define and OpenSSL in the requirements of the program's project, the resource defined once, the install first in `+main+`. + Its Jamfile, built and run on native: diff --git a/doc/generated/use-cases.adoc b/doc/generated/use-cases.adoc index 90af5b92..4b0738a9 100644 --- a/doc/generated/use-cases.adoc +++ b/doc/generated/use-cases.adoc @@ -32,13 +32,15 @@ |Encrypt a database field, a cookie or a token at rest |In `+ciphers+`: `+aes256_gcm+` |the default: OpenSSL natively, BearSSL on WebAssembly -|`+/webcpp/crypto//crypto+`; natively `+/webcpp/crypto//openssl+`, on WebAssembly `+/third_party//bearssl+` +|`+/webcpp/crypto//crypto+` + +`+/webcpp/crypto//gcm-default+` |<> |Encrypt a large file or a stream |In `+ciphers+`: `+aes256_gcm+`: records, or `+begin_seal+`, `+update+` and `+result+` |the default -|`+/webcpp/crypto//crypto+`; natively `+/webcpp/crypto//openssl+`, on WebAssembly `+/third_party//bearssl+` +|`+/webcpp/crypto//crypto+` + +`+/webcpp/crypto//gcm-default+` |<> |Tell a forged message from a malformed one @@ -71,13 +73,17 @@ |Agree on a key with a peer through a relay that sees everything |In `+curves::secp256k1+`: `+keypair::ecdh+` (SHA-256 of the shared point: not NIP-44's raw x coordinate), then HKDF on Boost.Hash2 and `+aes256_gcm+` |libsecp256k1, and AES-GCM's default -|`+/webcpp/crypto//crypto+` `+/third_party//secp256k1+`; natively `+/webcpp/crypto//openssl+`, on WebAssembly `+/third_party//bearssl+` +|`+/webcpp/crypto//crypto+` + +`+/third_party//secp256k1+` + +`+/webcpp/crypto//gcm-default+` |<> |Make and keep a wallet's key |In `+curves::secp256k1+`: `+keypair::make+`, `+xonly_public_key+`, `+public_key+`; `+aes256_gcm+` at rest |libsecp256k1, and AES-GCM's default -|`+/webcpp/crypto//crypto+` `+/third_party//secp256k1+`; natively `+/webcpp/crypto//openssl+`, on WebAssembly `+/third_party//bearssl+` +|`+/webcpp/crypto//crypto+` + +`+/third_party//secp256k1+` + +`+/webcpp/crypto//gcm-default+` |<> |Sign a Bitcoin SegWit v0 input (a domain library's job) diff --git a/doc/jamfile.adoc b/doc/jamfile.adoc index 3c1a5f45..ced13f7d 100644 --- a/doc/jamfile.adoc +++ b/doc/jamfile.adoc @@ -46,15 +46,21 @@ and the type that names BearSSL. Version 0.1's `WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL` stop the build with the type to write (<>). -A program built for every target links its default's library on each, as -the examples of this page do: a rule of its Jamfile gives the library by -target, and the program names `aes256_gcm`: +A program built for every target links its default with one line, +`/webcpp/crypto//gcm-default`, which links OpenSSL natively and BearSSL on +WebAssembly, the library of the backend `aes256_gcm` names on each target; the +examples of this page link it so. The whole Jamfile of the fixture +`gcm_default`, built and run on native, wasip2, wasip3 and Emscripten +(<>): [listing] ---- -include::{library-root}/example/Jamfile[tag=default_aead] +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/gcm_default/Jamfile[tag=jamfile] ---- +Each family with a default has such a line, `/webcpp/crypto//-default` +(`secp256k1-default` too), generated with the defaults from the same table. + The source-built OpenSSL is compiled without assembly (`no-asm`) on MSVC, wasip2 and wasip3: its AES is table-based and its GHASH 4-bit, neither constant time, and there is no AES-NI. A program for which timing attacks matter on @@ -99,10 +105,11 @@ include::generated/jamfiles.adoc[] A user builds a case from its directory with `b2` natively, `b2 toolset=emscripten` for the browser, and `b2 toolset=clang-wasip2` or `b2 toolset=clang-wasip3` for WASI, and runs the program as each target runs one: -`./app`, `node app.js`, or a WASI runtime such as wasmtime. The cases `web` and -`server` are one program, byte for byte (the test checks the copy), whose -output names the backend that ran: BearSSL, the default on WebAssembly, and -OpenSSL, the default natively. `both_bearssl_named` links both and names +`./app`, `node app.js`, or a WASI runtime such as wasmtime. The cases `web`, +`server` and `gcm_default` are one program, byte for byte (the test checks the +copies), whose output names the backend that ran: BearSSL, the default on +WebAssembly, and OpenSSL, the default natively; `gcm_default` links whichever +the target needs. `both_bearssl_named` links both and names BearSSL in the type where OpenSSL is the default. On WASI the default is BearSSL even when OpenSSL is linked (<>), so `server` is a native case; a WASI program that wants OpenSSL names the backend in the diff --git a/doc/llms.txt b/doc/llms.txt index e08d72b3..2161dfc5 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -83,14 +83,14 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [Generate a session token, a password-reset link or an API key](https://webcpporg.github.io/libs/crypto/#crypto-entropy): `random_device::fill` (webcpp::crypto); backend the system's generator; Jamfile /webcpp/crypto//crypto. Example: example/reset_token.cpp. - [Draw an unbiased number in a range, such as a six-digit code](https://webcpporg.github.io/libs/crypto/#crypto-entropy): `random_device` with `std::uniform_int_distribution` (webcpp::crypto); backend the system's generator; Jamfile /webcpp/crypto//crypto. Example: example/reset_token.cpp. - [Check a webhook's or an API's HMAC signature](https://webcpporg.github.io/libs/crypto/#crypto-equal): `equal`, with Boost.Hash2's `hmac` (webcpp::crypto); backend none; Jamfile /webcpp/crypto//crypto. Example: example/equal_hmac.cpp. -- [Encrypt a database field, a cookie or a token at rest](https://webcpporg.github.io/libs/crypto/#crypto-gcm): `aes256_gcm` (webcpp::crypto::ciphers); backend the default: OpenSSL natively, BearSSL on WebAssembly; Jamfile `/webcpp/crypto//crypto`; natively `/webcpp/crypto//openssl`, on WebAssembly `/third_party//bearssl`. Example: example/store_token.cpp. -- [Encrypt a large file or a stream](https://webcpporg.github.io/libs/crypto/#crypto-gcm-incremental): `aes256_gcm`: records, or `begin_seal`, `update` and `result` (webcpp::crypto::ciphers); backend the default; Jamfile `/webcpp/crypto//crypto`; natively `/webcpp/crypto//openssl`, on WebAssembly `/third_party//bearssl`. Example: example/sealed_records.cpp. +- [Encrypt a database field, a cookie or a token at rest](https://webcpporg.github.io/libs/crypto/#crypto-gcm): `aes256_gcm` (webcpp::crypto::ciphers); backend the default: OpenSSL natively, BearSSL on WebAssembly; Jamfile /webcpp/crypto//crypto /webcpp/crypto//gcm-default. Example: example/store_token.cpp. +- [Encrypt a large file or a stream](https://webcpporg.github.io/libs/crypto/#crypto-gcm-incremental): `aes256_gcm`: records, or `begin_seal`, `update` and `result` (webcpp::crypto::ciphers); backend the default; Jamfile /webcpp/crypto//crypto /webcpp/crypto//gcm-default. Example: example/sealed_records.cpp. - [Tell a forged message from a malformed one](https://webcpporg.github.io/libs/crypto/#crypto-errors): `error` (webcpp::crypto); backend any; Jamfile /webcpp/crypto//crypto. Example: example/failure_reasons.cpp. - [Turn a sequential id into an opaque reference](https://webcpporg.github.io/libs/crypto/#crypto-block): `aes256` (webcpp::crypto::ciphers); backend ctaes, or OpenSSL natively and on WASI; Jamfile /webcpp/crypto//crypto /third_party//ctaes. Example: example/order_reference.cpp. - [Prove who wrote a message posted to a relay](https://webcpporg.github.io/libs/crypto/#crypto-p2p-signed): `keypair::sign_schnorr`, `verify_schnorr` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/signed_message.cpp. - [Check a software update or a licence file](https://webcpporg.github.io/libs/crypto/#crypto-everyday-update): `keypair::sign_ecdsa`, `verify_ecdsa` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/signed_update.cpp. -- [Agree on a key with a peer through a relay that sees everything](https://webcpporg.github.io/libs/crypto/#crypto-p2p-session): `keypair::ecdh` (SHA-256 of the shared point: not NIP-44's raw x coordinate), then HKDF on Boost.Hash2 and `aes256_gcm` (webcpp::crypto::curves::secp256k1); backend libsecp256k1, and AES-GCM's default; Jamfile `/webcpp/crypto//crypto` `/third_party//secp256k1`; natively `/webcpp/crypto//openssl`, on WebAssembly `/third_party//bearssl`. Example: example/ecdh_session.cpp. -- [Make and keep a wallet's key](https://webcpporg.github.io/libs/crypto/#crypto-wallets-key): `keypair::make`, `xonly_public_key`, `public_key`; `aes256_gcm` at rest (webcpp::crypto::curves::secp256k1); backend libsecp256k1, and AES-GCM's default; Jamfile `/webcpp/crypto//crypto` `/third_party//secp256k1`; natively `/webcpp/crypto//openssl`, on WebAssembly `/third_party//bearssl`. Example: example/wallet_key.cpp. +- [Agree on a key with a peer through a relay that sees everything](https://webcpporg.github.io/libs/crypto/#crypto-p2p-session): `keypair::ecdh` (SHA-256 of the shared point: not NIP-44's raw x coordinate), then HKDF on Boost.Hash2 and `aes256_gcm` (webcpp::crypto::curves::secp256k1); backend libsecp256k1, and AES-GCM's default; Jamfile /webcpp/crypto//crypto /third_party//secp256k1 /webcpp/crypto//gcm-default. Example: example/ecdh_session.cpp. +- [Make and keep a wallet's key](https://webcpporg.github.io/libs/crypto/#crypto-wallets-key): `keypair::make`, `xonly_public_key`, `public_key`; `aes256_gcm` at rest (webcpp::crypto::curves::secp256k1); backend libsecp256k1, and AES-GCM's default; Jamfile /webcpp/crypto//crypto /third_party//secp256k1 /webcpp/crypto//gcm-default. Example: example/wallet_key.cpp. - [Sign a Bitcoin SegWit v0 input (a domain library's job)](https://webcpporg.github.io/libs/crypto/#crypto-wallets-der): `sign_ecdsa`, `to_der`, `normalize_ecdsa` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/ecdsa_der.cpp. - [Derive a Bitcoin Taproot output key and spend by key path (a domain library's job)](https://webcpporg.github.io/libs/crypto/#crypto-wallets-taproot): `tweak_xonly`, `keypair::tweak_xonly` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/taproot_tweak.cpp. - [Sign where allocation is restricted to the program's arena](https://webcpporg.github.io/libs/crypto/#crypto-memory): `keypair::make(secret, resource)` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/arena_signer.cpp. diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 0258d3ff..ea572f31 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -386,14 +386,14 @@ {"need": "Generate a session token, a password-reset link or an API key", "namespace": "webcpp::crypto", "api": "`random_device::fill`", "backend": "the system's generator", "jamfile": "/webcpp/crypto//crypto", "example": "reset_token", "section": "crypto-entropy"}, {"need": "Draw an unbiased number in a range, such as a six-digit code", "namespace": "webcpp::crypto", "api": "`random_device` with `std::uniform_int_distribution`", "backend": "the system's generator", "jamfile": "/webcpp/crypto//crypto", "example": "reset_token", "section": "crypto-entropy"}, {"need": "Check a webhook's or an API's HMAC signature", "namespace": "webcpp::crypto", "api": "`equal`, with Boost.Hash2's `hmac`", "backend": "none", "jamfile": "/webcpp/crypto//crypto", "example": "equal_hmac", "section": "crypto-equal"}, - {"need": "Encrypt a database field, a cookie or a token at rest", "namespace": "webcpp::crypto::ciphers", "api": "`aes256_gcm`", "backend": "the default: OpenSSL natively, BearSSL on WebAssembly", "jamfile": "`/webcpp/crypto//crypto`; natively `/webcpp/crypto//openssl`, on WebAssembly `/third_party//bearssl`", "example": "store_token", "section": "crypto-gcm"}, - {"need": "Encrypt a large file or a stream", "namespace": "webcpp::crypto::ciphers", "api": "`aes256_gcm`: records, or `begin_seal`, `update` and `result`", "backend": "the default", "jamfile": "`/webcpp/crypto//crypto`; natively `/webcpp/crypto//openssl`, on WebAssembly `/third_party//bearssl`", "example": "sealed_records", "section": "crypto-gcm-incremental"}, + {"need": "Encrypt a database field, a cookie or a token at rest", "namespace": "webcpp::crypto::ciphers", "api": "`aes256_gcm`", "backend": "the default: OpenSSL natively, BearSSL on WebAssembly", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//gcm-default", "example": "store_token", "section": "crypto-gcm"}, + {"need": "Encrypt a large file or a stream", "namespace": "webcpp::crypto::ciphers", "api": "`aes256_gcm`: records, or `begin_seal`, `update` and `result`", "backend": "the default", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//gcm-default", "example": "sealed_records", "section": "crypto-gcm-incremental"}, {"need": "Tell a forged message from a malformed one", "namespace": "webcpp::crypto", "api": "`error`", "backend": "any", "jamfile": "/webcpp/crypto//crypto", "example": "failure_reasons", "section": "crypto-errors"}, {"need": "Turn a sequential id into an opaque reference", "namespace": "webcpp::crypto::ciphers", "api": "`aes256`", "backend": "ctaes, or OpenSSL natively and on WASI", "jamfile": "/webcpp/crypto//crypto /third_party//ctaes", "example": "order_reference", "section": "crypto-block"}, {"need": "Prove who wrote a message posted to a relay", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::sign_schnorr`, `verify_schnorr`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "signed_message", "section": "crypto-p2p-signed"}, {"need": "Check a software update or a licence file", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::sign_ecdsa`, `verify_ecdsa`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "signed_update", "section": "crypto-everyday-update"}, - {"need": "Agree on a key with a peer through a relay that sees everything", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::ecdh` (SHA-256 of the shared point: not NIP-44's raw x coordinate), then HKDF on Boost.Hash2 and `aes256_gcm`", "backend": "libsecp256k1, and AES-GCM's default", "jamfile": "`/webcpp/crypto//crypto` `/third_party//secp256k1`; natively `/webcpp/crypto//openssl`, on WebAssembly `/third_party//bearssl`", "example": "ecdh_session", "section": "crypto-p2p-session"}, - {"need": "Make and keep a wallet's key", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::make`, `xonly_public_key`, `public_key`; `aes256_gcm` at rest", "backend": "libsecp256k1, and AES-GCM's default", "jamfile": "`/webcpp/crypto//crypto` `/third_party//secp256k1`; natively `/webcpp/crypto//openssl`, on WebAssembly `/third_party//bearssl`", "example": "wallet_key", "section": "crypto-wallets-key"}, + {"need": "Agree on a key with a peer through a relay that sees everything", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::ecdh` (SHA-256 of the shared point: not NIP-44's raw x coordinate), then HKDF on Boost.Hash2 and `aes256_gcm`", "backend": "libsecp256k1, and AES-GCM's default", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1 /webcpp/crypto//gcm-default", "example": "ecdh_session", "section": "crypto-p2p-session"}, + {"need": "Make and keep a wallet's key", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::make`, `xonly_public_key`, `public_key`; `aes256_gcm` at rest", "backend": "libsecp256k1, and AES-GCM's default", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1 /webcpp/crypto//gcm-default", "example": "wallet_key", "section": "crypto-wallets-key"}, {"need": "Sign a Bitcoin SegWit v0 input (a domain library's job)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`sign_ecdsa`, `to_der`, `normalize_ecdsa`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "ecdsa_der", "section": "crypto-wallets-der"}, {"need": "Derive a Bitcoin Taproot output key and spend by key path (a domain library's job)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`tweak_xonly`, `keypair::tweak_xonly`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "taproot_tweak", "section": "crypto-wallets-taproot"}, {"need": "Sign where allocation is restricted to the program's arena", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::make(secret, resource)`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "arena_signer", "section": "crypto-memory"}, @@ -407,7 +407,8 @@ "server": "A server, natively: the same program with OpenSSL, the default natively.", "both_bearssl_named": "Both backends linked, and BearSSL named in the type where the default is OpenSSL.", "block": "The AES block cipher on ctaes: the FIPS 197 block encrypted and decrypted again.", - "encrypt_and_sign": "Two backends in one program on WebAssembly: AES-256-GCM on its default, BearSSL, and a BIP 340 signature.", + "encrypt_and_sign": "Two backends in one program on every target: AES-256-GCM on its default, through `/webcpp/crypto//gcm-default`, and a BIP 340 signature.", + "gcm_default": "AES-256-GCM on its default on every target, with the one line `/webcpp/crypto//gcm-default`, which links OpenSSL natively and BearSSL on WebAssembly; the same program as `web`.", "openssl_linked": "OpenSSL, built from source, named in the type: natively and on WASI.", "sign": "A BIP 340 signature with libsecp256k1's default tables.", "sign_small": "The same program with libsecp256k1's small tables, which libsecp256k1 documents as smaller and slower to verify ({secp256k1-configure}); not measured here yet.", diff --git a/doc/tables/generate.py b/doc/tables/generate.py index 1fd6765b..4817217f 100644 --- a/doc/tables/generate.py +++ b/doc/tables/generate.py @@ -71,6 +71,10 @@ CAPABILITIES = Path('include/webcpp/crypto/detail/capabilities.hpp') CAPABILITIES_TEST = Path('test/capabilities_test.cpp') DEFAULTS = Path('include/webcpp/crypto/detail/defaults.hpp') +BUILD = Path('build.jam') +# The lines around the block of build.jam that default_aliases writes. +ALIASES_BEGIN = "# generate.py: begin the defaults' aliases" +ALIASES_END = "# generate.py: end the defaults' aliases" Data = Dict[str, Any] @@ -699,6 +703,42 @@ def needs(data: Data, family: Data, target: str, backend: str) -> str: f'that have it: {have_list(data, family)}. {without}') +def default_aliases(data: Data) -> str: + """The block of build.jam that gives each family with a default the alias + /webcpp/crypto//-default, which links the library of its default on each target, + as detail/defaults.hpp chooses it: one Jamfile line for a program built for every target.""" + out = [ALIASES_BEGIN, + '# Generated by doc/tables/generate.py from doc/tables/crypto.json: run it', + '# again, never edit this block. Each family with a default backend has the', + '# alias /webcpp/crypto//-default, which links the library of its', + '# default on each target, the backend detail/defaults.hpp chooses there.'] + for family in data['families']: + cases = [(target, default_on(family, target)) for target in data['targets']] + if not any(backend for _, backend in cases): + continue + name = family['name'] + out += [f'rule {name}-default-linked ( properties * )', '{', + ' switch [ webcpp-target.target-of $(properties) ]', ' {'] + out += [f' case {target} : return {data["backends"][backend]["jamfile"]} ;' + for target, backend in cases if backend] + out += [' }', '}', + f'alias {name}-default : : : : @{name}-default-linked ;'] + out.append(ALIASES_END) + return '\n'.join(out) + '\n' + + +def with_aliases(text: str, block: str) -> str: + """build.jam's text with its block of the defaults' aliases replaced by block.""" + lines = text.splitlines(keepends=True) + try: + begin = lines.index(ALIASES_BEGIN + '\n') + end = lines.index(ALIASES_END + '\n') + except ValueError: + raise Fault(f'build.jam has no block between "{ALIASES_BEGIN}" and "{ALIASES_END}"') \ + from None + return ''.join(lines[:begin]) + block + ''.join(lines[end + 1:]) + + def defaults_header(data: Data) -> str: """include/webcpp/crypto/detail/defaults.hpp: each family's default backend per target, chosen by the target alone (design D32), and the macro that tells the family's header which @@ -1272,6 +1312,8 @@ def generate(root: Path, library: Path) -> Dict[Path, str]: for path in list(files): files[path] = NOTICE + files[path] files[DOC / 'llms.txt'] = llms(data, matrix, library) + files[library / BUILD] = with_aliases((library / BUILD).read_text(encoding='utf-8'), + default_aliases(data)) return files diff --git a/doc/tables/generate_test.py b/doc/tables/generate_test.py index 9bf63fd1..6e308396 100644 --- a/doc/tables/generate_test.py +++ b/doc/tables/generate_test.py @@ -492,6 +492,34 @@ def test_a_row_of_some_compilers_is_labelled_with_their_names(_: Path) -> None: 'wasip2, wasip3') +def test_each_family_s_default_has_an_alias_that_links_it_per_target(_: Path) -> None: + block = generate.default_aliases(two_backends()) + assert block.startswith(generate.ALIASES_BEGIN + '\n'), block + assert block.endswith(generate.ALIASES_END + '\n'), block + assert ('rule ed25519-default-linked ( properties * )\n{\n' + ' switch [ webcpp-target.target-of $(properties) ]\n {\n' + ' case native : return /third_party//sodium ;\n' + ' case wasip2 : return /third_party//bearssl ;\n' + ' case wasip3 : return /third_party//bearssl ;\n' + ' case emscripten : return /third_party//bearssl ;\n' + ' }\n}\n' + 'alias ed25519-default : : : : @ed25519-default-linked ;\n') in block, ( + block) + # A family without a default has no alias. + data = small_table() + data['families'][0]['default'] = [a_default(EVERY_TARGET, None)] + assert 'rule' not in generate.default_aliases(data), generate.default_aliases(data) + # The block replaces the one of build.jam, whose other lines stay as they are. + old = f'head\n{generate.ALIASES_BEGIN}\nold\n{generate.ALIASES_END}\ntail\n' + assert generate.with_aliases(old, block) == f'head\n{block}tail\n' + try: + generate.with_aliases('no block\n', block) + except generate.Fault as fault: + assert 'build.jam has no block' in str(fault), fault + else: + raise AssertionError('a build.jam without the block was accepted') + + def test_a_family_without_a_default_has_no_type(_: Path) -> None: data = small_table() data['families'][0]['default'] = [a_default(EVERY_TARGET, None)] @@ -617,6 +645,7 @@ def test_the_check_names_a_file_that_differs(scratch: Path) -> None: test_a_row_of_some_compilers_is_labelled_with_their_names, test_the_other_backend_a_refusal_names_is_chosen_as_stated, test_a_family_without_a_default_has_no_type, + test_each_family_s_default_has_an_alias_that_links_it_per_target, test_the_default_s_refusal_says_what_the_program_needs, test_a_refusal_holds_on_its_target, test_a_type_names_only_crypto_s_namespaces_from_the_root, diff --git a/example/Jamfile b/example/Jamfile index 7bb28dd8..c89124f2 100644 --- a/example/Jamfile +++ b/example/Jamfile @@ -7,24 +7,9 @@ project : requirements /webcpp/crypto//crypto ; import webcpp ; -import webcpp-target ; webcpp.targets native wasip2 wasip3 emscripten ; -# The library of AES-GCM's default backend, which aes128_gcm and aes256_gcm -# name: OpenSSL natively, BearSSL on WebAssembly (the guide's "The default -# backend per target"). -# tag::default_aead[] -rule default-aead ( properties * ) -{ - if [ webcpp-target.target-of $(properties) ] = native - { - return /webcpp/crypto//openssl ; - } - return /third_party//bearssl ; -} -# end::default_aead[] - # The guide's secp256k1 program: BIP340's first vector signed and verified, then # the key pair tweaked and used again. webcpp.example schnorr_sign.cpp : /third_party//secp256k1 ; @@ -41,16 +26,16 @@ webcpp.example equal_hmac.cpp ; webcpp.example bearssl_prng.cpp : /third_party//bearssl ; # The three ways AES-GCM refuses a message, on the default backend. -webcpp.example failure_reasons.cpp : @default-aead ; +webcpp.example failure_reasons.cpp : /webcpp/crypto//gcm-default ; # A reset token and a one-time code from random_device; no backend. webcpp.example reset_token.cpp ; # An API token stored in a row, bound to the user id as additional data. -webcpp.example store_token.cpp : @default-aead ; +webcpp.example store_token.cpp : /webcpp/crypto//gcm-default ; # The incremental seal, and records bound to their numbers. -webcpp.example sealed_records.cpp : @default-aead ; +webcpp.example sealed_records.cpp : /webcpp/crypto//gcm-default ; # An order id turned into an opaque reference with the raw AES block cipher. webcpp.example order_reference.cpp : /third_party//ctaes ; @@ -62,10 +47,10 @@ webcpp.example signed_message.cpp : /third_party//secp256k1 ; webcpp.example signed_update.cpp : /third_party//secp256k1 ; # ECDH, HKDF-SHA-256 and AES-256-GCM between two peers. -webcpp.example ecdh_session.cpp : /third_party//secp256k1 @default-aead ; +webcpp.example ecdh_session.cpp : /third_party//secp256k1 /webcpp/crypto//gcm-default ; # A wallet's key pair, its secret sealed at rest and restored. -webcpp.example wallet_key.cpp : /third_party//secp256k1 @default-aead ; +webcpp.example wallet_key.cpp : /third_party//secp256k1 /webcpp/crypto//gcm-default ; # ECDSA with DER encoding and the low-S rule, as a domain library uses them. webcpp.example ecdsa_der.cpp : /third_party//secp256k1 ; diff --git a/test/Jamfile b/test/Jamfile index 97946170..99f1959b 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -317,8 +317,10 @@ webcpp.compile doc_block : ../../../tools/test/fixtures/crypto_jamfiles/block/bl : /third_party//ctaes ; webcpp.compile doc_encrypt_and_sign : ../../../tools/test/fixtures/crypto_jamfiles/encrypt_and_sign/app.cpp - : /third_party//bearssl /third_party//secp256k1 - : wasip2 wasip3 emscripten ; + : /webcpp/crypto//gcm-default /third_party//secp256k1 ; +webcpp.compile doc_gcm_default_app + : ../../../tools/test/fixtures/crypto_jamfiles/gcm_default/app.cpp + : /webcpp/crypto//gcm-default ; webcpp.compile doc_openssl_linked : ../../../tools/test/fixtures/crypto_jamfiles/openssl_linked/app.cpp : /webcpp/crypto//openssl : native wasip2 wasip3 ; From 8ea4d40f6d7827e0e1016b2acca5ca67254fd2cd Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 15:20:40 -0300 Subject: [PATCH 016/110] crypto: Ed25519 and Ed25519ph on libsodium --- README.md | 10 +- build.jam | 23 +- doc/changelog.adoc | 2 +- doc/crypto.adoc | 2 + doc/curves.adoc | 14 +- doc/ed25519.adoc | 72 +++ doc/generated/backends-ed25519_keypair.adoc | 25 + doc/generated/backends-ed25519_verify.adoc | 20 + doc/generated/backends-ed25519ph.adoc | 20 + doc/generated/defaults.adoc | 6 + doc/generated/matrix.adoc | 38 ++ doc/generated/messages.adoc | 72 +++ doc/generated/sizes.adoc | 24 + doc/generated/use-cases.adoc | 11 +- doc/llms.txt | 18 +- doc/tables/crypto.json | 74 ++- doc/tables/generate.py | 5 +- example/Jamfile | 4 + example/ed25519_sign.cpp | 103 ++++ example/ed25519_sign.expected | 7 + include/webcpp/crypto.hpp | 4 +- include/webcpp/crypto/backends/sodium.hpp | 184 +++++++ include/webcpp/crypto/curves/ed25519.hpp | 508 ++++++++++++++++++ include/webcpp/crypto/detail/capabilities.hpp | 58 ++ include/webcpp/crypto/detail/defaults.hpp | 8 + test/Jamfile | 16 +- test/capabilities_test.cpp | 36 ++ test/default_backend_test.cpp | 10 + test/ed25519_sodium_test.cpp | 264 +++++++++ test/ed25519_wycheproof_sodium_test.cpp | 83 +++ test/ed25519ph_sodium_test.cpp | 151 ++++++ test/messages/Jamfile | 3 + .../ed25519_default_not_linked/Jamfile | 12 + .../ed25519_default_not_linked.cpp | 22 + test/messages/ed25519_on_bearssl/Jamfile | 12 + .../ed25519_on_bearssl/ed25519_on_bearssl.cpp | 25 + test/messages/ed25519ph_sha256/Jamfile | 12 + .../ed25519ph_sha256/ed25519ph_sha256.cpp | 18 + test/msvc/Jamfile | 3 + test/msvc/ed25519_default_not_linked/Jamfile | 9 + test/msvc/ed25519_default_not_linked/app.cpp | 17 + test/msvc/ed25519_on_bearssl/Jamfile | 9 + test/msvc/ed25519_on_bearssl/app.cpp | 21 + test/msvc/ed25519ph_sha256/Jamfile | 9 + test/msvc/ed25519ph_sha256/app.cpp | 14 + test/support/capabilities.hpp | 18 +- 46 files changed, 2041 insertions(+), 35 deletions(-) create mode 100644 doc/ed25519.adoc create mode 100644 doc/generated/backends-ed25519_keypair.adoc create mode 100644 doc/generated/backends-ed25519_verify.adoc create mode 100644 doc/generated/backends-ed25519ph.adoc create mode 100644 example/ed25519_sign.cpp create mode 100644 example/ed25519_sign.expected create mode 100644 include/webcpp/crypto/curves/ed25519.hpp create mode 100644 test/ed25519_sodium_test.cpp create mode 100644 test/ed25519_wycheproof_sodium_test.cpp create mode 100644 test/ed25519ph_sodium_test.cpp create mode 100644 test/messages/ed25519_default_not_linked/Jamfile create mode 100644 test/messages/ed25519_default_not_linked/ed25519_default_not_linked.cpp create mode 100644 test/messages/ed25519_on_bearssl/Jamfile create mode 100644 test/messages/ed25519_on_bearssl/ed25519_on_bearssl.cpp create mode 100644 test/messages/ed25519ph_sha256/Jamfile create mode 100644 test/messages/ed25519ph_sha256/ed25519ph_sha256.cpp create mode 100644 test/msvc/ed25519_default_not_linked/Jamfile create mode 100644 test/msvc/ed25519_default_not_linked/app.cpp create mode 100644 test/msvc/ed25519_on_bearssl/Jamfile create mode 100644 test/msvc/ed25519_on_bearssl/app.cpp create mode 100644 test/msvc/ed25519ph_sha256/Jamfile create mode 100644 test/msvc/ed25519ph_sha256/app.cpp diff --git a/README.md b/README.md index eb83a678..e709ad50 100644 --- a/README.md +++ b/README.md @@ -10,14 +10,16 @@ MSVC), wasip2, wasip3 and Emscripten. 32 bytes, and the AES block cipher (`aes128`, `aes192`, `aes256`). - `webcpp::crypto::curves::secp256k1`: BIP 340 Schnorr and ECDSA signatures, their verification, ECDH, ECDSA's strict DER and low-S forms, and the x-only tweak. +- `webcpp::crypto::curves::ed25519`: Ed25519 signatures (RFC 8032) with strict verification, the + X25519 secret key of a key pair, and Ed25519ph over SHA-512 for a message given in pieces. The algorithms are those of widely used, reviewed C libraries, each a backend that a program names in its own Jamfile and that webcpp builds from its sources: BearSSL (`/third_party//bearssl`), OpenSSL 3.5.9 (`/webcpp/crypto//openssl`, never the system's, refused -on Emscripten), ctaes (`/third_party//ctaes`) and libsecp256k1 (`/third_party//secp256k1`). Which -operation runs on which backend and target is the page's generated table, from the tests that run -each. Hashing and HMAC stay with Boost.Hash2. Protocols built on these primitives (Bitcoin, -Ethereum, Nostr) belong to domain libraries. +on Emscripten), ctaes (`/third_party//ctaes`), libsecp256k1 (`/third_party//secp256k1`) and +libsodium (`/third_party//sodium`). Which operation runs on which backend and target is the +page's generated table, from the tests that run each. Hashing and HMAC stay with Boost.Hash2. +Protocols built on these primitives (Bitcoin, Ethereum, Nostr) belong to domain libraries. ## Building and testing diff --git a/build.jam b/build.jam index f43a5ffd..a868ec48 100644 --- a/build.jam +++ b/build.jam @@ -4,7 +4,8 @@ # accompanying file LICENSE_1_0.txt or copy at # https://www.boost.org/LICENSE_1_0.txt) -# crypto: authenticated encryption, randomness and secp256k1 over C backends. +# crypto: authenticated encryption, randomness, secp256k1 and Ed25519 over C +# backends. # A program names /webcpp/crypto//crypto and the library of each backend it # uses, /third_party// (third_party/Jamfile), or, for OpenSSL, # /webcpp/crypto//openssl; or, for a family's default backend on every @@ -16,11 +17,14 @@ import webcpp-target ; project /webcpp/crypto ; -# Header-only, on webcpp's configuration. random_device reads Windows' -# generator through bcrypt (BCryptGenRandom), a system library. +# Header-only, on webcpp's configuration, with webcpp::hash's header-only +# alias, whose algorithms name a signature's prehash (Ed25519ph's SHA-512; +# design D1). random_device reads Windows' generator through bcrypt +# (BCryptGenRandom), a system library. # tag::crypto[] alias crypto : : : : include /boost//headers - /webcpp/config//config windows:bcrypt ; + /webcpp/config//config /webcpp/hash//hash + windows:bcrypt ; # end::crypto[] # tag::openssl[] @@ -74,4 +78,15 @@ rule secp256k1-default-linked ( properties * ) } } alias secp256k1-default : : : : @secp256k1-default-linked ; +rule ed25519-default-linked ( properties * ) +{ + switch [ webcpp-target.target-of $(properties) ] + { + case native : return /third_party//sodium ; + case wasip2 : return /third_party//sodium ; + case wasip3 : return /third_party//sodium ; + case emscripten : return /third_party//sodium ; + } +} +alias ed25519-default : : : : @ed25519-default-linked ; # generate.py: end the defaults' aliases diff --git a/doc/changelog.adoc b/doc/changelog.adoc index b9a8da85..83a24591 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -21,7 +21,7 @@ of every version are on webcpp's index page. * Added default_backend_t and /webcpp/crypto//-default, one default backend per family and target whatever is linked, ciphers::aes128_gcm and aes256_gcm, and refusals naming the Jamfile line and another backend's type. * Added backends::bearssl (AES-GCM allocating nothing, no block cipher), backends::openssl through /webcpp/crypto//openssl on native and WASI (allocating at make only), and backends::ctaes (block cipher alone). * Added WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE: OpenSSL's allocations in the program's resource, refused on WebAssembly (WASI included) and without OpenSSL: openssl_memory_resource, install_memory_functions, memory_functions_refused, memory_functions_not_installed. -* Added curves::secp256k1: key pairs, BIP340 and ECDSA signatures, ECDH, strict DER, low-S and the x-only tweak. +* Added curves::secp256k1: key pairs, BIP340 and ECDSA signatures, ECDH, strict DER, low-S and the x-only tweak; and curves::ed25519 on libsodium: key pairs, signatures verified strictly, the X25519 secret key, and Ed25519ph over webcpp::hash's sha2_512, which /webcpp/crypto//crypto now brings. * Added backends::sodium on /third_party//sodium, shared with webcpp::hash and initialised before every engine, and every backend's link-time canary and C suite. * Added the page: a chapter per namespace and use case, the memory option's guide and example, tables generated from the tests, every Jamfile and message, and llms.txt. * Added supports_v, the capability table on the target being compiled, and the tags of its families and algorithms, which ciphers::gcm, the AES block cipher and secp256k1's key pair name. diff --git a/doc/crypto.adoc b/doc/crypto.adoc index 34d6ae07..02e6fecc 100644 --- a/doc/crypto.adoc +++ b/doc/crypto.adoc @@ -52,6 +52,8 @@ include::curves.adoc[] include::secp256k1.adoc[] +include::ed25519.adoc[] + include::backends.adoc[] include::wallets.adoc[] diff --git a/doc/curves.adoc b/doc/curves.adoc index e12d2dd8..ee0b49b8 100644 --- a/doc/curves.adoc +++ b/doc/curves.adoc @@ -15,17 +15,19 @@ back from the point to the number is infeasible. On a curve a program can on a key*, so that two parties who only exchanged public keys share a secret (link:https://en.wikipedia.org/wiki/Elliptic-curve_Diffie%E2%80%93Hellman[Wikipedia]). -The namespace `webcpp::crypto::curves` holds one curve in this version, -secp256k1 (link:https://www.secg.org/sec2-v2.pdf[SEC 2]; +The namespace `webcpp::crypto::curves` holds two curves in this version. +The first is secp256k1 (link:https://www.secg.org/sec2-v2.pdf[SEC 2]; link:https://en.bitcoin.it/wiki/Secp256k1[Bitcoin Wiki]), the curve of Bitcoin, Ethereum and Nostr. This version covers Bitcoin's keys and signatures, Nostr's event signatures (NIP-01) and the verification of Ethereum's ECDSA signatures with a known key. It does not cover Ethereum's recoverable signatures (the recovery id `v`, and the recovery of a public key from a signature), nor ECDH in the raw x-coordinate form that Nostr's encrypted -messages (NIP-44) use. A program chooses a curve for compatibility: a -signature on secp256k1 is checked only with secp256k1, and the curves of -passkeys, SSH or TLS certificates are others, which this version does not -offer. +messages (NIP-44) use. The second is Ed25519, RFC 8032's signatures on +edwards25519, with Ed25519ph for a message given in pieces +(link:https://www.rfc-editor.org/rfc/rfc8032[RFC 8032]; <>). A +program chooses a curve for compatibility: a signature on one curve is checked +only with that curve, and the curve of passkeys and TLS certificates, P-256, is +another, which this version does not offer. include::generated/namespace-curves.adoc[] diff --git a/doc/ed25519.adoc b/doc/ed25519.adoc new file mode 100644 index 00000000..ca83135b --- /dev/null +++ b/doc/ed25519.adoc @@ -0,0 +1,72 @@ +// 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) + +[#crypto-ed25519] +=== Ed25519 + +`` is Ed25519, the Edwards-curve signature +scheme of RFC 8032 (link:https://www.rfc-editor.org/rfc/rfc8032[RFC 8032]), on +libsodium (`/third_party//sodium`, or `/webcpp/crypto//ed25519-default`, which +links it on every target), in the namespace `webcpp::crypto::curves::ed25519`. +A signature is 64 bytes over a message of any length, made with a 32-byte +secret key, the seed, and checked with a 32-byte public key. The signature is +deterministic: the same key and message always give the same signature, so no +weak generator at signing time can leak the key. + +A `keypair` is made from a seed with `make(seed)`, or drawn from +`random_device` with `generate()`; it gives its public key (`public_key`), +signs (`sign`), and gives its X25519 secret key (`x25519_secret`, a +`secret<32>`), so that one seed serves for signatures and for key agreement. +The key pair wipes its secret key when it is moved from and destroyed. +`verify(public_key, message, signature)` checks a signature with the public key +alone. + +*Ed25519ph* signs the SHA-512 of a message instead of the message: a program +that signs a large file reads it in pieces, gives each to `update`, and signs +once at the end. Its type names the hash, `ph` (the +same type as Boost.Hash2's `sha2_512`), since RFC 8032 fixes it; another hash +does not compile. An Ed25519ph signature is not an Ed25519 signature of the +same message, and neither verifies as the other: a protocol says which of the +two it uses. + +include::generated/backends-ed25519_keypair.adoc[] + +include::generated/backends-ed25519_verify.adoc[] + +include::generated/backends-ed25519ph.adoc[] + +*Example.* RFC 8032's second test signed and verified, then its Ed25519ph test, +the message given in two pieces: + +[source,cpp] +---- +include::{examples}/ed25519_sign.cpp[tag=program] +---- + +[listing] +---- +include::{examples}/ed25519_sign.expected[] +---- + +*Strict verification.* Implementations of Ed25519 disagree on some signatures +that no honest signer produces: a scalar `S` not reduced below the group order, +a point encoded in a non-canonical form, a public key of small order. `verify` +takes a verification policy, `strict` by default and the only one in this +version: libsodium's rules, which refuse all three +(link:https://doc.libsodium.org/public-key_cryptography/public-key_signatures[libsodium's documentation]). +Every valid signature of Wycheproof's EdDSA file is accepted and every invalid +one refused (`ed25519_wycheproof_sodium`). Honest signatures verify everywhere; +a network that mixes verifiers must still agree on one rule for the others, +since a more lenient verifier accepts signatures that `strict` refuses. + +*Pitfalls.* + +* Keep the seed out of logs, crash reports and source control: whoever holds it +signs as the key's owner. The examples use RFC 8032's published seeds only to +print fixed signatures. +* A signature proves who signed the bytes, not when or for what: a protocol +that must refuse a replayed message signs a counter, a time or a context with +it. diff --git a/doc/generated/backends-ed25519_keypair.adoc b/doc/generated/backends-ed25519_keypair.adoc new file mode 100644 index 00000000..37caa39b --- /dev/null +++ b/doc/generated/backends-ed25519_keypair.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 `+curves::ed25519::keypair+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|BearSSL +|`+/third_party//bearssl+` +|`++` +|refused at compile time (`+ed25519_on_bearssl+`) + +|libsodium +|`+/third_party//sodium+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+ed25519_sodium+`) +|=== diff --git a/doc/generated/backends-ed25519_verify.adoc b/doc/generated/backends-ed25519_verify.adoc new file mode 100644 index 00000000..d51157b0 --- /dev/null +++ b/doc/generated/backends-ed25519_verify.adoc @@ -0,0 +1,20 @@ +// 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 `+curves::ed25519::verify+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|libsodium +|`+/third_party//sodium+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+ed25519_sodium+`, `+ed25519_wycheproof_sodium+`) +|=== diff --git a/doc/generated/backends-ed25519ph.adoc b/doc/generated/backends-ed25519ph.adoc new file mode 100644 index 00000000..646fe019 --- /dev/null +++ b/doc/generated/backends-ed25519ph.adoc @@ -0,0 +1,20 @@ +// 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 `+curves::ed25519::ph+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|libsodium +|`+/third_party//sodium+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+ed25519ph_sodium+`) +|=== diff --git a/doc/generated/defaults.adoc b/doc/generated/defaults.adoc index c62fcb88..9062c722 100644 --- a/doc/generated/defaults.adoc +++ b/doc/generated/defaults.adoc @@ -46,4 +46,10 @@ |libsecp256k1 |the only backend (link:https://github.com/bitcoin-core/secp256k1#readme[libsecp256k1's README]) |`+secp256k1+`, `+default_backend_none_linked+` + +|Ed25519 +|native, wasip2, wasip3, emscripten +|libsodium +|the only backend in this version, on every target, and its verification is the policy `strict` (link:https://doc.libsodium.org/public-key_cryptography/public-key_signatures[libsodium's documentation, public-key signatures]; link:https://www.rfc-editor.org/rfc/rfc8032[RFC 8032, the Edwards-curve Digital Signature Algorithm (EdDSA)]) +|`+ed25519_sodium+`, `+default_backend_none_linked+` |=== diff --git a/doc/generated/matrix.adoc b/doc/generated/matrix.adoc index 402d41e1..c162a2e0 100644 --- a/doc/generated/matrix.adoc +++ b/doc/generated/matrix.adoc @@ -80,6 +80,26 @@ |OpenSSL |native; not on wasip2, wasip3, emscripten: `+config.hpp+` refuses the option on every WebAssembly target |`+adapter+`, `+everything+`, `+late+`, `+foreign+`, `+fresh_install+`, `+forgotten+`, `+replaced+`, `+second_install+`, `+fail_second+`, `+fail_init+`, `+fail_init_threads+`, `+neighbours+`, `+handshake+` + +|`+curves::ed25519::keypair+` +|BearSSL +|refused at compile time +|`+ed25519_on_bearssl+` + +|`+curves::ed25519::keypair+` +|libsodium +|native, wasip2, wasip3, emscripten +|`+ed25519_sodium+` + +|`+curves::ed25519::verify+` +|libsodium +|native, wasip2, wasip3, emscripten +|`+ed25519_sodium+`, `+ed25519_wycheproof_sodium+` + +|`+curves::ed25519::ph+` +|libsodium +|native, wasip2, wasip3, emscripten +|`+ed25519ph_sodium+` |=== The same, by target: the backends each operation runs on. @@ -147,4 +167,22 @@ The same, by target: the backends each operation runs on. |none |none |none + +|`+curves::ed25519::keypair+` +|libsodium +|libsodium +|libsodium +|libsodium + +|`+curves::ed25519::verify+` +|libsodium +|libsodium +|libsodium +|libsodium + +|`+curves::ed25519::ph+` +|libsodium +|libsodium +|libsodium +|libsodium |=== diff --git a/doc/generated/messages.adoc b/doc/generated/messages.adoc index 80912ea6..7d08a410 100644 --- a/doc/generated/messages.adoc +++ b/doc/generated/messages.adoc @@ -43,6 +43,24 @@ The fix: Remove the define, and name `+gcm>+` where th The fix: Remove the define, and name `+gcm>+` where the program wants BearSSL. +|`+ed25519_default_not_linked+` +|native, wasip2, wasip3 +|`+webcpp::crypto: Ed25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)+` + +The fix: Add `+/third_party//sodium+`, or `+/webcpp/crypto//ed25519-default+`, which links it on every target. + +|`+ed25519_on_bearssl+` +|native, wasip2, wasip3 +|`+webcpp::crypto: bearssl has no Ed25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten).+` + +The fix: Leave the backend out, as in `+curves::ed25519::keypair+`, or name `+backends::sodium+`, and add `+/third_party//sodium+`. + +|`+ed25519ph_sha256+` +|native, wasip2, wasip3 +|`+webcpp::crypto: Ed25519ph is defined over SHA-512 (RFC 8032 section 5.1); name curves::ed25519::ph.+` + +The fix: Name `+curves::ed25519::ph+`: RFC 8032 defines Ed25519ph over SHA-512. + |`+gcm_default_openssl_not_linked+` |native |`+webcpp::crypto: AES-GCM's default backend on this target is OpenSSL, which is not linked. Add /webcpp/crypto//openssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//openssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_OPENSSL=1 and link libcrypto)+` @@ -364,6 +382,48 @@ On each target, the build's output contains: * emscripten: ** `+webcpp::crypto: WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL no longer chooses a default. Write the backend in the type where the program wants it, as in ciphers::gcm>.+` +`+ed25519_default_not_linked_on_emscripten+`:: A program for Emscripten that makes an Ed25519 key pair on its default, libsodium, and links none. The fix: As `+ed25519_default_not_linked+`. ++ +Its Jamfile: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/ed25519_default_not_linked_on_emscripten/Jamfile[tag=jamfile] +---- ++ +On each target, the build's output contains: ++ +* emscripten: +** `+webcpp::crypto: Ed25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)+` + +`+ed25519_on_bearssl_on_emscripten+`:: A program for Emscripten that names BearSSL, which has no Ed25519, in an Ed25519 key pair's type. The fix: As `+ed25519_on_bearssl+`. ++ +Its Jamfile: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/ed25519_on_bearssl_on_emscripten/Jamfile[tag=jamfile] +---- ++ +On each target, the build's output contains: ++ +* emscripten: +** `+webcpp::crypto: bearssl has no Ed25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten).+` + +`+ed25519ph_sha256_on_emscripten+`:: A program for Emscripten that names SHA-256 in Ed25519ph's type, which RFC 8032 defines over SHA-512. The fix: As `+ed25519ph_sha256+`. ++ +Its Jamfile: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/ed25519ph_sha256_on_emscripten/Jamfile[tag=jamfile] +---- ++ +On each target, the build's output contains: ++ +* emscripten: +** `+webcpp::crypto: Ed25519ph is defined over SHA-512 (RFC 8032 section 5.1); name curves::ed25519::ph.+` + `+has_openssl_on_emscripten+`:: OpenSSL declared linked, without b2, in a build for Emscripten. The fix: Replace `+/webcpp/crypto//openssl+` with `+/third_party//bearssl+`. + Its Jamfile: @@ -530,6 +590,18 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |Remove the define, and name `+gcm>+` where the program wants BearSSL. +|`+ed25519_default_not_linked+` +|the compile +|Add `+/third_party//sodium+`, or `+/webcpp/crypto//ed25519-default+`, which links it on every target. + +|`+ed25519_on_bearssl+` +|the compile +|Leave the backend out, as in `+curves::ed25519::keypair+`, or name `+backends::sodium+`, and add `+/third_party//sodium+`. + +|`+ed25519ph_sha256+` +|the compile +|Name `+curves::ed25519::ph+`: RFC 8032 defines Ed25519ph over SHA-512. + |`+gcm_default_openssl_not_linked+` |the compile |Natively the default is OpenSSL: add `+/webcpp/crypto//openssl+`, or name BearSSL in the type, as in `+gcm>+`. diff --git a/doc/generated/sizes.adoc b/doc/generated/sizes.adoc index af563d38..c8f32b15 100644 --- a/doc/generated/sizes.adoc +++ b/doc/generated/sizes.adoc @@ -58,4 +58,28 @@ |not measured yet |not measured yet |not measured yet + +|`+curves::ed25519::keypair+` +|not measured yet +|not measured yet +|not measured yet +|not measured yet +|not measured yet +|not measured yet + +|`+curves::ed25519::verify+` +|not measured yet +|not measured yet +|not measured yet +|not measured yet +|not measured yet +|not measured yet + +|`+curves::ed25519::ph+` +|not measured yet +|not measured yet +|not measured yet +|not measured yet +|not measured yet +|not measured yet |=== diff --git a/doc/generated/use-cases.adoc b/doc/generated/use-cases.adoc index 4b0738a9..0044100e 100644 --- a/doc/generated/use-cases.adoc +++ b/doc/generated/use-cases.adoc @@ -126,8 +126,15 @@ |`+/webcpp/crypto//crypto+` brings Boost's headers |<> -|Use P-256 (passkeys, JWT's ES256), Ed25519 or X25519 -|None in this version: secp256k1 keys and signatures do not interoperate with these curves +|Sign and verify with Ed25519 (RFC 8032), or sign a large message in pieces with Ed25519ph +|In `+curves::ed25519+`: `+keypair::make+`, `+keypair::generate+`, `+keypair::sign+`, `+verify+`; `+ph+` +|libsodium +|`+/webcpp/crypto//crypto+` + +`+/webcpp/crypto//ed25519-default+` +|<> + +|Use P-256 (passkeys, JWT's ES256) or X25519 +|None in this version: secp256k1 and Ed25519 keys and signatures do not interoperate with these curves |none |none |<> diff --git a/doc/llms.txt b/doc/llms.txt index 2161dfc5..7dd19a86 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -1,6 +1,6 @@ # webcpp::crypto -> Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA, ECDH, the x-only tweak), a random_device on the system's generator and a constant-time equal, each over a widely used, reviewed C library (BearSSL, OpenSSL, ctaes, libsecp256k1) that the program names in its Jamfile. Hashing and HMAC are Boost.Hash2's. Every failure is a boost::system::result value. Protocols (Bitcoin, Ethereum, Nostr) belong to domain libraries built on these primitives. +> Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA, ECDH, the x-only tweak), Ed25519 and Ed25519ph (RFC 8032), a random_device on the system's generator and a constant-time equal, each over a widely used, reviewed C library (BearSSL, OpenSSL, ctaes, libsecp256k1, libsodium) that the program names in its Jamfile. Hashing and HMAC are Boost.Hash2's. Every failure is a boost::system::result value. Protocols (Bitcoin, Ethereum, Nostr) belong to domain libraries built on these primitives. Generated by doc/tables/generate.py with the page's tables. Page: https://webcpporg.github.io/libs/crypto/ @@ -55,6 +55,17 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - normalize_ecdsa: The low-S form of a compact ECDSA signature (`secp256k1_ecdsa_signature_normalize`), the only form `verify_ecdsa` accepts; a low-S signature is returned unchanged. - [curves::secp256k1::tweak_xonly](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1): Tweaks an x-only public key by a 32-byte tweak a protocol computes. Header . Backends: libsecp256k1 (/third_party//secp256k1) on native, wasip2, wasip3, emscripten. - tweak_xonly: Tweaks an x-only public key by a 32-byte tweak t: P + t*G, with libsecp256k1's static context, which allocates nothing (`secp256k1_xonly_pubkey_tweak_add`). +- [curves::ed25519::keypair](https://webcpporg.github.io/libs/crypto/#crypto-ed25519): An Ed25519 key pair (RFC 8032): made from a 32-byte seed or drawn from `random_device`, its 32-byte public key, 64-byte signatures, and its X25519 secret key. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. + - make: Makes a key pair from a seed, RFC 8032's secret key. + - generate: Makes a key pair from a seed drawn from `random_device`. + - public_key: The public key. + - sign: Signs a message. + - x25519_secret: The X25519 secret key of this key pair, RFC 7748's form of the clamped first half of the seed's SHA-512. +- [curves::ed25519::verify](https://webcpporg.github.io/libs/crypto/#crypto-ed25519): Verifies an Ed25519 signature with a public key alone, under the policy `strict`: libsodium's rules, which refuse non-canonical encodings and keys of small order. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. + - verify: Verifies an Ed25519 signature under a verification policy (design D31). +- [curves::ed25519::ph](https://webcpporg.github.io/libs/crypto/#crypto-ed25519): Ed25519ph (RFC 8032): a message given in pieces, hashed with SHA-512, then signed with a key pair or verified with a public key. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. + - begin: Begins a message. + - update: Adds a piece of the message. ## Default backend per family @@ -64,6 +75,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - AES-GCM, emscripten: BearSSL; the only AEAD backend there: webcpp does not build OpenSSL for Emscripten. - AES block cipher, native, wasip2, wasip3, emscripten: none; a raw block cipher is a building block a program chooses deliberately, naming its backend; `aes256<>` takes AES-GCM's default as its argument, and its `make` does not compile where that is BearSSL. - secp256k1, native, wasip2, wasip3, emscripten: libsecp256k1; the only backend ([libsecp256k1's README](https://github.com/bitcoin-core/secp256k1#readme)). +- Ed25519, native, wasip2, wasip3, emscripten: libsodium; the only backend in this version, on every target, and its verification is the policy `strict` ([libsodium's documentation, public-key signatures](https://doc.libsodium.org/public-key_cryptography/public-key_signatures); [RFC 8032, the Edwards-curve Digital Signature Algorithm (EdDSA)](https://www.rfc-editor.org/rfc/rfc8032)). ## Rules of use @@ -97,7 +109,8 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [Keep every allocation of OpenSSL's in the program's arena](https://webcpporg.github.io/libs/crypto/#crypto-memory-openssl): `openssl_memory_resource`, `backends::openssl::install_memory_functions` (webcpp::crypto); backend OpenSSL, natively; Jamfile `/webcpp/crypto//crypto` in the program; in the project requirements, `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE` and `/webcpp/crypto//openssl`. Example: example/openssl_memory.cpp. - [Seed BearSSL's own generator for code that calls BearSSL directly](https://webcpporg.github.io/libs/crypto/#crypto-entropy-bearssl): `random_device::fill` (webcpp::crypto); backend BearSSL's C API; Jamfile /webcpp/crypto//crypto /third_party//bearssl. Example: example/bearssl_prng.cpp. - [Hash, or compute an HMAC](https://webcpporg.github.io/libs/crypto/#crypto-overview-hash2): `boost::hash2::sha2_256`, `hmac_sha2_256` (Boost.Hash2, not this library); backend none; Jamfile `/webcpp/crypto//crypto` brings Boost's headers. Example: example/equal_hmac.cpp. -- [Use P-256 (passkeys, JWT's ES256), Ed25519 or X25519](https://webcpporg.github.io/libs/crypto/#crypto-curves): secp256k1 keys and signatures do not interoperate with these curves (none in this version); backend none; Jamfile none. +- [Sign and verify with Ed25519 (RFC 8032), or sign a large message in pieces with Ed25519ph](https://webcpporg.github.io/libs/crypto/#crypto-ed25519): `keypair::make`, `keypair::generate`, `keypair::sign`, `verify`; `ph` (webcpp::crypto::curves::ed25519); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//ed25519-default. Example: example/ed25519_sign.cpp. +- [Use P-256 (passkeys, JWT's ES256) or X25519](https://webcpporg.github.io/libs/crypto/#crypto-curves): secp256k1 and Ed25519 keys and signatures do not interoperate with these curves (none in this version); backend none; Jamfile none. ## Examples @@ -106,6 +119,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - example/bearssl_prng.cpp: Seeds BearSSL's own HMAC-DRBG from webcpp::crypto::random_device and draws bytes from it. A generator is only as good as its seed: the seed must come from the system's entropy, never from the clock or a counter. - example/ecdh_session.cpp: Two peers agree on a shared secret with ECDH, derive a session key from it with HKDF-SHA-256 and talk over AES-256-GCM. The raw ECDH output is not a key: HKDF turns it into one and ties it to this application with a context string. - example/ecdsa_der.cpp: Signs with ECDSA the way a domain library does: a sighash computed by the library, a 64-byte signature, its strict DER form for the wire, and the low-S rule. The same signature has a twin with S replaced by n - S; accepting both makes transaction ids malleable, so verifiers refuse the high-S twin. +- example/ed25519_sign.cpp: Signs RFC 8032's second Ed25519 test with a key pair made from its seed and verifies the signature with the public key alone; then signs the message "abc" given in two pieces with Ed25519ph, as RFC 8032's Ed25519ph test does, and verifies it. Prints each key and signature in hex. - example/equal_hmac.cpp: Checks an HMAC-SHA-256 tag from Boost.Hash2 with webcpp::crypto::equal, the constant-time comparison. Comparing tags with == or memcmp stops at the first difference, and that timing lets an attacker guess a valid tag one byte at a time. - example/failure_reasons.cpp: Shows the three ways AES-GCM can refuse a message: a tampered ciphertext, an IV 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/openssl_memory.cpp: Sends every allocation of OpenSSL's to the program's own memory resource, natively, then seals and opens one block with AES-256-GCM on OpenSSL, on a worker thread as an audio engine's or a server's would. Built with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE, /webcpp/crypto//openssl and threads (example/Jamfile). diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index ea572f31..3a988f63 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -61,7 +61,9 @@ "secp256k1-configure": ["libsecp256k1's configure.ac, the precomputed tables' trade", "https://github.com/bitcoin-core/secp256k1/blob/master/configure.ac"], "nip44": ["Nostr NIP-44, encrypted payloads", "https://github.com/nostr-protocol/nips/blob/master/44.md"], "bip32": ["BIP 32, hierarchical deterministic wallets", "https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki"], - "openssl-mem": ["OpenSSL 3.5's OPENSSL_malloc(3), CRYPTO_set_mem_functions", "https://docs.openssl.org/3.5/man3/OPENSSL_malloc/"] + "openssl-mem": ["OpenSSL 3.5's OPENSSL_malloc(3), CRYPTO_set_mem_functions", "https://docs.openssl.org/3.5/man3/OPENSSL_malloc/"], + "rfc8032": ["RFC 8032, the Edwards-curve Digital Signature Algorithm (EdDSA)", "https://www.rfc-editor.org/rfc/rfc8032"], + "libsodium-signatures": ["libsodium's documentation, public-key signatures", "https://doc.libsodium.org/public-key_cryptography/public-key_signatures"] }, "backends": { "bearssl": { @@ -268,6 +270,43 @@ "what": "With `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE`, natively, every allocation of OpenSSL's in the process goes to a `std::pmr::memory_resource` the program defines.", "section": "crypto-memory-openssl", "backends": {"openssl": {"tests": ["adapter", "everything", "late", "foreign", "fresh_install", "forgotten", "replaced", "second_install", "fail_second", "fail_init", "fail_init_threads", "neighbours", "handshake"], "elsewhere": "memory"}} + }, + { + "id": "ed25519_keypair", + "family": "ed25519", + "functions": ["make", "generate", "public_key", "sign", "x25519_secret"], + "namespace": "curves", + "api": "curves::ed25519::keypair", + "header": "", + "what": "An Ed25519 key pair (RFC 8032): made from a 32-byte seed or drawn from `random_device`, its 32-byte public key, 64-byte signatures, and its X25519 secret key.", + "section": "crypto-ed25519", + "backends": { + "sodium": {"tests": ["ed25519_sodium"]}, + "bearssl": {"refused": "ed25519_on_bearssl"} + } + }, + { + "id": "ed25519_verify", + "family": "ed25519", + "free": true, + "functions": ["verify"], + "namespace": "curves", + "api": "curves::ed25519::verify", + "header": "", + "what": "Verifies an Ed25519 signature with a public key alone, under the policy `strict`: libsodium's rules, which refuse non-canonical encodings and keys of small order.", + "section": "crypto-ed25519", + "backends": {"sodium": {"tests": ["ed25519_sodium", "ed25519_wycheproof_sodium"]}} + }, + { + "id": "ed25519ph", + "family": "ed25519", + "functions": ["begin", "update"], + "namespace": "curves", + "api": "curves::ed25519::ph", + "header": "", + "what": "Ed25519ph (RFC 8032): a message given in pieces, hashed with SHA-512, then signed with a key pair or verified with a public key.", + "section": "crypto-ed25519", + "backends": {"sodium": {"tests": ["ed25519ph_sodium"]}} } ], "families": [ @@ -328,6 +367,23 @@ "backends": { "secp256k1": {"targets": "all"} } + }, + { + "name": "ed25519", + "title": "Ed25519", + "group": "curves::ed25519", + "since": "0.2", + "header": "", + "names": [ + {"name": "ed25519", "title": "Ed25519", "type": "curves::ed25519::basic_keypair<{backend}>"}, + {"name": "ed25519ph", "title": "Ed25519ph", "type": "curves::ed25519::ph"} + ], + "default": [ + {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": ["ed25519_sodium", "default_backend_none_linked"], "why": "the only backend in this version, on every target, and its verification is the policy `strict` ({libsodium-signatures}; {rfc8032})"} + ], + "backends": { + "sodium": {"targets": "all"} + } } ], "rules": [ @@ -400,7 +456,8 @@ {"need": "Keep every allocation of OpenSSL's in the program's arena", "namespace": "webcpp::crypto", "api": "`openssl_memory_resource`, `backends::openssl::install_memory_functions`", "backend": "OpenSSL, natively", "jamfile": "`/webcpp/crypto//crypto` in the program; in the project requirements, `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE` and `/webcpp/crypto//openssl`", "example": "openssl_memory", "section": "crypto-memory-openssl"}, {"need": "Seed BearSSL's own generator for code that calls BearSSL directly", "namespace": "webcpp::crypto", "api": "`random_device::fill`", "backend": "BearSSL's C API", "jamfile": "/webcpp/crypto//crypto /third_party//bearssl", "example": "bearssl_prng", "section": "crypto-entropy-bearssl"}, {"need": "Hash, or compute an HMAC", "namespace": "Boost.Hash2, not this library", "api": "`boost::hash2::sha2_256`, `hmac_sha2_256`", "backend": "none", "jamfile": "`/webcpp/crypto//crypto` brings Boost's headers", "example": "equal_hmac", "section": "crypto-overview-hash2"}, - {"need": "Use P-256 (passkeys, JWT's ES256), Ed25519 or X25519", "namespace": "none in this version", "api": "secp256k1 keys and signatures do not interoperate with these curves", "backend": "none", "jamfile": "none", "example": "", "section": "crypto-curves"} + {"need": "Sign and verify with Ed25519 (RFC 8032), or sign a large message in pieces with Ed25519ph", "namespace": "webcpp::crypto::curves::ed25519", "api": "`keypair::make`, `keypair::generate`, `keypair::sign`, `verify`; `ph`", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//ed25519-default", "example": "ed25519_sign", "section": "crypto-ed25519"}, + {"need": "Use P-256 (passkeys, JWT's ES256) or X25519", "namespace": "none in this version", "api": "secp256k1 and Ed25519 keys and signatures do not interoperate with these curves", "backend": "none", "jamfile": "none", "example": "", "section": "crypto-curves"} ], "fixtures": { "web": "A web application: AES-256-GCM on BearSSL, the default on WebAssembly.", @@ -430,7 +487,10 @@ "memory_option": "OpenSSL's allocations in the program's own resource: the define and OpenSSL in the requirements of the program's project, the resource defined once, the install first in `main`.", "no_backend_on_emscripten": "A program for Emscripten that uses the default backend and links none.", "canary_sodium_other_commit": "A libsodium of another commit than the headers'.", - "sodium_not_linked_on_emscripten": "A program for Emscripten that names libsodium and links none." + "sodium_not_linked_on_emscripten": "A program for Emscripten that names libsodium and links none.", + "ed25519_default_not_linked_on_emscripten": "A program for Emscripten that makes an Ed25519 key pair on its default, libsodium, and links none.", + "ed25519_on_bearssl_on_emscripten": "A program for Emscripten that names BearSSL, which has no Ed25519, in an Ed25519 key pair's type.", + "ed25519ph_sha256_on_emscripten": "A program for Emscripten that names SHA-256 in Ed25519ph's type, which RFC 8032 defines over SHA-512." }, "fixes": { "gcm_default_openssl_not_linked": "Natively the default is OpenSSL: add `/webcpp/crypto//openssl`, or name BearSSL in the type, as in `gcm>`.", @@ -469,6 +529,12 @@ "no_backend_on_emscripten": "Add `/third_party//bearssl` to the program's sources.", "canary_secp256k1_two_files": "Compile every file of the program with the same backend settings.", "canary_two_files": "Compile every file of the program with the same backend settings.", - "openssl_not_linked_msvc": "As `openssl_not_linked`." + "openssl_not_linked_msvc": "As `openssl_not_linked`.", + "ed25519_on_bearssl": "Leave the backend out, as in `curves::ed25519::keypair`, or name `backends::sodium`, and add `/third_party//sodium`.", + "ed25519_on_bearssl_on_emscripten": "As `ed25519_on_bearssl`.", + "ed25519ph_sha256": "Name `curves::ed25519::ph`: RFC 8032 defines Ed25519ph over SHA-512.", + "ed25519ph_sha256_on_emscripten": "As `ed25519ph_sha256`.", + "ed25519_default_not_linked": "Add `/third_party//sodium`, or `/webcpp/crypto//ed25519-default`, which links it on every target.", + "ed25519_default_not_linked_on_emscripten": "As `ed25519_default_not_linked`." } } diff --git a/doc/tables/generate.py b/doc/tables/generate.py index 4817217f..279eb350 100644 --- a/doc/tables/generate.py +++ b/doc/tables/generate.py @@ -1229,8 +1229,9 @@ def llms(data: Data, matrix: Matrix, library: Path) -> str: out = ['# webcpp::crypto', '', '> Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: ' 'AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA, ECDH, the x-only ' - 'tweak), a random_device on the system\'s generator and a constant-time equal, each ' - 'over a widely used, reviewed C library (BearSSL, OpenSSL, ctaes, libsecp256k1) that ' + 'tweak), Ed25519 and Ed25519ph (RFC 8032), a random_device on the system\'s generator ' + 'and a constant-time equal, each over a widely used, reviewed C library (BearSSL, ' + 'OpenSSL, ctaes, libsecp256k1, libsodium) that ' 'the program names in its Jamfile. Hashing and HMAC are Boost.Hash2\'s. Every ' 'failure is a boost::system::result value. Protocols (Bitcoin, Ethereum, Nostr) ' 'belong to domain libraries built on these primitives.', '', diff --git a/example/Jamfile b/example/Jamfile index c89124f2..e1e0cb5d 100644 --- a/example/Jamfile +++ b/example/Jamfile @@ -70,3 +70,7 @@ webcpp.example openssl_memory.cpp multi : native ; # end::openssl_memory[] + +# The guide's Ed25519 program: RFC 8032's second test signed and verified, then +# Ed25519ph's test given in two pieces, on the family's default. +webcpp.example ed25519_sign.cpp : /webcpp/crypto//ed25519-default ; diff --git a/example/ed25519_sign.cpp b/example/ed25519_sign.cpp new file mode 100644 index 00000000..2bae6c5a --- /dev/null +++ b/example/ed25519_sign.cpp @@ -0,0 +1,103 @@ +// 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) + +// Signs RFC 8032's second Ed25519 test with a key pair made from its seed and verifies the +// signature with the public key alone; then signs the message "abc" given in two pieces with +// Ed25519ph, as RFC 8032's Ed25519ph test does, and verifies it. Prints each key and signature +// in hex. +// tag::program[] +#include + +#include + +#include +#include +#include +#include +#include + +namespace ed25519 = webcpp::crypto::curves::ed25519; + +namespace { + +// Prints bytes in hex after a name, 32 bytes (64 digits) to a line, the lines after the first +// indented under the first, so that a long value stays readable on a narrow page. +void print(char const* name, std::span bytes) { + int const indent = std::printf("%s ", name); + for (std::size_t i = 0; i < bytes.size(); ++i) { + if (i != 0 && i % 32 == 0) { + std::printf("\n%*s", indent, ""); + } + std::printf("%02x", bytes[i]); + } + std::printf("\n"); +} + +// Ed25519: one message in one call. +bool sign_whole() { + // RFC 8032 section 7.1, TEST 2: a published seed, never a real key; a program draws its + // own with keypair::generate(). + std::array const seed{ + 0x4c, 0xcd, 0x08, 0x9b, 0x28, 0xff, 0x96, 0xda, 0x9d, 0xb6, 0xc3, + 0x46, 0xec, 0x11, 0x4e, 0x0f, 0x5b, 0x8a, 0x31, 0x9f, 0x35, 0xab, + 0xa6, 0x24, 0xda, 0x8c, 0xf6, 0xed, 0x4f, 0xb8, 0xa6, 0xfb, + }; + std::array const message{0x72}; + auto const key = ed25519::keypair::make(seed); + if (!key) { + return false; + } + auto const public_key = key->public_key(); + auto const signature = key->sign(message); + if (!public_key || !signature) { + return false; + } + print("public key", *public_key); + print("signature ", *signature); + // The verifier holds the public key, the message and the signature; nothing secret. + return ed25519::verify(*public_key, message, *signature).has_value(); +} + +// Ed25519ph: the message given in pieces, as a large file is read, signed once at the end. +// webcpp::hash::sha2_512 names Boost.Hash2's sha2_512, the hash RFC 8032 fixes. +bool sign_in_pieces() { + std::array const seed{ + 0x83, 0x3f, 0xe6, 0x24, 0x09, 0x23, 0x7b, 0x9d, 0x62, 0xec, 0x77, + 0x58, 0x75, 0x20, 0x91, 0x1e, 0x9a, 0x75, 0x9c, 0xec, 0x1d, 0x19, + 0x75, 0x5b, 0x7d, 0xa9, 0x01, 0xb9, 0x6d, 0xca, 0x3d, 0x42, + }; + std::array const first{'a'}; + std::array const second{'b', 'c'}; + using signer = ed25519::ph; + auto const key = ed25519::keypair::make(seed); + auto signing = signer::begin(); + if (!key || !signing || !signing->update(first) || !signing->update(second)) { + return false; + } + auto const public_key = key->public_key(); + auto const signature = signing->sign(*key); + if (!public_key || !signature) { + return false; + } + print("public key", *public_key); + print("signature ", *signature); + auto verifying = signer::begin(); + return verifying && verifying->update(first) && verifying->update(second) && + verifying->verify(*public_key, *signature).has_value(); +} + +} // namespace + +int main() { + if (!sign_whole() || !sign_in_pieces()) { + std::printf("failed\n"); + return 1; + } + std::printf("verified\n"); + return 0; +} + +// end::program[] diff --git a/example/ed25519_sign.expected b/example/ed25519_sign.expected new file mode 100644 index 00000000..7bccf783 --- /dev/null +++ b/example/ed25519_sign.expected @@ -0,0 +1,7 @@ +public key 3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c +signature 92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da + 085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00 +public key ec172b93ad5e563bf4932c70e1245034c35467ef2efd4d64ebf819683467e2bf +signature 98a70222f0b8121aa9d30f813d683f809e462b469c7ff87639499bb94e6dae41 + 31f85042463c2a355a2003d062adf5aaa10b8c61e636062aaad11c2a26083406 +verified diff --git a/include/webcpp/crypto.hpp b/include/webcpp/crypto.hpp index 2f8a8b21..fd00244a 100644 --- a/include/webcpp/crypto.hpp +++ b/include/webcpp/crypto.hpp @@ -6,7 +6,8 @@ /** Every header of webcpp::crypto that needs no backend, the header of each backend the build - links, and `ciphers/aes256_gcm.hpp`, whose `aes128_gcm` and `aes256_gcm` name AES-GCM's default + links with the curves it holds (libsecp256k1's secp256k1, libsodium's Ed25519), and + `ciphers/aes256_gcm.hpp`, whose `aes128_gcm` and `aes256_gcm` name AES-GCM's default backend: a program that does not link the default names another in the type, as `ciphers::gcm>` on WebAssembly. */ @@ -37,6 +38,7 @@ #ifdef WEBCPP_CRYPTO_HAS_SODIUM #include +#include #endif #ifdef WEBCPP_CRYPTO_HAS_SECP256K1 diff --git a/include/webcpp/crypto/backends/sodium.hpp b/include/webcpp/crypto/backends/sodium.hpp index 288cd585..6ecc9c94 100644 --- a/include/webcpp/crypto/backends/sodium.hpp +++ b/include/webcpp/crypto/backends/sodium.hpp @@ -72,3 +72,187 @@ namespace webcpp::crypto::detail { #endif // WEBCPP_CRYPTO_HAS_SODIUM #endif // WEBCPP_CRYPTO_BACKENDS_SODIUM_HPP + +// Ed25519 and Ed25519ph on libsodium, for a program that includes curves/ed25519.hpp, before +// this header or after it: outside the guard above, so that curves/ed25519.hpp, which includes +// this header last, gets them either way; a program that does not include it pays nothing. +#if defined(WEBCPP_CRYPTO_CURVES_ED25519_HPP) && defined(WEBCPP_CRYPTO_HAS_SODIUM) && \ + !defined(WEBCPP_CRYPTO_BACKENDS_SODIUM_ED25519) +/** Defined once libsodium's Ed25519 engines are. */ +#define WEBCPP_CRYPTO_BACKENDS_SODIUM_ED25519 + +#include + +#include + +#include +#include +#include + +namespace webcpp::crypto::detail { + +/** What an Ed25519 key pair stores on libsodium. */ +template <> +struct ed25519_state { + /** libsodium's secret key: the seed, then the public key. */ + std::array secret_key{}; +}; + +/** Ed25519 on libsodium: strict verification, `crypto_sign_ed25519_verify_detached`. */ +template <> +struct ed25519_engine { + /** The key pair's state. */ + using state = ed25519_state; + + /** + * Makes the secret key of a seed, `crypto_sign_ed25519_seed_keypair`. + * + * @return Nothing; `backend_failure`. + */ + [[nodiscard]] static boost::system::result make( + state& keyed, std::span seed) noexcept { + auto const ready = sodium_ready(); + if (!ready) { + return ready; + } + std::array public_key{}; + if (crypto_sign_ed25519_seed_keypair(public_key.data(), keyed.secret_key.data(), + seed.data()) != 0) { + return error::backend_failure; + } + return {}; + } + + /** The public key, the secret key's second half. */ + static void public_key(state const& keyed, std::span out) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); + static_cast(crypto_sign_ed25519_sk_to_pk(out.data(), keyed.secret_key.data())); + } + + /** + * Signs a message, `crypto_sign_ed25519_detached`. + * + * @return Nothing; `backend_failure`. + */ + [[nodiscard]] static boost::system::result sign( + state const& keyed, std::span message, + std::span out) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); + if (crypto_sign_ed25519_detached(out.data(), nullptr, message.data(), message.size(), + keyed.secret_key.data()) != 0) { + return error::backend_failure; + } + return {}; + } + + /** + * Verifies a signature, `crypto_sign_ed25519_verify_detached`: the policy `strict`. + * + * @return Nothing; `invalid_signature`; `backend_failure`. + */ + [[nodiscard]] static boost::system::result verify( + std::span public_key, std::span message, + std::span signature) noexcept { + auto const ready = sodium_ready(); + if (!ready) { + return ready; + } + if (crypto_sign_ed25519_verify_detached(signature.data(), message.data(), message.size(), + public_key.data()) != 0) { + return error::invalid_signature; + } + return {}; + } + + /** + * The X25519 secret key, `crypto_sign_ed25519_sk_to_curve25519`. + * + * @return Nothing; `backend_failure`. + */ + [[nodiscard]] static boost::system::result x25519_secret( + state const& keyed, std::span out) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); + if (crypto_sign_ed25519_sk_to_curve25519(out.data(), keyed.secret_key.data()) != 0) { + return error::backend_failure; + } + return {}; + } + + /** Wipes the secret key. */ + static void reset(state& keyed) noexcept { wipe_object(keyed.secret_key); } +}; + +/** What an Ed25519ph signer stores on libsodium: the message's SHA-512 state. */ +template <> +struct ed25519ph_state { + /** libsodium's state. */ + crypto_sign_ed25519ph_state hashing{}; +}; + +/** Ed25519ph on libsodium, `crypto_sign_ed25519ph_*`. */ +template <> +struct ed25519ph_engine { + /** The signer's state. */ + using state = ed25519ph_state; + + /** + * Begins a message, `crypto_sign_ed25519ph_init`. + * + * @return Nothing; `backend_failure`. + */ + [[nodiscard]] static boost::system::result begin(state& begun) noexcept { + auto const ready = sodium_ready(); + if (!ready) { + return ready; + } + if (crypto_sign_ed25519ph_init(&begun.hashing) != 0) { + return error::backend_failure; + } + return {}; + } + + /** Adds a piece, `crypto_sign_ed25519ph_update`, which cannot fail. */ + static void update(state& begun, std::span piece) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); + static_cast(crypto_sign_ed25519ph_update(&begun.hashing, piece.data(), piece.size())); + } + + /** + * Signs the message, `crypto_sign_ed25519ph_final_create`. + * + * @return Nothing; `backend_failure`. + */ + [[nodiscard]] static boost::system::result sign( + state& begun, ed25519_state const& keyed, + std::span out) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); + if (crypto_sign_ed25519ph_final_create(&begun.hashing, out.data(), nullptr, + keyed.secret_key.data()) != 0) { + return error::backend_failure; + } + return {}; + } + + /** + * Verifies a signature of the message, `crypto_sign_ed25519ph_final_verify`, strict. + * + * @return Nothing; `invalid_signature`. + */ + [[nodiscard]] static boost::system::result verify( + state& begun, std::span public_key, + std::span signature) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); + if (crypto_sign_ed25519ph_final_verify(&begun.hashing, signature.data(), + public_key.data()) != 0) { + return error::invalid_signature; + } + return {}; + } + + /** Wipes the message's state. */ + static void reset(state& begun) noexcept { wipe_object(begun.hashing); } +}; + +} // namespace webcpp::crypto::detail + +#endif // Ed25519 on libsodium diff --git a/include/webcpp/crypto/curves/ed25519.hpp b/include/webcpp/crypto/curves/ed25519.hpp new file mode 100644 index 00000000..af93338d --- /dev/null +++ b/include/webcpp/crypto/curves/ed25519.hpp @@ -0,0 +1,508 @@ +// 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) + +/** + Ed25519 signatures (RFC 8032): a key pair made from a 32-byte seed, signatures of 64 bytes, + and verification, strict on libsodium; and Ed25519ph, the same signature over SHA-512 of a + message given in pieces. + + The family's default backend, libsodium on every target, is included when the program links + it; a program that uses the family without linking it stops where it calls it, with the + Jamfile line that links it. + + @see "Ed25519", in the guide. +*/ +#ifndef WEBCPP_CRYPTO_CURVES_ED25519_HPP +#define WEBCPP_CRYPTO_CURVES_ED25519_HPP + +#include + +#include +#include +#include +#include +#include // lint-world: random_device draws generate()'s seed +#include + +// webcpp::hash::sha2_512, Ed25519ph's hash, is this type (webcpp/hash/algorithms.hpp); its header +// is not included, so that crypto's headers declare nothing of hash's beside crypto's own. +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace webcpp::crypto::detail { + +/** + * What an Ed25519 key pair stores on a backend whose header does not specialise it: nothing, + * since its engine refuses the backend where the family is called. + */ +template +struct ed25519_state {}; + +/** The work of Ed25519 on a backend; the primary refuses (defined at the end of this header). */ +template +struct ed25519_engine; + +/** What an Ed25519ph signer stores on a backend (see @ref ed25519_state). */ +template +struct ed25519ph_state {}; + +/** The work of Ed25519ph on a backend; the primary refuses (defined at the end of this header). */ +template +struct ed25519ph_engine; + +} // namespace webcpp::crypto::detail + +namespace webcpp::crypto::curves::ed25519 { + +template +class ph; + +/** + * An Ed25519 key pair (RFC 8032): its secret key, kept by the backend and wiped by every move + * and by the destructor, and its public key. + * + * @tparam Backend The backend; by default the family's (`default_backend_t`). + */ +template > +class basic_keypair { + using state_type = detail::ed25519_state; + using engine = detail::ed25519_engine; + + template + friend class ph; + +public: + /** The family, for `supports_v`. */ + using family_type = families::ed25519; + /** The algorithm, for `supports_v`. */ + using name_type = families::ed25519; + /** The backend. */ + using backend_type = Backend; + /** The seed's size. */ + static constexpr std::size_t seed_size = 32; + /** The public key's size. */ + static constexpr std::size_t public_key_size = 32; + /** The signature's size. */ + static constexpr std::size_t signature_size = 64; + + /** + * Makes a key pair from a seed, RFC 8032's secret key. + * + * @param seed 32 bytes. + * @return The key pair; `invalid_key_size`; `backend_failure`. + */ + static boost::system::result make(std::span seed) noexcept { + if (seed.size() != seed_size) { + return error::invalid_key_size; + } + basic_keypair made; + auto const keyed = engine::make(made.state_, seed.template first()); + if (!keyed) { + return keyed.error(); + } + made.keyed_ = true; + return made; + } + + /** + * Makes a key pair from a seed drawn from `random_device`. + * + * @return The key pair; `entropy_unavailable` when the system's generator fails or there is + * none; `backend_failure`. + */ + static boost::system::result generate() noexcept { + secret seed; + auto const drawn = random_device().fill(seed.writable()); // lint-world: the seed + if (!drawn) { + // The generator's not_supported (an Emscripten audio worklet) is the same failure + // for a key pair: one error to handle. + return error::entropy_unavailable; + } + return make(seed.bytes()); + } + + /** + * Moves the key pair; the source is wiped and empty. + * + * @param other The key pair moved from. + */ + basic_keypair(basic_keypair&& other) noexcept : keyed_(std::exchange(other.keyed_, false)) { + state_ = other.state_; + engine::reset(other.state_); + } + + /** + * Moves over this key pair, which is wiped first. + * + * @param other The key pair moved from, wiped and empty after. + * @return This key pair. + */ + basic_keypair& operator=(basic_keypair&& other) noexcept { + if (this != &other) { + engine::reset(state_); + keyed_ = std::exchange(other.keyed_, false); + state_ = other.state_; + engine::reset(other.state_); + } + return *this; + } + + /** Not copyable: a secret key has one owner. */ + basic_keypair(basic_keypair const&) = delete; + /** Not copyable: a secret key has one owner. */ + basic_keypair& operator=(basic_keypair const&) = delete; + + /** Wipes the secret key. */ + ~basic_keypair() { engine::reset(state_); } + + /** + * The public key. + * + * @return 32 bytes; `invalid_state` moved from. + */ + [[nodiscard]] boost::system::result> public_key() const noexcept { + if (!keyed_) { + return error::invalid_state; + } + std::array key{}; + engine::public_key(state_, key); + return key; + } + + /** + * Signs a message. + * + * @param message Any bytes. + * @return The 64-byte signature; `invalid_state`; `backend_failure`. + */ + [[nodiscard]] boost::system::result> sign( + std::span message) const noexcept { + if (!keyed_) { + return error::invalid_state; + } + std::array signature{}; + auto const signed_message = engine::sign(state_, message, signature); + if (!signed_message) { + return signed_message.error(); + } + return signature; + } + + /** + * The X25519 secret key of this key pair, RFC 7748's form of the clamped first half of the + * seed's SHA-512. + * + * @return 32 secret bytes; `invalid_state`; `backend_failure`. + */ + [[nodiscard]] boost::system::result> x25519_secret() const noexcept { + if (!keyed_) { + return error::invalid_state; + } + secret<32> converted; + auto const done = engine::x25519_secret(state_, converted.writable()); + if (!done) { + return done.error(); + } + return converted; + } + +private: + basic_keypair() noexcept = default; + + state_type state_{}; + bool keyed_ = false; +}; + +/** The key pair on the default backend. */ +using keypair = basic_keypair<>; + +/** + * Ed25519 verification as libsodium does it: `S` below the group order, `A` and `R` canonical, + * neither of small order (design D31). + */ +struct strict {}; + +/** + * Verifies an Ed25519 signature under a verification policy (design D31). + * + * @tparam Policy `strict` (libsodium's rules), the only policy declared. + * @tparam Backend The backend; by default the family's. + * @param public_key 32 bytes. + * @param message The signed bytes. + * @param signature 64 bytes. + * @return Nothing; `invalid_public_key` for a key of another size; `invalid_signature`. + */ +template > +boost::system::result verify(std::span public_key, + std::span message, + std::span signature) noexcept { + static_assert(std::is_same_v, + "webcpp::crypto: Ed25519's only verification policy is curves::ed25519::strict."); + if (public_key.size() != 32) { + return error::invalid_public_key; + } + if (signature.size() != 64) { + return error::invalid_signature; + } + return detail::ed25519_engine::verify( + public_key.first<32>(), message, signature.first<64>()); +} + +/** + * Ed25519ph (RFC 8032 section 5.1), the Ed25519 signature of a message's SHA-512, given in + * pieces. + * + * A large message need not be held whole: the signer is begun, updated with each piece, then + * signs with a key pair or verifies with a public key, either of which ends the message. Its + * state is wiped by every move, by the end of a message and by the destructor. + * + * Its signature is not Ed25519's of the same message: a verifier is told which of the two a + * protocol uses. + * + * @tparam Hash `webcpp::hash::sha2_512`, which RFC 8032 fixes (Boost.Hash2's `sha2_512`, the + * same type); any other is refused. + * @tparam Backend The backend; by default the family's (`default_backend_t`). + */ +template > +class ph { + // clang-format off + static_assert(std::is_same_v, "webcpp::crypto: Ed25519ph is defined over SHA-512 (RFC 8032 section 5.1); name curves::ed25519::ph."); + // clang-format on + + using state_type = detail::ed25519ph_state; + using engine = detail::ed25519ph_engine; + +public: + /** The family, for `supports_v`. */ + using family_type = families::ed25519; + /** The algorithm, for `supports_v`. */ + using name_type = tags::ed25519ph; + /** The backend. */ + using backend_type = Backend; + /** The hash, SHA-512. */ + using hash_type = Hash; + /** The signature's size. */ + static constexpr std::size_t signature_size = 64; + + /** + * Begins a message. + * + * @return The signer, ready for the message's pieces; `backend_failure`. + */ + static boost::system::result begin() noexcept { + ph begun; + auto const started = engine::begin(begun.state_); + if (!started) { + return started.error(); + } + begun.begun_ = true; + return begun; + } + + /** + * Moves the signer and its message; the source is wiped and ended. + * + * @param other The signer moved from. + */ + ph(ph&& other) noexcept : begun_(std::exchange(other.begun_, false)) { + state_ = other.state_; + engine::reset(other.state_); + } + + /** + * Moves over this signer, whose message is wiped first. + * + * @param other The signer moved from, wiped and ended after. + * @return This signer. + */ + ph& operator=(ph&& other) noexcept { + if (this != &other) { + engine::reset(state_); + begun_ = std::exchange(other.begun_, false); + state_ = other.state_; + engine::reset(other.state_); + } + return *this; + } + + /** Not copyable: the state of a message has one owner. */ + ph(ph const&) = delete; + /** Not copyable: the state of a message has one owner. */ + ph& operator=(ph const&) = delete; + + /** Wipes the state of the message. */ + ~ph() { engine::reset(state_); } + + /** + * Adds a piece of the message. + * + * @param piece Any bytes, empty included. + * @return Nothing; `invalid_state` once the message is signed or verified, or moved from. + */ + boost::system::result update(std::span piece) noexcept { + if (!begun_) { + return error::invalid_state; + } + engine::update(state_, piece); + return {}; + } + + /** + * Signs the message given, which it ends. + * + * @param key The key pair, of the same backend. + * @return The 64-byte signature; `invalid_state` once the message is ended, or moved from, + * or with a moved-from key pair; `backend_failure`. + */ + [[nodiscard]] boost::system::result> sign( + basic_keypair const& key) noexcept { + if (!begun_ || !key.keyed_) { + return error::invalid_state; + } + std::array signature{}; + auto const signed_message = engine::sign(state_, key.state_, signature); + end(); + if (!signed_message) { + return signed_message.error(); + } + return signature; + } + + /** + * Verifies a signature of the message given, which it ends, strictly (design D31). + * + * @param public_key 32 bytes. + * @param signature 64 bytes. + * @return Nothing; `invalid_state` once the message is ended, or moved from; + * `invalid_public_key` for a key of another size; `invalid_signature`. + */ + [[nodiscard]] boost::system::result verify( + std::span public_key, + std::span signature) noexcept { + if (!begun_) { + return error::invalid_state; + } + boost::system::result verified = error::invalid_signature; + if (public_key.size() != 32) { + verified = error::invalid_public_key; + } else if (signature.size() == 64) { + verified = engine::verify(state_, public_key.first<32>(), signature.first<64>()); + } + end(); + return verified; + } + +private: + ph() noexcept = default; + + // The message is ended: its state is wiped, and only begin makes another. + void end() noexcept { + engine::reset(state_); + begun_ = false; + } + + state_type state_{}; + bool begun_ = false; +}; + +} // namespace webcpp::crypto::curves::ed25519 + +namespace webcpp::crypto::detail { + +/** + * Ed25519's engine on a backend whose header does not specialise it: the family's refusal, + * which names what the program needs (`detail/capabilities.hpp`). Its functions are never + * called: the refusal stops the build where the class is instantiated, and they keep the + * compiler from adding errors of their own after it; those that return report + * `backend_failure`, so that a path the refusal missed fails closed. + */ +template +struct ed25519_engine { + WEBCPP_CRYPTO_DETAIL_REFUSE_ED25519(Backend); + + /** Never called; fails closed. */ + template + [[nodiscard]] static boost::system::result make(Arguments&&... /*arguments*/) noexcept { + return error::backend_failure; + } + + /** Never called. */ + template + static void public_key(Arguments&&... /*arguments*/) noexcept {} + + /** Never called; fails closed. */ + template + [[nodiscard]] static boost::system::result sign(Arguments&&... /*arguments*/) noexcept { + return error::backend_failure; + } + + /** Never called; fails closed. */ + template + [[nodiscard]] static boost::system::result verify(Arguments&&... /*arguments*/) noexcept { + return error::backend_failure; + } + + /** Never called; fails closed. */ + template + [[nodiscard]] static boost::system::result x25519_secret( + Arguments&&... /*arguments*/) noexcept { + return error::backend_failure; + } + + /** Never called. */ + template + static void reset(Arguments&&... /*arguments*/) noexcept {} +}; + +/** Ed25519ph's engine on a backend whose header does not specialise it (see @ref ed25519_engine). + */ +template +struct ed25519ph_engine { + WEBCPP_CRYPTO_DETAIL_REFUSE_ED25519(Backend); + + /** Never called; fails closed. */ + template + [[nodiscard]] static boost::system::result begin(Arguments&&... /*arguments*/) noexcept { + return error::backend_failure; + } + + /** Never called. */ + template + static void update(Arguments&&... /*arguments*/) noexcept {} + + /** Never called; fails closed. */ + template + [[nodiscard]] static boost::system::result sign(Arguments&&... /*arguments*/) noexcept { + return error::backend_failure; + } + + /** Never called; fails closed. */ + template + [[nodiscard]] static boost::system::result verify(Arguments&&... /*arguments*/) noexcept { + return error::backend_failure; + } + + /** Never called. */ + template + static void reset(Arguments&&... /*arguments*/) noexcept {} +}; + +} // namespace webcpp::crypto::detail + +// The default backend's engines, when the program links it (design D32): libsodium on every +// target. Its header specialises them for this header, wherever it was first included. +#if defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_ED25519_SODIUM) && defined(WEBCPP_CRYPTO_HAS_SODIUM) +#include +#endif + +#endif // WEBCPP_CRYPTO_CURVES_ED25519_HPP diff --git a/include/webcpp/crypto/detail/capabilities.hpp b/include/webcpp/crypto/detail/capabilities.hpp index d5593b11..372c6103 100644 --- a/include/webcpp/crypto/detail/capabilities.hpp +++ b/include/webcpp/crypto/detail/capabilities.hpp @@ -33,6 +33,11 @@ struct aes_block; /** The family secp256k1, of `curves::secp256k1`, also the tag of its one algorithm. */ struct secp256k1; +/** + * The family Ed25519, of `curves::ed25519`; its algorithms: `families::ed25519`, `tags::ed25519ph`. + */ +struct ed25519; + } // namespace webcpp::crypto::families namespace webcpp::crypto::tags { @@ -55,6 +60,9 @@ struct aes192; /** AES-256, of the family `families::aes_block`. */ struct aes256; +/** Ed25519ph, of the family `families::ed25519`. */ +struct ed25519ph; + } // namespace webcpp::crypto::tags namespace webcpp::crypto::detail { @@ -131,6 +139,15 @@ inline constexpr bool supported inline constexpr bool supported = true; #endif +// Ed25519 on sodium: native, wasip2, wasip3, emscripten. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool supported = true; +#endif // clang-format on /** @@ -289,6 +306,47 @@ inline constexpr bool linked = true; static_assert(!std::is_same_v, "webcpp::crypto: sodium has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: secp256k1 has no backend of that name. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten).") #endif +#ifdef WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE +/** The refusals of the family Ed25519's primary engine for `Backend`, on native. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_ED25519(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no Ed25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no Ed25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no Ed25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no Ed25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: Ed25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's Ed25519 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: Ed25519 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_WASIP2) +/** The refusals of the family Ed25519's primary engine for `Backend`, on wasip2. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_ED25519(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no Ed25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no Ed25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no Ed25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no Ed25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: Ed25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's Ed25519 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: Ed25519 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_WASIP3) +/** The refusals of the family Ed25519's primary engine for `Backend`, on wasip3. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_ED25519(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no Ed25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no Ed25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no Ed25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no Ed25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: Ed25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's Ed25519 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: Ed25519 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_EMSCRIPTEN) +/** The refusals of the family Ed25519's primary engine for `Backend`, on emscripten. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_ED25519(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no Ed25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no Ed25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no Ed25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no Ed25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: Ed25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's Ed25519 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: Ed25519 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#endif // clang-format on #endif // WEBCPP_CRYPTO_DETAIL_CAPABILITIES_HPP diff --git a/include/webcpp/crypto/detail/defaults.hpp b/include/webcpp/crypto/detail/defaults.hpp index 965af4da..5b6c224b 100644 --- a/include/webcpp/crypto/detail/defaults.hpp +++ b/include/webcpp/crypto/detail/defaults.hpp @@ -58,6 +58,14 @@ struct default_backend_of { /** `backends::secp256k1`. */ using type = backends::secp256k1; }; +/** Defined where libsodium is the default of Ed25519. */ +#define WEBCPP_CRYPTO_DETAIL_DEFAULT_ED25519_SODIUM 1 +/** The default of Ed25519 on native, wasip2, wasip3, emscripten: libsodium. */ +template <> +struct default_backend_of { + /** `backends::sodium`. */ + using type = backends::sodium; +}; // clang-format on /** diff --git a/test/Jamfile b/test/Jamfile index 99f1959b..280c640d 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -50,8 +50,10 @@ webcpp.headers-alone crypto : ../include : crypto/backends/openssl.hpp # The backend ctaes's header alone, with ctaes linked, on every target. webcpp.headers-alone crypto : ../include : crypto/backends/ctaes.hpp : /third_party//ctaes ; -# The backend libsodium's header alone, with libsodium linked, on every target. -webcpp.headers-alone crypto : ../include : crypto/backends/sodium.hpp +# The backend libsodium's header alone, and Ed25519's with it, with libsodium +# linked, on every target. +webcpp.headers-alone crypto : ../include + : crypto/backends/sodium.hpp crypto/curves/ed25519.hpp : /third_party//sodium ; # libsecp256k1's headers compile alone only with its library, which defines # WEBCPP_CRYPTO_HAS_SECP256K1 (without it, each stops with its message). @@ -257,6 +259,16 @@ crypto-run aes_ctaes : aes_ctaes_test.cpp : /third_party//ctaes ; # The backend libsodium: its canary, its initialisation and its three layers. crypto-run sodium_backend : sodium_backend_test.cpp : /third_party//sodium ; +# Ed25519 on libsodium: RFC 8032's tests, the guards, generate() under the +# planted entropy source and the conversion to X25519; Wycheproof's EdDSA +# file, strict; Ed25519ph, RFC 8032's test in one piece and in two. +crypto-run ed25519_sodium : ed25519_sodium_test.cpp + : /third_party//sodium WEBCPP_CRYPTO_DETAIL_TEST_ENTROPY ; +crypto-run ed25519_wycheproof_sodium : ed25519_wycheproof_sodium_test.cpp + : /third_party//sodium /third_party//wycheproof + /webcpp//boost_json ; +crypto-run ed25519ph_sodium : ed25519ph_sodium_test.cpp : /third_party//sodium ; + # The capability table of doc/tables/crypto.json, which generate.py writes # this test from: supports_v of every cell on the target, and each present # cell made, with every backend the target builds linked. diff --git a/test/capabilities_test.cpp b/test/capabilities_test.cpp index 7d3fe38f..a2a55985 100644 --- a/test/capabilities_test.cpp +++ b/test/capabilities_test.cpp @@ -15,6 +15,7 @@ #include #include +#include #include #include #include @@ -73,6 +74,12 @@ struct refuses_secp256k1 { WEBCPP_CRYPTO_DETAIL_REFUSE_SECP256K1(Backend); }; +/** The refusals of Ed25519, parsed: nothing instantiates it. */ +template +struct refuses_ed25519 { + WEBCPP_CRYPTO_DETAIL_REFUSE_ED25519(Backend); +}; + } // namespace // clang-format off @@ -178,6 +185,29 @@ static_assert(!crypto::supports_v, backends::sodium>); +// Ed25519 on bearssl: none. +static_assert(!crypto::supports_v, backends::bearssl>); +static_assert(!crypto::supports_v, backends::bearssl>); +// Ed25519 on openssl: none. +static_assert(!crypto::supports_v, backends::openssl>); +static_assert(!crypto::supports_v, backends::openssl>); +// Ed25519 on ctaes: none. +static_assert(!crypto::supports_v, backends::ctaes>); +static_assert(!crypto::supports_v, backends::ctaes>); +// Ed25519 on secp256k1: none. +static_assert(!crypto::supports_v, backends::secp256k1>); +static_assert(!crypto::supports_v, backends::secp256k1>); +// Ed25519 on sodium: native, wasip2, wasip3, emscripten. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_v, backends::sodium>); +#else +static_assert(!crypto::supports_v, backends::sodium>); +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_v, backends::sodium>); +#else +static_assert(!crypto::supports_v, backends::sodium>); +#endif // clang-format on int main() { @@ -220,6 +250,12 @@ int main() { #endif #if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN)) && defined(WEBCPP_CRYPTO_HAS_SECP256K1) BOOST_TEST((webcpp::test::made, families::secp256k1, families::secp256k1, backends::secp256k1>())); +#endif +#if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN)) && defined(WEBCPP_CRYPTO_HAS_SODIUM) + BOOST_TEST((webcpp::test::made, families::ed25519, families::ed25519, backends::sodium>())); +#endif +#if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN)) && defined(WEBCPP_CRYPTO_HAS_SODIUM) + BOOST_TEST((webcpp::test::made, families::ed25519, tags::ed25519ph, backends::sodium>())); #endif // clang-format on return webcpp::test::exit_status(boost::report_errors()); diff --git a/test/default_backend_test.cpp b/test/default_backend_test.cpp index 4fceab44..24f3d744 100644 --- a/test/default_backend_test.cpp +++ b/test/default_backend_test.cpp @@ -55,3 +55,13 @@ static_assert(!has_default); static_assert(std::is_same_v, backends::secp256k1>); static_assert(crypto::detail::supported>); + +// Ed25519 and Ed25519ph: libsodium, the only backend, on every target. +static_assert(std::is_same_v, backends::sodium>); +#ifndef WEBCPP_CRYPTO_DETAIL_DEFAULT_ED25519_SODIUM +#error "curves/ed25519.hpp is told to include another header than libsodium's" +#endif +static_assert(crypto::detail::supported>); +static_assert(crypto::detail::supported>); diff --git a/test/ed25519_sodium_test.cpp b/test/ed25519_sodium_test.cpp new file mode 100644 index 00000000..03bf0183 --- /dev/null +++ b/test/ed25519_sodium_test.cpp @@ -0,0 +1,264 @@ +// 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) + +// Ed25519 on libsodium: RFC 8032 section 7.1's tests 1, 2, 3 and SHA(abc), each key pair made +// from the RFC's secret key, its public key and signature the RFC's, and verify accepting them; +// the guards (a seed of 31 bytes, a moved-from key pair, a signature changed in one bit, keys and +// signatures of other sizes); generate() under the planted entropy source of the test seam +// WEBCPP_CRYPTO_DETAIL_TEST_ENTROPY, failing and answering; and x25519_secret(), whose public key +// is crypto_sign_ed25519_pk_to_curve25519's of the Ed25519 public key. + +#include +#include +#include + +#include "support/hex.hpp" + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace crypto = webcpp::crypto; +namespace ed25519 = webcpp::crypto::curves::ed25519; +namespace test = webcpp::test; + +namespace { + +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the planted source's script +bool entropy_fails = false; + +} // namespace + +// The planted source: 0x42 in every byte, or -1 with EIO, as getentropy fails. +extern "C" int webcpp_test_entropy(void* output_bytes, std::size_t byte_count) { + if (entropy_fails) { + errno = EIO; + return -1; + } + std::memset(output_bytes, 0x42, byte_count); + return 0; +} + +namespace { + +/** One test of RFC 8032 section 7.1, as the RFC writes it. */ +struct rfc8032_case { + std::string_view name; + std::string_view secret_key; + std::string_view public_key; + std::string_view message; + std::string_view signature; +}; + +// clang-format off +constexpr auto rfc8032_cases = std::to_array({ + {.name = "TEST 1", + .secret_key = "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", + .public_key = "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a", + .message = "", + .signature = "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b", + }, + {.name = "TEST 2", + .secret_key = "4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb", + .public_key = "3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c", + .message = "72", + .signature = "92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00", + }, + {.name = "TEST 3", + .secret_key = "c5aa8df43f9f837bedb7442f31dcb7b166d38535076f094b85ce3a2e0b4458f7", + .public_key = "fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025", + .message = "af82", + .signature = "6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac18ff9b538d16f290ae67f760984dc6594a7c15e9716ed28dc027beceea1ec40a", + }, + {.name = "TEST SHA(abc)", + .secret_key = "833fe62409237b9d62ec77587520911e9a759cec1d19755b7da901b96dca3d42", + .public_key = "ec172b93ad5e563bf4932c70e1245034c35467ef2efd4d64ebf819683467e2bf", + .message = "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f", + .signature = "dc2a4459e7369633a52b1bf277839a00201009a3efbf3ecb69bea2186c26b58909351fc9ac90b3ecfdfbc7c66431e0303dca179c138ac17ad9bef1177331a704", + }, +}); +// clang-format on + +void rfc8032() { + for (auto const& tested : rfc8032_cases) { + auto const seed = test::from_hex(tested.secret_key); + auto const expected_public_key = test::from_hex(tested.public_key); + auto const message = test::from_hex(tested.message); + auto const expected_signature = test::from_hex(tested.signature); + + auto const key = ed25519::keypair::make(seed); + BOOST_TEST(key.has_value()); + if (!key) { + continue; + } + auto const public_key = key->public_key(); + BOOST_TEST(public_key && std::ranges::equal(*public_key, expected_public_key)); + auto const signature = key->sign(message); + BOOST_TEST(signature && std::ranges::equal(*signature, expected_signature)); + if (!signature || !public_key) { + continue; + } + // The default policy, and strict named, on the default backend and on libsodium named. + BOOST_TEST(ed25519::verify(*public_key, message, *signature).has_value()); + BOOST_TEST((ed25519::verify(*public_key, message, + *signature) + .has_value())); + BOOST_TEST(ed25519::verify(expected_public_key, message, expected_signature).has_value()); + } +} + +void guards() { + auto const seed = test::from_hex(rfc8032_cases[1].secret_key); + auto const message = test::from_hex(rfc8032_cases[1].message); + + // A seed of 31 or 33 bytes is not a seed. + auto const short_seed = ed25519::keypair::make(std::span(seed).first(31)); + BOOST_TEST(short_seed.has_error() && short_seed.error() == crypto::error::invalid_key_size); + std::vector long_seed(seed); + long_seed.push_back(0); + auto const long_made = ed25519::keypair::make(long_seed); + BOOST_TEST(long_made.has_error() && long_made.error() == crypto::error::invalid_key_size); + + // A moved-from key pair is empty: every member says invalid_state; the target works. + auto made = ed25519::keypair::make(seed); + BOOST_TEST(made.has_value()); + if (!made) { + return; + } + ed25519::keypair source = std::move(*made); + ed25519::keypair target = std::move(source); + // NOLINTBEGIN(bugprone-use-after-move,clang-analyzer-cplusplus.Move): the moved-from state + // is what is tested + BOOST_TEST(source.public_key().error() == crypto::error::invalid_state); + BOOST_TEST(source.sign(message).error() == crypto::error::invalid_state); + BOOST_TEST(source.x25519_secret().error() == crypto::error::invalid_state); + // NOLINTEND(bugprone-use-after-move,clang-analyzer-cplusplus.Move) + auto const signature = target.sign(message); + BOOST_TEST(signature && + std::ranges::equal(*signature, test::from_hex(rfc8032_cases[1].signature))); + + // Moved over: the target takes the key, the source is empty. + auto other = ed25519::keypair::make(test::from_hex(rfc8032_cases[0].secret_key)); + BOOST_TEST(other.has_value()); + if (other) { + target = std::move(*other); + auto const first = target.public_key(); + BOOST_TEST(first && + std::ranges::equal(*first, test::from_hex(rfc8032_cases[0].public_key))); + // NOLINTNEXTLINE(bugprone-use-after-move,clang-analyzer-cplusplus.Move): tested + BOOST_TEST(other->public_key().error() == crypto::error::invalid_state); + } +} + +void refusals() { + auto const message = test::from_hex(rfc8032_cases[1].message); + // A signature changed in one bit, of R or of S, and a message changed in one bit. + auto const public_key = test::from_hex(rfc8032_cases[1].public_key); + auto const good = test::from_hex(rfc8032_cases[1].signature); + for (std::size_t const index : + {std::size_t{0}, std::size_t{31}, std::size_t{32}, std::size_t{63}}) { + auto changed = good; + changed[index] ^= 0x01U; + auto const refused = ed25519::verify(public_key, message, changed); + BOOST_TEST(refused.has_error() && refused.error() == crypto::error::invalid_signature); + } + auto changed_message = message; + changed_message[0] ^= 0x01U; + BOOST_TEST(ed25519::verify(public_key, changed_message, good).error() == + crypto::error::invalid_signature); + + // A public key or a signature of another size. + BOOST_TEST(ed25519::verify(std::span(public_key).first(31), message, good).error() == + crypto::error::invalid_public_key); + BOOST_TEST(ed25519::verify(public_key, message, std::span(good).first(63)).error() == + crypto::error::invalid_signature); + std::vector long_signature(good); + long_signature.push_back(0); + BOOST_TEST(ed25519::verify(public_key, message, long_signature).error() == + crypto::error::invalid_signature); +} + +void generated() { + // The source fails: no key pair, entropy_unavailable. + entropy_fails = true; + auto const refused = ed25519::keypair::generate(); + BOOST_TEST(refused.has_error() && refused.error() == crypto::error::entropy_unavailable); + + // The source answers: the key pair of the seed it gave, 32 bytes of 0x42. + entropy_fails = false; + auto const drawn = ed25519::keypair::generate(); + std::array seed{}; + seed.fill(0x42); + auto const made = ed25519::keypair::make(seed); + BOOST_TEST(drawn.has_value() && made.has_value()); + if (drawn && made) { + auto const drawn_key = drawn->public_key(); + auto const made_key = made->public_key(); + BOOST_TEST(drawn_key && made_key && *drawn_key == *made_key); + } +} + +void conversion() { + for (auto const& tested : rfc8032_cases) { + auto const key = ed25519::keypair::make(test::from_hex(tested.secret_key)); + BOOST_TEST(key.has_value()); + if (!key) { + continue; + } + auto const x25519_secret = key->x25519_secret(); + BOOST_TEST(x25519_secret.has_value()); + if (!x25519_secret) { + continue; + } + static_assert( + std::is_same_v, crypto::secret<32>>); + // The X25519 public key of the converted secret is libsodium's conversion of the + // Ed25519 public key. + std::array from_secret{}; + BOOST_TEST_EQ( + crypto_scalarmult_curve25519_base(from_secret.data(), x25519_secret->bytes().data()), + 0); + std::array from_public{}; + auto const public_key = test::from_hex(tested.public_key); + BOOST_TEST_EQ(crypto_sign_ed25519_pk_to_curve25519(from_public.data(), public_key.data()), + 0); + BOOST_TEST(from_secret == from_public); + } +} + +} // namespace + +int main() { + static_assert( + std::is_same_v>); + static_assert(std::is_same_v); + static_assert(std::is_same_v); + static_assert(ed25519::keypair::seed_size == 32 && ed25519::keypair::public_key_size == 32 && + ed25519::keypair::signature_size == 64); + static_assert(!std::is_copy_constructible_v && + !std::is_copy_assignable_v); + static_assert(std::is_nothrow_move_constructible_v && + std::is_nothrow_move_assignable_v); + rfc8032(); + guards(); + refusals(); + generated(); + conversion(); + return test::exit_status(boost::report_errors()); +} diff --git a/test/ed25519_wycheproof_sodium_test.cpp b/test/ed25519_wycheproof_sodium_test.cpp new file mode 100644 index 00000000..31b3853d --- /dev/null +++ b/test/ed25519_wycheproof_sodium_test.cpp @@ -0,0 +1,83 @@ +// 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) + +// Ed25519 against Wycheproof's EdDSA file (testvectors_v1/ed25519_test.json) through +// curves::ed25519::verify on libsodium, strict: every valid case accepted and every invalid +// case refused with invalid_signature, without exception (a disagreement is reported, never +// listed away). + +#include +#include +#include + +#include "support/hex.hpp" +#include "support/test_data.hpp" + +#include +#include + +#include +#include +#include +#include + +namespace crypto = webcpp::crypto; +namespace ed25519 = webcpp::crypto::curves::ed25519; +namespace test = webcpp::test; +namespace json = boost::json; + +namespace { + +std::string text_of(json::value const& value) { + return std::string(std::string_view(value.as_string())); +} + +} // namespace + +int main() { + auto const document_text = + test::read_file(WEBCPP_TEST_WYCHEPROOF "/testvectors_v1/ed25519_test.json"); + boost::system::error_code parse_error; + auto const document = json::parse(document_text, parse_error); + BOOST_TEST(!parse_error); + if (parse_error) { + return test::exit_status(boost::report_errors()); + } + int total = 0; + int accepted = 0; + int refused = 0; + for (auto const& group : document.at("testGroups").as_array()) { + auto const public_key = test::from_hex(text_of(group.at("publicKey").at("pk"))); + for (auto const& tested : group.at("tests").as_array()) { + ++total; + auto const message = test::from_hex(text_of(tested.at("msg"))); + auto const signature = test::from_hex(text_of(tested.at("sig"))); + auto const verdict = text_of(tested.at("result")); + auto const verified = ed25519::verify(public_key, message, signature); + auto label = "tcId " + std::to_string(tested.at("tcId").to_number()); + if (verdict == "valid") { + ++accepted; + if (!verified) { + BOOST_ERROR((label += ": a valid signature refused").c_str()); + } + } else if (verdict == "invalid") { + ++refused; + if (verified || verified.error() != crypto::error::invalid_signature) { + BOOST_ERROR((label += ": an invalid signature not refused as invalid_signature") + .c_str()); + } + } else { + BOOST_ERROR(((label += ": the verdict ") += verdict).c_str()); + } + } + } + std::cout << "ed25519 wycheproof: tests=" << total << " valid=" << accepted + << " invalid=" << refused << '\n'; + BOOST_TEST_EQ(total, 151); + BOOST_TEST_EQ(accepted, 88); + BOOST_TEST_EQ(refused, 63); + return test::exit_status(boost::report_errors()); +} diff --git a/test/ed25519ph_sodium_test.cpp b/test/ed25519ph_sodium_test.cpp new file mode 100644 index 00000000..2c718b06 --- /dev/null +++ b/test/ed25519ph_sodium_test.cpp @@ -0,0 +1,151 @@ +// 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) + +// Ed25519ph on libsodium: RFC 8032 section 7.3's test, the message "abc" given in one piece and +// in two, signed into the RFC's signature and verified; a signature changed in one bit and a +// different message refused; a message is signed or verified once, and a moved-from signer and +// a moved-from key pair are refused with invalid_state. + +#include +#include +#include + +#include "support/hex.hpp" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace crypto = webcpp::crypto; +namespace ed25519 = webcpp::crypto::curves::ed25519; +namespace test = webcpp::test; + +namespace { + +// webcpp::hash::sha2_512, which a program names, is Boost.Hash2's sha2_512 +// (webcpp/hash/algorithms.hpp); hash's header is left out of crypto's tests. +using signer = ed25519::ph; + +// RFC 8032 section 7.3, TEST abc. +constexpr char const* secret_key = + "833fe62409237b9d62ec77587520911e9a759cec1d19755b7da901b96dca3d42"; +constexpr char const* public_key_hex = + "ec172b93ad5e563bf4932c70e1245034c35467ef2efd4d64ebf819683467e2bf"; +// clang-format off +constexpr char const* signature_hex = "98a70222f0b8121aa9d30f813d683f809e462b469c7ff87639499bb94e6dae4131f85042463c2a355a2003d062adf5aaa10b8c61e636062aaad11c2a26083406"; +// clang-format on + +/** The message in the pieces given, signed or verified by a signer begun for it. */ +signer begun(std::vector> const& pieces) { + auto started = signer::begin(); + BOOST_TEST(started.has_value()); + for (auto const& piece : pieces) { + BOOST_TEST(started->update(piece).has_value()); + } + return std::move(*started); +} + +void rfc8032_ph() { + auto const key = ed25519::keypair::make(test::from_hex(secret_key)); + BOOST_TEST(key.has_value()); + if (!key) { + return; + } + auto const public_key = test::from_hex(public_key_hex); + auto const expected = test::from_hex(signature_hex); + std::vector const abc{0x61, 0x62, 0x63}; + std::vector> const one_piece{abc}; + std::vector> const two_pieces{{0x61}, {0x62, 0x63}}; + std::vector> const with_empty{{}, {0x61, 0x62}, {}, {0x63}}; + for (auto const& pieces : {one_piece, two_pieces, with_empty}) { + auto signing = begun(pieces); + auto const signature = signing.sign(*key); + BOOST_TEST(signature && std::ranges::equal(*signature, expected)); + auto verifying = begun(pieces); + BOOST_TEST(verifying.verify(public_key, expected).has_value()); + } + + // Changed in one bit, the signature is refused; so is another message. + auto changed = expected; + changed[40] ^= 0x01U; + auto verifying = begun(two_pieces); + BOOST_TEST(verifying.verify(public_key, changed).error() == crypto::error::invalid_signature); + auto other = begun({{0x61, 0x62}}); + BOOST_TEST(other.verify(public_key, expected).error() == crypto::error::invalid_signature); + + // Ed25519ph's signature is not Ed25519's of the same message. + BOOST_TEST(ed25519::verify(public_key, abc, expected).error() == + crypto::error::invalid_signature); + + // Keys and signatures of other sizes. + auto short_key = begun(one_piece); + BOOST_TEST(short_key.verify(std::span(public_key).first(31), expected).error() == + crypto::error::invalid_public_key); + auto short_signature = begun(one_piece); + BOOST_TEST(short_signature.verify(public_key, std::span(expected).first(63)).error() == + crypto::error::invalid_signature); +} + +void spent_and_moved() { + auto key = ed25519::keypair::make(test::from_hex(secret_key)); + BOOST_TEST(key.has_value()); + if (!key) { + return; + } + std::vector const abc{0x61, 0x62, 0x63}; + + // A message is signed once: the signer is then spent until begun again. + auto signing = begun({abc}); + BOOST_TEST(signing.sign(*key).has_value()); + BOOST_TEST(signing.update(abc).error() == crypto::error::invalid_state); + BOOST_TEST(signing.sign(*key).error() == crypto::error::invalid_state); + BOOST_TEST( + signing.verify(test::from_hex(public_key_hex), test::from_hex(signature_hex)).error() == + crypto::error::invalid_state); + + // Moved, the target carries the message on; the source is spent. + auto first = begun({{0x61}}); + signer second = std::move(first); + // NOLINTBEGIN(bugprone-use-after-move,clang-analyzer-cplusplus.Move): the moved-from state + // is what is tested + BOOST_TEST(first.update(abc).error() == crypto::error::invalid_state); + // NOLINTEND(bugprone-use-after-move,clang-analyzer-cplusplus.Move) + BOOST_TEST(second.update(std::vector{0x62, 0x63}).has_value()); + auto third = begun({}); + third = std::move(second); + auto const signature = third.sign(*key); + BOOST_TEST(signature && std::ranges::equal(*signature, test::from_hex(signature_hex))); + + // A moved-from key pair signs nothing, and the message stays to be signed. + ed25519::keypair const taken = std::move(*key); + auto fourth = begun({abc}); + // NOLINTNEXTLINE(bugprone-use-after-move,clang-analyzer-cplusplus.Move): tested + BOOST_TEST(fourth.sign(*key).error() == crypto::error::invalid_state); + auto const after = fourth.sign(taken); + BOOST_TEST(after && std::ranges::equal(*after, test::from_hex(signature_hex))); +} + +} // namespace + +int main() { + static_assert( + std::is_same_v>); + static_assert(std::is_same_v); + static_assert(std::is_same_v); + static_assert(!std::is_copy_constructible_v && !std::is_copy_assignable_v); + static_assert(std::is_nothrow_move_constructible_v && + std::is_nothrow_move_assignable_v); + rfc8032_ph(); + spent_and_moved(); + return test::exit_status(boost::report_errors()); +} diff --git a/test/messages/Jamfile b/test/messages/Jamfile index 7783c628..1ae3ab7e 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -25,3 +25,6 @@ build-project secp256k1_other_backend ; build-project openssl_memory_on_webassembly ; build-project openssl_memory_not_linked ; build-project sodium_not_linked ; +build-project ed25519_on_bearssl ; +build-project ed25519ph_sha256 ; +build-project ed25519_default_not_linked ; diff --git a/test/messages/ed25519_default_not_linked/Jamfile b/test/messages/ed25519_default_not_linked/Jamfile new file mode 100644 index 00000000..08bd1b06 --- /dev/null +++ b/test/messages/ed25519_default_not_linked/Jamfile @@ -0,0 +1,12 @@ +# 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 ; + +webcpp.compile-diagnostic ed25519_default_not_linked : ed25519_default_not_linked.cpp + : : native wasip2 wasip3 ; diff --git a/test/messages/ed25519_default_not_linked/ed25519_default_not_linked.cpp b/test/messages/ed25519_default_not_linked/ed25519_default_not_linked.cpp new file mode 100644 index 00000000..7d4a0d9c --- /dev/null +++ b/test/messages/ed25519_default_not_linked/ed25519_default_not_linked.cpp @@ -0,0 +1,22 @@ +// 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 program that makes an Ed25519 key pair on its default backend, libsodium on every target +// (design D32), and does not link it stops where it makes it, with the line that links it. + +// clang-format off +// expected-error@webcpp/crypto/curves/ed25519.hpp:* {{webcpp::crypto: Ed25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)}} +// clang-format on + +#include + +#include +#include + +int main() { + std::array const seed{}; + return webcpp::crypto::curves::ed25519::keypair::make(seed) ? 0 : 1; +} diff --git a/test/messages/ed25519_on_bearssl/Jamfile b/test/messages/ed25519_on_bearssl/Jamfile new file mode 100644 index 00000000..5d48ffc4 --- /dev/null +++ b/test/messages/ed25519_on_bearssl/Jamfile @@ -0,0 +1,12 @@ +# 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 ; + +webcpp.compile-diagnostic ed25519_on_bearssl : ed25519_on_bearssl.cpp + : /third_party//sodium : native wasip2 wasip3 ; diff --git a/test/messages/ed25519_on_bearssl/ed25519_on_bearssl.cpp b/test/messages/ed25519_on_bearssl/ed25519_on_bearssl.cpp new file mode 100644 index 00000000..81161467 --- /dev/null +++ b/test/messages/ed25519_on_bearssl/ed25519_on_bearssl.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) + +// An Ed25519 key pair named with BearSSL, which has no Ed25519, stops where it is made, with the +// capability table's refusal, which names the backends that have it. + +// clang-format off +// expected-error@webcpp/crypto/curves/ed25519.hpp:* {{webcpp::crypto: bearssl has no Ed25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten).}} +// clang-format on + +#include + +#include +#include + +int main() { + std::array const seed{}; + return webcpp::crypto::curves::ed25519::basic_keypair::make( + seed) + ? 0 + : 1; +} diff --git a/test/messages/ed25519ph_sha256/Jamfile b/test/messages/ed25519ph_sha256/Jamfile new file mode 100644 index 00000000..b1b0233e --- /dev/null +++ b/test/messages/ed25519ph_sha256/Jamfile @@ -0,0 +1,12 @@ +# 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 ; + +webcpp.compile-diagnostic ed25519ph_sha256 : ed25519ph_sha256.cpp + : /third_party//sodium : native wasip2 wasip3 ; diff --git a/test/messages/ed25519ph_sha256/ed25519ph_sha256.cpp b/test/messages/ed25519ph_sha256/ed25519ph_sha256.cpp new file mode 100644 index 00000000..0bf1c444 --- /dev/null +++ b/test/messages/ed25519ph_sha256/ed25519ph_sha256.cpp @@ -0,0 +1,18 @@ +// 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) + +// Ed25519ph named with SHA-256 stops at its static_assert: RFC 8032 defines it over SHA-512. + +// clang-format off +// expected-error@webcpp/crypto/curves/ed25519.hpp:* {{webcpp::crypto: Ed25519ph is defined over SHA-512 (RFC 8032 section 5.1); name curves::ed25519::ph.}} +// clang-format on + +#include +#include + +int main() { + return webcpp::crypto::curves::ed25519::ph::begin() ? 0 : 1; +} diff --git a/test/msvc/Jamfile b/test/msvc/Jamfile index 77d6aaa4..3548f797 100644 --- a/test/msvc/Jamfile +++ b/test/msvc/Jamfile @@ -44,3 +44,6 @@ build-project memory_missing_definition_make ; build-project memory_two_files ; build-project sodium_not_linked ; build-project canary_sodium_other_commit ; +build-project ed25519_on_bearssl ; +build-project ed25519ph_sha256 ; +build-project ed25519_default_not_linked ; diff --git a/test/msvc/ed25519_default_not_linked/Jamfile b/test/msvc/ed25519_default_not_linked/Jamfile new file mode 100644 index 00000000..1e50d36b --- /dev/null +++ b/test/msvc/ed25519_default_not_linked/Jamfile @@ -0,0 +1,9 @@ +# 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 ed25519_default_not_linked : app.cpp : /webcpp/crypto//crypto : native ; diff --git a/test/msvc/ed25519_default_not_linked/app.cpp b/test/msvc/ed25519_default_not_linked/app.cpp new file mode 100644 index 00000000..ca4b7ba5 --- /dev/null +++ b/test/msvc/ed25519_default_not_linked/app.cpp @@ -0,0 +1,17 @@ +// 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) + +// An Ed25519 key pair on its default, libsodium, not linked, stops where it is made: on MSVC the +// compile fails. The text is checked on clang, in test/messages/ed25519_default_not_linked. +#include + +#include +#include + +int main() { + std::array const seed{}; + return webcpp::crypto::curves::ed25519::keypair::make(seed) ? 0 : 1; +} diff --git a/test/msvc/ed25519_on_bearssl/Jamfile b/test/msvc/ed25519_on_bearssl/Jamfile new file mode 100644 index 00000000..81b79f86 --- /dev/null +++ b/test/msvc/ed25519_on_bearssl/Jamfile @@ -0,0 +1,9 @@ +# 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 ed25519_on_bearssl : app.cpp : /webcpp/crypto//crypto /third_party//sodium : native ; diff --git a/test/msvc/ed25519_on_bearssl/app.cpp b/test/msvc/ed25519_on_bearssl/app.cpp new file mode 100644 index 00000000..6807d822 --- /dev/null +++ b/test/msvc/ed25519_on_bearssl/app.cpp @@ -0,0 +1,21 @@ +// 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) + +// An Ed25519 key pair named with BearSSL, which has no Ed25519, stops at the capability table's +// refusal: on MSVC the compile fails. The text is checked on clang, in +// test/messages/ed25519_on_bearssl. +#include + +#include +#include + +int main() { + std::array const seed{}; + return webcpp::crypto::curves::ed25519::basic_keypair::make( + seed) + ? 0 + : 1; +} diff --git a/test/msvc/ed25519ph_sha256/Jamfile b/test/msvc/ed25519ph_sha256/Jamfile new file mode 100644 index 00000000..27da9ff3 --- /dev/null +++ b/test/msvc/ed25519ph_sha256/Jamfile @@ -0,0 +1,9 @@ +# 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 ed25519ph_sha256 : app.cpp : /webcpp/crypto//crypto /third_party//sodium : native ; diff --git a/test/msvc/ed25519ph_sha256/app.cpp b/test/msvc/ed25519ph_sha256/app.cpp new file mode 100644 index 00000000..7ffa0509 --- /dev/null +++ b/test/msvc/ed25519ph_sha256/app.cpp @@ -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) + +// Ed25519ph named with SHA-256 stops at its static_assert: on MSVC the compile fails. The text is +// checked on clang, in test/messages/ed25519ph_sha256. +#include +#include + +int main() { + return webcpp::crypto::curves::ed25519::ph::begin() ? 0 : 1; +} diff --git a/test/support/capabilities.hpp b/test/support/capabilities.hpp index 2a77e2c8..c654419a 100644 --- a/test/support/capabilities.hpp +++ b/test/support/capabilities.hpp @@ -27,10 +27,10 @@ constexpr std::size_t key_size_of() { } /** - * Makes an algorithm, through the type a program names, from a key whose bytes are all 1: a - * cell the capability table marks present whose engine is missing fails to compile here. The - * type names its family and its algorithm as the table does, and `supports_v` says that the - * backend has it. + * Makes an algorithm, through the type a program names, from a key whose bytes are all 1, or, + * for one keyed by no key of its own (Ed25519ph's signer), begins it: a cell the capability + * table marks present whose engine is missing fails to compile here. The type names its family + * and its algorithm as the table does, and `supports_v` says that the backend has it. * * @tparam Algorithm The type a program names, on `Backend`. * @tparam Family Its family's tag. @@ -43,9 +43,13 @@ template static_assert(std::is_same_v); static_assert(std::is_same_v); static_assert(webcpp::crypto::supports_v); - std::array()> key_bytes{}; - key_bytes.fill(1); - return Algorithm::make(key_bytes).has_value(); + if constexpr (requires { Algorithm::begin(); }) { + return Algorithm::begin().has_value(); + } else { + std::array()> key_bytes{}; + key_bytes.fill(1); + return Algorithm::make(key_bytes).has_value(); + } } } // namespace webcpp::test From 5015df35cbdc4e2ca53478b8b02af32deaf271f9 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 15:57:24 -0300 Subject: [PATCH 017/110] crypto: X25519 and the Ed25519 to X25519 conversion --- README.md | 2 + build.jam | 15 +- doc/changelog.adoc | 2 +- doc/crypto.adoc | 2 + doc/curves.adoc | 7 +- .../backends-ed25519_to_x25519_public.adoc | 20 ++ doc/generated/backends-x25519_agree.adoc | 20 ++ doc/generated/backends-x25519_public_key.adoc | 20 ++ doc/generated/defaults.adoc | 6 + doc/generated/matrix.adoc | 33 +++ doc/generated/namespace-curves.adoc | 14 +- doc/generated/sizes.adoc | 24 ++ doc/generated/use-cases.adoc | 11 +- doc/llms.txt | 13 +- doc/tables/crypto.json | 67 +++++- doc/tables/generate.py | 2 +- doc/x25519.adoc | 69 ++++++ example/Jamfile | 5 + example/x25519_agree.cpp | 128 +++++++++++ example/x25519_agree.expected | 6 + include/webcpp/crypto.hpp | 3 +- include/webcpp/crypto/backends/sodium.hpp | 78 +++++++ include/webcpp/crypto/curves/ed25519.hpp | 36 ++- include/webcpp/crypto/curves/x25519.hpp | 181 +++++++++++++++ include/webcpp/crypto/detail/bytes.hpp | 37 +++ include/webcpp/crypto/detail/capabilities.hpp | 49 ++++ include/webcpp/crypto/detail/defaults.hpp | 8 + test/Jamfile | 22 +- test/capabilities_test.cpp | 24 ++ test/default_backend_test.cpp | 8 + test/support/capabilities.hpp | 13 +- test/x25519_sodium_test.cpp | 213 ++++++++++++++++++ test/x25519_wycheproof_sodium_test.cpp | 96 ++++++++ 33 files changed, 1204 insertions(+), 30 deletions(-) create mode 100644 doc/generated/backends-ed25519_to_x25519_public.adoc create mode 100644 doc/generated/backends-x25519_agree.adoc create mode 100644 doc/generated/backends-x25519_public_key.adoc create mode 100644 doc/x25519.adoc create mode 100644 example/x25519_agree.cpp create mode 100644 example/x25519_agree.expected create mode 100644 include/webcpp/crypto/curves/x25519.hpp create mode 100644 include/webcpp/crypto/detail/bytes.hpp create mode 100644 test/x25519_sodium_test.cpp create mode 100644 test/x25519_wycheproof_sodium_test.cpp diff --git a/README.md b/README.md index e709ad50..60acb093 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,8 @@ MSVC), wasip2, wasip3 and Emscripten. ECDH, ECDSA's strict DER and low-S forms, and the x-only tweak. - `webcpp::crypto::curves::ed25519`: Ed25519 signatures (RFC 8032) with strict verification, the X25519 secret key of a key pair, and Ed25519ph over SHA-512 for a message given in pieces. +- `webcpp::crypto::curves::x25519`: X25519 key agreement (RFC 7748), refusing an all-zero shared + secret, and `curves::ed25519::to_x25519_public` for a peer known by its Ed25519 key. The algorithms are those of widely used, reviewed C libraries, each a backend that a program names in its own Jamfile and that webcpp builds from its sources: BearSSL diff --git a/build.jam b/build.jam index a868ec48..f1fe6989 100644 --- a/build.jam +++ b/build.jam @@ -4,8 +4,8 @@ # accompanying file LICENSE_1_0.txt or copy at # https://www.boost.org/LICENSE_1_0.txt) -# crypto: authenticated encryption, randomness, secp256k1 and Ed25519 over C -# backends. +# crypto: authenticated encryption, randomness, secp256k1, Ed25519 and X25519 +# over C backends. # A program names /webcpp/crypto//crypto and the library of each backend it # uses, /third_party// (third_party/Jamfile), or, for OpenSSL, # /webcpp/crypto//openssl; or, for a family's default backend on every @@ -89,4 +89,15 @@ rule ed25519-default-linked ( properties * ) } } alias ed25519-default : : : : @ed25519-default-linked ; +rule x25519-default-linked ( properties * ) +{ + switch [ webcpp-target.target-of $(properties) ] + { + case native : return /third_party//sodium ; + case wasip2 : return /third_party//sodium ; + case wasip3 : return /third_party//sodium ; + case emscripten : return /third_party//sodium ; + } +} +alias x25519-default : : : : @x25519-default-linked ; # generate.py: end the defaults' aliases diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 83a24591..24a9176a 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -21,7 +21,7 @@ of every version are on webcpp's index page. * Added default_backend_t and /webcpp/crypto//-default, one default backend per family and target whatever is linked, ciphers::aes128_gcm and aes256_gcm, and refusals naming the Jamfile line and another backend's type. * Added backends::bearssl (AES-GCM allocating nothing, no block cipher), backends::openssl through /webcpp/crypto//openssl on native and WASI (allocating at make only), and backends::ctaes (block cipher alone). * Added WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE: OpenSSL's allocations in the program's resource, refused on WebAssembly (WASI included) and without OpenSSL: openssl_memory_resource, install_memory_functions, memory_functions_refused, memory_functions_not_installed. -* Added curves::secp256k1: key pairs, BIP340 and ECDSA signatures, ECDH, strict DER, low-S and the x-only tweak; and curves::ed25519 on libsodium: key pairs, signatures verified strictly, the X25519 secret key, and Ed25519ph over webcpp::hash's sha2_512, which /webcpp/crypto//crypto now brings. +* Added curves::secp256k1: key pairs, BIP340 and ECDSA signatures, ECDH, strict DER, low-S and the x-only tweak; curves::ed25519 on libsodium: key pairs, signatures verified strictly, the X25519 secret key and public key, and Ed25519ph over webcpp::hash's sha2_512, which /webcpp/crypto//crypto now brings; and curves::x25519 on libsodium, whose agree refuses an all-zero secret. * Added backends::sodium on /third_party//sodium, shared with webcpp::hash and initialised before every engine, and every backend's link-time canary and C suite. * Added the page: a chapter per namespace and use case, the memory option's guide and example, tables generated from the tests, every Jamfile and message, and llms.txt. * Added supports_v, the capability table on the target being compiled, and the tags of its families and algorithms, which ciphers::gcm, the AES block cipher and secp256k1's key pair name. diff --git a/doc/crypto.adoc b/doc/crypto.adoc index 02e6fecc..57bfc8ee 100644 --- a/doc/crypto.adoc +++ b/doc/crypto.adoc @@ -54,6 +54,8 @@ include::secp256k1.adoc[] include::ed25519.adoc[] +include::x25519.adoc[] + include::backends.adoc[] include::wallets.adoc[] diff --git a/doc/curves.adoc b/doc/curves.adoc index ee0b49b8..9a1a73d7 100644 --- a/doc/curves.adoc +++ b/doc/curves.adoc @@ -15,7 +15,7 @@ back from the point to the number is infeasible. On a curve a program can on a key*, so that two parties who only exchanged public keys share a secret (link:https://en.wikipedia.org/wiki/Elliptic-curve_Diffie%E2%80%93Hellman[Wikipedia]). -The namespace `webcpp::crypto::curves` holds two curves in this version. +The namespace `webcpp::crypto::curves` holds three curves in this version. The first is secp256k1 (link:https://www.secg.org/sec2-v2.pdf[SEC 2]; link:https://en.bitcoin.it/wiki/Secp256k1[Bitcoin Wiki]), the curve of Bitcoin, Ethereum and Nostr. This version covers Bitcoin's keys and signatures, @@ -25,7 +25,10 @@ signatures (the recovery id `v`, and the recovery of a public key from a signature), nor ECDH in the raw x-coordinate form that Nostr's encrypted messages (NIP-44) use. The second is Ed25519, RFC 8032's signatures on edwards25519, with Ed25519ph for a message given in pieces -(link:https://www.rfc-editor.org/rfc/rfc8032[RFC 8032]; <>). A +(link:https://www.rfc-editor.org/rfc/rfc8032[RFC 8032]; <>). The +third is X25519, RFC 7748's key agreement on Curve25519, the same curve in +another form, with the conversion of an Ed25519 key to it +(link:https://www.rfc-editor.org/rfc/rfc7748[RFC 7748]; <>). A program chooses a curve for compatibility: a signature on one curve is checked only with that curve, and the curve of passkeys and TLS certificates, P-256, is another, which this version does not offer. diff --git a/doc/generated/backends-ed25519_to_x25519_public.adoc b/doc/generated/backends-ed25519_to_x25519_public.adoc new file mode 100644 index 00000000..6b79e106 --- /dev/null +++ b/doc/generated/backends-ed25519_to_x25519_public.adoc @@ -0,0 +1,20 @@ +// 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 `+curves::ed25519::to_x25519_public+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|libsodium +|`+/third_party//sodium+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+x25519_sodium+`) +|=== diff --git a/doc/generated/backends-x25519_agree.adoc b/doc/generated/backends-x25519_agree.adoc new file mode 100644 index 00000000..25829e43 --- /dev/null +++ b/doc/generated/backends-x25519_agree.adoc @@ -0,0 +1,20 @@ +// 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 `+curves::x25519::agree+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|libsodium +|`+/third_party//sodium+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+x25519_sodium+`, `+x25519_wycheproof_sodium+`) +|=== diff --git a/doc/generated/backends-x25519_public_key.adoc b/doc/generated/backends-x25519_public_key.adoc new file mode 100644 index 00000000..1144f3b6 --- /dev/null +++ b/doc/generated/backends-x25519_public_key.adoc @@ -0,0 +1,20 @@ +// 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 `+curves::x25519::public_key+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|libsodium +|`+/third_party//sodium+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+x25519_sodium+`) +|=== diff --git a/doc/generated/defaults.adoc b/doc/generated/defaults.adoc index 9062c722..825b5f86 100644 --- a/doc/generated/defaults.adoc +++ b/doc/generated/defaults.adoc @@ -52,4 +52,10 @@ |libsodium |the only backend in this version, on every target, and its verification is the policy `strict` (link:https://doc.libsodium.org/public-key_cryptography/public-key_signatures[libsodium's documentation, public-key signatures]; link:https://www.rfc-editor.org/rfc/rfc8032[RFC 8032, the Edwards-curve Digital Signature Algorithm (EdDSA)]) |`+ed25519_sodium+`, `+default_backend_none_linked+` + +|X25519 +|native, wasip2, wasip3, emscripten +|libsodium +|the only backend in this version, on every target; it refuses an all-zero shared secret itself (link:https://www.rfc-editor.org/rfc/rfc7748[RFC 7748, Elliptic Curves for Security (X25519 and X448)]) +|`+x25519_sodium+`, `+default_backend_none_linked+` |=== diff --git a/doc/generated/matrix.adoc b/doc/generated/matrix.adoc index c162a2e0..60511771 100644 --- a/doc/generated/matrix.adoc +++ b/doc/generated/matrix.adoc @@ -100,6 +100,21 @@ |libsodium |native, wasip2, wasip3, emscripten |`+ed25519ph_sodium+` + +|`+curves::ed25519::to_x25519_public+` +|libsodium +|native, wasip2, wasip3, emscripten +|`+x25519_sodium+` + +|`+curves::x25519::public_key+` +|libsodium +|native, wasip2, wasip3, emscripten +|`+x25519_sodium+` + +|`+curves::x25519::agree+` +|libsodium +|native, wasip2, wasip3, emscripten +|`+x25519_sodium+`, `+x25519_wycheproof_sodium+` |=== The same, by target: the backends each operation runs on. @@ -185,4 +200,22 @@ The same, by target: the backends each operation runs on. |libsodium |libsodium |libsodium + +|`+curves::ed25519::to_x25519_public+` +|libsodium +|libsodium +|libsodium +|libsodium + +|`+curves::x25519::public_key+` +|libsodium +|libsodium +|libsodium +|libsodium + +|`+curves::x25519::agree+` +|libsodium +|libsodium +|libsodium +|libsodium |=== diff --git a/doc/generated/namespace-curves.adoc b/doc/generated/namespace-curves.adoc index 91f14e00..f051c0d4 100644 --- a/doc/generated/namespace-curves.adoc +++ b/doc/generated/namespace-curves.adoc @@ -7,37 +7,47 @@ // 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",options="header"] +[cols="2h,5,5",options="header"] |=== -|Curve |`secp256k1` +|Curve |`secp256k1` |`x25519` |What it does |BIP 340 Schnorr and ECDSA signatures, ECDH, the x-only tweak +|Key agreement (Diffie-Hellman on Curve25519): two parties who exchanged public keys share a 32-byte secret |Security level |about 128 bits (link:https://www.secg.org/sec2-v2.pdf[SEC 2, Recommended Elliptic Curve Domain Parameters]) +|about 128 bits (link:https://www.rfc-editor.org/rfc/rfc7748[RFC 7748, Elliptic Curves for Security (X25519 and X448)]) |Key sizes |secret 32 bytes; public 33 bytes compressed, 32 bytes x-only +|secret 32 bytes; public 32 bytes |Signature sizes |64 bytes; ECDSA in DER up to 72 +|none: no signatures |Speed |not measured yet +|not measured yet |Constant time, measured |not measured yet +|not measured yet |Standards |link:https://www.secg.org/sec2-v2.pdf[SEC 2, Recommended Elliptic Curve Domain Parameters], link:https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki[BIP 340, Schnorr signatures for secp256k1], link:https://www.rfc-editor.org/rfc/rfc6979[RFC 6979, deterministic ECDSA nonces] +|link:https://www.rfc-editor.org/rfc/rfc7748[RFC 7748, Elliptic Curves for Security (X25519 and X448)] |Ecosystems that require it |Bitcoin (link:https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki[BIP 340, Schnorr signatures for secp256k1]), Ethereum (link:https://ethereum.github.io/yellowpaper/paper.pdf[The Ethereum yellow paper, appendix F: ECDSA on secp256k1]), Nostr (link:https://github.com/nostr-protocol/nips/blob/master/01.md[Nostr NIP-01, events signed with BIP 340 on secp256k1]) +|TLS 1.3 (link:https://www.rfc-editor.org/rfc/rfc8446#section-4.2.7[RFC 8446, TLS 1.3, section 4.2.7 (supported groups)]), SSH (link:https://www.rfc-editor.org/rfc/rfc8731[RFC 8731, Secure Shell key exchange with Curve25519]), WireGuard (link:https://www.wireguard.com/protocol/[WireGuard's protocol, cryptography]), Signal (link:https://signal.org/docs/specifications/x3dh/[Signal, the X3DH key agreement protocol]) |Browsers' WebCrypto |no: WebCrypto offers P-256, P-384, P-521, Ed25519 and X25519, not secp256k1 (link:https://www.w3.org/TR/WebCryptoAPI/[W3C Web Cryptography API]) +|yes: X25519 (link:https://www.w3.org/TR/WebCryptoAPI/[W3C Web Cryptography API]) |Choose it for compatibility with |Bitcoin's keys and signatures; Nostr's event signatures (link:https://github.com/nostr-protocol/nips/blob/master/01.md[Nostr NIP-01, events signed with BIP 340 on secp256k1]); Ethereum's ECDSA verification with a known key. Not in this version: Ethereum's recoverable signatures and its addresses from the uncompressed key; ECDH in the raw x-coordinate form of Nostr's encrypted messages (link:https://github.com/nostr-protocol/nips/blob/master/44.md[Nostr NIP-44, encrypted payloads]); BIP 32's derivation (link:https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki[BIP 32, hierarchical deterministic wallets]) +|TLS 1.3's and SSH's key exchange, WireGuard, Signal; libsodium's `crypto_box` and `crypto_kx` keys. The Ed25519 public key of a peer converts with `curves::ed25519::to_x25519_public`. A shared secret goes through a KDF before it keys a cipher. Every case of Wycheproof's X25519 file is tested (link:https://github.com/C2SP/wycheproof[Project Wycheproof, test vectors for cryptographic libraries]) |=== diff --git a/doc/generated/sizes.adoc b/doc/generated/sizes.adoc index c8f32b15..350be8ed 100644 --- a/doc/generated/sizes.adoc +++ b/doc/generated/sizes.adoc @@ -82,4 +82,28 @@ |not measured yet |not measured yet |not measured yet + +|`+curves::ed25519::to_x25519_public+` +|not measured yet +|not measured yet +|not measured yet +|not measured yet +|not measured yet +|not measured yet + +|`+curves::x25519::public_key+` +|not measured yet +|not measured yet +|not measured yet +|not measured yet +|not measured yet +|not measured yet + +|`+curves::x25519::agree+` +|not measured yet +|not measured yet +|not measured yet +|not measured yet +|not measured yet +|not measured yet |=== diff --git a/doc/generated/use-cases.adoc b/doc/generated/use-cases.adoc index 0044100e..e75bfc5e 100644 --- a/doc/generated/use-cases.adoc +++ b/doc/generated/use-cases.adoc @@ -133,8 +133,15 @@ `+/webcpp/crypto//ed25519-default+` |<> -|Use P-256 (passkeys, JWT's ES256) or X25519 -|None in this version: secp256k1 and Ed25519 keys and signatures do not interoperate with these curves +|Agree a shared secret with a peer's public key (X25519, RFC 7748), or with the X25519 form of an Ed25519 key +|In `+curves::x25519+`: `+public_key+`, `+agree+`; `+curves::ed25519::to_x25519_public+`, `+keypair::x25519_secret+` +|libsodium +|`+/webcpp/crypto//crypto+` + +`+/webcpp/crypto//x25519-default+` +|<> + +|Use P-256 (passkeys, JWT's ES256) +|None in this version: secp256k1, Ed25519 and X25519 keys and signatures do not interoperate with this curve |none |none |<> diff --git a/doc/llms.txt b/doc/llms.txt index 7dd19a86..b038f4c6 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -1,6 +1,6 @@ # webcpp::crypto -> Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA, ECDH, the x-only tweak), Ed25519 and Ed25519ph (RFC 8032), a random_device on the system's generator and a constant-time equal, each over a widely used, reviewed C library (BearSSL, OpenSSL, ctaes, libsecp256k1, libsodium) that the program names in its Jamfile. Hashing and HMAC are Boost.Hash2's. Every failure is a boost::system::result value. Protocols (Bitcoin, Ethereum, Nostr) belong to domain libraries built on these primitives. +> Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA, ECDH, the x-only tweak), Ed25519 and Ed25519ph (RFC 8032), X25519 (RFC 7748), a random_device on the system's generator and a constant-time equal, each over a widely used, reviewed C library (BearSSL, OpenSSL, ctaes, libsecp256k1, libsodium) that the program names in its Jamfile. Hashing and HMAC are Boost.Hash2's. Every failure is a boost::system::result value. Protocols (Bitcoin, Ethereum, Nostr) belong to domain libraries built on these primitives. Generated by doc/tables/generate.py with the page's tables. Page: https://webcpporg.github.io/libs/crypto/ @@ -66,6 +66,12 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [curves::ed25519::ph](https://webcpporg.github.io/libs/crypto/#crypto-ed25519): Ed25519ph (RFC 8032): a message given in pieces, hashed with SHA-512, then signed with a key pair or verified with a public key. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. - begin: Begins a message. - update: Adds a piece of the message. +- [curves::ed25519::to_x25519_public](https://webcpporg.github.io/libs/crypto/#crypto-x25519): The X25519 public key of an Ed25519 public key (the birational map), refusing a key of small order or not canonical with `invalid_public_key`. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. + - to_x25519_public: The X25519 public key of an Ed25519 public key (the birational map from edwards25519 to Curve25519), so that a peer known by its Ed25519 key can be agreed with by `curves::x25519::agree`; the key pair's own side is `basic_keypair::x25519_secret`. +- [curves::x25519::public_key](https://webcpporg.github.io/libs/crypto/#crypto-x25519): The 32-byte X25519 public key of a 32-byte secret key (RFC 7748). Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. + - public_key: The public key of a secret key: `algorithm::public_key`. +- [curves::x25519::agree](https://webcpporg.github.io/libs/crypto/#crypto-x25519): The 32-byte shared secret of a secret key and a peer's public key, a `secret<32>`, refused with `weak_public_key` when it is all zero (a peer key of low order). Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. + - agree: The shared secret, refused when all zero: `algorithm::agree`. ## Default backend per family @@ -76,6 +82,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - AES block cipher, native, wasip2, wasip3, emscripten: none; a raw block cipher is a building block a program chooses deliberately, naming its backend; `aes256<>` takes AES-GCM's default as its argument, and its `make` does not compile where that is BearSSL. - secp256k1, native, wasip2, wasip3, emscripten: libsecp256k1; the only backend ([libsecp256k1's README](https://github.com/bitcoin-core/secp256k1#readme)). - Ed25519, native, wasip2, wasip3, emscripten: libsodium; the only backend in this version, on every target, and its verification is the policy `strict` ([libsodium's documentation, public-key signatures](https://doc.libsodium.org/public-key_cryptography/public-key_signatures); [RFC 8032, the Edwards-curve Digital Signature Algorithm (EdDSA)](https://www.rfc-editor.org/rfc/rfc8032)). +- X25519, native, wasip2, wasip3, emscripten: libsodium; the only backend in this version, on every target; it refuses an all-zero shared secret itself ([RFC 7748, Elliptic Curves for Security (X25519 and X448)](https://www.rfc-editor.org/rfc/rfc7748)). ## Rules of use @@ -110,7 +117,8 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [Seed BearSSL's own generator for code that calls BearSSL directly](https://webcpporg.github.io/libs/crypto/#crypto-entropy-bearssl): `random_device::fill` (webcpp::crypto); backend BearSSL's C API; Jamfile /webcpp/crypto//crypto /third_party//bearssl. Example: example/bearssl_prng.cpp. - [Hash, or compute an HMAC](https://webcpporg.github.io/libs/crypto/#crypto-overview-hash2): `boost::hash2::sha2_256`, `hmac_sha2_256` (Boost.Hash2, not this library); backend none; Jamfile `/webcpp/crypto//crypto` brings Boost's headers. Example: example/equal_hmac.cpp. - [Sign and verify with Ed25519 (RFC 8032), or sign a large message in pieces with Ed25519ph](https://webcpporg.github.io/libs/crypto/#crypto-ed25519): `keypair::make`, `keypair::generate`, `keypair::sign`, `verify`; `ph` (webcpp::crypto::curves::ed25519); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//ed25519-default. Example: example/ed25519_sign.cpp. -- [Use P-256 (passkeys, JWT's ES256) or X25519](https://webcpporg.github.io/libs/crypto/#crypto-curves): secp256k1 and Ed25519 keys and signatures do not interoperate with these curves (none in this version); backend none; Jamfile none. +- [Agree a shared secret with a peer's public key (X25519, RFC 7748), or with the X25519 form of an Ed25519 key](https://webcpporg.github.io/libs/crypto/#crypto-x25519): `public_key`, `agree`; `curves::ed25519::to_x25519_public`, `keypair::x25519_secret` (webcpp::crypto::curves::x25519); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//x25519-default. Example: example/x25519_agree.cpp. +- [Use P-256 (passkeys, JWT's ES256)](https://webcpporg.github.io/libs/crypto/#crypto-curves): secp256k1, Ed25519 and X25519 keys and signatures do not interoperate with this curve (none in this version); backend none; Jamfile none. ## Examples @@ -132,6 +140,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - example/store_token.cpp: Stores a user's API token encrypted in a database row, bound to the user's id. The id is additional data: authenticated but not encrypted, so a row copied to another user's record no longer opens. Without that binding a database writer could swap the rows of two users. - example/taproot_tweak.cpp: Tweaks an internal key as Bitcoin's Taproot does for a key-path-only output (BIP341): the tweak is a tagged hash of the internal key, and the output key commits to it. The same tweak applied to the key pair lets the owner sign for the output key, so spending needs no script. - example/wallet_key.cpp: Makes a wallet's key pair from a random secret, then seals the secret at rest with AES-256-GCM and restores it. A secret that sits unencrypted on disk, or lingers in memory after use, is the first thing an attacker looks for, so the copies are wiped as soon as they are not needed. +- example/x25519_agree.cpp: Alice and Bob of RFC 7748 section 6.1 agree a shared secret from each other's public keys; then two Ed25519 key pairs, made from RFC 8032's seeds, agree one through their X25519 forms; and a peer key of low order is refused. Prints each public key and the shared secrets in hex. ## Optional diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 3a988f63..b8694e0b 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -63,7 +63,14 @@ "bip32": ["BIP 32, hierarchical deterministic wallets", "https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki"], "openssl-mem": ["OpenSSL 3.5's OPENSSL_malloc(3), CRYPTO_set_mem_functions", "https://docs.openssl.org/3.5/man3/OPENSSL_malloc/"], "rfc8032": ["RFC 8032, the Edwards-curve Digital Signature Algorithm (EdDSA)", "https://www.rfc-editor.org/rfc/rfc8032"], - "libsodium-signatures": ["libsodium's documentation, public-key signatures", "https://doc.libsodium.org/public-key_cryptography/public-key_signatures"] + "libsodium-signatures": ["libsodium's documentation, public-key signatures", "https://doc.libsodium.org/public-key_cryptography/public-key_signatures"], + "rfc7748": ["RFC 7748, Elliptic Curves for Security (X25519 and X448)", "https://www.rfc-editor.org/rfc/rfc7748"], + "libsodium-ed25519-to-curve25519": ["libsodium's documentation, Ed25519 to Curve25519", "https://doc.libsodium.org/advanced/ed25519-curve25519"], + "wycheproof": ["Project Wycheproof, test vectors for cryptographic libraries", "https://github.com/C2SP/wycheproof"], + "rfc8446-groups": ["RFC 8446, TLS 1.3, section 4.2.7 (supported groups)", "https://www.rfc-editor.org/rfc/rfc8446#section-4.2.7"], + "rfc8731": ["RFC 8731, Secure Shell key exchange with Curve25519", "https://www.rfc-editor.org/rfc/rfc8731"], + "wireguard": ["WireGuard's protocol, cryptography", "https://www.wireguard.com/protocol/"], + "x3dh": ["Signal, the X3DH key agreement protocol", "https://signal.org/docs/specifications/x3dh/"] }, "backends": { "bearssl": { @@ -307,6 +314,42 @@ "what": "Ed25519ph (RFC 8032): a message given in pieces, hashed with SHA-512, then signed with a key pair or verified with a public key.", "section": "crypto-ed25519", "backends": {"sodium": {"tests": ["ed25519ph_sodium"]}} + }, + { + "id": "ed25519_to_x25519_public", + "family": "ed25519", + "free": true, + "functions": ["to_x25519_public"], + "namespace": "curves", + "api": "curves::ed25519::to_x25519_public", + "header": "", + "what": "The X25519 public key of an Ed25519 public key (the birational map), refusing a key of small order or not canonical with `invalid_public_key`.", + "section": "crypto-x25519", + "backends": {"sodium": {"tests": ["x25519_sodium"]}} + }, + { + "id": "x25519_public_key", + "family": "x25519", + "free": true, + "functions": ["public_key"], + "namespace": "curves", + "api": "curves::x25519::public_key", + "header": "", + "what": "The 32-byte X25519 public key of a 32-byte secret key (RFC 7748).", + "section": "crypto-x25519", + "backends": {"sodium": {"tests": ["x25519_sodium"]}} + }, + { + "id": "x25519_agree", + "family": "x25519", + "free": true, + "functions": ["agree"], + "namespace": "curves", + "api": "curves::x25519::agree", + "header": "", + "what": "The 32-byte shared secret of a secret key and a peer's public key, a `secret<32>`, refused with `weak_public_key` when it is all zero (a peer key of low order).", + "section": "crypto-x25519", + "backends": {"sodium": {"tests": ["x25519_sodium", "x25519_wycheproof_sodium"]}} } ], "families": [ @@ -384,6 +427,22 @@ "backends": { "sodium": {"targets": "all"} } + }, + { + "name": "x25519", + "title": "X25519", + "group": "curves::x25519", + "since": "0.2", + "header": "", + "names": [ + {"name": "x25519", "title": "X25519", "type": "curves::x25519::algorithm<{backend}>"} + ], + "default": [ + {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": ["x25519_sodium", "default_backend_none_linked"], "why": "the only backend in this version, on every target; it refuses an all-zero shared secret itself ({rfc7748})"} + ], + "backends": { + "sodium": {"targets": "all"} + } } ], "rules": [ @@ -434,7 +493,8 @@ "title": "webcpp::crypto::curves", "columns": ["Curve", "What it does", "Security level", "Key sizes", "Signature sizes", "Speed", "Constant time, measured", "Standards", "Ecosystems that require it", "Browsers' WebCrypto", "Choose it for compatibility with"], "rows": [ - ["`secp256k1`", "BIP 340 Schnorr and ECDSA signatures, ECDH, the x-only tweak", "about 128 bits ({sec2})", "secret 32 bytes; public 33 bytes compressed, 32 bytes x-only", "64 bytes; ECDSA in DER up to 72", "not measured yet", "not measured yet", "{sec2}, {bip340}, {rfc6979}", "Bitcoin ({bip340}), Ethereum ({ethereum}), Nostr ({nip01})", "no: WebCrypto offers P-256, P-384, P-521, Ed25519 and X25519, not secp256k1 ({webcrypto})", "Bitcoin's keys and signatures; Nostr's event signatures ({nip01}); Ethereum's ECDSA verification with a known key. Not in this version: Ethereum's recoverable signatures and its addresses from the uncompressed key; ECDH in the raw x-coordinate form of Nostr's encrypted messages ({nip44}); BIP 32's derivation ({bip32})"] + ["`secp256k1`", "BIP 340 Schnorr and ECDSA signatures, ECDH, the x-only tweak", "about 128 bits ({sec2})", "secret 32 bytes; public 33 bytes compressed, 32 bytes x-only", "64 bytes; ECDSA in DER up to 72", "not measured yet", "not measured yet", "{sec2}, {bip340}, {rfc6979}", "Bitcoin ({bip340}), Ethereum ({ethereum}), Nostr ({nip01})", "no: WebCrypto offers P-256, P-384, P-521, Ed25519 and X25519, not secp256k1 ({webcrypto})", "Bitcoin's keys and signatures; Nostr's event signatures ({nip01}); Ethereum's ECDSA verification with a known key. Not in this version: Ethereum's recoverable signatures and its addresses from the uncompressed key; ECDH in the raw x-coordinate form of Nostr's encrypted messages ({nip44}); BIP 32's derivation ({bip32})"], + ["`x25519`", "Key agreement (Diffie-Hellman on Curve25519): two parties who exchanged public keys share a 32-byte secret", "about 128 bits ({rfc7748})", "secret 32 bytes; public 32 bytes", "none: no signatures", "not measured yet", "not measured yet", "{rfc7748}", "TLS 1.3 ({rfc8446-groups}), SSH ({rfc8731}), WireGuard ({wireguard}), Signal ({x3dh})", "yes: X25519 ({webcrypto})", "TLS 1.3's and SSH's key exchange, WireGuard, Signal; libsodium's `crypto_box` and `crypto_kx` keys. The Ed25519 public key of a peer converts with `curves::ed25519::to_x25519_public`. A shared secret goes through a KDF before it keys a cipher. Every case of Wycheproof's X25519 file is tested ({wycheproof})"] ] } }, @@ -457,7 +517,8 @@ {"need": "Seed BearSSL's own generator for code that calls BearSSL directly", "namespace": "webcpp::crypto", "api": "`random_device::fill`", "backend": "BearSSL's C API", "jamfile": "/webcpp/crypto//crypto /third_party//bearssl", "example": "bearssl_prng", "section": "crypto-entropy-bearssl"}, {"need": "Hash, or compute an HMAC", "namespace": "Boost.Hash2, not this library", "api": "`boost::hash2::sha2_256`, `hmac_sha2_256`", "backend": "none", "jamfile": "`/webcpp/crypto//crypto` brings Boost's headers", "example": "equal_hmac", "section": "crypto-overview-hash2"}, {"need": "Sign and verify with Ed25519 (RFC 8032), or sign a large message in pieces with Ed25519ph", "namespace": "webcpp::crypto::curves::ed25519", "api": "`keypair::make`, `keypair::generate`, `keypair::sign`, `verify`; `ph`", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//ed25519-default", "example": "ed25519_sign", "section": "crypto-ed25519"}, - {"need": "Use P-256 (passkeys, JWT's ES256) or X25519", "namespace": "none in this version", "api": "secp256k1 and Ed25519 keys and signatures do not interoperate with these curves", "backend": "none", "jamfile": "none", "example": "", "section": "crypto-curves"} + {"need": "Agree a shared secret with a peer's public key (X25519, RFC 7748), or with the X25519 form of an Ed25519 key", "namespace": "webcpp::crypto::curves::x25519", "api": "`public_key`, `agree`; `curves::ed25519::to_x25519_public`, `keypair::x25519_secret`", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//x25519-default", "example": "x25519_agree", "section": "crypto-x25519"}, + {"need": "Use P-256 (passkeys, JWT's ES256)", "namespace": "none in this version", "api": "secp256k1, Ed25519 and X25519 keys and signatures do not interoperate with this curve", "backend": "none", "jamfile": "none", "example": "", "section": "crypto-curves"} ], "fixtures": { "web": "A web application: AES-256-GCM on BearSSL, the default on WebAssembly.", diff --git a/doc/tables/generate.py b/doc/tables/generate.py index 279eb350..eddb252d 100644 --- a/doc/tables/generate.py +++ b/doc/tables/generate.py @@ -1229,7 +1229,7 @@ def llms(data: Data, matrix: Matrix, library: Path) -> str: out = ['# webcpp::crypto', '', '> Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: ' 'AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA, ECDH, the x-only ' - 'tweak), Ed25519 and Ed25519ph (RFC 8032), a random_device on the system\'s generator ' + 'tweak), Ed25519 and Ed25519ph (RFC 8032), X25519 (RFC 7748), a random_device on the system\'s generator ' 'and a constant-time equal, each over a widely used, reviewed C library (BearSSL, ' 'OpenSSL, ctaes, libsecp256k1, libsodium) that ' 'the program names in its Jamfile. Hashing and HMAC are Boost.Hash2\'s. Every ' diff --git a/doc/x25519.adoc b/doc/x25519.adoc new file mode 100644 index 00000000..a94e57be --- /dev/null +++ b/doc/x25519.adoc @@ -0,0 +1,69 @@ +// 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) + +[#crypto-x25519] +=== X25519 + +`` is X25519, the Diffie-Hellman key agreement +on Curve25519 of RFC 7748 +(link:https://www.rfc-editor.org/rfc/rfc7748[RFC 7748]), on libsodium +(`/third_party//sodium`, or `/webcpp/crypto//x25519-default`, which links it on +every target), in the namespace `webcpp::crypto::curves::x25519`. Two parties +each keep a 32-byte secret key and send the other its 32-byte public key; each +combines its own secret key with the other's public key and both get the same +32-byte shared secret, which no one who saw only the public keys can compute. +A chat app agrees a key this way with each contact, and TLS 1.3, SSH, +WireGuard and Signal start their sessions with it +(link:https://www.rfc-editor.org/rfc/rfc8446#section-4.2.7[RFC 8446]; +link:https://www.rfc-editor.org/rfc/rfc8731[RFC 8731]; +link:https://www.wireguard.com/protocol/[WireGuard]; +link:https://signal.org/docs/specifications/x3dh/[X3DH]). + +`public_key(secret_key)` gives the public key of any 32 bytes, which a program +draws with `random_device`; `agree(secret_key, peer_public_key)` gives the +shared secret, a `secret<32>` that wipes itself. A peer's public key of low +order makes the shared secret all zero, whatever the secret key: `agree` +refuses it with `weak_public_key`, so that an attacker who sends such a key +cannot make both sides use a secret it knows (design D8). Every case of +Wycheproof's X25519 file gives its shared secret, and its 31 all-zero cases +give `weak_public_key` (`x25519_wycheproof_sodium`). + +include::generated/backends-x25519_public_key.adoc[] + +include::generated/backends-x25519_agree.adoc[] + +*From Ed25519.* A program that already holds an Ed25519 key pair (<>) +agrees with the same seed: `keypair::x25519_secret()` is its X25519 secret key, +and `curves::ed25519::to_x25519_public(public_key)` converts a peer's Ed25519 +public key to its X25519 public key, the birational map between the two forms +of the curve. The conversion refuses with `invalid_public_key` a key of small +order, off the curve or outside the main subgroup, as libsodium does +(link:https://doc.libsodium.org/advanced/ed25519-curve25519[libsodium's documentation]). + +include::generated/backends-ed25519_to_x25519_public.adoc[] + +*Example.* RFC 7748's Alice and Bob, then two Ed25519 key pairs that agree +through their X25519 forms, then a peer key of low order refused: + +[source,cpp] +---- +include::{examples}/x25519_agree.cpp[tag=program] +---- + +[listing] +---- +include::{examples}/x25519_agree.expected[] +---- + +*Pitfalls.* + +* The shared secret is not a key: a program derives its keys from it, with the +two public keys, through a KDF such as HKDF, and never uses its bytes as a +cipher's key directly +(link:https://doc.libsodium.org/advanced/scalar_multiplication[libsodium's documentation, scalar multiplication]). +* X25519 proves nothing about who sent a public key: an attacker in the middle +agrees one secret with each side. A protocol signs the public keys, or checks +them against keys it already trusts. diff --git a/example/Jamfile b/example/Jamfile index e1e0cb5d..3c06cb1d 100644 --- a/example/Jamfile +++ b/example/Jamfile @@ -74,3 +74,8 @@ webcpp.example openssl_memory.cpp # The guide's Ed25519 program: RFC 8032's second test signed and verified, then # Ed25519ph's test given in two pieces, on the family's default. webcpp.example ed25519_sign.cpp : /webcpp/crypto//ed25519-default ; + +# The guide's X25519 program: RFC 7748's Alice and Bob, the agreement of two +# Ed25519 key pairs through their X25519 forms, and a peer of low order +# refused, on the family's default. +webcpp.example x25519_agree.cpp : /webcpp/crypto//x25519-default ; diff --git a/example/x25519_agree.cpp b/example/x25519_agree.cpp new file mode 100644 index 00000000..54c16779 --- /dev/null +++ b/example/x25519_agree.cpp @@ -0,0 +1,128 @@ +// 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) + +// Alice and Bob of RFC 7748 section 6.1 agree a shared secret from each other's public keys; +// then two Ed25519 key pairs, made from RFC 8032's seeds, agree one through their X25519 forms; +// and a peer key of low order is refused. Prints each public key and the shared secrets in hex. +// tag::program[] +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace crypto = webcpp::crypto; +namespace ed25519 = webcpp::crypto::curves::ed25519; +namespace x25519 = webcpp::crypto::curves::x25519; + +namespace { + +// Prints bytes in hex after a name. +void print(char const* name, std::span bytes) { + std::printf("%s ", name); + for (auto const byte : bytes) { + std::printf("%02x", byte); + } + std::printf("\n"); +} + +// X25519: each side sends its public key and keeps its secret key. +bool alice_and_bob() { + // RFC 7748 section 6.1's secret keys: published, never real keys; a program draws its own + // 32 bytes with random_device. + std::array const alice_secret{ + 0x77, 0x07, 0x6d, 0x0a, 0x73, 0x18, 0xa5, 0x7d, 0x3c, 0x16, 0xc1, + 0x72, 0x51, 0xb2, 0x66, 0x45, 0xdf, 0x4c, 0x2f, 0x87, 0xeb, 0xc0, + 0x99, 0x2a, 0xb1, 0x77, 0xfb, 0xa5, 0x1d, 0xb9, 0x2c, 0x2a, + }; + std::array const bob_secret{ + 0x5d, 0xab, 0x08, 0x7e, 0x62, 0x4a, 0x8a, 0x4b, 0x79, 0xe1, 0x7f, + 0x8b, 0x83, 0x80, 0x0e, 0xe6, 0x6f, 0x3b, 0xb1, 0x29, 0x26, 0x18, + 0xb6, 0xfd, 0x1c, 0x2f, 0x8b, 0x27, 0xff, 0x88, 0xe0, 0xeb, + }; + auto const alice_public = x25519::public_key(alice_secret); + auto const bob_public = x25519::public_key(bob_secret); + if (!alice_public || !bob_public) { + return false; + } + print("alice public", *alice_public); + print("bob public ", *bob_public); + auto const alice_shared = x25519::agree(alice_secret, *bob_public); + auto const bob_shared = x25519::agree(bob_secret, *alice_public); + if (!alice_shared || !bob_shared) { + return false; + } + // Printed here only because RFC 7748 publishes it; a program never prints a shared secret, + // and derives its keys from it with a KDF. + print("shared ", alice_shared->bytes()); + return crypto::equal(alice_shared->bytes(), bob_shared->bytes()); +} + +// The same agreement from Ed25519 key pairs: one seed for signatures and key agreement. +bool from_ed25519() { + std::array const first_seed{ + 0x9d, 0x61, 0xb1, 0x9d, 0xef, 0xfd, 0x5a, 0x60, 0xba, 0x84, 0x4a, + 0xf4, 0x92, 0xec, 0x2c, 0xc4, 0x44, 0x49, 0xc5, 0x69, 0x7b, 0x32, + 0x69, 0x19, 0x70, 0x3b, 0xac, 0x03, 0x1c, 0xae, 0x7f, 0x60, + }; + std::array const second_seed{ + 0x4c, 0xcd, 0x08, 0x9b, 0x28, 0xff, 0x96, 0xda, 0x9d, 0xb6, 0xc3, + 0x46, 0xec, 0x11, 0x4e, 0x0f, 0x5b, 0x8a, 0x31, 0x9f, 0x35, 0xab, + 0xa6, 0x24, 0xda, 0x8c, 0xf6, 0xed, 0x4f, 0xb8, 0xa6, 0xfb, + }; + auto const first = ed25519::keypair::make(first_seed); + auto const second = ed25519::keypair::make(second_seed); + if (!first || !second) { + return false; + } + auto const first_secret = first->x25519_secret(); + auto const second_secret = second->x25519_secret(); + auto const first_signing = first->public_key(); + auto const second_signing = second->public_key(); + if (!first_secret || !second_secret || !first_signing || !second_signing) { + return false; + } + // Each side knows the other by its Ed25519 public key, and converts it. + auto const first_peer = ed25519::to_x25519_public(*second_signing); + auto const second_peer = ed25519::to_x25519_public(*first_signing); + if (!first_peer || !second_peer) { + return false; + } + print("converted ", *second_peer); + auto const first_shared = x25519::agree(first_secret->bytes(), *first_peer); + auto const second_shared = x25519::agree(second_secret->bytes(), *second_peer); + return first_shared && second_shared && + crypto::equal(first_shared->bytes(), second_shared->bytes()); +} + +// A peer key of low order gives an all-zero secret, which agree refuses. +bool low_order_refused() { + std::array const secret_key{1}; + std::array const zero_point{}; + auto const shared = x25519::agree(secret_key, zero_point); + if (!shared && shared.error() == crypto::error::weak_public_key) { + std::printf("low order refused: weak_public_key\n"); + return true; + } + return false; +} + +} // namespace + +int main() { + if (!alice_and_bob() || !from_ed25519() || !low_order_refused()) { + std::printf("failed\n"); + return 1; + } + std::printf("agreed\n"); + return 0; +} + +// end::program[] diff --git a/example/x25519_agree.expected b/example/x25519_agree.expected new file mode 100644 index 00000000..0447d59f --- /dev/null +++ b/example/x25519_agree.expected @@ -0,0 +1,6 @@ +alice public 8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a +bob public de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f +shared 4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742 +converted d85e07ec22b0ad881537c2f44d662d1a143cf830c57aca4305d85c7a90f6b62e +low order refused: weak_public_key +agreed diff --git a/include/webcpp/crypto.hpp b/include/webcpp/crypto.hpp index fd00244a..0dd1cb9c 100644 --- a/include/webcpp/crypto.hpp +++ b/include/webcpp/crypto.hpp @@ -6,7 +6,7 @@ /** Every header of webcpp::crypto that needs no backend, the header of each backend the build - links with the curves it holds (libsecp256k1's secp256k1, libsodium's Ed25519), and + links with the curves it holds (libsecp256k1's secp256k1, libsodium's Ed25519 and X25519), and `ciphers/aes256_gcm.hpp`, whose `aes128_gcm` and `aes256_gcm` name AES-GCM's default backend: a program that does not link the default names another in the type, as `ciphers::gcm>` on WebAssembly. @@ -39,6 +39,7 @@ #ifdef WEBCPP_CRYPTO_HAS_SODIUM #include #include +#include #endif #ifdef WEBCPP_CRYPTO_HAS_SECP256K1 diff --git a/include/webcpp/crypto/backends/sodium.hpp b/include/webcpp/crypto/backends/sodium.hpp index 6ecc9c94..68d9693a 100644 --- a/include/webcpp/crypto/backends/sodium.hpp +++ b/include/webcpp/crypto/backends/sodium.hpp @@ -178,6 +178,24 @@ struct ed25519_engine { return {}; } + /** + * The X25519 public key of an Ed25519 public key, `crypto_sign_ed25519_pk_to_curve25519`, + * which refuses a key of small order, not on the curve or outside the main subgroup. + * + * @return Nothing; `invalid_public_key`; `backend_failure`. + */ + [[nodiscard]] static boost::system::result to_x25519_public( + std::span public_key, std::span out) noexcept { + auto const ready = sodium_ready(); + if (!ready) { + return ready; + } + if (crypto_sign_ed25519_pk_to_curve25519(out.data(), public_key.data()) != 0) { + return error::invalid_public_key; + } + return {}; + } + /** Wipes the secret key. */ static void reset(state& keyed) noexcept { wipe_object(keyed.secret_key); } }; @@ -256,3 +274,63 @@ struct ed25519ph_engine { } // namespace webcpp::crypto::detail #endif // Ed25519 on libsodium + +// X25519 on libsodium, for a program that includes curves/x25519.hpp, before this header or +// after it, as Ed25519's above. +#if defined(WEBCPP_CRYPTO_CURVES_X25519_HPP) && defined(WEBCPP_CRYPTO_HAS_SODIUM) && \ + !defined(WEBCPP_CRYPTO_BACKENDS_SODIUM_X25519) +/** Defined once libsodium's X25519 engine is. */ +#define WEBCPP_CRYPTO_BACKENDS_SODIUM_X25519 + +#include + +#include +#include + +namespace webcpp::crypto::detail { + +/** X25519 on libsodium, `crypto_scalarmult_curve25519`. */ +template <> +struct x25519_engine { + /** + * The public key of a secret key, `crypto_scalarmult_curve25519_base`. + * + * @return Nothing; `backend_failure`. + */ + [[nodiscard]] static boost::system::result base( + std::span secret_key, std::span out) noexcept { + auto const ready = sodium_ready(); + if (!ready) { + return ready; + } + if (crypto_scalarmult_curve25519_base(out.data(), secret_key.data()) != 0) { + return error::backend_failure; + } + return {}; + } + + /** + * The shared secret, `crypto_scalarmult_curve25519`, which returns -1 for an all-zero + * result. + * + * @return Nothing; `weak_public_key`; `backend_failure`. + */ + [[nodiscard]] static boost::system::result agree( + std::span secret_key, + std::span peer_public_key, + std::span out) noexcept { + auto const ready = sodium_ready(); + if (!ready) { + return ready; + } + if (crypto_scalarmult_curve25519(out.data(), secret_key.data(), peer_public_key.data()) != + 0) { + return error::weak_public_key; + } + return {}; + } +}; + +} // namespace webcpp::crypto::detail + +#endif // X25519 on libsodium diff --git a/include/webcpp/crypto/curves/ed25519.hpp b/include/webcpp/crypto/curves/ed25519.hpp index af93338d..e025ea63 100644 --- a/include/webcpp/crypto/curves/ed25519.hpp +++ b/include/webcpp/crypto/curves/ed25519.hpp @@ -6,8 +6,8 @@ /** Ed25519 signatures (RFC 8032): a key pair made from a 32-byte seed, signatures of 64 bytes, - and verification, strict on libsodium; and Ed25519ph, the same signature over SHA-512 of a - message given in pieces. + verification, strict on libsodium, and the conversion of a public key to X25519's; and Ed25519ph, + the same signature over SHA-512 of a message given in pieces. The family's default backend, libsodium on every target, is included when the program links it; a program that uses the family without linking it stops where it calls it, with the @@ -258,6 +258,31 @@ boost::system::result verify(std::span public_key, public_key.first<32>(), message, signature.first<64>()); } +/** + * The X25519 public key of an Ed25519 public key (the birational map from edwards25519 to + * Curve25519), so that a peer known by its Ed25519 key can be agreed with by + * `curves::x25519::agree`; the key pair's own side is `basic_keypair::x25519_secret`. + * + * @tparam Backend The backend; by default the family's. + * @param ed25519_public_key 32 bytes. + * @return 32 bytes; `invalid_public_key` for a key of another size, not canonical, not on the + * curve or of small order. + */ +template > +boost::system::result> to_x25519_public( + std::span ed25519_public_key) noexcept { + if (ed25519_public_key.size() != 32) { + return error::invalid_public_key; + } + std::array converted{}; + auto const done = detail::ed25519_engine::to_x25519_public( + ed25519_public_key.first<32>(), converted); + if (!done) { + return done.error(); + } + return converted; +} + /** * Ed25519ph (RFC 8032 section 5.1), the Ed25519 signature of a message's SHA-512, given in * pieces. @@ -459,6 +484,13 @@ struct ed25519_engine { return error::backend_failure; } + /** Never called; fails closed. */ + template + [[nodiscard]] static boost::system::result to_x25519_public( + Arguments&&... /*arguments*/) noexcept { + return error::backend_failure; + } + /** Never called. */ template static void reset(Arguments&&... /*arguments*/) noexcept {} diff --git a/include/webcpp/crypto/curves/x25519.hpp b/include/webcpp/crypto/curves/x25519.hpp new file mode 100644 index 00000000..342176c1 --- /dev/null +++ b/include/webcpp/crypto/curves/x25519.hpp @@ -0,0 +1,181 @@ +// 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) + +/** + X25519 key agreement (RFC 7748): the 32-byte public key of a 32-byte secret key, and the 32-byte + shared secret of a secret key and a peer's public key, refused when it is all zero. + + The family's default backend, libsodium on every target, is included when the program links + it; a program that uses the family without linking it stops where it calls it, with the + Jamfile line that links it. + + @see "X25519", in the guide. +*/ +#ifndef WEBCPP_CRYPTO_CURVES_X25519_HPP +#define WEBCPP_CRYPTO_CURVES_X25519_HPP + +#include + +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include + +namespace webcpp::crypto::detail { + +/** The work of X25519 on a backend; the primary refuses (defined at the end of this header). */ +template +struct x25519_engine; + +} // namespace webcpp::crypto::detail + +namespace webcpp::crypto::curves::x25519 { + +/** + * X25519 (RFC 7748) on a backend: the type `supports_v` names, whose functions the free + * functions below call. + * + * @tparam Backend The backend; by default the family's (`default_backend_t`). + */ +template > +struct algorithm { + /** The family, for `supports_v`. */ + using family_type = families::x25519; + /** The algorithm, for `supports_v`: the family's one name. */ + using name_type = families::x25519; + /** The backend. */ + using backend_type = Backend; + /** The secret key's, the public key's and the shared secret's size. */ + static constexpr std::size_t key_size = 32; + + /** + * The public key of a secret key: its product with the base point, `u = 9`. + * + * @param secret_key 32 bytes; any 32 bytes are a secret key (RFC 7748 clamps them). + * @return 32 bytes; `invalid_key_size`; `backend_failure`. + */ + static boost::system::result> public_key( + std::span secret_key) noexcept { + if (secret_key.size() != key_size) { + return error::invalid_key_size; + } + std::array out{}; + auto const done = engine::base(secret_key.first(), out); + if (!done) { + return done.error(); + } + return out; + } + + /** + * The shared secret of a secret key and a peer's public key, refused when it is all zero. + * + * @param secret_key 32 bytes. + * @param peer_public_key 32 bytes. + * @return 32 secret bytes; `invalid_key_size`; `invalid_public_key`; `weak_public_key` + * for a peer key of low order, whose shared secret is all zero; `backend_failure`. + */ + static boost::system::result> agree( + std::span secret_key, + std::span peer_public_key) noexcept { + if (secret_key.size() != key_size) { + return error::invalid_key_size; + } + if (peer_public_key.size() != key_size) { + return error::invalid_public_key; + } + secret<32> shared; + auto const done = engine::agree(secret_key.first(), + peer_public_key.first(), shared.writable()); + if (!done) { + return done.error(); + } + // Every backend gives the same answer: libsodium refuses an all-zero result itself, + // and the others are checked here, in constant time (design D8). + if (detail::is_all_zero(shared.bytes())) { + return error::weak_public_key; + } + return shared; + } + +private: + using engine = detail::x25519_engine; +}; + +/** + * The public key of a secret key: `algorithm::public_key`. + * + * @tparam Backend The backend; by default the family's. + * @param secret_key 32 bytes. + * @return 32 bytes; `invalid_key_size`; `backend_failure`. + */ +template > +boost::system::result> public_key( + std::span secret_key) noexcept { + return algorithm::public_key(secret_key); +} + +/** + * The shared secret, refused when all zero: `algorithm::agree`. + * + * @tparam Backend The backend; by default the family's. + * @param secret_key 32 bytes. + * @param peer_public_key 32 bytes. + * @return 32 secret bytes; `invalid_key_size`; `invalid_public_key`; `weak_public_key`; + * `backend_failure`. + */ +template > +boost::system::result> agree(std::span secret_key, + std::span peer_public_key) noexcept { + return algorithm::agree(secret_key, peer_public_key); +} + +} // namespace webcpp::crypto::curves::x25519 + +namespace webcpp::crypto::detail { + +/** + * X25519's engine on a backend whose header does not specialise it: the family's refusal, + * which names what the program needs (`detail/capabilities.hpp`). Its functions are never + * called: the refusal stops the build where the class is instantiated, and they keep the + * compiler from adding errors of their own after it; they report `backend_failure`, so that a + * path the refusal missed fails closed. + */ +template +struct x25519_engine { + WEBCPP_CRYPTO_DETAIL_REFUSE_X25519(Backend); + + /** Never called; fails closed. */ + template + [[nodiscard]] static boost::system::result base(Arguments&&... /*arguments*/) noexcept { + return error::backend_failure; + } + + /** Never called; fails closed. */ + template + [[nodiscard]] static boost::system::result agree(Arguments&&... /*arguments*/) noexcept { + return error::backend_failure; + } +}; + +} // namespace webcpp::crypto::detail + +// The default backend's engine, when the program links it (design D32): libsodium on every +// target. Its header specialises it for this header, wherever it was first included. +#if defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_X25519_SODIUM) && defined(WEBCPP_CRYPTO_HAS_SODIUM) +#include +#endif + +#endif // WEBCPP_CRYPTO_CURVES_X25519_HPP diff --git a/include/webcpp/crypto/detail/bytes.hpp b/include/webcpp/crypto/detail/bytes.hpp new file mode 100644 index 00000000..95d8ff23 --- /dev/null +++ b/include/webcpp/crypto/detail/bytes.hpp @@ -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) + +#ifndef WEBCPP_CRYPTO_DETAIL_BYTES_HPP +#define WEBCPP_CRYPTO_DETAIL_BYTES_HPP + +#include + +#include +#include + +namespace webcpp::crypto::detail { + +/** + * Whether every byte is zero, in a time that does not depend on the bytes: an OR over all of + * them in a volatile local, read once after the loop, with no early exit, and reduced to one + * bit without a branch, as `equal` does. + * + * @param checked_bytes A secret, such as a shared secret checked for the all-zero result. + * @return Whether every byte is zero (true for none). + */ +[[nodiscard]] inline bool is_all_zero(std::span checked_bytes) noexcept { + unsigned volatile accumulated_bits = 0; + for (std::uint8_t const checked_byte : checked_bytes) { + accumulated_bits = accumulated_bits | static_cast(checked_byte); + } + unsigned const total_bits = accumulated_bits; + // total_bits is at most 255: total_bits - 1 wraps to the type's maximum only when it is 0. + return (((total_bits - 1U) >> 8U) & 1U) != 0; +} + +} // namespace webcpp::crypto::detail + +#endif // WEBCPP_CRYPTO_DETAIL_BYTES_HPP diff --git a/include/webcpp/crypto/detail/capabilities.hpp b/include/webcpp/crypto/detail/capabilities.hpp index 372c6103..5b60e472 100644 --- a/include/webcpp/crypto/detail/capabilities.hpp +++ b/include/webcpp/crypto/detail/capabilities.hpp @@ -38,6 +38,9 @@ struct secp256k1; */ struct ed25519; +/** The family X25519, of `curves::x25519`, also the tag of its one algorithm. */ +struct x25519; + } // namespace webcpp::crypto::families namespace webcpp::crypto::tags { @@ -148,6 +151,11 @@ inline constexpr bool supported inline constexpr bool supported = true; #endif +// X25519 on sodium: native, wasip2, wasip3, emscripten. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool supported = true; +#endif // clang-format on /** @@ -347,6 +355,47 @@ inline constexpr bool linked = true; static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's Ed25519 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: Ed25519 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") #endif +#ifdef WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE +/** The refusals of the family X25519's primary engine for `Backend`, on native. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_X25519(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no X25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no X25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no X25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no X25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: X25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's X25519 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: X25519 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_WASIP2) +/** The refusals of the family X25519's primary engine for `Backend`, on wasip2. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_X25519(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no X25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no X25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no X25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no X25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: X25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's X25519 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: X25519 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_WASIP3) +/** The refusals of the family X25519's primary engine for `Backend`, on wasip3. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_X25519(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no X25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no X25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no X25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no X25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: X25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's X25519 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: X25519 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_EMSCRIPTEN) +/** The refusals of the family X25519's primary engine for `Backend`, on emscripten. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_X25519(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no X25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no X25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no X25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no X25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: X25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's X25519 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: X25519 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#endif // clang-format on #endif // WEBCPP_CRYPTO_DETAIL_CAPABILITIES_HPP diff --git a/include/webcpp/crypto/detail/defaults.hpp b/include/webcpp/crypto/detail/defaults.hpp index 5b6c224b..5badf486 100644 --- a/include/webcpp/crypto/detail/defaults.hpp +++ b/include/webcpp/crypto/detail/defaults.hpp @@ -66,6 +66,14 @@ struct default_backend_of { /** `backends::sodium`. */ using type = backends::sodium; }; +/** Defined where libsodium is the default of X25519. */ +#define WEBCPP_CRYPTO_DETAIL_DEFAULT_X25519_SODIUM 1 +/** The default of X25519 on native, wasip2, wasip3, emscripten: libsodium. */ +template <> +struct default_backend_of { + /** `backends::sodium`. */ + using type = backends::sodium; +}; // clang-format on /** diff --git a/test/Jamfile b/test/Jamfile index 280c640d..f561416b 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -28,10 +28,10 @@ OPTIMISED = speed emscripten:off ; webcpp.headers-alone crypto : ../include : crypto.hpp crypto/config.hpp crypto/equal.hpp crypto/error.hpp crypto/ciphers/aes.hpp crypto/ciphers/gcm.hpp - crypto/random_device.hpp crypto/detail/declassify.hpp crypto/detail/engines.hpp - crypto/detail/entropy.hpp crypto/detail/limits.hpp crypto/detail/windows.hpp - crypto/detail/wipe.hpp crypto/secret.hpp crypto/supports.hpp - crypto/detail/capabilities.hpp crypto/detail/defaults.hpp ; + crypto/random_device.hpp crypto/detail/bytes.hpp crypto/detail/declassify.hpp + crypto/detail/engines.hpp crypto/detail/entropy.hpp crypto/detail/limits.hpp + crypto/detail/windows.hpp crypto/detail/wipe.hpp crypto/secret.hpp + crypto/supports.hpp crypto/detail/capabilities.hpp crypto/detail/defaults.hpp ; # The backend BearSSL's header and the default backend's, with BearSSL linked, # on every target. @@ -50,10 +50,10 @@ webcpp.headers-alone crypto : ../include : crypto/backends/openssl.hpp # The backend ctaes's header alone, with ctaes linked, on every target. webcpp.headers-alone crypto : ../include : crypto/backends/ctaes.hpp : /third_party//ctaes ; -# The backend libsodium's header alone, and Ed25519's with it, with libsodium -# linked, on every target. +# The backend libsodium's header alone, and Ed25519's and X25519's with it, +# with libsodium linked, on every target. webcpp.headers-alone crypto : ../include - : crypto/backends/sodium.hpp crypto/curves/ed25519.hpp + : crypto/backends/sodium.hpp crypto/curves/ed25519.hpp crypto/curves/x25519.hpp : /third_party//sodium ; # libsecp256k1's headers compile alone only with its library, which defines # WEBCPP_CRYPTO_HAS_SECP256K1 (without it, each stops with its message). @@ -269,6 +269,14 @@ crypto-run ed25519_wycheproof_sodium : ed25519_wycheproof_sodium_test.cpp /webcpp//boost_json ; crypto-run ed25519ph_sodium : ed25519ph_sodium_test.cpp : /third_party//sodium ; +# X25519 on libsodium: RFC 7748's scalar multiplications and Alice and Bob, a +# peer of order 8 refused as weak, the guards and the conversion from Ed25519; +# Wycheproof's X25519 file, every case. +crypto-run x25519_sodium : x25519_sodium_test.cpp : /third_party//sodium ; +crypto-run x25519_wycheproof_sodium : x25519_wycheproof_sodium_test.cpp + : /third_party//sodium /third_party//wycheproof + /webcpp//boost_json ; + # The capability table of doc/tables/crypto.json, which generate.py writes # this test from: supports_v of every cell on the target, and each present # cell made, with every backend the target builds linked. diff --git a/test/capabilities_test.cpp b/test/capabilities_test.cpp index a2a55985..3889d595 100644 --- a/test/capabilities_test.cpp +++ b/test/capabilities_test.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include @@ -80,6 +81,12 @@ struct refuses_ed25519 { WEBCPP_CRYPTO_DETAIL_REFUSE_ED25519(Backend); }; +/** The refusals of X25519, parsed: nothing instantiates it. */ +template +struct refuses_x25519 { + WEBCPP_CRYPTO_DETAIL_REFUSE_X25519(Backend); +}; + } // namespace // clang-format off @@ -208,6 +215,20 @@ static_assert(crypto::supports_v, #else static_assert(!crypto::supports_v, backends::sodium>); #endif +// X25519 on bearssl: none. +static_assert(!crypto::supports_v, backends::bearssl>); +// X25519 on openssl: none. +static_assert(!crypto::supports_v, backends::openssl>); +// X25519 on ctaes: none. +static_assert(!crypto::supports_v, backends::ctaes>); +// X25519 on secp256k1: none. +static_assert(!crypto::supports_v, backends::secp256k1>); +// X25519 on sodium: native, wasip2, wasip3, emscripten. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_v, backends::sodium>); +#else +static_assert(!crypto::supports_v, backends::sodium>); +#endif // clang-format on int main() { @@ -256,6 +277,9 @@ int main() { #endif #if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN)) && defined(WEBCPP_CRYPTO_HAS_SODIUM) BOOST_TEST((webcpp::test::made, families::ed25519, tags::ed25519ph, backends::sodium>())); +#endif +#if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN)) && defined(WEBCPP_CRYPTO_HAS_SODIUM) + BOOST_TEST((webcpp::test::made, families::x25519, families::x25519, backends::sodium>())); #endif // clang-format on return webcpp::test::exit_status(boost::report_errors()); diff --git a/test/default_backend_test.cpp b/test/default_backend_test.cpp index 24f3d744..4c4688ed 100644 --- a/test/default_backend_test.cpp +++ b/test/default_backend_test.cpp @@ -65,3 +65,11 @@ static_assert(crypto::detail::supported>); static_assert(crypto::detail::supported>); + +// X25519: libsodium, the only backend, on every target. +static_assert(std::is_same_v, backends::sodium>); +#ifndef WEBCPP_CRYPTO_DETAIL_DEFAULT_X25519_SODIUM +#error "curves/x25519.hpp is told to include another header than libsodium's" +#endif +static_assert(crypto::detail::supported>); diff --git a/test/support/capabilities.hpp b/test/support/capabilities.hpp index c654419a..c792bdbe 100644 --- a/test/support/capabilities.hpp +++ b/test/support/capabilities.hpp @@ -28,7 +28,8 @@ constexpr std::size_t key_size_of() { /** * Makes an algorithm, through the type a program names, from a key whose bytes are all 1, or, - * for one keyed by no key of its own (Ed25519ph's signer), begins it: a cell the capability + * for one keyed by no key of its own (Ed25519ph's signer), begins it, or, for one of free + * functions alone (X25519), gives that key's public key: a cell the capability * table marks present whose engine is missing fails to compile here. The type names its family * and its algorithm as the table does, and `supports_v` says that the backend has it. * @@ -36,19 +37,21 @@ constexpr std::size_t key_size_of() { * @tparam Family Its family's tag. * @tparam Name Its algorithm's tag. * @tparam Backend Its backend. - * @return Whether `make` succeeded. + * @return Whether `make`, `begin` or `public_key` succeeded. */ template [[nodiscard]] bool made() { static_assert(std::is_same_v); static_assert(std::is_same_v); static_assert(webcpp::crypto::supports_v); + std::array()> key_bytes{}; + key_bytes.fill(1); if constexpr (requires { Algorithm::begin(); }) { return Algorithm::begin().has_value(); - } else { - std::array()> key_bytes{}; - key_bytes.fill(1); + } else if constexpr (requires { Algorithm::make(key_bytes); }) { return Algorithm::make(key_bytes).has_value(); + } else { + return Algorithm::public_key(key_bytes).has_value(); } } diff --git a/test/x25519_sodium_test.cpp b/test/x25519_sodium_test.cpp new file mode 100644 index 00000000..16d802f9 --- /dev/null +++ b/test/x25519_sodium_test.cpp @@ -0,0 +1,213 @@ +// 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) + +// X25519 on libsodium: RFC 7748 section 5.2's two scalar multiplications and section 6.1's +// Alice and Bob; a peer key of order 8 (Wycheproof's tcId 63) refused with weak_public_key; the +// guards (keys of other sizes); detail::is_all_zero; and the conversion from Ed25519: the X25519 +// public key of a key pair's x25519_secret() equals curves::ed25519::to_x25519_public of its +// Ed25519 public key, and an Ed25519 key of small order, not canonical or off the curve is +// invalid_public_key. + +#include +#include +#include +#include +#include +#include +#include + +#include "support/hex.hpp" + +#include + +#include +#include +#include +#include +#include +#include + +namespace crypto = webcpp::crypto; +namespace x25519 = webcpp::crypto::curves::x25519; +namespace ed25519 = webcpp::crypto::curves::ed25519; +namespace test = webcpp::test; + +namespace { + +/** The bytes of a secret, as a vector a test compares. */ +std::vector bytes_of(crypto::secret<32> const& shared) { + auto const view = shared.bytes(); + return {view.begin(), view.end()}; +} + +/** The bytes of a public key, as a vector a test compares. */ +std::vector bytes_of(std::array const& key) { + return {key.begin(), key.end()}; +} + +/** RFC 7748 section 5.2: an input scalar and u-coordinate, and the output u-coordinate. */ +void scalar_multiplication(std::string_view scalar, std::string_view u, std::string_view out) { + auto const shared = x25519::agree(test::from_hex(scalar), test::from_hex(u)); + BOOST_TEST(shared.has_value()); + if (shared) { + BOOST_TEST(bytes_of(*shared) == test::from_hex(out)); + } +} + +void rfc7748_section_5_2() { + scalar_multiplication("a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4", + "e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c", + "c3da55379de9c6908e94ea4df28d084f32eccf03491c71f754b4075577a28552"); + scalar_multiplication("4b66e9d4d1b4673c5ad22691957d6af5c11b6421e0ea01d42ca4169e7918ba0d", + "e5210f12786811d3f4b7959d0538ae2c31dbe7106fc03c3efc4cd549c715a493", + "95cbde9476e8907d7aade45cb4b873f88b595a68799fa152e6f8f7647aac7957"); +} + +void rfc7748_section_6_1() { + auto const alice_secret = + test::from_hex("77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a"); + auto const bob_secret = + test::from_hex("5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb"); + auto const alice_public = x25519::public_key(alice_secret); + auto const bob_public = x25519::public_key(bob_secret); + BOOST_TEST(alice_public.has_value()); + BOOST_TEST(bob_public.has_value()); + if (!alice_public || !bob_public) { + return; + } + BOOST_TEST(bytes_of(*alice_public) == + test::from_hex("8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a")); + BOOST_TEST(bytes_of(*bob_public) == + test::from_hex("de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f")); + auto const shared = + test::from_hex("4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742"); + auto const alice_shared = x25519::agree(alice_secret, *bob_public); + auto const bob_shared = + x25519::algorithm::agree(bob_secret, *alice_public); + BOOST_TEST(alice_shared.has_value()); + BOOST_TEST(bob_shared.has_value()); + if (alice_shared && bob_shared) { + BOOST_TEST(bytes_of(*alice_shared) == shared); + BOOST_TEST(bytes_of(*bob_shared) == shared); + } +} + +void weak_peer() { + // Wycheproof x25519_test.json, tcId 63: a public key of order 8, whose shared secret is 0. + auto const shared = x25519::agree( + test::from_hex("e0f978dfcd3a8f1a5093418de54136a584c20b7b349afdf6c0520886f95b1272"), + test::from_hex("e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b800")); + BOOST_TEST(!shared.has_value()); + BOOST_TEST(shared.error() == crypto::error::weak_public_key); +} + +void guards() { + std::array const long_key{}; + std::array const key{9}; + BOOST_TEST(x25519::public_key(std::span(long_key).first(31)).error() == + crypto::error::invalid_key_size); + BOOST_TEST(x25519::public_key(long_key).error() == crypto::error::invalid_key_size); + BOOST_TEST(x25519::agree(std::span(long_key).first(31), key).error() == + crypto::error::invalid_key_size); + BOOST_TEST(x25519::agree(key, std::span(long_key).first(31)).error() == + crypto::error::invalid_public_key); + BOOST_TEST(x25519::agree(key, long_key).error() == crypto::error::invalid_public_key); + BOOST_TEST(ed25519::to_x25519_public(std::span(long_key).first(31)).error() == + crypto::error::invalid_public_key); + BOOST_TEST(ed25519::to_x25519_public(long_key).error() == crypto::error::invalid_public_key); +} + +void all_zero() { + std::array bytes{}; + BOOST_TEST(crypto::detail::is_all_zero(bytes)); + BOOST_TEST(crypto::detail::is_all_zero(std::span{})); + bytes.back() = 0x80; + BOOST_TEST(!crypto::detail::is_all_zero(bytes)); + bytes.back() = 0; + bytes.front() = 1; + BOOST_TEST(!crypto::detail::is_all_zero(bytes)); +} + +/** One Ed25519 key pair's X25519 public key, derived from its secret and converted. */ +void converted(std::string_view seed) { + auto const key = ed25519::keypair::make(test::from_hex(seed)); + BOOST_TEST(key.has_value()); + if (!key) { + return; + } + auto const secret_key = key->x25519_secret(); + auto const ed25519_public = key->public_key(); + BOOST_TEST(secret_key.has_value()); + BOOST_TEST(ed25519_public.has_value()); + if (!secret_key || !ed25519_public) { + return; + } + auto const derived = x25519::public_key(secret_key->bytes()); + auto const converted_key = ed25519::to_x25519_public(*ed25519_public); + auto const named = ed25519::to_x25519_public(*ed25519_public); + BOOST_TEST(derived.has_value()); + BOOST_TEST(converted_key.has_value()); + BOOST_TEST(named.has_value()); + if (derived && converted_key && named) { + BOOST_TEST(bytes_of(*derived) == bytes_of(*converted_key)); + BOOST_TEST(bytes_of(*named) == bytes_of(*converted_key)); + } +} + +void conversion() { + // RFC 8032 section 7.1's secret keys (seeds): the X25519 key pair of an Ed25519 key pair. + constexpr auto seeds = std::to_array({ + "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", + "4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb", + "c5aa8df43f9f837bedb7442f31dcb7b166d38535076f094b85ce3a2e0b4458f7", + "833fe62409237b9d62ec77587520911e9a759cec1d19755b7da901b96dca3d42", + }); + for (auto const seed : seeds) { + converted(seed); + } +} + +void conversion_refuses() { + constexpr auto refused = std::to_array({ + // The neutral element, of order 1. + "0100000000000000000000000000000000000000000000000000000000000000", + // A point of order 8. + "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a", + // A point of order 4, (0, -1). + "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f", + // The neutral element written with y = p + 1, not canonical. + "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f", + // y = 2, whose x is not on the curve. + "0200000000000000000000000000000000000000000000000000000000000000", + }); + for (auto const key : refused) { + auto const converted = ed25519::to_x25519_public(test::from_hex(key)); + BOOST_TEST(!converted.has_value()); + if (!converted) { + BOOST_TEST(converted.error() == crypto::error::invalid_public_key); + } + } +} + +// The algorithm names its family, its name and its backend, as the capability table does. +static_assert(std::is_same_v::family_type, crypto::families::x25519>); +static_assert(std::is_same_v::name_type, crypto::families::x25519>); +static_assert(std::is_same_v::backend_type, crypto::backends::sodium>); +static_assert(x25519::algorithm<>::key_size == 32); +static_assert(crypto::supports_v, crypto::backends::sodium>); + +} // namespace + +int main() { + rfc7748_section_5_2(); + rfc7748_section_6_1(); + weak_peer(); + guards(); + all_zero(); + conversion(); + conversion_refuses(); + return test::exit_status(boost::report_errors()); +} diff --git a/test/x25519_wycheproof_sodium_test.cpp b/test/x25519_wycheproof_sodium_test.cpp new file mode 100644 index 00000000..c7d6ed5a --- /dev/null +++ b/test/x25519_wycheproof_sodium_test.cpp @@ -0,0 +1,96 @@ +// 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) + +// X25519 against Wycheproof's file (testvectors_v1/x25519_test.json) through curves::x25519::agree +// on libsodium, every case: each shared secret Wycheproof gives, except the all-zero ones (keys of +// low order), which libsodium refuses and agree reports as weak_public_key (design D8). A +// disagreement is reported, never listed away. + +#include +#include +#include + +#include "support/hex.hpp" +#include "support/test_data.hpp" + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace crypto = webcpp::crypto; +namespace x25519 = webcpp::crypto::curves::x25519; +namespace test = webcpp::test; +namespace json = boost::json; + +namespace { + +std::string text_of(json::value const& value) { + return std::string(std::string_view(value.as_string())); +} + +/** What one case gave: an agreed secret, a refused weak one, or a verdict not known. */ +enum class outcome { agreed, weak, unknown }; + +/** Runs one case, reporting a disagreement under its tcId. */ +outcome run_case(json::value const& tested) { + auto const secret_key = test::from_hex(text_of(tested.at("private"))); + auto const peer_key = test::from_hex(text_of(tested.at("public"))); + auto const expected = test::from_hex(text_of(tested.at("shared"))); + auto const verdict = text_of(tested.at("result")); + auto label = "tcId " + std::to_string(tested.at("tcId").to_number()); + if (verdict != "valid" && verdict != "acceptable") { + BOOST_ERROR(((label += ": the verdict ") += verdict).c_str()); + return outcome::unknown; + } + auto const shared = x25519::agree(secret_key, peer_key); + if (std::ranges::all_of(expected, [](std::uint8_t byte) { return byte == 0; })) { + if (shared || shared.error() != crypto::error::weak_public_key) { + BOOST_ERROR((label += ": an all-zero secret not refused as weak_public_key").c_str()); + } + return outcome::weak; + } + if (!shared || !std::ranges::equal(shared->bytes(), expected)) { + BOOST_ERROR((label += ": not Wycheproof's shared secret").c_str()); + } + return outcome::agreed; +} + +} // namespace + +int main() { + auto const document_text = + test::read_file(WEBCPP_TEST_WYCHEPROOF "/testvectors_v1/x25519_test.json"); + boost::system::error_code parse_error; + auto const document = json::parse(document_text, parse_error); + BOOST_TEST(!parse_error); + if (parse_error) { + return test::exit_status(boost::report_errors()); + } + int total = 0; + int agreed = 0; + int weak = 0; + for (auto const& group : document.at("testGroups").as_array()) { + BOOST_TEST(text_of(group.at("curve")) == "curve25519"); + for (auto const& tested : group.at("tests").as_array()) { + ++total; + auto const result = run_case(tested); + agreed += result == outcome::agreed ? 1 : 0; + weak += result == outcome::weak ? 1 : 0; + } + } + std::cout << "x25519 wycheproof: tests=" << total << " agreed=" << agreed << " weak=" << weak + << '\n'; + BOOST_TEST_EQ(total, 518); + BOOST_TEST_EQ(agreed, 487); + BOOST_TEST_EQ(weak, 31); + return test::exit_status(boost::report_errors()); +} From 150934312c3be81651f942501ede7c622daf30ad Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 15:59:51 -0300 Subject: [PATCH 018/110] crypto: secret's deleted bytes() on an rvalue is [[nodiscard]], as clang-tidy's modernize-use-nodiscard asks --- include/webcpp/crypto/secret.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/webcpp/crypto/secret.hpp b/include/webcpp/crypto/secret.hpp index dcc665fc..05ff087f 100644 --- a/include/webcpp/crypto/secret.hpp +++ b/include/webcpp/crypto/secret.hpp @@ -95,7 +95,7 @@ class secret { @return Nothing. */ - std::span bytes() const&& = delete; + [[nodiscard]] std::span bytes() const&& = delete; /** The bytes, for the library's engines to write. From eafacac4fb477846125c60c5fce87917a3a5906b Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 18:07:44 -0300 Subject: [PATCH 019/110] crypto: X25519's refusals each pinned by a test (mixed order, y = p + 3, agree's own all-zero check), and its results [[nodiscard]] The conversion's main-subgroup check is now the only check that refuses two of the keys the test passes; a stand-in engine that does not refuse an all-zero shared secret shows that agree refuses it itself. The point (0, -1) is of order 2. The use case names curves::ed25519::keypair::x25519_secret in full. --- doc/generated/use-cases.adoc | 2 +- doc/llms.txt | 2 +- doc/tables/crypto.json | 2 +- include/webcpp/crypto/curves/ed25519.hpp | 2 +- include/webcpp/crypto/curves/x25519.hpp | 11 ++- test/Jamfile | 3 + test/x25519_mock_test.cpp | 120 +++++++++++++++++++++++ test/x25519_sodium_test.cpp | 13 ++- 8 files changed, 143 insertions(+), 12 deletions(-) create mode 100644 test/x25519_mock_test.cpp diff --git a/doc/generated/use-cases.adoc b/doc/generated/use-cases.adoc index e75bfc5e..d1859ba2 100644 --- a/doc/generated/use-cases.adoc +++ b/doc/generated/use-cases.adoc @@ -134,7 +134,7 @@ |<> |Agree a shared secret with a peer's public key (X25519, RFC 7748), or with the X25519 form of an Ed25519 key -|In `+curves::x25519+`: `+public_key+`, `+agree+`; `+curves::ed25519::to_x25519_public+`, `+keypair::x25519_secret+` +|In `+curves::x25519+`: `+public_key+`, `+agree+`; `+curves::ed25519::to_x25519_public+`, `+curves::ed25519::keypair::x25519_secret+` |libsodium |`+/webcpp/crypto//crypto+` + `+/webcpp/crypto//x25519-default+` diff --git a/doc/llms.txt b/doc/llms.txt index b038f4c6..4788a414 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -117,7 +117,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [Seed BearSSL's own generator for code that calls BearSSL directly](https://webcpporg.github.io/libs/crypto/#crypto-entropy-bearssl): `random_device::fill` (webcpp::crypto); backend BearSSL's C API; Jamfile /webcpp/crypto//crypto /third_party//bearssl. Example: example/bearssl_prng.cpp. - [Hash, or compute an HMAC](https://webcpporg.github.io/libs/crypto/#crypto-overview-hash2): `boost::hash2::sha2_256`, `hmac_sha2_256` (Boost.Hash2, not this library); backend none; Jamfile `/webcpp/crypto//crypto` brings Boost's headers. Example: example/equal_hmac.cpp. - [Sign and verify with Ed25519 (RFC 8032), or sign a large message in pieces with Ed25519ph](https://webcpporg.github.io/libs/crypto/#crypto-ed25519): `keypair::make`, `keypair::generate`, `keypair::sign`, `verify`; `ph` (webcpp::crypto::curves::ed25519); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//ed25519-default. Example: example/ed25519_sign.cpp. -- [Agree a shared secret with a peer's public key (X25519, RFC 7748), or with the X25519 form of an Ed25519 key](https://webcpporg.github.io/libs/crypto/#crypto-x25519): `public_key`, `agree`; `curves::ed25519::to_x25519_public`, `keypair::x25519_secret` (webcpp::crypto::curves::x25519); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//x25519-default. Example: example/x25519_agree.cpp. +- [Agree a shared secret with a peer's public key (X25519, RFC 7748), or with the X25519 form of an Ed25519 key](https://webcpporg.github.io/libs/crypto/#crypto-x25519): `public_key`, `agree`; `curves::ed25519::to_x25519_public`, `curves::ed25519::keypair::x25519_secret` (webcpp::crypto::curves::x25519); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//x25519-default. Example: example/x25519_agree.cpp. - [Use P-256 (passkeys, JWT's ES256)](https://webcpporg.github.io/libs/crypto/#crypto-curves): secp256k1, Ed25519 and X25519 keys and signatures do not interoperate with this curve (none in this version); backend none; Jamfile none. ## Examples diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index b8694e0b..98eb6c5e 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -517,7 +517,7 @@ {"need": "Seed BearSSL's own generator for code that calls BearSSL directly", "namespace": "webcpp::crypto", "api": "`random_device::fill`", "backend": "BearSSL's C API", "jamfile": "/webcpp/crypto//crypto /third_party//bearssl", "example": "bearssl_prng", "section": "crypto-entropy-bearssl"}, {"need": "Hash, or compute an HMAC", "namespace": "Boost.Hash2, not this library", "api": "`boost::hash2::sha2_256`, `hmac_sha2_256`", "backend": "none", "jamfile": "`/webcpp/crypto//crypto` brings Boost's headers", "example": "equal_hmac", "section": "crypto-overview-hash2"}, {"need": "Sign and verify with Ed25519 (RFC 8032), or sign a large message in pieces with Ed25519ph", "namespace": "webcpp::crypto::curves::ed25519", "api": "`keypair::make`, `keypair::generate`, `keypair::sign`, `verify`; `ph`", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//ed25519-default", "example": "ed25519_sign", "section": "crypto-ed25519"}, - {"need": "Agree a shared secret with a peer's public key (X25519, RFC 7748), or with the X25519 form of an Ed25519 key", "namespace": "webcpp::crypto::curves::x25519", "api": "`public_key`, `agree`; `curves::ed25519::to_x25519_public`, `keypair::x25519_secret`", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//x25519-default", "example": "x25519_agree", "section": "crypto-x25519"}, + {"need": "Agree a shared secret with a peer's public key (X25519, RFC 7748), or with the X25519 form of an Ed25519 key", "namespace": "webcpp::crypto::curves::x25519", "api": "`public_key`, `agree`; `curves::ed25519::to_x25519_public`, `curves::ed25519::keypair::x25519_secret`", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//x25519-default", "example": "x25519_agree", "section": "crypto-x25519"}, {"need": "Use P-256 (passkeys, JWT's ES256)", "namespace": "none in this version", "api": "secp256k1, Ed25519 and X25519 keys and signatures do not interoperate with this curve", "backend": "none", "jamfile": "none", "example": "", "section": "crypto-curves"} ], "fixtures": { diff --git a/include/webcpp/crypto/curves/ed25519.hpp b/include/webcpp/crypto/curves/ed25519.hpp index e025ea63..22674c7d 100644 --- a/include/webcpp/crypto/curves/ed25519.hpp +++ b/include/webcpp/crypto/curves/ed25519.hpp @@ -269,7 +269,7 @@ boost::system::result verify(std::span public_key, * curve or of small order. */ template > -boost::system::result> to_x25519_public( +[[nodiscard]] boost::system::result> to_x25519_public( std::span ed25519_public_key) noexcept { if (ed25519_public_key.size() != 32) { return error::invalid_public_key; diff --git a/include/webcpp/crypto/curves/x25519.hpp b/include/webcpp/crypto/curves/x25519.hpp index 342176c1..a06b050d 100644 --- a/include/webcpp/crypto/curves/x25519.hpp +++ b/include/webcpp/crypto/curves/x25519.hpp @@ -66,7 +66,7 @@ struct algorithm { * @param secret_key 32 bytes; any 32 bytes are a secret key (RFC 7748 clamps them). * @return 32 bytes; `invalid_key_size`; `backend_failure`. */ - static boost::system::result> public_key( + [[nodiscard]] static boost::system::result> public_key( std::span secret_key) noexcept { if (secret_key.size() != key_size) { return error::invalid_key_size; @@ -87,7 +87,7 @@ struct algorithm { * @return 32 secret bytes; `invalid_key_size`; `invalid_public_key`; `weak_public_key` * for a peer key of low order, whose shared secret is all zero; `backend_failure`. */ - static boost::system::result> agree( + [[nodiscard]] static boost::system::result> agree( std::span secret_key, std::span peer_public_key) noexcept { if (secret_key.size() != key_size) { @@ -122,7 +122,7 @@ struct algorithm { * @return 32 bytes; `invalid_key_size`; `backend_failure`. */ template > -boost::system::result> public_key( +[[nodiscard]] boost::system::result> public_key( std::span secret_key) noexcept { return algorithm::public_key(secret_key); } @@ -137,8 +137,9 @@ boost::system::result> public_key( * `backend_failure`. */ template > -boost::system::result> agree(std::span secret_key, - std::span peer_public_key) noexcept { +[[nodiscard]] boost::system::result> agree( + std::span secret_key, + std::span peer_public_key) noexcept { return algorithm::agree(secret_key, peer_public_key); } diff --git a/test/Jamfile b/test/Jamfile index f561416b..143ce031 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -273,6 +273,9 @@ crypto-run ed25519ph_sodium : ed25519ph_sodium_test.cpp : /third_party/ # peer of order 8 refused as weak, the guards and the conversion from Ed25519; # Wycheproof's X25519 file, every case. crypto-run x25519_sodium : x25519_sodium_test.cpp : /third_party//sodium ; +# X25519's generic layer on a stand-in engine that does not refuse an all-zero +# shared secret: agree refuses it itself (design D8). +crypto-run x25519_mock : x25519_mock_test.cpp ; crypto-run x25519_wycheproof_sodium : x25519_wycheproof_sodium_test.cpp : /third_party//sodium /third_party//wycheproof /webcpp//boost_json ; diff --git a/test/x25519_mock_test.cpp b/test/x25519_mock_test.cpp new file mode 100644 index 00000000..25309747 --- /dev/null +++ b/test/x25519_mock_test.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) + +// X25519's generic layer on a stand-in backend whose engine reports success for every shared +// secret: curves::x25519::agree refuses an all-zero result itself (design D8), as libsodium +// does, so that a backend that does not refuse it gives the same answer; any other result is +// the shared secret, and an engine's error is passed on. + +#include +#include +#include + +#include +#include + +#include +#include +#include +#include + +namespace webcpp::test { + +/** A backend tag for X25519's generic layer alone. */ +struct x25519_stand_in {}; + +/** What the stand-in's agree writes, or the error it returns instead. */ +struct x25519_stand_in_knobs { + /** The byte every byte of the shared secret is set to. */ + std::uint8_t fill = 0; + /** The error agree returns, when set. */ + boost::system::error_code error; +}; + +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the knobs a test turns +inline x25519_stand_in_knobs x25519_stand_in_control{}; + +} // namespace webcpp::test + +namespace webcpp::crypto::detail { + +/** The stand-in's engine: agree writes the knob's byte and succeeds, as a backend that does + * not refuse an all-zero shared secret would. */ +template <> +struct x25519_engine { + /** Writes the knob's byte. */ + [[nodiscard]] static boost::system::result base( + std::span /*secret_key*/, + std::span out) noexcept { + std::ranges::fill(out, test::x25519_stand_in_control.fill); + return {}; + } + + /** Writes the knob's byte, or returns the knob's error. */ + [[nodiscard]] static boost::system::result agree( + std::span /*secret_key*/, + std::span /*peer_public_key*/, + std::span out) noexcept { + if (test::x25519_stand_in_control.error) { + return test::x25519_stand_in_control.error; + } + std::ranges::fill(out, test::x25519_stand_in_control.fill); + return {}; + } +}; + +} // namespace webcpp::crypto::detail + +namespace { + +namespace crypto = webcpp::crypto; +namespace test = webcpp::test; +using stand_in = crypto::curves::x25519::algorithm; + +void all_zero_refused() { + test::x25519_stand_in_control = {}; + std::array const key{9}; + auto const shared = stand_in::agree(key, key); + BOOST_TEST(!shared.has_value()); + if (!shared) { + BOOST_TEST(shared.error() == crypto::error::weak_public_key); + } + auto const named = crypto::curves::x25519::agree(key, key); + BOOST_TEST(!named.has_value()); + if (!named) { + BOOST_TEST(named.error() == crypto::error::weak_public_key); + } +} + +void other_result_kept() { + test::x25519_stand_in_control = {.fill = 0x5a, .error = {}}; + std::array const key{9}; + auto const shared = stand_in::agree(key, key); + BOOST_TEST(shared.has_value()); + if (shared) { + auto const bytes = shared->bytes(); + BOOST_TEST(std::ranges::all_of(bytes, [](std::uint8_t byte) { return byte == 0x5a; })); + } +} + +void engine_error_passed_on() { + test::x25519_stand_in_control = {.fill = 0, .error = crypto::error::backend_failure}; + std::array const key{9}; + auto const shared = stand_in::agree(key, key); + BOOST_TEST(!shared.has_value()); + if (!shared) { + BOOST_TEST(shared.error() == crypto::error::backend_failure); + } +} + +} // namespace + +int main() { + all_zero_refused(); + other_result_kept(); + engine_error_passed_on(); + return test::exit_status(boost::report_errors()); +} diff --git a/test/x25519_sodium_test.cpp b/test/x25519_sodium_test.cpp index 16d802f9..5a627b6f 100644 --- a/test/x25519_sodium_test.cpp +++ b/test/x25519_sodium_test.cpp @@ -8,8 +8,8 @@ // Alice and Bob; a peer key of order 8 (Wycheproof's tcId 63) refused with weak_public_key; the // guards (keys of other sizes); detail::is_all_zero; and the conversion from Ed25519: the X25519 // public key of a key pair's x25519_secret() equals curves::ed25519::to_x25519_public of its -// Ed25519 public key, and an Ed25519 key of small order, not canonical or off the curve is -// invalid_public_key. +// Ed25519 public key, and an Ed25519 key of small order, of mixed order, not canonical or off the +// curve is invalid_public_key. #include #include @@ -176,12 +176,19 @@ void conversion_refuses() { "0100000000000000000000000000000000000000000000000000000000000000", // A point of order 8. "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a", - // A point of order 4, (0, -1). + // A point of order 2, (0, -1). "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f", // The neutral element written with y = p + 1, not canonical. "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f", // y = 2, whose x is not on the curve. "0200000000000000000000000000000000000000000000000000000000000000", + // A point of mixed order 8L: RFC 8032 section 7.1's first public key plus the point of + // order 8 above. Not of small order and on the curve: refused only as outside the + // prime-order subgroup. + "9158312a9a8d6e3b34c891d6d61444f8b8211c5117ebad15bdb0bd68b07e0245", + // y = p + 3, not canonical: on the curve, of order 8L, so refused only as outside the + // prime-order subgroup. + "f0ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f", }); for (auto const key : refused) { auto const converted = ed25519::to_x25519_public(test::from_hex(key)); From 2413fc5358d3f990536f9a645d9b6d7a451daa93 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 18:46:16 -0300 Subject: [PATCH 020/110] crypto: threads detection, and heavy operations' variants refused without threads config.hpp defines WEBCPP_CRYPTO_HAS_THREADS by design D23's rule (natively BOOST_HAS_THREADS, on Emscripten -pthread, never on WASI, never with WEBCPP_CRYPTO_NO_THREADS). detail/heavy.hpp holds the refusal every heavy operation's async_ variant starts with, and detail::run_heavy, which posts the synchronous call to the program's executor and completes on the handler's associated executor. Increment 1 declares no heavy operation (design D32). --- doc/changelog.adoc | 2 +- doc/generated/jamfiles.adoc | 16 +++ doc/generated/messages.adoc | 24 ++++ doc/tables/crypto.json | 8 +- include/webcpp/crypto/config.hpp | 36 ++++- include/webcpp/crypto/detail/heavy.hpp | 112 +++++++++++++++ test/Jamfile | 19 ++- test/heavy_test.cpp | 134 ++++++++++++++++++ test/messages/Jamfile | 1 + test/messages/heavy_without_threads/Jamfile | 23 +++ .../heavy_without_threads.cpp | 46 ++++++ test/msvc/Jamfile | 1 + test/msvc/heavy_without_threads/Jamfile | 9 ++ test/msvc/heavy_without_threads/app.cpp | 36 +++++ test/threads_config_test.cpp | 48 +++++++ 15 files changed, 508 insertions(+), 7 deletions(-) create mode 100644 include/webcpp/crypto/detail/heavy.hpp create mode 100644 test/heavy_test.cpp create mode 100644 test/messages/heavy_without_threads/Jamfile create mode 100644 test/messages/heavy_without_threads/heavy_without_threads.cpp create mode 100644 test/msvc/heavy_without_threads/Jamfile create mode 100644 test/msvc/heavy_without_threads/app.cpp create mode 100644 test/threads_config_test.cpp diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 24a9176a..23ea1ee1 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -16,7 +16,7 @@ of every version are on webcpp's index page. === Unreleased // tag::unreleased[] -* Added crypto, primitives over C backends: ciphers, curves and randomness, with errors of fixed values in webcpp.crypto, every result `+[[nodiscard]]+`. +* Added crypto, primitives over C backends: ciphers, curves and randomness, with errors of fixed values in webcpp.crypto, every result `+[[nodiscard]]+`, and WEBCPP_CRYPTO_HAS_THREADS, defined natively and on Emscripten with -pthread unless WEBCPP_CRYPTO_NO_THREADS is. * Added equal, random_device, ciphers::aes128, aes192 and aes256, the AES block cipher, and ciphers::gcm, AES-GCM in place with an incremental seal whose failed open zeroes the data. * Added default_backend_t and /webcpp/crypto//-default, one default backend per family and target whatever is linked, ciphers::aes128_gcm and aes256_gcm, and refusals naming the Jamfile line and another backend's type. * Added backends::bearssl (AES-GCM allocating nothing, no block cipher), backends::openssl through /webcpp/crypto//openssl on native and WASI (allocating at make only), and backends::ctaes (block cipher alone). diff --git a/doc/generated/jamfiles.adoc b/doc/generated/jamfiles.adoc index 333dfd27..e8612790 100644 --- a/doc/generated/jamfiles.adoc +++ b/doc/generated/jamfiles.adoc @@ -151,6 +151,22 @@ It prints: include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/sign_small/sign_small.outcome[tag=output] ---- +`+threads_on_emscripten+`:: A program for Emscripten built with `+multi+`, which is `+-pthread+`: the build has threads. ++ +Its Jamfile, built and run on emscripten: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/threads_on_emscripten/Jamfile[tag=jamfile] +---- ++ +It prints: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/threads_on_emscripten/threads_on_emscripten.outcome[tag=output] +---- + `+web+`:: A web application: AES-256-GCM on BearSSL, the default on WebAssembly. + Its Jamfile, built and run on wasip2, wasip3, emscripten: diff --git a/doc/generated/messages.adoc b/doc/generated/messages.adoc index 7d08a410..b42dbf8c 100644 --- a/doc/generated/messages.adoc +++ b/doc/generated/messages.adoc @@ -73,6 +73,12 @@ The fix: Natively the default is OpenSSL: add `+/webcpp/crypto//openssl+`, or na The fix: Name `+gcm>+` or `+gcm>+`, or use `+aes256_gcm+` with its default linked. +|`+heavy_without_threads+` +|native, wasip2, wasip3 +|`+webcpp::crypto: async_slow runs on another thread and needs a build with threads (natively b2 threading=multi; on Emscripten -pthread). Without threads, call slow.+` + +The fix: Call the synchronous operation the message names, or build with threads: natively without `+WEBCPP_CRYPTO_NO_THREADS+` (b2's `+threading=multi+`), on Emscripten with `+-pthread+`; WASI has none. + |`+no_backend_wasm+` |wasip2, wasip3 |`+webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked. Add /third_party//bearssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)+` @@ -438,6 +444,20 @@ On each target, the build's output contains: * emscripten: ** `+webcpp::crypto: OpenSSL is not built for Emscripten. In the program's Jamfile, replace /webcpp/crypto//openssl with /third_party//bearssl.+` +`+heavy_without_threads_on_emscripten+`:: A program for Emscripten without `+-pthread+` that calls a heavy operation's `+async_+` variant (a test's own). The fix: As `+heavy_without_threads+`: on Emscripten, add `+multi+`. ++ +Its Jamfile: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/heavy_without_threads_on_emscripten/Jamfile[tag=jamfile] +---- ++ +On each target, the build's output contains: ++ +* emscripten: +** `+webcpp::crypto: async_slow runs on another thread and needs a build with threads (natively b2 threading=multi; on Emscripten -pthread). Without threads, call slow.+` + `+memory_missing_definition_install+`:: The memory option set in the program's project, the install called, and `+openssl_memory_resource()+` not defined. The fix: Define `+std::pmr::memory_resource& webcpp::crypto::openssl_memory_resource() noexcept+` once in the program, returning a resource that is never destroyed. + Its Jamfile: @@ -610,6 +630,10 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |Name `+gcm>+` or `+gcm>+`, or use `+aes256_gcm+` with its default linked. +|`+heavy_without_threads+` +|the compile +|Call the synchronous operation the message names, or build with threads: natively without `+WEBCPP_CRYPTO_NO_THREADS+` (b2's `+threading=multi+`), on Emscripten with `+-pthread+`; WASI has none. + |`+memory_missing_definition_install+` |the link |Define `+std::pmr::memory_resource& webcpp::crypto::openssl_memory_resource() noexcept+` once in the program, returning a resource that is never destroyed. diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 98eb6c5e..ccef1c45 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -551,7 +551,9 @@ "sodium_not_linked_on_emscripten": "A program for Emscripten that names libsodium and links none.", "ed25519_default_not_linked_on_emscripten": "A program for Emscripten that makes an Ed25519 key pair on its default, libsodium, and links none.", "ed25519_on_bearssl_on_emscripten": "A program for Emscripten that names BearSSL, which has no Ed25519, in an Ed25519 key pair's type.", - "ed25519ph_sha256_on_emscripten": "A program for Emscripten that names SHA-256 in Ed25519ph's type, which RFC 8032 defines over SHA-512." + "ed25519ph_sha256_on_emscripten": "A program for Emscripten that names SHA-256 in Ed25519ph's type, which RFC 8032 defines over SHA-512.", + "heavy_without_threads_on_emscripten": "A program for Emscripten without `-pthread` that calls a heavy operation's `async_` variant (a test's own).", + "threads_on_emscripten": "A program for Emscripten built with `multi`, which is `-pthread`: the build has threads." }, "fixes": { "gcm_default_openssl_not_linked": "Natively the default is OpenSSL: add `/webcpp/crypto//openssl`, or name BearSSL in the type, as in `gcm>`.", @@ -596,6 +598,8 @@ "ed25519ph_sha256": "Name `curves::ed25519::ph`: RFC 8032 defines Ed25519ph over SHA-512.", "ed25519ph_sha256_on_emscripten": "As `ed25519ph_sha256`.", "ed25519_default_not_linked": "Add `/third_party//sodium`, or `/webcpp/crypto//ed25519-default`, which links it on every target.", - "ed25519_default_not_linked_on_emscripten": "As `ed25519_default_not_linked`." + "ed25519_default_not_linked_on_emscripten": "As `ed25519_default_not_linked`.", + "heavy_without_threads": "Call the synchronous operation the message names, or build with threads: natively without `WEBCPP_CRYPTO_NO_THREADS` (b2's `threading=multi`), on Emscripten with `-pthread`; WASI has none.", + "heavy_without_threads_on_emscripten": "As `heavy_without_threads`: on Emscripten, add `multi`." } } diff --git a/include/webcpp/crypto/config.hpp b/include/webcpp/crypto/config.hpp index d0585364..f4afac49 100644 --- a/include/webcpp/crypto/config.hpp +++ b/include/webcpp/crypto/config.hpp @@ -6,9 +6,10 @@ /** The configuration of webcpp::crypto, which each of its headers includes first: - whether it is built without exceptions, whether the target is WebAssembly, the - backends the build links, and the refusal of version 0.1's defines that chose the - default backend, which the target alone now chooses (`detail/defaults.hpp`). + whether it is built without exceptions, whether the target is WebAssembly, whether + the build has threads, the backends the build links, and the refusal of version + 0.1's defines that chose the default backend, which the target alone now chooses + (`detail/defaults.hpp`). @see "Using webcpp::crypto in your Jamfile", in the guide. */ @@ -40,6 +41,26 @@ /** Defined on the WebAssembly targets, wasip2, wasip3 and Emscripten. */ #define WEBCPP_CRYPTO_WEBASSEMBLY 1 #undef WEBCPP_CRYPTO_WEBASSEMBLY +/** + Defined when the build has threads (design D23): natively when Boost.Config defines + `BOOST_HAS_THREADS`, on Emscripten when the program is built with `-pthread` (b2's + `threading=multi`), never on wasip2 or wasip3, and never when the program defines + `WEBCPP_CRYPTO_NO_THREADS`. Only then do the heavy operations' `async_` variants run on + another thread; without it, a program that calls one stops with the synchronous name to + call instead. + + Natively Boost.Config defines `BOOST_HAS_THREADS` whatever b2's `threading` says on macOS, + on Windows and with libstdc++ or libc++ on Linux, so that a native build has threads + unless the program defines `WEBCPP_CRYPTO_NO_THREADS`. +*/ +#define WEBCPP_CRYPTO_HAS_THREADS 1 +#undef WEBCPP_CRYPTO_HAS_THREADS +/** + Defined by a program that wants no threads from webcpp::crypto: `WEBCPP_CRYPTO_HAS_THREADS` + stays undefined, and the heavy operations' `async_` variants refuse to compile. +*/ +#define WEBCPP_CRYPTO_NO_THREADS +#undef WEBCPP_CRYPTO_NO_THREADS #ifdef WEBCPP_CRYPTO_HAS_BEARSSL /** Defined while config.hpp reads a reference's build that links BearSSL (doc/Jamfile). */ #define WEBCPP_CRYPTO_DETAIL_REFERENCE_LINKS_BEARSSL @@ -145,6 +166,15 @@ #define WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE 1 #endif +// Threads (design D23): natively when Boost.Config sees threads (b2 threading=multi), on +// Emscripten with -pthread, never on WASI. +#if !defined(WEBCPP_CRYPTO_NO_THREADS) && !defined(WEBCPP_TARGET_WASIP2) && \ + !defined(WEBCPP_TARGET_WASIP3) && \ + ((defined(WEBCPP_TARGET_EMSCRIPTEN) && defined(__EMSCRIPTEN_PTHREADS__)) || \ + (!defined(WEBCPP_TARGET_EMSCRIPTEN) && defined(BOOST_HAS_THREADS))) +#define WEBCPP_CRYPTO_HAS_THREADS 1 +#endif + // The refusals of impossible combinations. Clang and gcc go on after an // #error, so the first error is the instruction; MSVC stops at it. OpenSSL is built for // native, wasip2 and wasip3 (/webcpp/crypto//openssl), never for Emscripten; with b2, diff --git a/include/webcpp/crypto/detail/heavy.hpp b/include/webcpp/crypto/detail/heavy.hpp new file mode 100644 index 00000000..c93f73cc --- /dev/null +++ b/include/webcpp/crypto/detail/heavy.hpp @@ -0,0 +1,112 @@ +// 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 heavy operations' `async_` variants (design D23): in a build with threads + (`WEBCPP_CRYPTO_HAS_THREADS`), `detail::run_heavy` runs the synchronous call on the executor + the program gives and completes on the handler's associated executor; without threads, the + variant's first statement, `WEBCPP_CRYPTO_DETAIL_REQUIRE_THREADS`, stops the build where the + program calls it. + + The heavy operations are stated (design D32): RSA key generation at every size and RSA private + operations at 3072 bits and above; SLH-DSA key generation, signing and verification; ML-DSA key + generation and signing; BLS12-381 verification, aggregate verification, fast aggregate + verification and aggregation; KZG's commitments and proofs over a blob and their batch + verification; BN254's `pairing_check`. Everything else is cheap and synchronous only. +*/ +#ifndef WEBCPP_CRYPTO_DETAIL_HEAVY_HPP +#define WEBCPP_CRYPTO_DETAIL_HEAVY_HPP + +#include + +#include + +#include +#include + +#ifdef WEBCPP_CRYPTO_HAS_THREADS +#include +#include +#include +#include +#include +#include +#endif + +namespace webcpp::crypto::detail { + +/** + The refusal of a heavy operation's `async_` variant in a build without threads (design D23). + Each such variant's body starts with it, so that a program fails only where it calls one. + The variant's completion token is its parameter `token`. +*/ +#ifdef WEBCPP_CRYPTO_HAS_THREADS +#define WEBCPP_CRYPTO_DETAIL_REQUIRE_THREADS(async_name, sync_name) +#else +#define WEBCPP_CRYPTO_DETAIL_REQUIRE_THREADS(async_name, sync_name) \ + static_assert(::webcpp::crypto::detail::dependent_false, \ + "webcpp::crypto: " async_name \ + " runs on another thread and needs a build with threads (natively b2 " \ + "threading=multi; on Emscripten -pthread). Without threads, call " sync_name \ + ".") +#endif + +#ifdef WEBCPP_CRYPTO_HAS_THREADS + +/** + * Runs a heavy operation's synchronous call on another thread: posts `function` to `executor` + * (natively a `thread_pool`'s; on Emscripten a pool whose threads are Web Workers) and + * dispatches its result to the handler's associated executor, which by default is `executor`. + * The handler's executor is kept busy until then, so that an `io_context` the handler runs on + * does not run out of work while the call runs elsewhere. + * + * @tparam Executor The executor the call runs on. + * @tparam Function A call without arguments that reports its errors as values, not by throwing. + * @tparam CompletionToken Any completion token; the completion signature is `void(R)`, `R` the + * call's result. + * @param executor Where the call runs. + * @param function The synchronous call. + * @param token How the program is told of the result. + * @return What the completion token makes of the operation. + */ +template +auto run_heavy(Executor executor, Function function, CompletionToken&& token) { + static_assert(std::is_nothrow_invocable_v, + "webcpp::crypto: a heavy operation's call reports its errors as values"); + using result_type = std::invoke_result_t; + auto initiation = [](auto handler, Executor work_executor, Function call) { + auto completion_executor = + boost::asio::prefer(boost::asio::get_associated_executor(handler, work_executor), + boost::asio::execution::outstanding_work.tracked); + boost::asio::post( + work_executor, [handler = std::move(handler), call = std::move(call), + completion_executor = std::move(completion_executor)]() mutable { + auto result = call(); + boost::asio::dispatch(completion_executor, [handler = std::move(handler), + result = std::move(result)]() mutable { + std::move(handler)(std::move(result)); + }); + }); + }; + return boost::asio::async_initiate( + std::move(initiation), token, std::move(executor), std::move(function)); +} + +#else + +/** + * Without threads, a stand-in that does nothing: a refused variant's body compiles past its + * refusal, which has stopped the build already, without errors of its own. + */ +template +void run_heavy(Executor&& /*executor*/, Function&& /*function*/, + CompletionToken&& /*token*/) noexcept {} + +#endif + +} // namespace webcpp::crypto::detail + +#endif // WEBCPP_CRYPTO_DETAIL_HEAVY_HPP diff --git a/test/Jamfile b/test/Jamfile index 143ce031..dea7e9d3 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -31,7 +31,8 @@ webcpp.headers-alone crypto : ../include : crypto.hpp crypto/config.hpp crypto/random_device.hpp crypto/detail/bytes.hpp crypto/detail/declassify.hpp crypto/detail/engines.hpp crypto/detail/entropy.hpp crypto/detail/limits.hpp crypto/detail/windows.hpp crypto/detail/wipe.hpp crypto/secret.hpp - crypto/supports.hpp crypto/detail/capabilities.hpp crypto/detail/defaults.hpp ; + crypto/supports.hpp crypto/detail/capabilities.hpp crypto/detail/defaults.hpp + crypto/detail/heavy.hpp ; # The backend BearSSL's header and the default backend's, with BearSSL linked, # on every target. @@ -71,6 +72,22 @@ webcpp.compile config_all_off : config_test.cpp webcpp.compile config_developer_defined : config_test.cpp : WEBCPP_CRYPTO_NO_EXCEPTIONS WEBCPP_TEST_CRYPTO_DEVELOPER_DEFINED ; +# config.hpp defines WEBCPP_CRYPTO_HAS_THREADS by design D23's rule: natively +# with b2's threading=single (where Boost.Config's BOOST_HAS_THREADS decides), +# with threading=multi, and with WEBCPP_CRYPTO_NO_THREADS; on WebAssembly +# without -pthread (Emscripten with -pthread is the fixture +# threads_on_emscripten of tools/test/crypto_jamfiles_test.py). +webcpp.compile threads_config_single : threads_config_test.cpp + : single WEBCPP_TEST_CRYPTO_THREADING_SINGLE : native ; +webcpp.compile threads_config_multi : threads_config_test.cpp + : multi WEBCPP_TEST_CRYPTO_THREADING_MULTI : native ; +webcpp.compile threads_config_opted_out : threads_config_test.cpp + : multi WEBCPP_CRYPTO_NO_THREADS : native ; +webcpp.compile threads_config_wasm : threads_config_test.cpp : : wasip2 wasip3 emscripten ; +# A heavy operation's async_ variant with threads: detail::run_heavy runs the +# work on a thread_pool and completes on the caller's io_context. +crypto-run heavy : heavy_test.cpp : multi : native ; + crypto-run error : error_test.cpp ; crypto-run equal : equal_test.cpp ; # alone, with no backend linked, compiles, links and runs. diff --git a/test/heavy_test.cpp b/test/heavy_test.cpp new file mode 100644 index 00000000..c3a700a7 --- /dev/null +++ b/test/heavy_test.cpp @@ -0,0 +1,134 @@ +// 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) + +// detail::run_heavy, the initiator of every heavy operation's async_ variant (design D23), in a +// build with threads, on a test-only heavy operation: the work runs on the executor given (a +// thread_pool's), not on the caller's thread; the caller's io_context goes on meanwhile (a 10 ms +// timer on it fires while the work waits for it); the completion runs on the handler's +// associated executor (the caller's io_context, on the caller's thread), whose io_context does +// not run out of work before it; a move-only result reaches the handler; and any completion +// token works (asio's deferred). + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#ifndef WEBCPP_CRYPTO_HAS_THREADS +#error "test/Jamfile builds this test with threading=multi, where the build has threads" +#endif + +namespace crypto = webcpp::crypto; + +namespace { + +/** The test-only heavy operation, synchronous. */ +int slow(int value) noexcept { + return value + 1; +} + +/** Its async_ variant, as every heavy operation declares one. */ +template +auto async_slow(Executor executor, int value, CompletionToken&& token) { + WEBCPP_CRYPTO_DETAIL_REQUIRE_THREADS("async_slow", "slow"); + return crypto::detail::run_heavy( + std::move(executor), [value]() noexcept { return slow(value); }, + std::forward(token)); +} + +/** Waits, at most 5 s, until `flag` is set; whether it was. */ +bool wait_for(std::atomic const& flag) noexcept { + auto const deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); + while (!flag.load() && std::chrono::steady_clock::now() < deadline) { + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + return flag.load(); +} + +void runs_elsewhere_and_completes_on_the_caller() { + boost::asio::io_context caller; + boost::asio::thread_pool pool(1); + auto const caller_thread = std::this_thread::get_id(); + std::atomic fired{false}; + boost::asio::steady_timer timer(caller, std::chrono::milliseconds(10)); + timer.async_wait([&fired](boost::system::error_code const& error) { + BOOST_TEST(!error); + fired.store(true); + }); + std::thread::id work_thread; + std::thread::id completion_thread; + bool timer_fired_meanwhile = false; + bool completed = false; + crypto::detail::run_heavy( + pool.get_executor(), + [&work_thread, &fired]() noexcept { + work_thread = std::this_thread::get_id(); + return wait_for(fired); + }, + boost::asio::bind_executor(caller.get_executor(), [&](bool timer_fired) { + completion_thread = std::this_thread::get_id(); + timer_fired_meanwhile = timer_fired; + completed = true; + })); + // The completion keeps the caller's io_context busy: run returns after it, not before. + caller.run(); + pool.join(); + BOOST_TEST(completed); + BOOST_TEST(timer_fired_meanwhile); + BOOST_TEST(work_thread != caller_thread); + BOOST_TEST(work_thread != std::thread::id{}); + BOOST_TEST(completion_thread == caller_thread); +} + +void move_only_result() { + boost::asio::io_context caller; + boost::asio::thread_pool pool(1); + std::unique_ptr received; + crypto::detail::run_heavy( + pool.get_executor(), []() noexcept { return std::make_unique(7); }, + boost::asio::bind_executor(caller.get_executor(), [&received](std::unique_ptr result) { + received = std::move(result); + })); + caller.run(); + pool.join(); + BOOST_TEST(received != nullptr); + if (received) { + BOOST_TEST_EQ(*received, 7); + } +} + +void heavy_operation_with_any_token() { + boost::asio::io_context caller; + boost::asio::thread_pool pool(1); + int received = 0; + auto operation = async_slow(pool.get_executor(), 41, boost::asio::deferred); + std::move(operation)(boost::asio::bind_executor( + caller.get_executor(), [&received](int result) { received = result; })); + caller.run(); + pool.join(); + BOOST_TEST_EQ(received, 42); +} + +} // namespace + +int main() { + runs_elsewhere_and_completes_on_the_caller(); + move_only_result(); + heavy_operation_with_any_token(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/messages/Jamfile b/test/messages/Jamfile index 1ae3ab7e..fb3b8912 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -28,3 +28,4 @@ build-project sodium_not_linked ; build-project ed25519_on_bearssl ; build-project ed25519ph_sha256 ; build-project ed25519_default_not_linked ; +build-project heavy_without_threads ; diff --git a/test/messages/heavy_without_threads/Jamfile b/test/messages/heavy_without_threads/Jamfile new file mode 100644 index 00000000..a7306ce7 --- /dev/null +++ b/test/messages/heavy_without_threads/Jamfile @@ -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) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; +import webcpp-target ; + +# Natively Boost.Config always sees threads, so the build without them defines +# WEBCPP_CRYPTO_NO_THREADS; WASI has none of its own. +rule without-threads ( properties * ) +{ + if [ webcpp-target.target-of $(properties) ] = native + { + return WEBCPP_CRYPTO_NO_THREADS ; + } +} + +webcpp.compile-diagnostic heavy_without_threads : heavy_without_threads.cpp + : @without-threads : native wasip2 wasip3 ; diff --git a/test/messages/heavy_without_threads/heavy_without_threads.cpp b/test/messages/heavy_without_threads/heavy_without_threads.cpp new file mode 100644 index 00000000..3e092768 --- /dev/null +++ b/test/messages/heavy_without_threads/heavy_without_threads.cpp @@ -0,0 +1,46 @@ +// 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 heavy operation's async_ variant called in a build without threads (natively with +// WEBCPP_CRYPTO_NO_THREADS; on WASI always) stops where it is called, with the synchronous +// operation to call instead (design D23). The operation is a test's own, declared as every heavy +// operation declares its variant. + +// clang-format off +// expected-error@*:* {{webcpp::crypto: async_slow runs on another thread and needs a build with threads (natively b2 threading=multi; on Emscripten -pthread). Without threads, call slow.}} +// clang-format on + +#include + +#include + +namespace { + +/** The test-only heavy operation, synchronous. */ +int slow(int value) noexcept { + return value + 1; +} + +/** Its async_ variant, as every heavy operation declares one. */ +template +auto async_slow(Executor executor, int value, CompletionToken&& token) { + WEBCPP_CRYPTO_DETAIL_REQUIRE_THREADS("async_slow", "slow"); + return webcpp::crypto::detail::run_heavy( + std::move(executor), [value]() noexcept { return slow(value); }, + std::forward(token)); +} + +/** An executor and a completion token, which a build without threads never uses. */ +struct executor {}; + +struct token {}; + +} // namespace + +int main() { + async_slow(executor{}, 41, token{}); + return slow(0) == 1 ? 0 : 1; +} diff --git a/test/msvc/Jamfile b/test/msvc/Jamfile index 3548f797..580685c4 100644 --- a/test/msvc/Jamfile +++ b/test/msvc/Jamfile @@ -47,3 +47,4 @@ build-project canary_sodium_other_commit ; build-project ed25519_on_bearssl ; build-project ed25519ph_sha256 ; build-project ed25519_default_not_linked ; +build-project heavy_without_threads ; diff --git a/test/msvc/heavy_without_threads/Jamfile b/test/msvc/heavy_without_threads/Jamfile new file mode 100644 index 00000000..14cb5414 --- /dev/null +++ b/test/msvc/heavy_without_threads/Jamfile @@ -0,0 +1,9 @@ +# 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 heavy_without_threads : app.cpp : /webcpp/crypto//crypto WEBCPP_CRYPTO_NO_THREADS : native ; diff --git a/test/msvc/heavy_without_threads/app.cpp b/test/msvc/heavy_without_threads/app.cpp new file mode 100644 index 00000000..9c2d89d6 --- /dev/null +++ b/test/msvc/heavy_without_threads/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 heavy operation's async_ variant called in a build without threads stops where it is called: +// on MSVC the compile fails. The text is checked on clang, in test/messages/heavy_without_threads. +#include + +#include + +namespace { + +int slow(int value) noexcept { + return value + 1; +} + +template +auto async_slow(Executor executor, int value, CompletionToken&& token) { + WEBCPP_CRYPTO_DETAIL_REQUIRE_THREADS("async_slow", "slow"); + return webcpp::crypto::detail::run_heavy( + std::move(executor), [value]() noexcept { return slow(value); }, + std::forward(token)); +} + +struct executor {}; + +struct token {}; + +} // namespace + +int main() { + async_slow(executor{}, 41, token{}); + return slow(0) == 1 ? 0 : 1; +} diff --git a/test/threads_config_test.cpp b/test/threads_config_test.cpp new file mode 100644 index 00000000..3aeb657f --- /dev/null +++ b/test/threads_config_test.cpp @@ -0,0 +1,48 @@ +// 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) + +// defines WEBCPP_CRYPTO_HAS_THREADS by design D23's rule: natively +// exactly when Boost.Config defines BOOST_HAS_THREADS, on Emscripten exactly with -pthread, never +// on wasip2 or wasip3, and never when the program defines WEBCPP_CRYPTO_NO_THREADS. test/Jamfile +// builds this file natively with b2's threading=single (WEBCPP_TEST_CRYPTO_THREADING_SINGLE), +// with threading=multi (WEBCPP_TEST_CRYPTO_THREADING_MULTI), and with threading=multi and +// WEBCPP_CRYPTO_NO_THREADS; and on wasip2, wasip3 and Emscripten without -pthread. The +// Emscripten build with -pthread is the fixture threads_on_emscripten of +// tools/test/crypto_jamfiles_test.py. +// +// threading=single does not take BOOST_HAS_THREADS away: Boost.Config (1.92) defines it on macOS +// (__APPLE__, boost/config/detail/suffix.hpp), on MSVC (_MT), with libstdc++ where it has gthreads +// (boost/config/stdlib/libstdcpp3.hpp) and with libc++ always (boost/config/stdlib/libcpp.hpp), so +// that a native build without WEBCPP_CRYPTO_NO_THREADS has threads; the single build checks the +// rule against Boost.Config's macro, whatever it says on the machine. + +#include + +#if defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) +#ifdef WEBCPP_CRYPTO_HAS_THREADS +#error "WEBCPP_CRYPTO_HAS_THREADS is defined on WASI" +#endif +#elif defined(WEBCPP_TARGET_EMSCRIPTEN) +#if defined(WEBCPP_CRYPTO_HAS_THREADS) != defined(__EMSCRIPTEN_PTHREADS__) +#error "WEBCPP_CRYPTO_HAS_THREADS is not defined exactly with -pthread on Emscripten" +#endif +#elif defined(WEBCPP_CRYPTO_NO_THREADS) +#ifdef WEBCPP_CRYPTO_HAS_THREADS +#error "WEBCPP_CRYPTO_HAS_THREADS is defined though the program defines WEBCPP_CRYPTO_NO_THREADS" +#endif +#elif defined(WEBCPP_TEST_CRYPTO_THREADING_MULTI) +#ifndef WEBCPP_CRYPTO_HAS_THREADS +#error "WEBCPP_CRYPTO_HAS_THREADS is not defined with threading=multi" +#endif +#elif defined(WEBCPP_TEST_CRYPTO_THREADING_SINGLE) +#if defined(WEBCPP_CRYPTO_HAS_THREADS) != defined(BOOST_HAS_THREADS) +#error "WEBCPP_CRYPTO_HAS_THREADS is not defined exactly when BOOST_HAS_THREADS is" +#endif +#else +#error "test/Jamfile builds this file natively with one of the threading cases" +#endif + +int main() {} From 47a040bdfefb5f2de252a05c045658fce0376757 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 16:00:29 -0300 Subject: [PATCH 021/110] crypto: Ed25519ph names webcpp::hash::sha2_512 from hash's header, Ed25519 joins the curves table, its results are nodiscard, its wipes are tested, and llms.txt reads ph's sign and verify in their class --- doc/curves.adoc | 4 +- doc/ed25519.adoc | 14 ++- doc/generated/namespace-curves.adoc | 14 ++- doc/llms.txt | 2 + doc/tables/crypto.json | 12 +- doc/tables/generate.py | 28 ++++- doc/tables/generate_test.py | 20 ++++ example/ed25519_sign.cpp | 8 +- include/webcpp/crypto/curves/ed25519.hpp | 24 ++-- test/Jamfile | 4 + test/capabilities_test.cpp | 2 +- test/ed25519_sodium_test.cpp | 13 ++- test/ed25519_wipe_sodium_test.cpp | 140 +++++++++++++++++++++++ test/ed25519ph_sodium_test.cpp | 8 +- 14 files changed, 252 insertions(+), 41 deletions(-) create mode 100644 test/ed25519_wipe_sodium_test.cpp diff --git a/doc/curves.adoc b/doc/curves.adoc index 9a1a73d7..c9c3bdc2 100644 --- a/doc/curves.adoc +++ b/doc/curves.adoc @@ -15,8 +15,8 @@ back from the point to the number is infeasible. On a curve a program can on a key*, so that two parties who only exchanged public keys share a secret (link:https://en.wikipedia.org/wiki/Elliptic-curve_Diffie%E2%80%93Hellman[Wikipedia]). -The namespace `webcpp::crypto::curves` holds three curves in this version. -The first is secp256k1 (link:https://www.secg.org/sec2-v2.pdf[SEC 2]; +The namespace `webcpp::crypto::curves` holds three curves in this version, the +three columns of the table below. The first is secp256k1 (link:https://www.secg.org/sec2-v2.pdf[SEC 2]; link:https://en.bitcoin.it/wiki/Secp256k1[Bitcoin Wiki]), the curve of Bitcoin, Ethereum and Nostr. This version covers Bitcoin's keys and signatures, Nostr's event signatures (NIP-01) and the verification of Ethereum's ECDSA diff --git a/doc/ed25519.adoc b/doc/ed25519.adoc index ca83135b..78ae7228 100644 --- a/doc/ed25519.adoc +++ b/doc/ed25519.adoc @@ -14,7 +14,13 @@ links it on every target), in the namespace `webcpp::crypto::curves::ed25519`. A signature is 64 bytes over a message of any length, made with a 32-byte secret key, the seed, and checked with a 32-byte public key. The signature is deterministic: the same key and message always give the same signature, so no -weak generator at signing time can leak the key. +weak generator at signing time can leak the key. Ed25519 is the signature of +SSH keys (link:https://www.rfc-editor.org/rfc/rfc8709[RFC 8709]), of Tor's +identity keys (link:https://spec.torproject.org/cert-spec.html[Tor's +specifications]) and of Solana's accounts +(link:https://solana.com/docs/core/accounts[Solana's documentation]); browsers' +WebCrypto has it too (link:https://www.w3.org/TR/WebCryptoAPI/[W3C]). Bitcoin, +Ethereum and Nostr sign on secp256k1 instead (<>). A `keypair` is made from a seed with `make(seed)`, or drawn from `random_device` with `generate()`; it gives its public key (`public_key`), @@ -26,9 +32,9 @@ alone. *Ed25519ph* signs the SHA-512 of a message instead of the message: a program that signs a large file reads it in pieces, gives each to `update`, and signs -once at the end. Its type names the hash, `ph` (the -same type as Boost.Hash2's `sha2_512`), since RFC 8032 fixes it; another hash -does not compile. An Ed25519ph signature is not an Ed25519 signature of the +once at the end. Its type names the hash, `ph`, which +the header brings with it, since RFC 8032 fixes it; another hash does not +compile. An Ed25519ph signature is not an Ed25519 signature of the same message, and neither verifies as the other: a protocol says which of the two it uses. diff --git a/doc/generated/namespace-curves.adoc b/doc/generated/namespace-curves.adoc index f051c0d4..784a915c 100644 --- a/doc/generated/namespace-curves.adoc +++ b/doc/generated/namespace-curves.adoc @@ -7,47 +7,57 @@ // 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",options="header"] +[cols="2h,5,5,5",options="header"] |=== -|Curve |`secp256k1` |`x25519` +|Curve |`secp256k1` |`ed25519` |`x25519` |What it does |BIP 340 Schnorr and ECDSA signatures, ECDH, the x-only tweak +|Ed25519 signatures, and Ed25519ph over SHA-512 for a message given in pieces; the X25519 secret key of a key pair |Key agreement (Diffie-Hellman on Curve25519): two parties who exchanged public keys share a 32-byte secret |Security level |about 128 bits (link:https://www.secg.org/sec2-v2.pdf[SEC 2, Recommended Elliptic Curve Domain Parameters]) +|about 128 bits (link:https://www.rfc-editor.org/rfc/rfc8032[RFC 8032, the Edwards-curve Digital Signature Algorithm (EdDSA)]) |about 128 bits (link:https://www.rfc-editor.org/rfc/rfc7748[RFC 7748, Elliptic Curves for Security (X25519 and X448)]) |Key sizes |secret 32 bytes; public 33 bytes compressed, 32 bytes x-only +|secret 32 bytes (the seed); public 32 bytes |secret 32 bytes; public 32 bytes |Signature sizes |64 bytes; ECDSA in DER up to 72 +|64 bytes |none: no signatures |Speed |not measured yet |not measured yet +|not measured yet |Constant time, measured |not measured yet |not measured yet +|not measured yet |Standards |link:https://www.secg.org/sec2-v2.pdf[SEC 2, Recommended Elliptic Curve Domain Parameters], link:https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki[BIP 340, Schnorr signatures for secp256k1], link:https://www.rfc-editor.org/rfc/rfc6979[RFC 6979, deterministic ECDSA nonces] +|link:https://www.rfc-editor.org/rfc/rfc8032[RFC 8032, the Edwards-curve Digital Signature Algorithm (EdDSA)], link:https://csrc.nist.gov/pubs/fips/186-5/final[FIPS 186-5, the Digital Signature Standard, which adds EdDSA] |link:https://www.rfc-editor.org/rfc/rfc7748[RFC 7748, Elliptic Curves for Security (X25519 and X448)] |Ecosystems that require it |Bitcoin (link:https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki[BIP 340, Schnorr signatures for secp256k1]), Ethereum (link:https://ethereum.github.io/yellowpaper/paper.pdf[The Ethereum yellow paper, appendix F: ECDSA on secp256k1]), Nostr (link:https://github.com/nostr-protocol/nips/blob/master/01.md[Nostr NIP-01, events signed with BIP 340 on secp256k1]) +|SSH keys (link:https://www.rfc-editor.org/rfc/rfc8709[RFC 8709, Ed25519 and Ed448 public keys for SSH]), Signal's signatures on its Curve25519 keys (link:https://signal.org/docs/specifications/xeddsa/[Signal, the XEdDSA and VXEdDSA signature schemes]), Tor's identity keys (link:https://spec.torproject.org/cert-spec.html[Tor's specifications, Ed25519 certificates]), Solana's accounts (link:https://solana.com/docs/core/accounts[Solana's documentation, accounts and their Ed25519 keys]) |TLS 1.3 (link:https://www.rfc-editor.org/rfc/rfc8446#section-4.2.7[RFC 8446, TLS 1.3, section 4.2.7 (supported groups)]), SSH (link:https://www.rfc-editor.org/rfc/rfc8731[RFC 8731, Secure Shell key exchange with Curve25519]), WireGuard (link:https://www.wireguard.com/protocol/[WireGuard's protocol, cryptography]), Signal (link:https://signal.org/docs/specifications/x3dh/[Signal, the X3DH key agreement protocol]) |Browsers' WebCrypto |no: WebCrypto offers P-256, P-384, P-521, Ed25519 and X25519, not secp256k1 (link:https://www.w3.org/TR/WebCryptoAPI/[W3C Web Cryptography API]) +|yes: Ed25519 (link:https://www.w3.org/TR/WebCryptoAPI/[W3C Web Cryptography API]) |yes: X25519 (link:https://www.w3.org/TR/WebCryptoAPI/[W3C Web Cryptography API]) |Choose it for compatibility with |Bitcoin's keys and signatures; Nostr's event signatures (link:https://github.com/nostr-protocol/nips/blob/master/01.md[Nostr NIP-01, events signed with BIP 340 on secp256k1]); Ethereum's ECDSA verification with a known key. Not in this version: Ethereum's recoverable signatures and its addresses from the uncompressed key; ECDH in the raw x-coordinate form of Nostr's encrypted messages (link:https://github.com/nostr-protocol/nips/blob/master/44.md[Nostr NIP-44, encrypted payloads]); BIP 32's derivation (link:https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki[BIP 32, hierarchical deterministic wallets]) +|SSH, Tor and Solana keys and signatures, and any protocol that names RFC 8032's Ed25519 or Ed25519ph; verification is strict (libsodium's rules), which some lenient verifiers are not. Not Bitcoin, Ethereum or Nostr, whose keys are secp256k1's |TLS 1.3's and SSH's key exchange, WireGuard, Signal; libsodium's `crypto_box` and `crypto_kx` keys. The Ed25519 public key of a peer converts with `curves::ed25519::to_x25519_public`. A shared secret goes through a KDF before it keys a cipher. Every case of Wycheproof's X25519 file is tested (link:https://github.com/C2SP/wycheproof[Project Wycheproof, test vectors for cryptographic libraries]) |=== diff --git a/doc/llms.txt b/doc/llms.txt index 4788a414..f25e980e 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -66,6 +66,8 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [curves::ed25519::ph](https://webcpporg.github.io/libs/crypto/#crypto-ed25519): Ed25519ph (RFC 8032): a message given in pieces, hashed with SHA-512, then signed with a key pair or verified with a public key. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. - begin: Begins a message. - update: Adds a piece of the message. + - ph::sign: Signs the message given, which it ends. + - ph::verify: Verifies a signature of the message given, which it ends, strictly (design D31). - [curves::ed25519::to_x25519_public](https://webcpporg.github.io/libs/crypto/#crypto-x25519): The X25519 public key of an Ed25519 public key (the birational map), refusing a key of small order or not canonical with `invalid_public_key`. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. - to_x25519_public: The X25519 public key of an Ed25519 public key (the birational map from edwards25519 to Curve25519), so that a peer known by its Ed25519 key can be agreed with by `curves::x25519::agree`; the key pair's own side is `basic_keypair::x25519_secret`. - [curves::x25519::public_key](https://webcpporg.github.io/libs/crypto/#crypto-x25519): The 32-byte X25519 public key of a 32-byte secret key (RFC 7748). Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index ccef1c45..98ba8138 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -70,7 +70,12 @@ "rfc8446-groups": ["RFC 8446, TLS 1.3, section 4.2.7 (supported groups)", "https://www.rfc-editor.org/rfc/rfc8446#section-4.2.7"], "rfc8731": ["RFC 8731, Secure Shell key exchange with Curve25519", "https://www.rfc-editor.org/rfc/rfc8731"], "wireguard": ["WireGuard's protocol, cryptography", "https://www.wireguard.com/protocol/"], - "x3dh": ["Signal, the X3DH key agreement protocol", "https://signal.org/docs/specifications/x3dh/"] + "x3dh": ["Signal, the X3DH key agreement protocol", "https://signal.org/docs/specifications/x3dh/"], + "fips186-5": ["FIPS 186-5, the Digital Signature Standard, which adds EdDSA", "https://csrc.nist.gov/pubs/fips/186-5/final"], + "rfc8709": ["RFC 8709, Ed25519 and Ed448 public keys for SSH", "https://www.rfc-editor.org/rfc/rfc8709"], + "signal-xeddsa": ["Signal, the XEdDSA and VXEdDSA signature schemes", "https://signal.org/docs/specifications/xeddsa/"], + "tor-cert-spec": ["Tor's specifications, Ed25519 certificates", "https://spec.torproject.org/cert-spec.html"], + "solana-accounts": ["Solana's documentation, accounts and their Ed25519 keys", "https://solana.com/docs/core/accounts"] }, "backends": { "bearssl": { @@ -307,7 +312,7 @@ { "id": "ed25519ph", "family": "ed25519", - "functions": ["begin", "update"], + "functions": ["begin", "update", "ph::sign", "ph::verify"], "namespace": "curves", "api": "curves::ed25519::ph", "header": "", @@ -419,7 +424,7 @@ "header": "", "names": [ {"name": "ed25519", "title": "Ed25519", "type": "curves::ed25519::basic_keypair<{backend}>"}, - {"name": "ed25519ph", "title": "Ed25519ph", "type": "curves::ed25519::ph"} + {"name": "ed25519ph", "title": "Ed25519ph", "type": "curves::ed25519::ph"} ], "default": [ {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": ["ed25519_sodium", "default_backend_none_linked"], "why": "the only backend in this version, on every target, and its verification is the policy `strict` ({libsodium-signatures}; {rfc8032})"} @@ -494,6 +499,7 @@ "columns": ["Curve", "What it does", "Security level", "Key sizes", "Signature sizes", "Speed", "Constant time, measured", "Standards", "Ecosystems that require it", "Browsers' WebCrypto", "Choose it for compatibility with"], "rows": [ ["`secp256k1`", "BIP 340 Schnorr and ECDSA signatures, ECDH, the x-only tweak", "about 128 bits ({sec2})", "secret 32 bytes; public 33 bytes compressed, 32 bytes x-only", "64 bytes; ECDSA in DER up to 72", "not measured yet", "not measured yet", "{sec2}, {bip340}, {rfc6979}", "Bitcoin ({bip340}), Ethereum ({ethereum}), Nostr ({nip01})", "no: WebCrypto offers P-256, P-384, P-521, Ed25519 and X25519, not secp256k1 ({webcrypto})", "Bitcoin's keys and signatures; Nostr's event signatures ({nip01}); Ethereum's ECDSA verification with a known key. Not in this version: Ethereum's recoverable signatures and its addresses from the uncompressed key; ECDH in the raw x-coordinate form of Nostr's encrypted messages ({nip44}); BIP 32's derivation ({bip32})"], + ["`ed25519`", "Ed25519 signatures, and Ed25519ph over SHA-512 for a message given in pieces; the X25519 secret key of a key pair", "about 128 bits ({rfc8032})", "secret 32 bytes (the seed); public 32 bytes", "64 bytes", "not measured yet", "not measured yet", "{rfc8032}, {fips186-5}", "SSH keys ({rfc8709}), Signal's signatures on its Curve25519 keys ({signal-xeddsa}), Tor's identity keys ({tor-cert-spec}), Solana's accounts ({solana-accounts})", "yes: Ed25519 ({webcrypto})", "SSH, Tor and Solana keys and signatures, and any protocol that names RFC 8032's Ed25519 or Ed25519ph; verification is strict (libsodium's rules), which some lenient verifiers are not. Not Bitcoin, Ethereum or Nostr, whose keys are secp256k1's"], ["`x25519`", "Key agreement (Diffie-Hellman on Curve25519): two parties who exchanged public keys share a 32-byte secret", "about 128 bits ({rfc7748})", "secret 32 bytes; public 32 bytes", "none: no signatures", "not measured yet", "not measured yet", "{rfc7748}", "TLS 1.3 ({rfc8446-groups}), SSH ({rfc8731}), WireGuard ({wireguard}), Signal ({x3dh})", "yes: X25519 ({webcrypto})", "TLS 1.3's and SSH's key exchange, WireGuard, Signal; libsodium's `crypto_box` and `crypto_kx` keys. The Ed25519 public key of a peer converts with `curves::ed25519::to_x25519_public`. A shared secret goes through a KDF before it keys a cipher. Every case of Wycheproof's X25519 file is tested ({wycheproof})"] ] } diff --git a/doc/tables/generate.py b/doc/tables/generate.py index eddb252d..eab66073 100644 --- a/doc/tables/generate.py +++ b/doc/tables/generate.py @@ -1183,23 +1183,41 @@ def use_cases_page(data: Data, library: Path) -> str: DOC_COMMENT = re.compile(r'/\*\*(.*?)\*/', re.S) +def class_body(text: str, name: str) -> str: + """The body of the class or struct name that text defines, between its braces, or nothing + when text defines none of that name.""" + found = re.search(rf'\b(?:class|struct)\s+{re.escape(name)}\b[^;{{]*\{{', text) + if not found: + return '' + depth = 0 + for index in range(found.end() - 1, len(text)): + depth += {'{': 1, '}': -1}.get(text[index], 0) + if depth == 0: + return text[found.end():index] + return text[found.end():] + + def declared_brief(library: Path, operation: Data, function: str) -> str: """The first sentence of the Doc Comment of a function an operation names, read from the - operation's headers: the description llms.txt gives it. A function no header declares is a - fault.""" - if function == 'operator()': + operation's headers: the description llms.txt gives it. A function written `class::name` is + read in that class's body alone, for a name that another class of the header declares first. + A function no header declares is a fault.""" + scope, _, name = function.rpartition('::') + if name == 'operator()': pattern = re.compile(r'\boperator\(\)\(') else: - pattern = re.compile(rf'(?:\b{re.escape(function)}|\({re.escape(function)}\))\s*\(') + pattern = re.compile(rf'(?:\b{re.escape(name)}|\({re.escape(name)}\))\s*\(') for header in HEADER.findall(operation['header']): text = (library / 'include' / header).read_text(encoding='utf-8') + if scope: + text = class_body(text, scope) for comment in DOC_COMMENT.finditer(text): rest = text[comment.end():] declaration = rest[:rest.find('{') if '{' in rest else len(rest)] declaration = declaration.split(';', 1)[0] declaration = '\n'.join(line.split('//', 1)[0] for line in declaration.splitlines()) free = not declaration.lstrip('\n').startswith(' ') - if operation.get('free') and not free: + if operation.get('free') and not free and not scope: continue found = pattern.search(declaration) # The declared name: the first parenthesis of the declaration is its own. diff --git a/doc/tables/generate_test.py b/doc/tables/generate_test.py index 6e308396..e1d9cb99 100644 --- a/doc/tables/generate_test.py +++ b/doc/tables/generate_test.py @@ -154,6 +154,25 @@ def test_a_brief_leaves_out_a_line_reference(scratch: Path) -> None: raise AssertionError('a function no header declares was given a brief') +def test_a_qualified_function_is_read_in_its_class(scratch: Path) -> None: + written(scratch, 'include/webcpp/crypto/two.hpp', ( + 'namespace webcpp::crypto {\n' + 'class key {\npublic:\n /** Signs a message. */\n int sign(int message);\n};\n' + 'class signer {\n struct inner {\n /** Not this one. */\n' + ' int other(int x);\n };\n\npublic:\n' + ' /** Signs the message given in pieces. */\n int sign(int key);\n};\n}\n')) + operation = {'id': 'two', 'header': ''} + assert generate.declared_brief(scratch, operation, 'sign') == 'Signs a message.' + brief = generate.declared_brief(scratch, operation, 'signer::sign') + assert brief == 'Signs the message given in pieces.', brief + try: + generate.declared_brief(scratch, operation, 'nothing::sign') + except generate.Fault: + pass + else: + raise AssertionError('a function of a class no header defines was given a brief') + + def test_code_that_holds_a_plus_is_one_span(_: Path) -> None: # `+em++: error:+` would be read as `+em+` and a stray rest: the text is a passthrough. assert generate.code('em++: error:') == '`pass:[em++: error:]`', generate.code('em++') @@ -629,6 +648,7 @@ def test_the_check_names_a_file_that_differs(scratch: Path) -> None: test_a_reason_elsewhere_is_openssl_s_alone, test_an_outcome_reads_each_directive, test_a_brief_leaves_out_a_line_reference, + test_a_qualified_function_is_read_in_its_class, test_code_that_holds_a_plus_is_one_span, test_a_failing_fixture_lists_its_texts_per_target, test_a_fixture_that_builds_and_runs_nothing_is_a_record, diff --git a/example/ed25519_sign.cpp b/example/ed25519_sign.cpp index 2bae6c5a..0ec040fb 100644 --- a/example/ed25519_sign.cpp +++ b/example/ed25519_sign.cpp @@ -11,7 +11,7 @@ // tag::program[] #include -#include +#include #include #include @@ -61,8 +61,8 @@ bool sign_whole() { return ed25519::verify(*public_key, message, *signature).has_value(); } -// Ed25519ph: the message given in pieces, as a large file is read, signed once at the end. -// webcpp::hash::sha2_512 names Boost.Hash2's sha2_512, the hash RFC 8032 fixes. +// Ed25519ph: the message given in pieces, as a large file is read, signed once at the end, +// over SHA-512, the hash RFC 8032 fixes. bool sign_in_pieces() { std::array const seed{ 0x83, 0x3f, 0xe6, 0x24, 0x09, 0x23, 0x7b, 0x9d, 0x62, 0xec, 0x77, @@ -71,7 +71,7 @@ bool sign_in_pieces() { }; std::array const first{'a'}; std::array const second{'b', 'c'}; - using signer = ed25519::ph; + using signer = ed25519::ph; auto const key = ed25519::keypair::make(seed); auto signing = signer::begin(); if (!key || !signing || !signing->update(first) || !signing->update(second)) { diff --git a/include/webcpp/crypto/curves/ed25519.hpp b/include/webcpp/crypto/curves/ed25519.hpp index 22674c7d..0a756da0 100644 --- a/include/webcpp/crypto/curves/ed25519.hpp +++ b/include/webcpp/crypto/curves/ed25519.hpp @@ -26,10 +26,8 @@ #include #include // lint-world: random_device draws generate()'s seed #include +#include // webcpp::hash::sha2_512, Ed25519ph's hash (design D1) -// webcpp::hash::sha2_512, Ed25519ph's hash, is this type (webcpp/hash/algorithms.hpp); its header -// is not included, so that crypto's headers declare nothing of hash's beside crypto's own. -#include #include #include @@ -101,7 +99,8 @@ class basic_keypair { * @param seed 32 bytes. * @return The key pair; `invalid_key_size`; `backend_failure`. */ - static boost::system::result make(std::span seed) noexcept { + [[nodiscard]] static boost::system::result make( + std::span seed) noexcept { if (seed.size() != seed_size) { return error::invalid_key_size; } @@ -120,7 +119,7 @@ class basic_keypair { * @return The key pair; `entropy_unavailable` when the system's generator fails or there is * none; `backend_failure`. */ - static boost::system::result generate() noexcept { + [[nodiscard]] static boost::system::result generate() noexcept { secret seed; auto const drawn = random_device().fill(seed.writable()); // lint-world: the seed if (!drawn) { @@ -243,9 +242,9 @@ struct strict {}; * @return Nothing; `invalid_public_key` for a key of another size; `invalid_signature`. */ template > -boost::system::result verify(std::span public_key, - std::span message, - std::span signature) noexcept { +[[nodiscard]] boost::system::result verify(std::span public_key, + std::span message, + std::span signature) noexcept { static_assert(std::is_same_v, "webcpp::crypto: Ed25519's only verification policy is curves::ed25519::strict."); if (public_key.size() != 32) { @@ -294,14 +293,13 @@ template > * Its signature is not Ed25519's of the same message: a verifier is told which of the two a * protocol uses. * - * @tparam Hash `webcpp::hash::sha2_512`, which RFC 8032 fixes (Boost.Hash2's `sha2_512`, the - * same type); any other is refused. + * @tparam Hash `webcpp::hash::sha2_512`, which RFC 8032 fixes; any other is refused. * @tparam Backend The backend; by default the family's (`default_backend_t`). */ template > class ph { // clang-format off - static_assert(std::is_same_v, "webcpp::crypto: Ed25519ph is defined over SHA-512 (RFC 8032 section 5.1); name curves::ed25519::ph."); + static_assert(std::is_same_v, "webcpp::crypto: Ed25519ph is defined over SHA-512 (RFC 8032 section 5.1); name curves::ed25519::ph."); // clang-format on using state_type = detail::ed25519ph_state; @@ -324,7 +322,7 @@ class ph { * * @return The signer, ready for the message's pieces; `backend_failure`. */ - static boost::system::result begin() noexcept { + [[nodiscard]] static boost::system::result begin() noexcept { ph begun; auto const started = engine::begin(begun.state_); if (!started) { @@ -374,7 +372,7 @@ class ph { * @param piece Any bytes, empty included. * @return Nothing; `invalid_state` once the message is signed or verified, or moved from. */ - boost::system::result update(std::span piece) noexcept { + [[nodiscard]] boost::system::result update(std::span piece) noexcept { if (!begun_) { return error::invalid_state; } diff --git a/test/Jamfile b/test/Jamfile index dea7e9d3..edf938fd 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -285,6 +285,10 @@ crypto-run ed25519_wycheproof_sodium : ed25519_wycheproof_sodium_test.cpp : /third_party//sodium /third_party//wycheproof /webcpp//boost_json ; crypto-run ed25519ph_sodium : ed25519ph_sodium_test.cpp : /third_party//sodium ; +# The key pair's secret key and the signer's state are zero once moved from, +# moved over, ended and destroyed: optimised, every call inlined, as secret's. +crypto-run ed25519_wipe_sodium : ed25519_wipe_sodium_test.cpp + : /third_party//sodium $(OPTIMISED) full ; # X25519 on libsodium: RFC 7748's scalar multiplications and Alice and Bob, a # peer of order 8 refused as weak, the guards and the conversion from Ed25519; diff --git a/test/capabilities_test.cpp b/test/capabilities_test.cpp index 3889d595..23576ba8 100644 --- a/test/capabilities_test.cpp +++ b/test/capabilities_test.cpp @@ -276,7 +276,7 @@ int main() { BOOST_TEST((webcpp::test::made, families::ed25519, families::ed25519, backends::sodium>())); #endif #if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN)) && defined(WEBCPP_CRYPTO_HAS_SODIUM) - BOOST_TEST((webcpp::test::made, families::ed25519, tags::ed25519ph, backends::sodium>())); + BOOST_TEST((webcpp::test::made, families::ed25519, tags::ed25519ph, backends::sodium>())); #endif #if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN)) && defined(WEBCPP_CRYPTO_HAS_SODIUM) BOOST_TEST((webcpp::test::made, families::x25519, families::x25519, backends::sodium>())); diff --git a/test/ed25519_sodium_test.cpp b/test/ed25519_sodium_test.cpp index 03bf0183..31dd31b0 100644 --- a/test/ed25519_sodium_test.cpp +++ b/test/ed25519_sodium_test.cpp @@ -42,13 +42,15 @@ namespace { // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the planted source's script bool entropy_fails = false; +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the planted source's script +int entropy_errno = EIO; } // namespace -// The planted source: 0x42 in every byte, or -1 with EIO, as getentropy fails. +// The planted source: 0x42 in every byte, or -1 with errno set, as getentropy fails. extern "C" int webcpp_test_entropy(void* output_bytes, std::size_t byte_count) { if (entropy_fails) { - errno = EIO; + errno = entropy_errno; return -1; } std::memset(output_bytes, 0x42, byte_count); @@ -199,6 +201,13 @@ void generated() { entropy_fails = true; auto const refused = ed25519::keypair::generate(); BOOST_TEST(refused.has_error() && refused.error() == crypto::error::entropy_unavailable); + // No generator at all (ENOTSUP, an Emscripten audio worklet, which random_device reports as + // not_supported) is the same failure for a key pair. + entropy_errno = ENOTSUP; + auto const unsupported = ed25519::keypair::generate(); + BOOST_TEST(unsupported.has_error() && + unsupported.error() == crypto::error::entropy_unavailable); + entropy_errno = EIO; // The source answers: the key pair of the seed it gave, 32 bytes of 0x42. entropy_fails = false; diff --git a/test/ed25519_wipe_sodium_test.cpp b/test/ed25519_wipe_sodium_test.cpp new file mode 100644 index 00000000..54b16fb4 --- /dev/null +++ b/test/ed25519_wipe_sodium_test.cpp @@ -0,0 +1,140 @@ +// 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) + +// An Ed25519 key pair's secret key and an Ed25519ph signer's SHA-512 state are zero in their +// storage once moved from, once moved over, once the message is ended (the signer) and once +// destroyed, read at -O2 with every call inlined (the Jamfile's requirements), where a wipe the +// optimiser may drop as a dead store would be dropped. Each object's state is its first member, +// at the start of its storage: the classes are standard-layout, which the test asserts. + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace crypto = webcpp::crypto; +namespace ed25519 = webcpp::crypto::curves::ed25519; + +using ed25519::keypair; +using signer = ed25519::ph; +constexpr std::size_t keypair_state = + sizeof(crypto::detail::ed25519_state); +constexpr std::size_t signer_state = + sizeof(crypto::detail::ed25519ph_state); + +static_assert(std::is_standard_layout_v && std::is_standard_layout_v); +static_assert(keypair_state == 64 && signer_state <= sizeof(signer)); + +// A function the optimiser cannot see into, so that what it is handed is read from memory. +#if defined(_MSC_VER) && !defined(__clang__) +#define WEBCPP_TEST_NOINLINE __declspec(noinline) +#else +#define WEBCPP_TEST_NOINLINE __attribute__((noinline)) +#endif + +// Whether every byte at `where` is zero, read through a volatile pointer in a function that is +// never inlined. It may be handed the storage of an object that is gone (the destructor's +// check), so it is exempt from the sanitizers that would stop that read. +#if defined(__clang__) || defined(__GNUC__) +__attribute__((no_sanitize("address"))) +#endif +WEBCPP_TEST_NOINLINE bool memory_is_zero(void const* where, std::size_t count) { + auto const volatile* const bytes = static_cast(where); + for (std::size_t i = 0; i < count; ++i) { + if (bytes[i] != 0) { + return false; + } + } + return true; +} + +// RFC 8032 section 7.3's seed, and its message "abc". +constexpr std::array seed{ + 0x83, 0x3f, 0xe6, 0x24, 0x09, 0x23, 0x7b, 0x9d, 0x62, 0xec, 0x77, 0x58, 0x75, 0x20, 0x91, 0x1e, + 0x9a, 0x75, 0x9c, 0xec, 0x1d, 0x19, 0x75, 0x5b, 0x7d, 0xa9, 0x01, 0xb9, 0x6d, 0xca, 0x3d, 0x42, +}; +constexpr std::array abc{0x61, 0x62, 0x63}; + +void key_pairs() { + auto made = keypair::make(seed); + BOOST_TEST(made.has_value()); + if (!made) { + return; + } + // Alive, the state holds the secret key: the checks below can fail. + BOOST_TEST(!memory_is_zero(&*made, keypair_state)); + + keypair taken = std::move(*made); + BOOST_TEST(memory_is_zero(&*made, keypair_state)); + + auto other = keypair::make(seed); + BOOST_TEST(other.has_value()); + if (other) { + taken = std::move(*other); + BOOST_TEST(memory_is_zero(&*other, keypair_state)); + } + + // Destroyed in storage this frame owns: its bytes are read after the destructor. + alignas(keypair) std::array storage{}; + keypair* const placed = + std::construct_at(reinterpret_cast(storage.data()), std::move(taken)); + BOOST_TEST(!memory_is_zero(placed, keypair_state)); + std::destroy_at(placed); + BOOST_TEST(memory_is_zero(storage.data(), keypair_state)); +} + +void signers() { + auto const key = keypair::make(seed); + auto begun = signer::begin(); + BOOST_TEST(key.has_value() && begun.has_value()); + if (!key || !begun) { + return; + } + BOOST_TEST(begun->update(abc).has_value()); + BOOST_TEST(!memory_is_zero(&*begun, signer_state)); + + signer moved = std::move(*begun); + BOOST_TEST(memory_is_zero(&*begun, signer_state)); + + // Signed, the message is ended and its state wiped. + BOOST_TEST(moved.sign(*key).has_value()); + BOOST_TEST(memory_is_zero(&moved, signer_state)); + + auto other = signer::begin(); + BOOST_TEST(other.has_value()); + if (!other) { + return; + } + BOOST_TEST(other->update(abc).has_value()); + moved = std::move(*other); + BOOST_TEST(memory_is_zero(&*other, signer_state)); + + alignas(signer) std::array storage{}; + signer* const placed = + std::construct_at(reinterpret_cast(storage.data()), std::move(moved)); + BOOST_TEST(!memory_is_zero(placed, signer_state)); + std::destroy_at(placed); + BOOST_TEST(memory_is_zero(storage.data(), signer_state)); +} + +} // namespace + +int main() { + key_pairs(); + signers(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/ed25519ph_sodium_test.cpp b/test/ed25519ph_sodium_test.cpp index 2c718b06..850e95e8 100644 --- a/test/ed25519ph_sodium_test.cpp +++ b/test/ed25519ph_sodium_test.cpp @@ -11,12 +11,12 @@ #include #include +#include #include #include "support/hex.hpp" #include -#include #include #include @@ -32,9 +32,7 @@ namespace test = webcpp::test; namespace { -// webcpp::hash::sha2_512, which a program names, is Boost.Hash2's sha2_512 -// (webcpp/hash/algorithms.hpp); hash's header is left out of crypto's tests. -using signer = ed25519::ph; +using signer = ed25519::ph; // RFC 8032 section 7.3, TEST abc. constexpr char const* secret_key = @@ -139,7 +137,7 @@ void spent_and_moved() { int main() { static_assert( - std::is_same_v>); + std::is_same_v>); static_assert(std::is_same_v); static_assert(std::is_same_v); static_assert(!std::is_copy_constructible_v && !std::is_copy_assignable_v); From 965cefccb78aa830a1954be67c938824e721d5cb Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 18:49:09 -0300 Subject: [PATCH 022/110] crypto: llms.txt names a class's functions bare, as every other entry, Ed25519ph's sign and verify included --- doc/llms.txt | 4 ++-- doc/tables/generate.py | 12 +++++++++--- doc/tables/generate_test.py | 15 +++++++++++++++ 3 files changed, 26 insertions(+), 5 deletions(-) diff --git a/doc/llms.txt b/doc/llms.txt index f25e980e..1357bef5 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -66,8 +66,8 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [curves::ed25519::ph](https://webcpporg.github.io/libs/crypto/#crypto-ed25519): Ed25519ph (RFC 8032): a message given in pieces, hashed with SHA-512, then signed with a key pair or verified with a public key. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. - begin: Begins a message. - update: Adds a piece of the message. - - ph::sign: Signs the message given, which it ends. - - ph::verify: Verifies a signature of the message given, which it ends, strictly (design D31). + - sign: Signs the message given, which it ends. + - verify: Verifies a signature of the message given, which it ends, strictly (design D31). - [curves::ed25519::to_x25519_public](https://webcpporg.github.io/libs/crypto/#crypto-x25519): The X25519 public key of an Ed25519 public key (the birational map), refusing a key of small order or not canonical with `invalid_public_key`. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. - to_x25519_public: The X25519 public key of an Ed25519 public key (the birational map from edwards25519 to Curve25519), so that a peer known by its Ed25519 key can be agreed with by `curves::x25519::agree`; the key pair's own side is `basic_keypair::x25519_secret`. - [curves::x25519::public_key](https://webcpporg.github.io/libs/crypto/#crypto-x25519): The 32-byte X25519 public key of a 32-byte secret key (RFC 7748). Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. diff --git a/doc/tables/generate.py b/doc/tables/generate.py index eab66073..07a45fa4 100644 --- a/doc/tables/generate.py +++ b/doc/tables/generate.py @@ -1230,6 +1230,13 @@ def declared_brief(library: Path, operation: Data, function: str) -> str: f'{operation["header"]} declares') +def llms_entry(library: Path, operation: Data, function: str) -> str: + """The line of llms.txt that lists a function of an operation, under the operation's entry: + its bare name, a function written `class::name` included, and its brief.""" + name = function.rpartition('::')[2] + return f' - {name}: {declared_brief(library, operation, function)}' + + def first_comment(source: Path) -> str: """The comment that opens an example after its licence: what the program does.""" lines = source.read_text(encoding='utf-8').splitlines()[6:] @@ -1266,9 +1273,8 @@ def llms(data: Data, matrix: Matrix, library: Path) -> str: if (operation['id'], backend) in matrix.supported) out.append(f'- [{operation["api"]}]({page}#{operation["section"]}): ' f'{operation["what"]} Header {operation["header"]}. Backends: {backends}.') - for function in operation['functions']: - out.append(f' - {function}: ' - f'{declared_brief(library, operation, function)}') + out += [llms_entry(library, operation, function) + for function in operation['functions']] out.append('') out += ['## Default backend per family', ''] for family in data['families']: diff --git a/doc/tables/generate_test.py b/doc/tables/generate_test.py index e1d9cb99..3a1c08c2 100644 --- a/doc/tables/generate_test.py +++ b/doc/tables/generate_test.py @@ -173,6 +173,20 @@ def test_a_qualified_function_is_read_in_its_class(scratch: Path) -> None: raise AssertionError('a function of a class no header defines was given a brief') +def test_an_index_entry_names_a_qualified_function_bare(scratch: Path) -> None: + # llms.txt lists a class's functions under the class: `signer::sign` is read in its class + # and written `sign`, as every other entry is. + written(scratch, 'include/webcpp/crypto/two.hpp', ( + 'namespace webcpp::crypto {\n' + 'class key {\npublic:\n /** Signs a message. */\n int sign(int message);\n};\n' + 'class signer {\npublic:\n' + ' /** Signs the message given in pieces. */\n int sign(int key);\n};\n}\n')) + operation = {'id': 'two', 'header': ''} + entry = generate.llms_entry(scratch, operation, 'signer::sign') + assert entry == ' - sign: Signs the message given in pieces.', entry + entry = generate.llms_entry(scratch, operation, 'sign') + assert entry == ' - sign: Signs a message.', entry + def test_code_that_holds_a_plus_is_one_span(_: Path) -> None: # `+em++: error:+` would be read as `+em+` and a stray rest: the text is a passthrough. assert generate.code('em++: error:') == '`pass:[em++: error:]`', generate.code('em++') @@ -649,6 +663,7 @@ def test_the_check_names_a_file_that_differs(scratch: Path) -> None: test_an_outcome_reads_each_directive, test_a_brief_leaves_out_a_line_reference, test_a_qualified_function_is_read_in_its_class, + test_an_index_entry_names_a_qualified_function_bare, test_code_that_holds_a_plus_is_one_span, test_a_failing_fixture_lists_its_texts_per_target, test_a_fixture_that_builds_and_runs_nothing_is_a_record, From bda4735006a5e9cc5d791ba33efa4a34ca1e5e19 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 18:57:41 -0300 Subject: [PATCH 023/110] crypto: Ed25519's strict policy, and the twelve edge cases per backend --- doc/changelog.adoc | 2 +- doc/ed25519.adoc | 28 ++- doc/generated/backends-ed25519_verify.adoc | 2 +- doc/generated/ed25519-cases.adoc | 85 ++++++++ doc/generated/matrix.adoc | 2 +- doc/tables/crypto.json | 2 +- doc/tables/generate.py | 55 ++++- doc/tables/generate_test.py | 28 ++- meta/ed25519_cases.json | 16 ++ test/Jamfile | 15 ++ test/ed25519_speccheck_test.cpp | 234 +++++++++++++++++++++ 11 files changed, 451 insertions(+), 18 deletions(-) create mode 100644 doc/generated/ed25519-cases.adoc create mode 100644 meta/ed25519_cases.json create mode 100644 test/ed25519_speccheck_test.cpp diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 23ea1ee1..59256d65 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -21,7 +21,7 @@ of every version are on webcpp's index page. * Added default_backend_t and /webcpp/crypto//-default, one default backend per family and target whatever is linked, ciphers::aes128_gcm and aes256_gcm, and refusals naming the Jamfile line and another backend's type. * Added backends::bearssl (AES-GCM allocating nothing, no block cipher), backends::openssl through /webcpp/crypto//openssl on native and WASI (allocating at make only), and backends::ctaes (block cipher alone). * Added WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE: OpenSSL's allocations in the program's resource, refused on WebAssembly (WASI included) and without OpenSSL: openssl_memory_resource, install_memory_functions, memory_functions_refused, memory_functions_not_installed. -* Added curves::secp256k1: key pairs, BIP340 and ECDSA signatures, ECDH, strict DER, low-S and the x-only tweak; curves::ed25519 on libsodium: key pairs, signatures verified strictly, the X25519 secret key and public key, and Ed25519ph over webcpp::hash's sha2_512, which /webcpp/crypto//crypto now brings; and curves::x25519 on libsodium, whose agree refuses an all-zero secret. +* Added curves::secp256k1: key pairs, BIP340 and ECDSA signatures, ECDH, strict DER, low-S and the x-only tweak; curves::ed25519 on libsodium: key pairs, signatures verified strictly (each backend's verdicts on the twelve edge cases of "Taming the many EdDSAs" tested and tabled), the X25519 secret key and public key, and Ed25519ph over webcpp::hash's sha2_512, which /webcpp/crypto//crypto now brings; and curves::x25519 on libsodium, whose agree refuses an all-zero secret. * Added backends::sodium on /third_party//sodium, shared with webcpp::hash and initialised before every engine, and every backend's link-time canary and C suite. * Added the page: a chapter per namespace and use case, the memory option's guide and example, tables generated from the tests, every Jamfile and message, and llms.txt. * Added supports_v, the capability table on the target being compiled, and the tags of its families and algorithms, which ciphers::gcm, the AES block cipher and secp256k1's key pair name. diff --git a/doc/ed25519.adoc b/doc/ed25519.adoc index 78ae7228..d06e0fa7 100644 --- a/doc/ed25519.adoc +++ b/doc/ed25519.adoc @@ -64,9 +64,31 @@ takes a verification policy, `strict` by default and the only one in this version: libsodium's rules, which refuse all three (link:https://doc.libsodium.org/public-key_cryptography/public-key_signatures[libsodium's documentation]). Every valid signature of Wycheproof's EdDSA file is accepted and every invalid -one refused (`ed25519_wycheproof_sodium`). Honest signatures verify everywhere; -a network that mixes verifiers must still agree on one rule for the others, -since a more lenient verifier accepts signatures that `strict` refuses. +one refused (`ed25519_wycheproof_sodium`). + +*The twelve edge cases.* Chalkias, Garillot and Nikolaenko, "Taming the many +EdDSAs" (link:https://eprint.iacr.org/2020/1244[IACR ePrint 2020/1244]), give +twelve signatures on which implementations disagree, in their suite +(link:https://github.com/novifinancial/ed25519-speccheck[novifinancial/ed25519-speccheck]). +They run against every Ed25519 backend: its own verdict (raw), and its verdict +under `strict`, which is libsodium's on every backend. The test +`ed25519_speccheck` asserts the table below, so that a new version of a backend +that changes a verdict fails until the table is regenerated; WebCrypto in node +is an outside view, recorded and never held to `strict`. + +include::generated/ed25519-cases.adoc[] + +Honest signatures verify everywhere: the cases differ only on signatures no +honest signer makes, and a network that mixes verifiers must agree on one rule +for them. Rust peers that use ed25519-dalek's default `verify` accept cases 0 +to 2 and 11, which `strict` refuses +(link:https://github.com/novifinancial/ed25519-speccheck#results[the suite's +results]). ZIP-215 verifiers (link:https://zips.z.cash/zip-0215[ZIP 215]), the +rule of Zcash, accept every case but 6 to 8 by design: they verify with the +cofactor and accept non-canonical encodings of `A` and `R`, so that every +ZIP-215 verifier agrees on every signature. `strict` refuses the cases they +accept beyond it; `zip215` is not a policy of this version, and waits for a +mature C or {cpp} implementation of ZIP-215. *Pitfalls.* diff --git a/doc/generated/backends-ed25519_verify.adoc b/doc/generated/backends-ed25519_verify.adoc index d51157b0..c80815b4 100644 --- a/doc/generated/backends-ed25519_verify.adoc +++ b/doc/generated/backends-ed25519_verify.adoc @@ -16,5 +16,5 @@ The backends of `+curves::ed25519::verify+`, from the test programs that run it: |libsodium |`+/third_party//sodium+` |`++` -|native, wasip2, wasip3, emscripten (tested by `+ed25519_sodium+`, `+ed25519_wycheproof_sodium+`) +|native, wasip2, wasip3, emscripten (tested by `+ed25519_sodium+`, `+ed25519_wycheproof_sodium+`, `+ed25519_speccheck+`) |=== diff --git a/doc/generated/ed25519-cases.adoc b/doc/generated/ed25519-cases.adoc new file mode 100644 index 00000000..b0c547c0 --- /dev/null +++ b/doc/generated/ed25519-cases.adoc @@ -0,0 +1,85 @@ +// 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 meta/ed25519_cases.json, which +// test/ed25519_speccheck_test.cpp asserts: run it again, never edit this file. + +[cols="1,5,2,2,2",options="header"] +|=== +|Case |What it tests |libsodium, raw |libsodium, strict |WebCrypto in node, outside view + +|0 +|`+S+` = 0, `+A+` and `+R+` of small order +|reject +|reject +|reject + +|1 +|`+A+` of small order +|reject +|reject +|reject + +|2 +|`+R+` of small order +|reject +|reject +|reject + +|3 +|`+A+` and `+R+` of mixed order, valid with or without the cofactor +|accept +|accept +|accept + +|4 +|`+A+` and `+R+` of mixed order, valid with the cofactor alone +|reject +|reject +|reject + +|5 +|`+R+` of full order, valid with the cofactor unless `+8h+` is reduced first +|reject +|reject +|reject + +|6 +|`+S+` above the group order `+L+` +|reject +|reject +|reject + +|7 +|`+S+` far above `+L+`, its top bit set +|reject +|reject +|reject + +|8 +|`+R+` non-canonical, reduced before hashing +|reject +|reject +|reject + +|9 +|`+R+` non-canonical, hashed as given +|reject +|reject +|reject + +|10 +|`+A+` non-canonical, reduced before hashing +|reject +|reject +|reject + +|11 +|`+A+` non-canonical, hashed as given +|reject +|reject +|reject +|=== diff --git a/doc/generated/matrix.adoc b/doc/generated/matrix.adoc index 60511771..6e13f2db 100644 --- a/doc/generated/matrix.adoc +++ b/doc/generated/matrix.adoc @@ -94,7 +94,7 @@ |`+curves::ed25519::verify+` |libsodium |native, wasip2, wasip3, emscripten -|`+ed25519_sodium+`, `+ed25519_wycheproof_sodium+` +|`+ed25519_sodium+`, `+ed25519_wycheproof_sodium+`, `+ed25519_speccheck+` |`+curves::ed25519::ph+` |libsodium diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 98ba8138..21019af2 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -307,7 +307,7 @@ "header": "", "what": "Verifies an Ed25519 signature with a public key alone, under the policy `strict`: libsodium's rules, which refuse non-canonical encodings and keys of small order.", "section": "crypto-ed25519", - "backends": {"sodium": {"tests": ["ed25519_sodium", "ed25519_wycheproof_sodium"]}} + "backends": {"sodium": {"tests": ["ed25519_sodium", "ed25519_wycheproof_sodium", "ed25519_speccheck"]}} }, { "id": "ed25519ph", diff --git a/doc/tables/generate.py b/doc/tables/generate.py index 07a45fa4..d36847ab 100644 --- a/doc/tables/generate.py +++ b/doc/tables/generate.py @@ -16,8 +16,9 @@ superproject's fixtures of the user's Jamfiles (tools/test/fixtures/crypto_jamfiles//), whose Jamfile lines and printed results the page shows as the fixtures hold them. crypto.json holds what no build produces: the facts about the world with their sources, the use cases, the fix of each -message and the description of each fixture. A measurement no lane takes yet (size, throughput, -constant time measured) is written as not measured yet. +message and the description of each fixture. The table of Ed25519's twelve edge cases is +meta/ed25519_cases.json's, the verdicts test/ed25519_speccheck_test.cpp asserts. A measurement no +lane takes yet (size, throughput, constant time measured) is written as not measured yet. The capability table is crypto.json's families: each family's algorithms and, per backend, the targets on which it has them, which the tests of the family's operations must run on (a cell is @@ -48,13 +49,23 @@ HERE = Path(__file__).resolve().parent DOC = HERE.parent LIBRARY = DOC.parent -NOTICE = ('// Copyright (c) 2026 WebCpp.org\n//\n' - '// Distributed under the Boost Software License, Version 1.0. (See\n' - '// accompanying file LICENSE_1_0.txt or copy at\n' - '// https://www.boost.org/LICENSE_1_0.txt)\n\n' - '// Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles,\n' - '// the message tests and the Jamfile fixtures: run it again, never edit this file.\n\n') +LICENCE = ('// Copyright (c) 2026 WebCpp.org\n//\n' + '// Distributed under the Boost Software License, Version 1.0. (See\n' + '// accompanying file LICENSE_1_0.txt or copy at\n' + '// https://www.boost.org/LICENSE_1_0.txt)\n\n') +NOTICE = LICENCE + ( + '// Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles,\n' + '// the message tests and the Jamfile fixtures: run it again, never edit this file.\n\n') +# The notice of the table of Ed25519's edge cases, whose data is meta/ed25519_cases.json alone. +CASES_NOTICE = LICENCE + ( + '// Generated by doc/tables/generate.py from meta/ed25519_cases.json, which\n' + '// test/ed25519_speccheck_test.cpp asserts: run it again, never edit this file.\n\n') FIXTURES = 'tools/test/fixtures/crypto_jamfiles' +ED25519_CASES = Path('meta/ed25519_cases.json') +# The outside views of the edge cases, by their key in meta/ed25519_cases.json: verdicts recorded +# beside the backends', which strict is never compared with. +OUTSIDE_TITLES = {'webcrypto-node': 'WebCrypto in node, outside view'} +VERDICTS = ('accept', 'reject') BACKEND_ORDER = ('bearssl', 'openssl', 'ctaes', 'secp256k1', 'sodium', 'system', 'none') NAMESPACE_TITLES = {'root': 'webcpp::crypto', 'ciphers': 'webcpp::crypto::ciphers', 'curves': 'webcpp::crypto::curves'} @@ -1020,6 +1031,32 @@ def sizes_page(data: Data) -> str: + ['Throughput, native', 'Throughput, node'], rows) +def ed25519_cases_page(data: Data, cases: Data) -> str: + """The twelve Ed25519 edge cases of meta/ed25519_cases.json: a row per case, what it tests, + then each backend's raw verdict and its verdict under `strict`, then each outside view's. A + row whose length is not the cases' or a verdict other than accept or reject is a fault.""" + columns = ['Case', 'What it tests'] + verdicts: List[List[str]] = [] + for backend in BACKEND_ORDER: + rows = cases['backends'].get(backend) + if rows is None: + continue + title = data['backends'][backend]['title'] + columns += [f'{title}, raw', f'{title}, strict'] + verdicts += [rows['raw'], rows['strict']] + for name, row in cases['outside'].items(): + columns.append(OUTSIDE_TITLES[name]) + verdicts.append(row) + for column, row in zip(columns[2:], verdicts): + if len(row) != len(cases['cases']) or any(entry not in VERDICTS for entry in row): + raise Fault(f'{ED25519_CASES}: the row {column} is not one verdict, accept or ' + f'reject, per case: {row}') + rows = [[str(index), marked(text)] + [row[index] for row in verdicts] + for index, text in enumerate(cases['cases'])] + widths = ','.join(['1', '5'] + ['2'] * len(verdicts)) + return table(columns, rows, f'cols="{widths}",') + + def block(lines: List[str]) -> str: """A block of lines as they are, with no language: a Jamfile, which highlight.js does not know, or what a build prints.""" @@ -1336,6 +1373,8 @@ def generate(root: Path, library: Path) -> Dict[Path, str]: files[library / DEFAULTS] = defaults_header(data) for path in list(files): files[path] = NOTICE + files[path] + cases_data: Data = json.loads((library / ED25519_CASES).read_text(encoding='utf-8')) + files[generated / 'ed25519-cases.adoc'] = CASES_NOTICE + ed25519_cases_page(data, cases_data) files[DOC / 'llms.txt'] = llms(data, matrix, library) files[library / BUILD] = with_aliases((library / BUILD).read_text(encoding='utf-8'), default_aliases(data)) diff --git a/doc/tables/generate_test.py b/doc/tables/generate_test.py index 3a1c08c2..e9aeee9d 100644 --- a/doc/tables/generate_test.py +++ b/doc/tables/generate_test.py @@ -11,9 +11,9 @@ outcome reader (each directive and section), the Doc Comment reader (a line reference left out), the writers whose output a reader of the page sees (inline code that holds a `+` or a backtick, a failing fixture's output per target, a comparison table's names of code, the decision table's -Jamfile column), and the capability table's: its checks of crypto.json's families, the refusals and -cells of include/webcpp/crypto/detail/capabilities.hpp, the cells test/capabilities_test.cpp -asserts, and the comparison --check makes. +Jamfile column, the table of Ed25519's edge cases), and the capability table's: its checks of +crypto.json's families, the refusals and cells of include/webcpp/crypto/detail/capabilities.hpp, the +cells test/capabilities_test.cpp asserts, and the comparison --check makes. generate.py --check proves only that the committed tables are what generate.py writes now: a reader that regresses and is regenerated in the same change would pass it, and fails here. @@ -187,6 +187,27 @@ def test_an_index_entry_names_a_qualified_function_bare(scratch: Path) -> None: entry = generate.llms_entry(scratch, operation, 'sign') assert entry == ' - sign: Signs a message.', entry +def test_the_edge_cases_table_has_a_row_per_case_and_a_column_per_verdict(_: Path) -> None: + data = {'backends': {'sodium': {'title': 'libsodium'}}} + cases = {'source': {'repository': 'novifinancial/ed25519-speccheck', 'commit': '65519336', + 'file': 'cases.json'}, + 'backends': {'sodium': {'raw': ['reject', 'accept'], 'strict': ['reject', 'accept']}}, + 'outside': {'webcrypto-node': ['accept', 'accept']}, + 'cases': ['`S` = 0', '`A` non-canonical']} + page = generate.ed25519_cases_page(data, cases) + header = '|Case |What it tests |libsodium, raw |libsodium, strict |WebCrypto in node' + assert header in page, page + assert '\n|0\n|`+S+` = 0\n|reject\n|reject\n|accept\n' in page, page + assert '\n|1\n|`+A+` non-canonical\n|accept\n|accept\n|accept\n' in page, page + for broken in ({'raw': ['reject'], 'strict': ['reject', 'accept']}, + {'raw': ['reject', 'maybe'], 'strict': ['reject', 'accept']}): + try: + generate.ed25519_cases_page(data, {**cases, 'backends': {'sodium': broken}}) + except generate.Fault: + pass + else: + raise AssertionError(f'a row {broken} was written') + def test_code_that_holds_a_plus_is_one_span(_: Path) -> None: # `+em++: error:+` would be read as `+em+` and a stray rest: the text is a passthrough. assert generate.code('em++: error:') == '`pass:[em++: error:]`', generate.code('em++') @@ -664,6 +685,7 @@ def test_the_check_names_a_file_that_differs(scratch: Path) -> None: test_a_brief_leaves_out_a_line_reference, test_a_qualified_function_is_read_in_its_class, test_an_index_entry_names_a_qualified_function_bare, + test_the_edge_cases_table_has_a_row_per_case_and_a_column_per_verdict, test_code_that_holds_a_plus_is_one_span, test_a_failing_fixture_lists_its_texts_per_target, test_a_fixture_that_builds_and_runs_nothing_is_a_record, diff --git a/meta/ed25519_cases.json b/meta/ed25519_cases.json new file mode 100644 index 00000000..1eb174d9 --- /dev/null +++ b/meta/ed25519_cases.json @@ -0,0 +1,16 @@ +{"source": {"repository": "novifinancial/ed25519-speccheck", "commit": "65519336", "file": "cases.json"}, + "backends": {"sodium": {"raw": ["reject", "reject", "reject", "accept", "reject", "reject", "reject", "reject", "reject", "reject", "reject", "reject"], + "strict": ["reject", "reject", "reject", "accept", "reject", "reject", "reject", "reject", "reject", "reject", "reject", "reject"]}}, + "outside": {"webcrypto-node": ["reject", "reject", "reject", "accept", "reject", "reject", "reject", "reject", "reject", "reject", "reject", "reject"]}, + "cases": ["`S` = 0, `A` and `R` of small order", + "`A` of small order", + "`R` of small order", + "`A` and `R` of mixed order, valid with or without the cofactor", + "`A` and `R` of mixed order, valid with the cofactor alone", + "`R` of full order, valid with the cofactor unless `8h` is reduced first", + "`S` above the group order `L`", + "`S` far above `L`, its top bit set", + "`R` non-canonical, reduced before hashing", + "`R` non-canonical, hashed as given", + "`A` non-canonical, reduced before hashing", + "`A` non-canonical, hashed as given"]} diff --git a/test/Jamfile b/test/Jamfile index edf938fd..494570d5 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -6,6 +6,7 @@ project : requirements /webcpp/crypto//crypto ; +import regex ; import webcpp ; webcpp.targets native wasip2 wasip3 emscripten ; @@ -289,6 +290,20 @@ crypto-run ed25519ph_sodium : ed25519ph_sodium_test.cpp : /third_party/ # moved over, ended and destroyed: optimised, every call inlined, as secret's. crypto-run ed25519_wipe_sodium : ed25519_wipe_sodium_test.cpp : /third_party//sodium $(OPTIMISED) full ; +# The twelve Ed25519 edge cases of "Taming the many EdDSAs" (design D31): +# each backend's raw verdict and strict's against meta/ed25519_cases.json, read +# at run time from the directory WEBCPP_TEST_CRYPTO_META gives, quoted as +# wycheproof's is, with forward slashes, and preopened on WASI; on Emscripten +# node's WebCrypto too, the outside view (the JSPI link, for EM_ASYNC_JS). +path-constant CRYPTO_TEST_META : ../meta ; +.crypto-meta = [ regex.replace $(CRYPTO_TEST_META) "\\\\" "/" ] ; +crypto-run ed25519_speccheck : ed25519_speccheck_test.cpp + : /third_party//sodium /third_party//ed25519-speccheck + /webcpp//boost_json + "\"WEBCPP_TEST_CRYPTO_META=\\\"$(.crypto-meta)\\\"\"" + [ webcpp.data $(CRYPTO_TEST_META) ] + ../meta/ed25519_cases.json + emscripten:-sJSPI ; # X25519 on libsodium: RFC 7748's scalar multiplications and Alice and Bob, a # peer of order 8 refused as weak, the guards and the conversion from Ed25519; diff --git a/test/ed25519_speccheck_test.cpp b/test/ed25519_speccheck_test.cpp new file mode 100644 index 00000000..7b7ff65e --- /dev/null +++ b/test/ed25519_speccheck_test.cpp @@ -0,0 +1,234 @@ +// 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 twelve Ed25519 edge cases of Chalkias, Garillot and Nikolaenko, "Taming the many EdDSAs" +// (2020), novifinancial/ed25519-speccheck's cases.json, against every Ed25519 backend linked +// (design D31): each backend's raw verdict, its own library called directly, and the verdict of +// curves::ed25519::verify, compared with the verdicts committed in +// meta/ed25519_cases.json. Under strict every backend gives libsodium's verdicts. On Emscripten, +// node's WebCrypto verify (Ed25519) gives the row webcrypto-node, an outside view that is compared +// with its committed row but never with strict's. A pin move that changes a verdict fails here +// until the data and the page are regenerated. Each row is printed, so that a first run gives +// the data to review. + +#include +#include +#include +#include + +#include "support/hex.hpp" +#include "support/test_data.hpp" + +#include +#include + +#include +#include + +#if defined(__EMSCRIPTEN__) +#include +#endif + +#include +#include +#include +#include +#include +#include + +namespace crypto = webcpp::crypto; +namespace ed25519 = webcpp::crypto::curves::ed25519; +namespace test = webcpp::test; +namespace json = boost::json; + +#if defined(__EMSCRIPTEN__) +// node's crypto.subtle.verify with an Ed25519 key imported raw: 1 when it accepts, 0 when it +// refuses, 2 when importKey refuses the public key (a refusal of the case too), -1 when verify +// itself throws (the message goes to the console). The inputs are copied before the first await. +// clang-format off +EM_ASYNC_JS(int, subtle_ed25519_verify, (const std::uint8_t* key, const std::uint8_t* msg, + std::size_t msg_size, const std::uint8_t* sig), { + const key_bytes = HEAPU8.slice(key, key + 32); + const data = HEAPU8.slice(msg, msg + msg_size); + const signature = HEAPU8.slice(sig, sig + 64); + let imported; + try { + imported = await globalThis.crypto.subtle.importKey( + "raw", key_bytes, {name: "Ed25519"}, false, ["verify"]); + } catch (e) { + return 2; + } + try { + return (await globalThis.crypto.subtle.verify({name: "Ed25519"}, imported, signature, + data)) ? 1 : 0; + } catch (e) { + console.error("subtle.verify: " + e); + return -1; + } +}); +// clang-format on +#endif + +namespace { + +constexpr std::size_t case_count = 12; + +using verdicts = std::vector; + +// One of cases.json's twelve. +struct edge_case { + std::vector message; + std::vector public_key; + std::vector signature; +}; + +std::string text_of(json::value const& value) { + return std::string(std::string_view(value.as_string())); +} + +std::string verdict(bool accepted) { + return accepted ? "accept" : "reject"; +} + +// A committed row: twelve verdicts, each accept or reject. +verdicts committed_row(json::value const& row, std::string const& label) { + verdicts out; + for (auto const& entry : row.as_array()) { + out.push_back(text_of(entry)); + if (out.back() != "accept" && out.back() != "reject") { + BOOST_ERROR( + (label + ": a committed verdict is neither accept nor reject: " + out.back()) + .c_str()); + } + } + BOOST_TEST_EQ(out.size(), case_count); + return out; +} + +void print_row(std::string const& label, verdicts const& row) { + std::cout << label << ':'; + for (auto const& entry : row) { + std::cout << ' ' << entry; + } + std::cout << '\n'; +} + +// The row computed against the row committed, case by case. +void compare(std::string const& label, verdicts const& computed, verdicts const& expected) { + print_row(label, computed); + if (computed.size() != expected.size()) { + BOOST_ERROR((label + ": the committed row has another number of cases").c_str()); + return; + } + for (std::size_t index = 0; index < computed.size(); ++index) { + if (computed[index] != expected[index]) { + BOOST_ERROR((label + ", case " + std::to_string(index) + ": " + computed[index] + + ", committed " + expected[index]) + .c_str()); + } + } +} + +// libsodium's raw verdicts, crypto_sign_ed25519_verify_detached called directly, and strict's, +// curves::ed25519::verify, whose refusal is invalid_signature. +void sodium_rows(std::vector const& cases, verdicts& raw, verdicts& strict) { + for (auto const& tested : cases) { + raw.push_back(verdict(crypto_sign_ed25519_verify_detached( + tested.signature.data(), tested.message.data(), + tested.message.size(), tested.public_key.data()) == 0)); + auto const verified = ed25519::verify( + tested.public_key, tested.message, tested.signature); + if (!verified) { + BOOST_TEST(verified.error() == crypto::error::invalid_signature); + } + strict.push_back(verdict(static_cast(verified))); + } +} + +} // namespace + +int main() { + BOOST_TEST(sodium_init() >= 0); + boost::system::error_code parse_error; + auto const cases_document = + json::parse(test::read_file(WEBCPP_TEST_ED25519_SPECCHECK "/cases.json"), parse_error); + BOOST_TEST(!parse_error); + auto const committed = + json::parse(test::read_file(WEBCPP_TEST_CRYPTO_META "/ed25519_cases.json"), parse_error); + BOOST_TEST(!parse_error); + if (parse_error) { + return test::exit_status(boost::report_errors()); + } + + std::vector cases; + for (auto const& entry : cases_document.as_array()) { + cases.push_back({test::from_hex(text_of(entry.at("message"))), + test::from_hex(text_of(entry.at("pub_key"))), + test::from_hex(text_of(entry.at("signature")))}); + BOOST_TEST_EQ(cases.back().public_key.size(), 32U); + BOOST_TEST_EQ(cases.back().signature.size(), 64U); + } + BOOST_TEST_EQ(cases.size(), case_count); + if (cases.size() != case_count) { + return test::exit_status(boost::report_errors()); + } + + // What each case tests, the page's first column: one text per case. + BOOST_TEST_EQ(committed.at("cases").as_array().size(), case_count); + + auto const& source = committed.at("source"); + BOOST_TEST_EQ(text_of(source.at("repository")), "novifinancial/ed25519-speccheck"); + BOOST_TEST_EQ(text_of(source.at("commit")), "65519336"); + BOOST_TEST_EQ(text_of(source.at("file")), "cases.json"); + + // Every committed backend is one this test runs (libsodium alone in this version), and each + // backend's strict verdicts are compared with libsodium's committed row: under strict every + // backend gives libsodium's verdicts. + auto const& backends = committed.at("backends").as_object(); + BOOST_TEST(backends.contains("sodium")); + if (!backends.contains("sodium")) { + return test::exit_status(boost::report_errors()); + } + auto const sodium_raw = committed_row(backends.at("sodium").at("raw"), "sodium raw"); + auto const sodium_strict = committed_row(backends.at("sodium").at("strict"), "sodium strict"); + // A backend's rows are committed with its run here. + for (auto const& entry : backends) { + if (entry.key() != "sodium") { + BOOST_ERROR(("a committed backend this test does not run: " + std::string(entry.key())) + .c_str()); + } + } + + verdicts raw; + verdicts strict; + sodium_rows(cases, raw, strict); + compare("sodium raw", raw, sodium_raw); + compare("sodium strict", strict, sodium_strict); + + // The outside view: node's WebCrypto, committed as one row. + auto const* outside = committed.as_object().if_contains("outside"); + BOOST_TEST(outside != nullptr && outside->as_object().size() == 1U && + outside->as_object().contains("webcrypto-node")); + if (outside == nullptr || !outside->as_object().contains("webcrypto-node")) { + return test::exit_status(boost::report_errors()); + } + auto const webcrypto = committed_row(outside->at("webcrypto-node"), "webcrypto-node"); +#if defined(__EMSCRIPTEN__) + verdicts subtle; + for (auto const& tested : cases) { + auto const answer = subtle_ed25519_verify(tested.public_key.data(), tested.message.data(), + tested.message.size(), tested.signature.data()); + BOOST_TEST(answer >= 0); + subtle.push_back(verdict(answer == 1)); + } + compare("webcrypto-node", subtle, webcrypto); +#else + static_cast(webcrypto); +#endif + + std::cout << "ed25519 speccheck: cases=" << cases.size() << '\n'; + return test::exit_status(boost::report_errors()); +} From aa29922742cd7db79caeca0fcbc346bb9141a572 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 20:09:45 -0300 Subject: [PATCH 024/110] crypto: Ed25519's edge cases record the node and OpenSSL of WebCrypto's row, the generator refuses keys it does not know, and the changelog's lines fit the lint --- doc/changelog.adoc | 8 +++---- doc/ed25519.adoc | 23 +++++++++++------- doc/generated/ed25519-cases.adoc | 4 ++-- doc/tables/generate.py | 27 +++++++++++++++------ doc/tables/generate_test.py | 27 +++++++++++++++++++-- meta/ed25519_cases.json | 5 ++-- test/ed25519_speccheck_test.cpp | 40 +++++++++++++++++++++++++------- 7 files changed, 99 insertions(+), 35 deletions(-) diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 59256d65..ad5f7312 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -19,11 +19,11 @@ of every version are on webcpp's index page. * Added crypto, primitives over C backends: ciphers, curves and randomness, with errors of fixed values in webcpp.crypto, every result `+[[nodiscard]]+`, and WEBCPP_CRYPTO_HAS_THREADS, defined natively and on Emscripten with -pthread unless WEBCPP_CRYPTO_NO_THREADS is. * Added equal, random_device, ciphers::aes128, aes192 and aes256, the AES block cipher, and ciphers::gcm, AES-GCM in place with an incremental seal whose failed open zeroes the data. * Added default_backend_t and /webcpp/crypto//-default, one default backend per family and target whatever is linked, ciphers::aes128_gcm and aes256_gcm, and refusals naming the Jamfile line and another backend's type. -* Added backends::bearssl (AES-GCM allocating nothing, no block cipher), backends::openssl through /webcpp/crypto//openssl on native and WASI (allocating at make only), and backends::ctaes (block cipher alone). -* Added WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE: OpenSSL's allocations in the program's resource, refused on WebAssembly (WASI included) and without OpenSSL: openssl_memory_resource, install_memory_functions, memory_functions_refused, memory_functions_not_installed. -* Added curves::secp256k1: key pairs, BIP340 and ECDSA signatures, ECDH, strict DER, low-S and the x-only tweak; curves::ed25519 on libsodium: key pairs, signatures verified strictly (each backend's verdicts on the twelve edge cases of "Taming the many EdDSAs" tested and tabled), the X25519 secret key and public key, and Ed25519ph over webcpp::hash's sha2_512, which /webcpp/crypto//crypto now brings; and curves::x25519 on libsodium, whose agree refuses an all-zero secret. +* Added backends::bearssl (AES-GCM alone, allocating nothing), backends::openssl via /webcpp/crypto//openssl natively and on WASI (allocating at make only, or natively in openssl_memory_resource with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE), and backends::ctaes (block cipher alone). +* Added curves::secp256k1: key pairs, BIP340 and ECDSA signatures, ECDH, strict DER, low-S and the x-only tweak. +* Added curves::ed25519 and curves::x25519 on libsodium: strict verification tabled on twelve edge cases, Ed25519ph over webcpp::hash's sha2_512 (/webcpp/crypto//crypto brings hash), the conversion, and agree refusing all-zero secrets. * Added backends::sodium on /third_party//sodium, shared with webcpp::hash and initialised before every engine, and every backend's link-time canary and C suite. * Added the page: a chapter per namespace and use case, the memory option's guide and example, tables generated from the tests, every Jamfile and message, and llms.txt. * Added supports_v, the capability table on the target being compiled, and the tags of its families and algorithms, which ciphers::gcm, the AES block cipher and secp256k1's key pair name. -* Added secret, a self-wiping array that is copied only by clone, and the errors 15 to 20: weak_public_key, invalid_point, invalid_scalar, invalid_padding, invalid_encoding and invalid_ciphertext_size. +* Added secret, a self-wiping array that is copied only by clone, and the errors 13 to 20: memory_functions_refused, memory_functions_not_installed, weak_public_key, invalid_point, invalid_scalar, invalid_padding, invalid_encoding and invalid_ciphertext_size. // end::unreleased[] diff --git a/doc/ed25519.adoc b/doc/ed25519.adoc index d06e0fa7..1c7f4ef5 100644 --- a/doc/ed25519.adoc +++ b/doc/ed25519.adoc @@ -73,21 +73,26 @@ twelve signatures on which implementations disagree, in their suite They run against every Ed25519 backend: its own verdict (raw), and its verdict under `strict`, which is libsodium's on every backend. The test `ed25519_speccheck` asserts the table below, so that a new version of a backend -that changes a verdict fails until the table is regenerated; WebCrypto in node -is an outside view, recorded and never held to `strict`. +that changes a verdict fails until the table is regenerated. WebCrypto in node +is an outside view, recorded with the node and the OpenSSL that gave it (node's +Ed25519 is OpenSSL's) and never held to `strict`. The suite's results of 2021 +show OpenSSL 3.0 accepting cases 0 to 2 and 11; the newer OpenSSL of the +column's node refuses them, as libsodium does. include::generated/ed25519-cases.adoc[] Honest signatures verify everywhere: the cases differ only on signatures no honest signer makes, and a network that mixes verifiers must agree on one rule -for them. Rust peers that use ed25519-dalek's default `verify` accept cases 0 -to 2 and 11, which `strict` refuses +for them. In the suite's results of 2021 (link:https://github.com/novifinancial/ed25519-speccheck#results[the suite's -results]). ZIP-215 verifiers (link:https://zips.z.cash/zip-0215[ZIP 215]), the -rule of Zcash, accept every case but 6 to 8 by design: they verify with the -cofactor and accept non-canonical encodings of `A` and `R`, so that every -ZIP-215 verifier agrees on every signature. `strict` refuses the cases they -accept beyond it; `zip215` is not a policy of this version, and waits for a +results], whose `Cargo.toml` pins them), Rust peers that used the default +`verify` of ed25519-dalek 1.0.0-pre.4 accepted cases 0 to 2 and 11, which +`strict` refuses, and ed25519-zebra 2.1.1, a ZIP-215 verifier +(link:https://zips.z.cash/zip-0215[ZIP 215], the rule of Zcash), accepted every +case but 6 to 8. ZIP-215 does so by design: it verifies with the +cofactor and accepts non-canonical encodings of `A` and `R`, so that every +ZIP-215 verifier agrees on every signature. `strict` refuses the cases ZIP-215 +accepts beyond it; `zip215` is not a policy of this version, and waits for a mature C or {cpp} implementation of ZIP-215. *Pitfalls.* diff --git a/doc/generated/ed25519-cases.adoc b/doc/generated/ed25519-cases.adoc index b0c547c0..9cb99e4f 100644 --- a/doc/generated/ed25519-cases.adoc +++ b/doc/generated/ed25519-cases.adoc @@ -9,7 +9,7 @@ [cols="1,5,2,2,2",options="header"] |=== -|Case |What it tests |libsodium, raw |libsodium, strict |WebCrypto in node, outside view +|Case |What it tests |libsodium, raw |libsodium, strict |WebCrypto in node 26.13.0 (OpenSSL 4.1.0), outside view |0 |`+S+` = 0, `+A+` and `+R+` of small order @@ -54,7 +54,7 @@ |reject |7 -|`+S+` far above `+L+`, its top bit set +|`+S+` above twice `+L+` |reject |reject |reject diff --git a/doc/tables/generate.py b/doc/tables/generate.py index d36847ab..6d32c0ca 100644 --- a/doc/tables/generate.py +++ b/doc/tables/generate.py @@ -63,8 +63,8 @@ FIXTURES = 'tools/test/fixtures/crypto_jamfiles' ED25519_CASES = Path('meta/ed25519_cases.json') # The outside views of the edge cases, by their key in meta/ed25519_cases.json: verdicts recorded -# beside the backends', which strict is never compared with. -OUTSIDE_TITLES = {'webcrypto-node': 'WebCrypto in node, outside view'} +# beside the backends', which strict is never compared with, headed by the versions that gave them. +OUTSIDE_TITLES = {'webcrypto-node': 'WebCrypto in node {node} (OpenSSL {openssl}), outside view'} VERDICTS = ('accept', 'reject') BACKEND_ORDER = ('bearssl', 'openssl', 'ctaes', 'secp256k1', 'sodium', 'system', 'none') NAMESPACE_TITLES = {'root': 'webcpp::crypto', 'ciphers': 'webcpp::crypto::ciphers', @@ -1033,10 +1033,16 @@ def sizes_page(data: Data) -> str: def ed25519_cases_page(data: Data, cases: Data) -> str: """The twelve Ed25519 edge cases of meta/ed25519_cases.json: a row per case, what it tests, - then each backend's raw verdict and its verdict under `strict`, then each outside view's. A - row whose length is not the cases' or a verdict other than accept or reject is a fault.""" + then each backend's raw verdict and its verdict under `strict`, then each outside view's, + headed by the node and OpenSSL that gave it. A backend or an outside view the generator does + not know, an outside view without its node and OpenSSL, a row whose length is not the cases' + and a verdict other than accept or reject are faults.""" columns = ['Case', 'What it tests'] verdicts: List[List[str]] = [] + for backend in cases['backends']: + if backend not in BACKEND_ORDER or backend not in data['backends']: + raise Fault(f'{ED25519_CASES} names the backend {backend}, which crypto.json does ' + 'not list') for backend in BACKEND_ORDER: rows = cases['backends'].get(backend) if rows is None: @@ -1044,9 +1050,16 @@ def ed25519_cases_page(data: Data, cases: Data) -> str: title = data['backends'][backend]['title'] columns += [f'{title}, raw', f'{title}, strict'] verdicts += [rows['raw'], rows['strict']] - for name, row in cases['outside'].items(): - columns.append(OUTSIDE_TITLES[name]) - verdicts.append(row) + for name, view in cases['outside'].items(): + if name not in OUTSIDE_TITLES: + raise Fault(f'{ED25519_CASES} names the outside view {name}, which generate.py does ' + f'not know: {", ".join(OUTSIDE_TITLES)}') + if not isinstance(view, dict) or not all(isinstance(view.get(key), str) + for key in ('node', 'openssl')): + raise Fault(f'{ED25519_CASES}: the outside view {name} records no node and OpenSSL ' + 'versions') + columns.append(OUTSIDE_TITLES[name].format(**view)) + verdicts.append(view.get('verdicts', [])) for column, row in zip(columns[2:], verdicts): if len(row) != len(cases['cases']) or any(entry not in VERDICTS for entry in row): raise Fault(f'{ED25519_CASES}: the row {column} is not one verdict, accept or ' diff --git a/doc/tables/generate_test.py b/doc/tables/generate_test.py index e9aeee9d..3650e0d5 100644 --- a/doc/tables/generate_test.py +++ b/doc/tables/generate_test.py @@ -187,15 +187,18 @@ def test_an_index_entry_names_a_qualified_function_bare(scratch: Path) -> None: entry = generate.llms_entry(scratch, operation, 'sign') assert entry == ' - sign: Signs a message.', entry + def test_the_edge_cases_table_has_a_row_per_case_and_a_column_per_verdict(_: Path) -> None: data = {'backends': {'sodium': {'title': 'libsodium'}}} cases = {'source': {'repository': 'novifinancial/ed25519-speccheck', 'commit': '65519336', 'file': 'cases.json'}, 'backends': {'sodium': {'raw': ['reject', 'accept'], 'strict': ['reject', 'accept']}}, - 'outside': {'webcrypto-node': ['accept', 'accept']}, + 'outside': {'webcrypto-node': {'node': '26.13.0', 'openssl': '4.1.0', + 'verdicts': ['accept', 'accept']}}, 'cases': ['`S` = 0', '`A` non-canonical']} page = generate.ed25519_cases_page(data, cases) - header = '|Case |What it tests |libsodium, raw |libsodium, strict |WebCrypto in node' + header = ('|Case |What it tests |libsodium, raw |libsodium, strict ' + '|WebCrypto in node 26.13.0 (OpenSSL 4.1.0), outside view') assert header in page, page assert '\n|0\n|`+S+` = 0\n|reject\n|reject\n|accept\n' in page, page assert '\n|1\n|`+A+` non-canonical\n|accept\n|accept\n|accept\n' in page, page @@ -208,6 +211,25 @@ def test_the_edge_cases_table_has_a_row_per_case_and_a_column_per_verdict(_: Pat else: raise AssertionError(f'a row {broken} was written') + +def test_an_edge_cases_key_the_generator_does_not_know_is_a_fault(_: Path) -> None: + # A backend misnamed, an outside view without a title, or one whose node or OpenSSL is not + # recorded would leave the page silently short of a row or of its provenance. + data = {'backends': {'sodium': {'title': 'libsodium'}}} + row = {'raw': ['reject'], 'strict': ['reject']} + view = {'node': '26.13.0', 'openssl': '4.1.0', 'verdicts': ['reject']} + for backends, outside in (({'libsodium': row}, {'webcrypto-node': view}), + ({'sodium': row}, {'webcrypto-deno': view}), + ({'sodium': row}, {'webcrypto-node': {'verdicts': ['reject']}})): + cases = {'backends': backends, 'outside': outside, 'cases': ['`S` = 0']} + try: + generate.ed25519_cases_page(data, cases) + except generate.Fault: + pass + else: + raise AssertionError(f'the keys {backends}, {outside} were written') + + def test_code_that_holds_a_plus_is_one_span(_: Path) -> None: # `+em++: error:+` would be read as `+em+` and a stray rest: the text is a passthrough. assert generate.code('em++: error:') == '`pass:[em++: error:]`', generate.code('em++') @@ -686,6 +708,7 @@ def test_the_check_names_a_file_that_differs(scratch: Path) -> None: test_a_qualified_function_is_read_in_its_class, test_an_index_entry_names_a_qualified_function_bare, test_the_edge_cases_table_has_a_row_per_case_and_a_column_per_verdict, + test_an_edge_cases_key_the_generator_does_not_know_is_a_fault, test_code_that_holds_a_plus_is_one_span, test_a_failing_fixture_lists_its_texts_per_target, test_a_fixture_that_builds_and_runs_nothing_is_a_record, diff --git a/meta/ed25519_cases.json b/meta/ed25519_cases.json index 1eb174d9..421ecf6f 100644 --- a/meta/ed25519_cases.json +++ b/meta/ed25519_cases.json @@ -1,7 +1,8 @@ {"source": {"repository": "novifinancial/ed25519-speccheck", "commit": "65519336", "file": "cases.json"}, "backends": {"sodium": {"raw": ["reject", "reject", "reject", "accept", "reject", "reject", "reject", "reject", "reject", "reject", "reject", "reject"], "strict": ["reject", "reject", "reject", "accept", "reject", "reject", "reject", "reject", "reject", "reject", "reject", "reject"]}}, - "outside": {"webcrypto-node": ["reject", "reject", "reject", "accept", "reject", "reject", "reject", "reject", "reject", "reject", "reject", "reject"]}, + "outside": {"webcrypto-node": {"node": "26.13.0", "openssl": "4.1.0", + "verdicts": ["reject", "reject", "reject", "accept", "reject", "reject", "reject", "reject", "reject", "reject", "reject", "reject"]}}, "cases": ["`S` = 0, `A` and `R` of small order", "`A` of small order", "`R` of small order", @@ -9,7 +10,7 @@ "`A` and `R` of mixed order, valid with the cofactor alone", "`R` of full order, valid with the cofactor unless `8h` is reduced first", "`S` above the group order `L`", - "`S` far above `L`, its top bit set", + "`S` above twice `L`", "`R` non-canonical, reduced before hashing", "`R` non-canonical, hashed as given", "`A` non-canonical, reduced before hashing", diff --git a/test/ed25519_speccheck_test.cpp b/test/ed25519_speccheck_test.cpp index 7b7ff65e..4de47456 100644 --- a/test/ed25519_speccheck_test.cpp +++ b/test/ed25519_speccheck_test.cpp @@ -69,6 +69,12 @@ EM_ASYNC_JS(int, subtle_ed25519_verify, (const std::uint8_t* key, const std::uin return -1; } }); + +// The versions of the node running this program, and of its OpenSSL, on one line. +EM_JS(void, print_node_versions, (), { + console.log("webcrypto-node run with node " + process.versions.node + ", OpenSSL " + + process.versions.openssl); +}); // clang-format on #endif @@ -152,14 +158,15 @@ void sodium_rows(std::vector const& cases, verdicts& raw, verdicts& s int main() { BOOST_TEST(sodium_init() >= 0); - boost::system::error_code parse_error; + boost::system::error_code cases_error; auto const cases_document = - json::parse(test::read_file(WEBCPP_TEST_ED25519_SPECCHECK "/cases.json"), parse_error); - BOOST_TEST(!parse_error); - auto const committed = - json::parse(test::read_file(WEBCPP_TEST_CRYPTO_META "/ed25519_cases.json"), parse_error); - BOOST_TEST(!parse_error); - if (parse_error) { + json::parse(test::read_file(WEBCPP_TEST_ED25519_SPECCHECK "/cases.json"), cases_error); + BOOST_TEST(!cases_error); + boost::system::error_code committed_error; + auto const committed = json::parse( + test::read_file(WEBCPP_TEST_CRYPTO_META "/ed25519_cases.json"), committed_error); + BOOST_TEST(!committed_error); + if (cases_error || committed_error) { return test::exit_status(boost::report_errors()); } @@ -208,15 +215,30 @@ int main() { compare("sodium raw", raw, sodium_raw); compare("sodium strict", strict, sodium_strict); - // The outside view: node's WebCrypto, committed as one row. + // The outside view: node's WebCrypto, committed as one row with the node and OpenSSL that + // gave it. auto const* outside = committed.as_object().if_contains("outside"); BOOST_TEST(outside != nullptr && outside->as_object().size() == 1U && outside->as_object().contains("webcrypto-node")); if (outside == nullptr || !outside->as_object().contains("webcrypto-node")) { return test::exit_status(boost::report_errors()); } - auto const webcrypto = committed_row(outside->at("webcrypto-node"), "webcrypto-node"); + auto const& view = outside->at("webcrypto-node").as_object(); + BOOST_TEST(view.contains("node") && view.at("node").is_string()); + BOOST_TEST(view.contains("openssl") && view.at("openssl").is_string()); + BOOST_TEST(view.contains("verdicts")); + if (!view.contains("verdicts")) { + return test::exit_status(boost::report_errors()); + } + auto const webcrypto = committed_row(view.at("verdicts"), "webcrypto-node"); #if defined(__EMSCRIPTEN__) + // The versions this run's node has, beside those committed: a node whose row differs says + // which it is. + if (view.contains("node") && view.contains("openssl")) { + std::cout << "webcrypto-node committed with node " << text_of(view.at("node")) + << ", OpenSSL " << text_of(view.at("openssl")) << '\n'; + } + print_node_versions(); verdicts subtle; for (auto const& tested : cases) { auto const answer = subtle_ed25519_verify(tested.public_key.data(), tested.message.data(), From cc7acc690ce098b57893720a0e36efbfb2c32633 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 15:16:43 -0300 Subject: [PATCH 025/110] crypto: one AEAD template, and ChaCha20-Poly1305, its original form and XChaCha20-Poly1305 on libsodium --- build.jam | 33 + doc/chacha.adoc | 67 ++ doc/changelog.adoc | 2 +- doc/crypto.adoc | 2 + doc/generated/backends-chacha20_poly1305.adoc | 30 + .../backends-chacha20_poly1305_original.adoc | 30 + .../backends-xchacha20_poly1305.adoc | 30 + doc/generated/defaults.adoc | 18 + doc/generated/matrix.adoc | 33 + doc/generated/messages.adoc | 6 + doc/generated/sizes.adoc | 24 + doc/llms.txt | 15 + doc/tables/crypto.json | 92 ++- include/webcpp/crypto.hpp | 7 +- include/webcpp/crypto/backends/sodium.hpp | 135 ++++ include/webcpp/crypto/ciphers/aead.hpp | 354 +++++++++++ .../crypto/ciphers/chacha20_poly1305.hpp | 59 ++ include/webcpp/crypto/detail/capabilities.hpp | 156 +++++ include/webcpp/crypto/detail/defaults.hpp | 24 + include/webcpp/crypto/detail/engines.hpp | 17 +- test/Jamfile | 17 +- test/allocation_sodium_test.cpp | 72 +++ test/capabilities_test.cpp | 70 +++ test/chacha_original_sodium_test.cpp | 41 ++ test/chacha_sodium_test.cpp | 46 ++ test/chacha_wycheproof_sodium_test.cpp | 29 + test/default_backend_test.cpp | 20 + test/messages/Jamfile | 1 + .../chacha_default_not_linked/Jamfile | 12 + .../chacha_default_not_linked.cpp | 32 + test/support/aead_checks.hpp | 584 ++++++++++++++++++ test/support/wycheproof_aead.hpp | 101 +++ test/windows_h_after_test.cpp | 3 + test/windows_h_before_test.cpp | 3 + test/xchacha_sodium_test.cpp | 39 ++ 35 files changed, 2193 insertions(+), 11 deletions(-) create mode 100644 doc/chacha.adoc create mode 100644 doc/generated/backends-chacha20_poly1305.adoc create mode 100644 doc/generated/backends-chacha20_poly1305_original.adoc create mode 100644 doc/generated/backends-xchacha20_poly1305.adoc create mode 100644 include/webcpp/crypto/ciphers/aead.hpp create mode 100644 include/webcpp/crypto/ciphers/chacha20_poly1305.hpp create mode 100644 test/allocation_sodium_test.cpp create mode 100644 test/chacha_original_sodium_test.cpp create mode 100644 test/chacha_sodium_test.cpp create mode 100644 test/chacha_wycheproof_sodium_test.cpp create mode 100644 test/messages/chacha_default_not_linked/Jamfile create mode 100644 test/messages/chacha_default_not_linked/chacha_default_not_linked.cpp create mode 100644 test/support/aead_checks.hpp create mode 100644 test/support/wycheproof_aead.hpp create mode 100644 test/xchacha_sodium_test.cpp diff --git a/build.jam b/build.jam index f1fe6989..e59eed8e 100644 --- a/build.jam +++ b/build.jam @@ -100,4 +100,37 @@ rule x25519-default-linked ( properties * ) } } alias x25519-default : : : : @x25519-default-linked ; +rule chacha20_poly1305-default-linked ( properties * ) +{ + switch [ webcpp-target.target-of $(properties) ] + { + case native : return /third_party//sodium ; + case wasip2 : return /third_party//sodium ; + case wasip3 : return /third_party//sodium ; + case emscripten : return /third_party//sodium ; + } +} +alias chacha20_poly1305-default : : : : @chacha20_poly1305-default-linked ; +rule chacha20_poly1305_original-default-linked ( properties * ) +{ + switch [ webcpp-target.target-of $(properties) ] + { + case native : return /third_party//sodium ; + case wasip2 : return /third_party//sodium ; + case wasip3 : return /third_party//sodium ; + case emscripten : return /third_party//sodium ; + } +} +alias chacha20_poly1305_original-default : : : : @chacha20_poly1305_original-default-linked ; +rule xchacha20_poly1305-default-linked ( properties * ) +{ + switch [ webcpp-target.target-of $(properties) ] + { + case native : return /third_party//sodium ; + case wasip2 : return /third_party//sodium ; + case wasip3 : return /third_party//sodium ; + case emscripten : return /third_party//sodium ; + } +} +alias xchacha20_poly1305-default : : : : @xchacha20_poly1305-default-linked ; # generate.py: end the defaults' aliases diff --git a/doc/chacha.adoc b/doc/chacha.adoc new file mode 100644 index 00000000..b45a3372 --- /dev/null +++ b/doc/chacha.adoc @@ -0,0 +1,67 @@ +// 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) + +[#crypto-chacha] +=== ChaCha20-Poly1305 + +*ChaCha20-Poly1305* is authenticated encryption built from two of Daniel J. +Bernstein's designs: the stream cipher ChaCha20 encrypts, and the one-time +authenticator Poly1305 computes a 16-byte tag over the ciphertext and the +additional data +(link:https://en.wikipedia.org/wiki/ChaCha20-Poly1305[Wikipedia]; +link:https://www.rfc-editor.org/rfc/rfc8439[RFC 8439]). It needs no AES +instructions to be fast and has no table indexed by a secret, so it is +constant time in plain portable code: on a phone or a WebAssembly page +without AES hardware it is the safe choice. It is a cipher suite of TLS 1.3 +(link:https://www.rfc-editor.org/rfc/rfc8446#section-9.1[RFC 8446]) and the +AEAD of WireGuard (link:https://www.wireguard.com/protocol/[WireGuard]). + +`ciphers::aead`, in ``, is +one-shot authenticated encryption in place over a family; three aliases, in +``, name its three +ChaCha20-Poly1305 families on their default backend, libsodium on every +target: + +* `chacha20_poly1305<>`, RFC 8439's form: a 32-byte key, a 12-byte nonce, and +messages of at most 2^38^ - 64 bytes; +* `chacha20_poly1305_original<>`, the original form libsodium keeps: an 8-byte +nonce, too short to draw at random, which a counter numbers +(link:https://doc.libsodium.org/secret-key_cryptography/aead/chacha20-poly1305[libsodium]); +* `xchacha20_poly1305<>`: a 24-byte nonce, safe to draw at random for every +message (link:https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha[the +XChaCha draft]). When in doubt, this one. + +Each is made with `make(key_bytes)` and works in place, as AES-GCM's one-shot +calls do: `seal(iv_bytes, additional_data_bytes, data_bytes)` encrypts +`data_bytes` and returns the 16-byte tag; `open(iv_bytes, +additional_data_bytes, data_bytes, tag_bytes)` checks the tag and decrypts. +A failed `open` zeroes `data_bytes`; a guard's refusal leaves it untouched. + +include::generated/backends-chacha20_poly1305.adoc[] + +include::generated/backends-chacha20_poly1305_original.adoc[] + +include::generated/backends-xchacha20_poly1305.adoc[] + +[#crypto-chacha-guards] +==== The guards + +Each function checks its guards first, in the order of the table, and returns +before it reads a byte of the data; the last two rows are the failures of the +work itself: + +[cols="3,1"] +|=== +|Condition |Error + +|`make`: a key of another size than 32 bytes |`invalid_key_size` +|any other function: the object was moved from |`invalid_state` +|a nonce of another size than the family's, 12, 8 or 24 bytes |`invalid_iv_size` +|`open`: a tag of another size than 16 |`invalid_tag_size` +|a message longer than `max_message_size` |`message_too_long` +|`open`: the tag does not match |`authentication_failed` +|the backend fails where it should not |`backend_failure` +|=== diff --git a/doc/changelog.adoc b/doc/changelog.adoc index ad5f7312..07f933b2 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -22,7 +22,7 @@ of every version are on webcpp's index page. * Added backends::bearssl (AES-GCM alone, allocating nothing), backends::openssl via /webcpp/crypto//openssl natively and on WASI (allocating at make only, or natively in openssl_memory_resource with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE), and backends::ctaes (block cipher alone). * Added curves::secp256k1: key pairs, BIP340 and ECDSA signatures, ECDH, strict DER, low-S and the x-only tweak. * Added curves::ed25519 and curves::x25519 on libsodium: strict verification tabled on twelve edge cases, Ed25519ph over webcpp::hash's sha2_512 (/webcpp/crypto//crypto brings hash), the conversion, and agree refusing all-zero secrets. -* Added backends::sodium on /third_party//sodium, shared with webcpp::hash and initialised before every engine, and every backend's link-time canary and C suite. +* Added backends::sodium on /third_party//sodium, shared with webcpp::hash and initialised before every engine, every backend's link-time canary and C suite, and on it ciphers::aead's chacha20_poly1305, chacha20_poly1305_original and xchacha20_poly1305. * Added the page: a chapter per namespace and use case, the memory option's guide and example, tables generated from the tests, every Jamfile and message, and llms.txt. * Added supports_v, the capability table on the target being compiled, and the tags of its families and algorithms, which ciphers::gcm, the AES block cipher and secp256k1's key pair name. * Added secret, a self-wiping array that is copied only by clone, and the errors 13 to 20: memory_functions_refused, memory_functions_not_installed, weak_public_key, invalid_point, invalid_scalar, invalid_padding, invalid_encoding and invalid_ciphertext_size. diff --git a/doc/crypto.adoc b/doc/crypto.adoc index 57bfc8ee..c2e1ddb6 100644 --- a/doc/crypto.adoc +++ b/doc/crypto.adoc @@ -46,6 +46,8 @@ include::ciphers.adoc[] include::aead.adoc[] +include::chacha.adoc[] + include::block.adoc[] include::curves.adoc[] diff --git a/doc/generated/backends-chacha20_poly1305.adoc b/doc/generated/backends-chacha20_poly1305.adoc new file mode 100644 index 00000000..1557d860 --- /dev/null +++ b/doc/generated/backends-chacha20_poly1305.adoc @@ -0,0 +1,30 @@ +// 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 `+ciphers::chacha20_poly1305+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|libsodium +|`+/third_party//sodium+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+chacha_sodium+`, `+chacha_wycheproof_sodium+`, `+allocation_sodium+`) +|=== + +`+chacha20_poly1305<>+` names the default backend. The default per target, whatever the program links, as <> gives it with its reasons and tests: + +[cols="1,1",options="header"] +|=== +|Target |Default + +|native, wasip2, wasip3, emscripten +|libsodium +|=== diff --git a/doc/generated/backends-chacha20_poly1305_original.adoc b/doc/generated/backends-chacha20_poly1305_original.adoc new file mode 100644 index 00000000..5eb910ec --- /dev/null +++ b/doc/generated/backends-chacha20_poly1305_original.adoc @@ -0,0 +1,30 @@ +// 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 `+ciphers::chacha20_poly1305_original+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|libsodium +|`+/third_party//sodium+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+chacha_original_sodium+`, `+allocation_sodium+`) +|=== + +`+chacha20_poly1305_original<>+` names the default backend. The default per target, whatever the program links, as <> gives it with its reasons and tests: + +[cols="1,1",options="header"] +|=== +|Target |Default + +|native, wasip2, wasip3, emscripten +|libsodium +|=== diff --git a/doc/generated/backends-xchacha20_poly1305.adoc b/doc/generated/backends-xchacha20_poly1305.adoc new file mode 100644 index 00000000..eeba188c --- /dev/null +++ b/doc/generated/backends-xchacha20_poly1305.adoc @@ -0,0 +1,30 @@ +// 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 `+ciphers::xchacha20_poly1305+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|libsodium +|`+/third_party//sodium+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+xchacha_sodium+`, `+chacha_wycheproof_sodium+`, `+allocation_sodium+`) +|=== + +`+xchacha20_poly1305<>+` names the default backend. The default per target, whatever the program links, as <> gives it with its reasons and tests: + +[cols="1,1",options="header"] +|=== +|Target |Default + +|native, wasip2, wasip3, emscripten +|libsodium +|=== diff --git a/doc/generated/defaults.adoc b/doc/generated/defaults.adoc index 825b5f86..905edfc5 100644 --- a/doc/generated/defaults.adoc +++ b/doc/generated/defaults.adoc @@ -58,4 +58,22 @@ |libsodium |the only backend in this version, on every target; it refuses an all-zero shared secret itself (link:https://www.rfc-editor.org/rfc/rfc7748[RFC 7748, Elliptic Curves for Security (X25519 and X448)]) |`+x25519_sodium+`, `+default_backend_none_linked+` + +|ChaCha20-Poly1305 +|native, wasip2, wasip3, emscripten +|libsodium +|the only backend that has it: libsodium's own C code, the same on every target (link:https://doc.libsodium.org/secret-key_cryptography/aead/chacha20-poly1305[libsodium's ChaCha20-Poly1305 constructions]) +|`+chacha_sodium+`, `+default_backend_none_linked+` + +|original ChaCha20-Poly1305 +|native, wasip2, wasip3, emscripten +|libsodium +|the only backend that has it: libsodium's own C code, the same on every target (link:https://doc.libsodium.org/secret-key_cryptography/aead/chacha20-poly1305[libsodium's ChaCha20-Poly1305 constructions]) +|`+chacha_original_sodium+`, `+default_backend_none_linked+` + +|XChaCha20-Poly1305 +|native, wasip2, wasip3, emscripten +|libsodium +|the only backend that has it: libsodium's own C code, the same on every target (link:https://doc.libsodium.org/secret-key_cryptography/aead/chacha20-poly1305[libsodium's ChaCha20-Poly1305 constructions]) +|`+xchacha_sodium+`, `+default_backend_none_linked+` |=== diff --git a/doc/generated/matrix.adoc b/doc/generated/matrix.adoc index 6e13f2db..2c43feb1 100644 --- a/doc/generated/matrix.adoc +++ b/doc/generated/matrix.adoc @@ -115,6 +115,21 @@ |libsodium |native, wasip2, wasip3, emscripten |`+x25519_sodium+`, `+x25519_wycheproof_sodium+` + +|`+ciphers::chacha20_poly1305+` +|libsodium +|native, wasip2, wasip3, emscripten +|`+chacha_sodium+`, `+chacha_wycheproof_sodium+`, `+allocation_sodium+` + +|`+ciphers::chacha20_poly1305_original+` +|libsodium +|native, wasip2, wasip3, emscripten +|`+chacha_original_sodium+`, `+allocation_sodium+` + +|`+ciphers::xchacha20_poly1305+` +|libsodium +|native, wasip2, wasip3, emscripten +|`+xchacha_sodium+`, `+chacha_wycheproof_sodium+`, `+allocation_sodium+` |=== The same, by target: the backends each operation runs on. @@ -218,4 +233,22 @@ The same, by target: the backends each operation runs on. |libsodium |libsodium |libsodium + +|`+ciphers::chacha20_poly1305+` +|libsodium +|libsodium +|libsodium +|libsodium + +|`+ciphers::chacha20_poly1305_original+` +|libsodium +|libsodium +|libsodium +|libsodium + +|`+ciphers::xchacha20_poly1305+` +|libsodium +|libsodium +|libsodium +|libsodium |=== diff --git a/doc/generated/messages.adoc b/doc/generated/messages.adoc index b42dbf8c..f171d115 100644 --- a/doc/generated/messages.adoc +++ b/doc/generated/messages.adoc @@ -25,6 +25,12 @@ The fix: Name `+ciphers::aes256+`, include `+, . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. + - make: Makes an object under a key. + - seal: Seals a message in place: `data_bytes` holds the plaintext before and the ciphertext after. + - open: Opens a message in place: `data_bytes` holds the ciphertext before and the plaintext after. +- [ciphers::chacha20_poly1305_original](https://webcpporg.github.io/libs/crypto/#crypto-chacha): The original ChaCha20-Poly1305, authenticated encryption in place with an 8-byte nonce a counter numbers. Header , . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. + - make: Makes an object under a key. + - seal: Seals a message in place: `data_bytes` holds the plaintext before and the ciphertext after. + - open: Opens a message in place: `data_bytes` holds the ciphertext before and the plaintext after. +- [ciphers::xchacha20_poly1305](https://webcpporg.github.io/libs/crypto/#crypto-chacha): XChaCha20-Poly1305, authenticated encryption in place with a 24-byte nonce safe to draw at random. Header , . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. + - make: Makes an object under a key. + - seal: Seals a message in place: `data_bytes` holds the plaintext before and the ciphertext after. + - open: Opens a message in place: `data_bytes` holds the ciphertext before and the plaintext after. ## webcpp::crypto::curves @@ -85,6 +97,9 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - secp256k1, native, wasip2, wasip3, emscripten: libsecp256k1; the only backend ([libsecp256k1's README](https://github.com/bitcoin-core/secp256k1#readme)). - Ed25519, native, wasip2, wasip3, emscripten: libsodium; the only backend in this version, on every target, and its verification is the policy `strict` ([libsodium's documentation, public-key signatures](https://doc.libsodium.org/public-key_cryptography/public-key_signatures); [RFC 8032, the Edwards-curve Digital Signature Algorithm (EdDSA)](https://www.rfc-editor.org/rfc/rfc8032)). - X25519, native, wasip2, wasip3, emscripten: libsodium; the only backend in this version, on every target; it refuses an all-zero shared secret itself ([RFC 7748, Elliptic Curves for Security (X25519 and X448)](https://www.rfc-editor.org/rfc/rfc7748)). +- ChaCha20-Poly1305, native, wasip2, wasip3, emscripten: libsodium; the only backend that has it: libsodium's own C code, the same on every target ([libsodium's ChaCha20-Poly1305 constructions](https://doc.libsodium.org/secret-key_cryptography/aead/chacha20-poly1305)). +- original ChaCha20-Poly1305, native, wasip2, wasip3, emscripten: libsodium; the only backend that has it: libsodium's own C code, the same on every target ([libsodium's ChaCha20-Poly1305 constructions](https://doc.libsodium.org/secret-key_cryptography/aead/chacha20-poly1305)). +- XChaCha20-Poly1305, native, wasip2, wasip3, emscripten: libsodium; the only backend that has it: libsodium's own C code, the same on every target ([libsodium's ChaCha20-Poly1305 constructions](https://doc.libsodium.org/secret-key_cryptography/aead/chacha20-poly1305)). ## Rules of use diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 21019af2..e5af2a5f 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -75,7 +75,9 @@ "rfc8709": ["RFC 8709, Ed25519 and Ed448 public keys for SSH", "https://www.rfc-editor.org/rfc/rfc8709"], "signal-xeddsa": ["Signal, the XEdDSA and VXEdDSA signature schemes", "https://signal.org/docs/specifications/xeddsa/"], "tor-cert-spec": ["Tor's specifications, Ed25519 certificates", "https://spec.torproject.org/cert-spec.html"], - "solana-accounts": ["Solana's documentation, accounts and their Ed25519 keys", "https://solana.com/docs/core/accounts"] + "solana-accounts": ["Solana's documentation, accounts and their Ed25519 keys", "https://solana.com/docs/core/accounts"], + "rfc8439": ["RFC 8439, ChaCha20 and Poly1305 for IETF Protocols", "https://www.rfc-editor.org/rfc/rfc8439"], + "libsodium-aead": ["libsodium's ChaCha20-Poly1305 constructions", "https://doc.libsodium.org/secret-key_cryptography/aead/chacha20-poly1305"] }, "backends": { "bearssl": { @@ -355,6 +357,42 @@ "what": "The 32-byte shared secret of a secret key and a peer's public key, a `secret<32>`, refused with `weak_public_key` when it is all zero (a peer key of low order).", "section": "crypto-x25519", "backends": {"sodium": {"tests": ["x25519_sodium", "x25519_wycheproof_sodium"]}} + }, + { + "id": "chacha20_poly1305", + "family": "chacha20_poly1305", + "functions": ["make", "seal", "open"], + "namespace": "ciphers", + "api": "ciphers::chacha20_poly1305", + "header": ", ", + "what": "RFC 8439's ChaCha20-Poly1305, authenticated encryption in place with a 12-byte nonce.", + "section": "crypto-chacha", + "default": "`chacha20_poly1305<>` names the default backend.", + "backends": {"sodium": {"tests": ["chacha_sodium", "chacha_wycheproof_sodium", "allocation_sodium"]}} + }, + { + "id": "chacha20_poly1305_original", + "family": "chacha20_poly1305_original", + "functions": ["make", "seal", "open"], + "namespace": "ciphers", + "api": "ciphers::chacha20_poly1305_original", + "header": ", ", + "what": "The original ChaCha20-Poly1305, authenticated encryption in place with an 8-byte nonce a counter numbers.", + "section": "crypto-chacha", + "default": "`chacha20_poly1305_original<>` names the default backend.", + "backends": {"sodium": {"tests": ["chacha_original_sodium", "allocation_sodium"]}} + }, + { + "id": "xchacha20_poly1305", + "family": "xchacha20_poly1305", + "functions": ["make", "seal", "open"], + "namespace": "ciphers", + "api": "ciphers::xchacha20_poly1305", + "header": ", ", + "what": "XChaCha20-Poly1305, authenticated encryption in place with a 24-byte nonce safe to draw at random.", + "section": "crypto-chacha", + "default": "`xchacha20_poly1305<>` names the default backend.", + "backends": {"sodium": {"tests": ["xchacha_sodium", "chacha_wycheproof_sodium", "allocation_sodium"]}} } ], "families": [ @@ -448,6 +486,57 @@ "backends": { "sodium": {"targets": "all"} } + }, + { + "name": "chacha20_poly1305", + "title": "ChaCha20-Poly1305", + "group": "ciphers", + "since": "0.2", + "header": "", + "shown": "chacha20_poly1305", + "names": [ + {"name": "chacha20_poly1305", "title": "ChaCha20-Poly1305", "type": "ciphers::chacha20_poly1305<{backend}>"} + ], + "default": [ + {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": ["chacha_sodium", "default_backend_none_linked"], "why": "the only backend that has it: libsodium's own C code, the same on every target ({libsodium-aead})"} + ], + "backends": { + "sodium": {"targets": "all"} + } + }, + { + "name": "chacha20_poly1305_original", + "title": "original ChaCha20-Poly1305", + "group": "ciphers", + "since": "0.2", + "header": "", + "shown": "chacha20_poly1305_original", + "names": [ + {"name": "chacha20_poly1305_original", "title": "original ChaCha20-Poly1305", "type": "ciphers::chacha20_poly1305_original<{backend}>"} + ], + "default": [ + {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": ["chacha_original_sodium", "default_backend_none_linked"], "why": "the only backend that has it: libsodium's own C code, the same on every target ({libsodium-aead})"} + ], + "backends": { + "sodium": {"targets": "all"} + } + }, + { + "name": "xchacha20_poly1305", + "title": "XChaCha20-Poly1305", + "group": "ciphers", + "since": "0.2", + "header": "", + "shown": "xchacha20_poly1305", + "names": [ + {"name": "xchacha20_poly1305", "title": "XChaCha20-Poly1305", "type": "ciphers::xchacha20_poly1305<{backend}>"} + ], + "default": [ + {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": ["xchacha_sodium", "default_backend_none_linked"], "why": "the only backend that has it: libsodium's own C code, the same on every target ({libsodium-aead})"} + ], + "backends": { + "sodium": {"targets": "all"} + } } ], "rules": [ @@ -570,6 +659,7 @@ "openssl_old": "Name `/webcpp/crypto//openssl`, which builds OpenSSL 3.5.9; without b2, put OpenSSL 3's `include/` first.", "ctaes_not_linked": "Add `/third_party//ctaes`.", "sodium_not_linked": "Add `/third_party//sodium`.", + "chacha_default_not_linked": "The ChaCha20-Poly1305 AEADs' default is libsodium on every target: add `/third_party//sodium`.", "sodium_not_linked_on_emscripten": "Add `/third_party//sodium` to the program's sources.", "canary_sodium_other_commit": "Build the library at the commit of webcpp's submodule, or link it through b2.", "secp256k1_not_linked": "Add `/third_party//secp256k1`.", diff --git a/include/webcpp/crypto.hpp b/include/webcpp/crypto.hpp index 0dd1cb9c..fab012ff 100644 --- a/include/webcpp/crypto.hpp +++ b/include/webcpp/crypto.hpp @@ -6,9 +6,10 @@ /** Every header of webcpp::crypto that needs no backend, the header of each backend the build - links with the curves it holds (libsecp256k1's secp256k1, libsodium's Ed25519 and X25519), and + links with the curves it holds (libsecp256k1's secp256k1, libsodium's Ed25519 and X25519), `ciphers/aes256_gcm.hpp`, whose `aes128_gcm` and `aes256_gcm` name AES-GCM's default - backend: a program that does not link the default names another in the type, as + backend, and `ciphers/chacha20_poly1305.hpp`, whose AEADs name libsodium: a program that does + not link the default names another in the type, as `ciphers::gcm>` on WebAssembly. */ #ifndef WEBCPP_CRYPTO_HPP @@ -16,8 +17,10 @@ #include +#include #include #include +#include #include #include #include diff --git a/include/webcpp/crypto/backends/sodium.hpp b/include/webcpp/crypto/backends/sodium.hpp index 68d9693a..4e080eaf 100644 --- a/include/webcpp/crypto/backends/sodium.hpp +++ b/include/webcpp/crypto/backends/sodium.hpp @@ -22,12 +22,21 @@ #else #include +#include #include +#include #include #include // through /third_party//sodium, as webcpp::hash's header does +#include +#include +#include #include +#include +#include +#include +#include #include /** The canary's name, which every libsodium function of webcpp::crypto reads. */ @@ -68,6 +77,132 @@ namespace webcpp::crypto::detail { return {}; } +/** libsodium's detached functions of an AEAD family, which differ only by name. */ +template +struct sodium_aead_calls; + +/** RFC 8439's ChaCha20-Poly1305: libsodium's `_ietf` functions. */ +template <> +struct sodium_aead_calls { + /** Encrypts and computes the tag apart. */ + static constexpr auto encrypt = &crypto_aead_chacha20poly1305_ietf_encrypt_detached; + /** Checks the tag apart, then decrypts. */ + static constexpr auto decrypt = &crypto_aead_chacha20poly1305_ietf_decrypt_detached; +}; + +/** The original ChaCha20-Poly1305: libsodium's functions without a suffix. */ +template <> +struct sodium_aead_calls { + /** Encrypts and computes the tag apart. */ + static constexpr auto encrypt = &crypto_aead_chacha20poly1305_encrypt_detached; + /** Checks the tag apart, then decrypts. */ + static constexpr auto decrypt = &crypto_aead_chacha20poly1305_decrypt_detached; +}; + +/** XChaCha20-Poly1305: libsodium's `xchacha20poly1305_ietf` functions. */ +template <> +struct sodium_aead_calls { + /** Encrypts and computes the tag apart. */ + static constexpr auto encrypt = &crypto_aead_xchacha20poly1305_ietf_encrypt_detached; + /** Checks the tag apart, then decrypts. */ + static constexpr auto decrypt = &crypto_aead_xchacha20poly1305_ietf_decrypt_detached; +}; + +/** An AEAD's state on libsodium: the key, in the object, since libsodium takes it per call. */ +template + requires requires { sodium_aead_calls::encrypt; } +struct aead_state { + /** The key. */ + std::array key{}; +}; + +/** + * An AEAD on libsodium, one template for the three ChaCha20-Poly1305 families. libsodium's + * detached decryption checks the tag before it writes a byte, and zeroes the data when it + * does not match; `aead` zeroes it too. + */ +template + requires requires { sodium_aead_calls::encrypt; } +struct aead_engine { + /** The state. */ + using state = aead_state; + /** libsodium's functions of the family. */ + using calls = sodium_aead_calls; + + /** + * Initialises libsodium and keeps the key. + * + * @param s The state. + * @param key The key, 32 bytes (`aead` has checked its size). + * @return Nothing; `backend_failure` when libsodium cannot start. + */ + [[nodiscard]] static boost::system::result init( + state& s, std::span key) noexcept { + auto const ready = sodium_ready(); + if (!ready) { + return ready; + } + std::ranges::copy(key, s.key.begin()); + return {}; + } + + /** + * Encrypts `data` in place and writes the tag; libsodium reads the nonce and the + * additional data before it writes a byte of the ciphertext. + * + * @return Nothing; `backend_failure` when libsodium fails. + */ + [[nodiscard]] static boost::system::result seal( + state& s, std::span iv, std::span additional_data, + std::span data, boost::hash2::digest<16>& tag) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); + unsigned long long tag_length = 0; + auto* const bytes = writable(data); + // libsodium encrypts in place when the output is the input (its documented contract). + if (calls::encrypt(bytes, tag.data(), &tag_length, bytes, data.size(), + additional_data.data(), additional_data.size(), nullptr, iv.data(), + s.key.data()) != 0) { + return error::backend_failure; + } + return {}; + } + + /** + * Checks the tag, then decrypts `data` in place. + * + * @return Nothing; `authentication_failed` when the tag does not match. + */ + [[nodiscard]] static boost::system::result open( + state& s, std::span iv, std::span additional_data, + std::span data, std::array const& tag) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); + auto* const bytes = writable(data); + if (calls::decrypt(bytes, nullptr, bytes, data.size(), tag.data(), additional_data.data(), + additional_data.size(), iv.data(), s.key.data()) != 0) { + return error::authentication_failed; + } + return {}; + } + + /** Moves the key; the source is wiped. */ + static void move(state& to, state& from) noexcept { + to.key = from.key; + wipe_object(from.key); + } + + /** Wipes the key. */ + static void reset(state& s) noexcept { wipe_object(s.key); } + +private: + // The data's first byte, or one of the engine's own for an empty span, whose data() may be + // null: libsodium clears the output of a failed open with memset, which takes no null + // pointer, even for no byte. + static std::uint8_t* writable(std::span data) noexcept { + static std::uint8_t none = 0; + return data.empty() ? &none : data.data(); + } +}; + } // namespace webcpp::crypto::detail #endif // WEBCPP_CRYPTO_HAS_SODIUM diff --git a/include/webcpp/crypto/ciphers/aead.hpp b/include/webcpp/crypto/ciphers/aead.hpp new file mode 100644 index 00000000..88398337 --- /dev/null +++ b/include/webcpp/crypto/ciphers/aead.hpp @@ -0,0 +1,354 @@ +// 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) + +/** + `aead`, one-shot authenticated encryption in place, and the families it + takes: ChaCha20-Poly1305, its original form and XChaCha20-Poly1305. + + @see "ChaCha20-Poly1305", in the guide. +*/ +#ifndef WEBCPP_CRYPTO_CIPHERS_AEAD_HPP +#define WEBCPP_CRYPTO_CIPHERS_AEAD_HPP + +#include + +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace webcpp::crypto::families { + +/** RFC 8439's ChaCha20-Poly1305: a 32-byte key, a 12-byte nonce, a 16-byte tag. */ +struct chacha20_poly1305 { + /** The key's size. */ + static constexpr std::size_t key_size = 32; + /** The nonce's size, exactly (RFC 8439 section 2.8). */ + static constexpr std::size_t iv_size = 12; + /** The tag's size. */ + static constexpr std::size_t tag_size = 16; + /** The longest message, 2^38 - 64 bytes: ChaCha20's 32-bit block counter (section 2.8). */ + static constexpr std::uint64_t max_message_size = (std::uint64_t{1} << 38U) - 64; + /** The longest additional data, 2^64 - 1 bytes (section 2.8). */ + static constexpr std::uint64_t max_additional_data_size = ~std::uint64_t{0}; +}; + +/** + * The original ChaCha20-Poly1305, an 8-byte nonce and a 64-bit block counter, as libsodium's + * `crypto_aead_chacha20poly1305` has it. + */ +struct chacha20_poly1305_original { + /** The key's size. */ + static constexpr std::size_t key_size = 32; + /** The nonce's size, exactly. */ + static constexpr std::size_t iv_size = 8; + /** The tag's size. */ + static constexpr std::size_t tag_size = 16; + /** The longest message, 2^64 - 17 bytes. */ + static constexpr std::uint64_t max_message_size = ~std::uint64_t{0} - 16; + /** The longest additional data, 2^64 - 1 bytes. */ + static constexpr std::uint64_t max_additional_data_size = ~std::uint64_t{0}; +}; + +/** XChaCha20-Poly1305, a 24-byte nonce safe to draw at random. */ +struct xchacha20_poly1305 { + /** The key's size. */ + static constexpr std::size_t key_size = 32; + /** The nonce's size, exactly. */ + static constexpr std::size_t iv_size = 24; + /** The tag's size. */ + static constexpr std::size_t tag_size = 16; + /** The longest message, 2^64 - 17 bytes. */ + static constexpr std::uint64_t max_message_size = ~std::uint64_t{0} - 16; + /** The longest additional data, 2^64 - 1 bytes. */ + static constexpr std::uint64_t max_additional_data_size = ~std::uint64_t{0}; +}; + +} // namespace webcpp::crypto::families + +namespace webcpp::crypto::detail { + +/** + * What a `ciphers::aead` stores on a backend whose header does not specialise it: nothing, + * since its engine refuses the backend where the family is called. + */ +template +struct aead_state {}; + +/** + * The refusal of an AEAD family on a backend whose header does not specialise its engine: the + * primary refuses a type that is no AEAD family. + */ +template +struct aead_refusal { + static_assert(dependent_false, + "webcpp::crypto: ciphers::aead takes an AEAD family: " + "families::chacha20_poly1305, families::chacha20_poly1305_original or " + "families::xchacha20_poly1305."); +}; + +/** ChaCha20-Poly1305's refusal, which names what the program needs (`detail/capabilities.hpp`). */ +template +struct aead_refusal { + WEBCPP_CRYPTO_DETAIL_REFUSE_CHACHA20_POLY1305(Backend); +}; + +/** The original ChaCha20-Poly1305's refusal (see the first). */ +template +struct aead_refusal { + WEBCPP_CRYPTO_DETAIL_REFUSE_CHACHA20_POLY1305_ORIGINAL(Backend); +}; + +/** XChaCha20-Poly1305's refusal (see the first). */ +template +struct aead_refusal { + WEBCPP_CRYPTO_DETAIL_REFUSE_XCHACHA20_POLY1305(Backend); +}; + +/** + * An AEAD's engine on a backend whose header does not specialise it: the family's refusal. + * Its functions are never called: the refusal stops the build where the class is + * instantiated, and they keep the compiler from adding errors of their own after it; those + * that return report `backend_failure`, so that a path the refusal missed fails closed. + */ +template +struct aead_engine : aead_refusal { + /** Never called; fails closed. */ + template + [[nodiscard]] static boost::system::result init(Arguments&&... /*arguments*/) noexcept { + return error::backend_failure; + } + + /** Never called; fails closed. */ + template + [[nodiscard]] static boost::system::result seal(Arguments&&... /*arguments*/) noexcept { + return error::backend_failure; + } + + /** Never called; fails closed. */ + template + [[nodiscard]] static boost::system::result open(Arguments&&... /*arguments*/) noexcept { + return error::backend_failure; + } + + /** Never called. */ + template + static void move(Arguments&&... /*arguments*/) noexcept {} + + /** Never called. */ + template + static void reset(Arguments&&... /*arguments*/) noexcept {} +}; + +} // namespace webcpp::crypto::detail + +namespace webcpp::crypto::ciphers { + +/** + * An AEAD of the family `Family` on `Backend`, one shot: authenticated encryption in place, + * the tag apart. + * + * An object holds a key: it is used by one thread at a time. A nonce (the IV) is never + * repeated under one key: two messages under one key and one nonce reveal the XOR of their + * plaintexts and let an attacker forge tags. Drawn at random, ChaCha20-Poly1305's 12-byte + * nonce lets a key seal at most 2^32 messages, and the original's 8 bytes are too few: a + * counter numbers them. XChaCha20-Poly1305's 24-byte nonce is safe to draw at random. + * + * @tparam Family `families::chacha20_poly1305`, `families::chacha20_poly1305_original` or + * `families::xchacha20_poly1305`. + * @tparam Backend The backend; `ciphers::chacha20_poly1305<>` and its two siblings name the + * family's default. + */ +template +class aead { + using state_type = detail::aead_state; + using engine = detail::aead_engine; + +public: + /** The backend. */ + using backend_type = Backend; + /** The family of the capability table, which `supports_v` reads. */ + using family_type = Family; + /** The algorithm of the capability table: the family's own tag, its one algorithm. */ + using name_type = Family; + /** The tag, Boost.Hash2's digest of `tag_size` bytes. */ + using result_type = boost::hash2::digest; + /** The key's size. */ + static constexpr std::size_t key_size = Family::key_size; + /** The nonce's size, exactly. */ + static constexpr std::size_t iv_size = Family::iv_size; + /** The tag's size. */ + static constexpr std::size_t tag_size = Family::tag_size; + /** The longest message. */ + static constexpr std::uint64_t max_message_size = Family::max_message_size; + /** The longest additional data. */ + static constexpr std::uint64_t max_additional_data_size = Family::max_additional_data_size; + + /** + * Makes an object under a key. + * + * @param key_bytes `key_size` bytes. + * @return The object; `invalid_key_size`; `backend_failure` when the backend cannot start. + */ + [[nodiscard]] static boost::system::result make( + std::span key_bytes) noexcept { + if (key_bytes.size() != key_size) { + return error::invalid_key_size; + } + aead made_object; + auto const key_result = engine::init(made_object.state_, key_bytes); + if (!key_result) { + return key_result.error(); + } + made_object.keyed_ = true; + return made_object; + } + + /** + * Moves the key; the source is wiped and empty. + * + * Moving an empty object gives an empty one. + * + * @param moved_source The source, empty afterwards. + */ + aead(aead&& moved_source) noexcept : keyed_(std::exchange(moved_source.keyed_, false)) { + if (keyed_) { + engine::move(state_, moved_source.state_); + } + } + + /** + * Moves the key over this one, which is wiped first; an empty source gives an empty object. + * + * @param moved_source The source, empty afterwards. + * @return This object. + */ + aead& operator=(aead&& moved_source) noexcept { + if (this != &moved_source) { + engine::reset(state_); + keyed_ = std::exchange(moved_source.keyed_, false); + if (keyed_) { + engine::move(state_, moved_source.state_); + } + } + return *this; + } + + /** Not copyable: a key has one owner, which wipes it. */ + aead(aead const&) = delete; + /** Not copyable: a key has one owner, which wipes it. */ + aead& operator=(aead const&) = delete; + + /** Wipes the key. */ + ~aead() { engine::reset(state_); } + + /** + * Seals a message in place: `data_bytes` holds the plaintext before and the ciphertext + * after. + * + * The nonce and the additional data are read before the first byte of `data_bytes` is + * written, so they may lie in `data_bytes`. + * + * @param iv_bytes The nonce, `iv_size` bytes, never repeated under this key. + * @param additional_data_bytes Authenticated, not encrypted. + * @param data_bytes The message. + * @return The tag; `invalid_state` moved from; `invalid_iv_size`; `message_too_long`; + * `backend_failure`. + */ + [[nodiscard]] boost::system::result seal( + std::span iv_bytes, std::span additional_data_bytes, + std::span data_bytes) noexcept { + auto const guard_result = + guard_message(iv_bytes, additional_data_bytes, data_bytes.size(), tag_size); + if (!guard_result) { + return guard_result.error(); + } + result_type tag_bytes{}; + auto const seal_result = + engine::seal(state_, iv_bytes, additional_data_bytes, data_bytes, tag_bytes); + if (!seal_result) { + return seal_result.error(); + } + return tag_bytes; + } + + /** + * Opens a message in place: `data_bytes` holds the ciphertext before and the plaintext + * after. + * + * When the tag does not match, or the backend fails, `data_bytes` is zeroed; a guard's + * refusal leaves it untouched. + * + * @param iv_bytes The nonce of the seal. + * @param additional_data_bytes The additional data of the seal. + * @param data_bytes The ciphertext. + * @param tag_bytes The seal's tag, `tag_size` bytes, which may lie anywhere, `data_bytes` + * included. + * @return Nothing; `invalid_state` moved from; `invalid_iv_size`; `invalid_tag_size`; + * `message_too_long`; `authentication_failed`; `backend_failure`. + */ + [[nodiscard]] boost::system::result open( + std::span iv_bytes, std::span additional_data_bytes, + std::span data_bytes, std::span tag_bytes) noexcept { + auto const guard_result = + guard_message(iv_bytes, additional_data_bytes, data_bytes.size(), tag_bytes.size()); + if (!guard_result) { + return guard_result.error(); + } + // The tag may lie in data, which decryption overwrites: a copy is checked. + std::array expected_tag{}; + std::ranges::copy(tag_bytes, expected_tag.begin()); + auto const open_result = + engine::open(state_, iv_bytes, additional_data_bytes, data_bytes, expected_tag); + if (!open_result) { + detail::wipe(data_bytes.data(), data_bytes.size()); + return open_result.error(); + } + return {}; + } + +private: + aead() noexcept = default; + + // Every guard of a message, in the documented order: the state, the nonce, the tag + // (open's; seal passes tag_size), the lengths. None reads a byte of the spans. + [[nodiscard]] boost::system::result guard_message( + std::span iv_bytes, std::span additional_data_bytes, + std::size_t byte_count, std::size_t tag_bytes) const noexcept { + if (!keyed_) { + return error::invalid_state; + } + if (iv_bytes.size() != iv_size) { + return error::invalid_iv_size; + } + if (tag_bytes != tag_size) { + return error::invalid_tag_size; + } + if (detail::exceeds(byte_count, max_message_size) || + detail::exceeds(additional_data_bytes.size(), max_additional_data_size)) { + return error::message_too_long; + } + return {}; + } + + state_type state_{}; + bool keyed_ = false; +}; + +} // namespace webcpp::crypto::ciphers + +#endif // WEBCPP_CRYPTO_CIPHERS_AEAD_HPP diff --git a/include/webcpp/crypto/ciphers/chacha20_poly1305.hpp b/include/webcpp/crypto/ciphers/chacha20_poly1305.hpp new file mode 100644 index 00000000..bd7cd3b6 --- /dev/null +++ b/include/webcpp/crypto/ciphers/chacha20_poly1305.hpp @@ -0,0 +1,59 @@ +// 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) + +/** + `chacha20_poly1305`, `chacha20_poly1305_original` and `xchacha20_poly1305`, the + ChaCha20-Poly1305 AEADs of `aead`, each on its family's default backend unless the type names + another: libsodium on every target, whose header it includes when the program links it + (`default_backend_t`). A program that uses them without linking the default stops where it + calls them, with the Jamfile line that links it. + + @see "ChaCha20-Poly1305", in the guide. +*/ +#ifndef WEBCPP_CRYPTO_CIPHERS_CHACHA20_POLY1305_HPP +#define WEBCPP_CRYPTO_CIPHERS_CHACHA20_POLY1305_HPP + +#include + +#include +#include + +#if (defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_CHACHA20_POLY1305_SODIUM) || \ + defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_CHACHA20_POLY1305_ORIGINAL_SODIUM) || \ + defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_XCHACHA20_POLY1305_SODIUM)) && \ + defined(WEBCPP_CRYPTO_HAS_SODIUM) +#include +#endif + +namespace webcpp::crypto::ciphers { + +/** + * RFC 8439's ChaCha20-Poly1305: a 32-byte key, a 12-byte nonce, a 16-byte tag. + * + * @tparam Backend The backend; the default is the family's. + */ +template > +using chacha20_poly1305 = aead; + +/** + * The original ChaCha20-Poly1305: a 32-byte key, an 8-byte nonce, a 16-byte tag. + * + * @tparam Backend The backend; the default is the family's. + */ +template > +using chacha20_poly1305_original = aead; + +/** + * XChaCha20-Poly1305: a 32-byte key, a 24-byte nonce safe to draw at random, a 16-byte tag. + * + * @tparam Backend The backend; the default is the family's. + */ +template > +using xchacha20_poly1305 = aead; + +} // namespace webcpp::crypto::ciphers + +#endif // WEBCPP_CRYPTO_CIPHERS_CHACHA20_POLY1305_HPP diff --git a/include/webcpp/crypto/detail/capabilities.hpp b/include/webcpp/crypto/detail/capabilities.hpp index 5b60e472..1b66f490 100644 --- a/include/webcpp/crypto/detail/capabilities.hpp +++ b/include/webcpp/crypto/detail/capabilities.hpp @@ -41,6 +41,15 @@ struct ed25519; /** The family X25519, of `curves::x25519`, also the tag of its one algorithm. */ struct x25519; +/** The family ChaCha20-Poly1305, of `ciphers`, also the tag of its one algorithm. */ +struct chacha20_poly1305; + +/** The family original ChaCha20-Poly1305, of `ciphers`, also the tag of its one algorithm. */ +struct chacha20_poly1305_original; + +/** The family XChaCha20-Poly1305, of `ciphers`, also the tag of its one algorithm. */ +struct xchacha20_poly1305; + } // namespace webcpp::crypto::families namespace webcpp::crypto::tags { @@ -156,6 +165,21 @@ inline constexpr bool supported inline constexpr bool supported = true; #endif +// ChaCha20-Poly1305 on sodium: native, wasip2, wasip3, emscripten. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool supported = true; +#endif +// original ChaCha20-Poly1305 on sodium: native, wasip2, wasip3, emscripten. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool supported = true; +#endif +// XChaCha20-Poly1305 on sodium: native, wasip2, wasip3, emscripten. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool supported = true; +#endif // clang-format on /** @@ -396,6 +420,138 @@ inline constexpr bool linked = true; static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's X25519 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: X25519 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") #endif +#ifdef WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE +/** The refusals of the family ChaCha20-Poly1305's primary engine for `Backend`, on native. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_CHACHA20_POLY1305(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's ChaCha20-Poly1305 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: ChaCha20-Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_WASIP2) +/** The refusals of the family ChaCha20-Poly1305's primary engine for `Backend`, on wasip2. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_CHACHA20_POLY1305(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's ChaCha20-Poly1305 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: ChaCha20-Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_WASIP3) +/** The refusals of the family ChaCha20-Poly1305's primary engine for `Backend`, on wasip3. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_CHACHA20_POLY1305(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's ChaCha20-Poly1305 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: ChaCha20-Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_EMSCRIPTEN) +/** The refusals of the family ChaCha20-Poly1305's primary engine for `Backend`, on emscripten. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_CHACHA20_POLY1305(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's ChaCha20-Poly1305 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: ChaCha20-Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#endif +#ifdef WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE +/** + * The refusals of the family original ChaCha20-Poly1305's primary engine for `Backend`, on native. + */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_CHACHA20_POLY1305_ORIGINAL(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no original ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no original ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no original ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no original ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: original ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's original ChaCha20-Poly1305 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: original ChaCha20-Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_WASIP2) +/** + * The refusals of the family original ChaCha20-Poly1305's primary engine for `Backend`, on wasip2. + */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_CHACHA20_POLY1305_ORIGINAL(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no original ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no original ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no original ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no original ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: original ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's original ChaCha20-Poly1305 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: original ChaCha20-Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_WASIP3) +/** + * The refusals of the family original ChaCha20-Poly1305's primary engine for `Backend`, on wasip3. + */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_CHACHA20_POLY1305_ORIGINAL(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no original ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no original ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no original ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no original ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: original ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's original ChaCha20-Poly1305 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: original ChaCha20-Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_EMSCRIPTEN) +/** + * The refusals of the family original ChaCha20-Poly1305's primary engine for `Backend`, on + * emscripten. + */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_CHACHA20_POLY1305_ORIGINAL(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no original ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no original ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no original ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no original ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: original ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's original ChaCha20-Poly1305 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: original ChaCha20-Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#endif +#ifdef WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE +/** The refusals of the family XChaCha20-Poly1305's primary engine for `Backend`, on native. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_XCHACHA20_POLY1305(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no XChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no XChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no XChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no XChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: XChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's XChaCha20-Poly1305 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: XChaCha20-Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_WASIP2) +/** The refusals of the family XChaCha20-Poly1305's primary engine for `Backend`, on wasip2. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_XCHACHA20_POLY1305(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no XChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no XChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no XChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no XChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: XChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's XChaCha20-Poly1305 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: XChaCha20-Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_WASIP3) +/** The refusals of the family XChaCha20-Poly1305's primary engine for `Backend`, on wasip3. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_XCHACHA20_POLY1305(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no XChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no XChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no XChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no XChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: XChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's XChaCha20-Poly1305 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: XChaCha20-Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_EMSCRIPTEN) +/** The refusals of the family XChaCha20-Poly1305's primary engine for `Backend`, on emscripten. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_XCHACHA20_POLY1305(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no XChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no XChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no XChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no XChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: XChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's XChaCha20-Poly1305 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: XChaCha20-Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#endif // clang-format on #endif // WEBCPP_CRYPTO_DETAIL_CAPABILITIES_HPP diff --git a/include/webcpp/crypto/detail/defaults.hpp b/include/webcpp/crypto/detail/defaults.hpp index 5badf486..d21a7bd3 100644 --- a/include/webcpp/crypto/detail/defaults.hpp +++ b/include/webcpp/crypto/detail/defaults.hpp @@ -74,6 +74,30 @@ struct default_backend_of { /** `backends::sodium`. */ using type = backends::sodium; }; +/** Defined where libsodium is the default of ChaCha20-Poly1305. */ +#define WEBCPP_CRYPTO_DETAIL_DEFAULT_CHACHA20_POLY1305_SODIUM 1 +/** The default of ChaCha20-Poly1305 on native, wasip2, wasip3, emscripten: libsodium. */ +template <> +struct default_backend_of { + /** `backends::sodium`. */ + using type = backends::sodium; +}; +/** Defined where libsodium is the default of original ChaCha20-Poly1305. */ +#define WEBCPP_CRYPTO_DETAIL_DEFAULT_CHACHA20_POLY1305_ORIGINAL_SODIUM 1 +/** The default of original ChaCha20-Poly1305 on native, wasip2, wasip3, emscripten: libsodium. */ +template <> +struct default_backend_of { + /** `backends::sodium`. */ + using type = backends::sodium; +}; +/** Defined where libsodium is the default of XChaCha20-Poly1305. */ +#define WEBCPP_CRYPTO_DETAIL_DEFAULT_XCHACHA20_POLY1305_SODIUM 1 +/** The default of XChaCha20-Poly1305 on native, wasip2, wasip3, emscripten: libsodium. */ +template <> +struct default_backend_of { + /** `backends::sodium`. */ + using type = backends::sodium; +}; // clang-format on /** diff --git a/include/webcpp/crypto/detail/engines.hpp b/include/webcpp/crypto/detail/engines.hpp index 71b286f2..5dcf893e 100644 --- a/include/webcpp/crypto/detail/engines.hpp +++ b/include/webcpp/crypto/detail/engines.hpp @@ -41,12 +41,17 @@ struct gcm_state; /** The work of GCM on a backend (see @ref block_state). */ template struct gcm_engine; -/** What a `chacha20_poly1305` stores (see @ref block_state). */ -template -struct chacha_state; -/** The work of ChaCha20-Poly1305 on a backend (see @ref block_state). */ -template -struct chacha_engine; +/** What a `ciphers::aead` of the family `Family` stores (see @ref block_state). */ +template +struct aead_state; +/** + * The work of a `ciphers::aead` of the family `Family` on a backend, whose specialisation + * provides `init(state&, key)`, `seal(state&, iv, additional_data, data, tag&)`, + * `open(state&, iv, additional_data, data, tag const&)`, `move(to, from)` and `reset(state&)` + * (see @ref block_state). + */ +template +struct aead_engine; /** * Reads a backend's canary with a volatile load, which no linker can drop: a program built diff --git a/test/Jamfile b/test/Jamfile index 494570d5..20053d5c 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -33,7 +33,7 @@ webcpp.headers-alone crypto : ../include : crypto.hpp crypto/config.hpp crypto/detail/engines.hpp crypto/detail/entropy.hpp crypto/detail/limits.hpp crypto/detail/windows.hpp crypto/detail/wipe.hpp crypto/secret.hpp crypto/supports.hpp crypto/detail/capabilities.hpp crypto/detail/defaults.hpp - crypto/detail/heavy.hpp ; + crypto/detail/heavy.hpp crypto/ciphers/aead.hpp crypto/ciphers/chacha20_poly1305.hpp ; # The backend BearSSL's header and the default backend's, with BearSSL linked, # on every target. @@ -316,6 +316,19 @@ crypto-run x25519_wycheproof_sodium : x25519_wycheproof_sodium_test.cpp : /third_party//sodium /third_party//wycheproof /webcpp//boost_json ; +# The ChaCha20-Poly1305 AEADs on libsodium, their default on every target: each +# family's known answers and every check of support/aead_checks.hpp, natively +# the message's limit too; Wycheproof's vectors of ChaCha20-Poly1305 and +# XChaCha20-Poly1305; and nothing allocated. +crypto-run chacha_sodium : chacha_sodium_test.cpp : /third_party//sodium ; +crypto-run chacha_original_sodium : chacha_original_sodium_test.cpp + : /third_party//sodium ; +crypto-run xchacha_sodium : xchacha_sodium_test.cpp : /third_party//sodium ; +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 ; + # The capability table of doc/tables/crypto.json, which generate.py writes # this test from: supports_v of every cell on the target, and each present # cell made, with every backend the target builds linked. @@ -354,10 +367,12 @@ crypto-run agreement_gcm_portable : agreement_gcm_portable_test.cpp crypto-run windows_h_before : windows_h_before_test.cpp : /third_party//bearssl /webcpp/crypto//openssl /third_party//ctaes /third_party//secp256k1 + /third_party//sodium : native ; crypto-run windows_h_after : windows_h_after_test.cpp : /third_party//bearssl /webcpp/crypto//openssl /third_party//ctaes /third_party//secp256k1 + /third_party//sodium : native ; # The programs of the user's Jamfiles that the page shows, fixtures of diff --git a/test/allocation_sodium_test.cpp b/test/allocation_sodium_test.cpp new file mode 100644 index 00000000..f40fcc9f --- /dev/null +++ b/test/allocation_sodium_test.cpp @@ -0,0 +1,72 @@ +// 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) + +// On libsodium nothing allocates: make, seal and open of the three ChaCha20-Poly1305 AEADs, +// a failed open included, 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. Each later +// family on libsodium adds its calls here. + +#include +#include +#include + +#include "support/counting.hpp" + +#include + +#include +#include +#include +#include +#include + +namespace { + +namespace crypto = webcpp::crypto; + +/** Makes an AEAD, seals, opens, and opens a forged message: none of it allocates. */ +template +void expect_no_allocation() { + std::array key{}; + key.fill(3); + std::array const iv{}; + std::array const additional_data{}; + std::array data{}; + std::size_t const before = webcpp::test::allocations(); + { + auto made = Aead::make(key); + BOOST_TEST(made.has_value()); + auto const tag = made->seal(iv, additional_data, data); + BOOST_TEST(tag.has_value()); + BOOST_TEST(made->open(iv, additional_data, data, *tag).has_value()); + std::array const forged{}; + BOOST_TEST(made->open(iv, additional_data, data, forged).error() == + crypto::error::authentication_failed); + Aead const moved = std::move(*made); + } + BOOST_TEST_EQ(webcpp::test::allocations(), before); +} + +} // namespace + +int main() { + // The control: a malloc of the C library's moves the counter where it is counted. + std::size_t const control = webcpp::test::allocations(); + void* volatile block = std::malloc(40); + std::free(block); + // A constant condition: `if constexpr`, which MSVC's C4127 (an error under /W4 /WX) leaves be. + if constexpr (webcpp::test::c_allocations_counted) { + BOOST_TEST_EQ(webcpp::test::allocations() - control, 1U); + } else { + BOOST_TEST_EQ(webcpp::test::allocations() - control, 0U); + std::printf("the C library's allocations are not counted on this target\n"); + } + // libsodium's initialisation, the first make's, is counted too. + expect_no_allocation>(); + expect_no_allocation>(); + expect_no_allocation>(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/capabilities_test.cpp b/test/capabilities_test.cpp index 23576ba8..16e6129b 100644 --- a/test/capabilities_test.cpp +++ b/test/capabilities_test.cpp @@ -14,6 +14,7 @@ // does; and each family's refusal, parsed. #include +#include #include #include #include @@ -87,6 +88,24 @@ struct refuses_x25519 { WEBCPP_CRYPTO_DETAIL_REFUSE_X25519(Backend); }; +/** The refusals of ChaCha20-Poly1305, parsed: nothing instantiates it. */ +template +struct refuses_chacha20_poly1305 { + WEBCPP_CRYPTO_DETAIL_REFUSE_CHACHA20_POLY1305(Backend); +}; + +/** The refusals of original ChaCha20-Poly1305, parsed: nothing instantiates it. */ +template +struct refuses_chacha20_poly1305_original { + WEBCPP_CRYPTO_DETAIL_REFUSE_CHACHA20_POLY1305_ORIGINAL(Backend); +}; + +/** The refusals of XChaCha20-Poly1305, parsed: nothing instantiates it. */ +template +struct refuses_xchacha20_poly1305 { + WEBCPP_CRYPTO_DETAIL_REFUSE_XCHACHA20_POLY1305(Backend); +}; + } // namespace // clang-format off @@ -229,6 +248,48 @@ static_assert(crypto::supports_v, #else static_assert(!crypto::supports_v, backends::sodium>); #endif +// ChaCha20-Poly1305 on bearssl: none. +static_assert(!crypto::supports_v, backends::bearssl>); +// ChaCha20-Poly1305 on openssl: none. +static_assert(!crypto::supports_v, backends::openssl>); +// ChaCha20-Poly1305 on ctaes: none. +static_assert(!crypto::supports_v, backends::ctaes>); +// ChaCha20-Poly1305 on secp256k1: none. +static_assert(!crypto::supports_v, backends::secp256k1>); +// ChaCha20-Poly1305 on sodium: native, wasip2, wasip3, emscripten. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_v, backends::sodium>); +#else +static_assert(!crypto::supports_v, backends::sodium>); +#endif +// original ChaCha20-Poly1305 on bearssl: none. +static_assert(!crypto::supports_v, backends::bearssl>); +// original ChaCha20-Poly1305 on openssl: none. +static_assert(!crypto::supports_v, backends::openssl>); +// original ChaCha20-Poly1305 on ctaes: none. +static_assert(!crypto::supports_v, backends::ctaes>); +// original ChaCha20-Poly1305 on secp256k1: none. +static_assert(!crypto::supports_v, backends::secp256k1>); +// original ChaCha20-Poly1305 on sodium: native, wasip2, wasip3, emscripten. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_v, backends::sodium>); +#else +static_assert(!crypto::supports_v, backends::sodium>); +#endif +// XChaCha20-Poly1305 on bearssl: none. +static_assert(!crypto::supports_v, backends::bearssl>); +// XChaCha20-Poly1305 on openssl: none. +static_assert(!crypto::supports_v, backends::openssl>); +// XChaCha20-Poly1305 on ctaes: none. +static_assert(!crypto::supports_v, backends::ctaes>); +// XChaCha20-Poly1305 on secp256k1: none. +static_assert(!crypto::supports_v, backends::secp256k1>); +// XChaCha20-Poly1305 on sodium: native, wasip2, wasip3, emscripten. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_v, backends::sodium>); +#else +static_assert(!crypto::supports_v, backends::sodium>); +#endif // clang-format on int main() { @@ -280,6 +341,15 @@ int main() { #endif #if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN)) && defined(WEBCPP_CRYPTO_HAS_SODIUM) BOOST_TEST((webcpp::test::made, families::x25519, families::x25519, backends::sodium>())); +#endif +#if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN)) && defined(WEBCPP_CRYPTO_HAS_SODIUM) + BOOST_TEST((webcpp::test::made, families::chacha20_poly1305, families::chacha20_poly1305, backends::sodium>())); +#endif +#if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN)) && defined(WEBCPP_CRYPTO_HAS_SODIUM) + BOOST_TEST((webcpp::test::made, families::chacha20_poly1305_original, families::chacha20_poly1305_original, backends::sodium>())); +#endif +#if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN)) && defined(WEBCPP_CRYPTO_HAS_SODIUM) + BOOST_TEST((webcpp::test::made, families::xchacha20_poly1305, families::xchacha20_poly1305, backends::sodium>())); #endif // clang-format on return webcpp::test::exit_status(boost::report_errors()); diff --git a/test/chacha_original_sodium_test.cpp b/test/chacha_original_sodium_test.cpp new file mode 100644 index 00000000..50332f47 --- /dev/null +++ b/test/chacha_original_sodium_test.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) + +// The original ChaCha20-Poly1305, its 8-byte nonce, on libsodium, through its default type, +// ciphers::chacha20_poly1305_original<>: libsodium's own cases, every guard, tampering, moves, +// empty inputs and aliasing spans (support/aead_checks.hpp). Its limit, 2^64 - 17 bytes, no +// span reaches. + +#include +#include +#include + +#include "support/aead_checks.hpp" + +#include + +#include + +namespace crypto = webcpp::crypto; + +using original = crypto::ciphers::chacha20_poly1305_original<>; + +static_assert( + std::is_same_v, + crypto::backends::sodium>); +static_assert( + std::is_same_v>); +static_assert(std::is_same_v); +static_assert(std::is_same_v); +static_assert(crypto::supports_v); +static_assert(original::key_size == 32 && original::iv_size == 8 && original::tag_size == 16); +static_assert(original::max_message_size == ~std::uint64_t{0} - 16); + +int main() { + webcpp::test::check_aead(webcpp::test::chacha20_poly1305_original_cases); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/chacha_sodium_test.cpp b/test/chacha_sodium_test.cpp new file mode 100644 index 00000000..db034068 --- /dev/null +++ b/test/chacha_sodium_test.cpp @@ -0,0 +1,46 @@ +// 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) + +// ChaCha20-Poly1305 (RFC 8439) on libsodium, through its default type, +// ciphers::chacha20_poly1305<>, whose backend is libsodium on every target: RFC 8439's section +// 2.8.2 and appendix A.5 and libsodium's own case, every guard, tampering, moves, empty +// inputs and aliasing spans (support/aead_checks.hpp), and natively the message's limit. + +#include +#include +#include + +#include "support/aead_checks.hpp" + +#include + +#include + +namespace crypto = webcpp::crypto; + +using chacha = crypto::ciphers::chacha20_poly1305<>; + +// The default is libsodium on every target (the owner's answer Q4), and the type names its +// family and its algorithm as the capability table does. +static_assert(std::is_same_v, + crypto::backends::sodium>); +static_assert(std::is_same_v>); +static_assert(std::is_same_v); +static_assert(std::is_same_v); +static_assert(crypto::supports_v); +static_assert(chacha::key_size == 32 && chacha::iv_size == 12 && chacha::tag_size == 16); +static_assert(chacha::max_message_size == (std::uint64_t{1} << 38U) - 64); + +int main() { + webcpp::test::check_aead(webcpp::test::chacha20_poly1305_cases); +#if !defined(__wasi__) && !defined(__EMSCRIPTEN__) + if constexpr (sizeof(std::size_t) == 8) { + webcpp::test::check_aead_limits(); + } +#endif + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/chacha_wycheproof_sodium_test.cpp b/test/chacha_wycheproof_sodium_test.cpp new file mode 100644 index 00000000..606f445d --- /dev/null +++ b/test/chacha_wycheproof_sodium_test.cpp @@ -0,0 +1,29 @@ +// 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) + +// ChaCha20-Poly1305 and XChaCha20-Poly1305 on libsodium against Wycheproof's vectors, read at +// run time from third_party/libs/wycheproof (support/wycheproof_aead.hpp): of +// chacha20_poly1305_test.json's 325 tests, 256 valid, 60 invalid and 9 with a nonce of +// another size than 12 bytes; of xchacha20_poly1305_test.json's 315, 246 valid, 60 invalid +// and 9 with a nonce of another size than 24 bytes. + +#include +#include +#include + +#include "support/wycheproof_aead.hpp" + +#include + +int main() { + namespace ciphers = webcpp::crypto::ciphers; + using webcpp::crypto::backends::sodium; + webcpp::test::check_wycheproof_aead>( + "chacha20_poly1305_test.json", {.valid = 256, .invalid = 60, .other_iv = 9}); + webcpp::test::check_wycheproof_aead>( + "xchacha20_poly1305_test.json", {.valid = 246, .invalid = 60, .other_iv = 9}); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/default_backend_test.cpp b/test/default_backend_test.cpp index 4c4688ed..c54e8496 100644 --- a/test/default_backend_test.cpp +++ b/test/default_backend_test.cpp @@ -73,3 +73,23 @@ static_assert(std::is_same_v, backen #endif static_assert(crypto::detail::supported>); + +// The three ChaCha20-Poly1305 AEADs: libsodium, the only backend, on every target (the owner's +// answer Q4). +static_assert( + std::is_same_v, backends::sodium>); +static_assert(std::is_same_v, + backends::sodium>); +static_assert( + std::is_same_v, backends::sodium>); +static_assert(crypto::detail::supported); +static_assert(crypto::detail::supported); +static_assert(crypto::detail::supported); +#if !defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_CHACHA20_POLY1305_SODIUM) || \ + !defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_CHACHA20_POLY1305_ORIGINAL_SODIUM) || \ + !defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_XCHACHA20_POLY1305_SODIUM) +#error "chacha20_poly1305.hpp is not told to include libsodium's header" +#endif diff --git a/test/messages/Jamfile b/test/messages/Jamfile index fb3b8912..21a1324e 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -29,3 +29,4 @@ build-project ed25519_on_bearssl ; build-project ed25519ph_sha256 ; build-project ed25519_default_not_linked ; build-project heavy_without_threads ; +build-project chacha_default_not_linked ; diff --git a/test/messages/chacha_default_not_linked/Jamfile b/test/messages/chacha_default_not_linked/Jamfile new file mode 100644 index 00000000..7f0fdc2b --- /dev/null +++ b/test/messages/chacha_default_not_linked/Jamfile @@ -0,0 +1,12 @@ +# 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 ; + +webcpp.compile-diagnostic chacha_default_not_linked : chacha_default_not_linked.cpp + : : native wasip2 wasip3 ; diff --git a/test/messages/chacha_default_not_linked/chacha_default_not_linked.cpp b/test/messages/chacha_default_not_linked/chacha_default_not_linked.cpp new file mode 100644 index 00000000..1da936ea --- /dev/null +++ b/test/messages/chacha_default_not_linked/chacha_default_not_linked.cpp @@ -0,0 +1,32 @@ +// 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 program that calls the three ChaCha20-Poly1305 AEADs on their default backend, libsodium +// on every target, without linking it, stops where it calls each, with the line that links +// libsodium (design D32; ruling C20). + +// 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/ciphers/aead.hpp:* {{webcpp::crypto: ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)}} +// expected-error@webcpp/crypto/ciphers/aead.hpp:* {{webcpp::crypto: original ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)}} +// expected-error@webcpp/crypto/ciphers/aead.hpp:* {{webcpp::crypto: XChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)}} +// clang-format on + +#include + +#include +#include + +int main() { + namespace ciphers = webcpp::crypto::ciphers; + std::array const key{}; + return ciphers::chacha20_poly1305<>::make(key) && + ciphers::chacha20_poly1305_original<>::make(key) && + ciphers::xchacha20_poly1305<>::make(key) + ? 0 + : 1; +} diff --git a/test/support/aead_checks.hpp b/test/support/aead_checks.hpp new file mode 100644 index 00000000..6b194f5d --- /dev/null +++ b/test/support/aead_checks.hpp @@ -0,0 +1,584 @@ +// 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 checks of a ciphers::aead on one family and backend: the family's known answers, every +// guard in its order (the state, the IV's size, the tag's size, the length) each leaving the +// data untouched, tampering with every byte of the ciphertext, the tag, the additional data +// and the IV, each failing with authentication_failed and the data zeroed, moves of empty +// objects, empty inputs, and spans that touch or overlap (the genesis's Review Focus 2, 3 +// and 6). +// +// The known answers: RFC 8439's section 2.8.2 and appendix A.5 for ChaCha20-Poly1305, the +// XChaCha draft's appendix A.3.1 for XChaCha20-Poly1305, and the cases of libsodium's own +// tests (test/default/aead_chacha20poly1305.exp and aead_xchacha20poly1305.exp) for the +// three. + +#ifndef WEBCPP_TEST_CRYPTO_SUPPORT_AEAD_CHECKS_HPP +#define WEBCPP_TEST_CRYPTO_SUPPORT_AEAD_CHECKS_HPP + +#include "gcm_checks.hpp" +#include "hex.hpp" + +#if !defined(__wasi__) && !defined(__EMSCRIPTEN__) +#include "reserved.hpp" +#endif + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::test { + +/** One known answer of an AEAD, every field in hex. */ +struct aead_case { + /** The key. */ + std::string_view key; + /** The IV (the nonce). */ + std::string_view iv; + /** The additional data. */ + std::string_view additional_data; + /** The plaintext. */ + std::string_view plaintext; + /** The ciphertext. */ + std::string_view ciphertext; + /** The tag. */ + std::string_view tag; +}; + +/** "Ladies and Gentlemen of the class of '99: ...", the plaintext of RFC 8439 section 2.8.2. */ +inline constexpr std::string_view sunscreen = + "4c616469657320616e642047656e746c656d656e206f662074686520636c617373206f66202739393a20" + "4966204920636f756c64206f6666657220796f75206f6e6c79206f6e652074697020666f722074686520" + "6675747572652c2073756e73637265656e20776f756c642062652069742e"; + +/** + * ChaCha20-Poly1305's known answers: RFC 8439 section 2.8.2, appendix A.5, and libsodium's + * second case, section 2.8.2's without the additional data. + */ +inline constexpr std::array chacha20_poly1305_cases{ + aead_case{ + .key = "808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f", + .iv = "070000004041424344454647", + .additional_data = "50515253c0c1c2c3c4c5c6c7", + .plaintext = sunscreen, + .ciphertext = + "d31a8d34648e60db7b86afbc53ef7ec2a4aded51296e08fea9e2b5a736ee62d63dbea45e8ca9671282fa" + "fb69da92728b1a71de0a9e060b2905d6a5b67ecd3b3692ddbd7f2d778b8c9803aee328091b58fab324e4" + "fad675945585808b4831d7bc3ff4def08e4b7a9de576d26586cec64b6116", + .tag = "1ae10b594f09e26a7e902ecbd0600691", + }, + aead_case{ + .key = "1c9240a5eb55d38af333888604f6b5f0473917c1402b80099dca5cbc207075c0", + .iv = "000000000102030405060708", + .additional_data = "f33388860000000000004e91", + .plaintext = + "496e7465726e65742d4472616674732061726520647261667420646f63756d656e74732076616c696420" + "666f722061206d6178696d756d206f6620736978206d6f6e74687320616e64206d617920626520757064" + "617465642c207265706c616365642c206f72206f62736f6c65746564206279206f7468657220646f6375" + "6d656e747320617420616e792074696d652e20497420697320696e617070726f70726961746520746f20" + "75736520496e7465726e65742d447261667473206173207265666572656e6365206d6174657269616c20" + "6f7220746f2063697465207468656d206f74686572207468616e206173202fe2809c776f726b20696e20" + "70726f67726573732e2fe2809d", + .ciphertext = + "64a0861575861af460f062c79be643bd5e805cfd345cf389f108670ac76c8cb24c6cfc18755d43eea09e" + "e94e382d26b0bdb7b73c321b0100d4f03b7f355894cf332f830e710b97ce98c8a84abd0b948114ad176e" + "008d33bd60f982b1ff37c8559797a06ef4f0ef61c186324e2b3506383606907b6a7c02b0f9f6157b53c8" + "67e4b9166c767b804d46a59b5216cde7a4e99040c5a40433225ee282a1b0a06c523eaf4534d7f83fa115" + "5b0047718cbc546a0d072b04b3564eea1b422273f548271a0bb2316053fa76991955ebd63159434ecebb" + "4e466dae5a1073a6727627097a1049e617d91d361094fa68f0ff77987130305beaba2eda04df997b714d" + "6c6f2c29a6ad5cb4022b02709b", + .tag = "eead9d67890cbb22392336fea1851f38", + }, + aead_case{ + .key = "808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f", + .iv = "070000004041424344454647", + .additional_data = "", + .plaintext = sunscreen, + .ciphertext = + "d31a8d34648e60db7b86afbc53ef7ec2a4aded51296e08fea9e2b5a736ee62d63dbea45e8ca9671282fa" + "fb69da92728b1a71de0a9e060b2905d6a5b67ecd3b3692ddbd7f2d778b8c9803aee328091b58fab324e4" + "fad675945585808b4831d7bc3ff4def08e4b7a9de576d26586cec64b6116", + .tag = "6a23a4681fd59456aea1d29f82477216", + }, +}; + +/** + * The original ChaCha20-Poly1305's known answers: libsodium's two, with and without the + * additional data. + */ +inline constexpr std::array chacha20_poly1305_original_cases{ + aead_case{ + .key = "4290bcb154173531f314af57f3be3b5006da371ece272afa1b5dbdd1100a1007", + .iv = "cd7cf67be39c794a", + .additional_data = "87e229d4500845a079c0", + .plaintext = "86d09974840bded2a5ca", + .ciphertext = "e3e446f7ede9a19b62a4", + .tag = "677dabf4e3d24b876bb284753896e1d6", + }, + aead_case{ + .key = "4290bcb154173531f314af57f3be3b5006da371ece272afa1b5dbdd1100a1007", + .iv = "cd7cf67be39c794a", + .additional_data = "", + .plaintext = "86d09974840bded2a5ca", + .ciphertext = "e3e446f7ede9a19b62a4", + .tag = "69e7789bcd954e658ed38423e23161dc", + }, +}; + +/** + * XChaCha20-Poly1305's known answers: the draft's appendix A.3.1, and libsodium's two, with + * and without the additional data. + */ +inline constexpr std::array xchacha20_poly1305_cases{ + aead_case{ + .key = "808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f", + .iv = "404142434445464748494a4b4c4d4e4f5051525354555657", + .additional_data = "50515253c0c1c2c3c4c5c6c7", + .plaintext = sunscreen, + .ciphertext = + "bd6d179d3e83d43b9576579493c0e939572a1700252bfaccbed2902c21396cbb731c7f1b0b4aa6440bf3" + "a82f4eda7e39ae64c6708c54c216cb96b72e1213b4522f8c9ba40db5d945b11b69b982c1bb9e3f3fac2b" + "c369488f76b2383565d3fff921f9664c97637da9768812f615c68b13b52e", + .tag = "c0875924c1c7987947deafd8780acf49", + }, + aead_case{ + .key = "808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f", + .iv = "07000000404142434445464748494a4b4c4d4e4f50515253", + .additional_data = "50515253c0c1c2c3c4c5c6c7", + .plaintext = sunscreen, + .ciphertext = + "f8ebea4875044066fc162a0604e171feecfb3d20425248563bcfd5a155dcc47bbda70b86e5ab9b55002b" + "d1274c02db35321acd7af8b2e2d25015e136b7679458e9f43243bf719d639badb5feac03f80a19a96ef1" + "0cb1d15333a837b90946ba3854ee74da3f2585efc7e1e170e17e15e563e7", + .tag = "7601f4f85cafa8e5877614e143e68420", + }, + aead_case{ + .key = "808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f", + .iv = "07000000404142434445464748494a4b4c4d4e4f50515253", + .additional_data = "", + .plaintext = sunscreen, + .ciphertext = + "f8ebea4875044066fc162a0604e171feecfb3d20425248563bcfd5a155dcc47bbda70b86e5ab9b55002b" + "d1274c02db35321acd7af8b2e2d25015e136b7679458e9f43243bf719d639badb5feac03f80a19a96ef1" + "0cb1d15333a837b90946ba3854ee74da3f2585efc7e1e170e17e15e563e7", + .tag = "e096e033d91b63f7ac92e9972e0d43e5", + }, +}; + +/** A key of the AEAD's size, its bytes counting up from `first`. */ +template +std::array aead_key(std::uint8_t first = 1) { + std::array key{}; + for (std::size_t i = 0; i < key.size(); ++i) { + key[i] = static_cast(first + i); + } + return key; +} + +/** Seals and opens each known answer, and checks ciphertext and tag. */ +template +void check_aead_cases(std::span cases) { + for (auto const& c : cases) { + auto made = Aead::make(from_hex(c.key)); + if (!BOOST_TEST(made.has_value())) { + continue; + } + auto const iv = from_hex(c.iv); + auto const additional_data = from_hex(c.additional_data); + auto const plaintext = from_hex(c.plaintext); + auto const tag = from_hex(c.tag); + auto data = plaintext; + auto const sealed = made->seal(iv, additional_data, data); + BOOST_TEST(sealed.has_value()); + BOOST_TEST_EQ(to_hex(data), c.ciphertext); + BOOST_TEST(sealed && crypto::equal(*sealed, std::span(tag))); + BOOST_TEST(made->open(iv, additional_data, data, tag).has_value()); + BOOST_TEST_EQ(to_hex(data), c.plaintext); + } +} + +/** + * Every guard but the length's, in its order: the key's size; the state before the IV and the + * tag; the IV's size before the tag's. Each refusal leaves the data untouched. + */ +template +void check_aead_guards() { + for (std::size_t const size : {std::size_t{0}, Aead::key_size - 1, Aead::key_size + 1}) { + std::vector const wrong_key(size, 7); + BOOST_TEST(Aead::make(wrong_key).error() == crypto::error::invalid_key_size); + } + auto made = Aead::make(aead_key()); + if (!BOOST_TEST(made.has_value())) { + return; + } + std::array data{}; + data.fill(0x33); + auto const untouched = data; + std::vector const iv(Aead::iv_size, 9); + std::array const tag{}; + // Every IV size but the family's: none, one byte less and more, and the other families'. + std::array const sizes{0, Aead::iv_size - 1, Aead::iv_size + 1, 8, 12, 24}; + for (std::size_t const size : sizes) { + if (size == Aead::iv_size) { + continue; + } + std::vector const wrong_iv(size, 9); + BOOST_TEST(made->seal(wrong_iv, {}, data).error() == crypto::error::invalid_iv_size); + BOOST_TEST(made->open(wrong_iv, {}, data, tag).error() == crypto::error::invalid_iv_size); + } + for (std::size_t const size : {std::size_t{0}, Aead::tag_size - 1, Aead::tag_size + 1}) { + std::vector const wrong_tag(size); + BOOST_TEST(made->open(iv, {}, data, wrong_tag).error() == crypto::error::invalid_tag_size); + } + // The IV is checked before the tag: both wrong gives the IV's error. + BOOST_TEST(made->open({}, {}, data, std::span(tag).first(Aead::tag_size - 1)).error() == + crypto::error::invalid_iv_size); + BOOST_TEST(data == untouched); + // The state is checked before the IV and the tag. + Aead const moved = std::move(*made); + BOOST_TEST(made->seal({}, {}, data).error() == crypto::error::invalid_state); + BOOST_TEST(made->open({}, {}, data, {}).error() == crypto::error::invalid_state); + BOOST_TEST(data == untouched); +} + +/** An open of a changed message fails with authentication_failed and zeroes the data. */ +template +void expect_aead_tampered(Aead& made, std::span iv, + std::span additional_data, + std::span data, std::span tag) { + BOOST_TEST(made.open(iv, additional_data, data, tag).error() == + crypto::error::authentication_failed); + BOOST_TEST(all_zero(data)); +} + +/** + * Changing any byte of the ciphertext, the tag, the additional data or the IV of a known + * answer fails, and zeroes the data; so does a ciphertext one byte shorter. The object works + * after the failures. + */ +template +void check_aead_tampering(aead_case const& c) { + auto const key = from_hex(c.key); + auto const iv = from_hex(c.iv); + auto const additional_data = from_hex(c.additional_data); + auto const ciphertext = from_hex(c.ciphertext); + auto const tag = from_hex(c.tag); + auto made = Aead::make(key); + if (!BOOST_TEST(made.has_value()) || !BOOST_TEST(!ciphertext.empty()) || + !BOOST_TEST(!additional_data.empty())) { + return; + } + for (std::size_t i = 0; i < ciphertext.size(); ++i) { + auto data = ciphertext; + data[i] ^= 1U; + expect_aead_tampered(*made, iv, additional_data, data, tag); + } + for (std::size_t i = 0; i < tag.size(); ++i) { + auto data = ciphertext; + auto bad = tag; + bad[i] ^= 0x80U; + expect_aead_tampered(*made, iv, additional_data, data, bad); + } + for (std::size_t i = 0; i < additional_data.size(); ++i) { + auto data = ciphertext; + auto bad = additional_data; + bad[i] ^= 2U; + expect_aead_tampered(*made, iv, bad, data, tag); + } + for (std::size_t i = 0; i < iv.size(); ++i) { + auto data = ciphertext; + auto bad = iv; + bad[i] ^= 4U; + expect_aead_tampered(*made, bad, additional_data, data, tag); + } + { + auto data = ciphertext; + expect_aead_tampered(*made, iv, additional_data, std::span(data).first(data.size() - 1), + tag); + } + // Without its additional data, the message does not open either. + { + auto data = ciphertext; + expect_aead_tampered(*made, iv, {}, data, tag); + } + auto data = ciphertext; + BOOST_TEST(made->open(iv, additional_data, data, tag).has_value()); + BOOST_TEST_EQ(to_hex(data), c.plaintext); +} + +/** Every call of an empty AEAD is refused with invalid_state, and leaves the data untouched. */ +template +void expect_aead_refused(Aead& empty, std::span iv, + std::span data, std::span tag, + std::span untouched) { + BOOST_TEST(empty.seal(iv, {}, data).error() == crypto::error::invalid_state); + BOOST_TEST(empty.open(iv, {}, data, tag).error() == crypto::error::invalid_state); + BOOST_TEST(empty.seal(iv, {}, {}).error() == crypto::error::invalid_state); + BOOST_TEST(empty.open(iv, {}, {}, tag).error() == crypto::error::invalid_state); + BOOST_TEST(std::ranges::equal(data, untouched)); +} + +/** + * Moves (Review Focus 6): a moved-from AEAD answers invalid_state to everything but assignment + * and destruction; moving it, empty, gives an empty one; the destination, a swap and an + * assignment back carry the key; a self-move keeps it. + */ +template +void check_aead_moves(aead_case const& c) { + auto const iv = from_hex(c.iv); + auto const additional_data = from_hex(c.additional_data); + auto const plaintext = from_hex(c.plaintext); + auto made = Aead::make(from_hex(c.key)); + if (!BOOST_TEST(made.has_value())) { + return; + } + // Seals the case's plaintext with an AEAD, which gives the case's ciphertext and tag. + auto const seals_the_case = [&](Aead& aead) { + auto data = plaintext; + auto const sealed = aead.seal(iv, additional_data, data); + return sealed && to_hex(data) == c.ciphertext && to_hex(*sealed) == c.tag; + }; + Aead moved = std::move(*made); + std::array const tag{}; + std::array data{}; + data.fill(0x6c); // a guard's refusal leaves this pattern, not only zeroes, untouched + auto const untouched = data; + auto const all_refused = [&](Aead& empty) { + expect_aead_refused(empty, iv, data, tag, untouched); + }; + all_refused(*made); + BOOST_TEST(seals_the_case(moved)); + // Moving an object that was moved from gives an empty object. + Aead again = std::move(*made); + all_refused(again); + all_refused(*made); + again = std::move(*made); + all_refused(again); + all_refused(*made); + // A swap of an empty object and a live one moves the key, both ways. + std::swap(again, moved); + BOOST_TEST(seals_the_case(again)); + all_refused(moved); + std::swap(again, moved); + BOOST_TEST(seals_the_case(moved)); + all_refused(again); + // An assignment over a live object from an empty one leaves it empty. + auto other = Aead::make(from_hex(c.key)); + if (!BOOST_TEST(other.has_value())) { + return; + } + *other = std::move(again); + all_refused(*other); + // An assignment back makes the source whole again. + *made = std::move(moved); + BOOST_TEST(seals_the_case(*made)); + all_refused(moved); + // A self-move-assignment leaves the key in place. + auto& self = *made; + *made = std::move(self); + BOOST_TEST(seals_the_case(*made)); +} + +/** + * Empty inputs (Review Focus 3): an empty message and empty additional data, through spans + * whose data() is null, seal and open; a zero tag does not open them; each of the two empty + * alone seals and opens. + */ +template +void check_aead_empty(Aead& made, std::span iv) { + auto const empty = made.seal(iv, std::span(), std::span()); + BOOST_TEST(empty.has_value()); + BOOST_TEST(empty && made.open(iv, {}, std::span(), *empty).has_value()); + std::array const zero_tag{}; + BOOST_TEST(made.open(iv, {}, std::span(), zero_tag).error() == + crypto::error::authentication_failed); + std::array const additional_data{1, 2, 3, 4, 5}; + auto const only_additional = made.seal(iv, additional_data, std::span()); + BOOST_TEST(only_additional && empty && !crypto::equal(*only_additional, *empty)); + BOOST_TEST( + only_additional && + made.open(iv, additional_data, std::span(), *only_additional).has_value()); + BOOST_TEST(only_additional && + made.open(iv, {}, std::span(), *only_additional).error() == + crypto::error::authentication_failed); + std::array data{}; + data.fill(0x42); + auto const original = data; + auto const only_data = made.seal(iv, {}, data); + BOOST_TEST(only_data.has_value() && data != original); + BOOST_TEST(only_data && made.open(iv, {}, data, *only_data).has_value()); + BOOST_TEST(data == original); +} + +/** A tag right after the data in one buffer: the open leaves the tag's bytes as they were. */ +template +void check_aead_wire_tag(Aead& made, std::span iv) { + std::array wire{}; + std::fill(wire.begin(), wire.begin() + 16, 0x33); + auto const sealed = made.seal(iv, {}, std::span(wire).first(16)); + if (!BOOST_TEST(sealed.has_value())) { + return; + } + std::ranges::copy(*sealed, wire.begin() + 16); + BOOST_TEST(made.open(iv, {}, std::span(wire).first(16), std::span(wire).last(Aead::tag_size)) + .has_value()); + BOOST_TEST( + std::all_of(wire.begin(), wire.begin() + 16, [](std::uint8_t b) { return b == 0x33; })); + BOOST_TEST(std::equal(sealed->begin(), sealed->end(), wire.begin() + 16)); +} + +/** + * A tag that overlaps the data's end fails cleanly (Review Focus 2): the data is zeroed, and + * the bytes after the data, which only the tag covers, are as they were. + */ +template +void check_aead_overlap(Aead& made, std::span iv) { + std::array overlap{}; + overlap.fill(0x5a); + BOOST_TEST( + made.open(iv, {}, std::span(overlap).first(20), std::span(overlap).last(Aead::tag_size)) + .error() == crypto::error::authentication_failed); + BOOST_TEST(all_zero(std::span(overlap).first(20))); + BOOST_TEST( + std::all_of(overlap.begin() + 20, overlap.end(), [](std::uint8_t b) { return b == 0x5a; })); +} + +/** + * An IV and additional data inside the sealed buffer itself give what copies of them give: + * both are read before the first byte of the data is written. + */ +template +void check_aead_in_place(Aead& made) { + constexpr std::size_t additional_size = 16; + std::array buffer{}; + for (std::size_t i = 0; i < buffer.size(); ++i) { + buffer[i] = static_cast((i * 7) + 1); + } + std::array iv_copy{}; + std::array additional_copy{}; + auto data_copy = buffer; + std::copy_n(buffer.begin(), Aead::iv_size, iv_copy.begin()); + std::copy_n(buffer.begin() + Aead::iv_size, additional_size, additional_copy.begin()); + auto const expected = made.seal(iv_copy, additional_copy, data_copy); + auto const in_place = + made.seal(std::span(buffer).first(Aead::iv_size), + std::span(buffer).subspan(Aead::iv_size, additional_size), buffer); + BOOST_TEST(expected && in_place && to_hex(*expected) == to_hex(*in_place)); + BOOST_TEST(data_copy == buffer); +} + +/** + * A wire buffer [IV | additional data | ciphertext], opened in place with spans into it, gives + * what an open of copies gives, and leaves the IV and the additional data as they were. + */ +template +void check_aead_wire_open(Aead& made) { + constexpr std::size_t additional_size = 16; + std::array wire_iv{}; + std::array wire_additional{}; + std::array wire_plain{}; + for (std::size_t i = 0; i < wire_plain.size(); ++i) { + wire_plain[i] = static_cast((i * 11) + 3); + } + wire_iv.fill(0x17); + wire_additional.fill(0x29); + auto wire_data = wire_plain; + auto const wire_sealed = made.seal(wire_iv, wire_additional, wire_data); + if (!BOOST_TEST(wire_sealed.has_value())) { + return; + } + constexpr std::size_t data_at = Aead::iv_size + additional_size; + std::array message{}; + std::ranges::copy(wire_iv, message.begin()); + std::ranges::copy(wire_additional, message.begin() + Aead::iv_size); + std::ranges::copy(wire_data, message.begin() + data_at); + auto copy_data = wire_data; + BOOST_TEST(made.open(wire_iv, wire_additional, copy_data, *wire_sealed).has_value()); + BOOST_TEST(made.open(std::span(message).first(Aead::iv_size), + std::span(message).subspan(Aead::iv_size, additional_size), + std::span(message).subspan(data_at), *wire_sealed) + .has_value()); + BOOST_TEST(std::equal(copy_data.begin(), copy_data.end(), message.begin() + data_at)); + BOOST_TEST(copy_data == wire_plain); + BOOST_TEST(std::equal(wire_iv.begin(), wire_iv.end(), message.begin())); + BOOST_TEST(std::equal(wire_additional.begin(), wire_additional.end(), + message.begin() + Aead::iv_size)); +} + +/** Empty inputs, and spans that touch or overlap (Review Focus 2 and 3). */ +template +void check_aead_edges() { + auto made = Aead::make(aead_key()); + if (!BOOST_TEST(made.has_value())) { + return; + } + std::array iv{}; + iv.fill(0x24); + check_aead_empty(*made, iv); + check_aead_wire_tag(*made, iv); + check_aead_overlap(*made, iv); + check_aead_in_place(*made); + check_aead_wire_open(*made); +} + +/** Every check of this file on one AEAD, against the family's known answers. */ +template +void check_aead(std::span cases) { + check_aead_cases(cases); + check_aead_guards(); + check_aead_tampering(cases.front()); + check_aead_moves(cases.front()); + check_aead_edges(); +} + +#if !defined(__wasi__) && !defined(__EMSCRIPTEN__) +/** + * The message's limit, the last guard, refused before any byte is read, where a span can pass + * it: natively, on 64-bit targets, for a family whose limit is below the largest size, as + * ChaCha20-Poly1305's 2^38 - 64 bytes. Each earlier guard is still checked first. The other + * families' limits, 2^64 - 17 bytes, and the additional data's, 2^64 - 1, no span reaches. + */ +template +void check_aead_limits() { + static_assert(sizeof(std::size_t) == 8, "the limits are reachable only with 64-bit sizes"); + static_assert(Aead::max_message_size < std::numeric_limits::max()); + auto made = Aead::make(aead_key()); + auto const huge = reserved(static_cast(Aead::max_message_size) + 1); + if (!BOOST_TEST(made.has_value()) || !BOOST_TEST(!huge.empty())) { + return; + } + std::array const iv{}; + std::array const tag{}; + BOOST_TEST(made->seal(iv, {}, huge).error() == crypto::error::message_too_long); + BOOST_TEST(made->open(iv, {}, huge, tag).error() == crypto::error::message_too_long); + // The IV and the tag are checked before the length. + BOOST_TEST(made->seal({}, {}, huge).error() == crypto::error::invalid_iv_size); + BOOST_TEST(made->open(iv, {}, huge, std::span(tag).first(Aead::tag_size - 1)).error() == + crypto::error::invalid_tag_size); + // The error ends nothing: the object seals afterwards. + std::array data{}; + BOOST_TEST(made->seal(iv, {}, data).has_value()); + // The state is checked before the length. + Aead const moved = std::move(*made); + BOOST_TEST(made->seal(iv, {}, huge).error() == crypto::error::invalid_state); +} +#endif + +} // namespace webcpp::test + +#endif diff --git a/test/support/wycheproof_aead.hpp b/test/support/wycheproof_aead.hpp new file mode 100644 index 00000000..c7471358 --- /dev/null +++ b/test/support/wycheproof_aead.hpp @@ -0,0 +1,101 @@ +// 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) + +// Wycheproof's tests of an AEAD of ciphers::aead, read at run time from +// third_party/libs/wycheproof: those with the family's IV size seal and open, the valid +// matching and the invalid failing with authentication_failed and the data zeroed; those with +// another IV size give invalid_iv_size on seal and open, the data untouched. + +#ifndef WEBCPP_TEST_CRYPTO_SUPPORT_WYCHEPROOF_AEAD_HPP +#define WEBCPP_TEST_CRYPTO_SUPPORT_WYCHEPROOF_AEAD_HPP + +#include "aead_checks.hpp" +#include "hex.hpp" +#include "test_data.hpp" +#include "wycheproof_gcm.hpp" + +#include +#include + +#include +#include +#include +#include +#include + +namespace webcpp::test { + +/** The counts of an AEAD's Wycheproof tests, by how each ended. */ +struct wycheproof_aead_counts { + /** Valid, opened and sealed. */ + std::size_t valid = 0; + /** Invalid, refused with authentication_failed and the data zeroed. */ + std::size_t invalid = 0; + /** An IV of another size than the family's, refused with invalid_iv_size. */ + std::size_t other_iv = 0; +}; + +/** Runs one Wycheproof test through `Aead` and counts how it ended. */ +template +void check_wycheproof_aead_test(boost::json::value const& test, wycheproof_aead_counts& counts) { + auto made = Aead::make(wycheproof_bytes(test, "key")); + if (!BOOST_TEST(made.has_value())) { + return; + } + auto const iv = wycheproof_bytes(test, "iv"); + auto const additional_data = wycheproof_bytes(test, "aad"); + auto const message = wycheproof_bytes(test, "msg"); + auto const ciphertext = wycheproof_bytes(test, "ct"); + auto const tag = wycheproof_bytes(test, "tag"); + auto data = ciphertext; + auto const opened = made->open(iv, additional_data, data, tag); + if (iv.size() != Aead::iv_size) { + BOOST_TEST(opened.error() == crypto::error::invalid_iv_size); + BOOST_TEST(data == ciphertext); + auto plaintext = message; + BOOST_TEST(made->seal(iv, additional_data, plaintext).error() == + crypto::error::invalid_iv_size); + BOOST_TEST(plaintext == message); + ++counts.other_iv; + return; + } + if (test.at("result").as_string() != "valid") { + BOOST_TEST(opened.error() == crypto::error::authentication_failed); + BOOST_TEST(all_zero(data)); + ++counts.invalid; + return; + } + BOOST_TEST(opened.has_value()); + BOOST_TEST(data == message); + auto sealed_data = message; + auto const sealed = made->seal(iv, additional_data, sealed_data); + BOOST_TEST(sealed_data == ciphertext); + BOOST_TEST(sealed && to_hex(*sealed) == to_hex(tag)); + ++counts.valid; +} + +/** + * Every test of one of Wycheproof's files of an AEAD (`testvectors_v1/`) through `Aead`, + * each counted by how it ended against the counts the file holds. + */ +template +void check_wycheproof_aead(std::string_view file, wycheproof_aead_counts const& expected) { + auto const document = boost::json::parse( + read_file(std::string(WEBCPP_TEST_WYCHEPROOF) + "/testvectors_v1/" + std::string(file))); + wycheproof_aead_counts counts; + for (auto const& group : document.at("testGroups").as_array()) { + for (auto const& test : group.at("tests").as_array()) { + check_wycheproof_aead_test(test, counts); + } + } + BOOST_TEST_EQ(counts.valid, expected.valid); + BOOST_TEST_EQ(counts.invalid, expected.invalid); + BOOST_TEST_EQ(counts.other_iv, expected.other_iv); +} + +} // namespace webcpp::test + +#endif diff --git a/test/windows_h_after_test.cpp b/test/windows_h_after_test.cpp index d0393255..f2b2a398 100644 --- a/test/windows_h_after_test.cpp +++ b/test/windows_h_after_test.cpp @@ -16,8 +16,11 @@ #include #include #include +#include +#include #include #include +#include #include #include #include diff --git a/test/windows_h_before_test.cpp b/test/windows_h_before_test.cpp index 1c88eca9..2a9d1f9d 100644 --- a/test/windows_h_before_test.cpp +++ b/test/windows_h_before_test.cpp @@ -31,8 +31,11 @@ #include #include #include +#include +#include #include #include +#include #include #include #include diff --git a/test/xchacha_sodium_test.cpp b/test/xchacha_sodium_test.cpp new file mode 100644 index 00000000..0c363542 --- /dev/null +++ b/test/xchacha_sodium_test.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) + +// XChaCha20-Poly1305, its 24-byte nonce, on libsodium, through its default type, +// ciphers::xchacha20_poly1305<>: the XChaCha draft's appendix A.3.1 and libsodium's own +// cases, every guard, tampering, moves, empty inputs and aliasing spans +// (support/aead_checks.hpp). Its limit, 2^64 - 17 bytes, no span reaches. + +#include +#include +#include + +#include "support/aead_checks.hpp" + +#include + +#include + +namespace crypto = webcpp::crypto; + +using xchacha = crypto::ciphers::xchacha20_poly1305<>; + +static_assert(std::is_same_v, + crypto::backends::sodium>); +static_assert(std::is_same_v>); +static_assert(std::is_same_v); +static_assert(std::is_same_v); +static_assert(crypto::supports_v); +static_assert(xchacha::key_size == 32 && xchacha::iv_size == 24 && xchacha::tag_size == 16); +static_assert(xchacha::max_message_size == ~std::uint64_t{0} - 16); + +int main() { + webcpp::test::check_aead(webcpp::test::xchacha20_poly1305_cases); + return webcpp::test::exit_status(boost::report_errors()); +} From a3a17ea205c5a2544b5d780aeda9ca5b91d73db3 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 17:13:09 -0300 Subject: [PATCH 026/110] crypto: ciphers::aead refuses a type that is no AEAD family first and alone, and libsodium's engine passes an empty span's data as it is libsodium's detached decryptions check the tag alone when the output is null, and its ChaCha20 streams return at once on no byte, so the engine's static placeholder byte goes. The AEAD tests include what they use, and the ChaCha20-Poly1305 default's message gains its MSVC case. --- doc/changelog.adoc | 2 +- doc/generated/messages.adoc | 14 ++++ doc/tables/crypto.json | 1 + include/webcpp/crypto/backends/sodium.hpp | 25 +++---- include/webcpp/crypto/ciphers/aead.hpp | 72 +++++++++++++++---- test/allocation_sodium_test.cpp | 1 + test/chacha_original_sodium_test.cpp | 1 + test/chacha_sodium_test.cpp | 2 + test/messages/Jamfile | 1 + test/messages/aead_not_a_family/Jamfile | 12 ++++ .../aead_not_a_family/aead_not_a_family.cpp | 23 ++++++ test/msvc/Jamfile | 2 + test/msvc/aead_not_a_family/Jamfile | 11 +++ test/msvc/aead_not_a_family/app.cpp | 18 +++++ test/msvc/chacha_default_not_linked/Jamfile | 11 +++ test/msvc/chacha_default_not_linked/app.cpp | 18 +++++ test/xchacha_sodium_test.cpp | 1 + 17 files changed, 185 insertions(+), 30 deletions(-) create mode 100644 test/messages/aead_not_a_family/Jamfile create mode 100644 test/messages/aead_not_a_family/aead_not_a_family.cpp create mode 100644 test/msvc/aead_not_a_family/Jamfile create mode 100644 test/msvc/aead_not_a_family/app.cpp create mode 100644 test/msvc/chacha_default_not_linked/Jamfile create mode 100644 test/msvc/chacha_default_not_linked/app.cpp diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 07f933b2..806f0045 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -22,7 +22,7 @@ of every version are on webcpp's index page. * Added backends::bearssl (AES-GCM alone, allocating nothing), backends::openssl via /webcpp/crypto//openssl natively and on WASI (allocating at make only, or natively in openssl_memory_resource with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE), and backends::ctaes (block cipher alone). * Added curves::secp256k1: key pairs, BIP340 and ECDSA signatures, ECDH, strict DER, low-S and the x-only tweak. * Added curves::ed25519 and curves::x25519 on libsodium: strict verification tabled on twelve edge cases, Ed25519ph over webcpp::hash's sha2_512 (/webcpp/crypto//crypto brings hash), the conversion, and agree refusing all-zero secrets. -* Added backends::sodium on /third_party//sodium, shared with webcpp::hash and initialised before every engine, every backend's link-time canary and C suite, and on it ciphers::aead's chacha20_poly1305, chacha20_poly1305_original and xchacha20_poly1305. +* Added backends::sodium on /third_party//sodium, shared with webcpp::hash and initialised before every engine, every backend's link-time canary and C suite, and on it ciphers::aead's chacha20_poly1305, chacha20_poly1305_original and xchacha20_poly1305, refusing first any other family. * Added the page: a chapter per namespace and use case, the memory option's guide and example, tables generated from the tests, every Jamfile and message, and llms.txt. * Added supports_v, the capability table on the target being compiled, and the tags of its families and algorithms, which ciphers::gcm, the AES block cipher and secp256k1's key pair name. * Added secret, a self-wiping array that is copied only by clone, and the errors 13 to 20: memory_functions_refused, memory_functions_not_installed, weak_public_key, invalid_point, invalid_scalar, invalid_padding, invalid_encoding and invalid_ciphertext_size. diff --git a/doc/generated/messages.adoc b/doc/generated/messages.adoc index f171d115..31feb62b 100644 --- a/doc/generated/messages.adoc +++ b/doc/generated/messages.adoc @@ -13,6 +13,12 @@ At compile time, checked word for word by the message tests of `test/messages` w |=== |Case |Checked on |The message, and its fix +|`+aead_not_a_family+` +|native, wasip2, wasip3 +|`+webcpp::crypto: ciphers::aead takes an AEAD family: families::chacha20_poly1305, families::chacha20_poly1305_original or families::xchacha20_poly1305.+` + +The fix: Name one of the three ChaCha20-Poly1305 families; AES-GCM is `+ciphers::gcm+`, as in `+aes256_gcm+`. + |`+aes_on_bearssl+` |native, wasip2 |`+webcpp::crypto: ciphers::aes256: BearSSL exports AES only inside its modes, with no block cipher. Name a backend that exports it, as in ciphers::aes256 or ciphers::aes256, and add its library to the program's Jamfile.+` @@ -560,6 +566,10 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |=== |Case |Stops |Fix +|`+aead_not_a_family+` +|the compile +|Name one of the three ChaCha20-Poly1305 families; AES-GCM is `+ciphers::gcm+`, as in `+aes256_gcm+`. + |`+aes_on_bearssl+` |the compile |Name `+ciphers::aes256+`, include `++` and add `+/third_party//ctaes+`. @@ -604,6 +614,10 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the link |Compile every file of the program with the same backend settings. +|`+chacha_default_not_linked+` +|the compile +|The ChaCha20-Poly1305 AEADs' default is libsodium on every target: add `+/third_party//sodium+`. + |`+ctaes_not_linked+` |the compile |Add `+/third_party//ctaes+`. diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index e5af2a5f..2bbf22f2 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -660,6 +660,7 @@ "ctaes_not_linked": "Add `/third_party//ctaes`.", "sodium_not_linked": "Add `/third_party//sodium`.", "chacha_default_not_linked": "The ChaCha20-Poly1305 AEADs' default is libsodium on every target: add `/third_party//sodium`.", + "aead_not_a_family": "Name one of the three ChaCha20-Poly1305 families; AES-GCM is `ciphers::gcm`, as in `aes256_gcm`.", "sodium_not_linked_on_emscripten": "Add `/third_party//sodium` to the program's sources.", "canary_sodium_other_commit": "Build the library at the commit of webcpp's submodule, or link it through b2.", "secp256k1_not_linked": "Add `/third_party//secp256k1`.", diff --git a/include/webcpp/crypto/backends/sodium.hpp b/include/webcpp/crypto/backends/sodium.hpp index 4e080eaf..5a74cd83 100644 --- a/include/webcpp/crypto/backends/sodium.hpp +++ b/include/webcpp/crypto/backends/sodium.hpp @@ -157,9 +157,10 @@ struct aead_engine { std::span data, boost::hash2::digest<16>& tag) noexcept { read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); unsigned long long tag_length = 0; - auto* const bytes = writable(data); - // libsodium encrypts in place when the output is the input (its documented contract). - if (calls::encrypt(bytes, tag.data(), &tag_length, bytes, data.size(), + // libsodium encrypts in place when the output is the input (its documented contract); + // an empty span's null data() is never read or written, since every stream of + // ChaCha20 returns at once on no byte. + if (calls::encrypt(data.data(), tag.data(), &tag_length, data.data(), data.size(), additional_data.data(), additional_data.size(), nullptr, iv.data(), s.key.data()) != 0) { return error::backend_failure; @@ -176,9 +177,12 @@ struct aead_engine { state& s, std::span iv, std::span additional_data, std::span data, std::array const& tag) noexcept { read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); - auto* const bytes = writable(data); - if (calls::decrypt(bytes, nullptr, bytes, data.size(), tag.data(), additional_data.data(), - additional_data.size(), iv.data(), s.key.data()) != 0) { + // An empty span's null data() makes libsodium check the tag alone: its detached + // decryptions return the verdict when the output is null, before clearing or decrypting + // it. + if (calls::decrypt(data.data(), nullptr, data.data(), data.size(), tag.data(), + additional_data.data(), additional_data.size(), iv.data(), + s.key.data()) != 0) { return error::authentication_failed; } return {}; @@ -192,15 +196,6 @@ struct aead_engine { /** Wipes the key. */ static void reset(state& s) noexcept { wipe_object(s.key); } - -private: - // The data's first byte, or one of the engine's own for an empty span, whose data() may be - // null: libsodium clears the output of a failed open with memset, which takes no null - // pointer, even for no byte. - static std::uint8_t* writable(std::span data) noexcept { - static std::uint8_t none = 0; - return data.empty() ? &none : data.data(); - } }; } // namespace webcpp::crypto::detail diff --git a/include/webcpp/crypto/ciphers/aead.hpp b/include/webcpp/crypto/ciphers/aead.hpp index 88398337..d7e2e743 100644 --- a/include/webcpp/crypto/ciphers/aead.hpp +++ b/include/webcpp/crypto/ciphers/aead.hpp @@ -89,18 +89,55 @@ namespace webcpp::crypto::detail { template struct aead_state {}; +/** Whether `Family` is one of the AEAD families `ciphers::aead` takes. */ +template +inline constexpr bool aead_family = false; + +/** ChaCha20-Poly1305 is an AEAD family. */ +template <> +inline constexpr bool aead_family = true; + +/** The original ChaCha20-Poly1305 is an AEAD family. */ +template <> +inline constexpr bool aead_family = true; + +/** XChaCha20-Poly1305 is an AEAD family. */ +template <> +inline constexpr bool aead_family = true; + /** - * The refusal of an AEAD family on a backend whose header does not specialise its engine: the - * primary refuses a type that is no AEAD family. + * The sizes and limits `ciphers::aead` reads from its family: the family's own. + * + * @tparam Family An AEAD family. */ -template -struct aead_refusal { - static_assert(dependent_false, - "webcpp::crypto: ciphers::aead takes an AEAD family: " - "families::chacha20_poly1305, families::chacha20_poly1305_original or " - "families::xchacha20_poly1305."); +template > +struct aead_sizes : Family {}; + +/** + * The sizes of a type that is no AEAD family, which `ciphers::aead` refuses first: placeholders, + * so that the compiler adds no error of its own after the refusal. + */ +template +struct aead_sizes { + /** A placeholder. */ + static constexpr std::size_t key_size = 1; + /** A placeholder. */ + static constexpr std::size_t iv_size = 1; + /** A placeholder. */ + static constexpr std::size_t tag_size = 1; + /** A placeholder. */ + static constexpr std::uint64_t max_message_size = 0; + /** A placeholder. */ + static constexpr std::uint64_t max_additional_data_size = 0; }; +/** + * The refusal of an AEAD family on a backend whose header does not specialise its engine: each + * family's below. A type that is no AEAD family has none here: `ciphers::aead` refuses it first. + */ +template +struct aead_refusal {}; + /** ChaCha20-Poly1305's refusal, which names what the program needs (`detail/capabilities.hpp`). */ template struct aead_refusal { @@ -175,6 +212,13 @@ namespace webcpp::crypto::ciphers { */ template class aead { + // The first error a program that names another type sees, and its only one. + static_assert(detail::aead_family, + "webcpp::crypto: ciphers::aead takes an AEAD family: " + "families::chacha20_poly1305, families::chacha20_poly1305_original or " + "families::xchacha20_poly1305."); + + using sizes = detail::aead_sizes; using state_type = detail::aead_state; using engine = detail::aead_engine; @@ -186,17 +230,17 @@ class aead { /** The algorithm of the capability table: the family's own tag, its one algorithm. */ using name_type = Family; /** The tag, Boost.Hash2's digest of `tag_size` bytes. */ - using result_type = boost::hash2::digest; + using result_type = boost::hash2::digest; /** The key's size. */ - static constexpr std::size_t key_size = Family::key_size; + static constexpr std::size_t key_size = sizes::key_size; /** The nonce's size, exactly. */ - static constexpr std::size_t iv_size = Family::iv_size; + static constexpr std::size_t iv_size = sizes::iv_size; /** The tag's size. */ - static constexpr std::size_t tag_size = Family::tag_size; + static constexpr std::size_t tag_size = sizes::tag_size; /** The longest message. */ - static constexpr std::uint64_t max_message_size = Family::max_message_size; + static constexpr std::uint64_t max_message_size = sizes::max_message_size; /** The longest additional data. */ - static constexpr std::uint64_t max_additional_data_size = Family::max_additional_data_size; + static constexpr std::uint64_t max_additional_data_size = sizes::max_additional_data_size; /** * Makes an object under a key. diff --git a/test/allocation_sodium_test.cpp b/test/allocation_sodium_test.cpp index f40fcc9f..649568bd 100644 --- a/test/allocation_sodium_test.cpp +++ b/test/allocation_sodium_test.cpp @@ -22,6 +22,7 @@ #include #include #include +#include namespace { diff --git a/test/chacha_original_sodium_test.cpp b/test/chacha_original_sodium_test.cpp index 50332f47..cc5c72b0 100644 --- a/test/chacha_original_sodium_test.cpp +++ b/test/chacha_original_sodium_test.cpp @@ -17,6 +17,7 @@ #include +#include #include namespace crypto = webcpp::crypto; diff --git a/test/chacha_sodium_test.cpp b/test/chacha_sodium_test.cpp index db034068..595218a5 100644 --- a/test/chacha_sodium_test.cpp +++ b/test/chacha_sodium_test.cpp @@ -17,6 +17,8 @@ #include +#include +#include #include namespace crypto = webcpp::crypto; diff --git a/test/messages/Jamfile b/test/messages/Jamfile index 21a1324e..2c0fa975 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -30,3 +30,4 @@ build-project ed25519ph_sha256 ; build-project ed25519_default_not_linked ; build-project heavy_without_threads ; build-project chacha_default_not_linked ; +build-project aead_not_a_family ; diff --git a/test/messages/aead_not_a_family/Jamfile b/test/messages/aead_not_a_family/Jamfile new file mode 100644 index 00000000..01a54343 --- /dev/null +++ b/test/messages/aead_not_a_family/Jamfile @@ -0,0 +1,12 @@ +# 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 ; + +webcpp.compile-diagnostic aead_not_a_family : aead_not_a_family.cpp + : : native wasip2 wasip3 ; diff --git a/test/messages/aead_not_a_family/aead_not_a_family.cpp b/test/messages/aead_not_a_family/aead_not_a_family.cpp new file mode 100644 index 00000000..113eac92 --- /dev/null +++ b/test/messages/aead_not_a_family/aead_not_a_family.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) + +// ciphers::aead given a family that is no AEAD's, AES-GCM's, stops with the families it +// takes, and with that error alone. + +// clang-format off +// expected-error@webcpp/crypto/ciphers/aead.hpp:* {{webcpp::crypto: ciphers::aead takes an AEAD family: families::chacha20_poly1305, families::chacha20_poly1305_original or families::xchacha20_poly1305.}} +// clang-format on +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + using aead = crypto::ciphers::aead; + std::array const key{}; + return aead::make(key) ? 0 : 1; +} diff --git a/test/msvc/Jamfile b/test/msvc/Jamfile index 580685c4..fa0e62aa 100644 --- a/test/msvc/Jamfile +++ b/test/msvc/Jamfile @@ -48,3 +48,5 @@ build-project ed25519_on_bearssl ; build-project ed25519ph_sha256 ; build-project ed25519_default_not_linked ; build-project heavy_without_threads ; +build-project chacha_default_not_linked ; +build-project aead_not_a_family ; diff --git a/test/msvc/aead_not_a_family/Jamfile b/test/msvc/aead_not_a_family/Jamfile new file mode 100644 index 00000000..bb2cc0d7 --- /dev/null +++ b/test/msvc/aead_not_a_family/Jamfile @@ -0,0 +1,11 @@ +# 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 aead_not_a_family : app.cpp + : /webcpp/crypto//crypto + : native ; diff --git a/test/msvc/aead_not_a_family/app.cpp b/test/msvc/aead_not_a_family/app.cpp new file mode 100644 index 00000000..4947f516 --- /dev/null +++ b/test/msvc/aead_not_a_family/app.cpp @@ -0,0 +1,18 @@ +// 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) + +// ciphers::aead given AES-GCM's family, which is no AEAD family of its: refused. +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const key{}; + auto made = crypto::ciphers::aead::make(key); + return made ? 0 : 1; +} diff --git a/test/msvc/chacha_default_not_linked/Jamfile b/test/msvc/chacha_default_not_linked/Jamfile new file mode 100644 index 00000000..794f2b21 --- /dev/null +++ b/test/msvc/chacha_default_not_linked/Jamfile @@ -0,0 +1,11 @@ +# 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 chacha_default_not_linked : app.cpp + : /webcpp/crypto//crypto + : native ; diff --git a/test/msvc/chacha_default_not_linked/app.cpp b/test/msvc/chacha_default_not_linked/app.cpp new file mode 100644 index 00000000..fad16682 --- /dev/null +++ b/test/msvc/chacha_default_not_linked/app.cpp @@ -0,0 +1,18 @@ +// 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) + +// ChaCha20-Poly1305 on its default backend, libsodium, which the program does not link: +// refused where it is called. +#include + +#include +#include + +int main() { + std::array const key{}; + auto made = webcpp::crypto::ciphers::chacha20_poly1305<>::make(key); + return made ? 0 : 1; +} diff --git a/test/xchacha_sodium_test.cpp b/test/xchacha_sodium_test.cpp index 0c363542..c55038ab 100644 --- a/test/xchacha_sodium_test.cpp +++ b/test/xchacha_sodium_test.cpp @@ -17,6 +17,7 @@ #include +#include #include namespace crypto = webcpp::crypto; From 68acb518f12bbcb7df20e1fc54790893e4227a00 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 17:24:03 -0300 Subject: [PATCH 027/110] crypto: ChaCha20-Poly1305 on BearSSL and OpenSSL over ciphers::aead, against RFC 8439, Wycheproof and libsodium BearSSL runs SSE2's ChaCha20 and ctmulq's Poly1305 where it has them and its constant-time portable code otherwise, the seam pinning the latter, and its tag is compared by equal; OpenSSL's EVP ChaCha20-Poly1305 runs GCM's sequence of AEAD controls on its own context. Both pass aead_checks.hpp, Wycheproof's 325 cases and agree with libsodium pairwise; ctaes's refusal and the default's now name the three backends. The additional data may touch the data but not overlap it, since BearSSL reads it after it encrypts. --- doc/backends.adoc | 9 +- doc/chacha.adoc | 8 + doc/changelog.adoc | 2 +- doc/generated/backends-chacha20_poly1305.adoc | 17 +- doc/generated/defaults.adoc | 4 +- doc/generated/matrix.adoc | 25 ++- doc/generated/messages.adoc | 10 ++ doc/llms.txt | 6 +- doc/tables/crypto.json | 20 ++- include/webcpp/crypto.hpp | 4 +- include/webcpp/crypto/backends/bearssl.hpp | 147 +++++++++++++++++- include/webcpp/crypto/backends/openssl.hpp | 115 +++++++++++++- include/webcpp/crypto/ciphers/aead.hpp | 7 +- include/webcpp/crypto/detail/capabilities.hpp | 58 ++++--- test/Jamfile | 35 +++++ test/agreement_chacha_portable_test.cpp | 12 ++ test/agreement_chacha_test.cpp | 74 +++++++++ test/allocation_bearssl_test.cpp | 15 +- test/allocation_openssl_test.cpp | 18 ++- test/capabilities_test.cpp | 18 ++- test/chacha_bearssl_test.cpp | 46 ++++++ test/chacha_openssl_test.cpp | 46 ++++++ test/chacha_wycheproof_bearssl_test.cpp | 25 +++ test/chacha_wycheproof_openssl_test.cpp | 25 +++ test/messages/Jamfile | 1 + .../chacha_default_not_linked.cpp | 5 +- test/messages/chacha_on_ctaes/Jamfile | 12 ++ .../chacha_on_ctaes/chacha_on_ctaes.cpp | 24 +++ test/msvc/Jamfile | 1 + test/msvc/chacha_on_ctaes/Jamfile | 11 ++ test/msvc/chacha_on_ctaes/app.cpp | 19 +++ test/openssl_error_queue_test.cpp | 58 ++++--- test/support/aead_checks.hpp | 22 +-- test/support/agreement.hpp | 56 +++++++ test/wipe_objects_test.cpp | 12 ++ 35 files changed, 879 insertions(+), 88 deletions(-) create mode 100644 test/agreement_chacha_portable_test.cpp create mode 100644 test/agreement_chacha_test.cpp create mode 100644 test/chacha_bearssl_test.cpp create mode 100644 test/chacha_openssl_test.cpp create mode 100644 test/chacha_wycheproof_bearssl_test.cpp create mode 100644 test/chacha_wycheproof_openssl_test.cpp create mode 100644 test/messages/chacha_on_ctaes/Jamfile create mode 100644 test/messages/chacha_on_ctaes/chacha_on_ctaes.cpp create mode 100644 test/msvc/chacha_on_ctaes/Jamfile create mode 100644 test/msvc/chacha_on_ctaes/app.cpp diff --git a/doc/backends.adoc b/doc/backends.adoc index 37009fb5..e2eb962a 100644 --- a/doc/backends.adoc +++ b/doc/backends.adoc @@ -36,7 +36,7 @@ Each family has one default backend per target, for the reason the table gives, whatever the program links; no define changes it, and every other backend is reached by naming it in the type. AES-GCM's is OpenSSL natively, whose assembly uses the CPU's AES instructions on x86-64 and ARMv8 with Clang -and GCC, and BearSSL on WebAssembly, the only AEAD backend on Emscripten and +and GCC, and BearSSL on WebAssembly, the only AES-GCM backend on Emscripten and constant time by design where OpenSSL is built without assembly. On MSVC OpenSSL is built without assembly too: the default is then table-based and not constant time, and a program that timing attacks threaten names @@ -46,8 +46,11 @@ links it and the type that names another backend (<>). AES-GCM's default applies to `aes128_gcm`, `aes256_gcm` and `aes256<>`; the AES block cipher has none of its own, and libsecp256k1 is the only backend of -secp256k1. In {cpp}, `default_backend_t` names a family's default on -the target being compiled, and `default_backend` AES-GCM's. +secp256k1. The three ChaCha20-Poly1305 AEADs' default is libsodium on every +target; RFC 8439's form also runs on BearSSL, on every target, and on OpenSSL, +natively and on WASI, each named in the type. In {cpp}, +`default_backend_t` names a family's default on the target being +compiled, and `default_backend` AES-GCM's. include::generated/defaults.adoc[] diff --git a/doc/chacha.adoc b/doc/chacha.adoc index b45a3372..11e59f1a 100644 --- a/doc/chacha.adoc +++ b/doc/chacha.adoc @@ -39,6 +39,14 @@ calls do: `seal(iv_bytes, additional_data_bytes, data_bytes)` encrypts `data_bytes` and returns the 16-byte tag; `open(iv_bytes, additional_data_bytes, data_bytes, tag_bytes)` checks the tag and decrypts. A failed `open` zeroes `data_bytes`; a guard's refusal leaves it untouched. +The nonce may lie in `data_bytes`, and the additional data may touch it, as a +wire format that puts it just before the message does, but not overlap it. + +RFC 8439's form also runs on BearSSL, on every target, and on OpenSSL, +natively and on WASI, with the same results byte for byte: name the backend in +the type, as in `chacha20_poly1305`, and link its library. +On BearSSL nothing allocates; on OpenSSL `make` allocates and a message does +not. include::generated/backends-chacha20_poly1305.adoc[] diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 806f0045..b590a491 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -22,7 +22,7 @@ of every version are on webcpp's index page. * Added backends::bearssl (AES-GCM alone, allocating nothing), backends::openssl via /webcpp/crypto//openssl natively and on WASI (allocating at make only, or natively in openssl_memory_resource with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE), and backends::ctaes (block cipher alone). * Added curves::secp256k1: key pairs, BIP340 and ECDSA signatures, ECDH, strict DER, low-S and the x-only tweak. * Added curves::ed25519 and curves::x25519 on libsodium: strict verification tabled on twelve edge cases, Ed25519ph over webcpp::hash's sha2_512 (/webcpp/crypto//crypto brings hash), the conversion, and agree refusing all-zero secrets. -* Added backends::sodium on /third_party//sodium, shared with webcpp::hash and initialised before every engine, every backend's link-time canary and C suite, and on it ciphers::aead's chacha20_poly1305, chacha20_poly1305_original and xchacha20_poly1305, refusing first any other family. +* Added backends::sodium on /third_party//sodium, shared with webcpp::hash and initialised before every engine, every backend's link-time canary and C suite, and on it ciphers::aead's chacha20_poly1305, chacha20_poly1305_original and xchacha20_poly1305, refusing first any other family; chacha20_poly1305 also on BearSSL and OpenSSL. * Added the page: a chapter per namespace and use case, the memory option's guide and example, tables generated from the tests, every Jamfile and message, and llms.txt. * Added supports_v, the capability table on the target being compiled, and the tags of its families and algorithms, which ciphers::gcm, the AES block cipher and secp256k1's key pair name. * Added secret, a self-wiping array that is copied only by clone, and the errors 13 to 20: memory_functions_refused, memory_functions_not_installed, weak_public_key, invalid_point, invalid_scalar, invalid_padding, invalid_encoding and invalid_ciphertext_size. diff --git a/doc/generated/backends-chacha20_poly1305.adoc b/doc/generated/backends-chacha20_poly1305.adoc index 1557d860..7fb19074 100644 --- a/doc/generated/backends-chacha20_poly1305.adoc +++ b/doc/generated/backends-chacha20_poly1305.adoc @@ -13,10 +13,25 @@ The backends of `+ciphers::chacha20_poly1305+`, from the test programs that run |=== |Backend |Jamfile |Header |Targets +|BearSSL +|`+/third_party//bearssl+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+chacha_bearssl+`, `+chacha_wycheproof_bearssl+`, `+allocation_bearssl+`, `+agreement_chacha+`, `+agreement_chacha_emscripten+`, `+agreement_chacha_portable+`, `+agreement_chacha_portable_emscripten+`) + +|OpenSSL +|`+/webcpp/crypto//openssl+` +|`++` +|native, wasip2, wasip3 (tested by `+chacha_openssl+`, `+chacha_wycheproof_openssl+`, `+allocation_openssl+`, `+openssl_error_queue+`, `+agreement_chacha+`, `+agreement_chacha_portable+`); not on emscripten: `+/webcpp/crypto//openssl+` stops the build there + +|ctaes +|`+/third_party//ctaes+` +|`++` +|refused at compile time (`+chacha_on_ctaes+`) + |libsodium |`+/third_party//sodium+` |`++` -|native, wasip2, wasip3, emscripten (tested by `+chacha_sodium+`, `+chacha_wycheproof_sodium+`, `+allocation_sodium+`) +|native, wasip2, wasip3, emscripten (tested by `+chacha_sodium+`, `+chacha_wycheproof_sodium+`, `+allocation_sodium+`, `+agreement_chacha+`, `+agreement_chacha_emscripten+`) |=== `+chacha20_poly1305<>+` names the default backend. The default per target, whatever the program links, as <> gives it with its reasons and tests: diff --git a/doc/generated/defaults.adoc b/doc/generated/defaults.adoc index 905edfc5..cbca4b47 100644 --- a/doc/generated/defaults.adoc +++ b/doc/generated/defaults.adoc @@ -32,7 +32,7 @@ |AES-GCM |emscripten |BearSSL -|the only AEAD backend there: webcpp does not build OpenSSL for Emscripten +|the only AES-GCM backend there: webcpp does not build OpenSSL for Emscripten |`+default_bearssl+`, `+default_backend_all_linked_emscripten+` |AES block cipher @@ -62,7 +62,7 @@ |ChaCha20-Poly1305 |native, wasip2, wasip3, emscripten |libsodium -|the only backend that has it: libsodium's own C code, the same on every target (link:https://doc.libsodium.org/secret-key_cryptography/aead/chacha20-poly1305[libsodium's ChaCha20-Poly1305 constructions]) +|one library for the three ChaCha20-Poly1305 AEADs on every target, where BearSSL and OpenSSL have RFC 8439's alone (link:https://doc.libsodium.org/secret-key_cryptography/aead/chacha20-poly1305[libsodium's ChaCha20-Poly1305 constructions]); a program that links BearSSL or OpenSSL alone names it in the type, as in `chacha20_poly1305` |`+chacha_sodium+`, `+default_backend_none_linked+` |original ChaCha20-Poly1305 diff --git a/doc/generated/matrix.adoc b/doc/generated/matrix.adoc index 2c43feb1..202f0f50 100644 --- a/doc/generated/matrix.adoc +++ b/doc/generated/matrix.adoc @@ -116,10 +116,25 @@ |native, wasip2, wasip3, emscripten |`+x25519_sodium+`, `+x25519_wycheproof_sodium+` +|`+ciphers::chacha20_poly1305+` +|BearSSL +|native, wasip2, wasip3, emscripten +|`+chacha_bearssl+`, `+chacha_wycheproof_bearssl+`, `+allocation_bearssl+`, `+agreement_chacha+`, `+agreement_chacha_emscripten+`, `+agreement_chacha_portable+`, `+agreement_chacha_portable_emscripten+` + +|`+ciphers::chacha20_poly1305+` +|OpenSSL +|native, wasip2, wasip3; not on emscripten: `+/webcpp/crypto//openssl+` stops the build there +|`+chacha_openssl+`, `+chacha_wycheproof_openssl+`, `+allocation_openssl+`, `+openssl_error_queue+`, `+agreement_chacha+`, `+agreement_chacha_portable+` + +|`+ciphers::chacha20_poly1305+` +|ctaes +|refused at compile time +|`+chacha_on_ctaes+` + |`+ciphers::chacha20_poly1305+` |libsodium |native, wasip2, wasip3, emscripten -|`+chacha_sodium+`, `+chacha_wycheproof_sodium+`, `+allocation_sodium+` +|`+chacha_sodium+`, `+chacha_wycheproof_sodium+`, `+allocation_sodium+`, `+agreement_chacha+`, `+agreement_chacha_emscripten+` |`+ciphers::chacha20_poly1305_original+` |libsodium @@ -235,10 +250,10 @@ The same, by target: the backends each operation runs on. |libsodium |`+ciphers::chacha20_poly1305+` -|libsodium -|libsodium -|libsodium -|libsodium +|BearSSL, OpenSSL, libsodium +|BearSSL, OpenSSL, libsodium +|BearSSL, OpenSSL, libsodium +|BearSSL, libsodium |`+ciphers::chacha20_poly1305_original+` |libsodium diff --git a/doc/generated/messages.adoc b/doc/generated/messages.adoc index 31feb62b..bc267ea7 100644 --- a/doc/generated/messages.adoc +++ b/doc/generated/messages.adoc @@ -37,6 +37,12 @@ The fix: Add `+/third_party//bearssl+`. The fix: The ChaCha20-Poly1305 AEADs' default is libsodium on every target: add `+/third_party//sodium+`. +|`+chacha_on_ctaes+` +|native, wasip2, wasip3 +|`+webcpp::crypto: ctaes has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).+` + +The fix: Name a backend that has ChaCha20-Poly1305, as in `+chacha20_poly1305+`, or its default, `+chacha20_poly1305<>+`, and link its library. + |`+ctaes_not_linked+` |native, wasip2, wasip3 |`+webcpp::crypto: the backend ctaes is used and not linked. In the program's Jamfile, add /third_party//ctaes beside /webcpp/crypto//crypto. (without b2: define WEBCPP_CRYPTO_HAS_CTAES=1 and link ctaes.c with webcpp's src/canary_ctaes.c)+` @@ -618,6 +624,10 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |The ChaCha20-Poly1305 AEADs' default is libsodium on every target: add `+/third_party//sodium+`. +|`+chacha_on_ctaes+` +|the compile +|Name a backend that has ChaCha20-Poly1305, as in `+chacha20_poly1305+`, or its default, `+chacha20_poly1305<>+`, and link its library. + |`+ctaes_not_linked+` |the compile |Add `+/third_party//ctaes+`. diff --git a/doc/llms.txt b/doc/llms.txt index 4d58ed42..587d121e 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -35,7 +35,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - begin_seal: Begins an incremental seal: the IV and the whole additional data first, both read before this returns. - update: Encrypts the next piece of the message in place. - result: Ends the message with its tag. -- [ciphers::chacha20_poly1305](https://webcpporg.github.io/libs/crypto/#crypto-chacha): RFC 8439's ChaCha20-Poly1305, authenticated encryption in place with a 12-byte nonce. Header , . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. +- [ciphers::chacha20_poly1305](https://webcpporg.github.io/libs/crypto/#crypto-chacha): RFC 8439's ChaCha20-Poly1305, authenticated encryption in place with a 12-byte nonce. Header , . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten; OpenSSL (/webcpp/crypto//openssl) on native, wasip2, wasip3; libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. - make: Makes an object under a key. - seal: Seals a message in place: `data_bytes` holds the plaintext before and the ciphertext after. - open: Opens a message in place: `data_bytes` holds the ciphertext before and the plaintext after. @@ -92,12 +92,12 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - AES-GCM, native, Clang and GCC: OpenSSL; OpenSSL's assembly uses the CPU's AES and carry-less multiplication instructions on x86-64 and ARMv8 ([OpenSSL's AES assembly for ARMv8 and x86-64](https://github.com/openssl/openssl/tree/master/crypto/aes/asm); [OpenSSL's GHASH and AES-GCM assembly](https://github.com/openssl/openssl/tree/master/crypto/modes/asm)); BearSSL has them on x86 only ([BearSSL, the AES implementations it selects](https://www.bearssl.org/support.html)). OpenSSL whatever the program links: a program that links BearSSL alone names `gcm>`. - AES-GCM, native, MSVC: OpenSSL; the same rule as with Clang and GCC, but here OpenSSL is built no-asm: table-based AES and 4-bit GHASH, no AES-NI, not constant time ([OpenSSL's INSTALL.md, no-asm](https://github.com/openssl/openssl/blob/master/INSTALL.md)); where timing attacks matter, link BearSSL and name `gcm>`. - AES-GCM, wasip2, wasip3: BearSSL; constant time by design ([BearSSL, constant-time crypto](https://www.bearssl.org/constanttime.html)), where OpenSSL is built no-asm and its AES and GHASH are table-based ([OpenSSL's INSTALL.md, no-asm](https://github.com/openssl/openssl/blob/master/INSTALL.md)). BearSSL whatever the program links: a program that links OpenSSL alone names `gcm>`. -- AES-GCM, emscripten: BearSSL; the only AEAD backend there: webcpp does not build OpenSSL for Emscripten. +- AES-GCM, emscripten: BearSSL; the only AES-GCM backend there: webcpp does not build OpenSSL for Emscripten. - AES block cipher, native, wasip2, wasip3, emscripten: none; a raw block cipher is a building block a program chooses deliberately, naming its backend; `aes256<>` takes AES-GCM's default as its argument, and its `make` does not compile where that is BearSSL. - secp256k1, native, wasip2, wasip3, emscripten: libsecp256k1; the only backend ([libsecp256k1's README](https://github.com/bitcoin-core/secp256k1#readme)). - Ed25519, native, wasip2, wasip3, emscripten: libsodium; the only backend in this version, on every target, and its verification is the policy `strict` ([libsodium's documentation, public-key signatures](https://doc.libsodium.org/public-key_cryptography/public-key_signatures); [RFC 8032, the Edwards-curve Digital Signature Algorithm (EdDSA)](https://www.rfc-editor.org/rfc/rfc8032)). - X25519, native, wasip2, wasip3, emscripten: libsodium; the only backend in this version, on every target; it refuses an all-zero shared secret itself ([RFC 7748, Elliptic Curves for Security (X25519 and X448)](https://www.rfc-editor.org/rfc/rfc7748)). -- ChaCha20-Poly1305, native, wasip2, wasip3, emscripten: libsodium; the only backend that has it: libsodium's own C code, the same on every target ([libsodium's ChaCha20-Poly1305 constructions](https://doc.libsodium.org/secret-key_cryptography/aead/chacha20-poly1305)). +- ChaCha20-Poly1305, native, wasip2, wasip3, emscripten: libsodium; one library for the three ChaCha20-Poly1305 AEADs on every target, where BearSSL and OpenSSL have RFC 8439's alone ([libsodium's ChaCha20-Poly1305 constructions](https://doc.libsodium.org/secret-key_cryptography/aead/chacha20-poly1305)); a program that links BearSSL or OpenSSL alone names it in the type, as in `chacha20_poly1305`. - original ChaCha20-Poly1305, native, wasip2, wasip3, emscripten: libsodium; the only backend that has it: libsodium's own C code, the same on every target ([libsodium's ChaCha20-Poly1305 constructions](https://doc.libsodium.org/secret-key_cryptography/aead/chacha20-poly1305)). - XChaCha20-Poly1305, native, wasip2, wasip3, emscripten: libsodium; the only backend that has it: libsodium's own C code, the same on every target ([libsodium's ChaCha20-Poly1305 constructions](https://doc.libsodium.org/secret-key_cryptography/aead/chacha20-poly1305)). diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 2bbf22f2..c36e2640 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -368,7 +368,16 @@ "what": "RFC 8439's ChaCha20-Poly1305, authenticated encryption in place with a 12-byte nonce.", "section": "crypto-chacha", "default": "`chacha20_poly1305<>` names the default backend.", - "backends": {"sodium": {"tests": ["chacha_sodium", "chacha_wycheproof_sodium", "allocation_sodium"]}} + "backends": { + "sodium": {"tests": ["chacha_sodium", "chacha_wycheproof_sodium", "allocation_sodium", + "agreement_chacha", "agreement_chacha_emscripten"]}, + "bearssl": {"tests": ["chacha_bearssl", "chacha_wycheproof_bearssl", "allocation_bearssl", + "agreement_chacha", "agreement_chacha_emscripten", + "agreement_chacha_portable", "agreement_chacha_portable_emscripten"]}, + "openssl": {"tests": ["chacha_openssl", "chacha_wycheproof_openssl", "allocation_openssl", + "openssl_error_queue", "agreement_chacha", "agreement_chacha_portable"]}, + "ctaes": {"refused": "chacha_on_ctaes"} + } }, { "id": "chacha20_poly1305_original", @@ -412,7 +421,7 @@ {"targets": ["native"], "compilers": ["clang", "gcc"], "backend": "openssl", "tests": ["default_both", "default_backend_all_linked"], "why": "OpenSSL's assembly uses the CPU's AES and carry-less multiplication instructions on x86-64 and ARMv8 ({openssl-armv8}; {openssl-ghash-asm}); BearSSL has them on x86 only ({bearssl-aes}). OpenSSL whatever the program links: a program that links BearSSL alone names `gcm>`"}, {"targets": ["native"], "compilers": ["msvc"], "backend": "openssl", "tests": ["default_both"], "why": "the same rule as with Clang and GCC, but here OpenSSL is built no-asm: table-based AES and 4-bit GHASH, no AES-NI, not constant time ({openssl-install}); where timing attacks matter, link BearSSL and name `gcm>`"}, {"targets": ["wasip2", "wasip3"], "backend": "bearssl", "tests": ["default_bearssl", "default_both_wasm", "default_backend_all_linked"], "why": "constant time by design ({bearssl-ct}), where OpenSSL is built no-asm and its AES and GHASH are table-based ({openssl-install}). BearSSL whatever the program links: a program that links OpenSSL alone names `gcm>`"}, - {"targets": ["emscripten"], "backend": "bearssl", "tests": ["default_bearssl", "default_backend_all_linked_emscripten"], "why": "the only AEAD backend there: webcpp does not build OpenSSL for Emscripten"} + {"targets": ["emscripten"], "backend": "bearssl", "tests": ["default_bearssl", "default_backend_all_linked_emscripten"], "why": "the only AES-GCM backend there: webcpp does not build OpenSSL for Emscripten"} ], "backends": { "bearssl": {"targets": "all"}, @@ -498,10 +507,12 @@ {"name": "chacha20_poly1305", "title": "ChaCha20-Poly1305", "type": "ciphers::chacha20_poly1305<{backend}>"} ], "default": [ - {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": ["chacha_sodium", "default_backend_none_linked"], "why": "the only backend that has it: libsodium's own C code, the same on every target ({libsodium-aead})"} + {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": ["chacha_sodium", "default_backend_none_linked"], "why": "one library for the three ChaCha20-Poly1305 AEADs on every target, where BearSSL and OpenSSL have RFC 8439's alone ({libsodium-aead}); a program that links BearSSL or OpenSSL alone names it in the type, as in `chacha20_poly1305`"} ], "backends": { - "sodium": {"targets": "all"} + "sodium": {"targets": "all"}, + "bearssl": {"targets": "all"}, + "openssl": {"targets": "all"} } }, { @@ -660,6 +671,7 @@ "ctaes_not_linked": "Add `/third_party//ctaes`.", "sodium_not_linked": "Add `/third_party//sodium`.", "chacha_default_not_linked": "The ChaCha20-Poly1305 AEADs' default is libsodium on every target: add `/third_party//sodium`.", + "chacha_on_ctaes": "Name a backend that has ChaCha20-Poly1305, as in `chacha20_poly1305`, or its default, `chacha20_poly1305<>`, and link its library.", "aead_not_a_family": "Name one of the three ChaCha20-Poly1305 families; AES-GCM is `ciphers::gcm`, as in `aes256_gcm`.", "sodium_not_linked_on_emscripten": "Add `/third_party//sodium` to the program's sources.", "canary_sodium_other_commit": "Build the library at the commit of webcpp's submodule, or link it through b2.", diff --git a/include/webcpp/crypto.hpp b/include/webcpp/crypto.hpp index fab012ff..9309ee70 100644 --- a/include/webcpp/crypto.hpp +++ b/include/webcpp/crypto.hpp @@ -10,7 +10,9 @@ `ciphers/aes256_gcm.hpp`, whose `aes128_gcm` and `aes256_gcm` name AES-GCM's default backend, and `ciphers/chacha20_poly1305.hpp`, whose AEADs name libsodium: a program that does not link the default names another in the type, as - `ciphers::gcm>` on WebAssembly. + `ciphers::gcm>` on WebAssembly or + `ciphers::chacha20_poly1305`, or, for the original ChaCha20-Poly1305 and + XChaCha20-Poly1305, which libsodium alone has, links libsodium. */ #ifndef WEBCPP_CRYPTO_HPP #define WEBCPP_CRYPTO_HPP diff --git a/include/webcpp/crypto/backends/bearssl.hpp b/include/webcpp/crypto/backends/bearssl.hpp index 9dfdd5c0..ca34bc59 100644 --- a/include/webcpp/crypto/backends/bearssl.hpp +++ b/include/webcpp/crypto/backends/bearssl.hpp @@ -6,8 +6,8 @@ /** The backend BearSSL: BearSSL's own C code, built from its sources by - `/third_party//bearssl`. It serves `ciphers::gcm>`, and has no - block cipher. + `/third_party//bearssl`. It serves `ciphers::gcm>` and + `ciphers::chacha20_poly1305`, and has no block cipher. @see "The backends", in the guide. */ @@ -25,15 +25,18 @@ #else #include +#include #include #include #include +#include #include #include #include #include +#include #include #include #include @@ -259,6 +262,146 @@ struct gcm_engine { static void reset(state& engine_state) noexcept { wipe_object(engine_state); } }; +/** + * ChaCha20's code: SSE2's where the CPU and the build have it, else the constant-time portable + * code. The test seam WEBCPP_CRYPTO_DETAIL_BEARSSL_PORTABLE keeps the portable code on every + * CPU. Both are constant time (inc/bearssl_block.h). + * + * @return The function `br_poly1305_run` is given. + */ +inline br_chacha20_run bearssl_chacha20() noexcept { +#ifndef WEBCPP_CRYPTO_DETAIL_BEARSSL_PORTABLE + if (br_chacha20_run const sse2_impl = br_chacha20_sse2_get()) { + return sse2_impl; + } +#endif + return &br_chacha20_ct_run; +} + +/** + * Poly1305's code: the 64-bit multiplication's where the compiler has 128-bit integers, else the + * constant-time 32-bit multiplication's. The test seam WEBCPP_CRYPTO_DETAIL_BEARSSL_PORTABLE keeps + * the latter on every target. Both are constant time (inc/bearssl_block.h). + * + * @return The function that runs ChaCha20-Poly1305. + */ +inline br_poly1305_run bearssl_poly1305() noexcept { +#ifndef WEBCPP_CRYPTO_DETAIL_BEARSSL_PORTABLE + if (br_poly1305_run const ctmulq_impl = br_poly1305_ctmulq_get()) { + return ctmulq_impl; + } +#endif + return &br_poly1305_ctmul_run; +} + +/** ChaCha20-Poly1305's state on BearSSL: the key, in the object, since BearSSL takes it per call. + */ +template <> +struct aead_state { + /** The key. */ + std::array key{}; +}; + +/** + * ChaCha20-Poly1305 on BearSSL: one function over the whole message, which encrypts or decrypts + * and computes the tag (inc/bearssl_block.h, `br_poly1305_run`). BearSSL leaves the tag's check + * to its caller: `equal` does it. BearSSL allocates nothing and never fails. + */ +template <> +struct aead_engine { + /** The state. */ + using state = aead_state; + + /** + * Keeps the key. + * + * @param engine_state An empty state. + * @param key_bytes 32 bytes (`aead` has checked their size). + * @return Nothing. + */ + [[nodiscard]] static boost::system::result init( + state& engine_state, std::span key_bytes) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_BEARSSL_CANARY); + std::ranges::copy(key_bytes, engine_state.key.begin()); + return {}; + } + + /** + * Encrypts `data_bytes` in place and writes the tag. BearSSL reads the nonce and the + * additional data before it writes a byte of the data. + * + * @param engine_state A keyed state. + * @param iv_bytes 12 bytes. + * @param additional_data_bytes Authenticated, not encrypted. + * @param data_bytes The message. + * @param tag_bytes The tag. + * @return Nothing. + */ + [[nodiscard]] static boost::system::result seal( + state& engine_state, std::span iv_bytes, + std::span additional_data_bytes, std::span data_bytes, + boost::hash2::digest<16>& tag_bytes) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_BEARSSL_CANARY); + bearssl_poly1305()(engine_state.key.data(), iv_bytes.data(), data_bytes.data(), + data_bytes.size(), additional_data_bytes.data(), + additional_data_bytes.size(), tag_bytes.data(), bearssl_chacha20(), 1); + return {}; + } + + /** + * Decrypts `data_bytes` in place, then compares the tag it computed with `tag_bytes` in + * constant time; `aead` zeroes the data when they differ. + * + * @param engine_state A keyed state. + * @param iv_bytes 12 bytes. + * @param additional_data_bytes The additional data of the seal. + * @param data_bytes The ciphertext. + * @param tag_bytes The expected tag. + * @return Nothing; `authentication_failed`. + */ + [[nodiscard]] static boost::system::result open( + state& engine_state, std::span iv_bytes, + std::span additional_data_bytes, std::span data_bytes, + std::array const& tag_bytes) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_BEARSSL_CANARY); + std::array computed_tag{}; + bearssl_poly1305()(engine_state.key.data(), iv_bytes.data(), data_bytes.data(), + data_bytes.size(), additional_data_bytes.data(), + additional_data_bytes.size(), computed_tag.data(), bearssl_chacha20(), + 0); + // The verdict is public by design (a failed open is reported): declassified here, + // where webcpp's code first branches on it, for the constant-time checks. + // Not const: the branch below must read the variable again after the declassifying + // client request, whose memory clobber reaches a mutable object only. + // NOLINTNEXTLINE(misc-const-correctness): see above + bool tag_matches = equal(computed_tag, tag_bytes); + WEBCPP_CRYPTO_DETAIL_DECLASSIFY(&tag_matches, sizeof tag_matches); + wipe(computed_tag.data(), computed_tag.size()); + if (!tag_matches) { + return error::authentication_failed; + } + return {}; + } + + /** + * Moves the key into an empty state, and wipes the source. + * + * @param target_state An empty state. + * @param source_state A keyed state, wiped. + */ + static void move(state& target_state, state& source_state) noexcept { + target_state.key = source_state.key; + wipe_object(source_state.key); + } + + /** + * Wipes the key; the state is empty. + * + * @param engine_state Any state. + */ + static void reset(state& engine_state) noexcept { wipe_object(engine_state.key); } +}; + /** * BearSSL has no AES block cipher: its state is empty, so `ciphers::aes256` is * complete, and `ciphers::gcm>` can read its key size. diff --git a/include/webcpp/crypto/backends/openssl.hpp b/include/webcpp/crypto/backends/openssl.hpp index efa857d9..73bddf39 100644 --- a/include/webcpp/crypto/backends/openssl.hpp +++ b/include/webcpp/crypto/backends/openssl.hpp @@ -7,11 +7,11 @@ /** The backend OpenSSL: OpenSSL 3.5.9 built from `third_party/libs/openssl` by `/webcpp/crypto//openssl`, static, on native, wasip2 and wasip3; never on Emscripten. It - serves `ciphers::aes128/192/256` and `ciphers::gcm<...>`. Its - `make` allocates through OpenSSL's own functions, unless a native program sets - `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE`, which sends every allocation of OpenSSL's to - `openssl_memory_resource()`. On MSVC, wasip2 and wasip3 OpenSSL is compiled - without assembly: table-driven AES and 4-bit GHASH, no AES-NI, not constant time. + serves `ciphers::aes128/192/256`, `ciphers::gcm<...>` and + `ciphers::chacha20_poly1305`. Its `make` allocates through OpenSSL's own + functions, unless a native program sets `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE`, which sends every + allocation of OpenSSL's to `openssl_memory_resource()`. On MSVC, wasip2 and wasip3 OpenSSL is + compiled without assembly: table-driven AES and 4-bit GHASH, no AES-NI, not constant time. OpenSSL's default initialisation reads the configuration file of the directory it was configured with (`/etc/ssl/openssl.cnf`, when the machine has one), as any program of OpenSSL does; what it raises meanwhile is popped with the backend's mark. @@ -44,6 +44,7 @@ "webcpp::crypto: the backend OpenSSL needs OpenSSL 3.0 or later, and the headers found are of an older OpenSSL. In the program's Jamfile, name /webcpp/crypto//openssl, which builds OpenSSL 3.5.9. (without b2: put OpenSSL 3's include/ first)" #else +#include #include #include #include @@ -539,6 +540,110 @@ struct gcm_engine { } }; +/** ChaCha20-Poly1305's state on OpenSSL: one context, keyed once. */ +template <> +struct aead_state { + /** The context, keyed for ChaCha20-Poly1305; null when the object holds no key. */ + EVP_CIPHER_CTX* context = nullptr; +}; + +/** + * ChaCha20-Poly1305 on OpenSSL (`EVP_chacha20_poly1305`, fetched by name). A message runs GCM's + * sequence of calls on its own context, borrowed from GCM's engine: the controls GCM's engine + * sends are the AEAD ones, which OpenSSL 3 names twice (`EVP_CTRL_GCM_SET_IVLEN` is + * `EVP_CTRL_AEAD_SET_IVLEN`, and so are the tag's, include/openssl/evp.h). The error queue is + * left as GCM's engine leaves it. + */ +template <> +struct aead_engine { + /** The state. */ + using state = aead_state; + /** GCM's engine, whose message calls take a state that names the context alone. */ + using sequence = gcm_engine; + + /** + * Keys a context for ChaCha20-Poly1305 with the key. + * + * @param engine_state An empty state. + * @param key_bytes 32 bytes. + * @return Nothing; `errc::not_enough_memory`; `backend_failure`. + */ + [[nodiscard]] static boost::system::result init( + state& engine_state, std::span key_bytes) noexcept { + EVP_CIPHER_CTX* made_context = nullptr; + if (auto const failure_code = + openssl_context(made_context, "ChaCha20-Poly1305", key_bytes, true, true)) { + return failure_code; + } + engine_state.context = made_context; + return {}; + } + + /** + * Encrypts `data_bytes` in place and gives the tag. + * + * @param engine_state A keyed state. + * @param iv_bytes 12 bytes. + * @param additional_data_bytes Authenticated, not encrypted. + * @param data_bytes The message. + * @param tag_bytes The tag. + * @return Nothing; `backend_failure`. + */ + [[nodiscard]] static boost::system::result seal( + state& engine_state, std::span iv_bytes, + std::span additional_data_bytes, std::span data_bytes, + boost::hash2::digest<16>& tag_bytes) noexcept { + sequence::state view{engine_state.context}; + auto const started = sequence::start(view, true, iv_bytes, additional_data_bytes); + if (!started) { + return started; + } + auto const ran = sequence::run(view, data_bytes); + if (!ran) { + return ran; + } + return sequence::tag(view, tag_bytes); + } + + /** + * Decrypts `data_bytes` in place and checks the tag; `aead` zeroes the data when it does not + * match. + * + * @param engine_state A keyed state. + * @param iv_bytes 12 bytes. + * @param additional_data_bytes The additional data of the seal. + * @param data_bytes The ciphertext. + * @param tag_bytes The expected tag. + * @return Nothing; `authentication_failed`; `backend_failure`. + */ + [[nodiscard]] static boost::system::result open( + state& engine_state, std::span iv_bytes, + std::span additional_data_bytes, std::span data_bytes, + std::array const& tag_bytes) noexcept { + sequence::state view{engine_state.context}; + auto const started = sequence::start(view, false, iv_bytes, additional_data_bytes); + if (!started) { + return started; + } + auto const ran = sequence::run(view, data_bytes); + if (!ran) { + return ran; + } + return sequence::check(view, tag_bytes); + } + + /** Moves the context, leaving the source empty. */ + static void move(state& target_state, state& source_state) noexcept { + target_state.context = std::exchange(source_state.context, nullptr); + } + + // EVP_CIPHER_CTX_free cleanses the key before it frees. + /** Frees the context. */ + static void reset(state& engine_state) noexcept { + EVP_CIPHER_CTX_free(std::exchange(engine_state.context, nullptr)); + } +}; + /** * The block cipher's state on OpenSSL: a context per direction, since a context keyed for * encryption keeps the encryption schedule only. diff --git a/include/webcpp/crypto/ciphers/aead.hpp b/include/webcpp/crypto/ciphers/aead.hpp index d7e2e743..c401dd21 100644 --- a/include/webcpp/crypto/ciphers/aead.hpp +++ b/include/webcpp/crypto/ciphers/aead.hpp @@ -304,8 +304,11 @@ class aead { * Seals a message in place: `data_bytes` holds the plaintext before and the ciphertext * after. * - * The nonce and the additional data are read before the first byte of `data_bytes` is - * written, so they may lie in `data_bytes`. + * The nonce is read before the first byte of `data_bytes` is written, so it may lie in + * `data_bytes`. The additional data may touch `data_bytes`, as a wire format that puts it + * just before the message does, but not overlap it: BearSSL's ChaCha20-Poly1305 reads it + * after it encrypts, in one call over the whole message, and an overlap would give a tag + * that no open accepts. * * @param iv_bytes The nonce, `iv_size` bytes, never repeated under this key. * @param additional_data_bytes Authenticated, not encrypted. diff --git a/include/webcpp/crypto/detail/capabilities.hpp b/include/webcpp/crypto/detail/capabilities.hpp index 1b66f490..503f6a40 100644 --- a/include/webcpp/crypto/detail/capabilities.hpp +++ b/include/webcpp/crypto/detail/capabilities.hpp @@ -170,6 +170,16 @@ inline constexpr bool supported inline constexpr bool supported = true; #endif +// ChaCha20-Poly1305 on bearssl: native, wasip2, wasip3, emscripten. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool supported = true; +#endif +// ChaCha20-Poly1305 on openssl: native, wasip2, wasip3. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) +template <> +inline constexpr bool supported = true; +#endif // original ChaCha20-Poly1305 on sodium: native, wasip2, wasip3, emscripten. #if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) template <> @@ -423,43 +433,43 @@ inline constexpr bool linked = true; #ifdef WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE /** The refusals of the family ChaCha20-Poly1305's primary engine for `Backend`, on native. */ #define WEBCPP_CRYPTO_DETAIL_REFUSE_CHACHA20_POLY1305(Backend) \ - static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v, "webcpp::crypto: openssl has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl's ChaCha20-Poly1305 is in , which the program does not include. Include it, and add /third_party//bearssl to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl's ChaCha20-Poly1305 is in , which the program does not include. Include it, and add /webcpp/crypto//openssl to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; or name another backend in the type, as in ciphers::chacha20_poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's ChaCha20-Poly1305 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ - static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: ChaCha20-Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: ChaCha20-Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).") #elif defined(WEBCPP_TARGET_WASIP2) /** The refusals of the family ChaCha20-Poly1305's primary engine for `Backend`, on wasip2. */ #define WEBCPP_CRYPTO_DETAIL_REFUSE_CHACHA20_POLY1305(Backend) \ - static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v, "webcpp::crypto: openssl has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl's ChaCha20-Poly1305 is in , which the program does not include. Include it, and add /third_party//bearssl to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl's ChaCha20-Poly1305 is in , which the program does not include. Include it, and add /webcpp/crypto//openssl to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; or name another backend in the type, as in ciphers::chacha20_poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's ChaCha20-Poly1305 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ - static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: ChaCha20-Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: ChaCha20-Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).") #elif defined(WEBCPP_TARGET_WASIP3) /** The refusals of the family ChaCha20-Poly1305's primary engine for `Backend`, on wasip3. */ #define WEBCPP_CRYPTO_DETAIL_REFUSE_CHACHA20_POLY1305(Backend) \ - static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v, "webcpp::crypto: openssl has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl's ChaCha20-Poly1305 is in , which the program does not include. Include it, and add /third_party//bearssl to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl's ChaCha20-Poly1305 is in , which the program does not include. Include it, and add /webcpp/crypto//openssl to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; or name another backend in the type, as in ciphers::chacha20_poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's ChaCha20-Poly1305 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ - static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: ChaCha20-Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: ChaCha20-Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).") #elif defined(WEBCPP_TARGET_EMSCRIPTEN) /** The refusals of the family ChaCha20-Poly1305's primary engine for `Backend`, on emscripten. */ #define WEBCPP_CRYPTO_DETAIL_REFUSE_CHACHA20_POLY1305(Backend) \ - static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v, "webcpp::crypto: openssl has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl's ChaCha20-Poly1305 is in , which the program does not include. Include it, and add /third_party//bearssl to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no ChaCha20-Poly1305 on emscripten. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; or name another backend in the type, as in ciphers::chacha20_poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's ChaCha20-Poly1305 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ - static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: ChaCha20-Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: ChaCha20-Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).") #endif #ifdef WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE /** diff --git a/test/Jamfile b/test/Jamfile index 20053d5c..06fb815c 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -329,6 +329,19 @@ crypto-run chacha_wycheproof_sodium : chacha_wycheproof_sodium_test.cpp /webcpp//boost_json ; crypto-run allocation_sodium : allocation_sodium_test.cpp : /third_party//sodium ; +# 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. +crypto-run chacha_bearssl : chacha_bearssl_test.cpp : /third_party//bearssl ; +crypto-run chacha_wycheproof_bearssl : chacha_wycheproof_bearssl_test.cpp + : /third_party//bearssl /third_party//wycheproof + /webcpp//boost_json ; +crypto-run chacha_openssl : chacha_openssl_test.cpp : /webcpp/crypto//openssl + : native wasip2 wasip3 ; +crypto-run chacha_wycheproof_openssl : chacha_wycheproof_openssl_test.cpp + : /webcpp/crypto//openssl /third_party//wycheproof + /webcpp//boost_json : native wasip2 wasip3 ; + # The capability table of doc/tables/crypto.json, which generate.py writes # this test from: supports_v of every cell on the target, and each present # cell made, with every backend the target builds linked. @@ -361,6 +374,28 @@ crypto-run agreement_gcm_portable : agreement_gcm_portable_test.cpp WEBCPP_CRYPTO_DETAIL_BEARSSL_PORTABLE : native wasip2 wasip3 ; +# libsodium, BearSSL and OpenSSL pairwise on ChaCha20-Poly1305 (spec section +# 8.2), on native, wasip2 and wasip3; on Emscripten, which has no OpenSSL, +# libsodium against BearSSL. The portable twins keep BearSSL on chacha20_ct +# and poly1305_ctmul through the backend's test seam, as AES-GCM's does: on +# x86-64 its other ChaCha20 is SSE2's, and wherever the compiler has 128-bit +# integers, the WebAssembly targets included, its other Poly1305 is ctmulq. +crypto-run agreement_chacha : agreement_chacha_test.cpp + : /third_party//sodium /third_party//bearssl + /webcpp/crypto//openssl + : native wasip2 wasip3 ; +crypto-run agreement_chacha_emscripten : agreement_chacha_test.cpp + : /third_party//sodium /third_party//bearssl + : emscripten ; +crypto-run agreement_chacha_portable : agreement_chacha_portable_test.cpp + : /third_party//sodium /third_party//bearssl + /webcpp/crypto//openssl WEBCPP_CRYPTO_DETAIL_BEARSSL_PORTABLE + : native wasip2 wasip3 ; +crypto-run agreement_chacha_portable_emscripten : agreement_chacha_portable_test.cpp + : /third_party//sodium /third_party//bearssl + WEBCPP_CRYPTO_DETAIL_BEARSSL_PORTABLE + : emscripten ; + # 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/agreement_chacha_portable_test.cpp b/test/agreement_chacha_portable_test.cpp new file mode 100644 index 00000000..67d382ac --- /dev/null +++ b/test/agreement_chacha_portable_test.cpp @@ -0,0 +1,12 @@ +// 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) + +// agreement_chacha_test.cpp with WEBCPP_CRYPTO_DETAIL_BEARSSL_PORTABLE, which the Jamfile +// defines: BearSSL on chacha20_ct and poly1305_ctmul against libsodium and OpenSSL. A source of +// its own, so that b2 compiles it with its own defines (spec section 4.3's pitfall); the code is +// shared. + +#include "agreement_chacha_test.cpp" // NOLINT(bugprone-suspicious-include): one program, twice diff --git a/test/agreement_chacha_test.cpp b/test/agreement_chacha_test.cpp new file mode 100644 index 00000000..466f85dc --- /dev/null +++ b/test/agreement_chacha_test.cpp @@ -0,0 +1,74 @@ +// 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) + +// ChaCha20-Poly1305 on libsodium, BearSSL and OpenSSL, pairwise (spec section 8.2), with a +// fixed seed and with one the system draws, printed first; on Emscripten, which has no OpenSSL, +// libsodium against BearSSL. agreement_chacha_portable_test.cpp compiles this source again with +// WEBCPP_CRYPTO_DETAIL_BEARSSL_PORTABLE defined, so that both of BearSSL's code paths meet the +// others'; each program first checks that BearSSL runs the code the seam says. + +#include +#include +#ifdef WEBCPP_CRYPTO_HAS_OPENSSL +#include +#endif +#include + +#include "support/agreement.hpp" + +#include + +#include +#include +#include + +namespace { + +namespace crypto = webcpp::crypto; + +/** Checks that BearSSL runs the code the seam selects. */ +void check_code_paths() { +#ifdef WEBCPP_CRYPTO_DETAIL_BEARSSL_PORTABLE + // On every target the seam keeps the constant-time portable code. + BOOST_TEST(crypto::detail::bearssl_chacha20() == &br_chacha20_ct_run); + BOOST_TEST(crypto::detail::bearssl_poly1305() == &br_poly1305_ctmul_run); +#else + // Without it, SSE2's ChaCha20 and the 64-bit multiplication's Poly1305 where the CPU and the + // build have them. + br_chacha20_run const sse2 = br_chacha20_sse2_get(); + br_poly1305_run const ctmulq = br_poly1305_ctmulq_get(); + BOOST_TEST(crypto::detail::bearssl_chacha20() == + (sse2 != nullptr ? sse2 : &br_chacha20_ct_run)); + BOOST_TEST(crypto::detail::bearssl_poly1305() == + (ctmulq != nullptr ? ctmulq : &br_poly1305_ctmul_run)); + std::printf("BearSSL's ChaCha20: %s; its Poly1305: %s\n", sse2 != nullptr ? "SSE2" : "ct", + ctmulq != nullptr ? "ctmulq" : "ctmul"); +#endif +} + +/** Every pair of the target's backends from one seed. */ +void agree(std::uint64_t seed) { + using crypto::backends::bearssl; + using crypto::backends::sodium; + webcpp::test::agree_chacha(seed); +#ifdef WEBCPP_CRYPTO_HAS_OPENSSL + using crypto::backends::openssl; + webcpp::test::agree_chacha(seed); + webcpp::test::agree_chacha(seed); +#endif +} + +} // namespace + +int main() { + check_code_paths(); + // A fixed seed, so that a failure repeats. + agree(20261011); + std::uint64_t const seed = std::random_device{}(); + std::printf("seed %llu\n", static_cast(seed)); + agree(seed); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/allocation_bearssl_test.cpp b/test/allocation_bearssl_test.cpp index 84aef5e1..ea04869d 100644 --- a/test/allocation_bearssl_test.cpp +++ b/test/allocation_bearssl_test.cpp @@ -5,10 +5,12 @@ // https://www.boost.org/LICENSE_1_0.txt) // On BearSSL nothing allocates (spec section 3.2): make, seal, open, the incremental seal, -// equal and random_device's fill make no call of operator new, nor of the C library's +// equal and random_device's fill, and ChaCha20-Poly1305's make, seal, open (good and failed) +// and move 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. #include +#include #include #include // lint-world: a test #include @@ -23,6 +25,7 @@ #include #include #include +#include int main() { namespace crypto = webcpp::crypto; @@ -54,6 +57,16 @@ int main() { BOOST_TEST(made->update(data).has_value()); BOOST_TEST(made->result().has_value()); BOOST_TEST(crypto::equal(*tag, *tag)); + using chacha = crypto::ciphers::chacha20_poly1305; + auto sealer = chacha::make(key); + BOOST_TEST(sealer.has_value()); + auto const sealed = sealer->seal(iv, iv, data); + BOOST_TEST(sealed.has_value()); + BOOST_TEST(sealer->open(iv, iv, data, *sealed).has_value()); + std::array const forged{}; + BOOST_TEST(sealer->open(iv, iv, data, forged).error() == + crypto::error::authentication_failed); + chacha const moved = std::move(*sealer); } BOOST_TEST_EQ(webcpp::test::allocations(), before); return webcpp::test::exit_status(boost::report_errors()); diff --git a/test/allocation_openssl_test.cpp b/test/allocation_openssl_test.cpp index 888dd63a..1af6f864 100644 --- a/test/allocation_openssl_test.cpp +++ b/test/allocation_openssl_test.cpp @@ -6,13 +6,15 @@ // On OpenSSL a message allocates nothing (spec section 8.5): after make, which allocates // through OpenSSL's functions (counted here and printed, not refused), seal, open (good and -// failed), the incremental seal, encrypt and decrypt make no call of OpenSSL's allocator, of +// failed), the incremental seal, encrypt and decrypt, and ChaCha20-Poly1305's seal and open +// (good and failed) make no call of OpenSSL's allocator, of // operator new, nor of the C library's allocator where the target lets a program count it. // OpenSSL's allocations are outside the user's allocator (the accepted departure); its count // is measured per target on OpenSSL 3.5.9 (native with assembly; MSVC, wasip2 and wasip3 // without it). #include +#include #include #include "support/counting.hpp" @@ -77,7 +79,12 @@ int main() { std::size_t const second_count = openssl_allocations.load() - second_first; BOOST_TEST(second.has_value()); std::printf("second make: %zu\n", second_count); - if (!made.has_value() || !second.has_value()) { + std::size_t const chacha_first = openssl_allocations.load(); + auto chacha = crypto::ciphers::chacha20_poly1305::make(key); + std::size_t const chacha_count = openssl_allocations.load() - chacha_first; + BOOST_TEST(chacha.has_value()); + std::printf("ChaCha20-Poly1305's make: %zu\n", chacha_count); + if (!made.has_value() || !second.has_value() || !chacha.has_value()) { return webcpp::test::exit_status(boost::report_errors()); } @@ -93,6 +100,10 @@ int main() { bool const resulted = made->result().has_value(); bool const encrypted = second->encrypt(block).has_value(); bool const decrypted = second->decrypt(block).has_value(); + auto const chacha_tag = chacha->seal(iv, iv, data); + bool const chacha_sealed = chacha_tag.has_value(); + bool const chacha_opened = chacha_sealed && chacha->open(iv, iv, data, *chacha_tag).has_value(); + bool const chacha_refused = !chacha->open(iv, iv, data, wrong).has_value(); std::size_t const after = webcpp::test::allocations(); std::size_t const own_after = openssl_allocations.load(); BOOST_TEST(sealed); @@ -103,6 +114,9 @@ int main() { BOOST_TEST(resulted); BOOST_TEST(encrypted); BOOST_TEST(decrypted); + BOOST_TEST(chacha_sealed); + BOOST_TEST(chacha_opened); + BOOST_TEST(chacha_refused); BOOST_TEST_EQ(own_after, own_before); BOOST_TEST_EQ(after, before); return webcpp::test::exit_status(boost::report_errors()); diff --git a/test/capabilities_test.cpp b/test/capabilities_test.cpp index 16e6129b..a6cd0d33 100644 --- a/test/capabilities_test.cpp +++ b/test/capabilities_test.cpp @@ -248,10 +248,18 @@ static_assert(crypto::supports_v, #else static_assert(!crypto::supports_v, backends::sodium>); #endif -// ChaCha20-Poly1305 on bearssl: none. +// ChaCha20-Poly1305 on bearssl: native, wasip2, wasip3, emscripten. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_v, backends::bearssl>); +#else static_assert(!crypto::supports_v, backends::bearssl>); -// ChaCha20-Poly1305 on openssl: none. +#endif +// ChaCha20-Poly1305 on openssl: native, wasip2, wasip3. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) +static_assert(crypto::supports_v, backends::openssl>); +#else static_assert(!crypto::supports_v, backends::openssl>); +#endif // ChaCha20-Poly1305 on ctaes: none. static_assert(!crypto::supports_v, backends::ctaes>); // ChaCha20-Poly1305 on secp256k1: none. @@ -342,6 +350,12 @@ int main() { #if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN)) && defined(WEBCPP_CRYPTO_HAS_SODIUM) BOOST_TEST((webcpp::test::made, families::x25519, families::x25519, backends::sodium>())); #endif +#if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN)) && defined(WEBCPP_CRYPTO_HAS_BEARSSL) + BOOST_TEST((webcpp::test::made, families::chacha20_poly1305, families::chacha20_poly1305, backends::bearssl>())); +#endif +#if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3)) && defined(WEBCPP_CRYPTO_HAS_OPENSSL) + BOOST_TEST((webcpp::test::made, families::chacha20_poly1305, families::chacha20_poly1305, backends::openssl>())); +#endif #if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN)) && defined(WEBCPP_CRYPTO_HAS_SODIUM) BOOST_TEST((webcpp::test::made, families::chacha20_poly1305, families::chacha20_poly1305, backends::sodium>())); #endif diff --git a/test/chacha_bearssl_test.cpp b/test/chacha_bearssl_test.cpp new file mode 100644 index 00000000..1f38fe76 --- /dev/null +++ b/test/chacha_bearssl_test.cpp @@ -0,0 +1,46 @@ +// 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) + +// ChaCha20-Poly1305 (RFC 8439) on BearSSL, on every target: RFC 8439's section 2.8.2 and +// appendix A.5 and libsodium's own case, every guard, tampering, moves, empty inputs and +// aliasing spans (support/aead_checks.hpp), and natively the message's limit. BearSSL's ChaCha20 +// and Poly1305 run in one function over the whole message, the tag compared by equal. + +#include +#include +#include +#include + +#include "support/aead_checks.hpp" + +#include + +#include +#include +#include + +namespace crypto = webcpp::crypto; + +using chacha = crypto::ciphers::chacha20_poly1305; + +// The type names its family and its algorithm as the capability table does, and the table +// has the cell on this target. +static_assert(std::is_same_v>); +static_assert(std::is_same_v); +static_assert(crypto::supports_v); +static_assert(chacha::key_size == 32 && chacha::iv_size == 12 && chacha::tag_size == 16); +static_assert(chacha::max_message_size == (std::uint64_t{1} << 38U) - 64); + +int main() { + webcpp::test::check_aead(webcpp::test::chacha20_poly1305_cases); +#if !defined(__wasi__) && !defined(__EMSCRIPTEN__) + if constexpr (sizeof(std::size_t) == 8) { + webcpp::test::check_aead_limits(); + } +#endif + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/chacha_openssl_test.cpp b/test/chacha_openssl_test.cpp new file mode 100644 index 00000000..f7439468 --- /dev/null +++ b/test/chacha_openssl_test.cpp @@ -0,0 +1,46 @@ +// 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) + +// ChaCha20-Poly1305 (RFC 8439) on OpenSSL, on native, wasip2 and wasip3: RFC 8439's section 2.8.2 +// and appendix A.5 and libsodium's own case, every guard, tampering, moves, empty inputs and +// aliasing spans (support/aead_checks.hpp), and natively the message's limit. OpenSSL's +// EVP_chacha20_poly1305, the error queue left as found (openssl_error_queue_test.cpp). + +#include +#include +#include +#include + +#include "support/aead_checks.hpp" + +#include + +#include +#include +#include + +namespace crypto = webcpp::crypto; + +using chacha = crypto::ciphers::chacha20_poly1305; + +// The type names its family and its algorithm as the capability table does, and the table +// has the cell on this target. +static_assert(std::is_same_v>); +static_assert(std::is_same_v); +static_assert(crypto::supports_v); +static_assert(chacha::key_size == 32 && chacha::iv_size == 12 && chacha::tag_size == 16); +static_assert(chacha::max_message_size == (std::uint64_t{1} << 38U) - 64); + +int main() { + webcpp::test::check_aead(webcpp::test::chacha20_poly1305_cases); +#if !defined(__wasi__) && !defined(__EMSCRIPTEN__) + if constexpr (sizeof(std::size_t) == 8) { + webcpp::test::check_aead_limits(); + } +#endif + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/chacha_wycheproof_bearssl_test.cpp b/test/chacha_wycheproof_bearssl_test.cpp new file mode 100644 index 00000000..5b669ffe --- /dev/null +++ b/test/chacha_wycheproof_bearssl_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) + +// ChaCha20-Poly1305 on BearSSL against Wycheproof's vectors, read at run time from +// third_party/libs/wycheproof (support/wycheproof_aead.hpp): of chacha20_poly1305_test.json's +// 325 tests, 256 valid, 60 invalid and 9 with a nonce of another size than 12 bytes. + +#include +#include +#include + +#include "support/wycheproof_aead.hpp" + +#include + +int main() { + namespace ciphers = webcpp::crypto::ciphers; + webcpp::test::check_wycheproof_aead< + ciphers::chacha20_poly1305>( + "chacha20_poly1305_test.json", {.valid = 256, .invalid = 60, .other_iv = 9}); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/chacha_wycheproof_openssl_test.cpp b/test/chacha_wycheproof_openssl_test.cpp new file mode 100644 index 00000000..495ecc0c --- /dev/null +++ b/test/chacha_wycheproof_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) + +// ChaCha20-Poly1305 on OpenSSL against Wycheproof's vectors, read at run time from +// third_party/libs/wycheproof (support/wycheproof_aead.hpp): of chacha20_poly1305_test.json's +// 325 tests, 256 valid, 60 invalid and 9 with a nonce of another size than 12 bytes. + +#include +#include +#include + +#include "support/wycheproof_aead.hpp" + +#include + +int main() { + namespace ciphers = webcpp::crypto::ciphers; + webcpp::test::check_wycheproof_aead< + ciphers::chacha20_poly1305>( + "chacha20_poly1305_test.json", {.valid = 256, .invalid = 60, .other_iv = 9}); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/messages/Jamfile b/test/messages/Jamfile index 2c0fa975..13e12a2f 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -31,3 +31,4 @@ build-project ed25519_default_not_linked ; build-project heavy_without_threads ; build-project chacha_default_not_linked ; build-project aead_not_a_family ; +build-project chacha_on_ctaes ; diff --git a/test/messages/chacha_default_not_linked/chacha_default_not_linked.cpp b/test/messages/chacha_default_not_linked/chacha_default_not_linked.cpp index 1da936ea..03104350 100644 --- a/test/messages/chacha_default_not_linked/chacha_default_not_linked.cpp +++ b/test/messages/chacha_default_not_linked/chacha_default_not_linked.cpp @@ -6,12 +6,13 @@ // A program that calls the three ChaCha20-Poly1305 AEADs on their default backend, libsodium // on every target, without linking it, stops where it calls each, with the line that links -// libsodium (design D32; ruling C20). +// libsodium, and for ChaCha20-Poly1305, which BearSSL and OpenSSL also have, the type that +// names another backend (design D32; ruling C20). // 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/ciphers/aead.hpp:* {{webcpp::crypto: ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)}} +// expected-error@webcpp/crypto/ciphers/aead.hpp:* {{webcpp::crypto: ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; or name another backend in the type, as in ciphers::chacha20_poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)}} // expected-error@webcpp/crypto/ciphers/aead.hpp:* {{webcpp::crypto: original ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)}} // expected-error@webcpp/crypto/ciphers/aead.hpp:* {{webcpp::crypto: XChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)}} // clang-format on diff --git a/test/messages/chacha_on_ctaes/Jamfile b/test/messages/chacha_on_ctaes/Jamfile new file mode 100644 index 00000000..8ef56cb2 --- /dev/null +++ b/test/messages/chacha_on_ctaes/Jamfile @@ -0,0 +1,12 @@ +# 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 ; + +webcpp.compile-diagnostic chacha_on_ctaes : chacha_on_ctaes.cpp + : /third_party//ctaes : native wasip2 wasip3 ; diff --git a/test/messages/chacha_on_ctaes/chacha_on_ctaes.cpp b/test/messages/chacha_on_ctaes/chacha_on_ctaes.cpp new file mode 100644 index 00000000..a4ef042b --- /dev/null +++ b/test/messages/chacha_on_ctaes/chacha_on_ctaes.cpp @@ -0,0 +1,24 @@ +// 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) + +// ChaCha20-Poly1305 on ctaes, which exports the AES block cipher alone, is refused where it is +// called, with the backends that have it and their targets (the generated refusal, +// detail/capabilities.hpp). + +// clang-format off +// expected-error@webcpp/crypto/ciphers/aead.hpp:* {{webcpp::crypto: ctaes has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).}} +// clang-format on +#include +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const key{}; + return crypto::ciphers::chacha20_poly1305::make(key) ? 0 : 1; +} diff --git a/test/msvc/Jamfile b/test/msvc/Jamfile index fa0e62aa..347578e6 100644 --- a/test/msvc/Jamfile +++ b/test/msvc/Jamfile @@ -50,3 +50,4 @@ build-project ed25519_default_not_linked ; build-project heavy_without_threads ; build-project chacha_default_not_linked ; build-project aead_not_a_family ; +build-project chacha_on_ctaes ; diff --git a/test/msvc/chacha_on_ctaes/Jamfile b/test/msvc/chacha_on_ctaes/Jamfile new file mode 100644 index 00000000..0cc0c37f --- /dev/null +++ b/test/msvc/chacha_on_ctaes/Jamfile @@ -0,0 +1,11 @@ +# 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 chacha_on_ctaes : app.cpp + : /webcpp/crypto//crypto /third_party//ctaes + : native ; diff --git a/test/msvc/chacha_on_ctaes/app.cpp b/test/msvc/chacha_on_ctaes/app.cpp new file mode 100644 index 00000000..b0b058f3 --- /dev/null +++ b/test/msvc/chacha_on_ctaes/app.cpp @@ -0,0 +1,19 @@ +// 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) + +// ChaCha20-Poly1305 on ctaes, which exports the AES block cipher alone: refused. +#include +#include + +#include +#include + +int main() { + std::array const key{}; + auto made = + webcpp::crypto::ciphers::chacha20_poly1305::make(key); + return made ? 0 : 1; +} diff --git a/test/openssl_error_queue_test.cpp b/test/openssl_error_queue_test.cpp index 72f54cfc..9d65aa30 100644 --- a/test/openssl_error_queue_test.cpp +++ b/test/openssl_error_queue_test.cpp @@ -4,12 +4,14 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// OpenSSL's error queue (spec section 3.3): on an empty queue, a make of the block cipher -// and of gcm leaves it empty; an entry of the caller's survives a make, a seal, a good open -// and a failed one, and nothing of webcpp's is left beside it. +// OpenSSL's error queue (spec section 3.3): on an empty queue, a make of the block cipher, +// of gcm and of ChaCha20-Poly1305 leaves it empty; for each AEAD, an entry of the caller's +// survives a make, a seal, a good open and a failed one, and nothing of webcpp's is left +// beside it. #include #include +#include #include #include @@ -20,6 +22,7 @@ #include #include #include +#include namespace { @@ -33,34 +36,51 @@ std::size_t drain(unsigned long& first) { return count; } +/** + * An entry of the caller's survives a make of `Aead`, a seal, a good open and a failed one, and + * is the queue's one entry afterwards. + */ +template +void check_queue(std::span key, std::span iv) { + namespace crypto = webcpp::crypto; + std::array data{}; + // NOLINTNEXTLINE(bugprone-signed-bitwise): OpenSSL's reason macro ORs signed flags + ERR_raise(ERR_LIB_USER, ERR_R_PASSED_INVALID_ARGUMENT); + unsigned long const ours = ERR_peek_last_error(); + auto made = Aead::make(key); + BOOST_TEST(made.has_value()); + if (!made) { + return; + } + auto const tag = made->seal(iv, {}, data); + BOOST_TEST(tag.has_value()); + BOOST_TEST(tag && made->open(iv, {}, data, *tag).has_value()); + std::array const bad{}; + BOOST_TEST(made->open(iv, {}, data, bad).error() == crypto::error::authentication_failed); + unsigned long first = 0; + BOOST_TEST_EQ(drain(first), 1U); + BOOST_TEST_EQ(first, ours); +} + } // namespace int main() { namespace crypto = webcpp::crypto; - using aead = crypto::ciphers::gcm>; + using gcm = crypto::ciphers::gcm>; + using chacha = crypto::ciphers::chacha20_poly1305; std::array const key{}; std::array const iv{}; - std::array data{}; // OpenSSL's first fetch and its initialisation leave nothing behind either. BOOST_TEST_EQ(ERR_peek_error(), 0UL); BOOST_TEST(crypto::ciphers::aes256::make(key).has_value()); BOOST_TEST_EQ(ERR_peek_error(), 0UL); - BOOST_TEST(aead::make(key).has_value()); + BOOST_TEST(gcm::make(key).has_value()); + BOOST_TEST_EQ(ERR_peek_error(), 0UL); + BOOST_TEST(chacha::make(key).has_value()); BOOST_TEST_EQ(ERR_peek_error(), 0UL); - // NOLINTNEXTLINE(bugprone-signed-bitwise): OpenSSL's reason macro ORs signed flags - ERR_raise(ERR_LIB_USER, ERR_R_PASSED_INVALID_ARGUMENT); - unsigned long const ours = ERR_peek_last_error(); - auto made = aead::make(key); - BOOST_TEST(made.has_value()); - auto const tag = made->seal(iv, {}, data); - BOOST_TEST(tag.has_value()); - BOOST_TEST(made->open(iv, {}, data, *tag).has_value()); - std::array bad{}; - BOOST_TEST(made->open(iv, {}, data, bad).error() == crypto::error::authentication_failed); - unsigned long first = 0; - BOOST_TEST_EQ(drain(first), 1U); - BOOST_TEST_EQ(first, ours); + check_queue(key, iv); + check_queue(key, iv); return webcpp::test::exit_status(boost::report_errors()); } diff --git a/test/support/aead_checks.hpp b/test/support/aead_checks.hpp index 6b194f5d..7c8fb715 100644 --- a/test/support/aead_checks.hpp +++ b/test/support/aead_checks.hpp @@ -459,27 +459,31 @@ void check_aead_overlap(Aead& made, std::span iv) { } /** - * An IV and additional data inside the sealed buffer itself give what copies of them give: - * both are read before the first byte of the data is written. + * An IV inside the sealed buffer, and additional data just before it in the same buffer, give + * what copies of them give: the IV is read before the first byte of the data is written, and + * the additional data, which may touch the data but not overlap it, is left as it was. */ template void check_aead_in_place(Aead& made) { constexpr std::size_t additional_size = 16; - std::array buffer{}; + std::array buffer{}; for (std::size_t i = 0; i < buffer.size(); ++i) { buffer[i] = static_cast((i * 7) + 1); } + auto const original = buffer; std::array iv_copy{}; std::array additional_copy{}; - auto data_copy = buffer; - std::copy_n(buffer.begin(), Aead::iv_size, iv_copy.begin()); - std::copy_n(buffer.begin() + Aead::iv_size, additional_size, additional_copy.begin()); + std::copy_n(buffer.begin(), additional_size, additional_copy.begin()); + std::copy_n(buffer.begin() + additional_size, Aead::iv_size, iv_copy.begin()); + std::array data_copy{}; + std::copy_n(buffer.begin() + additional_size, data_copy.size(), data_copy.begin()); auto const expected = made.seal(iv_copy, additional_copy, data_copy); + auto const data = std::span(buffer).subspan(additional_size); auto const in_place = - made.seal(std::span(buffer).first(Aead::iv_size), - std::span(buffer).subspan(Aead::iv_size, additional_size), buffer); + made.seal(data.first(Aead::iv_size), std::span(buffer).first(additional_size), data); BOOST_TEST(expected && in_place && to_hex(*expected) == to_hex(*in_place)); - BOOST_TEST(data_copy == buffer); + BOOST_TEST(std::equal(data_copy.begin(), data_copy.end(), data.begin())); + BOOST_TEST(std::equal(original.begin(), original.begin() + additional_size, buffer.begin())); } /** diff --git a/test/support/agreement.hpp b/test/support/agreement.hpp index 8b81ed81..8f64be22 100644 --- a/test/support/agreement.hpp +++ b/test/support/agreement.hpp @@ -14,11 +14,17 @@ // // The AES block cipher: 10,000 random keys of each size, each with a random message of 0 to // 64 blocks; encrypting and decrypting give the same bytes on both backends. +// +// ChaCha20-Poly1305: a random key, a 12-byte nonce and 0 to 64 bytes of additional data per +// message, messages of every size within 1 of a multiple of 64 up to 4,096 bytes and one in +// sixteen of the others. What one seals the other opens, and the ciphertexts and tags are +// byte-identical. #ifndef WEBCPP_TEST_CRYPTO_SUPPORT_AGREEMENT_HPP #define WEBCPP_TEST_CRYPTO_SUPPORT_AGREEMENT_HPP #include +#include #include #include @@ -159,6 +165,56 @@ void agree_aes(std::uint64_t seed) { agree_aes_size, ciphers::aes256>(generator, seed); } +/** One ChaCha20-Poly1305 message on backends A and B; false once they disagree. */ +template +bool agree_chacha_once(std::mt19937_64& generator, std::size_t message_size, std::uint64_t seed) { + namespace ciphers = crypto::ciphers; + auto const key = random_bytes(generator, 32); + auto const iv = random_bytes(generator, 12); + auto const additional_data = random_bytes(generator, generator() % 65); + auto const message = random_bytes(generator, message_size); + auto a = ciphers::chacha20_poly1305::make(key); + auto b = ciphers::chacha20_poly1305::make(key); + if (!BOOST_TEST(a.has_value()) || !BOOST_TEST(b.has_value())) { + return false; + } + auto data_a = message; + auto data_b = message; + auto const tag_a = a->seal(iv, additional_data, data_a); + auto const tag_b = b->seal(iv, additional_data, data_b); + bool const same = tag_a && tag_b && data_a == data_b && *tag_a == *tag_b; + if (!BOOST_TEST(same)) { + print_disagreement(seed, "ChaCha20-Poly1305", 32, message_size); + return false; + } + bool const opened = BOOST_TEST(b->open(iv, additional_data, data_a, *tag_a).has_value()) && + BOOST_TEST(a->open(iv, additional_data, data_b, *tag_b).has_value()) && + BOOST_TEST(data_a == message && data_b == message); + if (!opened) { + print_disagreement(seed, "ChaCha20-Poly1305", 32, message_size); + } + return opened; +} + +/** + * ChaCha20-Poly1305 on backends A and B: every message size within 1 of a multiple of 64 up to + * 4,096 bytes, and one in sixteen of the others; stops at the first disagreement. + */ +template +void agree_chacha(std::uint64_t seed) { + constexpr std::size_t largest = 4096; + std::mt19937_64 generator(seed); + for (std::size_t size = 0; size <= largest; ++size) { + bool const near = size % 64 <= 1 || size % 64 == 63; + if (!near && generator() % 16 != 0) { + continue; + } + if (!agree_chacha_once(generator, size, seed)) { + return; + } + } +} + } // namespace webcpp::test #endif diff --git a/test/wipe_objects_test.cpp b/test/wipe_objects_test.cpp index cbfeed50..6e73be78 100644 --- a/test/wipe_objects_test.cpp +++ b/test/wipe_objects_test.cpp @@ -19,6 +19,7 @@ #ifdef WEBCPP_TEST_WIPE_BEARSSL #include #include +#include #include #elif defined(WEBCPP_TEST_WIPE_CTAES) #include @@ -28,6 +29,7 @@ #elif defined(WEBCPP_TEST_WIPE_OPENSSL) #include #include +#include #include #else #error "name a backend: WEBCPP_TEST_WIPE_BEARSSL, _CTAES, _SECP256K1 or _OPENSSL" @@ -161,6 +163,12 @@ int main() { using type = crypto::ciphers::gcm>; check_wiped( {.offset = 0, .size = sizeof(crypto::detail::gcm_state)}); + // ChaCha20-Poly1305's state is aead's first member: the key itself. + using chacha = crypto::ciphers::chacha20_poly1305; + check_wiped( + {.offset = 0, + .size = sizeof(crypto::detail::aead_state)}); #elif defined(WEBCPP_TEST_WIPE_CTAES) // The state is the block cipher's first member: the expanded schedule. using type = crypto::ciphers::aes256; @@ -180,6 +188,10 @@ int main() { {.offset = 0, .size = sizeof(crypto::detail::gcm_state)}); check_wiped>( {.offset = 0, .size = sizeof(crypto::detail::block_state)}); + check_wiped>( + {.offset = 0, + .size = sizeof(crypto::detail::aead_state)}); #endif return webcpp::test::exit_status(boost::report_errors()); } From d3214e52a5b03bfe3ea9c5d3d0c8cca66f107782 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 21:08:03 -0300 Subject: [PATCH 028/110] crypto: the libsodium allocation test counts Ed25519 and X25519 too --- test/allocation_sodium_test.cpp | 92 +++++++++++++++++++++++++++++++-- 1 file changed, 89 insertions(+), 3 deletions(-) diff --git a/test/allocation_sodium_test.cpp b/test/allocation_sodium_test.cpp index 649568bd..518ad59b 100644 --- a/test/allocation_sodium_test.cpp +++ b/test/allocation_sodium_test.cpp @@ -5,12 +5,17 @@ // https://www.boost.org/LICENSE_1_0.txt) // On libsodium nothing allocates: make, seal and open of the three ChaCha20-Poly1305 AEADs, -// a failed open included, 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. Each later -// family on libsodium adds its calls here. +// a failed open included; Ed25519's key pair, signature, strict verification, Ed25519ph and +// the conversion to X25519; and X25519's public key and agreement, a refused one included, +// 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. Each later family on libsodium adds +// its calls here. #include #include +#include +#include +#include #include #include "support/counting.hpp" @@ -22,6 +27,7 @@ #include #include #include +#include #include namespace { @@ -51,6 +57,84 @@ void expect_no_allocation() { BOOST_TEST_EQ(webcpp::test::allocations(), before); } +/** + * Makes and draws Ed25519 key pairs, signs, verifies strictly, refuses a forged signature, + * signs and verifies with Ed25519ph in two pieces, and converts both keys to X25519: none of + * it allocates. + */ +void expect_no_allocation_ed25519() { + using keypair = crypto::curves::ed25519::basic_keypair; + using ph = crypto::curves::ed25519::ph; + // Strict verification on libsodium, named once: a template's commas would split a macro's + // argument. + auto const verify = [](auto const& public_key, auto const& message, auto const& signature) { + return crypto::curves::ed25519::verify(public_key, message, + signature); + }; + std::array seed{}; + seed.fill(5); + std::array const message{}; + std::size_t const before = webcpp::test::allocations(); + { + auto made = keypair::make(seed); + BOOST_TEST(made.has_value()); + auto const drawn = keypair::generate(); + BOOST_TEST(drawn.has_value()); + auto const public_key = made->public_key(); + BOOST_TEST(public_key.has_value()); + auto const signature = made->sign(message); + BOOST_TEST(signature.has_value()); + auto const verified = verify(*public_key, message, *signature); + BOOST_TEST(verified.has_value()); + std::array const forged{}; + BOOST_TEST(verify(*public_key, message, forged).error() == + crypto::error::invalid_signature); + auto signer = ph::begin(); + BOOST_TEST(signer.has_value()); + BOOST_TEST(signer->update(std::span(message).first(40)).has_value()); + BOOST_TEST(signer->update(std::span(message).subspan(40)).has_value()); + auto const ph_signature = signer->sign(*made); + BOOST_TEST(ph_signature.has_value()); + auto verifier = ph::begin(); + BOOST_TEST(verifier.has_value()); + BOOST_TEST(verifier->update(message).has_value()); + BOOST_TEST(verifier->verify(*public_key, *ph_signature).has_value()); + auto const x25519_secret = made->x25519_secret(); + BOOST_TEST(x25519_secret.has_value()); + BOOST_TEST(crypto::curves::ed25519::to_x25519_public(*public_key) + .has_value()); + keypair const moved = std::move(*made); + } + BOOST_TEST_EQ(webcpp::test::allocations(), before); +} + +/** + * Computes two X25519 public keys, agrees both ways, and refuses a peer key of low order (the + * all-zero point): none of it allocates. + */ +void expect_no_allocation_x25519() { + using x25519 = crypto::curves::x25519::algorithm; + std::array alice{}; + alice.fill(7); + std::array bob{}; + bob.fill(9); + std::array const low_order{}; + std::size_t const before = webcpp::test::allocations(); + { + auto const alice_public = x25519::public_key(alice); + BOOST_TEST(alice_public.has_value()); + auto const bob_public = x25519::public_key(bob); + BOOST_TEST(bob_public.has_value()); + auto const alice_shared = x25519::agree(alice, *bob_public); + BOOST_TEST(alice_shared.has_value()); + auto const bob_shared = x25519::agree(bob, *alice_public); + BOOST_TEST(bob_shared.has_value()); + BOOST_TEST(x25519::agree(alice, low_order).error() == crypto::error::weak_public_key); + } + BOOST_TEST_EQ(webcpp::test::allocations(), before); +} + } // namespace int main() { @@ -69,5 +153,7 @@ int main() { expect_no_allocation>(); expect_no_allocation>(); expect_no_allocation>(); + expect_no_allocation_ed25519(); + expect_no_allocation_x25519(); return webcpp::test::exit_status(boost::report_errors()); } From 11db183f249b9a0f8ac0b6acfe70ba2d46a48fb9 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 21:29:31 -0300 Subject: [PATCH 029/110] crypto: the changelog's Unreleased lines fit the lint again, the ChaCha20-Poly1305 AEADs merged into libsodium's line --- doc/changelog.adoc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc/changelog.adoc b/doc/changelog.adoc index b590a491..e4db303b 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -16,13 +16,13 @@ of every version are on webcpp's index page. === Unreleased // tag::unreleased[] -* Added crypto, primitives over C backends: ciphers, curves and randomness, with errors of fixed values in webcpp.crypto, every result `+[[nodiscard]]+`, and WEBCPP_CRYPTO_HAS_THREADS, defined natively and on Emscripten with -pthread unless WEBCPP_CRYPTO_NO_THREADS is. +* Added crypto, primitives over C backends: ciphers, curves and randomness, errors of fixed values in webcpp.crypto, every result `+[[nodiscard]]+`, and WEBCPP_CRYPTO_HAS_THREADS, defined natively and with Emscripten's -pthread unless WEBCPP_CRYPTO_NO_THREADS is. * Added equal, random_device, ciphers::aes128, aes192 and aes256, the AES block cipher, and ciphers::gcm, AES-GCM in place with an incremental seal whose failed open zeroes the data. * Added default_backend_t and /webcpp/crypto//-default, one default backend per family and target whatever is linked, ciphers::aes128_gcm and aes256_gcm, and refusals naming the Jamfile line and another backend's type. * Added backends::bearssl (AES-GCM alone, allocating nothing), backends::openssl via /webcpp/crypto//openssl natively and on WASI (allocating at make only, or natively in openssl_memory_resource with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE), and backends::ctaes (block cipher alone). * Added curves::secp256k1: key pairs, BIP340 and ECDSA signatures, ECDH, strict DER, low-S and the x-only tweak. * Added curves::ed25519 and curves::x25519 on libsodium: strict verification tabled on twelve edge cases, Ed25519ph over webcpp::hash's sha2_512 (/webcpp/crypto//crypto brings hash), the conversion, and agree refusing all-zero secrets. -* Added backends::sodium on /third_party//sodium, shared with webcpp::hash and initialised before every engine, every backend's link-time canary and C suite, and on it ciphers::aead's chacha20_poly1305, chacha20_poly1305_original and xchacha20_poly1305, refusing first any other family; chacha20_poly1305 also on BearSSL and OpenSSL. +* Added backends::sodium on /third_party//sodium, shared with webcpp::hash, every backend's link-time canary and C suite, and ciphers::aead, refusing other families first: chacha20_poly1305 (also BearSSL, OpenSSL), its original form and xchacha20_poly1305. * Added the page: a chapter per namespace and use case, the memory option's guide and example, tables generated from the tests, every Jamfile and message, and llms.txt. * Added supports_v, the capability table on the target being compiled, and the tags of its families and algorithms, which ciphers::gcm, the AES block cipher and secp256k1's key pair name. * Added secret, a self-wiping array that is copied only by clone, and the errors 13 to 20: memory_functions_refused, memory_functions_not_installed, weak_public_key, invalid_point, invalid_scalar, invalid_padding, invalid_encoding and invalid_ciphertext_size. From 6ce469e989b6d6ef5abe7305b3cab1caf4c1baa0 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 22:32:31 -0300 Subject: [PATCH 030/110] crypto: the heavy operations' runner passes clang-tidy, names Boost.Asio for its async_ variants, and its test says why it runs the io_context --- include/webcpp/crypto/detail/heavy.hpp | 25 ++++++++++++------------- test/heavy_test.cpp | 6 +++--- 2 files changed, 15 insertions(+), 16 deletions(-) diff --git a/include/webcpp/crypto/detail/heavy.hpp b/include/webcpp/crypto/detail/heavy.hpp index c93f73cc..12104755 100644 --- a/include/webcpp/crypto/detail/heavy.hpp +++ b/include/webcpp/crypto/detail/heavy.hpp @@ -28,12 +28,12 @@ #include #ifdef WEBCPP_CRYPTO_HAS_THREADS -#include -#include -#include -#include -#include -#include +#include // lint-world: async_ variants (D23) +#include // lint-world: async_ variants (D23) +#include // lint-world: async_ variants (D23) +#include // lint-world: async_ variants (D23) +#include // lint-world: async_ variants (D23) +#include // lint-world: async_ variants (D23) #endif namespace webcpp::crypto::detail { @@ -77,18 +77,17 @@ auto run_heavy(Executor executor, Function function, CompletionToken&& token) { static_assert(std::is_nothrow_invocable_v, "webcpp::crypto: a heavy operation's call reports its errors as values"); using result_type = std::invoke_result_t; - auto initiation = [](auto handler, Executor work_executor, Function call) { + auto initiation = [](auto handler, Executor const& work_executor, Function call) { auto completion_executor = boost::asio::prefer(boost::asio::get_associated_executor(handler, work_executor), - boost::asio::execution::outstanding_work.tracked); + boost::asio::execution::outstanding_work_t::tracked); boost::asio::post( work_executor, [handler = std::move(handler), call = std::move(call), completion_executor = std::move(completion_executor)]() mutable { - auto result = call(); - boost::asio::dispatch(completion_executor, [handler = std::move(handler), - result = std::move(result)]() mutable { - std::move(handler)(std::move(result)); - }); + boost::asio::dispatch(completion_executor, + [handler = std::move(handler), result = call()]() mutable { + std::move(handler)(std::move(result)); + }); }); }; return boost::asio::async_initiate( diff --git a/test/heavy_test.cpp b/test/heavy_test.cpp index c3a700a7..dcffd513 100644 --- a/test/heavy_test.cpp +++ b/test/heavy_test.cpp @@ -86,7 +86,7 @@ void runs_elsewhere_and_completes_on_the_caller() { completed = true; })); // The completion keeps the caller's io_context busy: run returns after it, not before. - caller.run(); + caller.run(); // lint-run: that run waits for the tracked work is what this test proves pool.join(); BOOST_TEST(completed); BOOST_TEST(timer_fired_meanwhile); @@ -104,7 +104,7 @@ void move_only_result() { boost::asio::bind_executor(caller.get_executor(), [&received](std::unique_ptr result) { received = std::move(result); })); - caller.run(); + caller.run(); // lint-run: waits for the pool's thread to post the completion pool.join(); BOOST_TEST(received != nullptr); if (received) { @@ -119,7 +119,7 @@ void heavy_operation_with_any_token() { auto operation = async_slow(pool.get_executor(), 41, boost::asio::deferred); std::move(operation)(boost::asio::bind_executor( caller.get_executor(), [&received](int result) { received = result; })); - caller.run(); + caller.run(); // lint-run: waits for the pool's thread to post the completion pool.join(); BOOST_TEST_EQ(received, 42); } From 1703bef3e1b011f29b79fe8bacf0167694d798b8 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 22:32:31 -0300 Subject: [PATCH 031/110] crypto: X25519's stand-in backend has internal linkage, as clang-tidy asks --- test/x25519_mock_test.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/x25519_mock_test.cpp b/test/x25519_mock_test.cpp index 25309747..f0c2744d 100644 --- a/test/x25519_mock_test.cpp +++ b/test/x25519_mock_test.cpp @@ -22,6 +22,7 @@ #include namespace webcpp::test { +namespace { /** A backend tag for X25519's generic layer alone. */ struct x25519_stand_in {}; @@ -35,8 +36,9 @@ struct x25519_stand_in_knobs { }; // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the knobs a test turns -inline x25519_stand_in_knobs x25519_stand_in_control{}; +x25519_stand_in_knobs x25519_stand_in_control{}; +} // namespace } // namespace webcpp::test namespace webcpp::crypto::detail { From 185ebfbf12754b0676b0dd1fddd525cf4c1a5e83 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 22:32:31 -0300 Subject: [PATCH 032/110] crypto: Ed25519's edge-case test passes clang-tidy and holds no fluent chain, and generate.py keeps to 100 columns --- doc/tables/generate.py | 6 +++--- test/ed25519_speccheck_test.cpp | 29 ++++++++++++++++------------- 2 files changed, 19 insertions(+), 16 deletions(-) diff --git a/doc/tables/generate.py b/doc/tables/generate.py index 6d32c0ca..942eebb4 100644 --- a/doc/tables/generate.py +++ b/doc/tables/generate.py @@ -1304,9 +1304,9 @@ def llms(data: Data, matrix: Matrix, library: Path) -> str: out = ['# webcpp::crypto', '', '> Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: ' 'AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA, ECDH, the x-only ' - 'tweak), Ed25519 and Ed25519ph (RFC 8032), X25519 (RFC 7748), a random_device on the system\'s generator ' - 'and a constant-time equal, each over a widely used, reviewed C library (BearSSL, ' - 'OpenSSL, ctaes, libsecp256k1, libsodium) that ' + 'tweak), Ed25519 and Ed25519ph (RFC 8032), X25519 (RFC 7748), a random_device on the ' + 'system\'s generator and a constant-time equal, each over a widely used, reviewed C ' + 'library (BearSSL, OpenSSL, ctaes, libsecp256k1, libsodium) that ' 'the program names in its Jamfile. Hashing and HMAC are Boost.Hash2\'s. Every ' 'failure is a boost::system::result value. Protocols (Bitcoin, Ethereum, Nostr) ' 'belong to domain libraries built on these primitives.', '', diff --git a/test/ed25519_speccheck_test.cpp b/test/ed25519_speccheck_test.cpp index 4de47456..05644b8e 100644 --- a/test/ed25519_speccheck_test.cpp +++ b/test/ed25519_speccheck_test.cpp @@ -28,7 +28,7 @@ #include #include -#if defined(__EMSCRIPTEN__) +#ifdef __EMSCRIPTEN__ #include #endif @@ -44,7 +44,7 @@ namespace ed25519 = webcpp::crypto::curves::ed25519; namespace test = webcpp::test; namespace json = boost::json; -#if defined(__EMSCRIPTEN__) +#ifdef __EMSCRIPTEN__ // node's crypto.subtle.verify with an Ed25519 key imported raw: 1 when it accepts, 0 when it // refuses, 2 when importKey refuses the public key (a refusal of the case too), -1 when verify // itself throws (the message goes to the console). The inputs are copied before the first await. @@ -95,7 +95,7 @@ std::string text_of(json::value const& value) { return std::string(std::string_view(value.as_string())); } -std::string verdict(bool accepted) { +std::string_view verdict(bool accepted) { return accepted ? "accept" : "reject"; } @@ -142,15 +142,15 @@ void compare(std::string const& label, verdicts const& computed, verdicts const& // curves::ed25519::verify, whose refusal is invalid_signature. void sodium_rows(std::vector const& cases, verdicts& raw, verdicts& strict) { for (auto const& tested : cases) { - raw.push_back(verdict(crypto_sign_ed25519_verify_detached( - tested.signature.data(), tested.message.data(), - tested.message.size(), tested.public_key.data()) == 0)); + raw.emplace_back(verdict(crypto_sign_ed25519_verify_detached( + tested.signature.data(), tested.message.data(), + tested.message.size(), tested.public_key.data()) == 0)); auto const verified = ed25519::verify( tested.public_key, tested.message, tested.signature); if (!verified) { BOOST_TEST(verified.error() == crypto::error::invalid_signature); } - strict.push_back(verdict(static_cast(verified))); + strict.emplace_back(verdict(static_cast(verified))); } } @@ -172,9 +172,11 @@ int main() { std::vector cases; for (auto const& entry : cases_document.as_array()) { - cases.push_back({test::from_hex(text_of(entry.at("message"))), - test::from_hex(text_of(entry.at("pub_key"))), - test::from_hex(text_of(entry.at("signature")))}); + cases.push_back({ + .message = test::from_hex(text_of(entry.at("message"))), + .public_key = test::from_hex(text_of(entry.at("pub_key"))), + .signature = test::from_hex(text_of(entry.at("signature"))), + }); BOOST_TEST_EQ(cases.back().public_key.size(), 32U); BOOST_TEST_EQ(cases.back().signature.size(), 64U); } @@ -184,7 +186,8 @@ int main() { } // What each case tests, the page's first column: one text per case. - BOOST_TEST_EQ(committed.at("cases").as_array().size(), case_count); + auto const& texts = committed.at("cases").as_array(); + BOOST_TEST_EQ(texts.size(), case_count); auto const& source = committed.at("source"); BOOST_TEST_EQ(text_of(source.at("repository")), "novifinancial/ed25519-speccheck"); @@ -231,7 +234,7 @@ int main() { return test::exit_status(boost::report_errors()); } auto const webcrypto = committed_row(view.at("verdicts"), "webcrypto-node"); -#if defined(__EMSCRIPTEN__) +#ifdef __EMSCRIPTEN__ // The versions this run's node has, beside those committed: a node whose row differs says // which it is. if (view.contains("node") && view.contains("openssl")) { @@ -244,7 +247,7 @@ int main() { auto const answer = subtle_ed25519_verify(tested.public_key.data(), tested.message.data(), tested.message.size(), tested.signature.data()); BOOST_TEST(answer >= 0); - subtle.push_back(verdict(answer == 1)); + subtle.emplace_back(verdict(answer == 1)); } compare("webcrypto-node", subtle, webcrypto); #else From 56e507a2a3ff8fead46bf2a48715d3abc9ccf3d1 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 22:32:31 -0300 Subject: [PATCH 033/110] crypto: Ed25519's generate() says its seed comes from the system's generator, without the name the lint reads as reaching the world --- doc/llms.txt | 2 +- include/webcpp/crypto/curves/ed25519.hpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/doc/llms.txt b/doc/llms.txt index 587d121e..f4840530 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -69,7 +69,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - tweak_xonly: Tweaks an x-only public key by a 32-byte tweak t: P + t*G, with libsecp256k1's static context, which allocates nothing (`secp256k1_xonly_pubkey_tweak_add`). - [curves::ed25519::keypair](https://webcpporg.github.io/libs/crypto/#crypto-ed25519): An Ed25519 key pair (RFC 8032): made from a 32-byte seed or drawn from `random_device`, its 32-byte public key, 64-byte signatures, and its X25519 secret key. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. - make: Makes a key pair from a seed, RFC 8032's secret key. - - generate: Makes a key pair from a seed drawn from `random_device`. + - generate: Makes a key pair from a fresh seed, drawn from the system's generator. - public_key: The public key. - sign: Signs a message. - x25519_secret: The X25519 secret key of this key pair, RFC 7748's form of the clamped first half of the seed's SHA-512. diff --git a/include/webcpp/crypto/curves/ed25519.hpp b/include/webcpp/crypto/curves/ed25519.hpp index 0a756da0..25383869 100644 --- a/include/webcpp/crypto/curves/ed25519.hpp +++ b/include/webcpp/crypto/curves/ed25519.hpp @@ -114,7 +114,7 @@ class basic_keypair { } /** - * Makes a key pair from a seed drawn from `random_device`. + * Makes a key pair from a fresh seed, drawn from the system's generator. * * @return The key pair; `entropy_unavailable` when the system's generator fails or there is * none; `backend_failure`. From adad54cd2bbb019f4148b4d49d9427cfbb04f420 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 22:32:31 -0300 Subject: [PATCH 034/110] crypto: the OpenSSL error-queue and the wipe tests pass clang-tidy --- test/openssl_error_queue_test.cpp | 4 ++-- test/wipe_objects_test.cpp | 18 ++++++++++-------- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/test/openssl_error_queue_test.cpp b/test/openssl_error_queue_test.cpp index 9d65aa30..860211ca 100644 --- a/test/openssl_error_queue_test.cpp +++ b/test/openssl_error_queue_test.cpp @@ -26,6 +26,8 @@ namespace { +namespace crypto = webcpp::crypto; + /** The queue's entries, oldest first, emptied. */ std::size_t drain(unsigned long& first) { std::size_t count = 0; @@ -42,7 +44,6 @@ std::size_t drain(unsigned long& first) { */ template void check_queue(std::span key, std::span iv) { - namespace crypto = webcpp::crypto; std::array data{}; // NOLINTNEXTLINE(bugprone-signed-bitwise): OpenSSL's reason macro ORs signed flags ERR_raise(ERR_LIB_USER, ERR_R_PASSED_INVALID_ARGUMENT); @@ -65,7 +66,6 @@ void check_queue(std::span key, std::span>; using chacha = crypto::ciphers::chacha20_poly1305; std::array const key{}; diff --git a/test/wipe_objects_test.cpp b/test/wipe_objects_test.cpp index 6e73be78..bbdd0984 100644 --- a/test/wipe_objects_test.cpp +++ b/test/wipe_objects_test.cpp @@ -165,10 +165,11 @@ int main() { {.offset = 0, .size = sizeof(crypto::detail::gcm_state)}); // ChaCha20-Poly1305's state is aead's first member: the key itself. using chacha = crypto::ciphers::chacha20_poly1305; - check_wiped( - {.offset = 0, - .size = sizeof(crypto::detail::aead_state)}); + check_wiped({ + .offset = 0, + .size = sizeof(crypto::detail::aead_state), + }); #elif defined(WEBCPP_TEST_WIPE_CTAES) // The state is the block cipher's first member: the expanded schedule. using type = crypto::ciphers::aes256; @@ -188,10 +189,11 @@ int main() { {.offset = 0, .size = sizeof(crypto::detail::gcm_state)}); check_wiped>( {.offset = 0, .size = sizeof(crypto::detail::block_state)}); - check_wiped>( - {.offset = 0, - .size = sizeof(crypto::detail::aead_state)}); + check_wiped>({ + .offset = 0, + .size = sizeof(crypto::detail::aead_state), + }); #endif return webcpp::test::exit_status(boost::report_errors()); } From 5c6ce509d951db3635564a70713c51e0aa2f1c42 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 22:32:32 -0300 Subject: [PATCH 035/110] crypto: secret's test states why it reads moved-from secrets, as clang-tidy asks --- test/secret_test.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/test/secret_test.cpp b/test/secret_test.cpp index 894bffe5..38cd3996 100644 --- a/test/secret_test.cpp +++ b/test/secret_test.cpp @@ -144,7 +144,8 @@ int main() { key from; fill(from, 7); key const expected = from.clone(); - key to(std::move(from)); + key const to(std::move(from)); + // NOLINTNEXTLINE(bugprone-use-after-move): a moved-from secret's bytes are what is tested BOOST_TEST(is_zero(from)); BOOST_TEST(std::equal(to.bytes().begin(), to.bytes().end(), expected.bytes().begin())); @@ -154,6 +155,7 @@ int main() { key source; fill(source, 7); assigned = std::move(source); + // NOLINTNEXTLINE(bugprone-use-after-move): a moved-from secret's bytes are what is tested BOOST_TEST(is_zero(source)); BOOST_TEST( std::equal(assigned.bytes().begin(), assigned.bytes().end(), expected.bytes().begin())); @@ -169,7 +171,8 @@ int main() { key gone; fill(gone, 5); - key taker(std::move(gone)); + key const taker(std::move(gone)); + // NOLINTNEXTLINE(bugprone-use-after-move): a moved-from secret's clone is what is tested key const empty = gone.clone(); BOOST_TEST(is_zero(empty)); BOOST_TEST(!is_zero(taker)); From 22d598c11bf79c899a112085555c1447a2089b85 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 22:43:59 -0300 Subject: [PATCH 036/110] crypto: WEBCPP_CRYPTO_HAS_THREADS has its Doc Comment, so the page's reference builds --- include/webcpp/crypto/config.hpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/include/webcpp/crypto/config.hpp b/include/webcpp/crypto/config.hpp index f4afac49..d820d392 100644 --- a/include/webcpp/crypto/config.hpp +++ b/include/webcpp/crypto/config.hpp @@ -172,6 +172,12 @@ !defined(WEBCPP_TARGET_WASIP3) && \ ((defined(WEBCPP_TARGET_EMSCRIPTEN) && defined(__EMSCRIPTEN_PTHREADS__)) || \ (!defined(WEBCPP_TARGET_EMSCRIPTEN) && defined(BOOST_HAS_THREADS))) +/** + Defined in a build with threads, where the heavy operations' `async_` variants exist (design + D23): natively unless the program defines `WEBCPP_CRYPTO_NO_THREADS` (Boost.Config's + `BOOST_HAS_THREADS`, which b2's `threading=single` leaves defined), on Emscripten with + `-pthread`, never on WASI. +*/ #define WEBCPP_CRYPTO_HAS_THREADS 1 #endif From 1189d77ecac33327658b7952a4ddee32dff0fc0a Mon Sep 17 00:00:00 2001 From: R Date: Wed, 18 Nov 2026 02:24:33 -0300 Subject: [PATCH 037/110] crypto: the threads test pins that a native build with threading=single has threads --- test/threads_config_test.cpp | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/test/threads_config_test.cpp b/test/threads_config_test.cpp index 3aeb657f..15a6e770 100644 --- a/test/threads_config_test.cpp +++ b/test/threads_config_test.cpp @@ -16,8 +16,10 @@ // threading=single does not take BOOST_HAS_THREADS away: Boost.Config (1.92) defines it on macOS // (__APPLE__, boost/config/detail/suffix.hpp), on MSVC (_MT), with libstdc++ where it has gthreads // (boost/config/stdlib/libstdcpp3.hpp) and with libc++ always (boost/config/stdlib/libcpp.hpp), so -// that a native build without WEBCPP_CRYPTO_NO_THREADS has threads; the single build checks the -// rule against Boost.Config's macro, whatever it says on the machine. +// that a native build without WEBCPP_CRYPTO_NO_THREADS has threads. The single build checks the +// rule against Boost.Config's macro, and pins the documented outcome: should Boost (or its pin) +// stop defining BOOST_HAS_THREADS under threading=single, the documentation would be wrong, and +// this build fails. #include @@ -41,6 +43,9 @@ #if defined(WEBCPP_CRYPTO_HAS_THREADS) != defined(BOOST_HAS_THREADS) #error "WEBCPP_CRYPTO_HAS_THREADS is not defined exactly when BOOST_HAS_THREADS is" #endif +#ifndef WEBCPP_CRYPTO_HAS_THREADS +#error "a native build has threads unless the program defines WEBCPP_CRYPTO_NO_THREADS" +#endif #else #error "test/Jamfile builds this file natively with one of the threading cases" #endif From 39762d33da5d716972c49a0caa854b427b0aa168 Mon Sep 17 00:00:00 2001 From: R Date: Wed, 18 Nov 2026 02:25:16 -0300 Subject: [PATCH 038/110] crypto: the heavy refusal tells a native build to leave out WEBCPP_CRYPTO_NO_THREADS, not to use threading=multi --- doc/generated/messages.adoc | 6 +++--- doc/tables/crypto.json | 2 +- include/webcpp/crypto/config.hpp | 5 +++-- include/webcpp/crypto/detail/heavy.hpp | 12 ++++++------ .../heavy_without_threads/heavy_without_threads.cpp | 2 +- 5 files changed, 14 insertions(+), 13 deletions(-) diff --git a/doc/generated/messages.adoc b/doc/generated/messages.adoc index bc267ea7..d5b2f9fb 100644 --- a/doc/generated/messages.adoc +++ b/doc/generated/messages.adoc @@ -93,9 +93,9 @@ The fix: Name `+gcm>+` or `+gcmmulti`." } } diff --git a/include/webcpp/crypto/config.hpp b/include/webcpp/crypto/config.hpp index d820d392..b12a2bfb 100644 --- a/include/webcpp/crypto/config.hpp +++ b/include/webcpp/crypto/config.hpp @@ -166,8 +166,9 @@ #define WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE 1 #endif -// Threads (design D23): natively when Boost.Config sees threads (b2 threading=multi), on -// Emscripten with -pthread, never on WASI. +// Threads (design D23): natively when Boost.Config sees threads, which it does whatever b2's +// threading says (so natively unless WEBCPP_CRYPTO_NO_THREADS), on Emscripten with -pthread, +// never on WASI. #if !defined(WEBCPP_CRYPTO_NO_THREADS) && !defined(WEBCPP_TARGET_WASIP2) && \ !defined(WEBCPP_TARGET_WASIP3) && \ ((defined(WEBCPP_TARGET_EMSCRIPTEN) && defined(__EMSCRIPTEN_PTHREADS__)) || \ diff --git a/include/webcpp/crypto/detail/heavy.hpp b/include/webcpp/crypto/detail/heavy.hpp index 12104755..94146f95 100644 --- a/include/webcpp/crypto/detail/heavy.hpp +++ b/include/webcpp/crypto/detail/heavy.hpp @@ -46,12 +46,12 @@ namespace webcpp::crypto::detail { #ifdef WEBCPP_CRYPTO_HAS_THREADS #define WEBCPP_CRYPTO_DETAIL_REQUIRE_THREADS(async_name, sync_name) #else -#define WEBCPP_CRYPTO_DETAIL_REQUIRE_THREADS(async_name, sync_name) \ - static_assert(::webcpp::crypto::detail::dependent_false, \ - "webcpp::crypto: " async_name \ - " runs on another thread and needs a build with threads (natively b2 " \ - "threading=multi; on Emscripten -pthread). Without threads, call " sync_name \ - ".") +#define WEBCPP_CRYPTO_DETAIL_REQUIRE_THREADS(async_name, sync_name) \ + static_assert( \ + ::webcpp::crypto::detail::dependent_false, \ + "webcpp::crypto: " async_name \ + " runs on another thread and needs a build with threads (natively without " \ + "WEBCPP_CRYPTO_NO_THREADS; on Emscripten -pthread). Without threads, call " sync_name ".") #endif #ifdef WEBCPP_CRYPTO_HAS_THREADS diff --git a/test/messages/heavy_without_threads/heavy_without_threads.cpp b/test/messages/heavy_without_threads/heavy_without_threads.cpp index 3e092768..57b004a2 100644 --- a/test/messages/heavy_without_threads/heavy_without_threads.cpp +++ b/test/messages/heavy_without_threads/heavy_without_threads.cpp @@ -10,7 +10,7 @@ // operation declares its variant. // clang-format off -// expected-error@*:* {{webcpp::crypto: async_slow runs on another thread and needs a build with threads (natively b2 threading=multi; on Emscripten -pthread). Without threads, call slow.}} +// expected-error@*:* {{webcpp::crypto: async_slow runs on another thread and needs a build with threads (natively without WEBCPP_CRYPTO_NO_THREADS; on Emscripten -pthread). Without threads, call slow.}} // clang-format on #include From 19f2921349fc1478014e4df1a66cd531723d6f36 Mon Sep 17 00:00:00 2001 From: R Date: Wed, 18 Nov 2026 02:29:45 -0300 Subject: [PATCH 039/110] crypto: aead_not_a_family is declared alone, so another error beside the refusal fails it --- test/messages/aead_not_a_family/Jamfile | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/messages/aead_not_a_family/Jamfile b/test/messages/aead_not_a_family/Jamfile index 01a54343..64868aa9 100644 --- a/test/messages/aead_not_a_family/Jamfile +++ b/test/messages/aead_not_a_family/Jamfile @@ -8,5 +8,7 @@ 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 aead_not_a_family : aead_not_a_family.cpp - : : native wasip2 wasip3 ; + : : native wasip2 wasip3 : alone ; From 4fbd5dc608e4725ac672b699d4cd730d29f2f519 Mon Sep 17 00:00:00 2001 From: R Date: Wed, 18 Nov 2026 02:30:42 -0300 Subject: [PATCH 040/110] crypto: without threads, detail::run_heavy's stand-in stops a heavy variant that forgets its refusal --- include/webcpp/crypto/detail/heavy.hpp | 15 +++++-- test/Jamfile | 5 +++ test/heavy_refusal_forgotten_test.cpp | 45 +++++++++++++++++++ .../heavy_without_threads.cpp | 3 +- 4 files changed, 63 insertions(+), 5 deletions(-) create mode 100644 test/heavy_refusal_forgotten_test.cpp diff --git a/include/webcpp/crypto/detail/heavy.hpp b/include/webcpp/crypto/detail/heavy.hpp index 94146f95..9560d38a 100644 --- a/include/webcpp/crypto/detail/heavy.hpp +++ b/include/webcpp/crypto/detail/heavy.hpp @@ -40,7 +40,8 @@ namespace webcpp::crypto::detail { /** The refusal of a heavy operation's `async_` variant in a build without threads (design D23). - Each such variant's body starts with it, so that a program fails only where it calls one. + Each such variant's body starts with it, so that a program fails only where it calls one, + with this error first; a variant that forgets it stops at `run_heavy`'s stand-in instead. The variant's completion token is its parameter `token`. */ #ifdef WEBCPP_CRYPTO_HAS_THREADS @@ -97,12 +98,18 @@ auto run_heavy(Executor executor, Function function, CompletionToken&& token) { #else /** - * Without threads, a stand-in that does nothing: a refused variant's body compiles past its - * refusal, which has stopped the build already, without errors of its own. + * Without threads, a stand-in that is never meant to compile: a variant that starts with its + * refusal stops there first, and one that forgets `WEBCPP_CRYPTO_DETAIL_REQUIRE_THREADS` stops + * here, rather than compile into a call that never runs the work nor calls the handler. */ template void run_heavy(Executor&& /*executor*/, Function&& /*function*/, - CompletionToken&& /*token*/) noexcept {} + CompletionToken&& /*token*/) noexcept { + static_assert(::webcpp::crypto::detail::dependent_false, + "webcpp::crypto: a heavy operation's async_ variant starts with " + "WEBCPP_CRYPTO_DETAIL_REQUIRE_THREADS, which stops a build without threads " + "where the program calls it; this one does not."); +} #endif diff --git a/test/Jamfile b/test/Jamfile index 06fb815c..b89d4f25 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -88,6 +88,11 @@ webcpp.compile threads_config_wasm : threads_config_test.cpp : : wasip2 wasip3 e # A heavy operation's async_ variant with threads: detail::run_heavy runs the # work on a thread_pool and completes on the caller's io_context. crypto-run heavy : heavy_test.cpp : multi : native ; +# Without threads (WEBCPP_CRYPTO_NO_THREADS natively; WASI has none), a heavy +# operation's async_ variant that forgets its refusal stops at +# detail::run_heavy's stand-in, which names the refusal, and with that alone. +webcpp.compile-diagnostic heavy_refusal_forgotten : heavy_refusal_forgotten_test.cpp + : WEBCPP_CRYPTO_NO_THREADS : native wasip2 wasip3 : alone ; crypto-run error : error_test.cpp ; crypto-run equal : equal_test.cpp ; diff --git a/test/heavy_refusal_forgotten_test.cpp b/test/heavy_refusal_forgotten_test.cpp new file mode 100644 index 00000000..282ae3b2 --- /dev/null +++ b/test/heavy_refusal_forgotten_test.cpp @@ -0,0 +1,45 @@ +// 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 heavy operation's async_ variant that forgets WEBCPP_CRYPTO_DETAIL_REQUIRE_THREADS, called in a +// build without threads (natively with WEBCPP_CRYPTO_NO_THREADS; on WASI always), stops at +// detail::run_heavy's stand-in, which names the missing refusal, and with that error alone: +// without it, the variant would compile, never run the work and never call the handler. + +// clang-format off +// expected-error@webcpp/crypto/detail/heavy.hpp:* {{webcpp::crypto: a heavy operation's async_ variant starts with WEBCPP_CRYPTO_DETAIL_REQUIRE_THREADS, which stops a build without threads where the program calls it; this one does not.}} +// clang-format on + +#include + +#include + +namespace { + +/** The test-only heavy operation, synchronous. */ +int slow(int value) noexcept { + return value + 1; +} + +/** Its async_ variant, which forgets the refusal. */ +template +auto async_slow(Executor executor, int value, CompletionToken&& token) { + return webcpp::crypto::detail::run_heavy( + std::move(executor), [value]() noexcept { return slow(value); }, + std::forward(token)); +} + +/** An executor and a completion token, which a build without threads never uses. */ +struct executor {}; + +struct token {}; + +} // namespace + +int main() { + async_slow(executor{}, 41, token{}); + return slow(0) == 1 ? 0 : 1; +} diff --git a/test/messages/heavy_without_threads/heavy_without_threads.cpp b/test/messages/heavy_without_threads/heavy_without_threads.cpp index 57b004a2..d292a7aa 100644 --- a/test/messages/heavy_without_threads/heavy_without_threads.cpp +++ b/test/messages/heavy_without_threads/heavy_without_threads.cpp @@ -7,7 +7,8 @@ // A heavy operation's async_ variant called in a build without threads (natively with // WEBCPP_CRYPTO_NO_THREADS; on WASI always) stops where it is called, with the synchronous // operation to call instead (design D23). The operation is a test's own, declared as every heavy -// operation declares its variant. +// operation declares its variant. The refusal is the first error; detail::run_heavy's stand-in +// adds its own after it (test/heavy_refusal_forgotten_test.cpp states that one). // clang-format off // expected-error@*:* {{webcpp::crypto: async_slow runs on another thread and needs a build with threads (natively without WEBCPP_CRYPTO_NO_THREADS; on Emscripten -pthread). Without threads, call slow.}} From 2530a182f9513340357f7a56b9addcd2d82ee029 Mon Sep 17 00:00:00 2001 From: R Date: Wed, 18 Nov 2026 02:35:59 -0300 Subject: [PATCH 041/110] crypto: detail::run_heavy carries the handler's allocator and cancellation slot to what it posts and dispatches --- include/webcpp/crypto/detail/heavy.hpp | 57 +++++++++--- test/heavy_test.cpp | 122 ++++++++++++++++++++++++- 2 files changed, 163 insertions(+), 16 deletions(-) diff --git a/include/webcpp/crypto/detail/heavy.hpp b/include/webcpp/crypto/detail/heavy.hpp index 9560d38a..009163f7 100644 --- a/include/webcpp/crypto/detail/heavy.hpp +++ b/include/webcpp/crypto/detail/heavy.hpp @@ -28,12 +28,16 @@ #include #ifdef WEBCPP_CRYPTO_HAS_THREADS -#include // lint-world: async_ variants (D23) -#include // lint-world: async_ variants (D23) -#include // lint-world: async_ variants (D23) -#include // lint-world: async_ variants (D23) -#include // lint-world: async_ variants (D23) -#include // lint-world: async_ variants (D23) +#include // lint-world: async_ variants (D23) +#include // lint-world: async_ variants (D23) +#include // lint-world: async_ variants (D23) +#include // lint-world: async_ variants (D23) +#include // lint-world: async_ variants (D23) +#include // lint-world: async_ variants (D23) +#include // lint-world: async_ variants (D23) +#include // lint-world: async_ variants (D23) +#include // lint-world: async_ variants (D23) +#include // lint-world: async_ variants (D23) #endif namespace webcpp::crypto::detail { @@ -57,12 +61,29 @@ namespace webcpp::crypto::detail { #ifdef WEBCPP_CRYPTO_HAS_THREADS +/** + * `function` with a handler's associated allocator and cancellation slot, which asio reads + * from each function an operation posts or dispatches on its handler's behalf. + * + * @param allocator The handler's associated allocator. + * @param slot The handler's associated cancellation slot. + * @param function The function posted or dispatched. + * @return `function`, bound to both. + */ +template +auto carrying(Allocator const& allocator, Slot const& slot, Function function) { + return boost::asio::bind_cancellation_slot( + slot, boost::asio::bind_allocator(allocator, std::move(function))); +} + /** * Runs a heavy operation's synchronous call on another thread: posts `function` to `executor` * (natively a `thread_pool`'s; on Emscripten a pool whose threads are Web Workers) and * dispatches its result to the handler's associated executor, which by default is `executor`. * The handler's executor is kept busy until then, so that an `io_context` the handler runs on - * does not run out of work while the call runs elsewhere. + * does not run out of work while the call runs elsewhere. Both the posted and the dispatched + * functions carry the handler's associated allocator and cancellation slot, as asio asks of an + * operation's intermediate handlers; the call itself is never cancelled once posted. * * @tparam Executor The executor the call runs on. * @tparam Function A call without arguments that reports its errors as values, not by throwing. @@ -82,14 +103,22 @@ auto run_heavy(Executor executor, Function function, CompletionToken&& token) { auto completion_executor = boost::asio::prefer(boost::asio::get_associated_executor(handler, work_executor), boost::asio::execution::outstanding_work_t::tracked); + auto allocator = boost::asio::get_associated_allocator(handler); + auto slot = boost::asio::get_associated_cancellation_slot(handler); boost::asio::post( - work_executor, [handler = std::move(handler), call = std::move(call), - completion_executor = std::move(completion_executor)]() mutable { - boost::asio::dispatch(completion_executor, - [handler = std::move(handler), result = call()]() mutable { - std::move(handler)(std::move(result)); - }); - }); + work_executor, + carrying( + allocator, slot, + [handler = std::move(handler), call = std::move(call), + completion_executor = std::move(completion_executor), allocator, slot]() mutable { + auto result = call(); + boost::asio::dispatch(completion_executor, + carrying(allocator, slot, + [handler = std::move(handler), + result = std::move(result)]() mutable { + std::move(handler)(std::move(result)); + })); + })); }; return boost::asio::async_initiate( std::move(initiation), token, std::move(executor), std::move(function)); diff --git a/test/heavy_test.cpp b/test/heavy_test.cpp index dcffd513..39df5c77 100644 --- a/test/heavy_test.cpp +++ b/test/heavy_test.cpp @@ -9,15 +9,25 @@ // thread_pool's), not on the caller's thread; the caller's io_context goes on meanwhile (a 10 ms // timer on it fires while the work waits for it); the completion runs on the handler's // associated executor (the caller's io_context, on the caller's thread), whose io_context does -// not run out of work before it; a move-only result reaches the handler; and any completion -// token works (asio's deferred). +// not run out of work before it; a move-only result reaches the handler; any completion token +// works (asio's deferred); and the handler's associated allocator and cancellation slot are +// those of the function posted to the work's executor and of the one dispatched to the +// completion's, as asio asks of an operation's intermediate handlers. #include #include +#include +#include +#include +#include #include +#include #include #include +#include +#include +#include #include #include #include @@ -25,8 +35,10 @@ #include #include +#include #include #include +#include #include #ifndef WEBCPP_CRYPTO_HAS_THREADS @@ -124,11 +136,117 @@ void heavy_operation_with_any_token() { BOOST_TEST_EQ(received, 42); } +/** An allocator the test recognises by its type; it allocates as std::allocator does. */ +template +struct tagged_allocator { + using value_type = T; + + tagged_allocator() noexcept = default; + + template + explicit(false) tagged_allocator(tagged_allocator const& /*other*/) noexcept {} + + [[nodiscard]] T* allocate(std::size_t count) { return std::allocator{}.allocate(count); } + + void deallocate(T* pointer, std::size_t count) noexcept { + std::allocator{}.deallocate(pointer, count); + } + + friend bool operator==(tagged_allocator const& /*left*/, + tagged_allocator const& /*right*/) noexcept { + return true; + } +}; + +/** What a recording executor saw of the functions it was given to run. */ +struct record { + /** How many functions it ran. */ + std::atomic functions{0}; + /** How many of them had the handler's allocator associated. */ + std::atomic allocators{0}; + /** How many of them had the handler's cancellation slot associated. */ + std::atomic slots{0}; +}; + +/** An executor that records, of each function it runs, its associated allocator and + * cancellation slot, then runs it on `Inner`; properties are `Inner`'s. */ +template +class recording_executor { +public: + recording_executor(Inner inner, std::shared_ptr seen) noexcept + : inner_(std::move(inner)), seen_(std::move(seen)) {} + + template + void execute(Function&& function) const { + ++seen_->functions; + if constexpr (std::is_same_v< + std::decay_t, + tagged_allocator>) { + ++seen_->allocators; + } + if (boost::asio::get_associated_cancellation_slot(function).is_connected()) { + ++seen_->slots; + } + inner_.execute(std::forward(function)); + } + + template + auto query(Property const& property) const noexcept + -> decltype(boost::asio::query(std::declval(), property)) { + return boost::asio::query(inner_, property); + } + + template + auto require(Property const& property) const -> recording_executor< + std::decay_t(), property))>> { + return {boost::asio::require(inner_, property), seen_}; + } + + friend bool operator==(recording_executor const& left, + recording_executor const& right) noexcept { + return left.inner_ == right.inner_ && left.seen_ == right.seen_; + } + +private: + template + friend class recording_executor; + + Inner inner_; + std::shared_ptr seen_; +}; + +void carries_the_handlers_allocator_and_cancellation_slot() { + boost::asio::io_context caller; + boost::asio::thread_pool pool(1); + auto const work = std::make_shared(); + auto const completion = std::make_shared(); + boost::asio::cancellation_signal signal; + int received = 0; + crypto::detail::run_heavy( + recording_executor(pool.get_executor(), work), []() noexcept { return slow(41); }, + boost::asio::bind_cancellation_slot( + signal.slot(), + boost::asio::bind_allocator( + tagged_allocator{}, + boost::asio::bind_executor(recording_executor(caller.get_executor(), completion), + [&received](int result) { received = result; })))); + caller.run(); // lint-run: waits for the pool's thread to post the completion + pool.join(); + BOOST_TEST_EQ(received, 42); + BOOST_TEST_EQ(work->functions.load(), 1); + BOOST_TEST_EQ(work->allocators.load(), 1); + BOOST_TEST_EQ(work->slots.load(), 1); + BOOST_TEST_EQ(completion->functions.load(), 1); + BOOST_TEST_EQ(completion->allocators.load(), 1); + BOOST_TEST_EQ(completion->slots.load(), 1); +} + } // namespace int main() { runs_elsewhere_and_completes_on_the_caller(); move_only_result(); heavy_operation_with_any_token(); + carries_the_handlers_allocator_and_cancellation_slot(); return webcpp::test::exit_status(boost::report_errors()); } From c677a11f083bf489930cb3ee7966860d603fad36 Mon Sep 17 00:00:00 2001 From: R Date: Wed, 18 Nov 2026 02:36:44 -0300 Subject: [PATCH 042/110] crypto: the ChaCha20-Poly1305 docs say BearSSL reads the additional data after it encrypts, and what an overlap breaks --- include/webcpp/crypto/backends/bearssl.hpp | 5 +++-- include/webcpp/crypto/ciphers/aead.hpp | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/include/webcpp/crypto/backends/bearssl.hpp b/include/webcpp/crypto/backends/bearssl.hpp index ca34bc59..e7bbeda9 100644 --- a/include/webcpp/crypto/backends/bearssl.hpp +++ b/include/webcpp/crypto/backends/bearssl.hpp @@ -327,8 +327,9 @@ struct aead_engine { } /** - * Encrypts `data_bytes` in place and writes the tag. BearSSL reads the nonce and the - * additional data before it writes a byte of the data. + * Encrypts `data_bytes` in place and writes the tag. BearSSL reads the nonce before it + * writes a byte of the data, and the additional data after it encrypts (`aead` forbids + * their overlap). * * @param engine_state A keyed state. * @param iv_bytes 12 bytes. diff --git a/include/webcpp/crypto/ciphers/aead.hpp b/include/webcpp/crypto/ciphers/aead.hpp index c401dd21..da1dafc0 100644 --- a/include/webcpp/crypto/ciphers/aead.hpp +++ b/include/webcpp/crypto/ciphers/aead.hpp @@ -307,8 +307,9 @@ class aead { * The nonce is read before the first byte of `data_bytes` is written, so it may lie in * `data_bytes`. The additional data may touch `data_bytes`, as a wire format that puts it * just before the message does, but not overlap it: BearSSL's ChaCha20-Poly1305 reads it - * after it encrypts, in one call over the whole message, and an overlap would give a tag - * that no open accepts. + * after it encrypts, in one call over the whole message, so an overlap would authenticate + * other bytes than the caller's additional data; the backends would give different tags, + * and an open with the original additional data would fail. * * @param iv_bytes The nonce, `iv_size` bytes, never repeated under this key. * @param additional_data_bytes Authenticated, not encrypted. From 9c8805ea39d669081aa7f62db9fed92eed61cb7f Mon Sep 17 00:00:00 2001 From: R Date: Wed, 18 Nov 2026 02:36:44 -0300 Subject: [PATCH 043/110] crypto: OpenSSL's ChaCha20-Poly1305 engine records its constant-time compare and why the tag is set before each final --- include/webcpp/crypto/backends/openssl.hpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/include/webcpp/crypto/backends/openssl.hpp b/include/webcpp/crypto/backends/openssl.hpp index 73bddf39..e6f8778a 100644 --- a/include/webcpp/crypto/backends/openssl.hpp +++ b/include/webcpp/crypto/backends/openssl.hpp @@ -553,6 +553,12 @@ struct aead_state { * sends are the AEAD ones, which OpenSSL 3 names twice (`EVP_CTRL_GCM_SET_IVLEN` is * `EVP_CTRL_AEAD_SET_IVLEN`, and so are the tag's, include/openssl/evp.h). The error queue is * left as GCM's engine leaves it. + * + * GCM's `check` holds for ChaCha20-Poly1305's provider too: its final compares the tags with + * `CRYPTO_memcmp`, in constant time, and raises nothing on a mismatch + * (providers/implementations/ciphers/cipher_chacha20_poly1305_hw.c). Its tag length starts at 0 + * (the context is zero-allocated), and a final with no tag set would compare 0 bytes and accept + * any tag: the 16-byte tag `check` sets before each final is what makes the comparison. */ template <> struct aead_engine { @@ -629,6 +635,8 @@ struct aead_engine { if (!ran) { return ran; } + // GCM's check sets the 16-byte tag before the final, without which the provider would + // compare 0 bytes (see the class's comment). return sequence::check(view, tag_bytes); } From fab76649db8f84d8d83b61ea3e93595f163b1581 Mon Sep 17 00:00:00 2001 From: R Date: Wed, 18 Nov 2026 02:37:56 -0300 Subject: [PATCH 044/110] crypto: the speccheck test fails, rather than throws, on a committed WebCrypto view of another shape --- test/ed25519_speccheck_test.cpp | 53 ++++++++++++++++++++++----------- 1 file changed, 36 insertions(+), 17 deletions(-) diff --git a/test/ed25519_speccheck_test.cpp b/test/ed25519_speccheck_test.cpp index 05644b8e..75d03070 100644 --- a/test/ed25519_speccheck_test.cpp +++ b/test/ed25519_speccheck_test.cpp @@ -99,11 +99,18 @@ std::string_view verdict(bool accepted) { return accepted ? "accept" : "reject"; } -// A committed row: twelve verdicts, each accept or reject. +// A committed row: twelve verdicts, each accept or reject. A row of another shape fails the test, +// rather than end it on an exception. verdicts committed_row(json::value const& row, std::string const& label) { verdicts out; - for (auto const& entry : row.as_array()) { - out.push_back(text_of(entry)); + auto const* entries = row.if_array(); + if (entries == nullptr) { + BOOST_ERROR((label + ": the committed row is no array").c_str()); + return out; + } + for (auto const& entry : *entries) { + auto const* text = entry.if_string(); + out.emplace_back(text == nullptr ? "(not a string)" : std::string_view(*text)); if (out.back() != "accept" && out.back() != "reject") { BOOST_ERROR( (label + ": a committed verdict is neither accept nor reject: " + out.back()) @@ -154,6 +161,18 @@ void sodium_rows(std::vector const& cases, verdicts& raw, verdicts& s } } +// The object key names in parent; null when parent holds no key, or another kind of value there. +json::object const* object_in(json::object const& parent, std::string_view key) noexcept { + auto const* found = parent.if_contains(key); + return found == nullptr ? nullptr : found->if_object(); +} + +// The same, null also when parent is no object. +json::object const* object_in(json::value const& parent, std::string_view key) noexcept { + auto const* parent_object = parent.if_object(); + return parent_object == nullptr ? nullptr : object_in(*parent_object, key); +} + } // namespace int main() { @@ -219,27 +238,27 @@ int main() { compare("sodium strict", strict, sodium_strict); // The outside view: node's WebCrypto, committed as one row with the node and OpenSSL that - // gave it. - auto const* outside = committed.as_object().if_contains("outside"); - BOOST_TEST(outside != nullptr && outside->as_object().size() == 1U && - outside->as_object().contains("webcrypto-node")); - if (outside == nullptr || !outside->as_object().contains("webcrypto-node")) { + // gave it. A view of another shape fails the test, rather than end it on an exception. + auto const* outside = object_in(committed, "outside"); + auto const* view = outside == nullptr ? nullptr : object_in(*outside, "webcrypto-node"); + BOOST_TEST(outside != nullptr && outside->size() == 1U && view != nullptr); + if (view == nullptr) { return test::exit_status(boost::report_errors()); } - auto const& view = outside->at("webcrypto-node").as_object(); - BOOST_TEST(view.contains("node") && view.at("node").is_string()); - BOOST_TEST(view.contains("openssl") && view.at("openssl").is_string()); - BOOST_TEST(view.contains("verdicts")); - if (!view.contains("verdicts")) { + BOOST_TEST(view->contains("node") && view->at("node").is_string()); + BOOST_TEST(view->contains("openssl") && view->at("openssl").is_string()); + BOOST_TEST(view->contains("verdicts")); + if (!view->contains("verdicts")) { return test::exit_status(boost::report_errors()); } - auto const webcrypto = committed_row(view.at("verdicts"), "webcrypto-node"); + auto const webcrypto = committed_row(view->at("verdicts"), "webcrypto-node"); #ifdef __EMSCRIPTEN__ // The versions this run's node has, beside those committed: a node whose row differs says // which it is. - if (view.contains("node") && view.contains("openssl")) { - std::cout << "webcrypto-node committed with node " << text_of(view.at("node")) - << ", OpenSSL " << text_of(view.at("openssl")) << '\n'; + if (view->contains("node") && view->at("node").is_string() && view->contains("openssl") && + view->at("openssl").is_string()) { + std::cout << "webcrypto-node committed with node " << text_of(view->at("node")) + << ", OpenSSL " << text_of(view->at("openssl")) << '\n'; } print_node_versions(); verdicts subtle; From bd0870ea4039141cf515d597464c5fd6efcf466d Mon Sep 17 00:00:00 2001 From: R Date: Wed, 18 Nov 2026 02:39:54 -0300 Subject: [PATCH 045/110] crypto: a default not linked is refused with its family's /webcpp/crypto//-default line --- doc/generated/messages.adoc | 28 +++++----- doc/tables/crypto.json | 12 ++-- doc/tables/generate.py | 8 ++- doc/tables/generate_test.py | 14 +++-- include/webcpp/crypto/detail/capabilities.hpp | 56 +++++++++---------- .../chacha_default_not_linked.cpp | 6 +- .../ed25519_default_not_linked.cpp | 2 +- .../gcm_default_openssl_not_linked.cpp | 2 +- .../no_backend_wasm/no_backend_wasm.cpp | 2 +- .../openssl_only_on_wasi.cpp | 2 +- 10 files changed, 68 insertions(+), 64 deletions(-) diff --git a/doc/generated/messages.adoc b/doc/generated/messages.adoc index d5b2f9fb..722e652b 100644 --- a/doc/generated/messages.adoc +++ b/doc/generated/messages.adoc @@ -33,9 +33,9 @@ The fix: Add `+/third_party//bearssl+`. |`+chacha_default_not_linked+` |native, wasip2, wasip3 -|`+webcpp::crypto: XChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)+` +|`+webcpp::crypto: XChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//xchacha20_poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//xchacha20_poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)+` -The fix: The ChaCha20-Poly1305 AEADs' default is libsodium on every target: add `+/third_party//sodium+`. +The fix: The ChaCha20-Poly1305 AEADs' default is libsodium on every target: add the family's alias, as `+/webcpp/crypto//chacha20_poly1305-default+`, which links `+/third_party//sodium+`. |`+chacha_on_ctaes+` |native, wasip2, wasip3 @@ -63,9 +63,9 @@ The fix: Remove the define, and name `+gcm>+` where th |`+ed25519_default_not_linked+` |native, wasip2, wasip3 -|`+webcpp::crypto: Ed25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)+` +|`+webcpp::crypto: Ed25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//ed25519-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//ed25519-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)+` -The fix: Add `+/third_party//sodium+`, or `+/webcpp/crypto//ed25519-default+`, which links it on every target. +The fix: Add `+/webcpp/crypto//ed25519-default+`, which links `+/third_party//sodium+` on every target. |`+ed25519_on_bearssl+` |native, wasip2, wasip3 @@ -81,9 +81,9 @@ The fix: Name `+curves::ed25519::ph+`: RFC 8032 defines |`+gcm_default_openssl_not_linked+` |native -|`+webcpp::crypto: AES-GCM's default backend on this target is OpenSSL, which is not linked. Add /webcpp/crypto//openssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//openssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_OPENSSL=1 and link libcrypto)+` +|`+webcpp::crypto: AES-GCM's default backend on this target is OpenSSL, which is not linked. Add /webcpp/crypto//gcm-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//gcm-default ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_OPENSSL=1 and link libcrypto)+` -The fix: Natively the default is OpenSSL: add `+/webcpp/crypto//openssl+`, or name BearSSL in the type, as in `+gcm>+`. +The fix: Natively the default is OpenSSL: add `+/webcpp/crypto//gcm-default+`, which links `+/webcpp/crypto//openssl+` there, or name BearSSL in the type, as in `+gcm>+`. |`+gcm_on_ctaes+` |native, wasip2, wasip3 @@ -99,9 +99,9 @@ The fix: Call the synchronous operation the message names, or build with threads |`+no_backend_wasm+` |wasip2, wasip3 -|`+webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked. Add /third_party//bearssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)+` +|`+webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked. Add /webcpp/crypto//gcm-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//gcm-default ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)+` -The fix: On WASI the default is BearSSL: add `+/third_party//bearssl+`, or, with OpenSSL linked, name it in the type, as in `+gcm>+`. +The fix: On WASI the default is BearSSL: add `+/webcpp/crypto//gcm-default+`, which links `+/third_party//bearssl+` there, or, with OpenSSL linked, name it in the type, as in `+gcm>+`. |`+openssl_memory_not_linked+` |native @@ -129,9 +129,9 @@ The fix: Name `+/webcpp/crypto//openssl+`, which builds OpenSSL 3.5.9; without b |`+openssl_only_on_wasi+` |wasip2, wasip3 -|`+webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked. Add /third_party//bearssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)+` +|`+webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked. Add /webcpp/crypto//gcm-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//gcm-default ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)+` -The fix: On WASI the default is BearSSL: add `+/third_party//bearssl+`, or, with OpenSSL linked, name it in the type, as in `+gcm>+`. +The fix: On WASI the default is BearSSL: add `+/webcpp/crypto//gcm-default+`, which links `+/third_party//bearssl+` there, or, with OpenSSL linked, name it in the type, as in `+gcm>+`. |`+secp256k1_not_linked+` |native, wasip2 @@ -510,7 +510,7 @@ On each target, the build's output contains: * native, Linux: ** `pass:[undefined reference to `webcpp::crypto::openssl_memory_resource()']` -`+no_backend_on_emscripten+`:: A program for Emscripten that uses the default backend and links none. The fix: Add `+/third_party//bearssl+` to the program's sources. +`+no_backend_on_emscripten+`:: A program for Emscripten that uses the default backend and links none. The fix: Add `+/webcpp/crypto//gcm-default+`, which links `+/third_party//bearssl+` there, to the program's sources. + Its Jamfile: + @@ -622,7 +622,7 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |`+chacha_default_not_linked+` |the compile -|The ChaCha20-Poly1305 AEADs' default is libsodium on every target: add `+/third_party//sodium+`. +|The ChaCha20-Poly1305 AEADs' default is libsodium on every target: add the family's alias, as `+/webcpp/crypto//chacha20_poly1305-default+`, which links `+/third_party//sodium+`. |`+chacha_on_ctaes+` |the compile @@ -642,7 +642,7 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |`+ed25519_default_not_linked+` |the compile -|Add `+/third_party//sodium+`, or `+/webcpp/crypto//ed25519-default+`, which links it on every target. +|Add `+/webcpp/crypto//ed25519-default+`, which links `+/third_party//sodium+` on every target. |`+ed25519_on_bearssl+` |the compile @@ -654,7 +654,7 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |`+gcm_default_openssl_not_linked+` |the compile -|Natively the default is OpenSSL: add `+/webcpp/crypto//openssl+`, or name BearSSL in the type, as in `+gcm>+`. +|Natively the default is OpenSSL: add `+/webcpp/crypto//gcm-default+`, which links `+/webcpp/crypto//openssl+` there, or name BearSSL in the type, as in `+gcm>+`. |`+gcm_on_ctaes+` |the compile diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 77f4d659..19868bd9 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -662,15 +662,15 @@ "threads_on_emscripten": "A program for Emscripten built with `multi`, which is `-pthread`: the build has threads." }, "fixes": { - "gcm_default_openssl_not_linked": "Natively the default is OpenSSL: add `/webcpp/crypto//openssl`, or name BearSSL in the type, as in `gcm>`.", - "no_backend_wasm": "On WASI the default is BearSSL: add `/third_party//bearssl`, or, with OpenSSL linked, name it in the type, as in `gcm>`.", + "gcm_default_openssl_not_linked": "Natively the default is OpenSSL: add `/webcpp/crypto//gcm-default`, which links `/webcpp/crypto//openssl` there, or name BearSSL in the type, as in `gcm>`.", + "no_backend_wasm": "On WASI the default is BearSSL: add `/webcpp/crypto//gcm-default`, which links `/third_party//bearssl` there, or, with OpenSSL linked, name it in the type, as in `gcm>`.", "bearssl_not_linked": "Add `/third_party//bearssl`.", - "openssl_only_on_wasi": "On WASI the default is BearSSL: add `/third_party//bearssl`, or, with OpenSSL linked, name it in the type, as in `gcm>`.", + "openssl_only_on_wasi": "On WASI the default is BearSSL: add `/webcpp/crypto//gcm-default`, which links `/third_party//bearssl` there, or, with OpenSSL linked, name it in the type, as in `gcm>`.", "openssl_not_linked": "Add `/webcpp/crypto//openssl`.", "openssl_old": "Name `/webcpp/crypto//openssl`, which builds OpenSSL 3.5.9; without b2, put OpenSSL 3's `include/` first.", "ctaes_not_linked": "Add `/third_party//ctaes`.", "sodium_not_linked": "Add `/third_party//sodium`.", - "chacha_default_not_linked": "The ChaCha20-Poly1305 AEADs' default is libsodium on every target: add `/third_party//sodium`.", + "chacha_default_not_linked": "The ChaCha20-Poly1305 AEADs' default is libsodium on every target: add the family's alias, as `/webcpp/crypto//chacha20_poly1305-default`, which links `/third_party//sodium`.", "chacha_on_ctaes": "Name a backend that has ChaCha20-Poly1305, as in `chacha20_poly1305`, or its default, `chacha20_poly1305<>`, and link its library.", "aead_not_a_family": "Name one of the three ChaCha20-Poly1305 families; AES-GCM is `ciphers::gcm`, as in `aes256_gcm`.", "sodium_not_linked_on_emscripten": "Add `/third_party//sodium` to the program's sources.", @@ -698,7 +698,7 @@ "canary_ctaes_missing": "Link `/third_party//ctaes`.", "canary_secp256k1_missing": "Link `/third_party//secp256k1`.", "canary_secp256k1_small": "Give the program and the library the same ``, or link through b2.", - "no_backend_on_emscripten": "Add `/third_party//bearssl` to the program's sources.", + "no_backend_on_emscripten": "Add `/webcpp/crypto//gcm-default`, which links `/third_party//bearssl` there, to the program's sources.", "canary_secp256k1_two_files": "Compile every file of the program with the same backend settings.", "canary_two_files": "Compile every file of the program with the same backend settings.", "openssl_not_linked_msvc": "As `openssl_not_linked`.", @@ -706,7 +706,7 @@ "ed25519_on_bearssl_on_emscripten": "As `ed25519_on_bearssl`.", "ed25519ph_sha256": "Name `curves::ed25519::ph`: RFC 8032 defines Ed25519ph over SHA-512.", "ed25519ph_sha256_on_emscripten": "As `ed25519ph_sha256`.", - "ed25519_default_not_linked": "Add `/third_party//sodium`, or `/webcpp/crypto//ed25519-default`, which links it on every target.", + "ed25519_default_not_linked": "Add `/webcpp/crypto//ed25519-default`, which links `/third_party//sodium` on every target.", "ed25519_default_not_linked_on_emscripten": "As `ed25519_default_not_linked`.", "heavy_without_threads": "Call the synchronous operation the message names, or build with threads: natively without `WEBCPP_CRYPTO_NO_THREADS`, on Emscripten with `-pthread`; WASI has none.", "heavy_without_threads_on_emscripten": "As `heavy_without_threads`: on Emscripten, add `multi`." diff --git a/doc/tables/generate.py b/doc/tables/generate.py index 942eebb4..876d332f 100644 --- a/doc/tables/generate.py +++ b/doc/tables/generate.py @@ -694,15 +694,17 @@ def others_of(data: Data, family: Data, target: str, backend: str) -> List[str]: def needs(data: Data, family: Data, target: str, backend: str) -> str: """What a program that uses a family's default without linking it needs (design D32): the - Jamfile line that links it, and, where another backend has the family on the target, the type + Jamfile line that links it, the family's alias /webcpp/crypto//-default (which + default_aliases writes), and, where another backend has the family on the target, the type that names the first of them (others_of) in the family's shown name; then, as every message of a backend not linked, what a build without b2 defines and links. The text holds on every target where the default is that backend, so that one message test checks it on each.""" facts = data['backends'][backend] head = (f'webcpp::crypto: {family["title"]}\'s default backend on this target is ' f'{facts["title"]}, which is not linked') - add = (f'Add {facts["jamfile"]} to the program\'s Jamfile, as in: exe app : app.cpp ' - f'/webcpp/crypto//crypto {facts["jamfile"]} ;') + alias = f'/webcpp/crypto//{family["name"]}-default' + add = (f'Add {alias}, the default\'s library on every target, to the program\'s Jamfile, as ' + f'in: exe app : app.cpp /webcpp/crypto//crypto {alias} ;') without = (f'(without b2: define WEBCPP_CRYPTO_HAS_{backend.upper()}=1 and ' f'{facts["without_b2"]})') others = others_of(data, family, target, backend) diff --git a/doc/tables/generate_test.py b/doc/tables/generate_test.py index 3650e0d5..583f8e66 100644 --- a/doc/tables/generate_test.py +++ b/doc/tables/generate_test.py @@ -612,9 +612,10 @@ def test_the_default_s_refusal_says_what_the_program_needs(_: Path) -> None: # The default, not linked: what to add, and the type that names another backend. assert (f'static_assert(!std::is_same_v || ' f'::webcpp::crypto::detail::linked<{sodium}>, "webcpp::crypto: Ed25519\'s default ' - 'backend on this target is libsodium, which is not linked. Add /third_party//sodium to ' - 'the program\'s Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto ' - '/third_party//sodium ; or name another backend in the type, as in ' + 'backend on this target is libsodium, which is not linked. Add ' + '/webcpp/crypto//ed25519-default, the default\'s library on every target, to the ' + 'program\'s Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto ' + '/webcpp/crypto//ed25519-default ; or name another backend in the type, as in ' 'curves::ed25519::basic_keypair. The backends that have it: ' 'sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, ' 'emscripten). (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link ' @@ -628,10 +629,11 @@ def test_the_default_s_refusal_says_what_the_program_needs(_: Path) -> None: alone = generate.capabilities_header(data).split('#elif defined(WEBCPP_TARGET_EMSCRIPTEN)\n', 1)[1] assert ('"webcpp::crypto: Ed25519\'s default backend on this target is libsodium, which is ' - 'not linked, and the one backend that has it there. Add /third_party//sodium to the ' + 'not linked, and the one backend that has it there. Add ' + '/webcpp/crypto//ed25519-default, the default\'s library on every target, to the ' 'program\'s Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto ' - '/third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link ' - 'libsodium)")') in alone, alone + '/webcpp/crypto//ed25519-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and ' + 'link libsodium)")') in alone, alone assert 'default backend on this target is BearSSL' in emscripten, emscripten # Any other type is refused as no backend of the family, and nothing else is. assert ('static_assert(std::is_same_v || ' diff --git a/include/webcpp/crypto/detail/capabilities.hpp b/include/webcpp/crypto/detail/capabilities.hpp index 503f6a40..e7c5143f 100644 --- a/include/webcpp/crypto/detail/capabilities.hpp +++ b/include/webcpp/crypto/detail/capabilities.hpp @@ -233,7 +233,7 @@ inline constexpr bool linked = true; /** The refusals of the family AES-GCM's primary engine for `Backend`, on native. */ #define WEBCPP_CRYPTO_DETAIL_REFUSE_GCM(Backend) \ static_assert(!std::is_same_v, "webcpp::crypto: bearssl's AES-GCM is in , which the program does not include. Include it, and add /third_party//bearssl to the program's Jamfile."); \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::openssl>, "webcpp::crypto: AES-GCM's default backend on this target is OpenSSL, which is not linked. Add /webcpp/crypto//openssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//openssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_OPENSSL=1 and link libcrypto)"); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::openssl>, "webcpp::crypto: AES-GCM's default backend on this target is OpenSSL, which is not linked. Add /webcpp/crypto//gcm-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//gcm-default ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_OPENSSL=1 and link libcrypto)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::openssl>, "webcpp::crypto: openssl's AES-GCM is in , which the program does not include. Include it, and add /webcpp/crypto//openssl to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no AES-GCM. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no AES-GCM. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ @@ -242,7 +242,7 @@ inline constexpr bool linked = true; #elif defined(WEBCPP_TARGET_WASIP2) /** The refusals of the family AES-GCM's primary engine for `Backend`, on wasip2. */ #define WEBCPP_CRYPTO_DETAIL_REFUSE_GCM(Backend) \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::bearssl>, "webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked. Add /third_party//bearssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)"); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::bearssl>, "webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked. Add /webcpp/crypto//gcm-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//gcm-default ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::bearssl>, "webcpp::crypto: bearssl's AES-GCM is in , which the program does not include. Include it, and add /third_party//bearssl to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: openssl's AES-GCM is in , which the program does not include. Include it, and add /webcpp/crypto//openssl to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no AES-GCM. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ @@ -252,7 +252,7 @@ inline constexpr bool linked = true; #elif defined(WEBCPP_TARGET_WASIP3) /** The refusals of the family AES-GCM's primary engine for `Backend`, on wasip3. */ #define WEBCPP_CRYPTO_DETAIL_REFUSE_GCM(Backend) \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::bearssl>, "webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked. Add /third_party//bearssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)"); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::bearssl>, "webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked. Add /webcpp/crypto//gcm-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//gcm-default ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::bearssl>, "webcpp::crypto: bearssl's AES-GCM is in , which the program does not include. Include it, and add /third_party//bearssl to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: openssl's AES-GCM is in , which the program does not include. Include it, and add /webcpp/crypto//openssl to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no AES-GCM. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ @@ -262,7 +262,7 @@ inline constexpr bool linked = true; #elif defined(WEBCPP_TARGET_EMSCRIPTEN) /** The refusals of the family AES-GCM's primary engine for `Backend`, on emscripten. */ #define WEBCPP_CRYPTO_DETAIL_REFUSE_GCM(Backend) \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::bearssl>, "webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked, and the one backend that has it there. Add /third_party//bearssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ; (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)"); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::bearssl>, "webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked, and the one backend that has it there. Add /webcpp/crypto//gcm-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//gcm-default ; (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::bearssl>, "webcpp::crypto: bearssl's AES-GCM is in , which the program does not include. Include it, and add /third_party//bearssl to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: openssl has no AES-GCM on emscripten. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no AES-GCM. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ @@ -313,7 +313,7 @@ inline constexpr bool linked = true; static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: openssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::secp256k1>, "webcpp::crypto: secp256k1's default backend on this target is libsecp256k1, which is not linked, and the one backend that has it there. Add /third_party//secp256k1 to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//secp256k1 ; (without b2: define WEBCPP_CRYPTO_HAS_SECP256K1=1 and link libsecp256k1 built with webcpp's src/canary_secp256k1.c)"); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::secp256k1>, "webcpp::crypto: secp256k1's default backend on this target is libsecp256k1, which is not linked, and the one backend that has it there. Add /webcpp/crypto//secp256k1-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//secp256k1-default ; (without b2: define WEBCPP_CRYPTO_HAS_SECP256K1=1 and link libsecp256k1 built with webcpp's src/canary_secp256k1.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::secp256k1>, "webcpp::crypto: secp256k1's secp256k1 is in , which the program does not include. Include it, and add /third_party//secp256k1 to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: sodium has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: secp256k1 has no backend of that name. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten).") @@ -323,7 +323,7 @@ inline constexpr bool linked = true; static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: openssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::secp256k1>, "webcpp::crypto: secp256k1's default backend on this target is libsecp256k1, which is not linked, and the one backend that has it there. Add /third_party//secp256k1 to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//secp256k1 ; (without b2: define WEBCPP_CRYPTO_HAS_SECP256K1=1 and link libsecp256k1 built with webcpp's src/canary_secp256k1.c)"); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::secp256k1>, "webcpp::crypto: secp256k1's default backend on this target is libsecp256k1, which is not linked, and the one backend that has it there. Add /webcpp/crypto//secp256k1-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//secp256k1-default ; (without b2: define WEBCPP_CRYPTO_HAS_SECP256K1=1 and link libsecp256k1 built with webcpp's src/canary_secp256k1.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::secp256k1>, "webcpp::crypto: secp256k1's secp256k1 is in , which the program does not include. Include it, and add /third_party//secp256k1 to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: sodium has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: secp256k1 has no backend of that name. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten).") @@ -333,7 +333,7 @@ inline constexpr bool linked = true; static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: openssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::secp256k1>, "webcpp::crypto: secp256k1's default backend on this target is libsecp256k1, which is not linked, and the one backend that has it there. Add /third_party//secp256k1 to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//secp256k1 ; (without b2: define WEBCPP_CRYPTO_HAS_SECP256K1=1 and link libsecp256k1 built with webcpp's src/canary_secp256k1.c)"); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::secp256k1>, "webcpp::crypto: secp256k1's default backend on this target is libsecp256k1, which is not linked, and the one backend that has it there. Add /webcpp/crypto//secp256k1-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//secp256k1-default ; (without b2: define WEBCPP_CRYPTO_HAS_SECP256K1=1 and link libsecp256k1 built with webcpp's src/canary_secp256k1.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::secp256k1>, "webcpp::crypto: secp256k1's secp256k1 is in , which the program does not include. Include it, and add /third_party//secp256k1 to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: sodium has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: secp256k1 has no backend of that name. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten).") @@ -343,7 +343,7 @@ inline constexpr bool linked = true; static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: openssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::secp256k1>, "webcpp::crypto: secp256k1's default backend on this target is libsecp256k1, which is not linked, and the one backend that has it there. Add /third_party//secp256k1 to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//secp256k1 ; (without b2: define WEBCPP_CRYPTO_HAS_SECP256K1=1 and link libsecp256k1 built with webcpp's src/canary_secp256k1.c)"); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::secp256k1>, "webcpp::crypto: secp256k1's default backend on this target is libsecp256k1, which is not linked, and the one backend that has it there. Add /webcpp/crypto//secp256k1-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//secp256k1-default ; (without b2: define WEBCPP_CRYPTO_HAS_SECP256K1=1 and link libsecp256k1 built with webcpp's src/canary_secp256k1.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::secp256k1>, "webcpp::crypto: secp256k1's secp256k1 is in , which the program does not include. Include it, and add /third_party//secp256k1 to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: sodium has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: secp256k1 has no backend of that name. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten).") @@ -355,7 +355,7 @@ inline constexpr bool linked = true; static_assert(!std::is_same_v, "webcpp::crypto: openssl has no Ed25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no Ed25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no Ed25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: Ed25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: Ed25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//ed25519-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//ed25519-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's Ed25519 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: Ed25519 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") #elif defined(WEBCPP_TARGET_WASIP2) @@ -365,7 +365,7 @@ inline constexpr bool linked = true; static_assert(!std::is_same_v, "webcpp::crypto: openssl has no Ed25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no Ed25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no Ed25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: Ed25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: Ed25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//ed25519-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//ed25519-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's Ed25519 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: Ed25519 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") #elif defined(WEBCPP_TARGET_WASIP3) @@ -375,7 +375,7 @@ inline constexpr bool linked = true; static_assert(!std::is_same_v, "webcpp::crypto: openssl has no Ed25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no Ed25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no Ed25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: Ed25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: Ed25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//ed25519-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//ed25519-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's Ed25519 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: Ed25519 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") #elif defined(WEBCPP_TARGET_EMSCRIPTEN) @@ -385,7 +385,7 @@ inline constexpr bool linked = true; static_assert(!std::is_same_v, "webcpp::crypto: openssl has no Ed25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no Ed25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no Ed25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: Ed25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: Ed25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//ed25519-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//ed25519-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's Ed25519 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: Ed25519 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") #endif @@ -396,7 +396,7 @@ inline constexpr bool linked = true; static_assert(!std::is_same_v, "webcpp::crypto: openssl has no X25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no X25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no X25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: X25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: X25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//x25519-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//x25519-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's X25519 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: X25519 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") #elif defined(WEBCPP_TARGET_WASIP2) @@ -406,7 +406,7 @@ inline constexpr bool linked = true; static_assert(!std::is_same_v, "webcpp::crypto: openssl has no X25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no X25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no X25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: X25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: X25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//x25519-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//x25519-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's X25519 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: X25519 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") #elif defined(WEBCPP_TARGET_WASIP3) @@ -416,7 +416,7 @@ inline constexpr bool linked = true; static_assert(!std::is_same_v, "webcpp::crypto: openssl has no X25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no X25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no X25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: X25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: X25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//x25519-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//x25519-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's X25519 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: X25519 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") #elif defined(WEBCPP_TARGET_EMSCRIPTEN) @@ -426,7 +426,7 @@ inline constexpr bool linked = true; static_assert(!std::is_same_v, "webcpp::crypto: openssl has no X25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no X25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no X25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: X25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: X25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//x25519-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//x25519-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's X25519 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: X25519 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") #endif @@ -437,7 +437,7 @@ inline constexpr bool linked = true; static_assert(!std::is_same_v, "webcpp::crypto: openssl's ChaCha20-Poly1305 is in , which the program does not include. Include it, and add /webcpp/crypto//openssl to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; or name another backend in the type, as in ciphers::chacha20_poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked. Add /webcpp/crypto//chacha20_poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//chacha20_poly1305-default ; or name another backend in the type, as in ciphers::chacha20_poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's ChaCha20-Poly1305 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: ChaCha20-Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).") #elif defined(WEBCPP_TARGET_WASIP2) @@ -447,7 +447,7 @@ inline constexpr bool linked = true; static_assert(!std::is_same_v, "webcpp::crypto: openssl's ChaCha20-Poly1305 is in , which the program does not include. Include it, and add /webcpp/crypto//openssl to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; or name another backend in the type, as in ciphers::chacha20_poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked. Add /webcpp/crypto//chacha20_poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//chacha20_poly1305-default ; or name another backend in the type, as in ciphers::chacha20_poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's ChaCha20-Poly1305 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: ChaCha20-Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).") #elif defined(WEBCPP_TARGET_WASIP3) @@ -457,7 +457,7 @@ inline constexpr bool linked = true; static_assert(!std::is_same_v, "webcpp::crypto: openssl's ChaCha20-Poly1305 is in , which the program does not include. Include it, and add /webcpp/crypto//openssl to the program's Jamfile."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; or name another backend in the type, as in ciphers::chacha20_poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked. Add /webcpp/crypto//chacha20_poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//chacha20_poly1305-default ; or name another backend in the type, as in ciphers::chacha20_poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's ChaCha20-Poly1305 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: ChaCha20-Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).") #elif defined(WEBCPP_TARGET_EMSCRIPTEN) @@ -467,7 +467,7 @@ inline constexpr bool linked = true; static_assert(!std::is_same_v, "webcpp::crypto: openssl has no ChaCha20-Poly1305 on emscripten. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; or name another backend in the type, as in ciphers::chacha20_poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked. Add /webcpp/crypto//chacha20_poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//chacha20_poly1305-default ; or name another backend in the type, as in ciphers::chacha20_poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's ChaCha20-Poly1305 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: ChaCha20-Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).") #endif @@ -480,7 +480,7 @@ inline constexpr bool linked = true; static_assert(!std::is_same_v, "webcpp::crypto: openssl has no original ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no original ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no original ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: original ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: original ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//chacha20_poly1305_original-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//chacha20_poly1305_original-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's original ChaCha20-Poly1305 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: original ChaCha20-Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") #elif defined(WEBCPP_TARGET_WASIP2) @@ -492,7 +492,7 @@ inline constexpr bool linked = true; static_assert(!std::is_same_v, "webcpp::crypto: openssl has no original ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no original ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no original ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: original ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: original ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//chacha20_poly1305_original-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//chacha20_poly1305_original-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's original ChaCha20-Poly1305 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: original ChaCha20-Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") #elif defined(WEBCPP_TARGET_WASIP3) @@ -504,7 +504,7 @@ inline constexpr bool linked = true; static_assert(!std::is_same_v, "webcpp::crypto: openssl has no original ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no original ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no original ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: original ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: original ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//chacha20_poly1305_original-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//chacha20_poly1305_original-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's original ChaCha20-Poly1305 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: original ChaCha20-Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") #elif defined(WEBCPP_TARGET_EMSCRIPTEN) @@ -517,7 +517,7 @@ inline constexpr bool linked = true; static_assert(!std::is_same_v, "webcpp::crypto: openssl has no original ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no original ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no original ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: original ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: original ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//chacha20_poly1305_original-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//chacha20_poly1305_original-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's original ChaCha20-Poly1305 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: original ChaCha20-Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") #endif @@ -528,7 +528,7 @@ inline constexpr bool linked = true; static_assert(!std::is_same_v, "webcpp::crypto: openssl has no XChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no XChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no XChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: XChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: XChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//xchacha20_poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//xchacha20_poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's XChaCha20-Poly1305 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: XChaCha20-Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") #elif defined(WEBCPP_TARGET_WASIP2) @@ -538,7 +538,7 @@ inline constexpr bool linked = true; static_assert(!std::is_same_v, "webcpp::crypto: openssl has no XChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no XChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no XChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: XChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: XChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//xchacha20_poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//xchacha20_poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's XChaCha20-Poly1305 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: XChaCha20-Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") #elif defined(WEBCPP_TARGET_WASIP3) @@ -548,7 +548,7 @@ inline constexpr bool linked = true; static_assert(!std::is_same_v, "webcpp::crypto: openssl has no XChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no XChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no XChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: XChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: XChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//xchacha20_poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//xchacha20_poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's XChaCha20-Poly1305 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: XChaCha20-Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") #elif defined(WEBCPP_TARGET_EMSCRIPTEN) @@ -558,7 +558,7 @@ inline constexpr bool linked = true; static_assert(!std::is_same_v, "webcpp::crypto: openssl has no XChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no XChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no XChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ - static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: XChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: XChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//xchacha20_poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//xchacha20_poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's XChaCha20-Poly1305 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: XChaCha20-Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") #endif diff --git a/test/messages/chacha_default_not_linked/chacha_default_not_linked.cpp b/test/messages/chacha_default_not_linked/chacha_default_not_linked.cpp index 03104350..bf55c175 100644 --- a/test/messages/chacha_default_not_linked/chacha_default_not_linked.cpp +++ b/test/messages/chacha_default_not_linked/chacha_default_not_linked.cpp @@ -12,9 +12,9 @@ // 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/ciphers/aead.hpp:* {{webcpp::crypto: ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; or name another backend in the type, as in ciphers::chacha20_poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)}} -// expected-error@webcpp/crypto/ciphers/aead.hpp:* {{webcpp::crypto: original ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)}} -// expected-error@webcpp/crypto/ciphers/aead.hpp:* {{webcpp::crypto: XChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)}} +// expected-error@webcpp/crypto/ciphers/aead.hpp:* {{webcpp::crypto: ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked. Add /webcpp/crypto//chacha20_poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//chacha20_poly1305-default ; or name another backend in the type, as in ciphers::chacha20_poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)}} +// expected-error@webcpp/crypto/ciphers/aead.hpp:* {{webcpp::crypto: original ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//chacha20_poly1305_original-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//chacha20_poly1305_original-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)}} +// expected-error@webcpp/crypto/ciphers/aead.hpp:* {{webcpp::crypto: XChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//xchacha20_poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//xchacha20_poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)}} // clang-format on #include diff --git a/test/messages/ed25519_default_not_linked/ed25519_default_not_linked.cpp b/test/messages/ed25519_default_not_linked/ed25519_default_not_linked.cpp index 7d4a0d9c..0b05273f 100644 --- a/test/messages/ed25519_default_not_linked/ed25519_default_not_linked.cpp +++ b/test/messages/ed25519_default_not_linked/ed25519_default_not_linked.cpp @@ -8,7 +8,7 @@ // (design D32), and does not link it stops where it makes it, with the line that links it. // clang-format off -// expected-error@webcpp/crypto/curves/ed25519.hpp:* {{webcpp::crypto: Ed25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)}} +// expected-error@webcpp/crypto/curves/ed25519.hpp:* {{webcpp::crypto: Ed25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//ed25519-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//ed25519-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)}} // clang-format on #include diff --git a/test/messages/gcm_default_openssl_not_linked/gcm_default_openssl_not_linked.cpp b/test/messages/gcm_default_openssl_not_linked/gcm_default_openssl_not_linked.cpp index 5120110e..2b407366 100644 --- a/test/messages/gcm_default_openssl_not_linked/gcm_default_openssl_not_linked.cpp +++ b/test/messages/gcm_default_openssl_not_linked/gcm_default_openssl_not_linked.cpp @@ -9,7 +9,7 @@ // with the line that links OpenSSL and the type that names BearSSL. // clang-format off -// expected-error@webcpp/crypto/ciphers/gcm.hpp:* {{webcpp::crypto: AES-GCM's default backend on this target is OpenSSL, which is not linked. Add /webcpp/crypto//openssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//openssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_OPENSSL=1 and link libcrypto)}} +// expected-error@webcpp/crypto/ciphers/gcm.hpp:* {{webcpp::crypto: AES-GCM's default backend on this target is OpenSSL, which is not linked. Add /webcpp/crypto//gcm-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//gcm-default ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_OPENSSL=1 and link libcrypto)}} // clang-format on #include diff --git a/test/messages/no_backend_wasm/no_backend_wasm.cpp b/test/messages/no_backend_wasm/no_backend_wasm.cpp index 72f704dd..12ffaf56 100644 --- a/test/messages/no_backend_wasm/no_backend_wasm.cpp +++ b/test/messages/no_backend_wasm/no_backend_wasm.cpp @@ -9,7 +9,7 @@ // (design D32). // clang-format off -// expected-error@webcpp/crypto/ciphers/gcm.hpp:* {{webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked. Add /third_party//bearssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)}} +// expected-error@webcpp/crypto/ciphers/gcm.hpp:* {{webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked. Add /webcpp/crypto//gcm-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//gcm-default ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)}} // clang-format on #include diff --git a/test/messages/openssl_only_on_wasi/openssl_only_on_wasi.cpp b/test/messages/openssl_only_on_wasi/openssl_only_on_wasi.cpp index f2264419..8599dac8 100644 --- a/test/messages/openssl_only_on_wasi/openssl_only_on_wasi.cpp +++ b/test/messages/openssl_only_on_wasi/openssl_only_on_wasi.cpp @@ -9,7 +9,7 @@ // with the line that links BearSSL and the type that names OpenSSL. // clang-format off -// expected-error@webcpp/crypto/ciphers/gcm.hpp:* {{webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked. Add /third_party//bearssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)}} +// expected-error@webcpp/crypto/ciphers/gcm.hpp:* {{webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked. Add /webcpp/crypto//gcm-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//gcm-default ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)}} // clang-format on #include From dc26dff61107da53d0aa43a593549792f4c2d679 Mon Sep 17 00:00:00 2001 From: R Date: Wed, 18 Nov 2026 02:47:06 -0300 Subject: [PATCH 046/110] crypto: chacha_on_ctaes and aead_not_a_family have their Emscripten fixtures --- doc/generated/messages.adoc | 34 +++++++++++++++++++++++++++++++--- doc/tables/crypto.json | 8 ++++++-- 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/doc/generated/messages.adoc b/doc/generated/messages.adoc index 722e652b..1887b5c2 100644 --- a/doc/generated/messages.adoc +++ b/doc/generated/messages.adoc @@ -154,6 +154,20 @@ The fix: Add `+/third_party//sodium+`. At build and link time, from the fixtures of the user's Jamfiles, each built on a scratch superproject: the texts the build's output contains, per target and linker, as each fixture checks them. +`+aead_not_a_family_on_emscripten+`:: A program for Emscripten that gives `+ciphers::aead+` AES-GCM's family, which `+ciphers::gcm+` serves instead. The fix: As `+aead_not_a_family+`. ++ +Its Jamfile: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/aead_not_a_family_on_emscripten/Jamfile[tag=jamfile] +---- ++ +On each target, the build's output contains: ++ +* emscripten: +** `+webcpp::crypto: ciphers::aead takes an AEAD family: families::chacha20_poly1305, families::chacha20_poly1305_original or families::xchacha20_poly1305.+` + `+canary_ctaes_missing+`:: ctaes's headers used without its library. The fix: Link `+/third_party//ctaes+`. + Its Jamfile: @@ -378,6 +392,20 @@ On each target, the build's output contains: ** `+undefined symbol: webcpp_crypto_bearssl_7bea48e_getentropy__add_third_party_bearssl_to_your_link+` ** `pass:[em++: error:]` +`+chacha_on_ctaes_on_emscripten+`:: A program for Emscripten that names ctaes, which has no ChaCha20-Poly1305, in the AEAD's type. The fix: As `+chacha_on_ctaes+`. ++ +Its Jamfile: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/chacha_on_ctaes_on_emscripten/Jamfile[tag=jamfile] +---- ++ +On each target, the build's output contains: ++ +* emscripten: +** `+webcpp::crypto: ctaes has no ChaCha20-Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).+` + `+default_bearssl_on_emscripten+`:: Version 0.1's define that chose BearSSL as the default, in a build for Emscripten. The fix: Remove the define: on Emscripten the default is BearSSL. + Its Jamfile: @@ -418,7 +446,7 @@ include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/ed25519_default_not_l On each target, the build's output contains: + * emscripten: -** `+webcpp::crypto: Ed25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /third_party//sodium to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)+` +** `+webcpp::crypto: Ed25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//ed25519-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//ed25519-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)+` `+ed25519_on_bearssl_on_emscripten+`:: A program for Emscripten that names BearSSL, which has no Ed25519, in an Ed25519 key pair's type. The fix: As `+ed25519_on_bearssl+`. + @@ -474,7 +502,7 @@ include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/heavy_without_threads On each target, the build's output contains: + * emscripten: -** `+webcpp::crypto: async_slow runs on another thread and needs a build with threads (natively b2 threading=multi; on Emscripten -pthread). Without threads, call slow.+` +** `+webcpp::crypto: async_slow runs on another thread and needs a build with threads (natively without WEBCPP_CRYPTO_NO_THREADS; on Emscripten -pthread). Without threads, call slow.+` `+memory_missing_definition_install+`:: The memory option set in the program's project, the install called, and `+openssl_memory_resource()+` not defined. The fix: Define `+std::pmr::memory_resource& webcpp::crypto::openssl_memory_resource() noexcept+` once in the program, returning a resource that is never destroyed. + @@ -522,7 +550,7 @@ include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/no_backend_on_emscrip On each target, the build's output contains: + * emscripten: -** `+webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked, and the one backend that has it there. Add /third_party//bearssl to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ; (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)+` +** `+webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked, and the one backend that has it there. Add /webcpp/crypto//gcm-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//gcm-default ; (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)+` `+openssl_memory_on_emscripten+`:: The memory option of the OpenSSL backend set in a build for Emscripten. The fix: Remove `+WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE+` from the WebAssembly build: give that build a project of its own, without the define and OpenSSL, naming `+/third_party//bearssl+`. On WebAssembly the backend is BearSSL, which allocates nothing. + diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 19868bd9..60834334 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -659,7 +659,9 @@ "ed25519_on_bearssl_on_emscripten": "A program for Emscripten that names BearSSL, which has no Ed25519, in an Ed25519 key pair's type.", "ed25519ph_sha256_on_emscripten": "A program for Emscripten that names SHA-256 in Ed25519ph's type, which RFC 8032 defines over SHA-512.", "heavy_without_threads_on_emscripten": "A program for Emscripten without `-pthread` that calls a heavy operation's `async_` variant (a test's own).", - "threads_on_emscripten": "A program for Emscripten built with `multi`, which is `-pthread`: the build has threads." + "threads_on_emscripten": "A program for Emscripten built with `multi`, which is `-pthread`: the build has threads.", + "chacha_on_ctaes_on_emscripten": "A program for Emscripten that names ctaes, which has no ChaCha20-Poly1305, in the AEAD's type.", + "aead_not_a_family_on_emscripten": "A program for Emscripten that gives `ciphers::aead` AES-GCM's family, which `ciphers::gcm` serves instead." }, "fixes": { "gcm_default_openssl_not_linked": "Natively the default is OpenSSL: add `/webcpp/crypto//gcm-default`, which links `/webcpp/crypto//openssl` there, or name BearSSL in the type, as in `gcm>`.", @@ -709,6 +711,8 @@ "ed25519_default_not_linked": "Add `/webcpp/crypto//ed25519-default`, which links `/third_party//sodium` on every target.", "ed25519_default_not_linked_on_emscripten": "As `ed25519_default_not_linked`.", "heavy_without_threads": "Call the synchronous operation the message names, or build with threads: natively without `WEBCPP_CRYPTO_NO_THREADS`, on Emscripten with `-pthread`; WASI has none.", - "heavy_without_threads_on_emscripten": "As `heavy_without_threads`: on Emscripten, add `multi`." + "heavy_without_threads_on_emscripten": "As `heavy_without_threads`: on Emscripten, add `multi`.", + "chacha_on_ctaes_on_emscripten": "As `chacha_on_ctaes`.", + "aead_not_a_family_on_emscripten": "As `aead_not_a_family`." } } From 8085e7191976fa57458f802139cf0e617e70e634 Mon Sep 17 00:00:00 2001 From: R Date: Wed, 18 Nov 2026 02:47:10 -0300 Subject: [PATCH 047/110] crypto: every /webcpp/crypto//-default has a user-Jamfile fixture on its targets and a row on the page --- doc/generated/default-aliases.adoc | 48 +++++++++++++++ doc/generated/jamfiles.adoc | 96 ++++++++++++++++++++++++++++++ doc/jamfile.adoc | 11 ++-- doc/tables/crypto.json | 6 ++ doc/tables/generate.py | 36 +++++++++++ doc/tables/generate_test.py | 37 ++++++++++++ test/Jamfile | 18 ++++++ 7 files changed, 248 insertions(+), 4 deletions(-) create mode 100644 doc/generated/default-aliases.adoc diff --git a/doc/generated/default-aliases.adoc b/doc/generated/default-aliases.adoc new file mode 100644 index 00000000..461204df --- /dev/null +++ b/doc/generated/default-aliases.adoc @@ -0,0 +1,48 @@ +// 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. + +[cols="3,2,4,3",options="header"] +|=== +|Alias |Family |Links |Fixture + +|`+/webcpp/crypto//gcm-default+` +|AES-GCM +|`+/webcpp/crypto//openssl+` on native; `+/third_party//bearssl+` on wasip2, wasip3, emscripten +|<> + +|`+/webcpp/crypto//secp256k1-default+` +|secp256k1 +|`+/third_party//secp256k1+` on every target +|<> + +|`+/webcpp/crypto//ed25519-default+` +|Ed25519 +|`+/third_party//sodium+` on every target +|<> + +|`+/webcpp/crypto//x25519-default+` +|X25519 +|`+/third_party//sodium+` on every target +|<> + +|`+/webcpp/crypto//chacha20_poly1305-default+` +|ChaCha20-Poly1305 +|`+/third_party//sodium+` on every target +|<> + +|`+/webcpp/crypto//chacha20_poly1305_original-default+` +|original ChaCha20-Poly1305 +|`+/third_party//sodium+` on every target +|<> + +|`+/webcpp/crypto//xchacha20_poly1305-default+` +|XChaCha20-Poly1305 +|`+/third_party//sodium+` on every target +|<> +|=== diff --git a/doc/generated/jamfiles.adoc b/doc/generated/jamfiles.adoc index e8612790..348a72ce 100644 --- a/doc/generated/jamfiles.adoc +++ b/doc/generated/jamfiles.adoc @@ -39,6 +39,54 @@ It prints: include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/both_bearssl_named/both_bearssl_named.outcome[tag=output] ---- +`+chacha20_poly1305_default+`:: RFC 8439's ChaCha20-Poly1305 example, sealed and opened on its default on every target, with the one line `+/webcpp/crypto//chacha20_poly1305-default+`, which links libsodium. ++ +Its Jamfile, built and run on native, wasip2, wasip3, emscripten: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/chacha20_poly1305_default/Jamfile[tag=jamfile] +---- ++ +It prints: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/chacha20_poly1305_default/chacha20_poly1305_default.outcome[tag=output] +---- + +`+chacha20_poly1305_original_default+`:: libsodium's case of the original ChaCha20-Poly1305, sealed and opened on its default on every target, with the one line `+/webcpp/crypto//chacha20_poly1305_original-default+`, which links libsodium. ++ +Its Jamfile, built and run on native, wasip2, wasip3, emscripten: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/chacha20_poly1305_original_default/Jamfile[tag=jamfile] +---- ++ +It prints: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/chacha20_poly1305_original_default/chacha20_poly1305_original_default.outcome[tag=output] +---- + +`+ed25519_default+`:: RFC 8032's first Ed25519 test, signed and verified on Ed25519's default on every target, with the one line `+/webcpp/crypto//ed25519-default+`, which links libsodium. ++ +Its Jamfile, built and run on native, wasip2, wasip3, emscripten: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/ed25519_default/Jamfile[tag=jamfile] +---- ++ +It prints: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/ed25519_default/ed25519_default.outcome[tag=output] +---- + `+encrypt_and_sign+`:: Two backends in one program on every target: AES-256-GCM on its default, through `+/webcpp/crypto//gcm-default+`, and a BIP 340 signature. + Its Jamfile, built and run on native, wasip2, wasip3, emscripten: @@ -103,6 +151,22 @@ It prints: include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/openssl_linked/openssl_linked.outcome[tag=output] ---- +`+secp256k1_default+`:: BIP 340's first test vector, signed and verified on secp256k1's default on every target, with the one line `+/webcpp/crypto//secp256k1-default+`, which links libsecp256k1. ++ +Its Jamfile, built and run on native, wasip2, wasip3, emscripten: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/secp256k1_default/Jamfile[tag=jamfile] +---- ++ +It prints: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/secp256k1_default/secp256k1_default.outcome[tag=output] +---- + `+server+`:: A server, natively: the same program with OpenSSL, the default natively. + Its Jamfile, built and run on native: @@ -182,3 +246,35 @@ It prints: ---- include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/web/web.outcome[tag=output] ---- + +`+x25519_default+`:: RFC 7748's shared secret on X25519's default on every target, with the one line `+/webcpp/crypto//x25519-default+`, which links libsodium. ++ +Its Jamfile, built and run on native, wasip2, wasip3, emscripten: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/x25519_default/Jamfile[tag=jamfile] +---- ++ +It prints: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/x25519_default/x25519_default.outcome[tag=output] +---- + +`+xchacha20_poly1305_default+`:: The XChaCha20-Poly1305 draft's example, sealed and opened on its default on every target, with the one line `+/webcpp/crypto//xchacha20_poly1305-default+`, which links libsodium. ++ +Its Jamfile, built and run on native, wasip2, wasip3, emscripten: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/xchacha20_poly1305_default/Jamfile[tag=jamfile] +---- ++ +It prints: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/xchacha20_poly1305_default/xchacha20_poly1305_default.outcome[tag=output] +---- diff --git a/doc/jamfile.adoc b/doc/jamfile.adoc index ced13f7d..31c31107 100644 --- a/doc/jamfile.adoc +++ b/doc/jamfile.adoc @@ -40,8 +40,8 @@ natively OpenSSL, on WebAssembly BearSSL, whatever else the program links (<>). A program that wants another backend names it in the type, as `ciphers::gcm>`, and links it; no define chooses a default. A native program that links BearSSL alone and -uses `aes256_gcm` stops where it calls it, with the line that links OpenSSL -and the type that names BearSSL. Version 0.1's +uses `aes256_gcm` stops where it calls it, with the line that links its +default, `/webcpp/crypto//gcm-default`, and the type that names BearSSL. Version 0.1's `WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL` and `WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL` stop the build with the type to write (<>). @@ -58,8 +58,11 @@ examples of this page link it so. The whole Jamfile of the fixture include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/gcm_default/Jamfile[tag=jamfile] ---- -Each family with a default has such a line, `/webcpp/crypto//-default` -(`secp256k1-default` too), generated with the defaults from the same table. +Each family with a default has such a line, `/webcpp/crypto//-default`, +generated with the defaults from the same table; each is built and run on +every target where its family has a default by the fixture named in its row: + +include::generated/default-aliases.adoc[] The source-built OpenSSL is compiled without assembly (`no-asm`) on MSVC, wasip2 and wasip3: its AES is table-based and its GHASH 4-bit, neither constant diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 60834334..8de67846 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -634,6 +634,12 @@ "encrypt_and_sign": "Two backends in one program on every target: AES-256-GCM on its default, through `/webcpp/crypto//gcm-default`, and a BIP 340 signature.", "gcm_default": "AES-256-GCM on its default on every target, with the one line `/webcpp/crypto//gcm-default`, which links OpenSSL natively and BearSSL on WebAssembly; the same program as `web`.", "openssl_linked": "OpenSSL, built from source, named in the type: natively and on WASI.", + "secp256k1_default": "BIP 340's first test vector, signed and verified on secp256k1's default on every target, with the one line `/webcpp/crypto//secp256k1-default`, which links libsecp256k1.", + "ed25519_default": "RFC 8032's first Ed25519 test, signed and verified on Ed25519's default on every target, with the one line `/webcpp/crypto//ed25519-default`, which links libsodium.", + "x25519_default": "RFC 7748's shared secret on X25519's default on every target, with the one line `/webcpp/crypto//x25519-default`, which links libsodium.", + "chacha20_poly1305_default": "RFC 8439's ChaCha20-Poly1305 example, sealed and opened on its default on every target, with the one line `/webcpp/crypto//chacha20_poly1305-default`, which links libsodium.", + "chacha20_poly1305_original_default": "libsodium's case of the original ChaCha20-Poly1305, sealed and opened on its default on every target, with the one line `/webcpp/crypto//chacha20_poly1305_original-default`, which links libsodium.", + "xchacha20_poly1305_default": "The XChaCha20-Poly1305 draft's example, sealed and opened on its default on every target, with the one line `/webcpp/crypto//xchacha20_poly1305-default`, which links libsodium.", "sign": "A BIP 340 signature with libsecp256k1's default tables.", "sign_small": "The same program with libsecp256k1's small tables, which libsecp256k1 documents as smaller and slower to verify ({secp256k1-configure}); not measured here yet.", "canary_missing": "BearSSL's headers used without its library, built by other means than b2.", diff --git a/doc/tables/generate.py b/doc/tables/generate.py index 876d332f..a158d0ba 100644 --- a/doc/tables/generate.py +++ b/doc/tables/generate.py @@ -740,6 +740,41 @@ def default_aliases(data: Data) -> str: return '\n'.join(out) + '\n' +def aliases_page(data: Data, cases: Dict[str, Tuple[List[str], Outcome]]) -> str: + """The table of the aliases default_aliases writes: per family with a default, its alias + /webcpp/crypto//-default, the library it links on each target, and the fixture of the + user's Jamfiles that builds and runs it, _default, which must build and run on every + target where the family has a default: a public name that no build reaches is a fault.""" + rows: List[List[str]] = [] + for family in data['families']: + cases_of = [(target, default_on(family, target)) for target in data['targets']] + if not any(backend for _, backend in cases_of): + continue + name = family['name'] + alias = f'/webcpp/crypto//{name}-default' + fixture = f'{name}_default' + if fixture not in cases or not cases[fixture][1].succeeds: + raise Fault(f'the alias {alias} has no fixture {fixture} that builds it') + missing = [target for target, backend in cases_of + if backend and target not in cases[fixture][1].targets] + if missing: + raise Fault(f'the fixture {fixture} does not run on {", ".join(missing)}, where ' + f'{family["title"]} has a default') + # The targets of each library, in the order of their first target: one cell that + # says "on every target" when one library serves them all. + grouped: Dict[str, List[str]] = {} + for target, backend in cases_of: + if backend: + grouped.setdefault(data['backends'][backend]['jamfile'], []).append(target) + links = '; '.join( + f'{code(jamfile)} on ' + f'{"every target" if targets == data["targets"] else ", ".join(targets)}' + for jamfile, targets in grouped.items()) + rows.append([code(alias), family['title'], links, + f'<>']) + return table(['Alias', 'Family', 'Links', 'Fixture'], rows, 'cols="3,2,4,3",') + + def with_aliases(text: str, block: str) -> str: """build.jam's text with its block of the defaults' aliases replaced by block.""" lines = text.splitlines(keepends=True) @@ -1380,6 +1415,7 @@ def generate(root: Path, library: Path) -> Dict[Path, str]: files[generated / 'constant-time.adoc'] = constant_time_page(data) files[generated / 'sizes.adoc'] = sizes_page(data) files[generated / 'jamfiles.adoc'] = jamfiles_page(data, cases) + files[generated / 'default-aliases.adoc'] = aliases_page(data, cases) files[generated / 'messages.adoc'] = messages_page(data, refusals, cases, msvc_cases(library)) files[generated / 'use-cases.adoc'] = use_cases_page(data, library) diff --git a/doc/tables/generate_test.py b/doc/tables/generate_test.py index 583f8e66..a5b46167 100644 --- a/doc/tables/generate_test.py +++ b/doc/tables/generate_test.py @@ -596,6 +596,42 @@ def test_each_family_s_default_has_an_alias_that_links_it_per_target(_: Path) -> raise AssertionError('a build.jam without the block was accepted') +def test_each_alias_has_a_row_and_a_fixture_that_runs_it_where_its_family_has_a_default( + scratch: Path) -> None: + # The page's table of the aliases: per family with a default, its alias, the library it links + # on each target and the fixture of the user's Jamfiles that builds and runs it, + # _default, which must build and run on every target where the family has a default. + def outcome(name: str, text: str) -> generate.Outcome: + return generate.Outcome(written(scratch, f'{name}.outcome', text)) + every = 'targets: native wasip2 wasip3 emscripten\nbuild: succeeds\nrun: app\nok\n' + cases = {'ed25519_default': ([], outcome('every', every))} + page = generate.aliases_page(two_backends(), cases) + assert ('|`+/webcpp/crypto//ed25519-default+`\n|Ed25519\n|`+/third_party//sodium+` on ' + 'native; `+/third_party//bearssl+` on wasip2, wasip3, emscripten\n' + '|<>\n') in page, page + # One library on every target is said so. + one = generate.aliases_page(small_table(), cases) + assert '|`+/third_party//sodium+` on every target\n' in one, one + # A family without a default has no row. + data = small_table() + data['families'][0]['default'] = [a_default(EVERY_TARGET, None)] + assert '|`+/webcpp' not in generate.aliases_page(data, {}), generate.aliases_page(data, {}) + # An alias without its fixture, with one that fails, or with one that leaves out a target + # where its family has a default, is a fault. + for broken, wanted in ( + ({}, 'has no fixture ed25519_default'), + ({'ed25519_default': ([], outcome('fails', every.replace('succeeds', 'fails')))}, + 'has no fixture ed25519_default'), + ({'ed25519_default': ([], outcome('native', every.replace(' wasip2', '')))}, + 'the fixture ed25519_default does not run on wasip2')): + try: + generate.aliases_page(two_backends(), broken) + except generate.Fault as fault: + assert wanted in str(fault), fault + else: + raise AssertionError(f'no fault saying {wanted}') + + def test_a_family_without_a_default_has_no_type(_: Path) -> None: data = small_table() data['families'][0]['default'] = [a_default(EVERY_TARGET, None)] @@ -728,6 +764,7 @@ def test_the_check_names_a_file_that_differs(scratch: Path) -> None: test_the_other_backend_a_refusal_names_is_chosen_as_stated, test_a_family_without_a_default_has_no_type, test_each_family_s_default_has_an_alias_that_links_it_per_target, + test_each_alias_has_a_row_and_a_fixture_that_runs_it_where_its_family_has_a_default, test_the_default_s_refusal_says_what_the_program_needs, test_a_refusal_holds_on_its_target, test_a_type_names_only_crypto_s_namespaces_from_the_root, diff --git a/test/Jamfile b/test/Jamfile index b89d4f25..b6681311 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -435,6 +435,24 @@ webcpp.compile doc_encrypt_and_sign webcpp.compile doc_gcm_default_app : ../../../tools/test/fixtures/crypto_jamfiles/gcm_default/app.cpp : /webcpp/crypto//gcm-default ; +webcpp.compile doc_secp256k1_default_app + : ../../../tools/test/fixtures/crypto_jamfiles/secp256k1_default/app.cpp + : /webcpp/crypto//secp256k1-default ; +webcpp.compile doc_ed25519_default_app + : ../../../tools/test/fixtures/crypto_jamfiles/ed25519_default/app.cpp + : /webcpp/crypto//ed25519-default ; +webcpp.compile doc_x25519_default_app + : ../../../tools/test/fixtures/crypto_jamfiles/x25519_default/app.cpp + : /webcpp/crypto//x25519-default ; +webcpp.compile doc_chacha20_poly1305_default_app + : ../../../tools/test/fixtures/crypto_jamfiles/chacha20_poly1305_default/app.cpp + : /webcpp/crypto//chacha20_poly1305-default ; +webcpp.compile doc_chacha20_poly1305_original_default_app + : ../../../tools/test/fixtures/crypto_jamfiles/chacha20_poly1305_original_default/app.cpp + : /webcpp/crypto//chacha20_poly1305_original-default ; +webcpp.compile doc_xchacha20_poly1305_default_app + : ../../../tools/test/fixtures/crypto_jamfiles/xchacha20_poly1305_default/app.cpp + : /webcpp/crypto//xchacha20_poly1305-default ; webcpp.compile doc_openssl_linked : ../../../tools/test/fixtures/crypto_jamfiles/openssl_linked/app.cpp : /webcpp/crypto//openssl : native wasip2 wasip3 ; From 04edbe8f43e464e75f4b3e5860ef67d09fca18e1 Mon Sep 17 00:00:00 2001 From: R Date: Wed, 18 Nov 2026 03:28:37 -0300 Subject: [PATCH 048/110] crypto: the heavy stand-in's error defers to the refusal above it, and heavy_without_threads states both, alone --- include/webcpp/crypto/detail/heavy.hpp | 11 ++++++----- test/heavy_refusal_forgotten_test.cpp | 2 +- test/messages/heavy_without_threads/Jamfile | 2 +- .../heavy_without_threads/heavy_without_threads.cpp | 5 ++++- 4 files changed, 12 insertions(+), 8 deletions(-) diff --git a/include/webcpp/crypto/detail/heavy.hpp b/include/webcpp/crypto/detail/heavy.hpp index 009163f7..2973cb80 100644 --- a/include/webcpp/crypto/detail/heavy.hpp +++ b/include/webcpp/crypto/detail/heavy.hpp @@ -128,16 +128,17 @@ auto run_heavy(Executor executor, Function function, CompletionToken&& token) { /** * Without threads, a stand-in that is never meant to compile: a variant that starts with its - * refusal stops there first, and one that forgets `WEBCPP_CRYPTO_DETAIL_REQUIRE_THREADS` stops - * here, rather than compile into a call that never runs the work nor calls the handler. + * refusal stops there first, then here, with a text that defers to that refusal; one that + * forgets `WEBCPP_CRYPTO_DETAIL_REQUIRE_THREADS` stops here alone, rather than compile into a + * call that never runs the work nor calls the handler. */ template void run_heavy(Executor&& /*executor*/, Function&& /*function*/, CompletionToken&& /*token*/) noexcept { static_assert(::webcpp::crypto::detail::dependent_false, - "webcpp::crypto: a heavy operation's async_ variant starts with " - "WEBCPP_CRYPTO_DETAIL_REQUIRE_THREADS, which stops a build without threads " - "where the program calls it; this one does not."); + "webcpp::crypto: a heavy operation's async_ variant needs a build with " + "threads; if no error above names the synchronous call, this variant lacks " + "WEBCPP_CRYPTO_DETAIL_REQUIRE_THREADS."); } #endif diff --git a/test/heavy_refusal_forgotten_test.cpp b/test/heavy_refusal_forgotten_test.cpp index 282ae3b2..1a0764e9 100644 --- a/test/heavy_refusal_forgotten_test.cpp +++ b/test/heavy_refusal_forgotten_test.cpp @@ -10,7 +10,7 @@ // without it, the variant would compile, never run the work and never call the handler. // clang-format off -// expected-error@webcpp/crypto/detail/heavy.hpp:* {{webcpp::crypto: a heavy operation's async_ variant starts with WEBCPP_CRYPTO_DETAIL_REQUIRE_THREADS, which stops a build without threads where the program calls it; this one does not.}} +// expected-error@webcpp/crypto/detail/heavy.hpp:* {{webcpp::crypto: a heavy operation's async_ variant needs a build with threads; if no error above names the synchronous call, this variant lacks WEBCPP_CRYPTO_DETAIL_REQUIRE_THREADS.}} // clang-format on #include diff --git a/test/messages/heavy_without_threads/Jamfile b/test/messages/heavy_without_threads/Jamfile index a7306ce7..9289de98 100644 --- a/test/messages/heavy_without_threads/Jamfile +++ b/test/messages/heavy_without_threads/Jamfile @@ -20,4 +20,4 @@ rule without-threads ( properties * ) } webcpp.compile-diagnostic heavy_without_threads : heavy_without_threads.cpp - : @without-threads : native wasip2 wasip3 ; + : @without-threads : native wasip2 wasip3 : alone ; diff --git a/test/messages/heavy_without_threads/heavy_without_threads.cpp b/test/messages/heavy_without_threads/heavy_without_threads.cpp index d292a7aa..de5a872a 100644 --- a/test/messages/heavy_without_threads/heavy_without_threads.cpp +++ b/test/messages/heavy_without_threads/heavy_without_threads.cpp @@ -8,9 +8,12 @@ // WEBCPP_CRYPTO_NO_THREADS; on WASI always) stops where it is called, with the synchronous // operation to call instead (design D23). The operation is a test's own, declared as every heavy // operation declares its variant. The refusal is the first error; detail::run_heavy's stand-in -// adds its own after it (test/heavy_refusal_forgotten_test.cpp states that one). +// adds its own after it, which defers to an error above that names the synchronous call. The test +// is alone: these two errors are the compile's only ones. The refusal's directive comes last, as +// the message the page shows (doc/tables/generate.py reads a test's last directive). // clang-format off +// expected-error@webcpp/crypto/detail/heavy.hpp:* {{webcpp::crypto: a heavy operation's async_ variant needs a build with threads; if no error above names the synchronous call, this variant lacks WEBCPP_CRYPTO_DETAIL_REQUIRE_THREADS.}} // expected-error@*:* {{webcpp::crypto: async_slow runs on another thread and needs a build with threads (natively without WEBCPP_CRYPTO_NO_THREADS; on Emscripten -pthread). Without threads, call slow.}} // clang-format on From 8b14dcf2c0c88e55444e4e83a693cb376504974c Mon Sep 17 00:00:00 2001 From: R Date: Wed, 18 Nov 2026 03:29:47 -0300 Subject: [PATCH 049/110] crypto: the speccheck test fails, rather than throws, on any committed or upstream entry of another shape --- test/ed25519_speccheck_test.cpp | 100 ++++++++++++++++++++++---------- 1 file changed, 68 insertions(+), 32 deletions(-) diff --git a/test/ed25519_speccheck_test.cpp b/test/ed25519_speccheck_test.cpp index 75d03070..7fc5bfa9 100644 --- a/test/ed25519_speccheck_test.cpp +++ b/test/ed25519_speccheck_test.cpp @@ -91,8 +91,29 @@ struct edge_case { std::vector signature; }; -std::string text_of(json::value const& value) { - return std::string(std::string_view(value.as_string())); +// The null value a missing key reads as, which every reader below reports as of another shape. +json::value const missing_value; + +// The value key names in parent, or the null value when it holds none. +json::value const& value_at(json::object const& parent, std::string_view key) noexcept { + auto const* found = parent.if_contains(key); + return found == nullptr ? missing_value : *found; +} + +// The text of value, or an empty text and a failed test when it is no string: a committed or +// upstream file of another shape fails the test rather than end it on an exception. +std::string text_of(json::value const& value, std::string_view label) { + auto const* text = value.if_string(); + if (text == nullptr) { + BOOST_ERROR((std::string(label) + " is no string").c_str()); + return {}; + } + return std::string(std::string_view(*text)); +} + +// The text key names in parent (see text_of). +std::string text_at(json::object const& parent, std::string_view key) { + return text_of(value_at(parent, key), key); } std::string_view verdict(bool accepted) { @@ -167,12 +188,6 @@ json::object const* object_in(json::object const& parent, std::string_view key) return found == nullptr ? nullptr : found->if_object(); } -// The same, null also when parent is no object. -json::object const* object_in(json::value const& parent, std::string_view key) noexcept { - auto const* parent_object = parent.if_object(); - return parent_object == nullptr ? nullptr : object_in(*parent_object, key); -} - } // namespace int main() { @@ -190,11 +205,21 @@ int main() { } std::vector cases; - for (auto const& entry : cases_document.as_array()) { + auto const* entries = cases_document.if_array(); + BOOST_TEST(entries != nullptr); + if (entries == nullptr) { + return test::exit_status(boost::report_errors()); + } + for (auto const& entry : *entries) { + auto const* fields = entry.if_object(); + BOOST_TEST(fields != nullptr); + if (fields == nullptr) { + return test::exit_status(boost::report_errors()); + } cases.push_back({ - .message = test::from_hex(text_of(entry.at("message"))), - .public_key = test::from_hex(text_of(entry.at("pub_key"))), - .signature = test::from_hex(text_of(entry.at("signature"))), + .message = test::from_hex(text_at(*fields, "message")), + .public_key = test::from_hex(text_at(*fields, "pub_key")), + .signature = test::from_hex(text_at(*fields, "signature")), }); BOOST_TEST_EQ(cases.back().public_key.size(), 32U); BOOST_TEST_EQ(cases.back().signature.size(), 64U); @@ -204,27 +229,39 @@ int main() { return test::exit_status(boost::report_errors()); } + // The committed file: each part of another shape fails the test, rather than end it on an + // exception. + auto const* root = committed.if_object(); + BOOST_TEST(root != nullptr); + if (root == nullptr) { + return test::exit_status(boost::report_errors()); + } + // What each case tests, the page's first column: one text per case. - auto const& texts = committed.at("cases").as_array(); - BOOST_TEST_EQ(texts.size(), case_count); + auto const* texts = value_at(*root, "cases").if_array(); + BOOST_TEST(texts != nullptr && texts->size() == case_count); - auto const& source = committed.at("source"); - BOOST_TEST_EQ(text_of(source.at("repository")), "novifinancial/ed25519-speccheck"); - BOOST_TEST_EQ(text_of(source.at("commit")), "65519336"); - BOOST_TEST_EQ(text_of(source.at("file")), "cases.json"); + auto const* source = object_in(*root, "source"); + BOOST_TEST(source != nullptr); + if (source != nullptr) { + BOOST_TEST_EQ(text_at(*source, "repository"), "novifinancial/ed25519-speccheck"); + BOOST_TEST_EQ(text_at(*source, "commit"), "65519336"); + BOOST_TEST_EQ(text_at(*source, "file"), "cases.json"); + } // Every committed backend is one this test runs (libsodium alone in this version), and each // backend's strict verdicts are compared with libsodium's committed row: under strict every // backend gives libsodium's verdicts. - auto const& backends = committed.at("backends").as_object(); - BOOST_TEST(backends.contains("sodium")); - if (!backends.contains("sodium")) { + auto const* backends = object_in(*root, "backends"); + auto const* sodium = backends == nullptr ? nullptr : object_in(*backends, "sodium"); + BOOST_TEST(sodium != nullptr); + if (sodium == nullptr) { return test::exit_status(boost::report_errors()); } - auto const sodium_raw = committed_row(backends.at("sodium").at("raw"), "sodium raw"); - auto const sodium_strict = committed_row(backends.at("sodium").at("strict"), "sodium strict"); + auto const sodium_raw = committed_row(value_at(*sodium, "raw"), "sodium raw"); + auto const sodium_strict = committed_row(value_at(*sodium, "strict"), "sodium strict"); // A backend's rows are committed with its run here. - for (auto const& entry : backends) { + for (auto const& entry : *backends) { if (entry.key() != "sodium") { BOOST_ERROR(("a committed backend this test does not run: " + std::string(entry.key())) .c_str()); @@ -239,26 +276,25 @@ int main() { // The outside view: node's WebCrypto, committed as one row with the node and OpenSSL that // gave it. A view of another shape fails the test, rather than end it on an exception. - auto const* outside = object_in(committed, "outside"); + auto const* outside = object_in(*root, "outside"); auto const* view = outside == nullptr ? nullptr : object_in(*outside, "webcrypto-node"); BOOST_TEST(outside != nullptr && outside->size() == 1U && view != nullptr); if (view == nullptr) { return test::exit_status(boost::report_errors()); } - BOOST_TEST(view->contains("node") && view->at("node").is_string()); - BOOST_TEST(view->contains("openssl") && view->at("openssl").is_string()); + BOOST_TEST(value_at(*view, "node").is_string()); + BOOST_TEST(value_at(*view, "openssl").is_string()); BOOST_TEST(view->contains("verdicts")); if (!view->contains("verdicts")) { return test::exit_status(boost::report_errors()); } - auto const webcrypto = committed_row(view->at("verdicts"), "webcrypto-node"); + auto const webcrypto = committed_row(value_at(*view, "verdicts"), "webcrypto-node"); #ifdef __EMSCRIPTEN__ // The versions this run's node has, beside those committed: a node whose row differs says // which it is. - if (view->contains("node") && view->at("node").is_string() && view->contains("openssl") && - view->at("openssl").is_string()) { - std::cout << "webcrypto-node committed with node " << text_of(view->at("node")) - << ", OpenSSL " << text_of(view->at("openssl")) << '\n'; + if (value_at(*view, "node").is_string() && value_at(*view, "openssl").is_string()) { + std::cout << "webcrypto-node committed with node " << text_at(*view, "node") << ", OpenSSL " + << text_at(*view, "openssl") << '\n'; } print_node_versions(); verdicts subtle; From 75fed2dd80b09700ca7e1800a20a09c3b240fe50 Mon Sep 17 00:00:00 2001 From: R Date: Wed, 18 Nov 2026 05:42:28 -0300 Subject: [PATCH 050/110] crypto: box, sealed boxes and secretbox on libsodium ciphers::secretbox and secretbox_xchacha20poly1305 are ciphers::aead over two new families without additional data (max_additional_data_size 0, a non-empty one refused with invalid_input_size), on crypto_secretbox_detached and its XChaCha20 twin. hybrid::basic_box (box, box_xchacha20poly1305) agrees its key once with crypto_box_beforenm, refusing a peer key of small order with weak_public_key, and seals and opens with the afternm functions; hybrid::basic_sealed_box wraps crypto_box_seal and crypto_box_seal_open, sizes checked first and the output zeroed on failure. libsodium reads the nonce again after it writes the ciphertext's first bytes, so the engines copy it first. Five families in crypto.json with their defaults, aliases and the hybrid namespace's table; aead_checks.hpp reaches its object through an adapter (ruling C35); the libsodium allocation test covers the new families (C34); box_default_not_linked pins the refusals; the guide gains the secret boxes and the hybrid chapter. --- README.md | 6 +- build.jam | 55 +++ doc/changelog.adoc | 8 +- doc/crypto.adoc | 10 +- doc/generated/backends-box.adoc | 30 ++ .../backends-box_xchacha20poly1305.adoc | 30 ++ doc/generated/backends-sealed_box.adoc | 30 ++ doc/generated/backends-secretbox.adoc | 30 ++ .../backends-secretbox_xchacha20poly1305.adoc | 30 ++ doc/generated/default-aliases.adoc | 25 ++ doc/generated/defaults.adoc | 30 ++ doc/generated/jamfiles.adoc | 80 ++++ doc/generated/matrix.adoc | 55 +++ doc/generated/messages.adoc | 14 +- doc/generated/namespace-hybrid.adoc | 48 ++ doc/generated/sizes.adoc | 40 ++ doc/generated/use-cases.adoc | 21 + doc/hybrid.adoc | 96 ++++ doc/llms.txt | 32 +- doc/secretbox.adoc | 42 ++ doc/tables/crypto.json | 168 ++++++- doc/tables/generate.py | 5 +- include/webcpp/crypto.hpp | 15 +- include/webcpp/crypto/backends/sodium.hpp | 321 +++++++++++++ include/webcpp/crypto/ciphers/aead.hpp | 94 +++- include/webcpp/crypto/ciphers/secretbox.hpp | 53 +++ include/webcpp/crypto/detail/capabilities.hpp | 307 +++++++++++++ include/webcpp/crypto/detail/defaults.hpp | 47 ++ include/webcpp/crypto/hybrid/box.hpp | 343 ++++++++++++++ include/webcpp/crypto/hybrid/sealed_box.hpp | 185 ++++++++ test/Jamfile | 31 +- test/allocation_sodium_test.cpp | 93 +++- test/box_sodium_test.cpp | 422 ++++++++++++++++++ test/capabilities_test.cpp | 118 +++++ test/default_backend_test.cpp | 28 ++ test/messages/Jamfile | 1 + .../aead_not_a_family/aead_not_a_family.cpp | 2 +- test/messages/box_default_not_linked/Jamfile | 12 + .../box_default_not_linked.cpp | 39 ++ test/secretbox_sodium_test.cpp | 126 ++++++ test/support/aead_checks.hpp | 381 ++++++++++------ test/support/capabilities.hpp | 13 +- test/windows_h_after_test.cpp | 3 + test/windows_h_before_test.cpp | 3 + 44 files changed, 3330 insertions(+), 192 deletions(-) create mode 100644 doc/generated/backends-box.adoc create mode 100644 doc/generated/backends-box_xchacha20poly1305.adoc create mode 100644 doc/generated/backends-sealed_box.adoc create mode 100644 doc/generated/backends-secretbox.adoc create mode 100644 doc/generated/backends-secretbox_xchacha20poly1305.adoc create mode 100644 doc/generated/namespace-hybrid.adoc create mode 100644 doc/hybrid.adoc create mode 100644 doc/secretbox.adoc create mode 100644 include/webcpp/crypto/ciphers/secretbox.hpp create mode 100644 include/webcpp/crypto/hybrid/box.hpp create mode 100644 include/webcpp/crypto/hybrid/sealed_box.hpp create mode 100644 test/box_sodium_test.cpp create mode 100644 test/messages/box_default_not_linked/Jamfile create mode 100644 test/messages/box_default_not_linked/box_default_not_linked.cpp create mode 100644 test/secretbox_sodium_test.cpp diff --git a/README.md b/README.md index 60acb093..e0326c47 100644 --- a/README.md +++ b/README.md @@ -7,13 +7,17 @@ MSVC), wasip2, wasip3 and Emscripten. - `webcpp::crypto`: a `random_device` that reads the operating system's or the browser's generator, a constant-time `equal` for tags and MACs, and `error`, every failure's value. - `webcpp::crypto::ciphers`: AES-GCM (`gcm`, `aes128_gcm`, `aes256_gcm`) with keys of 16, 24 and - 32 bytes, and the AES block cipher (`aes128`, `aes192`, `aes256`). + 32 bytes, the AES block cipher (`aes128`, `aes192`, `aes256`), the ChaCha20-Poly1305 AEADs, and + NaCl's and libsodium's secret boxes (`secretbox`, `secretbox_xchacha20poly1305`). - `webcpp::crypto::curves::secp256k1`: BIP 340 Schnorr and ECDSA signatures, their verification, ECDH, ECDSA's strict DER and low-S forms, and the x-only tweak. - `webcpp::crypto::curves::ed25519`: Ed25519 signatures (RFC 8032) with strict verification, the X25519 secret key of a key pair, and Ed25519ph over SHA-512 for a message given in pieces. - `webcpp::crypto::curves::x25519`: X25519 key agreement (RFC 7748), refusing an all-zero shared secret, and `curves::ed25519::to_x25519_public` for a peer known by its Ed25519 key. +- `webcpp::crypto::hybrid`: 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. The algorithms are those of widely used, reviewed C libraries, each a backend that a program names in its own Jamfile and that webcpp builds from its sources: BearSSL diff --git a/build.jam b/build.jam index e59eed8e..a6033eb1 100644 --- a/build.jam +++ b/build.jam @@ -133,4 +133,59 @@ rule xchacha20_poly1305-default-linked ( properties * ) } } alias xchacha20_poly1305-default : : : : @xchacha20_poly1305-default-linked ; +rule secretbox_xsalsa20poly1305-default-linked ( properties * ) +{ + switch [ webcpp-target.target-of $(properties) ] + { + case native : return /third_party//sodium ; + case wasip2 : return /third_party//sodium ; + case wasip3 : return /third_party//sodium ; + case emscripten : return /third_party//sodium ; + } +} +alias secretbox_xsalsa20poly1305-default : : : : @secretbox_xsalsa20poly1305-default-linked ; +rule secretbox_xchacha20poly1305-default-linked ( properties * ) +{ + switch [ webcpp-target.target-of $(properties) ] + { + case native : return /third_party//sodium ; + case wasip2 : return /third_party//sodium ; + case wasip3 : return /third_party//sodium ; + case emscripten : return /third_party//sodium ; + } +} +alias secretbox_xchacha20poly1305-default : : : : @secretbox_xchacha20poly1305-default-linked ; +rule box_xsalsa20poly1305-default-linked ( properties * ) +{ + switch [ webcpp-target.target-of $(properties) ] + { + case native : return /third_party//sodium ; + case wasip2 : return /third_party//sodium ; + case wasip3 : return /third_party//sodium ; + case emscripten : return /third_party//sodium ; + } +} +alias box_xsalsa20poly1305-default : : : : @box_xsalsa20poly1305-default-linked ; +rule box_xchacha20poly1305-default-linked ( properties * ) +{ + switch [ webcpp-target.target-of $(properties) ] + { + case native : return /third_party//sodium ; + case wasip2 : return /third_party//sodium ; + case wasip3 : return /third_party//sodium ; + case emscripten : return /third_party//sodium ; + } +} +alias box_xchacha20poly1305-default : : : : @box_xchacha20poly1305-default-linked ; +rule sealed_box-default-linked ( properties * ) +{ + switch [ webcpp-target.target-of $(properties) ] + { + case native : return /third_party//sodium ; + case wasip2 : return /third_party//sodium ; + case wasip3 : return /third_party//sodium ; + case emscripten : return /third_party//sodium ; + } +} +alias sealed_box-default : : : : @sealed_box-default-linked ; # generate.py: end the defaults' aliases diff --git a/doc/changelog.adoc b/doc/changelog.adoc index e4db303b..3ab844ec 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -17,13 +17,13 @@ of every version are on webcpp's index page. // tag::unreleased[] * Added crypto, primitives over C backends: ciphers, curves and randomness, errors of fixed values in webcpp.crypto, every result `+[[nodiscard]]+`, and WEBCPP_CRYPTO_HAS_THREADS, defined natively and with Emscripten's -pthread unless WEBCPP_CRYPTO_NO_THREADS is. -* Added equal, random_device, ciphers::aes128, aes192 and aes256, the AES block cipher, and ciphers::gcm, AES-GCM in place with an incremental seal whose failed open zeroes the data. -* Added default_backend_t and /webcpp/crypto//-default, one default backend per family and target whatever is linked, ciphers::aes128_gcm and aes256_gcm, and refusals naming the Jamfile line and another backend's type. +* Added equal, random_device, ciphers::aes128, aes192 and aes256, the AES block cipher, and ciphers::gcm, aes128_gcm and aes256_gcm: AES-GCM in place, incremental seal, failed opens zeroing data. +* Added supports_v with its family tags, the capability table per target, default_backend_t and /webcpp/crypto//-default, one default per family and target, and refusals naming their Jamfile line. * Added backends::bearssl (AES-GCM alone, allocating nothing), backends::openssl via /webcpp/crypto//openssl natively and on WASI (allocating at make only, or natively in openssl_memory_resource with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE), and backends::ctaes (block cipher alone). * Added curves::secp256k1: key pairs, BIP340 and ECDSA signatures, ECDH, strict DER, low-S and the x-only tweak. * Added curves::ed25519 and curves::x25519 on libsodium: strict verification tabled on twelve edge cases, Ed25519ph over webcpp::hash's sha2_512 (/webcpp/crypto//crypto brings hash), the conversion, and agree refusing all-zero secrets. -* Added backends::sodium on /third_party//sodium, shared with webcpp::hash, every backend's link-time canary and C suite, and ciphers::aead, refusing other families first: chacha20_poly1305 (also BearSSL, OpenSSL), its original form and xchacha20_poly1305. +* Added backends::sodium on /third_party//sodium, shared with webcpp::hash, every backend's link-time canary and C suite, and ciphers::aead: chacha20_poly1305 (also BearSSL, OpenSSL), its original form and xchacha20_poly1305. +* Added ciphers::secretbox and secretbox_xchacha20poly1305, without additional data, and hybrid::box, box_xchacha20poly1305 and sealed_box on libsodium, refusing peer keys of small order. * Added the page: a chapter per namespace and use case, the memory option's guide and example, tables generated from the tests, every Jamfile and message, and llms.txt. -* Added supports_v, the capability table on the target being compiled, and the tags of its families and algorithms, which ciphers::gcm, the AES block cipher and secp256k1's key pair name. * Added secret, a self-wiping array that is copied only by clone, and the errors 13 to 20: memory_functions_refused, memory_functions_not_installed, weak_public_key, invalid_point, invalid_scalar, invalid_padding, invalid_encoding and invalid_ciphertext_size. // end::unreleased[] diff --git a/doc/crypto.adoc b/doc/crypto.adoc index c2e1ddb6..3c1cd154 100644 --- a/doc/crypto.adoc +++ b/doc/crypto.adoc @@ -16,8 +16,8 @@ crypto gives a {cpp}20 program the cryptographic primitives that Boost does not provide, on every target webcpp has: native (Linux, macOS, Windows with MSVC), wasip2, wasip3 and Emscripten. It is one of the libraries of https://github.com/webcpporg/webcpp[webcpp]. The algorithms are those of -widely used, reviewed C libraries, BearSSL, OpenSSL, ctaes and libsecp256k1, each a backend -that the program names in its own Jamfile. +widely used, reviewed C libraries, BearSSL, OpenSSL, ctaes, libsecp256k1 and +libsodium, each a backend that the program names in its own Jamfile. The page is written for two readers at once: a developer who knows little cryptography, and a language model that must pick the right tool for a @@ -48,6 +48,8 @@ include::aead.adoc[] include::chacha.adoc[] +include::secretbox.adoc[] + include::block.adoc[] include::curves.adoc[] @@ -58,6 +60,8 @@ include::ed25519.adoc[] include::x25519.adoc[] +include::hybrid.adoc[] + include::backends.adoc[] include::wallets.adoc[] @@ -74,7 +78,7 @@ include::testing.adoc[] == Reference Every name crypto declares, in the namespaces `webcpp::crypto`, `backends`, -`ciphers` and `curves::secp256k1`, from the Doc Comments of its headers: each +`ciphers`, `curves` and `hybrid`, from the Doc Comments of its headers: each class, function, type and enumerator with its declaration, what it does, what it asks of its caller and how it fails. The other sections teach the library; this one is where a name is looked up. diff --git a/doc/generated/backends-box.adoc b/doc/generated/backends-box.adoc new file mode 100644 index 00000000..1084cf66 --- /dev/null +++ b/doc/generated/backends-box.adoc @@ -0,0 +1,30 @@ +// 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 `+hybrid::box+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|libsodium +|`+/third_party//sodium+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+box_sodium+`, `+allocation_sodium+`) +|=== + +`+box+` names the default backend. The default per target, whatever the program links, as <> gives it with its reasons and tests: + +[cols="1,1",options="header"] +|=== +|Target |Default + +|native, wasip2, wasip3, emscripten +|libsodium +|=== diff --git a/doc/generated/backends-box_xchacha20poly1305.adoc b/doc/generated/backends-box_xchacha20poly1305.adoc new file mode 100644 index 00000000..e5fb2085 --- /dev/null +++ b/doc/generated/backends-box_xchacha20poly1305.adoc @@ -0,0 +1,30 @@ +// 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 `+hybrid::box_xchacha20poly1305+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|libsodium +|`+/third_party//sodium+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+box_sodium+`, `+allocation_sodium+`) +|=== + +`+box_xchacha20poly1305+` names the default backend. The default per target, whatever the program links, as <> gives it with its reasons and tests: + +[cols="1,1",options="header"] +|=== +|Target |Default + +|native, wasip2, wasip3, emscripten +|libsodium +|=== diff --git a/doc/generated/backends-sealed_box.adoc b/doc/generated/backends-sealed_box.adoc new file mode 100644 index 00000000..9bd50659 --- /dev/null +++ b/doc/generated/backends-sealed_box.adoc @@ -0,0 +1,30 @@ +// 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 `+hybrid::sealed_box+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|libsodium +|`+/third_party//sodium+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+box_sodium+`, `+allocation_sodium+`) +|=== + +`+sealed_box+` names the default backend. The default per target, whatever the program links, as <> gives it with its reasons and tests: + +[cols="1,1",options="header"] +|=== +|Target |Default + +|native, wasip2, wasip3, emscripten +|libsodium +|=== diff --git a/doc/generated/backends-secretbox.adoc b/doc/generated/backends-secretbox.adoc new file mode 100644 index 00000000..8a1dc1aa --- /dev/null +++ b/doc/generated/backends-secretbox.adoc @@ -0,0 +1,30 @@ +// 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 `+ciphers::secretbox+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|libsodium +|`+/third_party//sodium+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+secretbox_sodium+`, `+box_sodium+`, `+allocation_sodium+`) +|=== + +`+secretbox<>+` names the default backend. The default per target, whatever the program links, as <> gives it with its reasons and tests: + +[cols="1,1",options="header"] +|=== +|Target |Default + +|native, wasip2, wasip3, emscripten +|libsodium +|=== diff --git a/doc/generated/backends-secretbox_xchacha20poly1305.adoc b/doc/generated/backends-secretbox_xchacha20poly1305.adoc new file mode 100644 index 00000000..3b5cc94c --- /dev/null +++ b/doc/generated/backends-secretbox_xchacha20poly1305.adoc @@ -0,0 +1,30 @@ +// 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 `+ciphers::secretbox_xchacha20poly1305+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|libsodium +|`+/third_party//sodium+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+secretbox_sodium+`, `+box_sodium+`, `+allocation_sodium+`) +|=== + +`+secretbox_xchacha20poly1305<>+` names the default backend. The default per target, whatever the program links, as <> gives it with its reasons and tests: + +[cols="1,1",options="header"] +|=== +|Target |Default + +|native, wasip2, wasip3, emscripten +|libsodium +|=== diff --git a/doc/generated/default-aliases.adoc b/doc/generated/default-aliases.adoc index 461204df..2cb3f2f3 100644 --- a/doc/generated/default-aliases.adoc +++ b/doc/generated/default-aliases.adoc @@ -45,4 +45,29 @@ |XChaCha20-Poly1305 |`+/third_party//sodium+` on every target |<> + +|`+/webcpp/crypto//secretbox_xsalsa20poly1305-default+` +|XSalsa20-Poly1305 secret box +|`+/third_party//sodium+` on every target +|<> + +|`+/webcpp/crypto//secretbox_xchacha20poly1305-default+` +|XChaCha20-Poly1305 secret box +|`+/third_party//sodium+` on every target +|<> + +|`+/webcpp/crypto//box_xsalsa20poly1305-default+` +|X25519-XSalsa20-Poly1305 box +|`+/third_party//sodium+` on every target +|<> + +|`+/webcpp/crypto//box_xchacha20poly1305-default+` +|X25519-XChaCha20-Poly1305 box +|`+/third_party//sodium+` on every target +|<> + +|`+/webcpp/crypto//sealed_box-default+` +|X25519-XSalsa20-Poly1305 sealed box +|`+/third_party//sodium+` on every target +|<> |=== diff --git a/doc/generated/defaults.adoc b/doc/generated/defaults.adoc index cbca4b47..4db7b27c 100644 --- a/doc/generated/defaults.adoc +++ b/doc/generated/defaults.adoc @@ -76,4 +76,34 @@ |libsodium |the only backend that has it: libsodium's own C code, the same on every target (link:https://doc.libsodium.org/secret-key_cryptography/aead/chacha20-poly1305[libsodium's ChaCha20-Poly1305 constructions]) |`+xchacha_sodium+`, `+default_backend_none_linked+` + +|XSalsa20-Poly1305 secret box +|native, wasip2, wasip3, emscripten +|libsodium +|the only backend that has it: libsodium's own C code, NaCl's `crypto_secretbox`, the same on every target (link:https://doc.libsodium.org/secret-key_cryptography/secretbox[libsodium's documentation, secret-key authenticated encryption]) +|`+secretbox_sodium+`, `+default_backend_none_linked+` + +|XChaCha20-Poly1305 secret box +|native, wasip2, wasip3, emscripten +|libsodium +|the only backend that has it: libsodium's own C code, the same on every target (link:https://doc.libsodium.org/secret-key_cryptography/secretbox[libsodium's documentation, secret-key authenticated encryption]) +|`+secretbox_sodium+`, `+default_backend_none_linked+` + +|X25519-XSalsa20-Poly1305 box +|native, wasip2, wasip3, emscripten +|libsodium +|the only backend that has it: libsodium's own C code, NaCl's `crypto_box`, the same on every target (link:https://doc.libsodium.org/public-key_cryptography/authenticated_encryption[libsodium's documentation, public-key authenticated encryption]) +|`+box_sodium+`, `+default_backend_none_linked+` + +|X25519-XChaCha20-Poly1305 box +|native, wasip2, wasip3, emscripten +|libsodium +|the only backend that has it: libsodium's own C code, the same on every target (link:https://doc.libsodium.org/public-key_cryptography/authenticated_encryption[libsodium's documentation, public-key authenticated encryption]) +|`+box_sodium+`, `+default_backend_none_linked+` + +|X25519-XSalsa20-Poly1305 sealed box +|native, wasip2, wasip3, emscripten +|libsodium +|the only backend that has it: libsodium's own C code, which draws the key pair of each message from its own generator, the same on every target (link:https://doc.libsodium.org/public-key_cryptography/sealed_boxes[libsodium's documentation, sealed boxes]) +|`+box_sodium+`, `+default_backend_none_linked+` |=== diff --git a/doc/generated/jamfiles.adoc b/doc/generated/jamfiles.adoc index 348a72ce..2d738bc2 100644 --- a/doc/generated/jamfiles.adoc +++ b/doc/generated/jamfiles.adoc @@ -39,6 +39,38 @@ It prints: include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/both_bearssl_named/both_bearssl_named.outcome[tag=output] ---- +`+box_xchacha20poly1305_default+`:: Alice and Bob's keys in the XChaCha20 box, sealed by Alice and opened by Bob on its default on every target, with the one line `+/webcpp/crypto//box_xchacha20poly1305-default+`, which links libsodium. ++ +Its Jamfile, built and run on native, wasip2, wasip3, emscripten: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/box_xchacha20poly1305_default/Jamfile[tag=jamfile] +---- ++ +It prints: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/box_xchacha20poly1305_default/box_xchacha20poly1305_default.outcome[tag=output] +---- + +`+box_xsalsa20poly1305_default+`:: NaCl's box from Alice to Bob, sealed and opened by Bob on its default on every target, with the one line `+/webcpp/crypto//box_xsalsa20poly1305-default+`, which links libsodium. ++ +Its Jamfile, built and run on native, wasip2, wasip3, emscripten: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/box_xsalsa20poly1305_default/Jamfile[tag=jamfile] +---- ++ +It prints: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/box_xsalsa20poly1305_default/box_xsalsa20poly1305_default.outcome[tag=output] +---- + `+chacha20_poly1305_default+`:: RFC 8439's ChaCha20-Poly1305 example, sealed and opened on its default on every target, with the one line `+/webcpp/crypto//chacha20_poly1305-default+`, which links libsodium. + Its Jamfile, built and run on native, wasip2, wasip3, emscripten: @@ -151,6 +183,22 @@ It prints: include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/openssl_linked/openssl_linked.outcome[tag=output] ---- +`+sealed_box_default+`:: A message sealed to Bob's public key and opened with his key pair on the default on every target, with the one line `+/webcpp/crypto//sealed_box-default+`, which links libsodium. ++ +Its Jamfile, built and run on native, wasip2, wasip3, emscripten: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/sealed_box_default/Jamfile[tag=jamfile] +---- ++ +It prints: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/sealed_box_default/sealed_box_default.outcome[tag=output] +---- + `+secp256k1_default+`:: BIP 340's first test vector, signed and verified on secp256k1's default on every target, with the one line `+/webcpp/crypto//secp256k1-default+`, which links libsecp256k1. + Its Jamfile, built and run on native, wasip2, wasip3, emscripten: @@ -167,6 +215,38 @@ It prints: include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/secp256k1_default/secp256k1_default.outcome[tag=output] ---- +`+secretbox_xchacha20poly1305_default+`:: A case of libsodium's XChaCha20 secret boxes, sealed and opened on its default on every target, with the one line `+/webcpp/crypto//secretbox_xchacha20poly1305-default+`, which links libsodium. ++ +Its Jamfile, built and run on native, wasip2, wasip3, emscripten: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/secretbox_xchacha20poly1305_default/Jamfile[tag=jamfile] +---- ++ +It prints: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/secretbox_xchacha20poly1305_default/secretbox_xchacha20poly1305_default.outcome[tag=output] +---- + +`+secretbox_xsalsa20poly1305_default+`:: NaCl's secret box, sealed and opened on its default on every target, with the one line `+/webcpp/crypto//secretbox_xsalsa20poly1305-default+`, which links libsodium. ++ +Its Jamfile, built and run on native, wasip2, wasip3, emscripten: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/secretbox_xsalsa20poly1305_default/Jamfile[tag=jamfile] +---- ++ +It prints: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/secretbox_xsalsa20poly1305_default/secretbox_xsalsa20poly1305_default.outcome[tag=output] +---- + `+server+`:: A server, natively: the same program with OpenSSL, the default natively. + Its Jamfile, built and run on native: diff --git a/doc/generated/matrix.adoc b/doc/generated/matrix.adoc index 202f0f50..4a4da635 100644 --- a/doc/generated/matrix.adoc +++ b/doc/generated/matrix.adoc @@ -145,6 +145,31 @@ |libsodium |native, wasip2, wasip3, emscripten |`+xchacha_sodium+`, `+chacha_wycheproof_sodium+`, `+allocation_sodium+` + +|`+ciphers::secretbox+` +|libsodium +|native, wasip2, wasip3, emscripten +|`+secretbox_sodium+`, `+box_sodium+`, `+allocation_sodium+` + +|`+ciphers::secretbox_xchacha20poly1305+` +|libsodium +|native, wasip2, wasip3, emscripten +|`+secretbox_sodium+`, `+box_sodium+`, `+allocation_sodium+` + +|`+hybrid::box+` +|libsodium +|native, wasip2, wasip3, emscripten +|`+box_sodium+`, `+allocation_sodium+` + +|`+hybrid::box_xchacha20poly1305+` +|libsodium +|native, wasip2, wasip3, emscripten +|`+box_sodium+`, `+allocation_sodium+` + +|`+hybrid::sealed_box+` +|libsodium +|native, wasip2, wasip3, emscripten +|`+box_sodium+`, `+allocation_sodium+` |=== The same, by target: the backends each operation runs on. @@ -266,4 +291,34 @@ The same, by target: the backends each operation runs on. |libsodium |libsodium |libsodium + +|`+ciphers::secretbox+` +|libsodium +|libsodium +|libsodium +|libsodium + +|`+ciphers::secretbox_xchacha20poly1305+` +|libsodium +|libsodium +|libsodium +|libsodium + +|`+hybrid::box+` +|libsodium +|libsodium +|libsodium +|libsodium + +|`+hybrid::box_xchacha20poly1305+` +|libsodium +|libsodium +|libsodium +|libsodium + +|`+hybrid::sealed_box+` +|libsodium +|libsodium +|libsodium +|libsodium |=== diff --git a/doc/generated/messages.adoc b/doc/generated/messages.adoc index 1887b5c2..aaad0421 100644 --- a/doc/generated/messages.adoc +++ b/doc/generated/messages.adoc @@ -15,9 +15,9 @@ At compile time, checked word for word by the message tests of `test/messages` w |`+aead_not_a_family+` |native, wasip2, wasip3 -|`+webcpp::crypto: ciphers::aead takes an AEAD family: families::chacha20_poly1305, families::chacha20_poly1305_original or families::xchacha20_poly1305.+` +|`+webcpp::crypto: ciphers::aead takes an AEAD family: families::chacha20_poly1305, families::chacha20_poly1305_original, families::xchacha20_poly1305, families::secretbox_xsalsa20poly1305 or families::secretbox_xchacha20poly1305.+` -The fix: Name one of the three ChaCha20-Poly1305 families; AES-GCM is `+ciphers::gcm+`, as in `+aes256_gcm+`. +The fix: Name one of the three ChaCha20-Poly1305 families or the two secret boxes'; AES-GCM is `+ciphers::gcm+`, as in `+aes256_gcm+`. |`+aes_on_bearssl+` |native, wasip2 @@ -31,6 +31,12 @@ The fix: Name `+ciphers::aes256+`, include `+> +|Encrypt a record or a file under one secret key, each with a random nonce, in libsodium's secret-box format +|In `+ciphers+`: `+secretbox<>+`, `+secretbox_xchacha20poly1305<>+`: `+make+`, `+seal+`, `+open+` +|libsodium +|`+/webcpp/crypto//crypto+` + +`+/webcpp/crypto//secretbox_xsalsa20poly1305-default+` +|<> + +|Send messages between two people who know each other's public keys, as NaCl's and libsodium's crypto_box +|In `+hybrid+`: `+box::make+`, `+box::seal+`, `+box::open+` +|libsodium +|`+/webcpp/crypto//crypto+` + +`+/webcpp/crypto//box_xsalsa20poly1305-default+` +|<> + +|Let anyone send a message that only the recipient can read, without saying who sent it (anonymous feedback, a drop box) +|In `+hybrid+`: `+sealed_box::seal+`, `+sealed_box::open+` +|libsodium +|`+/webcpp/crypto//crypto+` + +`+/webcpp/crypto//sealed_box-default+` +|<> + |Use P-256 (passkeys, JWT's ES256) |None in this version: secp256k1, Ed25519 and X25519 keys and signatures do not interoperate with this curve |none diff --git a/doc/hybrid.adoc b/doc/hybrid.adoc new file mode 100644 index 00000000..b4d558d8 --- /dev/null +++ b/doc/hybrid.adoc @@ -0,0 +1,96 @@ +// 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) + +[#crypto-hybrid] +== Hybrid encryption: `webcpp::crypto::hybrid` + +*Hybrid encryption* joins a key agreement and a cipher: the agreement, on +public keys, gives a secret key, and a fast cipher encrypts the data under it +(link:https://en.wikipedia.org/wiki/Hybrid_cryptosystem[Wikipedia]). A chat app +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::hybrid` 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. + +include::generated/namespace-hybrid.adoc[] + +[#crypto-box] +=== Boxes + +`hybrid::box`, in ``, is NaCl's `crypto_box` +(link:https://nacl.cr.yp.to/box.html[NaCl]; +link:https://doc.libsodium.org/public-key_cryptography/authenticated_encryption[libsodium's documentation]). +`box::make(secret_key, peer_public_key)` agrees a key from the own X25519 +secret key and the peer's public key, once for the pair (libsodium's +`beforenm`); the box then works in place, as an AEAD without additional data: +`seal(iv_bytes, data_bytes)` encrypts and returns the 16-byte tag, and +`open(iv_bytes, data_bytes, tag_bytes)` checks it and decrypts, zeroing the +data when it does not match. Alice's box made from her secret key and Bob's +public key, and Bob's made from his secret key and Alice's public key, hold +the same key: what one seals the other opens. `box_xchacha20poly1305` is +libsodium's `crypto_box_curve25519xchacha20poly1305`, the same with +XChaCha20-Poly1305. A box is moved and not copied, and wipes its key when +moved from and destroyed. + +A peer's public key of small order makes the shared secret one an attacker +knows: `make` refuses it with `weak_public_key`, as libsodium's `beforenm` +does. + +include::generated/backends-box.adoc[] + +include::generated/backends-box_xchacha20poly1305.adoc[] + +[cols="3,1"] +|=== +|Condition |Error + +|`make`: a secret key of another size than 32 bytes |`invalid_key_size` +|`make`: a peer key of another size than 32 bytes |`invalid_public_key` +|`make`: a peer key of small order |`weak_public_key` +|`seal`, `open`: the object was moved from |`invalid_state` +|a nonce of another size than 24 bytes |`invalid_iv_size` +|`open`: a tag of another size than 16 |`invalid_tag_size` +|a message longer than `max_message_size` |`message_too_long` +|`open`: the tag does not match |`authentication_failed` +|the backend fails where it should not |`backend_failure` +|=== + +*Pitfalls.* + +* A box proves that one of the two key pairs wrote a message, not which one: +a protocol that needs to know says so inside the message, or signs it. +* A nonce is never repeated for one pair of keys, in either direction: draw +24 bytes at random for every message. + +[#crypto-sealed-box] +=== Sealed boxes + +`hybrid::sealed_box`, in ``, is +libsodium's sealed box, `crypto_box_seal` +(link:https://doc.libsodium.org/public-key_cryptography/sealed_boxes[libsodium's documentation]): +anyone who knows a public key can seal a message to it, and only the key pair +opens it. `seal(recipient_public_key, message, out)` writes to `out`, of the +message's size plus `overhead`, 48 bytes, a key pair libsodium draws for the +message, its public key, the tag and the ciphertext, and wipes the drawn +secret key; the nonce comes from the two public keys. `open(recipient_public_key, +recipient_secret_key, sealed, out)` writes the message to `out`, of the sealed +box's size less 48 bytes, and zeroes `out` when the box does not open: sealed to +another key pair, or changed. The sizes are checked first +(`invalid_input_size`), then the keys (`invalid_public_key`, +`invalid_key_size`). + +include::generated/backends-sealed_box.adoc[] + +*Pitfalls.* + +* A sealed box is anonymous: the recipient cannot tell who sealed it, nor +whether an attacker did. Where the sender matters, use a box or a signature. +* The sender cannot open what it sealed: it keeps its own copy of the +message if it needs one. diff --git a/doc/llms.txt b/doc/llms.txt index f4840530..22a76770 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -1,6 +1,6 @@ # webcpp::crypto -> Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA, ECDH, the x-only tweak), Ed25519 and Ed25519ph (RFC 8032), X25519 (RFC 7748), a random_device on the system's generator and a constant-time equal, each over a widely used, reviewed C library (BearSSL, OpenSSL, ctaes, libsecp256k1, libsodium) that the program names in its Jamfile. Hashing and HMAC are Boost.Hash2's. Every failure is a boost::system::result value. Protocols (Bitcoin, Ethereum, Nostr) belong to domain libraries built on these primitives. +> Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA, ECDH, the x-only tweak), Ed25519 and Ed25519ph (RFC 8032), X25519 (RFC 7748), the ChaCha20-Poly1305 AEADs, libsodium's secret boxes, boxes and sealed boxes, a random_device on the system's generator and a constant-time equal, each over a widely used, reviewed C library (BearSSL, OpenSSL, ctaes, libsecp256k1, libsodium) that the program names in its Jamfile. Hashing and HMAC are Boost.Hash2's. Every failure is a boost::system::result value. Protocols (Bitcoin, Ethereum, Nostr) belong to domain libraries built on these primitives. Generated by doc/tables/generate.py with the page's tables. Page: https://webcpporg.github.io/libs/crypto/ @@ -47,6 +47,14 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - make: Makes an object under a key. - seal: Seals a message in place: `data_bytes` holds the plaintext before and the ciphertext after. - open: Opens a message in place: `data_bytes` holds the ciphertext before and the plaintext after. +- [ciphers::secretbox](https://webcpporg.github.io/libs/crypto/#crypto-secretbox): NaCl's and libsodium's `crypto_secretbox`, XSalsa20-Poly1305: authenticated encryption in place under a 32-byte key, with a 24-byte nonce safe to draw at random and no additional data. Header , . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. + - make: Makes an object under a key. + - seal: Seals a message in place: `data_bytes` holds the plaintext before and the ciphertext after. + - open: Opens a message in place: `data_bytes` holds the ciphertext before and the plaintext after. +- [ciphers::secretbox_xchacha20poly1305](https://webcpporg.github.io/libs/crypto/#crypto-secretbox): libsodium's `crypto_secretbox_xchacha20poly1305`: the secret box with XChaCha20 in place of XSalsa20. Header , . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. + - make: Makes an object under a key. + - seal: Seals a message in place: `data_bytes` holds the plaintext before and the ciphertext after. + - open: Opens a message in place: `data_bytes` holds the ciphertext before and the plaintext after. ## webcpp::crypto::curves @@ -87,6 +95,20 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [curves::x25519::agree](https://webcpporg.github.io/libs/crypto/#crypto-x25519): The 32-byte shared secret of a secret key and a peer's public key, a `secret<32>`, refused with `weak_public_key` when it is all zero (a peer key of low order). Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. - agree: The shared secret, refused when all zero: `algorithm::agree`. +## webcpp::crypto::hybrid + +- [hybrid::box](https://webcpporg.github.io/libs/crypto/#crypto-box): NaCl's and libsodium's `crypto_box`: X25519 agrees a key once per pair of keys, refusing a peer key of small order, then XSalsa20-Poly1305 seals and opens each message in place, with a 24-byte nonce safe to draw at random. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. + - make: Agrees the box's key from the own secret key and the peer's public key. + - seal: Seals a message in place: `data_bytes` holds the plaintext before and the ciphertext after. + - open: Opens a message in place: `data_bytes` holds the ciphertext before and the plaintext after. +- [hybrid::box_xchacha20poly1305](https://webcpporg.github.io/libs/crypto/#crypto-box): libsodium's `crypto_box_curve25519xchacha20poly1305`: the box with XChaCha20 in place of XSalsa20. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. + - make: Agrees the box's key from the own secret key and the peer's public key. + - seal: Seals a message in place: `data_bytes` holds the plaintext before and the ciphertext after. + - open: Opens a message in place: `data_bytes` holds the ciphertext before and the plaintext after. +- [hybrid::sealed_box](https://webcpporg.github.io/libs/crypto/#crypto-sealed-box): libsodium's sealed boxes, `crypto_box_seal`: anonymous encryption to a public key under a key pair drawn per message, 48 bytes longer than the message, which only the recipient's key pair opens. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. + - seal: Seals `message` into `out`, of `message.size() + overhead` bytes: the drawn public key, the tag, then the ciphertext. + - open: Opens `sealed` into `out`, of `sealed.size() - overhead` bytes, with the recipient's keys. + ## Default backend per family - AES-GCM, native, Clang and GCC: OpenSSL; OpenSSL's assembly uses the CPU's AES and carry-less multiplication instructions on x86-64 and ARMv8 ([OpenSSL's AES assembly for ARMv8 and x86-64](https://github.com/openssl/openssl/tree/master/crypto/aes/asm); [OpenSSL's GHASH and AES-GCM assembly](https://github.com/openssl/openssl/tree/master/crypto/modes/asm)); BearSSL has them on x86 only ([BearSSL, the AES implementations it selects](https://www.bearssl.org/support.html)). OpenSSL whatever the program links: a program that links BearSSL alone names `gcm>`. @@ -100,6 +122,11 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - ChaCha20-Poly1305, native, wasip2, wasip3, emscripten: libsodium; one library for the three ChaCha20-Poly1305 AEADs on every target, where BearSSL and OpenSSL have RFC 8439's alone ([libsodium's ChaCha20-Poly1305 constructions](https://doc.libsodium.org/secret-key_cryptography/aead/chacha20-poly1305)); a program that links BearSSL or OpenSSL alone names it in the type, as in `chacha20_poly1305`. - original ChaCha20-Poly1305, native, wasip2, wasip3, emscripten: libsodium; the only backend that has it: libsodium's own C code, the same on every target ([libsodium's ChaCha20-Poly1305 constructions](https://doc.libsodium.org/secret-key_cryptography/aead/chacha20-poly1305)). - XChaCha20-Poly1305, native, wasip2, wasip3, emscripten: libsodium; the only backend that has it: libsodium's own C code, the same on every target ([libsodium's ChaCha20-Poly1305 constructions](https://doc.libsodium.org/secret-key_cryptography/aead/chacha20-poly1305)). +- XSalsa20-Poly1305 secret box, native, wasip2, wasip3, emscripten: libsodium; the only backend that has it: libsodium's own C code, NaCl's `crypto_secretbox`, the same on every target ([libsodium's documentation, secret-key authenticated encryption](https://doc.libsodium.org/secret-key_cryptography/secretbox)). +- XChaCha20-Poly1305 secret box, native, wasip2, wasip3, emscripten: libsodium; the only backend that has it: libsodium's own C code, the same on every target ([libsodium's documentation, secret-key authenticated encryption](https://doc.libsodium.org/secret-key_cryptography/secretbox)). +- X25519-XSalsa20-Poly1305 box, native, wasip2, wasip3, emscripten: libsodium; the only backend that has it: libsodium's own C code, NaCl's `crypto_box`, the same on every target ([libsodium's documentation, public-key authenticated encryption](https://doc.libsodium.org/public-key_cryptography/authenticated_encryption)). +- X25519-XChaCha20-Poly1305 box, native, wasip2, wasip3, emscripten: libsodium; the only backend that has it: libsodium's own C code, the same on every target ([libsodium's documentation, public-key authenticated encryption](https://doc.libsodium.org/public-key_cryptography/authenticated_encryption)). +- X25519-XSalsa20-Poly1305 sealed box, native, wasip2, wasip3, emscripten: libsodium; the only backend that has it: libsodium's own C code, which draws the key pair of each message from its own generator, the same on every target ([libsodium's documentation, sealed boxes](https://doc.libsodium.org/public-key_cryptography/sealed_boxes)). ## Rules of use @@ -135,6 +162,9 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [Hash, or compute an HMAC](https://webcpporg.github.io/libs/crypto/#crypto-overview-hash2): `boost::hash2::sha2_256`, `hmac_sha2_256` (Boost.Hash2, not this library); backend none; Jamfile `/webcpp/crypto//crypto` brings Boost's headers. Example: example/equal_hmac.cpp. - [Sign and verify with Ed25519 (RFC 8032), or sign a large message in pieces with Ed25519ph](https://webcpporg.github.io/libs/crypto/#crypto-ed25519): `keypair::make`, `keypair::generate`, `keypair::sign`, `verify`; `ph` (webcpp::crypto::curves::ed25519); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//ed25519-default. Example: example/ed25519_sign.cpp. - [Agree a shared secret with a peer's public key (X25519, RFC 7748), or with the X25519 form of an Ed25519 key](https://webcpporg.github.io/libs/crypto/#crypto-x25519): `public_key`, `agree`; `curves::ed25519::to_x25519_public`, `curves::ed25519::keypair::x25519_secret` (webcpp::crypto::curves::x25519); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//x25519-default. Example: example/x25519_agree.cpp. +- [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<>`: `make`, `seal`, `open` (webcpp::crypto::ciphers); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//secretbox_xsalsa20poly1305-default. +- [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::make`, `box::seal`, `box::open` (webcpp::crypto::hybrid); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//box_xsalsa20poly1305-default. +- [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::hybrid); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//sealed_box-default. - [Use P-256 (passkeys, JWT's ES256)](https://webcpporg.github.io/libs/crypto/#crypto-curves): secp256k1, Ed25519 and X25519 keys and signatures do not interoperate with this curve (none in this version); backend none; Jamfile none. ## Examples diff --git a/doc/secretbox.adoc b/doc/secretbox.adoc new file mode 100644 index 00000000..35270203 --- /dev/null +++ b/doc/secretbox.adoc @@ -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) + +[#crypto-secretbox] +=== Secret boxes + +A *secret box* is NaCl's name for authenticated encryption under one secret +key, with no additional data: the box hides the message and its tag proves it +unchanged (link:https://nacl.cr.yp.to/secretbox.html[NaCl]; +link:https://doc.libsodium.org/secret-key_cryptography/secretbox[libsodium's documentation]). +Its cipher is XSalsa20, Salsa20 with a 24-byte nonce +(link:https://cr.yp.to/snuffle/xsalsa-20081128.pdf[Extending the Salsa20 nonce]), +and its authenticator Poly1305. A program that stores records or files under +one key, each with a nonce drawn at random, and a program that must read +what libsodium's `crypto_secretbox` wrote, use it. + +`ciphers::secretbox<>` and `ciphers::secretbox_xchacha20poly1305<>`, in +``, are `ciphers::aead` over libsodium's +`crypto_secretbox` and its XChaCha20 twin, `crypto_secretbox_xchacha20poly1305`, +on libsodium, their default on every target: a 32-byte key, a 24-byte nonce +safe to draw at random from `random_device` for every message, a 16-byte tag. +They are made and used as the ChaCha20-Poly1305 AEADs are (<>), +with one difference: a secret box has no additional data, so their +`max_additional_data_size` is 0 and `seal` and `open` refuse a non-empty one +with `invalid_input_size`, after the nonce and the tag are checked and before +the length. The nonce may lie in the data: libsodium reads it again after it +writes the first bytes of the ciphertext, so it is copied first. + +include::generated/backends-secretbox.adoc[] + +include::generated/backends-secretbox_xchacha20poly1305.adoc[] + +*Pitfalls.* + +* The secret box's tag covers the ciphertext alone: a field that travels in +clear and must not change, a record's id for instance, belongs in an AEAD's +additional data (<>), not beside a secret box. +* A nonce is never repeated under one key: draw 24 bytes at random for every +message, which never collide in practice. diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 8de67846..2e1dcfc0 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -77,7 +77,13 @@ "tor-cert-spec": ["Tor's specifications, Ed25519 certificates", "https://spec.torproject.org/cert-spec.html"], "solana-accounts": ["Solana's documentation, accounts and their Ed25519 keys", "https://solana.com/docs/core/accounts"], "rfc8439": ["RFC 8439, ChaCha20 and Poly1305 for IETF Protocols", "https://www.rfc-editor.org/rfc/rfc8439"], - "libsodium-aead": ["libsodium's ChaCha20-Poly1305 constructions", "https://doc.libsodium.org/secret-key_cryptography/aead/chacha20-poly1305"] + "libsodium-aead": ["libsodium's ChaCha20-Poly1305 constructions", "https://doc.libsodium.org/secret-key_cryptography/aead/chacha20-poly1305"], + "nacl-box": ["NaCl, public-key authenticated encryption (crypto_box)", "https://nacl.cr.yp.to/box.html"], + "nacl-secretbox": ["NaCl, secret-key authenticated encryption (crypto_secretbox)", "https://nacl.cr.yp.to/secretbox.html"], + "xsalsa20": ["D. J. Bernstein, Extending the Salsa20 nonce, 2008", "https://cr.yp.to/snuffle/xsalsa-20081128.pdf"], + "libsodium-secretbox": ["libsodium's documentation, secret-key authenticated encryption", "https://doc.libsodium.org/secret-key_cryptography/secretbox"], + "libsodium-box": ["libsodium's documentation, public-key authenticated encryption", "https://doc.libsodium.org/public-key_cryptography/authenticated_encryption"], + "libsodium-sealed": ["libsodium's documentation, sealed boxes", "https://doc.libsodium.org/public-key_cryptography/sealed_boxes"] }, "backends": { "bearssl": { @@ -402,6 +408,66 @@ "section": "crypto-chacha", "default": "`xchacha20_poly1305<>` names the default backend.", "backends": {"sodium": {"tests": ["xchacha_sodium", "chacha_wycheproof_sodium", "allocation_sodium"]}} + }, + { + "id": "secretbox", + "family": "secretbox_xsalsa20poly1305", + "functions": ["make", "seal", "open"], + "namespace": "ciphers", + "api": "ciphers::secretbox", + "header": ", ", + "what": "NaCl's and libsodium's `crypto_secretbox`, XSalsa20-Poly1305: authenticated encryption in place under a 32-byte key, with a 24-byte nonce safe to draw at random and no additional data.", + "section": "crypto-secretbox", + "default": "`secretbox<>` names the default backend.", + "backends": {"sodium": {"tests": ["secretbox_sodium", "box_sodium", "allocation_sodium"]}} + }, + { + "id": "secretbox_xchacha20poly1305", + "family": "secretbox_xchacha20poly1305", + "functions": ["make", "seal", "open"], + "namespace": "ciphers", + "api": "ciphers::secretbox_xchacha20poly1305", + "header": ", ", + "what": "libsodium's `crypto_secretbox_xchacha20poly1305`: the secret box with XChaCha20 in place of XSalsa20.", + "section": "crypto-secretbox", + "default": "`secretbox_xchacha20poly1305<>` names the default backend.", + "backends": {"sodium": {"tests": ["secretbox_sodium", "box_sodium", "allocation_sodium"]}} + }, + { + "id": "box", + "family": "box_xsalsa20poly1305", + "functions": ["make", "seal", "open"], + "namespace": "hybrid", + "api": "hybrid::box", + "header": "", + "what": "NaCl's and libsodium's `crypto_box`: X25519 agrees a key once per pair of keys, refusing a peer key of small order, then XSalsa20-Poly1305 seals and opens each message in place, with a 24-byte nonce safe to draw at random.", + "section": "crypto-box", + "default": "`box` names the default backend.", + "backends": {"sodium": {"tests": ["box_sodium", "allocation_sodium"]}} + }, + { + "id": "box_xchacha20poly1305", + "family": "box_xchacha20poly1305", + "functions": ["make", "seal", "open"], + "namespace": "hybrid", + "api": "hybrid::box_xchacha20poly1305", + "header": "", + "what": "libsodium's `crypto_box_curve25519xchacha20poly1305`: the box with XChaCha20 in place of XSalsa20.", + "section": "crypto-box", + "default": "`box_xchacha20poly1305` names the default backend.", + "backends": {"sodium": {"tests": ["box_sodium", "allocation_sodium"]}} + }, + { + "id": "sealed_box", + "family": "sealed_box", + "functions": ["seal", "open"], + "namespace": "hybrid", + "api": "hybrid::sealed_box", + "header": "", + "what": "libsodium's sealed boxes, `crypto_box_seal`: anonymous encryption to a public key under a key pair drawn per message, 48 bytes longer than the message, which only the recipient's key pair opens.", + "section": "crypto-sealed-box", + "default": "`sealed_box` names the default backend.", + "backends": {"sodium": {"tests": ["box_sodium", "allocation_sodium"]}} } ], "families": [ @@ -548,6 +614,86 @@ "backends": { "sodium": {"targets": "all"} } + }, + { + "name": "secretbox_xsalsa20poly1305", + "title": "XSalsa20-Poly1305 secret box", + "group": "ciphers", + "since": "0.2", + "header": "", + "names": [ + {"name": "secretbox_xsalsa20poly1305", "title": "XSalsa20-Poly1305 secret box", "type": "ciphers::secretbox<{backend}>"} + ], + "default": [ + {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": ["secretbox_sodium", "default_backend_none_linked"], "why": "the only backend that has it: libsodium's own C code, NaCl's `crypto_secretbox`, the same on every target ({libsodium-secretbox})"} + ], + "backends": { + "sodium": {"targets": "all"} + } + }, + { + "name": "secretbox_xchacha20poly1305", + "title": "XChaCha20-Poly1305 secret box", + "group": "ciphers", + "since": "0.2", + "header": "", + "names": [ + {"name": "secretbox_xchacha20poly1305", "title": "XChaCha20-Poly1305 secret box", "type": "ciphers::secretbox_xchacha20poly1305<{backend}>"} + ], + "default": [ + {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": ["secretbox_sodium", "default_backend_none_linked"], "why": "the only backend that has it: libsodium's own C code, the same on every target ({libsodium-secretbox})"} + ], + "backends": { + "sodium": {"targets": "all"} + } + }, + { + "name": "box_xsalsa20poly1305", + "title": "X25519-XSalsa20-Poly1305 box", + "group": "hybrid", + "since": "0.2", + "header": "", + "names": [ + {"name": "box_xsalsa20poly1305", "title": "X25519-XSalsa20-Poly1305 box", "type": "hybrid::basic_box"} + ], + "default": [ + {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": ["box_sodium", "default_backend_none_linked"], "why": "the only backend that has it: libsodium's own C code, NaCl's `crypto_box`, the same on every target ({libsodium-box})"} + ], + "backends": { + "sodium": {"targets": "all"} + } + }, + { + "name": "box_xchacha20poly1305", + "title": "X25519-XChaCha20-Poly1305 box", + "group": "hybrid", + "since": "0.2", + "header": "", + "names": [ + {"name": "box_xchacha20poly1305", "title": "X25519-XChaCha20-Poly1305 box", "type": "hybrid::basic_box"} + ], + "default": [ + {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": ["box_sodium", "default_backend_none_linked"], "why": "the only backend that has it: libsodium's own C code, the same on every target ({libsodium-box})"} + ], + "backends": { + "sodium": {"targets": "all"} + } + }, + { + "name": "sealed_box", + "title": "X25519-XSalsa20-Poly1305 sealed box", + "group": "hybrid", + "since": "0.2", + "header": "", + "names": [ + {"name": "sealed_box", "title": "X25519-XSalsa20-Poly1305 sealed box", "type": "hybrid::basic_sealed_box<{backend}>"} + ], + "default": [ + {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": ["box_sodium", "default_backend_none_linked"], "why": "the only backend that has it: libsodium's own C code, which draws the key pair of each message from its own generator, the same on every target ({libsodium-sealed})"} + ], + "backends": { + "sodium": {"targets": "all"} + } } ], "rules": [ @@ -602,6 +748,15 @@ ["`ed25519`", "Ed25519 signatures, and Ed25519ph over SHA-512 for a message given in pieces; the X25519 secret key of a key pair", "about 128 bits ({rfc8032})", "secret 32 bytes (the seed); public 32 bytes", "64 bytes", "not measured yet", "not measured yet", "{rfc8032}, {fips186-5}", "SSH keys ({rfc8709}), Signal's signatures on its Curve25519 keys ({signal-xeddsa}), Tor's identity keys ({tor-cert-spec}), Solana's accounts ({solana-accounts})", "yes: Ed25519 ({webcrypto})", "SSH, Tor and Solana keys and signatures, and any protocol that names RFC 8032's Ed25519 or Ed25519ph; verification is strict (libsodium's rules), which some lenient verifiers are not. Not Bitcoin, Ethereum or Nostr, whose keys are secp256k1's"], ["`x25519`", "Key agreement (Diffie-Hellman on Curve25519): two parties who exchanged public keys share a 32-byte secret", "about 128 bits ({rfc7748})", "secret 32 bytes; public 32 bytes", "none: no signatures", "not measured yet", "not measured yet", "{rfc7748}", "TLS 1.3 ({rfc8446-groups}), SSH ({rfc8731}), WireGuard ({wireguard}), Signal ({x3dh})", "yes: X25519 ({webcrypto})", "TLS 1.3's and SSH's key exchange, WireGuard, Signal; libsodium's `crypto_box` and `crypto_kx` keys. The Ed25519 public key of a peer converts with `curves::ed25519::to_x25519_public`. A shared secret goes through a KDF before it keys a cipher. Every case of Wycheproof's X25519 file is tested ({wycheproof})"] ] + }, + "hybrid": { + "title": "webcpp::crypto::hybrid", + "columns": ["Construction", "What it does", "Keys", "Nonce (IV)", "Overhead per message", "Standards and sources", "Choose it when"], + "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 32-byte secret key and the peer's 32-byte 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 32-byte public key; to open, the recipient's 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"] + ] } }, "use_cases": [ @@ -624,6 +779,9 @@ {"need": "Hash, or compute an HMAC", "namespace": "Boost.Hash2, not this library", "api": "`boost::hash2::sha2_256`, `hmac_sha2_256`", "backend": "none", "jamfile": "`/webcpp/crypto//crypto` brings Boost's headers", "example": "equal_hmac", "section": "crypto-overview-hash2"}, {"need": "Sign and verify with Ed25519 (RFC 8032), or sign a large message in pieces with Ed25519ph", "namespace": "webcpp::crypto::curves::ed25519", "api": "`keypair::make`, `keypair::generate`, `keypair::sign`, `verify`; `ph`", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//ed25519-default", "example": "ed25519_sign", "section": "crypto-ed25519"}, {"need": "Agree a shared secret with a peer's public key (X25519, RFC 7748), or with the X25519 form of an Ed25519 key", "namespace": "webcpp::crypto::curves::x25519", "api": "`public_key`, `agree`; `curves::ed25519::to_x25519_public`, `curves::ed25519::keypair::x25519_secret`", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//x25519-default", "example": "x25519_agree", "section": "crypto-x25519"}, + {"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::ciphers", "api": "`secretbox<>`, `secretbox_xchacha20poly1305<>`: `make`, `seal`, `open`", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//secretbox_xsalsa20poly1305-default", "example": "", "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::hybrid", "api": "`box::make`, `box::seal`, `box::open`", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//box_xsalsa20poly1305-default", "example": "", "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::hybrid", "api": "`sealed_box::seal`, `sealed_box::open`", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//sealed_box-default", "example": "", "section": "crypto-sealed-box"}, {"need": "Use P-256 (passkeys, JWT's ES256)", "namespace": "none in this version", "api": "secp256k1, Ed25519 and X25519 keys and signatures do not interoperate with this curve", "backend": "none", "jamfile": "none", "example": "", "section": "crypto-curves"} ], "fixtures": { @@ -640,6 +798,11 @@ "chacha20_poly1305_default": "RFC 8439's ChaCha20-Poly1305 example, sealed and opened on its default on every target, with the one line `/webcpp/crypto//chacha20_poly1305-default`, which links libsodium.", "chacha20_poly1305_original_default": "libsodium's case of the original ChaCha20-Poly1305, sealed and opened on its default on every target, with the one line `/webcpp/crypto//chacha20_poly1305_original-default`, which links libsodium.", "xchacha20_poly1305_default": "The XChaCha20-Poly1305 draft's example, sealed and opened on its default on every target, with the one line `/webcpp/crypto//xchacha20_poly1305-default`, which links libsodium.", + "secretbox_xsalsa20poly1305_default": "NaCl's secret box, sealed and opened on its default on every target, with the one line `/webcpp/crypto//secretbox_xsalsa20poly1305-default`, which links libsodium.", + "secretbox_xchacha20poly1305_default": "A case of libsodium's XChaCha20 secret boxes, sealed and opened on its default on every target, with the one line `/webcpp/crypto//secretbox_xchacha20poly1305-default`, which links libsodium.", + "box_xsalsa20poly1305_default": "NaCl's box from Alice to Bob, sealed and opened by Bob on its default on every target, with the one line `/webcpp/crypto//box_xsalsa20poly1305-default`, which links libsodium.", + "box_xchacha20poly1305_default": "Alice and Bob's keys in the XChaCha20 box, sealed by Alice and opened by Bob on its default on every target, with the one line `/webcpp/crypto//box_xchacha20poly1305-default`, which links libsodium.", + "sealed_box_default": "A message sealed to Bob's public key and opened with his key pair on the default on every target, with the one line `/webcpp/crypto//sealed_box-default`, which links libsodium.", "sign": "A BIP 340 signature with libsecp256k1's default tables.", "sign_small": "The same program with libsecp256k1's small tables, which libsecp256k1 documents as smaller and slower to verify ({secp256k1-configure}); not measured here yet.", "canary_missing": "BearSSL's headers used without its library, built by other means than b2.", @@ -679,8 +842,9 @@ "ctaes_not_linked": "Add `/third_party//ctaes`.", "sodium_not_linked": "Add `/third_party//sodium`.", "chacha_default_not_linked": "The ChaCha20-Poly1305 AEADs' default is libsodium on every target: add the family's alias, as `/webcpp/crypto//chacha20_poly1305-default`, which links `/third_party//sodium`.", + "box_default_not_linked": "The secret boxes', the boxes' and the sealed boxes' default is libsodium on every target: add the family's alias, as `/webcpp/crypto//box_xsalsa20poly1305-default`, which links `/third_party//sodium`.", "chacha_on_ctaes": "Name a backend that has ChaCha20-Poly1305, as in `chacha20_poly1305`, or its default, `chacha20_poly1305<>`, and link its library.", - "aead_not_a_family": "Name one of the three ChaCha20-Poly1305 families; AES-GCM is `ciphers::gcm`, as in `aes256_gcm`.", + "aead_not_a_family": "Name one of the three ChaCha20-Poly1305 families or the two secret boxes'; AES-GCM is `ciphers::gcm`, as in `aes256_gcm`.", "sodium_not_linked_on_emscripten": "Add `/third_party//sodium` to the program's sources.", "canary_sodium_other_commit": "Build the library at the commit of webcpp's submodule, or link it through b2.", "secp256k1_not_linked": "Add `/third_party//secp256k1`.", diff --git a/doc/tables/generate.py b/doc/tables/generate.py index a158d0ba..030572b7 100644 --- a/doc/tables/generate.py +++ b/doc/tables/generate.py @@ -68,7 +68,7 @@ VERDICTS = ('accept', 'reject') BACKEND_ORDER = ('bearssl', 'openssl', 'ctaes', 'secp256k1', 'sodium', 'system', 'none') NAMESPACE_TITLES = {'root': 'webcpp::crypto', 'ciphers': 'webcpp::crypto::ciphers', - 'curves': 'webcpp::crypto::curves'} + 'curves': 'webcpp::crypto::curves', 'hybrid': 'webcpp::crypto::hybrid'} RUN_RULES = ('crypto-run', 'memory-run', 'webcpp.run', 'webcpp.compile', 'webcpp.compile-diagnostic', 'webcpp.compile-fail', 'webcpp.link-fail', 'webcpp.example') @@ -1341,7 +1341,8 @@ def llms(data: Data, matrix: Matrix, library: Path) -> str: out = ['# webcpp::crypto', '', '> Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: ' 'AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA, ECDH, the x-only ' - 'tweak), Ed25519 and Ed25519ph (RFC 8032), X25519 (RFC 7748), a random_device on the ' + 'tweak), Ed25519 and Ed25519ph (RFC 8032), X25519 (RFC 7748), the ChaCha20-Poly1305 ' + 'AEADs, libsodium\'s secret boxes, boxes and sealed boxes, a random_device on the ' 'system\'s generator and a constant-time equal, each over a widely used, reviewed C ' 'library (BearSSL, OpenSSL, ctaes, libsecp256k1, libsodium) that ' 'the program names in its Jamfile. Hashing and HMAC are Boost.Hash2\'s. Every ' diff --git a/include/webcpp/crypto.hpp b/include/webcpp/crypto.hpp index 9309ee70..873390f0 100644 --- a/include/webcpp/crypto.hpp +++ b/include/webcpp/crypto.hpp @@ -6,13 +6,13 @@ /** Every header of webcpp::crypto that needs no backend, the header of each backend the build - links with the curves it holds (libsecp256k1's secp256k1, libsodium's Ed25519 and X25519), - `ciphers/aes256_gcm.hpp`, whose `aes128_gcm` and `aes256_gcm` name AES-GCM's default - backend, and `ciphers/chacha20_poly1305.hpp`, whose AEADs name libsodium: a program that does - not link the default names another in the type, as + links with what it alone holds (libsecp256k1's secp256k1; libsodium's Ed25519, X25519, boxes + and sealed boxes), `ciphers/aes256_gcm.hpp`, whose `aes128_gcm` and `aes256_gcm` name AES-GCM's + default backend, and `ciphers/chacha20_poly1305.hpp` and `ciphers/secretbox.hpp`, whose AEADs + name libsodium: 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 and - XChaCha20-Poly1305, which libsodium alone has, links libsodium. + `ciphers::chacha20_poly1305`, or, for the original ChaCha20-Poly1305, + XChaCha20-Poly1305 and the secret boxes, which libsodium alone has, links libsodium. */ #ifndef WEBCPP_CRYPTO_HPP #define WEBCPP_CRYPTO_HPP @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include // lint-world: the system's entropy, a purpose of crypto @@ -45,6 +46,8 @@ #include #include #include +#include +#include #endif #ifdef WEBCPP_CRYPTO_HAS_SECP256K1 diff --git a/include/webcpp/crypto/backends/sodium.hpp b/include/webcpp/crypto/backends/sodium.hpp index 5a74cd83..ba755b2d 100644 --- a/include/webcpp/crypto/backends/sodium.hpp +++ b/include/webcpp/crypto/backends/sodium.hpp @@ -30,6 +30,8 @@ #include // through /third_party//sodium, as webcpp::hash's header does #include #include +#include +#include #include #include @@ -198,6 +200,140 @@ struct aead_engine { static void reset(state& s) noexcept { wipe_object(s.key); } }; +/** libsodium's detached functions of a secret box family, which differ only by name. */ +template +struct sodium_secretbox_calls; + +/** `crypto_secretbox`, XSalsa20-Poly1305. */ +template <> +struct sodium_secretbox_calls { + /** Encrypts and computes the tag apart. */ + static constexpr auto encrypt = &crypto_secretbox_detached; + /** Checks the tag apart, then decrypts. */ + static constexpr auto decrypt = &crypto_secretbox_open_detached; +}; + +/** `crypto_secretbox_xchacha20poly1305`. */ +template <> +struct sodium_secretbox_calls { + /** Encrypts and computes the tag apart. */ + static constexpr auto encrypt = &crypto_secretbox_xchacha20poly1305_detached; + /** Checks the tag apart, then decrypts. */ + static constexpr auto decrypt = &crypto_secretbox_xchacha20poly1305_open_detached; +}; + +/** + * Seals `data` in place with a secret box's detached function under a 32-byte key. libsodium + * reads the nonce again after it writes the first bytes of the ciphertext, so a nonce that + * lies in `data` is copied first; an empty span's null data() is never read or written. + * + * @return Nothing; `backend_failure` when libsodium fails. + */ +template +[[nodiscard]] boost::system::result sodium_secretbox_seal( + Encrypt encrypt, std::span key, std::span iv, + std::span data, boost::hash2::digest<16>& tag) noexcept { + std::array nonce{}; + std::ranges::copy(iv, nonce.begin()); + if (encrypt(data.data(), tag.data(), data.data(), data.size(), nonce.data(), key.data()) != 0) { + return error::backend_failure; + } + return {}; +} + +/** + * Checks the tag, then decrypts `data` in place, with a secret box's detached function; the + * nonce is copied first, as `sodium_secretbox_seal` says. An empty span's null data() makes + * libsodium check the tag alone. + * + * @return Nothing; `authentication_failed` when the tag does not match. + */ +template +[[nodiscard]] boost::system::result sodium_secretbox_open( + Decrypt decrypt, std::span key, std::span iv, + std::span data, std::array const& tag) noexcept { + std::array nonce{}; + std::ranges::copy(iv, nonce.begin()); + if (decrypt(data.data(), data.data(), tag.data(), data.size(), nonce.data(), key.data()) != 0) { + return error::authentication_failed; + } + return {}; +} + +/** A secret box's state on libsodium: the key, in the object, since libsodium takes it per call. */ +template + requires requires { sodium_secretbox_calls::encrypt; } +struct aead_state { + /** The key. */ + std::array key{}; +}; + +/** + * A secret box on libsodium, `crypto_secretbox` and its XChaCha20 twin, as an `aead` without + * additional data (`aead` has refused a non-empty one). libsodium's detached decryption checks + * the tag before it writes a byte; `aead` zeroes the data when it does not match. + */ +template + requires requires { sodium_secretbox_calls::encrypt; } +struct aead_engine { + /** The state. */ + using state = aead_state; + /** libsodium's functions of the family. */ + using calls = sodium_secretbox_calls; + + /** + * Initialises libsodium and keeps the key. + * + * @return Nothing; `backend_failure` when libsodium cannot start. + */ + [[nodiscard]] static boost::system::result init( + state& s, std::span key) noexcept { + auto const ready = sodium_ready(); + if (!ready) { + return ready; + } + std::ranges::copy(key, s.key.begin()); + return {}; + } + + /** + * Encrypts `data` in place and writes the tag. + * + * @return Nothing; `backend_failure` when libsodium fails. + */ + [[nodiscard]] static boost::system::result seal( + state& s, std::span iv, + std::span /*additional_data*/, std::span data, + boost::hash2::digest<16>& tag) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); + return sodium_secretbox_seal(calls::encrypt, std::span(s.key), + iv.first<24>(), data, tag); + } + + /** + * Checks the tag, then decrypts `data` in place. + * + * @return Nothing; `authentication_failed` when the tag does not match. + */ + [[nodiscard]] static boost::system::result open( + state& s, std::span iv, + std::span /*additional_data*/, std::span data, + std::array const& tag) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); + return sodium_secretbox_open(calls::decrypt, std::span(s.key), + iv.first<24>(), data, tag); + } + + /** Moves the key; the source is wiped. */ + static void move(state& to, state& from) noexcept { + to.key = from.key; + wipe_object(from.key); + } + + /** Wipes the key. */ + static void reset(state& s) noexcept { wipe_object(s.key); } +}; + } // namespace webcpp::crypto::detail #endif // WEBCPP_CRYPTO_HAS_SODIUM @@ -464,3 +600,188 @@ struct x25519_engine { } // namespace webcpp::crypto::detail #endif // X25519 on libsodium + +// The boxes on libsodium, for a program that includes hybrid/box.hpp, before this header or +// after it, as Ed25519's above. +#if defined(WEBCPP_CRYPTO_HYBRID_BOX_HPP) && defined(WEBCPP_CRYPTO_HAS_SODIUM) && \ + !defined(WEBCPP_CRYPTO_BACKENDS_SODIUM_BOX) +/** Defined once libsodium's box engines are. */ +#define WEBCPP_CRYPTO_BACKENDS_SODIUM_BOX + +#include + +#include +#include + +#include +#include +#include + +namespace webcpp::crypto::detail { + +/** libsodium's functions of a box family, which differ only by name. */ +template +struct sodium_box_calls; + +/** `crypto_box`, X25519-XSalsa20-Poly1305. */ +template <> +struct sodium_box_calls { + /** Agrees the key. */ + static constexpr auto beforenm = &crypto_box_beforenm; + /** Encrypts and computes the tag apart. */ + static constexpr auto encrypt = &crypto_box_detached_afternm; + /** Checks the tag apart, then decrypts. */ + static constexpr auto decrypt = &crypto_box_open_detached_afternm; +}; + +/** `crypto_box_curve25519xchacha20poly1305`, X25519-XChaCha20-Poly1305. */ +template <> +struct sodium_box_calls { + /** Agrees the key. */ + static constexpr auto beforenm = &crypto_box_curve25519xchacha20poly1305_beforenm; + /** Encrypts and computes the tag apart. */ + static constexpr auto encrypt = &crypto_box_curve25519xchacha20poly1305_detached_afternm; + /** Checks the tag apart, then decrypts. */ + static constexpr auto decrypt = &crypto_box_curve25519xchacha20poly1305_open_detached_afternm; +}; + +/** What a box stores on libsodium: the key `beforenm` agreed. */ +template + requires requires { sodium_box_calls::beforenm; } +struct box_state { + /** The agreed key. */ + std::array key{}; +}; + +/** A box on libsodium: `beforenm` once, then the `afternm` functions per message. */ +template + requires requires { sodium_box_calls::beforenm; } +struct box_engine { + /** The state. */ + using state = box_state; + /** libsodium's functions of the family. */ + using calls = sodium_box_calls; + + /** + * Agrees the key: X25519 of the secret key and the peer's public key, which libsodium + * refuses for a peer key of small order, then the family's key derivation. + * + * @return Nothing; `weak_public_key`; `backend_failure` when libsodium cannot start. + */ + [[nodiscard]] static boost::system::result init( + state& s, std::span secret_key, + std::span peer_public_key) noexcept { + auto const ready = sodium_ready(); + if (!ready) { + return ready; + } + if (calls::beforenm(s.key.data(), peer_public_key.data(), secret_key.data()) != 0) { + wipe_object(s.key); + return error::weak_public_key; + } + return {}; + } + + /** + * Encrypts `data` in place and writes the tag. + * + * @return Nothing; `backend_failure` when libsodium fails. + */ + [[nodiscard]] static boost::system::result seal(state& s, + std::span iv, + std::span data, + boost::hash2::digest<16>& tag) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); + return sodium_secretbox_seal(calls::encrypt, std::span(s.key), iv, + data, tag); + } + + /** + * Checks the tag, then decrypts `data` in place. + * + * @return Nothing; `authentication_failed` when the tag does not match. + */ + [[nodiscard]] static boost::system::result open( + state& s, std::span iv, std::span data, + std::array const& tag) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); + return sodium_secretbox_open(calls::decrypt, std::span(s.key), iv, + data, tag); + } + + /** Moves the key; the source is wiped. */ + static void move(state& to, state& from) noexcept { + to.key = from.key; + wipe_object(from.key); + } + + /** Wipes the key. */ + static void reset(state& s) noexcept { wipe_object(s.key); } +}; + +} // namespace webcpp::crypto::detail + +#endif // the boxes on libsodium + +// Sealed boxes on libsodium, for a program that includes hybrid/sealed_box.hpp, before this +// header or after it, as Ed25519's above. +#if defined(WEBCPP_CRYPTO_HYBRID_SEALED_BOX_HPP) && defined(WEBCPP_CRYPTO_HAS_SODIUM) && \ + !defined(WEBCPP_CRYPTO_BACKENDS_SODIUM_SEALED_BOX) +/** Defined once libsodium's sealed box engine is. */ +#define WEBCPP_CRYPTO_BACKENDS_SODIUM_SEALED_BOX + +#include + +#include +#include + +namespace webcpp::crypto::detail { + +/** Sealed boxes on libsodium, `crypto_box_seal` and `crypto_box_seal_open`. */ +template <> +struct sealed_box_engine { + /** + * Seals `message` into `out` (`basic_sealed_box` has checked the sizes): libsodium draws + * the key pair from its own generator and wipes its secret key. + * + * @return Nothing; `weak_public_key` for a recipient key of small order, which libsodium's + * box refuses; `backend_failure` when libsodium cannot start. + */ + [[nodiscard]] static boost::system::result seal( + std::span recipient_public_key, + std::span message, std::span out) noexcept { + auto const ready = sodium_ready(); + if (!ready) { + return ready; + } + if (crypto_box_seal(out.data(), message.data(), message.size(), + recipient_public_key.data()) != 0) { + return error::weak_public_key; + } + return {}; + } + + /** + * Opens `sealed` into `out` (`basic_sealed_box` has checked the sizes). + * + * @return Nothing; `authentication_failed`; `backend_failure` when libsodium cannot start. + */ + [[nodiscard]] static boost::system::result open( + std::span recipient_public_key, + std::span recipient_secret_key, + std::span sealed, std::span out) noexcept { + auto const ready = sodium_ready(); + if (!ready) { + return ready; + } + if (crypto_box_seal_open(out.data(), sealed.data(), sealed.size(), + recipient_public_key.data(), recipient_secret_key.data()) != 0) { + return error::authentication_failed; + } + return {}; + } +}; + +} // namespace webcpp::crypto::detail + +#endif // sealed boxes on libsodium diff --git a/include/webcpp/crypto/ciphers/aead.hpp b/include/webcpp/crypto/ciphers/aead.hpp index da1dafc0..f23c4b3f 100644 --- a/include/webcpp/crypto/ciphers/aead.hpp +++ b/include/webcpp/crypto/ciphers/aead.hpp @@ -6,9 +6,10 @@ /** `aead`, one-shot authenticated encryption in place, and the families it - takes: ChaCha20-Poly1305, its original form and XChaCha20-Poly1305. + takes: ChaCha20-Poly1305, its original form and XChaCha20-Poly1305, and libsodium's + `crypto_secretbox`, XSalsa20-Poly1305 and XChaCha20-Poly1305 without additional data. - @see "ChaCha20-Poly1305", in the guide. + @see "ChaCha20-Poly1305" and "Secret boxes", in the guide. */ #ifndef WEBCPP_CRYPTO_CIPHERS_AEAD_HPP #define WEBCPP_CRYPTO_CIPHERS_AEAD_HPP @@ -78,6 +79,40 @@ struct xchacha20_poly1305 { static constexpr std::uint64_t max_additional_data_size = ~std::uint64_t{0}; }; +/** + * NaCl's and libsodium's `crypto_secretbox`, XSalsa20-Poly1305: a 32-byte key, a 24-byte nonce + * safe to draw at random, a 16-byte tag, and no additional data. + */ +struct secretbox_xsalsa20poly1305 { + /** The key's size. */ + static constexpr std::size_t key_size = 32; + /** The nonce's size, exactly. */ + static constexpr std::size_t iv_size = 24; + /** The tag's size. */ + static constexpr std::size_t tag_size = 16; + /** The longest message, 2^64 - 17 bytes, as libsodium's `crypto_secretbox_MESSAGEBYTES_MAX`. */ + static constexpr std::uint64_t max_message_size = ~std::uint64_t{0} - 16; + /** No additional data: `aead` refuses a non-empty one with `invalid_input_size`. */ + static constexpr std::uint64_t max_additional_data_size = 0; +}; + +/** + * libsodium's `crypto_secretbox_xchacha20poly1305`: `crypto_secretbox` with XChaCha20 in place + * of XSalsa20, a 24-byte nonce safe to draw at random, and no additional data. + */ +struct secretbox_xchacha20poly1305 { + /** The key's size. */ + static constexpr std::size_t key_size = 32; + /** The nonce's size, exactly. */ + static constexpr std::size_t iv_size = 24; + /** The tag's size. */ + static constexpr std::size_t tag_size = 16; + /** The longest message, 2^64 - 17 bytes. */ + static constexpr std::uint64_t max_message_size = ~std::uint64_t{0} - 16; + /** No additional data: `aead` refuses a non-empty one with `invalid_input_size`. */ + static constexpr std::uint64_t max_additional_data_size = 0; +}; + } // namespace webcpp::crypto::families namespace webcpp::crypto::detail { @@ -105,6 +140,14 @@ inline constexpr bool aead_family = true; template <> inline constexpr bool aead_family = true; +/** `crypto_secretbox`, XSalsa20-Poly1305, is an AEAD family without additional data. */ +template <> +inline constexpr bool aead_family = true; + +/** `crypto_secretbox_xchacha20poly1305` is an AEAD family without additional data. */ +template <> +inline constexpr bool aead_family = true; + /** * The sizes and limits `ciphers::aead` reads from its family: the family's own. * @@ -156,6 +199,18 @@ struct aead_refusal { WEBCPP_CRYPTO_DETAIL_REFUSE_XCHACHA20_POLY1305(Backend); }; +/** XSalsa20-Poly1305's secret box's refusal (see the first). */ +template +struct aead_refusal { + WEBCPP_CRYPTO_DETAIL_REFUSE_SECRETBOX_XSALSA20POLY1305(Backend); +}; + +/** XChaCha20-Poly1305's secret box's refusal (see the first). */ +template +struct aead_refusal { + WEBCPP_CRYPTO_DETAIL_REFUSE_SECRETBOX_XCHACHA20POLY1305(Backend); +}; + /** * An AEAD's engine on a backend whose header does not specialise it: the family's refusal. * Its functions are never called: the refusal stops the build where the class is @@ -203,20 +258,23 @@ namespace webcpp::crypto::ciphers { * repeated under one key: two messages under one key and one nonce reveal the XOR of their * plaintexts and let an attacker forge tags. Drawn at random, ChaCha20-Poly1305's 12-byte * nonce lets a key seal at most 2^32 messages, and the original's 8 bytes are too few: a - * counter numbers them. XChaCha20-Poly1305's 24-byte nonce is safe to draw at random. + * counter numbers them. XChaCha20-Poly1305's 24-byte nonce, and the secret boxes', are safe + * to draw at random. * - * @tparam Family `families::chacha20_poly1305`, `families::chacha20_poly1305_original` or - * `families::xchacha20_poly1305`. - * @tparam Backend The backend; `ciphers::chacha20_poly1305<>` and its two siblings name the - * family's default. + * @tparam Family `families::chacha20_poly1305`, `families::chacha20_poly1305_original`, + * `families::xchacha20_poly1305`, or the secret boxes' `families::secretbox_xsalsa20poly1305` + * and `families::secretbox_xchacha20poly1305`, which take no additional data. + * @tparam Backend The backend; `ciphers::chacha20_poly1305<>`, its two siblings and + * `ciphers::secretbox<>` and its twin name the family's default. */ template class aead { // The first error a program that names another type sees, and its only one. static_assert(detail::aead_family, "webcpp::crypto: ciphers::aead takes an AEAD family: " - "families::chacha20_poly1305, families::chacha20_poly1305_original or " - "families::xchacha20_poly1305."); + "families::chacha20_poly1305, families::chacha20_poly1305_original, " + "families::xchacha20_poly1305, families::secretbox_xsalsa20poly1305 or " + "families::secretbox_xchacha20poly1305."); using sizes = detail::aead_sizes; using state_type = detail::aead_state; @@ -239,7 +297,7 @@ class aead { static constexpr std::size_t tag_size = sizes::tag_size; /** The longest message. */ static constexpr std::uint64_t max_message_size = sizes::max_message_size; - /** The longest additional data. */ + /** The longest additional data; 0 for a family that takes none. */ static constexpr std::uint64_t max_additional_data_size = sizes::max_additional_data_size; /** @@ -312,10 +370,11 @@ class aead { * and an open with the original additional data would fail. * * @param iv_bytes The nonce, `iv_size` bytes, never repeated under this key. - * @param additional_data_bytes Authenticated, not encrypted. + * @param additional_data_bytes Authenticated, not encrypted; empty for a family that takes + * none (`max_additional_data_size` 0). * @param data_bytes The message. - * @return The tag; `invalid_state` moved from; `invalid_iv_size`; `message_too_long`; - * `backend_failure`. + * @return The tag; `invalid_state` moved from; `invalid_iv_size`; `invalid_input_size` for + * additional data given to a family that takes none; `message_too_long`; `backend_failure`. */ [[nodiscard]] boost::system::result seal( std::span iv_bytes, std::span additional_data_bytes, @@ -347,6 +406,7 @@ class aead { * @param tag_bytes The seal's tag, `tag_size` bytes, which may lie anywhere, `data_bytes` * included. * @return Nothing; `invalid_state` moved from; `invalid_iv_size`; `invalid_tag_size`; + * `invalid_input_size` for additional data given to a family that takes none; * `message_too_long`; `authentication_failed`; `backend_failure`. */ [[nodiscard]] boost::system::result open( @@ -373,7 +433,8 @@ class aead { aead() noexcept = default; // Every guard of a message, in the documented order: the state, the nonce, the tag - // (open's; seal passes tag_size), the lengths. None reads a byte of the spans. + // (open's; seal passes tag_size), additional data given to a family that takes none, the + // lengths. None reads a byte of the spans. [[nodiscard]] boost::system::result guard_message( std::span iv_bytes, std::span additional_data_bytes, std::size_t byte_count, std::size_t tag_bytes) const noexcept { @@ -386,6 +447,11 @@ class aead { if (tag_bytes != tag_size) { return error::invalid_tag_size; } + if constexpr (max_additional_data_size == 0) { + if (!additional_data_bytes.empty()) { + return error::invalid_input_size; + } + } if (detail::exceeds(byte_count, max_message_size) || detail::exceeds(additional_data_bytes.size(), max_additional_data_size)) { return error::message_too_long; diff --git a/include/webcpp/crypto/ciphers/secretbox.hpp b/include/webcpp/crypto/ciphers/secretbox.hpp new file mode 100644 index 00000000..77594928 --- /dev/null +++ b/include/webcpp/crypto/ciphers/secretbox.hpp @@ -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) + +/** + `secretbox` and `secretbox_xchacha20poly1305`, NaCl's and libsodium's secret boxes as `aead`s + without additional data, each on its family's default backend unless the type names another: + libsodium on every target, whose header it includes when the program links it + (`default_backend_t`). A program that uses them without linking the default stops where it + calls them, with the Jamfile line that links it. + + @see "Secret boxes", in the guide. +*/ +#ifndef WEBCPP_CRYPTO_CIPHERS_SECRETBOX_HPP +#define WEBCPP_CRYPTO_CIPHERS_SECRETBOX_HPP + +#include + +#include +#include + +#if (defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_SECRETBOX_XSALSA20POLY1305_SODIUM) || \ + defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_SECRETBOX_XCHACHA20POLY1305_SODIUM)) && \ + defined(WEBCPP_CRYPTO_HAS_SODIUM) +#include +#endif + +namespace webcpp::crypto::ciphers { + +/** + * NaCl's and libsodium's `crypto_secretbox`, XSalsa20-Poly1305: a 32-byte key, a 24-byte nonce + * safe to draw at random, a 16-byte tag, and no additional data, which `seal` and `open` refuse + * unless empty (`invalid_input_size`). + * + * @tparam Backend The backend; the default is the family's. + */ +template > +using secretbox = aead; + +/** + * libsodium's `crypto_secretbox_xchacha20poly1305`: the secret box with XChaCha20 in place of + * XSalsa20, of the same sizes and without additional data. + * + * @tparam Backend The backend; the default is the family's. + */ +template > +using secretbox_xchacha20poly1305 = aead; + +} // namespace webcpp::crypto::ciphers + +#endif // WEBCPP_CRYPTO_CIPHERS_SECRETBOX_HPP diff --git a/include/webcpp/crypto/detail/capabilities.hpp b/include/webcpp/crypto/detail/capabilities.hpp index e7c5143f..222c78b5 100644 --- a/include/webcpp/crypto/detail/capabilities.hpp +++ b/include/webcpp/crypto/detail/capabilities.hpp @@ -50,6 +50,23 @@ struct chacha20_poly1305_original; /** The family XChaCha20-Poly1305, of `ciphers`, also the tag of its one algorithm. */ struct xchacha20_poly1305; +/** The family XSalsa20-Poly1305 secret box, of `ciphers`, also the tag of its one algorithm. */ +struct secretbox_xsalsa20poly1305; + +/** The family XChaCha20-Poly1305 secret box, of `ciphers`, also the tag of its one algorithm. */ +struct secretbox_xchacha20poly1305; + +/** The family X25519-XSalsa20-Poly1305 box, of `hybrid`, also the tag of its one algorithm. */ +struct box_xsalsa20poly1305; + +/** The family X25519-XChaCha20-Poly1305 box, of `hybrid`, also the tag of its one algorithm. */ +struct box_xchacha20poly1305; + +/** + * The family X25519-XSalsa20-Poly1305 sealed box, of `hybrid`, also the tag of its one algorithm. + */ +struct sealed_box; + } // namespace webcpp::crypto::families namespace webcpp::crypto::tags { @@ -190,6 +207,31 @@ inline constexpr bool supported inline constexpr bool supported = true; #endif +// XSalsa20-Poly1305 secret box on sodium: native, wasip2, wasip3, emscripten. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool supported = true; +#endif +// XChaCha20-Poly1305 secret box on sodium: native, wasip2, wasip3, emscripten. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool supported = true; +#endif +// X25519-XSalsa20-Poly1305 box on sodium: native, wasip2, wasip3, emscripten. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool supported = true; +#endif +// X25519-XChaCha20-Poly1305 box on sodium: native, wasip2, wasip3, emscripten. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool supported = true; +#endif +// X25519-XSalsa20-Poly1305 sealed box on sodium: native, wasip2, wasip3, emscripten. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool supported = true; +#endif // clang-format on /** @@ -562,6 +604,271 @@ inline constexpr bool linked = true; static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's XChaCha20-Poly1305 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: XChaCha20-Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") #endif +#ifdef WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE +/** + * The refusals of the family XSalsa20-Poly1305 secret box's primary engine for `Backend`, on + * native. + */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_SECRETBOX_XSALSA20POLY1305(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no XSalsa20-Poly1305 secret box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no XSalsa20-Poly1305 secret box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no XSalsa20-Poly1305 secret box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no XSalsa20-Poly1305 secret box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: XSalsa20-Poly1305 secret box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//secretbox_xsalsa20poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//secretbox_xsalsa20poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's XSalsa20-Poly1305 secret box is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: XSalsa20-Poly1305 secret box has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_WASIP2) +/** + * The refusals of the family XSalsa20-Poly1305 secret box's primary engine for `Backend`, on + * wasip2. + */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_SECRETBOX_XSALSA20POLY1305(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no XSalsa20-Poly1305 secret box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no XSalsa20-Poly1305 secret box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no XSalsa20-Poly1305 secret box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no XSalsa20-Poly1305 secret box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: XSalsa20-Poly1305 secret box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//secretbox_xsalsa20poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//secretbox_xsalsa20poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's XSalsa20-Poly1305 secret box is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: XSalsa20-Poly1305 secret box has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_WASIP3) +/** + * The refusals of the family XSalsa20-Poly1305 secret box's primary engine for `Backend`, on + * wasip3. + */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_SECRETBOX_XSALSA20POLY1305(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no XSalsa20-Poly1305 secret box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no XSalsa20-Poly1305 secret box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no XSalsa20-Poly1305 secret box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no XSalsa20-Poly1305 secret box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: XSalsa20-Poly1305 secret box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//secretbox_xsalsa20poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//secretbox_xsalsa20poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's XSalsa20-Poly1305 secret box is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: XSalsa20-Poly1305 secret box has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_EMSCRIPTEN) +/** + * The refusals of the family XSalsa20-Poly1305 secret box's primary engine for `Backend`, on + * emscripten. + */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_SECRETBOX_XSALSA20POLY1305(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no XSalsa20-Poly1305 secret box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no XSalsa20-Poly1305 secret box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no XSalsa20-Poly1305 secret box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no XSalsa20-Poly1305 secret box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: XSalsa20-Poly1305 secret box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//secretbox_xsalsa20poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//secretbox_xsalsa20poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's XSalsa20-Poly1305 secret box is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: XSalsa20-Poly1305 secret box has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#endif +#ifdef WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE +/** + * The refusals of the family XChaCha20-Poly1305 secret box's primary engine for `Backend`, on + * native. + */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_SECRETBOX_XCHACHA20POLY1305(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no XChaCha20-Poly1305 secret box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no XChaCha20-Poly1305 secret box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no XChaCha20-Poly1305 secret box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no XChaCha20-Poly1305 secret box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: XChaCha20-Poly1305 secret box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//secretbox_xchacha20poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//secretbox_xchacha20poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's XChaCha20-Poly1305 secret box is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: XChaCha20-Poly1305 secret box has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_WASIP2) +/** + * The refusals of the family XChaCha20-Poly1305 secret box's primary engine for `Backend`, on + * wasip2. + */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_SECRETBOX_XCHACHA20POLY1305(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no XChaCha20-Poly1305 secret box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no XChaCha20-Poly1305 secret box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no XChaCha20-Poly1305 secret box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no XChaCha20-Poly1305 secret box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: XChaCha20-Poly1305 secret box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//secretbox_xchacha20poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//secretbox_xchacha20poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's XChaCha20-Poly1305 secret box is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: XChaCha20-Poly1305 secret box has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_WASIP3) +/** + * The refusals of the family XChaCha20-Poly1305 secret box's primary engine for `Backend`, on + * wasip3. + */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_SECRETBOX_XCHACHA20POLY1305(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no XChaCha20-Poly1305 secret box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no XChaCha20-Poly1305 secret box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no XChaCha20-Poly1305 secret box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no XChaCha20-Poly1305 secret box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: XChaCha20-Poly1305 secret box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//secretbox_xchacha20poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//secretbox_xchacha20poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's XChaCha20-Poly1305 secret box is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: XChaCha20-Poly1305 secret box has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_EMSCRIPTEN) +/** + * The refusals of the family XChaCha20-Poly1305 secret box's primary engine for `Backend`, on + * emscripten. + */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_SECRETBOX_XCHACHA20POLY1305(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no XChaCha20-Poly1305 secret box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no XChaCha20-Poly1305 secret box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no XChaCha20-Poly1305 secret box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no XChaCha20-Poly1305 secret box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: XChaCha20-Poly1305 secret box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//secretbox_xchacha20poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//secretbox_xchacha20poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's XChaCha20-Poly1305 secret box is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: XChaCha20-Poly1305 secret box has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#endif +#ifdef WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE +/** + * The refusals of the family X25519-XSalsa20-Poly1305 box's primary engine for `Backend`, on + * native. + */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_BOX_XSALSA20POLY1305(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no X25519-XSalsa20-Poly1305 box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no X25519-XSalsa20-Poly1305 box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no X25519-XSalsa20-Poly1305 box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no X25519-XSalsa20-Poly1305 box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: X25519-XSalsa20-Poly1305 box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//box_xsalsa20poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//box_xsalsa20poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's X25519-XSalsa20-Poly1305 box is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: X25519-XSalsa20-Poly1305 box has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_WASIP2) +/** + * The refusals of the family X25519-XSalsa20-Poly1305 box's primary engine for `Backend`, on + * wasip2. + */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_BOX_XSALSA20POLY1305(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no X25519-XSalsa20-Poly1305 box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no X25519-XSalsa20-Poly1305 box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no X25519-XSalsa20-Poly1305 box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no X25519-XSalsa20-Poly1305 box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: X25519-XSalsa20-Poly1305 box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//box_xsalsa20poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//box_xsalsa20poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's X25519-XSalsa20-Poly1305 box is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: X25519-XSalsa20-Poly1305 box has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_WASIP3) +/** + * The refusals of the family X25519-XSalsa20-Poly1305 box's primary engine for `Backend`, on + * wasip3. + */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_BOX_XSALSA20POLY1305(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no X25519-XSalsa20-Poly1305 box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no X25519-XSalsa20-Poly1305 box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no X25519-XSalsa20-Poly1305 box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no X25519-XSalsa20-Poly1305 box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: X25519-XSalsa20-Poly1305 box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//box_xsalsa20poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//box_xsalsa20poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's X25519-XSalsa20-Poly1305 box is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: X25519-XSalsa20-Poly1305 box has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_EMSCRIPTEN) +/** + * The refusals of the family X25519-XSalsa20-Poly1305 box's primary engine for `Backend`, on + * emscripten. + */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_BOX_XSALSA20POLY1305(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no X25519-XSalsa20-Poly1305 box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no X25519-XSalsa20-Poly1305 box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no X25519-XSalsa20-Poly1305 box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no X25519-XSalsa20-Poly1305 box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: X25519-XSalsa20-Poly1305 box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//box_xsalsa20poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//box_xsalsa20poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's X25519-XSalsa20-Poly1305 box is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: X25519-XSalsa20-Poly1305 box has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#endif +#ifdef WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE +/** + * The refusals of the family X25519-XChaCha20-Poly1305 box's primary engine for `Backend`, on + * native. + */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_BOX_XCHACHA20POLY1305(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no X25519-XChaCha20-Poly1305 box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no X25519-XChaCha20-Poly1305 box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no X25519-XChaCha20-Poly1305 box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no X25519-XChaCha20-Poly1305 box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: X25519-XChaCha20-Poly1305 box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//box_xchacha20poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//box_xchacha20poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's X25519-XChaCha20-Poly1305 box is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: X25519-XChaCha20-Poly1305 box has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_WASIP2) +/** + * The refusals of the family X25519-XChaCha20-Poly1305 box's primary engine for `Backend`, on + * wasip2. + */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_BOX_XCHACHA20POLY1305(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no X25519-XChaCha20-Poly1305 box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no X25519-XChaCha20-Poly1305 box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no X25519-XChaCha20-Poly1305 box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no X25519-XChaCha20-Poly1305 box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: X25519-XChaCha20-Poly1305 box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//box_xchacha20poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//box_xchacha20poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's X25519-XChaCha20-Poly1305 box is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: X25519-XChaCha20-Poly1305 box has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_WASIP3) +/** + * The refusals of the family X25519-XChaCha20-Poly1305 box's primary engine for `Backend`, on + * wasip3. + */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_BOX_XCHACHA20POLY1305(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no X25519-XChaCha20-Poly1305 box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no X25519-XChaCha20-Poly1305 box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no X25519-XChaCha20-Poly1305 box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no X25519-XChaCha20-Poly1305 box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: X25519-XChaCha20-Poly1305 box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//box_xchacha20poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//box_xchacha20poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's X25519-XChaCha20-Poly1305 box is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: X25519-XChaCha20-Poly1305 box has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_EMSCRIPTEN) +/** + * The refusals of the family X25519-XChaCha20-Poly1305 box's primary engine for `Backend`, on + * emscripten. + */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_BOX_XCHACHA20POLY1305(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no X25519-XChaCha20-Poly1305 box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no X25519-XChaCha20-Poly1305 box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no X25519-XChaCha20-Poly1305 box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no X25519-XChaCha20-Poly1305 box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: X25519-XChaCha20-Poly1305 box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//box_xchacha20poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//box_xchacha20poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's X25519-XChaCha20-Poly1305 box is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: X25519-XChaCha20-Poly1305 box has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#endif +#ifdef WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE +/** + * The refusals of the family X25519-XSalsa20-Poly1305 sealed box's primary engine for `Backend`, on + * native. + */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_SEALED_BOX(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no X25519-XSalsa20-Poly1305 sealed box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no X25519-XSalsa20-Poly1305 sealed box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no X25519-XSalsa20-Poly1305 sealed box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no X25519-XSalsa20-Poly1305 sealed box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: X25519-XSalsa20-Poly1305 sealed box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//sealed_box-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//sealed_box-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's X25519-XSalsa20-Poly1305 sealed box is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: X25519-XSalsa20-Poly1305 sealed box has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_WASIP2) +/** + * The refusals of the family X25519-XSalsa20-Poly1305 sealed box's primary engine for `Backend`, on + * wasip2. + */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_SEALED_BOX(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no X25519-XSalsa20-Poly1305 sealed box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no X25519-XSalsa20-Poly1305 sealed box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no X25519-XSalsa20-Poly1305 sealed box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no X25519-XSalsa20-Poly1305 sealed box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: X25519-XSalsa20-Poly1305 sealed box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//sealed_box-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//sealed_box-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's X25519-XSalsa20-Poly1305 sealed box is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: X25519-XSalsa20-Poly1305 sealed box has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_WASIP3) +/** + * The refusals of the family X25519-XSalsa20-Poly1305 sealed box's primary engine for `Backend`, on + * wasip3. + */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_SEALED_BOX(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no X25519-XSalsa20-Poly1305 sealed box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no X25519-XSalsa20-Poly1305 sealed box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no X25519-XSalsa20-Poly1305 sealed box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no X25519-XSalsa20-Poly1305 sealed box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: X25519-XSalsa20-Poly1305 sealed box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//sealed_box-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//sealed_box-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's X25519-XSalsa20-Poly1305 sealed box is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: X25519-XSalsa20-Poly1305 sealed box has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_EMSCRIPTEN) +/** + * The refusals of the family X25519-XSalsa20-Poly1305 sealed box's primary engine for `Backend`, on + * emscripten. + */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_SEALED_BOX(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no X25519-XSalsa20-Poly1305 sealed box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no X25519-XSalsa20-Poly1305 sealed box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no X25519-XSalsa20-Poly1305 sealed box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no X25519-XSalsa20-Poly1305 sealed box. The backends that have it: sodium (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: X25519-XSalsa20-Poly1305 sealed box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//sealed_box-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//sealed_box-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's X25519-XSalsa20-Poly1305 sealed box is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: X25519-XSalsa20-Poly1305 sealed box has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") +#endif // clang-format on #endif // WEBCPP_CRYPTO_DETAIL_CAPABILITIES_HPP diff --git a/include/webcpp/crypto/detail/defaults.hpp b/include/webcpp/crypto/detail/defaults.hpp index d21a7bd3..65fe323f 100644 --- a/include/webcpp/crypto/detail/defaults.hpp +++ b/include/webcpp/crypto/detail/defaults.hpp @@ -98,6 +98,53 @@ struct default_backend_of { /** `backends::sodium`. */ using type = backends::sodium; }; +/** Defined where libsodium is the default of XSalsa20-Poly1305 secret box. */ +#define WEBCPP_CRYPTO_DETAIL_DEFAULT_SECRETBOX_XSALSA20POLY1305_SODIUM 1 +/** The default of XSalsa20-Poly1305 secret box on native, wasip2, wasip3, emscripten: libsodium. */ +template <> +struct default_backend_of { + /** `backends::sodium`. */ + using type = backends::sodium; +}; +/** Defined where libsodium is the default of XChaCha20-Poly1305 secret box. */ +#define WEBCPP_CRYPTO_DETAIL_DEFAULT_SECRETBOX_XCHACHA20POLY1305_SODIUM 1 +/** + * The default of XChaCha20-Poly1305 secret box on native, wasip2, wasip3, emscripten: libsodium. + */ +template <> +struct default_backend_of { + /** `backends::sodium`. */ + using type = backends::sodium; +}; +/** Defined where libsodium is the default of X25519-XSalsa20-Poly1305 box. */ +#define WEBCPP_CRYPTO_DETAIL_DEFAULT_BOX_XSALSA20POLY1305_SODIUM 1 +/** The default of X25519-XSalsa20-Poly1305 box on native, wasip2, wasip3, emscripten: libsodium. */ +template <> +struct default_backend_of { + /** `backends::sodium`. */ + using type = backends::sodium; +}; +/** Defined where libsodium is the default of X25519-XChaCha20-Poly1305 box. */ +#define WEBCPP_CRYPTO_DETAIL_DEFAULT_BOX_XCHACHA20POLY1305_SODIUM 1 +/** + * The default of X25519-XChaCha20-Poly1305 box on native, wasip2, wasip3, emscripten: libsodium. + */ +template <> +struct default_backend_of { + /** `backends::sodium`. */ + using type = backends::sodium; +}; +/** Defined where libsodium is the default of X25519-XSalsa20-Poly1305 sealed box. */ +#define WEBCPP_CRYPTO_DETAIL_DEFAULT_SEALED_BOX_SODIUM 1 +/** + * The default of X25519-XSalsa20-Poly1305 sealed box on native, wasip2, wasip3, emscripten: + * libsodium. + */ +template <> +struct default_backend_of { + /** `backends::sodium`. */ + using type = backends::sodium; +}; // clang-format on /** diff --git a/include/webcpp/crypto/hybrid/box.hpp b/include/webcpp/crypto/hybrid/box.hpp new file mode 100644 index 00000000..4082651c --- /dev/null +++ b/include/webcpp/crypto/hybrid/box.hpp @@ -0,0 +1,343 @@ +// 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) + +/** + `basic_box`, NaCl's and libsodium's `crypto_box`: X25519 agrees a key with a peer's public key + once (libsodium's `beforenm`), then each message is sealed and opened in place with + XSalsa20-Poly1305, or XChaCha20-Poly1305, the tag apart. `box` and `box_xchacha20poly1305` name + the two families on their default backend, libsodium on every target, whose header this one + includes when the program links it; a program that uses them without linking it stops where it + calls them, with the Jamfile line that links it. + + @see "Boxes", in the guide. +*/ +#ifndef WEBCPP_CRYPTO_HYBRID_BOX_HPP +#define WEBCPP_CRYPTO_HYBRID_BOX_HPP + +#include + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace webcpp::crypto::detail { + +/** + * What a `hybrid::basic_box` of the family `Family` stores on a backend whose header does not + * specialise it: nothing, since its engine refuses the backend where the box is used. + */ +template +struct box_state {}; + +/** + * The work of a box on a backend, whose specialisation provides `init(state&, secret_key, + * peer_public_key)`, `seal(state&, iv, data, tag&)`, `open(state&, iv, data, tag const&)`, + * `move(to, from)` and `reset(state&)`; the primary refuses (defined at the end of this header). + */ +template +struct box_engine; + +/** Whether `Family` is one of the families `hybrid::basic_box` takes. */ +template +inline constexpr bool box_family = false; + +/** X25519-XSalsa20-Poly1305, `crypto_box`, is a box family. */ +template <> +inline constexpr bool box_family = true; + +/** X25519-XChaCha20-Poly1305, `crypto_box_curve25519xchacha20poly1305`, is a box family. */ +template <> +inline constexpr bool box_family = true; + +} // namespace webcpp::crypto::detail + +namespace webcpp::crypto::hybrid { + +/** + * `crypto_box`: authenticated encryption between two key pairs. + * + * `make` agrees a key from the own secret key and the peer's public key, once per pair of keys + * (libsodium's `beforenm`); `seal` and `open` then work in place, the tag apart, under that key. + * Either party of the pair can have written a message: the box proves that it comes from one of + * them, not which. + * + * An object holds the agreed key, the state that every message uses: it is used by one thread + * at a time, moved and not copied, and wiped when moved from and destroyed. A nonce (the IV) is + * never repeated for one pair of keys, in either direction: two messages under one pair and + * one nonce reveal the XOR of their plaintexts and let an attacker forge tags. Its 24 bytes are + * safe to draw at random from `random_device` for every message. + * + * @tparam Family `families::box_xsalsa20poly1305`, NaCl's `crypto_box`, or + * `families::box_xchacha20poly1305`, libsodium's `crypto_box_curve25519xchacha20poly1305`. + * @tparam Backend The backend; by default the family's. + */ +template > +class basic_box { + // The first error a program that names another type sees. + static_assert(detail::box_family, + "webcpp::crypto: hybrid::basic_box takes a box family: " + "families::box_xsalsa20poly1305 or families::box_xchacha20poly1305."); + + using state_type = detail::box_state; + using engine = detail::box_engine; + +public: + /** The backend. */ + using backend_type = Backend; + /** The family of the capability table, which `supports_v` reads. */ + using family_type = Family; + /** The algorithm of the capability table: the family's own tag, its one algorithm. */ + using name_type = Family; + /** The tag, Boost.Hash2's digest of `tag_size` bytes. */ + using result_type = boost::hash2::digest<16>; + /** The secret key's and the peer's public key's size. */ + static constexpr std::size_t key_size = 32; + /** The nonce's size, exactly. */ + static constexpr std::size_t iv_size = 24; + /** The tag's size. */ + static constexpr std::size_t tag_size = 16; + /** The longest message, 2^64 - 17 bytes, as libsodium's `crypto_box_MESSAGEBYTES_MAX`. */ + static constexpr std::uint64_t max_message_size = ~std::uint64_t{0} - 16; + + /** + * Agrees the box's key from the own secret key and the peer's public key. + * + * @param secret_key The own X25519 secret key, `key_size` bytes. + * @param peer_public_key The peer's X25519 public key, `key_size` bytes. + * @return The box; `invalid_key_size`; `invalid_public_key` for a peer key of another + * size; `weak_public_key` for a peer key of small order, whose shared secret an attacker + * knows; `backend_failure` when the backend cannot start. + */ + [[nodiscard]] static boost::system::result make( + std::span secret_key, + std::span peer_public_key) noexcept { + if (secret_key.size() != key_size) { + return error::invalid_key_size; + } + if (peer_public_key.size() != key_size) { + return error::invalid_public_key; + } + basic_box made_object; + auto const agreed = engine::init(made_object.state_, secret_key.first(), + peer_public_key.first()); + if (!agreed) { + return agreed.error(); + } + made_object.keyed_ = true; + return made_object; + } + + /** + * Moves the key; the source is wiped and empty. + * + * Moving an empty object gives an empty one. + * + * @param moved_source The source, empty afterwards. + */ + basic_box(basic_box&& moved_source) noexcept + : keyed_(std::exchange(moved_source.keyed_, false)) { + if (keyed_) { + engine::move(state_, moved_source.state_); + } + } + + /** + * Moves the key over this one, which is wiped first; an empty source gives an empty object. + * + * @param moved_source The source, empty afterwards. + * @return This object. + */ + basic_box& operator=(basic_box&& moved_source) noexcept { + if (this != &moved_source) { + engine::reset(state_); + keyed_ = std::exchange(moved_source.keyed_, false); + if (keyed_) { + engine::move(state_, moved_source.state_); + } + } + return *this; + } + + /** Not copyable: a key has one owner, which wipes it. */ + basic_box(basic_box const&) = delete; + /** Not copyable: a key has one owner, which wipes it. */ + basic_box& operator=(basic_box const&) = delete; + + /** Wipes the key. */ + ~basic_box() { engine::reset(state_); } + + /** + * Seals a message in place: `data_bytes` holds the plaintext before and the ciphertext + * after. + * + * The nonce may lie in `data_bytes`: it is read before the first byte is written. + * + * @param iv_bytes The nonce, `iv_size` bytes, never repeated for this pair of keys. + * @param data_bytes The message. + * @return The tag; `invalid_state` moved from; `invalid_iv_size`; `message_too_long`; + * `backend_failure`. + */ + [[nodiscard]] boost::system::result seal( + std::span iv_bytes, std::span data_bytes) noexcept { + auto const guard_result = guard_message(iv_bytes, data_bytes.size(), tag_size); + if (!guard_result) { + return guard_result.error(); + } + result_type tag_bytes{}; + auto const seal_result = + engine::seal(state_, iv_bytes.first(), data_bytes, tag_bytes); + if (!seal_result) { + return seal_result.error(); + } + return tag_bytes; + } + + /** + * Opens a message in place: `data_bytes` holds the ciphertext before and the plaintext + * after. + * + * When the tag does not match, or the backend fails, `data_bytes` is zeroed; a guard's + * refusal leaves it untouched. + * + * @param iv_bytes The nonce of the seal, which may lie in `data_bytes`. + * @param data_bytes The ciphertext. + * @param tag_bytes The seal's tag, `tag_size` bytes, which may lie anywhere, `data_bytes` + * included. + * @return Nothing; `invalid_state` moved from; `invalid_iv_size`; `invalid_tag_size`; + * `message_too_long`; `authentication_failed`; `backend_failure`. + */ + [[nodiscard]] boost::system::result open( + std::span iv_bytes, std::span data_bytes, + std::span tag_bytes) noexcept { + auto const guard_result = guard_message(iv_bytes, data_bytes.size(), tag_bytes.size()); + if (!guard_result) { + return guard_result.error(); + } + // The tag may lie in data, which decryption overwrites: a copy is checked. + std::array expected_tag{}; + std::ranges::copy(tag_bytes, expected_tag.begin()); + auto const open_result = + engine::open(state_, iv_bytes.first(), data_bytes, expected_tag); + if (!open_result) { + detail::wipe(data_bytes.data(), data_bytes.size()); + return open_result.error(); + } + return {}; + } + +private: + basic_box() noexcept = default; + + // Every guard of a message, in the documented order: the state, the nonce, the tag (open's; + // seal passes tag_size), the length. None reads a byte of the spans. + [[nodiscard]] boost::system::result guard_message(std::span iv_bytes, + std::size_t byte_count, + std::size_t tag_bytes) const noexcept { + if (!keyed_) { + return error::invalid_state; + } + if (iv_bytes.size() != iv_size) { + return error::invalid_iv_size; + } + if (tag_bytes != tag_size) { + return error::invalid_tag_size; + } + if (detail::exceeds(byte_count, max_message_size)) { + return error::message_too_long; + } + return {}; + } + + state_type state_{}; + bool keyed_ = false; +}; + +/** `crypto_box`, X25519-XSalsa20-Poly1305, on its default backend: NaCl's box. */ +using box = basic_box<>; + +/** `crypto_box_curve25519xchacha20poly1305`, X25519-XChaCha20-Poly1305, on its default backend. */ +using box_xchacha20poly1305 = basic_box; + +} // namespace webcpp::crypto::hybrid + +namespace webcpp::crypto::detail { + +/** The refusal of a box family on a backend whose header does not specialise its engine. */ +template +struct box_refusal {}; + +/** X25519-XSalsa20-Poly1305's refusal, which names what the program needs. */ +template +struct box_refusal { + WEBCPP_CRYPTO_DETAIL_REFUSE_BOX_XSALSA20POLY1305(Backend); +}; + +/** X25519-XChaCha20-Poly1305's refusal (see the first). */ +template +struct box_refusal { + WEBCPP_CRYPTO_DETAIL_REFUSE_BOX_XCHACHA20POLY1305(Backend); +}; + +/** + * A box's engine on a backend whose header does not specialise it: the family's refusal + * (`detail/capabilities.hpp`). Its functions are never called: the refusal stops the build + * where the class is instantiated, and they keep the compiler from adding errors of their own + * after it; those that return report `backend_failure`, so that a path the refusal missed + * fails closed. + */ +template +struct box_engine : box_refusal { + /** Never called; fails closed. */ + template + [[nodiscard]] static boost::system::result init(Arguments&&... /*arguments*/) noexcept { + return error::backend_failure; + } + + /** Never called; fails closed. */ + template + [[nodiscard]] static boost::system::result seal(Arguments&&... /*arguments*/) noexcept { + return error::backend_failure; + } + + /** Never called; fails closed. */ + template + [[nodiscard]] static boost::system::result open(Arguments&&... /*arguments*/) noexcept { + return error::backend_failure; + } + + /** Never called. */ + template + static void move(Arguments&&... /*arguments*/) noexcept {} + + /** Never called. */ + template + static void reset(Arguments&&... /*arguments*/) noexcept {} +}; + +} // namespace webcpp::crypto::detail + +// The default backend's engines, when the program links it (design D32): libsodium on every +// target. Its header specialises them for this header, wherever it was first included. +#if (defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_BOX_XSALSA20POLY1305_SODIUM) || \ + defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_BOX_XCHACHA20POLY1305_SODIUM)) && \ + defined(WEBCPP_CRYPTO_HAS_SODIUM) +#include +#endif + +#endif // WEBCPP_CRYPTO_HYBRID_BOX_HPP diff --git a/include/webcpp/crypto/hybrid/sealed_box.hpp b/include/webcpp/crypto/hybrid/sealed_box.hpp new file mode 100644 index 00000000..c0638f47 --- /dev/null +++ b/include/webcpp/crypto/hybrid/sealed_box.hpp @@ -0,0 +1,185 @@ +// 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) + +/** + `basic_sealed_box`, libsodium's sealed boxes (`crypto_box_seal`): anonymous encryption to a + public key. `sealed_box` names it on its default backend, libsodium on every target, whose + header this one includes when the program links it; a program that uses it without linking it + stops where it calls it, with the Jamfile line that links it. + + @see "Sealed boxes", in the guide. +*/ +#ifndef WEBCPP_CRYPTO_HYBRID_SEALED_BOX_HPP +#define WEBCPP_CRYPTO_HYBRID_SEALED_BOX_HPP + +#include + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +namespace webcpp::crypto::detail { + +/** + * The work of sealed boxes on a backend, whose specialisation provides `seal(recipient_public_key, + * message, out)` and `open(recipient_public_key, recipient_secret_key, sealed, out)`; the + * primary refuses (defined at the end of this header). + */ +template +struct sealed_box_engine; + +} // namespace webcpp::crypto::detail + +namespace webcpp::crypto::hybrid { + +/** + * Sealed boxes: anonymous encryption to a public key. + * + * `seal` draws a key pair for the message + * (libsodium draws it from its own generator), seals the message in a box from that key pair + * to the recipient's public key, under a nonce derived from the two public keys, and writes + * the drawn public key, the tag and the ciphertext; the drawn secret key is wiped. Only the + * recipient's key pair opens it. The recipient cannot tell who sealed it, and the sender + * cannot open it afterwards: a sealed box proves nothing about who wrote it. + * + * @tparam Backend The backend; by default the family's. + */ +template > +struct basic_sealed_box { + /** The backend. */ + using backend_type = Backend; + /** The family of the capability table, which `supports_v` reads. */ + using family_type = families::sealed_box; + /** The algorithm of the capability table: the family's own tag, its one algorithm. */ + using name_type = families::sealed_box; + /** The size of a public key and of a secret key. */ + static constexpr std::size_t key_size = 32; + /** How much longer a sealed box is than its message: the drawn public key and the tag. */ + static constexpr std::size_t overhead = 48; + + /** + * Seals `message` into `out`, of `message.size() + overhead` bytes: the drawn public key, + * the tag, then the ciphertext. + * + * The message may be the first `message.size()` bytes of + * `out`, sealed in place; it overlaps `out` in no other way, and the key does not. + * + * The sizes are checked first; a refusal of theirs or of the key's leaves `out` untouched. + * A failure of the work zeroes it. + * + * @param recipient_public_key The recipient's X25519 public key, `key_size` bytes. + * @param message The message. + * @param out `message.size() + overhead` bytes. + * @return Nothing; `invalid_input_size` for an `out` of another size; `invalid_public_key` + * for a key of another size; `weak_public_key` for a key of small order; `backend_failure`. + */ + [[nodiscard]] static boost::system::result seal( + std::span recipient_public_key, std::span message, + std::span out) noexcept { + if (out.size() < overhead || out.size() - overhead != message.size()) { + return error::invalid_input_size; + } + if (recipient_public_key.size() != key_size) { + return error::invalid_public_key; + } + auto const sealed = engine::seal(recipient_public_key.first(), message, out); + if (!sealed) { + detail::wipe(out.data(), out.size()); + return sealed.error(); + } + return {}; + } + + /** + * Opens `sealed` into `out`, of `sealed.size() - overhead` bytes, with the recipient's + * keys. + * + * `out` overlaps neither `sealed` nor the keys. + * + * The sizes are checked first; a refusal of theirs or of the keys' leaves `out` untouched. + * When the box does not open, or the backend fails, `out` is zeroed. + * + * @param recipient_public_key The recipient's X25519 public key, `key_size` bytes. + * @param recipient_secret_key The recipient's X25519 secret key, `key_size` bytes. + * @param sealed A sealed box, at least `overhead` bytes. + * @param out `sealed.size() - overhead` bytes. + * @return Nothing; `invalid_input_size` for a `sealed` shorter than `overhead` or an `out` + * of another size; `invalid_public_key`; `invalid_key_size`; `authentication_failed` when + * the box was not sealed to this key pair, or was changed; `backend_failure`. + */ + [[nodiscard]] static boost::system::result open( + std::span recipient_public_key, + std::span recipient_secret_key, std::span sealed, + std::span out) noexcept { + if (sealed.size() < overhead || out.size() != sealed.size() - overhead) { + return error::invalid_input_size; + } + if (recipient_public_key.size() != key_size) { + return error::invalid_public_key; + } + if (recipient_secret_key.size() != key_size) { + return error::invalid_key_size; + } + auto const opened = engine::open(recipient_public_key.first(), + recipient_secret_key.first(), sealed, out); + if (!opened) { + detail::wipe(out.data(), out.size()); + return opened.error(); + } + return {}; + } + +private: + using engine = detail::sealed_box_engine; +}; + +/** Sealed boxes on their default backend. */ +using sealed_box = basic_sealed_box<>; + +} // namespace webcpp::crypto::hybrid + +namespace webcpp::crypto::detail { + +/** + * The sealed boxes' engine on a backend whose header does not specialise it: the family's + * refusal (`detail/capabilities.hpp`). Its functions are never called: the refusal stops the + * build where the class is instantiated, and they keep the compiler from adding errors of their + * own after it; they report `backend_failure`, so that a path the refusal missed fails closed. + */ +template +struct sealed_box_engine { + WEBCPP_CRYPTO_DETAIL_REFUSE_SEALED_BOX(Backend); + + /** Never called; fails closed. */ + template + [[nodiscard]] static boost::system::result seal(Arguments&&... /*arguments*/) noexcept { + return error::backend_failure; + } + + /** Never called; fails closed. */ + template + [[nodiscard]] static boost::system::result open(Arguments&&... /*arguments*/) noexcept { + return error::backend_failure; + } +}; + +} // namespace webcpp::crypto::detail + +// The default backend's engine, when the program links it (design D32): libsodium on every +// target. Its header specialises it for this header, wherever it was first included. +#if defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_SEALED_BOX_SODIUM) && defined(WEBCPP_CRYPTO_HAS_SODIUM) +#include +#endif + +#endif // WEBCPP_CRYPTO_HYBRID_SEALED_BOX_HPP diff --git a/test/Jamfile b/test/Jamfile index b6681311..04c242e9 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -33,7 +33,8 @@ webcpp.headers-alone crypto : ../include : crypto.hpp crypto/config.hpp crypto/detail/engines.hpp crypto/detail/entropy.hpp crypto/detail/limits.hpp crypto/detail/windows.hpp crypto/detail/wipe.hpp crypto/secret.hpp crypto/supports.hpp crypto/detail/capabilities.hpp crypto/detail/defaults.hpp - crypto/detail/heavy.hpp crypto/ciphers/aead.hpp crypto/ciphers/chacha20_poly1305.hpp ; + crypto/detail/heavy.hpp crypto/ciphers/aead.hpp crypto/ciphers/chacha20_poly1305.hpp + crypto/ciphers/secretbox.hpp ; # The backend BearSSL's header and the default backend's, with BearSSL linked, # on every target. @@ -52,10 +53,11 @@ webcpp.headers-alone crypto : ../include : crypto/backends/openssl.hpp # The backend ctaes's header alone, with ctaes linked, on every target. webcpp.headers-alone crypto : ../include : crypto/backends/ctaes.hpp : /third_party//ctaes ; -# The backend libsodium's header alone, and Ed25519's and X25519's with it, -# with libsodium linked, on every target. +# The backend libsodium's header alone, and Ed25519's, X25519's, the boxes' and +# the sealed boxes' with it, with libsodium linked, on every target. webcpp.headers-alone crypto : ../include : crypto/backends/sodium.hpp crypto/curves/ed25519.hpp crypto/curves/x25519.hpp + crypto/hybrid/box.hpp crypto/hybrid/sealed_box.hpp : /third_party//sodium ; # libsecp256k1's headers compile alone only with its library, which defines # WEBCPP_CRYPTO_HAS_SECP256K1 (without it, each stops with its message). @@ -334,6 +336,14 @@ crypto-run chacha_wycheproof_sodium : chacha_wycheproof_sodium_test.cpp /webcpp//boost_json ; crypto-run allocation_sodium : allocation_sodium_test.cpp : /third_party//sodium ; +# libsodium's boxes, its default on every target: crypto_secretbox and its XChaCha20 twin, +# libsodium's cases and every check of support/aead_checks.hpp that applies to a family +# without additional data; hybrid::box and its XChaCha20 twin, NaCl's case both ways, the same +# checks through an adapter, make's guards and a peer key of small order; and sealed boxes, +# opened by their recipient alone and refused, the output zeroed, otherwise. +crypto-run secretbox_sodium : secretbox_sodium_test.cpp : /third_party//sodium ; +crypto-run box_sodium : box_sodium_test.cpp : /third_party//sodium ; + # 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. @@ -453,6 +463,21 @@ webcpp.compile doc_chacha20_poly1305_original_default_app webcpp.compile doc_xchacha20_poly1305_default_app : ../../../tools/test/fixtures/crypto_jamfiles/xchacha20_poly1305_default/app.cpp : /webcpp/crypto//xchacha20_poly1305-default ; +webcpp.compile doc_secretbox_xsalsa20poly1305_default_app + : ../../../tools/test/fixtures/crypto_jamfiles/secretbox_xsalsa20poly1305_default/app.cpp + : /webcpp/crypto//secretbox_xsalsa20poly1305-default ; +webcpp.compile doc_secretbox_xchacha20poly1305_default_app + : ../../../tools/test/fixtures/crypto_jamfiles/secretbox_xchacha20poly1305_default/app.cpp + : /webcpp/crypto//secretbox_xchacha20poly1305-default ; +webcpp.compile doc_box_xsalsa20poly1305_default_app + : ../../../tools/test/fixtures/crypto_jamfiles/box_xsalsa20poly1305_default/app.cpp + : /webcpp/crypto//box_xsalsa20poly1305-default ; +webcpp.compile doc_box_xchacha20poly1305_default_app + : ../../../tools/test/fixtures/crypto_jamfiles/box_xchacha20poly1305_default/app.cpp + : /webcpp/crypto//box_xchacha20poly1305-default ; +webcpp.compile doc_sealed_box_default_app + : ../../../tools/test/fixtures/crypto_jamfiles/sealed_box_default/app.cpp + : /webcpp/crypto//sealed_box-default ; webcpp.compile doc_openssl_linked : ../../../tools/test/fixtures/crypto_jamfiles/openssl_linked/app.cpp : /webcpp/crypto//openssl : native wasip2 wasip3 ; diff --git a/test/allocation_sodium_test.cpp b/test/allocation_sodium_test.cpp index 518ad59b..eaefc8f1 100644 --- a/test/allocation_sodium_test.cpp +++ b/test/allocation_sodium_test.cpp @@ -4,17 +4,21 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// On libsodium nothing allocates: make, seal and open of the three ChaCha20-Poly1305 AEADs, -// a failed open included; Ed25519's key pair, signature, strict verification, Ed25519ph and -// the conversion to X25519; and X25519's public key and agreement, a refused one included, -// 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. Each later family on libsodium adds -// its calls here. +// On libsodium nothing allocates: make, seal and open of the three ChaCha20-Poly1305 AEADs and +// of the two secret boxes, a failed open included; Ed25519's key pair, signature, strict +// verification, Ed25519ph and the conversion to X25519; X25519's public key and agreement, a +// refused one included; the two boxes' make, seal and open, a refused peer key and a failed open +// included; and the sealed boxes' seal and open, a failed open included, 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. Each later family on libsodium adds its calls here. #include #include +#include #include #include +#include +#include #include #include @@ -34,13 +38,18 @@ namespace { namespace crypto = webcpp::crypto; -/** Makes an AEAD, seals, opens, and opens a forged message: none of it allocates. */ +/** + * Makes an AEAD, seals, opens, and opens a forged message: none of it allocates. A family + * without additional data (a secret box) is given none. + */ template void expect_no_allocation() { std::array key{}; key.fill(3); std::array const iv{}; - std::array const additional_data{}; + std::array const some_additional_data{}; + auto const additional_data = std::span(some_additional_data) + .first(Aead::max_additional_data_size == 0 ? 0 : 13); std::array data{}; std::size_t const before = webcpp::test::allocations(); { @@ -135,6 +144,67 @@ void expect_no_allocation_x25519() { BOOST_TEST_EQ(webcpp::test::allocations(), before); } +/** + * Makes a box of each family from two key pairs, both ways, seals, opens, opens a forged + * message, and refuses a peer key of small order (the all-zero point): none of it allocates. + */ +template +void expect_no_allocation_box() { + std::array alice{}; + alice.fill(7); + std::array bob{}; + bob.fill(9); + std::array const low_order{}; + std::array const iv{}; + std::array data{}; + auto const alice_public = crypto::curves::x25519::public_key(alice); + auto const bob_public = crypto::curves::x25519::public_key(bob); + if (!BOOST_TEST(alice_public.has_value()) || !BOOST_TEST(bob_public.has_value())) { + return; + } + std::size_t const before = webcpp::test::allocations(); + { + auto sender = Box::make(alice, *bob_public); + auto receiver = Box::make(bob, *alice_public); + BOOST_TEST(sender.has_value() && receiver.has_value()); + auto const tag = sender->seal(iv, data); + BOOST_TEST(tag.has_value()); + BOOST_TEST(receiver->open(iv, data, *tag).has_value()); + std::array const forged{}; + BOOST_TEST(receiver->open(iv, data, forged).error() == + crypto::error::authentication_failed); + BOOST_TEST(Box::make(alice, low_order).error() == crypto::error::weak_public_key); + Box const moved = std::move(*sender); + } + BOOST_TEST_EQ(webcpp::test::allocations(), before); +} + +/** + * Seals a message to a public key, which draws a key pair from libsodium's generator, opens it, + * and opens a changed one: none of it allocates. + */ +void expect_no_allocation_sealed_box() { + using sealed_box = crypto::hybrid::basic_sealed_box; + std::array bob{}; + bob.fill(11); + auto const bob_public = crypto::curves::x25519::public_key(bob); + if (!BOOST_TEST(bob_public.has_value())) { + return; + } + std::array const message{}; + std::array sealed{}; + std::array opened{}; + std::size_t const before = webcpp::test::allocations(); + { + BOOST_TEST(sealed_box::seal(*bob_public, message, sealed).has_value()); + BOOST_TEST(sealed_box::open(*bob_public, bob, sealed, opened).has_value()); + sealed[40] ^= 1U; + BOOST_TEST(sealed_box::open(*bob_public, bob, sealed, opened).error() == + crypto::error::authentication_failed); + } + BOOST_TEST_EQ(webcpp::test::allocations(), before); +} + } // namespace int main() { @@ -155,5 +225,12 @@ int main() { expect_no_allocation>(); expect_no_allocation_ed25519(); expect_no_allocation_x25519(); + expect_no_allocation>(); + expect_no_allocation>(); + expect_no_allocation_box>(); + expect_no_allocation_box>(); + expect_no_allocation_sealed_box(); return webcpp::test::exit_status(boost::report_errors()); } diff --git a/test/box_sodium_test.cpp b/test/box_sodium_test.cpp new file mode 100644 index 00000000..50e01746 --- /dev/null +++ b/test/box_sodium_test.cpp @@ -0,0 +1,422 @@ +// 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) + +// hybrid::box, crypto_box, and hybrid::sealed_box, crypto_box_seal, on libsodium, their default +// on every target. +// +// The box: NaCl's case of libsodium's test/default/box.c and box2.c, Alice's secret key with +// Bob's public key and Bob's with Alice's, which box.exp and box2.exp show give one ciphertext +// and tag; the same keys, nonce and message under XChaCha20-Poly1305 +// (crypto_box_curve25519xchacha20poly1305), whose ciphertext and tag libsodium's tests do not +// print and which an independent implementation of X25519, HChaCha20, ChaCha20 and Poly1305 +// computed (checked against libsodium's own XChaCha20 secret boxes and RFC 7748); every check +// of support/aead_checks.hpp that applies to an object with no additional data, made of a +// secret key and a peer's public key (ruling C35); the guards of make; a peer key of small +// order refused with weak_public_key, as libsodium's beforenm refuses it; and the box as the +// secret box under its precomputed key. +// +// The sealed box: libsodium's test/default/box_seal.c, a message sealed to a public key and +// opened by its recipient, sealed in place, refused (authentication_failed, the output zeroed) +// with another key pair, with the keys swapped, after any byte of it changes and one byte +// shorter; two seals of one message differ; the sizes checked first, then the keys. + +#include +#include +#include +#include +#include +#include + +#include "support/aead_checks.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace crypto = webcpp::crypto; +namespace hybrid = webcpp::crypto::hybrid; +using webcpp::test::from_hex; +using webcpp::test::to_hex; + +namespace { + +using hybrid::box; +using box_xchacha = hybrid::box_xchacha20poly1305; +using hybrid::sealed_box; + +static_assert(std::is_same_v, + crypto::backends::sodium>); +static_assert(std::is_same_v, + crypto::backends::sodium>); +static_assert(std::is_same_v, + crypto::backends::sodium>); +static_assert(std::is_same_v>); +static_assert(std::is_same_v>); +static_assert(std::is_same_v>); +static_assert(std::is_same_v); +static_assert(std::is_same_v); +static_assert(std::is_same_v); +static_assert(std::is_same_v); +static_assert(crypto::supports_v); +static_assert(crypto::supports_v); +static_assert(crypto::supports_v); +static_assert(box::key_size == 32 && box::iv_size == 24 && box::tag_size == 16); +static_assert(box_xchacha::key_size == 32 && box_xchacha::iv_size == 24 && + box_xchacha::tag_size == 16); +static_assert(sealed_box::overhead == 48); +// Move-only: the precomputed key has one owner, which wipes it. +static_assert(!std::is_copy_constructible_v && !std::is_copy_assignable_v); +static_assert(std::is_nothrow_move_constructible_v && std::is_nothrow_move_assignable_v); + +/** + * NaCl's keys and nonce (libsodium's test/default/box.c and box2.c): Alice's secret key and + * Bob's public key; the cases below hold Bob's secret key and Alice's public key too. + */ +constexpr std::string_view alice_secret = + "77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a"; +constexpr std::string_view bob_public = + "de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f"; +constexpr std::string_view nonce = "69696ee955b62b73cd62bda875fc73d68219e0036b7a0b37"; +/** box.c's message after its 32 zero bytes, which box2.exp prints opened. */ +constexpr std::string_view message = + "be075fc53c81f2d5cf141316ebeb0c7b5228c52a4c62cbd44b66849b64244ffce5ecbaaf33bd751a1ac728d45e" + "6c61296cdc3c01233561f41db66cce314adb310e3be8250c46f06dceea3a7fa1348057e2f6556ad6b1318a024a" + "838f21af1fde048977eb48f59ffd4924ca1c60902e52f0a089bc76897040e082f937763848645e0705"; +/** A public key of small order, box.c's small_order_p. */ +constexpr std::string_view small_order = + "e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b800"; + +/** + * NaCl's box, Alice to Bob (box.exp: the tag, then the ciphertext) and Bob opening it with his + * secret key and Alice's public key (box2.exp). An aead_case's key is the secret key followed + * by the peer's public key. + */ +constexpr std::array box_cases{ + webcpp::test::aead_case{ + .key = "77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a" + "de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f", + .iv = nonce, + .additional_data = "", + .plaintext = message, + .ciphertext = + "8e993b9f48681273c29650ba32fc76ce48332ea7164d96a4476fb8c531a1186ac0dfc17c98dce87b4da7" + "f011ec48c97271d2c20f9b928fe2270d6fb863d51738b48eeee314a7cc8ab932164548e526ae90224368" + "517acfeabd6bb3732bc0e9da99832b61ca01b6de56244a9e88d5f9b37973f622a43d14a6599b1f654cb4" + "5a74e355a5", + .tag = "f3ffc7703f9400e52a7dfb4b3d3305d9", + }, + webcpp::test::aead_case{ + .key = "5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb" + "8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a", + .iv = nonce, + .additional_data = "", + .plaintext = message, + .ciphertext = + "8e993b9f48681273c29650ba32fc76ce48332ea7164d96a4476fb8c531a1186ac0dfc17c98dce87b4da7" + "f011ec48c97271d2c20f9b928fe2270d6fb863d51738b48eeee314a7cc8ab932164548e526ae90224368" + "517acfeabd6bb3732bc0e9da99832b61ca01b6de56244a9e88d5f9b37973f622a43d14a6599b1f654cb4" + "5a74e355a5", + .tag = "f3ffc7703f9400e52a7dfb4b3d3305d9", + }, +}; + +/** + * The same keys, nonce and message in crypto_box_curve25519xchacha20poly1305, both ways: the + * independent implementation's ciphertext and tag. Its precomputed key, HChaCha20 of the X25519 + * shared secret under a zero nonce, is box_xchacha_key. + */ +constexpr std::array box_xchacha_cases{ + webcpp::test::aead_case{ + .key = "77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a" + "de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f", + .iv = nonce, + .additional_data = "", + .plaintext = message, + .ciphertext = + "ef2c6061b7bcec0cfd723055f61f1ccca2946d5a04dbf83151f4894223ac9bc790c660e19dc64cc0d7f9" + "c7689ad1909955e7a9a7bdac777d6a7967d000ce841fc0f8f31d6d8720b374bc28982764a7dbeb4daa97" + "7aae1b7350fac79a177ece7541fed264461ea93e6d7ad9fc08c91e774abe79036e7f79ddcc6aab3abf52" + "7631048ce1", + .tag = "0b4ff00742f3c1aa99a6321e3883b03c", + }, + webcpp::test::aead_case{ + .key = "5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb" + "8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a", + .iv = nonce, + .additional_data = "", + .plaintext = message, + .ciphertext = + "ef2c6061b7bcec0cfd723055f61f1ccca2946d5a04dbf83151f4894223ac9bc790c660e19dc64cc0d7f9" + "c7689ad1909955e7a9a7bdac777d6a7967d000ce841fc0f8f31d6d8720b374bc28982764a7dbeb4daa97" + "7aae1b7350fac79a177ece7541fed264461ea93e6d7ad9fc08c91e774abe79036e7f79ddcc6aab3abf52" + "7631048ce1", + .tag = "0b4ff00742f3c1aa99a6321e3883b03c", + }, +}; + +/** NaCl's precomputed key of Alice and Bob, secretbox.c's "firstkey". */ +constexpr std::string_view box_key = + "1b27556473e985d462cd51197a9a46c76009549eac6474f206c4ee0844f68389"; +/** Their precomputed key in crypto_box_curve25519xchacha20poly1305. */ +constexpr std::string_view box_xchacha_key = + "8e47ca376bdc7e59d2ced8107ceb2c27f4a80e8575f996baffb1a869ffcd5179"; + +/** + * How the checks of support/aead_checks.hpp reach a box: its "key" is the secret key followed + * by the peer's public key, 64 bytes, and it has no additional data, which its calls do not + * take (the checks pass none). + */ +template +struct box_calls { + using object = Box; + static constexpr std::size_t key_size = 64; + static constexpr std::size_t iv_size = Box::iv_size; + static constexpr std::size_t tag_size = Box::tag_size; + static constexpr bool has_additional_data = false; + static constexpr bool takes_additional_data = false; + static constexpr bool one_key = false; + + static auto make(std::span key) { + auto const split = std::min(key.size(), 32); + return Box::make(key.first(split), key.subspan(split)); + } + + static auto seal(Box& made, std::span iv, + std::span additional_data, std::span data) { + BOOST_TEST(additional_data.empty()); + return made.seal(iv, data); + } + + static auto open(Box& made, std::span iv, + std::span additional_data, std::span data, + std::span tag) { + BOOST_TEST(additional_data.empty()); + return made.open(iv, data, tag); + } +}; + +/** + * make's guards: the secret key's size (invalid_key_size) before the peer key's + * (invalid_public_key); a peer key of small order, as libsodium's beforenm refuses it + * (weak_public_key), and the all-zero point. + */ +template +void check_box_make() { + auto const secret = from_hex(alice_secret); + auto const peer = from_hex(bob_public); + for (std::size_t const size : {std::size_t{0}, std::size_t{31}, std::size_t{33}}) { + std::vector const wrong(size, 7); + BOOST_TEST(Box::make(wrong, peer).error() == crypto::error::invalid_key_size); + BOOST_TEST(Box::make(secret, wrong).error() == crypto::error::invalid_public_key); + BOOST_TEST(Box::make(wrong, wrong).error() == crypto::error::invalid_key_size); + } + BOOST_TEST(Box::make(secret, from_hex(small_order)).error() == crypto::error::weak_public_key); + std::array const zero{}; + BOOST_TEST(Box::make(secret, zero).error() == crypto::error::weak_public_key); + BOOST_TEST(Box::make(secret, peer).has_value()); +} + +/** + * A box is the secret box of the same construction under its precomputed key: libsodium's + * crypto_box_afternm is crypto_secretbox, and its XChaCha20 twin the XChaCha20 secret box. + */ +template +void check_box_is_secretbox(std::string_view key) { + auto made_box = Box::make(from_hex(alice_secret), from_hex(bob_public)); + auto made_secretbox = Secretbox::make(from_hex(key)); + if (!BOOST_TEST(made_box.has_value()) || !BOOST_TEST(made_secretbox.has_value())) { + return; + } + auto const iv = from_hex(nonce); + auto by_box = from_hex(message); + auto by_secretbox = by_box; + auto const box_tag = made_box->seal(iv, by_box); + auto const secretbox_tag = made_secretbox->seal(iv, {}, by_secretbox); + BOOST_TEST(box_tag && secretbox_tag && to_hex(*box_tag) == to_hex(*secretbox_tag)); + BOOST_TEST(by_box == by_secretbox); +} + +/** A recipient's key pair: its secret key's bytes all `fill`, and its X25519 public key. */ +struct recipient { + std::array secret_key{}; + std::array public_key{}; + + explicit recipient(std::uint8_t fill) { + secret_key.fill(fill); + auto const made = crypto::curves::x25519::public_key(secret_key); + BOOST_TEST(made.has_value()); + if (made) { + public_key = *made; + } + } +}; + +/** A message of `size` bytes counting up from 3. */ +std::vector sealed_message(std::size_t size) { + std::vector bytes(size); + for (std::size_t i = 0; i < size; ++i) { + bytes[i] = static_cast((i * 5) + 3); + } + return bytes; +} + +/** + * An open that fails with authentication_failed and zeroes its output, filled beforehand with + * a pattern that is not zero. + */ +void expect_sealed_refused(std::span public_key, + std::span secret_key, + std::span sealed) { + std::vector out(sealed.size() - sealed_box::overhead, 0x77); + BOOST_TEST(sealed_box::open(public_key, secret_key, sealed, out).error() == + crypto::error::authentication_failed); + BOOST_TEST(webcpp::test::all_zero(out)); +} + +/** + * libsodium's tv1: a message sealed to a public key opens with the recipient's key pair alone; + * another key pair, the keys swapped, any byte changed and a sealed box one byte shorter are + * refused, the output zeroed; two seals of one message differ, each carrying its own ephemeral + * public key first. + */ +void check_sealed_box() { + recipient const bob(0x11); + recipient const eve(0x22); + auto const plain = sealed_message(100); + std::vector sealed(plain.size() + sealed_box::overhead); + BOOST_TEST(sealed_box::seal(bob.public_key, plain, sealed).has_value()); + BOOST_TEST(!std::equal(bob.public_key.begin(), bob.public_key.end(), sealed.begin())); + std::vector opened(plain.size()); + BOOST_TEST(sealed_box::open(bob.public_key, bob.secret_key, sealed, opened).has_value()); + BOOST_TEST(opened == plain); + // Another seal of the same message, under another ephemeral key pair. + std::vector again(sealed.size()); + BOOST_TEST(sealed_box::seal(bob.public_key, plain, again).has_value()); + BOOST_TEST(again != sealed); + BOOST_TEST(!std::equal(again.begin(), again.begin() + 32, sealed.begin())); + // Another key pair, Eve's secret key with Bob's public key, and Bob's keys swapped. + expect_sealed_refused(eve.public_key, eve.secret_key, sealed); + expect_sealed_refused(bob.public_key, eve.secret_key, sealed); + expect_sealed_refused(eve.public_key, bob.secret_key, sealed); + expect_sealed_refused(bob.secret_key, bob.public_key, sealed); + // Any byte changed: the ephemeral public key, the tag or the ciphertext. + for (std::size_t i = 0; i < sealed.size(); ++i) { + auto changed = sealed; + changed[i] ^= 0x40U; + expect_sealed_refused(bob.public_key, bob.secret_key, changed); + } + // One byte shorter. + expect_sealed_refused(bob.public_key, bob.secret_key, + std::span(sealed).first(sealed.size() - 1)); + // The refusals end nothing: the sealed box still opens. + BOOST_TEST(sealed_box::open(bob.public_key, bob.secret_key, sealed, opened).has_value()); + BOOST_TEST(opened == plain); +} + +/** + * libsodium's tv2: a message sealed in place, at the start of the output, opens. An empty + * message seals into the overhead alone and opens into an empty span. + */ +void check_sealed_box_edges() { + recipient const bob(0x33); + auto const plain = sealed_message(57); + std::vector buffer(plain.size() + sealed_box::overhead); + std::ranges::copy(plain, buffer.begin()); + BOOST_TEST(sealed_box::seal(bob.public_key, std::span(buffer).first(plain.size()), buffer) + .has_value()); + std::vector opened(plain.size()); + BOOST_TEST(sealed_box::open(bob.public_key, bob.secret_key, buffer, opened).has_value()); + BOOST_TEST(opened == plain); + std::array empty_sealed{}; + BOOST_TEST(sealed_box::seal(bob.public_key, {}, empty_sealed).has_value()); + BOOST_TEST( + sealed_box::open(bob.public_key, bob.secret_key, empty_sealed, std::span()) + .has_value()); + empty_sealed[40] ^= 1U; + BOOST_TEST( + sealed_box::open(bob.public_key, bob.secret_key, empty_sealed, std::span()) + .error() == crypto::error::authentication_failed); +} + +/** + * The guards, in their order: the sizes first (invalid_input_size: an output not of the + * message's size plus the overhead, a sealed box shorter than the overhead, an output not of + * its size less the overhead), then the keys (invalid_public_key, invalid_key_size); each + * refusal leaves the output untouched. A recipient key of small order is refused when sealing + * (weak_public_key), the output zeroed. + */ +void check_sealed_box_guards() { + recipient const bob(0x44); + auto const plain = sealed_message(10); + std::vector out(plain.size() + sealed_box::overhead, 0x55); + auto const untouched = out; + std::vector const short_key(31, 9); + for (std::size_t const size : + {std::size_t{0}, std::size_t{47}, plain.size() + 47, plain.size() + 49}) { + std::vector wrong(size, 0x55); + auto const wrong_untouched = wrong; + BOOST_TEST(sealed_box::seal(bob.public_key, plain, wrong).error() == + crypto::error::invalid_input_size); + BOOST_TEST(sealed_box::seal(short_key, plain, wrong).error() == + crypto::error::invalid_input_size); + BOOST_TEST(wrong == wrong_untouched); + } + BOOST_TEST(sealed_box::seal(short_key, plain, out).error() == + crypto::error::invalid_public_key); + BOOST_TEST(out == untouched); + BOOST_TEST(sealed_box::seal(bob.public_key, plain, out).has_value()); + auto const sealed = out; + std::vector opened(plain.size(), 0x66); + auto const opened_untouched = opened; + // A sealed box shorter than the overhead, and outputs of other sizes than it holds. + for (std::size_t const size : {std::size_t{0}, std::size_t{47}}) { + std::vector const too_short(size, 1); + BOOST_TEST( + sealed_box::open(bob.public_key, bob.secret_key, too_short, std::span()) + .error() == crypto::error::invalid_input_size); + } + for (std::size_t const size : {std::size_t{0}, plain.size() - 1, plain.size() + 1}) { + std::vector wrong(size, 0x66); + BOOST_TEST(sealed_box::open(bob.public_key, bob.secret_key, sealed, wrong).error() == + crypto::error::invalid_input_size); + BOOST_TEST(sealed_box::open(short_key, short_key, sealed, wrong).error() == + crypto::error::invalid_input_size); + } + BOOST_TEST(sealed_box::open(short_key, bob.secret_key, sealed, opened).error() == + crypto::error::invalid_public_key); + BOOST_TEST(sealed_box::open(bob.public_key, short_key, sealed, opened).error() == + crypto::error::invalid_key_size); + BOOST_TEST(opened == opened_untouched); + // A recipient key of small order: libsodium's box refuses it, and the output is zeroed. + BOOST_TEST(sealed_box::seal(from_hex(small_order), plain, out).error() == + crypto::error::weak_public_key); + BOOST_TEST(webcpp::test::all_zero(out)); +} + +} // namespace + +int main() { + webcpp::test::check_aead_with>(box_cases); + webcpp::test::check_aead_with>(box_xchacha_cases); + check_box_make(); + check_box_make(); + check_box_is_secretbox>(box_key); + check_box_is_secretbox>( + box_xchacha_key); + check_sealed_box(); + check_sealed_box_edges(); + check_sealed_box_guards(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/capabilities_test.cpp b/test/capabilities_test.cpp index a6cd0d33..76a03122 100644 --- a/test/capabilities_test.cpp +++ b/test/capabilities_test.cpp @@ -16,9 +16,12 @@ #include #include #include +#include #include #include #include +#include +#include #include #include @@ -106,6 +109,36 @@ struct refuses_xchacha20_poly1305 { WEBCPP_CRYPTO_DETAIL_REFUSE_XCHACHA20_POLY1305(Backend); }; +/** The refusals of XSalsa20-Poly1305 secret box, parsed: nothing instantiates it. */ +template +struct refuses_secretbox_xsalsa20poly1305 { + WEBCPP_CRYPTO_DETAIL_REFUSE_SECRETBOX_XSALSA20POLY1305(Backend); +}; + +/** The refusals of XChaCha20-Poly1305 secret box, parsed: nothing instantiates it. */ +template +struct refuses_secretbox_xchacha20poly1305 { + WEBCPP_CRYPTO_DETAIL_REFUSE_SECRETBOX_XCHACHA20POLY1305(Backend); +}; + +/** The refusals of X25519-XSalsa20-Poly1305 box, parsed: nothing instantiates it. */ +template +struct refuses_box_xsalsa20poly1305 { + WEBCPP_CRYPTO_DETAIL_REFUSE_BOX_XSALSA20POLY1305(Backend); +}; + +/** The refusals of X25519-XChaCha20-Poly1305 box, parsed: nothing instantiates it. */ +template +struct refuses_box_xchacha20poly1305 { + WEBCPP_CRYPTO_DETAIL_REFUSE_BOX_XCHACHA20POLY1305(Backend); +}; + +/** The refusals of X25519-XSalsa20-Poly1305 sealed box, parsed: nothing instantiates it. */ +template +struct refuses_sealed_box { + WEBCPP_CRYPTO_DETAIL_REFUSE_SEALED_BOX(Backend); +}; + } // namespace // clang-format off @@ -298,6 +331,76 @@ static_assert(crypto::supports_v, backends::sodium>); #endif +// XSalsa20-Poly1305 secret box on bearssl: none. +static_assert(!crypto::supports_v, backends::bearssl>); +// XSalsa20-Poly1305 secret box on openssl: none. +static_assert(!crypto::supports_v, backends::openssl>); +// XSalsa20-Poly1305 secret box on ctaes: none. +static_assert(!crypto::supports_v, backends::ctaes>); +// XSalsa20-Poly1305 secret box on secp256k1: none. +static_assert(!crypto::supports_v, backends::secp256k1>); +// XSalsa20-Poly1305 secret box on sodium: native, wasip2, wasip3, emscripten. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_v, backends::sodium>); +#else +static_assert(!crypto::supports_v, backends::sodium>); +#endif +// XChaCha20-Poly1305 secret box on bearssl: none. +static_assert(!crypto::supports_v, backends::bearssl>); +// XChaCha20-Poly1305 secret box on openssl: none. +static_assert(!crypto::supports_v, backends::openssl>); +// XChaCha20-Poly1305 secret box on ctaes: none. +static_assert(!crypto::supports_v, backends::ctaes>); +// XChaCha20-Poly1305 secret box on secp256k1: none. +static_assert(!crypto::supports_v, backends::secp256k1>); +// XChaCha20-Poly1305 secret box on sodium: native, wasip2, wasip3, emscripten. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_v, backends::sodium>); +#else +static_assert(!crypto::supports_v, backends::sodium>); +#endif +// X25519-XSalsa20-Poly1305 box on bearssl: none. +static_assert(!crypto::supports_v, backends::bearssl>); +// X25519-XSalsa20-Poly1305 box on openssl: none. +static_assert(!crypto::supports_v, backends::openssl>); +// X25519-XSalsa20-Poly1305 box on ctaes: none. +static_assert(!crypto::supports_v, backends::ctaes>); +// X25519-XSalsa20-Poly1305 box on secp256k1: none. +static_assert(!crypto::supports_v, backends::secp256k1>); +// X25519-XSalsa20-Poly1305 box on sodium: native, wasip2, wasip3, emscripten. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_v, backends::sodium>); +#else +static_assert(!crypto::supports_v, backends::sodium>); +#endif +// X25519-XChaCha20-Poly1305 box on bearssl: none. +static_assert(!crypto::supports_v, backends::bearssl>); +// X25519-XChaCha20-Poly1305 box on openssl: none. +static_assert(!crypto::supports_v, backends::openssl>); +// X25519-XChaCha20-Poly1305 box on ctaes: none. +static_assert(!crypto::supports_v, backends::ctaes>); +// X25519-XChaCha20-Poly1305 box on secp256k1: none. +static_assert(!crypto::supports_v, backends::secp256k1>); +// X25519-XChaCha20-Poly1305 box on sodium: native, wasip2, wasip3, emscripten. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_v, backends::sodium>); +#else +static_assert(!crypto::supports_v, backends::sodium>); +#endif +// X25519-XSalsa20-Poly1305 sealed box on bearssl: none. +static_assert(!crypto::supports_v, backends::bearssl>); +// X25519-XSalsa20-Poly1305 sealed box on openssl: none. +static_assert(!crypto::supports_v, backends::openssl>); +// X25519-XSalsa20-Poly1305 sealed box on ctaes: none. +static_assert(!crypto::supports_v, backends::ctaes>); +// X25519-XSalsa20-Poly1305 sealed box on secp256k1: none. +static_assert(!crypto::supports_v, backends::secp256k1>); +// X25519-XSalsa20-Poly1305 sealed box on sodium: native, wasip2, wasip3, emscripten. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_v, backends::sodium>); +#else +static_assert(!crypto::supports_v, backends::sodium>); +#endif // clang-format on int main() { @@ -364,6 +467,21 @@ int main() { #endif #if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN)) && defined(WEBCPP_CRYPTO_HAS_SODIUM) BOOST_TEST((webcpp::test::made, families::xchacha20_poly1305, families::xchacha20_poly1305, backends::sodium>())); +#endif +#if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN)) && defined(WEBCPP_CRYPTO_HAS_SODIUM) + BOOST_TEST((webcpp::test::made, families::secretbox_xsalsa20poly1305, families::secretbox_xsalsa20poly1305, backends::sodium>())); +#endif +#if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN)) && defined(WEBCPP_CRYPTO_HAS_SODIUM) + BOOST_TEST((webcpp::test::made, families::secretbox_xchacha20poly1305, families::secretbox_xchacha20poly1305, backends::sodium>())); +#endif +#if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN)) && defined(WEBCPP_CRYPTO_HAS_SODIUM) + BOOST_TEST((webcpp::test::made, families::box_xsalsa20poly1305, families::box_xsalsa20poly1305, backends::sodium>())); +#endif +#if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN)) && defined(WEBCPP_CRYPTO_HAS_SODIUM) + BOOST_TEST((webcpp::test::made, families::box_xchacha20poly1305, families::box_xchacha20poly1305, backends::sodium>())); +#endif +#if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN)) && defined(WEBCPP_CRYPTO_HAS_SODIUM) + BOOST_TEST((webcpp::test::made, families::sealed_box, families::sealed_box, backends::sodium>())); #endif // clang-format on return webcpp::test::exit_status(boost::report_errors()); diff --git a/test/default_backend_test.cpp b/test/default_backend_test.cpp index c54e8496..7138eab2 100644 --- a/test/default_backend_test.cpp +++ b/test/default_backend_test.cpp @@ -93,3 +93,31 @@ static_assert(crypto::detail::supported, + backends::sodium>); +static_assert(std::is_same_v, + backends::sodium>); +static_assert( + std::is_same_v, backends::sodium>); +static_assert( + std::is_same_v, backends::sodium>); +static_assert(std::is_same_v, backends::sodium>); +static_assert(crypto::detail::supported); +static_assert(crypto::detail::supported); +static_assert(crypto::detail::supported); +static_assert(crypto::detail::supported); +static_assert( + crypto::detail::supported); +#if !defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_SECRETBOX_XSALSA20POLY1305_SODIUM) || \ + !defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_SECRETBOX_XCHACHA20POLY1305_SODIUM) || \ + !defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_BOX_XSALSA20POLY1305_SODIUM) || \ + !defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_BOX_XCHACHA20POLY1305_SODIUM) || \ + !defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_SEALED_BOX_SODIUM) +#error "secretbox.hpp, box.hpp and sealed_box.hpp are not told to include libsodium's header" +#endif diff --git a/test/messages/Jamfile b/test/messages/Jamfile index 13e12a2f..d1493cd9 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -32,3 +32,4 @@ build-project heavy_without_threads ; build-project chacha_default_not_linked ; build-project aead_not_a_family ; build-project chacha_on_ctaes ; +build-project box_default_not_linked ; diff --git a/test/messages/aead_not_a_family/aead_not_a_family.cpp b/test/messages/aead_not_a_family/aead_not_a_family.cpp index 113eac92..65874143 100644 --- a/test/messages/aead_not_a_family/aead_not_a_family.cpp +++ b/test/messages/aead_not_a_family/aead_not_a_family.cpp @@ -8,7 +8,7 @@ // takes, and with that error alone. // clang-format off -// expected-error@webcpp/crypto/ciphers/aead.hpp:* {{webcpp::crypto: ciphers::aead takes an AEAD family: families::chacha20_poly1305, families::chacha20_poly1305_original or families::xchacha20_poly1305.}} +// expected-error@webcpp/crypto/ciphers/aead.hpp:* {{webcpp::crypto: ciphers::aead takes an AEAD family: families::chacha20_poly1305, families::chacha20_poly1305_original, families::xchacha20_poly1305, families::secretbox_xsalsa20poly1305 or families::secretbox_xchacha20poly1305.}} // clang-format on #include diff --git a/test/messages/box_default_not_linked/Jamfile b/test/messages/box_default_not_linked/Jamfile new file mode 100644 index 00000000..385d56b6 --- /dev/null +++ b/test/messages/box_default_not_linked/Jamfile @@ -0,0 +1,12 @@ +# 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 ; + +webcpp.compile-diagnostic box_default_not_linked : box_default_not_linked.cpp + : : native wasip2 wasip3 ; diff --git a/test/messages/box_default_not_linked/box_default_not_linked.cpp b/test/messages/box_default_not_linked/box_default_not_linked.cpp new file mode 100644 index 00000000..4bba527f --- /dev/null +++ b/test/messages/box_default_not_linked/box_default_not_linked.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 program that calls the secret boxes, the boxes and the sealed boxes on their default +// backend, libsodium on every target, without linking it, stops where it calls each, with the +// line that links libsodium, the one backend that has them (design D32; ruling C22). + +// 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/ciphers/aead.hpp:* {{webcpp::crypto: XSalsa20-Poly1305 secret box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//secretbox_xsalsa20poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//secretbox_xsalsa20poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)}} +// expected-error@webcpp/crypto/ciphers/aead.hpp:* {{webcpp::crypto: XChaCha20-Poly1305 secret box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//secretbox_xchacha20poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//secretbox_xchacha20poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)}} +// expected-error@webcpp/crypto/hybrid/box.hpp:* {{webcpp::crypto: X25519-XSalsa20-Poly1305 box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//box_xsalsa20poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//box_xsalsa20poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)}} +// expected-error@webcpp/crypto/hybrid/box.hpp:* {{webcpp::crypto: X25519-XChaCha20-Poly1305 box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//box_xchacha20poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//box_xchacha20poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)}} +// expected-error@webcpp/crypto/hybrid/sealed_box.hpp:* {{webcpp::crypto: X25519-XSalsa20-Poly1305 sealed box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//sealed_box-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//sealed_box-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)}} +// clang-format on + +#include +#include +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const key{}; + std::array sealed{}; + return crypto::ciphers::secretbox<>::make(key) && + crypto::ciphers::secretbox_xchacha20poly1305<>::make(key) && + crypto::hybrid::box::make(key, key) && + crypto::hybrid::box_xchacha20poly1305::make(key, key) && + crypto::hybrid::sealed_box::seal(key, {}, sealed) + ? 0 + : 1; +} diff --git a/test/secretbox_sodium_test.cpp b/test/secretbox_sodium_test.cpp new file mode 100644 index 00000000..c9cb4518 --- /dev/null +++ b/test/secretbox_sodium_test.cpp @@ -0,0 +1,126 @@ +// 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) + +// libsodium's secret boxes, crypto_secretbox (XSalsa20-Poly1305) and +// crypto_secretbox_xchacha20poly1305, through their default types, ciphers::secretbox<> and +// ciphers::secretbox_xchacha20poly1305<>, whose backend is libsodium on every target: NaCl's +// case of libsodium's test/default/secretbox.c and .exp and libsodium's XChaCha20 cases of +// test/default/xchacha20.c, every guard, tampering, moves, empty inputs and aliasing spans of +// support/aead_checks.hpp that apply to a family without additional data, which refuses a +// non-empty one with invalid_input_size. Their limit, 2^64 - 17 bytes, no span reaches. + +#include +#include +#include + +#include "support/aead_checks.hpp" + +#include + +#include +#include +#include + +namespace crypto = webcpp::crypto; + +namespace { + +using secretbox = crypto::ciphers::secretbox<>; +using secretbox_xchacha = crypto::ciphers::secretbox_xchacha20poly1305<>; + +// The default is libsodium on every target, the one backend of both families, and the types +// name their family and their algorithm as the capability table does. +static_assert( + std::is_same_v, + crypto::backends::sodium>); +static_assert( + std::is_same_v, + crypto::backends::sodium>); +static_assert( + std::is_same_v>); +static_assert(std::is_same_v>); +static_assert(std::is_same_v); +static_assert(std::is_same_v); +static_assert(crypto::supports_v); +static_assert(crypto::supports_v); +static_assert(secretbox::key_size == 32 && secretbox::iv_size == 24 && secretbox::tag_size == 16); +static_assert(secretbox_xchacha::key_size == 32 && secretbox_xchacha::iv_size == 24 && + secretbox_xchacha::tag_size == 16); +static_assert(secretbox::max_message_size == ~std::uint64_t{0} - 16); +static_assert(secretbox::max_additional_data_size == 0 && + secretbox_xchacha::max_additional_data_size == 0); + +/** + * NaCl's secret box, libsodium's test/default/secretbox.c: its key ("firstkey"), nonce and + * the 131 bytes after the 32 zero bytes of its message; secretbox.exp prints the tag, then the + * ciphertext, once sealed apart and once in place. + */ +constexpr std::array secretbox_cases{ + webcpp::test::aead_case{ + .key = "1b27556473e985d462cd51197a9a46c76009549eac6474f206c4ee0844f68389", + .iv = "69696ee955b62b73cd62bda875fc73d68219e0036b7a0b37", + .additional_data = "", + .plaintext = + "be075fc53c81f2d5cf141316ebeb0c7b5228c52a4c62cbd44b66849b64244ffce5ecbaaf33bd751a1ac7" + "28d45e6c61296cdc3c01233561f41db66cce314adb310e3be8250c46f06dceea3a7fa1348057e2f6556a" + "d6b1318a024a838f21af1fde048977eb48f59ffd4924ca1c60902e52f0a089bc76897040e082f9377638" + "48645e0705", + .ciphertext = + "8e993b9f48681273c29650ba32fc76ce48332ea7164d96a4476fb8c531a1186ac0dfc17c98dce87b4da7" + "f011ec48c97271d2c20f9b928fe2270d6fb863d51738b48eeee314a7cc8ab932164548e526ae90224368" + "517acfeabd6bb3732bc0e9da99832b61ca01b6de56244a9e88d5f9b37973f622a43d14a6599b1f654cb4" + "5a74e355a5", + .tag = "f3ffc7703f9400e52a7dfb4b3d3305d9", + }, +}; + +/** + * libsodium's XChaCha20 secret boxes, test/default/xchacha20.c's tv_secretbox_xchacha20poly1305: + * its first, second and seventh cases (an empty message among them), each tag the first 16 + * bytes of the case's output and the ciphertext the rest. The first carries a message: the + * checks tamper with it. + */ +constexpr std::array secretbox_xchacha_cases{ + webcpp::test::aead_case{ + .key = "d3c71d54e6b13506e07aa2e7b412a17a7a1f34df3d3148cd3f45b91ccaa5f4d9", + .iv = "943b454a853aa514c63cf99b1e197bbb99da24b2e2d93e47", + .additional_data = "", + .plaintext = "76bd706e07741e713d90efdb34ad202067263f984942aae8bda159f30dfccc72200f8093520b" + "85c5ad124ff7c8b2d920946e5cfff4b819abf84c7b35a6205ca72c9f8747c3044dd73fb4beb" + "da1b476", + .ciphertext = "1c6f526d2c19557cf8bd270fcde43fba1d88890663f7b2f5c6b1d7deccf5c91b4df5865dc55c" + "c7e04d6793fc2db8f9e3b418f95cb796d67a7f3f7e097150cb607c435dacf82eac3d669866e" + "5092ace", + .tag = "0384276f1cfa5c82c3e58f0f2acc1f82", + }, + webcpp::test::aead_case{ + .key = "065ff46a9dddb1ab047ee5914d6d575a828b8cc1f454b24e8cd0f57efdc49a34", + .iv = "f83262646ce01293b9923a65a073df78c54b2e799cd6c4e5", + .additional_data = "", + .plaintext = "", + .ciphertext = "", + .tag = "4c72340416339dcdea01b760db5adaf7", + }, + webcpp::test::aead_case{ + .key = "10c0ad4054b48d7d1de1d9ab6f782ca883d886573e9d18c1d47b6ee6b5208189", + .iv = "977edf57428d0e0247a3c88c9a9ec321bbaae1a4da8353b5", + .additional_data = "", + .plaintext = "518e4a27949812424b2a381c3efea6055ee5e75eff", + .ciphertext = "b05a15f8edb68b35773e81ac2aca18e9be53416f9a", + .tag = "0c801a037c2ed0500d6ef68e8d195ece", + }, +}; + +} // namespace + +int main() { + webcpp::test::check_aead(secretbox_cases); + webcpp::test::check_aead(secretbox_xchacha_cases); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/support/aead_checks.hpp b/test/support/aead_checks.hpp index 7c8fb715..b66ab3a6 100644 --- a/test/support/aead_checks.hpp +++ b/test/support/aead_checks.hpp @@ -9,7 +9,9 @@ // data untouched, tampering with every byte of the ciphertext, the tag, the additional data // and the IV, each failing with authentication_failed and the data zeroed, moves of empty // objects, empty inputs, and spans that touch or overlap (the genesis's Review Focus 2, 3 -// and 6). +// and 6). The checks reach the object through an adapter (aead_calls), so that an object of +// another shape, as hybrid::box, which has no additional data and is made of two keys, runs +// those that apply to it (ruling C35). // // The known answers: RFC 8439's section 2.8.2 and appendix A.5 for ChaCha20-Poly1305, the // XChaCha draft's appendix A.3.1 for XChaCha20-Poly1305, and the cases of libsodium's own @@ -180,10 +182,55 @@ inline constexpr std::array xchacha20_poly1305_cases{ }, }; -/** A key of the AEAD's size, its bytes counting up from `first`. */ +/** + * How the checks reach a `ciphers::aead`: made from `key_size` bytes, its calls its own. The + * checks take such an adapter, so that an object of another shape runs those that apply to it: + * `Calls` gives the object's type `object`, its sizes, `make(key)`, `seal(object&, iv, + * additional_data, data)` and `open(object&, iv, additional_data, data, tag)`, and says whether + * the object takes additional data (`has_additional_data`), whether it is made of one key of + * `key_size` bytes (`one_key`, whose sizes the guards check) and whether its calls take + * additional data at all (`takes_additional_data`, false for one whose calls have none). + * + * @tparam Aead A `ciphers::aead`. + */ template -std::array aead_key(std::uint8_t first = 1) { - std::array key{}; +struct aead_calls { + /** The object the checks make. */ + using object = Aead; + /** The key's size. */ + static constexpr std::size_t key_size = Aead::key_size; + /** The nonce's size. */ + static constexpr std::size_t iv_size = Aead::iv_size; + /** The tag's size. */ + static constexpr std::size_t tag_size = Aead::tag_size; + /** Whether a message carries additional data: not for a family whose limit is 0. */ + static constexpr bool has_additional_data = Aead::max_additional_data_size != 0; + /** The calls take additional data, which a family whose limit is 0 refuses unless empty. */ + static constexpr bool takes_additional_data = true; + /** Made of one key of `key_size` bytes. */ + static constexpr bool one_key = true; + + /** `Aead::make`. */ + static auto make(std::span key) { return Aead::make(key); } + + /** `seal`. */ + static auto seal(Aead& made, std::span iv, + std::span additional_data, std::span data) { + return made.seal(iv, additional_data, data); + } + + /** `open`. */ + static auto open(Aead& made, std::span iv, + std::span additional_data, std::span data, + std::span tag) { + return made.open(iv, additional_data, data, tag); + } +}; + +/** A key of the adapter's size, its bytes counting up from `first`. */ +template +std::array aead_key(std::uint8_t first = 1) { + std::array key{}; for (std::size_t i = 0; i < key.size(); ++i) { key[i] = static_cast(first + i); } @@ -191,10 +238,10 @@ std::array aead_key(std::uint8_t first = 1) { } /** Seals and opens each known answer, and checks ciphertext and tag. */ -template +template void check_aead_cases(std::span cases) { for (auto const& c : cases) { - auto made = Aead::make(from_hex(c.key)); + auto made = Calls::make(from_hex(c.key)); if (!BOOST_TEST(made.has_value())) { continue; } @@ -203,133 +250,173 @@ void check_aead_cases(std::span cases) { auto const plaintext = from_hex(c.plaintext); auto const tag = from_hex(c.tag); auto data = plaintext; - auto const sealed = made->seal(iv, additional_data, data); + auto const sealed = Calls::seal(*made, iv, additional_data, data); BOOST_TEST(sealed.has_value()); BOOST_TEST_EQ(to_hex(data), c.ciphertext); BOOST_TEST(sealed && crypto::equal(*sealed, std::span(tag))); - BOOST_TEST(made->open(iv, additional_data, data, tag).has_value()); + BOOST_TEST(Calls::open(*made, iv, additional_data, data, tag).has_value()); BOOST_TEST_EQ(to_hex(data), c.plaintext); } } -/** - * Every guard but the length's, in its order: the key's size; the state before the IV and the - * tag; the IV's size before the tag's. Each refusal leaves the data untouched. - */ -template -void check_aead_guards() { - for (std::size_t const size : {std::size_t{0}, Aead::key_size - 1, Aead::key_size + 1}) { +/** The key's size, for an object made of one key: any other is refused with invalid_key_size. */ +template +void check_aead_key_sizes() { + for (std::size_t const size : {std::size_t{0}, Calls::key_size - 1, Calls::key_size + 1}) { std::vector const wrong_key(size, 7); - BOOST_TEST(Aead::make(wrong_key).error() == crypto::error::invalid_key_size); - } - auto made = Aead::make(aead_key()); - if (!BOOST_TEST(made.has_value())) { - return; + BOOST_TEST(Calls::make(wrong_key).error() == crypto::error::invalid_key_size); } - std::array data{}; - data.fill(0x33); - auto const untouched = data; - std::vector const iv(Aead::iv_size, 9); - std::array const tag{}; +} + +/** The IV's size, then the tag's: each refused, the IV's before the tag's. */ +template +void check_aead_iv_and_tag_sizes(typename Calls::object& made, std::span data) { + std::vector const iv(Calls::iv_size, 9); + std::array const tag{}; // Every IV size but the family's: none, one byte less and more, and the other families'. - std::array const sizes{0, Aead::iv_size - 1, Aead::iv_size + 1, 8, 12, 24}; + std::array const sizes{0, Calls::iv_size - 1, Calls::iv_size + 1, 8, 12, 24}; for (std::size_t const size : sizes) { - if (size == Aead::iv_size) { + if (size == Calls::iv_size) { continue; } std::vector const wrong_iv(size, 9); - BOOST_TEST(made->seal(wrong_iv, {}, data).error() == crypto::error::invalid_iv_size); - BOOST_TEST(made->open(wrong_iv, {}, data, tag).error() == crypto::error::invalid_iv_size); + BOOST_TEST(Calls::seal(made, wrong_iv, {}, data).error() == crypto::error::invalid_iv_size); + BOOST_TEST(Calls::open(made, wrong_iv, {}, data, tag).error() == + crypto::error::invalid_iv_size); } - for (std::size_t const size : {std::size_t{0}, Aead::tag_size - 1, Aead::tag_size + 1}) { + for (std::size_t const size : {std::size_t{0}, Calls::tag_size - 1, Calls::tag_size + 1}) { std::vector const wrong_tag(size); - BOOST_TEST(made->open(iv, {}, data, wrong_tag).error() == crypto::error::invalid_tag_size); + BOOST_TEST(Calls::open(made, iv, {}, data, wrong_tag).error() == + crypto::error::invalid_tag_size); } // The IV is checked before the tag: both wrong gives the IV's error. - BOOST_TEST(made->open({}, {}, data, std::span(tag).first(Aead::tag_size - 1)).error() == + BOOST_TEST(Calls::open(made, {}, {}, data, std::span(tag).first(Calls::tag_size - 1)).error() == crypto::error::invalid_iv_size); +} + +/** + * A family that takes no additional data refuses a non-empty one with invalid_input_size, + * after the IV and the tag. + */ +template +void check_aead_no_additional_data(typename Calls::object& made, std::span data) { + std::vector const iv(Calls::iv_size, 9); + std::array const tag{}; + std::array const additional_data{5}; + BOOST_TEST(Calls::seal(made, iv, additional_data, data).error() == + crypto::error::invalid_input_size); + BOOST_TEST(Calls::open(made, iv, additional_data, data, tag).error() == + crypto::error::invalid_input_size); + BOOST_TEST(Calls::seal(made, {}, additional_data, data).error() == + crypto::error::invalid_iv_size); + BOOST_TEST(Calls::open(made, iv, additional_data, data, std::span(tag).first(1)).error() == + crypto::error::invalid_tag_size); +} + +/** + * Every guard but the length's, in its order: the key's size, for an object of one key; the + * state before the IV and the tag; the IV's size before the tag's; for a family that takes no + * additional data, a non-empty one refused with invalid_input_size, after the IV and the tag. + * Each refusal leaves the data untouched. + */ +template +void check_aead_guards() { + if constexpr (Calls::one_key) { + check_aead_key_sizes(); + } + auto made = Calls::make(aead_key()); + if (!BOOST_TEST(made.has_value())) { + return; + } + std::array data{}; + data.fill(0x33); + auto const untouched = data; + check_aead_iv_and_tag_sizes(*made, data); + if constexpr (Calls::takes_additional_data && !Calls::has_additional_data) { + check_aead_no_additional_data(*made, data); + } BOOST_TEST(data == untouched); // The state is checked before the IV and the tag. - Aead const moved = std::move(*made); - BOOST_TEST(made->seal({}, {}, data).error() == crypto::error::invalid_state); - BOOST_TEST(made->open({}, {}, data, {}).error() == crypto::error::invalid_state); + typename Calls::object const moved = std::move(*made); + BOOST_TEST(Calls::seal(*made, {}, {}, data).error() == crypto::error::invalid_state); + BOOST_TEST(Calls::open(*made, {}, {}, data, {}).error() == crypto::error::invalid_state); BOOST_TEST(data == untouched); } /** An open of a changed message fails with authentication_failed and zeroes the data. */ -template -void expect_aead_tampered(Aead& made, std::span iv, +template +void expect_aead_tampered(typename Calls::object& made, std::span iv, std::span additional_data, std::span data, std::span tag) { - BOOST_TEST(made.open(iv, additional_data, data, tag).error() == + BOOST_TEST(Calls::open(made, iv, additional_data, data, tag).error() == crypto::error::authentication_failed); BOOST_TEST(all_zero(data)); } /** - * Changing any byte of the ciphertext, the tag, the additional data or the IV of a known - * answer fails, and zeroes the data; so does a ciphertext one byte shorter. The object works - * after the failures. + * Changing any byte of the ciphertext, the tag, the additional data (where the family has it) + * or the IV of a known answer fails, and zeroes the data; so does a ciphertext one byte + * shorter. The object works after the failures. */ -template +template void check_aead_tampering(aead_case const& c) { auto const key = from_hex(c.key); auto const iv = from_hex(c.iv); auto const additional_data = from_hex(c.additional_data); auto const ciphertext = from_hex(c.ciphertext); auto const tag = from_hex(c.tag); - auto made = Aead::make(key); + auto made = Calls::make(key); if (!BOOST_TEST(made.has_value()) || !BOOST_TEST(!ciphertext.empty()) || - !BOOST_TEST(!additional_data.empty())) { + !BOOST_TEST(additional_data.empty() != Calls::has_additional_data)) { return; } for (std::size_t i = 0; i < ciphertext.size(); ++i) { auto data = ciphertext; data[i] ^= 1U; - expect_aead_tampered(*made, iv, additional_data, data, tag); + expect_aead_tampered(*made, iv, additional_data, data, tag); } for (std::size_t i = 0; i < tag.size(); ++i) { auto data = ciphertext; auto bad = tag; bad[i] ^= 0x80U; - expect_aead_tampered(*made, iv, additional_data, data, bad); + expect_aead_tampered(*made, iv, additional_data, data, bad); } for (std::size_t i = 0; i < additional_data.size(); ++i) { auto data = ciphertext; auto bad = additional_data; bad[i] ^= 2U; - expect_aead_tampered(*made, iv, bad, data, tag); + expect_aead_tampered(*made, iv, bad, data, tag); } for (std::size_t i = 0; i < iv.size(); ++i) { auto data = ciphertext; auto bad = iv; bad[i] ^= 4U; - expect_aead_tampered(*made, bad, additional_data, data, tag); + expect_aead_tampered(*made, bad, additional_data, data, tag); } { auto data = ciphertext; - expect_aead_tampered(*made, iv, additional_data, std::span(data).first(data.size() - 1), - tag); + expect_aead_tampered(*made, iv, additional_data, + std::span(data).first(data.size() - 1), tag); } - // Without its additional data, the message does not open either. - { + if constexpr (Calls::has_additional_data) { + // Without its additional data, the message does not open either. auto data = ciphertext; - expect_aead_tampered(*made, iv, {}, data, tag); + expect_aead_tampered(*made, iv, {}, data, tag); } auto data = ciphertext; - BOOST_TEST(made->open(iv, additional_data, data, tag).has_value()); + BOOST_TEST(Calls::open(*made, iv, additional_data, data, tag).has_value()); BOOST_TEST_EQ(to_hex(data), c.plaintext); } /** Every call of an empty AEAD is refused with invalid_state, and leaves the data untouched. */ -template -void expect_aead_refused(Aead& empty, std::span iv, +template +void expect_aead_refused(typename Calls::object& empty, std::span iv, std::span data, std::span tag, std::span untouched) { - BOOST_TEST(empty.seal(iv, {}, data).error() == crypto::error::invalid_state); - BOOST_TEST(empty.open(iv, {}, data, tag).error() == crypto::error::invalid_state); - BOOST_TEST(empty.seal(iv, {}, {}).error() == crypto::error::invalid_state); - BOOST_TEST(empty.open(iv, {}, {}, tag).error() == crypto::error::invalid_state); + BOOST_TEST(Calls::seal(empty, iv, {}, data).error() == crypto::error::invalid_state); + BOOST_TEST(Calls::open(empty, iv, {}, data, tag).error() == crypto::error::invalid_state); + BOOST_TEST(Calls::seal(empty, iv, {}, {}).error() == crypto::error::invalid_state); + BOOST_TEST(Calls::open(empty, iv, {}, {}, tag).error() == crypto::error::invalid_state); BOOST_TEST(std::ranges::equal(data, untouched)); } @@ -338,33 +425,34 @@ void expect_aead_refused(Aead& empty, std::span iv, * and destruction; moving it, empty, gives an empty one; the destination, a swap and an * assignment back carry the key; a self-move keeps it. */ -template +template void check_aead_moves(aead_case const& c) { + using object = Calls::object; auto const iv = from_hex(c.iv); auto const additional_data = from_hex(c.additional_data); auto const plaintext = from_hex(c.plaintext); - auto made = Aead::make(from_hex(c.key)); + auto made = Calls::make(from_hex(c.key)); if (!BOOST_TEST(made.has_value())) { return; } // Seals the case's plaintext with an AEAD, which gives the case's ciphertext and tag. - auto const seals_the_case = [&](Aead& aead) { + auto const seals_the_case = [&](object& aead) { auto data = plaintext; - auto const sealed = aead.seal(iv, additional_data, data); + auto const sealed = Calls::seal(aead, iv, additional_data, data); return sealed && to_hex(data) == c.ciphertext && to_hex(*sealed) == c.tag; }; - Aead moved = std::move(*made); - std::array const tag{}; + object moved = std::move(*made); + std::array const tag{}; std::array data{}; data.fill(0x6c); // a guard's refusal leaves this pattern, not only zeroes, untouched auto const untouched = data; - auto const all_refused = [&](Aead& empty) { - expect_aead_refused(empty, iv, data, tag, untouched); + auto const all_refused = [&](object& empty) { + expect_aead_refused(empty, iv, data, tag, untouched); }; all_refused(*made); BOOST_TEST(seals_the_case(moved)); // Moving an object that was moved from gives an empty object. - Aead again = std::move(*made); + object again = std::move(*made); all_refused(again); all_refused(*made); again = std::move(*made); @@ -378,7 +466,7 @@ void check_aead_moves(aead_case const& c) { BOOST_TEST(seals_the_case(moved)); all_refused(again); // An assignment over a live object from an empty one leaves it empty. - auto other = Aead::make(from_hex(c.key)); + auto other = Calls::make(from_hex(c.key)); if (!BOOST_TEST(other.has_value())) { return; } @@ -397,46 +485,51 @@ void check_aead_moves(aead_case const& c) { /** * Empty inputs (Review Focus 3): an empty message and empty additional data, through spans * whose data() is null, seal and open; a zero tag does not open them; each of the two empty - * alone seals and opens. + * alone seals and opens (the additional data alone where the family has it). */ -template -void check_aead_empty(Aead& made, std::span iv) { - auto const empty = made.seal(iv, std::span(), std::span()); +template +void check_aead_empty(typename Calls::object& made, std::span iv) { + auto const empty = + Calls::seal(made, iv, std::span(), std::span()); BOOST_TEST(empty.has_value()); - BOOST_TEST(empty && made.open(iv, {}, std::span(), *empty).has_value()); - std::array const zero_tag{}; - BOOST_TEST(made.open(iv, {}, std::span(), zero_tag).error() == + BOOST_TEST(empty && Calls::open(made, iv, {}, std::span(), *empty).has_value()); + std::array const zero_tag{}; + BOOST_TEST(Calls::open(made, iv, {}, std::span(), zero_tag).error() == crypto::error::authentication_failed); - std::array const additional_data{1, 2, 3, 4, 5}; - auto const only_additional = made.seal(iv, additional_data, std::span()); - BOOST_TEST(only_additional && empty && !crypto::equal(*only_additional, *empty)); - BOOST_TEST( - only_additional && - made.open(iv, additional_data, std::span(), *only_additional).has_value()); - BOOST_TEST(only_additional && - made.open(iv, {}, std::span(), *only_additional).error() == - crypto::error::authentication_failed); + if constexpr (Calls::has_additional_data) { + std::array const additional_data{1, 2, 3, 4, 5}; + auto const only_additional = + Calls::seal(made, iv, additional_data, std::span()); + BOOST_TEST(only_additional && empty && !crypto::equal(*only_additional, *empty)); + BOOST_TEST(only_additional && Calls::open(made, iv, additional_data, + std::span(), *only_additional) + .has_value()); + BOOST_TEST(only_additional && + Calls::open(made, iv, {}, std::span(), *only_additional).error() == + crypto::error::authentication_failed); + } std::array data{}; data.fill(0x42); auto const original = data; - auto const only_data = made.seal(iv, {}, data); + auto const only_data = Calls::seal(made, iv, {}, data); BOOST_TEST(only_data.has_value() && data != original); - BOOST_TEST(only_data && made.open(iv, {}, data, *only_data).has_value()); + BOOST_TEST(only_data && Calls::open(made, iv, {}, data, *only_data).has_value()); BOOST_TEST(data == original); } /** A tag right after the data in one buffer: the open leaves the tag's bytes as they were. */ -template -void check_aead_wire_tag(Aead& made, std::span iv) { - std::array wire{}; +template +void check_aead_wire_tag(typename Calls::object& made, std::span iv) { + std::array wire{}; std::fill(wire.begin(), wire.begin() + 16, 0x33); - auto const sealed = made.seal(iv, {}, std::span(wire).first(16)); + auto const sealed = Calls::seal(made, iv, {}, std::span(wire).first(16)); if (!BOOST_TEST(sealed.has_value())) { return; } std::ranges::copy(*sealed, wire.begin() + 16); - BOOST_TEST(made.open(iv, {}, std::span(wire).first(16), std::span(wire).last(Aead::tag_size)) - .has_value()); + BOOST_TEST( + Calls::open(made, iv, {}, std::span(wire).first(16), std::span(wire).last(Calls::tag_size)) + .has_value()); BOOST_TEST( std::all_of(wire.begin(), wire.begin() + 16, [](std::uint8_t b) { return b == 0x33; })); BOOST_TEST(std::equal(sealed->begin(), sealed->end(), wire.begin() + 16)); @@ -446,54 +539,56 @@ void check_aead_wire_tag(Aead& made, std::span iv) { * A tag that overlaps the data's end fails cleanly (Review Focus 2): the data is zeroed, and * the bytes after the data, which only the tag covers, are as they were. */ -template -void check_aead_overlap(Aead& made, std::span iv) { +template +void check_aead_overlap(typename Calls::object& made, std::span iv) { std::array overlap{}; overlap.fill(0x5a); - BOOST_TEST( - made.open(iv, {}, std::span(overlap).first(20), std::span(overlap).last(Aead::tag_size)) - .error() == crypto::error::authentication_failed); + BOOST_TEST(Calls::open(made, iv, {}, std::span(overlap).first(20), + std::span(overlap).last(Calls::tag_size)) + .error() == crypto::error::authentication_failed); BOOST_TEST(all_zero(std::span(overlap).first(20))); BOOST_TEST( std::all_of(overlap.begin() + 20, overlap.end(), [](std::uint8_t b) { return b == 0x5a; })); } /** - * An IV inside the sealed buffer, and additional data just before it in the same buffer, give - * what copies of them give: the IV is read before the first byte of the data is written, and - * the additional data, which may touch the data but not overlap it, is left as it was. + * An IV inside the sealed buffer, and additional data (where the family has it) just before it + * in the same buffer, give what copies of them give: the IV is read before the first byte of + * the data is written, and the additional data, which may touch the data but not overlap it, + * is left as it was. */ -template -void check_aead_in_place(Aead& made) { - constexpr std::size_t additional_size = 16; - std::array buffer{}; +template +void check_aead_in_place(typename Calls::object& made) { + constexpr std::size_t additional_size = Calls::has_additional_data ? 16 : 0; + std::array buffer{}; for (std::size_t i = 0; i < buffer.size(); ++i) { buffer[i] = static_cast((i * 7) + 1); } auto const original = buffer; - std::array iv_copy{}; + std::array iv_copy{}; std::array additional_copy{}; std::copy_n(buffer.begin(), additional_size, additional_copy.begin()); - std::copy_n(buffer.begin() + additional_size, Aead::iv_size, iv_copy.begin()); - std::array data_copy{}; + std::copy_n(buffer.begin() + additional_size, Calls::iv_size, iv_copy.begin()); + std::array data_copy{}; std::copy_n(buffer.begin() + additional_size, data_copy.size(), data_copy.begin()); - auto const expected = made.seal(iv_copy, additional_copy, data_copy); + auto const expected = Calls::seal(made, iv_copy, additional_copy, data_copy); auto const data = std::span(buffer).subspan(additional_size); - auto const in_place = - made.seal(data.first(Aead::iv_size), std::span(buffer).first(additional_size), data); + auto const in_place = Calls::seal(made, data.first(Calls::iv_size), + std::span(buffer).first(additional_size), data); BOOST_TEST(expected && in_place && to_hex(*expected) == to_hex(*in_place)); BOOST_TEST(std::equal(data_copy.begin(), data_copy.end(), data.begin())); BOOST_TEST(std::equal(original.begin(), original.begin() + additional_size, buffer.begin())); } /** - * A wire buffer [IV | additional data | ciphertext], opened in place with spans into it, gives - * what an open of copies gives, and leaves the IV and the additional data as they were. + * A wire buffer [IV | additional data | ciphertext], the additional data where the family has + * it, opened in place with spans into it, gives what an open of copies gives, and leaves the IV + * and the additional data as they were. */ -template -void check_aead_wire_open(Aead& made) { - constexpr std::size_t additional_size = 16; - std::array wire_iv{}; +template +void check_aead_wire_open(typename Calls::object& made) { + constexpr std::size_t additional_size = Calls::has_additional_data ? 16 : 0; + std::array wire_iv{}; std::array wire_additional{}; std::array wire_plain{}; for (std::size_t i = 0; i < wire_plain.size(); ++i) { @@ -502,52 +597,58 @@ void check_aead_wire_open(Aead& made) { wire_iv.fill(0x17); wire_additional.fill(0x29); auto wire_data = wire_plain; - auto const wire_sealed = made.seal(wire_iv, wire_additional, wire_data); + auto const wire_sealed = Calls::seal(made, wire_iv, wire_additional, wire_data); if (!BOOST_TEST(wire_sealed.has_value())) { return; } - constexpr std::size_t data_at = Aead::iv_size + additional_size; + constexpr std::size_t data_at = Calls::iv_size + additional_size; std::array message{}; std::ranges::copy(wire_iv, message.begin()); - std::ranges::copy(wire_additional, message.begin() + Aead::iv_size); + std::ranges::copy(wire_additional, message.begin() + Calls::iv_size); std::ranges::copy(wire_data, message.begin() + data_at); auto copy_data = wire_data; - BOOST_TEST(made.open(wire_iv, wire_additional, copy_data, *wire_sealed).has_value()); - BOOST_TEST(made.open(std::span(message).first(Aead::iv_size), - std::span(message).subspan(Aead::iv_size, additional_size), - std::span(message).subspan(data_at), *wire_sealed) + BOOST_TEST(Calls::open(made, wire_iv, wire_additional, copy_data, *wire_sealed).has_value()); + BOOST_TEST(Calls::open(made, std::span(message).first(Calls::iv_size), + std::span(message).subspan(Calls::iv_size, additional_size), + std::span(message).subspan(data_at), *wire_sealed) .has_value()); BOOST_TEST(std::equal(copy_data.begin(), copy_data.end(), message.begin() + data_at)); BOOST_TEST(copy_data == wire_plain); BOOST_TEST(std::equal(wire_iv.begin(), wire_iv.end(), message.begin())); BOOST_TEST(std::equal(wire_additional.begin(), wire_additional.end(), - message.begin() + Aead::iv_size)); + message.begin() + Calls::iv_size)); } /** Empty inputs, and spans that touch or overlap (Review Focus 2 and 3). */ -template +template void check_aead_edges() { - auto made = Aead::make(aead_key()); + auto made = Calls::make(aead_key()); if (!BOOST_TEST(made.has_value())) { return; } - std::array iv{}; + std::array iv{}; iv.fill(0x24); - check_aead_empty(*made, iv); - check_aead_wire_tag(*made, iv); - check_aead_overlap(*made, iv); - check_aead_in_place(*made); - check_aead_wire_open(*made); + check_aead_empty(*made, iv); + check_aead_wire_tag(*made, iv); + check_aead_overlap(*made, iv); + check_aead_in_place(*made); + check_aead_wire_open(*made); +} + +/** Every check of this file on one object, through its adapter, against its known answers. */ +template +void check_aead_with(std::span cases) { + check_aead_cases(cases); + check_aead_guards(); + check_aead_tampering(cases.front()); + check_aead_moves(cases.front()); + check_aead_edges(); } -/** Every check of this file on one AEAD, against the family's known answers. */ +/** Every check of this file on one `ciphers::aead`, against the family's known answers. */ template void check_aead(std::span cases) { - check_aead_cases(cases); - check_aead_guards(); - check_aead_tampering(cases.front()); - check_aead_moves(cases.front()); - check_aead_edges(); + check_aead_with>(cases); } #if !defined(__wasi__) && !defined(__EMSCRIPTEN__) diff --git a/test/support/capabilities.hpp b/test/support/capabilities.hpp index c792bdbe..1fcb1931 100644 --- a/test/support/capabilities.hpp +++ b/test/support/capabilities.hpp @@ -28,8 +28,10 @@ constexpr std::size_t key_size_of() { /** * Makes an algorithm, through the type a program names, from a key whose bytes are all 1, or, - * for one keyed by no key of its own (Ed25519ph's signer), begins it, or, for one of free - * functions alone (X25519), gives that key's public key: a cell the capability + * for one made of a secret key and a peer's public key (a box), from that key twice, or, for + * one keyed by no key of its own (Ed25519ph's signer), begins it, or, for sealed boxes, seals + * an empty message to that key as a public key, or, for one of free functions alone (X25519), + * gives that key's public key: a cell the capability * table marks present whose engine is missing fails to compile here. The type names its family * and its algorithm as the table does, and `supports_v` says that the backend has it. * @@ -37,7 +39,7 @@ constexpr std::size_t key_size_of() { * @tparam Family Its family's tag. * @tparam Name Its algorithm's tag. * @tparam Backend Its backend. - * @return Whether `make`, `begin` or `public_key` succeeded. + * @return Whether `make`, `begin`, `seal` or `public_key` succeeded. */ template [[nodiscard]] bool made() { @@ -50,6 +52,11 @@ template return Algorithm::begin().has_value(); } else if constexpr (requires { Algorithm::make(key_bytes); }) { return Algorithm::make(key_bytes).has_value(); + } else if constexpr (requires { Algorithm::make(key_bytes, key_bytes); }) { + return Algorithm::make(key_bytes, key_bytes).has_value(); + } else if constexpr (requires { Algorithm::overhead; }) { + std::array sealed{}; + return Algorithm::seal(key_bytes, {}, sealed).has_value(); } else { return Algorithm::public_key(key_bytes).has_value(); } diff --git a/test/windows_h_after_test.cpp b/test/windows_h_after_test.cpp index f2b2a398..682eab91 100644 --- a/test/windows_h_after_test.cpp +++ b/test/windows_h_after_test.cpp @@ -22,10 +22,13 @@ #include #include #include +#include #include #include #include #include +#include +#include #include #include diff --git a/test/windows_h_before_test.cpp b/test/windows_h_before_test.cpp index 2a9d1f9d..718693e5 100644 --- a/test/windows_h_before_test.cpp +++ b/test/windows_h_before_test.cpp @@ -37,10 +37,13 @@ #include #include #include +#include #include #include #include #include +#include +#include #include #include From 99121d1212ac3669d9a670fbf6d474a60e6251ec Mon Sep 17 00:00:00 2001 From: R Date: Wed, 18 Nov 2026 06:18:13 -0300 Subject: [PATCH 051/110] crypto: libsodium's own suite and WebCrypto's oracle for Ed25519 and X25519 --- doc/generated/backends-ed25519_keypair.adoc | 2 +- doc/generated/backends-ed25519_verify.adoc | 2 +- doc/generated/backends-x25519_agree.adoc | 2 +- doc/generated/backends-x25519_public_key.adoc | 2 +- doc/generated/matrix.adoc | 8 +- doc/tables/crypto.json | 14 +- doc/testing.adoc | 21 +- test/Jamfile | 12 + test/c_suites/Jamfile | 9 + test/oracle_25519_test.cpp | 267 ++++++++++++++++++ 10 files changed, 324 insertions(+), 15 deletions(-) create mode 100644 test/oracle_25519_test.cpp diff --git a/doc/generated/backends-ed25519_keypair.adoc b/doc/generated/backends-ed25519_keypair.adoc index 37caa39b..402b30f6 100644 --- a/doc/generated/backends-ed25519_keypair.adoc +++ b/doc/generated/backends-ed25519_keypair.adoc @@ -21,5 +21,5 @@ The backends of `+curves::ed25519::keypair+`, from the test programs that run it |libsodium |`+/third_party//sodium+` |`++` -|native, wasip2, wasip3, emscripten (tested by `+ed25519_sodium+`) +|native, wasip2, wasip3, emscripten (tested by `+ed25519_sodium+`, `+oracle_25519+`) |=== diff --git a/doc/generated/backends-ed25519_verify.adoc b/doc/generated/backends-ed25519_verify.adoc index c80815b4..95b5540a 100644 --- a/doc/generated/backends-ed25519_verify.adoc +++ b/doc/generated/backends-ed25519_verify.adoc @@ -16,5 +16,5 @@ The backends of `+curves::ed25519::verify+`, from the test programs that run it: |libsodium |`+/third_party//sodium+` |`++` -|native, wasip2, wasip3, emscripten (tested by `+ed25519_sodium+`, `+ed25519_wycheproof_sodium+`, `+ed25519_speccheck+`) +|native, wasip2, wasip3, emscripten (tested by `+ed25519_sodium+`, `+ed25519_wycheproof_sodium+`, `+ed25519_speccheck+`, `+oracle_25519+`) |=== diff --git a/doc/generated/backends-x25519_agree.adoc b/doc/generated/backends-x25519_agree.adoc index 25829e43..25ce8d0a 100644 --- a/doc/generated/backends-x25519_agree.adoc +++ b/doc/generated/backends-x25519_agree.adoc @@ -16,5 +16,5 @@ The backends of `+curves::x25519::agree+`, from the test programs that run it: |libsodium |`+/third_party//sodium+` |`++` -|native, wasip2, wasip3, emscripten (tested by `+x25519_sodium+`, `+x25519_wycheproof_sodium+`) +|native, wasip2, wasip3, emscripten (tested by `+x25519_sodium+`, `+x25519_wycheproof_sodium+`, `+oracle_25519+`) |=== diff --git a/doc/generated/backends-x25519_public_key.adoc b/doc/generated/backends-x25519_public_key.adoc index 1144f3b6..58aa4e24 100644 --- a/doc/generated/backends-x25519_public_key.adoc +++ b/doc/generated/backends-x25519_public_key.adoc @@ -16,5 +16,5 @@ The backends of `+curves::x25519::public_key+`, from the test programs that run |libsodium |`+/third_party//sodium+` |`++` -|native, wasip2, wasip3, emscripten (tested by `+x25519_sodium+`) +|native, wasip2, wasip3, emscripten (tested by `+x25519_sodium+`, `+oracle_25519+`) |=== diff --git a/doc/generated/matrix.adoc b/doc/generated/matrix.adoc index 4a4da635..93b3d5dd 100644 --- a/doc/generated/matrix.adoc +++ b/doc/generated/matrix.adoc @@ -89,12 +89,12 @@ |`+curves::ed25519::keypair+` |libsodium |native, wasip2, wasip3, emscripten -|`+ed25519_sodium+` +|`+ed25519_sodium+`, `+oracle_25519+` |`+curves::ed25519::verify+` |libsodium |native, wasip2, wasip3, emscripten -|`+ed25519_sodium+`, `+ed25519_wycheproof_sodium+`, `+ed25519_speccheck+` +|`+ed25519_sodium+`, `+ed25519_wycheproof_sodium+`, `+ed25519_speccheck+`, `+oracle_25519+` |`+curves::ed25519::ph+` |libsodium @@ -109,12 +109,12 @@ |`+curves::x25519::public_key+` |libsodium |native, wasip2, wasip3, emscripten -|`+x25519_sodium+` +|`+x25519_sodium+`, `+oracle_25519+` |`+curves::x25519::agree+` |libsodium |native, wasip2, wasip3, emscripten -|`+x25519_sodium+`, `+x25519_wycheproof_sodium+` +|`+x25519_sodium+`, `+x25519_wycheproof_sodium+`, `+oracle_25519+` |`+ciphers::chacha20_poly1305+` |BearSSL diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 2e1dcfc0..6f8e3e7f 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -145,7 +145,11 @@ "targets": ["native", "wasip2", "wasip3", "emscripten"], "header": "", "library": "libsodium 1.0.22, built from source", - "licence": "ISC" + "licence": "ISC", + "own_suite": { + "lane": "webcpp::hash's own lane `c-suites`, `libs/hash/test/c_suites/Jamfile`, on every target, against the same `/third_party//sodium` that crypto links", + "programs": ["sign", "box", "box2", "box7", "box8", "box_seal", "secretbox", "secretbox2", "secretbox7", "secretbox8", "aead_chacha20poly1305", "aead_chacha20poly13052", "aead_xchacha20poly1305", "kx", "scalarmult", "ed25519_convert"] + } }, "system": { "title": "the system's generator", @@ -301,7 +305,7 @@ "what": "An Ed25519 key pair (RFC 8032): made from a 32-byte seed or drawn from `random_device`, its 32-byte public key, 64-byte signatures, and its X25519 secret key.", "section": "crypto-ed25519", "backends": { - "sodium": {"tests": ["ed25519_sodium"]}, + "sodium": {"tests": ["ed25519_sodium", "oracle_25519"]}, "bearssl": {"refused": "ed25519_on_bearssl"} } }, @@ -315,7 +319,7 @@ "header": "", "what": "Verifies an Ed25519 signature with a public key alone, under the policy `strict`: libsodium's rules, which refuse non-canonical encodings and keys of small order.", "section": "crypto-ed25519", - "backends": {"sodium": {"tests": ["ed25519_sodium", "ed25519_wycheproof_sodium", "ed25519_speccheck"]}} + "backends": {"sodium": {"tests": ["ed25519_sodium", "ed25519_wycheproof_sodium", "ed25519_speccheck", "oracle_25519"]}} }, { "id": "ed25519ph", @@ -350,7 +354,7 @@ "header": "", "what": "The 32-byte X25519 public key of a 32-byte secret key (RFC 7748).", "section": "crypto-x25519", - "backends": {"sodium": {"tests": ["x25519_sodium"]}} + "backends": {"sodium": {"tests": ["x25519_sodium", "oracle_25519"]}} }, { "id": "x25519_agree", @@ -362,7 +366,7 @@ "header": "", "what": "The 32-byte shared secret of a secret key and a peer's public key, a `secret<32>`, refused with `weak_public_key` when it is all zero (a peer key of low order).", "section": "crypto-x25519", - "backends": {"sodium": {"tests": ["x25519_sodium", "x25519_wycheproof_sodium"]}} + "backends": {"sodium": {"tests": ["x25519_sodium", "x25519_wycheproof_sodium", "oracle_25519"]}} }, { "id": "chacha20_poly1305", diff --git a/doc/testing.adoc b/doc/testing.adoc index 6568a1e0..0d3d5629 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -33,14 +33,31 @@ MSVC and Apple Clang run in the continuous integration only. The own lane `c-suites` runs the C libraries' own test suites (BearSSL's, ctaes's and libsecp256k1's) on webcpp's build of them, on every target, on every push: the target's lane command with `libs/crypto/test/c_suites//c-suites` in place -of the two directories. +of the two directories. libsodium's own suite runs in webcpp::hash's lane +`c-suites` (`libs/hash/test/c_suites//c-suites`), on every target, against the +same build of libsodium that crypto links: each program of its `test/default`, +those of crypto's operations among them (`sign`, `box`, `box2`, `box7`, +`box8`, `box_seal`, `secretbox`, `secretbox2`, `secretbox7`, `secretbox8`, +`aead_chacha20poly1305`, `aead_chacha20poly13052`, `aead_xchacha20poly1305`, +`kx`, `scalarmult`, `ed25519_convert`), compared with its `.exp`. What the tests check: * *The vectors.* AES-GCM against the GCM specification's cases and Project Wycheproof's vectors, on BearSSL and on OpenSSL; AES against FIPS 197 on ctaes and OpenSSL; secp256k1 against BIP 340's vectors and Wycheproof's ECDSA and DER -vectors, and the x-only tweak against BIP 341's. +vectors, and the x-only tweak against BIP 341's. Ed25519 against RFC 8032's +tests, Wycheproof's EdDSA vectors and the twelve edge cases of "Taming the +many EdDSAs"; X25519 against RFC 7748's and Wycheproof's; ChaCha20-Poly1305 +and XChaCha20-Poly1305 against RFC 8439's and the XChaCha20 draft's examples +and Wycheproof's vectors, on every backend that has them. +* *node's WebCrypto as an outside oracle,* on Emscripten: 200 Ed25519 key +pairs, messages and signatures from a fixed seed, each verified and signed +again by `crypto.subtle`, which must give the same public key and signature, +and 200 X25519 agreements, each derived again to the same public key and +shared secret (`oracle_25519`, which prints `oracle ok 400`). +`oracle_25519_corrupted` flips one signature and one shared secret, and +passes only when WebCrypto disagrees on exactly those two. * *The backends against each other,* on random keys, IVs, additional data and messages of every size around a block's: BearSSL and OpenSSL seal the same bytes with AES-GCM and each opens what the other sealed, with BearSSL on its diff --git a/test/Jamfile b/test/Jamfile index 04c242e9..4fdb6fe0 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -323,6 +323,18 @@ crypto-run x25519_wycheproof_sodium : x25519_wycheproof_sodium_test.cpp : /third_party//sodium /third_party//wycheproof /webcpp//boost_json ; +# node's WebCrypto as an outside oracle of Ed25519 and X25519, on Emscripten +# (EM_ASYNC_JS under the JSPI link, as webcpp::hash's webcrypto_oracle): 200 +# seeded Ed25519 key pairs, messages and signatures, each verified and signed +# again by WebCrypto, and 200 X25519 agreements, each derived again; it prints +# `oracle ok 400`. oracle_25519_corrupted flips one signature and one shared +# secret and passes only when WebCrypto disagrees on exactly those two cases. +crypto-run oracle_25519 : oracle_25519_test.cpp + : /third_party//sodium -sJSPI : emscripten ; +crypto-run oracle_25519_corrupted : oracle_25519_test.cpp + : /third_party//sodium -sJSPI + WEBCPP_TEST_CRYPTO_ORACLE_CORRUPTED : emscripten ; + # The ChaCha20-Poly1305 AEADs on libsodium, their default on every target: each # family's known answers and every check of support/aead_checks.hpp, natively # the message's limit too; Wycheproof's vectors of ChaCha20-Poly1305 and diff --git a/test/c_suites/Jamfile b/test/c_suites/Jamfile index 009e1689..c6b544d3 100644 --- a/test/c_suites/Jamfile +++ b/test/c_suites/Jamfile @@ -11,6 +11,15 @@ # bearssl_bound.cpp's, which runs BearSSL's only when it is given the argument # all, and fails otherwise: upstream's main lists its tests and returns 0 for # any other argument, which would read green. +# +# libsodium's own suite is not repeated here: webcpp::hash's lane c-suites +# (libs/hash/test/c_suites/Jamfile) runs all of libsodium's test/default +# programs, each compared with its .exp, on every target, against the same +# archive /third_party//sodium that crypto links, canary included. Among them +# are the programs of crypto's operations on libsodium: sign, box, box2, box7, +# box8, box_seal, secretbox, secretbox2, secretbox7, secretbox8, +# aead_chacha20poly1305, aead_chacha20poly13052, aead_xchacha20poly1305, kx, +# scalarmult and ed25519_convert. import webcpp ; webcpp.targets native wasip2 wasip3 emscripten ; diff --git a/test/oracle_25519_test.cpp b/test/oracle_25519_test.cpp new file mode 100644 index 00000000..d9d1f3fa --- /dev/null +++ b/test/oracle_25519_test.cpp @@ -0,0 +1,267 @@ +// 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) + +// WebCrypto, node's `globalThis.crypto.subtle`, as an outside oracle of Ed25519 and X25519 on +// every backend linked here (libsodium, the default of both on every target), on Emscripten +// under node. From a fixed seed, 200 Ed25519 cases: a key pair made from a random seed, a random +// message (the first one empty) and its signature; WebCrypto imports the seed (PKCS #8) and the +// public key (raw), and the case agrees when WebCrypto's public key and its signature (Ed25519 is +// deterministic) equal ours and it verifies ours. Then 200 X25519 cases: two random secret keys +// and their public keys; WebCrypto imports the first secret key (PKCS #8) and the peer's public +// key (raw), and the case agrees when WebCrypto's public key of the secret key and its derived +// 256 bits equal ours. The program prints `oracle ok `, the cases that agree, and passes when +// n is 400. Each WebCrypto call is an EM_ASYNC_JS function, which suspends the program (the JSPI +// link) and returns its bytes through the heap, as webcpp::hash's webcrypto_oracle_test.cpp. +// +// Built with WEBCPP_TEST_CRYPTO_ORACLE_CORRUPTED, the program flips one bit of the signature of +// Ed25519 case 17, before WebCrypto verifies it, and of our shared secret of X25519 case 42, and +// passes only when exactly those two cases disagree and n is 398: the oracle's teeth. + +#include +#include +#include +#include + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace ed25519 = webcpp::crypto::curves::ed25519; +namespace x25519 = webcpp::crypto::curves::x25519; + +// The cases per algorithm, and the seed that makes a failure reproducible. +constexpr std::size_t cases = 200; +constexpr std::uint64_t seed = 0x4f7261636c653235ULL; + +// Each function returns 0 when every WebCrypto call ran, -1 when one threw (the message goes to +// the console). The inputs are copied before the first await; the heap is written after the +// last. A seed of 32 bytes is a private key in PKCS #8 behind RFC 8410's 16-byte prefix, whose +// OID is 1.3.101.112 for Ed25519 and 1.3.101.110 for X25519; a JWK export of a private key +// carries its public key, `x`, in base64url. +// clang-format off +EM_ASYNC_JS(int, subtle_ed25519, (const std::uint8_t* seed, const std::uint8_t* public_key, + const std::uint8_t* msg, std::size_t msg_size, + const std::uint8_t* sig, std::uint8_t* oracle_public_key, + std::uint8_t* oracle_signature, int* verified), { + try { + const pkcs8 = new Uint8Array(48); + pkcs8.set([0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, + 0x04, 0x22, 0x04, 0x20]); + pkcs8.set(HEAPU8.slice(seed, seed + 32), 16); + const raw = HEAPU8.slice(public_key, public_key + 32); + const data = HEAPU8.slice(msg, msg + msg_size); + const signature = HEAPU8.slice(sig, sig + 64); + const subtle = globalThis.crypto.subtle; + const private_key = await subtle.importKey("pkcs8", pkcs8, {name: "Ed25519"}, true, + ["sign"]); + const jwk = await subtle.exportKey("jwk", private_key); + const verifier = await subtle.importKey("raw", raw, {name: "Ed25519"}, false, + ["verify"]); + const ok = await subtle.verify({name: "Ed25519"}, verifier, signature, data); + const signed = new Uint8Array(await subtle.sign({name: "Ed25519"}, private_key, data)); + const derived = Buffer.from(jwk.x, "base64url"); + if (derived.length !== 32 || signed.length !== 64) { + console.error("subtle (Ed25519): sizes " + derived.length + ", " + signed.length); + return -1; + } + HEAPU8.set(derived, oracle_public_key); + HEAPU8.set(signed, oracle_signature); + HEAP32[verified >> 2] = ok ? 1 : 0; + return 0; + } catch (e) { + console.error("subtle (Ed25519): " + e); + return -1; + } +}); + +EM_ASYNC_JS(int, subtle_x25519, (const std::uint8_t* secret_key, const std::uint8_t* peer, + std::uint8_t* oracle_public_key, std::uint8_t* oracle_shared), { + try { + const pkcs8 = new Uint8Array(48); + pkcs8.set([0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6e, + 0x04, 0x22, 0x04, 0x20]); + pkcs8.set(HEAPU8.slice(secret_key, secret_key + 32), 16); + const raw = HEAPU8.slice(peer, peer + 32); + const subtle = globalThis.crypto.subtle; + const private_key = await subtle.importKey("pkcs8", pkcs8, {name: "X25519"}, true, + ["deriveBits"]); + const jwk = await subtle.exportKey("jwk", private_key); + const public_key = await subtle.importKey("raw", raw, {name: "X25519"}, false, []); + const shared = new Uint8Array( + await subtle.deriveBits({name: "X25519", public: public_key}, private_key, 256)); + const derived = Buffer.from(jwk.x, "base64url"); + if (derived.length !== 32 || shared.length !== 32) { + console.error("subtle (X25519): sizes " + derived.length + ", " + shared.length); + return -1; + } + HEAPU8.set(derived, oracle_public_key); + HEAPU8.set(shared, oracle_shared); + return 0; + } catch (e) { + console.error("subtle (X25519): " + e); + return -1; + } +}); + +// The versions of the node running this program, and of its OpenSSL, on one line. +EM_JS(void, print_node_versions, (), { + console.log("oracle run with node " + process.versions.node + ", OpenSSL " + + process.versions.openssl); +}); +// clang-format on + +namespace { + +using bytes = std::vector; + +#ifdef WEBCPP_TEST_CRYPTO_ORACLE_CORRUPTED +constexpr bool corrupted = true; +#else +constexpr bool corrupted = false; +#endif +// The case of each algorithm whose bytes the corrupted program flips. +constexpr std::size_t corrupted_ed25519 = 17; +constexpr std::size_t corrupted_x25519 = 42; + +template +std::array random_array(std::mt19937_64& rng) { + std::array out{}; + for (auto& b : out) { + b = static_cast(rng() & 0xffU); + } + return out; +} + +bytes random_bytes(std::mt19937_64& rng, std::size_t min_size, std::size_t max_size) { + bytes out(std::uniform_int_distribution(min_size, max_size)(rng)); + for (auto& b : out) { + b = static_cast(rng() & 0xffU); + } + return out; +} + +// One Ed25519 case: true when WebCrypto agrees with it. +bool ed25519_case(std::mt19937_64& rng, std::size_t index) { + auto const key_seed = random_array<32>(rng); + // The first message is empty; the others cross SHA-512's block of 128 bytes. + bytes const message = index == 0 ? bytes{} : random_bytes(rng, 1, 300); + auto const pair = ed25519::keypair::make(key_seed); + BOOST_TEST(pair.has_value()); + if (!pair) { + return false; + } + auto const public_key = pair->public_key(); + auto signature = pair->sign(message); + BOOST_TEST(public_key.has_value()); + BOOST_TEST(signature.has_value()); + if (!public_key || !signature) { + return false; + } + BOOST_TEST(ed25519::verify(*public_key, message, *signature).has_value()); + if (corrupted && index == corrupted_ed25519) { + (*signature)[5] ^= 0x01U; + } + std::array oracle_public_key{}; + std::array oracle_signature{}; + int verified = 0; + int const ran = subtle_ed25519(key_seed.data(), public_key->data(), message.data(), + message.size(), signature->data(), oracle_public_key.data(), + oracle_signature.data(), &verified); + BOOST_TEST_EQ(ran, 0); + bool const agrees = ran == 0 && verified == 1 && oracle_public_key == *public_key && + oracle_signature == *signature; + if (!agrees) { + std::printf( + "Ed25519 case %zu: WebCrypto disagrees (verified %d, public key %s, " + "signature %s)\n", + index, verified, oracle_public_key == *public_key ? "equal" : "differs", + oracle_signature == *signature ? "equal" : "differs"); + } + return agrees; +} + +// One X25519 case: true when WebCrypto agrees with it. +bool x25519_case(std::mt19937_64& rng, std::size_t index) { + auto const secret_key = random_array<32>(rng); + auto const peer_secret_key = random_array<32>(rng); + auto const public_key = x25519::public_key(secret_key); + auto const peer_public_key = x25519::public_key(peer_secret_key); + BOOST_TEST(public_key.has_value()); + BOOST_TEST(peer_public_key.has_value()); + if (!public_key || !peer_public_key) { + return false; + } + auto const shared = x25519::agree(secret_key, *peer_public_key); + auto const peer_shared = x25519::agree(peer_secret_key, *public_key); + BOOST_TEST(shared.has_value()); + BOOST_TEST(peer_shared.has_value()); + if (!shared || !peer_shared) { + return false; + } + auto const ours = shared->bytes(); + auto const theirs = peer_shared->bytes(); + BOOST_TEST(bytes(ours.begin(), ours.end()) == bytes(theirs.begin(), theirs.end())); + bytes expected(ours.begin(), ours.end()); + if (corrupted && index == corrupted_x25519) { + expected[7] ^= 0x01U; + } + std::array oracle_public_key{}; + std::array oracle_shared{}; + int const ran = subtle_x25519(secret_key.data(), peer_public_key->data(), + oracle_public_key.data(), oracle_shared.data()); + BOOST_TEST_EQ(ran, 0); + bool const agrees = ran == 0 && oracle_public_key == *public_key && + bytes(oracle_shared.begin(), oracle_shared.end()) == expected; + if (!agrees) { + std::printf( + "X25519 case %zu: WebCrypto disagrees (public key %s, shared secret %s)\n", index, + oracle_public_key == *public_key ? "equal" : "differs", + bytes(oracle_shared.begin(), oracle_shared.end()) == expected ? "equal" : "differs"); + } + return agrees; +} + +} // namespace + +int main() { + std::printf("oracle 25519: seed %llu\n", static_cast(seed)); + print_node_versions(); + std::mt19937_64 rng(seed); + std::size_t agreed = 0; + std::vector ed25519_disagreed; + std::vector x25519_disagreed; + for (std::size_t i = 0; i < cases; ++i) { + if (ed25519_case(rng, i)) { + ++agreed; + } else { + ed25519_disagreed.push_back(i); + } + } + for (std::size_t i = 0; i < cases; ++i) { + if (x25519_case(rng, i)) { + ++agreed; + } else { + x25519_disagreed.push_back(i); + } + } + std::printf("oracle ok %zu\n", agreed); + if (corrupted) { + BOOST_TEST_EQ(agreed, (2 * cases) - 2); + BOOST_TEST(ed25519_disagreed == std::vector{corrupted_ed25519}); + BOOST_TEST(x25519_disagreed == std::vector{corrupted_x25519}); + } else { + BOOST_TEST_EQ(agreed, 2 * cases); + } + return webcpp::test::exit_status(boost::report_errors()); +} From 1d7547de513f631844a6165a54ac43d0842b2b1d Mon Sep 17 00:00:00 2001 From: R Date: Wed, 18 Nov 2026 05:51:15 -0300 Subject: [PATCH 052/110] crypto: the constant-time lane over version 0.1's backends, memcheck and MemorySanitizer shown to fail on a planted leak The own lane constant-time (test/constant_time) builds the genesis's Task 20 over version 0.1's names: under Valgrind's memcheck and under MemorySanitizer, equal, BearSSL's AES-GCM make, seal and open, OpenSSL's make and seal, ctaes's AES and libsecp256k1's own ctime_tests.c, each with its key, data and tag secret, and a planted branch on a key byte that each checker must report; dudect's Welch t-test on BearSSL's seal and open, ctaes and equal, natively and under wasmtime. memcheck and MemorySanitizer build on Linux alone; MemorySanitizer's eager checks of arguments and return values are off, as libsecp256k1's build turns them off for its ctime_tests. dudect's classes copy their input through a volatile pointer, so that an optimiser cannot split the store by class, which leaked the class into the measured call. The backends page says what the lane checks and that a tag's verdict is the one value webcpp marks public. --- .gitignore | 2 + doc/backends.adoc | 18 +++ doc/testing.adoc | 6 +- test/Jamfile | 4 + test/constant_time/Jamfile | 115 +++++++++++++++++ test/constant_time/ctgrind_planted_test.cpp | 9 ++ test/constant_time/ctgrind_test.cpp | 100 +++++++++++++++ test/constant_time/dudect.hpp | 129 ++++++++++++++++++++ test/constant_time/dudect_test.cpp | 121 ++++++++++++++++++ test/constant_time/msan_planted_test.cpp | 9 ++ test/constant_time/msan_report.mjs | 41 +++++++ test/constant_time/msan_test.cpp | 63 ++++++++++ test/constant_time/openssl.supp | 9 ++ test/constant_time/package-lock.json | 10 ++ test/constant_time/package.json | 1 + test/constant_time/valgrind.mjs | 26 ++++ 16 files changed, 662 insertions(+), 1 deletion(-) create mode 100644 test/constant_time/Jamfile create mode 100644 test/constant_time/ctgrind_planted_test.cpp create mode 100644 test/constant_time/ctgrind_test.cpp create mode 100644 test/constant_time/dudect.hpp create mode 100644 test/constant_time/dudect_test.cpp create mode 100644 test/constant_time/msan_planted_test.cpp create mode 100644 test/constant_time/msan_report.mjs create mode 100644 test/constant_time/msan_test.cpp create mode 100644 test/constant_time/openssl.supp create mode 100644 test/constant_time/package-lock.json create mode 100644 test/constant_time/package.json create mode 100644 test/constant_time/valgrind.mjs diff --git a/.gitignore b/.gitignore index a6516011..6db4c4e1 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,3 @@ doc/html/ +node_modules +.node-modules/ diff --git a/doc/backends.adoc b/doc/backends.adoc index e2eb962a..00b0f5cc 100644 --- a/doc/backends.adoc +++ b/doc/backends.adoc @@ -91,6 +91,24 @@ as webcpp compiles it, per target, is not taken in this version. include::generated/constant-time.adoc[] +The own lane `constant-time` (`libs/crypto/test/constant_time`) checks the code +as webcpp compiles it, natively on Linux: under Valgrind's memcheck, as +link:https://github.com/agl/ctgrind[ctgrind] does, and under MemorySanitizer, +the key, the data and the tag are marked secret, and any branch or memory index +that depends on them fails the run. It covers `equal`, BearSSL's AES-GCM `make`, +`seal` and `open`, OpenSSL's `make` and `seal`, ctaes's AES, and libsecp256k1's +own `ctime_tests.c`; each check is shown to fail on a planted branch on a key +byte. dudect's statistics (link:https://eprint.iacr.org/2016/1123[Reparaz, +Balasch and Verbauwhede]) time BearSSL's seal and open, ctaes and `equal` +natively and under wasmtime. + +Whether a tag matched is public by design, since `open` reports it, but it is +computed from the key and the tag: it is the one value webcpp marks public +(BearSSL's engines declassify it where webcpp first branches on it), so that +the checkers report every other branch. OpenSSL's verdict is OpenSSL's own +internal branch, which webcpp cannot mark: OpenSSL is checked with the key +secret during `seal` only. + [#crypto-backends-sizes] === Size and speed diff --git a/doc/testing.adoc b/doc/testing.adoc index 0d3d5629..484799a4 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -39,7 +39,11 @@ same build of libsodium that crypto links: each program of its `test/default`, those of crypto's operations among them (`sign`, `box`, `box2`, `box7`, `box8`, `box_seal`, `secretbox`, `secretbox2`, `secretbox7`, `secretbox8`, `aead_chacha20poly1305`, `aead_chacha20poly13052`, `aead_xchacha20poly1305`, -`kx`, `scalarmult`, `ed25519_convert`), compared with its `.exp`. +`kx`, `scalarmult`, `ed25519_convert`), compared with its `.exp`. The own lane +`constant-time`, natively on Linux with Valgrind and clang's MemorySanitizer, +and on wasip2, checks constant time (<>): the +native lane's command with `libs/crypto/test/constant_time//constant-time` in +place of the two directories. What the tests check: diff --git a/test/Jamfile b/test/Jamfile index 4fdb6fe0..a9dc2fb6 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -245,6 +245,10 @@ webcpp.compile-diagnostic random_device_no_call : random_device_no_call_test.cpp # The C libraries' own suites, in the own lane c-suites. build-project c_suites ; +# Constant time under memcheck, MemorySanitizer and dudect, in the own lane +# constant-time. +build-project constant_time ; + # A backend named and not called adds no byte (webcpp.same-program). build-project unused ; diff --git a/test/constant_time/Jamfile b/test/constant_time/Jamfile new file mode 100644 index 00000000..bf7ee0be --- /dev/null +++ b/test/constant_time/Jamfile @@ -0,0 +1,115 @@ +# 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) + +# Constant time (spec section 8.3): Valgrind and MemorySanitizer on Linux, and +# dudect's statistics natively and under wasmtime, as the own lane +# constant-time, outside the ordinary lanes. Each deterministic check is shown +# to fail on a planted leak, a branch on a key byte. The paths are version +# 0.1's: BearSSL's AES-GCM make, seal and open, OpenSSL's make and seal (its +# open branches on the verdict inside OpenSSL, where webcpp cannot mark it +# public), ctaes's make, encrypt and decrypt, equal, and libsecp256k1's own +# ctime_tests.c. MemorySanitizer builds only with clang. +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +webcpp.targets native wasip2 ; + +webcpp.original node ; + +# Valgrind and MemorySanitizer run on Linux alone: elsewhere their programs +# are not built, and the lane runs dudect_bearssl alone. +rule linux-only ( properties * ) +{ + if ! linux in $(properties) + { + return no ; + } +} + +# The libraries the memcheck programs link: BearSSL, OpenSSL and ctaes. +CTGRIND = /third_party//bearssl /webcpp/crypto//openssl + /third_party//ctaes release on + @linux-only + WEBCPP_CRYPTO_DETAIL_CT_VALGRIND 300 ; + +webcpp.drive ctgrind : ctgrind_test.cpp : $(CTGRIND) : valgrind.mjs : : native ; +# The planted leak: the same program must fail under memcheck. +webcpp.drive ctgrind_planted : ctgrind_planted_test.cpp + : $(CTGRIND) WEBCPP_TEST_CRYPTO_PLANTED_LEAK + : valgrind.mjs : --expect-leak : native ; +# equal compiles in the user's translation unit, so it is checked at both +# optimisations of spec section 2.6, each a program of its own. +webcpp.drive ctgrind_speed : ctgrind_test.cpp : $(CTGRIND) speed + : valgrind.mjs : : native ; +webcpp.drive ctgrind_space : ctgrind_test.cpp : $(CTGRIND) space + : valgrind.mjs : : native ; + +# MemorySanitizer's checking of what a function is passed and returns, eager +# since clang 16, is off: a value derived from a secret is passed and returned +# by design, and only a branch or an index on one is a leak. libsecp256k1's +# build turns it off for its ctime_tests in the same way (its configure.ac). +MSAN_FLAGS = -fsanitize=memory -fno-sanitize-memory-param-retval ; + +# BearSSL's and ctaes's sources once more, instrumented, for MemorySanitizer +# alone (it reports falsely through code it did not compile), with +# third_party/Jamfile's defines for Linux and webcpp's canaries. +path-constant BEARSSL : ../../../../third_party/libs/bearssl ; +path-constant CTAES : ../../../../third_party/libs/bitcoin/src/crypto/ctaes ; +lib bearssl_msan + : [ glob $(BEARSSL)/src/*.c $(BEARSSL)/src/*/*.c ] ../../src/canary_bearssl.c + : static off off $(BEARSSL)/inc + $(BEARSSL)/src ../../include BR_RDRAND=0 + BR_USE_URANDOM=0 BR_USE_GETENTROPY=1 _DEFAULT_SOURCE + $(MSAN_FLAGS) @linux-only + : : $(BEARSSL)/inc WEBCPP_CRYPTO_HAS_BEARSSL=1 ; +explicit bearssl_msan ; +lib ctaes_msan : $(CTAES)/ctaes.c ../../src/canary_ctaes.c + : static off off $(CTAES) + ../../include $(MSAN_FLAGS) @linux-only + : : $(CTAES) WEBCPP_CRYPTO_HAS_CTAES=1 ; +explicit ctaes_msan ; + +# BearSSL stays on its portable code, whose plain C MemorySanitizer follows +# exactly; the engine marks the tag's verdict public. +MSAN = bearssl_msan ctaes_msan + WEBCPP_CRYPTO_DETAIL_BEARSSL_PORTABLE WEBCPP_CRYPTO_DETAIL_CT_MSAN + $(MSAN_FLAGS) -fsanitize=memory release + on @linux-only ; + +webcpp.run msan : msan_test.cpp : $(MSAN) : native ; +# The planted leak under MemorySanitizer: passes only on MemorySanitizer's own +# report of it, never on any other failure. +webcpp.drive msan_planted : msan_planted_test.cpp + : $(MSAN) WEBCPP_TEST_CRYPTO_PLANTED_LEAK : msan_report.mjs : : native ; + +# libsecp256k1's own constant-time test, src/ctime_tests.c, unchanged, with +# the library's sources compiled into the program as its CMake builds them +# (ctime_tests links the library, which must be built with the same checker's +# interface): with VALGRIND under memcheck, and with MemorySanitizer, which +# its checkmem.h prefers when the compiler has it. +path-constant SECP256K1 : ../../../../third_party/libs/secp256k1 ; +SECP256K1_CTIME = $(SECP256K1)/src/ctime_tests.c $(SECP256K1)/src/secp256k1.c + $(SECP256K1)/src/precomputed_ecmult.c + $(SECP256K1)/src/precomputed_ecmult_gen.c ; +webcpp.drive secp256k1_ctime : $(SECP256K1_CTIME) + : /third_party//secp256k1-test-config off + off VALGRIND release on + 600 @linux-only + : valgrind.mjs : : native ; +webcpp.run secp256k1_ctime_msan : $(SECP256K1_CTIME) + : /third_party//secp256k1-test-config off + off $(MSAN_FLAGS) -fsanitize=memory + release on @linux-only : native ; + +# dudect's statistics on BearSSL, ctaes and equal, natively and under wasmtime. +webcpp.run dudect_bearssl : dudect_test.cpp + : /third_party//bearssl /third_party//ctaes release + : native wasip2 ; + +webcpp.lane constant-time : ctgrind ctgrind_planted ctgrind_speed ctgrind_space + msan msan_planted secp256k1_ctime secp256k1_ctime_msan dudect_bearssl + : native wasip2 ; diff --git a/test/constant_time/ctgrind_planted_test.cpp b/test/constant_time/ctgrind_planted_test.cpp new file mode 100644 index 00000000..bc4fe3a3 --- /dev/null +++ b/test/constant_time/ctgrind_planted_test.cpp @@ -0,0 +1,9 @@ +// 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) + +// ctgrind_test.cpp with WEBCPP_TEST_CRYPTO_PLANTED_LEAK, a source of its own so that b2 compiles it +// with its own defines: the build the lane expects the checker to fail. +#include "ctgrind_test.cpp" // NOLINT(bugprone-suspicious-include) diff --git a/test/constant_time/ctgrind_test.cpp b/test/constant_time/ctgrind_test.cpp new file mode 100644 index 00000000..68555ce9 --- /dev/null +++ b/test/constant_time/ctgrind_test.cpp @@ -0,0 +1,100 @@ +// 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) + +// Under Valgrind's memcheck, the key, the plaintext, the block and the tag are marked undefined: +// a branch or a memory index that depends on them is an error, and the run fails +// (--error-exitcode). It covers equal; make, seal and open of BearSSL's AES-GCM; make and seal +// of OpenSSL's; and make, encrypt and decrypt of ctaes's AES. + +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +namespace { + +/** make, seal and open of BearSSL with the key, the data and the tag secret. */ +int bearssl_seal_and_open() { + namespace crypto = webcpp::crypto; + std::array key{}; + std::array const iv{}; + std::array data{}; + key.fill(0x42); + data.fill(0x17); + VALGRIND_MAKE_MEM_UNDEFINED(key.data(), key.size()); + VALGRIND_MAKE_MEM_UNDEFINED(data.data(), data.size()); +#ifdef WEBCPP_TEST_CRYPTO_PLANTED_LEAK + // The planted leak: a branch on a secret byte, which memcheck must report. + if (key[0] == 0x42) { + std::printf("planted\n"); + } +#endif + auto made = crypto::ciphers::gcm>::make(key); + auto tag = made->seal(iv, {}, data); + VALGRIND_MAKE_MEM_UNDEFINED(tag->data(), tag->size()); + // The verdict is declassified inside the engine (WEBCPP_CRYPTO_DETAIL_DECLASSIFY). + auto const opened = made->open(iv, {}, data, *tag); + // And only because of that mark is the verdict defined: checked, since an optimiser may + // turn the engine's branch on it into a select, which memcheck does not report. + bool const verdict = opened.has_value(); + static_cast(VALGRIND_CHECK_VALUE_IS_DEFINED(verdict)); + return verdict ? 0 : 1; +} + +/** + * make and seal of OpenSSL with the key and the data secret. Its open is not checked with + * secrets: OpenSSL branches on the tag's verdict inside EVP_DecryptFinal_ex, where webcpp + * cannot declassify it; the documentation says so. + */ +int openssl_seal() { + namespace crypto = webcpp::crypto; + std::array key{}; + std::array const iv{}; + std::array data{}; + key.fill(0x42); + data.fill(0x17); + VALGRIND_MAKE_MEM_UNDEFINED(key.data(), key.size()); + VALGRIND_MAKE_MEM_UNDEFINED(data.data(), data.size()); + auto made = crypto::ciphers::gcm>::make(key); + auto const tag = made->seal(iv, {}, data); + return tag ? 0 : 1; +} + +/** make, encrypt and decrypt of ctaes with the key and the block secret. */ +int ctaes_block() { + namespace crypto = webcpp::crypto; + std::array key{}; + std::array block{}; + key.fill(0x42); + block.fill(0x17); + VALGRIND_MAKE_MEM_UNDEFINED(key.data(), key.size()); + VALGRIND_MAKE_MEM_UNDEFINED(block.data(), block.size()); + auto made = crypto::ciphers::aes256::make(key); + bool const ok = made && made->encrypt(block) && made->decrypt(block); + return ok ? 0 : 1; +} + +} // namespace + +int main() { + std::array a{}; + std::array b{}; + VALGRIND_MAKE_MEM_UNDEFINED(a.data(), a.size()); + VALGRIND_MAKE_MEM_UNDEFINED(b.data(), b.size()); + bool equal = webcpp::crypto::equal(a, b); + VALGRIND_MAKE_MEM_DEFINED(&equal, sizeof equal); // the test's own branch below + int const failures = (equal ? 0 : 1) + bearssl_seal_and_open() + openssl_seal() + ctaes_block(); + std::printf("constant time under memcheck: %s\n", failures == 0 ? "ok" : "FAILED"); + return failures; +} diff --git a/test/constant_time/dudect.hpp b/test/constant_time/dudect.hpp new file mode 100644 index 00000000..9300c840 --- /dev/null +++ b/test/constant_time/dudect.hpp @@ -0,0 +1,129 @@ +// 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) + +// Welch's t-test over two classes of timings, with dudect's cropping. + +#ifndef WEBCPP_TEST_CRYPTO_DUDECT_HPP +#define WEBCPP_TEST_CRYPTO_DUDECT_HPP + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::test { + +/** Online mean and variance of one class, Welford's. */ +struct moments { + /** The number of values pushed. */ + double n = 0; + /** Their mean. */ + double mean = 0; + /** The sum of squared differences from the mean. */ + double m2 = 0; + + /** + * Adds a value. + * @param x The value. + */ + void push(double x) { + n += 1; + double const delta = x - mean; + mean += delta / n; + m2 += delta * (x - mean); + } + + /** + * The sample variance. + * @return The variance, 0 below two values. + */ + [[nodiscard]] double variance() const { return n > 1 ? m2 / (n - 1) : 0; } +}; + +/** + * Welch's t of two classes. + * @param a The first class. + * @param b The second class. + * @return t, 0 when both variances are 0. + */ +inline double welch(moments const& a, moments const& b) { + double const denominator = std::sqrt(a.variance() / a.n + b.variance() / b.n); + return denominator == 0 ? 0 : (a.mean - b.mean) / denominator; +} + +/** + * The largest |t| over the whole set and dudect's 100 croppings. + * @param timings The measurements. + * @param classes The class, 0 or 1, of each. + * @return The largest |t|. + */ +inline double largest_t(std::vector const& timings, std::vector const& classes) { + std::vector sorted = timings; + std::sort(sorted.begin(), sorted.end()); + double largest = 0; + for (int k = -1; k < 100; ++k) { + double const keep = k < 0 ? 1.0 : 1.0 - std::pow(0.5, 10.0 * (k + 1) / 100.0); + double const limit = + sorted[static_cast(keep * static_cast(sorted.size() - 1))]; + std::array m{}; + for (std::size_t i = 0; i < timings.size(); ++i) { + if (timings[i] <= limit) { + m[static_cast(classes[i])].push(timings[i]); + } + } + largest = (std::max)(largest, std::fabs(welch(m[0], m[1]))); + } + return largest; +} + +/** + * The largest |t| of `count` measurements of `run`, each after `prepare(class, generator)` + * with a class drawn at random from the seeded generator, prepare unmeasured. + * @param seed The generator's seed. + * @param count The number of measurements. + * @param prepare Sets up the class's input, unmeasured. + * @param run The operation measured. + * @return The largest |t|. + */ +template +double measure(std::uint64_t seed, std::size_t count, Prepare&& prepare, Run&& run) { + std::mt19937_64 generator(seed); + std::vector timings; + std::vector classes; + timings.reserve(count); + classes.reserve(count); + for (std::size_t i = 0; i < count; ++i) { + int const which = static_cast(generator() & 1U); + prepare(which, generator); + auto const start = std::chrono::steady_clock::now(); + run(); + auto const end = std::chrono::steady_clock::now(); + timings.push_back(std::chrono::duration(end - start).count()); + classes.push_back(which); + } + return largest_t(timings, classes); +} + +/** + * The largest |t| of a first run, and of a second with another seed when the first exceeds 10. + * @param count The number of measurements of each run. + * @param prepare Sets up the class's input, unmeasured. + * @param run The operation measured. + * @return The first run's |t| below 10, else the smaller of the two runs'. + */ +template +double twice(std::size_t count, Prepare&& prepare, Run&& run) { + double const first = measure(20261011, count, prepare, run); + return first < 10 ? first : (std::min)(first, measure(20261012, count, prepare, run)); +} + +} // namespace webcpp::test + +#endif diff --git a/test/constant_time/dudect_test.cpp b/test/constant_time/dudect_test.cpp new file mode 100644 index 00000000..6736d891 --- /dev/null +++ b/test/constant_time/dudect_test.cpp @@ -0,0 +1,121 @@ +// 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) + +// dudect's statistics (spec section 8.3): BearSSL's AES-GCM seal's time against its key, open's +// against its tag (the failure's zeroing included), ctaes's block encryption's against its key, +// and equal's against its second argument; natively and under wasmtime, where the engine's +// compiler decides whether BearSSL's 64-bit multiplication stays constant time. + +#include "dudect.hpp" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace { + +/** + * Draws `Size` bytes, then copies into `input` either `fixed`, for class 0, or the drawn bytes, + * for class 1. Both classes draw the same bytes and store the same way: the source is chosen + * through a volatile pointer, which the compiler cannot see through, so that it cannot split + * the copy by class into a store of constants for one and of drawn bytes for the other. Such + * a split, which an optimiser makes of `which == 0 ? 0 : drawn`, leaks the class into the + * measured call (measured natively on an Apple M5, 2026-11-18: |t| 16 to 18 on equal and 9 to + * 26 on open with the split, below 3 for both through this copy). + * @param which The class, 0 or 1. + * @param generator The seeded generator. + * @param fixed The class 0 input. + * @param input Where the input of the class is copied. + */ +template +void choose(int which, Generator& generator, std::array const& fixed, + std::array& input) { + std::array drawn{}; + for (auto& byte : drawn) { + byte = static_cast(generator()); + } + std::uint8_t const* volatile chosen = which == 0 ? fixed.data() : drawn.data(); + std::uint8_t const* const source = chosen; + std::copy(source, source + Size, input.begin()); +} + +} // namespace + +int main() { + namespace crypto = webcpp::crypto; + using aead = crypto::ciphers::gcm>; + using block_cipher = crypto::ciphers::aes256; + constexpr std::size_t count = 2'000'000; + std::array const zero_key{}; + std::array key{}; + std::array const iv{}; + std::array data{}; + std::optional made; + + // The classes differ only in the key: all zero, against random keys. + double const seal_t = webcpp::test::twice( + count, + [&](int which, auto& generator) { + choose(which, generator, zero_key, key); + made.emplace(*aead::make(key)); + }, + [&] { static_cast(made->seal(iv, {}, data)); }); + + key.fill(0x42); + made.emplace(*aead::make(key)); + std::array const plaintext{}; + std::array ciphertext = plaintext; + auto const right = *made->seal(iv, {}, ciphertext); + // Both classes fail: the right tag with its last byte flipped, against random wrong tags, + // the classic probe of an early exit; a success and a failure differ by design (the + // failure zeroes data and returns another way), and that difference is public. + std::array nearly_right{}; + std::copy(right.data(), right.data() + right.size(), nearly_right.begin()); + nearly_right[15] ^= 1; + std::array tag{}; + double const open_t = webcpp::test::twice( + count, + [&](int which, auto& generator) { + data = ciphertext; + choose(which, generator, nearly_right, tag); + if (std::equal(tag.begin(), tag.end(), right.data())) { + tag[15] ^= 1; // a random tag equal to the right one, which never happens + } + }, + [&] { static_cast(made->open(iv, {}, data, tag)); }); + + std::optional block_made; + std::array block{}; + double const block_t = webcpp::test::twice( + count, + [&](int which, auto& generator) { + choose(which, generator, zero_key, key); + block_made.emplace(*block_cipher::make(key)); + block.fill(0); + }, + [&] { static_cast(block_made->encrypt(block)); }); + + std::array const a{}; + std::array b{}; + bool volatile sink = false; // keeps the comparison from being optimised away + // The classes differ only in the second argument: equal to the first, against random. + double const equal_t = webcpp::test::twice( + count, [&](int which, auto& generator) { choose(which, generator, a, b); }, + [&] { sink = crypto::equal(a, b); }); + + std::printf("|t| seal %.2f, open %.2f, ctaes %.2f, equal %.2f (threshold 10)\n", seal_t, open_t, + block_t, equal_t); + return seal_t < 10 && open_t < 10 && block_t < 10 && equal_t < 10 ? 0 : 1; +} diff --git a/test/constant_time/msan_planted_test.cpp b/test/constant_time/msan_planted_test.cpp new file mode 100644 index 00000000..0e5c7bca --- /dev/null +++ b/test/constant_time/msan_planted_test.cpp @@ -0,0 +1,9 @@ +// 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) + +// msan_test.cpp with WEBCPP_TEST_CRYPTO_PLANTED_LEAK, a source of its own so that b2 compiles it +// with its own defines: the build the lane expects the checker to fail. +#include "msan_test.cpp" // NOLINT(bugprone-suspicious-include) diff --git a/test/constant_time/msan_report.mjs b/test/constant_time/msan_report.mjs new file mode 100644 index 00000000..a406f8f6 --- /dev/null +++ b/test/constant_time/msan_report.mjs @@ -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) + +// Runs the planted build under MemorySanitizer and passes only when MemorySanitizer reported a +// use of an uninitialised value in the planted branch, with its exit code 77. Any other end of +// the program, a crash or a success, fails. The report is symbolised by the toolchain's +// llvm-symbolizer (llvm-symbolizer-18 on the lane's runner, installed with the lane's +// packages), named in MSAN_SYMBOLIZER_PATH; without symbols the frames are bare addresses, +// so the driver refuses to judge and says what is missing. +import {spawnSync} from 'node:child_process' + +const program = process.argv[process.argv.length - 1] +const symbolizer = ['llvm-symbolizer-18', 'llvm-symbolizer'] + .map(name => spawnSync('sh', ['-c', `command -v ${name}`], {encoding: 'utf8'}).stdout.trim()) + .find(path => path !== '') +if (symbolizer === undefined) { + console.error('msan_planted: no llvm-symbolizer-18 or llvm-symbolizer on PATH; install ' + + 'llvm-18 (the lane constant-time lists it among its packages)') + process.exit(1) +} +const run = spawnSync(program, [], { + encoding: 'utf8', + env: {...process.env, MSAN_OPTIONS: 'exitcode=77', MSAN_SYMBOLIZER_PATH: symbolizer}, +}) +process.stdout.write(run.stdout ?? '') +process.stderr.write(run.stderr ?? '') +const stderr = run.stderr ?? '' +const reported = stderr.includes('WARNING: MemorySanitizer: use-of-uninitialized-value') +// The planted branch is in main, in msan_test.cpp: the first frame or the SUMMARY line names it. +const inTheTest = /msan_test\.cpp:\d+/.test(stderr) || + /^SUMMARY: MemorySanitizer: use-of-uninitialized-value .* in main$/m.test(stderr) +if (run.status === 77 && reported && inTheTest) { + console.log('msan_planted: MemorySanitizer reported the planted branch') + process.exit(0) +} +console.error(`msan_planted: expected MemorySanitizer's report in msan_test.cpp and exit 77; ` + + `got status ${run.status}, signal ${run.signal}, report ${reported}, in the test ${inTheTest}`) +process.exit(1) diff --git a/test/constant_time/msan_test.cpp b/test/constant_time/msan_test.cpp new file mode 100644 index 00000000..c5eac81c --- /dev/null +++ b/test/constant_time/msan_test.cpp @@ -0,0 +1,63 @@ +// 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) + +// MemorySanitizer's poisoning (spec section 8.3): the key, the plaintext, the block and the tag +// are poisoned, and a branch or an index that depends on them, in webcpp's code, BearSSL's or +// ctaes's, all instrumented, ends the run with a report. + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array a{}; + std::array b{}; + __msan_poison(a.data(), a.size()); + __msan_poison(b.data(), b.size()); + bool same = crypto::equal(a, b); + __msan_unpoison(&same, sizeof same); + + std::array key{}; + std::array const iv{}; + std::array data{}; + __msan_poison(key.data(), key.size()); + __msan_poison(data.data(), data.size()); +#ifdef WEBCPP_TEST_CRYPTO_PLANTED_LEAK + if (key[0] == 0) { // the planted leak: MemorySanitizer must report it + std::printf("planted\n"); + } +#endif + auto made = crypto::ciphers::gcm>::make(key); + auto tag = made->seal(iv, {}, data); + __msan_poison(tag->data(), tag->size()); + // The verdict is declassified inside the engine (WEBCPP_CRYPTO_DETAIL_DECLASSIFY). That mark's + // teeth are memcheck's (ctgrind_test.cpp): MemorySanitizer's propagation already finds + // br_gcm_check_tag's result initialised for a poisoned tag without it (clang 18, measured + // 2026-11-18), so a build without the mark passes here too. + auto const opened = made->open(iv, {}, data, *tag); + bool const verdict = opened.has_value(); + + // ctaes's make, encrypt and decrypt with the key and the block poisoned. + std::array block{}; + __msan_poison(key.data(), key.size()); + __msan_poison(block.data(), block.size()); + auto block_cipher = crypto::ciphers::aes256::make(key); + bool const block_ok = + block_cipher && block_cipher->encrypt(block) && block_cipher->decrypt(block); + + bool const ok = verdict && block_ok && same; + std::printf("constant time under MemorySanitizer: %s\n", ok ? "ok" : "FAILED"); + return ok ? 0 : 1; +} diff --git a/test/constant_time/openssl.supp b/test/constant_time/openssl.supp new file mode 100644 index 00000000..57b04995 --- /dev/null +++ b/test/constant_time/openssl.supp @@ -0,0 +1,9 @@ +# 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) +# +# Valgrind's suppressions for valgrind.mjs: each frame of libcrypto's own start-up code that +# memcheck reports and that no secret reaches, with its reason; never a frame of seal. None is +# needed today: the Linux runs of the lane (arm64 by hand, 2026-11-18) report none. diff --git a/test/constant_time/package-lock.json b/test/constant_time/package-lock.json new file mode 100644 index 00000000..6b330057 --- /dev/null +++ b/test/constant_time/package-lock.json @@ -0,0 +1,10 @@ +{ + "name": "webcpp-crypto-constant-time", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "webcpp-crypto-constant-time" + } + } +} diff --git a/test/constant_time/package.json b/test/constant_time/package.json new file mode 100644 index 00000000..c6c080d7 --- /dev/null +++ b/test/constant_time/package.json @@ -0,0 +1 @@ +{"name": "webcpp-crypto-constant-time", "private": true} diff --git a/test/constant_time/valgrind.mjs b/test/constant_time/valgrind.mjs new file mode 100644 index 00000000..b5413233 --- /dev/null +++ b/test/constant_time/valgrind.mjs @@ -0,0 +1,26 @@ +// 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) + +// Runs the program under Valgrind's memcheck and passes with its exit status: 99 when +// memcheck found a use of an undefined value, which a branch on a secret is. +// With --expect-leak, it passes only when memcheck found one: the planted leak's build. +import {spawnSync} from 'node:child_process' +import {dirname, join} from 'node:path' +import {fileURLToPath} from 'node:url' + +const program = process.argv[process.argv.length - 1] +const expectLeak = process.argv.includes('--expect-leak') +const suppressions = join(dirname(fileURLToPath(import.meta.url)), 'openssl.supp') +const run = spawnSync('valgrind', ['--error-exitcode=99', '--track-origins=yes', '--quiet', + `--suppressions=${suppressions}`, program], {stdio: 'inherit'}) +if (run.error) { + console.error(`valgrind could not run: ${run.error.message}; install valgrind (Linux)`) + process.exit(1) +} +if (expectLeak) { + process.exit(run.status === 99 ? 0 : 1) +} +process.exit(run.status ?? 1) From 137148620a27eff45823d2f496ba1dde5587e154 Mon Sep 17 00:00:00 2001 From: R Date: Wed, 18 Nov 2026 07:59:39 -0300 Subject: [PATCH 053/110] crypto: the constant-time lane's review fixes: MemorySanitizer's verdict check, clang-only MSan, one optimisation each, and the page msan_test checks the verdict initialised, the twin of ctgrind's check, and says, as measured, why it still passes without the declassification: MSan approximates a subtraction's shadow without the carry, so BearSSL's EQ0 comes out initialised. The MSan programs and libraries build with clang on Linux alone; ctgrind_speed, ctgrind again under release, is gone; dudect's code is clean under clang-tidy. The Jamfile says how a later family adds its cases, libsecp256k1's included. The backends page no longer calls the code unmeasured, testing.adoc says which part runs where, and aead.adoc's open links the constant-time section. --- doc/aead.adoc | 4 ++- doc/backends.adoc | 10 ++++--- doc/testing.adoc | 9 +++--- test/constant_time/Jamfile | 45 +++++++++++++++++++++++------- test/constant_time/dudect.hpp | 4 +-- test/constant_time/dudect_test.cpp | 4 +-- test/constant_time/msan_test.cpp | 13 ++++++--- 7 files changed, 62 insertions(+), 27 deletions(-) diff --git a/doc/aead.adoc b/doc/aead.adoc index 45d27ef0..c1f4b3a1 100644 --- a/doc/aead.adoc +++ b/doc/aead.adoc @@ -105,7 +105,9 @@ tag in one pass; when the tag does not match, crypto zeroes the whole of `data_bytes`, so that no unauthenticated plaintext is left. A caller who needs the ciphertext after a failure keeps a copy. A guard's refusal (`invalid_state`, `invalid_iv_size`, `invalid_tag_size`, `message_too_long`) -comes before any work and leaves `data_bytes` untouched. +comes before any work and leaves `data_bytes` untouched. Whether the tag +matched is the one value derived from the key that crypto treats as public +(<>). * *Plaintext is in `data_bytes` while `open` runs.* The decrypted bytes sit in `data_bytes` before the tag is checked. When `data_bytes` is memory another party can read during the call (a shared segment, a `SharedArrayBuffer` that diff --git a/doc/backends.adoc b/doc/backends.adoc index 00b0f5cc..10bb628a 100644 --- a/doc/backends.adoc +++ b/doc/backends.adoc @@ -86,13 +86,15 @@ A cryptographic implementation is *constant time* when its running time and its memory accesses do not depend on secret data; otherwise a timing attack can recover the key (link:https://en.wikipedia.org/wiki/Timing_attack[Wikipedia]; link:https://www.bearssl.org/constanttime.html[BearSSL's explanation]). Each -backend's design is stated by its library; crypto's own measurement of the code -as webcpp compiles it, per target, is not taken in this version. +backend's design is stated by its library. The table's measured columns are +not filled in this version: the own lane below checks the code as webcpp +compiles it, and its results join the table when they are recorded in the +documentation's data, in a later version. include::generated/constant-time.adoc[] The own lane `constant-time` (`libs/crypto/test/constant_time`) checks the code -as webcpp compiles it, natively on Linux: under Valgrind's memcheck, as +as webcpp compiles it. On Linux, under Valgrind's memcheck, as link:https://github.com/agl/ctgrind[ctgrind] does, and under MemorySanitizer, the key, the data and the tag are marked secret, and any branch or memory index that depends on them fails the run. It covers `equal`, BearSSL's AES-GCM `make`, @@ -100,7 +102,7 @@ that depends on them fails the run. It covers `equal`, BearSSL's AES-GCM `make`, own `ctime_tests.c`; each check is shown to fail on a planted branch on a key byte. dudect's statistics (link:https://eprint.iacr.org/2016/1123[Reparaz, Balasch and Verbauwhede]) time BearSSL's seal and open, ctaes and `equal` -natively and under wasmtime. +natively, on Linux and macOS, and under wasmtime. Whether a tag matched is public by design, since `open` reports it, but it is computed from the key and the tag: it is the one value webcpp marks public diff --git a/doc/testing.adoc b/doc/testing.adoc index 484799a4..21d4989d 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -40,10 +40,11 @@ those of crypto's operations among them (`sign`, `box`, `box2`, `box7`, `box8`, `box_seal`, `secretbox`, `secretbox2`, `secretbox7`, `secretbox8`, `aead_chacha20poly1305`, `aead_chacha20poly13052`, `aead_xchacha20poly1305`, `kx`, `scalarmult`, `ed25519_convert`), compared with its `.exp`. The own lane -`constant-time`, natively on Linux with Valgrind and clang's MemorySanitizer, -and on wasip2, checks constant time (<>): the -native lane's command with `libs/crypto/test/constant_time//constant-time` in -place of the two directories. +`constant-time` checks constant time (<>): +natively, Valgrind and clang's MemorySanitizer on Linux and dudect's statistics +on Linux and macOS, and dudect's under wasmtime on wasip2; the native lane's +command with `libs/crypto/test/constant_time//constant-time` in place of the +two directories. What the tests check: diff --git a/test/constant_time/Jamfile b/test/constant_time/Jamfile index bf7ee0be..2ccd4a47 100644 --- a/test/constant_time/Jamfile +++ b/test/constant_time/Jamfile @@ -11,7 +11,22 @@ # 0.1's: BearSSL's AES-GCM make, seal and open, OpenSSL's make and seal (its # open branches on the verdict inside OpenSSL, where webcpp cannot mark it # public), ctaes's make, encrypt and decrypt, equal, and libsecp256k1's own -# ctime_tests.c. MemorySanitizer builds only with clang. +# ctime_tests.c. +# +# A later family adds its cases to ctgrind_test.cpp and msan_test.cpp, as +# BearSSL's are here: its secrets marked, its verdicts declassified where +# webcpp branches on them, and its C library built twice more for the lane, +# beside the programs. For libsecp256k1 (stream B, Task 2.7): libsecp256k1 +# marks its own public branches (a nonce's retry, a verdict) only when it is +# compiled with VALGRIND, or with MemorySanitizer, and its context is created +# with SECP256K1_CONTEXT_DECLASSIFY (secp256k1.c, as ctime_tests.c does); so +# the lane needs a lib of its sources and tables built with +# VALGRIND, which the memcheck programs link in place of +# /third_party//secp256k1, a seam under WEBCPP_CRYPTO_DETAIL_CT_VALGRIND and +# WEBCPP_CRYPTO_DETAIL_CT_MSAN that creates webcpp's context with that flag, +# and a secp256k1_msan lib, instrumented as bearssl_msan is. +# secp256k1_ctime and secp256k1_ctime_msan below compile the sources into +# upstream's program and serve none of webcpp's own calls. project : requirements /webcpp/crypto//crypto ; import webcpp ; @@ -30,6 +45,16 @@ rule linux-only ( properties * ) } } +# MemorySanitizer is clang's alone: its programs and libraries are built with +# clang on Linux, and not with GCC (-fsanitize=memory is no option of GCC's). +rule clang-on-linux ( properties * ) +{ + if ! linux in $(properties) || ! clang in $(properties) + { + return no ; + } +} + # The libraries the memcheck programs link: BearSSL, OpenSSL and ctaes. CTGRIND = /third_party//bearssl /webcpp/crypto//openssl /third_party//ctaes release on @@ -42,9 +67,9 @@ webcpp.drive ctgrind_planted : ctgrind_planted_test.cpp : $(CTGRIND) WEBCPP_TEST_CRYPTO_PLANTED_LEAK : valgrind.mjs : --expect-leak : native ; # equal compiles in the user's translation unit, so it is checked at both -# optimisations of spec section 2.6, each a program of its own. -webcpp.drive ctgrind_speed : ctgrind_test.cpp : $(CTGRIND) speed - : valgrind.mjs : : native ; +# optimisations of spec section 2.6: ctgrind is release, which is +# speed in b2, and ctgrind_space the other, a program of its +# own. (The genesis's ctgrind_speed would be ctgrind built and run again.) webcpp.drive ctgrind_space : ctgrind_test.cpp : $(CTGRIND) space : valgrind.mjs : : native ; @@ -64,12 +89,12 @@ lib bearssl_msan : static off off $(BEARSSL)/inc $(BEARSSL)/src ../../include BR_RDRAND=0 BR_USE_URANDOM=0 BR_USE_GETENTROPY=1 _DEFAULT_SOURCE - $(MSAN_FLAGS) @linux-only + $(MSAN_FLAGS) @clang-on-linux : : $(BEARSSL)/inc WEBCPP_CRYPTO_HAS_BEARSSL=1 ; explicit bearssl_msan ; lib ctaes_msan : $(CTAES)/ctaes.c ../../src/canary_ctaes.c : static off off $(CTAES) - ../../include $(MSAN_FLAGS) @linux-only + ../../include $(MSAN_FLAGS) @clang-on-linux : : $(CTAES) WEBCPP_CRYPTO_HAS_CTAES=1 ; explicit ctaes_msan ; @@ -78,7 +103,7 @@ explicit ctaes_msan ; MSAN = bearssl_msan ctaes_msan WEBCPP_CRYPTO_DETAIL_BEARSSL_PORTABLE WEBCPP_CRYPTO_DETAIL_CT_MSAN $(MSAN_FLAGS) -fsanitize=memory release - on @linux-only ; + on @clang-on-linux ; webcpp.run msan : msan_test.cpp : $(MSAN) : native ; # The planted leak under MemorySanitizer: passes only on MemorySanitizer's own @@ -103,13 +128,13 @@ webcpp.drive secp256k1_ctime : $(SECP256K1_CTIME) webcpp.run secp256k1_ctime_msan : $(SECP256K1_CTIME) : /third_party//secp256k1-test-config off off $(MSAN_FLAGS) -fsanitize=memory - release on @linux-only : native ; + release on @clang-on-linux : native ; # dudect's statistics on BearSSL, ctaes and equal, natively and under wasmtime. webcpp.run dudect_bearssl : dudect_test.cpp : /third_party//bearssl /third_party//ctaes release : native wasip2 ; -webcpp.lane constant-time : ctgrind ctgrind_planted ctgrind_speed ctgrind_space - msan msan_planted secp256k1_ctime secp256k1_ctime_msan dudect_bearssl +webcpp.lane constant-time : ctgrind ctgrind_planted ctgrind_space msan + msan_planted secp256k1_ctime secp256k1_ctime_msan dudect_bearssl : native wasip2 ; diff --git a/test/constant_time/dudect.hpp b/test/constant_time/dudect.hpp index 9300c840..b7ad177d 100644 --- a/test/constant_time/dudect.hpp +++ b/test/constant_time/dudect.hpp @@ -54,7 +54,7 @@ struct moments { * @return t, 0 when both variances are 0. */ inline double welch(moments const& a, moments const& b) { - double const denominator = std::sqrt(a.variance() / a.n + b.variance() / b.n); + double const denominator = std::sqrt((a.variance() / a.n) + (b.variance() / b.n)); return denominator == 0 ? 0 : (a.mean - b.mean) / denominator; } @@ -66,7 +66,7 @@ inline double welch(moments const& a, moments const& b) { */ inline double largest_t(std::vector const& timings, std::vector const& classes) { std::vector sorted = timings; - std::sort(sorted.begin(), sorted.end()); + std::ranges::sort(sorted); double largest = 0; for (int k = -1; k < 100; ++k) { double const keep = k < 0 ? 1.0 : 1.0 - std::pow(0.5, 10.0 * (k + 1) / 100.0); diff --git a/test/constant_time/dudect_test.cpp b/test/constant_time/dudect_test.cpp index 6736d891..529d38a9 100644 --- a/test/constant_time/dudect_test.cpp +++ b/test/constant_time/dudect_test.cpp @@ -83,7 +83,7 @@ int main() { // failure zeroes data and returns another way), and that difference is public. std::array nearly_right{}; std::copy(right.data(), right.data() + right.size(), nearly_right.begin()); - nearly_right[15] ^= 1; + nearly_right[15] ^= 1U; std::array tag{}; double const open_t = webcpp::test::twice( count, @@ -91,7 +91,7 @@ int main() { data = ciphertext; choose(which, generator, nearly_right, tag); if (std::equal(tag.begin(), tag.end(), right.data())) { - tag[15] ^= 1; // a random tag equal to the right one, which never happens + tag[15] ^= 1U; // a random tag equal to the right one, which never happens } }, [&] { static_cast(made->open(iv, {}, data, tag)); }); diff --git a/test/constant_time/msan_test.cpp b/test/constant_time/msan_test.cpp index c5eac81c..9aa89f8c 100644 --- a/test/constant_time/msan_test.cpp +++ b/test/constant_time/msan_test.cpp @@ -42,12 +42,17 @@ int main() { auto made = crypto::ciphers::gcm>::make(key); auto tag = made->seal(iv, {}, data); __msan_poison(tag->data(), tag->size()); - // The verdict is declassified inside the engine (WEBCPP_CRYPTO_DETAIL_DECLASSIFY). That mark's - // teeth are memcheck's (ctgrind_test.cpp): MemorySanitizer's propagation already finds - // br_gcm_check_tag's result initialised for a poisoned tag without it (clang 18, measured - // 2026-11-18), so a build without the mark passes here too. + // The verdict is declassified inside the engine (WEBCPP_CRYPTO_DETAIL_DECLASSIFY). auto const opened = made->open(iv, {}, data, *tag); + // And the verdict is checked initialised here, the twin of ctgrind_test.cpp's check: an + // optimiser may turn the engine's branch on it into a select, and neither the select nor + // what main passes on and returns is reported (-fno-sanitize-memory-param-retval). The mark's + // teeth are memcheck's all the same: without it this program passes too (measured with clang + // 18, 2026-11-18), since MemorySanitizer approximates a subtraction's shadow by its operands' + // without the carry, so that BearSSL's EQ0, ~(q | -q) >> 31, of an accumulated difference + // whose low byte is poisoned comes out initialised. bool const verdict = opened.has_value(); + __msan_check_mem_is_initialized(&verdict, sizeof verdict); // ctaes's make, encrypt and decrypt with the key and the block poisoned. std::array block{}; From 9e5ac7572b842e3193d6c734b5bbdddd77898101 Mon Sep 17 00:00:00 2001 From: R Date: Wed, 18 Nov 2026 03:56:09 -0300 Subject: [PATCH 054/110] crypto: SPKI, PKCS#8 and PEM for Ed25519 and X25519 --- README.md | 2 + build.jam | 11 + doc/changelog.adoc | 2 +- doc/crypto.adoc | 2 + doc/curves.adoc | 4 +- doc/formats.adoc | 98 ++++ doc/generated/backends-ed25519_formats.adoc | 20 + doc/generated/backends-pem.adoc | 20 + doc/generated/backends-x25519_formats.adoc | 20 + doc/generated/default-aliases.adoc | 5 + doc/generated/defaults.adoc | 6 + doc/generated/jamfiles.adoc | 16 + doc/generated/matrix.adoc | 33 ++ doc/generated/namespace-root.adoc | 9 +- doc/generated/sizes.adoc | 16 + doc/generated/use-cases.adoc | 8 + doc/llms.txt | 19 +- doc/root.adoc | 9 +- doc/tables/crypto.json | 62 +- doc/tables/generate.py | 5 +- example/Jamfile | 6 + example/key_formats.cpp | 118 ++++ example/key_formats.expected | 8 + include/webcpp/crypto.hpp | 12 +- include/webcpp/crypto/backends/sodium.hpp | 238 ++++++++ include/webcpp/crypto/curves/ed25519.hpp | 9 + .../webcpp/crypto/curves/ed25519/formats.hpp | 238 ++++++++ .../webcpp/crypto/curves/x25519/formats.hpp | 217 +++++++ include/webcpp/crypto/detail/capabilities.hpp | 49 ++ include/webcpp/crypto/detail/defaults.hpp | 8 + include/webcpp/crypto/pem.hpp | 378 ++++++++++++ test/Jamfile | 25 +- test/allocation_sodium_test.cpp | 52 +- test/capabilities_test.cpp | 24 + test/default_backend_test.cpp | 8 + test/formats_25519_openssl_oracle_test.cpp | 232 ++++++++ test/formats_25519_sodium_test.cpp | 537 ++++++++++++++++++ test/formats_25519_webcrypto_oracle_test.cpp | 260 +++++++++ test/support/capabilities.hpp | 11 +- 39 files changed, 2771 insertions(+), 26 deletions(-) create mode 100644 doc/formats.adoc create mode 100644 doc/generated/backends-ed25519_formats.adoc create mode 100644 doc/generated/backends-pem.adoc create mode 100644 doc/generated/backends-x25519_formats.adoc create mode 100644 example/key_formats.cpp create mode 100644 example/key_formats.expected create mode 100644 include/webcpp/crypto/curves/ed25519/formats.hpp create mode 100644 include/webcpp/crypto/curves/x25519/formats.hpp create mode 100644 include/webcpp/crypto/pem.hpp create mode 100644 test/formats_25519_openssl_oracle_test.cpp create mode 100644 test/formats_25519_sodium_test.cpp create mode 100644 test/formats_25519_webcrypto_oracle_test.cpp diff --git a/README.md b/README.md index e0326c47..362d0b96 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,8 @@ MSVC), wasip2, wasip3 and Emscripten. X25519 secret key of a key pair, and Ed25519ph over SHA-512 for a message given in pieces. - `webcpp::crypto::curves::x25519`: X25519 key agreement (RFC 7748), refusing an all-zero shared secret, and `curves::ed25519::to_x25519_public` for a peer known by its Ed25519 key. +- Ed25519's and X25519's keys in RFC 8410's SPKI and PKCS#8, as OpenSSL and WebCrypto write them, + and `webcpp::crypto::pem` for their PEM text, each decoded strictly. - `webcpp::crypto::hybrid`: 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. diff --git a/build.jam b/build.jam index a6033eb1..58afa0f3 100644 --- a/build.jam +++ b/build.jam @@ -100,6 +100,17 @@ rule x25519-default-linked ( properties * ) } } alias x25519-default : : : : @x25519-default-linked ; +rule pem-default-linked ( properties * ) +{ + switch [ webcpp-target.target-of $(properties) ] + { + case native : return /third_party//sodium ; + case wasip2 : return /third_party//sodium ; + case wasip3 : return /third_party//sodium ; + case emscripten : return /third_party//sodium ; + } +} +alias pem-default : : : : @pem-default-linked ; rule chacha20_poly1305-default-linked ( properties * ) { switch [ webcpp-target.target-of $(properties) ] diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 3ab844ec..0007dd09 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -21,7 +21,7 @@ of every version are on webcpp's index page. * Added supports_v with its family tags, the capability table per target, default_backend_t and /webcpp/crypto//-default, one default per family and target, and refusals naming their Jamfile line. * Added backends::bearssl (AES-GCM alone, allocating nothing), backends::openssl via /webcpp/crypto//openssl natively and on WASI (allocating at make only, or natively in openssl_memory_resource with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE), and backends::ctaes (block cipher alone). * Added curves::secp256k1: key pairs, BIP340 and ECDSA signatures, ECDH, strict DER, low-S and the x-only tweak. -* Added curves::ed25519 and curves::x25519 on libsodium: strict verification tabled on twelve edge cases, Ed25519ph over webcpp::hash's sha2_512 (/webcpp/crypto//crypto brings hash), the conversion, and agree refusing all-zero secrets. +* Added curves::ed25519 and curves::x25519 on libsodium: strict verification over twelve edge cases, Ed25519ph over hash's sha2_512 (/webcpp/crypto//crypto brings hash), conversion, all-zero secrets refused, RFC 8410's SPKI and PKCS#8, and pem. * Added backends::sodium on /third_party//sodium, shared with webcpp::hash, every backend's link-time canary and C suite, and ciphers::aead: chacha20_poly1305 (also BearSSL, OpenSSL), its original form and xchacha20_poly1305. * Added ciphers::secretbox and secretbox_xchacha20poly1305, without additional data, and hybrid::box, box_xchacha20poly1305 and sealed_box on libsodium, refusing peer keys of small order. * Added the page: a chapter per namespace and use case, the memory option's guide and example, tables generated from the tests, every Jamfile and message, and llms.txt. diff --git a/doc/crypto.adoc b/doc/crypto.adoc index 3c1cd154..240bc561 100644 --- a/doc/crypto.adoc +++ b/doc/crypto.adoc @@ -60,6 +60,8 @@ include::ed25519.adoc[] include::x25519.adoc[] +include::formats.adoc[] + include::hybrid.adoc[] include::backends.adoc[] diff --git a/doc/curves.adoc b/doc/curves.adoc index c9c3bdc2..ab12e476 100644 --- a/doc/curves.adoc +++ b/doc/curves.adoc @@ -31,6 +31,8 @@ another form, with the conversion of an Ed25519 key to it (link:https://www.rfc-editor.org/rfc/rfc7748[RFC 7748]; <>). A program chooses a curve for compatibility: a signature on one curve is checked only with that curve, and the curve of passkeys and TLS certificates, P-256, is -another, which this version does not offer. +another, which this version does not offer. Ed25519's and X25519's keys leave a +program, and enter it, in the standard forms OpenSSL and WebCrypto use, SPKI +and PKCS#8, as DER or PEM text (<>). include::generated/namespace-curves.adoc[] diff --git a/doc/formats.adoc b/doc/formats.adoc new file mode 100644 index 00000000..c4d48bb4 --- /dev/null +++ b/doc/formats.adoc @@ -0,0 +1,98 @@ +// 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) + +[#crypto-key-formats] +=== Key formats: SPKI, PKCS#8 and PEM + +A key leaves a program in a standard form when another program must read it: +OpenSSL's command line, a browser's WebCrypto, an SSH or TLS tool, a server +that stores a user's public key. Two forms of DER, the binary encoding of +ASN.1, carry a key with the name of its algorithm: *SPKI*, a public key +(SubjectPublicKeyInfo, the form inside every X.509 certificate), and +*PKCS#8*, a private key (RFC 5958's OneAsymmetricKey, +link:https://www.rfc-editor.org/rfc/rfc5958[RFC 5958]). *PEM* writes either as +text between `-----BEGIN PUBLIC KEY-----` and `-----END PUBLIC KEY-----`, or +`PRIVATE KEY`, so that it can be pasted into a file, a form or an e-mail +(link:https://www.rfc-editor.org/rfc/rfc7468[RFC 7468]). A chat app that lets +a user export an identity key to another device, or a server that accepts a +public key uploaded by a browser, speaks these forms. + +For Ed25519 and X25519, RFC 8410 fixes them to one layout each +(link:https://www.rfc-editor.org/rfc/rfc8410[RFC 8410]): an SPKI is 12 bytes +that name the curve, then the 32 bytes of the public key, 44 bytes in all; a +PKCS#8 is 16 bytes, then the 32 bytes of the seed (Ed25519) or secret key +(X25519), 48 bytes in all. These are exactly the bytes OpenSSL's `i2d_PUBKEY` +and `i2d_PrivateKey` and WebCrypto's `exportKey("spki")` and +`exportKey("pkcs8")` write +(link:https://www.w3.org/TR/webcrypto-2/#ed25519[W3C]), and the PEM texts +OpenSSL's `PEM_write_bio_PUBKEY` and `PEM_write_bio_PrivateKey` write: the +tests compare every byte with OpenSSL's natively and on WASI +(`formats_25519_openssl_oracle`) and with node's WebCrypto on Emscripten +(`formats_25519_webcrypto_oracle`), 200 keys per curve each. + +`` gives, in +`webcpp::crypto::curves::ed25519`, `encode_spki(public_key, out)`, +`decode_spki(spki)`, `encode_pkcs8(keypair, out)` and `decode_pkcs8(pkcs8)`, +which makes the key pair at once; `` +gives the same four in `webcpp::crypto::curves::x25519`, where a PKCS#8 +holds a 32-byte secret key and `decode_pkcs8` gives it as a `secret<32>`, which +wipes itself. `max_spki_size` and `max_pkcs8_size`, 44 and 48, size the +caller's buffers. `` gives, in `webcpp::crypto::pem`, +`armour(label, der, out)` and `unarmour(label, text, out)`, with the labels +`public_key_label` and `private_key_label`, and `armoured_size`, the text's +size. Each writes into the caller's buffer and returns how many bytes or +characters it wrote; on a refusal it writes nothing. All run on libsodium +(`/third_party//sodium`, or the families' aliases `/webcpp/crypto//ed25519-default`, +`/webcpp/crypto//x25519-default` and `/webcpp/crypto//pem-default`), whose base64 runs +in a time that does not depend on the bytes, those of a private key included +(link:https://doc.libsodium.org/helpers#base64-encoding-decoding[libsodium's documentation]). + +*Strict decoding.* A decoder accepts an input only if encoding what it +decoded gives the same bytes (design D30): the one form that OpenSSL and +WebCrypto write, and nothing else. It refuses with `invalid_encoding` another +curve's identifier (an Ed25519 key given to X25519's decoder), a byte left +over, a length in BER's long form where DER requires the short one, +PKCS#8 version 2, which carries the public key beside the seed, attributes, +and PEM with another label than the expected, lines of another length than 64, +carriage returns, text before or after the key, or base64 that is not the one +encoding of its bytes. A key that one library accepts and another refuses +lets two programs that should agree on a key disagree on it; one form, and +one verdict on every backend, closes that door. A program that receives +version 2, or PEM with Windows line ends, converts it with OpenSSL's +`openssl pkey` first. + +include::generated/backends-ed25519_formats.adoc[] + +include::generated/backends-x25519_formats.adoc[] + +include::generated/backends-pem.adoc[] + +*Example.* RFC 8410's own Ed25519 key pair read from PEM, its public key written +back as PEM, which is the RFC's to the character, and a signature; an X25519 +public key's SPKI; and the RFC's version 2 of the same private key refused: + +[source,cpp] +---- +include::{examples}/key_formats.cpp[tag=program] +---- + +[listing] +---- +include::{examples}/key_formats.expected[] +---- + +*Pitfalls.* + +* A PKCS#8, as DER or as PEM, is the secret key: kept in a `secret`, as the +example does, it is wiped when it goes; written to a file or a database, it is +sealed first, as any secret at rest (<>). +* `decode_spki` checks the form, not the key: Ed25519's `verify` refuses a +public key that is not a point of the curve, and X25519's `agree` one of low +order (`weak_public_key`). A key read from outside is used through those, which +check it. +* SPKI names the algorithm, the raw 32 bytes do not: an Ed25519 key and an +X25519 key of the same bytes are different keys, and the identifier keeps a +program from using one as the other. diff --git a/doc/generated/backends-ed25519_formats.adoc b/doc/generated/backends-ed25519_formats.adoc new file mode 100644 index 00000000..e4a255ab --- /dev/null +++ b/doc/generated/backends-ed25519_formats.adoc @@ -0,0 +1,20 @@ +// 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 `+curves::ed25519::encode_spki+`, `+decode_spki+`, `+encode_pkcs8+`, `+decode_pkcs8+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|libsodium +|`+/third_party//sodium+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+formats_25519_sodium+`, `+formats_25519_openssl_oracle+`, `+formats_25519_webcrypto_oracle+`, `+allocation_sodium+`) +|=== diff --git a/doc/generated/backends-pem.adoc b/doc/generated/backends-pem.adoc new file mode 100644 index 00000000..64c188b0 --- /dev/null +++ b/doc/generated/backends-pem.adoc @@ -0,0 +1,20 @@ +// 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 `+pem::armour+`, `+pem::unarmour+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|libsodium +|`+/third_party//sodium+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+formats_25519_sodium+`, `+formats_25519_openssl_oracle+`, `+allocation_sodium+`) +|=== diff --git a/doc/generated/backends-x25519_formats.adoc b/doc/generated/backends-x25519_formats.adoc new file mode 100644 index 00000000..089f304d --- /dev/null +++ b/doc/generated/backends-x25519_formats.adoc @@ -0,0 +1,20 @@ +// 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 `+curves::x25519::encode_spki+`, `+decode_spki+`, `+encode_pkcs8+`, `+decode_pkcs8+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|libsodium +|`+/third_party//sodium+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+formats_25519_sodium+`, `+formats_25519_openssl_oracle+`, `+formats_25519_webcrypto_oracle+`, `+allocation_sodium+`) +|=== diff --git a/doc/generated/default-aliases.adoc b/doc/generated/default-aliases.adoc index 2cb3f2f3..e6cf1684 100644 --- a/doc/generated/default-aliases.adoc +++ b/doc/generated/default-aliases.adoc @@ -31,6 +31,11 @@ |`+/third_party//sodium+` on every target |<> +|`+/webcpp/crypto//pem-default+` +|PEM +|`+/third_party//sodium+` on every target +|<> + |`+/webcpp/crypto//chacha20_poly1305-default+` |ChaCha20-Poly1305 |`+/third_party//sodium+` on every target diff --git a/doc/generated/defaults.adoc b/doc/generated/defaults.adoc index 4db7b27c..789bec5a 100644 --- a/doc/generated/defaults.adoc +++ b/doc/generated/defaults.adoc @@ -59,6 +59,12 @@ |the only backend in this version, on every target; it refuses an all-zero shared secret itself (link:https://www.rfc-editor.org/rfc/rfc7748[RFC 7748, Elliptic Curves for Security (X25519 and X448)]) |`+x25519_sodium+`, `+default_backend_none_linked+` +|PEM +|native, wasip2, wasip3, emscripten +|libsodium +|the only backend in this version, on every target; its base64 runs in a time that does not depend on the bytes, a private key's in a PKCS#8 (link:https://doc.libsodium.org/helpers#base64-encoding-decoding[libsodium's documentation, helpers: base64 encoding and decoding]) +|`+formats_25519_sodium+`, `+default_backend_none_linked+` + |ChaCha20-Poly1305 |native, wasip2, wasip3, emscripten |libsodium diff --git a/doc/generated/jamfiles.adoc b/doc/generated/jamfiles.adoc index 2d738bc2..9bd0f80f 100644 --- a/doc/generated/jamfiles.adoc +++ b/doc/generated/jamfiles.adoc @@ -183,6 +183,22 @@ It prints: include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/openssl_linked/openssl_linked.outcome[tag=output] ---- +`+pem_default+`:: RFC 8410's Ed25519 public key read from PEM and armoured again to the same text on PEM's default on every target, with the one line `+/webcpp/crypto//pem-default+`, which links libsodium. ++ +Its Jamfile, built and run on native, wasip2, wasip3, emscripten: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/pem_default/Jamfile[tag=jamfile] +---- ++ +It prints: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/pem_default/pem_default.outcome[tag=output] +---- + `+sealed_box_default+`:: A message sealed to Bob's public key and opened with his key pair on the default on every target, with the one line `+/webcpp/crypto//sealed_box-default+`, which links libsodium. + Its Jamfile, built and run on native, wasip2, wasip3, emscripten: diff --git a/doc/generated/matrix.adoc b/doc/generated/matrix.adoc index 93b3d5dd..2f99de78 100644 --- a/doc/generated/matrix.adoc +++ b/doc/generated/matrix.adoc @@ -116,6 +116,21 @@ |native, wasip2, wasip3, emscripten |`+x25519_sodium+`, `+x25519_wycheproof_sodium+`, `+oracle_25519+` +|`+curves::ed25519::encode_spki+`, `+decode_spki+`, `+encode_pkcs8+`, `+decode_pkcs8+` +|libsodium +|native, wasip2, wasip3, emscripten +|`+formats_25519_sodium+`, `+formats_25519_openssl_oracle+`, `+formats_25519_webcrypto_oracle+`, `+allocation_sodium+` + +|`+curves::x25519::encode_spki+`, `+decode_spki+`, `+encode_pkcs8+`, `+decode_pkcs8+` +|libsodium +|native, wasip2, wasip3, emscripten +|`+formats_25519_sodium+`, `+formats_25519_openssl_oracle+`, `+formats_25519_webcrypto_oracle+`, `+allocation_sodium+` + +|`+pem::armour+`, `+pem::unarmour+` +|libsodium +|native, wasip2, wasip3, emscripten +|`+formats_25519_sodium+`, `+formats_25519_openssl_oracle+`, `+allocation_sodium+` + |`+ciphers::chacha20_poly1305+` |BearSSL |native, wasip2, wasip3, emscripten @@ -274,6 +289,24 @@ The same, by target: the backends each operation runs on. |libsodium |libsodium +|`+curves::ed25519::encode_spki+`, `+decode_spki+`, `+encode_pkcs8+`, `+decode_pkcs8+` +|libsodium +|libsodium +|libsodium +|libsodium + +|`+curves::x25519::encode_spki+`, `+decode_spki+`, `+encode_pkcs8+`, `+decode_pkcs8+` +|libsodium +|libsodium +|libsodium +|libsodium + +|`+pem::armour+`, `+pem::unarmour+` +|libsodium +|libsodium +|libsodium +|libsodium + |`+ciphers::chacha20_poly1305+` |BearSSL, OpenSSL, libsodium |BearSSL, OpenSSL, libsodium diff --git a/doc/generated/namespace-root.adoc b/doc/generated/namespace-root.adoc index c196e7c0..a32f5422 100644 --- a/doc/generated/namespace-root.adoc +++ b/doc/generated/namespace-root.adoc @@ -7,37 +7,42 @@ // 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,5",options="header"] +[cols="2h,5,5,5,5,5",options="header"] |=== -|Name |`random_device` |`equal` |`error` |`openssl_memory_resource` +|Name |`random_device` |`equal` |`error` |`pem` |`openssl_memory_resource` |What it is for |Keys, IVs, tokens, nonces: every secret a program draws |Checking a tag, a MAC or a token |Telling failures apart +|A key's SPKI or PKCS#8 as text, to paste, store or exchange with OpenSSL |Keeping every allocation of OpenSSL's in the program's own resource, natively |Header |`` |`` |`` +|`` |`` |Errors |`entropy_unavailable`, `errc::not_supported` |none: it returns `bool` |its values are the errors +|`invalid_encoding`, `invalid_input_size` |`memory_functions_refused`, `memory_functions_not_installed` |Standards and sources |link:https://pubs.opengroup.org/onlinepubs/9799919799/functions/getentropy.html[POSIX.1-2024, getentropy], link:https://learn.microsoft.com/en-us/windows/win32/api/bcrypt/nf-bcrypt-bcryptgenrandom[Microsoft, BCryptGenRandom], link:https://www.w3.org/TR/WebCryptoAPI/#Crypto-method-getRandomValues[W3C Web Cryptography API, getRandomValues], link:https://github.com/WebAssembly/wasi-random[WASI, wasi:random] |link:https://cwe.mitre.org/data/definitions/208.html[CWE-208, observable timing discrepancy] |none +|link:https://www.rfc-editor.org/rfc/rfc7468[RFC 7468, textual encodings of PKIX, PKCS and CMS structures (PEM)], link:https://doc.libsodium.org/helpers#base64-encoding-decoding[libsodium's documentation, helpers: base64 encoding and decoding] |link:https://docs.openssl.org/3.5/man3/OPENSSL_malloc/[OpenSSL 3.5's OPENSSL_malloc(3), CRYPTO_set_mem_functions] |Choose it when |you need a random number an attacker must not predict; never `std::mt19937` or `rand` (link:https://cwe.mitre.org/data/definitions/338.html[CWE-338, a weak generator used for security]) |you compare anything secret; never `==` or `memcmp` on a MAC |you branch on a failure: forged data, a wrong size, no entropy +|a key goes to or comes from a file, a form or a tool as `-----BEGIN PUBLIC KEY-----` text; with the `encode_spki` and `encode_pkcs8` of `curves::ed25519` or `curves::x25519` |a native program on OpenSSL must allocate only from its own arena; on WebAssembly, BearSSL allocates nothing |=== diff --git a/doc/generated/sizes.adoc b/doc/generated/sizes.adoc index 14c8261a..f443406b 100644 --- a/doc/generated/sizes.adoc +++ b/doc/generated/sizes.adoc @@ -107,6 +107,22 @@ |not measured yet |not measured yet +|`+curves::ed25519::encode_spki+`, `+decode_spki+`, `+encode_pkcs8+`, `+decode_pkcs8+` +|not measured yet +|not measured yet +|not measured yet +|not measured yet +|not measured yet +|not measured yet + +|`+curves::x25519::encode_spki+`, `+decode_spki+`, `+encode_pkcs8+`, `+decode_pkcs8+` +|not measured yet +|not measured yet +|not measured yet +|not measured yet +|not measured yet +|not measured yet + |`+ciphers::chacha20_poly1305+` |not measured yet |not measured yet diff --git a/doc/generated/use-cases.adoc b/doc/generated/use-cases.adoc index 507db538..2ce42041 100644 --- a/doc/generated/use-cases.adoc +++ b/doc/generated/use-cases.adoc @@ -140,6 +140,14 @@ `+/webcpp/crypto//x25519-default+` |<> +|Export or import an Ed25519 or X25519 key in the standard forms OpenSSL and WebCrypto use: SPKI and PKCS#8 (RFC 8410), as DER or PEM text +|In `+curves::ed25519, webcpp::crypto::curves::x25519, webcpp::crypto::pem+`: `+encode_spki+`, `+decode_spki+`, `+encode_pkcs8+`, `+decode_pkcs8+`; `+pem::armour+`, `+pem::unarmour+` +|libsodium +|`+/webcpp/crypto//crypto+` + +`+/webcpp/crypto//ed25519-default+` + +`+/webcpp/crypto//pem-default+` +|<> + |Encrypt a record or a file under one secret key, each with a random nonce, in libsodium's secret-box format |In `+ciphers+`: `+secretbox<>+`, `+secretbox_xchacha20poly1305<>+`: `+make+`, `+seal+`, `+open+` |libsodium diff --git a/doc/llms.txt b/doc/llms.txt index 22a76770..686acc68 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -1,6 +1,6 @@ # webcpp::crypto -> Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA, ECDH, the x-only tweak), Ed25519 and Ed25519ph (RFC 8032), X25519 (RFC 7748), the ChaCha20-Poly1305 AEADs, libsodium's secret boxes, boxes and sealed boxes, a random_device on the system's generator and a constant-time equal, each over a widely used, reviewed C library (BearSSL, OpenSSL, ctaes, libsecp256k1, libsodium) that the program names in its Jamfile. Hashing and HMAC are Boost.Hash2's. Every failure is a boost::system::result value. Protocols (Bitcoin, Ethereum, Nostr) belong to domain libraries built on these primitives. +> Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA, ECDH, the x-only tweak), Ed25519 and Ed25519ph (RFC 8032), X25519 (RFC 7748), their SPKI and PKCS#8 (RFC 8410) and PEM, the ChaCha20-Poly1305 AEADs, libsodium's secret boxes, boxes and sealed boxes, a random_device on the system's generator and a constant-time equal, each over a widely used, reviewed C library (BearSSL, OpenSSL, ctaes, libsecp256k1, libsodium) that the program names in its Jamfile. Hashing and HMAC are Boost.Hash2's. Every failure is a boost::system::result value. Protocols (Bitcoin, Ethereum, Nostr) belong to domain libraries built on these primitives. Generated by doc/tables/generate.py with the page's tables. Page: https://webcpporg.github.io/libs/crypto/ @@ -21,6 +21,10 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [openssl_memory_resource, backends::openssl::install_memory_functions](https://webcpporg.github.io/libs/crypto/#crypto-memory-openssl): With `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE`, natively, every allocation of OpenSSL's in the process goes to a `std::pmr::memory_resource` the program defines. Header . Backends: OpenSSL (/webcpp/crypto//openssl) on native. - openssl_memory_resource: The resource every allocation of OpenSSL's in the process goes to, from any thread: declared by `` under `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE` and defined once by the program. - install_memory_functions: Installs webcpp's adapter as OpenSSL's memory functions, so that every allocation of OpenSSL's in the process goes to `openssl_memory_resource()`. +- [pem::armour, pem::unarmour](https://webcpporg.github.io/libs/crypto/#crypto-key-formats): PEM (RFC 7468): DER as base64 between `-----BEGIN