From 287e3590dcc26b3ff59b14f66d0c83187b5da7d4 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 06:27:10 -0300 Subject: [PATCH 1/7] hash: user_globals, a global of every one-word name a header gives a local or a parameter, before every public header and a call of every cell, which MSVC's C4459 reports at /W4 /WX --- test/Jamfile | 13 ++ test/user_globals_test.cpp | 426 +++++++++++++++++++++++++++++++++++++ 2 files changed, 439 insertions(+) create mode 100644 test/user_globals_test.cpp diff --git a/test/Jamfile b/test/Jamfile index d5770e7..87c9651 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -842,6 +842,19 @@ hash-run timing_coverage_blake3 : timing_coverage_blake3_test.cpp botan-run timing_coverage_botan : timing_coverage_botan_test.cpp : $(.hash-tables) msvc:/bigobj ; +# No local name in a header hides a program's global: every public header after +# a global of each one-word name a header's local once had, which MSVC's C4459 +# reports at /W4 /WX (clang and GCC never warn across namespaces), and every +# cell of every backend called, which instantiates the templates. Like +# timing_coverage_botan, it instantiates enough to pass the sections of an MSVC +# object (C1128), so MSVC compiles it with /bigobj. +hash-run user_globals : user_globals_test.cpp + : /webcpp/hash//openssl /third_party//xkcp + /third_party//blake3 /third_party//bearssl + /third_party//sodium /webcpp/asio//asio + @botan-native-with-exceptions msvc:/bigobj + : native ; + build-project messages ; # The canaries at link time, each C library's absence and another commit of diff --git a/test/user_globals_test.cpp b/test/user_globals_test.cpp new file mode 100644 index 0000000..73ce5b0 --- /dev/null +++ b/test/user_globals_test.cpp @@ -0,0 +1,426 @@ +// 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) + +// No local name in a hash header hides a program's global. MSVC warns, C4459, at a parameter or a +// local of a header's non-template function (inline code) that has the name of a global of the +// program ("declaration of 'timing' hides global declaration"), an error at /W4 /WX, and, where a +// function template is instantiated, at its locals (14.3 and 14.5, secure's user_globals test). +// Clang and GCC never warn across namespaces, so the test is MSVC's, and on the other native +// compilers it only runs the calls. A local takes two words, the role then the kind +// (`timing_scope`, `completion_token`, `salt_bytes`), which no program names a global. +// +// Every header of another library that a hash header includes comes first, so that their own +// names are parsed before the globals exist; then a global of every one-word name a hash header +// gave a local or a parameter until each took two words; then every public header. Every cell of +// every backend the program links is called (digests and hashers, MACs, the HKDFs over spans and +// over pieces, PBKDF2, KBKDF, SSKDF, X9.63, BLAKE2b's subkeys, Argon2, scrypt and bcrypt), and +// every asynchronous function on its default backend, which instantiates every template the calls +// reach. +// +// How the list was made: an aggregate translation unit of every header of include/, every backend +// and webcpp::asio linked, its AST dumped (clang -Xclang -ast-dump=json, filtered to webcpp::hash), +// each ParmVarDecl, VarDecl and BindingDecl inside a function of include/ whose name matches +// ^[a-z][a-z0-9]*$; again without exceptions, without threads, with the test seams +// (WEBCPP_HASH_DETAIL_TEST_*), and with Emscripten's compiler, for the code only they compile +// (backends::webcrypto's names are Emscripten's alone, and listed defensively). A name that the +// platform's C library already declares as a global (`index`, 's) cannot be a program's +// global there anyway: it is declared on MSVC alone. + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef WEBCPP_HASH_HAS_BOTAN +#include +#include +#include +#include +#include +#include +#include +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// NOLINTBEGIN(readability-redundant-declaration): clang-tidy takes Boost's dependent +// `...::value` for a declaration of `value` +extern int const absorbed, algorithm, allocator, bits, buffer, byte, bytes, c, characters, checked, + code, computed, context, cost, crypto, data, decimal, deeper, derive, derived, digest, done, + ended, executor, expected, extracted, finished, gathered, generator, guard, guarded, guards, + handler, hash, hashed, held, imported, initialised, inner, input, invoke, iterations, job, + joined, key, keyed, kind, label, length, limits, location, mac, made, name, named, nested, + nonce, object, offset, operation, options, other, outcome, output, owned, parameters, part, + password, piece, pieces, prefix, produced, promise, raised, ready, refusal, request, rest, + result, room, rounds, run, salt, same, secret, self, served, size, sized, slice, slot, started, + state, steps, storage, subtle, succeeded, suffix, tag, taken, target, tens, timing, token, + total, type, units, update, updated, usage, usages, used, value, version, whole, work, written, + zero; +#ifdef _MSC_VER +extern int const index; +#endif +// NOLINTEND(readability-redundant-declaration) + +#include +#include +#include + +// In webcpp::test, `hash::` names webcpp::hash before the global `hash` above. +namespace webcpp::test { +namespace { + +namespace digests = hash::digests; +namespace kdfs = hash::kdfs; +namespace macs = hash::macs; + +// Every tag of `digests`, of `macs`, every hmac of hmac.hpp, and argon2's variants. +using every_digest = + std::tuple; +using every_mac = std::tuple< + macs::hmac, macs::hmac, macs::hmac, + macs::hmac, macs::hmac, macs::hmac, + macs::hmac, macs::hmac, + macs::hmac, macs::hmac, macs::hmac, + macs::hmac, macs::hmac, macs::hmac, + macs::hmac, macs::hmac, + macs::hmac, macs::hmac, + macs::hmac, macs::hmac, macs::hmac, + macs::hmac, macs::hmac, + macs::hmac, macs::hmac, macs::kmac_128, macs::kmac_256, + macs::siphash_2_4, macs::siphash_2_4x, macs::blake2b_mac, macs::blake2s_mac>; +using every_hmac = + std::tuple; +using every_argon2 = std::tuple; +using every_backend = + std::tuple; + +/** Calls `each_call.template operator()()` for each tag of `Tags`. */ +template +void for_each_tag(Each const& each_call) { + [&each_call](std::tuple*) { + (each_call.template operator()(), ...); + }(static_cast(nullptr)); +} + +/** Whether the program links `Backend` and it has `Tag` (over `Key`). */ +template +inline constexpr bool cell_v = + hash::detail::linked_v && hash::backend_has_v; + +inline constexpr std::array test_key{1, 2, 3, 4, 5, 6, 7, 8, + 9, 10, 11, 12, 13, 14, 15, 16}; +inline constexpr std::array test_salt{16, 15, 14, 13, 12, 11, 10, 9, + 8, 7, 6, 5, 4, 3, 2, 1}; +inline constexpr std::array test_input{9, 8, 7, 6, 5, 4, 3, 2, 1}; + +/** The pieces of `test_input`, one of them empty. */ +std::array, 3> test_pieces() { + std::span const input_span(test_input); + return {input_span.first(5), std::span{}, input_span.subspan(5)}; +} + +/** `digest_of` and a hasher round of `Digest` on `Backend`, unkeyed, and keyed for BLAKE2b. */ +template +void call_digest() { + using traits = hash::detail::digest_traits; + hash::digest_options digest_choice{}; + if constexpr (requires { digest_choice.block_size; }) { + digest_choice.block_size = 8; // ParallelHash's, which has no default + } + std::array output_buffer{}; + auto const output_size = static_cast( + std::min({traits::max_output(digest_choice), + hash::detail::digest_engine::max_output, std::uint64_t{64}})); + auto const output_span = std::span(output_buffer).first(output_size); + static_cast(hash::digest_of(output_span, test_input, digest_choice)); + auto made_hasher = hash::hasher::make(digest_choice); + if (made_hasher) { + static_cast(made_hasher->update(test_input)); + static_cast(made_hasher->finish(output_span)); + } + if constexpr (std::is_same_v) { + hash::digest_options const keyed_choice{.key = test_key}; + static_cast(hash::digest_of(output_span, test_input, keyed_choice)); + static_cast(hash::hasher::make(keyed_choice)); + } +} + +/** `mac` of `Mac` on `Backend`, under the shortest key the backend takes. */ +template +void call_mac() { + using traits = hash::detail::mac_traits; + using engine = hash::detail::mac_engine; + std::array output_buffer{}; + auto const output_span = + std::span(output_buffer) + .first(static_cast(std::min(traits::max_output, std::uint64_t{64}))); + auto key_size = static_cast(traits::min_key); + while (!engine::accepts(hash::mac_options{}, key_size, output_span.size()) && + key_size < test_key.size()) { + ++key_size; + } + static_cast( + hash::mac(output_span, std::span(test_key).first(key_size), test_input)); +} + +/** Every key derivation over `Hmac` that `Backend` has: the HKDFs, PBKDF2 and KBKDF. */ +template +void call_hmac_family() { + std::array output_buffer{}; + std::array key_buffer{}; + auto const prk_span = std::span(key_buffer).first(typename Hmac::result_type().size()); + auto const piece_array = test_pieces(); + if constexpr (cell_v) { + static_cast(hash::hkdf_extract(test_salt, test_key)); + } + if constexpr (cell_v) { + static_cast(hash::hkdf_expand(output_buffer, prk_span, test_input)); + } + if constexpr (cell_v) { + static_cast( + hash::hkdf(output_buffer, test_salt, test_key, test_input)); + } + if constexpr (cell_v) { + static_cast(hash::hkdf_extract(test_salt, piece_array)); + } + if constexpr (cell_v) { + static_cast(hash::hkdf_expand(output_buffer, prk_span, piece_array)); + } + if constexpr (cell_v) { + static_cast( + hash::hkdf(output_buffer, test_salt, piece_array, piece_array)); + } + if constexpr (cell_v) { + static_cast(hash::pbkdf2(output_buffer, test_key, test_salt, 1)); + } + if constexpr (cell_v) { + static_cast(hash::kbkdf(output_buffer, test_key)); + } +} + +/** Every cell of `Backend`. */ +template +void call_every_cell() { + if constexpr (hash::detail::linked_v) { + for_each_tag([]() { + if constexpr (cell_v) { + call_digest(); + } + }); + for_each_tag([]() { + if constexpr (cell_v) { + call_mac(); + } + }); + for_each_tag([]() { call_hmac_family(); }); + std::array output_buffer{}; + if constexpr (cell_v) { + std::array const context_bytes{'c', 't', 'x', '_', 't', 'e', 's', 't'}; + static_cast( + hash::blake2b_subkey(output_buffer, test_key, 7, context_bytes)); + } + if constexpr (cell_v) { + static_cast( + hash::sskdf(output_buffer, test_key, test_input)); + } + if constexpr (cell_v) { + static_cast( + hash::x963kdf(output_buffer, test_key, test_input)); + } + if constexpr (cell_v) { + static_cast(hash::argon2id(output_buffer, test_key, test_salt, + {.passes = 1, .memory = 8192})); + } + for_each_tag([&output_buffer]() { + if constexpr (cell_v) { + static_cast(hash::argon2( + output_buffer, test_key, test_salt, {.passes = 3, .memory_kibibytes = 8})); + } + }); + if constexpr (cell_v) { + static_cast( + hash::scrypt(output_buffer, test_key, test_salt, + {.cost = 16, .block_size = 1, .parallelism = 1})); + } + if constexpr (cell_v) { + std::array hash_characters{}; + static_cast( + hash::bcrypt(hash_characters, test_key, test_salt, {.cost = 4})); + static_cast(hash::bcrypt_verify( + test_key, std::string_view(hash_characters.data(), hash_characters.size()))); + } + if constexpr (cell_v) { + static_cast(hash::bcrypt_pbkdf(output_buffer, test_key, test_salt, 1)); + } + } +} + +/** Every asynchronous function, on its default backend, each completing on `io_context`. */ +void call_every_async(asio::io_context& context_object) { + auto const io_executor = context_object.get_executor(); + std::array output_buffer{}; + std::array key_buffer{}; + auto const piece_array = test_pieces(); + auto const on_done = [](boost::system::error_code const&) {}; + hash::async_digest(io_executor, output_buffer, test_input, on_done); + hash::async_hmac(io_executor, output_buffer, test_key, test_input, + on_done); + hash::async_hkdf(io_executor, output_buffer, test_salt, test_key, + test_input, on_done); + hash::async_hkdf(io_executor, output_buffer, test_salt, piece_array, + piece_array, on_done); + hash::async_hkdf_extract(io_executor, key_buffer, test_salt, test_key, + on_done); + hash::async_hkdf_extract(io_executor, key_buffer, test_salt, piece_array, + on_done); + hash::async_hkdf_expand(io_executor, output_buffer, key_buffer, test_input, + on_done); + hash::async_hkdf_expand(io_executor, output_buffer, key_buffer, + piece_array, on_done); + hash::async_pbkdf2(io_executor, output_buffer, test_key, test_salt, 1, + on_done); +#ifdef WEBCPP_HASH_HAS_THREADS + hash::async_argon2id(io_executor, output_buffer, test_key, test_salt, + {.passes = 1, .memory = 8192}, on_done); + hash::async_argon2(io_executor, output_buffer, test_key, test_salt, + {.passes = 3, .memory_kibibytes = 8}, on_done); + hash::async_scrypt(io_executor, output_buffer, test_key, test_salt, + {.cost = 16, .block_size = 1, .parallelism = 1}, on_done); +#ifdef WEBCPP_HASH_HAS_BOTAN + std::array hash_characters{}; + using hash::backends::botan; + hash::async_bcrypt(io_executor, hash_characters, test_key, test_salt, {.cost = 4}, + on_done); + hash::async_bcrypt_pbkdf(io_executor, output_buffer, test_key, test_salt, 1, on_done); + hash::async_bcrypt_verify(io_executor, test_key, std::string_view("not a bcrypt string"), + [](boost::system::error_code const&, bool) {}); +#endif +#endif + context_object.run(); +} + +} // namespace +} // namespace webcpp::test + +int main() { + namespace test = webcpp::test; + [](std::tuple*) { + (test::call_every_cell(), ...); + }(static_cast(nullptr)); + webcpp::asio::io_context context_object; + test::call_every_async(context_object); + return webcpp::test::exit_status(boost::report_errors()); +} From 9e7cd0e1ac8da95837222eaf5a628880c176a089 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 06:42:41 -0300 Subject: [PATCH 2/7] hash: every local and parameter of a header's function takes two words (917 declarations of 119 one-word names, which MSVC's C4459 reports in a program with a global of one), the doc comments, kdfs.adoc and AGENTS.md with them; user_globals calls async_pbkdf2 only with threads --- AGENTS.md | 19 +- doc/kdfs.adoc | 8 +- include/webcpp/hash/argon2.hpp | 93 +- include/webcpp/hash/async.hpp | 952 ++++++++++---------- include/webcpp/hash/backends/bearssl.hpp | 258 +++--- include/webcpp/hash/backends/blake3.hpp | 46 +- include/webcpp/hash/backends/botan.hpp | 778 +++++++++-------- include/webcpp/hash/backends/hash2.hpp | 158 ++-- include/webcpp/hash/backends/openssl.hpp | 367 ++++---- include/webcpp/hash/backends/sodium.hpp | 332 +++---- include/webcpp/hash/backends/webcrypto.hpp | 958 +++++++++++---------- include/webcpp/hash/backends/xkcp.hpp | 524 +++++------ include/webcpp/hash/bcrypt.hpp | 205 ++--- include/webcpp/hash/blake2b_subkey.hpp | 39 +- include/webcpp/hash/blake3.hpp | 20 +- include/webcpp/hash/byte_pieces.hpp | 16 +- include/webcpp/hash/detail/engines.hpp | 79 +- include/webcpp/hash/digest.hpp | 226 ++--- include/webcpp/hash/hkdf.hpp | 82 +- include/webcpp/hash/kdf_standards.hpp | 147 ++-- include/webcpp/hash/mac.hpp | 57 +- include/webcpp/hash/pbkdf2.hpp | 8 +- include/webcpp/hash/scrypt.hpp | 10 +- test/user_globals_test.cpp | 8 +- 24 files changed, 2865 insertions(+), 2525 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 7afa199..a912717 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -25,12 +25,12 @@ specific to hash. without. - Every function that computes on a key, a password or a key derivation's secret input holds `secure::timing_guard` (webcpp::secure's, ``) as its first - statement (`timing{engaged}` where the arguments decide whether the call is keyed); unkeyed - digests and Boost.Hash2's types by alias hold none. A new keyed function, or a keyed cell that - `doc/capabilities.json` gains (a MAC, a key derivation, a password hash, on any backend), holds - the guard and gets its call in that backend's `test/timing_coverage__test.cpp`, which - fails until it does. The seam support (`test/support/timing_seam.hpp`) counts hash's own guards - by their file, under `include/webcpp/hash/`, in `timing_entries`, and every guard in + statement (`timing_scope{guard_engaged}` where the arguments decide whether the call is keyed); + unkeyed digests and Boost.Hash2's types by alias hold none. A new keyed function, or a keyed cell + that `doc/capabilities.json` gains (a MAC, a key derivation, a password hash, on any backend), + holds the guard and gets its call in that backend's `test/timing_coverage__test.cpp`, + which fails until it does. The seam support (`test/support/timing_seam.hpp`) counts hash's own + guards by their file, under `include/webcpp/hash/`, in `timing_entries`, and every guard in `timing_all_entries`. - Every wipe of a secret or of a failed output is `secure::erase_secret` over a span (``); a test sees each one through secure's seam @@ -38,3 +38,10 @@ specific to hash. secure, no other webcpp library. - `include/webcpp/hash/detail/canary.h` is a C header: it is in neither the headers-alone list nor `meta/include-boundaries.json`. +- Every local and parameter of a C++ function in `include/` takes two words, the role then the + kind (`timing_scope`, `salt_bytes`, `completion_token`): MSVC's C4459 at /W4 /WX stops a user's + program that has a global of a one-word name a header's function declares (a template's only + where it is instantiated). `test/user_globals_test.cpp` declares a global of each one-word name a + header once had, then calls every cell. The XKCP adapter's C declarations + (`detail/xkcp.hpp`) keep `src/xkcp_adapter.c`'s names: a declaration without a body raises no + C4459. diff --git a/doc/kdfs.adoc b/doc/kdfs.adoc index e4323b8..49af544 100644 --- a/doc/kdfs.adoc +++ b/doc/kdfs.adoc @@ -47,7 +47,7 @@ include::generated/compare-kdfs.adoc[] === HKDF HKDF (RFC 5869, 2010, Krawczyk) has two steps, both HMACs. *Extract* takes an -optional `salt` and the `input_key_material` (RFC 5869's IKM) and returns a +optional `salt_bytes` and the `input_key_material` (RFC 5869's IKM) and returns a `pseudorandom_key` (the PRK) of the hmac's digest size: `PRK = HMAC(salt, IKM)`. *Expand* takes the `pseudorandom_key` and the `application_info` (RFC 5869's info), the label of one purpose, and returns up @@ -78,7 +78,7 @@ include::{examples}/hkdf.expected[] Diffie-Hellman result) but must hold enough entropy: extract concentrates entropy, it never adds any. A password has too little; it goes through Argon2id. -* *`salt`* is optional and public: a random value per session, or a constant +* *`salt_bytes`* is optional and public: a random value per session, or a constant that names the application or the protocol (NIP-44 uses `nip44-v2`). It separates the keys of different applications that might share a secret. An empty salt is RFC 5869's string of zeros, and fine when the IKM is never @@ -146,10 +146,10 @@ On a synchronous backend each piece goes to the backend's HMAC: no buffer, no copy of the secret. WebCrypto's asynchronous forms copy the pieces into JavaScript memory instead (<>). -* `hkdf_extract(salt, input_key_material)` +* `hkdf_extract(salt_bytes, input_key_material)` * `hkdf_expand(output_key_material, pseudorandom_key, application_info)` -* `hkdf(output_key_material, salt, input_key_material, +* `hkdf(output_key_material, salt_bytes, input_key_material, application_info)` The salt and the pseudorandom key stay one span each. The bytes are those of diff --git a/include/webcpp/hash/argon2.hpp b/include/webcpp/hash/argon2.hpp index 81440ad..49930a7 100644 --- a/include/webcpp/hash/argon2.hpp +++ b/include/webcpp/hash/argon2.hpp @@ -164,11 +164,11 @@ template > std::span password_bytes, std::span salt_bytes, argon2id_parameters const& cost_parameters) { - secure::timing_guard const timing; - auto guarded = detail::argon2id_guards(output_bytes.size(), password_bytes.size(), - salt_bytes.size(), cost_parameters); - if (!guarded) { - return guarded; + secure::timing_guard const timing_scope; + auto guard_result = detail::argon2id_guards(output_bytes.size(), password_bytes.size(), + salt_bytes.size(), cost_parameters); + if (!guard_result) { + return guard_result; } auto derive_result = detail::argon2id_engine::derive( output_bytes, password_bytes, salt_bytes, cost_parameters.passes, cost_parameters.memory); @@ -217,20 +217,22 @@ inline constexpr std::uint64_t argon2_min_salt = 8; The backend's limits within RFC 9106's: whether `Engine` takes these values. @param output_size The tag's size. @param salt_size The salt's size. - @param parameters The parameters. + @param cost_parameters The parameters. @return Whether the engine's `limits` hold them all. */ template bool argon2_engine_takes(std::size_t output_size, std::size_t salt_size, - argon2_parameters const& parameters) noexcept { + argon2_parameters const& cost_parameters) noexcept { // Each bound through exceeds: a limit at the type's own bound would be a tautology. - constexpr argon2_limits limits = Engine::limits; - return !exceeds(limits.min_passes, parameters.passes) && - !exceeds(parameters.memory_kibibytes, limits.max_memory_kibibytes) && - !exceeds(parameters.lanes, limits.max_lanes) && - !exceeds(limits.min_output, output_size) && !exceeds(limits.min_salt, salt_size) && - !exceeds(salt_size, limits.max_salt) && (limits.secret || parameters.secret.empty()) && - (limits.associated_data || parameters.associated_data.empty()); + constexpr argon2_limits engine_limits = Engine::limits; + return !exceeds(engine_limits.min_passes, cost_parameters.passes) && + !exceeds(cost_parameters.memory_kibibytes, engine_limits.max_memory_kibibytes) && + !exceeds(cost_parameters.lanes, engine_limits.max_lanes) && + !exceeds(engine_limits.min_output, output_size) && + !exceeds(engine_limits.min_salt, salt_size) && + !exceeds(salt_size, engine_limits.max_salt) && + (engine_limits.secret || cost_parameters.secret.empty()) && + (engine_limits.associated_data || cost_parameters.associated_data.empty()); } /** @@ -239,13 +241,13 @@ bool argon2_engine_takes(std::size_t output_size, std::size_t salt_size, @tparam Variant The variant. @tparam Backend The backend. @param output_size The tag's size. @param password_size The password's size. - @param salt_size The salt's size. @param parameters The parameters. + @param salt_size The salt's size. @param cost_parameters The parameters. @return Success, or the error of the first guard that fails, as `argon2` returns it. */ template [[nodiscard]] boost::system::result argon2_guards( std::size_t output_size, std::size_t password_size, std::size_t salt_size, - argon2_parameters const& parameters) noexcept { + argon2_parameters const& cost_parameters) noexcept { using engine = argon2_engine; if (exceeds(argon2_min_output, output_size) || exceeds(output_size, argon2id_max_size)) { return error::invalid_output_size; @@ -254,16 +256,17 @@ template return error::invalid_salt_size; } if (exceeds(password_size, argon2id_max_size) || - exceeds(parameters.secret.size(), argon2id_max_size) || - exceeds(parameters.associated_data.size(), argon2id_max_size)) { + exceeds(cost_parameters.secret.size(), argon2id_max_size) || + exceeds(cost_parameters.associated_data.size(), argon2id_max_size)) { return error::input_too_long; } - if (parameters.passes < 1 || parameters.lanes < 1 || parameters.lanes > argon2_max_lanes || - parameters.memory_kibibytes < - argon2_min_memory_kibibytes_per_lane * std::uint64_t{parameters.lanes}) { + if (cost_parameters.passes < 1 || cost_parameters.lanes < 1 || + cost_parameters.lanes > argon2_max_lanes || + cost_parameters.memory_kibibytes < + argon2_min_memory_kibibytes_per_lane * std::uint64_t{cost_parameters.lanes}) { return error::invalid_parameters; } - if (!argon2_engine_takes(output_size, salt_size, parameters)) { + if (!argon2_engine_takes(output_size, salt_size, cost_parameters)) { return error::unsupported_by_backend; } return {}; @@ -272,42 +275,42 @@ template } // namespace detail /** - Argon2 version 0x13 (RFC 9106) of the variant `Variant` with every parameter: fills `output` from - `password` and `salt`. + Argon2 version 0x13 (RFC 9106) of the variant `Variant` with every parameter: fills `output_bytes` + from `password_bytes` and `salt_bytes`. Every guard of RFC 9106 runs first, then the backend's own limits (`unsupported_by_backend`), and - a refusal leaves `output` as it was; a backend's failure zeroes it. + a refusal leaves `output_bytes` as it was; a backend's failure zeroes it. @tparam Variant `kdfs::argon2id` (recommended for passwords), `kdfs::argon2i` or `kdfs::argon2d`. @tparam Backend The backend; by default @ref default_backend of `Variant` (spec 4.1): `backends::sodium` for Argon2id and Argon2i, none for Argon2d, which names its backend (`backends::openssl`, which has every variant with every parameter, or `backends::botan`, which has every variant with at most 128 lanes and 8 GiB of memory, 2 GiB on wasm32). - @param output The tag, 4 to 4,294,967,295 bytes; it must not overlap the inputs. - @param password The password, at most 4,294,967,295 bytes. - @param salt The salt, 8 to 4,294,967,295 bytes (16 random bytes are the usual choice). - @param parameters The costs, the lanes, the secret and the associated data. + @param output_bytes The tag, 4 to 4,294,967,295 bytes; it must not overlap the inputs. + @param password_bytes The password, at most 4,294,967,295 bytes. + @param salt_bytes The salt, 8 to 4,294,967,295 bytes (16 random bytes are the usual choice). + @param cost_parameters The costs, the lanes, the secret and the associated data. @return Success; or the first guard's error (`invalid_output_size`, `invalid_salt_size`, - `input_too_long`, `invalid_parameters`, `unsupported_by_backend`), `output` untouched; or - `errc::not_enough_memory` or `backend_failure`, `output` zeroed. + `input_too_long`, `invalid_parameters`, `unsupported_by_backend`), `output_bytes` untouched; or + `errc::not_enough_memory` or `backend_failure`, `output_bytes` zeroed. */ template > -[[nodiscard]] boost::system::result argon2(std::span output, - std::span password, - std::span salt, - argon2_parameters const& parameters) { - secure::timing_guard const timing; - auto guarded = detail::argon2_guards(output.size(), password.size(), - salt.size(), parameters); - if (!guarded) { - return guarded; +[[nodiscard]] boost::system::result argon2(std::span output_bytes, + std::span password_bytes, + std::span salt_bytes, + argon2_parameters const& cost_parameters) { + secure::timing_guard const timing_scope; + auto guard_result = detail::argon2_guards( + output_bytes.size(), password_bytes.size(), salt_bytes.size(), cost_parameters); + if (!guard_result) { + return guard_result; } - auto derived = - detail::argon2_engine::derive(output, password, salt, parameters); - if (!derived) { - secure::erase_secret(output); + auto derive_result = detail::argon2_engine::derive( + output_bytes, password_bytes, salt_bytes, cost_parameters); + if (!derive_result) { + secure::erase_secret(output_bytes); } - return derived; + return derive_result; } } // namespace webcpp::hash diff --git a/include/webcpp/hash/async.hpp b/include/webcpp/hash/async.hpp index 88a9e2c..3eca5e5 100644 --- a/include/webcpp/hash/async.hpp +++ b/include/webcpp/hash/async.hpp @@ -154,27 +154,27 @@ struct async_engine { /** Never called: the refusal has stopped the build. */ template - static void digest(Arguments&&... /*arguments*/) noexcept {} + static void digest(Arguments&&... /*call_arguments*/) noexcept {} /** Never called: the refusal has stopped the build. */ template - static void hmac(Arguments&&... /*arguments*/) noexcept {} + static void hmac(Arguments&&... /*call_arguments*/) noexcept {} /** Never called: the refusal has stopped the build. */ template - static void hkdf_extract(Arguments&&... /*arguments*/) noexcept {} + static void hkdf_extract(Arguments&&... /*call_arguments*/) noexcept {} /** Never called: the refusal has stopped the build. */ template - static void hkdf_expand(Arguments&&... /*arguments*/) noexcept {} + static void hkdf_expand(Arguments&&... /*call_arguments*/) noexcept {} /** Never called: the refusal has stopped the build. */ template - static void hkdf(Arguments&&... /*arguments*/) noexcept {} + static void hkdf(Arguments&&... /*call_arguments*/) noexcept {} /** Never called: the refusal has stopped the build. */ template - static void pbkdf2(Arguments&&... /*arguments*/) noexcept {} + static void pbkdf2(Arguments&&... /*call_arguments*/) noexcept {} }; #endif @@ -182,11 +182,11 @@ struct async_engine { The error code of a synchronous function's result. @tparam Value The result's value: `void`, or `bool` for `bcrypt_verify`. - @param done The result. @return Its error, or the empty code on success. + @param call_result The result. @return Its error, or the empty code on success. */ template -boost::system::error_code code_of(boost::system::result const& done) noexcept { - return done ? boost::system::error_code{} : done.error(); +boost::system::error_code code_of(boost::system::result const& call_result) noexcept { + return call_result ? boost::system::error_code{} : call_result.error(); } /** The value a heavy operation carries to its handler beside its code: none for `void`. */ @@ -240,29 +240,33 @@ using heavy_value_of = std::invoke_result_t::value_type; */ struct post_initiation { /** - Runs `operation` and posts `handler` with its error code. + Runs `bound_call` and posts `completion_handler` with its error code. - @param handler The completion handler. @param executor The I/O executor. - @param operation The synchronous function, bound to its arguments. + @param completion_handler The completion handler. @param completion_executor The I/O executor. + @param bound_call The synchronous function, bound to its arguments. */ template - void operator()(Handler&& handler, Executor const& executor, Operation const& operation) const { - auto const code = code_of(operation()); - webcpp::asio::post(executor, webcpp::asio::append(std::forward(handler), code)); + void operator()(Handler&& completion_handler, Executor const& completion_executor, + Operation const& bound_call) const { + auto const completion_code = code_of(bound_call()); + webcpp::asio::post( + completion_executor, + webcpp::asio::append(std::forward(completion_handler), completion_code)); } }; /** Initiates a cheap function on a synchronous backend (spec 11.2). - @param executor The I/O executor. @param token The completion token. - @param operation The synchronous function, bound to its arguments. + @param completion_executor The I/O executor. @param completion_token The completion token. + @param bound_call The synchronous function, bound to its arguments. @return What the completion token's `async_result` gives. */ template -auto complete_by_post(Executor const& executor, CompletionToken& token, Operation operation) { +auto complete_by_post(Executor const& completion_executor, CompletionToken& completion_token, + Operation bound_call) { return webcpp::asio_backend::async_initiate( - post_initiation{}, token, executor, std::move(operation)); + post_initiation{}, completion_token, completion_executor, std::move(bound_call)); } /** @@ -272,15 +276,17 @@ auto complete_by_post(Executor const& executor, CompletionToken& token, Operatio */ struct code_initiation { /** - Posts `handler` with `code`. + Posts `completion_handler` with `completion_code`. - @param handler The completion handler. @param executor The I/O executor. - @param code The work's error code. + @param completion_handler The completion handler. @param completion_executor The I/O executor. + @param completion_code The work's error code. */ template - void operator()(Handler&& handler, Executor const& executor, - boost::system::error_code code) const { - webcpp::asio::post(executor, webcpp::asio::append(std::forward(handler), code)); + void operator()(Handler&& completion_handler, Executor const& completion_executor, + boost::system::error_code completion_code) const { + webcpp::asio::post( + completion_executor, + webcpp::asio::append(std::forward(completion_handler), completion_code)); } }; @@ -290,15 +296,15 @@ struct code_initiation { `async_initiate`, so that no completion token, `asio::deferred` included, keeps the pieces' list past the call's full-expression. - @param executor The I/O executor. @param token The completion token. - @param code The work's error code. + @param completion_executor The I/O executor. @param completion_token The completion token. + @param completion_code The work's error code. @return What the completion token's `async_result` gives. */ template -auto complete_with_code(Executor const& executor, CompletionToken& token, - boost::system::error_code code) { +auto complete_with_code(Executor const& completion_executor, CompletionToken& completion_token, + boost::system::error_code completion_code) { return webcpp::asio_backend::async_initiate( - code_initiation{}, token, executor, code); + code_initiation{}, completion_token, completion_executor, completion_code); } /** @@ -309,13 +315,13 @@ auto complete_with_code(Executor const& executor, CompletionToken& token, @tparam Hmac A Boost.Hash2 hmac over a digest. @tparam Backend A synchronous backend. @tparam InputKeyMaterial `std::span`, or `byte_pieces`. @param pseudorandom_key The output, of exactly the digest size. - @param salt The salt. @param input_key_material The input keying material. + @param salt_bytes The salt. @param input_key_material The input keying material. @return Success; or `invalid_output_size` for an output of another size, then `hkdf_extract`'s guards' errors, `pseudorandom_key` untouched; or the backend's failure, `pseudorandom_key` zeroed. */ template [[nodiscard]] boost::system::result hkdf_extract_into( - std::span pseudorandom_key, std::span salt, + std::span pseudorandom_key, std::span salt_bytes, InputKeyMaterial input_key_material) { // No timing_guard here: the secret computation is hkdf_extract's, which holds the guard as its // first statement; this helper only checks sizes, then copies and wipes the key, work whose @@ -327,23 +333,24 @@ template return error::invalid_output_size; } if constexpr (std::is_same_v) { - auto const guarded = hkdf_pieces_salt_guard(salt.size()); - if (!guarded) { - return guarded; + auto const guard_result = hkdf_pieces_salt_guard(salt_bytes.size()); + if (!guard_result) { + return guard_result; } } else { - auto const guarded = hkdf_extract_guards(salt.size(), input_key_material.size()); - if (!guarded) { - return guarded; + auto const guard_result = + hkdf_extract_guards(salt_bytes.size(), input_key_material.size()); + if (!guard_result) { + return guard_result; } } - auto extracted = hkdf_extract(salt, input_key_material); - if (!extracted) { + auto extract_result = hkdf_extract(salt_bytes, input_key_material); + if (!extract_result) { secure::erase_secret(pseudorandom_key); - return extracted.error(); + return extract_result.error(); } - std::ranges::copy(*extracted, pseudorandom_key.begin()); - secure::erase_secret(std::span(&*extracted, 1)); + std::ranges::copy(*extract_result, pseudorandom_key.begin()); + secure::erase_secret(std::span(&*extract_result, 1)); return {}; } @@ -406,98 +413,103 @@ class heavy_state { /** A new state, in storage of the handler's associated allocator. - @param handler The completion handler. @param work The work executor. - @param run The synchronous function, bound to its arguments. @param output The output. + @param completion_handler The completion handler. @param work_executor The work executor. + @param bound_call The synchronous function, bound to its arguments. @param output_bytes The + output. @return The state. */ - static heavy_state* make(Handler handler, WorkExecutor const& work, Work run, - std::span output) { - allocator_type allocator(webcpp::asio::get_associated_allocator(handler)); - auto* const storage = std::allocator_traits::allocate(allocator, 1); - try_construct(allocator, storage, std::move(handler), work, std::move(run), output); - return storage; + static heavy_state* make(Handler completion_handler, WorkExecutor const& work_executor, + Work bound_call, std::span output_bytes) { + allocator_type handler_allocator( + webcpp::asio::get_associated_allocator(completion_handler)); + auto* const state_storage = + std::allocator_traits::allocate(handler_allocator, 1); + try_construct(handler_allocator, state_storage, std::move(completion_handler), + work_executor, std::move(bound_call), output_bytes); + return state_storage; } /** Installs the cancellation handler, when the handler's slot is connected. */ void install_cancellation() { // NOLINTNEXTLINE(bugprone-unchecked-optional-access): engaged until the completion - auto slot = webcpp::asio::get_associated_cancellation_slot(*handler_); - if (slot.is_connected()) { - slot.template emplace(this); + auto handler_slot = webcpp::asio::get_associated_cancellation_slot(*handler_); + if (handler_slot.is_connected()) { + handler_slot.template emplace(this); } } /** Records where the job holds the state, or that it holds it no longer (null). - @param location The job's atomic pointer. + @param job_location The job's atomic pointer. */ - void relocate(std::atomic* location) noexcept { + void relocate(std::atomic* job_location) noexcept { lock(); - location_ = location; + location_ = job_location; unlock(); } /** The job's turn on the work executor's thread, the state taken out of the job. */ void run_work() { relocate(nullptr); - auto expected = heavy_phase::queued; - if (!phase_.compare_exchange_strong(expected, heavy_phase::running, + auto expected_phase = heavy_phase::queued; + if (!phase_.compare_exchange_strong(expected_phase, heavy_phase::running, std::memory_order_acq_rel)) { // A cancellation won, and found the job holding the state no more: complete for it. complete_on_handler(webcpp::asio::error::operation_aborted); return; } - auto const outcome = run_(); - auto code = code_of(outcome); + auto const call_result = run_(); + auto completion_code = code_of(call_result); if constexpr (!std::is_void_v) { - value_.value = outcome ? *outcome : value_type{}; + value_.value = call_result ? *call_result : value_type{}; } if (cancelled_.load(std::memory_order_acquire)) { secure::erase_secret(output_); - code = webcpp::asio::error::operation_aborted; + completion_code = webcpp::asio::error::operation_aborted; value_ = {}; } phase_.store(heavy_phase::finished, std::memory_order_release); - complete_on_handler(code); + complete_on_handler(completion_code); } /** The job destroyed unrun (its executor shut down): the handler is destroyed, never called. */ void abandon() { relocate(nullptr); - auto expected = heavy_phase::queued; - if (!phase_.compare_exchange_strong(expected, heavy_phase::finished, + auto expected_phase = heavy_phase::queued; + if (!phase_.compare_exchange_strong(expected_phase, heavy_phase::finished, std::memory_order_acq_rel)) { complete_on_handler(webcpp::asio::error::operation_aborted); return; } - auto const executor = handler_work_.get_executor(); - webcpp::asio::post(executor, bound_completion({}, false)); + auto const completion_executor = handler_work_.get_executor(); + webcpp::asio::post(completion_executor, bound_completion({}, false)); } - /** A cancellation of type `type`, on the handler's executor, where the signal is emitted. */ - void cancel(webcpp::asio::cancellation_type_t type) { - auto expected = heavy_phase::queued; - if (phase_.compare_exchange_strong(expected, heavy_phase::finished, + /** A cancellation of type `requested_type`, on the handler's executor, where the signal is + * emitted. */ + void cancel(webcpp::asio::cancellation_type_t requested_type) { + auto expected_phase = heavy_phase::queued; + if (phase_.compare_exchange_strong(expected_phase, heavy_phase::finished, std::memory_order_acq_rel)) { // Take the state back from the queued job; a job that has just taken it out itself // completes for this cancellation instead. - bool taken = false; + bool state_taken = false; lock(); if (location_ != nullptr) { - taken = location_->exchange(nullptr, std::memory_order_acq_rel) != nullptr; + state_taken = location_->exchange(nullptr, std::memory_order_acq_rel) != nullptr; location_ = nullptr; } unlock(); - if (taken) { - auto const executor = handler_work_.get_executor(); - webcpp::asio::post(executor, + if (state_taken) { + auto const completion_executor = handler_work_.get_executor(); + webcpp::asio::post(completion_executor, bound_completion(webcpp::asio::error::operation_aborted)); } return; } using webcpp::asio::cancellation_type; - if ((type & (cancellation_type::terminal | cancellation_type::partial)) != + if ((requested_type & (cancellation_type::terminal | cancellation_type::partial)) != cancellation_type::none) { cancelled_.store(true, std::memory_order_release); } @@ -508,9 +520,11 @@ class heavy_state { // state is destroyed. class cancellation { public: - explicit cancellation(heavy_state* state) noexcept : state_(state) {} + explicit cancellation(heavy_state* operation_state) noexcept : state_(operation_state) {} - void operator()(webcpp::asio::cancellation_type_t type) { state_->cancel(type); } + void operator()(webcpp::asio::cancellation_type_t requested_type) { + state_->cancel(requested_type); + } private: heavy_state* state_; @@ -524,13 +538,14 @@ class heavy_state { // handler that owns a promise breaks it. class completion { public: - completion(heavy_state* state, boost::system::error_code code, bool invoke) noexcept - : state_(state), code_(code), invoke_(invoke) {} + completion(heavy_state* operation_state, boost::system::error_code completion_code, + bool invoke_handler) noexcept + : state_(operation_state), code_(completion_code), invoke_(invoke_handler) {} - completion(completion&& other) noexcept - : state_(std::exchange(other.state_, nullptr)), - code_(other.code_), - invoke_(other.invoke_) {} + completion(completion&& moved_completion) noexcept + : state_(std::exchange(moved_completion.state_, nullptr)), + code_(moved_completion.code_), + invoke_(moved_completion.invoke_) {} completion(completion const&) = delete; completion& operator=(completion const&) = delete; @@ -543,11 +558,11 @@ class heavy_state { } void operator()() { - auto* const state = std::exchange(state_, nullptr); + auto* const operation_state = std::exchange(state_, nullptr); if (invoke_) { - state->complete(code_); + operation_state->complete(code_); } else { - state->destroy(); + operation_state->destroy(); } } @@ -557,16 +572,18 @@ class heavy_state { bool invoke_; }; - heavy_state(Handler handler, WorkExecutor const& work, Work run, std::span output) - : handler_work_( - webcpp::asio::make_work_guard(webcpp::asio::get_associated_executor(handler, work))), - handler_(std::in_place, std::move(handler)), - run_(std::move(run)), - output_(output) {} + heavy_state(Handler completion_handler, WorkExecutor const& work_executor, Work bound_call, + std::span output_bytes) + : handler_work_(webcpp::asio::make_work_guard( + webcpp::asio::get_associated_executor(completion_handler, work_executor))), + handler_(std::in_place, std::move(completion_handler)), + run_(std::move(bound_call)), + output_(output_bytes) {} // Constructs the state in `storage`, which is given back if the construction throws. - static void try_construct(allocator_type& allocator, heavy_state* storage, Handler handler, - WorkExecutor const& work, Work run, std::span output) { + static void try_construct(allocator_type& handler_allocator, heavy_state* state_storage, + Handler completion_handler, WorkExecutor const& work_executor, + Work bound_call, std::span output_bytes) { struct give_back { allocator_type& allocator; heavy_state* storage; @@ -576,11 +593,11 @@ class heavy_state { std::allocator_traits::deallocate(allocator, storage, 1); } } - } guard{allocator, storage}; + } storage_guard{handler_allocator, state_storage}; - ::new (static_cast(storage)) - heavy_state(std::move(handler), work, std::move(run), output); - guard.storage = nullptr; + ::new (static_cast(state_storage)) heavy_state( + std::move(completion_handler), work_executor, std::move(bound_call), output_bytes); + storage_guard.storage = nullptr; } void lock() noexcept { @@ -592,58 +609,59 @@ class heavy_state { void unlock() noexcept { lock_.clear(std::memory_order_release); } // The completion bound to the handler's associated allocator; `invoke` false only discards. - auto bound_completion(boost::system::error_code code, bool invoke = true) { + auto bound_completion(boost::system::error_code completion_code, bool invoke_handler = true) { // NOLINTNEXTLINE(bugprone-unchecked-optional-access): engaged until the completion return webcpp::asio::bind_allocator(webcpp::asio::get_associated_allocator(*handler_), - completion(this, code, invoke)); + completion(this, completion_code, invoke_handler)); } // Dispatches the completion to the handler's executor; the caller touches the state no more. - void complete_on_handler(boost::system::error_code code) { - auto const executor = handler_work_.get_executor(); - webcpp::asio::dispatch(executor, bound_completion(code)); + void complete_on_handler(boost::system::error_code completion_code) { + auto const completion_executor = handler_work_.get_executor(); + webcpp::asio::dispatch(completion_executor, bound_completion(completion_code)); } // Clears the slot, takes the handler and the executor's work out, frees the state, then calls // the handler: nothing of the handler's allocator outlives the call. - void complete(boost::system::error_code code) { + void complete(boost::system::error_code completion_code) { clear_slot(); // NOLINTNEXTLINE(bugprone-unchecked-optional-access): engaged until here - Handler handler(std::move(*handler_)); - auto work = std::move(handler_work_); - allocator_type allocator(webcpp::asio::get_associated_allocator(handler)); + Handler completion_handler(std::move(*handler_)); + auto work_guard = std::move(handler_work_); + allocator_type handler_allocator( + webcpp::asio::get_associated_allocator(completion_handler)); if constexpr (std::is_void_v) { - release_storage(allocator); - std::move(handler)(code); + release_storage(handler_allocator); + std::move(completion_handler)(completion_code); } else { - value_type const value = value_.value; - release_storage(allocator); - std::move(handler)(code, value); + value_type const completion_value = value_.value; + release_storage(handler_allocator); + std::move(completion_handler)(completion_code, completion_value); } - work.reset(); + work_guard.reset(); } // Clears the slot, then destroys the state, the handler with it, and gives its storage back. void destroy() { clear_slot(); // NOLINTNEXTLINE(bugprone-unchecked-optional-access): engaged until here - allocator_type allocator(webcpp::asio::get_associated_allocator(*handler_)); - release_storage(allocator); + allocator_type handler_allocator(webcpp::asio::get_associated_allocator(*handler_)); + release_storage(handler_allocator); } // Removes the cancellation handler, on the handler's executor, before the state goes. void clear_slot() { // NOLINTNEXTLINE(bugprone-unchecked-optional-access): engaged until here - auto slot = webcpp::asio::get_associated_cancellation_slot(*handler_); - if (slot.is_connected()) { - slot.clear(); + auto handler_slot = webcpp::asio::get_associated_cancellation_slot(*handler_); + if (handler_slot.is_connected()) { + handler_slot.clear(); } } // Destroys the state and gives its storage back to a copy of the handler's allocator. - void release_storage(allocator_type& allocator) { - std::allocator_traits::destroy(allocator, this); - std::allocator_traits::deallocate(allocator, this, 1); + void release_storage(allocator_type& handler_allocator) { + std::allocator_traits::destroy(handler_allocator, this); + std::allocator_traits::deallocate(handler_allocator, this, 1); } std::atomic_flag lock_ = ATOMIC_FLAG_INIT; @@ -670,22 +688,25 @@ template class heavy_job { public: /** - Holds `state`, before the state can be cancelled. + Holds `operation_state`, before the state can be cancelled. - @param state The operation's state. + @param operation_state The operation's state. */ - explicit heavy_job(State* state) noexcept : state_(state) { state->relocate(&state_); } + explicit heavy_job(State* operation_state) noexcept : state_(operation_state) { + operation_state->relocate(&state_); + } /** - Takes `other`'s hold, and records the new location; a hold taken back by a cancellation is + Takes `moved_job`'s hold, and records the new location; a hold taken back by a cancellation is null, and the state is then touched no more. - @param other The job moved from. + @param moved_job The job moved from. */ - heavy_job(heavy_job&& other) noexcept - : state_(other.state_.exchange(nullptr, std::memory_order_acq_rel)) { - if (auto* const held = state_.load(std::memory_order_relaxed); held != nullptr) { - held->relocate(&state_); + heavy_job(heavy_job&& moved_job) noexcept + : state_(moved_job.state_.exchange(nullptr, std::memory_order_acq_rel)) { + if (auto* const held_state = state_.load(std::memory_order_relaxed); + held_state != nullptr) { + held_state->relocate(&state_); } } @@ -701,17 +722,17 @@ class heavy_job { // exception from any of Asio's destructors does. // NOLINTNEXTLINE(bugprone-exception-escape): see above ~heavy_job() { - if (auto* const held = state_.exchange(nullptr, std::memory_order_acq_rel); - held != nullptr) { - held->abandon(); + if (auto* const held_state = state_.exchange(nullptr, std::memory_order_acq_rel); + held_state != nullptr) { + held_state->abandon(); } } /** Runs the work on the work executor's thread, unless a cancellation took the state back. */ void operator()() { - if (auto* const held = state_.exchange(nullptr, std::memory_order_acq_rel); - held != nullptr) { - held->run_work(); + if (auto* const held_state = state_.exchange(nullptr, std::memory_order_acq_rel); + held_state != nullptr) { + held_state->run_work(); } } @@ -730,34 +751,38 @@ struct heavy_initiation { /** Checks the guards, then posts the work or the refusal. - @param handler The completion handler. @param work The work executor. - @param output The output. @param guards The guards, bound to the arguments. - @param run The synchronous function, bound to its arguments. + @param completion_handler The completion handler. @param work_executor The work executor. + @param output_bytes The output. @param bound_guards The guards, bound to the arguments. + @param bound_call The synchronous function, bound to its arguments. */ template - void operator()(Handler&& handler, WorkExecutor const& work, std::span output, - Guards const& guards, Work run) const { - auto const guarded = guards(); - if (!guarded) { - auto const executor = webcpp::asio::get_associated_executor(handler, work); + void operator()(Handler&& completion_handler, WorkExecutor const& work_executor, + std::span output_bytes, Guards const& bound_guards, + Work bound_call) const { + auto const guard_result = bound_guards(); + if (!guard_result) { + auto const completion_executor = + webcpp::asio::get_associated_executor(completion_handler, work_executor); if constexpr (std::is_void_v>) { - webcpp::asio::post(executor, webcpp::asio::append(std::forward(handler), - guarded.error())); + webcpp::asio::post(completion_executor, + webcpp::asio::append(std::forward(completion_handler), + guard_result.error())); } else { webcpp::asio::post( - executor, webcpp::asio::append(std::forward(handler), guarded.error(), - heavy_value_of{})); + completion_executor, + webcpp::asio::append(std::forward(completion_handler), + guard_result.error(), heavy_value_of{})); } return; } using state = heavy_state, WorkExecutor, Work>; // The job holds the state from its making on, so that a failure to install the // cancellation or to post abandons it rather than leak it with the executor's work. - auto* const made = - state::make(std::forward(handler), work, std::move(run), output); - heavy_job job(made); - made->install_cancellation(); - webcpp::asio::post(work, std::move(job)); + auto* const made_state = state::make(std::forward(completion_handler), + work_executor, std::move(bound_call), output_bytes); + heavy_job queued_job(made_state); + made_state->install_cancellation(); + webcpp::asio::post(work_executor, std::move(queued_job)); } }; @@ -765,26 +790,28 @@ struct heavy_initiation { Initiates a heavy function (spec 11.5), of the signature its synchronous function's value gives (@ref heavy_signature). - @param work The work executor. @param output The output's bytes, zeroed after a cancellation - during the work; empty for `bcrypt_verify`, which has none. - @param guards The guards, bound to the arguments. @param run The synchronous function, bound to - its arguments. @param token The completion token. + @param work_executor The work executor. @param output_bytes The output's bytes, zeroed after a + cancellation during the work; empty for `bcrypt_verify`, which has none. + @param bound_guards The guards, bound to the arguments. @param bound_call The synchronous function, + bound to its arguments. @param completion_token The completion token. @return What the completion token's `async_result` gives. */ template -auto run_on_work(WorkExecutor const& work, std::span output, Guards guards, Work run, - CompletionToken& token) { +auto run_on_work(WorkExecutor const& work_executor, std::span output_bytes, + Guards bound_guards, Work bound_call, CompletionToken& completion_token) { return webcpp::asio_backend::async_initiate>>( - heavy_initiation{}, token, work, output, std::move(guards), std::move(run)); + heavy_initiation{}, completion_token, work_executor, output_bytes, std::move(bound_guards), + std::move(bound_call)); } } // namespace detail /** - Hashes `input` into `output` with the digest `Digest`, asynchronously (spec 11): on a synchronous - backend, the default, at once, completing through a post on the handler's associated executor - (`executor` by default), never inside the call. + Hashes `input_bytes` into `output_bytes` with the digest `Digest`, asynchronously (spec 11): on a + synchronous backend, the default, at once, completing through a post on the handler's associated + executor + (`completion_executor` by default), never inside the call. @code webcpp::hash::async_digest( @@ -797,22 +824,23 @@ auto run_on_work(WorkExecutor const& work, std::span output, Guards g default. `backends::webcrypto` only on Emscripten. @tparam Executor An Asio executor, where the completion is posted. @tparam CompletionToken An Asio completion token of signature `void(boost::system::error_code)`. - @param executor The executor the completion is posted to; on `backends::webcrypto`, that of an - `io_context` run on the calling thread (see @ref async_pbkdf2), and a refusal of another goes to - the handler's associated executor, this one unless the handler is bound to another. - @param output The digest, of exactly the digest's size; the caller's until completion. - @param input The data; the caller's until completion. - @param token The completion token, of signature `void(boost::system::error_code)`. + @param completion_executor The executor the completion is posted to; on `backends::webcrypto`, that + of an `io_context` run on the calling thread (see @ref async_pbkdf2), and a refusal of another goes + to the handler's associated executor, this one unless the handler is bound to another. + @param output_bytes The digest, of exactly the digest's size; the caller's until completion. + @param input_bytes The data; the caller's until completion. + @param completion_token The completion token, of signature `void(boost::system::error_code)`. @return What the completion token's `async_result` gives. The completion's code is empty on - success, or `digest_of`'s error, `output` untouched by a guard's refusal and zeroed by a backend's - failure. On `backends::webcrypto` also `invalid_parameters` (the executor), `output` untouched, - `backend_failure` (a rejected promise, an unexpected result, no WebCrypto), `output` zeroed, and - `operation_aborted` (a `terminal` or `partial` cancellation, at once), `output` zeroed. + success, or `digest_of`'s error, `output_bytes` untouched by a guard's refusal and zeroed by a + backend's failure. On `backends::webcrypto` also `invalid_parameters` (the executor), + `output_bytes` untouched, `backend_failure` (a rejected promise, an unexpected result, no + WebCrypto), `output_bytes` zeroed, and `operation_aborted` (a `terminal` or `partial` cancellation, + at once), `output_bytes` zeroed. */ template , class Executor, class CompletionToken> -auto async_digest(Executor const& executor, std::span output, - std::span input, CompletionToken&& token) { +auto async_digest(Executor const& completion_executor, std::span output_bytes, + std::span input_bytes, CompletionToken&& completion_token) { if constexpr (!detail::webcrypto_digest_v) { static_assert(detail::always_false, "webcpp::hash: async_digest takes digests::sha1, digests::sha2_256, " @@ -820,15 +848,19 @@ auto async_digest(Executor const& executor, std::span output, "digest_of for the others."); } else if constexpr (detail::asynchronous_backend_v) { return detail::async_engine::template digest( - executor, output, input, std::forward(token)); + completion_executor, output_bytes, input_bytes, + std::forward(completion_token)); } else { return detail::complete_by_post( - executor, token, [output, input] { return digest_of(output, input); }); + completion_executor, completion_token, [output_bytes, input_bytes] { + return digest_of(output_bytes, input_bytes); + }); } } /** - The HMAC of `input` under `key` over the Boost.Hash2 hmac `Hmac`, asynchronously (spec 11), as + The HMAC of `input_bytes` under `key_bytes` over the Boost.Hash2 hmac `Hmac`, asynchronously (spec + 11), as @ref async_digest runs: the tag of `mac>` over `Hmac`'s digest. @tparam Hmac `hmac_sha1_160`, `hmac_sha2_256`, `hmac_sha2_384` or `hmac_sha2_512`, the hmacs @@ -837,23 +869,25 @@ auto async_digest(Executor const& executor, std::span output, synchronous default. `backends::webcrypto` only on Emscripten. @tparam Executor An Asio executor, where the completion is posted. @tparam CompletionToken An Asio completion token of signature `void(boost::system::error_code)`. - @param executor The executor the completion is posted to; on `backends::webcrypto`, that of an - `io_context` run on the calling thread (see @ref async_pbkdf2), and a refusal of another goes to - the handler's associated executor, this one unless the handler is bound to another. - @param output The tag, 10 bytes up to the digest's size; the caller's until completion. - @param key The key, of any size. @param input The message. Both the caller's until completion. - @param token The completion token, of signature `void(boost::system::error_code)`. + @param completion_executor The executor the completion is posted to; on `backends::webcrypto`, that + of an `io_context` run on the calling thread (see @ref async_pbkdf2), and a refusal of another goes + to the handler's associated executor, this one unless the handler is bound to another. + @param output_bytes The tag, 10 bytes up to the digest's size; the caller's until completion. + @param key_bytes The key, of any size. @param input_bytes The message. Both the caller's until + completion. + @param completion_token The completion token, of signature `void(boost::system::error_code)`. @return What the completion token's `async_result` gives. The completion's code is empty on - success, or `mac`'s error, `output` untouched by a guard's refusal and zeroed by a backend's - failure. On `backends::webcrypto` also `invalid_parameters` (the executor), `output` untouched, - `backend_failure` (a rejected promise, an unexpected result, no WebCrypto), `output` zeroed, and - `operation_aborted` (a `terminal` or `partial` cancellation, at once), `output` zeroed. + success, or `mac`'s error, `output_bytes` untouched by a guard's refusal and zeroed by a backend's + failure. On `backends::webcrypto` also `invalid_parameters` (the executor), `output_bytes` + untouched, `backend_failure` (a rejected promise, an unexpected result, no WebCrypto), + `output_bytes` zeroed, and `operation_aborted` (a `terminal` or `partial` cancellation, at once), + `output_bytes` zeroed. */ template >, class Executor, class CompletionToken> -auto async_hmac(Executor const& executor, std::span output, - std::span key, std::span input, - CompletionToken&& token) { +auto async_hmac(Executor const& completion_executor, std::span output_bytes, + std::span key_bytes, std::span input_bytes, + CompletionToken&& completion_token) { if constexpr (!detail::webcrypto_hmac_v) { static_assert(detail::always_false, "webcpp::hash: async_hmac takes hmac_sha1_160, hmac_sha2_256, " @@ -861,11 +895,14 @@ auto async_hmac(Executor const& executor, std::span output, "others."); } else if constexpr (detail::asynchronous_backend_v) { return detail::async_engine::template hmac( - executor, output, key, input, std::forward(token)); + completion_executor, output_bytes, key_bytes, input_bytes, + std::forward(completion_token)); } else { - return detail::complete_by_post(executor, token, [output, key, input] { - return mac, Backend>(output, key, input); - }); + return detail::complete_by_post(completion_executor, completion_token, + [output_bytes, key_bytes, input_bytes] { + return mac, Backend>( + output_bytes, key_bytes, input_bytes); + }); } } @@ -879,15 +916,15 @@ auto async_hmac(Executor const& executor, std::span output, synchronous default. `backends::webcrypto` only on Emscripten. @tparam Executor An Asio executor, where the completion is posted. @tparam CompletionToken An Asio completion token of signature `void(boost::system::error_code)`. - @param executor The executor the completion is posted to; on `backends::webcrypto`, that of an - `io_context` run on the calling thread (see @ref async_pbkdf2), and a refusal of another goes to - the handler's associated executor, this one unless the handler is bound to another. + @param completion_executor The executor the completion is posted to; on `backends::webcrypto`, that + of an `io_context` run on the calling thread (see @ref async_pbkdf2), and a refusal of another goes + to the handler's associated executor, this one unless the handler is bound to another. @param output_key_material The output keying material, 1 to 255 times the digest size. - @param salt The salt. @param input_key_material The input keying material. @param application_info - The context, at most `hkdf_max_application_info_size` bytes; on `backends::webcrypto` at most - 1,024, WebCrypto's limit + @param salt_bytes The salt. @param input_key_material The input keying material. @param + application_info The context, at most `hkdf_max_application_info_size` bytes; on + `backends::webcrypto` at most 1,024, WebCrypto's limit (`input_too_long` beyond). The spans are the caller's until completion. - @param token The completion token, of signature `void(boost::system::error_code)`. + @param completion_token The completion token, of signature `void(boost::system::error_code)`. @return What the completion token's `async_result` gives. The completion's code is empty on success, or `hkdf`'s error, `output_key_material` untouched by a guard's refusal and zeroed by a backend's failure. On `backends::webcrypto` also `invalid_parameters` (the executor), @@ -897,10 +934,11 @@ auto async_hmac(Executor const& executor, std::span output, */ template , class Executor, class CompletionToken> -auto async_hkdf(Executor const& executor, std::span output_key_material, - std::span salt, +auto async_hkdf(Executor const& completion_executor, std::span output_key_material, + std::span salt_bytes, std::span input_key_material, - std::span application_info, CompletionToken&& token) { + std::span application_info, + CompletionToken&& completion_token) { if constexpr (!detail::webcrypto_hmac_v) { static_assert(detail::always_false, "webcpp::hash: async_hkdf takes hmac_sha1_160, hmac_sha2_256, " @@ -908,12 +946,13 @@ auto async_hkdf(Executor const& executor, std::span output_key_mat "hkdf for the others."); } else if constexpr (detail::asynchronous_backend_v) { return detail::async_engine::template hkdf( - executor, output_key_material, salt, input_key_material, application_info, - std::forward(token)); + completion_executor, output_key_material, salt_bytes, input_key_material, + application_info, std::forward(completion_token)); } else { return detail::complete_by_post( - executor, token, [output_key_material, salt, input_key_material, application_info] { - return hkdf(output_key_material, salt, input_key_material, + completion_executor, completion_token, + [output_key_material, salt_bytes, input_key_material, application_info] { + return hkdf(output_key_material, salt_bytes, input_key_material, application_info); }); } @@ -925,8 +964,8 @@ auto async_hkdf(Executor const& executor, std::span output_key_mat On a synchronous backend, the default, the synchronous function runs in the call itself, before the operation is initiated, and only its error code is posted to the handler's associated - executor (`executor` by default): the pieces and their list are read before the call returns, so - that a braced list written at the call, whose array dies at the end of the call's + executor (`completion_executor` by default): the pieces and their list are read before the call + returns, so that a braced list written at the call, whose array dies at the end of the call's full-expression, is safe with every completion token, `asio::deferred` and `use_awaitable`'s lazy awaitable included (with those, the work is done at the call, not at the launch). On `backends::webcrypto` the pieces are gathered into JavaScript memory in the call too. @@ -943,23 +982,23 @@ auto async_hkdf(Executor const& executor, std::span output_key_mat synchronous default. `backends::webcrypto` only on Emscripten. @tparam Executor An Asio executor, where the completion is posted. @tparam CompletionToken An Asio completion token of signature `void(boost::system::error_code)`. - @param executor The executor the completion is posted to; on `backends::webcrypto`, that of an - `io_context` run on the calling thread (see @ref async_pbkdf2), and a refusal of another goes to - the handler's associated executor, this one unless the handler is bound to another. + @param completion_executor The executor the completion is posted to; on `backends::webcrypto`, that + of an `io_context` run on the calling thread (see @ref async_pbkdf2), and a refusal of another goes + to the handler's associated executor, this one unless the handler is bound to another. @param output_key_material The output keying material, 1 to 255 times the digest size; the caller's until completion. - @param salt The salt. @param input_key_material The input keying material's pieces. + @param salt_bytes The salt. @param input_key_material The input keying material's pieces. @param application_info The context's pieces. The salt and the pieces are read in the call. - @param token The completion token, of signature `void(boost::system::error_code)`. + @param completion_token The completion token, of signature `void(boost::system::error_code)`. @return What the completion token's `async_result` gives. The completion's code is empty on success, or `hkdf`'s error over pieces, `output_key_material` untouched by a guard's refusal and zeroed by a backend's failure. */ template , class Executor, class CompletionToken> -auto async_hkdf(Executor const& executor, std::span output_key_material, - std::span salt, byte_pieces input_key_material, - byte_pieces application_info, CompletionToken&& token) { +auto async_hkdf(Executor const& completion_executor, std::span output_key_material, + std::span salt_bytes, byte_pieces input_key_material, + byte_pieces application_info, CompletionToken&& completion_token) { if constexpr (!detail::webcrypto_hmac_v) { static_assert(detail::always_false, "webcpp::hash: async_hkdf takes hmac_sha1_160, hmac_sha2_256, " @@ -967,12 +1006,12 @@ auto async_hkdf(Executor const& executor, std::span output_key_mat "hkdf for the others."); } else if constexpr (detail::asynchronous_backend_v) { return detail::async_engine::template hkdf( - executor, output_key_material, salt, input_key_material, application_info, - std::forward(token)); + completion_executor, output_key_material, salt_bytes, input_key_material, + application_info, std::forward(completion_token)); } else { - auto const code = detail::code_of( - hkdf(output_key_material, salt, input_key_material, application_info)); - return detail::complete_with_code(executor, token, code); + auto const call_code = detail::code_of(hkdf( + output_key_material, salt_bytes, input_key_material, application_info)); + return detail::complete_with_code(completion_executor, completion_token, call_code); } } @@ -986,13 +1025,13 @@ auto async_hkdf(Executor const& executor, std::span output_key_mat synchronous default. `backends::webcrypto` only on Emscripten. @tparam Executor An Asio executor, where the completion is posted. @tparam CompletionToken An Asio completion token of signature `void(boost::system::error_code)`. - @param executor The executor the completion is posted to; on `backends::webcrypto`, that of an - `io_context` run on the calling thread (see @ref async_pbkdf2), and a refusal of another goes to - the handler's associated executor, this one unless the handler is bound to another. + @param completion_executor The executor the completion is posted to; on `backends::webcrypto`, that + of an `io_context` run on the calling thread (see @ref async_pbkdf2), and a refusal of another goes + to the handler's associated executor, this one unless the handler is bound to another. @param pseudorandom_key The pseudorandom key, of exactly the digest size. - @param salt The salt. @param input_key_material The input keying material. The spans are the + @param salt_bytes The salt. @param input_key_material The input keying material. The spans are the caller's until completion. - @param token The completion token, of signature `void(boost::system::error_code)`. + @param completion_token The completion token, of signature `void(boost::system::error_code)`. @return What the completion token's `async_result` gives. The completion's code is empty on success, or `invalid_output_size` for a `pseudorandom_key` of another size than the digest's, or `hkdf_extract`'s error, `pseudorandom_key` untouched by a guard's refusal and zeroed by a @@ -1000,9 +1039,11 @@ auto async_hkdf(Executor const& executor, std::span output_key_mat */ template , class Executor, class CompletionToken> -auto async_hkdf_extract(Executor const& executor, std::span pseudorandom_key, - std::span salt, - std::span input_key_material, CompletionToken&& token) { +auto async_hkdf_extract(Executor const& completion_executor, + std::span pseudorandom_key, + std::span salt_bytes, + std::span input_key_material, + CompletionToken&& completion_token) { if constexpr (!detail::webcrypto_hmac_v) { static_assert(detail::always_false, "webcpp::hash: async_hkdf_extract takes hmac_sha1_160, hmac_sha2_256, " @@ -1010,13 +1051,13 @@ auto async_hkdf_extract(Executor const& executor, std::span pseudo "hkdf_extract for the others."); } else if constexpr (detail::asynchronous_backend_v) { return detail::async_engine::template hkdf_extract( - executor, pseudorandom_key, salt, input_key_material, - std::forward(token)); + completion_executor, pseudorandom_key, salt_bytes, input_key_material, + std::forward(completion_token)); } else { - return detail::complete_by_post(executor, token, - [pseudorandom_key, salt, input_key_material] { + return detail::complete_by_post(completion_executor, completion_token, + [pseudorandom_key, salt_bytes, input_key_material] { return detail::hkdf_extract_into( - pseudorandom_key, salt, input_key_material); + pseudorandom_key, salt_bytes, input_key_material); }); } } @@ -1032,14 +1073,14 @@ auto async_hkdf_extract(Executor const& executor, std::span pseudo `kdfs::hkdf_extract_pieces`, the synchronous default. `backends::webcrypto` only on Emscripten. @tparam Executor An Asio executor, where the completion is posted. @tparam CompletionToken An Asio completion token of signature `void(boost::system::error_code)`. - @param executor The executor the completion is posted to; on `backends::webcrypto`, that of an - `io_context` run on the calling thread (see @ref async_pbkdf2), and a refusal of another goes to - the handler's associated executor, this one unless the handler is bound to another. + @param completion_executor The executor the completion is posted to; on `backends::webcrypto`, that + of an `io_context` run on the calling thread (see @ref async_pbkdf2), and a refusal of another goes + to the handler's associated executor, this one unless the handler is bound to another. @param pseudorandom_key The pseudorandom key, of exactly the digest size; the caller's until completion. - @param salt The salt. @param input_key_material The input keying material's pieces. Both read in - the call. - @param token The completion token, of signature `void(boost::system::error_code)`. + @param salt_bytes The salt. @param input_key_material The input keying material's pieces. Both read + in the call. + @param completion_token The completion token, of signature `void(boost::system::error_code)`. @return What the completion token's `async_result` gives. The completion's code is empty on success, or `invalid_output_size` for a `pseudorandom_key` of another size than the digest's, or `hkdf_extract`'s error over pieces, `pseudorandom_key` untouched by a guard's refusal and zeroed @@ -1047,9 +1088,10 @@ auto async_hkdf_extract(Executor const& executor, std::span pseudo */ template , class Executor, class CompletionToken> -auto async_hkdf_extract(Executor const& executor, std::span pseudorandom_key, - std::span salt, byte_pieces input_key_material, - CompletionToken&& token) { +auto async_hkdf_extract(Executor const& completion_executor, + std::span pseudorandom_key, + std::span salt_bytes, byte_pieces input_key_material, + CompletionToken&& completion_token) { if constexpr (!detail::webcrypto_hmac_v) { static_assert(detail::always_false, "webcpp::hash: async_hkdf_extract takes hmac_sha1_160, hmac_sha2_256, " @@ -1057,12 +1099,12 @@ auto async_hkdf_extract(Executor const& executor, std::span pseudo "hkdf_extract for the others."); } else if constexpr (detail::asynchronous_backend_v) { return detail::async_engine::template hkdf_extract( - executor, pseudorandom_key, salt, input_key_material, - std::forward(token)); + completion_executor, pseudorandom_key, salt_bytes, input_key_material, + std::forward(completion_token)); } else { - auto const code = detail::code_of( - detail::hkdf_extract_into(pseudorandom_key, salt, input_key_material)); - return detail::complete_with_code(executor, token, code); + auto const call_code = detail::code_of(detail::hkdf_extract_into( + pseudorandom_key, salt_bytes, input_key_material)); + return detail::complete_with_code(completion_executor, completion_token, call_code); } } @@ -1076,23 +1118,25 @@ auto async_hkdf_extract(Executor const& executor, std::span pseudo synchronous default. `backends::webcrypto` only on Emscripten. @tparam Executor An Asio executor, where the completion is posted. @tparam CompletionToken An Asio completion token of signature `void(boost::system::error_code)`. - @param executor The executor the completion is posted to; on `backends::webcrypto`, that of an - `io_context` run on the calling thread (see @ref async_pbkdf2), and a refusal of another goes to - the handler's associated executor, this one unless the handler is bound to another. + @param completion_executor The executor the completion is posted to; on `backends::webcrypto`, that + of an `io_context` run on the calling thread (see @ref async_pbkdf2), and a refusal of another goes + to the handler's associated executor, this one unless the handler is bound to another. @param output_key_material The output keying material, 1 to 255 times the digest size. @param pseudorandom_key The pseudorandom key, of exactly the digest size. @param application_info The context, at most `hkdf_max_application_info_size` bytes. The spans are the caller's until completion. - @param token The completion token, of signature `void(boost::system::error_code)`. + @param completion_token The completion token, of signature `void(boost::system::error_code)`. @return What the completion token's `async_result` gives. The completion's code is empty on success, or `hkdf_expand`'s error, `output_key_material` untouched by a guard's refusal and zeroed by a backend's failure. */ template , class Executor, class CompletionToken> -auto async_hkdf_expand(Executor const& executor, std::span output_key_material, +auto async_hkdf_expand(Executor const& completion_executor, + std::span output_key_material, std::span pseudorandom_key, - std::span application_info, CompletionToken&& token) { + std::span application_info, + CompletionToken&& completion_token) { if constexpr (!detail::webcrypto_hmac_v) { static_assert(detail::always_false, "webcpp::hash: async_hkdf_expand takes hmac_sha1_160, hmac_sha2_256, " @@ -1100,14 +1144,15 @@ auto async_hkdf_expand(Executor const& executor, std::span output_ "hkdf_expand for the others."); } else if constexpr (detail::asynchronous_backend_v) { return detail::async_engine::template hkdf_expand( - executor, output_key_material, pseudorandom_key, application_info, - std::forward(token)); + completion_executor, output_key_material, pseudorandom_key, application_info, + std::forward(completion_token)); } else { - return detail::complete_by_post( - executor, token, [output_key_material, pseudorandom_key, application_info] { - return hkdf_expand(output_key_material, pseudorandom_key, - application_info); - }); + return detail::complete_by_post(completion_executor, completion_token, + [output_key_material, pseudorandom_key, application_info] { + return hkdf_expand(output_key_material, + pseudorandom_key, + application_info); + }); } } @@ -1122,23 +1167,24 @@ auto async_hkdf_expand(Executor const& executor, std::span output_ `kdfs::hkdf_expand_pieces`, the synchronous default. `backends::webcrypto` only on Emscripten. @tparam Executor An Asio executor, where the completion is posted. @tparam CompletionToken An Asio completion token of signature `void(boost::system::error_code)`. - @param executor The executor the completion is posted to; on `backends::webcrypto`, that of an - `io_context` run on the calling thread (see @ref async_pbkdf2), and a refusal of another goes to - the handler's associated executor, this one unless the handler is bound to another. + @param completion_executor The executor the completion is posted to; on `backends::webcrypto`, that + of an `io_context` run on the calling thread (see @ref async_pbkdf2), and a refusal of another goes + to the handler's associated executor, this one unless the handler is bound to another. @param output_key_material The output keying material, 1 to 255 times the digest size; the caller's until completion. @param pseudorandom_key The pseudorandom key, of exactly the digest size. @param application_info The context's pieces. The key and the pieces are read in the call. - @param token The completion token, of signature `void(boost::system::error_code)`. + @param completion_token The completion token, of signature `void(boost::system::error_code)`. @return What the completion token's `async_result` gives. The completion's code is empty on success, or `hkdf_expand`'s error over pieces, `output_key_material` untouched by a guard's refusal and zeroed by a backend's failure. */ template , class Executor, class CompletionToken> -auto async_hkdf_expand(Executor const& executor, std::span output_key_material, +auto async_hkdf_expand(Executor const& completion_executor, + std::span output_key_material, std::span pseudorandom_key, byte_pieces application_info, - CompletionToken&& token) { + CompletionToken&& completion_token) { if constexpr (!detail::webcrypto_hmac_v) { static_assert(detail::always_false, "webcpp::hash: async_hkdf_expand takes hmac_sha1_160, hmac_sha2_256, " @@ -1146,12 +1192,12 @@ auto async_hkdf_expand(Executor const& executor, std::span output_ "hkdf_expand for the others."); } else if constexpr (detail::asynchronous_backend_v) { return detail::async_engine::template hkdf_expand( - executor, output_key_material, pseudorandom_key, application_info, - std::forward(token)); + completion_executor, output_key_material, pseudorandom_key, application_info, + std::forward(completion_token)); } else { - auto const code = detail::code_of( + auto const call_code = detail::code_of( hkdf_expand(output_key_material, pseudorandom_key, application_info)); - return detail::complete_with_code(executor, token, code); + return detail::complete_with_code(completion_executor, completion_token, call_code); } } @@ -1159,29 +1205,30 @@ auto async_hkdf_expand(Executor const& executor, std::span output_ PBKDF2 (RFC 8018), asynchronously. On a synchronous backend, the default, a heavy function (spec 11.5): the work runs on a thread of - `executor`'s context (a `webcpp::asio::thread_pool`'s) and completes on the handler's associated - executor (`executor` by default; a program binds its event loop's with `bind_executor`), and it - exists only where the build has threads (`WEBCPP_HASH_HAS_THREADS`). On `backends::webcrypto`, on - Emscripten, the browser runs it and no thread is needed: there `executor` must be that of an - `io_context` run on the calling thread, whose `run` returns to the JavaScript event loop where - WebCrypto's promise settles (ruling R73). The context is checked: a concrete executor of another - context (a `thread_pool`'s) stops the build, and a type-erased one (`any_io_executor`) whose - context is not an `io_context`, or whose `io_context` executor it hides behind another allocator or - two concrete strands, completes with `invalid_parameters`, posted to the handler's associated - executor. The calling thread is the program's duty, not checked. WebCrypto takes at most 2^32 - 1 - iterations (`invalid_iterations`) and an output of at most (2^32 - 1) / 8 bytes + `work_executor`'s context (a `webcpp::asio::thread_pool`'s) and completes on the handler's + associated executor (`work_executor` by default; a program binds its event loop's with + `bind_executor`), and it exists only where the build has threads (`WEBCPP_HASH_HAS_THREADS`). On + `backends::webcrypto`, on Emscripten, the browser runs it and no thread is needed: there + `work_executor` must be that of an `io_context` run on the calling thread, whose `run` returns to + the JavaScript event loop where WebCrypto's promise settles (ruling R73). The context is checked: a + concrete executor of another context (a `thread_pool`'s) stops the build, and a type-erased one + (`any_io_executor`) whose context is not an `io_context`, or whose `io_context` executor it hides + behind another allocator or two concrete strands, completes with `invalid_parameters`, posted to + the handler's associated executor. The calling thread is the program's duty, not checked. WebCrypto + takes at most 2^32 - 1 iterations (`invalid_iterations`) and an output of at most (2^32 - 1) / 8 + bytes (`invalid_output_size`), over `hmac_sha1_160`, `hmac_sha2_256`, `hmac_sha2_384` and `hmac_sha2_512` alone. Cancellation through the handler's slot, on a synchronous backend: before the work starts, any type completes the operation at once with `operation_aborted`, the work never runs; during it, a - `terminal` or `partial` one lets the work end, then `output` is zeroed and the completion is + `terminal` or `partial` one lets the work end, then `output_bytes` is zeroed and the completion is `operation_aborted` (a `total` one is then ignored). "At once" is on the handler's associated - executor: for a handler without one, that is `executor`, so the completion waits for its + executor: for a handler without one, that is `work_executor`, so the completion waits for its threads; bind the handler to the event loop's executor, and emit the signal there too, never from another thread, as Asio's slots require. On `backends::webcrypto` a `terminal` or `partial` - one completes at once with `operation_aborted`, `output` zeroed, while the browser's work runs to - its end unseen; a `total` one is ignored. + one completes at once with `operation_aborted`, `output_bytes` zeroed, while the browser's work + runs to its end unseen; a `total` one is ignored. @tparam Hmac The pseudorandom function, as `hmac_sha2_512`. @tparam Backend The backend; by default @ref default_async_backend of `kdfs::pbkdf2`, the @@ -1189,42 +1236,46 @@ auto async_hkdf_expand(Executor const& executor, std::span output_ @tparam Executor An Asio executor: of the threads the work runs on, or WebCrypto's `io_context`'s. @tparam CompletionToken An Asio completion token of signature `void(boost::system::error_code)`. - @param executor The work executor, or WebCrypto's `io_context` executor. - @param output The derived key, 1 to (2^32 - 1) times the digest size. - @param password The password. @param salt The salt. The spans are the caller's until completion. - @param iterations The iteration count, at least 1. - @param token The completion token, of signature `void(boost::system::error_code)`. + @param work_executor The work executor, or WebCrypto's `io_context` executor. + @param output_bytes The derived key, 1 to (2^32 - 1) times the digest size. + @param password_bytes The password. @param salt_bytes The salt. The spans are the caller's until + completion. + @param iteration_count The iteration count, at least 1. + @param completion_token The completion token, of signature `void(boost::system::error_code)`. @return What the completion token's `async_result` gives. The completion's code is empty on - success, or `pbkdf2`'s error, a guard's refusal completing through a post, `output` untouched; or - `operation_aborted`. On `backends::webcrypto` also `invalid_parameters` (the executor), - `output` untouched, and `backend_failure` (a rejected promise, an unexpected result, no - WebCrypto), `output` zeroed. + success, or `pbkdf2`'s error, a guard's refusal completing through a post, `output_bytes` + untouched; or `operation_aborted`. On `backends::webcrypto` also `invalid_parameters` (the + executor), `output_bytes` untouched, and `backend_failure` (a rejected promise, an unexpected + result, no WebCrypto), `output_bytes` zeroed. */ template , class Executor, class CompletionToken> -auto async_pbkdf2(Executor const& executor, std::span output, - std::span password, std::span salt, - std::uint64_t iterations, CompletionToken&& token) { +auto async_pbkdf2(Executor const& work_executor, std::span output_bytes, + std::span password_bytes, + std::span salt_bytes, std::uint64_t iteration_count, + CompletionToken&& completion_token) { if constexpr (detail::asynchronous_backend_v) { return detail::async_engine::template pbkdf2( - executor, output, password, salt, iterations, std::forward(token)); + work_executor, output_bytes, password_bytes, salt_bytes, iteration_count, + std::forward(completion_token)); } else { #ifdef WEBCPP_HASH_HAS_THREADS return detail::run_on_work( - executor, std::as_writable_bytes(output), - [output_size = output.size(), password_size = password.size(), salt_size = salt.size(), - iterations] { + work_executor, std::as_writable_bytes(output_bytes), + [output_size = output_bytes.size(), password_size = password_bytes.size(), + salt_size = salt_bytes.size(), iteration_count] { if constexpr (!detail::takes_hmac()) { return boost::system::result(error::backend_failure); } else { return detail::pbkdf2_guards(output_size, password_size, - salt_size, iterations); + salt_size, iteration_count); } }, - [output, password, salt, iterations] { - return pbkdf2(output, password, salt, iterations); + [output_bytes, password_bytes, salt_bytes, iteration_count] { + return pbkdf2(output_bytes, password_bytes, salt_bytes, + iteration_count); }, - token); + completion_token); #else static_assert(detail::always_false, "webcpp::hash: async_pbkdf2 runs on another thread and needs a build with " @@ -1237,205 +1288,225 @@ auto async_pbkdf2(Executor const& executor, std::span output, #ifdef WEBCPP_HASH_HAS_THREADS /** - Argon2id (RFC 9106, one lane) on a thread of `work`'s context (spec 11.5). + Argon2id (RFC 9106, one lane) on a thread of `work_executor`'s context (spec 11.5). The guards of `argon2id` first, whose refusal completes through a post; then the work, posted to - `work` (a `webcpp::asio::thread_pool`'s executor, typically); the completion on the handler's - associated executor (`work` by default; a program binds its event loop's with `bind_executor`), - so that the event loop never blocks. Exists only where the build has threads + `work_executor` (a `webcpp::asio::thread_pool`'s executor, typically); the completion on the + handler's associated executor (`work_executor` by default; a program binds its event loop's with + `bind_executor`), so that the event loop never blocks. Exists only where the build has threads (`WEBCPP_HASH_HAS_THREADS`). Cancellation through the handler's slot: before the work starts, any type completes the operation at once with `operation_aborted`, the work never runs; during it, a `terminal` or - `partial` one lets the work end (libsodium cannot be interrupted), then `output` is zeroed and - the completion is `operation_aborted` (a `total` one is then ignored: zeroing is a side effect). - "At once" is on the handler's associated executor: for a handler without one, that is `work`, so - the completion waits for its threads; bind the handler to the event loop's executor, and emit - the signal there too, never from another thread, as Asio's slots require. + `partial` one lets the work end (libsodium cannot be interrupted), then `output_bytes` is zeroed + and the completion is `operation_aborted` (a `total` one is then ignored: zeroing is a side + effect). "At once" is on the handler's associated executor: for a handler without one, that is + `work_executor`, so the completion waits for its threads; bind the handler to the event loop's + executor, and emit the signal there too, never from another thread, as Asio's slots require. @tparam Backend The backend; by default @ref default_backend of `kdfs::argon2id`. @tparam WorkExecutor An Asio executor whose context runs on other threads. @tparam CompletionToken An Asio completion token of signature `void(boost::system::error_code)`. - @param work The executor of the threads the work runs on. - @param output The tag, 16 to 4,294,967,295 bytes. @param password The password. - @param salt The salt, of `argon2id_salt_size` bytes. The spans are the caller's until completion. - @param parameters The costs, copied. - @param token The completion token, of signature `void(boost::system::error_code)`. + @param work_executor The executor of the threads the work runs on. + @param output_bytes The tag, 16 to 4,294,967,295 bytes. @param password_bytes The password. + @param salt_bytes The salt, of `argon2id_salt_size` bytes. The spans are the caller's until + completion. + @param cost_parameters The costs, copied. + @param completion_token The completion token, of signature `void(boost::system::error_code)`. @return What the completion token's `async_result` gives. The completion's code is empty on success, or `argon2id`'s error, or `operation_aborted`. */ template , class WorkExecutor, class CompletionToken> -auto async_argon2id(WorkExecutor const& work, std::span output, - std::span password, std::span salt, - argon2id_parameters const& parameters, CompletionToken&& token) { +auto async_argon2id(WorkExecutor const& work_executor, std::span output_bytes, + std::span password_bytes, + std::span salt_bytes, + argon2id_parameters const& cost_parameters, + CompletionToken&& completion_token) { return detail::run_on_work( - work, std::as_writable_bytes(output), - [output_size = output.size(), password_size = password.size(), salt_size = salt.size(), - parameters] { + work_executor, std::as_writable_bytes(output_bytes), + [output_size = output_bytes.size(), password_size = password_bytes.size(), + salt_size = salt_bytes.size(), cost_parameters] { return detail::argon2id_guards(output_size, password_size, salt_size, - parameters); + cost_parameters); }, - [output, password, salt, parameters] { - return argon2id(output, password, salt, parameters); + [output_bytes, password_bytes, salt_bytes, cost_parameters] { + return argon2id(output_bytes, password_bytes, salt_bytes, cost_parameters); }, - token); + completion_token); } /** - Argon2 of the variant `Variant` with every parameter (RFC 9106) on a thread of `work`'s context, - as @ref async_argon2id runs. + Argon2 of the variant `Variant` with every parameter (RFC 9106) on a thread of `work_executor`'s + context, as @ref async_argon2id runs. @tparam Variant `kdfs::argon2id`, `kdfs::argon2i` or `kdfs::argon2d`. @tparam Backend The backend; by default @ref default_backend of `Variant`. @tparam WorkExecutor An Asio executor whose context runs on other threads. @tparam CompletionToken An Asio completion token of signature `void(boost::system::error_code)`. - @param work The executor of the threads the work runs on. - @param output The tag, 4 to 4,294,967,295 bytes. @param password The password. - @param salt The salt, 8 to 4,294,967,295 bytes. The spans, and those of `parameters`, are the - caller's until completion. - @param parameters The costs, the lanes, the secret and the associated data, copied. - @param token The completion token, of signature `void(boost::system::error_code)`. + @param work_executor The executor of the threads the work runs on. + @param output_bytes The tag, 4 to 4,294,967,295 bytes. @param password_bytes The password. + @param salt_bytes The salt, 8 to 4,294,967,295 bytes. The spans, and those of `cost_parameters`, + are the caller's until completion. + @param cost_parameters The costs, the lanes, the secret and the associated data, copied. + @param completion_token The completion token, of signature `void(boost::system::error_code)`. @return What the completion token's `async_result` gives. The completion's code is empty on success, or `argon2`'s error, or `operation_aborted`. */ template , class WorkExecutor, class CompletionToken> -auto async_argon2(WorkExecutor const& work, std::span output, - std::span password, std::span salt, - argon2_parameters const& parameters, CompletionToken&& token) { +auto async_argon2(WorkExecutor const& work_executor, std::span output_bytes, + std::span password_bytes, + std::span salt_bytes, + argon2_parameters const& cost_parameters, CompletionToken&& completion_token) { return detail::run_on_work( - work, std::as_writable_bytes(output), - [output_size = output.size(), password_size = password.size(), salt_size = salt.size(), - parameters] { + work_executor, std::as_writable_bytes(output_bytes), + [output_size = output_bytes.size(), password_size = password_bytes.size(), + salt_size = salt_bytes.size(), cost_parameters] { return detail::argon2_guards(output_size, password_size, salt_size, - parameters); + cost_parameters); }, - [output, password, salt, parameters] { - return argon2(output, password, salt, parameters); + [output_bytes, password_bytes, salt_bytes, cost_parameters] { + return argon2(output_bytes, password_bytes, salt_bytes, + cost_parameters); }, - token); + completion_token); } /** - scrypt (RFC 7914) on a thread of `work`'s context, as @ref async_argon2id runs. + scrypt (RFC 7914) on a thread of `work_executor`'s context, as @ref async_argon2id runs. @tparam Backend The backend; by default @ref default_backend of `kdfs::scrypt`. @tparam WorkExecutor An Asio executor whose context runs on other threads. @tparam CompletionToken An Asio completion token of signature `void(boost::system::error_code)`. - @param work The executor of the threads the work runs on. - @param output The derived key. @param password The password. @param salt The salt. The spans - are the caller's until completion. - @param parameters The costs, copied. - @param token The completion token, of signature `void(boost::system::error_code)`. + @param work_executor The executor of the threads the work runs on. + @param output_bytes The derived key. @param password_bytes The password. @param salt_bytes The + salt. The spans are the caller's until completion. + @param cost_parameters The costs, copied. + @param completion_token The completion token, of signature `void(boost::system::error_code)`. @return What the completion token's `async_result` gives. The completion's code is empty on success, or `scrypt`'s error, or `operation_aborted`. */ template , class WorkExecutor, class CompletionToken> -auto async_scrypt(WorkExecutor const& work, std::span output, - std::span password, std::span salt, - scrypt_parameters const& parameters, CompletionToken&& token) { +auto async_scrypt(WorkExecutor const& work_executor, std::span output_bytes, + std::span password_bytes, + std::span salt_bytes, + scrypt_parameters const& cost_parameters, CompletionToken&& completion_token) { return detail::run_on_work( - work, std::as_writable_bytes(output), - [output_size = output.size(), password_size = password.size(), salt_size = salt.size(), - parameters] { + work_executor, std::as_writable_bytes(output_bytes), + [output_size = output_bytes.size(), password_size = password_bytes.size(), + salt_size = salt_bytes.size(), cost_parameters] { return detail::scrypt_guards(output_size, password_size, salt_size, - parameters); + cost_parameters); }, - [output, password, salt, parameters] { - return scrypt(output, password, salt, parameters); + [output_bytes, password_bytes, salt_bytes, cost_parameters] { + return scrypt(output_bytes, password_bytes, salt_bytes, cost_parameters); }, - token); + completion_token); } /** - bcrypt on a thread of `work`'s context (spec 11.5), as @ref async_argon2id runs: the guards of - `bcrypt` first, whose refusal completes through a post, `output` untouched; then the work. + bcrypt on a thread of `work_executor`'s context (spec 11.5), as @ref async_argon2id runs: the + guards of `bcrypt` first, whose refusal completes through a post, `output_characters` untouched; + then the work. @tparam Backend The backend; @ref default_backend of `kdfs::bcrypt` has none: the call names `backends::botan`. @tparam WorkExecutor An Asio executor whose context runs on other threads. @tparam CompletionToken An Asio completion token of signature `void(boost::system::error_code)`. - @param work The executor of the threads the work runs on. - @param output The string, exactly `bcrypt_hash_size` characters. @param password The password. - @param salt The salt, of `bcrypt_salt_size` bytes. The spans are the caller's until completion. - @param parameters The cost and the version, copied. - @param token The completion token, of signature `void(boost::system::error_code)`. + @param work_executor The executor of the threads the work runs on. + @param output_characters The string, exactly `bcrypt_hash_size` characters. @param password_bytes + The password. + @param salt_bytes The salt, of `bcrypt_salt_size` bytes. The spans are the caller's until + completion. + @param cost_parameters The cost and the version, copied. + @param completion_token The completion token, of signature `void(boost::system::error_code)`. @return What the completion token's `async_result` gives. The completion's code is empty on success, or `bcrypt`'s error, or `operation_aborted` (a cancellation during the work zeroes - `output`). + `output_characters`). */ template , class WorkExecutor, class CompletionToken> -auto async_bcrypt(WorkExecutor const& work, std::span output, - std::span password, std::span salt, - bcrypt_parameters const& parameters, CompletionToken&& token) { +auto async_bcrypt(WorkExecutor const& work_executor, std::span output_characters, + std::span password_bytes, + std::span salt_bytes, + bcrypt_parameters const& cost_parameters, CompletionToken&& completion_token) { return detail::run_on_work( - work, std::as_writable_bytes(output), - [output_size = output.size(), password, salt_size = salt.size(), parameters] { - return detail::bcrypt_guards(output_size, password, salt_size, parameters); + work_executor, std::as_writable_bytes(output_characters), + [output_size = output_characters.size(), password_bytes, salt_size = salt_bytes.size(), + cost_parameters] { + return detail::bcrypt_guards(output_size, password_bytes, salt_size, + cost_parameters); }, - [output, password, salt, parameters] { - return bcrypt(output, password, salt, parameters); + [output_characters, password_bytes, salt_bytes, cost_parameters] { + return bcrypt(output_characters, password_bytes, salt_bytes, cost_parameters); }, - token); + completion_token); } /** - OpenBSD's bcrypt_pbkdf on a thread of `work`'s context, as @ref async_argon2id runs. + OpenBSD's bcrypt_pbkdf on a thread of `work_executor`'s context, as @ref async_argon2id runs. @tparam Backend The backend; @ref default_backend of `kdfs::bcrypt_pbkdf` has none: the call names `backends::botan`. @tparam WorkExecutor An Asio executor whose context runs on other threads. @tparam CompletionToken An Asio completion token of signature `void(boost::system::error_code)`. - @param work The executor of the threads the work runs on. - @param output The derived key, 1 to 1,024 bytes. @param password The password, 1 byte or more. - @param salt The salt, 1 to 1,048,576 bytes. The spans are the caller's until completion. - @param rounds The rounds, 1 or more. - @param token The completion token, of signature `void(boost::system::error_code)`. + @param work_executor The executor of the threads the work runs on. + @param output_bytes The derived key, 1 to 1,024 bytes. @param password_bytes The password, 1 byte + or more. + @param salt_bytes The salt, 1 to 1,048,576 bytes. The spans are the caller's until completion. + @param round_count The rounds, 1 or more. + @param completion_token The completion token, of signature `void(boost::system::error_code)`. @return What the completion token's `async_result` gives. The completion's code is empty on success, or `bcrypt_pbkdf`'s error, or `operation_aborted`. */ template , class WorkExecutor, class CompletionToken> -auto async_bcrypt_pbkdf(WorkExecutor const& work, std::span output, - std::span password, std::span salt, - std::uint32_t rounds, CompletionToken&& token) { +auto async_bcrypt_pbkdf(WorkExecutor const& work_executor, std::span output_bytes, + std::span password_bytes, + std::span salt_bytes, std::uint32_t round_count, + CompletionToken&& completion_token) { return detail::run_on_work( - work, std::as_writable_bytes(output), - [output_size = output.size(), password_size = password.size(), salt_size = salt.size(), - rounds] { - return detail::bcrypt_pbkdf_guards(output_size, password_size, salt_size, rounds); + work_executor, std::as_writable_bytes(output_bytes), + [output_size = output_bytes.size(), password_size = password_bytes.size(), + salt_size = salt_bytes.size(), round_count] { + return detail::bcrypt_pbkdf_guards(output_size, password_size, salt_size, round_count); }, - [output, password, salt, rounds] { - return bcrypt_pbkdf(output, password, salt, rounds); + [output_bytes, password_bytes, salt_bytes, round_count] { + return bcrypt_pbkdf(output_bytes, password_bytes, salt_bytes, round_count); }, - token); + completion_token); } /** - `bcrypt_verify` on a thread of `work`'s context, as @ref async_argon2id runs, completing with - whether the password gives the string: it computes bcrypt in full, as slow as `bcrypt` (spec 11.5: - every deliberately slow function has its heavy variant). + `bcrypt_verify` on a thread of `work_executor`'s context, as @ref async_argon2id runs, completing + with whether the password gives the string: it computes bcrypt in full, as slow as `bcrypt` + (spec 11.5: every deliberately slow function has its heavy variant). @tparam Backend The backend; the call names `backends::botan`, as for @ref async_bcrypt. @tparam WorkExecutor An Asio executor whose context runs on other threads. @tparam CompletionToken An Asio completion token of signature `void(boost::system::error_code, bool)`. - @param work The executor of the threads the work runs on. - @param password The password. @param hash The string, of bcrypt's form. Both are the caller's - until completion. - @param token The completion token, of signature `void(boost::system::error_code, bool)`. + @param work_executor The executor of the threads the work runs on. + @param password_bytes The password. @param encoded_hash The string, of bcrypt's form. Both are the + caller's until completion. + @param completion_token The completion token, of signature `void(boost::system::error_code, bool)`. @return What the completion token's `async_result` gives. The completion's code is empty on success, its `bool` then whether the password gives the string; or `bcrypt_verify`'s error, or `operation_aborted`, the `bool` false. */ template , class WorkExecutor, class CompletionToken> -auto async_bcrypt_verify(WorkExecutor const& work, std::span password, - std::string_view hash, CompletionToken&& token) { +auto async_bcrypt_verify(WorkExecutor const& work_executor, + std::span password_bytes, + std::string_view encoded_hash, CompletionToken&& completion_token) { return detail::run_on_work( - work, std::span{}, - [password, hash] { return detail::bcrypt_verify_guards(password, hash); }, - [password, hash] { return bcrypt_verify(password, hash); }, token); + work_executor, std::span{}, + [password_bytes, encoded_hash] { + return detail::bcrypt_verify_guards(password_bytes, encoded_hash); + }, + [password_bytes, encoded_hash] { + return bcrypt_verify(password_bytes, encoded_hash); + }, + completion_token); } #else @@ -1448,10 +1519,11 @@ auto async_bcrypt_verify(WorkExecutor const& work, std::span */ template , class WorkExecutor, class CompletionToken> -void async_argon2id(WorkExecutor const& /*work*/, std::span /*output*/, - std::span /*password*/, - std::span /*salt*/, - argon2id_parameters const& /*parameters*/, CompletionToken&& /*token*/) { +void async_argon2id(WorkExecutor const& /*work_executor*/, std::span /*output_bytes*/, + std::span /*password_bytes*/, + std::span /*salt_bytes*/, + argon2id_parameters const& /*cost_parameters*/, + CompletionToken&& /*completion_token*/) { static_assert(detail::always_false, "webcpp::hash: async_argon2id runs on another thread and needs a build with " "threads (natively, remove WEBCPP_HASH_NO_THREADS; on Emscripten, link with " @@ -1467,10 +1539,11 @@ void async_argon2id(WorkExecutor const& /*work*/, std::span /*outp */ template , class WorkExecutor, class CompletionToken> -void async_argon2(WorkExecutor const& /*work*/, std::span /*output*/, - std::span /*password*/, - std::span /*salt*/, argon2_parameters const& /*parameters*/, - CompletionToken&& /*token*/) { +void async_argon2(WorkExecutor const& /*work_executor*/, std::span /*output_bytes*/, + std::span /*password_bytes*/, + std::span /*salt_bytes*/, + argon2_parameters const& /*cost_parameters*/, + CompletionToken&& /*completion_token*/) { static_assert(detail::always_false, "webcpp::hash: async_argon2 runs on another thread and needs a build with " "threads (natively, remove WEBCPP_HASH_NO_THREADS; on Emscripten, link with " @@ -1484,10 +1557,11 @@ void async_argon2(WorkExecutor const& /*work*/, std::span /*output @tparam Backend The backend. @return Nothing: the refusal has stopped the build. */ template , class WorkExecutor, class CompletionToken> -void async_scrypt(WorkExecutor const& /*work*/, std::span /*output*/, - std::span /*password*/, - std::span /*salt*/, scrypt_parameters const& /*parameters*/, - CompletionToken&& /*token*/) { +void async_scrypt(WorkExecutor const& /*work_executor*/, std::span /*output_bytes*/, + std::span /*password_bytes*/, + std::span /*salt_bytes*/, + scrypt_parameters const& /*cost_parameters*/, + CompletionToken&& /*completion_token*/) { static_assert(detail::always_false, "webcpp::hash: async_scrypt runs on another thread and needs a build with " "threads (natively, remove WEBCPP_HASH_NO_THREADS; on Emscripten, link with " @@ -1501,10 +1575,11 @@ void async_scrypt(WorkExecutor const& /*work*/, std::span /*output @tparam Backend The backend. @return Nothing: the refusal has stopped the build. */ template , class WorkExecutor, class CompletionToken> -void async_bcrypt(WorkExecutor const& /*work*/, std::span /*output*/, - std::span /*password*/, - std::span /*salt*/, bcrypt_parameters const& /*parameters*/, - CompletionToken&& /*token*/) { +void async_bcrypt(WorkExecutor const& /*work_executor*/, std::span /*output_characters*/, + std::span /*password_bytes*/, + std::span /*salt_bytes*/, + bcrypt_parameters const& /*cost_parameters*/, + CompletionToken&& /*completion_token*/) { static_assert(detail::always_false, "webcpp::hash: async_bcrypt runs on another thread and needs a build with " "threads (natively, remove WEBCPP_HASH_NO_THREADS; on Emscripten, link with " @@ -1519,10 +1594,11 @@ void async_bcrypt(WorkExecutor const& /*work*/, std::span /*output*/, */ template , class WorkExecutor, class CompletionToken> -void async_bcrypt_pbkdf(WorkExecutor const& /*work*/, std::span /*output*/, - std::span /*password*/, - std::span /*salt*/, std::uint32_t /*rounds*/, - CompletionToken&& /*token*/) { +void async_bcrypt_pbkdf(WorkExecutor const& /*work_executor*/, + std::span /*output_bytes*/, + std::span /*password_bytes*/, + std::span /*salt_bytes*/, std::uint32_t /*round_count*/, + CompletionToken&& /*completion_token*/) { static_assert(detail::always_false, "webcpp::hash: async_bcrypt_pbkdf runs on another thread and needs a build with " "threads (natively, remove WEBCPP_HASH_NO_THREADS; on Emscripten, link with " @@ -1536,8 +1612,10 @@ void async_bcrypt_pbkdf(WorkExecutor const& /*work*/, std::span /* @tparam Backend The backend. @return Nothing: the refusal has stopped the build. */ template , class WorkExecutor, class CompletionToken> -void async_bcrypt_verify(WorkExecutor const& /*work*/, std::span /*password*/, - std::string_view /*hash*/, CompletionToken&& /*token*/) { +void async_bcrypt_verify(WorkExecutor const& /*work_executor*/, + std::span /*password_bytes*/, + std::string_view /*encoded_hash*/, + CompletionToken&& /*completion_token*/) { static_assert(detail::always_false, "webcpp::hash: async_bcrypt_verify runs on another thread and needs a build " "with threads (natively, remove WEBCPP_HASH_NO_THREADS; on Emscripten, link " diff --git a/include/webcpp/hash/backends/bearssl.hpp b/include/webcpp/hash/backends/bearssl.hpp index 6560d74..5c411d7 100644 --- a/include/webcpp/hash/backends/bearssl.hpp +++ b/include/webcpp/hash/backends/bearssl.hpp @@ -126,21 +126,22 @@ struct bearssl_digest { /** BearSSL's context. */ using context = br_md5_context; - /** Starts a hash. @param hashed The context. */ - static void init(context& hashed) noexcept { br_md5_init(&hashed); } + /** Starts a hash. @param digest_state The context. */ + static void init(context& digest_state) noexcept { br_md5_init(&digest_state); } /** Absorbs bytes. - @param hashed The context. @param data The bytes. @param size Their number. + @param digest_state The context. @param input_data The bytes. @param input_size Their number. */ - static void update(context& hashed, void const* data, std::size_t size) noexcept { - br_md5_update(&hashed, data, size); + static void update(context& digest_state, void const* input_data, + std::size_t input_size) noexcept { + br_md5_update(&digest_state, input_data, input_size); } - /** Writes the output. @param hashed The context. @param output The 16 bytes. */ - static void out(context& hashed, std::span output) noexcept { - br_md5_out(&hashed, output.data()); + /** Writes the output. @param digest_state The context. @param output_bytes The 16 bytes. */ + static void out(context& digest_state, std::span output_bytes) noexcept { + br_md5_out(&digest_state, output_bytes.data()); } /** The hash HMAC runs over. @return `&br_md5_vtable`. */ @@ -153,21 +154,22 @@ struct bearssl_digest { /** BearSSL's context. */ using context = br_sha1_context; - /** Starts a hash. @param hashed The context. */ - static void init(context& hashed) noexcept { br_sha1_init(&hashed); } + /** Starts a hash. @param digest_state The context. */ + static void init(context& digest_state) noexcept { br_sha1_init(&digest_state); } /** Absorbs bytes. - @param hashed The context. @param data The bytes. @param size Their number. + @param digest_state The context. @param input_data The bytes. @param input_size Their number. */ - static void update(context& hashed, void const* data, std::size_t size) noexcept { - br_sha1_update(&hashed, data, size); + static void update(context& digest_state, void const* input_data, + std::size_t input_size) noexcept { + br_sha1_update(&digest_state, input_data, input_size); } - /** Writes the output. @param hashed The context. @param output The 20 bytes. */ - static void out(context& hashed, std::span output) noexcept { - br_sha1_out(&hashed, output.data()); + /** Writes the output. @param digest_state The context. @param output_bytes The 20 bytes. */ + static void out(context& digest_state, std::span output_bytes) noexcept { + br_sha1_out(&digest_state, output_bytes.data()); } /** The hash HMAC runs over. @return `&br_sha1_vtable`. */ @@ -180,21 +182,22 @@ struct bearssl_digest { /** BearSSL's context. */ using context = br_sha224_context; - /** Starts a hash. @param hashed The context. */ - static void init(context& hashed) noexcept { br_sha224_init(&hashed); } + /** Starts a hash. @param digest_state The context. */ + static void init(context& digest_state) noexcept { br_sha224_init(&digest_state); } /** Absorbs bytes. - @param hashed The context. @param data The bytes. @param size Their number. + @param digest_state The context. @param input_data The bytes. @param input_size Their number. */ - static void update(context& hashed, void const* data, std::size_t size) noexcept { - br_sha224_update(&hashed, data, size); + static void update(context& digest_state, void const* input_data, + std::size_t input_size) noexcept { + br_sha224_update(&digest_state, input_data, input_size); } - /** Writes the output. @param hashed The context. @param output The 28 bytes. */ - static void out(context& hashed, std::span output) noexcept { - br_sha224_out(&hashed, output.data()); + /** Writes the output. @param digest_state The context. @param output_bytes The 28 bytes. */ + static void out(context& digest_state, std::span output_bytes) noexcept { + br_sha224_out(&digest_state, output_bytes.data()); } /** The hash HMAC runs over. @return `&br_sha224_vtable`. */ @@ -207,21 +210,22 @@ struct bearssl_digest { /** BearSSL's context. */ using context = br_sha256_context; - /** Starts a hash. @param hashed The context. */ - static void init(context& hashed) noexcept { br_sha256_init(&hashed); } + /** Starts a hash. @param digest_state The context. */ + static void init(context& digest_state) noexcept { br_sha256_init(&digest_state); } /** Absorbs bytes. - @param hashed The context. @param data The bytes. @param size Their number. + @param digest_state The context. @param input_data The bytes. @param input_size Their number. */ - static void update(context& hashed, void const* data, std::size_t size) noexcept { - br_sha256_update(&hashed, data, size); + static void update(context& digest_state, void const* input_data, + std::size_t input_size) noexcept { + br_sha256_update(&digest_state, input_data, input_size); } - /** Writes the output. @param hashed The context. @param output The 32 bytes. */ - static void out(context& hashed, std::span output) noexcept { - br_sha256_out(&hashed, output.data()); + /** Writes the output. @param digest_state The context. @param output_bytes The 32 bytes. */ + static void out(context& digest_state, std::span output_bytes) noexcept { + br_sha256_out(&digest_state, output_bytes.data()); } /** The hash HMAC runs over. @return `&br_sha256_vtable`. */ @@ -234,21 +238,22 @@ struct bearssl_digest { /** BearSSL's context. */ using context = br_sha384_context; - /** Starts a hash. @param hashed The context. */ - static void init(context& hashed) noexcept { br_sha384_init(&hashed); } + /** Starts a hash. @param digest_state The context. */ + static void init(context& digest_state) noexcept { br_sha384_init(&digest_state); } /** Absorbs bytes. - @param hashed The context. @param data The bytes. @param size Their number. + @param digest_state The context. @param input_data The bytes. @param input_size Their number. */ - static void update(context& hashed, void const* data, std::size_t size) noexcept { - br_sha384_update(&hashed, data, size); + static void update(context& digest_state, void const* input_data, + std::size_t input_size) noexcept { + br_sha384_update(&digest_state, input_data, input_size); } - /** Writes the output. @param hashed The context. @param output The 48 bytes. */ - static void out(context& hashed, std::span output) noexcept { - br_sha384_out(&hashed, output.data()); + /** Writes the output. @param digest_state The context. @param output_bytes The 48 bytes. */ + static void out(context& digest_state, std::span output_bytes) noexcept { + br_sha384_out(&digest_state, output_bytes.data()); } /** The hash HMAC runs over. @return `&br_sha384_vtable`. */ @@ -261,21 +266,22 @@ struct bearssl_digest { /** BearSSL's context. */ using context = br_sha512_context; - /** Starts a hash. @param hashed The context. */ - static void init(context& hashed) noexcept { br_sha512_init(&hashed); } + /** Starts a hash. @param digest_state The context. */ + static void init(context& digest_state) noexcept { br_sha512_init(&digest_state); } /** Absorbs bytes. - @param hashed The context. @param data The bytes. @param size Their number. + @param digest_state The context. @param input_data The bytes. @param input_size Their number. */ - static void update(context& hashed, void const* data, std::size_t size) noexcept { - br_sha512_update(&hashed, data, size); + static void update(context& digest_state, void const* input_data, + std::size_t input_size) noexcept { + br_sha512_update(&digest_state, input_data, input_size); } - /** Writes the output. @param hashed The context. @param output The 64 bytes. */ - static void out(context& hashed, std::span output) noexcept { - br_sha512_out(&hashed, output.data()); + /** Writes the output. @param digest_state The context. @param output_bytes The 64 bytes. */ + static void out(context& digest_state, std::span output_bytes) noexcept { + br_sha512_out(&digest_state, output_bytes.data()); } /** The hash HMAC runs over. @return `&br_sha512_vtable`. */ @@ -288,21 +294,22 @@ struct bearssl_digest { /** BearSSL's context. */ using context = br_md5sha1_context; - /** Starts a hash. @param hashed The context. */ - static void init(context& hashed) noexcept { br_md5sha1_init(&hashed); } + /** Starts a hash. @param digest_state The context. */ + static void init(context& digest_state) noexcept { br_md5sha1_init(&digest_state); } /** Absorbs bytes. - @param hashed The context. @param data The bytes. @param size Their number. + @param digest_state The context. @param input_data The bytes. @param input_size Their number. */ - static void update(context& hashed, void const* data, std::size_t size) noexcept { - br_md5sha1_update(&hashed, data, size); + static void update(context& digest_state, void const* input_data, + std::size_t input_size) noexcept { + br_md5sha1_update(&digest_state, input_data, input_size); } - /** Writes the output. @param hashed The context. @param output The 36 bytes. */ - static void out(context& hashed, std::span output) noexcept { - br_md5sha1_out(&hashed, output.data()); + /** Writes the output. @param digest_state The context. @param output_bytes The 36 bytes. */ + static void out(context& digest_state, std::span output_bytes) noexcept { + br_md5sha1_out(&digest_state, output_bytes.data()); } /** The hash HMAC runs over. @return `&br_md5sha1_vtable`. */ @@ -321,26 +328,29 @@ struct bearssl_shake { /** BearSSL's context. */ using context = br_shake_context; - /** Starts a hash. @param hashed The context. */ - static void init(context& hashed) noexcept { br_shake_init(&hashed, SecurityLevel); } + /** Starts a hash. @param digest_state The context. */ + static void init(context& digest_state) noexcept { + br_shake_init(&digest_state, SecurityLevel); + } /** Absorbs bytes. - @param hashed The context. @param data The bytes. @param size Their number. + @param digest_state The context. @param input_data The bytes. @param input_size Their number. */ - static void update(context& hashed, void const* data, std::size_t size) noexcept { - br_shake_inject(&hashed, data, size); + static void update(context& digest_state, void const* input_data, + std::size_t input_size) noexcept { + br_shake_inject(&digest_state, input_data, input_size); } /** Writes the output. - @param hashed The context. @param output The output, of any size from 1 byte. + @param digest_state The context. @param output_bytes The output, of any size from 1 byte. */ - static void out(context& hashed, std::span output) noexcept { - br_shake_flip(&hashed); - br_shake_produce(&hashed, output.data(), output.size()); + static void out(context& digest_state, std::span output_bytes) noexcept { + br_shake_flip(&digest_state); + br_shake_produce(&digest_state, output_bytes.data(), output_bytes.size()); } }; @@ -407,7 +417,7 @@ struct hkdf_engine { @return Never: the program does not compile. */ [[nodiscard]] static boost::system::result extract( - std::span /*salt*/, + std::span /*salt_bytes*/, std::span /*input_key_material*/) noexcept { static_assert(always_false, "webcpp::hash: hkdf_extract and hkdf_expand are not in backends::bearssl, " @@ -437,18 +447,19 @@ struct hkdf_engine { 0, which HMAC pads with zeros to the block, RFC 5869's HashLen zeros), `br_hkdf_inject`, `br_hkdf_flip`, `br_hkdf_produce` into `output_key_material`; then the context is wiped. - @param output_key_material The OKM. @param salt The salt. @param input_key_material The input - keying material. + @param output_key_material The OKM. @param salt_bytes The salt. @param input_key_material The + input keying material. @param application_info The info. @return Success, or `error::backend_failure` when BearSSL produced fewer bytes than asked. */ [[nodiscard]] static boost::system::result extract_and_expand( - std::span output_key_material, std::span salt, + std::span output_key_material, std::span salt_bytes, std::span input_key_material, std::span application_info) noexcept { touch_bearssl_canary(); br_hkdf_context hkdf_context; - br_hkdf_init(&hkdf_context, bearssl_hash_class::vtable(), nonnull(salt), salt.size()); + br_hkdf_init(&hkdf_context, bearssl_hash_class::vtable(), nonnull(salt_bytes), + salt_bytes.size()); br_hkdf_inject(&hkdf_context, nonnull(input_key_material), input_key_material.size()); br_hkdf_flip(&hkdf_context); const std::size_t produced_count = @@ -486,13 +497,13 @@ struct hkdf_pieces_engine { "br_hmac_update takes every slice's length"); /** - Feeds every byte of `pieces` to `mac_context`, in slices of at most @ref slice_max bytes. + Feeds every byte of `input_pieces` to `mac_context`, in slices of at most @ref slice_max bytes. - @param mac_context The HMAC context. @param pieces The pieces. + @param mac_context The HMAC context. @param input_pieces The pieces. */ - static void update_all(br_hmac_context& mac_context, byte_pieces pieces) noexcept { - for_each_slice(pieces, [&](std::span slice) { - br_hmac_update(&mac_context, slice.data(), slice.size()); + static void update_all(br_hmac_context& mac_context, byte_pieces input_pieces) noexcept { + for_each_slice(input_pieces, [&](std::span slice_bytes) { + br_hmac_update(&mac_context, slice_bytes.data(), slice_bytes.size()); }); } @@ -500,18 +511,18 @@ struct hkdf_pieces_engine { RFC 5869, 2.2: PRK = HMAC-Hash(salt, piece_1 | ... | piece_n). An empty salt, of length 0, is padded by HMAC with zeros to the block: RFC 5869's HashLen zeros. - @param salt The salt. @param input_key_material The input keying material's pieces. + @param salt_bytes The salt. @param input_key_material The input keying material's pieces. @return The PRK, or `error::backend_failure` when BearSSL wrote another size than the digest's. */ [[nodiscard]] static boost::system::result extract( - std::span salt, byte_pieces input_key_material) noexcept { + std::span salt_bytes, byte_pieces input_key_material) noexcept { touch_bearssl_canary(); // The PRK is built in the result returned and BearSSL writes into it: a single return path // of the one named object, so that no copy of the PRK is left behind unwiped. boost::system::result pseudorandom_key{boost::system::in_place_value}; br_hmac_key_context key_context; - br_hmac_key_init(&key_context, bearssl_hash_class::vtable(), nonnull(salt), - salt.size()); + br_hmac_key_init(&key_context, bearssl_hash_class::vtable(), nonnull(salt_bytes), + salt_bytes.size()); br_hmac_context mac_context; br_hmac_init(&mac_context, &key_context, 0); update_all(mac_context, input_key_material); @@ -543,10 +554,10 @@ struct hkdf_pieces_engine { br_hmac_key_init(&key_context, bearssl_hash_class::vtable(), pseudorandom_key.data(), pseudorandom_key.size()); digest_type t_block{}; - bool computed = true; + bool call_succeeded = true; std::size_t written_count = 0; - for (unsigned block_counter = 1; computed && written_count < output_key_material.size(); - ++block_counter) { + for (unsigned block_counter = 1; + call_succeeded && written_count < output_key_material.size(); ++block_counter) { br_hmac_context mac_context; br_hmac_init(&mac_context, &key_context, 0); if (block_counter > 1) { @@ -555,9 +566,9 @@ struct hkdf_pieces_engine { update_all(mac_context, application_info); auto const octet_value = static_cast(block_counter); br_hmac_update(&mac_context, &octet_value, 1); - computed = br_hmac_out(&mac_context, t_block.data()) == t_block.size(); + call_succeeded = br_hmac_out(&mac_context, t_block.data()) == t_block.size(); secure::erase_secret(std::span(&mac_context, 1)); - if (computed) { + if (call_succeeded) { std::size_t const copied_count = std::min(t_block.size(), output_key_material.size() - written_count); std::copy_n(t_block.data(), copied_count, @@ -567,7 +578,7 @@ struct hkdf_pieces_engine { } secure::erase_secret(std::span(&t_block, 1)); secure::erase_secret(std::span(&key_context, 1)); - if (!computed) { + if (!call_succeeded) { return error::backend_failure; } return {}; @@ -576,16 +587,16 @@ struct hkdf_pieces_engine { /** RFC 5869, 2: HKDF-Extract, then HKDF-Expand, over pieces; the PRK is wiped between them. - @param output_key_material The OKM. @param salt The salt. + @param output_key_material The OKM. @param salt_bytes The salt. @param input_key_material The input keying material's pieces. @param application_info The info's pieces. @return Success, or `error::backend_failure`. */ [[nodiscard]] static boost::system::result extract_and_expand( - std::span output_key_material, std::span salt, + std::span output_key_material, std::span salt_bytes, byte_pieces input_key_material, byte_pieces application_info) noexcept { return hkdf_pieces_extract_and_expand>( - output_key_material, salt, input_key_material, application_info); + output_key_material, salt_bytes, input_key_material, application_info); } }; @@ -629,45 +640,49 @@ struct bearssl_digest_engine : full_engine { /** BearSSL's context, which is all of the state. */ using state = bearssl_digest::context; - /** Starts a hash. @param hashed The state. @return Success. */ + /** Starts a hash. @param digest_state The state. @return Success. */ [[nodiscard]] static boost::system::result init( - state& hashed, digest_options const& /*options*/) noexcept { + state& digest_state, digest_options const& /*algorithm_options*/) noexcept { touch_bearssl_canary(); - bearssl_digest::init(hashed); + bearssl_digest::init(digest_state); return {}; } - /** Absorbs `input`. @param hashed The state. @param input The bytes. @return Success. */ + /** Absorbs `input_bytes`. @param digest_state The state. @param input_bytes The bytes. @return + * Success. */ [[nodiscard]] static boost::system::result update( - state& hashed, std::span input) noexcept { - bearssl_digest::update(hashed, nonnull(input), input.size()); + state& digest_state, std::span input_bytes) noexcept { + bearssl_digest::update(digest_state, nonnull(input_bytes), input_bytes.size()); return {}; } - /** Writes the digest. @param hashed The state. @param output The digest. @return Success. */ + /** Writes the digest. @param digest_state The state. @param output_bytes The digest. @return + * Success. */ [[nodiscard]] static boost::system::result finish( - state& hashed, std::span output) noexcept { - bearssl_digest::out(hashed, output); + state& digest_state, std::span output_bytes) noexcept { + bearssl_digest::out(digest_state, output_bytes); return {}; } - /** Wipes the state. @param hashed The state. */ - static void destroy(state& hashed) noexcept { secure::erase_secret(std::span(&hashed, 1)); } + /** Wipes the state. @param digest_state The state. */ + static void destroy(state& digest_state) noexcept { + secure::erase_secret(std::span(&digest_state, 1)); + } /** - The digest of `input` at once, BearSSL's context wiped. + The digest of `input_bytes` at once, BearSSL's context wiped. - @param output The digest. @param input The bytes. @param options None. + @param output_bytes The digest. @param input_bytes The bytes. @param algorithm_options None. @return Success. */ [[nodiscard]] static boost::system::result one_shot( - std::span output, std::span input, - digest_options const& options) noexcept { - state hashed; - static_cast(init(hashed, options)); - static_cast(update(hashed, input)); - static_cast(finish(hashed, output)); - destroy(hashed); + std::span output_bytes, std::span input_bytes, + digest_options const& algorithm_options) noexcept { + state digest_state; + static_cast(init(digest_state, algorithm_options)); + static_cast(update(digest_state, input_bytes)); + static_cast(finish(digest_state, output_bytes)); + destroy(digest_state); return {}; } }; @@ -728,27 +743,30 @@ struct digest_engine template struct bearssl_hmac_engine : full_engine { /** - The tag of `input` under `key`. + The tag of `input_bytes` under `key_bytes`. - @param output The tag, 10 bytes up to the digest's size. @param key The key, of any size. - @param input The message. + @param output_bytes The tag, 10 bytes up to the digest's size. @param key_bytes The key, of any + size. + @param input_bytes The message. @return Success, or `error::backend_failure` when BearSSL wrote another size than asked. */ [[nodiscard]] static boost::system::result compute( - std::span output, std::span key, - std::span input, - mac_options> const& /*options*/) noexcept { + std::span output_bytes, std::span key_bytes, + std::span input_bytes, + mac_options> const& /*algorithm_options*/) noexcept { touch_bearssl_canary(); br_hmac_key_context key_context; - br_hmac_key_init(&key_context, bearssl_digest::vtable(), nonnull(key), key.size()); + br_hmac_key_init(&key_context, bearssl_digest::vtable(), nonnull(key_bytes), + key_bytes.size()); br_hmac_context mac_context; - br_hmac_init(&mac_context, &key_context, output.size()); - br_hmac_update(&mac_context, nonnull(input), input.size()); - std::size_t const written_count = br_hmac_out(&mac_context, output.data()); + br_hmac_init(&mac_context, &key_context, output_bytes.size()); + br_hmac_update(&mac_context, nonnull(input_bytes), input_bytes.size()); + std::size_t const written_count = br_hmac_out(&mac_context, output_bytes.data()); secure::erase_secret(std::span(&mac_context, 1)); secure::erase_secret(std::span(&key_context, 1)); - return written_count == output.size() ? boost::system::result() - : boost::system::result(error::backend_failure); + return written_count == output_bytes.size() + ? boost::system::result() + : boost::system::result(error::backend_failure); } }; diff --git a/include/webcpp/hash/backends/blake3.hpp b/include/webcpp/hash/backends/blake3.hpp index 0a5d936..3c89649 100644 --- a/include/webcpp/hash/backends/blake3.hpp +++ b/include/webcpp/hash/backends/blake3.hpp @@ -50,48 +50,52 @@ struct digest_engine : full_engine { /** webcpp's BLAKE3 over the C implementation, which is all of the state. */ using state = webcpp::hash::blake3; - /** Starts a hash. @param hashed The state. @return Success. */ + /** Starts a hash. @param digest_state The state. @return Success. */ [[nodiscard]] static boost::system::result init( - state& hashed, digest_options const& /*options*/) noexcept { - hashed = webcpp::hash::blake3(); + state& digest_state, + digest_options const& /*algorithm_options*/) noexcept { + digest_state = webcpp::hash::blake3(); return {}; } - /** Absorbs `input`. @param hashed The state. @param input The bytes. @return Success. */ + /** Absorbs `input_bytes`. @param digest_state The state. @param input_bytes The bytes. @return + * Success. */ [[nodiscard]] static boost::system::result update( - state& hashed, std::span input) noexcept { - hashed.update(input.data(), input.size()); + state& digest_state, std::span input_bytes) noexcept { + digest_state.update(input_bytes.data(), input_bytes.size()); return {}; } /** - Writes the first `output.size()` bytes of the extendable output. + Writes the first `output_bytes.size()` bytes of the extendable output. - @param hashed The state. @param output The output, of any size. @return Success. + @param digest_state The state. @param output_bytes The output, of any size. @return Success. */ [[nodiscard]] static boost::system::result finish( - state& hashed, std::span output) noexcept { - hashed.squeeze(output, 0); + state& digest_state, std::span output_bytes) noexcept { + digest_state.squeeze(output_bytes, 0); return {}; } - /** Wipes the state. @param hashed The state. */ - static void destroy(state& hashed) noexcept { secure::erase_secret(std::span(&hashed, 1)); } + /** Wipes the state. @param digest_state The state. */ + static void destroy(state& digest_state) noexcept { + secure::erase_secret(std::span(&digest_state, 1)); + } /** - The output of `input` at once, the state wiped. + The output of `input_bytes` at once, the state wiped. - @param output The output. @param input The bytes. @param options None. + @param output_bytes The output. @param input_bytes The bytes. @param algorithm_options None. @return Success. */ [[nodiscard]] static boost::system::result one_shot( - std::span output, std::span input, - digest_options const& options) noexcept { - state hashed; - static_cast(init(hashed, options)); - static_cast(update(hashed, input)); - static_cast(finish(hashed, output)); - destroy(hashed); + std::span output_bytes, std::span input_bytes, + digest_options const& algorithm_options) noexcept { + state digest_state; + static_cast(init(digest_state, algorithm_options)); + static_cast(update(digest_state, input_bytes)); + static_cast(finish(digest_state, output_bytes)); + destroy(digest_state); return {}; } }; diff --git a/include/webcpp/hash/backends/botan.hpp b/include/webcpp/hash/backends/botan.hpp index e9653b5..e7f5481 100644 --- a/include/webcpp/hash/backends/botan.hpp +++ b/include/webcpp/hash/backends/botan.hpp @@ -181,18 +181,18 @@ inline void touch_botan_canary() noexcept { } /** - Runs `work`, every call of Botan an engine function makes, inside one `try`, after reading the - canary: the boundary no exception crosses. + Runs `boundary_call`, every call of Botan an engine function makes, inside one `try`, after reading + the canary: the boundary no exception crosses. - @param work A callable that calls Botan. + @param boundary_call A callable that calls Botan. @return Success; `errc::not_enough_memory` when Botan or the standard library could not allocate (`std::bad_alloc`); `error::backend_failure` for any other exception. */ template -[[nodiscard]] boost::system::result botan_boundary(Work&& work) noexcept { +[[nodiscard]] boost::system::result botan_boundary(Work&& boundary_call) noexcept { touch_botan_canary(); try { - std::forward(work)(); + std::forward(boundary_call)(); } catch (std::bad_alloc const&) { return boost::system::errc::make_error_code(boost::system::errc::not_enough_memory); } catch (...) { @@ -203,34 +203,34 @@ template /** Makes the Botan object of `T` (`HashFunction`, `XOF` or `MessageAuthenticationCode`) Botan names - `name`, or, in a test that defines `WEBCPP_HASH_DETAIL_TEST_BOTAN_NAME` (a string literal), that - one, to provoke a failure, as backends::openssl's seam does. + `algorithm_name`, or, in a test that defines `WEBCPP_HASH_DETAIL_TEST_BOTAN_NAME` (a string + literal), that one, to provoke a failure, as backends::openssl's seam does. - @param name Botan's name of the algorithm. + @param algorithm_name Botan's name of the algorithm. @return The object; Botan throws `Lookup_Error` for a name it does not know. */ template -std::unique_ptr botan_create(std::string_view name) { +std::unique_ptr botan_create(std::string_view algorithm_name) { #ifdef WEBCPP_HASH_DETAIL_TEST_BOTAN_NAME - static_cast(name); + static_cast(algorithm_name); return T::create_or_throw(WEBCPP_HASH_DETAIL_TEST_BOTAN_NAME); #else - return T::create_or_throw(name); + return T::create_or_throw(algorithm_name); #endif } /** - `prefix`, the decimal `bits` and ")": Botan's name of an algorithm of a chosen size, as + `name_prefix`, the decimal `output_bits` and ")": Botan's name of an algorithm of a chosen size, as "BLAKE2b(256)" or "KMAC-128(128)". - @param prefix The name up to its argument, "(" included. @param bits The size in bits. + @param name_prefix The name up to its argument, "(" included. @param output_bits The size in bits. @return The name. */ -inline std::string botan_sized_name(std::string_view prefix, std::size_t bits) { - std::string name(prefix); - name += std::to_string(bits); - name += ')'; - return name; +inline std::string botan_sized_name(std::string_view name_prefix, std::size_t output_bits) { + std::string algorithm_name(name_prefix); + algorithm_name += std::to_string(output_bits); + algorithm_name += ')'; + return algorithm_name; } /** @@ -276,13 +276,13 @@ class botan_owned { ~botan_owned() { reset(); } /** - Owns `object` from here on, clearing and freeing the one it held. + Owns `botan_object` from here on, clearing and freeing the one it held. - @param object An object of Botan's. + @param botan_object An object of Botan's. */ - void adopt(std::unique_ptr object) noexcept { + void adopt(std::unique_ptr botan_object) noexcept { reset(); - object_ = std::move(object); + object_ = std::move(botan_object); } /** @@ -517,63 +517,66 @@ struct botan_hash_engine : full_engine { /** Makes the hash. - @param hashed The state. @return Success, or the boundary's failure. + @param digest_state The state. @return Success, or the boundary's failure. */ [[nodiscard]] static boost::system::result init( - state& hashed, digest_options const& /*options*/) noexcept { + state& digest_state, digest_options const& /*algorithm_options*/) noexcept { return botan_boundary([&] { - hashed.adopt(botan_create(botan_hash_name::value)); + digest_state.adopt(botan_create(botan_hash_name::value)); }); } /** - Absorbs `input`. + Absorbs `input_bytes`. - @param hashed The state. @param input The bytes. @return Success, or the boundary's failure. + @param digest_state The state. @param input_bytes The bytes. @return Success, or the boundary's + failure. */ [[nodiscard]] static boost::system::result update( - state& hashed, std::span input) noexcept { - return botan_boundary([&] { hashed.get().update(input); }); + state& digest_state, std::span input_bytes) noexcept { + return botan_boundary([&] { digest_state.get().update(input_bytes); }); } /** Writes the digest, then clears and releases the object. - @param hashed The state. @param output The digest, of its size. + @param digest_state The state. @param output_bytes The digest, of its size. @return Success, or the boundary's failure. */ [[nodiscard]] static boost::system::result finish( - state& hashed, std::span output) noexcept { - auto done = botan_boundary([&] { hashed.get().final(output); }); - hashed.reset(); - return done; + state& digest_state, std::span output_bytes) noexcept { + auto finish_result = botan_boundary([&] { digest_state.get().final(output_bytes); }); + digest_state.reset(); + return finish_result; } - /** Clears and releases the object; a second call does nothing. @param hashed The state. */ - static void destroy(state& hashed) noexcept { + /** Clears and releases the object; a second call does nothing. @param digest_state The state. + */ + static void destroy(state& digest_state) noexcept { touch_botan_canary(); - hashed.reset(); + digest_state.reset(); } /** - The digest of `input` at once, on an object released before the return. + The digest of `input_bytes` at once, on an object released before the return. - @param output The digest. @param input The bytes. @param options The digest's parameters. + @param output_bytes The digest. @param input_bytes The bytes. @param algorithm_options The + digest's parameters. @return Success, or the boundary's failure. */ [[nodiscard]] static boost::system::result one_shot( - std::span output, std::span input, - digest_options const& options) noexcept { - state hashed; - auto done = init(hashed, options); - if (done) { - done = update(hashed, input); + std::span output_bytes, std::span input_bytes, + digest_options const& algorithm_options) noexcept { + state digest_state; + auto init_result = init(digest_state, algorithm_options); + if (init_result) { + init_result = update(digest_state, input_bytes); } - if (done) { - done = finish(hashed, output); + if (init_result) { + init_result = finish(digest_state, output_bytes); } - destroy(hashed); - return done; + destroy(digest_state); + return init_result; } }; @@ -589,60 +592,64 @@ struct botan_xof_engine : full_engine { /** The object, owned. */ using state = botan_owned; - /** Makes the XOF. @param hashed The state. @return Success, or the boundary's failure. */ + /** Makes the XOF. @param digest_state The state. @return Success, or the boundary's failure. */ [[nodiscard]] static boost::system::result init( - state& hashed, digest_options const& /*options*/) noexcept { + state& digest_state, digest_options const& /*algorithm_options*/) noexcept { return botan_boundary( - [&] { hashed.adopt(botan_create(botan_hash_name::value)); }); + [&] { digest_state.adopt(botan_create(botan_hash_name::value)); }); } /** - Absorbs `input`. + Absorbs `input_bytes`. - @param hashed The state. @param input The bytes. @return Success, or the boundary's failure. + @param digest_state The state. @param input_bytes The bytes. @return Success, or the boundary's + failure. */ [[nodiscard]] static boost::system::result update( - state& hashed, std::span input) noexcept { - return botan_boundary([&] { hashed.get().update(input); }); + state& digest_state, std::span input_bytes) noexcept { + return botan_boundary([&] { digest_state.get().update(input_bytes); }); } /** - Squeezes `output.size()` bytes, then clears and releases the object. + Squeezes `output_bytes.size()` bytes, then clears and releases the object. - @param hashed The state. @param output The output. @return Success, or the boundary's failure. + @param digest_state The state. @param output_bytes The output. @return Success, or the + boundary's failure. */ [[nodiscard]] static boost::system::result finish( - state& hashed, std::span output) noexcept { - auto done = botan_boundary([&] { hashed.get().output(output); }); - hashed.reset(); - return done; + state& digest_state, std::span output_bytes) noexcept { + auto finish_result = botan_boundary([&] { digest_state.get().output(output_bytes); }); + digest_state.reset(); + return finish_result; } - /** Clears and releases the object; a second call does nothing. @param hashed The state. */ - static void destroy(state& hashed) noexcept { + /** Clears and releases the object; a second call does nothing. @param digest_state The state. + */ + static void destroy(state& digest_state) noexcept { touch_botan_canary(); - hashed.reset(); + digest_state.reset(); } /** - The output of `input` at once, on an object released before the return. + The output of `input_bytes` at once, on an object released before the return. - @param output The output. @param input The bytes. @param options The digest's parameters. + @param output_bytes The output. @param input_bytes The bytes. @param algorithm_options The + digest's parameters. @return Success, or the boundary's failure. */ [[nodiscard]] static boost::system::result one_shot( - std::span output, std::span input, - digest_options const& options) noexcept { - state hashed; - auto done = init(hashed, options); - if (done) { - done = update(hashed, input); + std::span output_bytes, std::span input_bytes, + digest_options const& algorithm_options) noexcept { + state digest_state; + auto init_result = init(digest_state, algorithm_options); + if (init_result) { + init_result = update(digest_state, input_bytes); } - if (done) { - done = finish(hashed, output); + if (init_result) { + init_result = finish(digest_state, output_bytes); } - destroy(hashed); - return done; + destroy(digest_state); + return init_result; } }; @@ -724,45 +731,48 @@ struct digest_engine : full_engine { Whether Botan's BLAKE2b computes these options: no salt, no personalisation. A template, so that it reads `digest_options`, which digest.hpp defines after this header. - @param options The options. @return Whether they have no salt and no personalisation. + @param algorithm_options The options. @return Whether they have no salt and no personalisation. */ template - static constexpr bool accepts(Options const& options) noexcept { - return options.salt.empty() && options.personalisation.empty(); + static constexpr bool accepts(Options const& algorithm_options) noexcept { + return algorithm_options.salt.empty() && algorithm_options.personalisation.empty(); } /** Makes the hash, or the MAC keyed with the options' key. - @param hashed The state. @param options The key and the output's size. + @param digest_state The state. @param algorithm_options The key and the output's size. @return Success, or the boundary's failure. */ template - [[nodiscard]] static boost::system::result init(state& hashed, - Options const& options) noexcept { + [[nodiscard]] static boost::system::result init( + state& digest_state, Options const& algorithm_options) noexcept { return botan_boundary([&] { - std::string const name = botan_sized_name("BLAKE2b(", options.output_size * 8); - if (options.key.empty()) { - hashed.unkeyed.adopt(botan_create(name)); + std::string const algorithm_name = + botan_sized_name("BLAKE2b(", algorithm_options.output_size * 8); + if (algorithm_options.key.empty()) { + digest_state.unkeyed.adopt(botan_create(algorithm_name)); } else { - hashed.keyed.adopt(botan_create(name)); - hashed.keyed.get().set_key(options.key); + digest_state.keyed.adopt( + botan_create(algorithm_name)); + digest_state.keyed.get().set_key(algorithm_options.key); } }); } /** - Absorbs `input`. + Absorbs `input_bytes`. - @param hashed The state. @param input The bytes. @return Success, or the boundary's failure. + @param digest_state The state. @param input_bytes The bytes. @return Success, or the boundary's + failure. */ [[nodiscard]] static boost::system::result update( - state& hashed, std::span input) noexcept { + state& digest_state, std::span input_bytes) noexcept { return botan_boundary([&] { - if (hashed.keyed.has_object()) { - hashed.keyed.get().update(input); + if (digest_state.keyed.has_object()) { + digest_state.keyed.get().update(input_bytes); } else { - hashed.unkeyed.get().update(input); + digest_state.unkeyed.get().update(input_bytes); } }); } @@ -770,70 +780,75 @@ struct digest_engine : full_engine { /** Writes the digest, of the options' size, then clears and releases the object. - @param hashed The state. @param output The digest. @return Success, or the boundary's failure. + @param digest_state The state. @param output_bytes The digest. @return Success, or the + boundary's failure. */ [[nodiscard]] static boost::system::result finish( - state& hashed, std::span output) noexcept { - auto done = botan_boundary([&] { - if (hashed.keyed.has_object()) { - hashed.keyed.get().final(output); + state& digest_state, std::span output_bytes) noexcept { + auto finish_result = botan_boundary([&] { + if (digest_state.keyed.has_object()) { + digest_state.keyed.get().final(output_bytes); } else { - hashed.unkeyed.get().final(output); + digest_state.unkeyed.get().final(output_bytes); } }); - destroy(hashed); - return done; + destroy(digest_state); + return finish_result; } - /** Clears and releases the object; a second call does nothing. @param hashed The state. */ - static void destroy(state& hashed) noexcept { + /** Clears and releases the object; a second call does nothing. @param digest_state The state. + */ + static void destroy(state& digest_state) noexcept { touch_botan_canary(); - hashed.unkeyed.reset(); - hashed.keyed.reset(); + digest_state.unkeyed.reset(); + digest_state.keyed.reset(); } /** - The digest of `input` at once, on an object released before the return. + The digest of `input_bytes` at once, on an object released before the return. - @param output The digest. @param input The bytes. @param options The digest's parameters. + @param output_bytes The digest. @param input_bytes The bytes. @param algorithm_options The + digest's parameters. @return Success, or the boundary's failure. */ template - [[nodiscard]] static boost::system::result one_shot(std::span output, - std::span input, - Options const& options) noexcept { - state hashed; - auto done = init(hashed, options); - if (done) { - done = update(hashed, input); + [[nodiscard]] static boost::system::result one_shot( + std::span output_bytes, std::span input_bytes, + Options const& algorithm_options) noexcept { + state digest_state; + auto init_result = init(digest_state, algorithm_options); + if (init_result) { + init_result = update(digest_state, input_bytes); } - if (done) { - done = finish(hashed, output); + if (init_result) { + init_result = finish(digest_state, output_bytes); } - destroy(hashed); - return done; + destroy(digest_state); + return init_result; } }; /** - Computes a MAC on Botan's `MessageAuthenticationCode` named `name`: makes it, keys it, starts it - with `nonce` (KMAC's customisation; empty for the others), absorbs `input`, and writes its tag, - of its whole size, into `tag`; the object is cleared and released before the return. + Computes a MAC on Botan's `MessageAuthenticationCode` named `algorithm_name`: makes it, keys it, + starts it with `nonce_bytes` (KMAC's customisation; empty for the others), absorbs `input_bytes`, + and writes its tag, of its whole size, into `tag_bytes`; the object is cleared and released before + the return. - @param name Botan's name of the MAC. @param tag The tag, of the MAC's size. - @param key The key. @param input The message. @param nonce What `start` takes. + @param algorithm_name Botan's name of the MAC. @param tag_bytes The tag, of the MAC's size. + @param key_bytes The key. @param input_bytes The message. @param nonce_bytes What `start` takes. @return Success, or the boundary's failure. */ [[nodiscard]] inline boost::system::result botan_mac( - std::string_view name, std::span tag, std::span key, - std::span input, std::span nonce) noexcept { + std::string_view algorithm_name, std::span tag_bytes, + std::span key_bytes, std::span input_bytes, + std::span nonce_bytes) noexcept { botan_owned mac_object; return botan_boundary([&] { - mac_object.adopt(botan_create(name)); - mac_object.get().set_key(key); - mac_object.get().start(nonce); - mac_object.get().update(input); - mac_object.get().final(tag); + mac_object.adopt(botan_create(algorithm_name)); + mac_object.get().set_key(key_bytes); + mac_object.get().start(nonce_bytes); + mac_object.get().update(input_bytes); + mac_object.get().final(tag_bytes); }); } @@ -852,44 +867,43 @@ inline constexpr std::size_t botan_hmac_max_key = 8192; template struct botan_hmac_engine : full_engine { /** - The tag of `input` under `key`, the HMAC cut to `output.size()` bytes. + The tag of `input_bytes` under `key_bytes`, the HMAC cut to `output_bytes.size()` bytes. - @param output The tag. @param key The key. @param input The message. + @param output_bytes The tag. @param key_bytes The key. @param input_bytes The message. @return Success, or the boundary's failure. */ template - [[nodiscard]] static boost::system::result compute(std::span output, - std::span key, - std::span input, - Options const& /*options*/) noexcept { + [[nodiscard]] static boost::system::result compute( + std::span output_bytes, std::span key_bytes, + std::span input_bytes, Options const& /*algorithm_options*/) noexcept { constexpr std::uint64_t digest_size = mac_traits>::max_output; - std::array whole{}; - static_assert(digest_size <= whole.size()); - auto const tag = std::span(whole).first(digest_size); + std::array whole_tag{}; + static_assert(digest_size <= whole_tag.size()); + auto const tag_bytes = std::span(whole_tag).first(digest_size); std::array hashed_key{}; - auto used_key = key; - auto computed = boost::system::result{}; - if (key.size() > botan_hmac_max_key) { - computed = digest_engine::one_shot( - std::span(hashed_key).first(digest_size), key, digest_options{}); + auto used_key = key_bytes; + auto compute_result = boost::system::result{}; + if (key_bytes.size() > botan_hmac_max_key) { + compute_result = digest_engine::one_shot( + std::span(hashed_key).first(digest_size), key_bytes, digest_options{}); used_key = std::span(hashed_key).first(digest_size); } - if (computed) { - std::string name; - computed = botan_boundary([&] { - name = "HMAC("; - name.append(botan_hash_name::value) += ')'; + if (compute_result) { + std::string algorithm_name; + compute_result = botan_boundary([&] { + algorithm_name = "HMAC("; + algorithm_name.append(botan_hash_name::value) += ')'; }); - if (computed) { - computed = botan_mac(name, tag, used_key, input, {}); + if (compute_result) { + compute_result = botan_mac(algorithm_name, tag_bytes, used_key, input_bytes, {}); } } - if (computed) { - std::copy_n(tag.begin(), output.size(), output.begin()); + if (compute_result) { + std::copy_n(tag_bytes.begin(), output_bytes.size(), output_bytes.begin()); } - secure::erase_secret(whole); + secure::erase_secret(whole_tag); secure::erase_secret(hashed_key); - return computed; + return compute_result; } }; @@ -910,35 +924,36 @@ struct botan_kmac_engine : full_engine { Whether Botan's KMAC takes these options and key size. A template, so that it reads `mac_options`, which mac.hpp defines after this header. - @param options The customisation and the form. @param key_size The key's size. + @param algorithm_options The customisation and the form. @param key_size The key's size. @return Whether Botan takes them. */ template - static constexpr bool accepts(Options const& options, std::size_t key_size, + static constexpr bool accepts(Options const& algorithm_options, std::size_t key_size, std::size_t /*output_size*/) noexcept { - return !options.xof && key_size <= max_key; + return !algorithm_options.xof && key_size <= max_key; } /** - The tag of `input` under `key`, of `output.size()` bytes, customised. + The tag of `input_bytes` under `key_bytes`, of `output_bytes.size()` bytes, customised. - @param output The tag. @param key The key. @param input The message. - @param options The customisation. + @param output_bytes The tag. @param key_bytes The key. @param input_bytes The message. + @param algorithm_options The customisation. @return Success, or the boundary's failure. */ template - [[nodiscard]] static boost::system::result compute(std::span output, - std::span key, - std::span input, - Options const& options) noexcept { - constexpr std::string_view prefix = + [[nodiscard]] static boost::system::result compute( + std::span output_bytes, std::span key_bytes, + std::span input_bytes, Options const& algorithm_options) noexcept { + constexpr std::string_view name_prefix = std::is_same_v ? "KMAC-128(" : "KMAC-256("; - std::string name; - auto computed = botan_boundary([&] { name = botan_sized_name(prefix, output.size() * 8); }); - if (computed) { - computed = botan_mac(name, output, key, input, options.customisation); + std::string algorithm_name; + auto compute_result = botan_boundary( + [&] { algorithm_name = botan_sized_name(name_prefix, output_bytes.size() * 8); }); + if (compute_result) { + compute_result = botan_mac(algorithm_name, output_bytes, key_bytes, input_bytes, + algorithm_options.customisation); } - return computed; + return compute_result; } }; @@ -954,17 +969,16 @@ struct mac_engine : botan_kmac_engine struct mac_engine : full_engine { /** - The tag of `input` under `key`. + The tag of `input_bytes` under `key_bytes`. - @param output The tag. @param key The key. @param input The message. + @param output_bytes The tag. @param key_bytes The key. @param input_bytes The message. @return Success, or the boundary's failure. */ template - [[nodiscard]] static boost::system::result compute(std::span output, - std::span key, - std::span input, - Options const& /*options*/) noexcept { - return botan_mac("SipHash(2,4)", output, key, input, {}); + [[nodiscard]] static boost::system::result compute( + std::span output_bytes, std::span key_bytes, + std::span input_bytes, Options const& /*algorithm_options*/) noexcept { + return botan_mac("SipHash(2,4)", output_bytes, key_bytes, input_bytes, {}); } }; @@ -975,23 +989,22 @@ struct mac_engine : full_engine { template <> struct mac_engine : full_engine { /** - The tag of `input` under `key`, of `output.size()` bytes. + The tag of `input_bytes` under `key_bytes`, of `output_bytes.size()` bytes. - @param output The tag. @param key The key. @param input The message. + @param output_bytes The tag. @param key_bytes The key. @param input_bytes The message. @return Success, or the boundary's failure. */ template - [[nodiscard]] static boost::system::result compute(std::span output, - std::span key, - std::span input, - Options const& /*options*/) noexcept { - std::string name; - auto computed = - botan_boundary([&] { name = botan_sized_name("BLAKE2b(", output.size() * 8); }); - if (computed) { - computed = botan_mac(name, output, key, input, {}); + [[nodiscard]] static boost::system::result compute( + std::span output_bytes, std::span key_bytes, + std::span input_bytes, Options const& /*algorithm_options*/) noexcept { + std::string algorithm_name; + auto compute_result = botan_boundary( + [&] { algorithm_name = botan_sized_name("BLAKE2b(", output_bytes.size() * 8); }); + if (compute_result) { + compute_result = botan_mac(algorithm_name, output_bytes, key_bytes, input_bytes, {}); } - return computed; + return compute_result; } }; @@ -1060,118 +1073,126 @@ inline constexpr bool botan_hmac_v = hmac_sha3_512, hmac_ripemd_160, hmac_blake2b_512, hmac_blake2s_256>; /** - The bytes of `bytes` as the characters Botan's password interfaces take (`std::string_view`, + The bytes of `source_bytes` as the characters Botan's password interfaces take (`std::string_view`, `const char*` with a length): the same bytes, any of them, a zero included. - @param bytes The password. @return A view of its bytes. + @param source_bytes The password. @return A view of its bytes. */ -inline std::string_view botan_chars(std::span bytes) noexcept { +inline std::string_view botan_chars(std::span source_bytes) noexcept { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): char may alias any byte - return {reinterpret_cast(nonnull(bytes)), bytes.size()}; + return {reinterpret_cast(nonnull(source_bytes)), source_bytes.size()}; } /** - The key Botan's HMAC over `Digest` is given for `key`: `key` itself, or, when it is longer than - the 8,192 bytes `HMAC::key_spec` takes, its digest under `Digest`, written into `hashed`; as RFC - 2104 hashes every key longer than the hash's block, the HMAC is the same. + The key Botan's HMAC over `Digest` is given for `key_bytes`: `key_bytes` itself, or, when it is + longer than the 8,192 bytes `HMAC::key_spec` takes, its digest under `Digest`, written into + `digest_buffer`; as RFC 2104 hashes every key longer than the hash's block, the HMAC is the same. @tparam Digest A tag of `digests` of a fixed size that Botan has. - @param key The key. @param hashed Room for the digest, which the caller wipes. + @param key_bytes The key. @param digest_buffer Room for the digest, which the caller wipes. @return The key to give Botan, or the digest's failure. */ template [[nodiscard]] boost::system::result> botan_hmac_key( - std::span key, std::array& hashed) noexcept { - if (key.size() <= botan_hmac_max_key) { - return key; + std::span key_bytes, std::array& digest_buffer) noexcept { + if (key_bytes.size() <= botan_hmac_max_key) { + return key_bytes; } constexpr std::uint64_t digest_size = mac_traits>::max_output; static_assert(digest_size <= std::tuple_size_v>); - auto const digest = std::span(hashed).first(digest_size); - auto const done = - digest_engine::one_shot(digest, key, digest_options{}); - if (!done) { - return done.error(); + auto const digest_bytes = std::span(digest_buffer).first(digest_size); + auto const digest_result = digest_engine::one_shot( + digest_bytes, key_bytes, digest_options{}); + if (!digest_result) { + return digest_result.error(); } - return std::span(digest); + return std::span(digest_bytes); } /** - Runs `derive` with the key Botan's HMAC over `Digest` is given for `key` (@ref botan_hmac_key), - the digest of a long key wiped after. + Runs `derive_call` with the key Botan's HMAC over `Digest` is given for `key_bytes` (@ref + botan_hmac_key), the digest of a long key wiped after. @tparam Digest A tag of `digests` of a fixed size that Botan has. - @param key The key. @param derive A callable taking the key Botan is given, `noexcept`. - @return `derive`'s result, or the digest's failure. + @param key_bytes The key. @param derive_call A callable taking the key Botan is given, `noexcept`. + @return `derive_call`'s result, or the digest's failure. */ template -[[nodiscard]] boost::system::result botan_keyed(std::span key, - Derive const& derive) noexcept { - std::array hashed{}; - auto const used = botan_hmac_key(key, hashed); - boost::system::result derived{}; - if (used) { - derived = derive(used.unsafe_value()); +[[nodiscard]] boost::system::result botan_keyed(std::span key_bytes, + Derive const& derive_call) noexcept { + std::array digest_buffer{}; + auto const key_result = botan_hmac_key(key_bytes, digest_buffer); + boost::system::result derive_result{}; + if (key_result) { + derive_result = derive_call(key_result.unsafe_value()); } else { - derived = used.error(); + derive_result = key_result.error(); } - secure::erase_secret(hashed); - return derived; + secure::erase_secret(digest_buffer); + return derive_result; } /** - Derives `output` by Botan's `KDF` whose name is the concatenation of `name`: makes it, calls its - `derive_key(output, secret, salt, label)` and releases it before the return. Botan's HMAC keeps - its key in a `secure_vector`, which Botan zeroes when it frees it. + Derives `output_bytes` by Botan's `KDF` whose name is the concatenation of `name_parts`: makes it, + calls its `derive_key(output_bytes, secret_bytes, salt_bytes, label_bytes)` and releases it before + the return. Botan's HMAC keeps its key in a `secure_vector`, which Botan zeroes when it frees it. - @param name Botan's name of the KDF, in parts. @param output What is derived, its whole size. - @param secret The KDF's secret. @param salt Its salt. @param label Its label. + @param name_parts Botan's name of the KDF, in parts. @param output_bytes What is derived, its whole + size. + @param secret_bytes The KDF's secret. @param salt_bytes Its salt. @param label_bytes Its label. @return Success, or the boundary's failure. */ [[nodiscard]] inline boost::system::result botan_kdf( - std::initializer_list name, std::span output, - std::span secret, std::span salt, - std::span label) noexcept { + std::initializer_list name_parts, std::span output_bytes, + std::span secret_bytes, std::span salt_bytes, + std::span label_bytes) noexcept { return botan_boundary([&] { - std::string joined; - for (std::string_view const part : name) { - joined.append(part); + std::string joined_name; + for (std::string_view const name_part : name_parts) { + joined_name.append(name_part); } - botan_create(joined)->derive_key(output, secret, salt, label); + botan_create(joined_name) + ->derive_key(output_bytes, secret_bytes, salt_bytes, label_bytes); }); } /** - Derives `output` by Botan's `PasswordHash` of the family whose name is the concatenation of - `name`, from its parameters `i1`, `i2` and `i3` (Botan's `from_params`), over `password` and - `salt`, and, for Argon2, `associated_data` and `secret`; both objects are released before the - return. - - @param name Botan's name of the family, in parts. @param parameters `from_params`'s three. - @param output The derived key. @param password The password. @param salt The salt. - @param associated_data Argon2's X, else empty. @param secret Argon2's K, else empty. + Derives `output_bytes` by Botan's `PasswordHash` of the family whose name is the concatenation of + `name_parts`, from its parameters `i1`, `i2` and `i3` (Botan's `from_params`), over + `password_bytes` and `salt_bytes`, and, for Argon2, `associated_data` and `secret_bytes`; both + objects are released before the return. + + @param name_parts Botan's name of the family, in parts. @param cost_parameters `from_params`'s + three. + @param output_bytes The derived key. @param password_bytes The password. @param salt_bytes The + salt. + @param associated_data Argon2's X, else empty. @param secret_bytes Argon2's K, else empty. @return Success, or the boundary's failure. */ [[nodiscard]] inline boost::system::result botan_password_hash( - std::initializer_list name, std::array parameters, - std::span output, std::span password, - std::span salt, std::span associated_data = {}, - std::span secret = {}) noexcept { + std::initializer_list name_parts, std::array cost_parameters, + std::span output_bytes, std::span password_bytes, + std::span salt_bytes, std::span associated_data = {}, + std::span secret_bytes = {}) noexcept { return botan_boundary([&] { - std::string joined; - for (std::string_view const part : name) { - joined.append(part); + std::string joined_name; + for (std::string_view const name_part : name_parts) { + joined_name.append(name_part); } - auto const hash = botan_create(joined)->from_params( - parameters[0], parameters[1], parameters[2]); - std::string_view const characters = botan_chars(password); - if (associated_data.empty() && secret.empty()) { - hash->derive_key(output.data(), output.size(), characters.data(), characters.size(), - nonnull(salt), salt.size()); + auto const password_hash = + botan_create(joined_name) + ->from_params(cost_parameters[0], cost_parameters[1], cost_parameters[2]); + std::string_view const password_characters = botan_chars(password_bytes); + if (associated_data.empty() && secret_bytes.empty()) { + password_hash->derive_key(output_bytes.data(), output_bytes.size(), + password_characters.data(), password_characters.size(), + nonnull(salt_bytes), salt_bytes.size()); } else { - hash->derive_key(output.data(), output.size(), characters.data(), characters.size(), - nonnull(salt), salt.size(), nonnull(associated_data), - associated_data.size(), nonnull(secret), secret.size()); + password_hash->derive_key(output_bytes.data(), output_bytes.size(), + password_characters.data(), password_characters.size(), + nonnull(salt_bytes), salt_bytes.size(), + nonnull(associated_data), associated_data.size(), + nonnull(secret_bytes), secret_bytes.size()); } }); } @@ -1192,7 +1213,7 @@ struct botan_refused_hmac_kdf { /** Never called: the refusal has stopped the build. */ [[nodiscard]] static boost::system::result extract( - std::span /*salt*/, + std::span /*salt_bytes*/, std::span /*input_key_material*/) noexcept { return error::backend_failure; } @@ -1207,7 +1228,8 @@ struct botan_refused_hmac_kdf { /** Never called: the refusal has stopped the build. */ [[nodiscard]] static boost::system::result extract_and_expand( - std::span /*output_key_material*/, std::span /*salt*/, + std::span /*output_key_material*/, + std::span /*salt_bytes*/, std::span /*input_key_material*/, std::span /*application_info*/) noexcept { return error::backend_failure; @@ -1238,25 +1260,25 @@ struct botan_hkdf_engine { /** RFC 5869, 2.2: the PRK, HashLen bytes; an empty salt is HashLen zeros, as Botan keys it. - @param salt The salt. @param input_key_material The input keying material. + @param salt_bytes The salt. @param input_key_material The input keying material. @return The PRK, or Botan's failure. */ [[nodiscard]] static boost::system::result extract( - std::span salt, + std::span salt_bytes, std::span input_key_material) noexcept { // The PRK is derived into the result returned, whose wiping is the caller's. boost::system::result pseudorandom_key{boost::system::in_place_value}; digest_type& pseudorandom_key_digest = pseudorandom_key.unsafe_value(); - auto const derived = - botan_keyed(salt, [&](std::span key) noexcept { + auto const derive_result = + botan_keyed(salt_bytes, [&](std::span key_bytes) noexcept { return botan_kdf({"HKDF-Extract(HMAC(", botan_hash_name::value, "))"}, std::span(pseudorandom_key_digest.data(), pseudorandom_key_digest.size()), - input_key_material, key, {}); + input_key_material, key_bytes, {}); }); - if (!derived) { + if (!derive_result) { secure::erase_secret(std::span(&pseudorandom_key_digest, 1)); - pseudorandom_key = derived.error(); + pseudorandom_key = derive_result.error(); } return pseudorandom_key; } @@ -1278,18 +1300,20 @@ struct botan_hkdf_engine { /** RFC 5869, 2: both steps, the PRK inside Botan's KDF. - @param output_key_material The OKM. @param salt The salt. @param input_key_material The input - keying material. @param application_info The info. + @param output_key_material The OKM. @param salt_bytes The salt. @param input_key_material The + input keying material. @param application_info The info. @return Success, or Botan's failure. */ [[nodiscard]] static boost::system::result extract_and_expand( - std::span output_key_material, std::span salt, + std::span output_key_material, std::span salt_bytes, std::span input_key_material, std::span application_info) noexcept { - return botan_keyed(salt, [&](std::span key) noexcept { - return botan_kdf({"HKDF(HMAC(", botan_hash_name::value, "))"}, - output_key_material, input_key_material, key, application_info); - }); + return botan_keyed( + salt_bytes, [&](std::span key_bytes) noexcept { + return botan_kdf({"HKDF(HMAC(", botan_hash_name::value, "))"}, + output_key_material, input_key_material, key_bytes, + application_info); + }); } }; @@ -1340,48 +1364,51 @@ struct hkdf_pieces_engine { @param mac_object The owner of the HMAC made. */ static void make(botan_owned& mac_object) { - std::string name = "HMAC("; - name.append(botan_hash_name::value) += ')'; - mac_object.adopt(botan_create(name)); + std::string algorithm_name = "HMAC("; + algorithm_name.append(botan_hash_name::value) += ')'; + mac_object.adopt(botan_create(algorithm_name)); } /** - Feeds every byte of `pieces` to `mac`, in slices of at most @ref slice_max bytes. + Feeds every byte of `input_pieces` to `mac_instance`, in slices of at most @ref slice_max + bytes. - @param mac The keyed HMAC. @param pieces The pieces. + @param mac_instance The keyed HMAC. @param input_pieces The pieces. */ - static void update_all(Botan::MessageAuthenticationCode& mac, byte_pieces pieces) { - for_each_slice(pieces, - [&](std::span slice) { mac.update(slice); }); + static void update_all(Botan::MessageAuthenticationCode& mac_instance, + byte_pieces input_pieces) { + for_each_slice(input_pieces, [&](std::span slice_bytes) { + mac_instance.update(slice_bytes); + }); } /** RFC 5869, 2.2: PRK = HMAC-Hash(salt, piece_1 | ... | piece_n). An empty salt, of length 0, is padded by HMAC with zeros to the block: RFC 5869's HashLen zeros. - @param salt The salt. @param input_key_material The input keying material's pieces. + @param salt_bytes The salt. @param input_key_material The input keying material's pieces. @return The PRK, or Botan's failure. */ [[nodiscard]] static boost::system::result extract( - std::span salt, byte_pieces input_key_material) noexcept { + std::span salt_bytes, byte_pieces input_key_material) noexcept { // The PRK is built in the result returned and Botan writes into it: a single return path // of the one named object, so that no copy of the PRK is left behind unwiped. boost::system::result pseudorandom_key{boost::system::in_place_value}; digest_type& pseudorandom_key_digest = pseudorandom_key.unsafe_value(); - auto const derived = - botan_keyed(salt, [&](std::span key) noexcept { + auto const derive_result = + botan_keyed(salt_bytes, [&](std::span key_bytes) noexcept { botan_owned mac_object; return botan_boundary([&] { make(mac_object); - mac_object.get().set_key(key); + mac_object.get().set_key(key_bytes); update_all(mac_object.get(), input_key_material); mac_object.get().final(std::span(pseudorandom_key_digest.data(), pseudorandom_key_digest.size())); }); }); - if (!derived) { + if (!derive_result) { secure::erase_secret(std::span(&pseudorandom_key_digest, 1)); - pseudorandom_key = derived.error(); + pseudorandom_key = derive_result.error(); } return pseudorandom_key; } @@ -1400,20 +1427,21 @@ struct hkdf_pieces_engine { byte_pieces application_info) noexcept { digest_type t_block{}; botan_owned mac_object; - auto const derived = botan_boundary([&] { + auto const derive_result = botan_boundary([&] { make(mac_object); - Botan::MessageAuthenticationCode& mac = mac_object.get(); + Botan::MessageAuthenticationCode& mac_instance = mac_object.get(); std::size_t written_count = 0; for (unsigned block_counter = 1; written_count < output_key_material.size(); ++block_counter) { - mac.clear(); - mac.set_key(pseudorandom_key); + mac_instance.clear(); + mac_instance.set_key(pseudorandom_key); if (block_counter > 1) { - mac.update(std::span(t_block.data(), t_block.size())); + mac_instance.update( + std::span(t_block.data(), t_block.size())); } - update_all(mac, application_info); - mac.update(static_cast(block_counter)); - mac.final(std::span(t_block.data(), t_block.size())); + update_all(mac_instance, application_info); + mac_instance.update(static_cast(block_counter)); + mac_instance.final(std::span(t_block.data(), t_block.size())); std::size_t const copied_count = std::min(t_block.size(), output_key_material.size() - written_count); std::copy_n(t_block.data(), copied_count, @@ -1423,22 +1451,22 @@ struct hkdf_pieces_engine { }); mac_object.reset(); secure::erase_secret(std::span(&t_block, 1)); - return derived; + return derive_result; } /** RFC 5869, 2: HKDF-Extract, then HKDF-Expand, over pieces; the PRK is wiped between them. - @param output_key_material The OKM. @param salt The salt. + @param output_key_material The OKM. @param salt_bytes The salt. @param input_key_material The input keying material's pieces. @param application_info The info's pieces. @return Success, or Botan's failure. */ [[nodiscard]] static boost::system::result extract_and_expand( - std::span output_key_material, std::span salt, + std::span output_key_material, std::span salt_bytes, byte_pieces input_key_material, byte_pieces application_info) noexcept { return hkdf_pieces_extract_and_expand>( - output_key_material, salt, input_key_material, application_info); + output_key_material, salt_bytes, input_key_material, application_info); } }; @@ -1459,18 +1487,19 @@ struct botan_pbkdf2_engine { /** RFC 8018, 5.2. - @param output_key_material DK. @param password_bytes P. @param salt S. @param iteration_count - c. + @param output_key_material DK. @param password_bytes P. @param salt_bytes S. @param + iteration_count c. @return Success, or Botan's failure. */ [[nodiscard]] static boost::system::result derive( std::span output_key_material, std::span password_bytes, - std::span salt, std::uint64_t iteration_count) noexcept { - return botan_keyed(password_bytes, [&](std::span key) noexcept { - return botan_password_hash({"PBKDF2(HMAC(", botan_hash_name::value, "))"}, - {static_cast(iteration_count), 0, 0}, - output_key_material, key, salt); - }); + std::span salt_bytes, std::uint64_t iteration_count) noexcept { + return botan_keyed( + password_bytes, [&](std::span key_bytes) noexcept { + return botan_password_hash({"PBKDF2(HMAC(", botan_hash_name::value, "))"}, + {static_cast(iteration_count), 0, 0}, + output_key_material, key_bytes, salt_bytes); + }); } }; @@ -1537,16 +1566,18 @@ struct botan_argon2_engine { RFC 9106, version 0x13. @param output_bytes The tag. @param password_bytes The password. @param salt_bytes The salt. - @param parameters The costs, the lanes, the secret and the associated data. + @param cost_parameters The costs, the lanes, the secret and the associated data. @return Success, `errc::not_enough_memory` or `error::backend_failure`. */ [[nodiscard]] static boost::system::result derive( std::span output_bytes, std::span password_bytes, - std::span salt_bytes, argon2_parameters const& parameters) noexcept { + std::span salt_bytes, + argon2_parameters const& cost_parameters) noexcept { return botan_password_hash( {botan_argon2_name::value}, - {parameters.memory_kibibytes, parameters.passes, parameters.lanes}, output_bytes, - password_bytes, salt_bytes, parameters.associated_data, parameters.secret); + {cost_parameters.memory_kibibytes, cost_parameters.passes, cost_parameters.lanes}, + output_bytes, password_bytes, salt_bytes, cost_parameters.associated_data, + cost_parameters.secret); } }; @@ -1623,10 +1654,10 @@ struct scrypt_engine { std::span salt_bytes, std::uint64_t cost_n, std::uint32_t block_size_r, std::uint32_t parallelism_p) noexcept { return botan_keyed( - password_bytes, [&](std::span key) noexcept { + password_bytes, [&](std::span key_bytes) noexcept { return botan_password_hash( {"Scrypt"}, {static_cast(cost_n), block_size_r, parallelism_p}, - output_bytes, key, salt_bytes); + output_bytes, key_bytes, salt_bytes); }); } }; @@ -1641,11 +1672,11 @@ struct scrypt_engine { class botan_salt final : public Botan::RandomNumberGenerator { public: /** - The generator of `salt`, which outlives it. + The generator of `salt_bytes`, which outlives it. - @param salt The 16 bytes of the salt. + @param salt_bytes The 16 bytes of the salt. */ - explicit botan_salt(std::span salt) noexcept : salt_(salt) {} + explicit botan_salt(std::span salt_bytes) noexcept : salt_(salt_bytes) {} /** Takes no input. @return false. */ [[nodiscard]] bool accepts_input() const override { return false; } @@ -1661,20 +1692,20 @@ class botan_salt final : public Botan::RandomNumberGenerator { protected: /** - Writes the salt into `output`, the one draw; throws on a second draw or another size. + Writes the salt into `output_bytes`, the one draw; throws on a second draw or another size. - @param output The 16 bytes drawn. + @param output_bytes The 16 bytes drawn. */ - void fill_bytes_with_input(std::span output, - std::span /*input*/) override { - if (output.empty()) { + void fill_bytes_with_input(std::span output_bytes, + std::span /*input_bytes*/) override { + if (output_bytes.empty()) { return; } - if (drawn_ || output.size() != salt_.size()) { + if (drawn_ || output_bytes.size() != salt_.size()) { boost::throw_exception( Botan::Invalid_State("webcpp::hash's bcrypt salt is drawn once, whole")); } - std::ranges::copy(salt_, output.begin()); + std::ranges::copy(salt_, output_bytes.begin()); drawn_ = true; } @@ -1699,41 +1730,44 @@ struct bcrypt_engine { /** The 60 characters. - @param output The string. @param password The password. @param salt The 16-byte salt. - @param cost The cost, 4 to 18. @param version 'a', 'b' or 'y'. + @param output_characters The string. @param password_bytes The password. @param salt_bytes The + 16-byte salt. + @param bcrypt_cost The cost, 4 to 18. @param version_character 'a', 'b' or 'y'. @return Success, or the boundary's failure. */ [[nodiscard]] static boost::system::result generate( - std::span output, std::span password, - std::span salt, std::uint32_t cost, char version) noexcept { + std::span output_characters, std::span password_bytes, + std::span salt_bytes, std::uint32_t bcrypt_cost, + char version_character) noexcept { return botan_boundary([&] { - botan_salt generator(salt); - std::string const made = Botan::generate_bcrypt( - botan_chars(password), generator, static_cast(cost), version); - if (made.size() != output.size()) { + botan_salt salt_generator(salt_bytes); + std::string const made_hash = + Botan::generate_bcrypt(botan_chars(password_bytes), salt_generator, + static_cast(bcrypt_cost), version_character); + if (made_hash.size() != output_characters.size()) { boost::throw_exception( Botan::Invalid_State("bcrypt's string is not 60 characters")); } - std::ranges::copy(made, output.begin()); + std::ranges::copy(made_hash, output_characters.begin()); }); } /** - Whether `password` gives `hash`. + Whether `password_bytes` gives `encoded_hash`. - @param password The password. @param hash The string, of bcrypt's form and a cost of at most - 18. + @param password_bytes The password. @param encoded_hash The string, of bcrypt's form and a cost + of at most 18. @return Whether it does, or the boundary's failure. */ - [[nodiscard]] static boost::system::result verify(std::span password, - std::string_view hash) noexcept { - bool same = false; - auto const checked = - botan_boundary([&] { same = Botan::check_bcrypt(botan_chars(password), hash); }); - if (!checked) { - return checked.error(); + [[nodiscard]] static boost::system::result verify( + std::span password_bytes, std::string_view encoded_hash) noexcept { + bool same_hash = false; + auto const boundary_result = botan_boundary( + [&] { same_hash = Botan::check_bcrypt(botan_chars(password_bytes), encoded_hash); }); + if (!boundary_result) { + return boundary_result.error(); } - return same; + return same_hash; } }; @@ -1747,15 +1781,16 @@ struct bcrypt_pbkdf_engine { /** OpenBSD's bcrypt_pbkdf. - @param output The derived key. @param password The password. @param salt The salt. - @param rounds The rounds. + @param output_bytes The derived key. @param password_bytes The password. @param salt_bytes The + salt. + @param round_count The rounds. @return Success, or the boundary's failure. */ - [[nodiscard]] static boost::system::result derive(std::span output, - std::span password, - std::span salt, - std::uint32_t rounds) noexcept { - return botan_password_hash({"Bcrypt-PBKDF"}, {rounds, 0, 0}, output, password, salt); + [[nodiscard]] static boost::system::result derive( + std::span output_bytes, std::span password_bytes, + std::span salt_bytes, std::uint32_t round_count) noexcept { + return botan_password_hash({"Bcrypt-PBKDF"}, {round_count, 0, 0}, output_bytes, + password_bytes, salt_bytes); } }; @@ -1793,31 +1828,32 @@ struct botan_kbkdf_engine { /** Whether Botan writes this fixed input: with the separator and L. - @param options The fixed input. @return Whether both are on. + @param algorithm_options The fixed input. @return Whether both are on. */ - static constexpr bool accepts(kbkdf_options const& options) noexcept { - return options.separator && options.length; + static constexpr bool accepts(kbkdf_options const& algorithm_options) noexcept { + return algorithm_options.separator && algorithm_options.length; } /** K_OUT. - @param output K_OUT. @param key K_IN. @param options The label, the context and r. + @param output_bytes K_OUT. @param key_bytes K_IN. @param algorithm_options The label, the + context and r. @return Success, or the boundary's failure. */ - [[nodiscard]] static boost::system::result derive(std::span output, - std::span key, - kbkdf_options const& options) noexcept { - return botan_keyed(key, [&](std::span used_key) noexcept { + [[nodiscard]] static boost::system::result derive( + std::span output_bytes, std::span key_bytes, + kbkdf_options const& algorithm_options) noexcept { + return botan_keyed(key_bytes, [&](std::span used_key) noexcept { return botan_kdf( { "SP800-108-Counter(HMAC(", botan_hash_name::value, "),", - botan_counter_width(options.counter_bits), + botan_counter_width(algorithm_options.counter_bits), ",32)", }, - output, used_key, options.context, options.label); + output_bytes, used_key, algorithm_options.context, algorithm_options.label); }); } }; @@ -1840,8 +1876,8 @@ struct botan_refused_kbkdf { /** Never called. @return backend_failure. */ [[nodiscard]] static boost::system::result derive( - std::span /*output*/, std::span /*key*/, - kbkdf_options const& /*options*/) noexcept { + std::span /*output_bytes*/, std::span /*key_bytes*/, + kbkdf_options const& /*algorithm_options*/) noexcept { return error::backend_failure; } }; @@ -1866,14 +1902,14 @@ struct botan_sskdf_engine { /** The derived keying material. - @param output The output. @param secret Z. @param fixed_info FixedInfo. + @param output_bytes The output. @param secret_bytes Z. @param fixed_info FixedInfo. @return Success, or the boundary's failure. */ [[nodiscard]] static boost::system::result derive( - std::span output, std::span secret, + std::span output_bytes, std::span secret_bytes, std::span fixed_info) noexcept { - return botan_kdf({"SP800-56A(", botan_hash_name::value, ")"}, output, secret, {}, - fixed_info); + return botan_kdf({"SP800-56A(", botan_hash_name::value, ")"}, output_bytes, + secret_bytes, {}, fixed_info); } }; @@ -1913,13 +1949,13 @@ struct x963kdf_engine { /** The derived keying material. - @param output The output. @param secret Z. @param shared_info SharedInfo. + @param output_bytes The output. @param secret_bytes Z. @param shared_info SharedInfo. @return Success, or the boundary's failure. */ [[nodiscard]] static boost::system::result derive( - std::span output, std::span secret, + std::span output_bytes, std::span secret_bytes, std::span shared_info) noexcept { - return botan_kdf({"KDF2(", botan_hash_name::value, ")"}, output, secret, + return botan_kdf({"KDF2(", botan_hash_name::value, ")"}, output_bytes, secret_bytes, shared_info, {}); } }; diff --git a/include/webcpp/hash/backends/hash2.hpp b/include/webcpp/hash/backends/hash2.hpp index d4afbfb..92c130a 100644 --- a/include/webcpp/hash/backends/hash2.hpp +++ b/include/webcpp/hash/backends/hash2.hpp @@ -71,13 +71,13 @@ struct hkdf_engine { RFC 5869, 2.2: PRK = HMAC-Hash(salt, IKM). An empty salt is HashLen zeros, which Hash2's hmac keys as zeros of the block, the same key. - @param salt The salt. @param input_key_material The input keying material. + @param salt_bytes The salt. @param input_key_material The input keying material. @return The PRK. */ [[nodiscard]] static boost::system::result extract( - std::span salt, + std::span salt_bytes, std::span input_key_material) noexcept { - Hmac mac_state(salt.data(), salt.size()); + Hmac mac_state(salt_bytes.data(), salt_bytes.size()); mac_state.update(input_key_material.data(), input_key_material.size()); // The PRK is stored in the result returned, whose wiping is the caller's. boost::system::result pseudorandom_key{ @@ -127,16 +127,16 @@ struct hkdf_engine { /** RFC 5869, 2: HKDF-Extract, then HKDF-Expand; the PRK is wiped. - @param output_key_material The OKM. @param salt The salt. @param input_key_material The input - keying material. + @param output_key_material The OKM. @param salt_bytes The salt. @param input_key_material The + input keying material. @param application_info The info. @return Success. */ [[nodiscard]] static boost::system::result extract_and_expand( - std::span output_key_material, std::span salt, + std::span output_key_material, std::span salt_bytes, std::span input_key_material, std::span application_info) noexcept { - auto pseudorandom_key = extract(salt, input_key_material); + auto pseudorandom_key = extract(salt_bytes, input_key_material); if (!pseudorandom_key) { return pseudorandom_key.error(); } @@ -170,15 +170,16 @@ struct hkdf_pieces_engine { RFC 5869, 2.2: PRK = HMAC-Hash(salt, piece_1 | ... | piece_n). An empty salt is HashLen zeros, which Hash2's hmac keys as zeros of the block, the same key. - @param salt The salt. @param input_key_material The input keying material's pieces. + @param salt_bytes The salt. @param input_key_material The input keying material's pieces. @return The PRK. */ [[nodiscard]] static boost::system::result extract( - std::span salt, byte_pieces input_key_material) noexcept { - Hmac mac_state(salt.data(), salt.size()); - for_each_slice(input_key_material, [&](std::span slice) { - mac_state.update(slice.data(), slice.size()); - }); + std::span salt_bytes, byte_pieces input_key_material) noexcept { + Hmac mac_state(salt_bytes.data(), salt_bytes.size()); + for_each_slice(input_key_material, + [&](std::span slice_bytes) { + mac_state.update(slice_bytes.data(), slice_bytes.size()); + }); // The PRK is stored in the result returned, whose wiping is the caller's. boost::system::result pseudorandom_key{ boost::system::in_place_value, @@ -210,9 +211,10 @@ struct hkdf_pieces_engine { if (block_counter > 1) { mac_state.update(t_block.data(), t_block.size()); } - for_each_slice(application_info, [&](std::span slice) { - mac_state.update(slice.data(), slice.size()); - }); + for_each_slice(application_info, + [&](std::span slice_bytes) { + mac_state.update(slice_bytes.data(), slice_bytes.size()); + }); const auto octet_value = static_cast(block_counter); mac_state.update(&octet_value, 1); t_block = mac_state.result(); @@ -230,16 +232,16 @@ struct hkdf_pieces_engine { /** RFC 5869, 2: HKDF-Extract, then HKDF-Expand, over pieces; the PRK is wiped between them. - @param output_key_material The OKM. @param salt The salt. + @param output_key_material The OKM. @param salt_bytes The salt. @param input_key_material The input keying material's pieces. @param application_info The info's pieces. @return Success. */ [[nodiscard]] static boost::system::result extract_and_expand( - std::span output_key_material, std::span salt, + std::span output_key_material, std::span salt_bytes, byte_pieces input_key_material, byte_pieces application_info) noexcept { return hkdf_pieces_extract_and_expand>( - output_key_material, salt, input_key_material, application_info); + output_key_material, salt_bytes, input_key_material, application_info); } }; @@ -317,54 +319,57 @@ struct hash2_digest_engine : full_engine { /** The Hash2 algorithm, which is all of the state. */ using state = Hash; - /** Starts a hash. @param hashed The state. @return Success. */ + /** Starts a hash. @param digest_state The state. @return Success. */ [[nodiscard]] static boost::system::result init( - state& hashed, digest_options const& /*options*/) noexcept { - hashed = Hash(); + state& digest_state, digest_options const& /*algorithm_options*/) noexcept { + digest_state = Hash(); return {}; } - /** Absorbs `input`. @param hashed The state. @param input The bytes. @return Success. */ + /** Absorbs `input_bytes`. @param digest_state The state. @param input_bytes The bytes. @return + * Success. */ [[nodiscard]] static boost::system::result update( - state& hashed, std::span input) noexcept { - hashed.update(input.data(), input.size()); + state& digest_state, std::span input_bytes) noexcept { + digest_state.update(input_bytes.data(), input_bytes.size()); return {}; } /** - Writes the first `output.size()` bytes of the successive results, each result wiped. + Writes the first `output_bytes.size()` bytes of the successive results, each result wiped. - @param hashed The state. @param output The digest. @return Success. + @param digest_state The state. @param output_bytes The digest. @return Success. */ [[nodiscard]] static boost::system::result finish( - state& hashed, std::span output) noexcept { - while (!output.empty()) { - auto result_bytes = hashed.result(); - auto const taken = std::min(output.size(), result_bytes.size()); - std::memcpy(output.data(), result_bytes.data(), taken); + state& digest_state, std::span output_bytes) noexcept { + while (!output_bytes.empty()) { + auto result_bytes = digest_state.result(); + auto const taken_size = std::min(output_bytes.size(), result_bytes.size()); + std::memcpy(output_bytes.data(), result_bytes.data(), taken_size); secure::erase_secret(std::span(&result_bytes, 1)); - output = output.subspan(taken); + output_bytes = output_bytes.subspan(taken_size); } return {}; } - /** Wipes the state. @param hashed The state. */ - static void destroy(state& hashed) noexcept { secure::erase_secret(std::span(&hashed, 1)); } + /** Wipes the state. @param digest_state The state. */ + static void destroy(state& digest_state) noexcept { + secure::erase_secret(std::span(&digest_state, 1)); + } /** - The hash of `input` at once, the state wiped. + The hash of `input_bytes` at once, the state wiped. - @param output The digest. @param input The bytes. @param options None. + @param output_bytes The digest. @param input_bytes The bytes. @param algorithm_options None. @return Success. */ [[nodiscard]] static boost::system::result one_shot( - std::span output, std::span input, - digest_options const& options) noexcept { - state hashed; - static_cast(init(hashed, options)); - static_cast(update(hashed, input)); - static_cast(finish(hashed, output)); - destroy(hashed); + std::span output_bytes, std::span input_bytes, + digest_options const& algorithm_options) noexcept { + state digest_state; + static_cast(init(digest_state, algorithm_options)); + static_cast(update(digest_state, input_bytes)); + static_cast(finish(digest_state, output_bytes)); + destroy(digest_state); return {}; } }; @@ -456,12 +461,13 @@ struct digest_engine personalisation. A template, so that it reads `digest_options`, which digest.hpp defines after this header. - @param options The options. @return Whether Boost.Hash2's `blake2b_512` computes them. + @param algorithm_options The options. @return Whether Boost.Hash2's `blake2b_512` computes + them. */ template - static constexpr bool accepts(Options const& options) noexcept { - return options.output_size == min_output && options.key.empty() && options.salt.empty() && - options.personalisation.empty(); + static constexpr bool accepts(Options const& algorithm_options) noexcept { + return algorithm_options.output_size == min_output && algorithm_options.key.empty() && + algorithm_options.salt.empty() && algorithm_options.personalisation.empty(); } }; @@ -493,19 +499,19 @@ struct digest_engine template struct hash2_hmac_engine : full_engine { /** - The tag of `input` under `key`. + The tag of `input_bytes` under `key_bytes`. - @param output The tag, at most the digest's size. @param key The key, of any size. - @param input The message. @return Success. + @param output_bytes The tag, at most the digest's size. @param key_bytes The key, of any size. + @param input_bytes The message. @return Success. */ [[nodiscard]] static boost::system::result compute( - std::span output, std::span key, - std::span input, - mac_options> const& /*options*/) noexcept { - boost::hash2::hmac keyed_mac(key.data(), key.size()); - keyed_mac.update(input.data(), input.size()); + std::span output_bytes, std::span key_bytes, + std::span input_bytes, + mac_options> const& /*algorithm_options*/) noexcept { + boost::hash2::hmac keyed_mac(key_bytes.data(), key_bytes.size()); + keyed_mac.update(input_bytes.data(), input_bytes.size()); auto tag_bytes = keyed_mac.result(); - std::memcpy(output.data(), tag_bytes.data(), output.size()); + std::memcpy(output_bytes.data(), tag_bytes.data(), output_bytes.size()); secure::erase_secret(std::span(&tag_bytes, 1)); secure::erase_secret(std::span(&keyed_mac, 1)); return {}; @@ -595,20 +601,21 @@ struct mac_engine> template <> struct mac_engine : full_engine { /** - The tag of `input` under `key`. + The tag of `input_bytes` under `key_bytes`. - @param output The tag, 8 bytes. @param key The key, 16 bytes. @param input The message. + @param output_bytes The tag, 8 bytes. @param key_bytes The key, 16 bytes. @param input_bytes + The message. @return Success. */ [[nodiscard]] static boost::system::result compute( - std::span output, std::span key, - std::span input, - mac_options const& /*options*/) noexcept { - boost::hash2::siphash_64 keyed_mac(key.data(), key.size()); - keyed_mac.update(input.data(), input.size()); + std::span output_bytes, std::span key_bytes, + std::span input_bytes, + mac_options const& /*algorithm_options*/) noexcept { + boost::hash2::siphash_64 keyed_mac(key_bytes.data(), key_bytes.size()); + keyed_mac.update(input_bytes.data(), input_bytes.size()); std::uint64_t tag_value = keyed_mac.result(); - for (std::uint8_t& byte : output) { - byte = static_cast(tag_value & 0xffU); + for (std::uint8_t& output_byte : output_bytes) { + output_byte = static_cast(tag_value & 0xffU); tag_value >>= 8U; } secure::erase_secret(std::span(&keyed_mac, 1)); @@ -628,25 +635,26 @@ struct mac_engine : full_engine { @param output_size The tag's size. @return Whether it is 32. */ - static constexpr bool accepts(mac_options const& /*options*/, + static constexpr bool accepts(mac_options const& /*algorithm_options*/, std::size_t /*key_size*/, std::size_t output_size) noexcept { return output_size == boost::hash2::blake2s_256::result_type().size(); } /** - The tag of `input` under `key`. + The tag of `input_bytes` under `key_bytes`. - @param output The tag, 32 bytes. @param key The key, 1 to 32 bytes. @param input The message. + @param output_bytes The tag, 32 bytes. @param key_bytes The key, 1 to 32 bytes. @param + input_bytes The message. @return Success. */ [[nodiscard]] static boost::system::result compute( - std::span output, std::span key, - std::span input, - mac_options const& /*options*/) noexcept { - boost::hash2::blake2s_256 keyed_mac(key.data(), key.size()); - keyed_mac.update(input.data(), input.size()); + std::span output_bytes, std::span key_bytes, + std::span input_bytes, + mac_options const& /*algorithm_options*/) noexcept { + boost::hash2::blake2s_256 keyed_mac(key_bytes.data(), key_bytes.size()); + keyed_mac.update(input_bytes.data(), input_bytes.size()); auto tag_bytes = keyed_mac.result(); - std::memcpy(output.data(), tag_bytes.data(), output.size()); + std::memcpy(output_bytes.data(), tag_bytes.data(), output_bytes.size()); secure::erase_secret(std::span(&tag_bytes, 1)); secure::erase_secret(std::span(&keyed_mac, 1)); return {}; diff --git a/include/webcpp/hash/backends/openssl.hpp b/include/webcpp/hash/backends/openssl.hpp index bb773a2..e28242b 100644 --- a/include/webcpp/hash/backends/openssl.hpp +++ b/include/webcpp/hash/backends/openssl.hpp @@ -487,16 +487,16 @@ struct openssl_memory_error { OpenSSL raised an error failed, whatever its functions returned: OpenSSL's Argon2 leaves some of its allocations unchecked and returns success over a wrong tag when one fails. - @param succeeded Whether OpenSSL's functions returned success. + @param call_succeeded Whether OpenSSL's functions returned success. @param memory_error An error that means the memory cannot be had, beside an allocation's. @return Success when OpenSSL succeeded and raised nothing; `errc::not_enough_memory` when an error raised since the mark is an allocation's or `memory_error`; `error::backend_failure` otherwise. */ [[nodiscard]] inline boost::system::result openssl_outcome( - bool succeeded, openssl_memory_error memory_error = {}) noexcept { + bool call_succeeded, openssl_memory_error memory_error = {}) noexcept { // NOLINTNEXTLINE(bugprone-signed-bitwise): OpenSSL's macro ORs signed constants constexpr int malloc_failure_reason = ERR_R_MALLOC_FAILURE; - const bool raised = ERR_count_to_mark() > 0; + const bool error_raised = ERR_count_to_mark() > 0; bool is_out_of_memory = false; while (ERR_count_to_mark() > 0) { unsigned long const error_code = ERR_peek_last_error(); @@ -507,7 +507,7 @@ struct openssl_memory_error { ERR_pop(); } ERR_pop_to_mark(); - if (succeeded && !raised) { + if (call_succeeded && !error_raised) { return {}; } if (is_out_of_memory) { @@ -564,17 +564,17 @@ struct hkdf_engine { RFC 5869, 2.2, in extract-only mode, which writes the PRK, HashLen bytes, into the digest. An empty salt is HashLen zeros, as OpenSSL's HMAC pads it. - @param salt The salt. @param input_key_material The input keying material. + @param salt_bytes The salt. @param input_key_material The input keying material. @return The PRK, or OpenSSL's failure. */ [[nodiscard]] static boost::system::result extract( - std::span salt, + std::span salt_bytes, std::span input_key_material) noexcept { int hkdf_mode = extract_only; std::array ossl_params{ openssl_text("digest", openssl_digest()), openssl_octets("key", input_key_material), - openssl_octets("salt", salt), + openssl_octets("salt", salt_bytes), OSSL_PARAM_construct_int("mode", &hkdf_mode), OSSL_PARAM_construct_end(), }; @@ -617,20 +617,20 @@ struct hkdf_engine { /** RFC 5869, 2, in extract-and-expand mode: the PRK stays inside OpenSSL's context. - @param output_key_material The OKM. @param salt The salt. @param input_key_material The input - keying material. + @param output_key_material The OKM. @param salt_bytes The salt. @param input_key_material The + input keying material. @param application_info The info. @return Success, or OpenSSL's failure. */ [[nodiscard]] static boost::system::result extract_and_expand( - std::span output_key_material, std::span salt, + std::span output_key_material, std::span salt_bytes, std::span input_key_material, std::span application_info) noexcept { int hkdf_mode = both; std::array ossl_params{ openssl_text("digest", openssl_digest()), openssl_octets("key", input_key_material), - openssl_octets("salt", salt), + openssl_octets("salt", salt_bytes), openssl_octets("info", application_info), OSSL_PARAM_construct_int("mode", &hkdf_mode), OSSL_PARAM_construct_end(), @@ -669,14 +669,14 @@ struct hkdf_pieces_engine { "EVP_MAC_update takes every slice's length"); /** - A context of `mac_algorithm` keyed by `key` with the hmac's digest (`EVP_MAC_CTX_new`, then - `EVP_MAC_init`), or null when OpenSSL could not make or key it (a context made is freed). + A context of `mac_algorithm` keyed by `key_bytes` with the hmac's digest (`EVP_MAC_CTX_new`, + then `EVP_MAC_init`), or null when OpenSSL could not make or key it (a context made is freed). - @param mac_algorithm The MAC "HMAC", or null. @param key The key, possibly empty. + @param mac_algorithm The MAC "HMAC", or null. @param key_bytes The key, possibly empty. @return The keyed context, which the caller frees, or null. */ - [[nodiscard]] static EVP_MAC_CTX* keyed_context(EVP_MAC* mac_algorithm, - std::span key) noexcept { + [[nodiscard]] static EVP_MAC_CTX* keyed_context( + EVP_MAC* mac_algorithm, std::span key_bytes) noexcept { if (mac_algorithm == nullptr) { return nullptr; } @@ -686,8 +686,8 @@ struct hkdf_pieces_engine { OSSL_PARAM_construct_end(), }; // A key's pointer is never null: OpenSSL takes a null key for "no key given". - if (mac_context != nullptr && - EVP_MAC_init(mac_context, nonnull(key), key.size(), ossl_params.data()) != 1) { + if (mac_context != nullptr && EVP_MAC_init(mac_context, nonnull(key_bytes), + key_bytes.size(), ossl_params.data()) != 1) { EVP_MAC_CTX_free(mac_context); mac_context = nullptr; } @@ -695,18 +695,20 @@ struct hkdf_pieces_engine { } /** - Feeds every byte of `pieces` to `mac_context`, in slices of at most @ref slice_max bytes, + Feeds every byte of `input_pieces` to `mac_context`, in slices of at most @ref slice_max bytes, until OpenSSL fails one. - @param mac_context The keyed context. @param pieces The pieces. + @param mac_context The keyed context. @param input_pieces The pieces. @return Whether OpenSSL took every slice. */ - [[nodiscard]] static bool update_all(EVP_MAC_CTX* mac_context, byte_pieces pieces) noexcept { - bool updated = true; - for_each_slice(pieces, [&](std::span slice) { - updated = updated && EVP_MAC_update(mac_context, slice.data(), slice.size()) == 1; + [[nodiscard]] static bool update_all(EVP_MAC_CTX* mac_context, + byte_pieces input_pieces) noexcept { + bool update_succeeded = true; + for_each_slice(input_pieces, [&](std::span slice_bytes) { + update_succeeded = update_succeeded && EVP_MAC_update(mac_context, slice_bytes.data(), + slice_bytes.size()) == 1; }); - return updated; + return update_succeeded; } /** @@ -717,38 +719,39 @@ struct hkdf_pieces_engine { @return Whether OpenSSL wrote the whole HMAC. */ [[nodiscard]] static bool finish(EVP_MAC_CTX* mac_context, digest_type& mac_result) noexcept { - std::size_t written = 0; + std::size_t written_size = 0; return EVP_MAC_CTX_get_mac_size(mac_context) == mac_result.size() && - EVP_MAC_final(mac_context, mac_result.data(), &written, mac_result.size()) == 1 && - written == mac_result.size(); + EVP_MAC_final(mac_context, mac_result.data(), &written_size, mac_result.size()) == + 1 && + written_size == mac_result.size(); } /** RFC 5869, 2.2: PRK = HMAC-Hash(salt, piece_1 | ... | piece_n). An empty salt, of length 0, is padded by HMAC with zeros to the block: RFC 5869's HashLen zeros. - @param salt The salt. @param input_key_material The input keying material's pieces. + @param salt_bytes The salt. @param input_key_material The input keying material's pieces. @return The PRK, or OpenSSL's failure. */ [[nodiscard]] static boost::system::result extract( - std::span salt, byte_pieces input_key_material) noexcept { + std::span salt_bytes, byte_pieces input_key_material) noexcept { // The PRK is built in the result returned and OpenSSL writes into it: a single return path // of the one named object, so that no copy of the PRK is left behind unwiped. boost::system::result pseudorandom_key{boost::system::in_place_value}; digest_type& pseudorandom_key_digest = pseudorandom_key.unsafe_value(); ERR_set_mark(); EVP_MAC* mac_algorithm = EVP_MAC_fetch(nullptr, "HMAC", nullptr); - EVP_MAC_CTX* mac_context = keyed_context(mac_algorithm, salt); - const bool computed = mac_context != nullptr && - update_all(mac_context, input_key_material) && - finish(mac_context, pseudorandom_key_digest); + EVP_MAC_CTX* mac_context = keyed_context(mac_algorithm, salt_bytes); + const bool call_succeeded = mac_context != nullptr && + update_all(mac_context, input_key_material) && + finish(mac_context, pseudorandom_key_digest); // The frees raise no error: the outcome read after them is the computation's. EVP_MAC_CTX_free(mac_context); EVP_MAC_free(mac_algorithm); - auto const outcome = openssl_outcome(computed); - if (!outcome) { + auto const extract_result = openssl_outcome(call_succeeded); + if (!extract_result) { secure::erase_secret(std::span(&pseudorandom_key_digest, 1)); - pseudorandom_key = outcome.error(); + pseudorandom_key = extract_result.error(); } return pseudorandom_key; } @@ -767,22 +770,22 @@ struct hkdf_pieces_engine { byte_pieces application_info) noexcept { ERR_set_mark(); EVP_MAC* mac_algorithm = EVP_MAC_fetch(nullptr, "HMAC", nullptr); - EVP_MAC_CTX* keyed = keyed_context(mac_algorithm, pseudorandom_key); + EVP_MAC_CTX* keyed_mac = keyed_context(mac_algorithm, pseudorandom_key); digest_type t_block{}; - bool computed = keyed != nullptr; + bool call_succeeded = keyed_mac != nullptr; std::size_t written_count = 0; - for (unsigned block_counter = 1; computed && written_count < output_key_material.size(); - ++block_counter) { - EVP_MAC_CTX* block_context = EVP_MAC_CTX_dup(keyed); + for (unsigned block_counter = 1; + call_succeeded && written_count < output_key_material.size(); ++block_counter) { + EVP_MAC_CTX* block_context = EVP_MAC_CTX_dup(keyed_mac); auto const octet_value = static_cast(block_counter); - computed = block_context != nullptr && - (block_counter == 1 || - EVP_MAC_update(block_context, t_block.data(), t_block.size()) == 1) && - update_all(block_context, application_info) && - EVP_MAC_update(block_context, &octet_value, 1) == 1 && - finish(block_context, t_block); + call_succeeded = block_context != nullptr && + (block_counter == 1 || + EVP_MAC_update(block_context, t_block.data(), t_block.size()) == 1) && + update_all(block_context, application_info) && + EVP_MAC_update(block_context, &octet_value, 1) == 1 && + finish(block_context, t_block); EVP_MAC_CTX_free(block_context); - if (computed) { + if (call_succeeded) { std::size_t const copied_count = std::min(t_block.size(), output_key_material.size() - written_count); std::copy_n(t_block.data(), copied_count, @@ -792,24 +795,24 @@ struct hkdf_pieces_engine { } secure::erase_secret(std::span(&t_block, 1)); // The frees raise no error: the outcome read after them is the computation's. - EVP_MAC_CTX_free(keyed); + EVP_MAC_CTX_free(keyed_mac); EVP_MAC_free(mac_algorithm); - return openssl_outcome(computed); + return openssl_outcome(call_succeeded); } /** RFC 5869, 2: HKDF-Extract, then HKDF-Expand, over pieces; the PRK is wiped between them. - @param output_key_material The OKM. @param salt The salt. + @param output_key_material The OKM. @param salt_bytes The salt. @param input_key_material The input keying material's pieces. @param application_info The info's pieces. @return Success, or OpenSSL's failure. */ [[nodiscard]] static boost::system::result extract_and_expand( - std::span output_key_material, std::span salt, + std::span output_key_material, std::span salt_bytes, byte_pieces input_key_material, byte_pieces application_info) noexcept { return hkdf_pieces_extract_and_expand>( - output_key_material, salt, input_key_material, application_info); + output_key_material, salt_bytes, input_key_material, application_info); } }; @@ -860,7 +863,7 @@ inline constexpr std::uint32_t openssl_argon2_max_memory_kibibytes = static_cast @param kdf_name "ARGON2D", "ARGON2I" or "ARGON2ID". @param output_bytes The tag. @param password_bytes The password. @param salt_bytes The salt. - @param parameters t, m in KiB, p, the secret and the associated data, within RFC 9106's + @param cost_parameters t, m in KiB, p, the secret and the associated data, within RFC 9106's bounds and `openssl_argon2_max_memory_kibibytes`. @return Success; `errc::not_enough_memory` when the memory cannot be allocated (OpenSSL raises its allocation's error, then its own "invalid memory size"); `error::backend_failure` otherwise. @@ -868,17 +871,17 @@ inline constexpr std::uint32_t openssl_argon2_max_memory_kibibytes = static_cast [[nodiscard]] inline boost::system::result openssl_argon2( char const* kdf_name, std::span output_bytes, std::span password_bytes, std::span salt_bytes, - argon2_parameters const& parameters) noexcept { - std::uint32_t pass_count = parameters.passes; - std::uint32_t memory_kibibytes = parameters.memory_kibibytes; - std::uint32_t lane_count = parameters.lanes; + argon2_parameters const& cost_parameters) noexcept { + std::uint32_t pass_count = cost_parameters.passes; + std::uint32_t memory_kibibytes = cost_parameters.memory_kibibytes; + std::uint32_t lane_count = cost_parameters.lanes; std::uint32_t thread_count = 1; // An empty secret or associated data is hashed as OpenSSL hashes none: its length, 0, alone. std::array ossl_params{ openssl_octets("pass", password_bytes), openssl_octets("salt", salt_bytes), - openssl_octets("secret", parameters.secret), - openssl_octets("ad", parameters.associated_data), + openssl_octets("secret", cost_parameters.secret), + openssl_octets("ad", cost_parameters.associated_data), OSSL_PARAM_construct_uint32("iter", &pass_count), OSSL_PARAM_construct_uint32("memcost", &memory_kibibytes), OSSL_PARAM_construct_uint32("lanes", &lane_count), @@ -934,14 +937,15 @@ struct openssl_argon2_engine { RFC 9106, version 0x13. @param output_bytes The tag. @param password_bytes The password. @param salt_bytes The salt. - @param parameters The costs, the lanes, the secret and the associated data. + @param cost_parameters The costs, the lanes, the secret and the associated data. @return Success, `errc::not_enough_memory` or `error::backend_failure`. */ [[nodiscard]] static boost::system::result derive( std::span output_bytes, std::span password_bytes, - std::span salt_bytes, argon2_parameters const& parameters) noexcept { + std::span salt_bytes, + argon2_parameters const& cost_parameters) noexcept { return openssl_argon2(openssl_argon2_name::value, output_bytes, password_bytes, - salt_bytes, parameters); + salt_bytes, cost_parameters); } }; @@ -1105,13 +1109,13 @@ class openssl_md_state { [[nodiscard]] EVP_MD_CTX* get() const noexcept { return context_; } /** - Owns `context` from here on, freeing the one it held. + Owns `digest_context` from here on, freeing the one it held. - @param context A context of `EVP_MD_CTX_new`, or null. + @param digest_context A context of `EVP_MD_CTX_new`, or null. */ - void adopt(EVP_MD_CTX* context) noexcept { + void adopt(EVP_MD_CTX* digest_context) noexcept { reset(); - context_ = context; + context_ = digest_context; } /** Frees the context; a state without one is left as it is. */ @@ -1147,86 +1151,90 @@ struct openssl_digest_engine : full_engine { Starts a hash: a new context, the digest fetched, `EVP_DigestInit_ex2` with no parameter (BLAKE2b's engine gives its size). - @param hashed The state, which owns the context from here on, even when the start fails. - @param options The digest's parameters. + @param digest_state The state, which owns the context from here on, even when the start fails. + @param algorithm_options The digest's parameters. @return Success; `errc::not_enough_memory`; or `error::backend_failure`. */ [[nodiscard]] static boost::system::result init( - state& hashed, digest_options const& options) noexcept { + state& digest_state, digest_options const& algorithm_options) noexcept { ERR_set_mark(); - hashed.adopt(EVP_MD_CTX_new()); - EVP_MD* digest_algorithm = hashed.get() != nullptr + digest_state.adopt(EVP_MD_CTX_new()); + EVP_MD* digest_algorithm = digest_state.get() != nullptr ? EVP_MD_fetch(nullptr, openssl_md(), nullptr) : nullptr; - const bool started = - digest_algorithm != nullptr && start(hashed.get(), digest_algorithm, options); + const bool start_succeeded = digest_algorithm != nullptr && + start(digest_state.get(), digest_algorithm, algorithm_options); // The context holds its own reference to the digest from EVP_DigestInit_ex2 on. EVP_MD_free(digest_algorithm); - return openssl_outcome(started); + return openssl_outcome(start_succeeded); } /** - Absorbs `input`: `EVP_DigestUpdate`, which returns at once on an empty input. + Absorbs `input_bytes`: `EVP_DigestUpdate`, which returns at once on an empty input. - @param hashed The state. @param input The bytes. + @param digest_state The state. @param input_bytes The bytes. @return Success, or OpenSSL's failure. */ [[nodiscard]] static boost::system::result update( - state& hashed, std::span input) noexcept { + state& digest_state, std::span input_bytes) noexcept { ERR_set_mark(); - return openssl_outcome(EVP_DigestUpdate(hashed.get(), input.data(), input.size()) == 1); + return openssl_outcome( + EVP_DigestUpdate(digest_state.get(), input_bytes.data(), input_bytes.size()) == 1); } /** - Writes the result, of `output.size()` bytes: `EVP_DigestFinalXOF` for an extendable-output - function; else `EVP_DigestFinal_ex`, once OpenSSL's size of the context is seen to be the - output's (the family's guards hold it to the digest's size, or BLAKE2b's option). + Writes the result, of `output_bytes.size()` bytes: `EVP_DigestFinalXOF` for an + extendable-output function; else `EVP_DigestFinal_ex`, once OpenSSL's size of the context is + seen to be the output's (the family's guards hold it to the digest's size, or BLAKE2b's + option). - @param hashed The state. @param output The digest. + @param digest_state The state. @param output_bytes The digest. @return Success, or OpenSSL's failure. */ [[nodiscard]] static boost::system::result finish( - state& hashed, std::span output) noexcept { + state& digest_state, std::span output_bytes) noexcept { ERR_set_mark(); - bool finished = false; + bool finish_succeeded = false; if constexpr (openssl_md_name::xof) { - finished = EVP_DigestFinalXOF(hashed.get(), output.data(), output.size()) == 1; + finish_succeeded = EVP_DigestFinalXOF(digest_state.get(), output_bytes.data(), + output_bytes.size()) == 1; } else { - const int context_size = EVP_MD_CTX_get_size(hashed.get()); - finished = context_size > 0 && - static_cast(context_size) == output.size() && - EVP_DigestFinal_ex(hashed.get(), output.data(), nullptr) == 1; + const int context_size = EVP_MD_CTX_get_size(digest_state.get()); + finish_succeeded = + context_size > 0 && static_cast(context_size) == output_bytes.size() && + EVP_DigestFinal_ex(digest_state.get(), output_bytes.data(), nullptr) == 1; } - return openssl_outcome(finished); + return openssl_outcome(finish_succeeded); } /** Frees the context (`EVP_MD_CTX_free`); a second call does nothing. - @param hashed The state. + @param digest_state The state. */ - static void destroy(state& hashed) noexcept { hashed.reset(); } + static void destroy(state& digest_state) noexcept { digest_state.reset(); } /** - The digest of `input` at once: `init`, `update` and `finish` on a context freed before the - return. + The digest of `input_bytes` at once: `init`, `update` and `finish` on a context freed before + the return. - @param output The digest. @param input The bytes. @param options The digest's parameters. + @param output_bytes The digest. @param input_bytes The bytes. @param algorithm_options The + digest's parameters. @return Success, or OpenSSL's failure. */ [[nodiscard]] static boost::system::result one_shot( - std::span output, std::span input, - digest_options const& options) noexcept { - state hashed; - auto done = init(hashed, options); - if (done) { - done = update(hashed, input); + std::span output_bytes, std::span input_bytes, + digest_options const& algorithm_options) noexcept { + state digest_state; + auto init_result = init(digest_state, algorithm_options); + if (init_result) { + init_result = update(digest_state, input_bytes); } - if (done) { - done = finish(hashed, output); + if (init_result) { + init_result = finish(digest_state, output_bytes); } - destroy(hashed); - return done; + destroy(digest_state); + return init_result; } private: @@ -1234,18 +1242,18 @@ struct openssl_digest_engine : full_engine { // a template parameter so that digest_options, which digest.hpp defines after // this header, is read only when the engine is used. template - static bool start(EVP_MD_CTX* context, EVP_MD const* digest_algorithm, - Options const& options) noexcept { + static bool start(EVP_MD_CTX* digest_context, EVP_MD const* digest_algorithm, + Options const& algorithm_options) noexcept { if constexpr (std::is_same_v) { - std::size_t output_size = options.output_size; + std::size_t output_size = algorithm_options.output_size; std::array const size_params{ OSSL_PARAM_construct_size_t("size", &output_size), OSSL_PARAM_construct_end(), }; - return EVP_DigestInit_ex2(context, digest_algorithm, size_params.data()) == 1; + return EVP_DigestInit_ex2(digest_context, digest_algorithm, size_params.data()) == 1; } else { - static_cast(options); - return EVP_DigestInit_ex2(context, digest_algorithm, nullptr) == 1; + static_cast(algorithm_options); + return EVP_DigestInit_ex2(digest_context, digest_algorithm, nullptr) == 1; } } }; @@ -1375,11 +1383,12 @@ struct digest_engine personalisation. A template, so that it reads `digest_options`, which digest.hpp defines after this header. - @param options The options. @return Whether the options are unkeyed BLAKE2b's. + @param algorithm_options The options. @return Whether the options are unkeyed BLAKE2b's. */ template - static constexpr bool accepts(Options const& options) noexcept { - return options.key.empty() && options.salt.empty() && options.personalisation.empty(); + static constexpr bool accepts(Options const& algorithm_options) noexcept { + return algorithm_options.key.empty() && algorithm_options.salt.empty() && + algorithm_options.personalisation.empty(); } }; @@ -1444,35 +1453,38 @@ struct openssl_mac_name { /** Fetches the MAC named `mac_name`, makes a context (`EVP_MAC_CTX_new`, through OpenSSL's - allocator), and computes the tag of `input` under `key` into `output` with `ossl_params`: - `EVP_MAC_init`, `EVP_MAC_update`, then `EVP_MAC_final` once OpenSSL's size of the tag is seen to - be the output's; frees both before it returns. The thread's error queue is left as it was found. + allocator), and computes the tag of `input_bytes` under `key_bytes` into `output_bytes` with + `ossl_params`: `EVP_MAC_init`, `EVP_MAC_update`, then `EVP_MAC_final` once OpenSSL's size of the + tag is seen to be the output's; frees both before it returns. The thread's error queue is left as + it was found. @param mac_name OpenSSL's name of the MAC. - @param output The tag, its whole size. @param key The key, possibly empty (HMAC's). - @param input The message. @param ossl_params The parameters, ending with + @param output_bytes The tag, its whole size. @param key_bytes The key, possibly empty (HMAC's). + @param input_bytes The message. @param ossl_params The parameters, ending with `OSSL_PARAM_construct_end()`, which `EVP_MAC_init` sets before the key. @return Success; `errc::not_enough_memory` when the last error OpenSSL raised is an allocation's; `error::backend_failure` for any other failure. */ [[nodiscard]] inline boost::system::result openssl_mac( - char const* mac_name, std::span output, std::span key, - std::span input, OSSL_PARAM const* ossl_params) noexcept { + char const* mac_name, std::span output_bytes, + std::span key_bytes, std::span input_bytes, + OSSL_PARAM const* ossl_params) noexcept { ERR_set_mark(); EVP_MAC* mac_algorithm = EVP_MAC_fetch(nullptr, mac_name, nullptr); EVP_MAC_CTX* mac_context = mac_algorithm != nullptr ? EVP_MAC_CTX_new(mac_algorithm) : nullptr; - std::size_t written = 0; + std::size_t written_size = 0; // A key's or an input's pointer is never null: OpenSSL takes a null key for "no key given". - const bool computed = mac_context != nullptr && - EVP_MAC_init(mac_context, nonnull(key), key.size(), ossl_params) == 1 && - EVP_MAC_update(mac_context, nonnull(input), input.size()) == 1 && - EVP_MAC_CTX_get_mac_size(mac_context) == output.size() && - EVP_MAC_final(mac_context, output.data(), &written, output.size()) == 1 && - written == output.size(); + const bool call_succeeded = + mac_context != nullptr && + EVP_MAC_init(mac_context, nonnull(key_bytes), key_bytes.size(), ossl_params) == 1 && + EVP_MAC_update(mac_context, nonnull(input_bytes), input_bytes.size()) == 1 && + EVP_MAC_CTX_get_mac_size(mac_context) == output_bytes.size() && + EVP_MAC_final(mac_context, output_bytes.data(), &written_size, output_bytes.size()) == 1 && + written_size == output_bytes.size(); // The frees raise no error: the outcome read after them is the computation's. EVP_MAC_CTX_free(mac_context); EVP_MAC_free(mac_algorithm); - return openssl_outcome(computed); + return openssl_outcome(call_succeeded); } /** @@ -1492,36 +1504,36 @@ struct openssl_hmac_engine : full_engine { @param key_size The key's size. @return Whether it is taken. */ template - static constexpr bool accepts(Options const& /*options*/, std::size_t key_size, + static constexpr bool accepts(Options const& /*algorithm_options*/, std::size_t key_size, std::size_t /*output_size*/) noexcept { return !exceeds(key_size, openssl_int_max); } /** - The tag of `input` under `key`, the HMAC cut to `output.size()` bytes. + The tag of `input_bytes` under `key_bytes`, the HMAC cut to `output_bytes.size()` bytes. - @param output The tag. @param key The key. @param input The message. + @param output_bytes The tag. @param key_bytes The key. @param input_bytes The message. @return Success, or OpenSSL's failure. */ template - [[nodiscard]] static boost::system::result compute(std::span output, - std::span key, - std::span input, - Options const& /*options*/) noexcept { + [[nodiscard]] static boost::system::result compute( + std::span output_bytes, std::span key_bytes, + std::span input_bytes, Options const& /*algorithm_options*/) noexcept { constexpr std::uint64_t digest_size = mac_traits>::max_output; static_assert(digest_size <= EVP_MAX_MD_SIZE); std::array ossl_params{ openssl_text("digest", openssl_md()), OSSL_PARAM_construct_end(), }; - std::array whole{}; - auto const tag = std::span(whole).first(digest_size); - auto computed = openssl_mac("HMAC", tag, key, input, ossl_params.data()); - if (computed) { - std::copy_n(tag.begin(), output.size(), output.begin()); + std::array whole_tag{}; + auto const tag_bytes = std::span(whole_tag).first(digest_size); + auto compute_result = + openssl_mac("HMAC", tag_bytes, key_bytes, input_bytes, ossl_params.data()); + if (compute_result) { + std::copy_n(tag_bytes.begin(), output_bytes.size(), output_bytes.begin()); } - secure::erase_secret(whole); - return computed; + secure::erase_secret(whole_tag); + return compute_result; } }; @@ -1550,37 +1562,39 @@ struct openssl_kmac_engine : full_engine { Whether OpenSSL takes these options, key size and tag size. A template, so that it reads `mac_options`, which mac.hpp defines after this header. - @param options The customisation and the form. @param key_size The key's size. + @param algorithm_options The customisation and the form. @param key_size The key's size. @param output_size The tag's size. @return Whether OpenSSL takes them. */ template - static constexpr bool accepts(Options const& options, std::size_t key_size, + static constexpr bool accepts(Options const& algorithm_options, std::size_t key_size, std::size_t output_size) noexcept { return key_size >= min_key && key_size <= max_key && - options.customisation.size() <= max_customisation && output_size <= max_tag; + algorithm_options.customisation.size() <= max_customisation && + output_size <= max_tag; } /** - The tag of `input` under `key`, of `output.size()` bytes, in the form the options choose. + The tag of `input_bytes` under `key_bytes`, of `output_bytes.size()` bytes, in the form the + options choose. - @param output The tag. @param key The key. @param input The message. - @param options The customisation and the form. + @param output_bytes The tag. @param key_bytes The key. @param input_bytes The message. + @param algorithm_options The customisation and the form. @return Success, or OpenSSL's failure. */ template - [[nodiscard]] static boost::system::result compute(std::span output, - std::span key, - std::span input, - Options const& options) noexcept { - std::size_t tag_size = output.size(); - int xof_form = options.xof ? 1 : 0; + [[nodiscard]] static boost::system::result compute( + std::span output_bytes, std::span key_bytes, + std::span input_bytes, Options const& algorithm_options) noexcept { + std::size_t tag_size = output_bytes.size(); + int xof_form = algorithm_options.xof ? 1 : 0; std::array ossl_params{ OSSL_PARAM_construct_size_t("size", &tag_size), OSSL_PARAM_construct_int("xof", &xof_form), - openssl_octets("custom", options.customisation), + openssl_octets("custom", algorithm_options.customisation), OSSL_PARAM_construct_end(), }; - return openssl_mac(openssl_mac_name::value, output, key, input, ossl_params.data()); + return openssl_mac(openssl_mac_name::value, output_bytes, key_bytes, input_bytes, + ossl_params.data()); } }; @@ -1595,22 +1609,22 @@ struct openssl_kmac_engine : full_engine { template struct openssl_sized_mac_engine : full_engine { /** - The tag of `input` under `key`, of `output.size()` bytes. + The tag of `input_bytes` under `key_bytes`, of `output_bytes.size()` bytes. - @param output The tag. @param key The key. @param input The message. + @param output_bytes The tag. @param key_bytes The key. @param input_bytes The message. @return Success, or OpenSSL's failure. */ template - [[nodiscard]] static boost::system::result compute(std::span output, - std::span key, - std::span input, - Options const& /*options*/) noexcept { - std::size_t tag_size = output.size(); + [[nodiscard]] static boost::system::result compute( + std::span output_bytes, std::span key_bytes, + std::span input_bytes, Options const& /*algorithm_options*/) noexcept { + std::size_t tag_size = output_bytes.size(); std::array ossl_params{ OSSL_PARAM_construct_size_t("size", &tag_size), OSSL_PARAM_construct_end(), }; - return openssl_mac(openssl_mac_name::value, output, key, input, ossl_params.data()); + return openssl_mac(openssl_mac_name::value, output_bytes, key_bytes, input_bytes, + ossl_params.data()); } }; @@ -1770,25 +1784,26 @@ struct kbkdf_engine { SP 800-108r1, section 4.1. @param output_bytes K_OUT, its size L. @param key_bytes K_IN. - @param options The label, the context, r, and whether the separator and L are written. + @param algorithm_options The label, the context, r, and whether the separator and L are + written. @return Success, or OpenSSL's failure. */ - [[nodiscard]] static boost::system::result derive(std::span output_bytes, - std::span key_bytes, - kbkdf_options const& options) noexcept { + [[nodiscard]] static boost::system::result derive( + std::span output_bytes, std::span key_bytes, + kbkdf_options const& algorithm_options) noexcept { if constexpr (!openssl_hmac_v) { return error::backend_failure; // unreachable: the refusal has stopped the build } else { - int counter_bits = static_cast(options.counter_bits); - int use_separator = options.separator ? 1 : 0; - int use_length = options.length ? 1 : 0; + int counter_bits = static_cast(algorithm_options.counter_bits); + int use_separator = algorithm_options.separator ? 1 : 0; + int use_length = algorithm_options.length ? 1 : 0; std::array ossl_params{ openssl_text("mode", "counter"), openssl_text("mac", "HMAC"), openssl_text("digest", openssl_digest()), openssl_octets("key", key_bytes), - openssl_octets("salt", options.label), - openssl_octets("info", options.context), + openssl_octets("salt", algorithm_options.label), + openssl_octets("info", algorithm_options.context), OSSL_PARAM_construct_int("r", &counter_bits), OSSL_PARAM_construct_int("use-separator", &use_separator), OSSL_PARAM_construct_int("use-l", &use_length), diff --git a/include/webcpp/hash/backends/sodium.hpp b/include/webcpp/hash/backends/sodium.hpp index e838ed7..0ebffb4 100644 --- a/include/webcpp/hash/backends/sodium.hpp +++ b/include/webcpp/hash/backends/sodium.hpp @@ -154,13 +154,13 @@ inline void touch_sodium_canary() noexcept { */ inline bool sodium_ready() noexcept { touch_sodium_canary(); - bool const ready = sodium_init() >= 0; + bool const sodium_initialised = sodium_init() >= 0; #if defined(WEBCPP_TARGET_EMSCRIPTEN) && defined(__EMSCRIPTEN_PTHREADS__) - if (ready) { + if (sodium_initialised) { randombytes_stir(); } #endif - return ready; + return sodium_initialised; } /** @@ -192,15 +192,15 @@ struct sodium_hkdf_sha256 { /** `crypto_kdf_hkdf_sha256_extract`. - @param pseudorandom_key The PRK. @param salt The salt. @param input_key_material The input - keying material. + @param pseudorandom_key The PRK. @param salt_bytes The salt. @param input_key_material The + input keying material. @return libsodium's status, 0 on success. */ - static int extract(std::uint8_t* pseudorandom_key, std::span salt, + static int extract(std::uint8_t* pseudorandom_key, std::span salt_bytes, std::span input_key_material) noexcept { // SHA-256's extract declares the IKM nonnull; an empty span's data() may be null. - return crypto_kdf_hkdf_sha256_extract(pseudorandom_key, salt.data(), salt.size(), - nonnull(input_key_material), + return crypto_kdf_hkdf_sha256_extract(pseudorandom_key, salt_bytes.data(), + salt_bytes.size(), nonnull(input_key_material), input_key_material.size()); } @@ -231,16 +231,16 @@ struct sodium_hkdf_sha512 { /** `crypto_kdf_hkdf_sha512_extract`. - @param pseudorandom_key The PRK. @param salt The salt. @param input_key_material The input - keying material. + @param pseudorandom_key The PRK. @param salt_bytes The salt. @param input_key_material The + input keying material. @return libsodium's status, 0 on success. */ - static int extract(std::uint8_t* pseudorandom_key, std::span salt, + static int extract(std::uint8_t* pseudorandom_key, std::span salt_bytes, std::span input_key_material) noexcept { // SHA-512's extract declares no IKM nonnull; it is passed as SHA-256's is all the same, so // that the two traits are alike: a non-null pointer where null is allowed is harmless. - return crypto_kdf_hkdf_sha512_extract(pseudorandom_key, salt.data(), salt.size(), - nonnull(input_key_material), + return crypto_kdf_hkdf_sha512_extract(pseudorandom_key, salt_bytes.data(), + salt_bytes.size(), nonnull(input_key_material), input_key_material.size()); } @@ -276,18 +276,18 @@ struct sodium_hkdf_engine { RFC 5869, 2.2: PRK = HMAC-Hash(salt, IKM), by libsodium's `_extract`; an empty salt is HashLen zeros, which libsodium's hmac keys as zeros of the block, the same key. - @param salt The salt. @param input_key_material The input keying material. + @param salt_bytes The salt. @param input_key_material The input keying material. @return The PRK, or `error::backend_failure`. */ [[nodiscard]] static boost::system::result extract( - std::span salt, + std::span salt_bytes, std::span input_key_material) noexcept { // The PRK is built in the result returned and libsodium writes into it: a single return // path of the one named object, so that C++20 permits NRVO (guaranteed by no compiler: // without it a copy or move would leave a PRK behind). The failure path reassigns the // object after wiping it, and the PRK leaves this function only as the result. boost::system::result pseudorandom_key{boost::system::in_place_value}; - if (!sodium_ready() || Traits::extract(pseudorandom_key.unsafe_value().data(), salt, + if (!sodium_ready() || Traits::extract(pseudorandom_key.unsafe_value().data(), salt_bytes, input_key_material) != 0) { secure::erase_secret(std::span(&pseudorandom_key.unsafe_value(), 1)); pseudorandom_key = boost::system::result(error::backend_failure); @@ -317,16 +317,16 @@ struct sodium_hkdf_engine { /** RFC 5869, 2: HKDF-Extract into a local PRK, HKDF-Expand, and the PRK wiped. - @param output_key_material The OKM. @param salt The salt. @param input_key_material The input - keying material. + @param output_key_material The OKM. @param salt_bytes The salt. @param input_key_material The + input keying material. @param application_info The info. @return Success, or `error::backend_failure`. */ [[nodiscard]] static boost::system::result extract_and_expand( - std::span output_key_material, std::span salt, + std::span output_key_material, std::span salt_bytes, std::span input_key_material, std::span application_info) noexcept { - auto pseudorandom_key = extract(salt, input_key_material); + auto pseudorandom_key = extract(salt_bytes, input_key_material); if (!pseudorandom_key) { return pseudorandom_key.error(); } @@ -365,7 +365,7 @@ struct hkdf_engine { /** Never called: the refusal has stopped the build. */ [[nodiscard]] static boost::system::result extract( - std::span /*salt*/, + std::span /*salt_bytes*/, std::span /*input_key_material*/) noexcept { return error::backend_failure; } @@ -380,7 +380,8 @@ struct hkdf_engine { /** Never called: the refusal has stopped the build. */ [[nodiscard]] static boost::system::result extract_and_expand( - std::span /*output_key_material*/, std::span /*salt*/, + std::span /*output_key_material*/, + std::span /*salt_bytes*/, std::span /*input_key_material*/, std::span /*application_info*/) noexcept { return error::backend_failure; @@ -414,52 +415,53 @@ struct sodium_hkdf_pieces_engine { "libsodium's _update takes every slice's length"); /** - Feeds every byte of `pieces` to `state`, in slices of at most @ref slice_max bytes. + Feeds every byte of `input_pieces` to `mac_state`, in slices of at most @ref slice_max bytes. - @param state The HMAC state. @param pieces The pieces. + @param mac_state The HMAC state. @param input_pieces The pieces. @return Whether libsodium took every slice. */ - [[nodiscard]] static bool update_all(State& state, byte_pieces pieces) noexcept { + [[nodiscard]] static bool update_all(State& mac_state, byte_pieces input_pieces) noexcept { // The lambda calls update_slice, not `Update` itself: MSVC 14.3 rejects a call of the // template parameter `Update` inside a lambda ("'&' requires l-value", C2102). - bool updated = true; - for_each_slice(pieces, [&](std::span slice) { - updated = updated && update_slice(state, slice); + bool update_succeeded = true; + for_each_slice(input_pieces, [&](std::span slice_bytes) { + update_succeeded = update_succeeded && update_slice(mac_state, slice_bytes); }); - return updated; + return update_succeeded; } /** - Feeds one slice to `state`. + Feeds one slice to `mac_state`. - @param state The HMAC state. @param slice At most @ref slice_max bytes. + @param mac_state The HMAC state. @param slice_bytes At most @ref slice_max bytes. @return Whether libsodium took it. */ - [[nodiscard]] static bool update_slice(State& state, - std::span slice) noexcept { - return Update(&state, slice.data(), slice.size()) == 0; + [[nodiscard]] static bool update_slice(State& mac_state, + std::span slice_bytes) noexcept { + return Update(&mac_state, slice_bytes.data(), slice_bytes.size()) == 0; } /** RFC 5869, 2.2: PRK = HMAC-Hash(salt, piece_1 | ... | piece_n). An empty salt is HashLen zeros, which libsodium's HMAC keys as zeros of the block, the same key. - @param salt The salt. @param input_key_material The input keying material's pieces. + @param salt_bytes The salt. @param input_key_material The input keying material's pieces. @return The PRK, or `error::backend_failure`. */ [[nodiscard]] static boost::system::result extract( - std::span salt, byte_pieces input_key_material) noexcept { + std::span salt_bytes, byte_pieces input_key_material) noexcept { // The PRK is built in the result returned and libsodium writes into it: a single return // path of the one named object, so that C++20 permits NRVO (guaranteed by no compiler: // without it a copy or move would leave a PRK behind). The failure path reassigns the // object after wiping it, and the PRK leaves this function only as the result. boost::system::result pseudorandom_key{boost::system::in_place_value}; State mac_state{}; - bool const computed = sodium_ready() && Init(&mac_state, nonnull(salt), salt.size()) == 0 && - update_all(mac_state, input_key_material) && - Final(&mac_state, pseudorandom_key.unsafe_value().data()) == 0; + bool const call_succeeded = sodium_ready() && + Init(&mac_state, nonnull(salt_bytes), salt_bytes.size()) == 0 && + update_all(mac_state, input_key_material) && + Final(&mac_state, pseudorandom_key.unsafe_value().data()) == 0; secure::erase_secret(std::span(&mac_state, 1)); - if (!computed) { + if (!call_succeeded) { secure::erase_secret(std::span(&pseudorandom_key.unsafe_value(), 1)); pseudorandom_key = boost::system::result(error::backend_failure); } @@ -478,20 +480,20 @@ struct sodium_hkdf_pieces_engine { std::span output_key_material, std::span pseudorandom_key, byte_pieces application_info) noexcept { State keyed_state{}; - bool computed = sodium_ready() && - Init(&keyed_state, pseudorandom_key.data(), pseudorandom_key.size()) == 0; + bool call_succeeded = sodium_ready() && Init(&keyed_state, pseudorandom_key.data(), + pseudorandom_key.size()) == 0; digest_type t_block{}; std::size_t written_count = 0; - for (unsigned block_counter = 1; computed && written_count < output_key_material.size(); - ++block_counter) { + for (unsigned block_counter = 1; + call_succeeded && written_count < output_key_material.size(); ++block_counter) { State mac_state = keyed_state; auto const octet_value = static_cast(block_counter); - computed = + call_succeeded = (block_counter == 1 || Update(&mac_state, t_block.data(), t_block.size()) == 0) && update_all(mac_state, application_info) && Update(&mac_state, &octet_value, 1) == 0 && Final(&mac_state, t_block.data()) == 0; secure::erase_secret(std::span(&mac_state, 1)); - if (computed) { + if (call_succeeded) { std::size_t const copied_count = std::min(t_block.size(), output_key_material.size() - written_count); std::copy_n(t_block.data(), copied_count, @@ -501,7 +503,7 @@ struct sodium_hkdf_pieces_engine { } secure::erase_secret(std::span(&t_block, 1)); secure::erase_secret(std::span(&keyed_state, 1)); - if (!computed) { + if (!call_succeeded) { return error::backend_failure; } return {}; @@ -510,16 +512,16 @@ struct sodium_hkdf_pieces_engine { /** RFC 5869, 2: HKDF-Extract, then HKDF-Expand, over pieces; the PRK is wiped between them. - @param output_key_material The OKM. @param salt The salt. + @param output_key_material The OKM. @param salt_bytes The salt. @param input_key_material The input keying material's pieces. @param application_info The info's pieces. @return Success, or `error::backend_failure`. */ [[nodiscard]] static boost::system::result extract_and_expand( - std::span output_key_material, std::span salt, + std::span output_key_material, std::span salt_bytes, byte_pieces input_key_material, byte_pieces application_info) noexcept { return hkdf_pieces_extract_and_expand( - output_key_material, salt, input_key_material, application_info); + output_key_material, salt_bytes, input_key_material, application_info); } }; @@ -567,10 +569,11 @@ struct pbkdf2_engine { A pointer libsodium reads as "absent" for an empty span, the span's bytes otherwise: its salt and personalisation are 16 bytes or a null pointer. - @param bytes The span. @return Null when `bytes` is empty, else its data. + @param source_bytes The span. @return Null when `source_bytes` is empty, else its data. */ -[[nodiscard]] inline std::uint8_t const* or_null(std::span bytes) noexcept { - return bytes.empty() ? nullptr : bytes.data(); +[[nodiscard]] inline std::uint8_t const* or_null( + std::span source_bytes) noexcept { + return source_bytes.empty() ? nullptr : source_bytes.data(); } /** @@ -592,30 +595,34 @@ struct digest_engine : full_engine { /** Starts a hash: `crypto_generichash_blake2b_init_salt_personal`. - @param hashed The state. @param options The key, salt, personalisation and output size. + @param digest_state The state. @param algorithm_options The key, salt, personalisation and + output size. @return Success, or `error::backend_failure`. */ [[nodiscard]] static boost::system::result init( - state& hashed, digest_options const& options) noexcept { + state& digest_state, digest_options const& algorithm_options) noexcept { if (!sodium_ready()) { return error::backend_failure; } if (crypto_generichash_blake2b_init_salt_personal( - &hashed, or_null(options.key), options.key.size(), options.output_size, - or_null(options.salt), or_null(options.personalisation)) != 0) { + &digest_state, or_null(algorithm_options.key), algorithm_options.key.size(), + algorithm_options.output_size, or_null(algorithm_options.salt), + or_null(algorithm_options.personalisation)) != 0) { return error::backend_failure; } return {}; } /** - Absorbs `input`: `crypto_generichash_blake2b_update`. + Absorbs `input_bytes`: `crypto_generichash_blake2b_update`. - @param hashed The state. @param input The bytes. @return Success, or `error::backend_failure`. + @param digest_state The state. @param input_bytes The bytes. @return Success, or + `error::backend_failure`. */ [[nodiscard]] static boost::system::result update( - state& hashed, std::span input) noexcept { - if (crypto_generichash_blake2b_update(&hashed, input.data(), input.size()) != 0) { + state& digest_state, std::span input_bytes) noexcept { + if (crypto_generichash_blake2b_update(&digest_state, input_bytes.data(), + input_bytes.size()) != 0) { return error::backend_failure; } return {}; @@ -625,37 +632,41 @@ struct digest_engine : full_engine { Writes the digest, of the size the hash was started for (the family's guard holds it): `crypto_generichash_blake2b_final`. - @param hashed The state. @param output The digest. + @param digest_state The state. @param output_bytes The digest. @return Success, or `error::backend_failure`. */ [[nodiscard]] static boost::system::result finish( - state& hashed, std::span output) noexcept { - if (crypto_generichash_blake2b_final(&hashed, output.data(), output.size()) != 0) { + state& digest_state, std::span output_bytes) noexcept { + if (crypto_generichash_blake2b_final(&digest_state, output_bytes.data(), + output_bytes.size()) != 0) { return error::backend_failure; } return {}; } - /** Wipes the state. @param hashed The state. */ - static void destroy(state& hashed) noexcept { secure::erase_secret(std::span(&hashed, 1)); } + /** Wipes the state. @param digest_state The state. */ + static void destroy(state& digest_state) noexcept { + secure::erase_secret(std::span(&digest_state, 1)); + } /** - The digest of `input` at once: `crypto_generichash_blake2b_salt_personal`, whose output size - is `output.size()`, equal to the options' (the family's guard). + The digest of `input_bytes` at once: `crypto_generichash_blake2b_salt_personal`, whose output + size is `output_bytes.size()`, equal to the options' (the family's guard). - @param output The digest. @param input The bytes. @param options The key, salt and - personalisation. + @param output_bytes The digest. @param input_bytes The bytes. @param algorithm_options The key, + salt and personalisation. @return Success, or `error::backend_failure`. */ [[nodiscard]] static boost::system::result one_shot( - std::span output, std::span input, - digest_options const& options) noexcept { + std::span output_bytes, std::span input_bytes, + digest_options const& algorithm_options) noexcept { if (!sodium_ready()) { return error::backend_failure; } if (crypto_generichash_blake2b_salt_personal( - output.data(), output.size(), input.data(), input.size(), or_null(options.key), - options.key.size(), or_null(options.salt), or_null(options.personalisation)) != 0) { + output_bytes.data(), output_bytes.size(), input_bytes.data(), input_bytes.size(), + or_null(algorithm_options.key), algorithm_options.key.size(), + or_null(algorithm_options.salt), or_null(algorithm_options.personalisation)) != 0) { return error::backend_failure; } return {}; @@ -687,40 +698,44 @@ struct sodium_incremental_engine : full_engine { using state = State; /** - Absorbs `input`. + Absorbs `input_bytes`. - @param hashed The state. @param input The bytes. @return Success, or `error::backend_failure`. + @param digest_state The state. @param input_bytes The bytes. @return Success, or + `error::backend_failure`. */ [[nodiscard]] static boost::system::result update( - state& hashed, std::span input) noexcept { - if (Update(&hashed, nonnull(input), input.size()) != 0) { + state& digest_state, std::span input_bytes) noexcept { + if (Update(&digest_state, nonnull(input_bytes), input_bytes.size()) != 0) { return error::backend_failure; } return {}; } - /** Wipes the state. @param hashed The state. */ - static void destroy(state& hashed) noexcept { secure::erase_secret(std::span(&hashed, 1)); } + /** Wipes the state. @param digest_state The state. */ + static void destroy(state& digest_state) noexcept { + secure::erase_secret(std::span(&digest_state, 1)); + } /** - The digest of `input` at once, on a state of this frame, wiped before the return. + The digest of `input_bytes` at once, on a state of this frame, wiped before the return. - @param output The digest. @param input The bytes. @param options The tag's options. + @param output_bytes The digest. @param input_bytes The bytes. @param algorithm_options The + tag's options. @return Success, or `error::backend_failure`. */ [[nodiscard]] static boost::system::result one_shot( - std::span output, std::span input, - digest_options const& options) noexcept { - state hashed{}; - auto done = Engine::init(hashed, options); - if (done) { - done = update(hashed, input); + std::span output_bytes, std::span input_bytes, + digest_options const& algorithm_options) noexcept { + state digest_state{}; + auto init_result = Engine::init(digest_state, algorithm_options); + if (init_result) { + init_result = update(digest_state, input_bytes); } - if (done) { - done = Engine::finish(hashed, output); + if (init_result) { + init_result = Engine::finish(digest_state, output_bytes); } - destroy(hashed); - return done; + destroy(digest_state); + return init_result; } private: @@ -749,17 +764,17 @@ struct sodium_fixed_digest_engine /** Starts a hash. - @param hashed The state. @return Success, or `error::backend_failure`. + @param digest_state The state. @return Success, or `error::backend_failure`. */ [[nodiscard]] static boost::system::result init( - State& hashed, digest_options const& /*options*/) noexcept { + State& digest_state, digest_options const& /*algorithm_options*/) noexcept { // The family's size is libsodium's, so that the guard passes exactly what _final writes. static_assert(digest_traits::min_output(digest_options{}) == Size && digest_traits::max_output(digest_options{}) == Size); if (!sodium_ready()) { return error::backend_failure; } - if (Init(&hashed) != 0) { + if (Init(&digest_state) != 0) { return error::backend_failure; } return {}; @@ -768,12 +783,13 @@ struct sodium_fixed_digest_engine /** Writes the digest. - @param hashed The state. @param output The digest, of `Size` bytes (the family's guard). + @param digest_state The state. @param output_bytes The digest, of `Size` bytes (the family's + guard). @return Success, or `error::backend_failure`. */ [[nodiscard]] static boost::system::result finish( - State& hashed, std::span output) noexcept { - if (Final(&hashed, output.data()) != 0) { + State& digest_state, std::span output_bytes) noexcept { + if (Final(&digest_state, output_bytes.data()) != 0) { return error::backend_failure; } return {}; @@ -831,13 +847,13 @@ struct sodium_xof_engine The domain byte the sponge pads with: TurboSHAKE's option `domain`, or SHAKE's standard byte, 0x1F, for a tag whose options have no domain. - @param options The tag's options. + @param algorithm_options The tag's options. @return The domain byte, D of RFC 9861 for TurboSHAKE. */ static constexpr unsigned char domain_of( - [[maybe_unused]] digest_options const& options) noexcept { - if constexpr (requires { options.domain; }) { - return options.domain; + [[maybe_unused]] digest_options const& algorithm_options) noexcept { + if constexpr (requires { algorithm_options.domain; }) { + return algorithm_options.domain; } else { return StandardDomain; } @@ -846,31 +862,31 @@ struct sodium_xof_engine /** Starts a hash with the options' domain byte. - @param hashed The state. @param options The tag's options. + @param digest_state The state. @param algorithm_options The tag's options. @return Success, or `error::backend_failure`. */ [[nodiscard]] static boost::system::result init( - State& hashed, digest_options const& options) noexcept { + State& digest_state, digest_options const& algorithm_options) noexcept { // SHAKE's and TurboSHAKE's standard byte, RFC 9861's default, is libsodium's. static_assert(StandardDomain == 0x1F); if (!sodium_ready()) { return error::backend_failure; } - if (Init(&hashed, domain_of(options)) != 0) { + if (Init(&digest_state, domain_of(algorithm_options)) != 0) { return error::backend_failure; } return {}; } /** - Writes `output.size()` bytes of the output stream. + Writes `output_bytes.size()` bytes of the output stream. - @param hashed The state. @param output The output, of any size from 1 byte. + @param digest_state The state. @param output_bytes The output, of any size from 1 byte. @return Success, or `error::backend_failure`. */ [[nodiscard]] static boost::system::result finish( - State& hashed, std::span output) noexcept { - if (Squeeze(&hashed, output.data(), output.size()) != 0) { + State& digest_state, std::span output_bytes) noexcept { + if (Squeeze(&digest_state, output_bytes.data(), output_bytes.size()) != 0) { return error::backend_failure; } return {}; @@ -932,34 +948,35 @@ template struct sodium_hmac_engine : full_engine { /** - The tag of `input` under `key`. + The tag of `input_bytes` under `key_bytes`. - @param output The tag, 10 bytes to the digest's size (the family's guard). @param key The key, - of any size. @param input The message. + @param output_bytes The tag, 10 bytes to the digest's size (the family's guard). @param + key_bytes The key, of any size. @param input_bytes The message. @return Success, or `error::backend_failure`. */ [[nodiscard]] static boost::system::result compute( - std::span output, std::span key, - std::span input, - mac_options> const& /*options*/) noexcept { + std::span output_bytes, std::span key_bytes, + std::span input_bytes, + mac_options> const& /*algorithm_options*/) noexcept { // The family's longest tag is libsodium's digest. Checked here, where mac.hpp's traits are // complete whatever the order of includes. static_assert(mac_traits>::max_output == Size); if (!sodium_ready()) { return error::backend_failure; } - State keyed{}; + State keyed_state{}; std::array digest_bytes{}; - bool const whole = output.size() == Size; - bool const computed = Init(&keyed, key.data(), key.size()) == 0 && - Update(&keyed, nonnull(input), input.size()) == 0 && - Final(&keyed, whole ? output.data() : digest_bytes.data()) == 0; - if (computed && !whole) { - std::copy_n(digest_bytes.begin(), output.size(), output.begin()); + bool const whole_output = output_bytes.size() == Size; + bool const call_succeeded = + Init(&keyed_state, key_bytes.data(), key_bytes.size()) == 0 && + Update(&keyed_state, nonnull(input_bytes), input_bytes.size()) == 0 && + Final(&keyed_state, whole_output ? output_bytes.data() : digest_bytes.data()) == 0; + if (call_succeeded && !whole_output) { + std::copy_n(digest_bytes.begin(), output_bytes.size(), output_bytes.begin()); } secure::erase_secret(digest_bytes); - secure::erase_secret(std::span(&keyed, 1)); - if (!computed) { + secure::erase_secret(std::span(&keyed_state, 1)); + if (!call_succeeded) { return error::backend_failure; } return {}; @@ -1004,15 +1021,17 @@ template struct sodium_siphash_engine : full_engine { /** - The tag of `input` under `key`. + The tag of `input_bytes` under `key_bytes`. - @param output The tag, of the tag's size (the family's guard). @param key The 16-byte key. - @param input The message. + @param output_bytes The tag, of the tag's size (the family's guard). @param key_bytes The + 16-byte key. + @param input_bytes The message. @return Success, or `error::backend_failure`. */ [[nodiscard]] static boost::system::result compute( - std::span output, std::span key, - std::span input, mac_options const& /*options*/) noexcept { + std::span output_bytes, std::span key_bytes, + std::span input_bytes, + mac_options const& /*algorithm_options*/) noexcept { // The family's sizes are libsodium's, so that its guards pass exactly what libsodium // takes. Checked here, where mac.hpp's traits are complete whatever the order of includes. static_assert(mac_traits::min_output == TagSize && @@ -1021,7 +1040,8 @@ struct sodium_siphash_engine : full_engine { if (!sodium_ready()) { return error::backend_failure; } - if (Function(output.data(), input.data(), input.size(), key.data()) != 0) { + if (Function(output_bytes.data(), input_bytes.data(), input_bytes.size(), + key_bytes.data()) != 0) { return error::backend_failure; } return {}; @@ -1059,15 +1079,16 @@ struct mac_engine template struct sodium_keyed_blake2b_engine : full_engine { /** - The tag of `input` under `key`. + The tag of `input_bytes` under `key_bytes`. - @param output The tag, 1 to 64 bytes (the family's guard). @param key The key, 1 to 64 bytes - (the family's guard). @param input The message. + @param output_bytes The tag, 1 to 64 bytes (the family's guard). @param key_bytes The key, 1 to + 64 bytes (the family's guard). @param input_bytes The message. @return Success, or `error::backend_failure`. */ [[nodiscard]] static boost::system::result compute( - std::span output, std::span key, - std::span input, mac_options const& /*options*/) noexcept { + std::span output_bytes, std::span key_bytes, + std::span input_bytes, + mac_options const& /*algorithm_options*/) noexcept { // The family's sizes are libsodium's bounds, so that libsodium never refuses what its // guards pass. Checked here, where mac.hpp's traits are complete whatever the order of // includes. @@ -1079,13 +1100,16 @@ struct sodium_keyed_blake2b_engine : full_engine { if (!sodium_ready()) { return error::backend_failure; } - crypto_generichash_blake2b_state keyed{}; - bool const computed = - crypto_generichash_blake2b_init(&keyed, key.data(), key.size(), output.size()) == 0 && - crypto_generichash_blake2b_update(&keyed, nonnull(input), input.size()) == 0 && - crypto_generichash_blake2b_final(&keyed, output.data(), output.size()) == 0; - secure::erase_secret(std::span(&keyed, 1)); - if (!computed) { + crypto_generichash_blake2b_state keyed_state{}; + bool const call_succeeded = + crypto_generichash_blake2b_init(&keyed_state, key_bytes.data(), key_bytes.size(), + output_bytes.size()) == 0 && + crypto_generichash_blake2b_update(&keyed_state, nonnull(input_bytes), + input_bytes.size()) == 0 && + crypto_generichash_blake2b_final(&keyed_state, output_bytes.data(), + output_bytes.size()) == 0; + secure::erase_secret(std::span(&keyed_state, 1)); + if (!call_succeeded) { return error::backend_failure; } return {}; @@ -1109,17 +1133,17 @@ struct blake2b_subkey_engine { The subkey, by `crypto_kdf_blake2b_derive_from_key`. @param output_bytes The subkey, 16 to 64 bytes. @param master_key The 32-byte master key. - @param subkey_id The subkey's id. @param context The 8-byte context. + @param subkey_id The subkey's id. @param context_bytes The 8-byte context. @return Success, or `error::backend_failure`. */ [[nodiscard]] static boost::system::result derive( std::span output_bytes, std::span master_key, - std::uint64_t subkey_id, std::span context) noexcept { + std::uint64_t subkey_id, std::span context_bytes) noexcept { if (!sodium_ready()) { return error::backend_failure; } // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): libsodium types it char - auto const* const context_chars = reinterpret_cast(context.data()); + auto const* const context_chars = reinterpret_cast(context_bytes.data()); if (crypto_kdf_blake2b_derive_from_key(output_bytes.data(), output_bytes.size(), subkey_id, context_chars, master_key.data()) != 0) { return error::backend_failure; @@ -1201,24 +1225,26 @@ struct sodium_argon2_engine { The tag, by libsodium, which computes it in a buffer of its own that it wipes; webcpp holds no copy of a secret. - @param output The tag. @param password The password. @param salt The 16-byte salt. - @param parameters The passes and the memory in KiB, within `limits`. + @param output_bytes The tag. @param password_bytes The password. @param salt_bytes The 16-byte + salt. + @param cost_parameters The passes and the memory in KiB, within `limits`. @return Success, `errc::not_enough_memory` or `error::backend_failure`. */ [[nodiscard]] static boost::system::result derive( - std::span output, std::span password, - std::span salt, argon2_parameters const& parameters) noexcept { + std::span output_bytes, std::span password_bytes, + std::span salt_bytes, + argon2_parameters const& cost_parameters) noexcept { if (!sodium_ready()) { return error::backend_failure; } errno = 0; // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): libsodium types it char - auto const* const password_chars = reinterpret_cast(nonnull(password)); + auto const* const password_chars = reinterpret_cast(nonnull(password_bytes)); // limits holds the memory to MaxMemory, a size_t, so the bytes never wrap. int const status_code = - Hash(output.data(), output.size(), password_chars, password.size(), salt.data(), - parameters.passes, std::size_t{parameters.memory_kibibytes} * argon2id_memory_unit, - Algorithm); + Hash(output_bytes.data(), output_bytes.size(), password_chars, password_bytes.size(), + salt_bytes.data(), cost_parameters.passes, + std::size_t{cost_parameters.memory_kibibytes} * argon2id_memory_unit, Algorithm); return sodium_pwhash_status(status_code, errno); } }; diff --git a/include/webcpp/hash/backends/webcrypto.hpp b/include/webcpp/hash/backends/webcrypto.hpp index aee7b7f..37c4fa1 100644 --- a/include/webcpp/hash/backends/webcrypto.hpp +++ b/include/webcpp/hash/backends/webcrypto.hpp @@ -215,75 +215,80 @@ using io_context_executor_with = webcpp::asio_backend::io_context::basic_executor_type, Bits>; /** - Whether the type-erased `executor` holds an `io_context`'s executor of one of the bits + Whether the type-erased `completion_executor` holds an `io_context`'s executor of one of the bits `Bits...`, or a strand over one. - @param executor The type-erased executor. @return Whether its target is one. + @param completion_executor The type-erased executor. @return Whether its target is one. */ template -bool targets_io_context(Executor const& executor, - std::integer_sequence /*bits*/) noexcept { - return ((executor.template target>() != nullptr) || ...) || - ((executor.template target>>() != +bool targets_io_context(Executor const& completion_executor, + std::integer_sequence /*bit_sequence*/) noexcept { + return ((completion_executor.template target>() != nullptr) || + ...) || + ((completion_executor + .template target>>() != nullptr) || ...); } /** - Whether `executor` completes on an `io_context` (ruling R73), whatever its form: a concrete - executor whose context is one (any allocator, any property); a strand, through the executor it - wraps, recursively; a type-erased executor (`any_io_executor`) that holds an `io_context`'s - executor with the standard allocator and any property, a strand over one, or a type-erased - strand, recursively. Anything else is answered false, among it, behind type erasure, an + Whether `completion_executor` completes on an `io_context` (ruling R73), whatever its form: a + concrete executor whose context is one (any allocator, any property); a strand, through the + executor it wraps, recursively; a type-erased executor (`any_io_executor`) that holds an + `io_context`'s executor with the standard allocator and any property, a strand over one, or a + type-erased strand, recursively. Anything else is answered false, among it, behind type erasure, an `io_context`'s executor rebound to another allocator and a concrete strand of a concrete strand - of one (`make_strand(make_strand(executor))`), whose types the erasure hides: the operation would - await a promise on a context it cannot tell runs the JavaScript event loop. + of one (`make_strand(make_strand(completion_executor))`), whose types the erasure hides: the + operation would await a promise on a context it cannot tell runs the JavaScript event loop. - @param executor The executor. @return Whether it completes on an io_context. + @param completion_executor The executor. @return Whether it completes on an io_context. */ template -bool completes_on_io_context(Executor const& executor) noexcept { - constexpr auto kind = webcrypto_context_of; - if constexpr (kind == webcrypto_context::io_context) { +bool completes_on_io_context(Executor const& completion_executor) noexcept { + constexpr auto context_kind = webcrypto_context_of; + if constexpr (context_kind == webcrypto_context::io_context) { return true; - } else if constexpr (kind == webcrypto_context::erased && - requires { executor.get_inner_executor(); }) { - return completes_on_io_context(executor.get_inner_executor()); - } else if constexpr (kind == webcrypto_context::erased && - requires { executor.template target(); }) { + } else if constexpr (context_kind == webcrypto_context::erased && + requires { completion_executor.get_inner_executor(); }) { + return completes_on_io_context(completion_executor.get_inner_executor()); + } else if constexpr (context_kind == webcrypto_context::erased && requires { + completion_executor.template target(); + }) { // Type-erased strands, unwrapped one after the other, then the executor they wrap. using strand = webcpp::asio::strand; - auto const* const nested = executor.template target(); - if (nested == nullptr) { - return targets_io_context(executor, std::make_integer_sequence{}); + auto const* const nested_strand = completion_executor.template target(); + if (nested_strand == nullptr) { + return targets_io_context(completion_executor, + std::make_integer_sequence{}); } - webcpp::asio::any_io_executor inner = nested->get_inner_executor(); - for (auto const* deeper = inner.template target(); deeper != nullptr; - deeper = inner.template target()) { - inner = deeper->get_inner_executor(); + webcpp::asio::any_io_executor inner_executor = nested_strand->get_inner_executor(); + for (auto const* deeper_strand = inner_executor.template target(); + deeper_strand != nullptr; deeper_strand = inner_executor.template target()) { + inner_executor = deeper_strand->get_inner_executor(); } - return targets_io_context(inner, std::make_integer_sequence{}); + return targets_io_context(inner_executor, std::make_integer_sequence{}); } else { return false; } } /** - Whether WebCrypto's promise can settle where `executor` completes (ruling R73): the executor's - context must be an `io_context`, checked at compile time for a concrete executor (another context - refuses with a `static_assert`) and at run time for a type-erased one, as @ref + Whether WebCrypto's promise can settle where `completion_executor` completes (ruling R73): the + executor's context must be an `io_context`, checked at compile time for a concrete executor + (another context refuses with a `static_assert`) and at run time for a type-erased one, as @ref completes_on_io_context says. That the `io_context` runs on the calling thread, whose JavaScript event loop settles the promise, is the program's duty: it cannot be checked. - @param executor The executor the call was given. @return Whether its context is an io_context. + @param completion_executor The executor the call was given. @return Whether its context is an + io_context. */ template -bool webcrypto_executor_accepted(Executor const& executor) noexcept { +bool webcrypto_executor_accepted(Executor const& completion_executor) noexcept { // clang-format off static_assert(webcrypto_context_of != webcrypto_context::other, "webcpp::hash: backends::webcrypto completes through an io_context run on the calling thread, whose run returns to the JavaScript event loop where WebCrypto's promise settles: pass that io_context's executor, not a thread_pool's."); // clang-format on - return completes_on_io_context(executor); + return completes_on_io_context(completion_executor); } /** @@ -292,33 +297,33 @@ bool webcrypto_executor_accepted(Executor const& executor) noexcept { @return The `SubtleCrypto` object. */ inline emscripten::val subtle_crypto() { - auto const crypto = emscripten::val::global("crypto"); - if (crypto.isUndefined() || crypto.isNull()) { + auto const crypto_object = emscripten::val::global("crypto"); + if (crypto_object.isUndefined() || crypto_object.isNull()) { return emscripten::val::undefined(); } - return crypto["subtle"]; + return crypto_object["subtle"]; } /** - A JavaScript copy of `bytes`, a `Uint8Array` over an `ArrayBuffer` of its own: WebCrypto takes - no view of the program's memory, which a build with threads shares. + A JavaScript copy of `source_bytes`, a `Uint8Array` over an `ArrayBuffer` of its own: WebCrypto + takes no view of the program's memory, which a build with threads shares. - @param bytes The bytes. @return The copy. + @param source_bytes The bytes. @return The copy. */ -inline emscripten::val webcrypto_bytes(std::span bytes) { - return emscripten::val(emscripten::typed_memory_view(bytes.size(), bytes.data())) +inline emscripten::val webcrypto_bytes(std::span source_bytes) { + return emscripten::val(emscripten::typed_memory_view(source_bytes.size(), source_bytes.data())) .call("slice"); } /** The usages of an imported key: one string, `"sign"` or `"deriveBits"`. - @param usage The usage. @return A JavaScript array of it. + @param key_usage The usage. @return A JavaScript array of it. */ -inline emscripten::val webcrypto_usages(char const* usage) { - auto usages = emscripten::val::array(); - usages.set(0, emscripten::val(usage)); - return usages; +inline emscripten::val webcrypto_usages(char const* key_usage) { + auto usage_array = emscripten::val::array(); + usage_array.set(0, emscripten::val(key_usage)); + return usage_array; } /** `crypto.subtle.digest(hash, input)`: one promise, of the digest. */ @@ -331,15 +336,15 @@ struct webcrypto_digest_request { /** The call has one promise. */ static constexpr bool two_promises = false; - /** The digest's promise. @param subtle `crypto.subtle`. @return The promise. */ - [[nodiscard]] emscripten::val first(emscripten::val const& subtle) const { - return subtle.call("digest", emscripten::val(hash), - webcrypto_bytes(input)); + /** The digest's promise. @param subtle_object `crypto.subtle`. @return The promise. */ + [[nodiscard]] emscripten::val first(emscripten::val const& subtle_object) const { + return subtle_object.call("digest", emscripten::val(hash), + webcrypto_bytes(input)); } /** Never called: the call has one promise. @return `undefined`. */ - [[nodiscard]] static emscripten::val second(emscripten::val const& /*subtle*/, - emscripten::val const& /*key*/) { + [[nodiscard]] static emscripten::val second(emscripten::val const& /*subtle_object*/, + emscripten::val const& /*key_bytes*/) { return emscripten::val::undefined(); } }; @@ -360,26 +365,26 @@ struct webcrypto_hmac_request { /** The call has two promises: the key, then the tag. */ static constexpr bool two_promises = true; - /** The key's promise. @param subtle `crypto.subtle`. @return The promise. */ - [[nodiscard]] emscripten::val first(emscripten::val const& subtle) const { - std::array const zero{}; - auto algorithm = emscripten::val::object(); - algorithm.set("name", emscripten::val("HMAC")); - algorithm.set("hash", emscripten::val(hash)); - return subtle.call( + /** The key's promise. @param subtle_object `crypto.subtle`. @return The promise. */ + [[nodiscard]] emscripten::val first(emscripten::val const& subtle_object) const { + std::array const zero_byte{}; + auto algorithm_object = emscripten::val::object(); + algorithm_object.set("name", emscripten::val("HMAC")); + algorithm_object.set("hash", emscripten::val(hash)); + return subtle_object.call( "importKey", emscripten::val("raw"), - webcrypto_bytes(key.empty() ? std::span(zero) : key), algorithm, - emscripten::val(false), webcrypto_usages("sign")); + webcrypto_bytes(key.empty() ? std::span(zero_byte) : key), + algorithm_object, emscripten::val(false), webcrypto_usages("sign")); } /** - The tag's promise. @param subtle `crypto.subtle`. @param imported The key. + The tag's promise. @param subtle_object `crypto.subtle`. @param imported_key The key. @return The promise. */ - [[nodiscard]] emscripten::val second(emscripten::val const& subtle, - emscripten::val const& imported) const { - return subtle.call("sign", emscripten::val("HMAC"), imported, - webcrypto_bytes(input)); + [[nodiscard]] emscripten::val second(emscripten::val const& subtle_object, + emscripten::val const& imported_key) const { + return subtle_object.call("sign", emscripten::val("HMAC"), imported_key, + webcrypto_bytes(input)); } }; @@ -402,26 +407,26 @@ struct webcrypto_hkdf_request { /** The call has two promises: the key, then the bits. */ static constexpr bool two_promises = true; - /** The key's promise. @param subtle `crypto.subtle`. @return The promise. */ - [[nodiscard]] emscripten::val first(emscripten::val const& subtle) const { - return subtle.call( + /** The key's promise. @param subtle_object `crypto.subtle`. @return The promise. */ + [[nodiscard]] emscripten::val first(emscripten::val const& subtle_object) const { + return subtle_object.call( "importKey", emscripten::val("raw"), webcrypto_bytes(input_key_material), emscripten::val("HKDF"), emscripten::val(false), webcrypto_usages("deriveBits")); } /** - The bits' promise. @param subtle `crypto.subtle`. @param imported The key. + The bits' promise. @param subtle_object `crypto.subtle`. @param imported_key The key. @return The promise. */ - [[nodiscard]] emscripten::val second(emscripten::val const& subtle, - emscripten::val const& imported) const { - auto algorithm = emscripten::val::object(); - algorithm.set("name", emscripten::val("HKDF")); - algorithm.set("hash", emscripten::val(hash)); - algorithm.set("salt", webcrypto_bytes(salt)); - algorithm.set("info", webcrypto_bytes(application_info)); - return subtle.call("deriveBits", algorithm, imported, - emscripten::val(bits)); + [[nodiscard]] emscripten::val second(emscripten::val const& subtle_object, + emscripten::val const& imported_key) const { + auto algorithm_object = emscripten::val::object(); + algorithm_object.set("name", emscripten::val("HKDF")); + algorithm_object.set("hash", emscripten::val(hash)); + algorithm_object.set("salt", webcrypto_bytes(salt)); + algorithm_object.set("info", webcrypto_bytes(application_info)); + return subtle_object.call("deriveBits", algorithm_object, imported_key, + emscripten::val(bits)); } }; @@ -444,26 +449,26 @@ struct webcrypto_pbkdf2_request { /** The call has two promises: the key, then the bits. */ static constexpr bool two_promises = true; - /** The key's promise. @param subtle `crypto.subtle`. @return The promise. */ - [[nodiscard]] emscripten::val first(emscripten::val const& subtle) const { - return subtle.call("importKey", emscripten::val("raw"), - webcrypto_bytes(password), emscripten::val("PBKDF2"), - emscripten::val(false), webcrypto_usages("deriveBits")); + /** The key's promise. @param subtle_object `crypto.subtle`. @return The promise. */ + [[nodiscard]] emscripten::val first(emscripten::val const& subtle_object) const { + return subtle_object.call( + "importKey", emscripten::val("raw"), webcrypto_bytes(password), + emscripten::val("PBKDF2"), emscripten::val(false), webcrypto_usages("deriveBits")); } /** - The bits' promise. @param subtle `crypto.subtle`. @param imported The key. + The bits' promise. @param subtle_object `crypto.subtle`. @param imported_key The key. @return The promise. */ - [[nodiscard]] emscripten::val second(emscripten::val const& subtle, - emscripten::val const& imported) const { - auto algorithm = emscripten::val::object(); - algorithm.set("name", emscripten::val("PBKDF2")); - algorithm.set("hash", emscripten::val(hash)); - algorithm.set("salt", webcrypto_bytes(salt)); - algorithm.set("iterations", emscripten::val(iterations)); - return subtle.call("deriveBits", algorithm, imported, - emscripten::val(bits)); + [[nodiscard]] emscripten::val second(emscripten::val const& subtle_object, + emscripten::val const& imported_key) const { + auto algorithm_object = emscripten::val::object(); + algorithm_object.set("name", emscripten::val("PBKDF2")); + algorithm_object.set("hash", emscripten::val(hash)); + algorithm_object.set("salt", webcrypto_bytes(salt)); + algorithm_object.set("iterations", emscripten::val(iterations)); + return subtle_object.call("deriveBits", algorithm_object, imported_key, + emscripten::val(bits)); } }; @@ -487,78 +492,84 @@ template class webcrypto_operation { public: /** - The operation of `request` into `output`. + The operation of `operation_request` into `output_bytes`. - @param executor The io_context's executor. @param output The output. - @param produced The bytes WebCrypto gives: `output`'s size, or an HMAC's whole tag, which - `output` takes the first bytes of. @param request The call. + @param completion_executor The io_context's executor. @param output_bytes The output. + @param produced_size The bytes WebCrypto gives: `output_bytes`'s size, or an HMAC's whole tag, + which `output_bytes` takes the first bytes of. @param operation_request The call. */ - webcrypto_operation(Executor executor, std::span output, std::size_t produced, - Request const& request) - : executor_(std::move(executor)), output_(output), produced_(produced), request_(request) {} + webcrypto_operation(Executor completion_executor, std::span output_bytes, + std::size_t produced_size, Request const& operation_request) + : executor_(std::move(completion_executor)), + output_(output_bytes), + produced_(produced_size), + request_(operation_request) {} /** Starts the operation: the first promise. - @param self The composed operation. + @param operation_self The composed operation. */ template - void operator()(Self& self) { - self.reset_cancellation_state(webcpp::asio::enable_partial_cancellation()); - // A copy: the wait moves `self`, and this operation with it, before it reads the executor. - auto const executor = executor_; - webcpp::asio::browser::async_await(executor, request_.first(subtle_crypto()), - std::move(self)); + void operator()(Self& operation_self) { + operation_self.reset_cancellation_state(webcpp::asio::enable_partial_cancellation()); + // A copy: the wait moves `operation_self`, and this operation with it, before it reads the + // executor. + auto const completion_executor = executor_; + webcpp::asio::browser::async_await(completion_executor, request_.first(subtle_crypto()), + std::move(operation_self)); } /** A promise has settled, been rejected, or been cancelled: the next promise, or the completion. - @param self The composed operation. @param code The wait's error. - @param value The promise's value: the imported key, or the result's `ArrayBuffer`. + @param operation_self The composed operation. @param completion_code The wait's error. + @param promise_value The promise's value: the imported key, or the result's `ArrayBuffer`. */ template - void operator()(Self& self, boost::system::error_code code, emscripten::val const& value) { + void operator()(Self& operation_self, boost::system::error_code completion_code, + emscripten::val const& promise_value) { if constexpr (Request::two_promises) { - if (!code && !second_) { + if (!completion_code && !second_) { second_ = true; - if (self.cancelled() != webcpp::asio::cancellation_type::none) { - self.complete(fail(webcpp::asio::error::operation_aborted)); + if (operation_self.cancelled() != webcpp::asio::cancellation_type::none) { + operation_self.complete(fail(webcpp::asio::error::operation_aborted)); return; } - auto const executor = executor_; - webcpp::asio::browser::async_await( - executor, request_.second(subtle_crypto(), value), std::move(self)); + auto const completion_executor = executor_; + webcpp::asio::browser::async_await(completion_executor, + request_.second(subtle_crypto(), promise_value), + std::move(operation_self)); return; } } - if (code) { - self.complete(fail(code == webcpp::asio::error::operation_aborted - ? code - : boost::system::error_code(error::backend_failure))); + if (completion_code) { + operation_self.complete(fail(completion_code == webcpp::asio::error::operation_aborted + ? completion_code + : boost::system::error_code(error::backend_failure))); return; } - self.complete(copy(value)); + operation_self.complete(copy(promise_value)); } private: // The output zeroed, with the completion's error. - boost::system::error_code fail(boost::system::error_code code) noexcept { + boost::system::error_code fail(boost::system::error_code failure_code) noexcept { secure::erase_secret(output_); - return code; + return failure_code; } // The result's bytes into the output: an ArrayBuffer of exactly `produced_` bytes, else // WebCrypto answered something else, a backend failure. - boost::system::error_code copy(emscripten::val const& result) { - if (!result.instanceof(emscripten::val::global("ArrayBuffer")) || - result["byteLength"].as() != produced_) { + boost::system::error_code copy(emscripten::val const& promise_result) { + if (!promise_result.instanceof(emscripten::val::global("ArrayBuffer")) || + promise_result["byteLength"].as() != produced_) { return fail(error::backend_failure); } - auto const bytes = emscripten::val::global("Uint8Array") - .new_(result, 0, static_cast(output_.size())); + auto const result_bytes = emscripten::val::global("Uint8Array") + .new_(promise_result, 0, static_cast(output_.size())); emscripten::val(emscripten::typed_memory_view(output_.size(), output_.data())) - .call("set", bytes); + .call("set", result_bytes); return {}; } @@ -574,39 +585,43 @@ class webcrypto_operation { check (ruling R73), then `crypto.subtle`'s presence. The output is untouched by a guard's refusal and the executor's, and zeroed when WebCrypto is missing (`backend_failure`). - @param executor The io_context's executor. @param output The output. - @param guarded The guards' verdict. @return The refusal's error, or none. + @param completion_executor The io_context's executor. @param output_bytes The output. + @param guard_result The guards' verdict. @return The refusal's error, or none. */ template -boost::system::error_code webcrypto_refusal(Executor const& executor, - std::span output, - boost::system::result const& guarded) { - if (!guarded) { - return guarded.error(); +boost::system::error_code webcrypto_refusal(Executor const& completion_executor, + std::span output_bytes, + boost::system::result const& guard_result) { + if (!guard_result) { + return guard_result.error(); } - if (!webcrypto_executor_accepted(executor)) { + if (!webcrypto_executor_accepted(completion_executor)) { return error::invalid_parameters; } if (subtle_crypto().isUndefined()) { // The backend's failure: the JavaScript runtime has no WebCrypto. The output is zeroed, as // every backend's failure leaves it. - secure::erase_secret(output); + secure::erase_secret(output_bytes); return error::backend_failure; } return {}; } /** - Posts a refusal to the handler's associated executor (`executor` by default). + Posts a refusal to the handler's associated executor (`completion_executor` by default). - @param handler The completion handler. @param executor The io_context's executor. - @param refusal The refusal's error. + @param completion_handler The completion handler. @param completion_executor The io_context's + executor. + @param refusal_code The refusal's error. */ template -void post_webcrypto_refusal(Handler&& handler, Executor const& executor, - boost::system::error_code refusal) { - auto const target = webcpp::asio::get_associated_executor(handler, executor); - webcpp::asio::post(target, webcpp::asio::append(std::forward(handler), refusal)); +void post_webcrypto_refusal(Handler&& completion_handler, Executor const& completion_executor, + boost::system::error_code refusal_code) { + auto const target_executor = + webcpp::asio::get_associated_executor(completion_handler, completion_executor); + webcpp::asio::post( + target_executor, + webcpp::asio::append(std::forward(completion_handler), refusal_code)); } /** @@ -618,40 +633,46 @@ struct webcrypto_initiation { /** Refuses or starts the call. - @param handler The completion handler. @param executor The io_context's executor. - @param output The output. @param produced The bytes WebCrypto gives. - @param request The call. @param guarded The guards' verdict. + @param completion_handler The completion handler. @param completion_executor The io_context's + executor. + @param output_bytes The output. @param produced_size The bytes WebCrypto gives. + @param operation_request The call. @param guard_result The guards' verdict. */ template - void operator()(Handler&& handler, Executor const& executor, std::span output, - std::size_t produced, Request const& request, - boost::system::result const& guarded) const { - auto const refusal = webcrypto_refusal(executor, output, guarded); - if (refusal) { - post_webcrypto_refusal(std::forward(handler), executor, refusal); + void operator()(Handler&& completion_handler, Executor const& completion_executor, + std::span output_bytes, std::size_t produced_size, + Request const& operation_request, + boost::system::result const& guard_result) const { + auto const refusal_code = + webcrypto_refusal(completion_executor, output_bytes, guard_result); + if (refusal_code) { + post_webcrypto_refusal(std::forward(completion_handler), completion_executor, + refusal_code); return; } - std::decay_t owned(std::forward(handler)); + std::decay_t owned_handler(std::forward(completion_handler)); webcpp::asio::async_compose, void(boost::system::error_code)>( - webcrypto_operation(executor, output, produced, request), owned, - executor); + webcrypto_operation(completion_executor, output_bytes, produced_size, + operation_request), + owned_handler, completion_executor); } }; /** Initiates a WebCrypto call. - @param executor The io_context's executor. @param output The output. - @param produced The bytes WebCrypto gives. @param request The call. - @param guarded The guards' verdict. @param token The completion token. + @param completion_executor The io_context's executor. @param output_bytes The output. + @param produced_size The bytes WebCrypto gives. @param operation_request The call. + @param guard_result The guards' verdict. @param completion_token The completion token. @return What the completion token's `async_result` gives. */ template -auto start_webcrypto(Executor const& executor, std::span output, std::size_t produced, - Request const& request, boost::system::result guarded, - CompletionToken& token) { +auto start_webcrypto(Executor const& completion_executor, std::span output_bytes, + std::size_t produced_size, Request const& operation_request, + boost::system::result guard_result, CompletionToken& completion_token) { return webcpp::asio_backend::async_initiate( - webcrypto_initiation{}, token, executor, output, produced, request, guarded); + webcrypto_initiation{}, completion_token, completion_executor, output_bytes, produced_size, + operation_request, guard_result); } /** @@ -665,20 +686,23 @@ class webcrypto_secret { /** No buffer. */ webcrypto_secret() = default; - /** The buffer `bytes`. @param bytes A `Uint8Array`. */ - explicit webcrypto_secret(emscripten::val bytes) noexcept : bytes_(std::move(bytes)) {} + /** The buffer `secret_bytes`. @param secret_bytes A `Uint8Array`. */ + explicit webcrypto_secret(emscripten::val secret_bytes) noexcept + : bytes_(std::move(secret_bytes)) {} - /** Takes `other`'s buffer, `other` left with none. @param other The holder. */ - webcrypto_secret(webcrypto_secret&& other) noexcept - : bytes_(std::exchange(other.bytes_, emscripten::val::undefined())) {} + /** Takes `moved_secret`'s buffer, `moved_secret` left with none. @param moved_secret The + * holder. */ + webcrypto_secret(webcrypto_secret&& moved_secret) noexcept + : bytes_(std::exchange(moved_secret.bytes_, emscripten::val::undefined())) {} /** - Wipes this buffer, then takes `other`'s. @param other The holder. @return This holder. + Wipes this buffer, then takes `moved_secret`'s. @param moved_secret The holder. @return This + holder. */ - webcrypto_secret& operator=(webcrypto_secret&& other) noexcept { - if (this != &other) { + webcrypto_secret& operator=(webcrypto_secret&& moved_secret) noexcept { + if (this != &moved_secret) { wipe(); - bytes_ = std::exchange(other.bytes_, emscripten::val::undefined()); + bytes_ = std::exchange(moved_secret.bytes_, emscripten::val::undefined()); } return *this; } @@ -727,13 +751,14 @@ static_assert(webcrypto_max_gathered > 64 + 1, "WEBCPP_HASH_DETAIL_TEST_WEBCRYPTO_MAX_GATHERED is more than 65"); /** - A new JavaScript `Uint8Array` of `length` zero bytes, or `undefined` when the runtime refuses it - (a `RangeError`, or an out of memory, as its memory allows). The refusal is caught in JavaScript, - before it can cross a WebAssembly frame, where it would end the program. + A new JavaScript `Uint8Array` of `byte_length` zero bytes, or `undefined` when the runtime refuses + it (a `RangeError`, or an out of memory, as its memory allows). The refusal is caught in + JavaScript, before it can cross a WebAssembly frame, where it would end the program. - @param length The length, at most @ref webcrypto_max_gathered. @return The array, or `undefined`. + @param byte_length The length, at most @ref webcrypto_max_gathered. @return The array, or + `undefined`. */ -inline emscripten::val webcrypto_new_bytes(double length) { +inline emscripten::val webcrypto_new_bytes(double byte_length) { // EM_ASM supports a definition in an inline function across translation units. // clang-format off return emscripten::val::take_ownership(reinterpret_cast(EM_ASM_PTR({ @@ -742,38 +767,40 @@ inline emscripten::val webcrypto_new_bytes(double length) { } catch (error) { return Emval.toHandle(undefined); } - }, length))); + }, byte_length))); // clang-format on } /** - The pieces gathered into one JavaScript `Uint8Array` of its own `ArrayBuffer`, of `prefix + - pieces.total_size() + suffix` bytes, the pieces one after another from offset `prefix` (each - copied by `set` from a `typed_memory_view` of it), the rest zeros. It runs in the initiating call, - so that no completion token keeps the list (ruling R4 of the change hkdf-pieces), and WebCrypto - then reads no view of the program's memory, which a build with threads shares. - - @param pieces The pieces. @param prefix The zeros before them. @param suffix The zeros after them, - the total within @ref webcrypto_max_gathered. @return The buffer, none (`undefined`) when the - runtime refuses to make it (@ref webcrypto_new_bytes). + The pieces gathered into one JavaScript `Uint8Array` of its own `ArrayBuffer`, of `prefix_size + + input_pieces.total_size() + suffix_size` bytes, the pieces one after another from offset + `prefix_size` (each copied by `set` from a `typed_memory_view` of it), the rest zeros. It runs in + the initiating call, so that no completion token keeps the list (ruling R4 of the change + hkdf-pieces), and WebCrypto then reads no view of the program's memory, which a build with threads + shares. + + @param input_pieces The pieces. @param prefix_size The zeros before them. @param suffix_size The + zeros after them, the total within @ref webcrypto_max_gathered. @return The buffer, none + (`undefined`) when the runtime refuses to make it (@ref webcrypto_new_bytes). */ -inline webcrypto_secret webcrypto_gather(byte_pieces pieces, std::size_t prefix, - std::size_t suffix) { - webcrypto_secret gathered( - webcrypto_new_bytes(static_cast(prefix + pieces.total_size() + suffix))); - if (gathered.bytes().isUndefined()) { - return gathered; +inline webcrypto_secret webcrypto_gather(byte_pieces input_pieces, std::size_t prefix_size, + std::size_t suffix_size) { + webcrypto_secret gathered_secret(webcrypto_new_bytes( + static_cast(prefix_size + input_pieces.total_size() + suffix_size))); + if (gathered_secret.bytes().isUndefined()) { + return gathered_secret; } - auto offset = static_cast(prefix); - for (auto const piece : pieces) { - if (!piece.empty()) { - gathered.bytes().call( - "set", emscripten::val(emscripten::typed_memory_view(piece.size(), piece.data())), - offset); - offset += static_cast(piece.size()); + auto byte_offset = static_cast(prefix_size); + for (auto const piece_bytes : input_pieces) { + if (!piece_bytes.empty()) { + gathered_secret.bytes().call("set", + emscripten::val(emscripten::typed_memory_view( + piece_bytes.size(), piece_bytes.data())), + byte_offset); + byte_offset += static_cast(piece_bytes.size()); } } - return gathered; + return gathered_secret; } /** Which steps of HKDF an operation over WebCrypto's HMAC runs. */ @@ -838,10 +865,10 @@ struct webcrypto_hmac_hkdf_request { /** Gathers Expand's HMAC key, the caller's pseudorandom key (Expand alone). - @param key The pseudorandom key. + @param key_bytes The pseudorandom key. */ - void gather_pseudorandom_key(std::span key) { - gather(pseudorandom_key, {key}, 0, 0); + void gather_pseudorandom_key(std::span key_bytes) { + gather(pseudorandom_key, {key_bytes}, 0, 0); } /** @@ -861,11 +888,11 @@ struct webcrypto_hmac_hkdf_request { private: // `pieces` into `buffer` (webcrypto_gather) while every earlier input has been gathered. - void gather(webcrypto_secret& buffer, byte_pieces pieces, std::size_t prefix, - std::size_t suffix) { + void gather(webcrypto_secret& target_buffer, byte_pieces input_pieces, std::size_t prefix_size, + std::size_t suffix_size) { if (gathered) { - buffer = webcrypto_gather(pieces, prefix, suffix); - gathered = !buffer.bytes().isUndefined(); + target_buffer = webcrypto_gather(input_pieces, prefix_size, suffix_size); + gathered = !target_buffer.bytes().isUndefined(); } } }; @@ -892,87 +919,93 @@ template class webcrypto_hmac_hkdf_operation { public: /** - The operation of `request` into `output`. + The operation of `operation_request` into `output_bytes`. - @param executor The io_context's executor. @param output The output: the pseudorandom key - (Extract alone) or the output keying material. @param request The inputs, gathered. + @param completion_executor The io_context's executor. @param output_bytes The output: the + pseudorandom key (Extract alone) or the output keying material. @param operation_request The + inputs, gathered. */ - webcrypto_hmac_hkdf_operation(Executor executor, std::span output, - webcrypto_hmac_hkdf_request request) - : executor_(std::move(executor)), output_(output), request_(std::move(request)) {} + webcrypto_hmac_hkdf_operation(Executor completion_executor, + std::span output_bytes, + webcrypto_hmac_hkdf_request operation_request) + : executor_(std::move(completion_executor)), + output_(output_bytes), + request_(std::move(operation_request)) {} /** Starts the operation: the first `importKey`, of the salt, or of the pseudorandom key for Expand alone. - @param self The composed operation. + @param operation_self The composed operation. */ template - void operator()(Self& self) { - self.reset_cancellation_state(webcpp::asio::enable_partial_cancellation()); + void operator()(Self& operation_self) { + operation_self.reset_cancellation_state(webcpp::asio::enable_partial_cancellation()); if (request_.steps == webcrypto_hkdf_steps::expand) { step_ = step::import_pseudorandom_key; - await(self, import_key(request_.pseudorandom_key.bytes())); + await(operation_self, import_key(request_.pseudorandom_key.bytes())); } else { step_ = step::import_salt; - await(self, import_key(request_.salt.bytes())); + await(operation_self, import_key(request_.salt.bytes())); } } /** A promise has settled, been rejected, or been cancelled: the next call, or the completion. - @param self The composed operation. @param code The wait's error. - @param value The promise's value: an imported key, or a tag's `ArrayBuffer`. + @param operation_self The composed operation. @param completion_code The wait's error. + @param promise_value The promise's value: an imported key, or a tag's `ArrayBuffer`. */ template - void operator()(Self& self, boost::system::error_code code, emscripten::val const& value) { - if (code) { - self.complete(fail(code == webcpp::asio::error::operation_aborted - ? code - : boost::system::error_code(error::backend_failure))); + void operator()(Self& operation_self, boost::system::error_code completion_code, + emscripten::val const& promise_value) { + if (completion_code) { + operation_self.complete(fail(completion_code == webcpp::asio::error::operation_aborted + ? completion_code + : boost::system::error_code(error::backend_failure))); return; } switch (step_) { case step::import_salt: request_.salt.wipe(); - key_ = value; - if (!stopped(self)) { + key_ = promise_value; + if (!stopped(operation_self)) { step_ = step::sign_input_key_material; - await(self, sign(request_.input_key_material.bytes())); + await(operation_self, sign(request_.input_key_material.bytes())); } return; case step::sign_input_key_material: request_.input_key_material.wipe(); - if (!is_tag(value)) { - self.complete(fail(error::backend_failure)); + if (!is_tag(promise_value)) { + operation_self.complete(fail(error::backend_failure)); return; } if (request_.steps == webcrypto_hkdf_steps::extract) { - webcrypto_secret tag(uint8_array(value)); - copy(tag.bytes(), 0, output_.size()); - tag.wipe(); - self.complete(finish()); + webcrypto_secret tag_secret(uint8_array(promise_value)); + copy(tag_secret.bytes(), 0, output_.size()); + tag_secret.wipe(); + operation_self.complete(finish()); return; } - request_.pseudorandom_key = webcrypto_secret(uint8_array(value)); - if (!stopped(self)) { + request_.pseudorandom_key = webcrypto_secret(uint8_array(promise_value)); + if (!stopped(operation_self)) { step_ = step::import_pseudorandom_key; - await(self, import_key(request_.pseudorandom_key.bytes())); + await(operation_self, import_key(request_.pseudorandom_key.bytes())); } return; case step::import_pseudorandom_key: request_.pseudorandom_key.wipe(); - key_ = value; - if (!stopped(self)) { + key_ = promise_value; + if (!stopped(operation_self)) { block_ = 1; request_.blocks.bytes().set(counter_index(), block_); step_ = step::sign_block; - await(self, sign(request_.blocks.bytes().call( - "subarray", static_cast(request_.digest_length)))); + await(operation_self, + sign(request_.blocks.bytes().call( + "subarray", static_cast(request_.digest_length)))); } return; - case step::sign_block: next_block(self, value); return; + case step::sign_block: next_block(operation_self, promise_value); return; } } @@ -987,71 +1020,74 @@ class webcrypto_hmac_hkdf_operation { // T(block_) has settled: into the output, then the next block's sign, or the completion. template - void next_block(Self& self, emscripten::val const& value) { - if (!is_tag(value)) { - self.complete(fail(error::backend_failure)); + void next_block(Self& operation_self, emscripten::val const& promise_value) { + if (!is_tag(promise_value)) { + operation_self.complete(fail(error::backend_failure)); return; } - webcrypto_secret tag(uint8_array(value)); - std::size_t const size = std::min(request_.digest_length, output_.size() - written_); - copy(tag.bytes(), written_, size); - written_ += size; + webcrypto_secret tag_secret(uint8_array(promise_value)); + std::size_t const block_size = std::min(request_.digest_length, output_.size() - written_); + copy(tag_secret.bytes(), written_, block_size); + written_ += block_size; if (written_ == output_.size()) { - tag.wipe(); - self.complete(finish()); + tag_secret.wipe(); + operation_self.complete(finish()); return; } - request_.blocks.bytes().call("set", tag.bytes(), 0); - tag.wipe(); - if (!stopped(self)) { + request_.blocks.bytes().call("set", tag_secret.bytes(), 0); + tag_secret.wipe(); + if (!stopped(operation_self)) { ++block_; request_.blocks.bytes().set(counter_index(), block_); - await(self, sign(request_.blocks.bytes())); + await(operation_self, sign(request_.blocks.bytes())); } } // Whether a cancellation has come since the last wait: then the completion, operation_aborted. template - bool stopped(Self& self) { - if (self.cancelled() == webcpp::asio::cancellation_type::none) { + bool stopped(Self& operation_self) { + if (operation_self.cancelled() == webcpp::asio::cancellation_type::none) { return false; } - self.complete(fail(webcpp::asio::error::operation_aborted)); + operation_self.complete(fail(webcpp::asio::error::operation_aborted)); return true; } // Awaits `promise`, the operation moved into the wait. template - void await(Self& self, emscripten::val promise) { - // A copy: the wait moves `self`, and this operation with it, before it reads the executor. - auto const executor = executor_; - webcpp::asio::browser::async_await(executor, std::move(promise), std::move(self)); + void await(Self& operation_self, emscripten::val pending_promise) { + // A copy: the wait moves `operation_self`, and this operation with it, before it reads the + // executor. + auto const completion_executor = executor_; + webcpp::asio::browser::async_await(completion_executor, std::move(pending_promise), + std::move(operation_self)); } // importKey("raw", bytes, {name: "HMAC", hash}, false, ["sign"]). - [[nodiscard]] emscripten::val import_key(emscripten::val const& bytes) const { - auto algorithm = emscripten::val::object(); - algorithm.set("name", emscripten::val("HMAC")); - algorithm.set("hash", emscripten::val(request_.hash)); - return subtle_crypto().call("importKey", emscripten::val("raw"), bytes, - algorithm, emscripten::val(false), + [[nodiscard]] emscripten::val import_key(emscripten::val const& key_bytes) const { + auto algorithm_object = emscripten::val::object(); + algorithm_object.set("name", emscripten::val("HMAC")); + algorithm_object.set("hash", emscripten::val(request_.hash)); + return subtle_crypto().call("importKey", emscripten::val("raw"), key_bytes, + algorithm_object, emscripten::val(false), webcrypto_usages("sign")); } // sign("HMAC", key_, data). - [[nodiscard]] emscripten::val sign(emscripten::val const& data) const { - return subtle_crypto().call("sign", emscripten::val("HMAC"), key_, data); + [[nodiscard]] emscripten::val sign(emscripten::val const& message_data) const { + return subtle_crypto().call("sign", emscripten::val("HMAC"), key_, + message_data); } // Whether `value` is a tag: an ArrayBuffer of HashLen bytes. - [[nodiscard]] bool is_tag(emscripten::val const& value) const { - return value.instanceof(emscripten::val::global("ArrayBuffer")) && - value["byteLength"].as() == request_.digest_length; + [[nodiscard]] bool is_tag(emscripten::val const& promise_value) const { + return promise_value.instanceof(emscripten::val::global("ArrayBuffer")) && + promise_value["byteLength"].as() == request_.digest_length; } // A Uint8Array over the ArrayBuffer `buffer`. - [[nodiscard]] static emscripten::val uint8_array(emscripten::val const& buffer) { - return emscripten::val::global("Uint8Array").new_(buffer); + [[nodiscard]] static emscripten::val uint8_array(emscripten::val const& array_buffer) { + return emscripten::val::global("Uint8Array").new_(array_buffer); } // The index of the block counter in the message buffer, its last byte. @@ -1060,9 +1096,11 @@ class webcrypto_hmac_hkdf_operation { } // The first `size` bytes of `tag` into the output at `offset`. - void copy(emscripten::val const& tag, std::size_t offset, std::size_t size) { - emscripten::val(emscripten::typed_memory_view(size, output_.subspan(offset, size).data())) - .call("set", tag.call("subarray", 0, static_cast(size))); + void copy(emscripten::val const& tag_value, std::size_t byte_offset, std::size_t byte_count) { + emscripten::val(emscripten::typed_memory_view( + byte_count, output_.subspan(byte_offset, byte_count).data())) + .call("set", tag_value.call("subarray", 0, + static_cast(byte_count))); } // Every JavaScript buffer zeroed and the key let go. @@ -1081,10 +1119,10 @@ class webcrypto_hmac_hkdf_operation { } // The output zeroed and the buffers released, with the completion's error. - [[nodiscard]] boost::system::error_code fail(boost::system::error_code code) noexcept { + [[nodiscard]] boost::system::error_code fail(boost::system::error_code failure_code) noexcept { secure::erase_secret(output_); release(); - return code; + return failure_code; } Executor executor_; @@ -1106,61 +1144,68 @@ struct webcrypto_hmac_hkdf_initiation { /** Refuses or starts the operation. - @param handler The completion handler. @param executor The io_context's executor. - @param output The output. @param request The inputs, gathered. - @param guarded The guards' verdict. + @param completion_handler The completion handler. @param completion_executor The io_context's + executor. + @param output_bytes The output. @param operation_request The inputs, gathered. + @param guard_result The guards' verdict. */ template - void operator()(Handler&& handler, Executor const& executor, std::span output, - webcrypto_hmac_hkdf_request request, - boost::system::result const& guarded) const { - auto refusal = webcrypto_refusal(executor, output, guarded); - if (!refusal && !request.gathered) { - secure::erase_secret(output); - refusal = error::backend_failure; + void operator()(Handler&& completion_handler, Executor const& completion_executor, + std::span output_bytes, + webcrypto_hmac_hkdf_request operation_request, + boost::system::result const& guard_result) const { + auto refusal_code = webcrypto_refusal(completion_executor, output_bytes, guard_result); + if (!refusal_code && !operation_request.gathered) { + secure::erase_secret(output_bytes); + refusal_code = error::backend_failure; } - if (refusal) { - post_webcrypto_refusal(std::forward(handler), executor, refusal); + if (refusal_code) { + post_webcrypto_refusal(std::forward(completion_handler), completion_executor, + refusal_code); return; } - std::decay_t owned(std::forward(handler)); + std::decay_t owned_handler(std::forward(completion_handler)); webcpp::asio::async_compose, void(boost::system::error_code)>( - webcrypto_hmac_hkdf_operation(executor, output, std::move(request)), owned, - executor); + webcrypto_hmac_hkdf_operation(completion_executor, output_bytes, + std::move(operation_request)), + owned_handler, completion_executor); } }; /** - The request over `Hmac`'s hash running `steps`, with no buffer yet. + The request over `Hmac`'s hash running `hkdf_steps`, with no buffer yet. @tparam Hmac `hmac_sha1_160`, `hmac_sha2_256`, `hmac_sha2_384` or `hmac_sha2_512`. - @param steps The steps. @return The request. + @param hkdf_steps The steps. @return The request. */ template -webcrypto_hmac_hkdf_request webcrypto_hmac_hkdf_of(webcrypto_hkdf_steps steps) { +webcrypto_hmac_hkdf_request webcrypto_hmac_hkdf_of(webcrypto_hkdf_steps hkdf_steps) { // Hash2 1.92 declares no std::tuple_size for digest; its size() is constexpr. constexpr std::size_t digest_length = typename Hmac::result_type().size(); - webcrypto_hmac_hkdf_request request; - request.hash = webcrypto_hash_name::type>; - request.digest_length = digest_length; - request.steps = steps; - return request; + webcrypto_hmac_hkdf_request operation_request; + operation_request.hash = webcrypto_hash_name::type>; + operation_request.digest_length = digest_length; + operation_request.steps = hkdf_steps; + return operation_request; } /** Initiates HKDF over WebCrypto's HMAC. - @param executor The io_context's executor. @param output The output. - @param request The inputs, gathered. @param guarded The guards' verdict. - @param token The completion token. + @param completion_executor The io_context's executor. @param output_bytes The output. + @param operation_request The inputs, gathered. @param guard_result The guards' verdict. + @param completion_token The completion token. @return What the completion token's `async_result` gives. */ template -auto start_webcrypto_hmac_hkdf(Executor const& executor, std::span output, - webcrypto_hmac_hkdf_request request, - boost::system::result guarded, CompletionToken& token) { +auto start_webcrypto_hmac_hkdf(Executor const& completion_executor, + std::span output_bytes, + webcrypto_hmac_hkdf_request operation_request, + boost::system::result guard_result, + CompletionToken& completion_token) { return webcpp::asio_backend::async_initiate( - webcrypto_hmac_hkdf_initiation{}, token, executor, output, std::move(request), guarded); + webcrypto_hmac_hkdf_initiation{}, completion_token, completion_executor, output_bytes, + std::move(operation_request), guard_result); } /** @@ -1174,10 +1219,11 @@ struct async_engine { // HKDF-Extract's output, the pseudorandom key: exactly the digest size, as // hkdf_extract_into requires of a synchronous backend's (invalid_output_size). template - [[nodiscard]] static boost::system::result extract_size_guard(std::size_t size) noexcept { + [[nodiscard]] static boost::system::result extract_size_guard( + std::size_t key_size) noexcept { // Hash2 1.92 declares no std::tuple_size for digest; its size() is constexpr. constexpr std::size_t digest_length = typename Hmac::result_type().size(); - if (size != digest_length) { + if (key_size != digest_length) { return error::invalid_output_size; } return {}; @@ -1190,11 +1236,11 @@ struct async_engine { std::size_t output_size, std::size_t pseudorandom_key_size) noexcept { // Hash2 1.92 declares no std::tuple_size for digest; its size() is constexpr. constexpr std::size_t digest_length = typename Hmac::result_type().size(); - auto guarded = hkdf_pieces_guards(output_size, 0); - if (guarded && pseudorandom_key_size != digest_length) { + auto guard_result = hkdf_pieces_guards(output_size, 0); + if (guard_result && pseudorandom_key_size != digest_length) { return error::invalid_key_size; } - return guarded; + return guard_result; } public: @@ -1202,75 +1248,84 @@ struct async_engine { `async_digest`: `crypto.subtle.digest`. @tparam Digest `digests::sha1`, `digests::sha2_256`, `digests::sha2_384` or - `digests::sha2_512`. @param executor The io_context's executor. @param output The digest. - @param input The data. @param token The completion token. + `digests::sha2_512`. @param completion_executor The io_context's executor. @param output_bytes + The digest. + @param input_bytes The data. @param completion_token The completion token. @return What the completion token's `async_result` gives. */ template - static auto digest(Executor const& executor, std::span output, - std::span input, CompletionToken&& token) { - auto const guarded = digest_guards(output.size(), digest_options{}); - webcrypto_digest_request const request{ + static auto digest(Executor const& completion_executor, std::span output_bytes, + std::span input_bytes, + CompletionToken&& completion_token) { + auto const guard_result = + digest_guards(output_bytes.size(), digest_options{}); + webcrypto_digest_request const operation_request{ .hash = webcrypto_hash_name, - .input = input, + .input = input_bytes, }; - return start_webcrypto(executor, output, output.size(), request, guarded, token); + return start_webcrypto(completion_executor, output_bytes, output_bytes.size(), + operation_request, guard_result, completion_token); } /** `async_hmac`: `importKey`, then `sign`; a tag shorter than the digest is its first bytes. @tparam Hmac `hmac_sha1_160`, `hmac_sha2_256`, `hmac_sha2_384` or `hmac_sha2_512`. - @param executor The io_context's executor. @param output The tag. @param key The key. - @param input The message. @param token The completion token. + @param completion_executor The io_context's executor. @param output_bytes The tag. @param + key_bytes The key. + @param input_bytes The message. @param completion_token The completion token. @return What the completion token's `async_result` gives. */ template - static auto hmac(Executor const& executor, std::span output, - std::span key, std::span input, - CompletionToken&& token) { + static auto hmac(Executor const& completion_executor, std::span output_bytes, + std::span key_bytes, + std::span input_bytes, + CompletionToken&& completion_token) { using digest = digest_tag_of::type; using tag = macs::hmac; - auto const guarded = mac_guards(output.size(), key.size(), mac_options{}); - webcrypto_hmac_request const request{ + auto const guard_result = + mac_guards(output_bytes.size(), key_bytes.size(), mac_options{}); + webcrypto_hmac_request const operation_request{ .hash = webcrypto_hash_name, - .key = key, - .input = input, + .key = key_bytes, + .input = input_bytes, }; - return start_webcrypto(executor, output, - static_cast(mac_traits::max_output), request, - guarded, token); + return start_webcrypto(completion_executor, output_bytes, + static_cast(mac_traits::max_output), + operation_request, guard_result, completion_token); } /** `async_hkdf`: `importKey`, then `deriveBits`. @tparam Hmac `hmac_sha1_160`, `hmac_sha2_256`, `hmac_sha2_384` or `hmac_sha2_512`. - @param executor The io_context's executor. @param output_key_material The output keying - material. - @param salt The salt. @param input_key_material The input keying material. @param + @param completion_executor The io_context's executor. @param output_key_material The output + keying material. + @param salt_bytes The salt. @param input_key_material The input keying material. @param application_info The application info. - @param token The completion token. + @param completion_token The completion token. @return What the completion token's `async_result` gives. */ template - static auto hkdf(Executor const& executor, std::span output_key_material, - std::span salt, + static auto hkdf(Executor const& completion_executor, + std::span output_key_material, + std::span salt_bytes, std::span input_key_material, - std::span application_info, CompletionToken&& token) { + std::span application_info, + CompletionToken&& completion_token) { using digest = digest_tag_of::type; - auto const guarded = hkdf_guards( - output_key_material.size(), salt.size(), input_key_material.size(), + auto const guard_result = hkdf_guards( + output_key_material.size(), salt_bytes.size(), input_key_material.size(), application_info.size()); - webcrypto_hkdf_request const request{ + webcrypto_hkdf_request const operation_request{ .hash = webcrypto_hash_name, - .salt = salt, + .salt = salt_bytes, .input_key_material = input_key_material, .application_info = application_info, - .bits = static_cast(guarded ? output_key_material.size() * 8 : 0), + .bits = static_cast(guard_result ? output_key_material.size() * 8 : 0), }; - return start_webcrypto(executor, output_key_material, output_key_material.size(), request, - guarded, token); + return start_webcrypto(completion_executor, output_key_material, output_key_material.size(), + operation_request, guard_result, completion_token); } /** @@ -1279,27 +1334,30 @@ struct async_engine { the call. No cap on the application info: WebCrypto's 1,024 bytes are `deriveBits`'. @tparam Hmac `hmac_sha1_160`, `hmac_sha2_256`, `hmac_sha2_384` or `hmac_sha2_512`. - @param executor The io_context's executor. @param output_key_material The output keying - material. @param salt The salt. @param input_key_material The input keying material's - pieces. @param application_info The application info's pieces. - @param token The completion token. + @param completion_executor The io_context's executor. @param output_key_material The output + keying material. @param salt_bytes The salt. @param input_key_material The input keying + material's pieces. @param application_info The application info's pieces. + @param completion_token The completion token. @return What the completion token's `async_result` gives. */ template - static auto hkdf(Executor const& executor, std::span output_key_material, - std::span salt, byte_pieces input_key_material, - byte_pieces application_info, CompletionToken&& token) { - secure::timing_guard const timing; - auto const guarded = - hkdf_pieces_guards(output_key_material.size(), salt.size()); - auto request = webcrypto_hmac_hkdf_of(webcrypto_hkdf_steps::extract_and_expand); - if (guarded) { - request.gather_extract(salt, input_key_material); + static auto hkdf(Executor const& completion_executor, + std::span output_key_material, + std::span salt_bytes, byte_pieces input_key_material, + byte_pieces application_info, CompletionToken&& completion_token) { + secure::timing_guard const timing_scope; + auto const guard_result = hkdf_pieces_guards( + output_key_material.size(), salt_bytes.size()); + auto operation_request = + webcrypto_hmac_hkdf_of(webcrypto_hkdf_steps::extract_and_expand); + if (guard_result) { + operation_request.gather_extract(salt_bytes, input_key_material); // Nothing when Extract's inputs were not gathered: the operation fails then. - request.gather_expand(application_info); + operation_request.gather_expand(application_info); } - return start_webcrypto_hmac_hkdf(executor, output_key_material, std::move(request), guarded, - token); + return start_webcrypto_hmac_hkdf(completion_executor, output_key_material, + std::move(operation_request), guard_result, + completion_token); } /** @@ -1307,28 +1365,30 @@ struct async_engine { salt, then `sign`), the input keying material its one piece. @tparam Hmac `hmac_sha1_160`, `hmac_sha2_256`, `hmac_sha2_384` or `hmac_sha2_512`. - @param executor The io_context's executor. @param pseudorandom_key The pseudorandom key, of - exactly the digest size. @param salt The salt. @param input_key_material The input keying - material. @param token The completion token. + @param completion_executor The io_context's executor. @param pseudorandom_key The pseudorandom + key, of exactly the digest size. @param salt_bytes The salt. @param input_key_material The + input keying material. @param completion_token The completion token. @return What the completion token's `async_result` gives. */ template - static auto hkdf_extract(Executor const& executor, std::span pseudorandom_key, - std::span salt, + static auto hkdf_extract(Executor const& completion_executor, + std::span pseudorandom_key, + std::span salt_bytes, std::span input_key_material, - CompletionToken&& token) { - secure::timing_guard const timing; - auto guarded = extract_size_guard(pseudorandom_key.size()); - if (guarded) { - guarded = - hkdf_extract_guards(salt.size(), input_key_material.size()); + CompletionToken&& completion_token) { + secure::timing_guard const timing_scope; + auto guard_result = extract_size_guard(pseudorandom_key.size()); + if (guard_result) { + guard_result = hkdf_extract_guards(salt_bytes.size(), + input_key_material.size()); } - auto request = webcrypto_hmac_hkdf_of(webcrypto_hkdf_steps::extract); - if (guarded) { - request.gather_extract(salt, {input_key_material}); + auto operation_request = webcrypto_hmac_hkdf_of(webcrypto_hkdf_steps::extract); + if (guard_result) { + operation_request.gather_extract(salt_bytes, {input_key_material}); } - return start_webcrypto_hmac_hkdf(executor, pseudorandom_key, std::move(request), guarded, - token); + return start_webcrypto_hmac_hkdf(completion_executor, pseudorandom_key, + std::move(operation_request), guard_result, + completion_token); } /** @@ -1336,26 +1396,28 @@ struct async_engine { into JavaScript memory in the call. @tparam Hmac `hmac_sha1_160`, `hmac_sha2_256`, `hmac_sha2_384` or `hmac_sha2_512`. - @param executor The io_context's executor. @param pseudorandom_key The pseudorandom key, of - exactly the digest size. @param salt The salt. @param input_key_material The input keying - material's pieces. @param token The completion token. + @param completion_executor The io_context's executor. @param pseudorandom_key The pseudorandom + key, of exactly the digest size. @param salt_bytes The salt. @param input_key_material The + input keying material's pieces. @param completion_token The completion token. @return What the completion token's `async_result` gives. */ template - static auto hkdf_extract(Executor const& executor, std::span pseudorandom_key, - std::span salt, byte_pieces input_key_material, - CompletionToken&& token) { - secure::timing_guard const timing; - auto guarded = extract_size_guard(pseudorandom_key.size()); - if (guarded) { - guarded = hkdf_pieces_salt_guard(salt.size()); + static auto hkdf_extract(Executor const& completion_executor, + std::span pseudorandom_key, + std::span salt_bytes, + byte_pieces input_key_material, CompletionToken&& completion_token) { + secure::timing_guard const timing_scope; + auto guard_result = extract_size_guard(pseudorandom_key.size()); + if (guard_result) { + guard_result = hkdf_pieces_salt_guard(salt_bytes.size()); } - auto request = webcrypto_hmac_hkdf_of(webcrypto_hkdf_steps::extract); - if (guarded) { - request.gather_extract(salt, input_key_material); + auto operation_request = webcrypto_hmac_hkdf_of(webcrypto_hkdf_steps::extract); + if (guard_result) { + operation_request.gather_extract(salt_bytes, input_key_material); } - return start_webcrypto_hmac_hkdf(executor, pseudorandom_key, std::move(request), guarded, - token); + return start_webcrypto_hmac_hkdf(completion_executor, pseudorandom_key, + std::move(operation_request), guard_result, + completion_token); } /** @@ -1365,28 +1427,31 @@ struct async_engine { hkdf-pieces), not the 1,024 bytes of `deriveBits`, which only `async_hkdf` calls. @tparam Hmac `hmac_sha1_160`, `hmac_sha2_256`, `hmac_sha2_384` or `hmac_sha2_512`. - @param executor The io_context's executor. @param output_key_material The output keying - material. @param pseudorandom_key The pseudorandom key. @param application_info The - application info. @param token The completion token. + @param completion_executor The io_context's executor. @param output_key_material The output + keying material. @param pseudorandom_key The pseudorandom key. @param application_info The + application info. @param completion_token The completion token. @return What the completion token's `async_result` gives. */ template - static auto hkdf_expand(Executor const& executor, std::span output_key_material, + static auto hkdf_expand(Executor const& completion_executor, + std::span output_key_material, std::span pseudorandom_key, std::span application_info, - CompletionToken&& token) { - secure::timing_guard const timing; - auto guarded = expand_guards(output_key_material.size(), pseudorandom_key.size()); - if (guarded && application_info.size() > hkdf_max_application_info_size) { - guarded = error::input_too_long; + CompletionToken&& completion_token) { + secure::timing_guard const timing_scope; + auto guard_result = + expand_guards(output_key_material.size(), pseudorandom_key.size()); + if (guard_result && application_info.size() > hkdf_max_application_info_size) { + guard_result = error::input_too_long; } - auto request = webcrypto_hmac_hkdf_of(webcrypto_hkdf_steps::expand); - if (guarded) { - request.gather_pseudorandom_key(pseudorandom_key); - request.gather_expand({application_info}); + auto operation_request = webcrypto_hmac_hkdf_of(webcrypto_hkdf_steps::expand); + if (guard_result) { + operation_request.gather_pseudorandom_key(pseudorandom_key); + operation_request.gather_expand({application_info}); } - return start_webcrypto_hmac_hkdf(executor, output_key_material, std::move(request), guarded, - token); + return start_webcrypto_hmac_hkdf(completion_executor, output_key_material, + std::move(operation_request), guard_result, + completion_token); } /** @@ -1394,40 +1459,44 @@ struct async_engine { the pieces gathered into JavaScript memory in the call; no cap on the application info. @tparam Hmac `hmac_sha1_160`, `hmac_sha2_256`, `hmac_sha2_384` or `hmac_sha2_512`. - @param executor The io_context's executor. @param output_key_material The output keying - material. @param pseudorandom_key The pseudorandom key. @param application_info The - application info's pieces. @param token The completion token. + @param completion_executor The io_context's executor. @param output_key_material The output + keying material. @param pseudorandom_key The pseudorandom key. @param application_info The + application info's pieces. @param completion_token The completion token. @return What the completion token's `async_result` gives. */ template - static auto hkdf_expand(Executor const& executor, std::span output_key_material, + static auto hkdf_expand(Executor const& completion_executor, + std::span output_key_material, std::span pseudorandom_key, - byte_pieces application_info, CompletionToken&& token) { - secure::timing_guard const timing; - auto const guarded = + byte_pieces application_info, CompletionToken&& completion_token) { + secure::timing_guard const timing_scope; + auto const guard_result = expand_guards(output_key_material.size(), pseudorandom_key.size()); - auto request = webcrypto_hmac_hkdf_of(webcrypto_hkdf_steps::expand); - if (guarded) { - request.gather_pseudorandom_key(pseudorandom_key); - request.gather_expand(application_info); + auto operation_request = webcrypto_hmac_hkdf_of(webcrypto_hkdf_steps::expand); + if (guard_result) { + operation_request.gather_pseudorandom_key(pseudorandom_key); + operation_request.gather_expand(application_info); } - return start_webcrypto_hmac_hkdf(executor, output_key_material, std::move(request), guarded, - token); + return start_webcrypto_hmac_hkdf(completion_executor, output_key_material, + std::move(operation_request), guard_result, + completion_token); } /** `async_pbkdf2`: `importKey`, then `deriveBits`. @tparam Hmac `hmac_sha1_160`, `hmac_sha2_256`, `hmac_sha2_384` or `hmac_sha2_512`; another - refuses at compile time. @param executor The io_context's executor. - @param output The derived key. @param password The password. @param salt The salt. - @param iterations The iteration count. @param token The completion token. + refuses at compile time. @param work_executor The io_context's executor. + @param output_bytes The derived key. @param password_bytes The password. @param salt_bytes The + salt. + @param iteration_count The iteration count. @param completion_token The completion token. @return What the completion token's `async_result` gives. */ template - static auto pbkdf2(Executor const& executor, std::span output, - std::span password, std::span salt, - std::uint64_t iterations, CompletionToken&& token) { + static auto pbkdf2(Executor const& work_executor, std::span output_bytes, + std::span password_bytes, + std::span salt_bytes, std::uint64_t iteration_count, + CompletionToken&& completion_token) { if constexpr (!webcrypto_hmac_v) { // clang-format off static_assert(always_false, @@ -1435,17 +1504,18 @@ struct async_engine { // clang-format on } else { using digest = digest_tag_of::type; - auto const guarded = pbkdf2_guards( - output.size(), password.size(), salt.size(), iterations); + auto const guard_result = pbkdf2_guards( + output_bytes.size(), password_bytes.size(), salt_bytes.size(), iteration_count); // Within backend_limits once the guards pass: 2^32 - 1 iterations, (2^32 - 1) bits. - webcrypto_pbkdf2_request const request{ + webcrypto_pbkdf2_request const operation_request{ .hash = webcrypto_hash_name, - .password = password, - .salt = salt, - .iterations = static_cast(guarded ? iterations : 0), - .bits = static_cast(guarded ? output.size() * 8 : 0), + .password = password_bytes, + .salt = salt_bytes, + .iterations = static_cast(guard_result ? iteration_count : 0), + .bits = static_cast(guard_result ? output_bytes.size() * 8 : 0), }; - return start_webcrypto(executor, output, output.size(), request, guarded, token); + return start_webcrypto(work_executor, output_bytes, output_bytes.size(), + operation_request, guard_result, completion_token); } } }; diff --git a/include/webcpp/hash/backends/xkcp.hpp b/include/webcpp/hash/backends/xkcp.hpp index f3a08de..40ddd8c 100644 --- a/include/webcpp/hash/backends/xkcp.hpp +++ b/include/webcpp/hash/backends/xkcp.hpp @@ -61,50 +61,54 @@ struct digest_engine : full_engine { /** webcpp's Keccak-256 over XKCP's permutation, which is all of the state. */ using state = keccak_256; - /** Starts a hash. @param hashed The state. @return Success. */ + /** Starts a hash. @param digest_state The state. @return Success. */ [[nodiscard]] static boost::system::result init( - state& hashed, digest_options const& /*options*/) noexcept { - hashed = keccak_256(); + state& digest_state, + digest_options const& /*algorithm_options*/) noexcept { + digest_state = keccak_256(); return {}; } - /** Absorbs `input`. @param hashed The state. @param input The bytes. @return Success. */ + /** Absorbs `input_bytes`. @param digest_state The state. @param input_bytes The bytes. @return + * Success. */ [[nodiscard]] static boost::system::result update( - state& hashed, std::span input) noexcept { - hashed.update(input.data(), input.size()); + state& digest_state, std::span input_bytes) noexcept { + digest_state.update(input_bytes.data(), input_bytes.size()); return {}; } /** Writes the 32-byte digest. - @param hashed The state. @param output The digest. @return Success. + @param digest_state The state. @param output_bytes The digest. @return Success. */ [[nodiscard]] static boost::system::result finish( - state& hashed, std::span output) noexcept { - auto result_bytes = hashed.result(); - std::memcpy(output.data(), result_bytes.data(), output.size()); + state& digest_state, std::span output_bytes) noexcept { + auto result_bytes = digest_state.result(); + std::memcpy(output_bytes.data(), result_bytes.data(), output_bytes.size()); secure::erase_secret(std::span(&result_bytes, 1)); return {}; } - /** Wipes the state. @param hashed The state. */ - static void destroy(state& hashed) noexcept { secure::erase_secret(std::span(&hashed, 1)); } + /** Wipes the state. @param digest_state The state. */ + static void destroy(state& digest_state) noexcept { + secure::erase_secret(std::span(&digest_state, 1)); + } /** - The digest of `input` at once, the state wiped. + The digest of `input_bytes` at once, the state wiped. - @param output The digest. @param input The bytes. @param options None. + @param output_bytes The digest. @param input_bytes The bytes. @param algorithm_options None. @return Success. */ [[nodiscard]] static boost::system::result one_shot( - std::span output, std::span input, - digest_options const& options) noexcept { - state hashed; - static_cast(init(hashed, options)); - static_cast(update(hashed, input)); - static_cast(finish(hashed, output)); - destroy(hashed); + std::span output_bytes, std::span input_bytes, + digest_options const& algorithm_options) noexcept { + state digest_state; + static_cast(init(digest_state, algorithm_options)); + static_cast(update(digest_state, input_bytes)); + static_cast(finish(digest_state, output_bytes)); + destroy(digest_state); return {}; } }; @@ -127,71 +131,75 @@ struct xkcp_keccak_hash_engine : full_engine { /** XKCP's `Keccak_HashInstance`, in storage the adapter checks is large enough. */ using state = xkcp_keccak_hash_storage; - /** Starts a hash. @param hashed The state. @return Success, or backend_failure. */ + /** Starts a hash. @param digest_state The state. @return Success, or backend_failure. */ [[nodiscard]] static boost::system::result init( - state& hashed, digest_options const& /*options*/) noexcept { - if (webcpp_hash_xkcp_keccak_hash_initialize(hashed.data(), 1600 - Capacity, Capacity, Fixed, - Suffix) != 0) { + state& digest_state, digest_options const& /*algorithm_options*/) noexcept { + if (webcpp_hash_xkcp_keccak_hash_initialize(digest_state.data(), 1600 - Capacity, Capacity, + Fixed, Suffix) != 0) { return error::backend_failure; } return {}; } /** - Absorbs `input`. @param hashed The state. @param input The bytes. + Absorbs `input_bytes`. @param digest_state The state. @param input_bytes The bytes. @return Success, or backend_failure. */ [[nodiscard]] static boost::system::result update( - state& hashed, std::span input) noexcept { - if (webcpp_hash_xkcp_keccak_hash_update(hashed.data(), input.data(), input.size()) != 0) { + state& digest_state, std::span input_bytes) noexcept { + if (webcpp_hash_xkcp_keccak_hash_update(digest_state.data(), input_bytes.data(), + input_bytes.size()) != 0) { return error::backend_failure; } return {}; } /** - Writes the digest, or the first `output.size()` bytes of the extendable output. + Writes the digest, or the first `output_bytes.size()` bytes of the extendable output. - @param hashed The state. @param output The output. @return Success, or backend_failure. + @param digest_state The state. @param output_bytes The output. @return Success, or + backend_failure. */ [[nodiscard]] static boost::system::result finish( - state& hashed, std::span output) noexcept { + state& digest_state, std::span output_bytes) noexcept { if constexpr (Fixed != 0) { - if (webcpp_hash_xkcp_keccak_hash_final(hashed.data(), output.data()) != 0) { + if (webcpp_hash_xkcp_keccak_hash_final(digest_state.data(), output_bytes.data()) != 0) { return error::backend_failure; } } else { - if (webcpp_hash_xkcp_keccak_hash_final(hashed.data(), nullptr) != 0 || - webcpp_hash_xkcp_keccak_hash_squeeze(hashed.data(), output.data(), output.size()) != - 0) { + if (webcpp_hash_xkcp_keccak_hash_final(digest_state.data(), nullptr) != 0 || + webcpp_hash_xkcp_keccak_hash_squeeze(digest_state.data(), output_bytes.data(), + output_bytes.size()) != 0) { return error::backend_failure; } } return {}; } - /** Wipes the state. @param hashed The state. */ - static void destroy(state& hashed) noexcept { secure::erase_secret(std::span(&hashed, 1)); } + /** Wipes the state. @param digest_state The state. */ + static void destroy(state& digest_state) noexcept { + secure::erase_secret(std::span(&digest_state, 1)); + } /** - The output of `input` at once, the state wiped. + The output of `input_bytes` at once, the state wiped. - @param output The output. @param input The bytes. @param options None. + @param output_bytes The output. @param input_bytes The bytes. @param algorithm_options None. @return Success, or backend_failure. */ [[nodiscard]] static boost::system::result one_shot( - std::span output, std::span input, - digest_options const& options) noexcept { - state hashed; - auto done = init(hashed, options); - if (done) { - done = update(hashed, input); - } - if (done) { - done = finish(hashed, output); - } - destroy(hashed); - return done; + std::span output_bytes, std::span input_bytes, + digest_options const& algorithm_options) noexcept { + state digest_state; + auto init_result = init(digest_state, algorithm_options); + if (init_result) { + init_result = update(digest_state, input_bytes); + } + if (init_result) { + init_result = finish(digest_state, output_bytes); + } + destroy(digest_state); + return init_result; } }; @@ -357,67 +365,75 @@ struct xkcp_cshake_engine : full_engine { /** Starts a hash with the function name and the customisation. - @param hashed The state. @param options N and S. @return Success, or backend_failure. + @param digest_state The state. @param algorithm_options N and S. @return Success, or + backend_failure. */ [[nodiscard]] static boost::system::result init( - state& hashed, digest_options const& options) noexcept { - if (Functions::initialize(hashed.data(), 0, options.function_name.data(), - options.function_name.size(), options.customisation.data(), - options.customisation.size()) != 0) { + state& digest_state, digest_options const& algorithm_options) noexcept { + if (Functions::initialize(digest_state.data(), 0, algorithm_options.function_name.data(), + algorithm_options.function_name.size(), + algorithm_options.customisation.data(), + algorithm_options.customisation.size()) != 0) { return error::backend_failure; } return {}; } /** - Absorbs `input`, which the adapter passes to XKCP in pieces of at most `SIZE_MAX / 8` bytes. + Absorbs `input_bytes`, which the adapter passes to XKCP in pieces of at most `SIZE_MAX / 8` + bytes. - @param hashed The state. @param input The bytes. @return Success, or backend_failure. + @param digest_state The state. @param input_bytes The bytes. @return Success, or + backend_failure. */ [[nodiscard]] static boost::system::result update( - state& hashed, std::span input) noexcept { - if (Functions::update(hashed.data(), input.data(), input.size()) != 0) { + state& digest_state, std::span input_bytes) noexcept { + if (Functions::update(digest_state.data(), input_bytes.data(), input_bytes.size()) != 0) { return error::backend_failure; } return {}; } /** - Writes the first `output.size()` bytes of the stream. + Writes the first `output_bytes.size()` bytes of the stream. - @param hashed The state. @param output The output. @return Success, or backend_failure. + @param digest_state The state. @param output_bytes The output. @return Success, or + backend_failure. */ [[nodiscard]] static boost::system::result finish( - state& hashed, std::span output) noexcept { - if (Functions::final(hashed.data(), nullptr) != 0 || - Functions::squeeze(hashed.data(), output.data(), output.size()) != 0) { + state& digest_state, std::span output_bytes) noexcept { + if (Functions::final(digest_state.data(), nullptr) != 0 || + Functions::squeeze(digest_state.data(), output_bytes.data(), output_bytes.size()) != + 0) { return error::backend_failure; } return {}; } - /** Wipes the state. @param hashed The state. */ - static void destroy(state& hashed) noexcept { secure::erase_secret(std::span(&hashed, 1)); } + /** Wipes the state. @param digest_state The state. */ + static void destroy(state& digest_state) noexcept { + secure::erase_secret(std::span(&digest_state, 1)); + } /** - The output of `input` at once, the state wiped. + The output of `input_bytes` at once, the state wiped. - @param output The output. @param input The bytes. @param options N and S. + @param output_bytes The output. @param input_bytes The bytes. @param algorithm_options N and S. @return Success, or backend_failure. */ [[nodiscard]] static boost::system::result one_shot( - std::span output, std::span input, - digest_options const& options) noexcept { - state hashed{}; - auto done = init(hashed, options); - if (done) { - done = update(hashed, input); - } - if (done) { - done = finish(hashed, output); - } - destroy(hashed); - return done; + std::span output_bytes, std::span input_bytes, + digest_options const& algorithm_options) noexcept { + state digest_state{}; + auto init_result = init(digest_state, algorithm_options); + if (init_result) { + init_result = update(digest_state, input_bytes); + } + if (init_result) { + init_result = finish(digest_state, output_bytes); + } + destroy(digest_state); + return init_result; } }; @@ -440,23 +456,24 @@ struct xkcp_sp800_185_state { /** Ends a TupleHash or a ParallelHash: in the fixed-length form, `final_length` with L the output's - size, which writes it; in the XOF form, `final_length` with 0, then `output.size()` bytes + size, which writes it; in the XOF form, `final_length` with 0, then `output_bytes.size()` bytes squeezed. The output's size is L itself, so the length the digest encodes is always the one it writes. @tparam Functions The adapter's functions. @tparam State `xkcp_sp800_185_state` of the instance's storage. - @param hashed The state. @param output The output. @return Success, or backend_failure. + @param digest_state The state. @param output_bytes The output. @return Success, or backend_failure. */ template [[nodiscard]] boost::system::result xkcp_finish_with_length( - State& hashed, std::span output) noexcept { - bool const ended = - hashed.xof - ? Functions::final_length(hashed.storage.data(), nullptr, 0) == 0 && - Functions::squeeze(hashed.storage.data(), output.data(), output.size()) == 0 - : Functions::final_length(hashed.storage.data(), output.data(), output.size()) == 0; - if (!ended) { + State& digest_state, std::span output_bytes) noexcept { + bool const finish_succeeded = + digest_state.xof ? Functions::final_length(digest_state.storage.data(), nullptr, 0) == 0 && + Functions::squeeze(digest_state.storage.data(), output_bytes.data(), + output_bytes.size()) == 0 + : Functions::final_length(digest_state.storage.data(), output_bytes.data(), + output_bytes.size()) == 0; + if (!finish_succeeded) { return error::backend_failure; } return {}; @@ -479,67 +496,74 @@ struct xkcp_tuplehash_engine : full_engine { /** Starts a hash with the customisation, in the form the options name. - @param hashed The state. @param options S and the form. @return Success, or backend_failure. + @param digest_state The state. @param algorithm_options S and the form. @return Success, or + backend_failure. */ [[nodiscard]] static boost::system::result init( - state& hashed, digest_options const& options) noexcept { - hashed.xof = options.xof; - if (Functions::initialize(hashed.storage.data(), 0, options.customisation.data(), - options.customisation.size()) != 0) { + state& digest_state, digest_options const& algorithm_options) noexcept { + digest_state.xof = algorithm_options.xof; + if (Functions::initialize(digest_state.storage.data(), 0, + algorithm_options.customisation.data(), + algorithm_options.customisation.size()) != 0) { return error::backend_failure; } return {}; } /** - Adds `input` to the tuple as its next element. + Adds `input_bytes` to the tuple as its next element. - @param hashed The state. @param input The element. + @param digest_state The state. @param input_bytes The element. @return Success, `input_too_long`, or backend_failure. */ [[nodiscard]] static boost::system::result update( - state& hashed, std::span input) noexcept { - if (exceeds(input.size(), sp800_185_max_bytes)) { + state& digest_state, std::span input_bytes) noexcept { + if (exceeds(input_bytes.size(), sp800_185_max_bytes)) { return error::input_too_long; } - if (Functions::update(hashed.storage.data(), input.data(), input.size()) != 0) { + if (Functions::update(digest_state.storage.data(), input_bytes.data(), + input_bytes.size()) != 0) { return error::backend_failure; } return {}; } /** - Writes the digest of `output.size()` bytes, the form's. + Writes the digest of `output_bytes.size()` bytes, the form's. - @param hashed The state. @param output The output. @return Success, or backend_failure. + @param digest_state The state. @param output_bytes The output. @return Success, or + backend_failure. */ [[nodiscard]] static boost::system::result finish( - state& hashed, std::span output) noexcept { - return xkcp_finish_with_length(hashed, output); + state& digest_state, std::span output_bytes) noexcept { + return xkcp_finish_with_length(digest_state, output_bytes); } - /** Wipes the state. @param hashed The state. */ - static void destroy(state& hashed) noexcept { secure::erase_secret(std::span(&hashed, 1)); } + /** Wipes the state. @param digest_state The state. */ + static void destroy(state& digest_state) noexcept { + secure::erase_secret(std::span(&digest_state, 1)); + } /** - The digest of the tuple of one element, `input`, the state wiped. + The digest of the tuple of one element, `input_bytes`, the state wiped. - @param output The output. @param input The element. @param options S and the form. + @param output_bytes The output. @param input_bytes The element. @param algorithm_options S and + the form. @return Success, `input_too_long`, or backend_failure. */ [[nodiscard]] static boost::system::result one_shot( - std::span output, std::span input, - digest_options const& options) noexcept { - state hashed{}; - auto done = init(hashed, options); - if (done) { - done = update(hashed, input); - } - if (done) { - done = finish(hashed, output); - } - destroy(hashed); - return done; + std::span output_bytes, std::span input_bytes, + digest_options const& algorithm_options) noexcept { + state digest_state{}; + auto init_result = init(digest_state, algorithm_options); + if (init_result) { + init_result = update(digest_state, input_bytes); + } + if (init_result) { + init_result = finish(digest_state, output_bytes); + } + destroy(digest_state); + return init_result; } }; @@ -566,82 +590,87 @@ struct xkcp_parallelhash_engine : full_engine { /** Whether XKCP takes the options' block size: a power of two of at least 8. - @param options The options. @return Whether it does. + @param algorithm_options The options. @return Whether it does. */ - static constexpr bool accepts(digest_options const& options) noexcept { - auto const block_size = options.block_size; + static constexpr bool accepts(digest_options const& algorithm_options) noexcept { + auto const block_size = algorithm_options.block_size; return block_size >= min_block_size && (block_size & (block_size - 1)) == 0; } /** Starts a hash with the block size and the customisation, in the form the options name. - @param hashed The state. @param options B, S and the form. + @param digest_state The state. @param algorithm_options B, S and the form. @return Success, or backend_failure. */ [[nodiscard]] static boost::system::result init( - state& hashed, digest_options const& options) noexcept { - hashed.xof = options.xof; - if (Functions::initialize(hashed.storage.data(), options.block_size, 0, - options.customisation.data(), - options.customisation.size()) != 0) { + state& digest_state, digest_options const& algorithm_options) noexcept { + digest_state.xof = algorithm_options.xof; + if (Functions::initialize(digest_state.storage.data(), algorithm_options.block_size, 0, + algorithm_options.customisation.data(), + algorithm_options.customisation.size()) != 0) { return error::backend_failure; } return {}; } /** - Absorbs `input`, which the adapter passes to XKCP in pieces of at most `SIZE_MAX / 8` bytes, - unless the whole input would pass `sp800_185_max_bytes`. + Absorbs `input_bytes`, which the adapter passes to XKCP in pieces of at most `SIZE_MAX / 8` + bytes, unless the whole input would pass `sp800_185_max_bytes`. - @param hashed The state. @param input The bytes. + @param digest_state The state. @param input_bytes The bytes. @return Success, `input_too_long`, or backend_failure. */ [[nodiscard]] static boost::system::result update( - state& hashed, std::span input) noexcept { + state& digest_state, std::span input_bytes) noexcept { // hashed.absorbed never exceeds the limit, so the subtraction does not wrap. - if (exceeds(input.size(), sp800_185_max_bytes - hashed.absorbed)) { + if (exceeds(input_bytes.size(), sp800_185_max_bytes - digest_state.absorbed)) { return error::input_too_long; } - if (Functions::update(hashed.storage.data(), input.data(), input.size()) != 0) { + if (Functions::update(digest_state.storage.data(), input_bytes.data(), + input_bytes.size()) != 0) { return error::backend_failure; } - hashed.absorbed += input.size(); + digest_state.absorbed += input_bytes.size(); return {}; } /** - Writes the digest of `output.size()` bytes, the form's. + Writes the digest of `output_bytes.size()` bytes, the form's. - @param hashed The state. @param output The output. @return Success, or backend_failure. + @param digest_state The state. @param output_bytes The output. @return Success, or + backend_failure. */ [[nodiscard]] static boost::system::result finish( - state& hashed, std::span output) noexcept { - return xkcp_finish_with_length(hashed, output); + state& digest_state, std::span output_bytes) noexcept { + return xkcp_finish_with_length(digest_state, output_bytes); } - /** Wipes the state. @param hashed The state. */ - static void destroy(state& hashed) noexcept { secure::erase_secret(std::span(&hashed, 1)); } + /** Wipes the state. @param digest_state The state. */ + static void destroy(state& digest_state) noexcept { + secure::erase_secret(std::span(&digest_state, 1)); + } /** - The digest of `input` at once, the state wiped. + The digest of `input_bytes` at once, the state wiped. - @param output The output. @param input The bytes. @param options B, S and the form. + @param output_bytes The output. @param input_bytes The bytes. @param algorithm_options B, S and + the form. @return Success, `input_too_long`, or backend_failure. */ [[nodiscard]] static boost::system::result one_shot( - std::span output, std::span input, - digest_options const& options) noexcept { - state hashed{}; - auto done = init(hashed, options); - if (done) { - done = update(hashed, input); - } - if (done) { - done = finish(hashed, output); - } - destroy(hashed); - return done; + std::span output_bytes, std::span input_bytes, + digest_options const& algorithm_options) noexcept { + state digest_state{}; + auto init_result = init(digest_state, algorithm_options); + if (init_result) { + init_result = update(digest_state, input_bytes); + } + if (init_result) { + init_result = finish(digest_state, output_bytes); + } + destroy(digest_state); + return init_result; } }; @@ -655,28 +684,32 @@ struct xkcp_parallelhash_engine : full_engine { template struct xkcp_kmac_engine : full_engine { /** - The tag of `input` under `key`, of `output.size()` bytes. + The tag of `input_bytes` under `key_bytes`, of `output_bytes.size()` bytes. - @param output The tag. @param key The key. @param input The message. - @param options S and the form. + @param output_bytes The tag. @param key_bytes The key. @param input_bytes The message. + @param algorithm_options S and the form. @return Success, or backend_failure. */ [[nodiscard]] static boost::system::result compute( - std::span output, std::span key, - std::span input, mac_options const& options) noexcept { - xkcp_kmac_storage storage{}; - bool done = Functions::initialize( - storage.data(), key.data(), key.size(), options.xof ? 0 : output.size(), - options.customisation.data(), options.customisation.size()) == 0 && - Functions::update(storage.data(), input.data(), input.size()) == 0; - if (done) { - done = options.xof - ? Functions::final(storage.data(), nullptr) == 0 && - Functions::squeeze(storage.data(), output.data(), output.size()) == 0 - : Functions::final(storage.data(), output.data()) == 0; - } - secure::erase_secret(std::span(&storage, 1)); - if (!done) { + std::span output_bytes, std::span key_bytes, + std::span input_bytes, + mac_options const& algorithm_options) noexcept { + xkcp_kmac_storage kmac_storage{}; + bool call_succeeded = + Functions::initialize(kmac_storage.data(), key_bytes.data(), key_bytes.size(), + algorithm_options.xof ? 0 : output_bytes.size(), + algorithm_options.customisation.data(), + algorithm_options.customisation.size()) == 0 && + Functions::update(kmac_storage.data(), input_bytes.data(), input_bytes.size()) == 0; + if (call_succeeded) { + call_succeeded = algorithm_options.xof + ? Functions::final(kmac_storage.data(), nullptr) == 0 && + Functions::squeeze(kmac_storage.data(), output_bytes.data(), + output_bytes.size()) == 0 + : Functions::final(kmac_storage.data(), output_bytes.data()) == 0; + } + secure::erase_secret(std::span(&kmac_storage, 1)); + if (!call_succeeded) { return error::backend_failure; } return {}; @@ -705,67 +738,71 @@ struct xkcp_turboshake_engine : full_engine { /** Starts a hash with the domain byte the options name. - @param hashed The state. @param options D. @return Success, or backend_failure. + @param digest_state The state. @param algorithm_options D. @return Success, or backend_failure. */ [[nodiscard]] static boost::system::result init( - state& hashed, digest_options const& options) noexcept { - hashed.domain = options.domain; - if (webcpp_hash_xkcp_turboshake_initialize(hashed.storage.data(), Capacity) != 0) { + state& digest_state, digest_options const& algorithm_options) noexcept { + digest_state.domain = algorithm_options.domain; + if (webcpp_hash_xkcp_turboshake_initialize(digest_state.storage.data(), Capacity) != 0) { return error::backend_failure; } return {}; } /** - Absorbs `input`. @param hashed The state. @param input The bytes. + Absorbs `input_bytes`. @param digest_state The state. @param input_bytes The bytes. @return Success, or backend_failure. */ [[nodiscard]] static boost::system::result update( - state& hashed, std::span input) noexcept { - if (webcpp_hash_xkcp_turboshake_update(hashed.storage.data(), input.data(), input.size()) != - 0) { + state& digest_state, std::span input_bytes) noexcept { + if (webcpp_hash_xkcp_turboshake_update(digest_state.storage.data(), input_bytes.data(), + input_bytes.size()) != 0) { return error::backend_failure; } return {}; } /** - Absorbs D and writes the first `output.size()` bytes of the stream. + Absorbs D and writes the first `output_bytes.size()` bytes of the stream. - @param hashed The state. @param output The output. @return Success, or backend_failure. + @param digest_state The state. @param output_bytes The output. @return Success, or + backend_failure. */ [[nodiscard]] static boost::system::result finish( - state& hashed, std::span output) noexcept { - if (webcpp_hash_xkcp_turboshake_final(hashed.storage.data(), hashed.domain) != 0 || - webcpp_hash_xkcp_turboshake_squeeze(hashed.storage.data(), output.data(), - output.size()) != 0) { + state& digest_state, std::span output_bytes) noexcept { + if (webcpp_hash_xkcp_turboshake_final(digest_state.storage.data(), digest_state.domain) != + 0 || + webcpp_hash_xkcp_turboshake_squeeze(digest_state.storage.data(), output_bytes.data(), + output_bytes.size()) != 0) { return error::backend_failure; } return {}; } - /** Wipes the state. @param hashed The state. */ - static void destroy(state& hashed) noexcept { secure::erase_secret(std::span(&hashed, 1)); } + /** Wipes the state. @param digest_state The state. */ + static void destroy(state& digest_state) noexcept { + secure::erase_secret(std::span(&digest_state, 1)); + } /** - The output of `input` at once, the state wiped. + The output of `input_bytes` at once, the state wiped. - @param output The output. @param input The bytes. @param options D. + @param output_bytes The output. @param input_bytes The bytes. @param algorithm_options D. @return Success, or backend_failure. */ [[nodiscard]] static boost::system::result one_shot( - std::span output, std::span input, - digest_options const& options) noexcept { - state hashed{}; - auto done = init(hashed, options); - if (done) { - done = update(hashed, input); - } - if (done) { - done = finish(hashed, output); - } - destroy(hashed); - return done; + std::span output_bytes, std::span input_bytes, + digest_options const& algorithm_options) noexcept { + state digest_state{}; + auto init_result = init(digest_state, algorithm_options); + if (init_result) { + init_result = update(digest_state, input_bytes); + } + if (init_result) { + init_result = finish(digest_state, output_bytes); + } + destroy(digest_state); + return init_result; } }; @@ -798,83 +835,86 @@ struct xkcp_kangarootwelve_engine : full_engine { /** Starts a hash, keeping the customisation's span for `finish`. - @param hashed The state. @param options C. + @param digest_state The state. @param algorithm_options C. @return Success, `input_too_long` for a C past `kangarootwelve_max_bytes`, or backend_failure. */ [[nodiscard]] static boost::system::result init( - state& hashed, digest_options const& options) noexcept { - if (exceeds(options.customisation.size(), kangarootwelve_max_bytes)) { + state& digest_state, digest_options const& algorithm_options) noexcept { + if (exceeds(algorithm_options.customisation.size(), kangarootwelve_max_bytes)) { return error::input_too_long; } - hashed.customisation = options.customisation; - hashed.counted = options.customisation.size(); - if (webcpp_hash_xkcp_kangarootwelve_initialize(hashed.storage.data(), SecurityLevel, 0) != - 0) { + digest_state.customisation = algorithm_options.customisation; + digest_state.counted = algorithm_options.customisation.size(); + if (webcpp_hash_xkcp_kangarootwelve_initialize(digest_state.storage.data(), SecurityLevel, + 0) != 0) { return error::backend_failure; } return {}; } /** - Absorbs `input`, unless it would take the message and C past `kangarootwelve_max_bytes`. + Absorbs `input_bytes`, unless it would take the message and C past `kangarootwelve_max_bytes`. - @param hashed The state. @param input The bytes. + @param digest_state The state. @param input_bytes The bytes. @return Success, `input_too_long`, or backend_failure. */ [[nodiscard]] static boost::system::result update( - state& hashed, std::span input) noexcept { + state& digest_state, std::span input_bytes) noexcept { // hashed.counted never exceeds the limit, so the subtraction does not wrap. - if (exceeds(input.size(), kangarootwelve_max_bytes - hashed.counted)) { + if (exceeds(input_bytes.size(), kangarootwelve_max_bytes - digest_state.counted)) { return error::input_too_long; } - if (webcpp_hash_xkcp_kangarootwelve_update(hashed.storage.data(), input.data(), - input.size()) != 0) { + if (webcpp_hash_xkcp_kangarootwelve_update(digest_state.storage.data(), input_bytes.data(), + input_bytes.size()) != 0) { return error::backend_failure; } - hashed.counted += input.size(); + digest_state.counted += input_bytes.size(); return {}; } /** - Absorbs C, ends the input, and writes the first `output.size()` bytes of the stream. + Absorbs C, ends the input, and writes the first `output_bytes.size()` bytes of the stream. - @param hashed The state. @param output The output. @return Success, or backend_failure. + @param digest_state The state. @param output_bytes The output. @return Success, or + backend_failure. */ [[nodiscard]] static boost::system::result finish( - state& hashed, std::span output) noexcept { - if (webcpp_hash_xkcp_kangarootwelve_final(hashed.storage.data(), nullptr, - hashed.customisation.data(), - hashed.customisation.size()) != 0 || - webcpp_hash_xkcp_kangarootwelve_squeeze(hashed.storage.data(), output.data(), - output.size()) != 0) { + state& digest_state, std::span output_bytes) noexcept { + if (webcpp_hash_xkcp_kangarootwelve_final(digest_state.storage.data(), nullptr, + digest_state.customisation.data(), + digest_state.customisation.size()) != 0 || + webcpp_hash_xkcp_kangarootwelve_squeeze( + digest_state.storage.data(), output_bytes.data(), output_bytes.size()) != 0) { return error::backend_failure; } return {}; } - /** Wipes the state. @param hashed The state. */ - static void destroy(state& hashed) noexcept { secure::erase_secret(std::span(&hashed, 1)); } + /** Wipes the state. @param digest_state The state. */ + static void destroy(state& digest_state) noexcept { + secure::erase_secret(std::span(&digest_state, 1)); + } /** - The output of `input` at once, the state wiped. + The output of `input_bytes` at once, the state wiped. - @param output The output. @param input The bytes. @param options C. + @param output_bytes The output. @param input_bytes The bytes. @param algorithm_options C. @return Success, `input_too_long`, or backend_failure. */ [[nodiscard]] static boost::system::result one_shot( - std::span output, std::span input, - digest_options const& options) noexcept { - state hashed{}; - auto done = init(hashed, options); - if (done) { - done = update(hashed, input); - } - if (done) { - done = finish(hashed, output); - } - destroy(hashed); - return done; + std::span output_bytes, std::span input_bytes, + digest_options const& algorithm_options) noexcept { + state digest_state{}; + auto init_result = init(digest_state, algorithm_options); + if (init_result) { + init_result = update(digest_state, input_bytes); + } + if (init_result) { + init_result = finish(digest_state, output_bytes); + } + destroy(digest_state); + return init_result; } }; diff --git a/include/webcpp/hash/bcrypt.hpp b/include/webcpp/hash/bcrypt.hpp index 8c0a2b4..7da77d3 100644 --- a/include/webcpp/hash/bcrypt.hpp +++ b/include/webcpp/hash/bcrypt.hpp @@ -86,68 +86,73 @@ inline constexpr std::size_t bcrypt_pbkdf_max_output = 1024; inline constexpr std::size_t bcrypt_pbkdf_max_salt = 1048576; /** - Whether `version` is one bcrypt writes. + Whether `version_character` is one bcrypt writes. - @param version The character after "$2". @return Whether it is 'a', 'b' or 'y'. + @param version_character The character after "$2". @return Whether it is 'a', 'b' or 'y'. */ -constexpr bool bcrypt_version(char version) noexcept { - return version == 'a' || version == 'b' || version == 'y'; +constexpr bool bcrypt_version(char version_character) noexcept { + return version_character == 'a' || version_character == 'b' || version_character == 'y'; } /** - Whether `c` is a character of bcrypt's base-64 alphabet, "./A-Za-z0-9". + Whether `encoded_character` is a character of bcrypt's base-64 alphabet, "./A-Za-z0-9". - @param c The character. @return Whether bcrypt's encoding writes it. + @param encoded_character The character. @return Whether bcrypt's encoding writes it. */ -constexpr bool bcrypt_base64(char c) noexcept { - return c == '.' || c == '/' || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || - (c >= '0' && c <= '9'); +constexpr bool bcrypt_base64(char encoded_character) noexcept { + return encoded_character == '.' || encoded_character == '/' || + (encoded_character >= 'A' && encoded_character <= 'Z') || + (encoded_character >= 'a' && encoded_character <= 'z') || + (encoded_character >= '0' && encoded_character <= '9'); } /** - The cost of `hash` when it has bcrypt's form: 60 characters, "$2", a version, "$", a cost of 04 - to 31 in two digits, "$", then 53 characters of bcrypt's base-64 alphabet. + The cost of `encoded_hash` when it has bcrypt's form: 60 characters, "$2", a version, "$", a cost + of 04 to 31 in two digits, "$", then 53 characters of bcrypt's base-64 alphabet. - @param hash The string. @return Its cost; 0 when it does not have the form. + @param encoded_hash The string. @return Its cost; 0 when it does not have the form. */ -constexpr std::uint32_t bcrypt_cost_of(std::string_view hash) noexcept { +constexpr std::uint32_t bcrypt_cost_of(std::string_view encoded_hash) noexcept { constexpr std::size_t cost_at = 4; constexpr std::size_t encoded_at = 7; - if (hash.size() != bcrypt_hash_size || hash[0] != '$' || hash[1] != '2' || - !bcrypt_version(hash[2]) || hash[3] != '$' || hash[6] != '$') { + if (encoded_hash.size() != bcrypt_hash_size || encoded_hash[0] != '$' || + encoded_hash[1] != '2' || !bcrypt_version(encoded_hash[2]) || encoded_hash[3] != '$' || + encoded_hash[6] != '$') { return 0; } - char const tens = hash[cost_at]; - char const units = hash[cost_at + 1]; - if (tens < '0' || tens > '9' || units < '0' || units > '9') { + char const tens_digit = encoded_hash[cost_at]; + char const units_digit = encoded_hash[cost_at + 1]; + if (tens_digit < '0' || tens_digit > '9' || units_digit < '0' || units_digit > '9') { return 0; } - constexpr std::uint32_t decimal = 10; - std::uint32_t const cost = (static_cast(tens - '0') * decimal) + - static_cast(units - '0'); - if (cost < bcrypt_min_cost || cost > bcrypt_max_cost) { + constexpr std::uint32_t decimal_base = 10; + std::uint32_t const bcrypt_cost = + (static_cast(tens_digit - '0') * decimal_base) + + static_cast(units_digit - '0'); + if (bcrypt_cost < bcrypt_min_cost || bcrypt_cost > bcrypt_max_cost) { return 0; } - for (std::size_t index = encoded_at; index < hash.size(); ++index) { - if (!bcrypt_base64(hash[index])) { + for (std::size_t character_index = encoded_at; character_index < encoded_hash.size(); + ++character_index) { + if (!bcrypt_base64(encoded_hash[character_index])) { return 0; } } - return cost; + return bcrypt_cost; } /** The guards of a password of bcrypt: at most 72 bytes (`input_too_long`) and without a zero byte (`invalid_parameters`). - @param password The password. @return Success, or the guard's error. + @param password_bytes The password. @return Success, or the guard's error. */ [[nodiscard]] inline boost::system::result bcrypt_password_guards( - std::span password) noexcept { - if (password.size() > bcrypt_max_password_size) { + std::span password_bytes) noexcept { + if (password_bytes.size() > bcrypt_max_password_size) { return error::input_too_long; } - if (std::ranges::find(password, std::uint8_t{0}) != password.end()) { + if (std::ranges::find(password_bytes, std::uint8_t{0}) != password_bytes.end()) { return error::invalid_parameters; } return {}; @@ -158,29 +163,29 @@ constexpr std::uint32_t bcrypt_cost_of(std::string_view hash) noexcept { before it posts the work to another thread. @tparam Backend The backend. - @param output_size The output's size. @param password The password. - @param salt_size The salt's size. @param parameters The cost and the version. + @param output_size The output's size. @param password_bytes The password. + @param salt_size The salt's size. @param cost_parameters The cost and the version. @return Success, or the error of the first guard that fails, as `bcrypt` returns it. */ template [[nodiscard]] boost::system::result bcrypt_guards( - std::size_t output_size, std::span password, std::size_t salt_size, - bcrypt_parameters const& parameters) noexcept { + std::size_t output_size, std::span password_bytes, std::size_t salt_size, + bcrypt_parameters const& cost_parameters) noexcept { if (output_size != bcrypt_hash_size) { return error::invalid_output_size; } if (salt_size != bcrypt_salt_size) { return error::invalid_salt_size; } - auto const password_guarded = bcrypt_password_guards(password); + auto const password_guarded = bcrypt_password_guards(password_bytes); if (!password_guarded) { return password_guarded; } - if (parameters.cost < bcrypt_min_cost || parameters.cost > bcrypt_max_cost || - !bcrypt_version(parameters.version)) { + if (cost_parameters.cost < bcrypt_min_cost || cost_parameters.cost > bcrypt_max_cost || + !bcrypt_version(cost_parameters.version)) { return error::invalid_parameters; } - if (parameters.cost > bcrypt_engine::max_cost) { + if (cost_parameters.cost > bcrypt_engine::max_cost) { return error::unsupported_by_backend; } return {}; @@ -191,21 +196,21 @@ template `async_bcrypt_verify` checks before it posts the work to another thread. @tparam Backend The backend. - @param password The password. @param hash The string. + @param password_bytes The password. @param encoded_hash The string. @return Success, or the error of the first guard that fails, as `bcrypt_verify` returns it. */ template [[nodiscard]] boost::system::result bcrypt_verify_guards( - std::span password, std::string_view hash) noexcept { - auto const password_guarded = bcrypt_password_guards(password); + std::span password_bytes, std::string_view encoded_hash) noexcept { + auto const password_guarded = bcrypt_password_guards(password_bytes); if (!password_guarded) { return password_guarded; } - std::uint32_t const cost = bcrypt_cost_of(hash); - if (cost == 0) { + std::uint32_t const bcrypt_cost = bcrypt_cost_of(encoded_hash); + if (bcrypt_cost == 0) { return error::invalid_parameters; } - if (cost > bcrypt_engine::max_cost) { + if (bcrypt_cost > bcrypt_engine::max_cost) { return error::unsupported_by_backend; } return {}; @@ -216,12 +221,12 @@ template checks before it posts the work to another thread. @param output_size The output's size. @param password_size The password's size. - @param salt_size The salt's size. @param rounds The rounds. + @param salt_size The salt's size. @param round_count The rounds. @return Success, or the error of the first guard that fails, as `bcrypt_pbkdf` returns it. */ [[nodiscard]] inline boost::system::result bcrypt_pbkdf_guards( std::size_t output_size, std::size_t password_size, std::size_t salt_size, - std::uint32_t rounds) noexcept { + std::uint32_t round_count) noexcept { if (output_size == 0 || output_size > bcrypt_pbkdf_max_output) { return error::invalid_output_size; } @@ -231,7 +236,7 @@ template if (password_size == 0) { return error::invalid_key_size; } - if (rounds == 0) { + if (round_count == 0) { return error::invalid_iterations; } return {}; @@ -240,93 +245,101 @@ template } // namespace detail /** - The modular crypt string of `password` under the caller's 16-byte `salt`, into 60 chars: + The modular crypt string of `password_bytes` under the caller's 16-byte `salt_bytes`, into 60 + chars: "$2", the version, "$", the cost in two digits, "$", the salt then the hash in bcrypt's base 64. @tparam Backend The backend; @ref default_backend of `kdfs::bcrypt` has none (design D34): the call names `backends::botan`. - @param output The string, exactly `bcrypt_hash_size` characters, not terminated by a zero. - @param password The password, at most `bcrypt_max_password_size` bytes, without a zero byte. - @param salt The salt, exactly `bcrypt_salt_size` random bytes. - @param parameters The cost (4 to 31) and the version ('a', 'b' or 'y'). + @param output_characters The string, exactly `bcrypt_hash_size` characters, not terminated by a + zero. + @param password_bytes The password, at most `bcrypt_max_password_size` bytes, without a zero byte. + @param salt_bytes The salt, exactly `bcrypt_salt_size` random bytes. + @param cost_parameters The cost (4 to 31) and the version ('a', 'b' or 'y'). @return Success; or the first guard's error (`invalid_output_size`, `invalid_salt_size`, `input_too_long`, `invalid_parameters`, then the backend's `unsupported_by_backend`: - `backends::botan`'s cost above 18), `output` untouched; or `errc::not_enough_memory` or - `backend_failure`, `output` zeroed. + `backends::botan`'s cost above 18), `output_characters` untouched; or `errc::not_enough_memory` or + `backend_failure`, `output_characters` zeroed. */ template > -[[nodiscard]] boost::system::result bcrypt(std::span output, - std::span password, - std::span salt, - bcrypt_parameters const& parameters = {}) { - secure::timing_guard const timing; - auto guarded = detail::bcrypt_guards(output.size(), password, salt.size(), parameters); - if (!guarded) { - return guarded; +[[nodiscard]] boost::system::result bcrypt(std::span output_characters, + std::span password_bytes, + std::span salt_bytes, + bcrypt_parameters const& cost_parameters = {}) { + secure::timing_guard const timing_scope; + auto guard_result = detail::bcrypt_guards(output_characters.size(), password_bytes, + salt_bytes.size(), cost_parameters); + if (!guard_result) { + return guard_result; } - auto made = detail::bcrypt_engine::generate(output, password, salt, parameters.cost, - parameters.version); - if (!made) { - secure::erase_secret(output); + auto generate_result = + detail::bcrypt_engine::generate(output_characters, password_bytes, salt_bytes, + cost_parameters.cost, cost_parameters.version); + if (!generate_result) { + secure::erase_secret(output_characters); } - return made; + return generate_result; } /** - Whether `password` gives `hash`, a modular crypt string of bcrypt, compared in constant time. + Whether `password_bytes` gives `encoded_hash`, a modular crypt string of bcrypt, compared in + constant time. A caller that checks strings made by an implementation that silently cuts a longer password (at 72 bytes, as OpenBSD's and most others do) passes the first 72 bytes of the password: bcrypt reads no more, so the answer is the same, where the whole password is refused with `input_too_long`. @tparam Backend The backend; the call names `backends::botan`, as for @ref bcrypt. - @param password The password, at most `bcrypt_max_password_size` bytes, without a zero byte. - @param hash The string, `bcrypt_hash_size` characters of bcrypt's form. + @param password_bytes The password, at most `bcrypt_max_password_size` bytes, without a zero byte. + @param encoded_hash The string, `bcrypt_hash_size` characters of bcrypt's form. @return `true` when the password gives the string, `false` otherwise; or the first guard's error (`input_too_long` or `invalid_parameters` for the password, `invalid_parameters` for a string not of bcrypt's form, then the backend's `unsupported_by_backend`: `backends::botan`'s cost above 18); or `errc::not_enough_memory` or `backend_failure`. */ template > -[[nodiscard]] boost::system::result bcrypt_verify(std::span password, - std::string_view hash) { - secure::timing_guard const timing; - auto const guarded = detail::bcrypt_verify_guards(password, hash); - if (!guarded) { - return guarded.error(); +[[nodiscard]] boost::system::result bcrypt_verify( + std::span password_bytes, std::string_view encoded_hash) { + secure::timing_guard const timing_scope; + auto const guard_result = detail::bcrypt_verify_guards(password_bytes, encoded_hash); + if (!guard_result) { + return guard_result.error(); } - return detail::bcrypt_engine::verify(password, hash); + return detail::bcrypt_engine::verify(password_bytes, encoded_hash); } /** - OpenBSD's bcrypt_pbkdf, as OpenSSH's keys use it: fills `output` from `password` and `salt` by - `rounds` rounds of bcrypt's hash over their SHA-512 digests, its blocks interleaved. + OpenBSD's bcrypt_pbkdf, as OpenSSH's keys use it: fills `output_bytes` from `password_bytes` and + `salt_bytes` by `round_count` rounds of bcrypt's hash over their SHA-512 digests, its blocks + interleaved. @tparam Backend The backend; @ref default_backend of `kdfs::bcrypt_pbkdf` has none (design D34): the call names `backends::botan`. - @param output The derived key, 1 to 1,024 bytes. - @param password The password, 1 byte or more. - @param salt The salt, 1 to 1,048,576 bytes. - @param rounds The rounds, 1 or more. + @param output_bytes The derived key, 1 to 1,024 bytes. + @param password_bytes The password, 1 byte or more. + @param salt_bytes The salt, 1 to 1,048,576 bytes. + @param round_count The rounds, 1 or more. @return Success; or the first guard's error (`invalid_output_size`, `invalid_salt_size`, - `invalid_key_size`, `invalid_iterations`), `output` untouched; or `errc::not_enough_memory` or - `backend_failure`, `output` zeroed. + `invalid_key_size`, `invalid_iterations`), `output_bytes` untouched; or `errc::not_enough_memory` + or `backend_failure`, `output_bytes` zeroed. */ template > -[[nodiscard]] boost::system::result bcrypt_pbkdf(std::span output, - std::span password, - std::span salt, - std::uint32_t rounds) { - secure::timing_guard const timing; - auto guarded = detail::bcrypt_pbkdf_guards(output.size(), password.size(), salt.size(), rounds); - if (!guarded) { - return guarded; +[[nodiscard]] boost::system::result bcrypt_pbkdf(std::span output_bytes, + std::span password_bytes, + std::span salt_bytes, + std::uint32_t round_count) { + secure::timing_guard const timing_scope; + auto guard_result = detail::bcrypt_pbkdf_guards(output_bytes.size(), password_bytes.size(), + salt_bytes.size(), round_count); + if (!guard_result) { + return guard_result; } - auto derived = detail::bcrypt_pbkdf_engine::derive(output, password, salt, rounds); - if (!derived) { - secure::erase_secret(output); + auto derive_result = detail::bcrypt_pbkdf_engine::derive(output_bytes, password_bytes, + salt_bytes, round_count); + if (!derive_result) { + secure::erase_secret(output_bytes); } - return derived; + return derive_result; } } // namespace webcpp::hash diff --git a/include/webcpp/hash/blake2b_subkey.hpp b/include/webcpp/hash/blake2b_subkey.hpp index 6ed0ef7..3cd56de 100644 --- a/include/webcpp/hash/blake2b_subkey.hpp +++ b/include/webcpp/hash/blake2b_subkey.hpp @@ -60,9 +60,9 @@ inline constexpr std::size_t blake2b_subkey_key_size = 32; inline constexpr std::size_t blake2b_subkey_context_size = 8; /** - The subkey `subkey_id` of `master_key` in `context`, libsodium's `crypto_kdf_derive_from_key`: - keys for different purposes from one master key, each unrelated to the others and to the master - key without it. + The subkey `subkey_id` of `master_key` in `context_bytes`, libsodium's + `crypto_kdf_derive_from_key`: keys for different purposes from one master key, each unrelated to + the others and to the master key without it. @code std::array file_key{}; @@ -72,37 +72,38 @@ inline constexpr std::size_t blake2b_subkey_context_size = 8; @tparam Backend The backend; by default @ref default_backend of `kdfs::blake2b_subkey` (spec 4.1), `backends::sodium`, the only one that has it. Another backend, or a program that does not link libsodium, refuses at compile time. - @param output The subkey, 16 to 64 bytes; it must not overlap `master_key` or `context`. Its - length is a parameter of BLAKE2b: a subkey of 32 bytes is not the first 32 bytes of the one of 64. + @param output_bytes The subkey, 16 to 64 bytes; it must not overlap `master_key` or + `context_bytes`. Its length is a parameter of BLAKE2b: a subkey of 32 bytes is not the first 32 + bytes of the one of 64. @param master_key The master key, 32 bytes, secret and uniformly random. @param subkey_id The subkey's number, any 64-bit value: one per key the application needs. - @param context 8 bytes naming the application or its purpose, as "vault v1": the same id in + @param context_bytes 8 bytes naming the application or its purpose, as "vault v1": the same id in another context gives an unrelated subkey. Not secret. @return Success; or the first guard's error (`invalid_output_size`, `invalid_key_size`, - `invalid_parameters` for the context), `output` untouched; or `backend_failure`, `output` - zeroed. + `invalid_parameters` for the context), `output_bytes` untouched; or `backend_failure`, + `output_bytes` zeroed. */ template > -[[nodiscard]] boost::system::result blake2b_subkey(std::span output, - std::span master_key, - std::uint64_t subkey_id, - std::span context) { - secure::timing_guard const timing; +[[nodiscard]] boost::system::result blake2b_subkey( + std::span output_bytes, std::span master_key, + std::uint64_t subkey_id, std::span context_bytes) { + secure::timing_guard const timing_scope; using engine = detail::blake2b_subkey_engine; - if (output.size() < blake2b_subkey_min_size || output.size() > blake2b_subkey_max_size) { + if (output_bytes.size() < blake2b_subkey_min_size || + output_bytes.size() > blake2b_subkey_max_size) { return error::invalid_output_size; } if (master_key.size() != blake2b_subkey_key_size) { return error::invalid_key_size; } - if (context.size() != blake2b_subkey_context_size) { + if (context_bytes.size() != blake2b_subkey_context_size) { return error::invalid_parameters; } - auto derived = engine::derive(output, master_key, subkey_id, context); - if (!derived) { - secure::erase_secret(output); + auto derive_result = engine::derive(output_bytes, master_key, subkey_id, context_bytes); + if (!derive_result) { + secure::erase_secret(output_bytes); } - return derived; + return derive_result; } } // namespace webcpp::hash diff --git a/include/webcpp/hash/blake3.hpp b/include/webcpp/hash/blake3.hpp index 9a75cce..d49366f 100644 --- a/include/webcpp/hash/blake3.hpp +++ b/include/webcpp/hash/blake3.hpp @@ -176,7 +176,7 @@ class blake3 { struct uninitialized {}; // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init): keyed and derive_key initialize it. - explicit blake3(uninitialized /*tag*/) noexcept {} + explicit blake3(uninitialized /*uninitialized_tag*/) noexcept {} blake3_hasher hasher_; // the C implementation's state, 1,912 bytes on 64-bit targets std::uint64_t squeezed_ = 0; // bytes result() returned since input was last added @@ -193,7 +193,7 @@ inline blake3::blake3() noexcept { } inline blake3::blake3(std::uint64_t seed_value) noexcept { - secure::timing_guard const timing{seed_value != 0}; + secure::timing_guard const timing_scope{seed_value != 0}; detail::touch_blake3_canary(); keyed_ = seed_value != 0; if (seed_value == 0) { @@ -211,7 +211,7 @@ inline blake3::blake3(void const* input_data, std::size_t input_size) noexcept : blake3(static_cast(input_data), input_size) {} inline blake3::blake3(unsigned char const* input_data, std::size_t input_size) noexcept { - secure::timing_guard const timing{input_size != 0}; + secure::timing_guard const timing_scope{input_size != 0}; detail::touch_blake3_canary(); keyed_ = input_size != 0; if (input_size == 0) { @@ -231,7 +231,7 @@ inline blake3::blake3(unsigned char const* input_data, std::size_t input_size) n // NOLINTEND(cppcoreguidelines-pro-type-member-init) inline blake3 blake3::keyed(std::span key_bytes) noexcept { - secure::timing_guard const timing; + secure::timing_guard const timing_scope; detail::touch_blake3_canary(); blake3 derived_hasher{uninitialized{}}; derived_hasher.keyed_ = true; @@ -240,7 +240,7 @@ inline blake3 blake3::keyed(std::span key_bytes) noexcep } inline blake3 blake3::derive_key(std::string_view context_string) noexcept { - secure::timing_guard const timing; + secure::timing_guard const timing_scope; detail::touch_blake3_canary(); blake3 derived_hasher{uninitialized{}}; derived_hasher.keyed_ = true; @@ -250,12 +250,12 @@ inline blake3 blake3::derive_key(std::string_view context_string) noexcept { } inline void blake3::update(void const* input_data, std::size_t input_size) noexcept { - secure::timing_guard const timing{keyed_}; + secure::timing_guard const timing_scope{keyed_}; update(static_cast(input_data), input_size); } inline void blake3::update(unsigned char const* input_data, std::size_t input_size) noexcept { - secure::timing_guard const timing{keyed_}; + secure::timing_guard const timing_scope{keyed_}; detail::touch_blake3_canary(); if (input_size == 0) { return; @@ -265,7 +265,7 @@ inline void blake3::update(unsigned char const* input_data, std::size_t input_si } inline blake3::result_type blake3::result() noexcept { - secure::timing_guard const timing{keyed_}; + secure::timing_guard const timing_scope{keyed_}; detail::touch_blake3_canary(); result_type output_bytes; blake3_hasher_finalize_seek(&hasher_, squeezed_, output_bytes.data(), output_bytes.size()); @@ -275,13 +275,13 @@ inline blake3::result_type blake3::result() noexcept { inline void blake3::squeeze(std::span output_bytes, std::uint64_t seek_position) const noexcept { - secure::timing_guard const timing{keyed_}; + secure::timing_guard const timing_scope{keyed_}; detail::touch_blake3_canary(); blake3_hasher_finalize_seek(&hasher_, seek_position, output_bytes.data(), output_bytes.size()); } inline void blake3::reset() noexcept { - secure::timing_guard const timing{keyed_}; + secure::timing_guard const timing_scope{keyed_}; detail::touch_blake3_canary(); blake3_hasher_reset(&hasher_); squeezed_ = 0; diff --git a/include/webcpp/hash/byte_pieces.hpp b/include/webcpp/hash/byte_pieces.hpp index 3c66835..3d7bc13 100644 --- a/include/webcpp/hash/byte_pieces.hpp +++ b/include/webcpp/hash/byte_pieces.hpp @@ -70,8 +70,8 @@ class byte_pieces { @param pieces The list; its array must outlive this object (it does, written at the call). */ constexpr byte_pieces( // NOLINT(misc-explicit-constructor): {a, b} converts to its pieces - std::initializer_list pieces WEBCPP_HASH_LIFETIMEBOUND) noexcept - : first_(std::data(pieces)), count_(pieces.size()) {} + std::initializer_list piece_list WEBCPP_HASH_LIFETIMEBOUND) noexcept + : first_(std::data(piece_list)), count_(piece_list.size()) {} /** The pieces of a contiguous range of spans of bytes: a `std::array`, a `std::vector`, a @@ -85,8 +85,8 @@ class byte_pieces { std::same_as, value_type> && (!std::same_as, byte_pieces>) // NOLINTNEXTLINE(misc-explicit-constructor): a range of spans is its pieces, as {a, b} is - constexpr byte_pieces(Range const& pieces WEBCPP_HASH_LIFETIMEBOUND) noexcept - : first_(std::ranges::data(pieces)), count_(std::ranges::size(pieces)) {} + constexpr byte_pieces(Range const& piece_range WEBCPP_HASH_LIFETIMEBOUND) noexcept + : first_(std::ranges::data(piece_range)), count_(std::ranges::size(piece_range)) {} /** The start of the pieces. @return A pointer to the first piece. */ [[nodiscard]] constexpr value_type const* begin() const noexcept { return first_; } @@ -102,11 +102,11 @@ class byte_pieces { /** The length of the input the pieces make. @return The bytes of all pieces, summed. */ [[nodiscard]] constexpr std::uint64_t total_size() const noexcept { - std::uint64_t total = 0; - for (value_type const piece : *this) { - total += piece.size(); + std::uint64_t total_bytes = 0; + for (value_type const piece_bytes : *this) { + total_bytes += piece_bytes.size(); } - return total; + return total_bytes; } private: diff --git a/include/webcpp/hash/detail/engines.hpp b/include/webcpp/hash/detail/engines.hpp index dceedc1..5b6e7bc 100644 --- a/include/webcpp/hash/detail/engines.hpp +++ b/include/webcpp/hash/detail/engines.hpp @@ -222,25 +222,26 @@ inline constexpr std::uint64_t hkdf_pieces_slice = : hkdf_pieces_slice_seam; /** - Hands `update` every byte of `pieces`, in order, as spans of at most `SliceMax` bytes: each - piece in one span when it fits, else in slices of `SliceMax` bytes and a last shorter one. An + Hands `update_call` every byte of `input_pieces`, in order, as spans of at most `SliceMax` bytes: + each piece in one span when it fits, else in slices of `SliceMax` bytes and a last shorter one. An empty piece is skipped (an HMAC's zero-length update changes nothing, and some C libraries take no null pointer). @tparam SliceMax The most bytes of one call, at least 1 (a slice of no byte would never advance, so 0 does not compile). @tparam Update A callable taking a `std::span`. - @param pieces The pieces. @param update What reads each slice. + @param input_pieces The pieces. @param update_call What reads each slice. */ template requires(SliceMax >= 1) -constexpr void for_each_slice(byte_pieces pieces, Update&& update) noexcept( - noexcept(update(byte_pieces::value_type{}))) { - for (byte_pieces::value_type rest : pieces) { - while (!rest.empty()) { - std::size_t const taken = - rest.size() > SliceMax ? static_cast(SliceMax) : rest.size(); - update(rest.first(taken)); - rest = rest.subspan(taken); +constexpr void for_each_slice(byte_pieces input_pieces, Update&& update_call) noexcept( + noexcept(update_call(byte_pieces::value_type{}))) { + for (byte_pieces::value_type remaining_piece : input_pieces) { + while (!remaining_piece.empty()) { + std::size_t const slice_size = remaining_piece.size() > SliceMax + ? static_cast(SliceMax) + : remaining_piece.size(); + update_call(remaining_piece.first(slice_size)); + remaining_piece = remaining_piece.subspan(slice_size); } } } @@ -298,18 +299,18 @@ struct hkdf_pieces_engine { Expand over the PRK, and the PRK wiped before the result returns (on success and on failure of the Expand). One copy, so that the wipe is the same on every backend. - @tparam Engine A pieces engine with `extract(salt, input_key_material)` returning a + @tparam Engine A pieces engine with `extract(salt_bytes, input_key_material)` returning a `boost::system::result` of the PRK's byte array and `expand(output, pseudorandom_key, info)`. - @param output_key_material The OKM. @param salt The salt. + @param output_key_material The OKM. @param salt_bytes The salt. @param input_key_material The input keying material's pieces. @param application_info The info's pieces. @return Success, or the Extract's or the Expand's error. */ template [[nodiscard]] boost::system::result hkdf_pieces_extract_and_expand( - std::span output_key_material, std::span salt, + std::span output_key_material, std::span salt_bytes, byte_pieces input_key_material, byte_pieces application_info) noexcept { - auto pseudorandom_key = Engine::extract(salt, input_key_material); + auto pseudorandom_key = Engine::extract(salt_bytes, input_key_material); if (!pseudorandom_key) { return pseudorandom_key.error(); } @@ -548,7 +549,7 @@ struct blake2b_subkey_engine { /** Never called: the refusal has stopped the build. */ [[nodiscard]] static boost::system::result derive( std::span /*output_bytes*/, std::span /*master_key*/, - std::uint64_t /*subkey_id*/, std::span /*context*/) noexcept { + std::uint64_t /*subkey_id*/, std::span /*context_bytes*/) noexcept { return error::backend_failure; } }; @@ -703,7 +704,7 @@ struct full_engine { @return true. */ template - static constexpr bool accepts(Options const& /*options*/) noexcept { + static constexpr bool accepts(Options const& /*algorithm_options*/) noexcept { return true; } @@ -713,7 +714,7 @@ struct full_engine { @return true. */ template - static constexpr bool accepts(Options const& /*options*/, std::size_t /*key_size*/, + static constexpr bool accepts(Options const& /*algorithm_options*/, std::size_t /*key_size*/, std::size_t /*output_size*/) noexcept { return true; } @@ -783,29 +784,29 @@ struct refused_digest_engine : full_engine { /** Never called. @return backend_failure. */ [[nodiscard]] static boost::system::result init( - state& /*hashed*/, digest_options const& /*options*/) noexcept { + state& /*digest_state*/, digest_options const& /*algorithm_options*/) noexcept { return error::backend_failure; } /** Never called. @return backend_failure. */ [[nodiscard]] static boost::system::result update( - state& /*hashed*/, std::span /*input*/) noexcept { + state& /*digest_state*/, std::span /*input_bytes*/) noexcept { return error::backend_failure; } /** Never called. @return backend_failure. */ [[nodiscard]] static boost::system::result finish( - state& /*hashed*/, std::span /*output*/) noexcept { + state& /*digest_state*/, std::span /*output_bytes*/) noexcept { return error::backend_failure; } /** Never called. */ - static void destroy(state& /*hashed*/) noexcept {} + static void destroy(state& /*digest_state*/) noexcept {} /** Never called. @return backend_failure. */ [[nodiscard]] static boost::system::result one_shot( - std::span /*output*/, std::span /*input*/, - digest_options const& /*options*/) noexcept { + std::span /*output_bytes*/, std::span /*input_bytes*/, + digest_options const& /*algorithm_options*/) noexcept { return error::backend_failure; } }; @@ -1228,8 +1229,9 @@ template struct refused_mac_engine : full_engine { /** Never called. @return backend_failure. */ [[nodiscard]] static boost::system::result compute( - std::span /*output*/, std::span /*key*/, - std::span /*input*/, mac_options const& /*options*/) noexcept { + std::span /*output_bytes*/, std::span /*key_bytes*/, + std::span /*input_bytes*/, + mac_options const& /*algorithm_options*/) noexcept { return error::backend_failure; } }; @@ -1621,8 +1623,9 @@ struct refused_argon2_engine { /** Never called. @return backend_failure. */ [[nodiscard]] static boost::system::result derive( - std::span /*output*/, std::span /*password*/, - std::span /*salt*/, argon2_parameters const& /*parameters*/) noexcept { + std::span /*output_bytes*/, std::span /*password_bytes*/, + std::span /*salt_bytes*/, + argon2_parameters const& /*cost_parameters*/) noexcept { return error::backend_failure; } }; @@ -1720,8 +1723,8 @@ struct kbkdf_engine : needs_library { /** Never called: the refusal has stopped the build. @return backend_failure. */ [[nodiscard]] static boost::system::result derive( - std::span /*output*/, std::span /*key*/, - kbkdf_options const& /*options*/) noexcept { + std::span /*output_bytes*/, std::span /*key_bytes*/, + kbkdf_options const& /*algorithm_options*/) noexcept { return error::backend_failure; } }; @@ -1736,8 +1739,8 @@ struct refused_digest_kdf_engine { /** Never called. @return backend_failure. */ [[nodiscard]] static boost::system::result derive( - std::span /*output*/, std::span /*secret*/, - std::span /*info*/) noexcept { + std::span /*output_bytes*/, std::span /*secret_bytes*/, + std::span /*info_bytes*/) noexcept { return error::backend_failure; } }; @@ -1840,14 +1843,16 @@ struct bcrypt_engine : needs_library { /** Never called: the refusal has stopped the build. @return backend_failure. */ [[nodiscard]] static boost::system::result generate( - std::span /*output*/, std::span /*password*/, - std::span /*salt*/, std::uint32_t /*cost*/, char /*version*/) noexcept { + std::span /*output_characters*/, std::span /*password_bytes*/, + std::span /*salt_bytes*/, std::uint32_t /*bcrypt_cost*/, + char /*version_character*/) noexcept { return error::backend_failure; } /** Never called: the refusal has stopped the build. @return backend_failure. */ [[nodiscard]] static boost::system::result verify( - std::span /*password*/, std::string_view /*hash*/) noexcept { + std::span /*password_bytes*/, + std::string_view /*encoded_hash*/) noexcept { return error::backend_failure; } }; @@ -1879,8 +1884,8 @@ struct bcrypt_pbkdf_engine : needs_library { /** Never called: the refusal has stopped the build. @return backend_failure. */ [[nodiscard]] static boost::system::result derive( - std::span /*output*/, std::span /*password*/, - std::span /*salt*/, std::uint32_t /*rounds*/) noexcept { + std::span /*output_bytes*/, std::span /*password_bytes*/, + std::span /*salt_bytes*/, std::uint32_t /*round_count*/) noexcept { return error::backend_failure; } }; diff --git a/include/webcpp/hash/digest.hpp b/include/webcpp/hash/digest.hpp index c59d504..30dd991 100644 --- a/include/webcpp/hash/digest.hpp +++ b/include/webcpp/hash/digest.hpp @@ -284,7 +284,7 @@ struct fixed_output { @return `Size`. */ template - static constexpr std::uint64_t min_output(Options const& /*options*/) noexcept { + static constexpr std::uint64_t min_output(Options const& /*algorithm_options*/) noexcept { return Size; } @@ -294,7 +294,7 @@ struct fixed_output { @return `Size`. */ template - static constexpr std::uint64_t max_output(Options const& /*options*/) noexcept { + static constexpr std::uint64_t max_output(Options const& /*algorithm_options*/) noexcept { return Size; } @@ -305,7 +305,7 @@ struct fixed_output { */ template [[nodiscard]] static constexpr boost::system::result check( - Options const& /*options*/) noexcept { + Options const& /*algorithm_options*/) noexcept { return {}; } }; @@ -318,7 +318,7 @@ struct extendable_output { @return 1. */ template - static constexpr std::uint64_t min_output(Options const& /*options*/) noexcept { + static constexpr std::uint64_t min_output(Options const& /*algorithm_options*/) noexcept { return 1; } @@ -328,7 +328,7 @@ struct extendable_output { @return `no_limit`. */ template - static constexpr std::uint64_t max_output(Options const& /*options*/) noexcept { + static constexpr std::uint64_t max_output(Options const& /*algorithm_options*/) noexcept { return no_limit; } @@ -339,7 +339,7 @@ struct extendable_output { */ template [[nodiscard]] static constexpr boost::system::result check( - Options const& /*options*/) noexcept { + Options const& /*algorithm_options*/) noexcept { return {}; } }; @@ -434,43 +434,44 @@ struct digest_traits { /** The shortest output: the options' size, and at least 1. - @param options The options. @return The size the output must have. + @param algorithm_options The options. @return The size the output must have. */ static constexpr std::uint64_t min_output( - digest_options const& options) noexcept { - return options.output_size == 0 ? 1 : options.output_size; + digest_options const& algorithm_options) noexcept { + return algorithm_options.output_size == 0 ? 1 : algorithm_options.output_size; } /** The longest output: the options' size, and at most 64, so that an output size out of range refuses every output. - @param options The options. @return The size the output must have. + @param algorithm_options The options. @return The size the output must have. */ static constexpr std::uint64_t max_output( - digest_options const& options) noexcept { - return options.output_size > max_size ? max_size : options.output_size; + digest_options const& algorithm_options) noexcept { + return algorithm_options.output_size > max_size ? max_size : algorithm_options.output_size; } /** Checks the options, in order: the output size, the key, the salt, the personalisation. - @param options The options. + @param algorithm_options The options. @return Success; or `invalid_output_size`, `invalid_key_size`, `invalid_salt_size` or `invalid_parameters`. */ [[nodiscard]] static constexpr boost::system::result check( - digest_options const& options) noexcept { - if (options.output_size == 0 || options.output_size > max_size) { + digest_options const& algorithm_options) noexcept { + if (algorithm_options.output_size == 0 || algorithm_options.output_size > max_size) { return error::invalid_output_size; } - if (options.key.size() > max_size) { + if (algorithm_options.key.size() > max_size) { return error::invalid_key_size; } - if (!options.salt.empty() && options.salt.size() != block_part_size) { + if (!algorithm_options.salt.empty() && algorithm_options.salt.size() != block_part_size) { return error::invalid_salt_size; } - if (!options.personalisation.empty() && options.personalisation.size() != block_part_size) { + if (!algorithm_options.personalisation.empty() && + algorithm_options.personalisation.size() != block_part_size) { return error::invalid_parameters; } return {}; @@ -491,12 +492,12 @@ struct turboshake_traits : extendable_output { /** Checks the domain byte. - @param options The options. @return Success, or `invalid_parameters`. + @param algorithm_options The options. @return Success, or `invalid_parameters`. */ template [[nodiscard]] static constexpr boost::system::result check( - Options const& options) noexcept { - if (options.domain < min_domain || options.domain > max_domain) { + Options const& algorithm_options) noexcept { + if (algorithm_options.domain < min_domain || algorithm_options.domain > max_domain) { return error::invalid_parameters; } return {}; @@ -535,15 +536,15 @@ struct cshake_traits : extendable_output { /** Checks the function name, then the customisation. - @param options The options. @return Success, or `input_too_long`. + @param algorithm_options The options. @return Success, or `input_too_long`. */ [[nodiscard]] static boost::system::result check( - digest_options const& options) noexcept { - auto named = check_sp800_185_string(options.function_name); - if (!named) { - return named; + digest_options const& algorithm_options) noexcept { + auto name_check = check_sp800_185_string(algorithm_options.function_name); + if (!name_check) { + return name_check; } - return check_sp800_185_string(options.customisation); + return check_sp800_185_string(algorithm_options.customisation); } }; @@ -570,33 +571,35 @@ struct sp800_185_hash_traits { @return 1. */ - static constexpr std::uint64_t min_output(digest_options const& /*options*/) noexcept { + static constexpr std::uint64_t min_output( + digest_options const& /*algorithm_options*/) noexcept { return 1; } /** The longest output: `sp800_185_max_bytes` in the fixed-length form, no limit in the XOF form. - @param options The options. @return The longest output. + @param algorithm_options The options. @return The longest output. */ - static constexpr std::uint64_t max_output(digest_options const& options) noexcept { - return options.xof ? no_limit : sp800_185_max_bytes; + static constexpr std::uint64_t max_output( + digest_options const& algorithm_options) noexcept { + return algorithm_options.xof ? no_limit : sp800_185_max_bytes; } /** Checks ParallelHash's block size, then the customisation. - @param options The options. + @param algorithm_options The options. @return Success, `invalid_parameters` or `input_too_long`. */ [[nodiscard]] static boost::system::result check( - digest_options const& options) noexcept { - if constexpr (requires { options.block_size; }) { - if (options.block_size == 0) { + digest_options const& algorithm_options) noexcept { + if constexpr (requires { algorithm_options.block_size; }) { + if (algorithm_options.block_size == 0) { return error::invalid_parameters; } } - return check_sp800_185_string(options.customisation); + return check_sp800_185_string(algorithm_options.customisation); } }; @@ -641,19 +644,19 @@ struct digest_traits : sp800_185_hash_traits -[[nodiscard]] boost::system::result digest_guards(std::size_t output_size, - digest_options const& options) { +[[nodiscard]] boost::system::result digest_guards( + std::size_t output_size, digest_options const& algorithm_options) { using traits = digest_traits; - auto sized = - check_output(output_size, traits::min_output(options), traits::max_output(options)); - if (!sized) { - return sized; + auto size_check = check_output(output_size, traits::min_output(algorithm_options), + traits::max_output(algorithm_options)); + if (!size_check) { + return size_check; } - return traits::check(options); + return traits::check(algorithm_options); } /** @@ -677,13 +680,13 @@ template Whether a digest's options carry a key: a keyed BLAKE2b is a MAC, and holds the timing guard of one (design D1); every other digest computes on public data. - @tparam Options A tag's `digest_options`. @param options The digest's parameters. + @tparam Options A tag's `digest_options`. @param algorithm_options The digest's parameters. @return Whether the options hold a non-empty `key`; `false` for options without one. */ template -[[nodiscard]] constexpr bool options_keyed(Options const& options) noexcept { - if constexpr (requires { options.key.empty(); }) { - return !options.key.empty(); +[[nodiscard]] constexpr bool options_keyed(Options const& algorithm_options) noexcept { + if constexpr (requires { algorithm_options.key.empty(); }) { + return !algorithm_options.key.empty(); } else { return false; } @@ -692,7 +695,7 @@ template } // namespace detail /** - Hashes `input` into `output` with the digest `Digest` on `Backend`, in one call. + Hashes `input_bytes` into `output_bytes` with the digest `Digest` on `Backend`, in one call. @code std::array id{}; @@ -703,35 +706,36 @@ template @tparam Backend The backend; by default @ref default_backend of `Digest` (spec 4.1). A backend without the tag, or one the program does not link, refuses at compile time, naming those that have it, or the Jamfile line to add. - @param output The digest: exactly the digest's size for a fixed-size digest, any size from 1 + @param output_bytes The digest: exactly the digest's size for a fixed-size digest, any size from 1 byte for an extendable-output function. - @param input The data, of any size. - @param options The digest's parameters (none for most tags). + @param input_bytes The data, of any size. + @param algorithm_options The digest's parameters (none for most tags). @return Success; or the first guard's error (`invalid_output_size`, an option's error, - `unsupported_by_backend`), `output` untouched; or the backend's failure, `output` zeroed. + `unsupported_by_backend`), `output_bytes` untouched; or the backend's failure, `output_bytes` + zeroed. */ template > -[[nodiscard]] boost::system::result digest_of(std::span output, - std::span input, - digest_options const& options = {}) { - secure::timing_guard const timing{detail::options_keyed(options)}; +[[nodiscard]] boost::system::result digest_of( + std::span output_bytes, std::span input_bytes, + digest_options const& algorithm_options = {}) { + secure::timing_guard const timing_scope{detail::options_keyed(algorithm_options)}; using engine = detail::digest_engine; - auto checked = detail::digest_guards(output.size(), options); - if (!checked) { - return checked; + auto guard_result = detail::digest_guards(output_bytes.size(), algorithm_options); + if (!guard_result) { + return guard_result; } - auto served = detail::check_engine_output(output.size()); - if (!served) { - return served; + auto output_check = detail::check_engine_output(output_bytes.size()); + if (!output_check) { + return output_check; } - if (!engine::accepts(options)) { + if (!engine::accepts(algorithm_options)) { return error::unsupported_by_backend; } - auto hashed = engine::one_shot(output, input, options); - if (!hashed) { - secure::erase_secret(output); + auto digest_state = engine::one_shot(output_bytes, input_bytes, algorithm_options); + if (!digest_state) { + secure::erase_secret(output_bytes); } - return hashed; + return digest_state; } // MSVC's warning C4324 ("structure was padded due to alignment specifier") is off for the hasher @@ -784,32 +788,32 @@ class hasher { /** Starts a hash. - @param options The digest's parameters (none for most tags). + @param algorithm_options The digest's parameters (none for most tags). @return The hasher; or an option's error or `unsupported_by_backend`; or the backend's failure. */ [[nodiscard]] static boost::system::result make( - digest_options const& options = {}) noexcept { - secure::timing_guard const timing{detail::options_keyed(options)}; - auto const checked = traits::check(options); - if (!checked) { - return checked.error(); + digest_options const& algorithm_options = {}) noexcept { + secure::timing_guard const timing_scope{detail::options_keyed(algorithm_options)}; + auto const check_result = traits::check(algorithm_options); + if (!check_result) { + return check_result.error(); } - if (!engine::accepts(options)) { + if (!engine::accepts(algorithm_options)) { return error::unsupported_by_backend; } - hasher started; - auto const initialised = engine::init(started.state_, options); - if (!initialised) { - engine::destroy(started.state_); - started.phase_ = phase::spent; - return initialised.error(); + hasher started_hasher; + auto const init_result = engine::init(started_hasher.state_, algorithm_options); + if (!init_result) { + engine::destroy(started_hasher.state_); + started_hasher.phase_ = phase::spent; + return init_result.error(); } - started.min_output_ = traits::min_output(options); - started.max_output_ = traits::max_output(options); - started.keyed_ = detail::options_keyed(options); - started.phase_ = phase::hashing; - return started; + started_hasher.min_output_ = traits::min_output(algorithm_options); + started_hasher.max_output_ = traits::max_output(algorithm_options); + started_hasher.keyed_ = detail::options_keyed(algorithm_options); + started_hasher.phase_ = phase::hashing; + return started_hasher; } /** @@ -855,55 +859,57 @@ class hasher { ~hasher() { end(); } /** - Absorbs `input`. + Absorbs `input_bytes`. - @param input The next piece of the data, of any size. + @param input_bytes The next piece of the data, of any size. @return Success; `invalid_state` after `finish` or once moved from; `input_too_long` when the input would pass a limit of the tag's options or of the backend (ParallelHash's whole input, a TupleHash element, KangarooTwelve's input on 32-bit XKCP); or the backend's failure. After either of the last two the hasher is spent (`invalid_state`). */ - [[nodiscard]] boost::system::result update(std::span input) noexcept { - secure::timing_guard const timing{keyed_}; + [[nodiscard]] boost::system::result update( + std::span input_bytes) noexcept { + secure::timing_guard const timing_scope{keyed_}; if (phase_ != phase::hashing) { return error::invalid_state; } - auto absorbed = engine::update(state_, input); - if (!absorbed) { + auto update_result = engine::update(state_, input_bytes); + if (!update_result) { end(); } - return absorbed; + return update_result; } /** - Writes the hash's result into `output`, once. + Writes the hash's result into `output_bytes`, once. - @param output The digest: exactly the digest's size for a fixed-size digest, any size from 1 - byte for an extendable-output function. + @param output_bytes The digest: exactly the digest's size for a fixed-size digest, any size + from 1 byte for an extendable-output function. @return Success, after which the hasher is spent; `invalid_state` after `finish` or once - moved from; a guard's error (`invalid_output_size`, `unsupported_by_backend`), `output` - untouched and the hasher still hashing; or the backend's failure, `output` zeroed and the + moved from; a guard's error (`invalid_output_size`, `unsupported_by_backend`), `output_bytes` + untouched and the hasher still hashing; or the backend's failure, `output_bytes` zeroed and the hasher spent. */ - [[nodiscard]] boost::system::result finish(std::span output) noexcept { - secure::timing_guard const timing{keyed_}; + [[nodiscard]] boost::system::result finish( + std::span output_bytes) noexcept { + secure::timing_guard const timing_scope{keyed_}; if (phase_ != phase::hashing) { return error::invalid_state; } - auto sized = detail::check_output(output.size(), min_output_, max_output_); - if (!sized) { - return sized; + auto size_check = detail::check_output(output_bytes.size(), min_output_, max_output_); + if (!size_check) { + return size_check; } - auto served = detail::check_engine_output(output.size()); - if (!served) { - return served; + auto output_check = detail::check_engine_output(output_bytes.size()); + if (!output_check) { + return output_check; } - auto finished = engine::finish(state_, output); - if (!finished) { - secure::erase_secret(output); + auto finish_result = engine::finish(state_, output_bytes); + if (!finish_result) { + secure::erase_secret(output_bytes); } end(); - return finished; + return finish_result; } private: diff --git a/include/webcpp/hash/hkdf.hpp b/include/webcpp/hash/hkdf.hpp index 473cf85..183b581 100644 --- a/include/webcpp/hash/hkdf.hpp +++ b/include/webcpp/hash/hkdf.hpp @@ -174,11 +174,12 @@ template } // namespace detail /** - HKDF-Extract (RFC 5869, section 2.2): the pseudorandom key of `input_key_material` under `salt`. + HKDF-Extract (RFC 5869, section 2.2): the pseudorandom key of `input_key_material` under + `salt_bytes`. @tparam Hmac The hmac, as `hmac_sha2_256`. @tparam Backend The backend; by default the one `default_kdf_backend` names, `backends::hash2`. - @param salt The salt, any length the backend takes; empty means `Hmac`'s digest size of + @param salt_bytes The salt, any length the backend takes; empty means `Hmac`'s digest size of zeros. @param input_key_material The input keying material, any length the backend takes. @return The pseudorandom key, an `Hmac::result_type` of the hmac's digest size; or @@ -187,17 +188,17 @@ template */ template > [[nodiscard]] boost::system::result::type> hkdf_extract( - std::span salt, std::span input_key_material) { - secure::timing_guard const timing; + std::span salt_bytes, std::span input_key_material) { + secure::timing_guard const timing_scope; if constexpr (!detail::takes_hmac()) { return error::backend_failure; // unreachable: takes_hmac has stopped the build } else { - auto const guarded = - detail::hkdf_extract_guards(salt.size(), input_key_material.size()); - if (!guarded) { - return guarded.error(); + auto const guard_result = + detail::hkdf_extract_guards(salt_bytes.size(), input_key_material.size()); + if (!guard_result) { + return guard_result.error(); } - return detail::hkdf_engine::extract(salt, input_key_material); + return detail::hkdf_engine::extract(salt_bytes, input_key_material); } } @@ -219,7 +220,7 @@ template hkdf_expand( std::span output_key_material, std::span pseudorandom_key, std::span application_info) { - secure::timing_guard const timing; + secure::timing_guard const timing_scope; if constexpr (!detail::takes_hmac()) { return error::backend_failure; // unreachable: takes_hmac has stopped the build } else { @@ -256,7 +257,7 @@ template > [[nodiscard]] boost::system::result hkdf(std::span output_key_material, - std::span salt, + std::span salt_bytes, std::span input_key_material, std::span application_info) { - secure::timing_guard const timing; + secure::timing_guard const timing_scope; if constexpr (!detail::takes_hmac()) { return error::backend_failure; // unreachable: takes_hmac has stopped the build } else { - auto guarded = - detail::hkdf_guards(output_key_material.size(), salt.size(), + auto guard_result = + detail::hkdf_guards(output_key_material.size(), salt_bytes.size(), input_key_material.size(), application_info.size()); - if (!guarded) { - return guarded; + if (!guard_result) { + return guard_result; } auto derive_result = detail::hkdf_engine::extract_and_expand( - output_key_material, salt, input_key_material, application_info); + output_key_material, salt_bytes, input_key_material, application_info); if (!derive_result) { secure::erase_secret(output_key_material); } @@ -291,7 +292,7 @@ template > /** HKDF-Extract (RFC 5869, section 2.2) over pieces: the pseudorandom key of the concatenation of - `input_key_material`'s pieces under `salt`, each piece fed to the backend's HMAC. + `input_key_material`'s pieces under `salt_bytes`, each piece fed to the backend's HMAC. @code auto prk = webcpp::hash::hkdf_extract(salt, {prefix, label, ikm}); @@ -299,8 +300,8 @@ template > @tparam Hmac The hmac, as `hmac_sha2_256`. @tparam Backend The backend; by default the one `default_kdf_backend` names, `backends::hash2`. - @param salt The salt, any length the backend's HMAC takes as a key; empty means `Hmac`'s digest - size of zeros. + @param salt_bytes The salt, any length the backend's HMAC takes as a key; empty means `Hmac`'s + digest size of zeros. @param input_key_material The input keying material's pieces, of any number and length. @return The pseudorandom key, an `Hmac::result_type` of the hmac's digest size; or `input_too_long` for a salt longer than the backend's HMAC takes (`backends::openssl`: more than @@ -308,16 +309,16 @@ template > */ template > [[nodiscard]] boost::system::result::type> hkdf_extract( - std::span salt, byte_pieces input_key_material) { - secure::timing_guard const timing; + std::span salt_bytes, byte_pieces input_key_material) { + secure::timing_guard const timing_scope; if constexpr (!detail::takes_hmac()) { return error::backend_failure; // unreachable: takes_hmac has stopped the build } else { - auto const guarded = detail::hkdf_pieces_salt_guard(salt.size()); - if (!guarded) { - return guarded.error(); + auto const guard_result = detail::hkdf_pieces_salt_guard(salt_bytes.size()); + if (!guard_result) { + return guard_result.error(); } - return detail::hkdf_pieces_engine::extract(salt, input_key_material); + return detail::hkdf_pieces_engine::extract(salt_bytes, input_key_material); } } @@ -339,13 +340,14 @@ template hkdf_expand( std::span output_key_material, std::span pseudorandom_key, byte_pieces application_info) { - secure::timing_guard const timing; + secure::timing_guard const timing_scope; if constexpr (!detail::takes_hmac()) { return error::backend_failure; // unreachable: takes_hmac has stopped the build } else { - auto guarded = detail::hkdf_pieces_guards(output_key_material.size(), 0); - if (!guarded) { - return guarded; + auto guard_result = + detail::hkdf_pieces_guards(output_key_material.size(), 0); + if (!guard_result) { + return guard_result; } // Hash2 1.92 declares no std::tuple_size for digest; its size() is constexpr. constexpr std::size_t digest_length = typename Hmac::result_type().size(); @@ -374,8 +376,8 @@ template ` names, `backends::hash2`. @param output_key_material The output keying material, 1 to 255 times the digest size. - @param salt The salt, any length the backend's HMAC takes as a key; empty means `Hmac`'s digest - size of zeros. + @param salt_bytes The salt, any length the backend's HMAC takes as a key; empty means `Hmac`'s + digest size of zeros. @param input_key_material The input keying material's pieces, of any number and length. @param application_info The context's pieces, of any number and length: no cap. @return Success, or the error of the first guard that fails (`invalid_output_size`, then @@ -384,20 +386,20 @@ template > [[nodiscard]] boost::system::result hkdf(std::span output_key_material, - std::span salt, + std::span salt_bytes, byte_pieces input_key_material, byte_pieces application_info) { - secure::timing_guard const timing; + secure::timing_guard const timing_scope; if constexpr (!detail::takes_hmac()) { return error::backend_failure; // unreachable: takes_hmac has stopped the build } else { - auto guarded = - detail::hkdf_pieces_guards(output_key_material.size(), salt.size()); - if (!guarded) { - return guarded; + auto guard_result = detail::hkdf_pieces_guards(output_key_material.size(), + salt_bytes.size()); + if (!guard_result) { + return guard_result; } auto derive_result = detail::hkdf_pieces_engine::extract_and_expand( - output_key_material, salt, input_key_material, application_info); + output_key_material, salt_bytes, input_key_material, application_info); if (!derive_result) { secure::erase_secret(output_key_material); } diff --git a/include/webcpp/hash/kdf_standards.hpp b/include/webcpp/hash/kdf_standards.hpp index c3bae2a..567a86e 100644 --- a/include/webcpp/hash/kdf_standards.hpp +++ b/include/webcpp/hash/kdf_standards.hpp @@ -216,9 +216,9 @@ inline constexpr std::uint64_t standard_kdf_counter_size = 4; template constexpr bool standard_kdf_input_too_long(std::uint64_t secret_size, std::uint64_t fixed_info_size) noexcept { - constexpr std::uint64_t room = + constexpr std::uint64_t input_room = standard_kdf_digest::max_input - standard_kdf_counter_size; - return exceeds(secret_size, room) || exceeds(fixed_info_size, room - secret_size); + return exceeds(secret_size, input_room) || exceeds(fixed_info_size, input_room - secret_size); } /** @@ -257,8 +257,8 @@ inline constexpr std::uint64_t kbkdf_max_output_with_length = 0xffffffffULL / 8; /** SP 800-108's key-based key derivation (NIST SP 800-108r1, section 4.1, counter mode) over the - HMAC `Hmac`: fills `output` from the key-derivation key `key`, each block an HMAC under `key` of - the counter, then the fixed input `options` states. + HMAC `Hmac`: fills `output_bytes` from the key-derivation key `key_bytes`, each block an HMAC under + `key_bytes` of the counter, then the fixed input `algorithm_options` states. @code std::array derived{}; @@ -276,64 +276,66 @@ inline constexpr std::uint64_t kbkdf_max_output_with_length = 0xffffffffULL / 8; `hmac_ripemd_128`, or `backends::botan`, which has every one but `hmac_ripemd_128` and `hmac_sha2_512_224` and writes the separator and L always (`unsupported_by_backend` without either). - @param output K_OUT, its size the length L: 1 byte up to (2^r - 1) digests, and, when - `options.length`, at most 536,870,911 bytes (L in bits fits its 32 bits). It must not overlap the - inputs. - @param key K_IN, the key-derivation key: at least 1 byte (`backends::openssl`: at most `INT_MAX`, - HMAC's key length in OpenSSL, `unsupported_by_backend` beyond). - @param options The label, the context, the counter's width and which parts the fixed input holds. + @param output_bytes K_OUT, its size the length L: 1 byte up to (2^r - 1) digests, and, when + `algorithm_options.length`, at most 536,870,911 bytes (L in bits fits its 32 bits). It must not + overlap the inputs. + @param key_bytes K_IN, the key-derivation key: at least 1 byte (`backends::openssl`: at most + `INT_MAX`, HMAC's key length in OpenSSL, `unsupported_by_backend` beyond). + @param algorithm_options The label, the context, the counter's width and which parts the fixed + input holds. @return Success; or the first guard's error (`invalid_parameters` for a counter width other than - 8, 16, 24 or 32, `invalid_output_size`, `invalid_key_size`, `unsupported_by_backend`), `output` - untouched; or `errc::not_enough_memory` or `backend_failure`, `output` zeroed. + 8, 16, 24 or 32, `invalid_output_size`, `invalid_key_size`, `unsupported_by_backend`), + `output_bytes` untouched; or `errc::not_enough_memory` or `backend_failure`, `output_bytes` zeroed. */ template > -[[nodiscard]] boost::system::result kbkdf(std::span output, - std::span key, - kbkdf_options const& options = {}) { - secure::timing_guard const timing; +[[nodiscard]] boost::system::result kbkdf(std::span output_bytes, + std::span key_bytes, + kbkdf_options const& algorithm_options = {}) { + secure::timing_guard const timing_scope; if constexpr (!detail::takes_hmac()) { return error::backend_failure; // unreachable: takes_hmac has stopped the build } else { using engine = detail::kbkdf_engine; constexpr std::uint64_t digest_length = typename Hmac::result_type().size(); - if (options.counter_bits != 8 && options.counter_bits != 16 && options.counter_bits != 24 && - options.counter_bits != 32) { + if (algorithm_options.counter_bits != 8 && algorithm_options.counter_bits != 16 && + algorithm_options.counter_bits != 24 && algorithm_options.counter_bits != 32) { return error::invalid_parameters; } // n = ceil(L / h) blocks, each numbered by the counter, 1 to 2^r - 1 (section 4.1). - std::uint64_t const max_blocks = (std::uint64_t{1} << options.counter_bits) - 1; - if (output.empty() || detail::exceeds(output.size(), max_blocks * digest_length) || - (options.length && - detail::exceeds(output.size(), detail::kbkdf_max_output_with_length))) { + std::uint64_t const max_blocks = (std::uint64_t{1} << algorithm_options.counter_bits) - 1; + if (output_bytes.empty() || + detail::exceeds(output_bytes.size(), max_blocks * digest_length) || + (algorithm_options.length && + detail::exceeds(output_bytes.size(), detail::kbkdf_max_output_with_length))) { return error::invalid_output_size; } - if (key.empty()) { + if (key_bytes.empty()) { return error::invalid_key_size; } - if (detail::exceeds(key.size(), engine::limits.max_key) || - detail::exceeds(output.size(), engine::limits.max_output)) { + if (detail::exceeds(key_bytes.size(), engine::limits.max_key) || + detail::exceeds(output_bytes.size(), engine::limits.max_output)) { return error::unsupported_by_backend; } // A backend that writes one form of the fixed input alone (backends::botan: the // separator and L, always) refuses the others. - if constexpr (requires { engine::accepts(options); }) { - if (!engine::accepts(options)) { + if constexpr (requires { engine::accepts(algorithm_options); }) { + if (!engine::accepts(algorithm_options)) { return error::unsupported_by_backend; } } - auto derived = engine::derive(output, key, options); - if (!derived) { - secure::erase_secret(output); + auto derive_result = engine::derive(output_bytes, key_bytes, algorithm_options); + if (!derive_result) { + secure::erase_secret(output_bytes); } - return derived; + return derive_result; } } /** SP 800-56C's one-step key derivation over the digest `Digest` (NIST SP 800-56C revision 2, - section 4.1, with H a hash function): fills `output` from the shared secret `secret` and - `fixed_info`, block after block, each `Digest(counter || secret || fixed_info)` with a 32-bit - big-endian counter from 1. + section 4.1, with H a hash function): fills `output_bytes` from the shared secret `secret_bytes` + and `fixed_info`, block after block, each `Digest(counter || secret_bytes || fixed_info)` with a + 32-bit big-endian counter from 1. @code std::array derived{}; @@ -346,53 +348,55 @@ template > @tparam Backend The backend; by default @ref default_backend of `kdfs::sskdf`, which has none (design D34): the call names `backends::openssl` or `backends::botan` (every digest but SHA-512/224, which Botan lacks: refused at compile time). - @param output The derived keying material: 1 byte to 2^32 - 1 digests (`backends::openssl`: at - most 2^30 bytes). It must not overlap the inputs. - @param secret Z, the shared secret: at least 1 byte (`backends::openssl`: at most 2^30). + @param output_bytes The derived keying material: 1 byte to 2^32 - 1 digests (`backends::openssl`: + at most 2^30 bytes). It must not overlap the inputs. + @param secret_bytes Z, the shared secret: at least 1 byte (`backends::openssl`: at most 2^30). @param fixed_info FixedInfo, which binds the derived key to its parties and purpose; empty for none (`backends::openssl`: at most 2^30 bytes). @return Success; or the first guard's error (`invalid_output_size`, `invalid_key_size`, `input_too_long` past what the digest hashes, `unsupported_by_backend` past the backend's - limits), `output` untouched; or `errc::not_enough_memory` or `backend_failure`, `output` zeroed. + limits), `output_bytes` untouched; or `errc::not_enough_memory` or `backend_failure`, + `output_bytes` zeroed. */ template > -[[nodiscard]] boost::system::result sskdf(std::span output, - std::span secret, +[[nodiscard]] boost::system::result sskdf(std::span output_bytes, + std::span secret_bytes, std::span fixed_info = {}) { - secure::timing_guard const timing; + secure::timing_guard const timing_scope; if constexpr (!detail::sskdf_takes()) { return error::backend_failure; // unreachable: sskdf_takes has stopped the build } else { using engine = detail::sskdf_engine; using digest = detail::standard_kdf_digest; // reps = ceil(L / H_outputBits) is at most 2^32 - 1 (section 4.1, step 2). - if (output.empty() || - detail::exceeds(output.size(), detail::standard_kdf_max_blocks * digest::size)) { + if (output_bytes.empty() || + detail::exceeds(output_bytes.size(), detail::standard_kdf_max_blocks * digest::size)) { return error::invalid_output_size; } - if (secret.empty()) { + if (secret_bytes.empty()) { return error::invalid_key_size; } - if (detail::standard_kdf_input_too_long(secret.size(), fixed_info.size())) { + if (detail::standard_kdf_input_too_long(secret_bytes.size(), fixed_info.size())) { return error::input_too_long; } - if (detail::exceeds(secret.size(), engine::limits.max_key) || + if (detail::exceeds(secret_bytes.size(), engine::limits.max_key) || detail::exceeds(fixed_info.size(), engine::limits.max_info) || - detail::exceeds(output.size(), engine::limits.max_output)) { + detail::exceeds(output_bytes.size(), engine::limits.max_output)) { return error::unsupported_by_backend; } - auto derived = engine::derive(output, secret, fixed_info); - if (!derived) { - secure::erase_secret(output); + auto derive_result = engine::derive(output_bytes, secret_bytes, fixed_info); + if (!derive_result) { + secure::erase_secret(output_bytes); } - return derived; + return derive_result; } } /** ANSI X9.63's key derivation (ANSI X9.63-2011, section 5.6.3; SEC 1 v2, section 3.6.1) over the - digest `Digest`: fills `output` from the shared secret `secret` and `shared_info`, block after - block, each `Digest(secret || counter || shared_info)` with a 32-bit big-endian counter from 1. + digest `Digest`: fills `output_bytes` from the shared secret `secret_bytes` and `shared_info`, + block after block, each `Digest(secret_bytes || counter || shared_info)` with a 32-bit big-endian + counter from 1. ECIES and the elliptic-curve key agreements of SEC 1, BSI TR-03111 and smart cards use it. @@ -407,46 +411,47 @@ template > another, SHA-512/224 and SHA-512/256 included, refuses at compile time. @tparam Backend The backend; by default @ref default_backend of `kdfs::x963kdf`, which has none (design D34): the call names `backends::openssl` or `backends::botan`. - @param output The derived keying material: 1 byte to 2^32 - 1 digests less 1 byte (the standard - refuses keydatalen >= hashlen (2^32 - 1); `backends::openssl`: at most 2^30 bytes). It must not - overlap the inputs. - @param secret Z, the shared secret: at least 1 byte (`backends::openssl`: at most 2^30). + @param output_bytes The derived keying material: 1 byte to 2^32 - 1 digests less 1 byte (the + standard refuses keydatalen >= hashlen (2^32 - 1); `backends::openssl`: at most 2^30 bytes). It + must not overlap the inputs. + @param secret_bytes Z, the shared secret: at least 1 byte (`backends::openssl`: at most 2^30). @param shared_info SharedInfo, the data both parties share; empty for none (`backends::openssl`: at most 2^30 bytes). @return Success; or the first guard's error (`invalid_output_size`, `invalid_key_size`, `input_too_long` past what the digest hashes, `unsupported_by_backend` past the backend's - limits), `output` untouched; or `errc::not_enough_memory` or `backend_failure`, `output` zeroed. + limits), `output_bytes` untouched; or `errc::not_enough_memory` or `backend_failure`, + `output_bytes` zeroed. */ template > -[[nodiscard]] boost::system::result x963kdf(std::span output, - std::span secret, +[[nodiscard]] boost::system::result x963kdf(std::span output_bytes, + std::span secret_bytes, std::span shared_info = {}) { - secure::timing_guard const timing; + secure::timing_guard const timing_scope; if constexpr (!detail::x963kdf_takes()) { return error::backend_failure; // unreachable: x963kdf_takes has stopped the build } else { using engine = detail::x963kdf_engine; using digest = detail::standard_kdf_digest; - if (output.empty() || - !detail::exceeds(detail::standard_kdf_max_blocks * digest::size, output.size())) { + if (output_bytes.empty() || + !detail::exceeds(detail::standard_kdf_max_blocks * digest::size, output_bytes.size())) { return error::invalid_output_size; } - if (secret.empty()) { + if (secret_bytes.empty()) { return error::invalid_key_size; } - if (detail::standard_kdf_input_too_long(secret.size(), shared_info.size())) { + if (detail::standard_kdf_input_too_long(secret_bytes.size(), shared_info.size())) { return error::input_too_long; } - if (detail::exceeds(secret.size(), engine::limits.max_key) || + if (detail::exceeds(secret_bytes.size(), engine::limits.max_key) || detail::exceeds(shared_info.size(), engine::limits.max_info) || - detail::exceeds(output.size(), engine::limits.max_output)) { + detail::exceeds(output_bytes.size(), engine::limits.max_output)) { return error::unsupported_by_backend; } - auto derived = engine::derive(output, secret, shared_info); - if (!derived) { - secure::erase_secret(output); + auto derive_result = engine::derive(output_bytes, secret_bytes, shared_info); + if (!derive_result) { + secure::erase_secret(output_bytes); } - return derived; + return derive_result; } } diff --git a/include/webcpp/hash/mac.hpp b/include/webcpp/hash/mac.hpp index 7066fba..02e8a56 100644 --- a/include/webcpp/hash/mac.hpp +++ b/include/webcpp/hash/mac.hpp @@ -120,7 +120,7 @@ struct mac_sizes { */ template [[nodiscard]] static constexpr boost::system::result check( - Options const& /*options*/) noexcept { + Options const& /*algorithm_options*/) noexcept { return {}; } }; @@ -177,11 +177,11 @@ struct kmac_traits : mac_sizes check( - mac_options const& options) noexcept { - return check_sp800_185_string(options.customisation); + mac_options const& algorithm_options) noexcept { + return check_sp800_185_string(algorithm_options.customisation); } }; @@ -210,12 +210,12 @@ template <> struct mac_traits : mac_sizes<1, 32, 1, 32> {}; that completes by itself (`backends::webcrypto`) checks before it starts the work. @tparam Mac A tag of `macs`. @param output_size The tag's size. @param key_size The key's size. - @param options The MAC's parameters. + @param algorithm_options The MAC's parameters. @return Success, or the error of the first guard that fails, as `mac` returns it. */ template [[nodiscard]] boost::system::result mac_guards(std::size_t output_size, std::size_t key_size, - mac_options const& options) { + mac_options const& algorithm_options) { using traits = mac_traits; // Each bound through exceeds, a function of two 64-bit values: a constant bound of 0 or of // no_limit compared with a size_t is a tautology the warnings refuse. @@ -225,13 +225,13 @@ template if (exceeds(traits::min_key, key_size) || exceeds(key_size, traits::max_key)) { return error::invalid_key_size; } - return traits::check(options); + return traits::check(algorithm_options); } } // namespace detail /** - The tag of `input` under `key`, with the MAC `Mac` on `Backend`. + The tag of `input_bytes` under `key_bytes`, with the MAC `Mac` on `Backend`. @code std::array tag{}; @@ -242,34 +242,35 @@ template @tparam Mac A tag of `macs`, as `macs::hmac`. @tparam Backend The backend; by default @ref default_backend of `Mac` (spec 4.1). A backend without the tag, or one the program does not link, refuses at compile time. - @param output The tag: for HMAC, 10 bytes up to the digest's size (a shorter tag is the digest - cut, RFC 2104 section 5); for the others, the size their traits give. - @param key The key. - @param input The message, of any size. - @param options The MAC's parameters (none for most tags). + @param output_bytes The tag: for HMAC, 10 bytes up to the digest's size (a shorter tag is the + digest cut, RFC 2104 section 5); for the others, the size their traits give. + @param key_bytes The key. + @param input_bytes The message, of any size. + @param algorithm_options The MAC's parameters (none for most tags). @return Success; or the first guard's error (`invalid_output_size`, `invalid_key_size`, an - option's error, `unsupported_by_backend`), `output` untouched; or the backend's failure, - `output` zeroed. + option's error, `unsupported_by_backend`), `output_bytes` untouched; or the backend's failure, + `output_bytes` zeroed. */ template > -[[nodiscard]] boost::system::result mac(std::span output, - std::span key, - std::span input, - mac_options const& options = {}) { - secure::timing_guard const timing; +[[nodiscard]] boost::system::result mac(std::span output_bytes, + std::span key_bytes, + std::span input_bytes, + mac_options const& algorithm_options = {}) { + secure::timing_guard const timing_scope; using engine = detail::mac_engine; - auto checked = detail::mac_guards(output.size(), key.size(), options); - if (!checked) { - return checked; + auto guard_result = + detail::mac_guards(output_bytes.size(), key_bytes.size(), algorithm_options); + if (!guard_result) { + return guard_result; } - if (!engine::accepts(options, key.size(), output.size())) { + if (!engine::accepts(algorithm_options, key_bytes.size(), output_bytes.size())) { return error::unsupported_by_backend; } - auto computed = engine::compute(output, key, input, options); - if (!computed) { - secure::erase_secret(output); + auto compute_result = engine::compute(output_bytes, key_bytes, input_bytes, algorithm_options); + if (!compute_result) { + secure::erase_secret(output_bytes); } - return computed; + return compute_result; } } // namespace webcpp::hash diff --git a/include/webcpp/hash/pbkdf2.hpp b/include/webcpp/hash/pbkdf2.hpp index b858df9..2f5be33 100644 --- a/include/webcpp/hash/pbkdf2.hpp +++ b/include/webcpp/hash/pbkdf2.hpp @@ -128,14 +128,14 @@ template > std::span password_bytes, std::span salt_bytes, std::uint64_t iteration_count) { - secure::timing_guard const timing; + secure::timing_guard const timing_scope; if constexpr (!detail::takes_hmac()) { return error::backend_failure; // unreachable: takes_hmac has stopped the build } else { - auto guarded = detail::pbkdf2_guards( + auto guard_result = detail::pbkdf2_guards( output_bytes.size(), password_bytes.size(), salt_bytes.size(), iteration_count); - if (!guarded) { - return guarded; + if (!guard_result) { + return guard_result; } auto derive_result = detail::pbkdf2_engine::derive( output_bytes, password_bytes, salt_bytes, iteration_count); diff --git a/include/webcpp/hash/scrypt.hpp b/include/webcpp/hash/scrypt.hpp index bfd190b..8d77764 100644 --- a/include/webcpp/hash/scrypt.hpp +++ b/include/webcpp/hash/scrypt.hpp @@ -162,11 +162,11 @@ template > std::span password_bytes, std::span salt_bytes, scrypt_parameters const& cost_parameters) { - secure::timing_guard const timing; - auto guarded = detail::scrypt_guards(output_bytes.size(), password_bytes.size(), - salt_bytes.size(), cost_parameters); - if (!guarded) { - return guarded; + secure::timing_guard const timing_scope; + auto guard_result = detail::scrypt_guards(output_bytes.size(), password_bytes.size(), + salt_bytes.size(), cost_parameters); + if (!guard_result) { + return guard_result; } auto derive_result = detail::scrypt_engine::derive( output_bytes, password_bytes, salt_bytes, cost_parameters.cost, cost_parameters.block_size, diff --git a/test/user_globals_test.cpp b/test/user_globals_test.cpp index 73ce5b0..2c2e4fd 100644 --- a/test/user_globals_test.cpp +++ b/test/user_globals_test.cpp @@ -17,8 +17,10 @@ // gave a local or a parameter until each took two words; then every public header. Every cell of // every backend the program links is called (digests and hashers, MACs, the HKDFs over spans and // over pieces, PBKDF2, KBKDF, SSKDF, X9.63, BLAKE2b's subkeys, Argon2, scrypt and bcrypt), and -// every asynchronous function on its default backend, which instantiates every template the calls -// reach. +// every asynchronous function on its default backend (bcrypt's on Botan, which is no default), +// which instantiates every template the calls reach. The parameters of detail/xkcp.hpp's C +// declarations, which have no body, raise no C4459 (14.3, with the globals `storage`, `input`, +// `output` and `length` below) and keep the C adapter's names. // // How the list was made: an aggregate translation unit of every header of include/, every backend // and webcpp::asio linked, its AST dumped (clang -Xclang -ast-dump=json, filtered to webcpp::hash), @@ -390,9 +392,9 @@ void call_every_async(asio::io_context& context_object) { on_done); hash::async_hkdf_expand(io_executor, output_buffer, key_buffer, piece_array, on_done); +#ifdef WEBCPP_HASH_HAS_THREADS hash::async_pbkdf2(io_executor, output_buffer, test_key, test_salt, 1, on_done); -#ifdef WEBCPP_HASH_HAS_THREADS hash::async_argon2id(io_executor, output_buffer, test_key, test_salt, {.passes = 1, .memory = 8192}, on_done); hash::async_argon2(io_executor, output_buffer, test_key, test_salt, From 048e90a18880b44701cc7649229196a088df61c8 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 06:48:13 -0300 Subject: [PATCH 3/7] hash: user_globals as clang-tidy wants it: the key and the salt counted, the options const, no key derivation calls on a backend without one, lambdas without an empty parameter list --- test/user_globals_test.cpp | 115 +++++++++++++++++++++++-------------- 1 file changed, 71 insertions(+), 44 deletions(-) diff --git a/test/user_globals_test.cpp b/test/user_globals_test.cpp index 2c2e4fd..1ecbd9c 100644 --- a/test/user_globals_test.cpp +++ b/test/user_globals_test.cpp @@ -222,10 +222,18 @@ template inline constexpr bool cell_v = hash::detail::linked_v && hash::backend_has_v; -inline constexpr std::array test_key{1, 2, 3, 4, 5, 6, 7, 8, - 9, 10, 11, 12, 13, 14, 15, 16}; -inline constexpr std::array test_salt{16, 15, 14, 13, 12, 11, 10, 9, - 8, 7, 6, 5, 4, 3, 2, 1}; +/** `Size` bytes, each its index plus `first_byte`. */ +template +constexpr std::array counted_bytes(std::uint8_t first_byte) { + std::array counted_array{}; + for (std::size_t byte_index = 0; byte_index < Size; ++byte_index) { + counted_array[byte_index] = static_cast(first_byte + byte_index); + } + return counted_array; +} + +inline constexpr std::array test_key = counted_bytes<32>(1); +inline constexpr std::array test_salt = counted_bytes<16>(101); inline constexpr std::array test_input{9, 8, 7, 6, 5, 4, 3, 2, 1}; /** The pieces of `test_input`, one of them empty. */ @@ -238,14 +246,20 @@ std::array, 3> test_pieces() { template void call_digest() { using traits = hash::detail::digest_traits; - hash::digest_options digest_choice{}; - if constexpr (requires { digest_choice.block_size; }) { - digest_choice.block_size = 8; // ParallelHash's, which has no default - } + // The default options, but ParallelHash's block size, which has no default. + auto const digest_choice = [] { + hash::digest_options chosen_options{}; + if constexpr (requires { chosen_options.block_size; }) { + chosen_options.block_size = 8; + } + return chosen_options; + }(); std::array output_buffer{}; - auto const output_size = static_cast( - std::min({traits::max_output(digest_choice), - hash::detail::digest_engine::max_output, std::uint64_t{64}})); + auto const output_size = static_cast(std::min({ + traits::max_output(digest_choice), + hash::detail::digest_engine::max_output, + std::uint64_t{64}, + })); auto const output_span = std::span(output_buffer).first(output_size); static_cast(hash::digest_of(output_span, test_input, digest_choice)); auto made_hasher = hash::hasher::make(digest_choice); @@ -278,38 +292,51 @@ void call_mac() { hash::mac(output_span, std::span(test_key).first(key_size), test_input)); } +/** Whether `Backend` has a key derivation over `Hmac`. */ +template +inline constexpr bool hmac_family_v = + cell_v || cell_v || + cell_v || cell_v || + cell_v || cell_v || + cell_v || cell_v; + /** Every key derivation over `Hmac` that `Backend` has: the HKDFs, PBKDF2 and KBKDF. */ template void call_hmac_family() { - std::array output_buffer{}; - std::array key_buffer{}; - auto const prk_span = std::span(key_buffer).first(typename Hmac::result_type().size()); - auto const piece_array = test_pieces(); - if constexpr (cell_v) { - static_cast(hash::hkdf_extract(test_salt, test_key)); - } - if constexpr (cell_v) { - static_cast(hash::hkdf_expand(output_buffer, prk_span, test_input)); - } - if constexpr (cell_v) { - static_cast( - hash::hkdf(output_buffer, test_salt, test_key, test_input)); - } - if constexpr (cell_v) { - static_cast(hash::hkdf_extract(test_salt, piece_array)); - } - if constexpr (cell_v) { - static_cast(hash::hkdf_expand(output_buffer, prk_span, piece_array)); - } - if constexpr (cell_v) { - static_cast( - hash::hkdf(output_buffer, test_salt, piece_array, piece_array)); - } - if constexpr (cell_v) { - static_cast(hash::pbkdf2(output_buffer, test_key, test_salt, 1)); - } - if constexpr (cell_v) { - static_cast(hash::kbkdf(output_buffer, test_key)); + if constexpr (hmac_family_v) { + std::array output_buffer{}; + std::array key_buffer{}; + auto const pseudorandom_key = + std::span(key_buffer).first(typename Hmac::result_type().size()); + auto const piece_array = test_pieces(); + if constexpr (cell_v) { + static_cast(hash::hkdf_extract(test_salt, test_key)); + } + if constexpr (cell_v) { + static_cast( + hash::hkdf_expand(output_buffer, pseudorandom_key, test_input)); + } + if constexpr (cell_v) { + static_cast( + hash::hkdf(output_buffer, test_salt, test_key, test_input)); + } + if constexpr (cell_v) { + static_cast(hash::hkdf_extract(test_salt, piece_array)); + } + if constexpr (cell_v) { + static_cast( + hash::hkdf_expand(output_buffer, pseudorandom_key, piece_array)); + } + if constexpr (cell_v) { + static_cast( + hash::hkdf(output_buffer, test_salt, piece_array, piece_array)); + } + if constexpr (cell_v) { + static_cast(hash::pbkdf2(output_buffer, test_key, test_salt, 1)); + } + if constexpr (cell_v) { + static_cast(hash::kbkdf(output_buffer, test_key)); + } } } @@ -317,17 +344,17 @@ void call_hmac_family() { template void call_every_cell() { if constexpr (hash::detail::linked_v) { - for_each_tag([]() { + for_each_tag([] { if constexpr (cell_v) { call_digest(); } }); - for_each_tag([]() { + for_each_tag([] { if constexpr (cell_v) { call_mac(); } }); - for_each_tag([]() { call_hmac_family(); }); + for_each_tag([] { call_hmac_family(); }); std::array output_buffer{}; if constexpr (cell_v) { std::array const context_bytes{'c', 't', 'x', '_', 't', 'e', 's', 't'}; @@ -346,7 +373,7 @@ void call_every_cell() { static_cast(hash::argon2id(output_buffer, test_key, test_salt, {.passes = 1, .memory = 8192})); } - for_each_tag([&output_buffer]() { + for_each_tag([&output_buffer] { if constexpr (cell_v) { static_cast(hash::argon2( output_buffer, test_key, test_salt, {.passes = 3, .memory_kibibytes = 8})); From 2d6775e603a0c8d8e187008a643f6e8caa05904d Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 06:50:18 -0300 Subject: [PATCH 4/7] hash: byte_pieces' constructors document piece_list and piece_range, the names of their parameters (MrDocs) --- include/webcpp/hash/byte_pieces.hpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/include/webcpp/hash/byte_pieces.hpp b/include/webcpp/hash/byte_pieces.hpp index 3d7bc13..971021a 100644 --- a/include/webcpp/hash/byte_pieces.hpp +++ b/include/webcpp/hash/byte_pieces.hpp @@ -67,7 +67,7 @@ class byte_pieces { /** The pieces of a braced list, `{a, b, c}`, each element converted to a span of bytes. - @param pieces The list; its array must outlive this object (it does, written at the call). + @param piece_list The list; its array must outlive this object (it does, written at the call). */ constexpr byte_pieces( // NOLINT(misc-explicit-constructor): {a, b} converts to its pieces std::initializer_list piece_list WEBCPP_HASH_LIFETIMEBOUND) noexcept @@ -78,7 +78,7 @@ class byte_pieces { `std::span` of them. @tparam Range A contiguous, sized range whose value type is `std::span`. - @param pieces The range; it must outlive this object. + @param piece_range The range; it must outlive this object. */ template requires std::ranges::sized_range && From 951c7bddf6a0f634400910e7ebd1c8883e22a2b3 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 07:06:52 -0300 Subject: [PATCH 5/7] hash: HKDF's public functions keep their parameter salt, as the change hkdf-pieces' spec names it (a function template's parameter raises no C4459); the kdfs page with them; libsodium's whole-digest test is writes_whole_digest --- doc/kdfs.adoc | 8 ++-- include/webcpp/hash/async.hpp | 50 ++++++++++++------------- include/webcpp/hash/backends/sodium.hpp | 7 ++-- include/webcpp/hash/hkdf.hpp | 43 +++++++++++---------- 4 files changed, 54 insertions(+), 54 deletions(-) diff --git a/doc/kdfs.adoc b/doc/kdfs.adoc index 49af544..e4323b8 100644 --- a/doc/kdfs.adoc +++ b/doc/kdfs.adoc @@ -47,7 +47,7 @@ include::generated/compare-kdfs.adoc[] === HKDF HKDF (RFC 5869, 2010, Krawczyk) has two steps, both HMACs. *Extract* takes an -optional `salt_bytes` and the `input_key_material` (RFC 5869's IKM) and returns a +optional `salt` and the `input_key_material` (RFC 5869's IKM) and returns a `pseudorandom_key` (the PRK) of the hmac's digest size: `PRK = HMAC(salt, IKM)`. *Expand* takes the `pseudorandom_key` and the `application_info` (RFC 5869's info), the label of one purpose, and returns up @@ -78,7 +78,7 @@ include::{examples}/hkdf.expected[] Diffie-Hellman result) but must hold enough entropy: extract concentrates entropy, it never adds any. A password has too little; it goes through Argon2id. -* *`salt_bytes`* is optional and public: a random value per session, or a constant +* *`salt`* is optional and public: a random value per session, or a constant that names the application or the protocol (NIP-44 uses `nip44-v2`). It separates the keys of different applications that might share a secret. An empty salt is RFC 5869's string of zeros, and fine when the IKM is never @@ -146,10 +146,10 @@ On a synchronous backend each piece goes to the backend's HMAC: no buffer, no copy of the secret. WebCrypto's asynchronous forms copy the pieces into JavaScript memory instead (<>). -* `hkdf_extract(salt_bytes, input_key_material)` +* `hkdf_extract(salt, input_key_material)` * `hkdf_expand(output_key_material, pseudorandom_key, application_info)` -* `hkdf(output_key_material, salt_bytes, input_key_material, +* `hkdf(output_key_material, salt, input_key_material, application_info)` The salt and the pseudorandom key stay one span each. The bytes are those of diff --git a/include/webcpp/hash/async.hpp b/include/webcpp/hash/async.hpp index 3eca5e5..bbe0ca4 100644 --- a/include/webcpp/hash/async.hpp +++ b/include/webcpp/hash/async.hpp @@ -920,9 +920,9 @@ auto async_hmac(Executor const& completion_executor, std::span out of an `io_context` run on the calling thread (see @ref async_pbkdf2), and a refusal of another goes to the handler's associated executor, this one unless the handler is bound to another. @param output_key_material The output keying material, 1 to 255 times the digest size. - @param salt_bytes The salt. @param input_key_material The input keying material. @param - application_info The context, at most `hkdf_max_application_info_size` bytes; on - `backends::webcrypto` at most 1,024, WebCrypto's limit + @param salt The salt. @param input_key_material The input keying material. @param application_info + The context, at most `hkdf_max_application_info_size` bytes; on `backends::webcrypto` at most + 1,024, WebCrypto's limit (`input_too_long` beyond). The spans are the caller's until completion. @param completion_token The completion token, of signature `void(boost::system::error_code)`. @return What the completion token's `async_result` gives. The completion's code is empty on @@ -935,7 +935,7 @@ auto async_hmac(Executor const& completion_executor, std::span out template , class Executor, class CompletionToken> auto async_hkdf(Executor const& completion_executor, std::span output_key_material, - std::span salt_bytes, + std::span salt, std::span input_key_material, std::span application_info, CompletionToken&& completion_token) { @@ -946,13 +946,13 @@ auto async_hkdf(Executor const& completion_executor, std::span out "hkdf for the others."); } else if constexpr (detail::asynchronous_backend_v) { return detail::async_engine::template hkdf( - completion_executor, output_key_material, salt_bytes, input_key_material, - application_info, std::forward(completion_token)); + completion_executor, output_key_material, salt, input_key_material, application_info, + std::forward(completion_token)); } else { return detail::complete_by_post( completion_executor, completion_token, - [output_key_material, salt_bytes, input_key_material, application_info] { - return hkdf(output_key_material, salt_bytes, input_key_material, + [output_key_material, salt, input_key_material, application_info] { + return hkdf(output_key_material, salt, input_key_material, application_info); }); } @@ -987,7 +987,7 @@ auto async_hkdf(Executor const& completion_executor, std::span out to the handler's associated executor, this one unless the handler is bound to another. @param output_key_material The output keying material, 1 to 255 times the digest size; the caller's until completion. - @param salt_bytes The salt. @param input_key_material The input keying material's pieces. + @param salt The salt. @param input_key_material The input keying material's pieces. @param application_info The context's pieces. The salt and the pieces are read in the call. @param completion_token The completion token, of signature `void(boost::system::error_code)`. @return What the completion token's `async_result` gives. The completion's code is empty on @@ -997,7 +997,7 @@ auto async_hkdf(Executor const& completion_executor, std::span out template , class Executor, class CompletionToken> auto async_hkdf(Executor const& completion_executor, std::span output_key_material, - std::span salt_bytes, byte_pieces input_key_material, + std::span salt, byte_pieces input_key_material, byte_pieces application_info, CompletionToken&& completion_token) { if constexpr (!detail::webcrypto_hmac_v) { static_assert(detail::always_false, @@ -1006,11 +1006,11 @@ auto async_hkdf(Executor const& completion_executor, std::span out "hkdf for the others."); } else if constexpr (detail::asynchronous_backend_v) { return detail::async_engine::template hkdf( - completion_executor, output_key_material, salt_bytes, input_key_material, - application_info, std::forward(completion_token)); + completion_executor, output_key_material, salt, input_key_material, application_info, + std::forward(completion_token)); } else { - auto const call_code = detail::code_of(hkdf( - output_key_material, salt_bytes, input_key_material, application_info)); + auto const call_code = detail::code_of( + hkdf(output_key_material, salt, input_key_material, application_info)); return detail::complete_with_code(completion_executor, completion_token, call_code); } } @@ -1029,7 +1029,7 @@ auto async_hkdf(Executor const& completion_executor, std::span out of an `io_context` run on the calling thread (see @ref async_pbkdf2), and a refusal of another goes to the handler's associated executor, this one unless the handler is bound to another. @param pseudorandom_key The pseudorandom key, of exactly the digest size. - @param salt_bytes The salt. @param input_key_material The input keying material. The spans are the + @param salt The salt. @param input_key_material The input keying material. The spans are the caller's until completion. @param completion_token The completion token, of signature `void(boost::system::error_code)`. @return What the completion token's `async_result` gives. The completion's code is empty on @@ -1041,7 +1041,7 @@ template auto async_hkdf_extract(Executor const& completion_executor, std::span pseudorandom_key, - std::span salt_bytes, + std::span salt, std::span input_key_material, CompletionToken&& completion_token) { if constexpr (!detail::webcrypto_hmac_v) { @@ -1051,13 +1051,13 @@ auto async_hkdf_extract(Executor const& completion_executor, "hkdf_extract for the others."); } else if constexpr (detail::asynchronous_backend_v) { return detail::async_engine::template hkdf_extract( - completion_executor, pseudorandom_key, salt_bytes, input_key_material, + completion_executor, pseudorandom_key, salt, input_key_material, std::forward(completion_token)); } else { return detail::complete_by_post(completion_executor, completion_token, - [pseudorandom_key, salt_bytes, input_key_material] { + [pseudorandom_key, salt, input_key_material] { return detail::hkdf_extract_into( - pseudorandom_key, salt_bytes, input_key_material); + pseudorandom_key, salt, input_key_material); }); } } @@ -1078,8 +1078,8 @@ auto async_hkdf_extract(Executor const& completion_executor, to the handler's associated executor, this one unless the handler is bound to another. @param pseudorandom_key The pseudorandom key, of exactly the digest size; the caller's until completion. - @param salt_bytes The salt. @param input_key_material The input keying material's pieces. Both read - in the call. + @param salt The salt. @param input_key_material The input keying material's pieces. Both read in + the call. @param completion_token The completion token, of signature `void(boost::system::error_code)`. @return What the completion token's `async_result` gives. The completion's code is empty on success, or `invalid_output_size` for a `pseudorandom_key` of another size than the digest's, or @@ -1090,7 +1090,7 @@ template auto async_hkdf_extract(Executor const& completion_executor, std::span pseudorandom_key, - std::span salt_bytes, byte_pieces input_key_material, + std::span salt, byte_pieces input_key_material, CompletionToken&& completion_token) { if constexpr (!detail::webcrypto_hmac_v) { static_assert(detail::always_false, @@ -1099,11 +1099,11 @@ auto async_hkdf_extract(Executor const& completion_executor, "hkdf_extract for the others."); } else if constexpr (detail::asynchronous_backend_v) { return detail::async_engine::template hkdf_extract( - completion_executor, pseudorandom_key, salt_bytes, input_key_material, + completion_executor, pseudorandom_key, salt, input_key_material, std::forward(completion_token)); } else { - auto const call_code = detail::code_of(detail::hkdf_extract_into( - pseudorandom_key, salt_bytes, input_key_material)); + auto const call_code = detail::code_of( + detail::hkdf_extract_into(pseudorandom_key, salt, input_key_material)); return detail::complete_with_code(completion_executor, completion_token, call_code); } } diff --git a/include/webcpp/hash/backends/sodium.hpp b/include/webcpp/hash/backends/sodium.hpp index 0ebffb4..e2dbf59 100644 --- a/include/webcpp/hash/backends/sodium.hpp +++ b/include/webcpp/hash/backends/sodium.hpp @@ -966,12 +966,13 @@ struct sodium_hmac_engine : full_engine { } State keyed_state{}; std::array digest_bytes{}; - bool const whole_output = output_bytes.size() == Size; + bool const writes_whole_digest = output_bytes.size() == Size; bool const call_succeeded = Init(&keyed_state, key_bytes.data(), key_bytes.size()) == 0 && Update(&keyed_state, nonnull(input_bytes), input_bytes.size()) == 0 && - Final(&keyed_state, whole_output ? output_bytes.data() : digest_bytes.data()) == 0; - if (call_succeeded && !whole_output) { + Final(&keyed_state, writes_whole_digest ? output_bytes.data() : digest_bytes.data()) == + 0; + if (call_succeeded && !writes_whole_digest) { std::copy_n(digest_bytes.begin(), output_bytes.size(), output_bytes.begin()); } secure::erase_secret(digest_bytes); diff --git a/include/webcpp/hash/hkdf.hpp b/include/webcpp/hash/hkdf.hpp index 183b581..25a4144 100644 --- a/include/webcpp/hash/hkdf.hpp +++ b/include/webcpp/hash/hkdf.hpp @@ -174,12 +174,11 @@ template } // namespace detail /** - HKDF-Extract (RFC 5869, section 2.2): the pseudorandom key of `input_key_material` under - `salt_bytes`. + HKDF-Extract (RFC 5869, section 2.2): the pseudorandom key of `input_key_material` under `salt`. @tparam Hmac The hmac, as `hmac_sha2_256`. @tparam Backend The backend; by default the one `default_kdf_backend` names, `backends::hash2`. - @param salt_bytes The salt, any length the backend takes; empty means `Hmac`'s digest size of + @param salt The salt, any length the backend takes; empty means `Hmac`'s digest size of zeros. @param input_key_material The input keying material, any length the backend takes. @return The pseudorandom key, an `Hmac::result_type` of the hmac's digest size; or @@ -188,17 +187,17 @@ template */ template > [[nodiscard]] boost::system::result::type> hkdf_extract( - std::span salt_bytes, std::span input_key_material) { + std::span salt, std::span input_key_material) { secure::timing_guard const timing_scope; if constexpr (!detail::takes_hmac()) { return error::backend_failure; // unreachable: takes_hmac has stopped the build } else { auto const guard_result = - detail::hkdf_extract_guards(salt_bytes.size(), input_key_material.size()); + detail::hkdf_extract_guards(salt.size(), input_key_material.size()); if (!guard_result) { return guard_result.error(); } - return detail::hkdf_engine::extract(salt_bytes, input_key_material); + return detail::hkdf_engine::extract(salt, input_key_material); } } @@ -257,7 +256,7 @@ template > [[nodiscard]] boost::system::result hkdf(std::span output_key_material, - std::span salt_bytes, + std::span salt, std::span input_key_material, std::span application_info) { secure::timing_guard const timing_scope; @@ -276,13 +275,13 @@ template > return error::backend_failure; // unreachable: takes_hmac has stopped the build } else { auto guard_result = - detail::hkdf_guards(output_key_material.size(), salt_bytes.size(), + detail::hkdf_guards(output_key_material.size(), salt.size(), input_key_material.size(), application_info.size()); if (!guard_result) { return guard_result; } auto derive_result = detail::hkdf_engine::extract_and_expand( - output_key_material, salt_bytes, input_key_material, application_info); + output_key_material, salt, input_key_material, application_info); if (!derive_result) { secure::erase_secret(output_key_material); } @@ -292,7 +291,7 @@ template > /** HKDF-Extract (RFC 5869, section 2.2) over pieces: the pseudorandom key of the concatenation of - `input_key_material`'s pieces under `salt_bytes`, each piece fed to the backend's HMAC. + `input_key_material`'s pieces under `salt`, each piece fed to the backend's HMAC. @code auto prk = webcpp::hash::hkdf_extract(salt, {prefix, label, ikm}); @@ -300,8 +299,8 @@ template > @tparam Hmac The hmac, as `hmac_sha2_256`. @tparam Backend The backend; by default the one `default_kdf_backend` names, `backends::hash2`. - @param salt_bytes The salt, any length the backend's HMAC takes as a key; empty means `Hmac`'s - digest size of zeros. + @param salt The salt, any length the backend's HMAC takes as a key; empty means `Hmac`'s digest + size of zeros. @param input_key_material The input keying material's pieces, of any number and length. @return The pseudorandom key, an `Hmac::result_type` of the hmac's digest size; or `input_too_long` for a salt longer than the backend's HMAC takes (`backends::openssl`: more than @@ -309,16 +308,16 @@ template > */ template > [[nodiscard]] boost::system::result::type> hkdf_extract( - std::span salt_bytes, byte_pieces input_key_material) { + std::span salt, byte_pieces input_key_material) { secure::timing_guard const timing_scope; if constexpr (!detail::takes_hmac()) { return error::backend_failure; // unreachable: takes_hmac has stopped the build } else { - auto const guard_result = detail::hkdf_pieces_salt_guard(salt_bytes.size()); + auto const guard_result = detail::hkdf_pieces_salt_guard(salt.size()); if (!guard_result) { return guard_result.error(); } - return detail::hkdf_pieces_engine::extract(salt_bytes, input_key_material); + return detail::hkdf_pieces_engine::extract(salt, input_key_material); } } @@ -376,8 +375,8 @@ template ` names, `backends::hash2`. @param output_key_material The output keying material, 1 to 255 times the digest size. - @param salt_bytes The salt, any length the backend's HMAC takes as a key; empty means `Hmac`'s - digest size of zeros. + @param salt The salt, any length the backend's HMAC takes as a key; empty means `Hmac`'s digest + size of zeros. @param input_key_material The input keying material's pieces, of any number and length. @param application_info The context's pieces, of any number and length: no cap. @return Success, or the error of the first guard that fails (`invalid_output_size`, then @@ -386,20 +385,20 @@ template > [[nodiscard]] boost::system::result hkdf(std::span output_key_material, - std::span salt_bytes, + std::span salt, byte_pieces input_key_material, byte_pieces application_info) { secure::timing_guard const timing_scope; if constexpr (!detail::takes_hmac()) { return error::backend_failure; // unreachable: takes_hmac has stopped the build } else { - auto guard_result = detail::hkdf_pieces_guards(output_key_material.size(), - salt_bytes.size()); + auto guard_result = + detail::hkdf_pieces_guards(output_key_material.size(), salt.size()); if (!guard_result) { return guard_result; } auto derive_result = detail::hkdf_pieces_engine::extract_and_expand( - output_key_material, salt_bytes, input_key_material, application_info); + output_key_material, salt, input_key_material, application_info); if (!derive_result) { secure::erase_secret(output_key_material); } From 85577d9e6c0ae97bdbe2a416fcf2ac6765fad086 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 07:13:57 -0300 Subject: [PATCH 6/7] hash: the review's fixes: the comments, the engines' interface sketches and the guide quote the new parameter names; OpenSSL's SSKDF and X9.63 engines take fixed_info and shared_info as the public functions do; every @param starts its line and the paragraphs the longer names left short are rewrapped; AGENTS.md cites a real guard and states HKDF's salt --- AGENTS.md | 13 +- doc/async.adoc | 10 +- include/webcpp/hash/async.hpp | 48 +++--- include/webcpp/hash/backends/bearssl.hpp | 2 +- include/webcpp/hash/backends/botan.hpp | 4 +- include/webcpp/hash/backends/hash2.hpp | 16 +- include/webcpp/hash/backends/openssl.hpp | 16 +- include/webcpp/hash/backends/sodium.hpp | 8 +- include/webcpp/hash/backends/webcrypto.hpp | 25 ++-- include/webcpp/hash/backends/xkcp.hpp | 18 +-- include/webcpp/hash/bcrypt.hpp | 4 +- include/webcpp/hash/detail/engines.hpp | 161 +++++++++++---------- include/webcpp/hash/detail/limits.hpp | 2 +- include/webcpp/hash/digest.hpp | 11 +- include/webcpp/hash/mac.hpp | 5 +- test/user_globals_test.cpp | 22 +-- 16 files changed, 191 insertions(+), 174 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index a912717..e6761bb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -25,7 +25,7 @@ specific to hash. without. - Every function that computes on a key, a password or a key derivation's secret input holds `secure::timing_guard` (webcpp::secure's, ``) as its first - statement (`timing_scope{guard_engaged}` where the arguments decide whether the call is keyed); + statement (`timing_scope{seed_value != 0}` where the arguments decide whether the call is keyed); unkeyed digests and Boost.Hash2's types by alias hold none. A new keyed function, or a keyed cell that `doc/capabilities.json` gains (a MAC, a key derivation, a password hash, on any backend), holds the guard and gets its call in that backend's `test/timing_coverage__test.cpp`, @@ -38,10 +38,11 @@ specific to hash. secure, no other webcpp library. - `include/webcpp/hash/detail/canary.h` is a C header: it is in neither the headers-alone list nor `meta/include-boundaries.json`. -- Every local and parameter of a C++ function in `include/` takes two words, the role then the - kind (`timing_scope`, `salt_bytes`, `completion_token`): MSVC's C4459 at /W4 /WX stops a user's - program that has a global of a one-word name a header's function declares (a template's only - where it is instantiated). `test/user_globals_test.cpp` declares a global of each one-word name a - header once had, then calls every cell. The XKCP adapter's C declarations +- Every local and parameter of a C++ function in `include/` takes two words, the role then the kind + (`timing_scope`, `salt_bytes`, `completion_token`): MSVC's C4459 at /W4 /WX stops a user's program + that has a global of a one-word name a header's function declares (a template's only where it is + instantiated). `test/user_globals_test.cpp` declares a global of each one-word name a header once + had, then calls every cell. HKDF's public functions keep `salt`, the name the change hkdf-pieces + gives them: a function template's parameter raises no C4459. The XKCP adapter's C declarations (`detail/xkcp.hpp`) keep `src/xkcp_adapter.c`'s names: a declaration without a body raises no C4459. diff --git a/doc/async.adoc b/doc/async.adoc index 10edbe9..79e309b 100644 --- a/doc/async.adoc +++ b/doc/async.adoc @@ -230,10 +230,12 @@ to the synchronous function. HKDF's three asynchronous functions are those of <>, the pseudorandom key written into a span of the digest's size: -`async_hkdf_extract(executor, pseudorandom_key, salt, input_key_material, -token)`, `async_hkdf_expand(executor, output_key_material, pseudorandom_key, -application_info, token)` and `async_hkdf(executor, output_key_material, salt, -input_key_material, application_info, token)`. Each also has a form over +`async_hkdf_extract(completion_executor, pseudorandom_key, salt, +input_key_material, completion_token)`, +`async_hkdf_expand(completion_executor, output_key_material, pseudorandom_key, +application_info, completion_token)` and `async_hkdf(completion_executor, +output_key_material, salt, input_key_material, application_info, +completion_token)`. Each also has a form over `byte_pieces` (<>), with no limit on the pieces, whose inputs are read in the call: on a synchronous backend the synchronous function over pieces runs in the call itself and only its error code is posted, and on diff --git a/include/webcpp/hash/async.hpp b/include/webcpp/hash/async.hpp index bbe0ca4..874089a 100644 --- a/include/webcpp/hash/async.hpp +++ b/include/webcpp/hash/async.hpp @@ -235,8 +235,9 @@ using heavy_value_of = std::invoke_result_t::value_type; /** The initiation of a cheap function on a synchronous backend: runs the function's work (its guards - first) at once and posts the completion, with its error code, to `executor`, whence it reaches the - handler's associated executor; the post's storage is the handler's associated allocator's. + first) at once and posts the completion, with its error code, to `completion_executor`, whence it + reaches the handler's associated executor; the post's storage is the handler's associated + allocator's. */ struct post_initiation { /** @@ -271,8 +272,8 @@ auto complete_by_post(Executor const& completion_executor, CompletionToken& comp /** The initiation of a form over pieces on a synchronous backend, whose work has already run: posts - the completion, with the work's error code, to `executor`, whence it reaches the handler's - associated executor; the post's storage is the handler's associated allocator's. + the completion, with the work's error code, to `completion_executor`, whence it reaches the + handler's associated executor; the post's storage is the handler's associated allocator's. */ struct code_initiation { /** @@ -375,10 +376,10 @@ enum class heavy_phase : std::uint8_t { `partial` are (no C library here can be interrupted: the work ends, then the output is zeroed and the completion is `operation_aborted`, a side effect that `total` does not allow). - The completion runs on the handler's associated executor (`work` by default), where the slot's - signal is emitted: it clears the cancellation slot, moves the handler out, destroys the state and - gives its storage back to the handler's allocator, and only then calls the handler, so that - nothing of that allocator outlives the call (Asio's rule). The job queued in the work executor + The completion runs on the handler's associated executor (`work_executor` by default), where the + slot's signal is emitted: it clears the cancellation slot, moves the handler out, destroys the + state and gives its storage back to the handler's allocator, and only then calls the handler, so + that nothing of that allocator outlives the call (Asio's rule). The job queued in the work executor holds the state through one atomic pointer, whose location the state records under a lock each time the job moves; a cancellation before the work starts takes the state back from that location, so that the job, which may wait behind other work for long, holds nothing of the @@ -391,7 +392,7 @@ enum class heavy_phase : std::uint8_t { template class heavy_state { public: - /** The handler's associated executor, `work` by default. */ + /** The handler's associated executor, `work_executor` by default. */ using executor_type = webcpp::asio::associated_executor_t; /** The value the handler receives beside its code: `void` (none), or `bcrypt_verify`'s bool. */ using value_type = heavy_value_of; @@ -531,11 +532,11 @@ class heavy_state { }; // The completion, on the handler's executor, its storage the handler's allocator's. It owns - // the state: run, it frees the state and calls the handler (`invoke`), or, for a job destroyed - // unrun, only frees it, the handler with it; destroyed without running (its executor shut down - // or destroyed with it queued, as Asio destroys a queued operation), it frees the state and - // the handler too, never calling it, so that nothing of the handler's allocator is left and a - // handler that owns a promise breaks it. + // the state: run, it frees the state and calls the handler (`invoke_handler`), or, for a job + // destroyed unrun, only frees it, the handler with it; destroyed without running (its executor + // shut down or destroyed with it queued, as Asio destroys a queued operation), it frees the + // state and the handler too, never calling it, so that nothing of the handler's allocator is + // left and a handler that owns a promise breaks it. class completion { public: completion(heavy_state* operation_state, boost::system::error_code completion_code, @@ -580,7 +581,7 @@ class heavy_state { run_(std::move(bound_call)), output_(output_bytes) {} - // Constructs the state in `storage`, which is given back if the construction throws. + // Constructs the state in `state_storage`, which is given back if the construction throws. static void try_construct(allocator_type& handler_allocator, heavy_state* state_storage, Handler completion_handler, WorkExecutor const& work_executor, Work bound_call, std::span output_bytes) { @@ -608,7 +609,8 @@ class heavy_state { void unlock() noexcept { lock_.clear(std::memory_order_release); } - // The completion bound to the handler's associated allocator; `invoke` false only discards. + // The completion bound to the handler's associated allocator; `invoke_handler` false only + // discards. auto bound_completion(boost::system::error_code completion_code, bool invoke_handler = true) { // NOLINTNEXTLINE(bugprone-unchecked-optional-access): engaged until the completion return webcpp::asio::bind_allocator(webcpp::asio::get_associated_allocator(*handler_), @@ -810,8 +812,7 @@ auto run_on_work(WorkExecutor const& work_executor, std::span output_ /** Hashes `input_bytes` into `output_bytes` with the digest `Digest`, asynchronously (spec 11): on a synchronous backend, the default, at once, completing through a post on the handler's associated - executor - (`completion_executor` by default), never inside the call. + executor (`completion_executor` by default), never inside the call. @code webcpp::hash::async_digest( @@ -860,8 +861,7 @@ auto async_digest(Executor const& completion_executor, std::span o /** The HMAC of `input_bytes` under `key_bytes` over the Boost.Hash2 hmac `Hmac`, asynchronously (spec - 11), as - @ref async_digest runs: the tag of `mac>` over `Hmac`'s digest. + 11), as @ref async_digest runs: the tag of `mac>` over `Hmac`'s digest. @tparam Hmac `hmac_sha1_160`, `hmac_sha2_256`, `hmac_sha2_384` or `hmac_sha2_512`, the hmacs WebCrypto has; another refuses at compile time (`mac` has them all). @@ -922,8 +922,7 @@ auto async_hmac(Executor const& completion_executor, std::span out @param output_key_material The output keying material, 1 to 255 times the digest size. @param salt The salt. @param input_key_material The input keying material. @param application_info The context, at most `hkdf_max_application_info_size` bytes; on `backends::webcrypto` at most - 1,024, WebCrypto's limit - (`input_too_long` beyond). The spans are the caller's until completion. + 1,024, WebCrypto's limit (`input_too_long` beyond). The spans are the caller's until completion. @param completion_token The completion token, of signature `void(boost::system::error_code)`. @return What the completion token's `async_result` gives. The completion's code is empty on success, or `hkdf`'s error, `output_key_material` untouched by a guard's refusal and zeroed by a @@ -1216,9 +1215,8 @@ auto async_hkdf_expand(Executor const& completion_executor, behind another allocator or two concrete strands, completes with `invalid_parameters`, posted to the handler's associated executor. The calling thread is the program's duty, not checked. WebCrypto takes at most 2^32 - 1 iterations (`invalid_iterations`) and an output of at most (2^32 - 1) / 8 - bytes - (`invalid_output_size`), over `hmac_sha1_160`, `hmac_sha2_256`, `hmac_sha2_384` and `hmac_sha2_512` - alone. + bytes (`invalid_output_size`), over `hmac_sha1_160`, `hmac_sha2_256`, `hmac_sha2_384` and + `hmac_sha2_512` alone. Cancellation through the handler's slot, on a synchronous backend: before the work starts, any type completes the operation at once with `operation_aborted`, the work never runs; during it, a diff --git a/include/webcpp/hash/backends/bearssl.hpp b/include/webcpp/hash/backends/bearssl.hpp index 5c411d7..0721245 100644 --- a/include/webcpp/hash/backends/bearssl.hpp +++ b/include/webcpp/hash/backends/bearssl.hpp @@ -735,7 +735,7 @@ struct digest_engine mac_engine. It runs `br_hmac_key_init` with the digest's `br_hash_class` and the key, - `br_hmac_init` for a tag of `output.size()` bytes (BearSSL cuts the digest to it, RFC 2104 + `br_hmac_init` for a tag of `output_bytes.size()` bytes (BearSSL cuts the digest to it, RFC 2104 section 5), `br_hmac_update` and `br_hmac_out`; both contexts are wiped. @tparam Digest The digest's tag. diff --git a/include/webcpp/hash/backends/botan.hpp b/include/webcpp/hash/backends/botan.hpp index e7f5481..5683bd9 100644 --- a/include/webcpp/hash/backends/botan.hpp +++ b/include/webcpp/hash/backends/botan.hpp @@ -1487,8 +1487,8 @@ struct botan_pbkdf2_engine { /** RFC 8018, 5.2. - @param output_key_material DK. @param password_bytes P. @param salt_bytes S. @param - iteration_count c. + @param output_key_material DK. @param password_bytes P. @param salt_bytes S. + @param iteration_count c. @return Success, or Botan's failure. */ [[nodiscard]] static boost::system::result derive( diff --git a/include/webcpp/hash/backends/hash2.hpp b/include/webcpp/hash/backends/hash2.hpp index 92c130a..8974d88 100644 --- a/include/webcpp/hash/backends/hash2.hpp +++ b/include/webcpp/hash/backends/hash2.hpp @@ -92,8 +92,8 @@ struct hkdf_engine { RFC 5869, 2.3: T(0) = empty; T(i) = HMAC-Hash(PRK, T(i-1) | info | i); OKM = the first L octets of T(1) | T(2) | ... | T(N), N = ceil(L/HashLen). - @param output_key_material The OKM, its size L. @param pseudorandom_key The PRK. @param - application_info The info. + @param output_key_material The OKM, its size L. @param pseudorandom_key The PRK. + @param application_info The info. @return Success. */ [[nodiscard]] static boost::system::result expand( @@ -307,10 +307,10 @@ struct pbkdf2_engine { /** A digest of `digests` on backends::hash2, over the Boost.Hash2 algorithm `Hash` (its interface is @ref digest_engine); the state is a `Hash`, wiped by `destroy`. The output is the first - `output.size()` bytes of the results of `result()`, called one after the other: one result, the - whole of it, for a fixed-size digest, which the family's guards hold to its size; for SHAKE, whose - every `result()` permutes and gives the next block of the stream, as many blocks as the output - needs. + `output_bytes.size()` bytes of the results of `result()`, called one after the other: one result, + the whole of it, for a fixed-size digest, which the family's guards hold to its size; for SHAKE, + whose every `result()` permutes and gives the next block of the stream, as many blocks as the + output needs. @tparam Digest The tag. @tparam Hash Its Boost.Hash2 algorithm. */ @@ -643,8 +643,8 @@ struct mac_engine : full_engine { /** The tag of `input_bytes` under `key_bytes`. - @param output_bytes The tag, 32 bytes. @param key_bytes The key, 1 to 32 bytes. @param - input_bytes The message. + @param output_bytes The tag, 32 bytes. @param key_bytes The key, 1 to 32 bytes. + @param input_bytes The message. @return Success. */ [[nodiscard]] static boost::system::result compute( diff --git a/include/webcpp/hash/backends/openssl.hpp b/include/webcpp/hash/backends/openssl.hpp index e28242b..958508e 100644 --- a/include/webcpp/hash/backends/openssl.hpp +++ b/include/webcpp/hash/backends/openssl.hpp @@ -596,8 +596,8 @@ struct hkdf_engine { /** RFC 5869, 2.3, in expand-only mode. - @param output_key_material The OKM, its size L. @param pseudorandom_key The PRK. @param - application_info The info. + @param output_key_material The OKM, its size L. @param pseudorandom_key The PRK. + @param application_info The info. @return Success, or OpenSSL's failure. */ [[nodiscard]] static boost::system::result expand( @@ -1861,14 +1861,14 @@ struct sskdf_engine : openssl_digest_kdf_engine derive( std::span output_bytes, std::span secret_bytes, - std::span fixed_info_bytes) noexcept { + std::span fixed_info) noexcept { return openssl_digest_kdf_engine::derive_with("SSKDF", output_bytes, secret_bytes, - fixed_info_bytes); + fixed_info); } }; @@ -1883,14 +1883,14 @@ struct x963kdf_engine : openssl_digest_kdf_engine derive( std::span output_bytes, std::span secret_bytes, - std::span shared_info_bytes) noexcept { + std::span shared_info) noexcept { return openssl_digest_kdf_engine::derive_with("X963KDF", output_bytes, secret_bytes, - shared_info_bytes); + shared_info); } }; diff --git a/include/webcpp/hash/backends/sodium.hpp b/include/webcpp/hash/backends/sodium.hpp index e2dbf59..6e76c27 100644 --- a/include/webcpp/hash/backends/sodium.hpp +++ b/include/webcpp/hash/backends/sodium.hpp @@ -298,8 +298,8 @@ struct sodium_hkdf_engine { /** RFC 5869, 2.3, by libsodium's `_expand`. - @param output_key_material The OKM, its size L. @param pseudorandom_key The PRK. @param - application_info The info. + @param output_key_material The OKM, its size L. @param pseudorandom_key The PRK. + @param application_info The info. @return Success, or `error::backend_failure`. */ [[nodiscard]] static boost::system::result expand( @@ -950,8 +950,8 @@ struct sodium_hmac_engine : full_engine { /** The tag of `input_bytes` under `key_bytes`. - @param output_bytes The tag, 10 bytes to the digest's size (the family's guard). @param - key_bytes The key, of any size. @param input_bytes The message. + @param output_bytes The tag, 10 bytes to the digest's size (the family's guard). + @param key_bytes The key, of any size. @param input_bytes The message. @return Success, or `error::backend_failure`. */ [[nodiscard]] static boost::system::result compute( diff --git a/include/webcpp/hash/backends/webcrypto.hpp b/include/webcpp/hash/backends/webcrypto.hpp index 37c4fa1..1662fd3 100644 --- a/include/webcpp/hash/backends/webcrypto.hpp +++ b/include/webcpp/hash/backends/webcrypto.hpp @@ -475,7 +475,7 @@ struct webcrypto_pbkdf2_request { /** One WebCrypto call as an Asio composed operation (`async_compose`): the request's first promise awaited through `browser::async_await`, then, for a call of two, its second with the first's - result (the imported key); the completion copies the resulting `ArrayBuffer` into `output`. + result (the imported key); the completion copies the resulting `ArrayBuffer` into `output_bytes`. Its storage is the bridge's, one wait at a time, taken from the handler's associated allocator and given back before the wait's completion is posted, so that nothing of that allocator @@ -626,8 +626,8 @@ void post_webcrypto_refusal(Handler&& completion_handler, Executor const& comple /** The initiation of a WebCrypto call: @ref webcrypto_refusal, whose refusal is posted to the - handler's associated executor (`executor` by default) with its error; else the composed operation - starts. + handler's associated executor (`completion_executor` by default) with its error; else the composed + operation starts. */ struct webcrypto_initiation { /** @@ -887,7 +887,8 @@ struct webcrypto_hmac_hkdf_request { } private: - // `pieces` into `buffer` (webcrypto_gather) while every earlier input has been gathered. + // `input_pieces` into `target_buffer` (webcrypto_gather) while every earlier input has been + // gathered. void gather(webcrypto_secret& target_buffer, byte_pieces input_pieces, std::size_t prefix_size, std::size_t suffix_size) { if (gathered) { @@ -1053,7 +1054,7 @@ class webcrypto_hmac_hkdf_operation { return true; } - // Awaits `promise`, the operation moved into the wait. + // Awaits `pending_promise`, the operation moved into the wait. template void await(Self& operation_self, emscripten::val pending_promise) { // A copy: the wait moves `operation_self`, and this operation with it, before it reads the @@ -1079,13 +1080,13 @@ class webcrypto_hmac_hkdf_operation { message_data); } - // Whether `value` is a tag: an ArrayBuffer of HashLen bytes. + // Whether `promise_value` is a tag: an ArrayBuffer of HashLen bytes. [[nodiscard]] bool is_tag(emscripten::val const& promise_value) const { return promise_value.instanceof(emscripten::val::global("ArrayBuffer")) && promise_value["byteLength"].as() == request_.digest_length; } - // A Uint8Array over the ArrayBuffer `buffer`. + // A Uint8Array over the ArrayBuffer `array_buffer`. [[nodiscard]] static emscripten::val uint8_array(emscripten::val const& array_buffer) { return emscripten::val::global("Uint8Array").new_(array_buffer); } @@ -1095,7 +1096,7 @@ class webcrypto_hmac_hkdf_operation { return request_.blocks.bytes()["length"].as() - 1; } - // The first `size` bytes of `tag` into the output at `offset`. + // The first `byte_count` bytes of `tag_value` into the output at `byte_offset`. void copy(emscripten::val const& tag_value, std::size_t byte_offset, std::size_t byte_count) { emscripten::val(emscripten::typed_memory_view( byte_count, output_.subspan(byte_offset, byte_count).data())) @@ -1271,8 +1272,8 @@ struct async_engine { `async_hmac`: `importKey`, then `sign`; a tag shorter than the digest is its first bytes. @tparam Hmac `hmac_sha1_160`, `hmac_sha2_256`, `hmac_sha2_384` or `hmac_sha2_512`. - @param completion_executor The io_context's executor. @param output_bytes The tag. @param - key_bytes The key. + @param completion_executor The io_context's executor. @param output_bytes The tag. + @param key_bytes The key. @param input_bytes The message. @param completion_token The completion token. @return What the completion token's `async_result` gives. */ @@ -1301,8 +1302,8 @@ struct async_engine { @tparam Hmac `hmac_sha1_160`, `hmac_sha2_256`, `hmac_sha2_384` or `hmac_sha2_512`. @param completion_executor The io_context's executor. @param output_key_material The output keying material. - @param salt_bytes The salt. @param input_key_material The input keying material. @param - application_info The application info. + @param salt_bytes The salt. @param input_key_material The input keying material. + @param application_info The application info. @param completion_token The completion token. @return What the completion token's `async_result` gives. */ diff --git a/include/webcpp/hash/backends/xkcp.hpp b/include/webcpp/hash/backends/xkcp.hpp index 40ddd8c..a9b6cab 100644 --- a/include/webcpp/hash/backends/xkcp.hpp +++ b/include/webcpp/hash/backends/xkcp.hpp @@ -117,8 +117,8 @@ struct digest_engine : full_engine { A digest of `digests` on backends::xkcp over FIPS 202's `Keccak_Hash` (its interface is @ref digest_engine); Keccak-n, SHA3-n or SHAKE, by the sponge's capacity and padding. The state is the instance's storage, `xkcp_keccak_hash_storage`, wiped by `destroy`. A fixed-size digest - is written by `final`; an extendable output is squeezed, `output.size()` bytes from the first. - A refusal of XKCP's, which the family's guards leave no way to reach, is `backend_failure`. + is written by `final`; an extendable output is squeezed, `output_bytes.size()` bytes from the + first. A refusal of XKCP's, which the family's guards leave no way to reach, is `backend_failure`. @tparam Digest The tag. @tparam Capacity The sponge's capacity in bits (twice the digest's size; 256 for SHAKE128, 512 @@ -351,7 +351,7 @@ struct xkcp_kmac256_functions { /** cSHAKE on backends::xkcp (its interface is @ref digest_engine); XKCP's `cSHAKE_Instance` in `xkcp_cshake_storage`, wiped by `destroy`. It starts in the XOF form, since cSHAKE does not - encode the output's length, and squeezes `output.size()` bytes. The family's guards hold the + encode the output's length, and squeezes `output_bytes.size()` bytes. The family's guards hold the strings within `sp800_185_max_bytes`, the adapter's only refusal at `initialize`; any other nonzero answer of XKCP's is `backend_failure`. @@ -676,8 +676,8 @@ struct xkcp_parallelhash_engine : full_engine { /** KMAC on backends::xkcp (its interface is @ref mac_engine); XKCP's `KMAC_Instance`, on the stack - and wiped. The fixed-length form starts with L = `output.size()` and writes the tag at `final`; - the XOF form starts with 0 and squeezes it. Every key and tag size the family accepts. + and wiped. The fixed-length form starts with L = `output_bytes.size()` and writes the tag at + `final`; the XOF form starts with 0 and squeezes it. Every key and tag size the family accepts. @tparam Mac The tag. @tparam Functions The adapter's functions of its security strength. */ @@ -719,8 +719,8 @@ struct xkcp_kmac_engine : full_engine { /** TurboSHAKE on backends::xkcp (its interface is @ref digest_engine); XKCP's `TurboSHAKE_Instance` in `xkcp_turboshake_storage`, with the domain byte, both wiped by `destroy`. `finish` absorbs D - and squeezes `output.size()` bytes. The family's guard holds D within 0x01 to 0x7F (XKCP takes - any byte but 0); any nonzero answer of XKCP's is `backend_failure`. Every option and output + and squeezes `output_bytes.size()` bytes. The family's guard holds D within 0x01 to 0x7F (XKCP + takes any byte but 0); any nonzero answer of XKCP's is `backend_failure`. Every option and output size the family accepts. @tparam Digest The tag. @tparam Capacity 256 for TurboSHAKE128, 512 for TurboSHAKE256. @@ -811,8 +811,8 @@ struct xkcp_turboshake_engine : full_engine { `KangarooTwelve_Instance` in `xkcp_kangarootwelve_storage`, started with no fixed output, the customisation's span, and the bytes counted so far, all wiped by `destroy`. XKCP takes C at `KangarooTwelve_Final`, so the state keeps the span `init` took (ruling R33) and `finish` reads - it, then squeezes `output.size()` bytes. XKCP counts the 8,192-byte chunks of the message and C - in a `size_t`, which on wasm32 would wrap past 32 TiB: the engine counts the bytes of C and the + it, then squeezes `output_bytes.size()` bytes. XKCP counts the 8,192-byte chunks of the message and + C in a `size_t`, which on wasm32 would wrap past 32 TiB: the engine counts the bytes of C and the message in 64 bits and refuses the call that would take them past `kangarootwelve_max_bytes` with `input_too_long`, before XKCP sees the bytes, after which a hasher is spent and `digest_of`'s output zeroed. XKCP computes the chunks one after another (no parallel permutation diff --git a/include/webcpp/hash/bcrypt.hpp b/include/webcpp/hash/bcrypt.hpp index 7da77d3..a9beb00 100644 --- a/include/webcpp/hash/bcrypt.hpp +++ b/include/webcpp/hash/bcrypt.hpp @@ -246,8 +246,8 @@ template /** The modular crypt string of `password_bytes` under the caller's 16-byte `salt_bytes`, into 60 - chars: - "$2", the version, "$", the cost in two digits, "$", the salt then the hash in bcrypt's base 64. + chars: "$2", the version, "$", the cost in two digits, "$", the salt then the hash in bcrypt's base + 64. @tparam Backend The backend; @ref default_backend of `kdfs::bcrypt` has none (design D34): the call names `backends::botan`. diff --git a/include/webcpp/hash/detail/engines.hpp b/include/webcpp/hash/detail/engines.hpp index 5b6e7bc..4edc30a 100644 --- a/include/webcpp/hash/detail/engines.hpp +++ b/include/webcpp/hash/detail/engines.hpp @@ -147,15 +147,16 @@ struct backend_limits { @code using digest_type = typename Hmac::result_type; using bytes = std::span; - // RFC 5869 2.2: the PRK of `input_key_material` under `salt` (empty: HashLen zeros). - static boost::system::result extract(bytes salt, bytes input_key_material) noexcept; + // RFC 5869 2.2: the PRK of `input_key_material` under `salt_bytes` (empty: HashLen zeros). + static boost::system::result extract(bytes salt_bytes, + bytes input_key_material) noexcept; // RFC 5869 2.3: `output_key_material` (1 to 255 digests) from `pseudorandom_key` (one digest) // and `application_info` (at most hkdf_max_application_info_size bytes). static boost::system::result expand(std::span output_key_material, bytes pseudorandom_key, bytes application_info) noexcept; // Both steps. static boost::system::result extract_and_expand(std::span output_key_material, - bytes salt, bytes input_key_material, + bytes salt_bytes, bytes input_key_material, bytes application_info) noexcept; @endcode @@ -262,7 +263,7 @@ constexpr void for_each_slice(byte_pieces input_pieces, Update&& update_call) no using digest_type = typename Hmac::result_type; using bytes = std::span; // RFC 5869 2.2: PRK = HMAC(salt or HashLen zeros, piece_1 | ... | piece_n). - static boost::system::result extract(bytes salt, + static boost::system::result extract(bytes salt_bytes, byte_pieces input_key_material) noexcept; // RFC 5869 2.3: T(i) = HMAC(PRK, T(i - 1) | piece_1 | ... | piece_n | i). static boost::system::result expand(std::span output_key_material, @@ -270,7 +271,8 @@ constexpr void for_each_slice(byte_pieces input_pieces, Update&& update_call) no byte_pieces application_info) noexcept; // Both steps, the PRK wiped between them. static boost::system::result extract_and_expand(std::span output_key_material, - bytes salt, byte_pieces input_key_material, + bytes salt_bytes, + byte_pieces input_key_material, byte_pieces application_info) noexcept; @endcode @@ -300,7 +302,8 @@ struct hkdf_pieces_engine { the Expand). One copy, so that the wipe is the same on every backend. @tparam Engine A pieces engine with `extract(salt_bytes, input_key_material)` returning a - `boost::system::result` of the PRK's byte array and `expand(output, pseudorandom_key, info)`. + `boost::system::result` of the PRK's byte array and `expand(output_key_material, pseudorandom_key, + application_info)`. @param output_key_material The OKM. @param salt_bytes The salt. @param input_key_material The input keying material's pieces. @param application_info The info's pieces. @@ -338,12 +341,12 @@ inline constexpr std::uint64_t pbkdf2_max_blocks = 0xffffffffULL; A specialisation has one static member function, called after the guards of spec 2.9: @code - // RFC 8018 5.2: `output` (1 to (2^32 - 1) digests) from `password` and `salt`, by - // `iterations` (at least 1) rounds of Hmac. - static boost::system::result derive(std::span output, - std::span password, - std::span salt, - std::uint64_t iterations) noexcept; + // RFC 8018 5.2: `output_bytes` (1 to (2^32 - 1) digests) from `password_bytes` and + // `salt_bytes`, by `iteration_count` (at least 1) rounds of Hmac. + static boost::system::result derive(std::span output_bytes, + std::span password_bytes, + std::span salt_bytes, + std::uint64_t iteration_count) noexcept; @endcode @tparam Backend A backend of `backends`. @tparam Hmac A Boost.Hash2 hmac over a digest. @@ -404,10 +407,11 @@ struct scrypt_limits { @code static constexpr argon2id_limits limits{...}; - static boost::system::result derive(std::span output, - std::span password, - std::span salt, - std::uint64_t passes, std::size_t memory) noexcept; + static boost::system::result derive(std::span output_bytes, + std::span password_bytes, + std::span salt_bytes, + std::uint64_t pass_count, + std::size_t memory_limit) noexcept; @endcode A failure is `error::backend_failure`, or `errc::not_enough_memory` when the library could not @@ -463,10 +467,11 @@ struct argon2id_engine { @code static constexpr scrypt_limits limits{...}; - static boost::system::result derive(std::span output, - std::span password, - std::span salt, std::uint64_t n, - std::uint32_t r, std::uint32_t p) noexcept; + static boost::system::result derive(std::span output_bytes, + std::span password_bytes, + std::span salt_bytes, + std::uint64_t cost_n, std::uint32_t block_size_r, + std::uint32_t parallelism_p) noexcept; @endcode @tparam Backend A backend of `backends`. @@ -521,13 +526,13 @@ struct scrypt_engine { subkey of 16 to 64 bytes, the master key of 32 bytes, the context of 8 bytes; ruling R22): @code - // The subkey of output.size() bytes: BLAKE2b of the empty message under master_key, with - // subkey_id in 8 little-endian bytes then 8 zero bytes as the salt, and context then 8 zero + // The subkey of output_bytes.size() bytes: BLAKE2b of the empty message under master_key, with + // subkey_id in 8 little-endian bytes then 8 zero bytes as the salt, and context_bytes then 8 zero // bytes as the personalisation. - static boost::system::result derive(std::span output, + static boost::system::result derive(std::span output_bytes, std::span master_key, std::uint64_t subkey_id, - std::span context) noexcept; + std::span context_bytes) noexcept; @endcode A failure is `error::backend_failure`; the public function then zeroes the output. @@ -743,22 +748,24 @@ struct full_engine { static constexpr std::uint64_t min_output = ...; static constexpr std::uint64_t max_output = ...; // Whether the backend takes these options, every one the family accepts or fewer. - static bool accepts(digest_options const& options) noexcept; - // Starts a hash in `hashed`, a default-constructed state. - static boost::system::result init(state& hashed, digest_options const& options) - noexcept; - // Absorbs `input`, of any size. - static boost::system::result update(state& hashed, std::span input) - noexcept; - // Writes the result, of output.size() bytes; called once per init. - static boost::system::result finish(state& hashed, std::span output) noexcept; + static bool accepts(digest_options const& algorithm_options) noexcept; + // Starts a hash in `digest_state`, a default-constructed state. + static boost::system::result init(state& digest_state, + digest_options const& algorithm_options) noexcept; + // Absorbs `input_bytes`, of any size. + static boost::system::result update(state& digest_state, + std::span input_bytes) noexcept; + // Writes the result, of output_bytes.size() bytes; called once per init. + static boost::system::result finish(state& digest_state, + std::span output_bytes) noexcept; // Wipes the state and frees what it owns: called once after every init, whether init, update // and finish succeeded or not, and on each state moved from; a second call does nothing. - static void destroy(state& hashed) noexcept; + static void destroy(state& digest_state) noexcept; // init, update and finish at once, the state wiped. - static boost::system::result one_shot(std::span output, - std::span input, - digest_options const& options) noexcept; + static boost::system::result one_shot(std::span output_bytes, + std::span input_bytes, + digest_options const& algorithm_options) + noexcept; @endcode @ref full_engine gives `min_output`, `max_output` and `accepts` to an engine without narrower @@ -1202,14 +1209,14 @@ struct digest_engine : refused_digest_engine const& options, std::size_t key_size, + static bool accepts(mac_options const& algorithm_options, std::size_t key_size, std::size_t output_size) noexcept; - // The tag of `input` under `key`, of output.size() bytes (for HMAC, the digest cut to it: - // RFC 2104, section 5), every intermediate wiped. - static boost::system::result compute(std::span output, - std::span key, - std::span input, - mac_options const& options) noexcept; + // The tag of `input_bytes` under `key_bytes`, of output_bytes.size() bytes (for HMAC, the digest + // cut to it: RFC 2104, section 5), every intermediate wiped. + static boost::system::result compute(std::span output_bytes, + std::span key_bytes, + std::span input_bytes, + mac_options const& algorithm_options) noexcept; @endcode @ref full_engine gives `accepts` to an engine without narrower limits. A failure is @@ -1595,11 +1602,11 @@ struct argon2_limits { @code static constexpr argon2_limits limits{...}; - // RFC 9106, version 0x13: the tag of output.size() bytes. - static boost::system::result derive(std::span output, - std::span password, - std::span salt, - argon2_parameters const& parameters) noexcept; + // RFC 9106, version 0x13: the tag of output_bytes.size() bytes. + static boost::system::result derive(std::span output_bytes, + std::span password_bytes, + std::span salt_bytes, + argon2_parameters const& cost_parameters) noexcept; @endcode A failure is `error::backend_failure`, or `errc::not_enough_memory` when the memory cannot be @@ -1697,11 +1704,12 @@ struct kdf_standard_limits { @code static constexpr kdf_standard_limits limits{...}; - static constexpr bool accepts(kbkdf_options const& options) noexcept; // optional - // K_OUT, output.size() bytes, from K_IN, key, and the fixed input options states. - static boost::system::result derive(std::span output, - std::span key, - kbkdf_options const& options) noexcept; + static constexpr bool accepts(kbkdf_options const& algorithm_options) noexcept; // optional + // K_OUT, output_bytes.size() bytes, from K_IN, key_bytes, and the fixed input algorithm_options + // states. + static boost::system::result derive(std::span output_bytes, + std::span key_bytes, + kbkdf_options const& algorithm_options) noexcept; @endcode A failure is `error::backend_failure`, or `errc::not_enough_memory` when the library could not @@ -1740,7 +1748,7 @@ struct refused_digest_kdf_engine { /** Never called. @return backend_failure. */ [[nodiscard]] static boost::system::result derive( std::span /*output_bytes*/, std::span /*secret_bytes*/, - std::span /*info_bytes*/) noexcept { + std::span /*fixed_or_shared_info*/) noexcept { return error::backend_failure; } }; @@ -1755,9 +1763,9 @@ struct refused_digest_kdf_engine { @code static constexpr kdf_standard_limits limits{...}; - // output.size() bytes: H(counter || Z || FixedInfo) for counter 1, 2, ..., concatenated. - static boost::system::result derive(std::span output, - std::span secret, + // output_bytes.size() bytes: H(counter || Z || FixedInfo) for counter 1, 2, ..., concatenated. + static boost::system::result derive(std::span output_bytes, + std::span secret_bytes, std::span fixed_info) noexcept; @endcode @@ -1782,8 +1790,8 @@ struct sskdf_engine : refused_digest_kdf_engine, needs_library { @code static constexpr kdf_standard_limits limits{...}; - static boost::system::result derive(std::span output, - std::span secret, + static boost::system::result derive(std::span output_bytes, + std::span secret_bytes, std::span shared_info) noexcept; @endcode @@ -1813,15 +1821,18 @@ struct x963kdf_engine : refused_digest_kdf_engine, needs_library { // The highest cost the backend computes; a higher one, within bcrypt's 31, is // unsupported_by_backend. static constexpr std::uint32_t max_cost = ...; - // The 60 characters of password's bcrypt under the 16-byte salt, of cost (4 to max_cost) and - // version ('a', 'b' or 'y'): the password of at most 72 bytes, without a zero byte. - static boost::system::result generate(std::span output, - std::span password, - std::span salt, - std::uint32_t cost, char version) noexcept; - // Whether password gives hash, 60 characters of bcrypt's form, compared in constant time. - static boost::system::result verify(std::span password, - std::string_view hash) noexcept; + // The 60 characters of password_bytes' bcrypt under the 16-byte salt_bytes, of bcrypt_cost (4 to + // max_cost) and version_character ('a', 'b' or 'y'): the password of at most 72 bytes, without a + // zero byte. + static boost::system::result generate(std::span output_characters, + std::span password_bytes, + std::span salt_bytes, + std::uint32_t bcrypt_cost, + char version_character) noexcept; + // Whether password_bytes gives encoded_hash, 60 characters of bcrypt's form, compared in constant + // time. + static boost::system::result verify(std::span password_bytes, + std::string_view encoded_hash) noexcept; @endcode A failure is `error::backend_failure`, or `errc::not_enough_memory` when the library could not @@ -1863,12 +1874,12 @@ struct bcrypt_engine : needs_library { `derive` is called only after every guard of `bcrypt_pbkdf` (OpenBSD's limits) has passed: @code - // output.size() bytes (1 to 1,024) from password (1 byte or more) and salt (1 to 1,048,576 - // bytes), by rounds (1 or more) of bcrypt's hash. - static boost::system::result derive(std::span output, - std::span password, - std::span salt, - std::uint32_t rounds) noexcept; + // output_bytes.size() bytes (1 to 1,024) from password_bytes (1 byte or more) and salt_bytes (1 to + // 1,048,576 bytes), by round_count (1 or more) rounds of bcrypt's hash. + static boost::system::result derive(std::span output_bytes, + std::span password_bytes, + std::span salt_bytes, + std::uint32_t round_count) noexcept; @endcode @tparam Backend A backend of `backends`, or `no_default`. diff --git a/include/webcpp/hash/detail/limits.hpp b/include/webcpp/hash/detail/limits.hpp index 16ca340..f924383 100644 --- a/include/webcpp/hash/detail/limits.hpp +++ b/include/webcpp/hash/detail/limits.hpp @@ -24,7 +24,7 @@ namespace webcpp::hash::detail { @param checked_value The size, widened. @param size_limit The limit. - @return `value > limit`. + @return `checked_value > size_limit`. */ inline bool exceeds(std::uint64_t checked_value, std::uint64_t size_limit) noexcept { return checked_value > size_limit; diff --git a/include/webcpp/hash/digest.hpp b/include/webcpp/hash/digest.hpp index 30dd991..5b47992 100644 --- a/include/webcpp/hash/digest.hpp +++ b/include/webcpp/hash/digest.hpp @@ -345,11 +345,12 @@ struct extendable_output { }; /** - The family's guards of a tag of `digests`, in one place (spec 2.15): `min_output(options)` and - `max_output(options)`, the output sizes the tag produces (`invalid_output_size` outside them); - `check(options)`, the options' own guards (`invalid_parameters`, `invalid_key_size`, - `invalid_salt_size` or `input_too_long`), success for a tag without options. Every tag of `digests` - has a specialisation; the increment that gives a tag options adds their check to it. + The family's guards of a tag of `digests`, in one place (spec 2.15): + `min_output(algorithm_options)` and `max_output(algorithm_options)`, the output sizes the tag + produces (`invalid_output_size` outside them); `check(algorithm_options)`, the options' own guards + (`invalid_parameters`, `invalid_key_size`, `invalid_salt_size` or `input_too_long`), success for a + tag without options. Every tag of `digests` has a specialisation; the increment that gives a tag + options adds their check to it. The primary template, reached only by a type that is not a tag, guards nothing: the engine's refusal is then the call's only error. diff --git a/include/webcpp/hash/mac.hpp b/include/webcpp/hash/mac.hpp index 02e8a56..946730f 100644 --- a/include/webcpp/hash/mac.hpp +++ b/include/webcpp/hash/mac.hpp @@ -131,8 +131,9 @@ inline constexpr std::uint64_t hmac_min_output = 10; /** The family's guards of a tag of `macs`, in one place (spec 2.15): `min_output` and `max_output` (`invalid_output_size` outside them), `min_key` and `max_key` (`invalid_key_size`), and - `check(options)`, the options' own guards (`input_too_long` for KMAC's customisation). Every tag of - `macs` has a specialisation; the increment that gives a tag options adds their check to it. + `check(algorithm_options)`, the options' own guards (`input_too_long` for KMAC's customisation). + Every tag of `macs` has a specialisation; the increment that gives a tag options adds their check + to it. The primary template, reached only by a type that is not a tag, guards nothing: the engine's refusal is then the call's only error. diff --git a/test/user_globals_test.cpp b/test/user_globals_test.cpp index 1ecbd9c..0a0198a 100644 --- a/test/user_globals_test.cpp +++ b/test/user_globals_test.cpp @@ -12,15 +12,17 @@ // compilers it only runs the calls. A local takes two words, the role then the kind // (`timing_scope`, `completion_token`, `salt_bytes`), which no program names a global. // -// Every header of another library that a hash header includes comes first, so that their own -// names are parsed before the globals exist; then a global of every one-word name a hash header -// gave a local or a parameter until each took two words; then every public header. Every cell of -// every backend the program links is called (digests and hashers, MACs, the HKDFs over spans and -// over pieces, PBKDF2, KBKDF, SSKDF, X9.63, BLAKE2b's subkeys, Argon2, scrypt and bcrypt), and -// every asynchronous function on its default backend (bcrypt's on Botan, which is no default), -// which instantiates every template the calls reach. The parameters of detail/xkcp.hpp's C -// declarations, which have no body, raise no C4459 (14.3, with the globals `storage`, `input`, -// `output` and `length` below) and keep the C adapter's names. +// Every header of another library that a hash header includes comes first, so that their own names +// are parsed before the globals exist; then a global of every one-word name a hash header gave a +// local or a parameter until each took two words (but the public HKDF functions' `salt`, which the +// change hkdf-pieces names so, and which, a function template's parameter, raises no C4459: 14.3 +// and 14.5 say nothing of a template's parameters); then every public header. Every cell of every +// backend the program links is called (digests and hashers, MACs, the HKDFs over spans and over +// pieces, PBKDF2, KBKDF, SSKDF, X9.63, BLAKE2b's subkeys, Argon2, scrypt and bcrypt), and every +// asynchronous function on its default backend (bcrypt's on Botan, which is no default), which +// instantiates every template the calls reach. The parameters of detail/xkcp.hpp's C declarations, +// which have no body, raise no C4459 (14.3, with the globals `storage`, `input`, `output` and +// `length` below) and keep the C adapter's names. // // How the list was made: an aggregate translation unit of every header of include/, every backend // and webcpp::asio linked, its AST dumped (clang -Xclang -ast-dump=json, filtered to webcpp::hash), @@ -397,7 +399,7 @@ void call_every_cell() { } } -/** Every asynchronous function, on its default backend, each completing on `io_context`. */ +/** Every asynchronous function, on its default backend, each completing on `context_object`. */ void call_every_async(asio::io_context& context_object) { auto const io_executor = context_object.get_executor(); std::array output_buffer{}; From 8a1c0266055d249d6fd52cfc2bb421886cb7a675 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 07:40:18 -0300 Subject: [PATCH 7/7] hash: user_globals drives its io_context with poll, as the lint asks: every completion is posted --- test/user_globals_test.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/user_globals_test.cpp b/test/user_globals_test.cpp index 0a0198a..c18d499 100644 --- a/test/user_globals_test.cpp +++ b/test/user_globals_test.cpp @@ -440,7 +440,7 @@ void call_every_async(asio::io_context& context_object) { [](boost::system::error_code const&, bool) {}); #endif #endif - context_object.run(); + context_object.poll(); // every completion is posted, none waits on I/O or a timer } } // namespace