diff --git a/bench/allocation_collect.py b/bench/allocation_collect.py index 8eef5a0..d92ca50 100755 --- a/bench/allocation_collect.py +++ b/bench/allocation_collect.py @@ -18,8 +18,10 @@ shaped like doc/measurements.throughput.json's: operation, backend, target, implementation and the counts. backends::botan's records (one per call of each of its entry points, a first call and a steady one) keep their tag; the table gives one row per operation and target, the range over the -tags. The page's table, between the `tag::table[]` and `end::table[]` lines, is rendered from the -data and never typed; --check fails when the page differs from what the data renders. +tags. An operation recorded as `_pieces`, HKDF's functions over byte pieces, is the table's +"`` over pieces". The page's table, between the `tag::table[]` and `end::table[]` lines, is +rendered from the data and never typed; --check fails when the page differs from what the data +renders. The table is built only from release builds: the counting programs are bench/Jamfile's allocation_release, allocation_openssl_release and allocation_botan_release (`b2 @@ -48,7 +50,23 @@ "the table is built only from release builds: bench/Jamfile's allocation_release, " "allocation_openssl_release and allocation_botan_release at " + BUILD ) -KEPT = {"argon2id", "scrypt", "sodium_init", "hkdf", "pbkdf2"} +# OpenSSL's operations the table keeps, in its order: HKDF, its three functions over byte pieces +# (operation=_pieces), and PBKDF2. +OPENSSL_OPERATIONS = ( + "hkdf", + "hkdf_extract_pieces", + "hkdf_expand_pieces", + "hkdf_pieces", + "pbkdf2", +) +KEPT = {"argon2id", "scrypt", "sodium_init", *OPENSSL_OPERATIONS} + + +def operation_name(operation): + """The table's name of a record's operation: `hkdf`, or `hkdf` over pieces for hkdf_pieces.""" + if operation.endswith("_pieces"): + return "`%s` over pieces" % operation.removesuffix("_pieces") + return "`%s`" % operation def build_of(output): @@ -218,7 +236,7 @@ def render(data): if not c["c_allocator_counted"]: counted = "C library: not counted" rows.append((c["operation"], c["backend"], target, str(c["operator_new"]), counted)) - for op in ("hkdf", "pbkdf2"): + for op in OPENSSL_OPERATIONS: mine = [ c for c in by_target[target] if c["operation"] == op and c["backend"] == "openssl" ] @@ -246,7 +264,11 @@ def at(hmac, call): "", ] for row in rows: - lines.append("| `%s` | `%s` | %s | %s | %s" % row) + operation, backend, target, operator_new, detail = row + lines.append( + "| %s | `%s` | %s | %s | %s" + % (operation_name(operation), backend, target, operator_new, detail) + ) lines.append("|===") return "\n".join(lines) + "\n" diff --git a/doc/allocation.adoc b/doc/allocation.adoc index b997187..2797e3a 100644 --- a/doc/allocation.adoc +++ b/doc/allocation.adoc @@ -10,7 +10,8 @@ hash's own code allocates nothing: no function of `webcpp::hash` calls the global `operator new`, on any target, and none calls the C library's allocator on the targets where a program can count it. Test `allocation` proves that hash allocates nothing for -Keccak-256, BLAKE3, Boost.Hash2's digests and hmacs, and HKDF and PBKDF2 on +Keccak-256, BLAKE3, Boost.Hash2's digests and hmacs, and HKDF (its three functions over +byte pieces too, with inputs of 4 KiB and 1 MiB in four pieces) and PBKDF2 on `backends::hash2`, `backends::sodium` and `backends::bearssl`, the failing calls (every guard's refusal) included. It counts every form of `operator new` and the C library's `malloc`, `calloc`, `realloc`, `aligned_alloc` and `posix_memalign` on glibc, macOS, @@ -23,9 +24,12 @@ counter does not see is `mmap`, which the C libraries below use. One exception is not hash's own: on Emscripten, a call on `backends::webcrypto` awaits each of WebCrypto's promises through webcpp::asio's `browser::async_await`, whose bridge to -JavaScript takes a block from the C library per promise awaited (one promise for -`async_digest`, two for `async_hmac`, `async_hkdf` and `async_pbkdf2`, which import a key -first). Test `allocation` counts a bare await's blocks, prints them as +JavaScript takes a block from the C library per promise awaited: one promise for +`async_digest`; two for `async_hmac`, `async_pbkdf2`, the single-buffer `async_hkdf` and +`async_hkdf_extract` (over pieces too), which import a key first; 1 + n for +`async_hkdf_expand` and 3 + n for `async_hkdf` over pieces, which sign once per block of +output, n the output's size in digests rounded up. The pieces are gathered into JavaScript +memory, not webcpp's. Test `allocation` counts a bare await's blocks, prints them as `record operation=async_await`, and checks that each WebCrypto call makes exactly that many per promise and nothing more. The table below leaves that block out: it lists the C libraries of hash's backends, and the block is webcpp::asio's. @@ -66,8 +70,8 @@ The table is generated from `measurements.allocation.json` by `allocation_release`, `allocation_openssl_release` and `allocation_botan_release` of `bench/Jamfile`, the programs of the three tests built at `variant=release`, and the collector refuses an output of any other variant. The tests of the lanes keep the lane's variant. The -figures are those of the machine the file records; Botan's rows, collected on 2026-11-21, are -to be re-measured in the final pass, with every other count, before the release. +figures are those of the machine and the day the file records (every row collected on +2026-11-24), to be measured again in the final pass before the release. // tag::table[] [cols="1,1,1,1,3",options="header"] @@ -78,6 +82,9 @@ to be re-measured in the final pass, with every other count, before the release. | `argon2id` | `sodium` | native | 0 | C library calls: 3 | `scrypt` | `sodium` | native | 0 | C library calls: 0 | `hkdf` | `openssl` | native | 0 | OpenSSL: 4080 first call (hmac_sha2_256), 30 first call (hmac_sha2_512), 24 steady state +| `hkdf_extract` over pieces | `openssl` | native | 0 | OpenSSL: 10 first call (hmac_sha2_256), 10 first call (hmac_sha2_512), 10 steady state +| `hkdf_expand` over pieces | `openssl` | native | 0 | OpenSSL: 30 first call (hmac_sha2_256), 20 first call (hmac_sha2_512), 20 steady state +| `hkdf` over pieces | `openssl` | native | 0 | OpenSSL: 40 first call (hmac_sha2_256), 30 first call (hmac_sha2_512), 30 steady state | `pbkdf2` | `openssl` | native | 0 | OpenSSL: 30 first call (hmac_sha2_256), 18 first call (hmac_sha2_512), 18 steady state | `digest_of` | `botan` | native | 1 to 4 | Botan: 1 to 13 C library calls (operator new's included), over its 25 algorithms; the same in a steady call | `hasher` | `botan` | native | 1 to 4 | Botan: 1 to 13 C library calls (operator new's included), over its 25 algorithms; the same in a steady call @@ -87,6 +94,9 @@ to be re-measured in the final pass, with every other count, before the release. | `hkdf` | `botan` | native | 17 to 30 | Botan: 25 to 39 C library calls (operator new's included), over its 14 algorithms; the same in a steady call | `pbkdf2` | `botan` | native | 16 to 29 | Botan: 21 to 34 C library calls (operator new's included), over its 14 algorithms; the same in a steady call | `kbkdf` | `botan` | native | 18 to 28 | Botan: 21 to 32 C library calls (operator new's included), over its 14 algorithms; the same in a steady call +| `hkdf_extract` over pieces | `botan` | native | 4 to 7 | Botan: 7 to 10 C library calls (operator new's included), over its 14 algorithms; the same in a steady call +| `hkdf_expand` over pieces | `botan` | native | 4 to 7 | Botan: 7 to 11 C library calls (operator new's included), over its 14 algorithms; the same in a steady call +| `hkdf` over pieces | `botan` | native | 8 to 14 | Botan: 14 to 20 C library calls (operator new's included), over its 14 algorithms; the same in a steady call | `sskdf` | `botan` | native | 4 to 7 | Botan: 5 to 8 C library calls (operator new's included), over its 10 algorithms; the same in a steady call | `x963kdf` | `botan` | native | 4 | Botan: 5 to 6 C library calls (operator new's included), over its 5 algorithms; the same in a steady call | `argon2id` | `botan` | native | 6 | Botan: 9 C library calls (operator new's included), of kdfs::argon2id; the same in a steady call @@ -99,11 +109,17 @@ to be re-measured in the final pass, with every other count, before the release. | `argon2id` | `sodium` | wasip2 | 0 | C library calls: 5 | `scrypt` | `sodium` | wasip2 | 0 | C library calls: 1 | `hkdf` | `openssl` | wasip2 | 0 | OpenSSL: 3960 first call (hmac_sha2_256), 30 first call (hmac_sha2_512), 24 steady state +| `hkdf_extract` over pieces | `openssl` | wasip2 | 0 | OpenSSL: 10 first call (hmac_sha2_256), 10 first call (hmac_sha2_512), 10 steady state +| `hkdf_expand` over pieces | `openssl` | wasip2 | 0 | OpenSSL: 30 first call (hmac_sha2_256), 20 first call (hmac_sha2_512), 20 steady state +| `hkdf` over pieces | `openssl` | wasip2 | 0 | OpenSSL: 40 first call (hmac_sha2_256), 30 first call (hmac_sha2_512), 30 steady state | `pbkdf2` | `openssl` | wasip2 | 0 | OpenSSL: 30 first call (hmac_sha2_256), 18 first call (hmac_sha2_512), 18 steady state | `sodium_init` | `sodium` | wasip3 | 0 | C library calls: 1 | `argon2id` | `sodium` | wasip3 | 0 | C library calls: 5 | `scrypt` | `sodium` | wasip3 | 0 | C library calls: 1 | `hkdf` | `openssl` | wasip3 | 0 | OpenSSL: 3960 first call (hmac_sha2_256), 30 first call (hmac_sha2_512), 24 steady state +| `hkdf_extract` over pieces | `openssl` | wasip3 | 0 | OpenSSL: 10 first call (hmac_sha2_256), 10 first call (hmac_sha2_512), 10 steady state +| `hkdf_expand` over pieces | `openssl` | wasip3 | 0 | OpenSSL: 30 first call (hmac_sha2_256), 20 first call (hmac_sha2_512), 20 steady state +| `hkdf` over pieces | `openssl` | wasip3 | 0 | OpenSSL: 40 first call (hmac_sha2_256), 30 first call (hmac_sha2_512), 30 steady state | `pbkdf2` | `openssl` | wasip3 | 0 | OpenSSL: 30 first call (hmac_sha2_256), 18 first call (hmac_sha2_512), 18 steady state | `sodium_init` | `sodium` | emscripten | 0 | C library calls: 0 | `argon2id` | `sodium` | emscripten | 0 | C library calls: 4 @@ -116,6 +132,9 @@ to be re-measured in the final pass, with every other count, before the release. | `hkdf` | `botan` | emscripten | 24 to 44 | Botan: 32 to 53 C library calls (operator new's included), over its 14 algorithms; the same in a steady call | `pbkdf2` | `botan` | emscripten | 23 to 43 | Botan: 28 to 48 C library calls (operator new's included), over its 14 algorithms; the same in a steady call | `kbkdf` | `botan` | emscripten | 24 to 43 | Botan: 27 to 47 C library calls (operator new's included), over its 14 algorithms; the same in a steady call +| `hkdf_extract` over pieces | `botan` | emscripten | 4 to 13 | Botan: 7 to 16 C library calls (operator new's included), over its 14 algorithms; the same in a steady call +| `hkdf_expand` over pieces | `botan` | emscripten | 4 to 13 | Botan: 10 to 17 C library calls (operator new's included), over its 14 algorithms; the same in a steady call +| `hkdf` over pieces | `botan` | emscripten | 8 to 26 | Botan: 18 to 32 C library calls (operator new's included), over its 14 algorithms; the same in a steady call | `sskdf` | `botan` | emscripten | 7 to 10 | Botan: 8 to 11 C library calls (operator new's included), over its 10 algorithms; the same in a steady call | `x963kdf` | `botan` | emscripten | 7 | Botan: 8 to 9 C library calls (operator new's included), over its 5 algorithms; the same in a steady call | `argon2id` | `botan` | emscripten | 10 | Botan: 13 C library calls (operator new's included), of kdfs::argon2id; the same in a steady call diff --git a/doc/async.adoc b/doc/async.adoc index b6cfe4a..10edbe9 100644 --- a/doc/async.adoc +++ b/doc/async.adoc @@ -29,15 +29,16 @@ The functions come in two kinds: * *The heavy functions*, `async_argon2id`, `async_argon2`, `async_scrypt`, `async_pbkdf2`, `async_bcrypt`, `async_bcrypt_pbkdf` and -`async_bcrypt_verify`, run the work on another thread, on an executor the program -gives (the executor of a `webcpp::asio::thread_pool`), and complete on the -event loop. They exist only where the build has threads. -* *The cheap functions*, `async_digest`, `async_hmac` and `async_hkdf`, cost -microseconds: they run at once and complete through the event loop, never -inside the call. They exist on every target, for the algorithms the browser's -WebCrypto has (SHA-1, SHA-256, SHA-384, SHA-512, and HMAC and HKDF over them), -so that a program written once against WebCrypto's family builds and runs -everywhere. +`async_bcrypt_verify`, run the work on another thread, on an executor the +program gives (the executor of a `webcpp::asio::thread_pool`), and complete on +the event loop. They exist only where the build has threads. +* *The cheap functions*, `async_digest`, `async_hmac`, `async_hkdf_extract`, +`async_hkdf_expand` and `async_hkdf` (each HKDF function also over byte +pieces), cost microseconds: they run at once and complete through the event +loop, never inside the call. They exist on every target, for the algorithms +the browser's WebCrypto has (SHA-1, SHA-256, SHA-384, SHA-512, and HMAC and +HKDF over them), so that a program written once against WebCrypto's family +builds and runs everywhere. Each runs, by default, on the synchronous function's backend (<>): `backends::webcrypto`, the browser's WebCrypto, is @@ -204,12 +205,12 @@ interrupted. [#hash-async-cheap] === The cheap functions through the event loop -`async_digest`, `async_hmac` and `async_hkdf` run the synchronous function at -once, its guards first, and post the completion, with its error code, to the -executor the call gives, whence it reaches the handler's associated executor. -The completion never runs inside the call, so a handler written for the -browser's WebCrypto, which always completes later, behaves the same on every -target: +`async_digest`, `async_hmac`, `async_hkdf_extract`, `async_hkdf_expand` and +`async_hkdf` run the synchronous function at once, its guards first, and post +the completion, with its error code, to the executor the call gives, whence it +reaches the handler's associated executor. The completion never runs inside +the call, so a handler written for the browser's WebCrypto, which always +completes later, behaves the same on every target: [source] ---- @@ -227,6 +228,25 @@ include::{examples}/async_hkdf.expected[] as `async_digest`, stops the build: a post would add nothing 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 +`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 +`backends::webcrypto` the salt, the pseudorandom key and the pieces are copied +into JavaScript memory in the call. So 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, a lazy one included: `async_hkdf(executor, key, salt, +{hpke_v1, suite_id, extract_label, ikm}, {length, hpke_v1, suite_id, +expand_label, info}, token)` runs one HPKE LabeledExtract and one +LabeledExpand in one asynchronous call. `hkdf_pieces.cpp` +(<>) calls `hkdf_extract` and `hkdf_expand` apart instead, +since HPKE's key schedule expands one secret three times. + *Pitfalls.* * *The storage is the handler's.* The post allocates with the handler's @@ -234,7 +254,21 @@ associated allocator (`bind_allocator`), as every Asio operation does; a program that counts or pools its allocations binds its own. * *The same spans rule.* The output and the inputs are the caller's until the completion, even though the work runs before the call returns: a backend -named in the type may run later (WebCrypto does). +named in the type may run later (WebCrypto does). The forms over pieces read +every input in the call, on every backend: the salt, the pseudorandom key, the +pieces and their list. Only the output stays the caller's until the +completion. +* *A lazy token does not delay the forms over pieces.* With `asio::deferred`, +or the awaitable of `use_awaitable`, an operation normally starts when it is +launched or awaited. The forms over pieces on a synchronous backend compute +and write the output at the call, before the token is used; only the +completion waits. A program that must not derive before the launch calls +them at the launch. +* *A lone `{}` is ambiguous.* As in the synchronous functions, `{}`, or a +braced list of one element that is not exactly a +`std::span`, in a pieces position matches both forms: +`async_hkdf(executor, okm, salt, {}, {}, token)` does not compile. Pass an +empty span, `x` itself or `+byte_pieces{...}+`. * *`backends::webcrypto` is for Emscripten.* Named off Emscripten, it stops the build: "webcpp::hash: backends::webcrypto exists only on Emscripten: name a synchronous backend, or leave the default." In a synchronous function it @@ -295,11 +329,26 @@ Strands and type-erased executors of the `io_context` are accepted; behind type: pass the inner strand, or the executor of the `io_context`. That the `io_context` runs on the calling thread is the program's duty: it cannot be checked. -* *WebCrypto's limits are narrower.* An HKDF info longer than 1,024 bytes -(node's limit, where the other backends take 32,768) completes with -`input_too_long`; PBKDF2's iteration count is at most 2^32 - 1 -(`invalid_iterations`); an output of HKDF or PBKDF2 is at most +* *WebCrypto's limits are narrower.* The single-buffer `async_hkdf` runs +WebCrypto's own HKDF, `deriveBits`, and an application_info longer than 1,024 +bytes (node's limit, where the other backends take 32,768) completes with +`input_too_long`. The other HKDF functions run RFC 5869's steps on WebCrypto's +HMAC: the single-buffer `async_hkdf_expand` keeps the 32,768 bytes of every +backend (Extract has no application info), and the forms over pieces have no +limit of hash's own, so `async_hkdf` over +`+byte_pieces{input_key_material}+` and `+byte_pieces{info}+` takes a longer +info. PBKDF2's iteration count is at most +2^32 - 1 (`invalid_iterations`); an output of HKDF or PBKDF2 is at most (2^32 - 1) / 8 bytes. A program that needs more names a synchronous backend. +* *HKDF over HMAC is a promise per block.* `async_hkdf_extract` imports the +salt and signs once; `async_hkdf_expand` imports the pseudorandom key and +signs once per digest of output; `async_hkdf` over pieces does both. The +inputs are gathered into JavaScript memory in the call, as long as the +runtime will allocate a buffer that size (`backend_failure` beyond), and every +buffer of JavaScript that held a secret is zeroed when its promise settles. +The keys WebCrypto imports (`CryptoKey`) cannot be zeroed, since WebCrypto has +no way to, and neither can a tag that arrives after a cancellation, which is +dropped unseen. * *An empty HMAC key is one zero byte.* WebCrypto refuses an empty key; HMAC pads every key with zeros to its block (RFC 2104), so the two are the same key, and webcpp passes one zero byte: the tag is the other backends'. diff --git a/doc/backends.adoc b/doc/backends.adoc index 9958790..219814d 100644 --- a/doc/backends.adoc +++ b/doc/backends.adoc @@ -1576,6 +1576,12 @@ states about its constant time. The backends: | not stated | native, emscripten +| hkdf_extract +| webcrypto (asynchronous family only) +| hmac_sha1_160, hmac_sha2_256, hmac_sha2_384, hmac_sha2_512 +| not stated +| emscripten + | hkdf_expand | hash2 | hmac_md5_128, hmac_sha1_160, hmac_sha2_224, hmac_sha2_256, hmac_sha2_384, hmac_sha2_512, hmac_sha2_512_224, hmac_sha2_512_256, hmac_sha3_224, hmac_sha3_256, hmac_sha3_384, hmac_sha3_512, hmac_ripemd_128, hmac_ripemd_160, hmac_blake2b_512, hmac_blake2s_256, other @@ -1600,6 +1606,12 @@ states about its constant time. The backends: | not stated | native, emscripten +| hkdf_expand +| webcrypto (asynchronous family only) +| hmac_sha1_160, hmac_sha2_256, hmac_sha2_384, hmac_sha2_512 +| not stated +| emscripten + | hkdf | hash2 | hmac_md5_128, hmac_sha1_160, hmac_sha2_224, hmac_sha2_256, hmac_sha2_384, hmac_sha2_512, hmac_sha2_512_224, hmac_sha2_512_256, hmac_sha3_224, hmac_sha3_256, hmac_sha3_384, hmac_sha3_512, hmac_ripemd_128, hmac_ripemd_160, hmac_blake2b_512, hmac_blake2s_256, other @@ -1631,7 +1643,115 @@ states about its constant time. The backends: | native, emscripten | hkdf -| webcrypto (asynchronous family only) (partial: an info longer than 1,024 bytes, which completes with input_too_long: WebCrypto's limit as node has it, where the other backends take 32,768) +| webcrypto (asynchronous family only) (partial: an application_info longer than 1,024 bytes, which completes with input_too_long: WebCrypto's limit as node has it, where the other backends take 32,768) +| hmac_sha1_160, hmac_sha2_256, hmac_sha2_384, hmac_sha2_512 +| not stated +| emscripten + +| hkdf_extract over pieces +| hash2 +| hmac_md5_128, hmac_sha1_160, hmac_sha2_224, hmac_sha2_256, hmac_sha2_384, hmac_sha2_512, hmac_sha2_512_224, hmac_sha2_512_256, hmac_sha3_224, hmac_sha3_256, hmac_sha3_384, hmac_sha3_512, hmac_ripemd_128, hmac_ripemd_160, hmac_blake2b_512, hmac_blake2s_256, other +| not stated +| native, wasip2, wasip3, emscripten + +| hkdf_extract over pieces +| sodium +| hmac_sha2_256, hmac_sha2_512 +| not stated +| native, wasip2, wasip3, emscripten + +| hkdf_extract over pieces +| bearssl +| hmac_md5_128, hmac_sha1_160, hmac_sha2_224, hmac_sha2_256, hmac_sha2_384, hmac_sha2_512 +| not stated +| native, wasip2, wasip3, emscripten + +| hkdf_extract over pieces +| openssl +| hmac_md5_128, hmac_sha1_160, hmac_sha2_224, hmac_sha2_256, hmac_sha2_384, hmac_sha2_512, hmac_sha2_512_224, hmac_sha2_512_256, hmac_sha3_224, hmac_sha3_256, hmac_sha3_384, hmac_sha3_512, hmac_ripemd_160, hmac_blake2b_512, hmac_blake2s_256 +| not stated +| native, wasip2, wasip3 + +| hkdf_extract over pieces +| botan (with exceptions only) +| hmac_md5_128, hmac_sha1_160, hmac_sha2_224, hmac_sha2_256, hmac_sha2_384, hmac_sha2_512, hmac_sha2_512_256, hmac_sha3_224, hmac_sha3_256, hmac_sha3_384, hmac_sha3_512, hmac_ripemd_160, hmac_blake2b_512, hmac_blake2s_256 +| not stated +| native, emscripten + +| hkdf_extract over pieces +| webcrypto (asynchronous family only) +| hmac_sha1_160, hmac_sha2_256, hmac_sha2_384, hmac_sha2_512 +| not stated +| emscripten + +| hkdf_expand over pieces +| hash2 +| hmac_md5_128, hmac_sha1_160, hmac_sha2_224, hmac_sha2_256, hmac_sha2_384, hmac_sha2_512, hmac_sha2_512_224, hmac_sha2_512_256, hmac_sha3_224, hmac_sha3_256, hmac_sha3_384, hmac_sha3_512, hmac_ripemd_128, hmac_ripemd_160, hmac_blake2b_512, hmac_blake2s_256, other +| not stated +| native, wasip2, wasip3, emscripten + +| hkdf_expand over pieces +| sodium +| hmac_sha2_256, hmac_sha2_512 +| not stated +| native, wasip2, wasip3, emscripten + +| hkdf_expand over pieces +| bearssl +| hmac_md5_128, hmac_sha1_160, hmac_sha2_224, hmac_sha2_256, hmac_sha2_384, hmac_sha2_512 +| not stated +| native, wasip2, wasip3, emscripten + +| hkdf_expand over pieces +| openssl +| hmac_md5_128, hmac_sha1_160, hmac_sha2_224, hmac_sha2_256, hmac_sha2_384, hmac_sha2_512, hmac_sha2_512_224, hmac_sha2_512_256, hmac_sha3_224, hmac_sha3_256, hmac_sha3_384, hmac_sha3_512, hmac_ripemd_160, hmac_blake2b_512, hmac_blake2s_256 +| not stated +| native, wasip2, wasip3 + +| hkdf_expand over pieces +| botan (with exceptions only) +| hmac_md5_128, hmac_sha1_160, hmac_sha2_224, hmac_sha2_256, hmac_sha2_384, hmac_sha2_512, hmac_sha2_512_256, hmac_sha3_224, hmac_sha3_256, hmac_sha3_384, hmac_sha3_512, hmac_ripemd_160, hmac_blake2b_512, hmac_blake2s_256 +| not stated +| native, emscripten + +| hkdf_expand over pieces +| webcrypto (asynchronous family only) +| hmac_sha1_160, hmac_sha2_256, hmac_sha2_384, hmac_sha2_512 +| not stated +| emscripten + +| hkdf over pieces +| hash2 +| hmac_md5_128, hmac_sha1_160, hmac_sha2_224, hmac_sha2_256, hmac_sha2_384, hmac_sha2_512, hmac_sha2_512_224, hmac_sha2_512_256, hmac_sha3_224, hmac_sha3_256, hmac_sha3_384, hmac_sha3_512, hmac_ripemd_128, hmac_ripemd_160, hmac_blake2b_512, hmac_blake2s_256, other +| not stated +| native, wasip2, wasip3, emscripten + +| hkdf over pieces +| sodium +| hmac_sha2_256, hmac_sha2_512 +| not stated +| native, wasip2, wasip3, emscripten + +| hkdf over pieces +| bearssl +| hmac_md5_128, hmac_sha1_160, hmac_sha2_224, hmac_sha2_256, hmac_sha2_384, hmac_sha2_512 +| not stated +| native, wasip2, wasip3, emscripten + +| hkdf over pieces +| openssl +| hmac_md5_128, hmac_sha1_160, hmac_sha2_224, hmac_sha2_256, hmac_sha2_384, hmac_sha2_512, hmac_sha2_512_224, hmac_sha2_512_256, hmac_sha3_224, hmac_sha3_256, hmac_sha3_384, hmac_sha3_512, hmac_ripemd_160, hmac_blake2b_512, hmac_blake2s_256 +| not stated +| native, wasip2, wasip3 + +| hkdf over pieces +| botan (with exceptions only) +| hmac_md5_128, hmac_sha1_160, hmac_sha2_224, hmac_sha2_256, hmac_sha2_384, hmac_sha2_512, hmac_sha2_512_256, hmac_sha3_224, hmac_sha3_256, hmac_sha3_384, hmac_sha3_512, hmac_ripemd_160, hmac_blake2b_512, hmac_blake2s_256 +| not stated +| native, emscripten + +| hkdf over pieces +| webcrypto (asynchronous family only) | hmac_sha1_160, hmac_sha2_256, hmac_sha2_384, hmac_sha2_512 | not stated | emscripten @@ -1814,7 +1934,7 @@ states about its constant time. The backends: The functions that set DIT, on every synchronous backend of their cells: * MACs: `mac`, `mac`, `mac`, `mac`, `mac`, `mac`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>`, `mac>` and `mac>`. -* Key derivation: `hkdf_extract`, `hkdf_expand`, `hkdf`, `pbkdf2`, `blake2b_subkey`, `kbkdf`, `sskdf` and `x963kdf`. +* Key derivation: `hkdf_extract`, `hkdf_expand`, `hkdf`, `hkdf_extract` over pieces, `hkdf_expand` over pieces, `hkdf` over pieces, `pbkdf2`, `blake2b_subkey`, `kbkdf`, `sskdf` and `x963kdf`. * Password hashing: `argon2id`, `argon2`, `argon2`, `argon2`, `scrypt`, `bcrypt`, `bcrypt_verify` and `bcrypt_pbkdf`. * Keyed by their arguments: `digest_of` and `hasher` (`make`, `update`, `finish`) when the options carry a key; the `blake3` class in its keyed, key-derivation and seeded keyed modes (a non-empty byte seed, a non-zero integer seed: BLAKE3's keyed hash): `keyed`, `derive_key`, those constructors, and `update`, `result`, `squeeze` and `reset` of such an object. Called without a key, they hold a disengaged guard, which reads its flag and does nothing else. @@ -2049,6 +2169,15 @@ The backend a call that names none uses, on every target, whatever the program l | hkdf | hash2 +| hkdf_extract over pieces +| hash2 + +| hkdf_expand over pieces +| hash2 + +| hkdf over pieces +| hash2 + | pbkdf2 | hash2 @@ -2086,11 +2215,12 @@ What each backend's upstream states, and where: ** BearSSL upstream 7bea48e (v0.6-39), unchanged in webcpp's pin 32381d6: bearssl_hash.h states constant time for its GHASH implementations alone, not for br_md5_*, br_sha1_*, br_sha224_* to br_sha512_* or br_md5sha1_*. ** BearSSL upstream 7bea48e (v0.6-39), unchanged in webcpp's pin 32381d6: bearssl_kdf.h states no constant-time property for br_shake_*. ** BearSSL upstream 7bea48e (v0.6-39), unchanged in webcpp's pin 32381d6: bearssl_hmac.h states constant time for br_hmac_outCT alone; mac calls br_hmac_out. -** BearSSL upstream 7bea48e (v0.6-39), unchanged in webcpp's pin 32381d6: bearssl_hmac.h states constant time for br_hmac_outCT alone; br_hkdf_* (src/kdf/hkdf.c) calls br_hmac_out. +** BearSSL upstream 7bea48e (v0.6-39), unchanged in webcpp's pin 32381d6: bearssl_hmac.h states constant time for br_hmac_outCT alone; br_hkdf_* (src/kdf/hkdf.c) and HKDF over pieces call br_hmac_out. * openssl: not stated. ** OpenSSL 3.5.9: doc/man7/EVP_MD-*.pod, doc/man3/EVP_DigestInit.pod and providers/implementations/digests/ state no constant-time property. ** OpenSSL 3.5.9: doc/man3/EVP_MAC.pod, doc/man7/EVP_MAC-HMAC.pod, EVP_MAC-KMAC.pod, EVP_MAC-BLAKE2.pod, EVP_MAC-Siphash.pod and providers/implementations/macs/ state no constant-time property. ** OpenSSL 3.5.9: doc/man7/EVP_KDF-HKDF.pod and EVP_KDF-PBKDF2.pod state no constant-time property. +** OpenSSL 3.5.9: doc/man3/EVP_MAC.pod and doc/man7/EVP_MAC-HMAC.pod state no constant-time property; HKDF over pieces calls EVP_MAC "HMAC". ** OpenSSL 3.5.9: doc/man7/EVP_KDF-KB.pod states no constant-time property. ** OpenSSL 3.5.9: doc/man7/EVP_KDF-SS.pod states no constant-time property. ** OpenSSL 3.5.9: doc/man7/EVP_KDF-X963.pod states no constant-time property. @@ -2101,6 +2231,7 @@ What each backend's upstream states, and where: ** Botan 3.14.1: doc/api_ref/hash.rst states no constant-time property of SHAKE or of its XOF interface, and its source (src/lib/xof/shake_xof/) none. ** Botan 3.14.1: doc/api_ref/message_auth_codes.rst states no constant-time property of this MAC, and its source (src/lib/mac/) none. ** Botan 3.14.1: doc/api_ref/kdf.rst states no constant-time property of its KDFs, and their source (src/lib/kdf/) none. +** Botan 3.14.1: doc/api_ref/message_auth_codes.rst states no constant-time property of HMAC, and its source (src/lib/mac/hmac/) none; HKDF over pieces calls its HMAC. ** Botan 3.14.1: doc/api_ref/pbkdf.rst states no constant-time property of PBKDF2, and its source (src/lib/pbkdf/pbkdf2/) none. ** Botan 3.14.1: doc/api_ref/pbkdf.rst states that Argon2i's memory accesses are independent of the data and Argon2id's depend on it after the first half of the first pass, and states no constant-time property. * botan: no. diff --git a/doc/capabilities.json b/doc/capabilities.json index e9705b6..20e2674 100644 --- a/doc/capabilities.json +++ b/doc/capabilities.json @@ -1,13 +1,13 @@ { "about": "webcpp::hash's capability table (spec section 3.5): which library implements each public name, over which hmacs, on which targets, what upstream states about constant time, and the backend a call that names none uses. backend_has_v is the same table for the key derivations and the families: test/capabilities_test.cpp compares them cell by cell, checks each type row against the code, each default against default_backend and each refusal text against its row. The documentation renders from it. The default rule (design D34): a key derivation of increment 1 runs on hash2, argon2id and scrypt on sodium; a tag of the families defaults to the first of hash2, xkcp, blake3 and sodium that has it fully once increments 2 to 7 have landed, else the first of them with a partial cell, else none (null: the call names its backend); bearssl, openssl, botan and webcrypto are never a default. A default never changes, and every default has its cell.", - "version": 5, + "version": 6, "layout": { "schema": "This description. The version of the layout is \"version\"; a change of layout raises it.", "targets": "The targets webcpp builds for.", - "backends[]": "Each library a function runs on: name (as cells name it), tag (its webcpp::hash::backends type), macro (the word of WEBCPP_HASH_HAS_, null for a backend that links no library of its own), library (name and pin), licence, jamfile (the target a program names), targets (where it builds), asynchronous_only (present and true on a backend that only the asynchronous family of async.hpp takes, backends::webcrypto: its cells are the asynchronous functions', async_digest, async_hmac, async_hkdf and async_pbkdf2, never the synchronous ones, and it is never a default), exceptions_only (present and true on a backend that a build without exceptions cannot have, backends::botan: its header declares nothing under WEBCPP_HASH_NO_EXCEPTIONS), and optionally omitted[] ({names, reason}: what the library has and hash does not expose or does not load, each with its upstream names and why).", + "backends[]": "Each library a function runs on: name (as cells name it), tag (its webcpp::hash::backends type), macro (the word of WEBCPP_HASH_HAS_, null for a backend that links no library of its own), library (name and pin), licence, jamfile (the target a program names), targets (where it builds), asynchronous_only (present and true on a backend that only the asynchronous family of async.hpp takes, backends::webcrypto: its cells are the asynchronous functions', async_digest, async_hmac, async_hkdf_extract, async_hkdf_expand, async_hkdf (each HKDF function also over pieces) and async_pbkdf2, never the synchronous ones, and it is never a default), exceptions_only (present and true on a backend that a build without exceptions cannot have, backends::botan: its header declares nothing under WEBCPP_HASH_NO_EXCEPTIONS), and optionally omitted[] ({names, reason}: what the library has and hash does not expose or does not load, each with its upstream names and why).", "hmacs": "The hmac columns of a function over an hmac: the aliases of , and \"other\", hmac over any other Boost.Hash2 hash whose result is a digest.", "algorithms[]": "One row group of spec 3.5: name, macro (the algorithm's word in upper case), tag (its kdfs:: type, or null), chapter (the documentation's chapter: digests, macs, kdfs, password_hashing, non-cryptographic), standard, functions.", - "functions[]": "One public name: name (a type's or function's own name; a family's row is named by its qualified tag, as digests::sha2_256 or macs::hmac), kind (\"type\": a Boost.Hash2-form type; \"function\": a function template with a Backend parameter; \"digest\": a tag of digest_of and hasher; \"mac\": a tag of mac; \"kdf\": a variant of argon2), header, default (for a function or a family's tag, the backend default_backend names when the call names none, null for a tag with no default (detail::no_default) and for a type; every default has its cell), backends.", + "functions[]": "One public name: name (a type's or function's own name; a family's row is named by its qualified tag, as digests::sha2_256 or macs::hmac), form (present only on a row of another form of a function the table also has without it: \"pieces\", the overloads of hkdf_extract, hkdf_expand and hkdf whose input keying material and application info are byte_pieces, each with its own tag of kdfs; a row is keyed by its name and form, and the documentation names it \" over pieces\"), kind (\"type\": a Boost.Hash2-form type; \"function\": a function template with a Backend parameter; \"digest\": a tag of digest_of and hasher; \"mac\": a tag of mac; \"kdf\": a variant of argon2), header, default (for a function or a family's tag, the backend default_backend names when the call names none, null for a tag with no default (detail::no_default) and for a type; every default has its cell), backends.", "backends{}": "Per backend name, the cell: since (the increment it came with, 1 to 7), hmacs (the columns it has, or null for a function or type that takes no hmac), partial (only on a cell that refuses some values the family accepts: what it refuses, with unsupported_by_backend, or, for a backend's narrower limits in its backend_limits (backends::webcrypto's, backends::botan's PBKDF2 count on wasm32), with the error they name), constant_time {value: \"yes\", \"no\" or \"not stated\", source: where upstream says so, or what was read and says nothing}. A cell holds on every target of its backend." }, "targets": [ @@ -3381,6 +3381,19 @@ "value": "not stated", "source": "Botan 3.14.1: doc/api_ref/kdf.rst states no constant-time property of its KDFs, and their source (src/lib/kdf/) none." } + }, + "webcrypto": { + "since": 7, + "hmacs": [ + "hmac_sha1_160", + "hmac_sha2_256", + "hmac_sha2_384", + "hmac_sha2_512" + ], + "constant_time": { + "value": "not stated", + "source": "The Web Cryptography API (W3C Recommendation, 2017) states no constant-time property of digest, sign or deriveBits; each JavaScript runtime's implementation decides, and webcpp reads none." + } } } }, @@ -3474,6 +3487,19 @@ "value": "not stated", "source": "Botan 3.14.1: doc/api_ref/kdf.rst states no constant-time property of its KDFs, and their source (src/lib/kdf/) none." } + }, + "webcrypto": { + "since": 7, + "hmacs": [ + "hmac_sha1_160", + "hmac_sha2_256", + "hmac_sha2_384", + "hmac_sha2_512" + ], + "constant_time": { + "value": "not stated", + "source": "The Web Cryptography API (W3C Recommendation, 2017) states no constant-time property of digest, sign or deriveBits; each JavaScript runtime's implementation decides, and webcpp reads none." + } } } }, @@ -3533,7 +3559,7 @@ ], "constant_time": { "value": "not stated", - "source": "BearSSL upstream 7bea48e (v0.6-39), unchanged in webcpp's pin 32381d6: bearssl_hmac.h states constant time for br_hmac_outCT alone; br_hkdf_* (src/kdf/hkdf.c) calls br_hmac_out." + "source": "BearSSL upstream 7bea48e (v0.6-39), unchanged in webcpp's pin 32381d6: bearssl_hmac.h states constant time for br_hmac_outCT alone; br_hkdf_* (src/kdf/hkdf.c) and HKDF over pieces call br_hmac_out." } }, "openssl": { @@ -3591,7 +3617,373 @@ "hmac_sha2_384", "hmac_sha2_512" ], - "partial": "an info longer than 1,024 bytes, which completes with input_too_long: WebCrypto's limit as node has it, where the other backends take 32,768", + "partial": "an application_info longer than 1,024 bytes, which completes with input_too_long: WebCrypto's limit as node has it, where the other backends take 32,768", + "constant_time": { + "value": "not stated", + "source": "The Web Cryptography API (W3C Recommendation, 2017) states no constant-time property of digest, sign or deriveBits; each JavaScript runtime's implementation decides, and webcpp reads none." + } + } + } + }, + { + "name": "hkdf_extract", + "form": "pieces", + "kind": "function", + "tag": "kdfs::hkdf_extract_pieces", + "header": "webcpp/hash/hkdf.hpp", + "default": "hash2", + "backends": { + "hash2": { + "since": 7, + "hmacs": [ + "hmac_md5_128", + "hmac_sha1_160", + "hmac_sha2_224", + "hmac_sha2_256", + "hmac_sha2_384", + "hmac_sha2_512", + "hmac_sha2_512_224", + "hmac_sha2_512_256", + "hmac_sha3_224", + "hmac_sha3_256", + "hmac_sha3_384", + "hmac_sha3_512", + "hmac_ripemd_128", + "hmac_ripemd_160", + "hmac_blake2b_512", + "hmac_blake2s_256", + "other" + ], + "constant_time": { + "value": "not stated", + "source": "Boost.Hash2 1.92: its headers (boost/hash2/) state no constant-time property." + } + }, + "sodium": { + "since": 7, + "hmacs": [ + "hmac_sha2_256", + "hmac_sha2_512" + ], + "constant_time": { + "value": "not stated", + "source": "libsodium 1.0.22: its headers state constant time for comparisons (sodium/utils.h) alone, not for its hashing, MAC, key derivation and password hashing functions (crypto_hash_*, crypto_xof_*, crypto_generichash_*, crypto_shorthash_*, crypto_auth_*, crypto_kdf_*, crypto_pwhash_*)." + } + }, + "bearssl": { + "since": 7, + "hmacs": [ + "hmac_md5_128", + "hmac_sha1_160", + "hmac_sha2_224", + "hmac_sha2_256", + "hmac_sha2_384", + "hmac_sha2_512" + ], + "constant_time": { + "value": "not stated", + "source": "BearSSL upstream 7bea48e (v0.6-39), unchanged in webcpp's pin 32381d6: bearssl_hmac.h states constant time for br_hmac_outCT alone; br_hkdf_* (src/kdf/hkdf.c) and HKDF over pieces call br_hmac_out." + } + }, + "openssl": { + "since": 7, + "hmacs": [ + "hmac_md5_128", + "hmac_sha1_160", + "hmac_sha2_224", + "hmac_sha2_256", + "hmac_sha2_384", + "hmac_sha2_512", + "hmac_sha2_512_224", + "hmac_sha2_512_256", + "hmac_sha3_224", + "hmac_sha3_256", + "hmac_sha3_384", + "hmac_sha3_512", + "hmac_ripemd_160", + "hmac_blake2b_512", + "hmac_blake2s_256" + ], + "constant_time": { + "value": "not stated", + "source": "OpenSSL 3.5.9: doc/man3/EVP_MAC.pod and doc/man7/EVP_MAC-HMAC.pod state no constant-time property; HKDF over pieces calls EVP_MAC \"HMAC\"." + } + }, + "botan": { + "since": 7, + "hmacs": [ + "hmac_md5_128", + "hmac_sha1_160", + "hmac_sha2_224", + "hmac_sha2_256", + "hmac_sha2_384", + "hmac_sha2_512", + "hmac_sha2_512_256", + "hmac_sha3_224", + "hmac_sha3_256", + "hmac_sha3_384", + "hmac_sha3_512", + "hmac_ripemd_160", + "hmac_blake2b_512", + "hmac_blake2s_256" + ], + "constant_time": { + "value": "not stated", + "source": "Botan 3.14.1: doc/api_ref/message_auth_codes.rst states no constant-time property of HMAC, and its source (src/lib/mac/hmac/) none; HKDF over pieces calls its HMAC." + } + }, + "webcrypto": { + "since": 7, + "hmacs": [ + "hmac_sha1_160", + "hmac_sha2_256", + "hmac_sha2_384", + "hmac_sha2_512" + ], + "constant_time": { + "value": "not stated", + "source": "The Web Cryptography API (W3C Recommendation, 2017) states no constant-time property of digest, sign or deriveBits; each JavaScript runtime's implementation decides, and webcpp reads none." + } + } + } + }, + { + "name": "hkdf_expand", + "form": "pieces", + "kind": "function", + "tag": "kdfs::hkdf_expand_pieces", + "header": "webcpp/hash/hkdf.hpp", + "default": "hash2", + "backends": { + "hash2": { + "since": 7, + "hmacs": [ + "hmac_md5_128", + "hmac_sha1_160", + "hmac_sha2_224", + "hmac_sha2_256", + "hmac_sha2_384", + "hmac_sha2_512", + "hmac_sha2_512_224", + "hmac_sha2_512_256", + "hmac_sha3_224", + "hmac_sha3_256", + "hmac_sha3_384", + "hmac_sha3_512", + "hmac_ripemd_128", + "hmac_ripemd_160", + "hmac_blake2b_512", + "hmac_blake2s_256", + "other" + ], + "constant_time": { + "value": "not stated", + "source": "Boost.Hash2 1.92: its headers (boost/hash2/) state no constant-time property." + } + }, + "sodium": { + "since": 7, + "hmacs": [ + "hmac_sha2_256", + "hmac_sha2_512" + ], + "constant_time": { + "value": "not stated", + "source": "libsodium 1.0.22: its headers state constant time for comparisons (sodium/utils.h) alone, not for its hashing, MAC, key derivation and password hashing functions (crypto_hash_*, crypto_xof_*, crypto_generichash_*, crypto_shorthash_*, crypto_auth_*, crypto_kdf_*, crypto_pwhash_*)." + } + }, + "bearssl": { + "since": 7, + "hmacs": [ + "hmac_md5_128", + "hmac_sha1_160", + "hmac_sha2_224", + "hmac_sha2_256", + "hmac_sha2_384", + "hmac_sha2_512" + ], + "constant_time": { + "value": "not stated", + "source": "BearSSL upstream 7bea48e (v0.6-39), unchanged in webcpp's pin 32381d6: bearssl_hmac.h states constant time for br_hmac_outCT alone; br_hkdf_* (src/kdf/hkdf.c) and HKDF over pieces call br_hmac_out." + } + }, + "openssl": { + "since": 7, + "hmacs": [ + "hmac_md5_128", + "hmac_sha1_160", + "hmac_sha2_224", + "hmac_sha2_256", + "hmac_sha2_384", + "hmac_sha2_512", + "hmac_sha2_512_224", + "hmac_sha2_512_256", + "hmac_sha3_224", + "hmac_sha3_256", + "hmac_sha3_384", + "hmac_sha3_512", + "hmac_ripemd_160", + "hmac_blake2b_512", + "hmac_blake2s_256" + ], + "constant_time": { + "value": "not stated", + "source": "OpenSSL 3.5.9: doc/man3/EVP_MAC.pod and doc/man7/EVP_MAC-HMAC.pod state no constant-time property; HKDF over pieces calls EVP_MAC \"HMAC\"." + } + }, + "botan": { + "since": 7, + "hmacs": [ + "hmac_md5_128", + "hmac_sha1_160", + "hmac_sha2_224", + "hmac_sha2_256", + "hmac_sha2_384", + "hmac_sha2_512", + "hmac_sha2_512_256", + "hmac_sha3_224", + "hmac_sha3_256", + "hmac_sha3_384", + "hmac_sha3_512", + "hmac_ripemd_160", + "hmac_blake2b_512", + "hmac_blake2s_256" + ], + "constant_time": { + "value": "not stated", + "source": "Botan 3.14.1: doc/api_ref/message_auth_codes.rst states no constant-time property of HMAC, and its source (src/lib/mac/hmac/) none; HKDF over pieces calls its HMAC." + } + }, + "webcrypto": { + "since": 7, + "hmacs": [ + "hmac_sha1_160", + "hmac_sha2_256", + "hmac_sha2_384", + "hmac_sha2_512" + ], + "constant_time": { + "value": "not stated", + "source": "The Web Cryptography API (W3C Recommendation, 2017) states no constant-time property of digest, sign or deriveBits; each JavaScript runtime's implementation decides, and webcpp reads none." + } + } + } + }, + { + "name": "hkdf", + "form": "pieces", + "kind": "function", + "tag": "kdfs::hkdf_pieces", + "header": "webcpp/hash/hkdf.hpp", + "default": "hash2", + "backends": { + "hash2": { + "since": 7, + "hmacs": [ + "hmac_md5_128", + "hmac_sha1_160", + "hmac_sha2_224", + "hmac_sha2_256", + "hmac_sha2_384", + "hmac_sha2_512", + "hmac_sha2_512_224", + "hmac_sha2_512_256", + "hmac_sha3_224", + "hmac_sha3_256", + "hmac_sha3_384", + "hmac_sha3_512", + "hmac_ripemd_128", + "hmac_ripemd_160", + "hmac_blake2b_512", + "hmac_blake2s_256", + "other" + ], + "constant_time": { + "value": "not stated", + "source": "Boost.Hash2 1.92: its headers (boost/hash2/) state no constant-time property." + } + }, + "sodium": { + "since": 7, + "hmacs": [ + "hmac_sha2_256", + "hmac_sha2_512" + ], + "constant_time": { + "value": "not stated", + "source": "libsodium 1.0.22: its headers state constant time for comparisons (sodium/utils.h) alone, not for its hashing, MAC, key derivation and password hashing functions (crypto_hash_*, crypto_xof_*, crypto_generichash_*, crypto_shorthash_*, crypto_auth_*, crypto_kdf_*, crypto_pwhash_*)." + } + }, + "bearssl": { + "since": 7, + "hmacs": [ + "hmac_md5_128", + "hmac_sha1_160", + "hmac_sha2_224", + "hmac_sha2_256", + "hmac_sha2_384", + "hmac_sha2_512" + ], + "constant_time": { + "value": "not stated", + "source": "BearSSL upstream 7bea48e (v0.6-39), unchanged in webcpp's pin 32381d6: bearssl_hmac.h states constant time for br_hmac_outCT alone; br_hkdf_* (src/kdf/hkdf.c) and HKDF over pieces call br_hmac_out." + } + }, + "openssl": { + "since": 7, + "hmacs": [ + "hmac_md5_128", + "hmac_sha1_160", + "hmac_sha2_224", + "hmac_sha2_256", + "hmac_sha2_384", + "hmac_sha2_512", + "hmac_sha2_512_224", + "hmac_sha2_512_256", + "hmac_sha3_224", + "hmac_sha3_256", + "hmac_sha3_384", + "hmac_sha3_512", + "hmac_ripemd_160", + "hmac_blake2b_512", + "hmac_blake2s_256" + ], + "constant_time": { + "value": "not stated", + "source": "OpenSSL 3.5.9: doc/man3/EVP_MAC.pod and doc/man7/EVP_MAC-HMAC.pod state no constant-time property; HKDF over pieces calls EVP_MAC \"HMAC\"." + } + }, + "botan": { + "since": 7, + "hmacs": [ + "hmac_md5_128", + "hmac_sha1_160", + "hmac_sha2_224", + "hmac_sha2_256", + "hmac_sha2_384", + "hmac_sha2_512", + "hmac_sha2_512_256", + "hmac_sha3_224", + "hmac_sha3_256", + "hmac_sha3_384", + "hmac_sha3_512", + "hmac_ripemd_160", + "hmac_blake2b_512", + "hmac_blake2s_256" + ], + "constant_time": { + "value": "not stated", + "source": "Botan 3.14.1: doc/api_ref/message_auth_codes.rst states no constant-time property of HMAC, and its source (src/lib/mac/hmac/) none; HKDF over pieces calls its HMAC." + } + }, + "webcrypto": { + "since": 7, + "hmacs": [ + "hmac_sha1_160", + "hmac_sha2_256", + "hmac_sha2_384", + "hmac_sha2_512" + ], "constant_time": { "value": "not stated", "source": "The Web Cryptography API (W3C Recommendation, 2017) states no constant-time property of digest, sign or deriveBits; each JavaScript runtime's implementation decides, and webcpp reads none." diff --git a/doc/changelog.adoc b/doc/changelog.adoc index e1330aa..fa1b14f 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -16,14 +16,14 @@ of every version are on webcpp's index page. === Unreleased // tag::unreleased[] +* *Breaking change:* Changed the public names: hkdf's input_key_material, pseudorandom_key, application_info, output_key_material and salt, hkdf_max_application_info_size, scrypt_parameters' cost, block_size and parallelism (from n, r, p) and argon2_parameters::memory_kibibytes. +* *Breaking change:* Changed HKDF's overloads: `+hkdf(out, {}, {}, {})+`, `+async_hkdf(ex, out, salt, {}, {}, token)+` and `+{vec}+` inputs are ambiguous; pass the vector itself, an empty span or `+byte_pieces{...}+`. * Added the library: Boost.Hash2's algorithms and HMAC under webcpp::hash's names, keccak_256 (Ethereum's Keccak-256 over XKCP), blake3 (keyed, key derivation, extendable output), every result `+[[nodiscard]]+`. * Added HKDF (RFC 5869) and PBKDF2 (RFC 8018) on hash2, argon2id (RFC 9106), scrypt and argon2's Argon2i and Argon2id on sodium; keyed calls set DIT on arm64 Apple and Linux. -* Added backends::openssl (OpenSSL 3.5.9; native, wasip2, wasip3), named in the call: its digests, MACs and key derivations. -* Added backends::botan: Botan 3.14.1's hashes, MACs, key derivations and bcrypt, with exceptions. -* Added backends::sodium's HKDF over HMAC-SHA-256/512, BLAKE2b with key, salt, personalisation and length, keyed BLAKE2b (macs::blake2b_mac), SipHash-2-4, SipHash-2-4x, blake2b_subkey, SHA-256/512, SHA3-256/512, SHAKE, TurboSHAKE with its domain byte, and HMAC-SHA-256/512. -* Added backends::bearssl's HKDF over MD5, SHA-1 and SHA-2 (hkdf alone), and its MD5, SHA-1, SHA-2, MD5-SHA1, SHAKE and HMAC as digests and MACs, named in the call. -* Added the default backend of every function and tag, the first of hash2, xkcp, blake3 and sodium that has it, and doc/capabilities.json naming each default and backends::webcrypto's asynchronous-only cells. -* Added async.hpp, async_digest, async_hmac, async_hkdf, async_pbkdf2, async_argon2id, async_argon2 and async_scrypt over webcpp::asio, and backends::webcrypto, the browser's WebCrypto, for them on Emscripten. -* Added the guide (chapters per family and use case, generated tables, llms.txt), measured tables from release builds that decide nothing, allocation tests, and a keccak_224-512 proposal to Boost.Hash2. +* Added HKDF over byte pieces (hkdf_extract, hkdf_expand, hkdf and their async forms), with no cap; on the synchronous backends hash makes no buffer, heap or copy of the inputs. +* Added backends::openssl (OpenSSL 3.5.9; native, wasip2, wasip3) and backends::botan (Botan 3.14.1, with exceptions), named in the call: their digests, MACs, key derivations and, on Botan, bcrypt. +* Added backends::sodium (HKDF, BLAKE2b with its options, keyed BLAKE2b, SipHash, blake2b_subkey, SHA-2, SHA-3, SHAKE, TurboSHAKE, HMAC) and backends::bearssl (HKDF, MD5, SHA-1, SHA-2, MD5-SHA1, SHAKE, HMAC). +* Added async.hpp, async_digest, async_hmac, async_hkdf_extract, async_hkdf_expand, async_hkdf, async_pbkdf2, async_argon2id, async_argon2 and async_scrypt over webcpp::asio, and backends::webcrypto, the browser's WebCrypto, for them on Emscripten. +* Added each function's default backend, the first of hash2, xkcp, blake3 and sodium that has it; the guide, doc/capabilities.json, measurements, allocation tests and a keccak_224-512 proposal to Boost.Hash2. * Added the families digest_of, hasher, mac and argon2 over digests, macs and kdfs tags on hash2, xkcp (Keccak, SHA-3, SHAKE, SP 800-185, KangarooTwelve, TurboSHAKE), blake3 and sodium, and error::invalid_state. // end::unreleased[] diff --git a/doc/generated/backends-hkdf.adoc b/doc/generated/backends-hkdf.adoc index 71649b3..960fe97 100644 --- a/doc/generated/backends-hkdf.adoc +++ b/doc/generated/backends-hkdf.adoc @@ -41,6 +41,13 @@ | `hmac_md5_128`, `hmac_sha1_160`, `hmac_sha2_224`, `hmac_sha2_256`, `hmac_sha2_384`, `hmac_sha2_512`, `hmac_sha2_512_256`, `hmac_sha3_224`, `hmac_sha3_256`, `hmac_sha3_384`, `hmac_sha3_512`, `hmac_ripemd_160`, `hmac_blake2b_512`, `hmac_blake2s_256` | not stated +| `hkdf_extract` +| `webcrypto` (asynchronous family only) +| `/webcpp/asio//asio` +| emscripten +| `hmac_sha1_160`, `hmac_sha2_256`, `hmac_sha2_384`, `hmac_sha2_512` +| not stated + | `hkdf_expand` | `hash2` | `/webcpp/hash//hash` @@ -69,6 +76,13 @@ | `hmac_md5_128`, `hmac_sha1_160`, `hmac_sha2_224`, `hmac_sha2_256`, `hmac_sha2_384`, `hmac_sha2_512`, `hmac_sha2_512_256`, `hmac_sha3_224`, `hmac_sha3_256`, `hmac_sha3_384`, `hmac_sha3_512`, `hmac_ripemd_160`, `hmac_blake2b_512`, `hmac_blake2s_256` | not stated +| `hkdf_expand` +| `webcrypto` (asynchronous family only) +| `/webcpp/asio//asio` +| emscripten +| `hmac_sha1_160`, `hmac_sha2_256`, `hmac_sha2_384`, `hmac_sha2_512` +| not stated + | `hkdf` | `hash2` | `/webcpp/hash//hash` @@ -105,7 +119,133 @@ | not stated | `hkdf` -| `webcrypto` (asynchronous family only) (partial: an info longer than 1,024 bytes, which completes with input_too_long: WebCrypto's limit as node has it, where the other backends take 32,768) +| `webcrypto` (asynchronous family only) (partial: an application_info longer than 1,024 bytes, which completes with input_too_long: WebCrypto's limit as node has it, where the other backends take 32,768) +| `/webcpp/asio//asio` +| emscripten +| `hmac_sha1_160`, `hmac_sha2_256`, `hmac_sha2_384`, `hmac_sha2_512` +| not stated + +| `hkdf_extract` over pieces +| `hash2` +| `/webcpp/hash//hash` +| native, wasip2, wasip3, emscripten +| `hmac_md5_128`, `hmac_sha1_160`, `hmac_sha2_224`, `hmac_sha2_256`, `hmac_sha2_384`, `hmac_sha2_512`, `hmac_sha2_512_224`, `hmac_sha2_512_256`, `hmac_sha3_224`, `hmac_sha3_256`, `hmac_sha3_384`, `hmac_sha3_512`, `hmac_ripemd_128`, `hmac_ripemd_160`, `hmac_blake2b_512`, `hmac_blake2s_256`, any other Hash2 hash (`hmac`) +| not stated + +| `hkdf_extract` over pieces +| `sodium` +| `/third_party//sodium` +| native, wasip2, wasip3, emscripten +| `hmac_sha2_256`, `hmac_sha2_512` +| not stated + +| `hkdf_extract` over pieces +| `bearssl` +| `/third_party//bearssl` +| native, wasip2, wasip3, emscripten +| `hmac_md5_128`, `hmac_sha1_160`, `hmac_sha2_224`, `hmac_sha2_256`, `hmac_sha2_384`, `hmac_sha2_512` +| not stated + +| `hkdf_extract` over pieces +| `openssl` +| `/webcpp/hash//openssl` +| native, wasip2, wasip3 +| `hmac_md5_128`, `hmac_sha1_160`, `hmac_sha2_224`, `hmac_sha2_256`, `hmac_sha2_384`, `hmac_sha2_512`, `hmac_sha2_512_224`, `hmac_sha2_512_256`, `hmac_sha3_224`, `hmac_sha3_256`, `hmac_sha3_384`, `hmac_sha3_512`, `hmac_ripemd_160`, `hmac_blake2b_512`, `hmac_blake2s_256` +| not stated + +| `hkdf_extract` over pieces +| `botan` (with exceptions only) +| `/third_party//botan` +| native, emscripten +| `hmac_md5_128`, `hmac_sha1_160`, `hmac_sha2_224`, `hmac_sha2_256`, `hmac_sha2_384`, `hmac_sha2_512`, `hmac_sha2_512_256`, `hmac_sha3_224`, `hmac_sha3_256`, `hmac_sha3_384`, `hmac_sha3_512`, `hmac_ripemd_160`, `hmac_blake2b_512`, `hmac_blake2s_256` +| not stated + +| `hkdf_extract` over pieces +| `webcrypto` (asynchronous family only) +| `/webcpp/asio//asio` +| emscripten +| `hmac_sha1_160`, `hmac_sha2_256`, `hmac_sha2_384`, `hmac_sha2_512` +| not stated + +| `hkdf_expand` over pieces +| `hash2` +| `/webcpp/hash//hash` +| native, wasip2, wasip3, emscripten +| `hmac_md5_128`, `hmac_sha1_160`, `hmac_sha2_224`, `hmac_sha2_256`, `hmac_sha2_384`, `hmac_sha2_512`, `hmac_sha2_512_224`, `hmac_sha2_512_256`, `hmac_sha3_224`, `hmac_sha3_256`, `hmac_sha3_384`, `hmac_sha3_512`, `hmac_ripemd_128`, `hmac_ripemd_160`, `hmac_blake2b_512`, `hmac_blake2s_256`, any other Hash2 hash (`hmac`) +| not stated + +| `hkdf_expand` over pieces +| `sodium` +| `/third_party//sodium` +| native, wasip2, wasip3, emscripten +| `hmac_sha2_256`, `hmac_sha2_512` +| not stated + +| `hkdf_expand` over pieces +| `bearssl` +| `/third_party//bearssl` +| native, wasip2, wasip3, emscripten +| `hmac_md5_128`, `hmac_sha1_160`, `hmac_sha2_224`, `hmac_sha2_256`, `hmac_sha2_384`, `hmac_sha2_512` +| not stated + +| `hkdf_expand` over pieces +| `openssl` +| `/webcpp/hash//openssl` +| native, wasip2, wasip3 +| `hmac_md5_128`, `hmac_sha1_160`, `hmac_sha2_224`, `hmac_sha2_256`, `hmac_sha2_384`, `hmac_sha2_512`, `hmac_sha2_512_224`, `hmac_sha2_512_256`, `hmac_sha3_224`, `hmac_sha3_256`, `hmac_sha3_384`, `hmac_sha3_512`, `hmac_ripemd_160`, `hmac_blake2b_512`, `hmac_blake2s_256` +| not stated + +| `hkdf_expand` over pieces +| `botan` (with exceptions only) +| `/third_party//botan` +| native, emscripten +| `hmac_md5_128`, `hmac_sha1_160`, `hmac_sha2_224`, `hmac_sha2_256`, `hmac_sha2_384`, `hmac_sha2_512`, `hmac_sha2_512_256`, `hmac_sha3_224`, `hmac_sha3_256`, `hmac_sha3_384`, `hmac_sha3_512`, `hmac_ripemd_160`, `hmac_blake2b_512`, `hmac_blake2s_256` +| not stated + +| `hkdf_expand` over pieces +| `webcrypto` (asynchronous family only) +| `/webcpp/asio//asio` +| emscripten +| `hmac_sha1_160`, `hmac_sha2_256`, `hmac_sha2_384`, `hmac_sha2_512` +| not stated + +| `hkdf` over pieces +| `hash2` +| `/webcpp/hash//hash` +| native, wasip2, wasip3, emscripten +| `hmac_md5_128`, `hmac_sha1_160`, `hmac_sha2_224`, `hmac_sha2_256`, `hmac_sha2_384`, `hmac_sha2_512`, `hmac_sha2_512_224`, `hmac_sha2_512_256`, `hmac_sha3_224`, `hmac_sha3_256`, `hmac_sha3_384`, `hmac_sha3_512`, `hmac_ripemd_128`, `hmac_ripemd_160`, `hmac_blake2b_512`, `hmac_blake2s_256`, any other Hash2 hash (`hmac`) +| not stated + +| `hkdf` over pieces +| `sodium` +| `/third_party//sodium` +| native, wasip2, wasip3, emscripten +| `hmac_sha2_256`, `hmac_sha2_512` +| not stated + +| `hkdf` over pieces +| `bearssl` +| `/third_party//bearssl` +| native, wasip2, wasip3, emscripten +| `hmac_md5_128`, `hmac_sha1_160`, `hmac_sha2_224`, `hmac_sha2_256`, `hmac_sha2_384`, `hmac_sha2_512` +| not stated + +| `hkdf` over pieces +| `openssl` +| `/webcpp/hash//openssl` +| native, wasip2, wasip3 +| `hmac_md5_128`, `hmac_sha1_160`, `hmac_sha2_224`, `hmac_sha2_256`, `hmac_sha2_384`, `hmac_sha2_512`, `hmac_sha2_512_224`, `hmac_sha2_512_256`, `hmac_sha3_224`, `hmac_sha3_256`, `hmac_sha3_384`, `hmac_sha3_512`, `hmac_ripemd_160`, `hmac_blake2b_512`, `hmac_blake2s_256` +| not stated + +| `hkdf` over pieces +| `botan` (with exceptions only) +| `/third_party//botan` +| native, emscripten +| `hmac_md5_128`, `hmac_sha1_160`, `hmac_sha2_224`, `hmac_sha2_256`, `hmac_sha2_384`, `hmac_sha2_512`, `hmac_sha2_512_256`, `hmac_sha3_224`, `hmac_sha3_256`, `hmac_sha3_384`, `hmac_sha3_512`, `hmac_ripemd_160`, `hmac_blake2b_512`, `hmac_blake2s_256` +| not stated + +| `hkdf` over pieces +| `webcrypto` (asynchronous family only) | `/webcpp/asio//asio` | emscripten | `hmac_sha1_160`, `hmac_sha2_256`, `hmac_sha2_384`, `hmac_sha2_512` @@ -114,15 +254,19 @@ What each backend states on constant time, as the capability table read it: -* `bearssl`: BearSSL upstream 7bea48e (v0.6-39), unchanged in webcpp's pin 32381d6: bearssl_hmac.h states constant time for br_hmac_outCT alone; br_hkdf_* (src/kdf/hkdf.c) calls br_hmac_out. -* `botan`: Botan 3.14.1: doc/api_ref/kdf.rst states no constant-time property of its KDFs, and their source (src/lib/kdf/) none. +* `bearssl`: BearSSL upstream 7bea48e (v0.6-39), unchanged in webcpp's pin 32381d6: bearssl_hmac.h states constant time for br_hmac_outCT alone; br_hkdf_* (src/kdf/hkdf.c) and HKDF over pieces call br_hmac_out. +* `botan`: +** Botan 3.14.1: doc/api_ref/kdf.rst states no constant-time property of its KDFs, and their source (src/lib/kdf/) none. +** Botan 3.14.1: doc/api_ref/message_auth_codes.rst states no constant-time property of HMAC, and its source (src/lib/mac/hmac/) none; HKDF over pieces calls its HMAC. * `hash2`: Boost.Hash2 1.92: its headers (boost/hash2/) state no constant-time property. -* `openssl`: OpenSSL 3.5.9: doc/man7/EVP_KDF-HKDF.pod and EVP_KDF-PBKDF2.pod state no constant-time property. +* `openssl`: +** OpenSSL 3.5.9: doc/man3/EVP_MAC.pod and doc/man7/EVP_MAC-HMAC.pod state no constant-time property; HKDF over pieces calls EVP_MAC "HMAC". +** OpenSSL 3.5.9: doc/man7/EVP_KDF-HKDF.pod and EVP_KDF-PBKDF2.pod state no constant-time property. * `sodium`: libsodium 1.0.22: its headers state constant time for comparisons (sodium/utils.h) alone, not for its hashing, MAC, key derivation and password hashing functions (crypto_hash_*, crypto_xof_*, crypto_generichash_*, crypto_shorthash_*, crypto_auth_*, crypto_kdf_*, crypto_pwhash_*). * `webcrypto`: The Web Cryptography API (W3C Recommendation, 2017) states no constant-time property of digest, sign or deriveBits; each JavaScript runtime's implementation decides, and webcpp reads none. The default of `hkdf_extract` and `hkdf_expand`: `hash2` on every target, whatever the program links; `botan`, `openssl`, `sodium` only where the call names it, as its second template argument (<>). -The default of `hkdf`: `hash2` on every target, whatever the program links; `bearssl`, `botan`, `openssl`, `sodium` only where the call names it, as its second template argument (<>). +The default of `hkdf`, `hkdf_extract` over pieces, `hkdf_expand` over pieces and `hkdf` over pieces: `hash2` on every target, whatever the program links; `bearssl`, `botan`, `openssl`, `sodium` only where the call names it, as its second template argument (<>). `webcrypto` serves the asynchronous family alone, on Emscripten, where the type of its asynchronous call names it (<>). diff --git a/doc/generated/choose.adoc b/doc/generated/choose.adoc index a01b0a9..b85bc19 100644 --- a/doc/generated/choose.adoc +++ b/doc/generated/choose.adoc @@ -49,7 +49,7 @@ | `example/bcrypt.cpp` | turn a shared secret (an ECDH result) into keys -| <> +| <> | `hash2`: `/webcpp/hash//hash`, `sodium`: `/third_party//sodium`, `bearssl`: `/third_party//bearssl`, `openssl`: `/webcpp/hash//openssl`, `botan` (with exceptions only): `/third_party//botan`, `webcrypto` (asynchronous family only): `/webcpp/asio//asio` | the default; name a backend only to match another program's | `example/hkdf.cpp` @@ -73,8 +73,8 @@ | `example/kbkdf.cpp` | derive many keys from one master key, one per purpose -| <> -| `hash2`: `/webcpp/hash//hash`, `sodium`: `/third_party//sodium`, `openssl`: `/webcpp/hash//openssl`, `botan` (with exceptions only): `/third_party//botan` +| <> +| `hash2`: `/webcpp/hash//hash`, `sodium`: `/third_party//sodium`, `openssl`: `/webcpp/hash//openssl`, `botan` (with exceptions only): `/third_party//botan`, `webcrypto` (asynchronous family only): `/webcpp/asio//asio` | the default | `example/subkeys.cpp` @@ -116,7 +116,7 @@ | derive NIP-44's conversation key | <> -| `hash2`: `/webcpp/hash//hash`, `sodium`: `/third_party//sodium`, `openssl`: `/webcpp/hash//openssl`, `botan` (with exceptions only): `/third_party//botan` +| `hash2`: `/webcpp/hash//hash`, `sodium`: `/third_party//sodium`, `openssl`: `/webcpp/hash//openssl`, `botan` (with exceptions only): `/third_party//botan`, `webcrypto` (asynchronous family only): `/webcpp/asio//asio` | the default | `example/nip44_conversation_key.cpp` diff --git a/doc/generated/compare-kdfs.adoc b/doc/generated/compare-kdfs.adoc index 7d2fa00..b8b391c 100644 --- a/doc/generated/compare-kdfs.adoc +++ b/doc/generated/compare-kdfs.adoc @@ -86,7 +86,7 @@ | 489 ns (sodium) | 24,778 bytes (sodium) | link:https://www.rfc-editor.org/rfc/rfc8446#section-7.1[TLS 1.3's key schedule]; link:https://signal.org/docs/specifications/doubleratchet/[Signal's Double Ratchet] -| Keys from a key that is already uniform (a master key), one per info label. +| Keys from a key that is already uniform (a master key), one per application info label. | <> | 980 ns (sodium) diff --git a/doc/guide.json b/doc/guide.json index 83ef802..5685ab0 100644 --- a/doc/guide.json +++ b/doc/guide.json @@ -666,10 +666,10 @@ {"text": "TLS 1.3's key schedule", "source": "https://www.rfc-editor.org/rfc/rfc8446#section-7.1"}, {"text": "Signal's Double Ratchet", "source": "https://signal.org/docs/specifications/doubleratchet/"} ], - "choose": "Keys from a key that is already uniform (a master key), one per info label." + "choose": "Keys from a key that is already uniform (a master key), one per application info label." }, "hkdf": { - "summary": "HKDF, extract then expand: keys from a shared secret, each separated by its info label.", + "summary": "HKDF, extract then expand: keys from a shared secret, each separated by its application info label.", "output": "1 to 255 times the digest size", "security": "that of the hmac, given input with enough entropy", "status": "recommended", @@ -1706,11 +1706,11 @@ {"need": "store users' passwords for a login", "use": "argon2id with argon2id_interactive or stronger, a random 16-byte salt per user", "function": "argon2id", "backend": "link /third_party//sodium", "example": "password_storage.cpp", "anchor": "hash-privacy-passwords"}, {"need": "turn a password into an encryption key (a password manager, an encrypted backup)", "use": "argon2id with argon2id_moderate or argon2id_sensitive, then hkdf for each purpose", "function": "argon2id", "backend": "link /third_party//sodium", "example": "argon2id.cpp", "anchor": "hash-argon2id"}, {"need": "check or make the bcrypt strings a system already stores, or read and write OpenSSH's encrypted private keys", "use": "bcrypt and bcrypt_verify at a cost of 10 or more (bcrypt_pbkdf for OpenSSH's keys); argon2id for a new design", "function": "bcrypt", "backend": "name backends::botan and link /third_party//botan, with exceptions", "example": "bcrypt.cpp", "anchor": "hash-bcrypt"}, - {"need": "turn a shared secret (an ECDH result) into keys", "use": "hkdf over hmac_sha2_256, one info label per key", "function": "hkdf", "backend": "the default; name a backend only to match another program's", "example": "hkdf.cpp", "anchor": "hash-hkdf"}, + {"need": "turn a shared secret (an ECDH result) into keys", "use": "hkdf over hmac_sha2_256, one application info label per key", "function": "hkdf", "backend": "the default; name a backend only to match another program's", "example": "hkdf.cpp", "anchor": "hash-hkdf"}, {"need": "derive the key JOSE's ECDH-ES (a JWE) or another NIST SP 800-56C protocol derives from a shared secret", "use": "sskdf over digests::sha2_256, the fixed info as the protocol writes it", "function": "sskdf", "backend": "name backends::openssl (or backends::botan) and link its library, /webcpp/hash//openssl (or /third_party//botan)", "example": "sskdf.cpp", "anchor": "hash-sskdf"}, {"need": "derive the keys of ECIES or of a smart card's key agreement (ANSI X9.63)", "use": "x963kdf over digests::sha2_256, the shared info as the scheme writes it", "function": "x963kdf", "backend": "name backends::openssl (or backends::botan) and link its library, /webcpp/hash//openssl (or /third_party//botan)", "example": "x963kdf.cpp", "anchor": "hash-x963kdf"}, {"need": "derive keys from a key as NIST SP 800-108 or Kerberos does (a label and a context)", "use": "kbkdf over hmac_sha2_256 with the label and the context", "function": "kbkdf", "backend": "name backends::openssl (or backends::botan) and link its library, /webcpp/hash//openssl (or /third_party//botan)", "example": "kbkdf.cpp", "anchor": "hash-kbkdf"}, - {"need": "derive many keys from one master key, one per purpose", "use": "hkdf_expand (or hkdf) with distinct info labels, blake2b_subkey (libsodium's crypto_kdf) by id, or blake3::derive_key with a context string", "function": "hkdf_expand", "backend": "the default", "example": "subkeys.cpp", "anchor": "hash-privacy-subkeys"}, + {"need": "derive many keys from one master key, one per purpose", "use": "hkdf_expand (or hkdf) with distinct application info labels, blake2b_subkey (libsodium's crypto_kdf) by id, or blake3::derive_key with a context string", "function": "hkdf_expand", "backend": "the default", "example": "subkeys.cpp", "anchor": "hash-privacy-subkeys"}, {"need": "build a hash table, set or Bloom filter whose keys come from the network", "use": "siphash_64 keyed with 16 random bytes per process", "function": "siphash_64", "backend": "none: one backend", "example": "siphash.cpp", "anchor": "hash-siphash"}, {"need": "build a hash table of my own trusted keys, or a fast checksum", "use": "xxh3_128 or fnv1a_64", "function": "xxh3_128", "backend": "none: one backend", "example": "checksums.cpp", "anchor": "hash-non-cryptographic-functions"}, {"need": "compute a Bitcoin wallet's BIP39 seed from its words", "use": "pbkdf2 over hmac_sha2_512, 2,048 iterations (a domain library's step)", "function": "pbkdf2", "backend": "the default", "example": "bip39_seed.cpp", "anchor": "hash-crypto-bip39"}, diff --git a/doc/jamfile.adoc b/doc/jamfile.adoc index 2b5a005..20c40e9 100644 --- a/doc/jamfile.adoc +++ b/doc/jamfile.adoc @@ -266,8 +266,8 @@ started zeroes the output, so that half a key is never used. |2 |`invalid_key_size` |A key is not of a size the function takes: the pseudorandom key given to `hkdf_expand` is not of the hmac's digest size; a MAC's key is outside the MAC's sizes (SipHash: 16 bytes; keyed BLAKE2b: 1 to 64 bytes; keyed BLAKE2s: 1 to 32 bytes; KMAC: at most `SIZE_MAX / 8` bytes); the key option of the BLAKE2b digest is longer than 64 bytes; the master key of `blake2b_subkey` is not of 32 bytes; the secret or key of `kbkdf`, `sskdf` or `x963kdf` is empty. |3 |`invalid_salt_size` |The salt is not of a size the function accepts (Argon2id: 16 bytes). |4 |`invalid_iterations` |PBKDF2's iteration count is zero, or more than the backend takes (`backend_limits::pbkdf2_iterations`: 2^32 - 1 on `backends::webcrypto`). -|5 |`invalid_parameters` |A parameter is outside the function's limits: a cost (Argon2id's passes or memory, Argon2's passes, lanes or memory, scrypt's N, r and p); an option (BLAKE2b's personalisation not of 16 bytes, TurboSHAKE's domain byte outside 0x01 to 0x7F, ParallelHash's block size of zero, the counter width of `kbkdf` other than 8, 16, 24 or 32 bits); the context of `blake2b_subkey` not of 8 bytes; an executor that `backends::webcrypto` cannot complete on. -|6 |`input_too_long` |An input is longer than the function or the backend accepts (HKDF's info past 32,768 bytes; OpenSSL's `int` lengths). +|5 |`invalid_parameters` |A parameter is outside the function's limits: a cost (Argon2id's passes or memory, Argon2's passes, lanes or memory, scrypt's cost, block_size and parallelism); an option (BLAKE2b's personalisation not of 16 bytes, TurboSHAKE's domain byte outside 0x01 to 0x7F, ParallelHash's block size of zero, the counter width of `kbkdf` other than 8, 16, 24 or 32 bits); the context of `blake2b_subkey` not of 8 bytes; an executor that `backends::webcrypto` cannot complete on. +|6 |`input_too_long` |An input is longer than the function or the backend accepts (HKDF: a single buffer's application info past 32,768 bytes, where the forms over pieces have no cap; OpenSSL's `int` lengths). |7 |`backend_failure` |A backend failed where its contract says it does not. |8 |`unsupported_by_backend` |A parameter the chosen backend does not take. |9 |`invalid_state` |A `hasher` is used after its `finish`, once moved from, or after a backend failure spent it. diff --git a/doc/kdfs.adoc b/doc/kdfs.adoc index c89d1d8..e4323b8 100644 --- a/doc/kdfs.adoc +++ b/doc/kdfs.adoc @@ -28,13 +28,15 @@ The key derivations are the functions of hash that run on a backend, a C library or Boost.Hash2, that the program names or leaves to the default, `backends::hash2` (<>); BLAKE2b subkeys run on libsodium alone, and the key derivations of standards on OpenSSL or Botan, which are -never a default: the call names one (<>). Each backend gives the same bytes for the same inputs: the -tests check them against each other on random inputs on every target. +never a default: the call names one (<>). Each backend gives +the same bytes for the same inputs: the tests check them against each other on +random inputs on every target. Every key derivation computes on a secret, and sets DIT (data-independent timing) around each call, on every synchronous backend, on 64-bit ARM under -Apple's systems and Linux where the CPU has FEAT_DIT, leaving the thread's DIT as it found it (<>): -`hkdf_extract`, `hkdf_expand`, `hkdf`, `pbkdf2`, `blake2b_subkey`, `kbkdf`, +Apple's systems and Linux where the CPU has FEAT_DIT, leaving the thread's DIT +as it found it (<>): `hkdf_extract`, `hkdf_expand`, +`hkdf` (each also over byte pieces), `pbkdf2`, `blake2b_subkey`, `kbkdf`, `sskdf` and `x963kdf`. `hkdf` enters one guard and runs the whole derivation inside it, and HKDF and PBKDF2 on `backends::hash2` run Boost.Hash2's `hmac` there too. @@ -45,14 +47,15 @@ include::generated/compare-kdfs.adoc[] === HKDF HKDF (RFC 5869, 2010, Krawczyk) has two steps, both HMACs. *Extract* takes an -optional salt and the input keying material (IKM) and returns a pseudorandom -key (PRK) of the hmac's digest size: `PRK = HMAC(salt, IKM)`. *Expand* takes -the PRK and an info string, the label of one purpose, and returns up to 255 -digests of output, each block an HMAC of the previous block, the info and a -counter. `hkdf` does both; `hkdf_extract` and `hkdf_expand` do one each, for -a protocol that names a step, or a program that extracts once and expands -many times. TLS 1.3, Signal, WireGuard, Noise and Nostr's NIP-44 derive their -keys with it. +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 +to 255 digests of `output_key_material`, each block an HMAC of the previous +block, the info and a counter. `hkdf` does both; `hkdf_extract` and +`hkdf_expand` do one each, for a protocol that names a step, or a program that +extracts once and expands many times. TLS 1.3, Signal, WireGuard, Noise and +Nostr's NIP-44 derive their keys with it. This section adapts the guidance of libsodium's documentation on HKDF (`key_derivation/hkdf.md` of @@ -71,22 +74,26 @@ include::{examples}/hkdf.expected[] *Choosing the inputs.* -* *IKM* is the secret. It may be non-uniform (a 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 +* *`input_key_material`* is the secret. It may be non-uniform (a +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 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 reused across applications. -* *Info* names the purpose and is public. Each key gets its own info, written -so that no two purposes can produce the same string: an application name, a -version and the purpose, as `example chat v1 encryption`. Info is limited to -32,768 bytes on every backend. -* *PRK* must stay secret, and `hkdf_expand` takes one of exactly the digest's -size (`invalid_key_size` otherwise). A key that is already uniform and of -that size, such as 32 bytes from `webcpp::crypto::random_device`, can be -expanded without the extract step. +* *`application_info`* names the purpose and is public. Each key gets its own +info, written so that no two purposes can produce the same string: an +application name, a version and the purpose, as `example chat v1 encryption`. +The info of a single buffer is limited to `hkdf_max_application_info_size`, +32,768 bytes, on every backend (1,024 in WebCrypto's `async_hkdf`, +<>); the forms over pieces take any length +(<>). +* *`pseudorandom_key`* must stay secret, and `hkdf_expand` takes one of +exactly the digest's size (`invalid_key_size` otherwise). A key that is +already uniform and of that size, such as 32 bytes from +`webcpp::crypto::random_device`, can be expanded without the extract step. * *HMAC-SHA-256 is the usual choice.* HMAC-SHA-512 gives longer blocks and no practical gain in security; use it when a protocol names it. @@ -106,11 +113,12 @@ include::generated/backends-hkdf.adoc[] Most programs never name a backend: the call takes the default, `backends::hash2`, on every target (<>). A program names -one as the call's second template argument, to match the bytes -of another program exactly, to share a C library the program already links, or to test one backend -against another. `backend_has_v` says at compile time -whether a backend has a function over an hmac; a call on a backend that does -not stops the build with a message that names the backends that do. +one as the call's second template argument, to match the bytes of another +program exactly, to share a C library the program already links, or to test +one backend against another. `backend_has_v` says at +compile time whether a backend has a function over an hmac; a call on a +backend that does not stops the build with a message that names the backends +that do. [source] ---- @@ -122,6 +130,97 @@ include::{examples}/hkdf_backends.cpp[tag=example,indent=0] include::{examples}/hkdf_backends.expected[] ---- +[#hash-hkdf-pieces] +=== HKDF over pieces + +Protocols seldom give HKDF one buffer. HPKE (RFC 9180) extracts from +`HPKE-v1`, the suite's identifier, a label and the secret, one after another; +TLS 1.3's `HKDF-Expand-Label` builds its info from a length, a label and a +context. Joining the parts takes a buffer: on the heap, with a copy of the +secret to wipe afterwards, or on the stack, with a size that someone must +bound. `hkdf_extract`, `hkdf_expand` and `hkdf` each have a form over +`byte_pieces` (``, which +`` includes) that takes the input keying material and +the application info as a list of spans, read one after another as if joined. +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_expand(output_key_material, pseudorandom_key, +application_info)` +* `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 +the single-buffer form over the parts joined: the tests check them against +each other on random inputs and random splits on every backend. + +*No cap, no heap.* The forms over pieces refuse only what RFC 5869 refuses: an +output of 0 bytes or of more than 255 digests (`invalid_output_size`), and for +`hkdf_expand` a pseudorandom key of another size than the digest's +(`invalid_key_size`); then the limits of the backend's HMAC key (OpenSSL takes +a salt of at most `INT_MAX` bytes, `input_too_long` beyond). The input keying +material, the application info and the number of pieces have no limit: +`hkdf_max_application_info_size` belongs to the single-buffer forms alone. A +piece longer than the backend's length type holds is fed in slices. On +`backends::hash2`, `backends::sodium` and `backends::bearssl` hash allocates +nothing, whatever the number and the size of the pieces (test `allocation`); +OpenSSL's and Botan's allocations are theirs, counted in <>. +Every HMAC state, every block and the pseudorandom key between the two steps +are wiped, on success and on failure. `backends::webcrypto` is the exception: +its asynchronous forms copy every input, the secret included, into JavaScript +buffers in the call, zeroed when their promises settle, and a runtime that +will not allocate a buffer that size completes with `backend_failure` +(<>, <>). + +*Writing the pieces.* + +* *A braced list at the call,* `{a, b, c}`: each element converts to +`std::span` (a `std::array`, a `std::vector`, a span). Its +array lives until the end of the call's full expression, after the call +returns. +* *One piece is `+byte_pieces{x}+`.* A braced list of one span, `+{x}+`, is +that span (the language's rule), so `+hkdf_expand(okm, prk, {info})+` calls +the single-buffer form, with its limit; +`+hkdf_expand(okm, prk, byte_pieces{info})+` calls the form over pieces. +`hkdf` takes both inputs as pieces or both as spans: beside a list, one buffer +is written `+byte_pieces{input_key_material}+`. +* *`{}` and `+{x}+` of another type do not compile.* Where both forms take +braces, a lone `{}`, or a braced list of one element that is not exactly a +`std::span` (`+{vec}+`, `+{array}+`), matches both forms +and the call is ambiguous: `hkdf(okm, salt, {}, {})` and +`hkdf(okm, {}, {}, {})`, which compiled before the forms over pieces existed, +no longer do. Pass `x` itself, an empty `std::span`, or +`+byte_pieces{...}+` (`byte_pieces{}` for no piece). The asynchronous forms +follow the same rule (<>). +* *A list kept in a variable is a `std::array` of spans,* as a +`std::array, 3>` of `prefix`, `label` and +`secret`, passed as it is (a `std::vector` or a span of spans too); never a +`byte_pieces` variable. `byte_pieces parts{a, b};` points to its braced list's +array, which dies at the end of the declaration; where the compiler has the +`lifetimebound` attribute, it warns. + +HPKE's labeled steps (RFC 9180, section 4) are one call each, here running +HPKE's key schedule on test vector A.1.1 of the RFC: + +[source] +---- +include::{examples}/hkdf_pieces.cpp[tag=example,indent=0] +---- + +[listing] +---- +include::{examples}/hkdf_pieces.expected[] +---- + +Every backend that has an HKDF function has the three forms over pieces, +`backends::bearssl` included (its `hkdf_extract` and `hkdf_expand` exist over +pieces alone, on BearSSL's HMAC), and `backends::webcrypto` has their +asynchronous forms (<>): <> lists +each form with its backends, targets and hmacs. The default is +`backends::hash2`, as for the single-buffer forms. + [#hash-pbkdf2] === PBKDF2 diff --git a/doc/llms.txt b/doc/llms.txt index 658ebce..d8c99ca 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -1,6 +1,6 @@ # webcpp::hash -> Hashing and key derivation for C++20 on every target webcpp has (native, wasip2, wasip3, Emscripten): Boost.Hash2's digests and HMAC, Keccak-256, BLAKE3, HKDF, PBKDF2, Argon2id, scrypt and the KDFs of NIST SP 800-108, SP 800-56C and ANSI X9.63 over C backends. Every synchronous function returns boost::system::result and allocates nothing in webcpp's own code; async.hpp gives the slow ones and the ones WebCrypto has an asynchronous form over webcpp::asio, and backends::webcrypto, the browser's WebCrypto, serves that form alone. A program links /webcpp/hash//hash and the library of each backend it uses. By default, hkdf_extract, hkdf_expand, hkdf and pbkdf2 run on backends::hash2 unless the call names another of its backends as its second template argument; blake2b_subkey runs on backends::sodium alone; kbkdf, sskdf and x963kdf have no default backend, and the call names one of its backends as its second template argument; argon2id and scrypt run on backends::sodium unless the call names another of its backends as its only template argument; bcrypt and bcrypt_pbkdf have no default backend, and the call names backends::botan as its only template argument. The families digest_of, hasher, mac and argon2 take a tag of digests, macs or kdfs and a backend, by default the first of backends::hash2, backends::xkcp, backends::blake3 and backends::sodium that has the tag. +> Hashing and key derivation for C++20 on every target webcpp has (native, wasip2, wasip3, Emscripten): Boost.Hash2's digests and HMAC, Keccak-256, BLAKE3, HKDF, PBKDF2, Argon2id, scrypt and the KDFs of NIST SP 800-108, SP 800-56C and ANSI X9.63 over C backends. Every synchronous function returns boost::system::result and allocates nothing in webcpp's own code; async.hpp gives the slow ones and the ones WebCrypto has an asynchronous form over webcpp::asio, and backends::webcrypto, the browser's WebCrypto, serves that form alone. A program links /webcpp/hash//hash and the library of each backend it uses. By default, hkdf_extract, hkdf_expand, hkdf, hkdf_extract over pieces, hkdf_expand over pieces, hkdf over pieces and pbkdf2 run on backends::hash2 unless the call names another of its backends as its second template argument; blake2b_subkey runs on backends::sodium alone; kbkdf, sskdf and x963kdf have no default backend, and the call names one of its backends as its second template argument; argon2id and scrypt run on backends::sodium unless the call names another of its backends as its only template argument; bcrypt and bcrypt_pbkdf have no default backend, and the call names backends::botan as its only template argument. The families digest_of, hasher, mac and argon2 take a tag of digests, macs or kdfs and a backend, by default the first of backends::hash2, backends::xkcp, backends::blake3 and backends::sodium that has the tag. Primitives only: protocol steps (BIP39, hash160, EIP-55, Nostr ids, NIP-44) are what a domain library builds from these functions; the guide shows them as examples, never as this library's API. @@ -130,9 +130,12 @@ Keyed hashes: a tag that only the holder of a secret key can compute, so that a HKDF, PBKDF2 and BLAKE2b subkeys: keys from a shared secret or a master key (HKDF, libsodium's crypto_kdf), or from a password where a standard demands PBKDF2. [Key derivation](https://webcpporg.github.io/libs/hash/#hash-kdfs) -- webcpp::hash::hkdf_extract (, RFC 5869): HKDF-Extract: a uniform pseudorandom key from a secret that is not uniform, such as a Diffie-Hellman result. Status: recommended. Choose it: When a protocol names the extract step alone. Backends: hash2 (/webcpp/hash//hash; native, wasip2, wasip3, emscripten), sodium (/third_party//sodium; native, wasip2, wasip3, emscripten), openssl (/webcpp/hash//openssl; native, wasip2, wasip3), botan, with exceptions only (/third_party//botan; native, emscripten). [Section](https://webcpporg.github.io/libs/hash/#hash-hkdf) -- webcpp::hash::hkdf_expand (, RFC 5869): HKDF-Expand: many keys, each for one purpose, from one pseudorandom key. Status: recommended. Choose it: Keys from a key that is already uniform (a master key), one per info label. Backends: hash2 (/webcpp/hash//hash; native, wasip2, wasip3, emscripten), sodium (/third_party//sodium; native, wasip2, wasip3, emscripten), openssl (/webcpp/hash//openssl; native, wasip2, wasip3), botan, with exceptions only (/third_party//botan; native, emscripten). [Section](https://webcpporg.github.io/libs/hash/#hash-hkdf) -- webcpp::hash::hkdf (, RFC 5869): HKDF, extract then expand: keys from a shared secret, each separated by its info label. Status: recommended. Choose it: The default way to turn one secret into several keys. Never for passwords. Backends: hash2 (/webcpp/hash//hash; native, wasip2, wasip3, emscripten), sodium (/third_party//sodium; native, wasip2, wasip3, emscripten), bearssl (/third_party//bearssl; native, wasip2, wasip3, emscripten), openssl (/webcpp/hash//openssl; native, wasip2, wasip3), botan, with exceptions only (/third_party//botan; native, emscripten), webcrypto, asynchronous family only (/webcpp/asio//asio; emscripten). [Section](https://webcpporg.github.io/libs/hash/#hash-hkdf) +- webcpp::hash::hkdf_extract (, RFC 5869): HKDF-Extract: a uniform pseudorandom key from a secret that is not uniform, such as a Diffie-Hellman result. Status: recommended. Choose it: When a protocol names the extract step alone. Backends: hash2 (/webcpp/hash//hash; native, wasip2, wasip3, emscripten), sodium (/third_party//sodium; native, wasip2, wasip3, emscripten), openssl (/webcpp/hash//openssl; native, wasip2, wasip3), botan, with exceptions only (/third_party//botan; native, emscripten), webcrypto, asynchronous family only (/webcpp/asio//asio; emscripten). [Section](https://webcpporg.github.io/libs/hash/#hash-hkdf) +- webcpp::hash::hkdf_expand (, RFC 5869): HKDF-Expand: many keys, each for one purpose, from one pseudorandom key. Status: recommended. Choose it: Keys from a key that is already uniform (a master key), one per application info label. Backends: hash2 (/webcpp/hash//hash; native, wasip2, wasip3, emscripten), sodium (/third_party//sodium; native, wasip2, wasip3, emscripten), openssl (/webcpp/hash//openssl; native, wasip2, wasip3), botan, with exceptions only (/third_party//botan; native, emscripten), webcrypto, asynchronous family only (/webcpp/asio//asio; emscripten). [Section](https://webcpporg.github.io/libs/hash/#hash-hkdf) +- webcpp::hash::hkdf (, RFC 5869): HKDF, extract then expand: keys from a shared secret, each separated by its application info label. Status: recommended. Choose it: The default way to turn one secret into several keys. Never for passwords. Backends: hash2 (/webcpp/hash//hash; native, wasip2, wasip3, emscripten), sodium (/third_party//sodium; native, wasip2, wasip3, emscripten), bearssl (/third_party//bearssl; native, wasip2, wasip3, emscripten), openssl (/webcpp/hash//openssl; native, wasip2, wasip3), botan, with exceptions only (/third_party//botan; native, emscripten), webcrypto, asynchronous family only (/webcpp/asio//asio; emscripten). [Section](https://webcpporg.github.io/libs/hash/#hash-hkdf) +- webcpp::hash::hkdf_extract over pieces (, RFC 5869): hkdf_extract with its input_key_material as byte_pieces, read one after another as if concatenated, with no cap. Backends: hash2 (/webcpp/hash//hash; native, wasip2, wasip3, emscripten), sodium (/third_party//sodium; native, wasip2, wasip3, emscripten), bearssl (/third_party//bearssl; native, wasip2, wasip3, emscripten), openssl (/webcpp/hash//openssl; native, wasip2, wasip3), botan, with exceptions only (/third_party//botan; native, emscripten), webcrypto, asynchronous family only (/webcpp/asio//asio; emscripten). [Section](https://webcpporg.github.io/libs/hash/#hash-hkdf) +- webcpp::hash::hkdf_expand over pieces (, RFC 5869): hkdf_expand with its application_info as byte_pieces, read one after another as if concatenated, with no cap. Backends: hash2 (/webcpp/hash//hash; native, wasip2, wasip3, emscripten), sodium (/third_party//sodium; native, wasip2, wasip3, emscripten), bearssl (/third_party//bearssl; native, wasip2, wasip3, emscripten), openssl (/webcpp/hash//openssl; native, wasip2, wasip3), botan, with exceptions only (/third_party//botan; native, emscripten), webcrypto, asynchronous family only (/webcpp/asio//asio; emscripten). [Section](https://webcpporg.github.io/libs/hash/#hash-hkdf) +- webcpp::hash::hkdf over pieces (, RFC 5869): hkdf with its input_key_material and application_info as byte_pieces, read one after another as if concatenated, with no cap. Backends: hash2 (/webcpp/hash//hash; native, wasip2, wasip3, emscripten), sodium (/third_party//sodium; native, wasip2, wasip3, emscripten), bearssl (/third_party//bearssl; native, wasip2, wasip3, emscripten), openssl (/webcpp/hash//openssl; native, wasip2, wasip3), botan, with exceptions only (/third_party//botan; native, emscripten), webcrypto, asynchronous family only (/webcpp/asio//asio; emscripten). [Section](https://webcpporg.github.io/libs/hash/#hash-hkdf) - webcpp::hash::pbkdf2 (, RFC 8018): PBKDF2: a key from a password by many iterations of an hmac; not memory-hard. Status: where a standard names it. Choose it: When a standard or FIPS 140 demands it; otherwise Argon2id for passwords. Backends: hash2 (/webcpp/hash//hash; native, wasip2, wasip3, emscripten), openssl (/webcpp/hash//openssl; native, wasip2, wasip3), botan, with exceptions only (/third_party//botan; native, emscripten), webcrypto, asynchronous family only (/webcpp/asio//asio; emscripten). [Section](https://webcpporg.github.io/libs/hash/#hash-pbkdf2) - webcpp::hash::blake2b_subkey (, libsodium's crypto_kdf: keyed BLAKE2b (RFC 7693) with the subkey's id as the salt and the context as the personalisation): BLAKE2b subkeys, libsodium's crypto_kdf: many keys of 16 to 64 bytes from one 32-byte master key, each named by a 64-bit id and an 8-byte context. Status: recommended. Choose it: To derive the keys a libsodium program derives from the same master key, or keys numbered by id from one random master key; hkdf for a secret that is not uniformly random. Backends: sodium (/third_party//sodium; native, wasip2, wasip3, emscripten). [Section](https://webcpporg.github.io/libs/hash/#hash-blake2b-subkey) - webcpp::hash::kbkdf (, NIST SP 800-108r1, counter mode over HMAC): KBKDF, NIST SP 800-108's key derivation in counter mode over HMAC: keys from a key-derivation key, a label and a context. Status: recommended. Choose it: When a standard, a protocol or a smart card names SP 800-108's counter mode; hkdf for a new design. Backends: openssl (/webcpp/hash//openssl; native, wasip2, wasip3), botan, with exceptions only (/third_party//botan; native, emscripten). [Section](https://webcpporg.github.io/libs/hash/#hash-kbkdf) @@ -172,11 +175,11 @@ Fast hashes for hash tables, checksums against accidents and identifiers that no - I need to store users' passwords for a login: argon2id with argon2id_interactive or stronger, a random 16-byte salt per user; backend: link /third_party//sodium; example libs/hash/example/password_storage.cpp. [Section](https://webcpporg.github.io/libs/hash/#hash-privacy-passwords) - I need to turn a password into an encryption key (a password manager, an encrypted backup): argon2id with argon2id_moderate or argon2id_sensitive, then hkdf for each purpose; backend: link /third_party//sodium; example libs/hash/example/argon2id.cpp. [Section](https://webcpporg.github.io/libs/hash/#hash-argon2id) - I need to check or make the bcrypt strings a system already stores, or read and write OpenSSH's encrypted private keys: bcrypt and bcrypt_verify at a cost of 10 or more (bcrypt_pbkdf for OpenSSH's keys); argon2id for a new design; backend: name backends::botan and link /third_party//botan, with exceptions; example libs/hash/example/bcrypt.cpp. [Section](https://webcpporg.github.io/libs/hash/#hash-bcrypt) -- I need to turn a shared secret (an ECDH result) into keys: hkdf over hmac_sha2_256, one info label per key; backend: the default; name a backend only to match another program's; example libs/hash/example/hkdf.cpp. [Section](https://webcpporg.github.io/libs/hash/#hash-hkdf) +- I need to turn a shared secret (an ECDH result) into keys: hkdf over hmac_sha2_256, one application info label per key; backend: the default; name a backend only to match another program's; example libs/hash/example/hkdf.cpp. [Section](https://webcpporg.github.io/libs/hash/#hash-hkdf) - I need to derive the key JOSE's ECDH-ES (a JWE) or another NIST SP 800-56C protocol derives from a shared secret: sskdf over digests::sha2_256, the fixed info as the protocol writes it; backend: name backends::openssl (or backends::botan) and link its library, /webcpp/hash//openssl (or /third_party//botan); example libs/hash/example/sskdf.cpp. [Section](https://webcpporg.github.io/libs/hash/#hash-sskdf) - I need to derive the keys of ECIES or of a smart card's key agreement (ANSI X9.63): x963kdf over digests::sha2_256, the shared info as the scheme writes it; backend: name backends::openssl (or backends::botan) and link its library, /webcpp/hash//openssl (or /third_party//botan); example libs/hash/example/x963kdf.cpp. [Section](https://webcpporg.github.io/libs/hash/#hash-x963kdf) - I need to derive keys from a key as NIST SP 800-108 or Kerberos does (a label and a context): kbkdf over hmac_sha2_256 with the label and the context; backend: name backends::openssl (or backends::botan) and link its library, /webcpp/hash//openssl (or /third_party//botan); example libs/hash/example/kbkdf.cpp. [Section](https://webcpporg.github.io/libs/hash/#hash-kbkdf) -- I need to derive many keys from one master key, one per purpose: hkdf_expand (or hkdf) with distinct info labels, blake2b_subkey (libsodium's crypto_kdf) by id, or blake3::derive_key with a context string; backend: the default; example libs/hash/example/subkeys.cpp. [Section](https://webcpporg.github.io/libs/hash/#hash-privacy-subkeys) +- I need to derive many keys from one master key, one per purpose: hkdf_expand (or hkdf) with distinct application info labels, blake2b_subkey (libsodium's crypto_kdf) by id, or blake3::derive_key with a context string; backend: the default; example libs/hash/example/subkeys.cpp. [Section](https://webcpporg.github.io/libs/hash/#hash-privacy-subkeys) - I need to build a hash table, set or Bloom filter whose keys come from the network: siphash_64 keyed with 16 random bytes per process; backend: none: one backend; example libs/hash/example/siphash.cpp. [Section](https://webcpporg.github.io/libs/hash/#hash-siphash) - I need to build a hash table of my own trusted keys, or a fast checksum: xxh3_128 or fnv1a_64; backend: none: one backend; example libs/hash/example/checksums.cpp. [Section](https://webcpporg.github.io/libs/hash/#hash-non-cryptographic-functions) - I need to compute a Bitcoin wallet's BIP39 seed from its words: pbkdf2 over hmac_sha2_512, 2,048 iterations (a domain library's step); backend: the default; example libs/hash/example/bip39_seed.cpp. [Section](https://webcpporg.github.io/libs/hash/#hash-crypto-bip39) diff --git a/doc/measurements.allocation.json b/doc/measurements.allocation.json index 82f8044..306ba39 100644 --- a/doc/measurements.allocation.json +++ b/doc/measurements.allocation.json @@ -1,6 +1,6 @@ { "measurement": "allocations per call, native with the C allocator counted where it can be", - "date": "2026-11-21", + "date": "2026-11-24", "build": "variant=release", "toolsets": { "native": "clang-darwin-21", @@ -1795,6 +1795,39 @@ "c_allocator_calls": 21, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_md5_128", + "call": 1, + "operator_new": 4, + "c_allocator_calls": 7, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_md5_128", + "call": 1, + "operator_new": 4, + "c_allocator_calls": 11, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_md5_128", + "call": 1, + "operator_new": 8, + "c_allocator_calls": 18, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -1850,6 +1883,39 @@ "c_allocator_calls": 21, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_md5_128", + "call": 2, + "operator_new": 4, + "c_allocator_calls": 7, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_md5_128", + "call": 2, + "operator_new": 4, + "c_allocator_calls": 11, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_md5_128", + "call": 2, + "operator_new": 8, + "c_allocator_calls": 18, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -1905,6 +1971,39 @@ "c_allocator_calls": 22, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha1_160", + "call": 1, + "operator_new": 4, + "c_allocator_calls": 7, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha1_160", + "call": 1, + "operator_new": 4, + "c_allocator_calls": 11, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha1_160", + "call": 1, + "operator_new": 8, + "c_allocator_calls": 18, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -1960,6 +2059,39 @@ "c_allocator_calls": 22, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha1_160", + "call": 2, + "operator_new": 4, + "c_allocator_calls": 7, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha1_160", + "call": 2, + "operator_new": 4, + "c_allocator_calls": 11, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha1_160", + "call": 2, + "operator_new": 8, + "c_allocator_calls": 18, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -2015,6 +2147,39 @@ "c_allocator_calls": 22, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha2_224", + "call": 1, + "operator_new": 4, + "c_allocator_calls": 7, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha2_224", + "call": 1, + "operator_new": 4, + "c_allocator_calls": 9, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha2_224", + "call": 1, + "operator_new": 8, + "c_allocator_calls": 16, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -2070,6 +2235,39 @@ "c_allocator_calls": 22, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha2_224", + "call": 2, + "operator_new": 4, + "c_allocator_calls": 7, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha2_224", + "call": 2, + "operator_new": 4, + "c_allocator_calls": 9, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha2_224", + "call": 2, + "operator_new": 8, + "c_allocator_calls": 16, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -2125,6 +2323,39 @@ "c_allocator_calls": 22, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha2_256", + "call": 1, + "operator_new": 4, + "c_allocator_calls": 7, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha2_256", + "call": 1, + "operator_new": 4, + "c_allocator_calls": 9, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha2_256", + "call": 1, + "operator_new": 8, + "c_allocator_calls": 16, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -2180,6 +2411,39 @@ "c_allocator_calls": 22, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha2_256", + "call": 2, + "operator_new": 4, + "c_allocator_calls": 7, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha2_256", + "call": 2, + "operator_new": 4, + "c_allocator_calls": 9, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha2_256", + "call": 2, + "operator_new": 8, + "c_allocator_calls": 16, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -2236,38 +2500,71 @@ "c_allocator_counted": true }, { - "operation": "hkdf_extract", + "operation": "hkdf_extract_pieces", "backend": "botan", "target": "native", "implementation": "backends::botan", "tag": "hmac_sha2_384", - "call": 2, - "operator_new": 16, - "c_allocator_calls": 19, + "call": 1, + "operator_new": 4, + "c_allocator_calls": 7, "c_allocator_counted": true }, { - "operation": "hkdf_expand", + "operation": "hkdf_expand_pieces", "backend": "botan", "target": "native", "implementation": "backends::botan", "tag": "hmac_sha2_384", - "call": 2, - "operator_new": 16, - "c_allocator_calls": 19, + "call": 1, + "operator_new": 4, + "c_allocator_calls": 7, "c_allocator_counted": true }, { - "operation": "hkdf", + "operation": "hkdf_pieces", "backend": "botan", "target": "native", "implementation": "backends::botan", "tag": "hmac_sha2_384", - "call": 2, - "operator_new": 17, - "c_allocator_calls": 25, - "c_allocator_counted": true - }, + "call": 1, + "operator_new": 8, + "c_allocator_calls": 14, + "c_allocator_counted": true + }, + { + "operation": "hkdf_extract", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha2_384", + "call": 2, + "operator_new": 16, + "c_allocator_calls": 19, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha2_384", + "call": 2, + "operator_new": 16, + "c_allocator_calls": 19, + "c_allocator_counted": true + }, + { + "operation": "hkdf", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha2_384", + "call": 2, + "operator_new": 17, + "c_allocator_calls": 25, + "c_allocator_counted": true + }, { "operation": "pbkdf2", "backend": "botan", @@ -2290,6 +2587,39 @@ "c_allocator_calls": 21, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha2_384", + "call": 2, + "operator_new": 4, + "c_allocator_calls": 7, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha2_384", + "call": 2, + "operator_new": 4, + "c_allocator_calls": 7, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha2_384", + "call": 2, + "operator_new": 8, + "c_allocator_calls": 14, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -2345,6 +2675,39 @@ "c_allocator_calls": 22, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha2_512", + "call": 1, + "operator_new": 4, + "c_allocator_calls": 7, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha2_512", + "call": 1, + "operator_new": 4, + "c_allocator_calls": 7, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha2_512", + "call": 1, + "operator_new": 8, + "c_allocator_calls": 14, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -2400,6 +2763,39 @@ "c_allocator_calls": 22, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha2_512", + "call": 2, + "operator_new": 4, + "c_allocator_calls": 7, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha2_512", + "call": 2, + "operator_new": 4, + "c_allocator_calls": 7, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha2_512", + "call": 2, + "operator_new": 8, + "c_allocator_calls": 14, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -2455,6 +2851,39 @@ "c_allocator_calls": 26, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha2_512_256", + "call": 1, + "operator_new": 4, + "c_allocator_calls": 7, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha2_512_256", + "call": 1, + "operator_new": 4, + "c_allocator_calls": 9, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha2_512_256", + "call": 1, + "operator_new": 8, + "c_allocator_calls": 16, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -2510,6 +2939,39 @@ "c_allocator_calls": 26, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha2_512_256", + "call": 2, + "operator_new": 4, + "c_allocator_calls": 7, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha2_512_256", + "call": 2, + "operator_new": 4, + "c_allocator_calls": 9, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha2_512_256", + "call": 2, + "operator_new": 8, + "c_allocator_calls": 16, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -2565,6 +3027,39 @@ "c_allocator_calls": 27, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha3_224", + "call": 1, + "operator_new": 7, + "c_allocator_calls": 9, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha3_224", + "call": 1, + "operator_new": 7, + "c_allocator_calls": 11, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha3_224", + "call": 1, + "operator_new": 14, + "c_allocator_calls": 20, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -2620,6 +3115,39 @@ "c_allocator_calls": 27, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha3_224", + "call": 2, + "operator_new": 7, + "c_allocator_calls": 9, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha3_224", + "call": 2, + "operator_new": 7, + "c_allocator_calls": 11, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha3_224", + "call": 2, + "operator_new": 14, + "c_allocator_calls": 20, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -2676,18 +3204,51 @@ "c_allocator_counted": true }, { - "operation": "hkdf_extract", + "operation": "hkdf_extract_pieces", "backend": "botan", "target": "native", "implementation": "backends::botan", "tag": "hmac_sha3_256", - "call": 2, - "operator_new": 22, - "c_allocator_calls": 24, + "call": 1, + "operator_new": 7, + "c_allocator_calls": 9, "c_allocator_counted": true }, { - "operation": "hkdf_expand", + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha3_256", + "call": 1, + "operator_new": 7, + "c_allocator_calls": 11, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha3_256", + "call": 1, + "operator_new": 14, + "c_allocator_calls": 20, + "c_allocator_counted": true + }, + { + "operation": "hkdf_extract", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha3_256", + "call": 2, + "operator_new": 22, + "c_allocator_calls": 24, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand", "backend": "botan", "target": "native", "implementation": "backends::botan", @@ -2730,6 +3291,39 @@ "c_allocator_calls": 27, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha3_256", + "call": 2, + "operator_new": 7, + "c_allocator_calls": 9, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha3_256", + "call": 2, + "operator_new": 7, + "c_allocator_calls": 11, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha3_256", + "call": 2, + "operator_new": 14, + "c_allocator_calls": 20, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -2785,6 +3379,39 @@ "c_allocator_calls": 26, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha3_384", + "call": 1, + "operator_new": 7, + "c_allocator_calls": 9, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha3_384", + "call": 1, + "operator_new": 7, + "c_allocator_calls": 9, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha3_384", + "call": 1, + "operator_new": 14, + "c_allocator_calls": 18, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -2840,6 +3467,39 @@ "c_allocator_calls": 26, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha3_384", + "call": 2, + "operator_new": 7, + "c_allocator_calls": 9, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha3_384", + "call": 2, + "operator_new": 7, + "c_allocator_calls": 9, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha3_384", + "call": 2, + "operator_new": 14, + "c_allocator_calls": 18, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -2895,6 +3555,39 @@ "c_allocator_calls": 27, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha3_512", + "call": 1, + "operator_new": 7, + "c_allocator_calls": 9, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha3_512", + "call": 1, + "operator_new": 7, + "c_allocator_calls": 9, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha3_512", + "call": 1, + "operator_new": 14, + "c_allocator_calls": 18, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -2950,6 +3643,39 @@ "c_allocator_calls": 27, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha3_512", + "call": 2, + "operator_new": 7, + "c_allocator_calls": 9, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha3_512", + "call": 2, + "operator_new": 7, + "c_allocator_calls": 9, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_sha3_512", + "call": 2, + "operator_new": 14, + "c_allocator_calls": 18, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -3005,6 +3731,39 @@ "c_allocator_calls": 22, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_ripemd_160", + "call": 1, + "operator_new": 4, + "c_allocator_calls": 7, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_ripemd_160", + "call": 1, + "operator_new": 4, + "c_allocator_calls": 11, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_ripemd_160", + "call": 1, + "operator_new": 8, + "c_allocator_calls": 18, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -3060,6 +3819,39 @@ "c_allocator_calls": 22, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_ripemd_160", + "call": 2, + "operator_new": 4, + "c_allocator_calls": 7, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_ripemd_160", + "call": 2, + "operator_new": 4, + "c_allocator_calls": 11, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_ripemd_160", + "call": 2, + "operator_new": 8, + "c_allocator_calls": 18, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -3116,38 +3908,71 @@ "c_allocator_counted": true }, { - "operation": "hkdf_extract", + "operation": "hkdf_extract_pieces", "backend": "botan", "target": "native", "implementation": "backends::botan", "tag": "hmac_blake2b_512", - "call": 2, - "operator_new": 26, - "c_allocator_calls": 29, + "call": 1, + "operator_new": 7, + "c_allocator_calls": 10, "c_allocator_counted": true }, { - "operation": "hkdf_expand", + "operation": "hkdf_expand_pieces", "backend": "botan", "target": "native", "implementation": "backends::botan", "tag": "hmac_blake2b_512", - "call": 2, - "operator_new": 26, - "c_allocator_calls": 30, + "call": 1, + "operator_new": 7, + "c_allocator_calls": 10, "c_allocator_counted": true }, { - "operation": "hkdf", + "operation": "hkdf_pieces", "backend": "botan", "target": "native", "implementation": "backends::botan", "tag": "hmac_blake2b_512", - "call": 2, - "operator_new": 30, - "c_allocator_calls": 39, - "c_allocator_counted": true - }, + "call": 1, + "operator_new": 14, + "c_allocator_calls": 20, + "c_allocator_counted": true + }, + { + "operation": "hkdf_extract", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_blake2b_512", + "call": 2, + "operator_new": 26, + "c_allocator_calls": 29, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_blake2b_512", + "call": 2, + "operator_new": 26, + "c_allocator_calls": 30, + "c_allocator_counted": true + }, + { + "operation": "hkdf", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_blake2b_512", + "call": 2, + "operator_new": 30, + "c_allocator_calls": 39, + "c_allocator_counted": true + }, { "operation": "pbkdf2", "backend": "botan", @@ -3170,6 +3995,39 @@ "c_allocator_calls": 32, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_blake2b_512", + "call": 2, + "operator_new": 7, + "c_allocator_calls": 10, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_blake2b_512", + "call": 2, + "operator_new": 7, + "c_allocator_calls": 10, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_blake2b_512", + "call": 2, + "operator_new": 14, + "c_allocator_calls": 20, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -3225,6 +4083,39 @@ "c_allocator_calls": 31, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_blake2s_256", + "call": 1, + "operator_new": 7, + "c_allocator_calls": 9, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_blake2s_256", + "call": 1, + "operator_new": 7, + "c_allocator_calls": 11, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_blake2s_256", + "call": 1, + "operator_new": 14, + "c_allocator_calls": 20, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -3280,6 +4171,39 @@ "c_allocator_calls": 31, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_blake2s_256", + "call": 2, + "operator_new": 7, + "c_allocator_calls": 9, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_blake2s_256", + "call": 2, + "operator_new": 7, + "c_allocator_calls": 11, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "native", + "implementation": "backends::botan", + "tag": "hmac_blake2s_256", + "call": 2, + "operator_new": 14, + "c_allocator_calls": 20, + "c_allocator_counted": true + }, { "operation": "sskdf", "backend": "botan", @@ -3807,44 +4731,34 @@ "openssl_allocations": 30 }, { - "operation": "hkdf", + "operation": "hkdf_extract_pieces", "backend": "openssl", "target": "native", "implementation": "backends::openssl", "operator_new": 0, "hmac": "hmac_sha2_256", - "call": 2, - "openssl_allocations": 24 + "call": 1, + "openssl_allocations": 10 }, { - "operation": "pbkdf2", + "operation": "hkdf_expand_pieces", "backend": "openssl", "target": "native", "implementation": "backends::openssl", "operator_new": 0, "hmac": "hmac_sha2_256", - "call": 2, - "openssl_allocations": 18 - }, - { - "operation": "hkdf", - "backend": "openssl", - "target": "native", - "implementation": "backends::openssl", - "operator_new": 0, - "hmac": "hmac_sha2_512", "call": 1, "openssl_allocations": 30 }, { - "operation": "pbkdf2", + "operation": "hkdf_pieces", "backend": "openssl", "target": "native", "implementation": "backends::openssl", "operator_new": 0, - "hmac": "hmac_sha2_512", + "hmac": "hmac_sha2_256", "call": 1, - "openssl_allocations": 18 + "openssl_allocations": 40 }, { "operation": "hkdf", @@ -3852,7 +4766,7 @@ "target": "native", "implementation": "backends::openssl", "operator_new": 0, - "hmac": "hmac_sha2_512", + "hmac": "hmac_sha2_256", "call": 2, "openssl_allocations": 24 }, @@ -3862,49 +4776,39 @@ "target": "native", "implementation": "backends::openssl", "operator_new": 0, - "hmac": "hmac_sha2_512", + "hmac": "hmac_sha2_256", "call": 2, "openssl_allocations": 18 }, { - "operation": "hkdf", - "backend": "openssl", - "target": "native", - "implementation": "backends::openssl", - "operator_new": 0, - "hmac": "hmac_sha3_256", - "call": 1, - "openssl_allocations": 30 - }, - { - "operation": "pbkdf2", + "operation": "hkdf_extract_pieces", "backend": "openssl", "target": "native", "implementation": "backends::openssl", "operator_new": 0, - "hmac": "hmac_sha3_256", - "call": 1, - "openssl_allocations": 18 + "hmac": "hmac_sha2_256", + "call": 2, + "openssl_allocations": 10 }, { - "operation": "hkdf", + "operation": "hkdf_expand_pieces", "backend": "openssl", "target": "native", "implementation": "backends::openssl", "operator_new": 0, - "hmac": "hmac_sha3_256", + "hmac": "hmac_sha2_256", "call": 2, - "openssl_allocations": 24 + "openssl_allocations": 30 }, { - "operation": "pbkdf2", + "operation": "hkdf_pieces", "backend": "openssl", "target": "native", "implementation": "backends::openssl", "operator_new": 0, - "hmac": "hmac_sha3_256", + "hmac": "hmac_sha2_256", "call": 2, - "openssl_allocations": 18 + "openssl_allocations": 40 }, { "operation": "hkdf", @@ -3912,7 +4816,7 @@ "target": "native", "implementation": "backends::openssl", "operator_new": 0, - "hmac": "hmac_blake2b_512", + "hmac": "hmac_sha2_512", "call": 1, "openssl_allocations": 30 }, @@ -3922,126 +4826,576 @@ "target": "native", "implementation": "backends::openssl", "operator_new": 0, - "hmac": "hmac_blake2b_512", + "hmac": "hmac_sha2_512", "call": 1, "openssl_allocations": 18 }, { - "operation": "hkdf", + "operation": "hkdf_extract_pieces", "backend": "openssl", "target": "native", "implementation": "backends::openssl", "operator_new": 0, - "hmac": "hmac_blake2b_512", - "call": 2, - "openssl_allocations": 24 + "hmac": "hmac_sha2_512", + "call": 1, + "openssl_allocations": 10 }, { - "operation": "pbkdf2", + "operation": "hkdf_expand_pieces", "backend": "openssl", "target": "native", "implementation": "backends::openssl", "operator_new": 0, - "hmac": "hmac_blake2b_512", - "call": 2, - "openssl_allocations": 18 - }, - { - "operation": "sodium_init", - "backend": "sodium", - "target": "wasip2", - "implementation": "backends::sodium", - "operator_new": 0, - "c_allocator_calls": 1, - "c_allocator_counted": true - }, - { - "operation": "argon2id", - "backend": "sodium", - "target": "wasip2", - "implementation": "backends::sodium", - "operator_new": 0, - "c_allocator_calls": 5, - "c_allocator_counted": true - }, - { - "operation": "scrypt", - "backend": "sodium", - "target": "wasip2", - "implementation": "backends::sodium", - "operator_new": 0, - "c_allocator_calls": 1, - "c_allocator_counted": true - }, - { - "operation": "hkdf", - "backend": "openssl", - "target": "wasip2", - "implementation": "backends::openssl", - "operator_new": 0, - "hmac": "hmac_sha2_256", + "hmac": "hmac_sha2_512", "call": 1, - "openssl_allocations": 3960 + "openssl_allocations": 20 }, { - "operation": "pbkdf2", + "operation": "hkdf_pieces", "backend": "openssl", - "target": "wasip2", + "target": "native", "implementation": "backends::openssl", "operator_new": 0, - "hmac": "hmac_sha2_256", + "hmac": "hmac_sha2_512", "call": 1, "openssl_allocations": 30 }, { "operation": "hkdf", "backend": "openssl", - "target": "wasip2", + "target": "native", "implementation": "backends::openssl", "operator_new": 0, - "hmac": "hmac_sha2_256", + "hmac": "hmac_sha2_512", "call": 2, "openssl_allocations": 24 }, { "operation": "pbkdf2", "backend": "openssl", - "target": "wasip2", + "target": "native", "implementation": "backends::openssl", "operator_new": 0, - "hmac": "hmac_sha2_256", + "hmac": "hmac_sha2_512", "call": 2, "openssl_allocations": 18 }, { - "operation": "hkdf", + "operation": "hkdf_extract_pieces", "backend": "openssl", - "target": "wasip2", + "target": "native", "implementation": "backends::openssl", "operator_new": 0, "hmac": "hmac_sha2_512", - "call": 1, - "openssl_allocations": 30 + "call": 2, + "openssl_allocations": 10 }, { - "operation": "pbkdf2", + "operation": "hkdf_expand_pieces", "backend": "openssl", - "target": "wasip2", + "target": "native", "implementation": "backends::openssl", "operator_new": 0, "hmac": "hmac_sha2_512", - "call": 1, - "openssl_allocations": 18 + "call": 2, + "openssl_allocations": 20 }, { - "operation": "hkdf", + "operation": "hkdf_pieces", "backend": "openssl", - "target": "wasip2", + "target": "native", "implementation": "backends::openssl", "operator_new": 0, "hmac": "hmac_sha2_512", "call": 2, - "openssl_allocations": 24 + "openssl_allocations": 30 + }, + { + "operation": "hkdf", + "backend": "openssl", + "target": "native", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha3_256", + "call": 1, + "openssl_allocations": 30 + }, + { + "operation": "pbkdf2", + "backend": "openssl", + "target": "native", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha3_256", + "call": 1, + "openssl_allocations": 18 + }, + { + "operation": "hkdf_extract_pieces", + "backend": "openssl", + "target": "native", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha3_256", + "call": 1, + "openssl_allocations": 10 + }, + { + "operation": "hkdf_expand_pieces", + "backend": "openssl", + "target": "native", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha3_256", + "call": 1, + "openssl_allocations": 30 + }, + { + "operation": "hkdf_pieces", + "backend": "openssl", + "target": "native", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha3_256", + "call": 1, + "openssl_allocations": 40 + }, + { + "operation": "hkdf", + "backend": "openssl", + "target": "native", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha3_256", + "call": 2, + "openssl_allocations": 24 + }, + { + "operation": "pbkdf2", + "backend": "openssl", + "target": "native", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha3_256", + "call": 2, + "openssl_allocations": 18 + }, + { + "operation": "hkdf_extract_pieces", + "backend": "openssl", + "target": "native", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha3_256", + "call": 2, + "openssl_allocations": 10 + }, + { + "operation": "hkdf_expand_pieces", + "backend": "openssl", + "target": "native", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha3_256", + "call": 2, + "openssl_allocations": 30 + }, + { + "operation": "hkdf_pieces", + "backend": "openssl", + "target": "native", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha3_256", + "call": 2, + "openssl_allocations": 40 + }, + { + "operation": "hkdf", + "backend": "openssl", + "target": "native", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_blake2b_512", + "call": 1, + "openssl_allocations": 30 + }, + { + "operation": "pbkdf2", + "backend": "openssl", + "target": "native", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_blake2b_512", + "call": 1, + "openssl_allocations": 18 + }, + { + "operation": "hkdf_extract_pieces", + "backend": "openssl", + "target": "native", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_blake2b_512", + "call": 1, + "openssl_allocations": 10 + }, + { + "operation": "hkdf_expand_pieces", + "backend": "openssl", + "target": "native", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_blake2b_512", + "call": 1, + "openssl_allocations": 20 + }, + { + "operation": "hkdf_pieces", + "backend": "openssl", + "target": "native", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_blake2b_512", + "call": 1, + "openssl_allocations": 30 + }, + { + "operation": "hkdf", + "backend": "openssl", + "target": "native", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_blake2b_512", + "call": 2, + "openssl_allocations": 24 + }, + { + "operation": "pbkdf2", + "backend": "openssl", + "target": "native", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_blake2b_512", + "call": 2, + "openssl_allocations": 18 + }, + { + "operation": "hkdf_extract_pieces", + "backend": "openssl", + "target": "native", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_blake2b_512", + "call": 2, + "openssl_allocations": 10 + }, + { + "operation": "hkdf_expand_pieces", + "backend": "openssl", + "target": "native", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_blake2b_512", + "call": 2, + "openssl_allocations": 20 + }, + { + "operation": "hkdf_pieces", + "backend": "openssl", + "target": "native", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_blake2b_512", + "call": 2, + "openssl_allocations": 30 + }, + { + "operation": "sodium_init", + "backend": "sodium", + "target": "wasip2", + "implementation": "backends::sodium", + "operator_new": 0, + "c_allocator_calls": 1, + "c_allocator_counted": true + }, + { + "operation": "argon2id", + "backend": "sodium", + "target": "wasip2", + "implementation": "backends::sodium", + "operator_new": 0, + "c_allocator_calls": 5, + "c_allocator_counted": true + }, + { + "operation": "scrypt", + "backend": "sodium", + "target": "wasip2", + "implementation": "backends::sodium", + "operator_new": 0, + "c_allocator_calls": 1, + "c_allocator_counted": true + }, + { + "operation": "hkdf", + "backend": "openssl", + "target": "wasip2", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha2_256", + "call": 1, + "openssl_allocations": 3960 + }, + { + "operation": "pbkdf2", + "backend": "openssl", + "target": "wasip2", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha2_256", + "call": 1, + "openssl_allocations": 30 + }, + { + "operation": "hkdf_extract_pieces", + "backend": "openssl", + "target": "wasip2", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha2_256", + "call": 1, + "openssl_allocations": 10 + }, + { + "operation": "hkdf_expand_pieces", + "backend": "openssl", + "target": "wasip2", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha2_256", + "call": 1, + "openssl_allocations": 30 + }, + { + "operation": "hkdf_pieces", + "backend": "openssl", + "target": "wasip2", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha2_256", + "call": 1, + "openssl_allocations": 40 + }, + { + "operation": "hkdf", + "backend": "openssl", + "target": "wasip2", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha2_256", + "call": 2, + "openssl_allocations": 24 + }, + { + "operation": "pbkdf2", + "backend": "openssl", + "target": "wasip2", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha2_256", + "call": 2, + "openssl_allocations": 18 + }, + { + "operation": "hkdf_extract_pieces", + "backend": "openssl", + "target": "wasip2", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha2_256", + "call": 2, + "openssl_allocations": 10 + }, + { + "operation": "hkdf_expand_pieces", + "backend": "openssl", + "target": "wasip2", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha2_256", + "call": 2, + "openssl_allocations": 30 + }, + { + "operation": "hkdf_pieces", + "backend": "openssl", + "target": "wasip2", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha2_256", + "call": 2, + "openssl_allocations": 40 + }, + { + "operation": "hkdf", + "backend": "openssl", + "target": "wasip2", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha2_512", + "call": 1, + "openssl_allocations": 30 + }, + { + "operation": "pbkdf2", + "backend": "openssl", + "target": "wasip2", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha2_512", + "call": 1, + "openssl_allocations": 18 + }, + { + "operation": "hkdf_extract_pieces", + "backend": "openssl", + "target": "wasip2", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha2_512", + "call": 1, + "openssl_allocations": 10 + }, + { + "operation": "hkdf_expand_pieces", + "backend": "openssl", + "target": "wasip2", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha2_512", + "call": 1, + "openssl_allocations": 20 + }, + { + "operation": "hkdf_pieces", + "backend": "openssl", + "target": "wasip2", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha2_512", + "call": 1, + "openssl_allocations": 30 + }, + { + "operation": "hkdf", + "backend": "openssl", + "target": "wasip2", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha2_512", + "call": 2, + "openssl_allocations": 24 + }, + { + "operation": "pbkdf2", + "backend": "openssl", + "target": "wasip2", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha2_512", + "call": 2, + "openssl_allocations": 18 + }, + { + "operation": "hkdf_extract_pieces", + "backend": "openssl", + "target": "wasip2", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha2_512", + "call": 2, + "openssl_allocations": 10 + }, + { + "operation": "hkdf_expand_pieces", + "backend": "openssl", + "target": "wasip2", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha2_512", + "call": 2, + "openssl_allocations": 20 + }, + { + "operation": "hkdf_pieces", + "backend": "openssl", + "target": "wasip2", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha2_512", + "call": 2, + "openssl_allocations": 30 + }, + { + "operation": "hkdf", + "backend": "openssl", + "target": "wasip2", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha3_256", + "call": 1, + "openssl_allocations": 30 + }, + { + "operation": "pbkdf2", + "backend": "openssl", + "target": "wasip2", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha3_256", + "call": 1, + "openssl_allocations": 18 + }, + { + "operation": "hkdf_extract_pieces", + "backend": "openssl", + "target": "wasip2", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha3_256", + "call": 1, + "openssl_allocations": 10 + }, + { + "operation": "hkdf_expand_pieces", + "backend": "openssl", + "target": "wasip2", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha3_256", + "call": 1, + "openssl_allocations": 30 + }, + { + "operation": "hkdf_pieces", + "backend": "openssl", + "target": "wasip2", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha3_256", + "call": 1, + "openssl_allocations": 40 + }, + { + "operation": "hkdf", + "backend": "openssl", + "target": "wasip2", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha3_256", + "call": 2, + "openssl_allocations": 24 }, { "operation": "pbkdf2", @@ -4049,17 +5403,47 @@ "target": "wasip2", "implementation": "backends::openssl", "operator_new": 0, - "hmac": "hmac_sha2_512", + "hmac": "hmac_sha3_256", "call": 2, "openssl_allocations": 18 }, { - "operation": "hkdf", + "operation": "hkdf_extract_pieces", + "backend": "openssl", + "target": "wasip2", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha3_256", + "call": 2, + "openssl_allocations": 10 + }, + { + "operation": "hkdf_expand_pieces", + "backend": "openssl", + "target": "wasip2", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha3_256", + "call": 2, + "openssl_allocations": 30 + }, + { + "operation": "hkdf_pieces", "backend": "openssl", "target": "wasip2", "implementation": "backends::openssl", "operator_new": 0, "hmac": "hmac_sha3_256", + "call": 2, + "openssl_allocations": 40 + }, + { + "operation": "hkdf", + "backend": "openssl", + "target": "wasip2", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_blake2b_512", "call": 1, "openssl_allocations": 30 }, @@ -4069,17 +5453,47 @@ "target": "wasip2", "implementation": "backends::openssl", "operator_new": 0, - "hmac": "hmac_sha3_256", + "hmac": "hmac_blake2b_512", "call": 1, "openssl_allocations": 18 }, + { + "operation": "hkdf_extract_pieces", + "backend": "openssl", + "target": "wasip2", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_blake2b_512", + "call": 1, + "openssl_allocations": 10 + }, + { + "operation": "hkdf_expand_pieces", + "backend": "openssl", + "target": "wasip2", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_blake2b_512", + "call": 1, + "openssl_allocations": 20 + }, + { + "operation": "hkdf_pieces", + "backend": "openssl", + "target": "wasip2", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_blake2b_512", + "call": 1, + "openssl_allocations": 30 + }, { "operation": "hkdf", "backend": "openssl", "target": "wasip2", "implementation": "backends::openssl", "operator_new": 0, - "hmac": "hmac_sha3_256", + "hmac": "hmac_blake2b_512", "call": 2, "openssl_allocations": 24 }, @@ -4089,136 +5503,316 @@ "target": "wasip2", "implementation": "backends::openssl", "operator_new": 0, - "hmac": "hmac_sha3_256", + "hmac": "hmac_blake2b_512", "call": 2, "openssl_allocations": 18 }, { - "operation": "hkdf", + "operation": "hkdf_extract_pieces", + "backend": "openssl", + "target": "wasip2", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_blake2b_512", + "call": 2, + "openssl_allocations": 10 + }, + { + "operation": "hkdf_expand_pieces", + "backend": "openssl", + "target": "wasip2", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_blake2b_512", + "call": 2, + "openssl_allocations": 20 + }, + { + "operation": "hkdf_pieces", "backend": "openssl", "target": "wasip2", "implementation": "backends::openssl", "operator_new": 0, "hmac": "hmac_blake2b_512", + "call": 2, + "openssl_allocations": 30 + }, + { + "operation": "sodium_init", + "backend": "sodium", + "target": "wasip3", + "implementation": "backends::sodium", + "operator_new": 0, + "c_allocator_calls": 1, + "c_allocator_counted": true + }, + { + "operation": "argon2id", + "backend": "sodium", + "target": "wasip3", + "implementation": "backends::sodium", + "operator_new": 0, + "c_allocator_calls": 5, + "c_allocator_counted": true + }, + { + "operation": "scrypt", + "backend": "sodium", + "target": "wasip3", + "implementation": "backends::sodium", + "operator_new": 0, + "c_allocator_calls": 1, + "c_allocator_counted": true + }, + { + "operation": "hkdf", + "backend": "openssl", + "target": "wasip3", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha2_256", + "call": 1, + "openssl_allocations": 3960 + }, + { + "operation": "pbkdf2", + "backend": "openssl", + "target": "wasip3", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha2_256", + "call": 1, + "openssl_allocations": 30 + }, + { + "operation": "hkdf_extract_pieces", + "backend": "openssl", + "target": "wasip3", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha2_256", + "call": 1, + "openssl_allocations": 10 + }, + { + "operation": "hkdf_expand_pieces", + "backend": "openssl", + "target": "wasip3", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha2_256", "call": 1, "openssl_allocations": 30 }, + { + "operation": "hkdf_pieces", + "backend": "openssl", + "target": "wasip3", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha2_256", + "call": 1, + "openssl_allocations": 40 + }, + { + "operation": "hkdf", + "backend": "openssl", + "target": "wasip3", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha2_256", + "call": 2, + "openssl_allocations": 24 + }, { "operation": "pbkdf2", "backend": "openssl", - "target": "wasip2", + "target": "wasip3", "implementation": "backends::openssl", "operator_new": 0, - "hmac": "hmac_blake2b_512", + "hmac": "hmac_sha2_256", + "call": 2, + "openssl_allocations": 18 + }, + { + "operation": "hkdf_extract_pieces", + "backend": "openssl", + "target": "wasip3", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha2_256", + "call": 2, + "openssl_allocations": 10 + }, + { + "operation": "hkdf_expand_pieces", + "backend": "openssl", + "target": "wasip3", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha2_256", + "call": 2, + "openssl_allocations": 30 + }, + { + "operation": "hkdf_pieces", + "backend": "openssl", + "target": "wasip3", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha2_256", + "call": 2, + "openssl_allocations": 40 + }, + { + "operation": "hkdf", + "backend": "openssl", + "target": "wasip3", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha2_512", + "call": 1, + "openssl_allocations": 30 + }, + { + "operation": "pbkdf2", + "backend": "openssl", + "target": "wasip3", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha2_512", + "call": 1, + "openssl_allocations": 18 + }, + { + "operation": "hkdf_extract_pieces", + "backend": "openssl", + "target": "wasip3", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha2_512", + "call": 1, + "openssl_allocations": 10 + }, + { + "operation": "hkdf_expand_pieces", + "backend": "openssl", + "target": "wasip3", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha2_512", + "call": 1, + "openssl_allocations": 20 + }, + { + "operation": "hkdf_pieces", + "backend": "openssl", + "target": "wasip3", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_sha2_512", "call": 1, - "openssl_allocations": 18 + "openssl_allocations": 30 }, { "operation": "hkdf", "backend": "openssl", - "target": "wasip2", + "target": "wasip3", "implementation": "backends::openssl", "operator_new": 0, - "hmac": "hmac_blake2b_512", + "hmac": "hmac_sha2_512", "call": 2, "openssl_allocations": 24 }, { "operation": "pbkdf2", "backend": "openssl", - "target": "wasip2", + "target": "wasip3", "implementation": "backends::openssl", "operator_new": 0, - "hmac": "hmac_blake2b_512", + "hmac": "hmac_sha2_512", "call": 2, "openssl_allocations": 18 }, { - "operation": "sodium_init", - "backend": "sodium", - "target": "wasip3", - "implementation": "backends::sodium", - "operator_new": 0, - "c_allocator_calls": 1, - "c_allocator_counted": true - }, - { - "operation": "argon2id", - "backend": "sodium", + "operation": "hkdf_extract_pieces", + "backend": "openssl", "target": "wasip3", - "implementation": "backends::sodium", + "implementation": "backends::openssl", "operator_new": 0, - "c_allocator_calls": 5, - "c_allocator_counted": true + "hmac": "hmac_sha2_512", + "call": 2, + "openssl_allocations": 10 }, { - "operation": "scrypt", - "backend": "sodium", + "operation": "hkdf_expand_pieces", + "backend": "openssl", "target": "wasip3", - "implementation": "backends::sodium", + "implementation": "backends::openssl", "operator_new": 0, - "c_allocator_calls": 1, - "c_allocator_counted": true + "hmac": "hmac_sha2_512", + "call": 2, + "openssl_allocations": 20 }, { - "operation": "hkdf", + "operation": "hkdf_pieces", "backend": "openssl", "target": "wasip3", "implementation": "backends::openssl", "operator_new": 0, - "hmac": "hmac_sha2_256", - "call": 1, - "openssl_allocations": 3960 + "hmac": "hmac_sha2_512", + "call": 2, + "openssl_allocations": 30 }, { - "operation": "pbkdf2", + "operation": "hkdf", "backend": "openssl", "target": "wasip3", "implementation": "backends::openssl", "operator_new": 0, - "hmac": "hmac_sha2_256", + "hmac": "hmac_sha3_256", "call": 1, "openssl_allocations": 30 }, { - "operation": "hkdf", + "operation": "pbkdf2", "backend": "openssl", "target": "wasip3", "implementation": "backends::openssl", "operator_new": 0, - "hmac": "hmac_sha2_256", - "call": 2, - "openssl_allocations": 24 + "hmac": "hmac_sha3_256", + "call": 1, + "openssl_allocations": 18 }, { - "operation": "pbkdf2", + "operation": "hkdf_extract_pieces", "backend": "openssl", "target": "wasip3", "implementation": "backends::openssl", "operator_new": 0, - "hmac": "hmac_sha2_256", - "call": 2, - "openssl_allocations": 18 + "hmac": "hmac_sha3_256", + "call": 1, + "openssl_allocations": 10 }, { - "operation": "hkdf", + "operation": "hkdf_expand_pieces", "backend": "openssl", "target": "wasip3", "implementation": "backends::openssl", "operator_new": 0, - "hmac": "hmac_sha2_512", + "hmac": "hmac_sha3_256", "call": 1, "openssl_allocations": 30 }, { - "operation": "pbkdf2", + "operation": "hkdf_pieces", "backend": "openssl", "target": "wasip3", "implementation": "backends::openssl", "operator_new": 0, - "hmac": "hmac_sha2_512", + "hmac": "hmac_sha3_256", "call": 1, - "openssl_allocations": 18 + "openssl_allocations": 40 }, { "operation": "hkdf", @@ -4226,7 +5820,7 @@ "target": "wasip3", "implementation": "backends::openssl", "operator_new": 0, - "hmac": "hmac_sha2_512", + "hmac": "hmac_sha3_256", "call": 2, "openssl_allocations": 24 }, @@ -4236,39 +5830,49 @@ "target": "wasip3", "implementation": "backends::openssl", "operator_new": 0, - "hmac": "hmac_sha2_512", + "hmac": "hmac_sha3_256", "call": 2, "openssl_allocations": 18 }, { - "operation": "hkdf", + "operation": "hkdf_extract_pieces", "backend": "openssl", "target": "wasip3", "implementation": "backends::openssl", "operator_new": 0, "hmac": "hmac_sha3_256", - "call": 1, - "openssl_allocations": 30 + "call": 2, + "openssl_allocations": 10 }, { - "operation": "pbkdf2", + "operation": "hkdf_expand_pieces", "backend": "openssl", "target": "wasip3", "implementation": "backends::openssl", "operator_new": 0, "hmac": "hmac_sha3_256", - "call": 1, - "openssl_allocations": 18 + "call": 2, + "openssl_allocations": 30 }, { - "operation": "hkdf", + "operation": "hkdf_pieces", "backend": "openssl", "target": "wasip3", "implementation": "backends::openssl", "operator_new": 0, "hmac": "hmac_sha3_256", "call": 2, - "openssl_allocations": 24 + "openssl_allocations": 40 + }, + { + "operation": "hkdf", + "backend": "openssl", + "target": "wasip3", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_blake2b_512", + "call": 1, + "openssl_allocations": 30 }, { "operation": "pbkdf2", @@ -4276,29 +5880,39 @@ "target": "wasip3", "implementation": "backends::openssl", "operator_new": 0, - "hmac": "hmac_sha3_256", - "call": 2, + "hmac": "hmac_blake2b_512", + "call": 1, "openssl_allocations": 18 }, { - "operation": "hkdf", + "operation": "hkdf_extract_pieces", "backend": "openssl", "target": "wasip3", "implementation": "backends::openssl", "operator_new": 0, "hmac": "hmac_blake2b_512", "call": 1, - "openssl_allocations": 30 + "openssl_allocations": 10 }, { - "operation": "pbkdf2", + "operation": "hkdf_expand_pieces", "backend": "openssl", "target": "wasip3", "implementation": "backends::openssl", "operator_new": 0, "hmac": "hmac_blake2b_512", "call": 1, - "openssl_allocations": 18 + "openssl_allocations": 20 + }, + { + "operation": "hkdf_pieces", + "backend": "openssl", + "target": "wasip3", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_blake2b_512", + "call": 1, + "openssl_allocations": 30 }, { "operation": "hkdf", @@ -4320,6 +5934,36 @@ "call": 2, "openssl_allocations": 18 }, + { + "operation": "hkdf_extract_pieces", + "backend": "openssl", + "target": "wasip3", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_blake2b_512", + "call": 2, + "openssl_allocations": 10 + }, + { + "operation": "hkdf_expand_pieces", + "backend": "openssl", + "target": "wasip3", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_blake2b_512", + "call": 2, + "openssl_allocations": 20 + }, + { + "operation": "hkdf_pieces", + "backend": "openssl", + "target": "wasip3", + "implementation": "backends::openssl", + "operator_new": 0, + "hmac": "hmac_blake2b_512", + "call": 2, + "openssl_allocations": 30 + }, { "operation": "sodium_init", "backend": "sodium", @@ -6096,6 +7740,39 @@ "c_allocator_calls": 27, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_md5_128", + "call": 1, + "operator_new": 4, + "c_allocator_calls": 7, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_md5_128", + "call": 1, + "operator_new": 4, + "c_allocator_calls": 11, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_md5_128", + "call": 1, + "operator_new": 8, + "c_allocator_calls": 18, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -6151,6 +7828,39 @@ "c_allocator_calls": 27, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_md5_128", + "call": 2, + "operator_new": 4, + "c_allocator_calls": 7, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_md5_128", + "call": 2, + "operator_new": 4, + "c_allocator_calls": 11, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_md5_128", + "call": 2, + "operator_new": 8, + "c_allocator_calls": 18, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -6206,6 +7916,39 @@ "c_allocator_calls": 34, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha1_160", + "call": 1, + "operator_new": 7, + "c_allocator_calls": 10, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha1_160", + "call": 1, + "operator_new": 7, + "c_allocator_calls": 14, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha1_160", + "call": 1, + "operator_new": 14, + "c_allocator_calls": 24, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -6235,30 +7978,63 @@ "implementation": "backends::botan", "tag": "hmac_sha1_160", "call": 2, - "operator_new": 30, - "c_allocator_calls": 39, + "operator_new": 30, + "c_allocator_calls": 39, + "c_allocator_counted": true + }, + { + "operation": "pbkdf2", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha1_160", + "call": 2, + "operator_new": 29, + "c_allocator_calls": 34, + "c_allocator_counted": true + }, + { + "operation": "kbkdf", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha1_160", + "call": 2, + "operator_new": 30, + "c_allocator_calls": 34, + "c_allocator_counted": true + }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha1_160", + "call": 2, + "operator_new": 7, + "c_allocator_calls": 10, "c_allocator_counted": true }, { - "operation": "pbkdf2", + "operation": "hkdf_expand_pieces", "backend": "botan", "target": "emscripten", "implementation": "backends::botan", "tag": "hmac_sha1_160", "call": 2, - "operator_new": 29, - "c_allocator_calls": 34, + "operator_new": 7, + "c_allocator_calls": 14, "c_allocator_counted": true }, { - "operation": "kbkdf", + "operation": "hkdf_pieces", "backend": "botan", "target": "emscripten", "implementation": "backends::botan", "tag": "hmac_sha1_160", "call": 2, - "operator_new": 30, - "c_allocator_calls": 34, + "operator_new": 14, + "c_allocator_calls": 24, "c_allocator_counted": true }, { @@ -6316,6 +8092,39 @@ "c_allocator_calls": 34, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha2_224", + "call": 1, + "operator_new": 7, + "c_allocator_calls": 10, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha2_224", + "call": 1, + "operator_new": 7, + "c_allocator_calls": 12, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha2_224", + "call": 1, + "operator_new": 14, + "c_allocator_calls": 22, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -6371,6 +8180,39 @@ "c_allocator_calls": 34, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha2_224", + "call": 2, + "operator_new": 7, + "c_allocator_calls": 10, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha2_224", + "call": 2, + "operator_new": 7, + "c_allocator_calls": 12, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha2_224", + "call": 2, + "operator_new": 14, + "c_allocator_calls": 22, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -6426,6 +8268,39 @@ "c_allocator_calls": 34, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha2_256", + "call": 1, + "operator_new": 7, + "c_allocator_calls": 10, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha2_256", + "call": 1, + "operator_new": 7, + "c_allocator_calls": 12, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha2_256", + "call": 1, + "operator_new": 14, + "c_allocator_calls": 22, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -6481,6 +8356,39 @@ "c_allocator_calls": 34, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha2_256", + "call": 2, + "operator_new": 7, + "c_allocator_calls": 10, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha2_256", + "call": 2, + "operator_new": 7, + "c_allocator_calls": 12, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha2_256", + "call": 2, + "operator_new": 14, + "c_allocator_calls": 22, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -6536,6 +8444,39 @@ "c_allocator_calls": 33, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha2_384", + "call": 1, + "operator_new": 7, + "c_allocator_calls": 10, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha2_384", + "call": 1, + "operator_new": 7, + "c_allocator_calls": 10, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha2_384", + "call": 1, + "operator_new": 14, + "c_allocator_calls": 20, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -6591,6 +8532,39 @@ "c_allocator_calls": 33, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha2_384", + "call": 2, + "operator_new": 7, + "c_allocator_calls": 10, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha2_384", + "call": 2, + "operator_new": 7, + "c_allocator_calls": 10, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha2_384", + "call": 2, + "operator_new": 14, + "c_allocator_calls": 20, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -6646,6 +8620,39 @@ "c_allocator_calls": 34, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha2_512", + "call": 1, + "operator_new": 7, + "c_allocator_calls": 10, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha2_512", + "call": 1, + "operator_new": 7, + "c_allocator_calls": 10, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha2_512", + "call": 1, + "operator_new": 14, + "c_allocator_calls": 20, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -6675,30 +8682,63 @@ "implementation": "backends::botan", "tag": "hmac_sha2_512", "call": 2, - "operator_new": 30, - "c_allocator_calls": 39, + "operator_new": 30, + "c_allocator_calls": 39, + "c_allocator_counted": true + }, + { + "operation": "pbkdf2", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha2_512", + "call": 2, + "operator_new": 29, + "c_allocator_calls": 34, + "c_allocator_counted": true + }, + { + "operation": "kbkdf", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha2_512", + "call": 2, + "operator_new": 30, + "c_allocator_calls": 34, + "c_allocator_counted": true + }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha2_512", + "call": 2, + "operator_new": 7, + "c_allocator_calls": 10, "c_allocator_counted": true }, { - "operation": "pbkdf2", + "operation": "hkdf_expand_pieces", "backend": "botan", "target": "emscripten", "implementation": "backends::botan", "tag": "hmac_sha2_512", "call": 2, - "operator_new": 29, - "c_allocator_calls": 34, + "operator_new": 7, + "c_allocator_calls": 10, "c_allocator_counted": true }, { - "operation": "kbkdf", + "operation": "hkdf_pieces", "backend": "botan", "target": "emscripten", "implementation": "backends::botan", "tag": "hmac_sha2_512", "call": 2, - "operator_new": 30, - "c_allocator_calls": 34, + "operator_new": 14, + "c_allocator_calls": 20, "c_allocator_counted": true }, { @@ -6756,6 +8796,39 @@ "c_allocator_calls": 42, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha2_512_256", + "call": 1, + "operator_new": 9, + "c_allocator_calls": 12, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha2_512_256", + "call": 1, + "operator_new": 9, + "c_allocator_calls": 14, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha2_512_256", + "call": 1, + "operator_new": 18, + "c_allocator_calls": 26, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -6811,6 +8884,39 @@ "c_allocator_calls": 42, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha2_512_256", + "call": 2, + "operator_new": 9, + "c_allocator_calls": 12, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha2_512_256", + "call": 2, + "operator_new": 9, + "c_allocator_calls": 14, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha2_512_256", + "call": 2, + "operator_new": 18, + "c_allocator_calls": 26, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -6866,6 +8972,39 @@ "c_allocator_calls": 39, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha3_224", + "call": 1, + "operator_new": 10, + "c_allocator_calls": 12, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha3_224", + "call": 1, + "operator_new": 10, + "c_allocator_calls": 14, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha3_224", + "call": 1, + "operator_new": 20, + "c_allocator_calls": 26, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -6921,6 +9060,39 @@ "c_allocator_calls": 39, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha3_224", + "call": 2, + "operator_new": 10, + "c_allocator_calls": 12, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha3_224", + "call": 2, + "operator_new": 10, + "c_allocator_calls": 14, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha3_224", + "call": 2, + "operator_new": 20, + "c_allocator_calls": 26, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -6976,6 +9148,39 @@ "c_allocator_calls": 39, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha3_256", + "call": 1, + "operator_new": 10, + "c_allocator_calls": 12, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha3_256", + "call": 1, + "operator_new": 10, + "c_allocator_calls": 14, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha3_256", + "call": 1, + "operator_new": 20, + "c_allocator_calls": 26, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -7031,6 +9236,39 @@ "c_allocator_calls": 39, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha3_256", + "call": 2, + "operator_new": 10, + "c_allocator_calls": 12, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha3_256", + "call": 2, + "operator_new": 10, + "c_allocator_calls": 14, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha3_256", + "call": 2, + "operator_new": 20, + "c_allocator_calls": 26, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -7086,6 +9324,39 @@ "c_allocator_calls": 38, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha3_384", + "call": 1, + "operator_new": 10, + "c_allocator_calls": 12, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha3_384", + "call": 1, + "operator_new": 10, + "c_allocator_calls": 12, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha3_384", + "call": 1, + "operator_new": 20, + "c_allocator_calls": 24, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -7109,36 +9380,69 @@ "c_allocator_counted": true }, { - "operation": "hkdf", + "operation": "hkdf", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha3_384", + "call": 2, + "operator_new": 36, + "c_allocator_calls": 41, + "c_allocator_counted": true + }, + { + "operation": "pbkdf2", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha3_384", + "call": 2, + "operator_new": 36, + "c_allocator_calls": 39, + "c_allocator_counted": true + }, + { + "operation": "kbkdf", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha3_384", + "call": 2, + "operator_new": 36, + "c_allocator_calls": 38, + "c_allocator_counted": true + }, + { + "operation": "hkdf_extract_pieces", "backend": "botan", "target": "emscripten", "implementation": "backends::botan", "tag": "hmac_sha3_384", "call": 2, - "operator_new": 36, - "c_allocator_calls": 41, + "operator_new": 10, + "c_allocator_calls": 12, "c_allocator_counted": true }, { - "operation": "pbkdf2", + "operation": "hkdf_expand_pieces", "backend": "botan", "target": "emscripten", "implementation": "backends::botan", "tag": "hmac_sha3_384", "call": 2, - "operator_new": 36, - "c_allocator_calls": 39, + "operator_new": 10, + "c_allocator_calls": 12, "c_allocator_counted": true }, { - "operation": "kbkdf", + "operation": "hkdf_pieces", "backend": "botan", "target": "emscripten", "implementation": "backends::botan", "tag": "hmac_sha3_384", "call": 2, - "operator_new": 36, - "c_allocator_calls": 38, + "operator_new": 20, + "c_allocator_calls": 24, "c_allocator_counted": true }, { @@ -7196,6 +9500,39 @@ "c_allocator_calls": 39, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha3_512", + "call": 1, + "operator_new": 10, + "c_allocator_calls": 12, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha3_512", + "call": 1, + "operator_new": 10, + "c_allocator_calls": 12, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha3_512", + "call": 1, + "operator_new": 20, + "c_allocator_calls": 24, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -7251,6 +9588,39 @@ "c_allocator_calls": 39, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha3_512", + "call": 2, + "operator_new": 10, + "c_allocator_calls": 12, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha3_512", + "call": 2, + "operator_new": 10, + "c_allocator_calls": 12, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_sha3_512", + "call": 2, + "operator_new": 20, + "c_allocator_calls": 24, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -7306,6 +9676,39 @@ "c_allocator_calls": 34, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_ripemd_160", + "call": 1, + "operator_new": 7, + "c_allocator_calls": 10, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_ripemd_160", + "call": 1, + "operator_new": 7, + "c_allocator_calls": 14, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_ripemd_160", + "call": 1, + "operator_new": 14, + "c_allocator_calls": 24, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -7361,6 +9764,39 @@ "c_allocator_calls": 34, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_ripemd_160", + "call": 2, + "operator_new": 7, + "c_allocator_calls": 10, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_ripemd_160", + "call": 2, + "operator_new": 7, + "c_allocator_calls": 14, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_ripemd_160", + "call": 2, + "operator_new": 14, + "c_allocator_calls": 24, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -7416,6 +9852,39 @@ "c_allocator_calls": 47, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_blake2b_512", + "call": 1, + "operator_new": 13, + "c_allocator_calls": 16, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_blake2b_512", + "call": 1, + "operator_new": 13, + "c_allocator_calls": 16, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_blake2b_512", + "call": 1, + "operator_new": 26, + "c_allocator_calls": 32, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -7471,6 +9940,39 @@ "c_allocator_calls": 47, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_blake2b_512", + "call": 2, + "operator_new": 13, + "c_allocator_calls": 16, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_blake2b_512", + "call": 2, + "operator_new": 13, + "c_allocator_calls": 16, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_blake2b_512", + "call": 2, + "operator_new": 26, + "c_allocator_calls": 32, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -7526,6 +10028,39 @@ "c_allocator_calls": 46, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_blake2s_256", + "call": 1, + "operator_new": 13, + "c_allocator_calls": 15, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_blake2s_256", + "call": 1, + "operator_new": 13, + "c_allocator_calls": 17, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_blake2s_256", + "call": 1, + "operator_new": 26, + "c_allocator_calls": 32, + "c_allocator_counted": true + }, { "operation": "hkdf_extract", "backend": "botan", @@ -7581,6 +10116,39 @@ "c_allocator_calls": 46, "c_allocator_counted": true }, + { + "operation": "hkdf_extract_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_blake2s_256", + "call": 2, + "operator_new": 13, + "c_allocator_calls": 15, + "c_allocator_counted": true + }, + { + "operation": "hkdf_expand_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_blake2s_256", + "call": 2, + "operator_new": 13, + "c_allocator_calls": 17, + "c_allocator_counted": true + }, + { + "operation": "hkdf_pieces", + "backend": "botan", + "target": "emscripten", + "implementation": "backends::botan", + "tag": "hmac_blake2s_256", + "call": 2, + "operator_new": 26, + "c_allocator_calls": 32, + "c_allocator_counted": true + }, { "operation": "sskdf", "backend": "botan", diff --git a/doc/password_hashing.adoc b/doc/password_hashing.adoc index 8aba2d2..df09251 100644 --- a/doc/password_hashing.adoc +++ b/doc/password_hashing.adoc @@ -172,7 +172,7 @@ include::{examples}/argon2_botan.expected[] *Pitfalls.* -* *Two units of memory.* `argon2_parameters::memory_kib` counts KiB, as +* *Two units of memory.* `argon2_parameters::memory_kibibytes` counts KiB, as RFC 9106's m does; `argon2id_parameters::memory`, the parameter of `argon2id`, counts bytes. The 268,435,456 bytes of `argon2id_moderate` are 262,144 KiB. * *Every parameter changes the tag.* The lanes, the secret and the associated @@ -216,8 +216,8 @@ include::generated/backends-argon2.adoc[] scrypt (Percival, 2009; RFC 7914) was the first memory-hard password hash: it fills a buffer of 128 r N bytes with Salsa20/8 and then reads it in an order that depends on the data, so that an attacker without the memory -recomputes it again and again. Its costs are N (the memory and time, a power -of two), r (the block size) and p (the parallelism). Ethereum's keystore files +recomputes it again and again. Its costs are `cost`, RFC 7914's N (the memory and time, a power +of two), `block_size`, its r, and `parallelism`, its p. Ethereum's keystore files and many disk and backup encryption tools use it. libsodium, which hash runs, recommends Argon2id unless a format demands scrypt. `scrypt` runs libsodium's by default, and OpenSSL's where the call names `backends::openssl` (native, wasip2 diff --git a/example/Jamfile b/example/Jamfile index 3dde4d1..1c719b4 100644 --- a/example/Jamfile +++ b/example/Jamfile @@ -57,6 +57,7 @@ webcpp.example macs_botan.cpp : $(.botan) : native emscripten ; # Key derivation. webcpp.example hkdf.cpp ; +webcpp.example hkdf_pieces.cpp ; webcpp.example hkdf_backends.cpp : /third_party//sodium /third_party//bearssl ; webcpp.example pbkdf2.cpp ; diff --git a/example/argon2_botan.cpp b/example/argon2_botan.cpp index d3c5f01..d71f904 100644 --- a/example/argon2_botan.cpp +++ b/example/argon2_botan.cpp @@ -33,7 +33,7 @@ int main() { context.fill(0x04); hash::argon2_parameters costs{ .passes = 3, - .memory_kib = 32, + .memory_kibibytes = 32, .lanes = 4, .secret = pepper, .associated_data = context, @@ -47,19 +47,19 @@ int main() { // scrypt: RFC 7914, N 1,024, r 8, p 16. std::array key{}; if (!hash::scrypt(key, example::bytes("password"), example::bytes("NaCl"), - {.n = 1024, .r = 8, .p = 16})) { + {.cost = 1024, .block_size = 8, .parallelism = 16})) { return 1; } std::cout << "scrypt " << example::hex(key).substr(0, 32) << "...\n"; // Botan's Argon2 takes at most 128 lanes, which RFC 9106 allows up to 2^24 - 1 of. costs.lanes = 129; - costs.memory_kib = 8 * 129; + costs.memory_kibibytes = 8 * 129; auto const lanes = hash::argon2(tag, password, salt, costs); std::cout << "129 lanes: " << lanes.error().message() << '\n'; // Botan's scrypt takes N up to 2^22. auto const large = hash::scrypt(key, example::bytes("password"), example::bytes("NaCl"), - {.n = 1U << 23U, .r = 2, .p = 1}); + {.cost = 1U << 23U, .block_size = 2, .parallelism = 1}); std::cout << "N 2^23: " << large.error().message() << '\n'; } diff --git a/example/argon2_family.cpp b/example/argon2_family.cpp index 81b47d6..8de238a 100644 --- a/example/argon2_family.cpp +++ b/example/argon2_family.cpp @@ -30,7 +30,7 @@ int main() { auto const password = example::bytes("correct horse battery staple"); // The family counts memory in KiB, as RFC 9106 does: 19,456 KiB are 19 MiB. - hash::argon2_parameters const login{.passes = 2, .memory_kib = 19456}; + hash::argon2_parameters const login{.passes = 2, .memory_kibibytes = 19456}; std::array tag{}; if (!hash::argon2(tag, password, salt, login)) { return 1; @@ -47,14 +47,14 @@ int main() { // Argon2i, only to check tags a system already stored with it; libsodium takes 3 passes or // more. if (!hash::argon2(tag, password, salt, - {.passes = 4, .memory_kib = 32768})) { + {.passes = 4, .memory_kibibytes = 32768})) { return 1; } std::cout << "argon2i " << example::hex(tag) << '\n'; // Four lanes are RFC 9106's, not libsodium's: refused before any work, the tag untouched. auto const refused = hash::argon2( - tag, password, salt, {.passes = 2, .memory_kib = 19456, .lanes = 4}); + tag, password, salt, {.passes = 2, .memory_kibibytes = 19456, .lanes = 4}); if (refused || refused.error() != hash::error::unsupported_by_backend) { return 1; } diff --git a/example/argon2_openssl.cpp b/example/argon2_openssl.cpp index 0b49760..ba417db 100644 --- a/example/argon2_openssl.cpp +++ b/example/argon2_openssl.cpp @@ -36,7 +36,7 @@ int main() { // far more memory; these are the RFC's costs, to check the tag. hash::argon2_parameters const costs{ .passes = 3, - .memory_kib = 32, + .memory_kibibytes = 32, .lanes = 4, .secret = pepper, .associated_data = context, diff --git a/example/async_hkdf.cpp b/example/async_hkdf.cpp index 63d172f..2c21c8a 100644 --- a/example/async_hkdf.cpp +++ b/example/async_hkdf.cpp @@ -24,21 +24,24 @@ #include int main() { - auto const ikm = example::from_hex("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"); + auto const input_key_material = + example::from_hex("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"); auto const salt = example::from_hex("000102030405060708090a0b0c"); - auto const info = example::from_hex("f0f1f2f3f4f5f6f7f8f9"); + auto const application_info = example::from_hex("f0f1f2f3f4f5f6f7f8f9"); webcpp::asio::io_context loop; - // The spans are the program's until the completion: okm and the inputs outlive the loop's run. - std::array okm{}; + // The spans are the program's until the completion: output_key_material and the inputs outlive + // the loop's run. + std::array output_key_material{}; bool returned = false; webcpp::hash::async_hkdf( - loop.get_executor(), okm, salt, ikm, info, [&](boost::system::error_code code) { + loop.get_executor(), output_key_material, salt, input_key_material, application_info, + [&](boost::system::error_code code) { if (code) { std::cerr << code.message() << '\n'; return; } - std::cout << "okm " << example::hex(okm) << '\n'; + std::cout << "okm " << example::hex(output_key_material) << '\n'; std::cout << "completed after the call returned: " << (returned ? "yes" : "no") << '\n'; }); returned = true; diff --git a/example/hkdf.cpp b/example/hkdf.cpp index 52a7632..b5c97b0 100644 --- a/example/hkdf.cpp +++ b/example/hkdf.cpp @@ -20,18 +20,20 @@ int main() { // RFC 5869, appendix A.1. - auto const ikm = example::from_hex("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"); + auto const input_key_material = + example::from_hex("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"); auto const salt = example::from_hex("000102030405060708090a0b0c"); - auto const info = example::from_hex("f0f1f2f3f4f5f6f7f8f9"); + auto const application_info = example::from_hex("f0f1f2f3f4f5f6f7f8f9"); - std::array okm{}; - auto done = webcpp::hash::hkdf(okm, salt, ikm, info); + std::array output_key_material{}; + auto done = webcpp::hash::hkdf( + output_key_material, salt, input_key_material, application_info); if (!done) { std::cerr << done.error().message() << '\n'; return 1; } - std::cout << "okm " << example::hex(okm) << '\n'; - if (example::hex(okm) != + std::cout << "okm " << example::hex(output_key_material) << '\n'; + if (example::hex(output_key_material) != "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865") { return 1; } @@ -39,23 +41,25 @@ int main() { // The two steps of HKDF apart: extract turns the input into a uniform pseudorandom key, and // expand stretches it to the length asked, once per context. A program that needs several // keys from one secret extracts once and expands as many times as it needs. - auto prk = webcpp::hash::hkdf_extract(salt, ikm); - if (!prk) { - std::cerr << prk.error().message() << '\n'; + auto pseudorandom_key = + webcpp::hash::hkdf_extract(salt, input_key_material); + if (!pseudorandom_key) { + std::cerr << pseudorandom_key.error().message() << '\n'; return 1; } std::array again{}; - done = webcpp::hash::hkdf_expand(again, *prk, info); + done = webcpp::hash::hkdf_expand(again, *pseudorandom_key, + application_info); if (!done) { std::cerr << done.error().message() << '\n'; return 1; } - std::cout << "two steps " << (again == okm ? "same" : "different") << '\n'; + std::cout << "two steps " << (again == output_key_material ? "same" : "different") << '\n'; - // The use: one shared secret, two keys. Each key has its own info, so that the encryption - // key and the authentication key are independent: a key used for two purposes can let an - // attack on one purpose break the other. The secret is already uniform (a key agreement's - // output hashed, say), so an empty salt is fine. + // The use: one shared secret, two keys. Each key has its own application_info, so that the + // encryption key and the authentication key are independent: a key used for two purposes can + // let an attack on one purpose break the other. The secret is already uniform (a key + // agreement's output hashed, say), so an empty salt is fine. auto const secret = example::from_hex("202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f"); std::array encryption{}; diff --git a/example/hkdf_backends.cpp b/example/hkdf_backends.cpp index a893b7f..5bbe02a 100644 --- a/example/hkdf_backends.cpp +++ b/example/hkdf_backends.cpp @@ -25,12 +25,13 @@ namespace { // RFC 5869, appendix A.1, on the backend `Backend`. template std::string okm() { - auto const ikm = example::from_hex("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"); + auto const input_key_material = + example::from_hex("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"); auto const salt = example::from_hex("000102030405060708090a0b0c"); - auto const info = example::from_hex("f0f1f2f3f4f5f6f7f8f9"); + auto const application_info = example::from_hex("f0f1f2f3f4f5f6f7f8f9"); std::array out{}; - auto const done = - webcpp::hash::hkdf(out, salt, ikm, info); + auto const done = webcpp::hash::hkdf( + out, salt, input_key_material, application_info); return done ? example::hex(out) : done.error().message(); } diff --git a/example/hkdf_pieces.cpp b/example/hkdf_pieces.cpp new file mode 100644 index 0000000..63d5cb8 --- /dev/null +++ b/example/hkdf_pieces.cpp @@ -0,0 +1,109 @@ +// 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) + +// HKDF over byte pieces: HPKE's LabeledExtract and LabeledExpand (RFC 9180, section 4), each one +// call whose input is its labeled parts, no buffer joined, then HPKE's key schedule in base mode, +// checked against RFC 9180's test vector A.1.1 (DHKEM(X25519, HKDF-SHA256), HKDF-SHA256, +// AES-128-GCM). The three values agree with an independent computation, Python's hmac module +// following RFC 5869 and RFC 9180. + +// tag::example[] +#include "hex.hpp" + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace { + +namespace hash = webcpp::hash; + +using bytes_view = std::span; + +// RFC 9180's version label, "HPKE-v1". +constexpr std::array hpke_v1{'H', 'P', 'K', 'E', '-', 'v', '1'}; + +// The suite's identifier: "HPKE", then the KEM (0x0020, DHKEM(X25519, HKDF-SHA256)), the KDF +// (0x0001, HKDF-SHA256) and the AEAD (0x0001, AES-128-GCM), two bytes each. +constexpr std::array suite_id{'H', 'P', 'K', 'E', 0, 0x20, 0, 1, 0, 1}; + +// LabeledExtract(salt, label, ikm) = Extract(salt, "HPKE-v1" || suite_id || label || ikm): the +// braced list at the call is the input keying material's pieces. +auto labeled_extract(bytes_view salt, std::string_view label, bytes_view ikm) { + return hash::hkdf_extract(salt, + {hpke_v1, suite_id, example::bytes(label), ikm}); +} + +// LabeledExpand(prk, label, info, L) = Expand(prk, I2OSP(L, 2) || "HPKE-v1" || suite_id || label +// || info, L), L the output's size. +auto labeled_expand(std::span output, bytes_view pseudorandom_key, + std::string_view label, bytes_view info) { + // I2OSP(L, 2): the size in two bytes, big-endian. + std::array const length{ + static_cast(output.size() >> 8U), + static_cast(output.size() & 0xffU), + }; + return hash::hkdf_expand( + output, pseudorandom_key, {length, hpke_v1, suite_id, example::bytes(label), info}); +} + +} // namespace + +int main() { + // RFC 9180, A.1.1: the application's info and the KEM's shared secret; no PSK (base mode). + auto const info = example::from_hex("4f6465206f6e2061204772656369616e2055726e"); + auto const shared_secret = + example::from_hex("fe0e18c9f024ce43799ae393c7e8fe8fce9d218875e8227b0187c04e7d2ea1fc"); + bytes_view const no_psk{}; + + // KeySchedule: key_schedule_context = mode || psk_id_hash || info_hash. + auto const psk_id_hash = labeled_extract({}, "psk_id_hash", no_psk); + auto const info_hash = labeled_extract({}, "info_hash", info); + auto const secret = labeled_extract(shared_secret, "secret", no_psk); + if (!psk_id_hash || !info_hash || !secret) { + std::cerr << "extract failed\n"; + return 1; + } + std::vector context{0x00}; // mode_base + context.insert(context.end(), psk_id_hash->begin(), psk_id_hash->end()); + context.insert(context.end(), info_hash->begin(), info_hash->end()); + + std::array key{}; + std::array base_nonce{}; + std::array exporter_secret{}; + if (!labeled_expand(key, *secret, "key", context) || + !labeled_expand(base_nonce, *secret, "base_nonce", context) || + !labeled_expand(exporter_secret, *secret, "exp", context)) { + std::cerr << "expand failed\n"; + return 1; + } + std::cout << "key " << example::hex(key) << '\n'; + std::cout << "base_nonce " << example::hex(base_nonce) << '\n'; + std::cout << "exporter_secret " << example::hex(exporter_secret) << '\n'; + if (example::hex(key) != "4531685d41d65f03dc48f6b8302c05b0" || + example::hex(base_nonce) != "56d890e5accaaf011cff4b7d" || + example::hex(exporter_secret) != + "45ff1c2e220db587171952c0592d5f5ebe103f1561a2614e38f2ffd47e99e3f8") { + return 1; + } + + // The pieces are read as if joined: the same extract over one buffer gives the same key. + std::vector joined(hpke_v1.begin(), hpke_v1.end()); + joined.insert(joined.end(), suite_id.begin(), suite_id.end()); + auto const label = example::bytes("secret"); + joined.insert(joined.end(), label.begin(), label.end()); + auto const from_joined = hash::hkdf_extract(shared_secret, joined); + std::cout << "pieces and joined " + << (from_joined && *from_joined == *secret ? "same" : "different") << '\n'; +} + +// end::example[] diff --git a/example/hkdf_pieces.expected b/example/hkdf_pieces.expected new file mode 100644 index 0000000..68dbb71 --- /dev/null +++ b/example/hkdf_pieces.expected @@ -0,0 +1,4 @@ +key 4531685d41d65f03dc48f6b8302c05b0 +base_nonce 56d890e5accaaf011cff4b7d +exporter_secret 45ff1c2e220db587171952c0592d5f5ebe103f1561a2614e38f2ffd47e99e3f8 +pieces and joined same diff --git a/example/kdfs_botan.cpp b/example/kdfs_botan.cpp index b420495..55489ca 100644 --- a/example/kdfs_botan.cpp +++ b/example/kdfs_botan.cpp @@ -26,15 +26,17 @@ int main() { using hash::backends::botan; // HKDF: RFC 5869, Test Case 1. - auto const ikm = example::from_hex("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"); + auto const input_key_material = + example::from_hex("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"); auto const salt = example::from_hex("000102030405060708090a0b0c"); - auto const info = example::from_hex("f0f1f2f3f4f5f6f7f8f9"); - std::array okm{}; - if (!hash::hkdf(okm, salt, ikm, info)) { + auto const application_info = example::from_hex("f0f1f2f3f4f5f6f7f8f9"); + std::array output_key_material{}; + if (!hash::hkdf(output_key_material, salt, input_key_material, + application_info)) { return 1; } - std::cout << "hkdf " << example::hex(okm) << '\n'; - if (example::hex(okm) != + std::cout << "hkdf " << example::hex(output_key_material) << '\n'; + if (example::hex(output_key_material) != "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf" "34007208d5b887185865") { return 1; diff --git a/example/password_storage.cpp b/example/password_storage.cpp index 055c33f..0bae690 100644 --- a/example/password_storage.cpp +++ b/example/password_storage.cpp @@ -29,9 +29,9 @@ namespace { // What the application stores for a user. Without the costs in the record, the service could not // raise them later: a login verifies an old tag with the costs that made it. struct credential { - std::array salt; - webcpp::hash::argon2id_parameters costs; - std::array tag; + std::array salt{}; + webcpp::hash::argon2id_parameters costs{}; + std::array tag{}; }; // Without a salt of its own per user, one guess tests every user at once, and two users with the diff --git a/example/scrypt.cpp b/example/scrypt.cpp index 2ab6dc0..c248037 100644 --- a/example/scrypt.cpp +++ b/example/scrypt.cpp @@ -22,7 +22,7 @@ int main() { // memory is 128 r N bytes, 1 MiB here. A real password hash uses a larger N. std::array key{}; auto const done = webcpp::hash::scrypt(key, example::bytes("password"), example::bytes("NaCl"), - {.n = 1024, .r = 8, .p = 16}); + {.cost = 1024, .block_size = 8, .parallelism = 16}); if (!done) { std::cerr << done.error().message() << '\n'; return 1; diff --git a/example/scrypt_openssl.cpp b/example/scrypt_openssl.cpp index 6531f98..9f73ee7 100644 --- a/example/scrypt_openssl.cpp +++ b/example/scrypt_openssl.cpp @@ -20,7 +20,8 @@ int main() { std::array key{}; auto const done = webcpp::hash::scrypt( - key, example::bytes("password"), example::bytes("NaCl"), {.n = 1024, .r = 8, .p = 16}); + key, example::bytes("password"), example::bytes("NaCl"), + {.cost = 1024, .block_size = 8, .parallelism = 16}); if (!done) { std::cerr << done.error().message() << '\n'; return 1; diff --git a/include/webcpp/hash.hpp b/include/webcpp/hash.hpp index ebdb9d2..39c1b44 100644 --- a/include/webcpp/hash.hpp +++ b/include/webcpp/hash.hpp @@ -22,6 +22,7 @@ #include #include #include +#include #include #include #include diff --git a/include/webcpp/hash/argon2.hpp b/include/webcpp/hash/argon2.hpp index 847c4a1..a52b1a3 100644 --- a/include/webcpp/hash/argon2.hpp +++ b/include/webcpp/hash/argon2.hpp @@ -59,12 +59,12 @@ namespace webcpp::hash { */ struct argon2id_parameters { /** The number of passes over the memory, t: 1 to 4,294,967,295. */ - std::uint64_t passes; + std::uint64_t passes{}; /** The memory in bytes, m times 1,024: at least 8,192, a multiple of 1,024, at most 4 TiB less 1 KiB (2 GiB on wasm32). */ - std::size_t memory; + std::size_t memory{}; }; /** libsodium's interactive costs: 2 passes over 64 MiB. */ @@ -191,9 +191,9 @@ template > */ struct argon2_parameters { /** The number of passes over the memory, t: at least 1. */ - std::uint32_t passes; - /** The memory in KiB, m: at least 8 times the lanes. */ - std::uint32_t memory_kib; + std::uint32_t passes{}; + /** The memory in kibibytes (KiB), RFC 9106's m: at least 8 times the lanes. */ + std::uint32_t memory_kibibytes{}; /** The degree of parallelism, p: 1 to 16,777,215. */ std::uint32_t lanes = 1; /** The secret, K (a pepper): at most 4,294,967,295 bytes, empty for none. */ @@ -207,7 +207,7 @@ namespace detail { /** The most lanes, 2^24 - 1 (RFC 9106, section 3.1). */ inline constexpr std::uint32_t argon2_max_lanes = 0xffffffU; /** The memory per lane at least, 8 KiB: m is at least 8p (RFC 9106, section 3.1). */ -inline constexpr std::uint64_t argon2_min_memory_kib_per_lane = 8; +inline constexpr std::uint64_t argon2_min_memory_kibibytes_per_lane = 8; /** The shortest tag, 4 bytes (RFC 9106, section 3.1). */ inline constexpr std::uint64_t argon2_min_output = 4; /** The shortest salt, 8 bytes (RFC 9106, section 3.1). */ @@ -226,7 +226,7 @@ bool argon2_engine_takes(std::size_t output_size, std::size_t salt_size, // 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_kib, limits.max_memory_kib) && + !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()) && @@ -259,7 +259,8 @@ template return error::input_too_long; } if (parameters.passes < 1 || parameters.lanes < 1 || parameters.lanes > argon2_max_lanes || - parameters.memory_kib < argon2_min_memory_kib_per_lane * std::uint64_t{parameters.lanes}) { + parameters.memory_kibibytes < + argon2_min_memory_kibibytes_per_lane * std::uint64_t{parameters.lanes}) { return error::invalid_parameters; } if (!argon2_engine_takes(output_size, salt_size, parameters)) { diff --git a/include/webcpp/hash/async.hpp b/include/webcpp/hash/async.hpp index bfdf6c6..8bfa6ba 100644 --- a/include/webcpp/hash/async.hpp +++ b/include/webcpp/hash/async.hpp @@ -10,10 +10,13 @@ so that one call works with a callback, `use_awaitable`, Cobalt's `use_op`, `use_future` and every other completion token. - - The cheap functions, `async_digest`, `async_hmac` and `async_hkdf`, exist on every target for - the algorithms the browser's WebCrypto has (SHA-1, SHA-256, SHA-384, SHA-512, and HMAC and HKDF + - The cheap functions, `async_digest`, `async_hmac`, `async_hkdf_extract`, `async_hkdf_expand` + and `async_hkdf`, each HKDF function also over `byte_pieces`, exist on every target for the + algorithms the browser's WebCrypto has (SHA-1, SHA-256, SHA-384, SHA-512, and HMAC and HKDF over them). On a synchronous backend, their default, they run it at once and complete through a - post on the handler's associated executor, never inside the initiating call. + post on the handler's associated executor, never inside the initiating call; a form over + pieces runs it in the call itself, before the operation is initiated, so that the pieces are + read before the call returns, whatever the completion token. - The heavy functions, `async_argon2id`, `async_argon2`, `async_scrypt`, `async_bcrypt`, `async_bcrypt_pbkdf`, `async_bcrypt_verify` and `async_pbkdf2` on a synchronous backend, run on another thread: they check their guards, post the work to the executor the caller gives (a @@ -48,6 +51,7 @@ #include #include #include +#include #include #include #include @@ -74,6 +78,7 @@ #include #include +#include #include #include #include @@ -125,7 +130,8 @@ inline constexpr bool asynchronous_backend_v = std::is_same_v`, - `hmac`, `hkdf` and `pbkdf2`, each taking the asynchronous function's arguments + `hmac`, `hkdf_extract`, `hkdf_expand`, `hkdf` and `pbkdf2`, each + taking the asynchronous function's arguments (a span, or `byte_pieces` for a form over pieces) and returning its result. @tparam Backend `backends::webcrypto`. @@ -154,6 +160,14 @@ struct async_engine { template static void hmac(Arguments&&... /*arguments*/) noexcept {} + /** Never called: the refusal has stopped the build. */ + template + static void hkdf_extract(Arguments&&... /*arguments*/) noexcept {} + + /** Never called: the refusal has stopped the build. */ + template + static void hkdf_expand(Arguments&&... /*arguments*/) noexcept {} + /** Never called: the refusal has stopped the build. */ template static void hkdf(Arguments&&... /*arguments*/) noexcept {} @@ -251,6 +265,88 @@ auto complete_by_post(Executor const& executor, CompletionToken& token, Operatio post_initiation{}, token, executor, std::move(operation)); } +/** + 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. +*/ +struct code_initiation { + /** + Posts `handler` with `code`. + + @param handler The completion handler. @param executor The I/O executor. + @param 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)); + } +}; + +/** + Completes a form over pieces on a synchronous backend with the code of its work, which the caller + has run in the initiating call (ruling R4 of the change hkdf-pieces): only the code reaches + `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. + @return What the completion token's `async_result` gives. +*/ +template +auto complete_with_code(Executor const& executor, CompletionToken& token, + boost::system::error_code code) { + return webcpp::asio_backend::async_initiate( + code_initiation{}, token, executor, code); +} + +/** + HKDF-Extract into `pseudorandom_key`, the work of `async_hkdf_extract` on a synchronous backend: + `hkdf_extract` over `input_key_material` (a span, or `byte_pieces`), its result + copied into `pseudorandom_key` and wiped. + + @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. + @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, + 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 + // time does not depend on the bytes. A guard here would be the first one the call enters, where + // the asynchronous family's rule (timing_async_test) is that it is the synchronous function's. + // 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 (pseudorandom_key.size() != digest_length) { + return error::invalid_output_size; + } + if constexpr (std::is_same_v) { + auto const guarded = hkdf_pieces_salt_guard(salt.size()); + if (!guarded) { + return guarded; + } + } else { + auto const guarded = hkdf_extract_guards(salt.size(), input_key_material.size()); + if (!guarded) { + return guarded; + } + } + auto extracted = hkdf_extract(salt, input_key_material); + if (!extracted) { + wipe(pseudorandom_key); + return extracted.error(); + } + std::ranges::copy(*extracted, pseudorandom_key.begin()); + wipe_object(*extracted); + return {}; +} + /** Where a heavy operation is: waiting in the work executor's queue, running, or completed. */ enum class heavy_phase : std::uint8_t { /** Posted to the work executor, not started. */ @@ -775,7 +871,7 @@ auto async_hmac(Executor const& executor, std::span output, /** HKDF (RFC 5869), extract and expand, asynchronously (spec 11), as @ref async_digest runs: the - output of `hkdf`. + output keying material of `hkdf`. @tparam Hmac `hmac_sha1_160`, `hmac_sha2_256`, `hmac_sha2_384` or `hmac_sha2_512`, the hmacs WebCrypto has HKDF over; another refuses at compile time (`hkdf` has them all). @@ -786,22 +882,25 @@ auto async_hmac(Executor const& executor, std::span output, @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 output keying material, 1 to 255 times the digest size. - @param salt The salt. @param ikm The input keying material. @param info The context, at most - `hkdf_max_info_size` bytes; on `backends::webcrypto` at most 1,024, WebCrypto's limit + @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. @param 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` 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 `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), + `output_key_material` untouched, `backend_failure` (a rejected promise, an unexpected result, no + WebCrypto), `output_key_material` zeroed, and `operation_aborted` (a `terminal` or `partial` + cancellation, at once), `output_key_material` zeroed. */ template , class Executor, class CompletionToken> -auto async_hkdf(Executor const& executor, std::span output, - std::span salt, std::span ikm, - std::span info, CompletionToken&& token) { +auto async_hkdf(Executor const& executor, std::span output_key_material, + std::span salt, + std::span input_key_material, + std::span application_info, CompletionToken&& token) { if constexpr (!detail::webcrypto_hmac_v) { static_assert(detail::always_false, "webcpp::hash: async_hkdf takes hmac_sha1_160, hmac_sha2_256, " @@ -809,11 +908,250 @@ auto async_hkdf(Executor const& executor, std::span output, "hkdf for the others."); } else if constexpr (detail::asynchronous_backend_v) { return detail::async_engine::template hkdf( - executor, output, salt, ikm, info, std::forward(token)); + executor, output_key_material, salt, input_key_material, application_info, + std::forward(token)); } else { - return detail::complete_by_post(executor, token, [output, salt, ikm, info] { - return hkdf(output, salt, ikm, info); - }); + 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, + application_info); + }); + } +} + +/** + HKDF (RFC 5869), extract and expand, over pieces, asynchronously (spec 11): the output keying + material of the `hkdf` over `byte_pieces`, with no cap on the application info. + + 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 + 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. + + @code + webcpp::hash::async_hkdf( + loop.get_executor(), key, salt, {version, suite_id, label, ikm}, + {length, version, suite_id, label, info}, [](boost::system::error_code code) { ... }); + @endcode + + @tparam Hmac `hmac_sha1_160`, `hmac_sha2_256`, `hmac_sha2_384` or `hmac_sha2_512`, the hmacs + WebCrypto has HKDF over; another refuses at compile time (`hkdf` has them all). + @tparam Backend The backend; by default @ref default_async_backend of `kdfs::hkdf_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 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 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)`. + @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) { + if constexpr (!detail::webcrypto_hmac_v) { + static_assert(detail::always_false, + "webcpp::hash: async_hkdf takes hmac_sha1_160, hmac_sha2_256, " + "hmac_sha2_384 or hmac_sha2_512, the hmacs WebCrypto has HKDF over: call " + "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)); + } 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); + } +} + +/** + HKDF-Extract (RFC 5869, section 2.2), asynchronously (spec 11), as @ref async_digest runs: the + pseudorandom key of `hkdf_extract`, written into `pseudorandom_key`. + + @tparam Hmac `hmac_sha1_160`, `hmac_sha2_256`, `hmac_sha2_384` or `hmac_sha2_512`, the hmacs + WebCrypto has HKDF over; another refuses at compile time (`hkdf_extract` has them all). + @tparam Backend The backend; by default @ref default_async_backend of `kdfs::hkdf_extract`, 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 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 + caller's until completion. + @param 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 + backend's failure. +*/ +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) { + if constexpr (!detail::webcrypto_hmac_v) { + static_assert(detail::always_false, + "webcpp::hash: async_hkdf_extract takes hmac_sha1_160, hmac_sha2_256, " + "hmac_sha2_384 or hmac_sha2_512, the hmacs WebCrypto has HKDF over: call " + "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)); + } else { + return detail::complete_by_post(executor, token, + [pseudorandom_key, salt, input_key_material] { + return detail::hkdf_extract_into( + pseudorandom_key, salt, input_key_material); + }); + } +} + +/** + HKDF-Extract (RFC 5869, section 2.2) over pieces, asynchronously (spec 11), as the + @ref async_hkdf over pieces runs: the pseudorandom key of `hkdf_extract` over + `byte_pieces`, written into `pseudorandom_key`, the pieces read in the call. + + @tparam Hmac `hmac_sha1_160`, `hmac_sha2_256`, `hmac_sha2_384` or `hmac_sha2_512`, the hmacs + WebCrypto has HKDF over; another refuses at compile time (`hkdf_extract` has them all). + @tparam Backend The backend; by default @ref default_async_backend of + `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 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)`. + @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 + by a backend's failure. +*/ +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) { + if constexpr (!detail::webcrypto_hmac_v) { + static_assert(detail::always_false, + "webcpp::hash: async_hkdf_extract takes hmac_sha1_160, hmac_sha2_256, " + "hmac_sha2_384 or hmac_sha2_512, the hmacs WebCrypto has HKDF over: call " + "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)); + } 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); + } +} + +/** + HKDF-Expand (RFC 5869, section 2.3), asynchronously (spec 11), as @ref async_digest runs: the + output keying material of `hkdf_expand`. + + @tparam Hmac `hmac_sha1_160`, `hmac_sha2_256`, `hmac_sha2_384` or `hmac_sha2_512`, the hmacs + WebCrypto has HKDF over; another refuses at compile time (`hkdf_expand` has them all). + @tparam Backend The backend; by default @ref default_async_backend of `kdfs::hkdf_expand`, 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 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)`. + @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, + std::span pseudorandom_key, + std::span application_info, CompletionToken&& token) { + if constexpr (!detail::webcrypto_hmac_v) { + static_assert(detail::always_false, + "webcpp::hash: async_hkdf_expand takes hmac_sha1_160, hmac_sha2_256, " + "hmac_sha2_384 or hmac_sha2_512, the hmacs WebCrypto has HKDF over: call " + "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)); + } 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); + }); + } +} + +/** + HKDF-Expand (RFC 5869, section 2.3) over pieces, asynchronously (spec 11), as the + @ref async_hkdf over pieces runs: the output keying material of `hkdf_expand` over + `byte_pieces`, with no cap on the application info, the pieces read in the call. + + @tparam Hmac `hmac_sha1_160`, `hmac_sha2_256`, `hmac_sha2_384` or `hmac_sha2_512`, the hmacs + WebCrypto has HKDF over; another refuses at compile time (`hkdf_expand` has them all). + @tparam Backend The backend; by default @ref default_async_backend of + `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 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)`. + @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, + std::span pseudorandom_key, byte_pieces application_info, + CompletionToken&& token) { + if constexpr (!detail::webcrypto_hmac_v) { + static_assert(detail::always_false, + "webcpp::hash: async_hkdf_expand takes hmac_sha1_160, hmac_sha2_256, " + "hmac_sha2_384 or hmac_sha2_512, the hmacs WebCrypto has HKDF over: call " + "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)); + } else { + auto const code = detail::code_of( + hkdf_expand(output_key_material, pseudorandom_key, application_info)); + return detail::complete_with_code(executor, token, code); } } diff --git a/include/webcpp/hash/backends/bearssl.hpp b/include/webcpp/hash/backends/bearssl.hpp index 961de3e..56f453c 100644 --- a/include/webcpp/hash/backends/bearssl.hpp +++ b/include/webcpp/hash/backends/bearssl.hpp @@ -13,6 +13,8 @@ `hmac_sha2_224`, `hmac_sha2_256`, `hmac_sha2_384` and `hmac_sha2_512`. BearSSL has `hkdf` alone: its context keeps the pseudorandom key and takes none in, so that `hkdf_extract` and `hkdf_expand` refuse at compile time, as `pbkdf2` does (spec section 3.3). + - HKDF over pieces (`hkdf_extract`, `hkdf_expand` and `hkdf` over `byte_pieces`) for the same six + hmacs, over BearSSL's HMAC, Extract and Expand included. - The digests of `digest_of` and `hasher` (spec 2.15): MD5, SHA-1, SHA-224, SHA-256, SHA-384 and SHA-512 over `br__init`, `br__update` and `br__out`; TLS 1.0's MD5-SHA1 (36 bytes, MD5 followed by SHA-1) over `br_md5sha1_*`; SHAKE128 and SHAKE256, any output size, @@ -49,8 +51,10 @@ #include #include +#include #include #include +#include #include #ifdef WEBCPP_HASH_BEARSSL_CANARY_CONFIGURATION @@ -82,9 +86,9 @@ extern "C" constinit const char WEBCPP_HASH_DETAIL_BEARSSL_CANARY; namespace webcpp::hash::backends { /** - BearSSL on every target: `hkdf` alone over six hmacs, MD5, SHA-1, SHA-2, MD5-SHA1 and SHAKE - through `digest_of` and `hasher`, and HMAC over MD5, SHA-1 and SHA-2 through `mac`; never a - default. + BearSSL on every target: `hkdf` alone over six hmacs, and HKDF's three functions over pieces; + MD5, SHA-1, SHA-2, MD5-SHA1 and SHAKE through `digest_of` and `hasher`, and HMAC over MD5, SHA-1 + and SHA-2 through `mac`; never a default. */ struct bearssl {}; @@ -403,8 +407,8 @@ struct hkdf_engine { @return Never: the program does not compile. */ [[nodiscard]] static boost::system::result extract( - std::span /*salt_bytes*/, - std::span /*ikm_bytes*/) noexcept { + std::span /*salt*/, + std::span /*input_key_material*/) noexcept { static_assert(always_false, "webcpp::hash: hkdf_extract and hkdf_expand are not in backends::bearssl, " "whose HKDF does both steps together: call hkdf, or name backends::hash2, " @@ -418,8 +422,9 @@ struct hkdf_engine { @return Never: the program does not compile. */ [[nodiscard]] static boost::system::result expand( - std::span /*output_bytes*/, std::span /*prk_bytes*/, - std::span /*info_bytes*/) noexcept { + std::span /*output_key_material*/, + std::span /*pseudorandom_key*/, + std::span /*application_info*/) noexcept { static_assert(always_false, "webcpp::hash: hkdf_extract and hkdf_expand are not in backends::bearssl, " "whose HKDF does both steps together: call hkdf, or name backends::hash2, " @@ -430,33 +435,160 @@ struct hkdf_engine { /** RFC 5869, 2, by BearSSL: `br_hkdf_init` with the hash and the salt (an empty one of length 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_bytes`; then the context is wiped. + `br_hkdf_flip`, `br_hkdf_produce` into `output_key_material`; then the context is wiped. - @param output_bytes The OKM. @param salt_bytes The salt. @param ikm_bytes The input keying - material. - @param info_bytes The info. + @param output_key_material The OKM. @param salt 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_bytes, std::span salt_bytes, - std::span ikm_bytes, - std::span info_bytes) noexcept { + std::span output_key_material, std::span salt, + 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_bytes), - salt_bytes.size()); - br_hkdf_inject(&hkdf_context, nonnull(ikm_bytes), ikm_bytes.size()); + br_hkdf_init(&hkdf_context, bearssl_hash_class::vtable(), nonnull(salt), salt.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 = - br_hkdf_produce(&hkdf_context, nonnull(info_bytes), info_bytes.size(), - output_bytes.data(), output_bytes.size()); + br_hkdf_produce(&hkdf_context, nonnull(application_info), application_info.size(), + output_key_material.data(), output_key_material.size()); wipe_object(hkdf_context); - return produced_count == output_bytes.size() + return produced_count == output_key_material.size() ? boost::system::result() : boost::system::result(error::backend_failure); } }; +/** + HKDF over pieces on backends::bearssl (the engine's interface: @ref hkdf_pieces_engine), over + BearSSL's HMAC rather than its HKDF, whose context keeps the pseudorandom key: RFC 5869 with + every concatenation replaced by successive `br_hmac_update`s, so that BearSSL has Extract and + Expand over pieces, while its single-buffer `hkdf_extract` and `hkdf_expand` stay refused. The + `br_hmac_key_context` of a key is made once by `br_hmac_key_init`, and a `br_hmac_context` is + started from it by `br_hmac_init` for each block (BearSSL copies what it needs, and modifies no + key context); every context, each block T(i) and the pseudorandom key between the steps are + wiped. `br_hmac_update` takes a `size_t`, which holds every slice of @ref hkdf_pieces_slice, so + that a piece is sliced only by the test seam. + + @tparam Hmac One of the six hmacs of @ref bearssl_hash_class. +*/ +template + requires bearssl_hmac_v +struct hkdf_pieces_engine { + /** The hmac's result, a `digest`: the PRK and each block T(i). */ + using digest_type = Hmac::result_type; + + /** The most bytes of one update. */ + static constexpr std::uint64_t slice_max = hkdf_pieces_slice; + static_assert(slice_max <= std::numeric_limits::max(), + "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. + + @param mac_context The HMAC context. @param 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()); + }); + } + + /** + 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. + @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 { + 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_context mac_context; + br_hmac_init(&mac_context, &key_context, 0); + update_all(mac_context, input_key_material); + std::size_t const written_count = + br_hmac_out(&mac_context, pseudorandom_key.unsafe_value().data()); + wipe_object(mac_context); + wipe_object(key_context); + if (written_count != pseudorandom_key.unsafe_value().size()) { + wipe_object(pseudorandom_key.unsafe_value()); + pseudorandom_key = boost::system::result(error::backend_failure); + } + return pseudorandom_key; + } + + /** + RFC 5869, 2.3: T(0) = empty; T(i) = HMAC-Hash(PRK, T(i-1) | piece_1 | ... | piece_n | 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's pieces. + @return Success, or `error::backend_failure` when BearSSL wrote another size than the digest's + (the public function then zeroes the output). + */ + [[nodiscard]] static boost::system::result expand( + std::span output_key_material, std::span pseudorandom_key, + byte_pieces application_info) noexcept { + touch_bearssl_canary(); + br_hmac_key_context key_context; + br_hmac_key_init(&key_context, bearssl_hash_class::vtable(), pseudorandom_key.data(), + pseudorandom_key.size()); + digest_type t_block{}; + bool computed = true; + std::size_t written_count = 0; + for (unsigned block_counter = 1; computed && 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) { + br_hmac_update(&mac_context, t_block.data(), t_block.size()); + } + 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(); + wipe_object(mac_context); + if (computed) { + 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, + output_key_material.data() + written_count); + written_count += copied_count; + } + } + wipe_object(t_block); + wipe_object(key_context); + if (!computed) { + return error::backend_failure; + } + return {}; + } + + /** + 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 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, + 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); + } +}; + /** PBKDF2 on backends::bearssl: BearSSL has none, and this specialisation refuses with spec 3.3's text for BearSSL rather than the primary template's. diff --git a/include/webcpp/hash/backends/botan.hpp b/include/webcpp/hash/backends/botan.hpp index c690ef3..b00b904 100644 --- a/include/webcpp/hash/backends/botan.hpp +++ b/include/webcpp/hash/backends/botan.hpp @@ -16,14 +16,15 @@ of at most 192 bytes, and no KMACXOF), SipHash-2-4 (an 8-byte tag) and keyed BLAKE2b. Botan's CMAC, GMAC, Poly1305 and X9.19-MAC, and the hashes hash has no tag for, are not exposed (`doc/capabilities.json` says why). - Its key derivations are HKDF, PBKDF2 and KBKDF (counter mode, with the separator and L) over every - hmac of `hmac.hpp` but `hmac_ripemd_128` and `hmac_sha2_512_224`, SSKDF (the hash form) over every - digest of SP 800-56C but SHA-512/224, ANSI X9.63's KDF (Botan's KDF2), scrypt (N of at most 2^22, - r 256, p 1,024, 8 GiB and 2 MiB of memory), Argon2d, Argon2i and Argon2id with lanes (at most 128), - a secret and associated data (at most 8 GiB, the lanes computed in turn), serving the function - `argon2id` too, bcrypt (a cost of at most 18) and bcrypt_pbkdf; on wasm32 PBKDF2 takes at most - 2^32 - 1 iterations and Argon2 and scrypt at most 2 GiB. bcrypt's salt is the caller's, given to - Botan through a generator that yields those 16 bytes alone: hash draws no random byte from Botan. + Its key derivations are HKDF (also over pieces, on its HMAC), PBKDF2 and KBKDF (counter mode, + with the separator and L) over every hmac of `hmac.hpp` but `hmac_ripemd_128` and + `hmac_sha2_512_224`, SSKDF (the hash form) over every digest of SP 800-56C but SHA-512/224, ANSI + X9.63's KDF (Botan's KDF2), scrypt (N of at most 2^22, r 256, p 1,024, 8 GiB and 2 MiB of memory), + Argon2d, Argon2i and Argon2id with lanes (at most 128), a secret and associated data (at most + 8 GiB, the lanes computed in turn), serving the function `argon2id` too, bcrypt (a cost of at + most 18) and bcrypt_pbkdf; on wasm32 PBKDF2 takes at most 2^32 - 1 iterations and Argon2 and + scrypt at most 2 GiB. bcrypt's salt is the caller's, given to Botan through a generator that + yields those 16 bytes alone: hash draws no random byte from Botan. Botan reports its errors by throwing, so this header declares nothing in a build without exceptions (`WEBCPP_HASH_NO_EXCEPTIONS`): a call on `backends::botan` then stops with the text @@ -139,11 +140,11 @@ struct backend_limits { /** HKDF's salt. */ static constexpr std::uint64_t hkdf_salt = no_limit; /** HKDF's input keying material. */ - static constexpr std::uint64_t hkdf_ikm = no_limit; + static constexpr std::uint64_t hkdf_input_key_material = no_limit; /** HKDF's pseudorandom key. */ - static constexpr std::uint64_t hkdf_prk = no_limit; + static constexpr std::uint64_t hkdf_pseudorandom_key = no_limit; /** HKDF's info. */ - static constexpr std::uint64_t hkdf_info = no_limit; + static constexpr std::uint64_t hkdf_application_info = no_limit; /** HKDF's output. */ static constexpr std::uint64_t hkdf_output = no_limit; /** PBKDF2's password. */ @@ -1191,23 +1192,24 @@ struct botan_refused_hmac_kdf { /** Never called: the refusal has stopped the build. */ [[nodiscard]] static boost::system::result extract( - std::span /*salt_bytes*/, - std::span /*ikm_bytes*/) noexcept { + std::span /*salt*/, + std::span /*input_key_material*/) noexcept { return error::backend_failure; } /** Never called: the refusal has stopped the build. */ [[nodiscard]] static boost::system::result expand( - std::span /*output_bytes*/, std::span /*prk_bytes*/, - std::span /*info_bytes*/) noexcept { + std::span /*output_key_material*/, + std::span /*pseudorandom_key*/, + std::span /*application_info*/) noexcept { return error::backend_failure; } /** Never called: the refusal has stopped the build. */ [[nodiscard]] static boost::system::result extract_and_expand( - std::span /*output_bytes*/, std::span /*salt_bytes*/, - std::span /*ikm_bytes*/, - std::span /*info_bytes*/) noexcept { + std::span /*output_key_material*/, std::span /*salt*/, + std::span /*input_key_material*/, + std::span /*application_info*/) noexcept { return error::backend_failure; } @@ -1236,55 +1238,57 @@ struct botan_hkdf_engine { /** RFC 5869, 2.2: the PRK, HashLen bytes; an empty salt is HashLen zeros, as Botan keys it. - @param salt_bytes The salt. @param ikm_bytes The input keying material. + @param salt 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_bytes, - std::span ikm_bytes) noexcept { + std::span salt, + std::span input_key_material) noexcept { // The PRK is derived into the result returned, whose wiping is the caller's. - boost::system::result prk_bytes{boost::system::in_place_value}; - digest_type& prk = prk_bytes.unsafe_value(); + 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_bytes, [&](std::span key) noexcept { + botan_keyed(salt, [&](std::span key) noexcept { return botan_kdf({"HKDF-Extract(HMAC(", botan_hash_name::value, "))"}, - std::span(prk.data(), prk.size()), ikm_bytes, key, - {}); + std::span(pseudorandom_key_digest.data(), + pseudorandom_key_digest.size()), + input_key_material, key, {}); }); if (!derived) { - wipe_object(prk); - prk_bytes = derived.error(); + wipe_object(pseudorandom_key_digest); + pseudorandom_key = derived.error(); } - return prk_bytes; + return pseudorandom_key; } /** RFC 5869, 2.3: the PRK as the secret, the info as the label. - @param output_bytes The OKM. @param prk_bytes The PRK. @param info_bytes The info. + @param output_key_material The OKM. @param pseudorandom_key The PRK. @param application_info + The info. @return Success, or Botan's failure. */ [[nodiscard]] static boost::system::result expand( - std::span output_bytes, std::span prk_bytes, - std::span info_bytes) noexcept { - return botan_kdf({"HKDF-Expand(HMAC(", botan_hash_name::value, "))"}, output_bytes, - prk_bytes, {}, info_bytes); + std::span output_key_material, std::span pseudorandom_key, + std::span application_info) noexcept { + return botan_kdf({"HKDF-Expand(HMAC(", botan_hash_name::value, "))"}, + output_key_material, pseudorandom_key, {}, application_info); } /** RFC 5869, 2: both steps, the PRK inside Botan's KDF. - @param output_bytes The OKM. @param salt_bytes The salt. @param ikm_bytes The input keying - material. @param info_bytes The info. + @param output_key_material The OKM. @param salt 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_bytes, std::span salt_bytes, - std::span ikm_bytes, - std::span info_bytes) noexcept { - return botan_keyed(salt_bytes, [&](std::span key) noexcept { - return botan_kdf({"HKDF(HMAC(", botan_hash_name::value, "))"}, output_bytes, - ikm_bytes, key, info_bytes); + std::span output_key_material, std::span salt, + 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); }); } }; @@ -1299,6 +1303,145 @@ struct hkdf_engine : std::conditional_t, botan_hkdf_engine, botan_refused_hmac_kdf> {}; +/** + HKDF over pieces on backends::botan (the engine's interface: @ref hkdf_pieces_engine), over Botan's + `MessageAuthenticationCode` "HMAC()" rather than its KDF "HKDF", which takes the input keying + material and the info whole: RFC 5869 with every concatenation replaced by successive `update`s. + Each call makes the HMAC (`create_or_throw`, through @ref botan_create), keys it (`set_key`) and + computes with `update` and `final`; Expand re-keys it for each block, `clear` then `set_key` with + the pseudorandom key. Every call of Botan runs inside @ref botan_boundary, which answers an + exception with `errc::not_enough_memory` (`std::bad_alloc`) or `error::backend_failure`. The object + is cleared and freed (@ref botan_owned) and Botan keeps its keys in `secure_vector`s, which it + zeroes when it frees them; hash wipes the room of a long salt's digest, each block T(i) and the + pseudorandom key between the steps, on success and on failure. A salt longer than the 8,192 bytes + Botan's HMAC takes is hashed first (@ref botan_keyed), as RFC 2104 hashes every key longer than the + hash's block. Botan's `update` takes a `size_t`, which holds every slice of @ref hkdf_pieces_slice, + so that a piece is sliced only by the test seam. + + @tparam Hmac A Boost.Hash2 hmac for which `botan_hmac_v` holds. +*/ +template + requires botan_hmac_v +struct hkdf_pieces_engine { + /** The hmac's result, a `digest`: the PRK and each block T(i). */ + using digest_type = Hmac::result_type; + /** The tag of the hmac's hash. */ + using digest = digest_tag_of::type; + + /** The most bytes of one update. */ + static constexpr std::uint64_t slice_max = hkdf_pieces_slice; + static_assert(slice_max <= std::numeric_limits::max(), + "Botan's update takes every slice's length"); + + /** + Makes Botan's HMAC over the hmac's hash, "HMAC()", into `mac_object`; Botan throws + for a name it does not know, and the standard library's string may throw `std::bad_alloc`. + + @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)); + } + + /** + Feeds every byte of `pieces` to `mac`, in slices of at most @ref slice_max bytes. + + @param mac The keyed HMAC. @param pieces The pieces. + */ + static void update_all(Botan::MessageAuthenticationCode& mac, byte_pieces pieces) { + for_each_slice(pieces, + [&](std::span slice) { mac.update(slice); }); + } + + /** + 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. + @return The PRK, or Botan's failure. + */ + [[nodiscard]] static boost::system::result extract( + std::span salt, 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 { + botan_owned mac_object; + return botan_boundary([&] { + make(mac_object); + mac_object.get().set_key(key); + update_all(mac_object.get(), input_key_material); + mac_object.get().final(std::span(pseudorandom_key_digest.data(), + pseudorandom_key_digest.size())); + }); + }); + if (!derived) { + wipe_object(pseudorandom_key_digest); + pseudorandom_key = derived.error(); + } + return pseudorandom_key; + } + + /** + RFC 5869, 2.3: T(0) = empty; T(i) = HMAC-Hash(PRK, T(i-1) | piece_1 | ... | piece_n | i); + OKM = the first L octets of T(1) | T(2) | ... | T(N), N = ceil(L/HashLen). The HMAC is + cleared and keyed by the PRK again for each block. + + @param output_key_material The OKM, its size L. @param pseudorandom_key The PRK. + @param application_info The info's pieces. + @return Success, or Botan's failure (the public function then zeroes the output). + */ + [[nodiscard]] static boost::system::result expand( + std::span output_key_material, std::span pseudorandom_key, + byte_pieces application_info) noexcept { + digest_type t_block{}; + botan_owned mac_object; + auto const derived = botan_boundary([&] { + make(mac_object); + Botan::MessageAuthenticationCode& mac = 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); + if (block_counter > 1) { + mac.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())); + 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, + output_key_material.data() + written_count); + written_count += copied_count; + } + }); + mac_object.reset(); + wipe_object(t_block); + return derived; + } + + /** + 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 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, + 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); + } +}; + /** PBKDF2 on backends::botan over an hmac it has: Botan's "PBKDF2(HMAC())" (the engine's interface: @ref pbkdf2_engine). The password is HMAC's key, hashed first when it is longer than @@ -1316,16 +1459,17 @@ struct botan_pbkdf2_engine { /** RFC 8018, 5.2. - @param output_bytes DK. @param password_bytes P. @param salt_bytes S. @param iteration_count c. + @param output_key_material DK. @param password_bytes P. @param salt S. @param iteration_count + c. @return Success, or Botan's failure. */ [[nodiscard]] static boost::system::result derive( - std::span output_bytes, std::span password_bytes, - std::span salt_bytes, std::uint64_t iteration_count) noexcept { + 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_bytes, key, salt_bytes); + output_key_material, key, salt); }); } }; @@ -1337,7 +1481,7 @@ struct pbkdf2_engine botan_refused_hmac_kdf> {}; /** The most memory of Botan's Argon2, in KiB: 8 GiB, 2 GiB on wasm32 (`MAX_ARGON_MEMORY_GB`). */ -inline constexpr std::uint32_t botan_argon2_max_memory_kib = +inline constexpr std::uint32_t botan_argon2_max_memory_kibibytes = (sizeof(std::size_t) == 4 ? 2U : 8U) * 1024U * 1024U; /** Botan's most lanes of Argon2 (`Argon2::Argon2`'s check, `m_p <= 128`). */ @@ -1383,9 +1527,9 @@ struct botan_argon2_name { */ template struct botan_argon2_engine { - /** RFC 9106's bounds, but at most 128 lanes and `botan_argon2_max_memory_kib`. */ + /** RFC 9106's bounds, but at most 128 lanes and `botan_argon2_max_memory_kibibytes`. */ static constexpr argon2_limits limits{ - .max_memory_kib = botan_argon2_max_memory_kib, + .max_memory_kibibytes = botan_argon2_max_memory_kibibytes, .max_lanes = botan_argon2_max_lanes, }; @@ -1399,10 +1543,10 @@ struct botan_argon2_engine { [[nodiscard]] static boost::system::result derive( std::span output_bytes, std::span password_bytes, std::span salt_bytes, argon2_parameters const& parameters) noexcept { - return botan_password_hash({botan_argon2_name::value}, - {parameters.memory_kib, parameters.passes, parameters.lanes}, - output_bytes, password_bytes, salt_bytes, - parameters.associated_data, parameters.secret); + 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); } }; @@ -1426,7 +1570,7 @@ template <> struct argon2id_engine { /** Botan's 8 GiB, 2 GiB on wasm32, in bytes. */ static constexpr argon2id_limits limits{ - .memory = std::uint64_t{botan_argon2_max_memory_kib} * argon2id_memory_unit, + .memory = std::uint64_t{botan_argon2_max_memory_kibibytes} * argon2id_memory_unit, }; /** @@ -1914,6 +2058,25 @@ template <> inline constexpr bool backend_has_v inline constexpr bool backend_has_v = detail::botan_hmac_v; +/** + backends::botan has HKDF over pieces over the hmacs of `detail::botan_hmac_v`, those of its HMAC + cells it has HKDF over, on its `MessageAuthenticationCode` "HMAC()" (its KDF "HKDF" takes the + input keying material and the info whole, and is not used). +*/ +template +inline constexpr bool backend_has_v = + detail::botan_hmac_v; + +/** backends::botan has HKDF-Extract over pieces wherever it has HKDF over pieces. */ +template +inline constexpr bool backend_has_v = + backend_has_v; + +/** backends::botan has HKDF-Expand over pieces wherever it has HKDF over pieces. */ +template +inline constexpr bool backend_has_v = + backend_has_v; + /** backends::botan has PBKDF2 ("PBKDF2(HMAC())") over the hmacs of `detail::botan_hmac_v`, in part: at most 2^32 - 2 blocks of output, and on wasm32 at most 2^32 - 1 iterations. diff --git a/include/webcpp/hash/backends/hash2.hpp b/include/webcpp/hash/backends/hash2.hpp index 17ac0fe..8dcb229 100644 --- a/include/webcpp/hash/backends/hash2.hpp +++ b/include/webcpp/hash/backends/hash2.hpp @@ -5,11 +5,11 @@ // https://www.boost.org/LICENSE_1_0.txt) /** - `backends::hash2`: HKDF (RFC 5869) and PBKDF2 (RFC 8018) written by webcpp over Boost.Hash2's - `hmac`, on every target and over every Hash2 hmac whose result is a digest; and the families' - engines over Boost.Hash2's own algorithms (spec 2.15): the digests MD5, SHA-1, SHA-2, SHA-3, - RIPEMD-160 and BLAKE2s-256, BLAKE2b with its 64-byte output alone, SHAKE128 and SHAKE256 with - any output size (each Hash2 `result()` permutes and gives the next block of the stream); HMAC + `backends::hash2`: HKDF (RFC 5869), also over pieces, and PBKDF2 (RFC 8018) written by webcpp over + Boost.Hash2's `hmac`, on every target and over every Hash2 hmac whose result is a digest; and + the families' engines over Boost.Hash2's own algorithms (spec 2.15): the digests MD5, SHA-1, SHA-2, + SHA-3, RIPEMD-160 and BLAKE2s-256, BLAKE2b with its 64-byte output alone, SHAKE128 and SHAKE256 + with any output size (each Hash2 `result()` permutes and gives the next block of the stream); HMAC over each fixed-size digest and over BLAKE2b-512; SipHash-2-4; and keyed BLAKE2s with its 32-byte tag alone. It needs no C library. @@ -24,6 +24,7 @@ #include +#include #include #include @@ -70,49 +71,52 @@ 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_bytes The salt. @param ikm_bytes The input keying material. + @param salt The salt. @param input_key_material The input keying material. @return The PRK. */ [[nodiscard]] static boost::system::result extract( - std::span salt_bytes, - std::span ikm_bytes) noexcept { - Hmac mac_state(salt_bytes.data(), salt_bytes.size()); - mac_state.update(ikm_bytes.data(), ikm_bytes.size()); + std::span salt, + std::span input_key_material) noexcept { + Hmac mac_state(salt.data(), salt.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 prk_bytes{ + boost::system::result pseudorandom_key{ boost::system::in_place_value, mac_state.result(), }; wipe_object(mac_state); - return prk_bytes; + return pseudorandom_key; } /** 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_bytes The OKM, its size L. @param prk_bytes The PRK. @param info_bytes 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( - std::span output_bytes, std::span prk_bytes, - std::span info_bytes) noexcept { - Hmac keyed_mac(prk_bytes.data(), prk_bytes.size()); // not const: it is wiped at the end + std::span output_key_material, std::span pseudorandom_key, + std::span application_info) noexcept { + Hmac keyed_mac(pseudorandom_key.data(), + pseudorandom_key.size()); // not const: it is wiped at the end digest_type t_block{}; std::size_t written_count = 0; - for (unsigned block_counter = 1; written_count < output_bytes.size(); ++block_counter) { + for (unsigned block_counter = 1; written_count < output_key_material.size(); + ++block_counter) { Hmac mac_state = keyed_mac; if (block_counter > 1) { mac_state.update(t_block.data(), t_block.size()); } - mac_state.update(info_bytes.data(), info_bytes.size()); + mac_state.update(application_info.data(), application_info.size()); const auto octet_value = static_cast(block_counter); mac_state.update(&octet_value, 1); t_block = mac_state.result(); wipe_object(mac_state); const std::size_t copied_count = - std::min(t_block.size(), output_bytes.size() - written_count); - std::memcpy(output_bytes.data() + written_count, t_block.data(), copied_count); + std::min(t_block.size(), output_key_material.size() - written_count); + std::memcpy(output_key_material.data() + written_count, t_block.data(), copied_count); written_count += copied_count; } wipe_object(t_block); @@ -123,28 +127,122 @@ struct hkdf_engine { /** RFC 5869, 2: HKDF-Extract, then HKDF-Expand; the PRK is wiped. - @param output_bytes The OKM. @param salt_bytes The salt. @param ikm_bytes The input keying - material. - @param info_bytes The info. + @param output_key_material The OKM. @param salt 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_bytes, std::span salt_bytes, - std::span ikm_bytes, - std::span info_bytes) noexcept { - auto prk_bytes = extract(salt_bytes, ikm_bytes); - if (!prk_bytes) { - return prk_bytes.error(); + std::span output_key_material, std::span salt, + std::span input_key_material, + std::span application_info) noexcept { + auto pseudorandom_key = extract(salt, input_key_material); + if (!pseudorandom_key) { + return pseudorandom_key.error(); } - digest_type& prk_digest = prk_bytes.unsafe_value(); - auto derive_result = - expand(output_bytes, - std::span(prk_digest.data(), prk_digest.size()), info_bytes); - wipe_object(prk_digest); + digest_type& pseudorandom_key_digest = pseudorandom_key.unsafe_value(); + auto derive_result = expand(output_key_material, + std::span(pseudorandom_key_digest.data(), + pseudorandom_key_digest.size()), + application_info); + wipe_object(pseudorandom_key_digest); return derive_result; } }; +/** + HKDF over pieces on backends::hash2, whose interface is @ref hkdf_pieces_engine's. RFC 5869 + with every concatenation replaced by successive updates of one Boost.Hash2 `hmac`, whose + `update` takes a `size_t`, so that a piece is never sliced (@ref hkdf_pieces_slice is a span's + whole length, unless the test seam lowers it). + + @tparam Hmac A Boost.Hash2 hmac over a digest. +*/ +template +struct hkdf_pieces_engine { + /** The hmac's result, a `digest`: the PRK and each block T(i). */ + using digest_type = Hmac::result_type; + + /** The most bytes of one update. */ + static constexpr std::uint64_t slice_max = hkdf_pieces_slice; + + /** + 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. + @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()); + }); + // The PRK is stored in the result returned, whose wiping is the caller's. + boost::system::result pseudorandom_key{ + boost::system::in_place_value, + mac_state.result(), + }; + wipe_object(mac_state); + return pseudorandom_key; + } + + /** + RFC 5869, 2.3: T(0) = empty; T(i) = HMAC-Hash(PRK, T(i-1) | piece_1 | ... | piece_n | i); + OKM = the first L octets of T(1) | T(2) | ... | T(N), N = ceil(L/HashLen). The hmac keyed by + the PRK is made once and copied for each block. + + @param output_key_material The OKM, its size L. @param pseudorandom_key The PRK. + @param application_info The info's pieces. + @return Success. + */ + [[nodiscard]] static boost::system::result expand( + std::span output_key_material, std::span pseudorandom_key, + byte_pieces application_info) noexcept { + Hmac keyed_mac(pseudorandom_key.data(), + pseudorandom_key.size()); // not const: it is wiped at the end + digest_type t_block{}; + std::size_t written_count = 0; + for (unsigned block_counter = 1; written_count < output_key_material.size(); + ++block_counter) { + Hmac mac_state = keyed_mac; + 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()); + }); + const auto octet_value = static_cast(block_counter); + mac_state.update(&octet_value, 1); + t_block = mac_state.result(); + wipe_object(mac_state); + const std::size_t copied_count = + std::min(t_block.size(), output_key_material.size() - written_count); + std::memcpy(output_key_material.data() + written_count, t_block.data(), copied_count); + written_count += copied_count; + } + wipe_object(t_block); + wipe_object(keyed_mac); + return {}; + } + + /** + 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 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, + 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); + } +}; + /** PBKDF2 on backends::hash2 (the engine's interface: @ref pbkdf2_engine). diff --git a/include/webcpp/hash/backends/openssl.hpp b/include/webcpp/hash/backends/openssl.hpp index 46eeb0b..8d84e21 100644 --- a/include/webcpp/hash/backends/openssl.hpp +++ b/include/webcpp/hash/backends/openssl.hpp @@ -7,9 +7,11 @@ /** `backends::openssl`: HKDF (RFC 5869), PBKDF2 (RFC 8018), scrypt (RFC 7914) and Argon2 (RFC 9106) of OpenSSL 3.5.9, its `EVP_KDF` implementations "HKDF", "PBKDF2", "SCRYPT", "ARGON2D", "ARGON2I" - and "ARGON2ID", the digests of its default provider through `EVP_MD` and its MACs through - `EVP_MAC`, built from `third_party/libs/openssl` by `/webcpp/hash//openssl`, static, on native, - wasip2 and wasip3; never on Emscripten, and never a default backend (design D34): a call names it. + and "ARGON2ID", HKDF over pieces (`hkdf_extract`, `hkdf_expand` and `hkdf` over `byte_pieces`) + over its `EVP_MAC` "HMAC", the digests of its default provider through `EVP_MD` and its MACs + through `EVP_MAC`, built from `third_party/libs/openssl` by `/webcpp/hash//openssl`, static, on + native, wasip2 and wasip3; never on Emscripten, and never a default backend (design D34): a call + names it. The key derivations have every hmac of `hmac.hpp` but `hmac_ripemd_128` (spec section 3.2). The digests are MD5, SHA-1, the six SHA-2, the four SHA-3, SHAKE128 and SHAKE256 (any output size), Keccak-224 to Keccak-512, BLAKE2s-256, BLAKE2b unkeyed (1 to 64 bytes), RIPEMD-160, MD5-SHA1 @@ -126,11 +128,12 @@ struct backend_limits { /** HKDF-Extract's salt is HMAC's key, whose length `HMAC_Init_ex` takes as an `int`. */ static constexpr std::uint64_t hkdf_salt = openssl_int_max; /** HKDF's IKM goes to `HMAC_Update` and its parameter in `size_t`s. */ - static constexpr std::uint64_t hkdf_ikm = no_limit; + static constexpr std::uint64_t hkdf_input_key_material = no_limit; /** HKDF-Expand's PRK is HMAC's key, as the salt is (always one digest). */ - static constexpr std::uint64_t hkdf_prk = openssl_int_max; - /** HKDF's info stays in a `size_t`, within OpenSSL's 32,768 bytes, `hkdf_max_info_size`. */ - static constexpr std::uint64_t hkdf_info = no_limit; + static constexpr std::uint64_t hkdf_pseudorandom_key = openssl_int_max; + /** HKDF's info stays in a `size_t`, within OpenSSL's 32,768 bytes, + * `hkdf_max_application_info_size`. */ + static constexpr std::uint64_t hkdf_application_info = no_limit; /** HKDF-Expand's output stays in a `size_t`, within 255 digests. */ static constexpr std::uint64_t hkdf_output = no_limit; /** PBKDF2's password is HMAC's key. */ @@ -561,75 +564,252 @@ 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_bytes The salt. @param ikm_bytes The input keying material. + @param salt 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_bytes, - std::span ikm_bytes) noexcept { + std::span salt, + std::span input_key_material) noexcept { int hkdf_mode = extract_only; std::array ossl_params{ openssl_text("digest", openssl_digest()), - openssl_octets("key", ikm_bytes), - openssl_octets("salt", salt_bytes), + openssl_octets("key", input_key_material), + openssl_octets("salt", salt), OSSL_PARAM_construct_int("mode", &hkdf_mode), OSSL_PARAM_construct_end(), }; // The PRK is derived into the result returned, whose wiping is the caller's: one return of // that one object, so that it is constructed in the caller's slot and no copy is left here. - boost::system::result prk_bytes{boost::system::in_place_value}; - digest_type& prk = prk_bytes.unsafe_value(); - const auto derive_result = - openssl_kdf("HKDF", std::span(prk.data(), prk.size()), ossl_params); + boost::system::result pseudorandom_key{boost::system::in_place_value}; + digest_type& pseudorandom_key_digest = pseudorandom_key.unsafe_value(); + const auto derive_result = openssl_kdf( + "HKDF", + std::span(pseudorandom_key_digest.data(), pseudorandom_key_digest.size()), + ossl_params); if (!derive_result) { - wipe_object(prk); - prk_bytes = derive_result.error(); + wipe_object(pseudorandom_key_digest); + pseudorandom_key = derive_result.error(); } - return prk_bytes; + return pseudorandom_key; } /** RFC 5869, 2.3, in expand-only mode. - @param output_bytes The OKM, its size L. @param prk_bytes The PRK. @param info_bytes 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( - std::span output_bytes, std::span prk_bytes, - std::span info_bytes) noexcept { + std::span output_key_material, std::span pseudorandom_key, + std::span application_info) noexcept { int hkdf_mode = expand_only; std::array ossl_params{ openssl_text("digest", openssl_digest()), - openssl_octets("key", prk_bytes), - openssl_octets("info", info_bytes), + openssl_octets("key", pseudorandom_key), + openssl_octets("info", application_info), OSSL_PARAM_construct_int("mode", &hkdf_mode), OSSL_PARAM_construct_end(), }; - return openssl_kdf("HKDF", output_bytes, ossl_params); + return openssl_kdf("HKDF", output_key_material, ossl_params); } /** RFC 5869, 2, in extract-and-expand mode: the PRK stays inside OpenSSL's context. - @param output_bytes The OKM. @param salt_bytes The salt. @param ikm_bytes The input keying - material. - @param info_bytes The info. + @param output_key_material The OKM. @param salt 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_bytes, std::span salt_bytes, - std::span ikm_bytes, - std::span info_bytes) noexcept { + std::span output_key_material, std::span salt, + 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", ikm_bytes), - openssl_octets("salt", salt_bytes), - openssl_octets("info", info_bytes), + openssl_octets("key", input_key_material), + openssl_octets("salt", salt), + openssl_octets("info", application_info), OSSL_PARAM_construct_int("mode", &hkdf_mode), OSSL_PARAM_construct_end(), }; - return openssl_kdf("HKDF", output_bytes, ossl_params); + return openssl_kdf("HKDF", output_key_material, ossl_params); + } +}; + +/** + HKDF over pieces on backends::openssl (the engine's interface: @ref hkdf_pieces_engine), over + OpenSSL's MAC "HMAC" rather than its KDF "HKDF", which takes the input keying material and the info + whole: RFC 5869 with every concatenation replaced by successive `EVP_MAC_update`s. Each call + fetches the MAC (`EVP_MAC_fetch`), makes a context (`EVP_MAC_CTX_new`) and keys it with the digest + the hmac names (`EVP_MAC_init`); Expand duplicates that keyed context for each block + (`EVP_MAC_CTX_dup`), so that the pseudorandom key is given to OpenSSL once. OpenSSL allocates the + contexts through its own allocator and frees them (`EVP_MAC_CTX_free`, whose HMAC clears its copy + of the key, as this header's comment says); hash wipes each block T(i) and the pseudorandom key + between the steps, on success and on failure. The thread's error queue is left as it was found, + and a failure is `errc::not_enough_memory` when an allocation failed, else + `error::backend_failure`, as @ref openssl_outcome reads them. The salt, HMAC's key, is at most + `INT_MAX` bytes (`HMAC_Init_ex` takes an `int`): `backend_limits::hkdf_salt`, + which the public functions guard. `EVP_MAC_update` takes a `size_t`, which holds every slice of + @ref hkdf_pieces_slice, so that a piece is sliced only by the test seam. + + @tparam Hmac A Boost.Hash2 hmac for which `openssl_hmac_v` holds. +*/ +template + requires openssl_hmac_v +struct hkdf_pieces_engine { + /** The hmac's result, a `digest`: the PRK and each block T(i). */ + using digest_type = Hmac::result_type; + + /** The most bytes of one update. */ + static constexpr std::uint64_t slice_max = hkdf_pieces_slice; + static_assert(slice_max <= std::numeric_limits::max(), + "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). + + @param mac_algorithm The MAC "HMAC", or null. @param key 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 { + if (mac_algorithm == nullptr) { + return nullptr; + } + EVP_MAC_CTX* mac_context = EVP_MAC_CTX_new(mac_algorithm); + std::array ossl_params{ + openssl_text("digest", openssl_digest()), + 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) { + EVP_MAC_CTX_free(mac_context); + mac_context = nullptr; + } + return mac_context; + } + + /** + Feeds every byte of `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. + @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; + }); + return updated; + } + + /** + Writes the HMAC of `mac_context` into `mac_result`, once OpenSSL's size of it is seen to be + the digest's. + + @param mac_context The context. @param mac_result The HMAC, of the digest's size. + @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; + 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(); + } + + /** + 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. + @return The PRK, or OpenSSL's failure. + */ + [[nodiscard]] static boost::system::result extract( + std::span salt, 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); + // 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) { + wipe_object(pseudorandom_key_digest); + pseudorandom_key = outcome.error(); + } + return pseudorandom_key; + } + + /** + RFC 5869, 2.3: T(0) = empty; T(i) = HMAC-Hash(PRK, T(i-1) | piece_1 | ... | piece_n | i); + OKM = the first L octets of T(1) | T(2) | ... | T(N), N = ceil(L/HashLen). Each block is + computed on a duplicate of the context keyed by the PRK. + + @param output_key_material The OKM, its size L. @param pseudorandom_key The PRK. + @param application_info The info's pieces. + @return Success, or OpenSSL's failure (the public function then zeroes the output). + */ + [[nodiscard]] static boost::system::result expand( + std::span output_key_material, std::span pseudorandom_key, + 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); + digest_type t_block{}; + bool computed = keyed != 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); + 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); + EVP_MAC_CTX_free(block_context); + if (computed) { + 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, + output_key_material.data() + written_count); + written_count += copied_count; + } + } + wipe_object(t_block); + // The frees raise no error: the outcome read after them is the computation's. + EVP_MAC_CTX_free(keyed); + EVP_MAC_free(mac_algorithm); + return openssl_outcome(computed); + } + + /** + 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 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, + 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); } }; @@ -669,7 +849,7 @@ struct pbkdf2_engine { The most memory OpenSSL's Argon2 takes, in KiB: m is a `uint32_t`, and the memory, m blocks of 1 KiB, a `size_t` (4,194,303 KiB on wasm32, where a larger m overflows it). */ -inline constexpr std::uint32_t openssl_argon2_max_memory_kib = static_cast( +inline constexpr std::uint32_t openssl_argon2_max_memory_kibibytes = static_cast( std::min(0xffffffffULL, std::numeric_limits::max() / 1024)); /** @@ -681,7 +861,7 @@ inline constexpr std::uint32_t openssl_argon2_max_memory_kib = static_cast password_bytes, std::span salt_bytes, argon2_parameters const& parameters) noexcept { std::uint32_t pass_count = parameters.passes; - std::uint32_t memory_kib = parameters.memory_kib; + std::uint32_t memory_kibibytes = parameters.memory_kibibytes; std::uint32_t lane_count = parameters.lanes; std::uint32_t thread_count = 1; // An empty secret or associated data is hashed as OpenSSL hashes none: its length, 0, alone. @@ -700,7 +880,7 @@ inline constexpr std::uint32_t openssl_argon2_max_memory_kib = static_cast { */ template struct openssl_argon2_engine { - /** RFC 9106's bounds, but the memory: at most `openssl_argon2_max_memory_kib`. */ + /** RFC 9106's bounds, but the memory: at most `openssl_argon2_max_memory_kibibytes`. */ static constexpr argon2_limits limits{ - .max_memory_kib = openssl_argon2_max_memory_kib, + .max_memory_kibibytes = openssl_argon2_max_memory_kibibytes, }; /** @@ -786,7 +966,7 @@ struct argon2id_engine { /** OpenSSL's m of at most 2^32 - 1 KiB, in bytes, within a `size_t` (4 GiB less 1 KiB on * wasm32). */ static constexpr argon2id_limits limits{ - .memory = std::uint64_t{openssl_argon2_max_memory_kib} * argon2id_memory_unit, + .memory = std::uint64_t{openssl_argon2_max_memory_kibibytes} * argon2id_memory_unit, }; /** @@ -806,7 +986,7 @@ struct argon2id_engine { openssl_argon2_name::value, output_bytes, password_bytes, salt_bytes, { .passes = static_cast(pass_count), - .memory_kib = static_cast(memory_limit / argon2id_memory_unit), + .memory_kibibytes = static_cast(memory_limit / argon2id_memory_unit), }); } }; @@ -1638,17 +1818,17 @@ struct openssl_digest_kdf_engine { The KDF `kdf_name` over `Digest`. @param kdf_name "SSKDF" or "X963KDF". @param output_bytes The output, its whole size. - @param secret_bytes Z. @param info_bytes FixedInfo or SharedInfo. + @param secret_bytes Z. @param application_info FixedInfo or SharedInfo. @return Success, or OpenSSL's failure. */ [[nodiscard]] static boost::system::result derive_with( char const* kdf_name, std::span output_bytes, std::span secret_bytes, - std::span info_bytes) noexcept { + std::span application_info) noexcept { std::array ossl_params{ openssl_text("digest", openssl_md_name::value), openssl_octets("secret", secret_bytes), - openssl_octets("info", info_bytes), + openssl_octets("info", application_info), OSSL_PARAM_construct_end(), }; return openssl_kdf(kdf_name, output_bytes, ossl_params); diff --git a/include/webcpp/hash/backends/sodium.hpp b/include/webcpp/hash/backends/sodium.hpp index f5f4e3d..cb68ba5 100644 --- a/include/webcpp/hash/backends/sodium.hpp +++ b/include/webcpp/hash/backends/sodium.hpp @@ -19,7 +19,10 @@ `crypto_pwhash_argon2i` and `crypto_pwhash_argon2id` (one lane, no secret, no associated data, Argon2i from 3 passes), built from source by `/third_party//sodium`, on every target. It has HKDF over `hmac_sha2_256` and `hmac_sha2_512` alone, and no PBKDF2; every other hmac and - PBKDF2 refuse at compile time with spec 3.3's texts. + PBKDF2 refuse at compile time with spec 3.3's texts. HKDF over pieces (`hkdf_extract`, + `hkdf_expand` and `hkdf` over `byte_pieces`), over the same two hmacs, runs on + `crypto_auth_hmacsha256_*` and `crypto_auth_hmacsha512_*` rather than libsodium's HKDF, whose + Expand takes the info whole. Its limits beyond the spec's: scrypt's N at most 4,294,967,295 (libsodium refuses a larger one); `argon2`'s values libsodium does not take, which the family answers with @@ -88,6 +91,7 @@ #include #include #include +#include #include #ifdef WEBCPP_HASH_SODIUM_CANARY_CONFIGURATION @@ -188,29 +192,32 @@ struct sodium_hkdf_sha256 { /** `crypto_kdf_hkdf_sha256_extract`. - @param prk_bytes The PRK. @param salt_bytes The salt. @param ikm_bytes The input keying - material. + @param pseudorandom_key The PRK. @param salt The salt. @param input_key_material The input + keying material. @return libsodium's status, 0 on success. */ - static int extract(std::uint8_t* prk_bytes, std::span salt_bytes, - std::span ikm_bytes) noexcept { + static int extract(std::uint8_t* pseudorandom_key, std::span salt, + 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(prk_bytes, salt_bytes.data(), salt_bytes.size(), - nonnull(ikm_bytes), ikm_bytes.size()); + return crypto_kdf_hkdf_sha256_extract(pseudorandom_key, salt.data(), salt.size(), + nonnull(input_key_material), + input_key_material.size()); } /** `crypto_kdf_hkdf_sha256_expand`, whose context is the info. - @param output_bytes The OKM. @param prk_bytes The PRK. @param info_bytes The info. + @param output_key_material The OKM. @param pseudorandom_key The PRK. @param application_info + The info. @return libsodium's status, 0 on success. */ - static int expand(std::span output_bytes, std::span prk_bytes, - std::span info_bytes) noexcept { + static int expand(std::span output_key_material, + std::span pseudorandom_key, + std::span application_info) noexcept { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): libsodium types ctx as char - return crypto_kdf_hkdf_sha256_expand(output_bytes.data(), output_bytes.size(), - reinterpret_cast(info_bytes.data()), - info_bytes.size(), prk_bytes.data()); + return crypto_kdf_hkdf_sha256_expand(output_key_material.data(), output_key_material.size(), + reinterpret_cast(application_info.data()), + application_info.size(), pseudorandom_key.data()); } }; @@ -224,30 +231,33 @@ struct sodium_hkdf_sha512 { /** `crypto_kdf_hkdf_sha512_extract`. - @param prk_bytes The PRK. @param salt_bytes The salt. @param ikm_bytes The input keying - material. + @param pseudorandom_key The PRK. @param salt The salt. @param input_key_material The input + keying material. @return libsodium's status, 0 on success. */ - static int extract(std::uint8_t* prk_bytes, std::span salt_bytes, - std::span ikm_bytes) noexcept { + static int extract(std::uint8_t* pseudorandom_key, std::span salt, + 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(prk_bytes, salt_bytes.data(), salt_bytes.size(), - nonnull(ikm_bytes), ikm_bytes.size()); + return crypto_kdf_hkdf_sha512_extract(pseudorandom_key, salt.data(), salt.size(), + nonnull(input_key_material), + input_key_material.size()); } /** `crypto_kdf_hkdf_sha512_expand`, whose context is the info. - @param output_bytes The OKM. @param prk_bytes The PRK. @param info_bytes The info. + @param output_key_material The OKM. @param pseudorandom_key The PRK. @param application_info + The info. @return libsodium's status, 0 on success. */ - static int expand(std::span output_bytes, std::span prk_bytes, - std::span info_bytes) noexcept { + static int expand(std::span output_key_material, + std::span pseudorandom_key, + std::span application_info) noexcept { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): libsodium types ctx as char - return crypto_kdf_hkdf_sha512_expand(output_bytes.data(), output_bytes.size(), - reinterpret_cast(info_bytes.data()), - info_bytes.size(), prk_bytes.data()); + return crypto_kdf_hkdf_sha512_expand(output_key_material.data(), output_key_material.size(), + reinterpret_cast(application_info.data()), + application_info.size(), pseudorandom_key.data()); } }; @@ -266,37 +276,39 @@ 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_bytes The salt. @param ikm_bytes The input keying material. + @param salt 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_bytes, - std::span ikm_bytes) noexcept { + std::span salt, + 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 the result is constructed in the caller's place - // (no copy or move, which would leave a PRK behind that nothing wipes). - boost::system::result prk_bytes{boost::system::in_place_value}; - if (!sodium_ready() || - Traits::extract(prk_bytes.unsafe_value().data(), salt_bytes, ikm_bytes) != 0) { - wipe_object(prk_bytes.unsafe_value()); - prk_bytes = boost::system::result(error::backend_failure); + // 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, + input_key_material) != 0) { + wipe_object(pseudorandom_key.unsafe_value()); + pseudorandom_key = boost::system::result(error::backend_failure); } - return prk_bytes; + return pseudorandom_key; } /** RFC 5869, 2.3, by libsodium's `_expand`. - @param output_bytes The OKM, its size L. @param prk_bytes The PRK. @param info_bytes 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( - std::span output_bytes, std::span prk_bytes, - std::span info_bytes) noexcept { + std::span output_key_material, std::span pseudorandom_key, + std::span application_info) noexcept { if (!sodium_ready()) { return error::backend_failure; } - if (Traits::expand(output_bytes, prk_bytes, info_bytes) != 0) { + if (Traits::expand(output_key_material, pseudorandom_key, application_info) != 0) { return error::backend_failure; } return {}; @@ -305,23 +317,23 @@ struct sodium_hkdf_engine { /** RFC 5869, 2: HKDF-Extract into a local PRK, HKDF-Expand, and the PRK wiped. - @param output_bytes The OKM. @param salt_bytes The salt. @param ikm_bytes The input keying - material. - @param info_bytes The info. + @param output_key_material The OKM. @param salt 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_bytes, std::span salt_bytes, - std::span ikm_bytes, - std::span info_bytes) noexcept { - auto prk_bytes = extract(salt_bytes, ikm_bytes); - if (!prk_bytes) { - return prk_bytes.error(); + std::span output_key_material, std::span salt, + std::span input_key_material, + std::span application_info) noexcept { + auto pseudorandom_key = extract(salt, input_key_material); + if (!pseudorandom_key) { + return pseudorandom_key.error(); } - digest_type& key_bytes = prk_bytes.unsafe_value(); - auto derive_result = - expand(output_bytes, std::span(key_bytes.data(), key_bytes.size()), - info_bytes); + digest_type& key_bytes = pseudorandom_key.unsafe_value(); + auto derive_result = expand( + output_key_material, std::span(key_bytes.data(), key_bytes.size()), + application_info); wipe_object(key_bytes); return derive_result; } @@ -353,27 +365,182 @@ struct hkdf_engine { /** Never called: the refusal has stopped the build. */ [[nodiscard]] static boost::system::result extract( - std::span /*salt_bytes*/, - std::span /*ikm_bytes*/) noexcept { + std::span /*salt*/, + std::span /*input_key_material*/) noexcept { return error::backend_failure; } /** Never called: the refusal has stopped the build. */ [[nodiscard]] static boost::system::result expand( - std::span /*output_bytes*/, std::span /*prk_bytes*/, - std::span /*info_bytes*/) noexcept { + std::span /*output_key_material*/, + std::span /*pseudorandom_key*/, + std::span /*application_info*/) noexcept { return error::backend_failure; } /** Never called: the refusal has stopped the build. */ [[nodiscard]] static boost::system::result extract_and_expand( - std::span /*output_bytes*/, std::span /*salt_bytes*/, - std::span /*ikm_bytes*/, - std::span /*info_bytes*/) noexcept { + std::span /*output_key_material*/, std::span /*salt*/, + std::span /*input_key_material*/, + std::span /*application_info*/) noexcept { return error::backend_failure; } }; +/** + HKDF over pieces on backends::sodium (the engine's interface: @ref hkdf_pieces_engine), over + libsodium's streaming HMAC `crypto_auth_hmacsha*_init`, `_update` and `_final` rather than its + HKDF, whose Expand takes the info whole: RFC 5869 with every concatenation replaced by successive + updates. The state struct keyed by the pseudorandom key is made once and copied for each block; + every state, each block T(i) and the pseudorandom key between the steps are wiped, on success and + on failure. `_update` takes an `unsigned long long`, which holds every slice of + @ref hkdf_pieces_slice (a `size_t`'s range at most), so that a piece is sliced only by the test + seam. + + @tparam Hmac The hmac, `hmac_sha2_256` or `hmac_sha2_512`. @tparam State libsodium's state. + @tparam Init libsodium's `_init`. @tparam Update libsodium's `_update`. @tparam Final libsodium's + `_final`. +*/ +template +struct sodium_hkdf_pieces_engine { + /** The hmac's result, a `digest`: the PRK and each block T(i). */ + using digest_type = Hmac::result_type; + + /** The most bytes of one update. */ + static constexpr std::uint64_t slice_max = hkdf_pieces_slice; + static_assert(slice_max <= std::numeric_limits::max(), + "libsodium's _update takes every slice's length"); + + /** + Feeds every byte of `pieces` to `state`, in slices of at most @ref slice_max bytes. + + @param state The HMAC state. @param pieces The pieces. + @return Whether libsodium took every slice. + */ + [[nodiscard]] static bool update_all(State& state, byte_pieces 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); + }); + return updated; + } + + /** + Feeds one slice to `state`. + + @param state The HMAC state. @param slice 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; + } + + /** + 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. + @return The PRK, or `error::backend_failure`. + */ + [[nodiscard]] static boost::system::result extract( + std::span salt, 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; + wipe_object(mac_state); + if (!computed) { + wipe_object(pseudorandom_key.unsafe_value()); + pseudorandom_key = boost::system::result(error::backend_failure); + } + return pseudorandom_key; + } + + /** + RFC 5869, 2.3: T(0) = empty; T(i) = HMAC-Hash(PRK, T(i-1) | piece_1 | ... | piece_n | 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's pieces. + @return Success, or `error::backend_failure` (the public function then zeroes the output). + */ + [[nodiscard]] static boost::system::result expand( + 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; + digest_type t_block{}; + std::size_t written_count = 0; + for (unsigned block_counter = 1; computed && written_count < output_key_material.size(); + ++block_counter) { + State mac_state = keyed_state; + auto const octet_value = static_cast(block_counter); + computed = + (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; + wipe_object(mac_state); + if (computed) { + 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, + output_key_material.data() + written_count); + written_count += copied_count; + } + } + wipe_object(t_block); + wipe_object(keyed_state); + if (!computed) { + return error::backend_failure; + } + return {}; + } + + /** + 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 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, + 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); + } +}; + +/** + HKDF over pieces on backends::sodium over HMAC-SHA-256: `crypto_auth_hmacsha256_*`. +*/ +template <> +struct hkdf_pieces_engine + : sodium_hkdf_pieces_engine {}; + +/** + HKDF over pieces on backends::sodium over HMAC-SHA-512: `crypto_auth_hmacsha512_*`. +*/ +template <> +struct hkdf_pieces_engine + : sodium_hkdf_pieces_engine {}; + /** PBKDF2 on backends::sodium: refuses with spec 3.3's text, libsodium having no PBKDF2. The member exists so that the refusal is the only error. @@ -1021,7 +1188,7 @@ struct sodium_argon2_engine { /** One lane, no secret, no associated data, libsodium's salt and shortest tag. */ static constexpr argon2_limits limits{ .min_passes = MinPasses, - .max_memory_kib = static_cast(MaxMemory / argon2id_memory_unit), + .max_memory_kibibytes = static_cast(MaxMemory / argon2id_memory_unit), .max_lanes = 1, .min_output = argon2id_min_output_size, .min_salt = argon2id_salt_size, @@ -1050,7 +1217,7 @@ struct sodium_argon2_engine { // 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_kib} * argon2id_memory_unit, + parameters.passes, std::size_t{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 f2ff751..61fd32d 100644 --- a/include/webcpp/hash/backends/webcrypto.hpp +++ b/include/webcpp/hash/backends/webcrypto.hpp @@ -8,22 +8,26 @@ `backends::webcrypto`: the browser's WebCrypto (`crypto.subtle`, the Web Cryptography API) as a backend of the asynchronous family of ``, on Emscripten, where the browsers and node have it (tested under node): `async_digest` over SHA-1, SHA-256, SHA-384 and - SHA-512, and `async_hmac`, `async_hkdf` and `async_pbkdf2` over the hmacs of those four. It is - never a default: a program names it in the type. No synchronous function takes it. + SHA-512, and `async_hmac`, `async_hkdf`, `async_hkdf_extract`, `async_hkdf_expand` (each HKDF + function also over `byte_pieces`) and `async_pbkdf2` over the hmacs of those four. It is never a + default: a program names it in the type. No synchronous function takes it. Each operation builds WebCrypto's call with `emscripten::val` (`digest`; `importKey`, then `sign` or `deriveBits`), awaits its promise through webcpp::asio's `webcpp::asio::browser::async_await`, and copies the resulting bytes into the output in its completion; a rejected promise is `error::backend_failure`, and a cancellation through the - handler's slot `asio::error::operation_aborted`, both with the output zeroed. The same guards as - the synchronous function run first, then WebCrypto's own limits (`detail::backend_limits`), then - the executor's check (ruling R73): its context must be an `io_context`, checked at compile time - for a concrete executor and at run time for a type-erased one (`invalid_parameters`). That the - `io_context` runs on the calling thread, whose `run` returns to the JavaScript event loop where - the promise settles, is the program's duty: it cannot be checked. A refusal completes through a - post to the handler's associated executor (the executor given, unless the handler is bound to - another), the output untouched; a runtime without WebCrypto is `backend_failure`, the output - zeroed. + handler's slot `asio::error::operation_aborted`, both with the output zeroed. The single-buffer + `async_hkdf` is `deriveBits` (an info of at most 1,024 bytes, node's limit); HKDF's two steps and + every form over pieces run RFC 5869 on WebCrypto's HMAC, one `sign` per block, the pieces gathered + into JavaScript memory in the initiating call and every buffer that held a secret zeroed at the + end. The same guards as the synchronous function run first, then WebCrypto's own limits + (`detail::backend_limits`), then the executor's check (ruling R73): its context must be an + `io_context`, checked at compile time for a concrete executor and at run time for a type-erased + one (`invalid_parameters`). That the `io_context` runs on the calling thread, whose `run` returns + to the JavaScript event loop where the promise settles, is the program's duty: it cannot be + checked. A refusal completes through a post to the handler's associated executor (the executor + given, unless the handler is bound to another), the output untouched; a runtime without WebCrypto + is `backend_failure`, the output zeroed. `async.hpp` includes this header: a program includes either. It needs webcpp::asio (`/webcpp/asio//asio`) and nothing else; off Emscripten it holds only the limits, since @@ -56,18 +60,24 @@ namespace webcpp::hash::detail { `deriveBits` takes its length in bits as an `unsigned long`, so an output of HKDF or PBKDF2 is at most (2^32 - 1) / 8 bytes; PBKDF2's iteration count is an `unsigned long`, at most 2^32 - 1; node refuses an HKDF info longer than 1,024 bytes ("algorithm.info must be at most 1024 - bytes"), where the other backends take `hkdf_max_info_size`. No limit elsewhere. + bytes"), where the other backends take `hkdf_max_application_info_size`: a limit of the + single-buffer `async_hkdf` alone, since HKDF's steps and HKDF over pieces run on WebCrypto's HMAC. + No limit elsewhere. */ template <> struct backend_limits { /** HKDF's salt: no limit of WebCrypto's own. */ static constexpr std::uint64_t hkdf_salt = no_limit; /** HKDF's input keying material: no limit of WebCrypto's own. */ - static constexpr std::uint64_t hkdf_ikm = no_limit; - /** HKDF's pseudorandom key: WebCrypto has no `hkdf_expand` (no limit to state). */ - static constexpr std::uint64_t hkdf_prk = no_limit; - /** HKDF's info: node's 1,024 bytes (`input_too_long` beyond). */ - static constexpr std::uint64_t hkdf_info = 1024; + static constexpr std::uint64_t hkdf_input_key_material = no_limit; + /** HKDF's pseudorandom key, Expand's HMAC key: no limit of WebCrypto's own. */ + static constexpr std::uint64_t hkdf_pseudorandom_key = no_limit; + /** + HKDF's info in `deriveBits`, which the single-buffer `async_hkdf` calls: node's 1,024 bytes + (`input_too_long` beyond). `async_hkdf_expand` and the forms over pieces run on HMAC and do + not read it. + */ + static constexpr std::uint64_t hkdf_application_info = 1024; /** HKDF's output: `deriveBits`' length, (2^32 - 1) bits, in whole bytes. */ static constexpr std::uint64_t hkdf_output = 0xffffffffULL / 8; /** PBKDF2's password: no limit of WebCrypto's own. */ @@ -96,7 +106,9 @@ struct backend_limits { #ifdef WEBCPP_TARGET_EMSCRIPTEN +#include #include +#include #include #include #include @@ -119,11 +131,13 @@ struct backend_limits { #include #include +#include #include #include #include +#include #include #include #include @@ -370,8 +384,8 @@ struct webcrypto_hmac_request { }; /** - `importKey("raw", ikm, "HKDF", false, ["deriveBits"])`, then - `deriveBits({name: "HKDF", hash, salt, info}, key, bits)`. + `importKey("raw", the input key material, "HKDF", false, ["deriveBits"])`, then + `deriveBits({name: "HKDF", hash, salt, info: application_info}, key, bits)`. */ struct webcrypto_hkdf_request { /** WebCrypto's name of the hash. */ @@ -379,10 +393,10 @@ struct webcrypto_hkdf_request { /** The salt. */ std::span salt; /** The input keying material. */ - std::span ikm; - /** The info. */ - std::span info; - /** The output's length in bits, within `backend_limits`. */ + std::span input_key_material; + /** The application info. */ + std::span application_info; + /** The output key material's length in bits, within `backend_limits`. */ std::uint32_t bits; /** The call has two promises: the key, then the bits. */ @@ -390,9 +404,9 @@ struct webcrypto_hkdf_request { /** 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(ikm), emscripten::val("HKDF"), - emscripten::val(false), webcrypto_usages("deriveBits")); + return subtle.call( + "importKey", emscripten::val("raw"), webcrypto_bytes(input_key_material), + emscripten::val("HKDF"), emscripten::val(false), webcrypto_usages("deriveBits")); } /** @@ -405,7 +419,7 @@ struct webcrypto_hkdf_request { algorithm.set("name", emscripten::val("HKDF")); algorithm.set("hash", emscripten::val(hash)); algorithm.set("salt", webcrypto_bytes(salt)); - algorithm.set("info", webcrypto_bytes(info)); + algorithm.set("info", webcrypto_bytes(application_info)); return subtle.call("deriveBits", algorithm, imported, emscripten::val(bits)); } @@ -556,10 +570,48 @@ class webcrypto_operation { }; /** - The initiation of a WebCrypto call: the guards' verdict, then the executor's check (ruling R73), - then `crypto.subtle`'s presence; a refusal is posted to the handler's associated executor - (`executor` by default) with its error, the output untouched by a guard's refusal and the - executor's, zeroed when WebCrypto is missing (`backend_failure`); else the composed operation + Whether a WebCrypto call is refused before it starts: the guards' verdict, then the executor's + 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. +*/ +template +boost::system::error_code webcrypto_refusal(Executor const& executor, + std::span output, + boost::system::result const& guarded) { + if (!guarded) { + return guarded.error(); + } + if (!webcrypto_executor_accepted(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. + wipe(output); + return error::backend_failure; + } + return {}; +} + +/** + Posts a refusal to the handler's associated executor (`executor` by default). + + @param handler The completion handler. @param executor The io_context's executor. + @param refusal 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)); +} + +/** + 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. */ struct webcrypto_initiation { @@ -574,21 +626,9 @@ struct webcrypto_initiation { void operator()(Handler&& handler, Executor const& executor, std::span output, std::size_t produced, Request const& request, boost::system::result const& guarded) const { - boost::system::error_code refusal; - if (!guarded) { - refusal = guarded.error(); - } else if (!webcrypto_executor_accepted(executor)) { - refusal = error::invalid_parameters; - } else 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. - wipe(output); - refusal = error::backend_failure; - } + auto const refusal = webcrypto_refusal(executor, output, guarded); if (refusal) { - auto const target = webcpp::asio::get_associated_executor(handler, executor); - webcpp::asio::post(target, - webcpp::asio::append(std::forward(handler), refusal)); + post_webcrypto_refusal(std::forward(handler), executor, refusal); return; } std::decay_t owned(std::forward(handler)); @@ -614,6 +654,515 @@ auto start_webcrypto(Executor const& executor, std::span output, s webcrypto_initiation{}, token, executor, output, produced, request, guarded); } +/** + A JavaScript `Uint8Array` that holds a secret (an HMAC key, an input keying material, Expand's + blocks, a tag), zeroed (`fill(0)`) when it is wiped and when it is dropped: after the last call + that reads it has settled, at the operation's end, on a refusal, and when a deferred operation is + never launched. It moves and does not copy, so that one holder owns each buffer. +*/ +class webcrypto_secret { +public: + /** No buffer. */ + webcrypto_secret() = default; + + /** The buffer `bytes`. @param bytes A `Uint8Array`. */ + explicit webcrypto_secret(emscripten::val bytes) noexcept : bytes_(std::move(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())) {} + + /** + Wipes this buffer, then takes `other`'s. @param other The holder. @return This holder. + */ + webcrypto_secret& operator=(webcrypto_secret&& other) noexcept { + if (this != &other) { + wipe(); + bytes_ = std::exchange(other.bytes_, emscripten::val::undefined()); + } + return *this; + } + + webcrypto_secret(webcrypto_secret const&) = delete; + webcrypto_secret& operator=(webcrypto_secret const&) = delete; + + /** Wipes the buffer. */ + ~webcrypto_secret() { wipe(); } + + /** @return The `Uint8Array`, or `undefined` when there is none. */ + [[nodiscard]] emscripten::val const& bytes() const noexcept { return bytes_; } + + /** @return The `Uint8Array`, or `undefined` when there is none. */ + [[nodiscard]] emscripten::val& bytes() noexcept { return bytes_; } + + /** Zeroes the buffer and lets it go. */ + void wipe() noexcept { + if (!bytes_.isUndefined()) { + bytes_.call("fill", 0); + bytes_ = emscripten::val::undefined(); + } + } + +private: + emscripten::val bytes_ = emscripten::val::undefined(); +}; + +#ifdef WEBCPP_HASH_DETAIL_TEST_WEBCRYPTO_MAX_GATHERED +// The test seam's value; the Doc Comment is in the #else branch, the one the reference reads. +inline constexpr std::uint64_t webcrypto_max_gathered = + WEBCPP_HASH_DETAIL_TEST_WEBCRYPTO_MAX_GATHERED; +#else +/** + The longest buffer the pieces are gathered into, 2^53 - 1 bytes: a typed array's length is a + JavaScript Number, exact up to there, so that the sum of the pieces' sizes is never rounded. Pieces + whose total, with Expand's block around the info, is longer fail with `backend_failure`, the output + zeroed, before any buffer is made. A runtime refuses far shorter buffers, as its memory allows: + that refusal is caught (@ref webcrypto_new_bytes) and fails likewise. The test seam + `WEBCPP_HASH_DETAIL_TEST_WEBCRYPTO_MAX_GATHERED` lowers it, so that a test reaches the refusal. +*/ +inline constexpr std::uint64_t webcrypto_max_gathered = (std::uint64_t{1} << 53U) - 1; +#endif +// Expand's block is HashLen + |info| + 1 bytes, HashLen at most 64: the bound holds its two ends. +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. + + @param length The length, at most @ref webcrypto_max_gathered. @return The array, or `undefined`. +*/ +inline emscripten::val webcrypto_new_bytes(double 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({ + try { + return Emval.toHandle(new Uint8Array($0)); + } catch (error) { + return Emval.toHandle(undefined); + } + }, 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). +*/ +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; + } + 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()); + } + } + return gathered; +} + +/** Which steps of HKDF an operation over WebCrypto's HMAC runs. */ +enum class webcrypto_hkdf_steps : std::uint8_t { + /** HKDF-Extract alone: the pseudorandom key into the output. */ + extract, + /** HKDF-Expand alone, from the caller's pseudorandom key. */ + expand, + /** Both, the pseudorandom key kept in JavaScript memory between them. */ + extract_and_expand, +}; + +/** + HKDF (RFC 5869) over WebCrypto's HMAC, as its operation needs it: every input already in + JavaScript memory, gathered in the initiating call. +*/ +struct webcrypto_hmac_hkdf_request { + /** WebCrypto's name of the hash. */ + char const* hash = ""; + /** HashLen, the digest's size. */ + std::size_t digest_length = 0; + /** The steps it runs. */ + webcrypto_hkdf_steps steps = webcrypto_hkdf_steps::extract; + /** Extract's HMAC key: the salt, or HashLen zeros for an empty one (design D2). */ + webcrypto_secret salt; + /** Extract's message: the input keying material's pieces, gathered. */ + webcrypto_secret input_key_material; + /** Expand's HMAC key: the caller's (Expand alone), else Extract's tag. */ + webcrypto_secret pseudorandom_key; + /** + Expand's message buffer, HashLen + |info| + 1 bytes: `T(i-1) || info || i`, the info's pieces + gathered at offset HashLen. + */ + webcrypto_secret blocks; + /** + Whether every input is in JavaScript memory: false once the pieces are longer than + @ref webcrypto_max_gathered or the runtime has refused a buffer, after which nothing more is + gathered and the operation fails with `backend_failure`. + */ + bool gathered = true; + + /** + Gathers Extract's inputs: the salt (HashLen zeros for an empty one) and the input keying + material's pieces. + + @param salt_bytes The salt. @param input_key_material_pieces The input keying material. + */ + void gather_extract(std::span salt_bytes, + byte_pieces input_key_material_pieces) { + if (input_key_material_pieces.total_size() > webcrypto_max_gathered) { + gathered = false; + return; + } + if (salt_bytes.empty()) { + gather(salt, {}, digest_length, 0); + } else { + gather(salt, {salt_bytes}, 0, 0); + } + gather(input_key_material, input_key_material_pieces, 0, 0); + } + + /** + Gathers Expand's HMAC key, the caller's pseudorandom key (Expand alone). + + @param key The pseudorandom key. + */ + void gather_pseudorandom_key(std::span key) { + gather(pseudorandom_key, {key}, 0, 0); + } + + /** + Gathers Expand's message buffer around the application info's pieces; nothing once an earlier + input was not gathered (Extract's, for `hkdf`), since the operation fails then. + + @param application_info The application info. + */ + void gather_expand(byte_pieces application_info) { + if (gathered && + application_info.total_size() > webcrypto_max_gathered - digest_length - 1) { + gathered = false; + return; + } + gather(blocks, application_info, digest_length, 1); + } + +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) { + if (gathered) { + buffer = webcrypto_gather(pieces, prefix, suffix); + gathered = !buffer.bytes().isUndefined(); + } + } +}; + +/** + HKDF over WebCrypto's HMAC as an Asio composed operation (`async_compose`), each promise awaited + through `browser::async_await` as @ref webcrypto_operation does: Extract is `importKey` of the + salt, then `sign` over the input keying material, its tag the pseudorandom key; Expand is + `importKey` of the pseudorandom key, then one `sign` per block, over the view `info || 1` of the + message buffer for the first and over `T(i-1) || info || i` for the others, each `T(i)` copied + into the output when its promise settles and into the buffer for the next block. + + Its state is `emscripten::val`s and the output's span, nothing of the C++ heap; its storage is the + bridge's, one wait at a time, from the handler's associated allocator (and `browser::async_await`'s + one C block per promise). Every JavaScript buffer that held a secret is zeroed once the promise of + the last call that reads it has settled, and every one at the completion, on success, failure and + cancellation. A rejected promise or a result of another size is `backend_failure`, a `terminal` or + `partial` cancellation `operation_aborted` at once, both with the output zeroed (the blocks + already written among it); a promise that settles after a cancellation writes nothing. + + @tparam Executor The io_context's executor. +*/ +template +class webcrypto_hmac_hkdf_operation { +public: + /** + The operation of `request` into `output`. + + @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. + */ + webcrypto_hmac_hkdf_operation(Executor executor, std::span output, + webcrypto_hmac_hkdf_request request) + : executor_(std::move(executor)), output_(output), request_(std::move(request)) {} + + /** + Starts the operation: the first `importKey`, of the salt, or of the pseudorandom key for + Expand alone. + + @param self The composed operation. + */ + template + void operator()(Self& self) { + 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())); + } else { + step_ = step::import_salt; + await(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`. + */ + 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))); + return; + } + switch (step_) { + case step::import_salt: + request_.salt.wipe(); + key_ = value; + if (!stopped(self)) { + step_ = step::sign_input_key_material; + await(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)); + 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()); + return; + } + request_.pseudorandom_key = webcrypto_secret(uint8_array(value)); + if (!stopped(self)) { + step_ = step::import_pseudorandom_key; + await(self, import_key(request_.pseudorandom_key.bytes())); + } + return; + case step::import_pseudorandom_key: + request_.pseudorandom_key.wipe(); + key_ = value; + if (!stopped(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)))); + } + return; + case step::sign_block: next_block(self, value); return; + } + } + +private: + // The step whose promise the operation awaits. + enum class step : std::uint8_t { + import_salt, + sign_input_key_material, + import_pseudorandom_key, + sign_block, + }; + + // 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)); + 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; + if (written_ == output_.size()) { + tag.wipe(); + self.complete(finish()); + return; + } + request_.blocks.bytes().call("set", tag.bytes(), 0); + tag.wipe(); + if (!stopped(self)) { + ++block_; + request_.blocks.bytes().set(counter_index(), block_); + await(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) { + return false; + } + 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)); + } + + // 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), + 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); + } + + // 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; + } + + // A Uint8Array over the ArrayBuffer `buffer`. + [[nodiscard]] static emscripten::val uint8_array(emscripten::val const& buffer) { + return emscripten::val::global("Uint8Array").new_(buffer); + } + + // The index of the block counter in the message buffer, its last byte. + [[nodiscard]] double counter_index() const { + return request_.blocks.bytes()["length"].as() - 1; + } + + // 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))); + } + + // Every JavaScript buffer zeroed and the key let go. + void release() noexcept { + request_.salt.wipe(); + request_.input_key_material.wipe(); + request_.pseudorandom_key.wipe(); + request_.blocks.wipe(); + key_ = emscripten::val::undefined(); + } + + // The buffers released: the completion's success. + [[nodiscard]] boost::system::error_code finish() noexcept { + release(); + return {}; + } + + // The output zeroed and the buffers released, with the completion's error. + [[nodiscard]] boost::system::error_code fail(boost::system::error_code code) noexcept { + wipe(output_); + release(); + return code; + } + + Executor executor_; + std::span output_; + webcrypto_hmac_hkdf_request request_; + emscripten::val key_ = emscripten::val::undefined(); + step step_ = step::import_salt; + std::uint8_t block_ = 0; + std::size_t written_ = 0; +}; + +/** + The initiation of HKDF over WebCrypto's HMAC: @ref webcrypto_refusal, then whether every input was + gathered (`backend_failure`, the output zeroed, else); a refusal is posted to the handler's + associated executor, the request's buffers zeroed as it is dropped; else the composed operation + starts. +*/ +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. + */ + 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) { + wipe(output); + refusal = error::backend_failure; + } + if (refusal) { + post_webcrypto_refusal(std::forward(handler), executor, refusal); + return; + } + std::decay_t owned(std::forward(handler)); + webcpp::asio::async_compose, void(boost::system::error_code)>( + webcrypto_hmac_hkdf_operation(executor, output, std::move(request)), owned, + executor); + } +}; + +/** + The request over `Hmac`'s hash running `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. +*/ +template +webcrypto_hmac_hkdf_request webcrypto_hmac_hkdf_of(webcrypto_hkdf_steps 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; +} + +/** + 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. + @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) { + return webcpp::asio_backend::async_initiate( + webcrypto_hmac_hkdf_initiation{}, token, executor, output, std::move(request), guarded); +} + /** The asynchronous family on `backends::webcrypto` (spec 11.1): each function checks the synchronous function's guards and WebCrypto's limits, then the executor, then runs WebCrypto's @@ -621,6 +1170,34 @@ auto start_webcrypto(Executor const& executor, std::span output, s */ template <> struct async_engine { +private: + // 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 { + // 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) { + return error::invalid_output_size; + } + return {}; + } + + // HKDF-Expand's guards, the synchronous hkdf_expand's order: RFC 5869's output size, then the + // pseudorandom key's size (invalid_key_size). + template + [[nodiscard]] static boost::system::result expand_guards( + 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) { + return error::invalid_key_size; + } + return guarded; + } + +public: /** `async_digest`: `crypto.subtle.digest`. @@ -669,26 +1246,173 @@ struct async_engine { `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 The output keying material. - @param salt The salt. @param ikm The input keying material. @param info The info. + @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 + application_info The application info. @param token The completion token. @return What the completion token's `async_result` gives. */ template - static auto hkdf(Executor const& executor, std::span output, - std::span salt, std::span ikm, - std::span info, CompletionToken&& token) { + static auto hkdf(Executor const& executor, std::span output_key_material, + std::span salt, + std::span input_key_material, + std::span application_info, CompletionToken&& token) { using digest = digest_tag_of::type; - auto const guarded = hkdf_guards(output.size(), salt.size(), - ikm.size(), info.size()); + auto const guarded = hkdf_guards( + output_key_material.size(), salt.size(), input_key_material.size(), + application_info.size()); webcrypto_hkdf_request const request{ .hash = webcrypto_hash_name, .salt = salt, - .ikm = ikm, - .info = info, - .bits = static_cast(guarded ? output.size() * 8 : 0), + .input_key_material = input_key_material, + .application_info = application_info, + .bits = static_cast(guarded ? output_key_material.size() * 8 : 0), }; - return start_webcrypto(executor, output, output.size(), request, guarded, token); + return start_webcrypto(executor, output_key_material, output_key_material.size(), request, + guarded, token); + } + + /** + `async_hkdf` over pieces: HKDF over WebCrypto's HMAC (`importKey`, then `sign`), as + @ref webcrypto_hmac_hkdf_operation runs it, the pieces gathered into JavaScript memory in + 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. + @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) { + 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); + // Nothing when Extract's inputs were not gathered: the operation fails then. + request.gather_expand(application_info); + } + return start_webcrypto_hmac_hkdf(executor, output_key_material, std::move(request), guarded, + token); + } + + /** + `async_hkdf_extract`, single-buffer: HKDF-Extract over WebCrypto's HMAC (`importKey` of the + 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. + @return What the completion token's `async_result` gives. + */ + template + static auto hkdf_extract(Executor const& executor, std::span pseudorandom_key, + std::span salt, + std::span input_key_material, + CompletionToken&& token) { + timing_guard const timing; + auto guarded = extract_size_guard(pseudorandom_key.size()); + if (guarded) { + guarded = + hkdf_extract_guards(salt.size(), input_key_material.size()); + } + auto request = webcrypto_hmac_hkdf_of(webcrypto_hkdf_steps::extract); + if (guarded) { + request.gather_extract(salt, {input_key_material}); + } + return start_webcrypto_hmac_hkdf(executor, pseudorandom_key, std::move(request), guarded, + token); + } + + /** + `async_hkdf_extract` over pieces: HKDF-Extract over WebCrypto's HMAC, the pieces gathered + 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. + @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) { + timing_guard const timing; + auto guarded = extract_size_guard(pseudorandom_key.size()); + if (guarded) { + guarded = hkdf_pieces_salt_guard(salt.size()); + } + auto request = webcrypto_hmac_hkdf_of(webcrypto_hkdf_steps::extract); + if (guarded) { + request.gather_extract(salt, input_key_material); + } + return start_webcrypto_hmac_hkdf(executor, pseudorandom_key, std::move(request), guarded, + token); + } + + /** + `async_hkdf_expand`, single-buffer: HKDF-Expand over WebCrypto's HMAC (`importKey` of the + pseudorandom key, then one `sign` per block), the application info its one piece. It keeps + the single-buffer forms' `hkdf_max_application_info_size` (ruling R3 of the change + 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. + @return What the completion token's `async_result` gives. + */ + template + static auto hkdf_expand(Executor const& executor, std::span output_key_material, + std::span pseudorandom_key, + std::span application_info, + CompletionToken&& token) { + 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; + } + auto request = webcrypto_hmac_hkdf_of(webcrypto_hkdf_steps::expand); + if (guarded) { + request.gather_pseudorandom_key(pseudorandom_key); + request.gather_expand({application_info}); + } + return start_webcrypto_hmac_hkdf(executor, output_key_material, std::move(request), guarded, + token); + } + + /** + `async_hkdf_expand` over pieces: HKDF-Expand over WebCrypto's HMAC, the pseudorandom key and + 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. + @return What the completion token's `async_result` gives. + */ + template + static auto hkdf_expand(Executor const& executor, std::span output_key_material, + std::span pseudorandom_key, + byte_pieces application_info, CompletionToken&& token) { + timing_guard const timing; + auto const guarded = + 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); + } + return start_webcrypto_hmac_hkdf(executor, output_key_material, std::move(request), guarded, + token); } /** diff --git a/include/webcpp/hash/backends/xkcp.hpp b/include/webcpp/hash/backends/xkcp.hpp index 2fb6aaa..084bf6b 100644 --- a/include/webcpp/hash/backends/xkcp.hpp +++ b/include/webcpp/hash/backends/xkcp.hpp @@ -790,7 +790,7 @@ struct xkcp_kangarootwelve_engine : full_engine { /** XKCP's `KangarooTwelve_Instance`, in storage the adapter checks is large enough. */ xkcp_kangarootwelve_storage storage{}; /** The customisation string C, which the caller keeps alive until `finish`. */ - std::span customisation; + std::span customisation{}; /** The bytes of C and of the message so far, in 64 bits on every target. */ std::uint64_t counted = 0; }; diff --git a/include/webcpp/hash/byte_pieces.hpp b/include/webcpp/hash/byte_pieces.hpp new file mode 100644 index 0000000..3c66835 --- /dev/null +++ b/include/webcpp/hash/byte_pieces.hpp @@ -0,0 +1,119 @@ +// 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) + +/** + `byte_pieces`: byte sequences a function reads one after another, as if concatenated, so that an + input made of parts (a label, a prefix and a secret) needs no buffer to join them: HKDF over pieces + (`hkdf.hpp`) takes its input keying material and its application info so. `` + includes it; `backends/hash2.hpp` and the engines include it for their parameters. + + @code + // label, suite_id and secret: std::span + auto prk = webcpp::hash::hkdf_extract(salt, + {label, suite_id, secret}); + @endcode + + @see "Key derivation", in the guide. +*/ +#ifndef WEBCPP_HASH_BYTE_PIECES_HPP +#define WEBCPP_HASH_BYTE_PIECES_HPP + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::hash { + +/** + Byte sequences read one after another, as if concatenated: `{a, b, c}` at the call. + + A view: it holds a pointer to a contiguous list of spans and their count, and the spans point to + the caller's bytes; neither is copied. Write the braced list at the call, where its array lives + until the end of the full expression, which outlasts the call; or name a `std::array` (or a + `std::vector`) of spans and pass it. A `byte_pieces` variable initialised from a braced list + points to an array that dies at the end of its declaration: its constructors carry + `WEBCPP_HASH_LIFETIMEBOUND`, which makes that a warning where the compiler has the attribute. + + A braced list of one `std::span`, `{x}`, is that span (the language's rule): + a function with a single-buffer overload takes it there. `{}`, or a braced list of one element of + another type (`{vec}`, `{array}`, a `std::span`), where both overloads take braces + is ambiguous: pass `x` itself, which converts to the span, or write `byte_pieces{x}` for the list + of one piece, `byte_pieces{}` for no piece, or an empty `std::span` for an + empty input (the same bytes). + + @code + std::array, 3> const parts{prefix, label, secret}; + auto prk = webcpp::hash::hkdf_extract(salt, parts); + @endcode +*/ +class byte_pieces { +public: + /** A piece: a span of bytes. */ + using value_type = std::span; + + /** No piece: the empty input. */ + constexpr byte_pieces() noexcept = default; + + /** + 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). + */ + 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()) {} + + /** + The pieces of a contiguous range of spans of bytes: a `std::array`, a `std::vector`, a + `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. + */ + template + requires std::ranges::sized_range && + 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)) {} + + /** The start of the pieces. @return A pointer to the first piece. */ + [[nodiscard]] constexpr value_type const* begin() const noexcept { return first_; } + + /** The end of the pieces. @return A pointer past the last piece. */ + [[nodiscard]] constexpr value_type const* end() const noexcept { return first_ + count_; } + + /** The size of the list. @return The number of pieces, empty ones included. */ + [[nodiscard]] constexpr std::size_t size() const noexcept { return count_; } + + /** Whether the list is empty. @return True when there is no piece. */ + [[nodiscard]] constexpr bool empty() const noexcept { return count_ == 0; } + + /** 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(); + } + return total; + } + +private: + value_type const* first_ = nullptr; + std::size_t count_ = 0; +}; + +} // namespace webcpp::hash + +#endif // WEBCPP_HASH_BYTE_PIECES_HPP diff --git a/include/webcpp/hash/config.hpp b/include/webcpp/hash/config.hpp index e21e23f..f4ba1ec 100644 --- a/include/webcpp/hash/config.hpp +++ b/include/webcpp/hash/config.hpp @@ -19,11 +19,11 @@ // MrDocs parses hash as a build with exceptions does, where none of these macros is defined: these // definitions are the ones the reference lists. Each is undone at once but WEBCPP_HASH_HAS_THREADS, -// which stays defined, as a native build has it. The libraries' WEBCPP_HASH_HAS_ are left as -// the build set them (push_macro and pop_macro keep the definition or its absence): hash's -// doc/Jamfile links every library, so its reference reads each backend's header, while the -// reference of a library that includes hash reads only the backends that library links (trystero's, -// for Emscripten's target, reads BearSSL's alone). +// which stays defined, as a native build has it, and WEBCPP_HASH_LIFETIMEBOUND, which stays empty. +// The libraries' WEBCPP_HASH_HAS_ are left as the build set them (push_macro and pop_macro +// keep the definition or its absence): hash's doc/Jamfile links every library, so its reference +// reads each backend's header, while the reference of a library that includes hash reads only the +// backends that library links (trystero's, for Emscripten's target, reads BearSSL's alone). #ifdef __MRDOCS__ /** Defined when webcpp::hash is built without exceptions: when webcpp has none (the compiler has @@ -109,6 +109,14 @@ */ #define WEBCPP_HASH_NO_THREADS #undef WEBCPP_HASH_NO_THREADS +/** + The attribute that says a parameter's object must outlive the object a constructor makes from it: + `[[clang::lifetimebound]]` under clang, `[[msvc::lifetimebound]]` under MSVC where it has it, + nothing elsewhere. `byte_pieces`' constructors carry it, so that a `byte_pieces` named from a + braced list, whose array dies at the end of its declaration, is a warning where the compiler + can tell. +*/ +#define WEBCPP_HASH_LIFETIMEBOUND #endif #if !defined(WEBCPP_HAS_EXCEPTIONS) && !defined(WEBCPP_HASH_NO_EXCEPTIONS) @@ -130,6 +138,19 @@ #define WEBCPP_HASH_HAS_THREADS 1 #endif +// The lifetimebound attribute, where the compiler has it; the reference's run keeps the +// documented, empty definition above. +#if !defined(WEBCPP_HASH_LIFETIMEBOUND) && defined(__has_cpp_attribute) +#if __has_cpp_attribute(clang::lifetimebound) +#define WEBCPP_HASH_LIFETIMEBOUND [[clang::lifetimebound]] +#elif __has_cpp_attribute(msvc::lifetimebound) +#define WEBCPP_HASH_LIFETIMEBOUND [[msvc::lifetimebound]] +#endif +#endif +#ifndef WEBCPP_HASH_LIFETIMEBOUND +#define WEBCPP_HASH_LIFETIMEBOUND +#endif + // The refusals of impossible combinations (spec 5.7). Clang and gcc go on after an #error, so // the first error is the instruction; MSVC stops at it. // A reference (MrDocs) describes the headers and builds no program, so none of them refuses it. @@ -210,6 +231,27 @@ struct hkdf_extract; A tag, declared and never defined, as @ref hkdf_extract is for the first step. */ struct hkdf_expand; +/** + HKDF over pieces, the operation `hkdf` whose input keying material and application info are + `byte_pieces`: RFC 5869 on the backend's streaming HMAC, with no cap on either input. + + A tag, declared and never defined: a backend has it exactly where it has the HMAC (design D4 of + the change hkdf-pieces), which @ref webcpp::hash::backend_has_v answers through it. +*/ +struct hkdf_pieces; +/** + HKDF-Extract over pieces, the operation `hkdf_extract` whose input keying material is + `byte_pieces`. + + A tag, declared and never defined, as @ref hkdf_pieces is. +*/ +struct hkdf_extract_pieces; +/** + HKDF-Expand over pieces, the operation `hkdf_expand` whose application info is `byte_pieces`. + + A tag, declared and never defined, as @ref hkdf_pieces is. +*/ +struct hkdf_expand_pieces; /** PBKDF2, RFC 8018, the operation `pbkdf2`. diff --git a/include/webcpp/hash/detail/engines.hpp b/include/webcpp/hash/detail/engines.hpp index 26787e9..9bffc1f 100644 --- a/include/webcpp/hash/detail/engines.hpp +++ b/include/webcpp/hash/detail/engines.hpp @@ -9,6 +9,8 @@ #include +#include +#include #include #include @@ -101,11 +103,11 @@ struct backend_limits { /** HKDF's salt (`hkdf_extract`, `hkdf`). */ static constexpr std::uint64_t hkdf_salt = no_limit; /** HKDF's input keying material (`hkdf_extract`, `hkdf`). */ - static constexpr std::uint64_t hkdf_ikm = no_limit; + static constexpr std::uint64_t hkdf_input_key_material = no_limit; /** HKDF's pseudorandom key (`hkdf_expand`). */ - static constexpr std::uint64_t hkdf_prk = no_limit; - /** HKDF's info (`hkdf_expand`, `hkdf`), within `hkdf_max_info_size`. */ - static constexpr std::uint64_t hkdf_info = no_limit; + static constexpr std::uint64_t hkdf_pseudorandom_key = no_limit; + /** HKDF's info (`hkdf_expand`, `hkdf`), within `hkdf_max_application_info_size`. */ + static constexpr std::uint64_t hkdf_application_info = no_limit; /** HKDF's output (`hkdf_expand`, `hkdf`), within 255 digests. */ static constexpr std::uint64_t hkdf_output = no_limit; /** PBKDF2's password. */ @@ -144,19 +146,17 @@ struct backend_limits { @code using digest_type = typename Hmac::result_type; - // RFC 5869 2.2: the PRK of `ikm` under `salt` (empty: HashLen zeros). - static boost::system::result extract(std::span salt, - std::span ikm) noexcept; - // RFC 5869 2.3: `output` (1 to 255 digests) from `prk` (one digest) and `info` (at most - // hkdf_max_info_size bytes). - static boost::system::result expand(std::span output, - std::span prk, - std::span info) noexcept; + 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.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, - std::span salt, - std::span ikm, - std::span info) noexcept; + static boost::system::result extract_and_expand(std::span output_key_material, + bytes salt, bytes input_key_material, + bytes application_info) noexcept; @endcode A failure is `error::backend_failure`, or `errc::not_enough_memory` when the library could not @@ -180,6 +180,148 @@ struct hkdf_engine { "but hmac_ripemd_128 and hmac_sha2_512_224)."); }; +#ifdef WEBCPP_HASH_DETAIL_TEST_HKDF_PIECES_SLICE +// The test seam's value; the Doc Comment is in the #else branch, the one the reference reads. +inline constexpr std::uint64_t hkdf_pieces_slice_seam = WEBCPP_HASH_DETAIL_TEST_HKDF_PIECES_SLICE; +#else +/** + The most bytes an engine of HKDF over pieces hands its HMAC in one update, on every backend: no + limit, unless the test seam `WEBCPP_HASH_DETAIL_TEST_HKDF_PIECES_SLICE` lowers it, so that a test + feeds every piece in small slices and checks the bytes are the same (Review Focus 4 of the change + hkdf-pieces). +*/ +inline constexpr std::uint64_t hkdf_pieces_slice_seam = no_limit; +#endif +// A slice of no byte would never advance for_each_slice. +static_assert(hkdf_pieces_slice_seam >= 1, + "WEBCPP_HASH_DETAIL_TEST_HKDF_PIECES_SLICE is at least 1"); + +/** + The most bytes `Backend`'s HMAC takes in one update: a `std::size_t`'s range, the primary + template's, for a backend whose update takes a `size_t` (`backends::hash2`); a backend whose + update takes a narrower length (an `int`, a `long`, or a `size_t` of 32 bits beside a 64-bit one) + specialises it with that type's largest value. + + @tparam Backend A backend of `backends`. A specialisation is at least 1, as + @ref for_each_slice requires. +*/ +template +inline constexpr std::uint64_t hkdf_pieces_update_max = std::numeric_limits::max(); + +/** + The most bytes an engine of HKDF over pieces on `Backend` hands its HMAC in one update: the + backend's @ref hkdf_pieces_update_max, or the test seam's @ref hkdf_pieces_slice_seam where it is + lower. A piece longer than it is fed in slices (@ref for_each_slice), so that no piece is refused + for its size. + + @tparam Backend A backend of `backends`. +*/ +template +inline constexpr std::uint64_t hkdf_pieces_slice = + hkdf_pieces_update_max < hkdf_pieces_slice_seam ? hkdf_pieces_update_max + : 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 + 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. +*/ +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); + } + } +} + +/** + HKDF over pieces of a backend over an hmac (design D2 and D4 of the change hkdf-pieces), on the + backend's streaming HMAC, which the backend's header specialises for each hmac whose HMAC it has. + The primary template is reached only by a backend without that HMAC, and refuses. + + A specialisation has three static member functions, each `noexcept`, called by the public + functions of `hkdf.hpp` only after their guards (RFC 5869's output and pseudorandom key sizes, + then the backend's HMAC key limits) have passed; an engine feeds each piece to the HMAC, in + slices of at most @ref hkdf_pieces_slice bytes (@ref for_each_slice), copies none, allocates + nothing in webcpp's code, and wipes every HMAC state, every block T(i) and the pseudorandom key + between the steps, on success and on failure: + + @code + 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, + 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, + bytes pseudorandom_key, + 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, + byte_pieces application_info) noexcept; + @endcode + + A failure is `error::backend_failure`, or `errc::not_enough_memory` when the library could not + allocate; the public function then zeroes the output. + + @tparam Backend A backend of `backends`. @tparam Hmac A Boost.Hash2 hmac over a digest. +*/ +template +struct hkdf_pieces_engine { + // clang-format off + static_assert(!std::is_same_v, + "webcpp::hash: backends::webcrypto is asynchronous: call async_hkdf_extract, async_hkdf_expand or async_hkdf with a completion token, or name a synchronous backend."); + // clang-format on + static_assert(std::is_same_v, + "webcpp::hash: this backend has no HMAC for HKDF over pieces. The backends that " + "have hkdf_extract, hkdf_expand and hkdf over pieces: backends::hash2 (every " + "hmac), backends::sodium (hmac_sha2_256, hmac_sha2_512), backends::bearssl " + "(MD5, SHA-1, SHA-224, SHA-256, SHA-384, SHA-512), backends::openssl (every " + "hmac but hmac_ripemd_128) and backends::botan (every hmac but hmac_ripemd_128 " + "and hmac_sha2_512_224)."); +}; + +/** + The body of `extract_and_expand` of every pieces engine: Extract, an early return of its error, + 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 + `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 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, + byte_pieces input_key_material, byte_pieces application_info) noexcept { + auto pseudorandom_key = Engine::extract(salt, input_key_material); + if (!pseudorandom_key) { + return pseudorandom_key.error(); + } + auto& pseudorandom_key_bytes = pseudorandom_key.unsafe_value(); + auto derive_result = Engine::expand( + output_key_material, + std::span(pseudorandom_key_bytes.data(), pseudorandom_key_bytes.size()), + application_info); + wipe_object(pseudorandom_key_bytes); + return derive_result; +} + /** The most blocks of PBKDF2's output a backend derives: RFC 8018's 2^32 - 1, unless the backend's header names fewer (backends::botan's 2^32 - 2); `pbkdf2` refuses a longer output with @@ -1425,7 +1567,7 @@ struct argon2_limits { /** The fewest passes, t (RFC 9106: 1). */ std::uint32_t min_passes = 1; /** The most memory, m, in KiB (RFC 9106: 2^32 - 1). */ - std::uint32_t max_memory_kib = 0xffffffffU; + std::uint32_t max_memory_kibibytes = 0xffffffffU; /** The most lanes, p (RFC 9106: 2^24 - 1). */ std::uint32_t max_lanes = 0xffffffU; /** The shortest tag, in bytes (RFC 9106: 4). */ diff --git a/include/webcpp/hash/hkdf.hpp b/include/webcpp/hash/hkdf.hpp index 0333b43..3f55482 100644 --- a/include/webcpp/hash/hkdf.hpp +++ b/include/webcpp/hash/hkdf.hpp @@ -8,6 +8,15 @@ HKDF, RFC 5869: `hkdf_extract`, `hkdf_expand` and `hkdf`, over any Boost.Hash2 hmac whose result is a digest, on the backend the call names or on @ref webcpp::hash::default_kdf_backend. + Each has a form over pieces: its input keying material and its application info as + @ref webcpp::hash::byte_pieces, read one after another as if concatenated, `{a, b, c}` at the + call, with no cap on either and no buffer of webcpp's (RFC 9180's labeled inputs need no join). + The single-buffer forms keep `hkdf_max_application_info_size`; the pieces forms refuse only RFC + 5869's sizes. A braced list of one `std::span`, `{x}`, is that span (the + language's rule): the single-buffer form. `{}`, or a braced list of one element of another type + (`{vec}`, `{array}`), in every pieces position is ambiguous between the two forms: pass `x` + itself, which converts to the span, or write `byte_pieces{...}`, or an empty span. + Every call holds the data-independent-timing guard (`detail::timing_guard`): where the CPU has DIT, the call sets it and leaves the thread's state as it found it. @@ -15,9 +24,10 @@ failure zeroes it. @code - // salt, secret and info: std::span + // salt, input_key_material and application_info: std::span std::array key{}; - auto done = webcpp::hash::hkdf(key, salt, secret, info); + auto done = webcpp::hash::hkdf(key, salt, input_key_material, + application_info); if (!done) { return done.error(); // key is as it was, or zeroed when the backend failed } @@ -31,6 +41,7 @@ #include #include +#include #include #include #include @@ -61,116 +72,180 @@ namespace webcpp::hash { -/** The longest info every backend accepts, 32,768 bytes (OpenSSL 3.5's limit). */ -inline constexpr std::size_t hkdf_max_info_size = 32768; +/** The longest application info every backend accepts, 32,768 bytes (OpenSSL 3.5's limit). */ +inline constexpr std::size_t hkdf_max_application_info_size = 32768; namespace detail { +/** + The guards of the single-buffer `hkdf_extract`, without the work: `Backend`'s limits on the salt + and on the input keying material. `async_hkdf_extract` checks them before its output is written, + and @ref hkdf_guards after the output's size. + + @tparam Backend The backend. @param salt_size The salt's size. + @param input_key_material_size The input keying material's size. + @return Success, or `input_too_long`. +*/ +template +[[nodiscard]] boost::system::result hkdf_extract_guards( + std::size_t salt_size, std::size_t input_key_material_size) noexcept { + using limits = backend_limits; + if (exceeds(salt_size, limits::hkdf_salt) || + exceeds(input_key_material_size, limits::hkdf_input_key_material)) { + return error::input_too_long; + } + return {}; +} + /** The guards of `hkdf` (spec 2.8), then `Backend`'s own limits, without the work: what `async_hkdf` checks on a backend that completes by itself before it starts the work. @tparam Hmac A Boost.Hash2 hmac over a digest. @tparam Backend The backend. @param output_size The output's size. @param salt_size The salt's size. - @param ikm_size The input keying material's size. @param info_size The info's size. + @param input_key_material_size The input keying material's size. + @param application_info_size The application info's size. @return Success, or the error of the first guard that fails, as `hkdf` returns it. */ template [[nodiscard]] boost::system::result hkdf_guards(std::size_t output_size, - std::size_t salt_size, std::size_t ikm_size, - std::size_t info_size) noexcept { + std::size_t salt_size, + std::size_t input_key_material_size, + std::size_t application_info_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 (output_size == 0 || output_size > 255 * digest_length) { return error::invalid_output_size; } - if (info_size > hkdf_max_info_size) { + if (application_info_size > hkdf_max_application_info_size) { return error::input_too_long; } using limits = backend_limits; if (exceeds(output_size, limits::hkdf_output)) { return error::invalid_output_size; } - if (exceeds(salt_size, limits::hkdf_salt) || exceeds(ikm_size, limits::hkdf_ikm) || - exceeds(info_size, limits::hkdf_info)) { + auto const extract_guarded = hkdf_extract_guards(salt_size, input_key_material_size); + if (!extract_guarded) { + return extract_guarded; + } + if (exceeds(application_info_size, limits::hkdf_application_info)) { + return error::input_too_long; + } + return {}; +} + +/** + The guard of HKDF's salt over pieces, the Extract HMAC's key: `Backend`'s HMAC key limit + (`backend_limits`' `hkdf_salt`, as `backends::openssl`'s `INT_MAX`). `hkdf_extract` over pieces + calls it alone, `hkdf_pieces_guards` after the output's size. + + @tparam Backend The backend. @param salt_size The salt's size. + @return Success, or `input_too_long`. +*/ +template +[[nodiscard]] boost::system::result hkdf_pieces_salt_guard(std::size_t salt_size) noexcept { + if (exceeds(salt_size, backend_limits::hkdf_salt)) { return error::input_too_long; } return {}; } +/** + The guards of `hkdf` over pieces and of `hkdf_expand`'s output, without the work: RFC 5869's + output size, then @ref hkdf_pieces_salt_guard; nothing on the input keying material or the + application info. + + @tparam Hmac A Boost.Hash2 hmac over a digest. @tparam Backend The backend. + @param output_size The output's size. @param salt_size The salt's size (0 for `hkdf_expand`). + @return Success, or the error of the first guard that fails: `invalid_output_size`, then + `input_too_long`. +*/ +template +[[nodiscard]] boost::system::result hkdf_pieces_guards(std::size_t output_size, + std::size_t salt_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 (output_size == 0 || output_size > 255 * digest_length) { + return error::invalid_output_size; + } + return hkdf_pieces_salt_guard(salt_size); +} + } // namespace detail /** - HKDF-Extract (RFC 5869, section 2.2): the pseudorandom key of `ikm_bytes` 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 ikm_bytes The input keying material, any length the backend takes. + @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 `input_too_long` for a salt or an IKM longer than the backend takes (`backends::openssl`: a salt of more than `INT_MAX` bytes); or the backend's failure. */ template > [[nodiscard]] boost::system::result::type> hkdf_extract( - std::span salt_bytes, std::span ikm_bytes) { + std::span salt, std::span input_key_material) { detail::timing_guard const timing; if constexpr (!detail::takes_hmac()) { return error::backend_failure; // unreachable: takes_hmac has stopped the build } else { - using limits = detail::backend_limits; - if (detail::exceeds(salt_bytes.size(), limits::hkdf_salt) || - detail::exceeds(ikm_bytes.size(), limits::hkdf_ikm)) { - return error::input_too_long; + auto const guarded = + detail::hkdf_extract_guards(salt.size(), input_key_material.size()); + if (!guarded) { + return guarded.error(); } - return detail::hkdf_engine::extract(salt_bytes, ikm_bytes); + return detail::hkdf_engine::extract(salt, input_key_material); } } /** - HKDF-Expand (RFC 5869, section 2.3): fills `output_bytes` from `prk_bytes` and `info_bytes`. + HKDF-Expand (RFC 5869, section 2.3): fills `output_key_material` from `pseudorandom_key` and + `application_info`. @tparam Hmac The hmac. @tparam Backend The backend; by default the one `default_kdf_backend` names, `backends::hash2`. - @param output_bytes The output keying material, 1 to 255 times the digest size. - @param prk_bytes The pseudorandom key, of exactly the digest size. - @param info_bytes The context, at most `hkdf_max_info_size` bytes. + @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. @return Success, or the error of the first guard that fails (`invalid_output_size`, `invalid_key_size`, `input_too_long`, then the backend's own limits: `invalid_output_size`, - `input_too_long`), `output_bytes` untouched; or the backend's failure, `output_bytes` zeroed. + `input_too_long`), `output_key_material` untouched; or the backend's failure, `output_key_material` + zeroed. */ template > -[[nodiscard]] boost::system::result hkdf_expand(std::span output_bytes, - std::span prk_bytes, - std::span info_bytes) { +[[nodiscard]] boost::system::result hkdf_expand( + std::span output_key_material, std::span pseudorandom_key, + std::span application_info) { detail::timing_guard const timing; if constexpr (!detail::takes_hmac()) { return error::backend_failure; // unreachable: takes_hmac has stopped the build } else { // 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 (output_bytes.empty() || output_bytes.size() > 255 * digest_length) { + if (output_key_material.empty() || output_key_material.size() > 255 * digest_length) { return error::invalid_output_size; } - if (prk_bytes.size() != digest_length) { + if (pseudorandom_key.size() != digest_length) { return error::invalid_key_size; } - if (info_bytes.size() > hkdf_max_info_size) { + if (application_info.size() > hkdf_max_application_info_size) { return error::input_too_long; } using limits = detail::backend_limits; - if (detail::exceeds(output_bytes.size(), limits::hkdf_output)) { + if (detail::exceeds(output_key_material.size(), limits::hkdf_output)) { return error::invalid_output_size; } - if (detail::exceeds(prk_bytes.size(), limits::hkdf_prk) || - detail::exceeds(info_bytes.size(), limits::hkdf_info)) { + if (detail::exceeds(pseudorandom_key.size(), limits::hkdf_pseudorandom_key) || + detail::exceeds(application_info.size(), limits::hkdf_application_info)) { return error::input_too_long; } - auto derive_result = - detail::hkdf_engine::expand(output_bytes, prk_bytes, info_bytes); + auto derive_result = detail::hkdf_engine::expand( + output_key_material, pseudorandom_key, application_info); if (!derive_result) { - detail::wipe(output_bytes); + detail::wipe(output_key_material); } return derive_result; } @@ -180,34 +255,151 @@ template > -[[nodiscard]] boost::system::result hkdf(std::span output_bytes, - std::span salt_bytes, - std::span ikm_bytes, - std::span info_bytes) { +[[nodiscard]] boost::system::result hkdf(std::span output_key_material, + std::span salt, + std::span input_key_material, + std::span application_info) { detail::timing_guard const timing; if constexpr (!detail::takes_hmac()) { return error::backend_failure; // unreachable: takes_hmac has stopped the build } else { - auto guarded = detail::hkdf_guards(output_bytes.size(), salt_bytes.size(), - ikm_bytes.size(), info_bytes.size()); + auto guarded = + detail::hkdf_guards(output_key_material.size(), salt.size(), + input_key_material.size(), application_info.size()); if (!guarded) { return guarded; } auto derive_result = detail::hkdf_engine::extract_and_expand( - output_bytes, salt_bytes, ikm_bytes, info_bytes); + output_key_material, salt, input_key_material, application_info); + if (!derive_result) { + detail::wipe(output_key_material); + } + return derive_result; + } +} + +/** + 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. + + @code + auto prk = webcpp::hash::hkdf_extract(salt, {prefix, label, ikm}); + @endcode + + @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 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 + `INT_MAX` bytes); or the backend's failure. +*/ +template > +[[nodiscard]] boost::system::result::type> hkdf_extract( + std::span salt, byte_pieces input_key_material) { + detail::timing_guard const timing; + 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(); + } + return detail::hkdf_pieces_engine::extract(salt, input_key_material); + } +} + +/** + HKDF-Expand (RFC 5869, section 2.3) over pieces: fills `output_key_material` from + `pseudorandom_key` and the concatenation of `application_info`'s pieces, each piece fed to the + backend's HMAC for each block. + + @tparam Hmac The hmac. @tparam Backend The backend; by default the one + `default_kdf_backend` names, `backends::hash2`. + @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's pieces, of any number and length: no cap. + @return Success, or the error of the first guard that fails (`invalid_output_size`, + `invalid_key_size`), `output_key_material` untouched; or the backend's failure, + `output_key_material` zeroed. +*/ +template > +[[nodiscard]] boost::system::result hkdf_expand( + std::span output_key_material, std::span pseudorandom_key, + byte_pieces application_info) { + detail::timing_guard const timing; + 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; + } + // 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 (pseudorandom_key.size() != digest_length) { + return error::invalid_key_size; + } + auto derive_result = detail::hkdf_pieces_engine::expand( + output_key_material, pseudorandom_key, application_info); + if (!derive_result) { + detail::wipe(output_key_material); + } + return derive_result; + } +} + +/** + HKDF (RFC 5869, section 2) over pieces: extract, then expand, the pseudorandom key wiped between + them. + + @code + // RFC 9180's LabeledExtract and LabeledExpand in one call, no buffer joined. + auto done = webcpp::hash::hkdf( + key, salt, {version, suite_id, label, ikm}, {length, version, suite_id, label, info}); + @endcode + + @tparam Hmac The hmac. @tparam Backend The backend; by default the one + `default_kdf_backend` 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 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 + `input_too_long` for a salt longer than the backend's HMAC takes), `output_key_material` + untouched; or the backend's failure, `output_key_material` zeroed. +*/ +template > +[[nodiscard]] boost::system::result hkdf(std::span output_key_material, + std::span salt, + byte_pieces input_key_material, + byte_pieces application_info) { + detail::timing_guard const timing; + 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 derive_result = detail::hkdf_pieces_engine::extract_and_expand( + output_key_material, salt, input_key_material, application_info); if (!derive_result) { - detail::wipe(output_bytes); + detail::wipe(output_key_material); } return derive_result; } diff --git a/include/webcpp/hash/kdf.hpp b/include/webcpp/hash/kdf.hpp index 0454929..ebfaef2 100644 --- a/include/webcpp/hash/kdf.hpp +++ b/include/webcpp/hash/kdf.hpp @@ -112,6 +112,88 @@ template inline constexpr bool backend_has_v = backend_has_v && !std::is_same_v; +/** + backends::hash2 has HKDF over pieces over every hmac it has HKDF over: Boost.Hash2's `hmac`, + whose `update` each piece is fed to (design D4 of the change hkdf-pieces: a backend has the pieces + forms exactly where it has the HMAC). +*/ +template +inline constexpr bool backend_has_v = + backend_has_v; + +/** backends::hash2 has HKDF-Extract over pieces wherever it has HKDF over pieces. */ +template +inline constexpr bool backend_has_v = + backend_has_v; + +/** backends::hash2 has HKDF-Expand over pieces wherever it has HKDF over pieces. */ +template +inline constexpr bool backend_has_v = + backend_has_v; + +/** + backends::sodium has HKDF over pieces over the hmacs of its HMAC cells, those it has HKDF over: + `hmac_sha2_256` and `hmac_sha2_512`, over `crypto_auth_hmacsha256_*` and + `crypto_auth_hmacsha512_*` (libsodium's own HKDF takes Expand's info whole, and is not used). +*/ +template +inline constexpr bool backend_has_v = + backend_has_v; + +/** backends::sodium has HKDF-Extract over pieces wherever it has HKDF over pieces. */ +template +inline constexpr bool backend_has_v = + backend_has_v; + +/** backends::sodium has HKDF-Expand over pieces wherever it has HKDF over pieces. */ +template +inline constexpr bool backend_has_v = + backend_has_v; + +/** + backends::bearssl has HKDF over pieces over its six hmacs, those of its HMAC cells, over + `br_hmac_key_init`, `br_hmac_init`, `br_hmac_update` and `br_hmac_out`. +*/ +template +inline constexpr bool backend_has_v = + detail::bearssl_hmac_v; + +/** + backends::bearssl has HKDF-Extract over pieces wherever it has HKDF over pieces: its HMAC keyed + by the salt, while the single-buffer `hkdf_extract` stays refused (`br_hkdf_*` keeps the + pseudorandom key inside its context). +*/ +template +inline constexpr bool backend_has_v = + backend_has_v; + +/** + backends::bearssl has HKDF-Expand over pieces wherever it has HKDF over pieces: its HMAC keyed by + the pseudorandom key, while the single-buffer `hkdf_expand` stays refused. +*/ +template +inline constexpr bool backend_has_v = + backend_has_v; + +/** + backends::openssl has HKDF over pieces over the hmacs of its HMAC cells, those it has HKDF over + (every alias of `hmac.hpp` but `hmac_ripemd_128`), over `EVP_MAC` "HMAC" (OpenSSL's `EVP_KDF` + "HKDF" takes the input keying material and the info whole, and is not used). +*/ +template +inline constexpr bool backend_has_v = + detail::openssl_hmac_v; + +/** backends::openssl has HKDF-Extract over pieces wherever it has HKDF over pieces. */ +template +inline constexpr bool backend_has_v = + backend_has_v; + +/** backends::openssl has HKDF-Expand over pieces wherever it has HKDF over pieces. */ +template +inline constexpr bool backend_has_v = + backend_has_v; + /** backends::sodium has Argon2id (`crypto_pwhash_argon2id`), which takes no hmac. */ template <> inline constexpr bool backend_has_v = true; @@ -1455,18 +1537,19 @@ struct default_of { /** The backend a function of `Algorithm` uses when the call names none (spec 4.1). - `backends::hash2` for `hkdf_extract`, `hkdf_expand`, `hkdf` and `pbkdf2`, on every target and - whatever the program links; `backends::sodium` for `argon2id`, `scrypt` (which `backends::openssl` - and `backends::botan` also have, named in the call) and `blake2b_subkey`, which stops the build - with the line to add to the Jamfile when the program does not link libsodium. A tag of the families + `backends::hash2` for `hkdf_extract`, `hkdf_expand`, `hkdf` (each also over pieces) and + `pbkdf2`, on every target and whatever the program links; `backends::sodium` for `argon2id`, + `scrypt` (which `backends::openssl` and `backends::botan` also have, named in the call) and + `blake2b_subkey`, which stops the build with the line to add to the Jamfile when the program + does not link libsodium. A tag of the families defaults to the first of `backends::hash2`, `backends::xkcp`, `backends::blake3` and `backends::sodium` that has it (design D34), or to `detail::no_default`, which refuses: the call names its backend. `backends::bearssl`, `backends::openssl` and `backends::botan` are never a default. No define changes it: another backend is chosen by naming it in the call, as `hkdf`. - @tparam Algorithm A tag of `kdfs` (`hkdf`, `hkdf_extract`, `hkdf_expand`, `pbkdf2`, `argon2id`, - `scrypt`, `blake2b_subkey`, ...), `digests` or `macs`. + @tparam Algorithm A tag of `kdfs` (`hkdf`, `hkdf_extract`, `hkdf_expand`, their `_pieces` + forms, `pbkdf2`, `argon2id`, `scrypt`, `blake2b_subkey`, ...), `digests` or `macs`. @tparam Hmac The hmac of a key derivation that takes one, else `void`; it does not change the answer. */ @@ -1478,7 +1561,8 @@ using default_backend = detail::default_of::type; @ref default_backend of `Kdf`, `backends::hash2` on every target. @tparam Hmac A Boost.Hash2 hmac; it does not change the answer. @tparam Kdf `kdfs::hkdf` (the - default), `kdfs::hkdf_extract`, `kdfs::hkdf_expand` or `kdfs::pbkdf2`. + default), `kdfs::hkdf_extract`, `kdfs::hkdf_expand`, `kdfs::hkdf_pieces`, + `kdfs::hkdf_extract_pieces`, `kdfs::hkdf_expand_pieces` or `kdfs::pbkdf2`. */ template using default_kdf_backend = default_backend; diff --git a/include/webcpp/hash/kdf_standards.hpp b/include/webcpp/hash/kdf_standards.hpp index 7905662..2df47a6 100644 --- a/include/webcpp/hash/kdf_standards.hpp +++ b/include/webcpp/hash/kdf_standards.hpp @@ -209,15 +209,16 @@ inline constexpr std::uint64_t standard_kdf_counter_size = 4; Whether `counter || secret || info` (in either order) is longer than `Digest` hashes (SP 800-56C section 4.1 and ANSI X9.63 section 5.6.3 refuse it), computed without overflow. - @param secret_size The shared secret's size. @param info_size The info's size. + @param secret_size The shared secret's size. @param fixed_info_size The fixed or shared info's + size. @return Whether the input is too long. */ template constexpr bool standard_kdf_input_too_long(std::uint64_t secret_size, - std::uint64_t info_size) noexcept { + std::uint64_t fixed_info_size) noexcept { constexpr std::uint64_t room = standard_kdf_digest::max_input - standard_kdf_counter_size; - return exceeds(secret_size, room) || exceeds(info_size, room - secret_size); + return exceeds(secret_size, room) || exceeds(fixed_info_size, room - secret_size); } /** diff --git a/include/webcpp/hash/scrypt.hpp b/include/webcpp/hash/scrypt.hpp index 3e1ceca..b1c1371 100644 --- a/include/webcpp/hash/scrypt.hpp +++ b/include/webcpp/hash/scrypt.hpp @@ -18,7 +18,8 @@ @code // password and salt: std::span std::array key{}; - auto done = webcpp::hash::scrypt(key, password, salt, {.n = 32768, .r = 8, .p = 1}); + auto done = webcpp::hash::scrypt( + key, password, salt, {.cost = 32768, .block_size = 8, .parallelism = 1}); if (!done) { return done.error(); // key is as it was, or zeroed when the backend failed } @@ -52,12 +53,12 @@ namespace webcpp::hash { /** The costs of scrypt, RFC 7914's N, r and p. */ struct scrypt_parameters { - /** The CPU and memory cost N: a power of two, greater than 1, less than 2^(16 r). */ - std::uint64_t n; - /** The block size r, at least 1. */ - std::uint32_t r; - /** The parallelisation p, at least 1, with r times p below 2^30. */ - std::uint32_t p; + /** The CPU and memory cost, RFC 7914's N: a power of two, greater than 1, below 2^(16 r). */ + std::uint64_t cost; + /** The block size, RFC 7914's r, at least 1. */ + std::uint32_t block_size; + /** The parallelisation, RFC 7914's p, at least 1, with r times p below 2^30. */ + std::uint32_t parallelism; }; namespace detail { @@ -168,8 +169,8 @@ template > return guarded; } auto derive_result = detail::scrypt_engine::derive( - output_bytes, password_bytes, salt_bytes, cost_parameters.n, cost_parameters.r, - cost_parameters.p); + output_bytes, password_bytes, salt_bytes, cost_parameters.cost, cost_parameters.block_size, + cost_parameters.parallelism); if (!derive_result) { detail::wipe(output_bytes); } diff --git a/meta/include-boundaries.json b/meta/include-boundaries.json index 7b153d3..83387bd 100644 --- a/meta/include-boundaries.json +++ b/meta/include-boundaries.json @@ -19,6 +19,7 @@ { "headers": [ "include/webcpp/hash/backends/hash2.hpp", + "include/webcpp/hash/byte_pieces.hpp", "include/webcpp/hash/detail/engines.hpp", "include/webcpp/hash/detail/limits.hpp", "include/webcpp/hash/detail/timing.hpp", diff --git a/test/Jamfile b/test/Jamfile index 1056c25..d008927 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -62,6 +62,7 @@ webcpp.headers-alone hash : ../include : hash/backends/hash2.hpp hash/bcrypt.hpp hash/blake2b_subkey.hpp + hash/byte_pieces.hpp hash/config.hpp hash/detail/engines.hpp hash/detail/limits.hpp @@ -233,6 +234,35 @@ hash-run hash2_mac_vectors : hash2_mac_vectors_test.cpp # reported through the seam WEBCPP_HASH_DETAIL_TEST_WIPE_RECORD. hash-run hkdf_hash2 : hkdf_hash2_test.cpp ; hash-run hkdf_guards : hkdf_guards_test.cpp ; + +# HKDF over pieces (byte_pieces): the call's overloads, the list's counts and +# the slicing of a piece; then the pieces forms on backends::hash2 against +# the single-buffer forms and an RFC 5869 computation of the test's own +# (support/hkdf_pieces.hpp), again with the seam that feeds the HMAC in +# slices of 7 bytes. +hash-run byte_pieces : byte_pieces_test.cpp ; +hash-run hkdf_pieces : hkdf_pieces_test.cpp ; +hash-run hkdf_pieces_sliced : hkdf_pieces_test.cpp + : WEBCPP_HASH_DETAIL_TEST_HKDF_PIECES_SLICE=7 ; +# The same on backends::sodium (libsodium's crypto_auth_hmacsha256_* and +# crypto_auth_hmacsha512_*) and on backends::bearssl (br_hmac_*, its six +# hmacs, Extract and Expand over pieces included), each with the wipe of every +# HMAC state, block and pseudorandom key reported through the seam +# WEBCPP_HASH_DETAIL_TEST_WIPE_RECORD, and again in slices of 7 bytes. +hash-run hkdf_pieces_sodium : hkdf_pieces_sodium_test.cpp + : /third_party//sodium WEBCPP_HASH_DETAIL_TEST_WIPE_RECORD ; +hash-run hkdf_pieces_sodium_sliced : hkdf_pieces_sodium_test.cpp + : /third_party//sodium WEBCPP_HASH_DETAIL_TEST_WIPE_RECORD + WEBCPP_HASH_DETAIL_TEST_HKDF_PIECES_SLICE=7 ; +hash-run hkdf_pieces_sodium_sha512_sliced : hkdf_pieces_sodium_test.cpp + : /third_party//sodium WEBCPP_HASH_DETAIL_TEST_WIPE_RECORD + WEBCPP_HASH_DETAIL_TEST_HKDF_PIECES_SLICE=7 + WEBCPP_HASH_DETAIL_TEST_SLICED_HMAC_SHA2_512 ; +hash-run hkdf_pieces_bearssl : hkdf_pieces_bearssl_test.cpp + : /third_party//bearssl WEBCPP_HASH_DETAIL_TEST_WIPE_RECORD ; +hash-run hkdf_pieces_bearssl_sliced : hkdf_pieces_bearssl_test.cpp + : /third_party//bearssl WEBCPP_HASH_DETAIL_TEST_WIPE_RECORD + WEBCPP_HASH_DETAIL_TEST_HKDF_PIECES_SLICE=7 ; hash-run wipe : wipe_test.cpp : WEBCPP_HASH_DETAIL_TEST_WIPE_RECORD ; # digests::blake2b on backends::sodium, libsodium's crypto_generichash_blake2b @@ -322,6 +352,17 @@ hash-run families_bearssl : families_bearssl_test.cpp # WEBCPP_HASH_DETAIL_TEST_OPENSSL_DIGEST, a digest OpenSSL cannot fetch. hash-run hkdf_openssl : hkdf_openssl_test.cpp : /webcpp/hash//openssl : native wasip2 wasip3 ; +# HKDF over pieces on backends::openssl, over EVP_MAC "HMAC" (its 15 hmacs): +# the equality harness, each block and pseudorandom key wiped through the seam +# WEBCPP_HASH_DETAIL_TEST_WIPE_RECORD, the error queue left empty; again in +# slices of 7 bytes. +hash-run hkdf_pieces_openssl : hkdf_pieces_openssl_test.cpp + : /webcpp/hash//openssl WEBCPP_HASH_DETAIL_TEST_WIPE_RECORD + : native wasip2 wasip3 ; +hash-run hkdf_pieces_openssl_sliced : hkdf_pieces_openssl_test.cpp + : /webcpp/hash//openssl WEBCPP_HASH_DETAIL_TEST_WIPE_RECORD + WEBCPP_HASH_DETAIL_TEST_HKDF_PIECES_SLICE=7 + : native wasip2 wasip3 ; hash-run pbkdf2_openssl : pbkdf2_openssl_test.cpp : /webcpp/hash//openssl : native wasip2 wasip3 ; hash-run openssl_error_queue : openssl_error_queue_test.cpp @@ -351,9 +392,9 @@ hash-run macs_openssl : macs_openssl_test.cpp /third_party//blake2_vectors /webcpp//boost_json : native wasip2 wasip3 ; # OpenSSL out of memory: each allocation of a call of backends::openssl (mac, -# digest_of, hasher::make, argon2, argon2id, scrypt) made to fail in turn, -# through CRYPTO_set_mem_functions; the answer, the output zeroed, every block -# freed and the error queue empty. +# digest_of, hasher::make, argon2, argon2id, scrypt, HKDF over pieces) made to +# fail in turn, through CRYPTO_set_mem_functions; the answer, the output zeroed, +# every block freed and the error queue empty. hash-run openssl_out_of_memory : openssl_out_of_memory_test.cpp : /webcpp/hash//openssl : native wasip2 wasip3 ; # backends::openssl's limits (OpenSSL holds some lengths in an int), natively: @@ -406,6 +447,15 @@ webcpp.compile botan_no_exceptions : botan_no_exceptions_test.cpp # RFC 7914's, the guards at their limits, keys past Botan's HMAC's 8,192 bytes, # and 1,000 seeded cases each against backends::hash2 over every hmac Botan has. botan-run kdfs_botan : kdfs_botan_test.cpp ; +# HKDF over pieces on backends::botan, over its HMAC (its 14 hmacs): the +# equality harness, a salt past Botan's 8,192-byte HMAC key, the digest room, +# each block and pseudorandom key wiped through the seam +# WEBCPP_HASH_DETAIL_TEST_WIPE_RECORD; again in slices of 7 bytes. +botan-run hkdf_pieces_botan : hkdf_pieces_botan_test.cpp + : WEBCPP_HASH_DETAIL_TEST_WIPE_RECORD ; +botan-run hkdf_pieces_botan_sliced : hkdf_pieces_botan_test.cpp + : WEBCPP_HASH_DETAIL_TEST_WIPE_RECORD + WEBCPP_HASH_DETAIL_TEST_HKDF_PIECES_SLICE=7 ; # Argon2 on backends::botan: RFC 9106's three cases through the family, # libsodium's table through argon2id, argon2_ctx on random cases with lanes, a # secret and associated data, libsodium at one lane, and Botan's limits (129 @@ -497,12 +547,14 @@ hash-run webcrypto_oracle : webcrypto_oracle_test.cpp -sJSPI : emscripten ; # The asynchronous family (spec 11). The cheap functions on a synchronous -# backend, their default and backends::hash2 named, complete through a post, -# never inside the call, on every target. The heavy functions run on a -# thread_pool's thread where the build has threads: natively and on Emscripten -# with -pthread (threading=multi), whose pools' three workers start before -# main blocks in run (PTHREAD_POOL_SIZE). -hash-run async_post : async_post_test.cpp : /webcpp/asio//asio ; +# backend, their default and backends::hash2 named (the HKDF functions also +# backends::sodium), complete through a post, never inside the call, on every +# target; the forms over pieces read them in the call. The heavy functions run +# on a thread_pool's thread where the build has threads: natively and on +# Emscripten with -pthread (threading=multi), whose pools' three workers start +# before main blocks in run (PTHREAD_POOL_SIZE). +hash-run async_post : async_post_test.cpp + : /webcpp/asio//asio /third_party//sodium ; # backends::webcrypto, node's crypto.subtle through webcpp::asio's promise # bridge (Emscripten only, asio's JSPI link): the published cases with three # completion tokens, 100 random cases per function against backends::hash2, @@ -510,6 +562,13 @@ hash-run async_post : async_post_test.cpp : /webcpp/asio//asio ; # cancellation and the handler's allocator. hash-run async_webcrypto : async_webcrypto_test.cpp : /webcpp/asio//asio : emscripten ; +# The same program with the bound of the bytes gathered into one JavaScript +# buffer lowered from 2^53 - 1 to 100 by a test seam: it checks that refusal +# alone (backend_failure, the output zeroed). +hash-run async_webcrypto_gathered : async_webcrypto_test.cpp + : /webcpp/asio//asio + WEBCPP_HASH_DETAIL_TEST_WEBCRYPTO_MAX_GATHERED=100 + : emscripten ; hash-run async_heavy : async_heavy_test.cpp : /webcpp/asio//asio /third_party//sodium multi emscripten:-sPTHREAD_POOL_SIZE=3 @@ -567,6 +626,9 @@ hash-run sodium_threads : sodium_threads_test.cpp # scrypt on backends::sodium: RFC 7914's first three cases and the guards. hash-run scrypt : scrypt_test.cpp : /third_party//sodium ; +# The spelled-out names (design D7): scrypt's cost, block_size, parallelism, +# argon2's memory_kibibytes and hkdf_max_application_info_size. +hash-run names : names_test.cpp : /third_party//sodium ; # RFC 7914's fourth case (1 GiB), on every target: it passed natively and on # wasip2, wasip3 and emscripten (with /third_party//sodium's memory growth), # each in 5 to 25 seconds unoptimised (wasmtime 47.0.3, node 26.13). @@ -725,7 +787,8 @@ botan-run timing_async_botan : timing_async_test.cpp # DIT is set while a keyed function computes: a Hash2-form probe records DIT at # each update under the hmac of hkdf_extract, hkdf_expand, hkdf, pbkdf2 and mac; -# timing_during_async the same through async_pbkdf2, on the pool's thread. +# timing_during_async the same through async_pbkdf2, on the pool's thread, and +# through the asynchronous HKDF functions over pieces, in the initiating call. hash-run timing_during : timing_during_test.cpp ; hash-run timing_during_async : timing_during_test.cpp : /webcpp/asio//asio multi WEBCPP_TEST_TIMING_DURING_ASYNC @@ -773,7 +836,11 @@ hash-run timing_coverage_xkcp : timing_coverage_xkcp_test.cpp : $(.hash-tables) /third_party//xkcp ; hash-run timing_coverage_blake3 : timing_coverage_blake3_test.cpp : $(.hash-tables) /third_party//blake3 ; -botan-run timing_coverage_botan : timing_coverage_botan_test.cpp : $(.hash-tables) ; +# Its every Botan cell (the HKDF-over-pieces ones too) instantiates enough +# templates to pass the 65,279 sections of an MSVC 14.3 x64 object (C1128), +# so MSVC compiles it with /bigobj, as tools/webcpp-botan.jam does Botan. +botan-run timing_coverage_botan : timing_coverage_botan_test.cpp + : $(.hash-tables) msvc:/bigobj ; build-project messages ; diff --git a/test/agreement_families_test.cpp b/test/agreement_families_test.cpp index 039279f..7042398 100644 --- a/test/agreement_families_test.cpp +++ b/test/agreement_families_test.cpp @@ -568,7 +568,7 @@ struct argon2_case { bytes secret; bytes associated_data; std::uint32_t passes = 1; - std::uint32_t memory_kib = 8; + std::uint32_t memory_kibibytes = 8; std::uint32_t lanes = 1; std::size_t output = 0; }; @@ -604,7 +604,7 @@ argon2_case next_argon2_case(random_source& rnd, std::size_t index) { c.output = rnd.between(0, 3) == 0 ? rnd.between(4, sodium_shortest_tag - 1) : rnd.between(sodium_shortest_tag, 80); c.passes = static_cast(rnd.between(1, 4)); - c.memory_kib = static_cast(rnd.between(std::size_t{8} * c.lanes, 256)); + c.memory_kibibytes = static_cast(rnd.between(std::size_t{8} * c.lanes, 256)); return c; } @@ -614,7 +614,7 @@ boost::system::result argon2_of(bytes& out, argon2_case const& c) { return hash::argon2(out, c.password, c.salt, { .passes = c.passes, - .memory_kib = c.memory_kib, + .memory_kibibytes = c.memory_kibibytes, .lanes = c.lanes, .secret = c.secret, .associated_data = c.associated_data, diff --git a/test/allocation_botan_test.cpp b/test/allocation_botan_test.cpp index 5755d59..c9ab454 100644 --- a/test/allocation_botan_test.cpp +++ b/test/allocation_botan_test.cpp @@ -9,15 +9,16 @@ // allocator), so each call of every entry point backends::botan has is counted, operator new and, // where the target counts it, the C library's allocator, and printed as a record, never bounded. // The calls are digest_of and a hasher's whole hash over each of its 25 digests, mac over each of -// its 27 MACs, and every key derivation and password hash: hkdf_extract, hkdf_expand, hkdf and -// pbkdf2 over each of its 14 hmacs, argon2id, argon2 of each variant, scrypt, bcrypt, -// bcrypt_verify, bcrypt_pbkdf, kbkdf over each hmac, sskdf over each of its 10 digests and x963kdf -// over each of its 5, each twice (a first call and a steady one). A refusal by a guard, before -// Botan is reached, allocates nothing at all, which is asserted. +// its 27 MACs, and every key derivation and password hash: hkdf_extract, hkdf_expand, hkdf (each +// also over pieces, on Botan's HMAC) and pbkdf2 over each of its 14 hmacs, argon2id, argon2 of +// each variant, scrypt, bcrypt, bcrypt_verify, bcrypt_pbkdf, kbkdf over each hmac, sskdf over each +// of its 10 digests and x963kdf over each of its 5, each twice (a first call and a steady one). A +// refusal by a guard, before Botan is reached, allocates nothing at all, which is asserted. #include #include #include +#include #include #include #include @@ -118,14 +119,16 @@ void mac_calls(std::string_view name, std::size_t size, std::size_t key_size) { }); } -// The key derivations over Hmac: hkdf_extract, hkdf_expand, hkdf, pbkdf2 and kbkdf, twice; then an -// empty output, refused. +// The key derivations over Hmac: hkdf_extract, hkdf_expand, hkdf (each also over pieces), pbkdf2 +// and kbkdf, twice; then an empty output, refused, of hkdf and of hkdf over pieces. template void hmac_kdf_calls(std::string_view name) { std::array output{}; std::array prk{}; constexpr std::size_t digest_size = typename Hmac::result_type().size(); auto const key = std::span(prk).first(digest_size); + std::span const head = std::span(message).first(40); + std::span const tail = std::span(message).subspan(40); for (int round = 1; round != 3; ++round) { counted("hkdf_extract", name, round, [&] { return hash::hkdf_extract(message, message).has_value(); }); @@ -138,12 +141,25 @@ void hmac_kdf_calls(std::string_view name) { [&] { return hash::pbkdf2(output, message, message, 2).has_value(); }); counted("kbkdf", name, round, [&] { return hash::kbkdf(output, message).has_value(); }); + counted("hkdf_extract_pieces", name, round, + [&] { return hash::hkdf_extract(message, {head, tail}).has_value(); }); + counted("hkdf_expand_pieces", name, round, [&] { + return hash::hkdf_expand(output, key, {head, tail}).has_value(); + }); + counted("hkdf_pieces", name, round, [&] { + return hash::hkdf(output, message, {head, tail}, {head, tail}).has_value(); + }); } refused_without_allocating(name, [&] { auto const refused = hash::hkdf(std::span(output).first(0), message, message, message); return refused.has_error() && refused.error() == hash::error::invalid_output_size; }); + refused_without_allocating(name, [&] { + auto const refused = hash::hkdf(std::span(output).first(0), message, + {head, tail}, {head, tail}); + return refused.has_error() && refused.error() == hash::error::invalid_output_size; + }); } // The digest key derivations over Digest: sskdf (and x963kdf where SEC 1 has the digest), twice. @@ -175,21 +191,22 @@ void password_calls() { }); counted("argon2", "kdfs::argon2d", round, [&] { return hash::argon2( - output, message, salt, {.passes = 1, .memory_kib = 16, .lanes = 2}) + output, message, salt, {.passes = 1, .memory_kibibytes = 16, .lanes = 2}) .has_value(); }); counted("argon2", "kdfs::argon2i", round, [&] { return hash::argon2( - output, message, salt, {.passes = 1, .memory_kib = 16, .lanes = 2}) + output, message, salt, {.passes = 1, .memory_kibibytes = 16, .lanes = 2}) .has_value(); }); counted("argon2", "kdfs::argon2id", round, [&] { return hash::argon2( - output, message, salt, {.passes = 1, .memory_kib = 16, .lanes = 2}) + output, message, salt, {.passes = 1, .memory_kibibytes = 16, .lanes = 2}) .has_value(); }); counted("scrypt", "kdfs::scrypt", round, [&] { - return hash::scrypt(output, message, salt, {.n = 16, .r = 1, .p = 1}) + return hash::scrypt(output, message, salt, + {.cost = 16, .block_size = 1, .parallelism = 1}) .has_value(); }); counted("bcrypt", "kdfs::bcrypt", round, @@ -209,12 +226,12 @@ void password_calls() { }); refused_without_allocating("kdfs::argon2", [&] { auto const refused = hash::argon2( - output, message, salt, {.passes = 1, .memory_kib = 8 * 129, .lanes = 129}); + output, message, salt, {.passes = 1, .memory_kibibytes = 8 * 129, .lanes = 129}); return refused.has_error() && refused.error() == hash::error::unsupported_by_backend; }); refused_without_allocating("kdfs::scrypt", [&] { - auto const refused = - hash::scrypt(output, message, salt, {.n = 16, .r = 257, .p = 1}); + auto const refused = hash::scrypt(output, message, salt, + {.cost = 16, .block_size = 257, .parallelism = 1}); return refused.has_error() && refused.error() == hash::error::unsupported_by_backend; }); refused_without_allocating("kdfs::bcrypt", [&] { @@ -317,9 +334,9 @@ int main() { password_calls(); // 25 digests (two calls each of digest_of and hasher, and a refusal) and 27 MACs (two calls - // and a refusal); 14 hmacs (two calls each of five functions, and a refusal); 10 digests of - // sskdf and 5 of x963kdf, two calls each; 8 password functions, two calls each, and 6 - // refusals. - BOOST_TEST_EQ(calls_made, (25U * 5U) + (27U * 3U) + (14U * 11U) + (15U * 2U) + (8U * 2U) + 6U); + // and a refusal); 14 hmacs (two calls each of eight functions, HKDF's three over pieces among + // them, and two refusals); 10 digests of sskdf and 5 of x963kdf, two calls each; 8 password + // functions, two calls each, and 6 refusals. + BOOST_TEST_EQ(calls_made, (25U * 5U) + (27U * 3U) + (14U * 18U) + (15U * 2U) + (8U * 2U) + 6U); return webcpp::test::exit_status(boost::report_errors()); } diff --git a/test/allocation_openssl_test.cpp b/test/allocation_openssl_test.cpp index 35c6b34..78b559d 100644 --- a/test/allocation_openssl_test.cpp +++ b/test/allocation_openssl_test.cpp @@ -11,7 +11,9 @@ // OpenSSL's allocator is a measurement, never a bound. The calls are every entry point // backends::openssl has (increments 1 and 4, ruling R94): HKDF and PBKDF2 over four hmacs (whose // records bench/allocation_collect.py collects into doc/measurements.allocation.json and -// doc/allocation.adoc); digest_of, and a hasher's whole hash, over each of its 23 digests, whose +// doc/allocation.adoc), and hkdf_extract, hkdf_expand and hkdf over pieces over the same four, +// whose EVP_MAC_CTX OpenSSL allocates with EVP_MAC_CTX_new, and Expand's for each block with +// EVP_MAC_CTX_dup; digest_of, and a hasher's whole hash, over each of its 23 digests, whose // EVP_MD_CTX OpenSSL allocates with EVP_MD_CTX_new; mac over each of its 26 MACs, whose // EVP_MAC_CTX OpenSSL allocates with EVP_MAC_CTX_new; argon2's three variants, argon2id, scrypt, // kbkdf, sskdf and x963kdf, whose EVP_KDF_CTX OpenSSL allocates (Argon2's and scrypt's memory @@ -24,7 +26,9 @@ #include #include +#include #include +#include #include #include #include @@ -96,33 +100,6 @@ void measured(char const* operation, char const* hmac, int call, F&& call_it) { operation, hmac, webcpp::test::target_name, call, own); } -template -void measure_one(char const* name) { - using hash::backends::openssl; - if constexpr (!hash::backend_has_v) { - std::printf("record operation=none hmac=%s backend=openssl target=%s\n", name, - webcpp::test::target_name); - } else { - std::array okm{}; - std::array key{}; - std::span const input(bytes); - // The first call of each function pays OpenSSL's one-time setup; the second is steady - // state. - for (int round = 1; round != 3; ++round) { - measured("hkdf", name, round, [&] { - auto const done = - hash::hkdf(okm, input.first(20), input, input.last(10)); - BOOST_TEST(done.has_value()); - }); - measured("pbkdf2", name, round, [&] { - auto const done = - hash::pbkdf2(key, input.first(20), input.last(16), 3); - BOOST_TEST(done.has_value()); - }); - } - } -} - // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): calls under the counters std::size_t calls_made = 0; @@ -142,16 +119,74 @@ void counted(char const* operation, char const* key, char const* name, int call, operation, key, name, webcpp::test::target_name, call, own); } -/** A refusal by a guard, before OpenSSL is reached: no allocation of any kind. */ +/** + A refusal by a guard, before OpenSSL is reached: `call_it()` returns the error `expected` and no + allocation of any kind happened. +*/ template -void refused_without_allocating(char const* name, F&& call_it) { +void refused_without_allocating(char const* name, hash::error expected, F&& call_it) { ++calls_made; std::size_t const own_before = openssl_allocations.load(); std::size_t const new_before = webcpp::test::counted_new.load(); - bool const refused = call_it(); - if (!BOOST_TEST(refused) || !BOOST_TEST_EQ(openssl_allocations.load(), own_before) || + auto const done = call_it(); + if (!BOOST_TEST(done.has_error()) || !BOOST_TEST(done.error() == expected) || + !BOOST_TEST_EQ(openssl_allocations.load(), own_before) || !BOOST_TEST_EQ(webcpp::test::counted_new.load(), new_before)) { - std::printf("allocated or not refused: %s\n", name); + std::printf("allocated or not refused with error %d: %s (error %d)\n", + static_cast(expected), name, done.has_error() ? done.error().value() : 0); + } +} + +/** + HKDF, PBKDF2 and HKDF's three functions over pieces over `Hmac`, twice each (the first call pays + OpenSSL's one-time setup); then hkdf over pieces with an empty output, refused. +*/ +template +void measure_one(char const* name) { + using hash::backends::openssl; + if constexpr (!hash::backend_has_v) { + std::printf("record operation=none hmac=%s backend=openssl target=%s\n", name, + webcpp::test::target_name); + } else { + std::array okm{}; + std::array key{}; + std::span const input(bytes); + // The first call of each function pays OpenSSL's one-time setup; the second is steady + // state. + for (int round = 1; round != 3; ++round) { + measured("hkdf", name, round, [&] { + auto const done = + hash::hkdf(okm, input.first(20), input, input.last(10)); + BOOST_TEST(done.has_value()); + }); + measured("pbkdf2", name, round, [&] { + auto const done = + hash::pbkdf2(key, input.first(20), input.last(16), 3); + BOOST_TEST(done.has_value()); + }); + measured("hkdf_extract_pieces", name, round, [&] { + auto const done = hash::hkdf_extract( + input.first(20), {input.first(30), input.last(34)}); + BOOST_TEST(done.has_value()); + }); + measured("hkdf_expand_pieces", name, round, [&] { + constexpr std::size_t digest_size = typename Hmac::result_type().size(); + auto const done = hash::hkdf_expand(okm, input.first(digest_size), + {input.first(4), input.last(6)}); + BOOST_TEST(done.has_value()); + }); + measured("hkdf_pieces", name, round, [&] { + auto const done = hash::hkdf(okm, input.first(20), + {input.first(30), input.last(34)}, + {input.first(4), input.last(6)}); + BOOST_TEST(done.has_value()); + }); + } + refused_without_allocating(name, hash::error::invalid_output_size, [&] { + return hash::hkdf(std::span{}, input.first(20), + {input.first(30), input.last(34)}, + {input.first(4), input.last(6)}); + }); } } @@ -180,8 +215,8 @@ void measure_digest(char const* name) { } }); } - refused_without_allocating(name, [&] { - return !hash::digest_of(std::span{}, input).has_value(); + refused_without_allocating(name, hash::error::invalid_output_size, [&] { + return hash::digest_of(std::span{}, input); }); } @@ -204,10 +239,9 @@ void measure_mac(char const* name, hash::mac_options const& options = {}) { (hash::mac(tag, input.first(key_size), input, options).has_value())); }); } - refused_without_allocating(name, [&] { - return !hash::mac(std::span{}, input.first(key_size), input, - options) - .has_value(); + refused_without_allocating(name, hash::error::invalid_output_size, [&] { + return hash::mac(std::span{}, input.first(key_size), input, + options); }); } @@ -277,15 +311,15 @@ void measure_macs() { } // A key derivation of backends::openssl, twice, then refused: `derive(output)` derives into the -// span, `refuse()` calls the function with a value its guards refuse. +// span, `refuse()` calls the function with a value its guards refuse with `expected`. template -void measure_kdf(char const* name, Derive derive, Refuse refuse) { +void measure_kdf(char const* name, Derive derive, hash::error expected, Refuse refuse) { std::array output{}; for (int round = 1; round != 3; ++round) { counted("kdf", "function", name, round, [&] { BOOST_TEST(derive(std::span(output)).has_value()); }); } - refused_without_allocating(name, [&] { return !refuse().has_value(); }); + refused_without_allocating(name, expected, refuse); } // One variant of argon2, two lanes with a secret and associated data, at 64 KiB. @@ -299,16 +333,17 @@ void measure_argon2(char const* name) { return hash::argon2(output, input.first(20), input.first(16), { .passes = 1, - .memory_kib = 64, + .memory_kibibytes = 64, .lanes = 2, .secret = input.first(8), .associated_data = input.last(12), }); }, + hash::error::invalid_parameters, [&] { std::array tag{}; return hash::argon2(tag, input, input.first(16), - {.passes = 0, .memory_kib = 64}); + {.passes = 0, .memory_kibibytes = 64}); }); } @@ -330,6 +365,7 @@ void measure_kdfs() { return hash::argon2id(output, input.first(20), salt, {.passes = 1, .memory = std::size_t{64} * 1024}); }, + hash::error::invalid_salt_size, [&] { std::array tag{}; return hash::argon2id(tag, input, input.first(15), @@ -339,11 +375,13 @@ void measure_kdfs() { "scrypt", [&](std::span output) { return hash::scrypt(output, input.first(20), salt, - {.n = 1024, .r = 8, .p = 1}); + {.cost = 1024, .block_size = 8, .parallelism = 1}); }, + hash::error::invalid_parameters, [&] { std::array key{}; - return hash::scrypt(key, input, salt, {.n = 1000, .r = 8, .p = 1}); + return hash::scrypt(key, input, salt, + {.cost = 1000, .block_size = 8, .parallelism = 1}); }); auto const kbkdf = [&](char const* name) { measure_kdf( @@ -352,6 +390,7 @@ void measure_kdfs() { return hash::kbkdf( output, input.first(32), {.label = input.first(5), .context = input.last(7)}); }, + hash::error::invalid_key_size, [&] { std::array key{}; return hash::kbkdf(key, {}); @@ -365,6 +404,7 @@ void measure_kdfs() { [&](std::span output) { return hash::sskdf(output, input.first(32), input.last(10)); }, + hash::error::invalid_key_size, [&] { std::array key{}; return hash::sskdf(key, {}); @@ -378,6 +418,7 @@ void measure_kdfs() { return hash::x963kdf(output, input.first(32), input.last(10)); }, + hash::error::invalid_key_size, [&] { std::array key{}; return hash::x963kdf(key, {}); diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index 5cc795f..8d2eccf 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -10,24 +10,26 @@ // XKCP (increment 3), BLAKE3, Boost.Hash2's digests and hmacs, HKDF and PBKDF2 on hash2, libsodium // (HKDF) and BearSSL (HKDF, and its digests and HMAC through the families: ruling R94); the // families digest_of, hasher, mac and argon2 on every backend that has a tag and on each tag's -// default, blake2b_subkey and the asynchronous family, on every target. A -// control that allocates once moves the counter, so a zero is not a broken counter. Every call is -// counted and the totals asserted exactly per backend, so a backend a wrong trait or a dropped -// define leaves out fails, and the refusals of every guard run under the counter too. Argon2id and -// scrypt are the one exception, and it is libsodium's: their working memory (Argon2id's matrix, 128 -// r N bytes of scrypt) comes from libsodium's own mmap, else posix_memalign, else malloc, outside -// webcpp's code; the test asserts only that operator new is not called, and prints the C allocator -// calls it saw (mmap is not among the calls the counter sees, so those are libsodium's small -// bookkeeping blocks, not the memory). The asynchronous family (async.hpp, increment 7) takes its -// storage from the handler's associated allocator, as Asio's operations do: with an arena of the -// test's bound to the handler, the cheap functions (async_digest, async_hmac, async_hkdf, and their -// guards' refusals) call neither operator new nor the C allocator, and the arena gets back every -// block before the handler runs; the heavy functions (natively, on a thread pool) take their state -// and completion from the arena too and call no operator new, the pool's queue and libsodium's -// memory being the C allocator's; on Emscripten the four functions on backends::webcrypto call the -// C allocator only as often as webcpp::asio's promise bridge does for a bare await, once per -// promise. Every printed result is one `record key=value ...` line, collected by -// bench/allocation_collect.py. +// default, blake2b_subkey and the asynchronous family, on every target. A control that allocates +// once moves the counter, so a zero is not a broken counter. Every call is counted and the totals +// asserted exactly per backend (HKDF over pieces on hash2, sodium and bearssl among them, with +// inputs of 4 KiB and 1 MiB in four pieces), so a backend a wrong trait or a dropped define leaves +// out fails, and the refusals of every guard run under the counter too. Argon2id and scrypt are the +// one exception, and it is libsodium's: their working memory (Argon2id's matrix, 128 r N bytes of +// scrypt) comes from libsodium's own mmap, else posix_memalign, else malloc, outside webcpp's code; +// the test asserts only that operator new is not called, and prints the C allocator calls it saw +// (mmap is not among the calls the counter sees, so those are libsodium's small bookkeeping blocks, +// not the memory). The asynchronous family (async.hpp, increment 7) takes its storage from the +// handler's associated allocator, as Asio's operations do: with an arena of the test's bound to the +// handler, the cheap functions (async_digest, async_hmac, async_hkdf_extract, async_hkdf_expand, +// async_hkdf, each HKDF function also over pieces, and their guards' refusals) call neither +// operator new nor the C allocator, and the arena gets back every block before the handler runs; +// the heavy functions (natively, on a thread pool) take their state and completion from the arena +// too and call no operator new, the pool's queue and libsodium's memory being the C allocator's; on +// Emscripten the functions on backends::webcrypto (HKDF over pieces on its HMAC among them) call +// the C allocator only as often as webcpp::asio's promise bridge does for a bare await, once per +// promise. Every printed result is +// one `record key=value ...` line, collected by bench/allocation_collect.py. #include #include @@ -127,6 +129,12 @@ void allocates_nothing(char const* name, F&& call) { } } +/** Whether `done` is the refusal `expected`: a guard's, not a refusal for another reason. */ +template +bool refused_with(Result const& done, hash::error expected) { + return done.has_error() && done.error() == expected; +} + /** A digest of Boost.Hash2's, from construction to result, in three update shapes. */ template void digest_allocates_nothing(char const* name) { @@ -166,13 +174,14 @@ void hkdf_steps_allocate_nothing(char const* name, std::span okm, BOOST_TEST(expanded.has_value()); }); allocates_nothing(name, [&] { - auto const refused = hash::hkdf_expand(okm, message_input.first(3), {}); - BOOST_TEST(!refused.has_value()); + auto const refused = hash::hkdf_expand(okm, message_input.first(3), + std::span{}); + BOOST_TEST(refused_with(refused, hash::error::invalid_key_size)); }); allocates_nothing(name, [&] { auto const refused = hash::hkdf_expand(okm, message_input.first(3), long_info); - BOOST_TEST(!refused.has_value()); + BOOST_TEST(refused_with(refused, hash::error::invalid_key_size)); }); } @@ -183,24 +192,25 @@ void hkdf_allocates_nothing(char const* name) { std::array okm{}; std::span const no_output; // One byte over the limit, in a real buffer: the guard refuses on the size alone. - static std::array const long_buffer{}; + static std::array const long_buffer{}; std::span const long_info(long_buffer); allocates_nothing(name, [&] { auto const full = hash::hkdf(okm, message_input.first(20), message_input, message_input.last(10)); - auto const empty = hash::hkdf(okm, {}, {}, {}); + std::span const none; + auto const empty = hash::hkdf(okm, none, none, none); BOOST_TEST(full.has_value()); BOOST_TEST(empty.has_value()); }); allocates_nothing(name, [&] { auto const refused = hash::hkdf(no_output, message_input, message_input, message_input); - BOOST_TEST(!refused.has_value()); + BOOST_TEST(refused_with(refused, hash::error::invalid_output_size)); }); allocates_nothing(name, [&] { auto const refused = hash::hkdf(okm, message_input, message_input, long_info); - BOOST_TEST(!refused.has_value()); + BOOST_TEST(refused_with(refused, hash::error::input_too_long)); }); if constexpr (split) { hkdf_steps_allocate_nothing(name, okm, long_info); @@ -219,7 +229,7 @@ void pbkdf2_allocates_nothing(char const* name) { allocates_nothing(name, [] { std::array key{}; auto const refused = hash::pbkdf2(key, message_input, message_input, 0); - BOOST_TEST(!refused.has_value()); + BOOST_TEST(refused_with(refused, hash::error::invalid_iterations)); }); } @@ -237,6 +247,73 @@ void kdfs_allocate_nothing(char const* name) { } } +// HKDF over pieces (design D3, D8): the three forms with inputs of 4 KiB and 1 MiB in four pieces +// (6), then each refusal of RFC 5869's sizes (5): Expand's and hkdf's outputs of no byte and of +// 255 digests and one byte, Expand's pseudorandom key of a byte less than the digest. 11 calls. +// The 1 MiB hkdf_expand is the spec's scenario "A Welcome-sized info", on each backend it runs on. +template +void hkdf_pieces_allocate_nothing(char const* name, std::size_t expected_calls) { + std::size_t const before = calls_made; + constexpr std::size_t digest_size = typename Hmac::result_type().size(); + // In static storage, filled before the counter starts: no allocation of the test's own. + static std::array long_buffer{}; + for (std::size_t i = 0; i != long_buffer.size(); ++i) { + long_buffer[i] = static_cast(i * 13); + } + static std::array too_long_output{}; + std::array okm{}; + std::array const prk{}; + for (std::size_t const size : {std::size_t{4096}, long_buffer.size()}) { + std::span const input = std::span(long_buffer).first(size); + std::size_t const quarter = size / 4; + std::array, 4> const pieces{ + input.first(quarter), + input.subspan(quarter, quarter), + input.subspan(2 * quarter, quarter), + input.subspan(3 * quarter), + }; + allocates_nothing(name, [&] { + BOOST_TEST((hash::hkdf_extract(message_input, pieces).has_value())); + }); + allocates_nothing(name, [&] { + BOOST_TEST((hash::hkdf_expand(okm, prk, pieces).has_value())); + }); + allocates_nothing(name, [&] { + BOOST_TEST((hash::hkdf(okm, message_input, pieces, pieces).has_value())); + }); + } + std::array, 2> const pieces{ + message_input.first(3), + message_input.last(7), + }; + std::span const no_output; + allocates_nothing(name, [&] { + BOOST_TEST(refused_with(hash::hkdf_expand(no_output, prk, pieces), + hash::error::invalid_output_size)); + }); + allocates_nothing(name, [&] { + BOOST_TEST(refused_with(hash::hkdf_expand(too_long_output, prk, pieces), + hash::error::invalid_output_size)); + }); + allocates_nothing(name, [&] { + BOOST_TEST(refused_with( + hash::hkdf_expand(okm, std::span(prk).first(digest_size - 1), pieces), + hash::error::invalid_key_size)); + }); + allocates_nothing(name, [&] { + BOOST_TEST(refused_with(hash::hkdf(no_output, message_input, pieces, pieces), + hash::error::invalid_output_size)); + }); + allocates_nothing(name, [&] { + BOOST_TEST( + refused_with(hash::hkdf(too_long_output, message_input, pieces, pieces), + hash::error::invalid_output_size)); + }); + BOOST_TEST_EQ(calls_made - before, expected_calls); + std::printf("record operation=hkdf-pieces-calls backend=%s target=%s calls=%zu expected=%zu\n", + name, webcpp::test::target_name, calls_made - before, expected_calls); +} + template void all_hmacs(char const* name, std::size_t expected_calls) { std::size_t const before = calls_made; @@ -437,8 +514,8 @@ void sodium_memory_hard() { webcpp::test::target_name, argon.news(), argon.cs(), webcpp::test::c_allocations_counted ? 1 : 0); window const scr; - auto const scrypt_done = hash::scrypt(out, message_input.first(20), salt, - {.n = 1024, .r = 8, .p = 1}); + auto const scrypt_done = hash::scrypt( + out, message_input.first(20), salt, {.cost = 1024, .block_size = 8, .parallelism = 1}); BOOST_TEST(scrypt_done.has_value()); BOOST_TEST_EQ(scr.news(), 0U); std::printf("record operation=scrypt backend=sodium target=%s new=%zu c=%zu counted=%d\n", @@ -562,12 +639,14 @@ void family_digest_refuses() { auto const options = family_options(); std::array output_bytes{}; std::span const output(output_bytes.data(), family_output_size(options)); - BOOST_TEST(!(hash::digest_of(std::span{}, message_input, options))); + BOOST_TEST(refused_with( + hash::digest_of(std::span{}, message_input, options), + hash::error::invalid_output_size)); auto hashing = hash::hasher::make(options); BOOST_TEST(hashing.has_value()); if (hashing) { BOOST_TEST(hashing->finish(output).has_value()); - BOOST_TEST(!hashing->finish(output).has_value()); + BOOST_TEST(refused_with(hashing->finish(output), hash::error::invalid_state)); } } @@ -678,7 +757,8 @@ void blake2b_subkey_allocates_nothing() { BOOST_TEST(hash::blake2b_subkey(subkey, message_input.first(32), 2, context).has_value()); }); allocates_nothing("blake2b_subkey", [&] { - BOOST_TEST(!hash::blake2b_subkey(subkey, message_input.first(31), 1, context)); + BOOST_TEST(refused_with(hash::blake2b_subkey(subkey, message_input.first(31), 1, context), + hash::error::invalid_key_size)); }); BOOST_TEST_EQ(calls_made - before, 3U); } @@ -690,7 +770,7 @@ template void argon2_family_on_sodium(char const* name, std::uint32_t passes) { std::array out{}; std::array const salt{}; - hash::argon2_parameters const cheapest{.passes = passes, .memory_kib = 8}; + hash::argon2_parameters const cheapest{.passes = passes, .memory_kibibytes = 8}; // Each call in its own window; the two counts are libsodium's, printed one after the other. for (bool const by_default : {false, true}) { window const w; @@ -706,8 +786,10 @@ void argon2_family_on_sodium(char const* name, std::uint32_t passes) { name, by_default ? "default" : "named", webcpp::test::target_name, w.news(), w.cs()); } allocates_nothing(name, [&] { - BOOST_TEST(!(hash::argon2(out, message_input.first(20), salt, - {.passes = passes, .memory_kib = 32, .lanes = 4}))); + BOOST_TEST(refused_with( + hash::argon2(out, message_input.first(20), salt, + {.passes = passes, .memory_kibibytes = 32, .lanes = 4}), + hash::error::unsupported_by_backend)); }); } #endif @@ -795,7 +877,8 @@ void async_allocates_nothing(char const* name, webcpp::asio::io_context& context } // The cheap functions on their default backend, a result and a refusal each (an output of 0 -// bytes): 6 calls. One call before the windows lets the io_context make what it makes once. +// bytes), each HKDF function also over pieces: 16 calls. One call before the windows lets the +// io_context make what it makes once. void async_cheap() { namespace asio = webcpp::asio; std::size_t const before = calls_made; @@ -832,18 +915,70 @@ void async_cheap() { hash::async_hkdf(executor, none, {}, message_input, {}, std::move(handler)); }); - BOOST_TEST_EQ(calls_made - before, 6U); + std::array, 3> const pieces{ + message_input.first(5), + std::span{}, + message_input.subspan(5), + }; + std::span const prk = message_input.first(32); + async_allocates_nothing("async_hkdf over pieces", context, fine, [&](auto handler) { + hash::async_hkdf(executor, out, {}, pieces, pieces, + std::move(handler)); + }); + async_allocates_nothing("async_hkdf over pieces refused", context, refused, [&](auto handler) { + hash::async_hkdf(executor, none, {}, pieces, pieces, + std::move(handler)); + }); + async_allocates_nothing("async_hkdf_extract", context, fine, [&](auto handler) { + hash::async_hkdf_extract(executor, out, {}, message_input, + std::move(handler)); + }); + async_allocates_nothing("async_hkdf_extract refused", context, refused, [&](auto handler) { + hash::async_hkdf_extract(executor, none, {}, message_input, + std::move(handler)); + }); + async_allocates_nothing("async_hkdf_extract over pieces", context, fine, [&](auto handler) { + hash::async_hkdf_extract(executor, out, {}, pieces, + std::move(handler)); + }); + async_allocates_nothing("async_hkdf_extract over pieces refused", context, refused, + [&](auto handler) { + hash::async_hkdf_extract( + executor, none, {}, pieces, std::move(handler)); + }); + async_allocates_nothing("async_hkdf_expand", context, fine, [&](auto handler) { + hash::async_hkdf_expand(executor, out, prk, message_input, + std::move(handler)); + }); + async_allocates_nothing("async_hkdf_expand refused", context, refused, [&](auto handler) { + hash::async_hkdf_expand(executor, none, prk, message_input, + std::move(handler)); + }); + async_allocates_nothing("async_hkdf_expand over pieces", context, fine, [&](auto handler) { + hash::async_hkdf_expand(executor, out, prk, pieces, + std::move(handler)); + }); + async_allocates_nothing("async_hkdf_expand over pieces refused", context, refused, + [&](auto handler) { + hash::async_hkdf_expand( + executor, none, prk, pieces, std::move(handler)); + }); + BOOST_TEST_EQ(calls_made - before, 16U); } #ifdef WEBCPP_TARGET_EMSCRIPTEN -// The four functions on backends::webcrypto (Emscripten): the bridge's waits, the operation and -// its posts are the handler's arena's, every block given back before the handler runs, and -// operator new is not called; a refusal (an output of 0 bytes) each too: 8 calls. webcpp::asio's -// promise bridge calls the C allocator itself, for each promise awaited, whoever awaits it: a -// bare async_await, measured first, gives its count, and each call is held to that count per -// promise (one for a digest, two for importKey and then sign or deriveBits), so that webcpp::hash's -// code adds none. One call before the windows lets the bridge and the io_context make what they -// make once. +// The functions on backends::webcrypto (Emscripten): async_digest, async_hmac, async_hkdf, +// async_pbkdf2, and HKDF over pieces and its steps on WebCrypto's HMAC (async_hkdf, +// async_hkdf_extract and async_hkdf_expand over pieces, the single-buffer async_hkdf_extract and +// async_hkdf_expand): the bridge's waits, the operation and its posts are the handler's arena's, +// every block given back before the handler runs, and operator new is not called; a refusal (an +// output of 0 bytes) each too: 18 calls. webcpp::asio's promise bridge calls the C allocator +// itself, for each promise awaited, whoever awaits it: a bare async_await, measured first, gives +// its count, and each call is held to that count per promise (one for a digest, two for importKey +// and then sign or deriveBits; over HMAC, two for Extract, 1 + ceil(L / HashLen) for Expand and +// 3 + ceil(L / HashLen) for both), so that webcpp::hash's code adds none: the pieces are gathered +// into JavaScript memory, not webcpp's. One call of each before the windows lets the bridge and the +// io_context make what they make once. void async_webcrypto() { namespace asio = webcpp::asio; using hash::backends::webcrypto; @@ -857,6 +992,21 @@ void async_webcrypto() { hash::async_pbkdf2(executor, out, message_input.first(20), message_input.first(16), 2, [](boost::system::error_code) {}); + // HKDF on HMAC: a 100-byte output is four blocks of SHA-256. + std::array long_out{}; + auto const prk = message_input.first(32); + auto const salt = message_input.first(16); + std::array, 3> const pieces{ + message_input.first(10), + message_input.subspan(10, 0), + message_input.subspan(10), + }; + hash::async_hkdf(executor, long_out, salt, pieces, pieces, + [](boost::system::error_code) {}); + hash::async_hkdf_extract(executor, out, salt, message_input, + [](boost::system::error_code) {}); + hash::async_hkdf_expand(executor, long_out, prk, message_input, + [](boost::system::error_code) {}); context.run(); // lint-run: the context's first run, outside the windows window const bare; asio::browser::async_await( @@ -917,7 +1067,68 @@ void async_webcrypto() { message_input.first(16), 2, std::move(handler)); }); - BOOST_TEST_EQ(calls_made - before, 8U); + std::size_t const blocks = (long_out.size() + 31) / 32; + async_allocates_nothing( + "async_hkdf over pieces webcrypto", context, fine, + [&](auto handler) { + hash::async_hkdf(executor, long_out, salt, pieces, + pieces, std::move(handler)); + }, + (3 + blocks) * per_promise); + async_allocates_nothing("async_hkdf over pieces webcrypto refused", context, refused, + [&](auto handler) { + hash::async_hkdf( + executor, none, salt, pieces, pieces, std::move(handler)); + }); + async_allocates_nothing( + "async_hkdf_extract over pieces webcrypto", context, fine, + [&](auto handler) { + hash::async_hkdf_extract(executor, out, salt, pieces, + std::move(handler)); + }, + 2 * per_promise); + async_allocates_nothing("async_hkdf_extract over pieces webcrypto refused", context, refused, + [&](auto handler) { + hash::async_hkdf_extract( + executor, none, salt, pieces, std::move(handler)); + }); + async_allocates_nothing( + "async_hkdf_extract webcrypto", context, fine, + [&](auto handler) { + hash::async_hkdf_extract( + executor, out, salt, message_input, std::move(handler)); + }, + 2 * per_promise); + async_allocates_nothing("async_hkdf_extract webcrypto refused", context, refused, + [&](auto handler) { + hash::async_hkdf_extract( + executor, none, salt, message_input, std::move(handler)); + }); + async_allocates_nothing( + "async_hkdf_expand over pieces webcrypto", context, fine, + [&](auto handler) { + hash::async_hkdf_expand(executor, long_out, prk, pieces, + std::move(handler)); + }, + (1 + blocks) * per_promise); + async_allocates_nothing("async_hkdf_expand over pieces webcrypto refused", context, refused, + [&](auto handler) { + hash::async_hkdf_expand( + executor, none, prk, pieces, std::move(handler)); + }); + async_allocates_nothing( + "async_hkdf_expand webcrypto", context, fine, + [&](auto handler) { + hash::async_hkdf_expand( + executor, long_out, prk, message_input, std::move(handler)); + }, + (1 + blocks) * per_promise); + async_allocates_nothing("async_hkdf_expand webcrypto refused", context, refused, + [&](auto handler) { + hash::async_hkdf_expand( + executor, none, prk, message_input, std::move(handler)); + }); + BOOST_TEST_EQ(calls_made - before, 18U); } #endif @@ -984,15 +1195,15 @@ void async_heavy() { }); heavy_allocates_nothing("async_argon2_argon2id", context, [&](auto handler) { hash::async_argon2( - work, out, password, salt, {.passes = 1, .memory_kib = 8}, std::move(handler)); + work, out, password, salt, {.passes = 1, .memory_kibibytes = 8}, std::move(handler)); }); heavy_allocates_nothing("async_argon2_argon2i", context, [&](auto handler) { - hash::async_argon2(work, out, password, salt, - {.passes = 3, .memory_kib = 8}, std::move(handler)); + hash::async_argon2( + work, out, password, salt, {.passes = 3, .memory_kibibytes = 8}, std::move(handler)); }); heavy_allocates_nothing("async_scrypt", context, [&](auto handler) { - hash::async_scrypt(work, out, password, salt, {.n = 1024, .r = 8, .p = 1}, - std::move(handler)); + hash::async_scrypt(work, out, password, salt, + {.cost = 1024, .block_size = 8, .parallelism = 1}, std::move(handler)); }); pool.join(); BOOST_TEST_EQ(calls_made - before, 5U); @@ -1005,6 +1216,7 @@ int main() { control(); digests(); all_hmacs("hash2", 128); + hkdf_pieces_allocate_nothing("hash2", 11); async_cheap(); #ifdef WEBCPP_HASH_HAS_THREADS async_heavy(); @@ -1021,6 +1233,7 @@ int main() { #ifdef WEBCPP_HASH_HAS_SODIUM sodium_first_call(); all_hmacs("sodium", 12); + hkdf_pieces_allocate_nothing("sodium", 11); sodium_memory_hard(); blake2b_subkey_allocates_nothing(); argon2_family_on_sodium("argon2i", 3); @@ -1045,6 +1258,7 @@ int main() { #endif #ifdef WEBCPP_HASH_HAS_BEARSSL all_hmacs("bearssl", 18); + hkdf_pieces_allocate_nothing("bearssl", 11); // BearSSL's entry points of increment 5 (ruling R94): two calls per tag it has, 9 digests // (MD5, SHA-1, SHA-2, MD5-SHA1, SHAKE) and 6 MACs (HMAC over MD5, SHA-1 and SHA-2). families_on("bearssl", 30); diff --git a/test/argon2_botan_test.cpp b/test/argon2_botan_test.cpp index 4808dd4..5ccb424 100644 --- a/test/argon2_botan_test.cpp +++ b/test/argon2_botan_test.cpp @@ -80,7 +80,7 @@ struct rfc9106_inputs { [[nodiscard]] hash::argon2_parameters parameters() const { return { .passes = 3, - .memory_kib = 32, + .memory_kibibytes = 32, .lanes = 4, .secret = secret, .associated_data = associated_data, @@ -202,7 +202,7 @@ void agree_with_reference(argon2_type type, std::string_view name) { auto const associated_data = index % 3 == 1 ? bytes{} : rnd.bytes(rnd.between(1, 32)); auto const passes = static_cast(rnd.between(1, 3)); auto const lanes = static_cast(rnd.between(1, 4)); - auto const memory_kib = + auto const memory_kibibytes = static_cast(rnd.between(std::size_t{8} * lanes, 256)); std::size_t const tag_size = rnd.between(16, 80); bytes expected(tag_size); @@ -212,7 +212,7 @@ void agree_with_reference(argon2_type type, std::string_view name) { .secret = secret, .associated_data = associated_data, .passes = passes, - .memory_kib = memory_kib, + .memory_kibibytes = memory_kibibytes, .lanes = lanes, .variant = type, }); @@ -220,7 +220,7 @@ void agree_with_reference(argon2_type type, std::string_view name) { auto const done = hash::argon2(tag, password, salt, { .passes = passes, - .memory_kib = memory_kib, + .memory_kibibytes = memory_kibibytes, .lanes = lanes, .secret = secret, .associated_data = associated_data, @@ -228,7 +228,7 @@ void agree_with_reference(argon2_type type, std::string_view name) { if (!BOOST_TEST_EQ(code, ARGON2_OK) || !BOOST_TEST(done.has_value()) || !BOOST_TEST_EQ(test::to_hex(tag), test::to_hex(expected))) { std::cerr << " " << name << " case " << index << ": t " << passes << ", m " - << memory_kib << ", p " << lanes << ", tag " << tag_size << '\n'; + << memory_kibibytes << ", p " << lanes << ", tag " << tag_size << '\n'; } } } @@ -243,13 +243,16 @@ void agree_with_sodium() { auto const password = rnd.bytes(rnd.between(0, 64)); auto const salt = rnd.bytes(hash::argon2id_salt_size); auto const passes = static_cast(rnd.between(3, 4)); - auto const memory_kib = static_cast(rnd.between(8, 256)); + auto const memory_kibibytes = static_cast(rnd.between(8, 256)); std::size_t const tag_size = rnd.between(16, 80); hash::argon2id_parameters const costs{ .passes = passes, - .memory = std::size_t{memory_kib} * 1024, + .memory = std::size_t{memory_kibibytes} * 1024, + }; + hash::argon2_parameters const family{ + .passes = passes, + .memory_kibibytes = memory_kibibytes, }; - hash::argon2_parameters const family{.passes = passes, .memory_kib = memory_kib}; bytes expected(tag_size); bytes tag(tag_size); bool agreed = hash::argon2id(expected, password, salt, costs).has_value() && @@ -264,8 +267,8 @@ void agree_with_sodium() { hash::argon2(tag, password, salt, family).has_value() && tag == expected; if (!BOOST_TEST(agreed)) { - std::cerr << " libsodium case " << index << ": t " << passes << ", m " << memory_kib - << ", tag " << tag_size << '\n'; + std::cerr << " libsodium case " << index << ": t " << passes << ", m " + << memory_kibibytes << ", tag " << tag_size << '\n'; } } } @@ -293,13 +296,15 @@ void check_limits() { return hash::argon2(out, {}, s, p); }, }) { - BOOST_TEST(failed_with(call(tag, salt, {.passes = 1, .memory_kib = 8 * 129, .lanes = 129}), - hash::error::unsupported_by_backend)); + BOOST_TEST( + failed_with(call(tag, salt, {.passes = 1, .memory_kibibytes = 8 * 129, .lanes = 129}), + hash::error::unsupported_by_backend)); constexpr std::uint32_t past = ((sizeof(std::size_t) == 4 ? 2U : 8U) * 1024U * 1024U) + 1; - BOOST_TEST(failed_with(call(tag, salt, {.passes = 1, .memory_kib = past}), + BOOST_TEST(failed_with(call(tag, salt, {.passes = 1, .memory_kibibytes = past}), hash::error::unsupported_by_backend)); BOOST_TEST(all_of(tag, untouched)); - BOOST_TEST(call(tag, salt, {.passes = 1, .memory_kib = 8 * 128, .lanes = 128}).has_value()); + BOOST_TEST( + call(tag, salt, {.passes = 1, .memory_kibibytes = 8 * 128, .lanes = 128}).has_value()); tag.fill(untouched); } constexpr std::uint64_t most = (sizeof(std::size_t) == 4 ? std::uint64_t{2} : 8) << 30U; diff --git a/test/argon2_openssl_test.cpp b/test/argon2_openssl_test.cpp index b4ffb79..709e455 100644 --- a/test/argon2_openssl_test.cpp +++ b/test/argon2_openssl_test.cpp @@ -92,7 +92,7 @@ struct rfc9106_inputs { [[nodiscard]] hash::argon2_parameters parameters() const { return { .passes = 3, - .memory_kib = 32, + .memory_kibibytes = 32, .lanes = 4, .secret = secret, .associated_data = associated_data, @@ -119,7 +119,7 @@ std::string rfc9106_reference(argon2_type type) { .secret = in.secret, .associated_data = in.associated_data, .passes = 3, - .memory_kib = 32, + .memory_kibibytes = 32, .lanes = 4, .variant = type, }); @@ -169,15 +169,15 @@ std::string evp_tag(stanza const& lines, std::size_t tag_size) { bytes const secret = ctrl("Ctrl.secret"); bytes const associated_data = ctrl("Ctrl.ad"); bytes tag(tag_size); - auto const done = - hash::argon2(tag, password, salt, - { - .passes = ctrl_number(lines, "Ctrl.iter", 3), - .memory_kib = ctrl_number(lines, "Ctrl.memcost", 8), - .lanes = ctrl_number(lines, "Ctrl.lanes", 1), - .secret = secret, - .associated_data = associated_data, - }); + auto const done = hash::argon2( + tag, password, salt, + { + .passes = ctrl_number(lines, "Ctrl.iter", 3), + .memory_kibibytes = ctrl_number(lines, "Ctrl.memcost", 8), + .lanes = ctrl_number(lines, "Ctrl.lanes", 1), + .secret = secret, + .associated_data = associated_data, + }); if (!BOOST_TEST(done.has_value())) { return {}; } @@ -208,13 +208,13 @@ bool refuses_evp_failure(stanza const& lines, std::size_t index, std::string_vie expected = hash::error::invalid_salt_size; } bytes tag(tag_size, untouched); - auto const refused = - hash::argon2(tag, {}, salt, - { - .passes = ctrl_number(lines, "Ctrl.iter", 3), - .memory_kib = ctrl_number(lines, "Ctrl.memcost", 8), - .lanes = ctrl_number(lines, "Ctrl.lanes", 1), - }); + auto const refused = hash::argon2( + tag, {}, salt, + { + .passes = ctrl_number(lines, "Ctrl.iter", 3), + .memory_kibibytes = ctrl_number(lines, "Ctrl.memcost", 8), + .lanes = ctrl_number(lines, "Ctrl.lanes", 1), + }); if (!BOOST_TEST(failed_with(refused, expected)) || !BOOST_TEST(all_of(tag, untouched))) { std::cerr << " evpkdf_argon2.txt, expected failure " << index << " (" << kdf << "), which the family does not refuse with " @@ -291,7 +291,7 @@ void agree_with_reference(argon2_type type, std::string_view name) { auto const associated_data = index % 3 == 1 ? bytes{} : rnd.bytes(rnd.between(1, 32)); auto const passes = static_cast(rnd.between(1, 3)); auto const lanes = static_cast(rnd.between(1, 4)); - auto const memory_kib = + auto const memory_kibibytes = static_cast(rnd.between(std::size_t{8} * lanes, 256)); std::size_t const tag_size = rnd.between(16, 80); @@ -302,7 +302,7 @@ void agree_with_reference(argon2_type type, std::string_view name) { .secret = secret, .associated_data = associated_data, .passes = passes, - .memory_kib = memory_kib, + .memory_kibibytes = memory_kibibytes, .lanes = lanes, .variant = type, }); @@ -310,7 +310,7 @@ void agree_with_reference(argon2_type type, std::string_view name) { auto const done = hash::argon2(tag, password, salt, { .passes = passes, - .memory_kib = memory_kib, + .memory_kibibytes = memory_kibibytes, .lanes = lanes, .secret = secret, .associated_data = associated_data, @@ -318,7 +318,7 @@ void agree_with_reference(argon2_type type, std::string_view name) { if (!BOOST_TEST_EQ(code, ARGON2_OK) || !BOOST_TEST(done.has_value()) || !BOOST_TEST_EQ(test::to_hex(tag), test::to_hex(expected))) { std::cerr << " " << name << " case " << index << ": t " << passes << ", m " - << memory_kib << ", p " << lanes << ", tag " << tag_size << '\n'; + << memory_kibibytes << ", p " << lanes << ", tag " << tag_size << '\n'; } } } @@ -332,11 +332,11 @@ void agree_argon2id_with_sodium() { auto const password = rnd.bytes(rnd.between(0, 64)); auto const salt = rnd.bytes(hash::argon2id_salt_size); auto const passes = static_cast(rnd.between(1, 3)); - auto const memory_kib = static_cast(rnd.between(8, 256)); + auto const memory_kibibytes = static_cast(rnd.between(8, 256)); std::size_t const tag_size = rnd.between(16, 80); hash::argon2id_parameters const costs{ .passes = passes, - .memory = std::size_t{memory_kib} * 1024, + .memory = std::size_t{memory_kibibytes} * 1024, }; bytes expected(tag_size); @@ -345,8 +345,9 @@ void agree_argon2id_with_sodium() { bool const all_done = hash::argon2id(expected, password, salt, costs).has_value() && hash::argon2id(function_tag, password, salt, costs).has_value() && - hash::argon2(family_tag, password, salt, - {.passes = passes, .memory_kib = memory_kib}) + hash::argon2( + family_tag, password, salt, + {.passes = passes, .memory_kibibytes = memory_kibibytes}) .has_value(); if (!BOOST_TEST(all_done) || !BOOST_TEST_EQ(test::to_hex(function_tag), test::to_hex(expected)) || @@ -365,7 +366,7 @@ void agree_argon2i_with_sodium() { auto const password = rnd.bytes(rnd.between(0, 64)); auto const salt = rnd.bytes(crypto_pwhash_argon2i_SALTBYTES); auto const passes = static_cast(rnd.between(3, 4)); - auto const memory_kib = static_cast(rnd.between(8, 256)); + auto const memory_kibibytes = static_cast(rnd.between(8, 256)); std::size_t const tag_size = rnd.between(16, 80); bytes expected(tag_size); @@ -373,10 +374,10 @@ void agree_argon2i_with_sodium() { auto const* const password_chars = reinterpret_cast(password.data()); int const code = crypto_pwhash_argon2i( expected.data(), expected.size(), password_chars, password.size(), salt.data(), passes, - std::size_t{memory_kib} * 1024, crypto_pwhash_argon2i_ALG_ARGON2I13); + std::size_t{memory_kibibytes} * 1024, crypto_pwhash_argon2i_ALG_ARGON2I13); bytes tag(tag_size); auto const done = hash::argon2( - tag, password, salt, {.passes = passes, .memory_kib = memory_kib}); + tag, password, salt, {.passes = passes, .memory_kibibytes = memory_kibibytes}); if (!BOOST_TEST_EQ(code, 0) || !BOOST_TEST(done.has_value()) || !BOOST_TEST_EQ(test::to_hex(tag), test::to_hex(expected))) { std::cerr << " argon2i against libsodium, case " << index << '\n'; @@ -408,11 +409,11 @@ void check_limits() { // The family: m of at most 4,194,303 KiB on wasm32 (a size_t of 4 GiB less 1 KiB), // unsupported_by_backend past it; natively RFC 9106's whole range. constexpr std::uint32_t family_limit = - hash::detail::argon2_engine::limits.max_memory_kib; + hash::detail::argon2_engine::limits.max_memory_kibibytes; static_assert(family_limit == (sizeof(std::size_t) == 4 ? 4194303U : 0xffffffffU)); if constexpr (sizeof(std::size_t) == 4) { auto const refused = hash::argon2( - output, {}, salt, {.passes = 1, .memory_kib = family_limit + 1}); + output, {}, salt, {.passes = 1, .memory_kibibytes = family_limit + 1}); BOOST_TEST(failed_with(refused, hash::error::unsupported_by_backend)); BOOST_TEST(all_of(output, untouched)); } @@ -420,14 +421,14 @@ void check_limits() { // RFC 9106's shortest tag, 4 bytes, which libsodium does not produce. std::array shortest{}; shortest.fill(untouched); - BOOST_TEST( - (hash::argon2(shortest, {}, salt, {.passes = 1, .memory_kib = 8}) - .has_value())); + BOOST_TEST((hash::argon2(shortest, {}, salt, + {.passes = 1, .memory_kibibytes = 8}) + .has_value())); BOOST_TEST(!all_of(shortest, untouched)); // The family's guards come before the backend: m below 8p. auto const refused = hash::argon2( - output, {}, salt, {.passes = 1, .memory_kib = 31, .lanes = 4}); + output, {}, salt, {.passes = 1, .memory_kibibytes = 31, .lanes = 4}); BOOST_TEST(failed_with(refused, hash::error::invalid_parameters)); BOOST_TEST(all_of(output, untouched)); } diff --git a/test/argon2_rfc9106_test.cpp b/test/argon2_rfc9106_test.cpp index 9388ea6..7d78289 100644 --- a/test/argon2_rfc9106_test.cpp +++ b/test/argon2_rfc9106_test.cpp @@ -40,7 +40,7 @@ void test_section_5_3() { .secret = secret, .associated_data = associated_data, .passes = 3, - .memory_kib = 32, + .memory_kibibytes = 32, .lanes = 4, }); BOOST_TEST_EQ(code, ARGON2_OK); diff --git a/test/argon2_sodium_test.cpp b/test/argon2_sodium_test.cpp index 7254de4..2f902d3 100644 --- a/test/argon2_sodium_test.cpp +++ b/test/argon2_sodium_test.cpp @@ -70,7 +70,7 @@ struct libsodium_case { std::string_view salt; std::size_t tag_size; std::uint32_t passes; - std::uint32_t memory_kib; + std::uint32_t memory_kibibytes; }; // The table's first three cases, each of which its .exp shows succeeding. @@ -83,7 +83,7 @@ constexpr std::array libsodium_cases{ .salt = "5541fbc995d5c197ba290346d2c559de", .tag_size = 155, .passes = 5, - .memory_kib = 7086, // 7256678 / 1024 + .memory_kibibytes = 7086, // 7256678 / 1024 }, libsodium_case{ .password = "e125cee61c8cb7778d9e5ad0a6f5d978ce9f84de213a8556d9ffe202020ab4a6" @@ -92,7 +92,7 @@ constexpr std::array libsodium_cases{ .salt = "f1192dd5dc2368b9cd421338b2243345", .tag_size = 250, .passes = 4, - .memory_kib = 7665, // 7849083 / 1024 + .memory_kibibytes = 7665, // 7849083 / 1024 }, libsodium_case{ .password = "92263cbf6ac376499f68a4289d3bb59e5a22335eba63a32e6410249155b956b6" @@ -104,7 +104,7 @@ constexpr std::array libsodium_cases{ .salt = "3b840e20e9555e9fb031c4ba1f1747ce", .tag_size = 249, .passes = 3, - .memory_kib = 7807, // 7994791 / 1024 + .memory_kibibytes = 7807, // 7994791 / 1024 }, }; @@ -116,7 +116,10 @@ void test_libsodium_table() { auto const& c = libsodium_cases[i]; auto const password = test::from_hex(c.password); auto const salt = test::from_hex(c.salt); - hash::argon2_parameters const parameters{.passes = c.passes, .memory_kib = c.memory_kib}; + hash::argon2_parameters const parameters{ + .passes = c.passes, + .memory_kibibytes = c.memory_kibibytes, + }; std::vector named(c.tag_size); std::vector by_default(c.tag_size); bool const computed = @@ -147,7 +150,7 @@ void test_against_argon2_ctx(argon2_type variant, std::uint32_t fewest_passes) { std::array salt{}; std::ranges::generate(salt, [&] { return static_cast(between(0, 255)); }); std::uint32_t const passes = between(fewest_passes, fewest_passes + 2); - std::uint32_t const memory_kib = between(8, 256); + std::uint32_t const memory_kibibytes = between(8, 256); std::size_t const tag_size = between(16, 80); std::vector expected(tag_size); @@ -157,7 +160,7 @@ void test_against_argon2_ctx(argon2_type variant, std::uint32_t fewest_passes) { .secret = {}, .associated_data = {}, .passes = passes, - .memory_kib = memory_kib, + .memory_kibibytes = memory_kibibytes, .lanes = 1, .variant = variant, }); @@ -165,10 +168,11 @@ void test_against_argon2_ctx(argon2_type variant, std::uint32_t fewest_passes) { std::vector tag(tag_size); auto const done = hash::argon2( - tag, password, salt, {.passes = passes, .memory_kib = memory_kib, .lanes = 1}); + tag, password, salt, + {.passes = passes, .memory_kibibytes = memory_kibibytes, .lanes = 1}); if (!BOOST_TEST(done.has_value()) || !BOOST_TEST_EQ(test::to_hex(tag), test::to_hex(expected))) { - std::cerr << " case " << i << ": passes " << passes << ", memory " << memory_kib + std::cerr << " case " << i << ": passes " << passes << ", memory " << memory_kibibytes << " KiB, password " << password.size() << " bytes, tag " << tag_size << '\n'; } } @@ -182,14 +186,14 @@ const std::array sample_salt{ // argon2 on libsodium is the function argon2id, whose memory counts bytes. void test_argon2id_function() { - for (std::uint32_t const memory_kib : {8U, 64U, 1024U}) { + for (std::uint32_t const memory_kibibytes : {8U, 64U, 1024U}) { std::array family{}; std::array function{}; BOOST_TEST(hash::argon2(family, sample_password, sample_salt, - {.passes = 2, .memory_kib = memory_kib}) + {.passes = 2, .memory_kibibytes = memory_kibibytes}) .has_value()); BOOST_TEST(hash::argon2id(function, sample_password, sample_salt, - {.passes = 2, .memory = std::size_t{memory_kib} * 1024}) + {.passes = 2, .memory = std::size_t{memory_kibibytes} * 1024}) .has_value()); BOOST_TEST_EQ(test::to_hex(family), test::to_hex(function)); } @@ -214,24 +218,29 @@ void expect_refused(std::size_t output_size, std::span salt_ template void test_unsupported(std::uint32_t fewest_passes) { constexpr auto unsupported = hash::error::unsupported_by_backend; - hash::argon2_parameters const cheapest{.passes = fewest_passes, .memory_kib = 32}; + hash::argon2_parameters const cheapest{.passes = fewest_passes, .memory_kibibytes = 32}; std::array secret{}; secret.fill(0x03); std::array associated_data{}; associated_data.fill(0x04); expect_refused(32, sample_salt, - {.passes = fewest_passes, .memory_kib = 32, .lanes = 4}, unsupported, - "four lanes"); + {.passes = fewest_passes, .memory_kibibytes = 32, .lanes = 4}, + unsupported, "four lanes"); expect_refused(32, sample_salt, - {.passes = fewest_passes, .memory_kib = 32, .lanes = 2}, unsupported, - "two lanes"); - expect_refused( - 32, sample_salt, {.passes = fewest_passes, .memory_kib = 32, .lanes = 1, .secret = secret}, - unsupported, "a secret"); + {.passes = fewest_passes, .memory_kibibytes = 32, .lanes = 2}, + unsupported, "two lanes"); expect_refused( 32, sample_salt, - {.passes = fewest_passes, .memory_kib = 32, .lanes = 1, .associated_data = associated_data}, - unsupported, "associated data"); + {.passes = fewest_passes, .memory_kibibytes = 32, .lanes = 1, .secret = secret}, + unsupported, "a secret"); + expect_refused(32, sample_salt, + { + .passes = fewest_passes, + .memory_kibibytes = 32, + .lanes = 1, + .associated_data = associated_data, + }, + unsupported, "associated data"); // RFC 9106's shortest tag, 4 bytes, and up to libsodium's 16. for (std::size_t const size : {4U, 8U, 15U}) { expect_refused(size, sample_salt, cheapest, unsupported, "a short tag"); @@ -245,23 +254,25 @@ void test_unsupported(std::uint32_t fewest_passes) { // On wasm32 libsodium's memory stops at 2 GiB, 2,097,152 KiB; natively at RFC 9106's own // bound, 2^32 - 1 KiB, which no uint32_t passes. if constexpr (std::numeric_limits::max() == 0xffffffffU) { - expect_refused(32, sample_salt, {.passes = fewest_passes, .memory_kib = 2097153}, - unsupported, "past 2 GiB on wasm32"); + expect_refused(32, sample_salt, + {.passes = fewest_passes, .memory_kibibytes = 2097153}, unsupported, + "past 2 GiB on wasm32"); } // RFC 9106's guards come first: no lane is invalid_parameters, a salt of 7 bytes // invalid_salt_size, a tag of 3 bytes invalid_output_size. expect_refused(32, sample_salt, - {.passes = fewest_passes, .memory_kib = 32, .lanes = 0}, + {.passes = fewest_passes, .memory_kibibytes = 32, .lanes = 0}, hash::error::invalid_parameters, "no lane"); - expect_refused(32, sample_salt, {.passes = 0, .memory_kib = 32, .lanes = 4}, + expect_refused(32, sample_salt, {.passes = 0, .memory_kibibytes = 32, .lanes = 4}, hash::error::invalid_parameters, "no pass, four lanes"); expect_refused(32, sample_salt, - {.passes = fewest_passes, .memory_kib = 31, .lanes = 4}, + {.passes = fewest_passes, .memory_kibibytes = 31, .lanes = 4}, hash::error::invalid_parameters, "under 8 KiB per lane"); expect_refused(32, std::span(sample_salt.data(), 7), - {.passes = fewest_passes, .memory_kib = 32, .lanes = 4}, + {.passes = fewest_passes, .memory_kibibytes = 32, .lanes = 4}, hash::error::invalid_salt_size, "a salt of 7 bytes"); - expect_refused(3, sample_salt, {.passes = fewest_passes, .memory_kib = 32, .lanes = 4}, + expect_refused(3, sample_salt, + {.passes = fewest_passes, .memory_kibibytes = 32, .lanes = 4}, hash::error::invalid_output_size, "a tag of 3 bytes"); } @@ -269,17 +280,17 @@ void test_unsupported(std::uint32_t fewest_passes) { // are unsupported_by_backend, and 3 runs. void test_argon2i_passes() { for (std::uint32_t const passes : {1U, 2U}) { - expect_refused(32, sample_salt, {.passes = passes, .memory_kib = 32}, + expect_refused(32, sample_salt, {.passes = passes, .memory_kibibytes = 32}, hash::error::unsupported_by_backend, "Argon2i, 1 or 2 passes"); } std::array tag{}; BOOST_TEST(hash::argon2(tag, sample_password, sample_salt, - {.passes = 3, .memory_kib = 8}) + {.passes = 3, .memory_kibibytes = 8}) .has_value()); // Argon2id runs from 1 pass, as RFC 9106 has it. BOOST_TEST(hash::argon2(tag, sample_password, sample_salt, - {.passes = 1, .memory_kib = 8}) + {.passes = 1, .memory_kibibytes = 8}) .has_value()); } diff --git a/test/argon2id_interactive_test.cpp b/test/argon2id_interactive_test.cpp index dd744e3..25e8879 100644 --- a/test/argon2id_interactive_test.cpp +++ b/test/argon2id_interactive_test.cpp @@ -46,16 +46,16 @@ void test_interactive() { std::array expected{}; int const code = webcpp::test::argon2_reference( - expected, - { - .password = password, - .salt = salt, - .secret = {}, - .associated_data = {}, - .passes = static_cast(hash::argon2id_interactive.passes), - .memory_kib = static_cast(hash::argon2id_interactive.memory / 1024), - .lanes = 1, - }); + expected, { + .password = password, + .salt = salt, + .secret = {}, + .associated_data = {}, + .passes = static_cast(hash::argon2id_interactive.passes), + .memory_kibibytes = + static_cast(hash::argon2id_interactive.memory / 1024), + .lanes = 1, + }); BOOST_TEST_EQ(code, ARGON2_OK); BOOST_TEST_EQ(to_hex(tag), to_hex(expected)); } diff --git a/test/argon2id_test.cpp b/test/argon2id_test.cpp index 04ac07d..0802213 100644 --- a/test/argon2id_test.cpp +++ b/test/argon2id_test.cpp @@ -192,31 +192,33 @@ void test_against_argon2_ctx() { std::array salt{}; std::ranges::generate(salt, [&] { return static_cast(between(0, 255)); }); std::uint32_t const passes = between(1, 3); - std::uint32_t const memory_kib = between(8, 256); + std::uint32_t const memory_kibibytes = between(8, 256); std::size_t const tag_size = between(16, 80); std::vector expected(tag_size); - int const code = webcpp::test::argon2_reference(expected, { - .password = password, - .salt = salt, - .secret = {}, - .associated_data = {}, - .passes = passes, - .memory_kib = memory_kib, - .lanes = 1, - }); + int const code = + webcpp::test::argon2_reference(expected, { + .password = password, + .salt = salt, + .secret = {}, + .associated_data = {}, + .passes = passes, + .memory_kibibytes = memory_kibibytes, + .lanes = 1, + }); BOOST_TEST_EQ(code, ARGON2_OK); std::vector tag(tag_size); - auto const done = hash::argon2id( - tag, password, salt, {.passes = passes, .memory = std::size_t{memory_kib} * 1024}); + auto const done = + hash::argon2id(tag, password, salt, + {.passes = passes, .memory = std::size_t{memory_kibibytes} * 1024}); BOOST_TEST(done.has_value()); BOOST_TEST_EQ(to_hex(tag), to_hex(expected)); } } -const std::array password{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'}; -const std::array salt{ +const std::array test_password{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'}; +const std::array test_salt{ 's', 'o', 'm', 'e', 's', 'a', 'l', 't', // "somesalt" twice 's', 'o', 'm', 'e', 's', 'a', 'l', 't', }; @@ -234,30 +236,30 @@ void test_output_guard() { std::array buffer{}; buffer.fill(untouched); auto const longest = std::uint64_t{0xffffffff}; - expect_refused(std::span(buffer.data(), 15), password, salt, cheapest, + expect_refused(std::span(buffer.data(), 15), test_password, test_salt, cheapest, hash::error::invalid_output_size); - expect_refused(std::span(buffer.data(), 0), password, salt, cheapest, + expect_refused(std::span(buffer.data(), 0), test_password, test_salt, cheapest, hash::error::invalid_output_size); // Natively a span of 2^32 bytes over 16, which the guard refuses before anything reads or // writes it; on wasm32 no span is that long. if constexpr (std::numeric_limits::max() > longest) { expect_refused( - std::span(buffer.data(), static_cast(longest + 1)), password, - salt, cheapest, hash::error::invalid_output_size); + std::span(buffer.data(), static_cast(longest + 1)), + test_password, test_salt, cheapest, hash::error::invalid_output_size); } BOOST_TEST(all_of(buffer, untouched)); // 16 bytes, the shortest, with an empty password and the cheapest costs: a default span, // whose data() is null, against argon2_ctx with the same empty password. std::span const nothing{}; BOOST_TEST(nothing.data() == nullptr); - BOOST_TEST(hash::argon2id(buffer, nothing, salt, cheapest).has_value()); + BOOST_TEST(hash::argon2id(buffer, nothing, test_salt, cheapest).has_value()); std::array expected{}; BOOST_TEST_EQ(webcpp::test::argon2_reference(expected, {.password = nothing, - .salt = salt, + .salt = test_salt, .secret = {}, .associated_data = {}, .passes = 1, - .memory_kib = 8, + .memory_kibibytes = 8, .lanes = 1}), ARGON2_OK); BOOST_TEST_EQ(to_hex(buffer), to_hex(expected)); @@ -268,11 +270,11 @@ void test_salt_guard() { buffer.fill(untouched); std::array long_salt{}; for (std::size_t const size : {0U, 8U, 15U, 17U}) { - expect_refused(buffer, password, std::span(long_salt.data(), size), + expect_refused(buffer, test_password, std::span(long_salt.data(), size), cheapest, hash::error::invalid_salt_size); } // The output's guard comes first. - expect_refused(std::span(buffer.data(), 15), password, + expect_refused(std::span(buffer.data(), 15), test_password, std::span(long_salt.data(), 15), cheapest, hash::error::invalid_output_size); BOOST_TEST(all_of(buffer, untouched)); @@ -284,11 +286,11 @@ void test_password_guard() { auto const longest = std::uint64_t{0xffffffff}; // Natively a password of 2^32 bytes over 8, refused before anything reads it. if constexpr (std::numeric_limits::max() > longest) { - std::span const past(password.data(), + std::span const past(test_password.data(), static_cast(longest + 1)); - expect_refused(buffer, past, salt, cheapest, hash::error::input_too_long); + expect_refused(buffer, past, test_salt, cheapest, hash::error::input_too_long); // The salt's guard comes first. - expect_refused(buffer, past, std::span(salt.data(), 15), cheapest, + expect_refused(buffer, past, std::span(test_salt.data(), 15), cheapest, hash::error::invalid_salt_size); } BOOST_TEST(all_of(buffer, untouched)); @@ -309,7 +311,8 @@ void test_parameters_guard() { {.passes = 1, .memory = static_cast(most_memory + 1024)}, }; for (auto const& parameters : refused) { - expect_refused(buffer, password, salt, parameters, hash::error::invalid_parameters); + expect_refused(buffer, test_password, test_salt, parameters, + hash::error::invalid_parameters); } BOOST_TEST(all_of(buffer, untouched)); // The most passes and libsodium's most memory pass every guard and reach the engine, which @@ -319,13 +322,13 @@ void test_parameters_guard() { .memory = static_cast(most_memory), }; int const before = test_backends::recorded_calls; - BOOST_TEST( - hash::argon2id(buffer, password, salt, largest).has_value()); + BOOST_TEST(hash::argon2id(buffer, test_password, test_salt, largest) + .has_value()); BOOST_TEST_EQ(test_backends::recorded_calls, before + 1); BOOST_TEST_EQ(test_backends::recorded_passes, largest.passes); BOOST_TEST_EQ(test_backends::recorded_memory, largest.memory); auto const past = hash::argon2id( - buffer, password, salt, + buffer, test_password, test_salt, {.passes = 1, .memory = static_cast(most_memory + 1024)}); BOOST_TEST(past.has_error() && past.error() == hash::error::invalid_parameters); BOOST_TEST_EQ(test_backends::recorded_calls, before + 1); @@ -334,8 +337,8 @@ void test_parameters_guard() { // 8 with no passes is input_too_long, never read. if constexpr (std::numeric_limits::max() > 0xffffffffU) { std::span const past_password( - password.data(), static_cast(std::uint64_t{0xffffffff} + 1)); - expect_refused(buffer, past_password, salt, {.passes = 0, .memory = 0}, + test_password.data(), static_cast(std::uint64_t{0xffffffff} + 1)); + expect_refused(buffer, past_password, test_salt, {.passes = 0, .memory = 0}, hash::error::input_too_long); } } @@ -343,13 +346,14 @@ void test_parameters_guard() { void test_backend_failure() { std::array buffer{}; buffer.fill(untouched); - auto failed = hash::argon2id(buffer, password, salt, cheapest); + auto failed = + hash::argon2id(buffer, test_password, test_salt, cheapest); BOOST_TEST(failed.has_error() && failed.error() == hash::error::backend_failure); BOOST_TEST(all_of(buffer, 0)); // A guard's refusal reaches no backend. buffer.fill(untouched); - failed = hash::argon2id(buffer, password, salt, + failed = hash::argon2id(buffer, test_password, test_salt, {.passes = 0, .memory = 8192}); BOOST_TEST(failed.has_error() && failed.error() == hash::error::invalid_parameters); BOOST_TEST(all_of(buffer, untouched)); diff --git a/test/async_cobalt_test.cpp b/test/async_cobalt_test.cpp index 015879c..be0d771 100644 --- a/test/async_cobalt_test.cpp +++ b/test/async_cobalt_test.cpp @@ -8,8 +8,9 @@ // promises on an io_context, on every target; a promise is never moved, since Boost.Cobalt aborts // on moving a pending coroutine without exceptions (Boost.Cobalt issue 287, as // records). The cheap functions on their default backend give the -// synchronous function's result; a guard's refusal is read through cobalt::as_tuple, and with -// exceptions a plain co_await throws boost::system::system_error with hash's code (ruling R71). +// synchronous function's result, async_hkdf over pieces too; a guard's refusal is read through +// cobalt::as_tuple, and with exceptions a plain co_await throws boost::system::system_error with +// hash's code (ruling R71). // Natively a heavy function, async_pbkdf2 on a thread pool, resumes the task on its own thread; on // Emscripten async_digest on backends::webcrypto completes through Cobalt's executor, an // io_context's. @@ -93,6 +94,13 @@ cobalt::promise cheap() { co_await hash::async_hkdf(executor, okm, key, abc, abc, cobalt::use_op); BOOST_TEST(okm == okm_expected); + // async_hkdf over pieces: "abc" as {"a", "bc"} gives the single-buffer bytes. + std::array okm_pieces{}; + co_await hash::async_hkdf(executor, okm_pieces, key, + {abc.first(1), abc.subspan(1)}, + {abc.first(2), abc.subspan(2)}, cobalt::use_op); + BOOST_TEST(okm_pieces == okm_expected); + std::span const none{}; auto [refused] = co_await cobalt::as_tuple( hash::async_digest(executor, none, abc, cobalt::use_op)); diff --git a/test/async_heavy_botan_test.cpp b/test/async_heavy_botan_test.cpp index 1505d84..6e55fce 100644 --- a/test/async_heavy_botan_test.cpp +++ b/test/async_heavy_botan_test.cpp @@ -125,32 +125,38 @@ completion complete_on_pool(Start start) { return c; } -// "password", as bytes. -constexpr std::array password{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'}; -constexpr std::array salt{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; +// "password", as bytes, and a salt: named test_*, which no parameter of the library hides (MSVC +// C4459 at /WX). +constexpr std::array test_password{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'}; +constexpr std::array test_salt{ + 1, 2, 3, 4, 5, 6, 7, 8, // bcrypt's 16 bytes + 9, 10, 11, 12, 13, 14, 15, 16, +}; void check_bcrypt(asio::io_context& context, asio::thread_pool& pool) { auto work = pool.get_executor(); hash::bcrypt_parameters const parameters{.cost = 5}; std::array expected{}; - BOOST_TEST((hash::bcrypt(expected, password, salt, parameters).has_value())); + BOOST_TEST((hash::bcrypt(expected, test_password, test_salt, parameters).has_value())); std::string_view const stored(expected.data(), expected.size()); std::array output{}; auto seen = complete_on_caller(context, [&](auto handler) { - hash::async_bcrypt(work, output, password, salt, parameters, std::move(handler)); + hash::async_bcrypt(work, output, test_password, test_salt, parameters, + std::move(handler)); }); BOOST_TEST(!seen.code); BOOST_TEST(output == expected); output.fill('\0'); seen = complete_on_pool([&](auto handler) { - hash::async_bcrypt(work, output, password, salt, parameters, std::move(handler)); + hash::async_bcrypt(work, output, test_password, test_salt, parameters, + std::move(handler)); }); BOOST_TEST(!seen.code); BOOST_TEST(output == expected); seen = complete_on_caller(context, [&](auto handler) { - hash::async_bcrypt_verify(work, password, stored, std::move(handler)); + hash::async_bcrypt_verify(work, test_password, stored, std::move(handler)); }); BOOST_TEST(!seen.code); BOOST_TEST(seen.same); @@ -164,13 +170,13 @@ void check_bcrypt(asio::io_context& context, asio::thread_pool& pool) { // string not of bcrypt's form, the bool false. output.fill('U'); seen = complete_on_caller(context, [&](auto handler) { - hash::async_bcrypt(work, output, password, std::span(salt).first(15), parameters, - std::move(handler)); + hash::async_bcrypt(work, output, test_password, std::span(test_salt).first(15), + parameters, std::move(handler)); }); BOOST_TEST(seen.code == hash::error::invalid_salt_size); BOOST_TEST(std::ranges::all_of(output, [](char c) { return c == 'U'; })); seen = complete_on_caller(context, [&](auto handler) { - hash::async_bcrypt_verify(work, password, stored.substr(1), std::move(handler)); + hash::async_bcrypt_verify(work, test_password, stored.substr(1), std::move(handler)); }); BOOST_TEST(seen.code == hash::error::invalid_parameters); BOOST_TEST(!seen.same); @@ -179,74 +185,81 @@ void check_bcrypt(asio::io_context& context, asio::thread_pool& pool) { void check_bcrypt_pbkdf(asio::io_context& context, asio::thread_pool& pool) { auto work = pool.get_executor(); std::array expected{}; - BOOST_TEST((hash::bcrypt_pbkdf(expected, password, salt, 4).has_value())); + BOOST_TEST((hash::bcrypt_pbkdf(expected, test_password, test_salt, 4).has_value())); std::array output{}; auto seen = complete_on_caller(context, [&](auto handler) { - hash::async_bcrypt_pbkdf(work, output, password, salt, 4, std::move(handler)); + hash::async_bcrypt_pbkdf(work, output, test_password, test_salt, 4, + std::move(handler)); }); BOOST_TEST(!seen.code); BOOST_TEST(output == expected); output.fill(0); seen = complete_on_pool([&](auto handler) { - hash::async_bcrypt_pbkdf(work, output, password, salt, 4, std::move(handler)); + hash::async_bcrypt_pbkdf(work, output, test_password, test_salt, 4, + std::move(handler)); }); BOOST_TEST(!seen.code); BOOST_TEST(output == expected); seen = complete_on_caller(context, [&](auto handler) { - hash::async_bcrypt_pbkdf(work, output, password, salt, 0, std::move(handler)); + hash::async_bcrypt_pbkdf(work, output, test_password, test_salt, 0, + std::move(handler)); }); BOOST_TEST(seen.code == hash::error::invalid_iterations); } void check_families(asio::io_context& context, asio::thread_pool& pool) { auto work = pool.get_executor(); - hash::argon2_parameters const family{.passes = 2, .memory_kib = 64, .lanes = 2}; + hash::argon2_parameters const family{.passes = 2, .memory_kibibytes = 64, .lanes = 2}; std::array argon2_expected{}; - BOOST_TEST((hash::argon2(argon2_expected, password, salt, family) - .has_value())); + BOOST_TEST(( + hash::argon2(argon2_expected, test_password, test_salt, family) + .has_value())); std::array argon2_output{}; auto seen = complete_on_caller(context, [&](auto handler) { - hash::async_argon2(work, argon2_output, password, salt, family, - std::move(handler)); + hash::async_argon2(work, argon2_output, test_password, + test_salt, family, std::move(handler)); }); BOOST_TEST(!seen.code); BOOST_TEST(argon2_output == argon2_expected); argon2_output.fill(0); seen = complete_on_pool([&](auto handler) { - hash::async_argon2(work, argon2_output, password, salt, family, - std::move(handler)); + hash::async_argon2(work, argon2_output, test_password, + test_salt, family, std::move(handler)); }); BOOST_TEST(argon2_output == argon2_expected); - hash::scrypt_parameters const costs{.n = 1024, .r = 8, .p = 1}; + hash::scrypt_parameters const costs{.cost = 1024, .block_size = 8, .parallelism = 1}; std::array scrypt_expected{}; - BOOST_TEST(hash::scrypt(scrypt_expected, password, salt, costs).has_value()); + BOOST_TEST(hash::scrypt(scrypt_expected, test_password, test_salt, costs).has_value()); std::array scrypt_output{}; seen = complete_on_caller(context, [&](auto handler) { - hash::async_scrypt(work, scrypt_output, password, salt, costs, std::move(handler)); + hash::async_scrypt(work, scrypt_output, test_password, test_salt, costs, + std::move(handler)); }); BOOST_TEST(!seen.code); BOOST_TEST(scrypt_output == scrypt_expected); scrypt_output.fill(0); seen = complete_on_pool([&](auto handler) { - hash::async_scrypt(work, scrypt_output, password, salt, costs, std::move(handler)); + hash::async_scrypt(work, scrypt_output, test_password, test_salt, costs, + std::move(handler)); }); BOOST_TEST(scrypt_output == scrypt_expected); std::array pbkdf2_expected{}; - BOOST_TEST((hash::pbkdf2(pbkdf2_expected, password, salt, 1000) - .has_value())); + BOOST_TEST( + (hash::pbkdf2(pbkdf2_expected, test_password, test_salt, 1000) + .has_value())); std::array pbkdf2_output{}; seen = complete_on_caller(context, [&](auto handler) { - hash::async_pbkdf2(work, pbkdf2_output, password, salt, 1000, - std::move(handler)); + hash::async_pbkdf2(work, pbkdf2_output, test_password, + test_salt, 1000, std::move(handler)); }); BOOST_TEST(!seen.code); BOOST_TEST(pbkdf2_output == pbkdf2_expected); pbkdf2_output.fill(0); seen = complete_on_pool([&](auto handler) { - hash::async_pbkdf2(work, pbkdf2_output, password, salt, 1000, - std::move(handler)); + hash::async_pbkdf2(work, pbkdf2_output, test_password, + test_salt, 1000, std::move(handler)); }); BOOST_TEST(pbkdf2_output == pbkdf2_expected); } @@ -287,21 +300,21 @@ void check_cancelled_before(asio::io_context& context) { std::array output{}; output.fill('U'); cancelled([&](auto handler) { - hash::async_bcrypt(busy.get_executor(), output, password, salt, {.cost = 4}, - std::move(handler)); + hash::async_bcrypt(busy.get_executor(), output, test_password, test_salt, + {.cost = 4}, std::move(handler)); }); BOOST_TEST(std::ranges::all_of(output, [](char c) { return c == 'U'; })); std::array derived{}; derived.fill(0x5a); cancelled([&](auto handler) { - hash::async_bcrypt_pbkdf(busy.get_executor(), derived, password, salt, 2, + hash::async_bcrypt_pbkdf(busy.get_executor(), derived, test_password, test_salt, 2, std::move(handler)); }); BOOST_TEST(std::ranges::all_of(derived, [](std::uint8_t b) { return b == 0x5a; })); std::array stored{}; - BOOST_TEST((hash::bcrypt(stored, password, salt, {.cost = 4}).has_value())); + BOOST_TEST((hash::bcrypt(stored, test_password, test_salt, {.cost = 4}).has_value())); auto const seen = cancelled([&](auto handler) { - hash::async_bcrypt_verify(busy.get_executor(), password, + hash::async_bcrypt_verify(busy.get_executor(), test_password, std::string_view(stored.data(), stored.size()), std::move(handler)); }); diff --git a/test/async_heavy_test.cpp b/test/async_heavy_test.cpp index 57caa0b..79413b5 100644 --- a/test/async_heavy_test.cpp +++ b/test/async_heavy_test.cpp @@ -251,8 +251,9 @@ struct argon2_engine { std::span salt, argon2_parameters const& parameters) noexcept { record_thread(); constexpr std::size_t kib = 1024; - return argon2id_engine::derive(output, password, salt, parameters.passes, - std::size_t{parameters.memory_kib} * kib); + return argon2id_engine::derive( + output, password, salt, parameters.passes, + std::size_t{parameters.memory_kibibytes} * kib); } }; @@ -316,7 +317,7 @@ void check_on_pool(asio::io_context& context, asio::thread_pool& pool) { BOOST_TEST(!code); BOOST_TEST(output == expected); - hash::argon2_parameters const family{.passes = 2, .memory_kib = 64}; + hash::argon2_parameters const family{.passes = 2, .memory_kibibytes = 64}; std::array family_expected{}; BOOST_TEST( (hash::argon2(family_expected, password, salt, family) @@ -330,7 +331,7 @@ void check_on_pool(asio::io_context& context, asio::thread_pool& pool) { BOOST_TEST(!code); BOOST_TEST(family_output == expected); - hash::scrypt_parameters const costs{.n = 1024, .r = 8, .p = 1}; + hash::scrypt_parameters const costs{.cost = 1024, .block_size = 8, .parallelism = 1}; std::array scrypt_expected{}; BOOST_TEST(hash::scrypt(scrypt_expected, password, salt, costs).has_value()); std::array scrypt_output{}; @@ -393,7 +394,7 @@ void check_family_defaults(asio::io_context& context, asio::thread_pool& pool, beyond.passes = 2; } else { beyond.lanes = 2; - beyond.memory_kib = 64; + beyond.memory_kibibytes = 64; } std::array untouched{0x5a}; code = complete_on_caller(context, [&](auto handler) { @@ -423,10 +424,12 @@ void check_defaults(asio::io_context& context, asio::thread_pool& pool) { BOOST_TEST(!code); BOOST_TEST(output == expected); - check_family_defaults(context, pool, {.passes = 1, .memory_kib = 32}); - check_family_defaults(context, pool, {.passes = 3, .memory_kib = 32}); + check_family_defaults(context, pool, + {.passes = 1, .memory_kibibytes = 32}); + check_family_defaults(context, pool, + {.passes = 3, .memory_kibibytes = 32}); - hash::scrypt_parameters const costs{.n = 16, .r = 1, .p = 1}; + hash::scrypt_parameters const costs{.cost = 16, .block_size = 1, .parallelism = 1}; std::array scrypt_expected{}; BOOST_TEST(hash::scrypt(scrypt_expected, bytes_of(""), bytes_of(""), costs).has_value()); std::array scrypt_output{}; @@ -472,14 +475,15 @@ void check_guards(asio::io_context& context, asio::thread_pool& pool) { std::array untouched{0x5a}; code = complete_on_caller(context, [&](auto handler) { hash::async_argon2( - work, untouched, {}, salt, hash::argon2_parameters{.passes = 0, .memory_kib = 64}, + work, untouched, {}, salt, hash::argon2_parameters{.passes = 0, .memory_kibibytes = 64}, std::move(handler)); }); BOOST_TEST(code == hash::error::invalid_parameters); BOOST_TEST_EQ(untouched[0], 0x5a); code = complete_on_caller(context, [&](auto handler) { - hash::async_scrypt(work, untouched, {}, {}, hash::scrypt_parameters{.n = 3, .r = 1, .p = 1}, + hash::async_scrypt(work, untouched, {}, {}, + hash::scrypt_parameters{.cost = 3, .block_size = 1, .parallelism = 1}, std::move(handler)); }); BOOST_TEST(code == hash::error::invalid_parameters); @@ -1058,7 +1062,7 @@ void check_awaitable(asio::io_context& context, asio::thread_pool& pool) { std::array output{}; std::array scrypt_output{}; std::array scrypt_expected{}; - hash::scrypt_parameters const costs{.n = 16, .r = 1, .p = 1}; + hash::scrypt_parameters const costs{.cost = 16, .block_size = 1, .parallelism = 1}; BOOST_TEST(hash::scrypt(scrypt_expected, password, salt, costs).has_value()); bool done = false; asio::co_spawn( @@ -1077,9 +1081,10 @@ void check_awaitable(asio::io_context& context, asio::thread_pool& pool) { asio::use_awaitable); bool thrown = false; try { - co_await hash::async_scrypt(pool.get_executor(), scrypt_output, password, salt, - hash::scrypt_parameters{.n = 3, .r = 1, .p = 1}, - asio::use_awaitable); + co_await hash::async_scrypt( + pool.get_executor(), scrypt_output, password, salt, + hash::scrypt_parameters{.cost = 3, .block_size = 1, .parallelism = 1}, + asio::use_awaitable); } catch (boost::system::system_error const& failure) { thrown = failure.code() == hash::error::invalid_parameters; } diff --git a/test/async_post_test.cpp b/test/async_post_test.cpp index d879cab..8ce1ce8 100644 --- a/test/async_post_test.cpp +++ b/test/async_post_test.cpp @@ -4,20 +4,28 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// The cheap functions of the asynchronous family, async_digest, async_hmac and async_hkdf, on a -// synchronous backend (spec 11.2): on their default, default_backend's (ruling R76), and on -// backends::hash2 named, as a program on Emscripten names it to keep WebCrypto out (ruling R77, -// C-m2). Each completes through a post on the handler's associated executor, never inside the -// initiating call: a callback records whether the call has returned. The result equals the -// synchronous function's; a guard's refusal (an output of 0 bytes) completes with -// invalid_output_size through the executor; use_future completes; co_await in Asio +// The cheap functions of the asynchronous family, async_digest, async_hmac, async_hkdf_extract, +// async_hkdf_expand and async_hkdf, each HKDF function also over byte pieces, on a synchronous +// backend (spec 11.2): on their default, default_backend's (ruling R76), and on backends::hash2 +// named, as a program on Emscripten names it to keep WebCrypto out (ruling R77, C-m2); the HKDF +// steps and the pieces forms also on backends::sodium. Each completes through a post on the +// handler's associated executor, never inside the initiating call: a callback records whether the +// call has returned. The result equals the synchronous function's; a guard's refusal (an output of +// 0 bytes, a pseudorandom key output or input of another size than the digest's) completes with +// its error through the executor, the output untouched; use_future completes; co_await in Asio // (use_awaitable) gives the result and, through as_tuple, a refusal; and a counting allocator -// associated with the handler holds the operation's storage. Without exceptions an error is -// read by a callback alone: use_future's error path makes an exception (ruling R71). The -// asynchronous default equals the synchronous one for every tag the family serves. +// associated with the handler holds the operation's storage. The pieces forms read their pieces in +// the initiating call (ruling R4): a braced list of pieces whose bytes are overwritten after the +// call gives the HKDF of the original bytes, with a callback, with asio::deferred launched after +// the list's full-expression has ended, and with a use_awaitable awaitable awaited after it. +// Without exceptions an error is read by a callback alone: use_future's error path makes an +// exception (ruling R71). The asynchronous default equals the synchronous one for every tag the +// family serves. #include #include +#include +#include #include #include #include @@ -29,6 +37,7 @@ #include #include #include +#include #include #include #include @@ -44,6 +53,7 @@ #include "support/hex.hpp" +#include #include #include #include @@ -54,6 +64,7 @@ #include #include #include +#include namespace asio = webcpp::asio; namespace hash = webcpp::hash; @@ -276,6 +287,243 @@ void check_hkdf(asio::io_context& context) { BOOST_TEST(code == hash::error::invalid_output_size); } +// RFC 5869's A.1: its input keying material, salt and application info, and its pseudorandom key +// and output keying material. +struct rfc5869_a1 { + std::vector input_key_material = + from_hex("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"); + std::vector salt = from_hex("000102030405060708090a0b0c"); + std::vector application_info = from_hex("f0f1f2f3f4f5f6f7f8f9"); + std::string pseudorandom_key = + "077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5"; + std::string output_key_material = + "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865"; +}; + +// One form of an HKDF function: `start(output, token)` initiates it into `output` and returns what +// the token gives. With a callback it completes through the executor after the call, with +// use_future and with a counting allocator too, each output equal to `expected`. +template +void check_form(asio::io_context& context, std::array const& expected, + Start start) { + std::array output{}; + auto const code = complete_by_callback( + context, [&](auto token) { start(std::span(output), std::move(token)); }); + BOOST_TEST(!code); + BOOST_TEST(output == expected); + + std::array by_future{}; + check_future(context, + [&](auto token) { return start(std::span(by_future), token); }); + BOOST_TEST(by_future == expected); + + std::array counted{}; + check_allocator(context, + [&](auto token) { start(std::span(counted), std::move(token)); }); + BOOST_TEST(counted == expected); +} + +// A guard's refusal of one form: `start(output, token)` on an output of `Size` bytes completes with +// `expected` through the executor, after the call, the output untouched. +template +void check_refusal(asio::io_context& context, boost::system::error_code expected, Start start) { + std::array output{}; + output.fill(0xa5); + auto const before = output; + auto const code = complete_by_callback( + context, [&](auto token) { start(std::span(output), std::move(token)); }); + BOOST_TEST(code == expected); + BOOST_TEST(output == before); +} + +// async_hkdf_extract and async_hkdf_expand, each single-buffer and over pieces, and async_hkdf over +// pieces, on Backend (none: the default): RFC 5869's A.1, the pieces a split of its inputs with an +// empty piece among them, against the synchronous functions; each with use_awaitable; and each +// refusal of RFC 5869's sizes. +template +void check_hkdf_steps(asio::io_context& context) { + auto executor = context.get_executor(); + rfc5869_a1 const a1; + std::span const salt(a1.salt); + std::span const ikm(a1.input_key_material); + std::span const info(a1.application_info); + std::array, 3> const ikm_pieces{ + ikm.first(5), + std::span{}, + ikm.subspan(5), + }; + std::array, 2> const info_pieces{info.first(3), info.subspan(3)}; + + std::array prk_expected{}; + auto const extracted = hash::hkdf_extract(salt, ikm); + BOOST_TEST(extracted.has_value()); + if (extracted) { + std::ranges::copy(*extracted, prk_expected.begin()); + } + BOOST_TEST_EQ(to_hex(prk_expected), a1.pseudorandom_key); + std::array okm_expected{}; + BOOST_TEST( + (hash::hkdf_expand(okm_expected, prk_expected, info)) + .has_value()); + BOOST_TEST_EQ(to_hex(okm_expected), a1.output_key_material); + std::span const prk(prk_expected); + + auto const extract = [&](std::span output, auto token) { + return hash::async_hkdf_extract(executor, output, salt, + ikm, std::move(token)); + }; + auto const extract_pieces = [&](std::span output, auto token) { + return hash::async_hkdf_extract( + executor, output, salt, ikm_pieces, std::move(token)); + }; + auto const expand = [&](std::span output, auto token) { + return hash::async_hkdf_expand(executor, output, prk, info, + std::move(token)); + }; + auto const expand_pieces = [&](std::span output, auto token) { + return hash::async_hkdf_expand( + executor, output, prk, info_pieces, std::move(token)); + }; + auto const derive_pieces = [&](std::span output, auto token) { + return hash::async_hkdf(executor, output, salt, ikm_pieces, + info_pieces, std::move(token)); + }; + check_form(context, prk_expected, extract); + check_form(context, prk_expected, extract_pieces); + check_form(context, okm_expected, expand); + check_form(context, okm_expected, expand_pieces); + check_form(context, okm_expected, derive_pieces); + + // use_awaitable: each form awaited in a coroutine of the context. + std::array awaited_prk{}; + std::array awaited_prk_pieces{}; + std::array awaited_okm{}; + std::array awaited_okm_pieces{}; + std::array awaited_derived{}; + bool done = false; + asio::co_spawn( + context, + [&]() -> asio::awaitable { + auto const token = asio::as_tuple(asio::use_awaitable); + auto [extracted_code] = co_await extract(awaited_prk, token); + BOOST_TEST(!extracted_code); + auto [extracted_pieces_code] = co_await extract_pieces(awaited_prk_pieces, token); + BOOST_TEST(!extracted_pieces_code); + auto [expanded_code] = co_await expand(awaited_okm, token); + BOOST_TEST(!expanded_code); + auto [expanded_pieces_code] = co_await expand_pieces(awaited_okm_pieces, token); + BOOST_TEST(!expanded_pieces_code); + auto [derived_code] = co_await derive_pieces(awaited_derived, token); + BOOST_TEST(!derived_code); + done = true; + }, + [](std::exception_ptr const& failure) { BOOST_TEST(!failure); }); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST(done); + BOOST_TEST(awaited_prk == prk_expected); + BOOST_TEST(awaited_prk_pieces == prk_expected); + BOOST_TEST(awaited_okm == okm_expected); + BOOST_TEST(awaited_okm_pieces == okm_expected); + BOOST_TEST(awaited_derived == okm_expected); + + // The refusals: Extract's pseudorandom key output of no byte, of 31 and of 33 bytes; Expand's + // output of no byte and pseudorandom key of 31 bytes; hkdf's output of no byte and of + // 255 * 32 + 1 bytes. + boost::system::error_code const output_size = hash::error::invalid_output_size; + boost::system::error_code const key_size = hash::error::invalid_key_size; + auto const refuse_extract = [&](auto const& start) { + check_refusal<0>(context, output_size, start); + check_refusal<31>(context, output_size, start); + check_refusal<33>(context, output_size, start); + }; + refuse_extract(extract); + refuse_extract(extract_pieces); + check_refusal<0>(context, output_size, expand); + check_refusal<0>(context, output_size, expand_pieces); + check_refusal<42>(context, key_size, [&](std::span output, auto token) { + hash::async_hkdf_expand(executor, output, prk.first(31), + info, std::move(token)); + }); + check_refusal<42>(context, key_size, [&](std::span output, auto token) { + hash::async_hkdf_expand(executor, output, prk.first(31), + info_pieces, std::move(token)); + }); + check_refusal<0>(context, output_size, derive_pieces); + check_refusal<(255 * 32) + 1>(context, output_size, derive_pieces); +} + +// The spec's temporary list: async_hkdf over the braced lists {a, b} and {c, d}, whose arrays die +// at the end of the call's full-expression, then a to d overwritten before the operation runs. +// The pieces are read in the call (ruling R4): with a callback, with asio::deferred launched after +// the overwrite, and with a use_awaitable awaitable awaited after it, the completion is a success +// and the output is the HKDF of the original bytes. +void check_temporary_lists(asio::io_context& context) { + auto const executor = context.get_executor(); + auto const salt = from_hex("000102030405060708090a0b0c"); + std::array a{}; + std::array b{}; + std::array c{}; + std::array d{}; + auto const restore = [&] { + a = {1, 2, 3, 4}; + b = {5, 6, 7}; + c = {8, 9}; + d = {10, 11, 12, 13, 14}; + }; + auto const overwrite = [&] { + a.fill(0xff); + b.fill(0xff); + c.fill(0xff); + d.fill(0xff); + }; + restore(); + std::array expected{}; + BOOST_TEST(hash::hkdf(expected, salt, {a, b}, {c, d}).has_value()); + std::array joined{}; + auto const ikm = from_hex("01020304050607"); + auto const info = from_hex("08090a0b0c0d0e"); + BOOST_TEST(hash::hkdf(joined, salt, ikm, info).has_value()); + BOOST_TEST(expected == joined); + + std::array output{}; + auto code = complete_by_callback(context, [&](auto token) { + hash::async_hkdf(executor, output, salt, {a, b}, {c, d}, + std::move(token)); + overwrite(); + }); + BOOST_TEST(!code); + BOOST_TEST(output == expected); + + restore(); + std::array deferred_output{}; + auto launch = hash::async_hkdf(executor, deferred_output, salt, {a, b}, + {c, d}, asio::deferred); + overwrite(); + code = complete_by_callback(context, [&](auto token) { std::move(launch)(std::move(token)); }); + BOOST_TEST(!code); + BOOST_TEST(deferred_output == expected); + + restore(); + std::array awaited{}; + bool done = false; + asio::co_spawn( + context, + [&]() -> asio::awaitable { + auto derive = hash::async_hkdf( + executor, awaited, salt, {a, b}, {c, d}, asio::as_tuple(asio::use_awaitable)); + overwrite(); + auto [derived] = co_await std::move(derive); + BOOST_TEST(!derived); + done = true; + }, + [](std::exception_ptr const& failure) { BOOST_TEST(!failure); }); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST(done); + BOOST_TEST(awaited == expected); +} + // co_await in Asio: each function with use_awaitable in a coroutine of the context, its result the // synchronous function's; a refusal (an output of 0 bytes) through as_tuple(use_awaitable), and // with exceptions a plain use_awaitable throws system_error with hash's code. @@ -365,6 +613,13 @@ static_assert(same_default> && same_default && same_default); static_assert(std::is_same_v, hash::backends::hash2>); +static_assert(same_default && same_default && + same_default && + same_default && + same_default); +static_assert( + std::is_same_v, + hash::backends::hash2>); } // namespace @@ -377,6 +632,10 @@ int main() { check_hmac(context); check_hkdf<>(context); check_hkdf(context); + check_hkdf_steps<>(context); + check_hkdf_steps(context); + check_hkdf_steps(context); + check_temporary_lists(context); check_awaitable(context); #ifndef WEBCPP_HASH_NO_EXCEPTIONS check_future_error(context); diff --git a/test/async_webcrypto_test.cpp b/test/async_webcrypto_test.cpp index 18ed0d0..2aa16cd 100644 --- a/test/async_webcrypto_test.cpp +++ b/test/async_webcrypto_test.cpp @@ -19,10 +19,26 @@ // settlement writes nothing; and the handler's associated allocator gets back every block it gave // before the handler runs. Without exceptions an error is read by a callback and // use_awaitable through as_tuple (ruling R71). +// +// HKDF over pieces (the change hkdf-pieces) on WebCrypto's HMAC (importKey, then sign): async_hkdf, +// async_hkdf_extract and async_hkdf_expand over byte_pieces and the single-buffer +// async_hkdf_extract and async_hkdf_expand, RFC 5869's seven cases split into pieces with the three +// completion tokens over the four hashes (backends::hash2's bytes over the hashes the RFC does not +// give); the empty list, one empty piece and {empty, a, empty} as each list; 100 random cases of +// each against backends::hash2, inputs split into 0 to 8 pieces, empty pieces and empty salts among +// them, and node's own HKDF (deriveBits, through the single-buffer async_hkdf) equal to the form +// over pieces for infos up to 1,024 bytes; an info of 64 KiB in pieces, which the single-buffer +// async_hkdf refuses, and the single-buffer async_hkdf_expand's 32,768 bytes (ruling R3); pieces +// overwritten after the call, with asio::deferred and use_awaitable; the guards; every JavaScript +// buffer that held a secret zeroed before the handler runs, after a success and after a failure of +// each step; the runtime refusing a buffer while the pieces are gathered (backend_failure); a +// cancellation during Expand's chain. Built with WEBCPP_HASH_DETAIL_TEST_WEBCRYPTO_MAX_GATHERED +// (async_webcrypto_gathered), it checks the refusal of pieces longer than that bound alone. #include #include #include +#include #include #include #include @@ -38,6 +54,7 @@ #include #include #include +#include #include #include #include @@ -61,6 +78,7 @@ #include "support/rfc5869.hpp" #include "support/rfc6070.hpp" +#include #include #include #include @@ -383,7 +401,7 @@ void check_refusal(asio::io_context& context, std::string_view name, std::size_t // The family's guards and WebCrypto's limits (ruling R74), each refused before any promise. void check_guards(asio::io_context& context) { static_assert(hash::detail::backend_limits::pbkdf2_iterations == 0xffffffffULL); - static_assert(hash::detail::backend_limits::hkdf_info == 1024); + static_assert(hash::detail::backend_limits::hkdf_application_info == 1024); static_assert(hash::detail::backend_limits::hkdf_output == 0xffffffffULL / 8); static_assert(hash::detail::backend_limits::pbkdf2_output == 0xffffffffULL / 8); static_assert(hash::detail::backend_limits::pbkdf2_iterations == @@ -582,7 +600,7 @@ EM_JS(void, stub_pending_digest, (), { }); }); -EM_JS(int, settle_pending_digest, (), { +EM_JS(int, settle_pending_promise, (), { const settle = globalThis.webcpp_test_settle; delete globalThis.webcpp_test_settle; if (settle === undefined) return 0; @@ -594,6 +612,7 @@ EM_JS(void, restore_subtle, (), { const subtle = globalThis.crypto.subtle; delete subtle.digest; delete subtle.sign; + delete subtle.importKey; }); EM_JS(void, hide_crypto, (), { @@ -707,7 +726,7 @@ void check_no_later_write(asio::io_context& context) { BOOST_TEST((output == std::array{})); output.fill(0x77); - BOOST_TEST_EQ(settle_pending_digest(), 1); + BOOST_TEST_EQ(settle_pending_promise(), 1); asio::steady_timer timer(context, std::chrono::milliseconds(20)); timer.async_wait([](boost::system::error_code) {}); context.restart(); @@ -773,6 +792,858 @@ void check_cancellation_between_promises(asio::io_context& context) { BOOST_TEST((output == std::array{})); } +// HKDF over pieces and its two steps on WebCrypto's HMAC (the change hkdf-pieces): async_hkdf, +// async_hkdf_extract and async_hkdf_expand over byte_pieces, and the single-buffer +// async_hkdf_extract and async_hkdf_expand, which run on the same HMAC chain. + +using byte_piece = std::span; + +// `input` split at random points into 0 to 8 pieces, at least one when it is not empty; points +// drawn twice, or at an end, make empty pieces. +std::vector random_split(webcpp::test::random_source& rnd, byte_piece input) { + std::size_t count = rnd.between(0, 8); + if (count == 0 && !input.empty()) { + count = 1; + } + std::vector points; + for (std::size_t i = 1; i < count; ++i) { + points.push_back(rnd.between(0, input.size())); + } + std::ranges::sort(points); + std::vector pieces; + std::size_t start = 0; + for (std::size_t const point : points) { + pieces.push_back(input.subspan(start, point - start)); + start = point; + } + if (count != 0) { + pieces.push_back(input.subspan(start)); + } + return pieces; +} + +// The inputs of one of RFC 5869's cases through the five forms over Hmac, each with the three +// completion tokens: the input keying material in two halves around an empty piece, the +// application info in two halves between two empty pieces. The pseudorandom key and the output +// keying material expected are backends::hash2's, which over the case's own hash (`own`) are first +// checked against the RFC's. +template +void check_published_pieces(asio::io_context& context, std::string_view name, + webcpp::test::rfc5869_case const& published, bool own) { + using hash::backends::hash2; + auto const executor = context.get_executor(); + auto const ikm = from_hex(published.ikm); + auto const salt = from_hex(published.salt); + auto const info = from_hex(published.info); + auto const extracted = hash::hkdf_extract(salt, hash::byte_pieces{ikm}); + BOOST_TEST(extracted.has_value()); + std::vector const prk(extracted->data(), extracted->data() + extracted->size()); + std::vector derived(published.length); + BOOST_TEST((hash::hkdf(derived, salt, ikm, info).has_value())); + std::string const prk_hex = to_hex(prk); + std::string const okm_hex = to_hex(derived); + if (own) { + BOOST_TEST_EQ(prk_hex, std::string(published.prk)); + BOOST_TEST_EQ(okm_hex, std::string(published.okm)); + } + byte_piece const empty{}; + byte_piece const whole_ikm(ikm); + byte_piece const whole_info(info); + std::array const ikm_pieces{ + whole_ikm.first(ikm.size() / 2), + empty, + whole_ikm.subspan(ikm.size() / 2), + }; + std::array const info_pieces{ + empty, + whole_info.first(info.size() / 2), + whole_info.subspan(info.size() / 2), + empty, + }; + std::string const label(name); + check_published(context, label + ", async_hkdf over pieces", okm_hex, + [&](std::span output, auto token) { + return hash::async_hkdf( + executor, output, salt, hash::byte_pieces(ikm_pieces), + hash::byte_pieces(info_pieces), std::move(token)); + }); + check_published(context, label + ", async_hkdf_extract over pieces", prk_hex, + [&](std::span output, auto token) { + return hash::async_hkdf_extract( + executor, output, salt, hash::byte_pieces(ikm_pieces), + std::move(token)); + }); + check_published(context, label + ", async_hkdf_expand over pieces", okm_hex, + [&](std::span output, auto token) { + return hash::async_hkdf_expand( + executor, output, prk, hash::byte_pieces(info_pieces), + std::move(token)); + }); + check_published(context, label + ", async_hkdf_extract", prk_hex, + [&](std::span output, auto token) { + return hash::async_hkdf_extract(executor, output, salt, + ikm, std::move(token)); + }); + check_published(context, label + ", async_hkdf_expand", okm_hex, + [&](std::span output, auto token) { + return hash::async_hkdf_expand(executor, output, prk, info, + std::move(token)); + }); +} + +// RFC 5869's seven cases over Hash: their own bytes over the case's hash (SHA-256 for A.1 to A.3, +// SHA-1 for A.4 to A.7), hash2's over the others. +template +void check_published_hkdf_pieces_over(asio::io_context& context, std::string_view hash_name) { + namespace test = webcpp::test; + using named_case = std::pair; + std::array const cases{ + named_case{"A.1", &test::a1}, named_case{"A.2", &test::a2}, named_case{"A.3", &test::a3}, + named_case{"A.4", &test::a4}, named_case{"A.5", &test::a5}, named_case{"A.6", &test::a6}, + named_case{"A.7", &test::a7}, + }; + for (auto const& [label, published] : cases) { + check_published_pieces( + context, "RFC 5869 " + std::string(label) + " over " + std::string(hash_name), + *published, published->hash == hash_name); + } +} + +// RFC 5869's seven cases over the four hmacs WebCrypto has (webcrypto_hmac_v). +void check_published_hkdf_pieces(asio::io_context& context) { + static_assert(hash::detail::webcrypto_hmac_v && + hash::detail::webcrypto_hmac_v && + hash::detail::webcrypto_hmac_v && + hash::detail::webcrypto_hmac_v); + check_published_hkdf_pieces_over(context, "sha1"); + check_published_hkdf_pieces_over(context, "sha256"); + check_published_hkdf_pieces_over(context, "sha384"); + check_published_hkdf_pieces_over(context, "sha512"); +} + +// Review Focus 5 of the change hkdf-pieces: the empty list, one empty piece and +// {empty, a, empty}, as the input keying material's list and as the application info's, through +// async_hkdf over pieces (each pair of the two), async_hkdf_extract and async_hkdf_expand over +// pieces, over the four hashes, each against backends::hash2's synchronous result. +template +void check_empty_pieces_over(asio::io_context& context) { + using hmac = Hash::hmac; + using hash::backends::hash2; + auto const executor = context.get_executor(); + auto const salt = bytes_of("salt"); + auto const a = bytes_of("a"); + byte_piece const empty{}; + std::array const one_empty{empty}; + std::array const around{empty, a, empty}; + using named_list = std::pair; + std::array const lists{ + named_list{"{}", hash::byte_pieces{}}, + named_list{"{empty}", hash::byte_pieces(one_empty)}, + named_list{"{empty, a, empty}", hash::byte_pieces(around)}, + }; + std::vector const key(Hash::size, 0x0b); + std::size_t const size = (2 * Hash::size) + 3; + for (auto const& [ikm_name, ikm] : lists) { + for (auto const& [info_name, info] : lists) { + std::vector expected(size); + BOOST_TEST((hash::hkdf(expected, salt, ikm, info).has_value())); + std::vector output(size); + auto const code = complete_by_callback(context, [&](auto token) { + hash::async_hkdf(executor, output, salt, ikm, info, + std::move(token)); + }); + compare("async_hkdf over " + std::string(ikm_name) + " and " + std::string(info_name), + Hash::size, code, output, expected); + } + + auto const extracted = hash::hkdf_extract(salt, ikm); + BOOST_TEST(extracted.has_value()); + std::vector extract_output(Hash::size); + auto code = complete_by_callback(context, [&](auto token) { + hash::async_hkdf_extract(executor, extract_output, salt, ikm, + std::move(token)); + }); + compare("async_hkdf_extract over " + std::string(ikm_name), Hash::size, code, + extract_output, std::span(extracted->data(), extracted->size())); + + auto const& info = ikm; + std::vector expanded(size); + BOOST_TEST((hash::hkdf_expand(expanded, key, info).has_value())); + std::vector expand_output(size); + code = complete_by_callback(context, [&](auto token) { + hash::async_hkdf_expand(executor, expand_output, key, info, + std::move(token)); + }); + compare("async_hkdf_expand over " + std::string(ikm_name), Hash::size, code, expand_output, + expanded); + } +} + +void check_empty_pieces(asio::io_context& context) { + check_empty_pieces_over(context); + check_empty_pieces_over(context); + check_empty_pieces_over(context); + check_empty_pieces_over(context); +} + +static_assert( + std::is_same_v, hash::backends::hash2>); + +// 100 random cases of each form against backends::hash2's, over SHA-1, SHA-256, SHA-384 and +// SHA-512 in turn: the first four with every input empty (an empty salt, each empty input split +// into 0 to 8 empty pieces: whether the empty list is drawn depends on the seed, so that +// check_empty_pieces runs it, one empty piece and {empty, a, empty} deterministically), the next +// four with an application info of 1,024 bytes and the longest output (255 digests), then +// salts of 0 to 64 bytes, inputs of 0 to 100 bytes and infos of 0 to 2,048 bytes (beyond +// deriveBits' 1,024), each split into 0 to 8 pieces. Where the info is 1,024 bytes or shorter, +// node's own HKDF (deriveBits, through the single-buffer async_hkdf) gives the bytes of the form +// over pieces too. +void check_random_hkdf_pieces(asio::io_context& context) { + webcpp::test::random_source rnd(webcpp::test::agreement_seed + 4); + auto const executor = context.get_executor(); + std::size_t derive_bits_cases = 0; + for_each_case([&](std::size_t index) { + using hmac = Hash::hmac; + using hash::backends::hash2; + bool const empty = index < 4; + bool const longest = index >= 4 && index < 8; + auto const salt = rnd.bytes(empty ? 0 : rnd.between(0, 64)); + auto const ikm = rnd.bytes(empty ? 0 : rnd.between(0, 100)); + auto const info = rnd.bytes(case_size(rnd, index, 1024, 0, 2048)); + auto const ikm_pieces = random_split(rnd, ikm); + auto const info_pieces = random_split(rnd, info); + auto const key = rnd.bytes(Hash::size); + std::size_t const size = longest ? 255 * Hash::size : rnd.between(1, 3 * Hash::size); + + std::vector expected(size); + BOOST_TEST((hash::hkdf(expected, salt, hash::byte_pieces(ikm_pieces), + hash::byte_pieces(info_pieces)) + .has_value())); + std::vector output(size); + auto code = complete_by_callback(context, [&](auto token) { + hash::async_hkdf(executor, output, salt, hash::byte_pieces(ikm_pieces), + hash::byte_pieces(info_pieces), std::move(token)); + }); + compare("async_hkdf over pieces", index, code, output, expected); + if (info.size() <= 1024) { + ++derive_bits_cases; + std::vector derived(size); + code = complete_by_callback(context, [&](auto token) { + hash::async_hkdf(executor, derived, salt, ikm, info, + std::move(token)); + }); + compare("async_hkdf (deriveBits) against over pieces", index, code, derived, output); + } + + auto const extracted = hash::hkdf_extract(salt, hash::byte_pieces(ikm_pieces)); + BOOST_TEST(extracted.has_value()); + byte_piece const pseudorandom_key(extracted->data(), extracted->size()); + std::vector extract_output(Hash::size); + code = complete_by_callback(context, [&](auto token) { + hash::async_hkdf_extract( + executor, extract_output, salt, hash::byte_pieces(ikm_pieces), std::move(token)); + }); + compare("async_hkdf_extract over pieces", index, code, extract_output, pseudorandom_key); + std::vector single_extract(Hash::size); + code = complete_by_callback(context, [&](auto token) { + hash::async_hkdf_extract(executor, single_extract, salt, ikm, + std::move(token)); + }); + compare("async_hkdf_extract", index, code, single_extract, pseudorandom_key); + + std::vector expanded(size); + BOOST_TEST((hash::hkdf_expand(expanded, key, hash::byte_pieces(info_pieces)) + .has_value())); + std::vector expand_output(size); + code = complete_by_callback(context, [&](auto token) { + hash::async_hkdf_expand( + executor, expand_output, key, hash::byte_pieces(info_pieces), std::move(token)); + }); + compare("async_hkdf_expand over pieces", index, code, expand_output, expanded); + std::vector single_expand(size); + code = complete_by_callback(context, [&](auto token) { + hash::async_hkdf_expand(executor, single_expand, key, info, + std::move(token)); + }); + compare("async_hkdf_expand", index, code, single_expand, expanded); + }); + BOOST_TEST_GE(derive_bits_cases, 40U); +} + +// The spec's scenario: an application info of 64 KiB in four pieces gives hash2's bytes, where +// the single-buffer async_hkdf refuses it (input_too_long, the output untouched). The single-buffer +// async_hkdf_expand runs on HMAC and keeps hash's 32,768 bytes (ruling R3), not deriveBits' 1,024: +// 1,025 and 32,768 bytes give hash2's bytes, 32,769 are refused, and the same 32,769 bytes as +// byte_pieces{info} are not. +void check_long_application_info(asio::io_context& context) { + webcpp::test::random_source rnd(webcpp::test::agreement_seed + 5); + auto const executor = context.get_executor(); + auto const salt = rnd.bytes(16); + auto const ikm = rnd.bytes(32); + auto const info = rnd.bytes(65536); + byte_piece const whole(info); + std::array const quarters{ + whole.first(16384), + whole.subspan(16384, 16384), + whole.subspan(32768, 16384), + whole.subspan(49152), + }; + std::vector expected(64); + BOOST_TEST(hash::hkdf(expected, salt, hash::byte_pieces{ikm}, quarters) + .has_value()); + std::vector output(64); + auto code = complete_by_callback(context, [&](auto token) { + hash::async_hkdf( + executor, output, salt, hash::byte_pieces{ikm}, hash::byte_pieces(quarters), + std::move(token)); + }); + compare("async_hkdf over 64 KiB of pieces", 0, code, output, expected); + check_refusal(context, "async_hkdf with 64 KiB of info", 64, hash::error::input_too_long, + [&](std::span refused, auto token) { + hash::async_hkdf(executor, refused, salt, ikm, + info, std::move(token)); + }); + + auto const key = rnd.bytes(32); + for (std::size_t const size : {std::size_t{1025}, hash::hkdf_max_application_info_size}) { + auto const head = whole.first(size); + std::vector expanded(80); + BOOST_TEST(hash::hkdf_expand(expanded, key, head).has_value()); + std::vector single(80); + code = complete_by_callback(context, [&](auto token) { + hash::async_hkdf_expand(executor, single, key, head, + std::move(token)); + }); + compare("async_hkdf_expand of a long info", size, code, single, expanded); + } + auto const over = whole.first(hash::hkdf_max_application_info_size + 1); + check_refusal(context, "async_hkdf_expand with 32,769 bytes of info", 80, + hash::error::input_too_long, [&](std::span refused, auto token) { + hash::async_hkdf_expand( + executor, refused, key, over, std::move(token)); + }); + std::vector expanded(80); + BOOST_TEST( + hash::hkdf_expand(expanded, key, hash::byte_pieces{over}).has_value()); + std::vector one_piece(80); + code = complete_by_callback(context, [&](auto token) { + hash::async_hkdf_expand( + executor, one_piece, key, hash::byte_pieces{over}, std::move(token)); + }); + compare("async_hkdf_expand over byte_pieces{32,769 bytes}", 0, code, one_piece, expanded); +} + +// The pieces are gathered into JavaScript memory in the call (ruling R4): async_hkdf over the +// braced lists {a, b} and {c, d}, whose arrays die at the end of the call's full-expression, then a +// to d overwritten before the operation runs, gives the HKDF of the original bytes with a callback, +// with asio::deferred launched after the overwrite and with a use_awaitable awaitable awaited after +// it; async_hkdf_extract and async_hkdf_expand over pieces likewise with asio::deferred. +void check_pieces_read_in_call(asio::io_context& context) { + auto const executor = context.get_executor(); + auto const salt = from_hex("000102030405060708090a0b0c"); + std::array a{}; + std::array b{}; + std::array c{}; + std::array d{}; + auto const restore = [&] { + a = {1, 2, 3, 4}; + b = {5, 6, 7}; + c = {8, 9}; + d = {10, 11, 12, 13, 14}; + }; + auto const overwrite = [&] { + a.fill(0xff); + b.fill(0xff); + c.fill(0xff); + d.fill(0xff); + }; + restore(); + std::array expected{}; + BOOST_TEST(hash::hkdf(expected, salt, {a, b}, {c, d}).has_value()); + auto const extracted = hash::hkdf_extract(salt, {a, b}); + BOOST_TEST(extracted.has_value()); + std::array key{}; + std::ranges::copy(*extracted, key.begin()); + std::array expanded{}; + BOOST_TEST(hash::hkdf_expand(expanded, key, {c, d}).has_value()); + BOOST_TEST(expanded == expected); + + std::array output{}; + auto code = complete_by_callback(context, [&](auto token) { + hash::async_hkdf(executor, output, salt, {a, b}, {c, d}, + std::move(token)); + overwrite(); + }); + BOOST_TEST(!code); + BOOST_TEST(output == expected); + + restore(); + std::array deferred_output{}; + auto launch = hash::async_hkdf(executor, deferred_output, salt, + {a, b}, {c, d}, asio::deferred); + overwrite(); + code = complete_by_callback(context, [&](auto token) { std::move(launch)(std::move(token)); }); + BOOST_TEST(!code); + BOOST_TEST(deferred_output == expected); + + restore(); + std::array extract_output{}; + auto extract = hash::async_hkdf_extract( + executor, extract_output, salt, {a, b}, asio::deferred); + overwrite(); + code = complete_by_callback(context, [&](auto token) { std::move(extract)(std::move(token)); }); + BOOST_TEST(!code); + BOOST_TEST(extract_output == key); + + restore(); + std::array expand_output{}; + auto expand = hash::async_hkdf_expand( + executor, expand_output, key, {c, d}, asio::deferred); + overwrite(); + code = complete_by_callback(context, [&](auto token) { std::move(expand)(std::move(token)); }); + BOOST_TEST(!code); + BOOST_TEST(expand_output == expected); + + restore(); + std::array awaited{}; + bool done = false; + asio::co_spawn( + context, + [&]() -> asio::awaitable { + auto derive = hash::async_hkdf( + executor, awaited, salt, {a, b}, {c, d}, asio::as_tuple(asio::use_awaitable)); + overwrite(); + auto [derived] = co_await std::move(derive); + BOOST_TEST(!derived); + done = true; + }, + [](std::exception_ptr const& failure) { BOOST_TEST(!failure); }); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST(done); + BOOST_TEST(awaited == expected); +} + +// The guards of the five forms (RFC 5869's, and hash's 32,768 bytes of the single-buffer +// async_hkdf_expand), each completing through the loop, the output untouched. +void check_hkdf_pieces_guards(asio::io_context& context) { + auto const executor = context.get_executor(); + auto const abc = bytes_of("abc"); + std::vector const key(32, 0x0b); + std::vector const short_key(31, 0x0b); + std::vector const long_info(hash::hkdf_max_application_info_size + 1, 0x01); + auto const hkdf = [&](std::span output, auto token) { + hash::async_hkdf(executor, output, abc, {abc, abc}, + {abc, abc}, std::move(token)); + }; + check_refusal(context, "async_hkdf over pieces of 0 bytes", 0, hash::error::invalid_output_size, + hkdf); + check_refusal(context, "async_hkdf over pieces of 255 digests and 1 byte", (255 * 32) + 1, + hash::error::invalid_output_size, hkdf); + auto const extract = [&](std::span output, auto token) { + hash::async_hkdf_extract(executor, output, abc, {abc, abc}, + std::move(token)); + }; + check_refusal(context, "async_hkdf_extract over pieces of 31 bytes", 31, + hash::error::invalid_output_size, extract); + check_refusal(context, "async_hkdf_extract over pieces of 33 bytes", 33, + hash::error::invalid_output_size, extract); + check_refusal(context, "async_hkdf_extract of 0 bytes", 0, hash::error::invalid_output_size, + [&](std::span output, auto token) { + hash::async_hkdf_extract( + executor, output, abc, abc, std::move(token)); + }); + check_refusal(context, "async_hkdf_expand over pieces of 0 bytes", 0, + hash::error::invalid_output_size, + [&](std::span output, auto token) { + hash::async_hkdf_expand( + executor, output, key, {abc, abc}, std::move(token)); + }); + check_refusal(context, "async_hkdf_expand over pieces with a key of 31 bytes", 32, + hash::error::invalid_key_size, [&](std::span output, auto token) { + hash::async_hkdf_expand( + executor, output, short_key, {abc, abc}, std::move(token)); + }); + check_refusal(context, "async_hkdf_expand of 255 digests and 1 byte", (255 * 32) + 1, + hash::error::invalid_output_size, + [&](std::span output, auto token) { + hash::async_hkdf_expand( + executor, output, key, abc, std::move(token)); + }); + check_refusal(context, "async_hkdf_expand with a key of 31 bytes", 32, + hash::error::invalid_key_size, [&](std::span output, auto token) { + hash::async_hkdf_expand( + executor, output, short_key, abc, std::move(token)); + }); + check_refusal(context, "async_hkdf_expand with 32,769 bytes of info", 32, + hash::error::input_too_long, [&](std::span output, auto token) { + hash::async_hkdf_expand( + executor, output, key, long_info, std::move(token)); + }); +} + +// crypto.subtle's importKey and sign wrapped for one test: each counted, every buffer they read +// and every tag sign gives recorded, so that the test can check that each was zeroed; sign's +// call number `pending_sign` returns a promise the test settles (settle_pending_promise), its call +// number `failing_sign` and importKey's number `failing_import` reject (0: none). +// clang-format off +EM_JS(void, stub_hmac_calls, (int pending_sign, int failing_sign, int failing_import), { + const subtle = globalThis.crypto.subtle; + const original = Object.getPrototypeOf(subtle); + const state = {signs: 0, imports: 0, buffers: []}; + globalThis.webcpp_test_hmac = state; + const record = (bytes) => { + if (ArrayBuffer.isView(bytes)) { + state.buffers.push(new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength)); + } else if (bytes instanceof ArrayBuffer) { + state.buffers.push(new Uint8Array(bytes)); + } + }; + subtle.importKey = function(format, data, ...rest) { + ++state.imports; + record(data); + if (state.imports === failing_import) return Promise.reject(new Error("stubbed rejection")); + return original.importKey.call(subtle, format, data, ...rest); + }; + subtle.sign = function(algorithm, key, data) { + ++state.signs; + record(data); + if (state.signs === pending_sign) { + return new Promise(resolve => { globalThis.webcpp_test_settle = resolve; }); + } + if (state.signs === failing_sign) return Promise.reject(new Error("stubbed rejection")); + return original.sign.call(subtle, algorithm, key, data).then(tag => { + record(tag); + return tag; + }); + }; +}); + +EM_JS(int, stubbed_signs, (), { return globalThis.webcpp_test_hmac.signs; }); + +EM_JS(int, recorded_buffers, (), { return globalThis.webcpp_test_hmac.buffers.length; }); + +EM_JS(int, unwiped_buffers, (), { + return globalThis.webcpp_test_hmac.buffers.filter(bytes => bytes.some(b => b !== 0)).length; +}); +// clang-format on + +// Every JavaScript buffer that held a secret is zeroed by the time the handler runs: the salt and +// the pseudorandom key importKey read, the input keying material and the blocks sign read, and each +// tag sign gave, the last one among them (each case records exactly the buffers of its calls), +// after a success of each of the five forms and after each failure of a step (importKey or sign +// rejected), the failures completing with backend_failure, the output zeroed, the first block of +// the output among it. +void check_secrets_wiped(asio::io_context& context) { + auto const executor = context.get_executor(); + auto const salt = bytes_of("salt"); + auto const ikm = bytes_of("input key material"); + auto const info = bytes_of("application info"); + std::vector const key(32, 0x0b); + auto const wiped = [&](std::string_view name, std::size_t size, + boost::system::error_code expected, int buffers, auto start) { + std::vector output(size, 0xa5); + int unwiped_in_handler = -1; + auto const code = complete_by_callback(context, [&](auto token) { + start(std::span(output), [&unwiped_in_handler, token = std::move(token)]( + boost::system::error_code done) mutable { + unwiped_in_handler = unwiped_buffers(); + std::move(token)(done); + }); + }); + bool const zeroed = std::ranges::all_of(output, [](std::uint8_t b) { return b == 0; }); + if (!BOOST_TEST(code == expected) || !BOOST_TEST_EQ(recorded_buffers(), buffers) || + !BOOST_TEST_EQ(unwiped_in_handler, 0) || !BOOST_TEST_EQ(unwiped_buffers(), 0) || + !BOOST_TEST(zeroed == bool(code))) { + std::cerr << " " << name << ": " << code.message() << '\n'; + } + restore_subtle(); + }; + auto const hkdf = [&](std::span output, auto token) { + hash::async_hkdf(executor, output, salt, {ikm, ikm}, + {info, info}, std::move(token)); + }; + auto const extract = [&](std::span output, auto token) { + hash::async_hkdf_extract(executor, output, salt, {ikm, ikm}, + std::move(token)); + }; + auto const expand = [&](std::span output, auto token) { + hash::async_hkdf_expand(executor, output, key, {info, info}, + std::move(token)); + }; + boost::system::error_code const fine; + boost::system::error_code const failure = hash::error::backend_failure; + + // A 100-byte output is four blocks: four signs over a block, four tags. + stub_hmac_calls(0, 0, 0); + wiped("async_hkdf over pieces", 100, fine, 12, hkdf); + stub_hmac_calls(0, 0, 0); + wiped("async_hkdf_extract over pieces", 32, fine, 3, extract); + stub_hmac_calls(0, 0, 0); + wiped("async_hkdf_expand over pieces", 100, fine, 9, expand); + stub_hmac_calls(0, 0, 0); + wiped("async_hkdf_extract", 32, fine, 3, [&](std::span output, auto token) { + hash::async_hkdf_extract(executor, output, salt, ikm, + std::move(token)); + }); + stub_hmac_calls(0, 0, 0); + wiped("async_hkdf_expand", 100, fine, 9, [&](std::span output, auto token) { + hash::async_hkdf_expand(executor, output, key, info, + std::move(token)); + }); + + stub_hmac_calls(0, 0, 1); + wiped("async_hkdf, the salt's importKey rejected", 100, failure, 1, hkdf); + stub_hmac_calls(0, 1, 0); + wiped("async_hkdf, Extract's sign rejected", 100, failure, 2, hkdf); + stub_hmac_calls(0, 0, 2); + wiped("async_hkdf, the pseudorandom key's importKey rejected", 100, failure, 4, hkdf); + stub_hmac_calls(0, 3, 0); + wiped("async_hkdf, the second block's sign rejected", 100, failure, 7, hkdf); + stub_hmac_calls(0, 2, 0); + wiped("async_hkdf_expand, the second block's sign rejected", 100, failure, 4, expand); +} + +// The global Uint8Array replaced for one initiating call by a subclass that records the length of +// every array made with a length and every such array, and throws a RangeError for the length +// `refused` (-1: none), as a runtime refuses a buffer its memory cannot hold. +// clang-format off +EM_JS(void, stub_uint8array, (double refused), { + const original = globalThis.Uint8Array; + const state = {original, lengths: [], made: []}; + globalThis.webcpp_test_bytes = state; + globalThis.Uint8Array = class extends original { + constructor(...args) { + const sized = typeof args[0] === "number"; + if (sized) { + state.lengths.push(args[0]); + if (args[0] === refused) throw new RangeError("stubbed refusal"); + } + super(...args); + if (sized) state.made.push(this); + } + }; +}); + +EM_JS(void, restore_uint8array, (), { + globalThis.Uint8Array = globalThis.webcpp_test_bytes.original; +}); + +EM_JS(int, uint8arrays_of_length, (double length), { + return globalThis.webcpp_test_bytes.lengths.filter(made => made === length).length; +}); + +EM_JS(int, uint8arrays_made, (), { return globalThis.webcpp_test_bytes.made.length; }); + +EM_JS(int, unwiped_uint8arrays, (), { + return globalThis.webcpp_test_bytes.made.filter(bytes => bytes.some(b => b !== 0)).length; +}); +// clang-format on + +// `start(output, token)`, an output of `size` bytes, with the Uint8Array stub refusing `refused` +// bytes during the initiating call: it completes through the loop with backend_failure, the output +// zeroed, every buffer made zeroed and none of `skipped` bytes attempted; `made` arrays were made. +template +void check_refused_gathering(asio::io_context& context, std::string_view name, std::size_t size, + double refused, double skipped, int made, Start start) { + std::vector output(size, 0xa5); + auto const code = complete_by_callback(context, [&](auto token) { + stub_uint8array(refused); + start(std::span(output), std::move(token)); + restore_uint8array(); + }); + bool const zeroed = std::ranges::all_of(output, [](std::uint8_t b) { return b == 0; }); + if (!BOOST_TEST(code == hash::error::backend_failure) || !BOOST_TEST(zeroed) || + !BOOST_TEST_EQ(uint8arrays_of_length(refused), refused < 0 ? 0 : 1) || + !BOOST_TEST_EQ(uint8arrays_of_length(skipped), 0) || + !BOOST_TEST_EQ(uint8arrays_made(), made) || !BOOST_TEST_EQ(unwiped_uint8arrays(), 0)) { + std::cerr << " " << name << ": " << code.message() << '\n'; + } +} + +// The runtime refusing a buffer while the pieces are gathered (a RangeError, or an out of memory, +// from new Uint8Array) completes with backend_failure, the output zeroed and the buffers already +// made zeroed, rather than end the program; async_hkdf gathers no application info once Extract's +// inputs were not gathered. The salt is 4 bytes, the input keying material 77 and the info 100. +void check_refused_gathering(asio::io_context& context) { + auto const executor = context.get_executor(); + std::vector const salt(4, 0x01); + std::vector const ikm(77, 0x02); + std::vector const info(100, 0x03); + std::vector const key(32, 0x0b); + byte_piece const whole_ikm(ikm); + byte_piece const whole_info(info); + std::array const ikm_pieces{whole_ikm.first(40), whole_ikm.subspan(40)}; + std::array const info_pieces{whole_info.first(50), whole_info.subspan(50)}; + // Expand's block over SHA-256: 32 + 100 + 1 bytes. + constexpr double block = 133; + auto const hkdf = [&](std::span output, auto token) { + hash::async_hkdf( + executor, output, salt, hash::byte_pieces(ikm_pieces), hash::byte_pieces(info_pieces), + std::move(token)); + }; + check_refused_gathering(context, "async_hkdf, the salt refused", 100, 4, block, 0, hkdf); + check_refused_gathering(context, "async_hkdf, the input keying material refused", 100, 77, + block, 1, hkdf); + check_refused_gathering(context, "async_hkdf, the application info refused", 100, block, -1, 2, + hkdf); + check_refused_gathering(context, + "async_hkdf_extract over pieces, the input keying material " + "refused", + 32, 77, -1, 1, [&](std::span output, auto token) { + hash::async_hkdf_extract( + executor, output, salt, hash::byte_pieces(ikm_pieces), + std::move(token)); + }); + check_refused_gathering(context, "async_hkdf_extract, the input keying material refused", 32, + 77, -1, 1, [&](std::span output, auto token) { + hash::async_hkdf_extract( + executor, output, salt, ikm, std::move(token)); + }); + check_refused_gathering(context, "async_hkdf_expand over pieces, the pseudorandom key refused", + 100, 32, block, 0, [&](std::span output, auto token) { + hash::async_hkdf_expand( + executor, output, key, hash::byte_pieces(info_pieces), + std::move(token)); + }); + check_refused_gathering(context, "async_hkdf_expand over pieces, the application info refused", + 100, block, -1, 1, [&](std::span output, auto token) { + hash::async_hkdf_expand( + executor, output, key, hash::byte_pieces(info_pieces), + std::move(token)); + }); + check_refused_gathering(context, "async_hkdf_expand, the application info refused", 100, block, + -1, 1, [&](std::span output, auto token) { + hash::async_hkdf_expand( + executor, output, key, info, std::move(token)); + }); + + // Restored: the same call succeeds. + std::vector expected(100); + BOOST_TEST(hash::hkdf(expected, salt, hash::byte_pieces(ikm_pieces), + hash::byte_pieces(info_pieces)) + .has_value()); + std::vector output(100); + auto const code = complete_by_callback(context, [&](auto token) { hkdf(output, token); }); + compare("async_hkdf after the stub", 0, code, output, expected); +} + +// The test seam lowers webcrypto_max_gathered (2^53 - 1 bytes otherwise, which no runtime holds) to +// 100 bytes: an input keying material of 100 bytes in pieces gives hash2's bytes, one of 101 is +// backend_failure, the output zeroed, before any buffer is made (async_hkdf then gathers no +// application info); over SHA-256, Expand's block of 32 + 67 + 1 bytes is gathered, one of +// 32 + 68 + 1 is backend_failure, every buffer made zeroed. +void check_gathered_bound(asio::io_context& context) { + BOOST_TEST_EQ(hash::detail::webcrypto_max_gathered, 100U); + auto const executor = context.get_executor(); + auto const salt = bytes_of("salt"); + std::vector const bytes(101, 0x5c); + std::vector const key(32, 0x0b); + byte_piece const whole(bytes); + auto const split = [&](std::size_t size) { + return std::array{ + whole.first(size / 2), + whole.subspan(size / 2, size - (size / 2)), + }; + }; + auto const ikm_at = split(100); + auto const ikm_over = split(101); + auto const info_at = split(67); + auto const info_over = split(68); + auto const short_info = split(10); + + auto const extracted = hash::hkdf_extract(salt, hash::byte_pieces(ikm_at)); + BOOST_TEST(extracted.has_value()); + std::vector extract_output(32); + auto code = complete_by_callback(context, [&](auto token) { + hash::async_hkdf_extract( + executor, extract_output, salt, hash::byte_pieces(ikm_at), std::move(token)); + }); + compare("async_hkdf_extract over 100 bytes of pieces", 100, code, extract_output, + std::span(extracted->data(), extracted->size())); + check_refused_gathering(context, "async_hkdf_extract over 101 bytes of pieces", 32, -1, -1, 0, + [&](std::span output, auto token) { + hash::async_hkdf_extract( + executor, output, salt, hash::byte_pieces(ikm_over), + std::move(token)); + }); + // Expand's block over the short info: 32 + 10 + 1 bytes, which async_hkdf does not attempt. + check_refused_gathering(context, "async_hkdf over 101 bytes of pieces", 100, -1, 43, 0, + [&](std::span output, auto token) { + hash::async_hkdf( + executor, output, salt, hash::byte_pieces(ikm_over), + hash::byte_pieces(short_info), std::move(token)); + }); + + std::vector expanded(100); + BOOST_TEST(hash::hkdf_expand(expanded, key, hash::byte_pieces(info_at)) + .has_value()); + std::vector expand_output(100); + code = complete_by_callback(context, [&](auto token) { + hash::async_hkdf_expand( + executor, expand_output, key, hash::byte_pieces(info_at), std::move(token)); + }); + compare("async_hkdf_expand over 67 bytes of pieces", 67, code, expand_output, expanded); + // The pseudorandom key's buffer is made, then zeroed. + check_refused_gathering(context, "async_hkdf_expand over 68 bytes of pieces", 100, -1, -1, 1, + [&](std::span output, auto token) { + hash::async_hkdf_expand( + executor, output, key, hash::byte_pieces(info_over), + std::move(token)); + }); +} + +// A cancellation during Expand's chain: async_hkdf_expand over pieces of three blocks, the second +// block's sign held pending by a stub once the first block is in the output; a terminal +// cancellation then completes at once with operation_aborted, the output zeroed (the first block +// with it) and every JavaScript buffer zeroed; the pending promise's later settlement writes +// nothing and calls no handler again. +void check_cancellation_in_expand(asio::io_context& context) { + auto const executor = context.get_executor(); + std::vector const key(32, 0x0b); + auto const info = bytes_of("application info"); + std::array expected{}; + BOOST_TEST(hash::hkdf_expand(expected, key, {info, info}).has_value()); + stub_hmac_calls(2, 0, 0); + asio::cancellation_signal signal; + std::array output{}; + output.fill(0xa5); + int calls = 0; + boost::system::error_code code; + hash::async_hkdf_expand( + executor, output, key, {info, info}, + asio::bind_cancellation_slot(signal.slot(), [&](boost::system::error_code done) { + ++calls; + code = done; + })); + context.restart(); + for (int step = 0; step != 20 && stubbed_signs() < 2; ++step) { + context.run_one(); // lint-run: one step of the chain, until the second sign is pending + } + BOOST_TEST_EQ(stubbed_signs(), 2); + BOOST_TEST_EQ(calls, 0); + BOOST_TEST(std::ranges::equal(std::span(output).first(32), std::span(expected).first(32))); + BOOST_TEST(std::ranges::all_of(std::span(output).subspan(32), + [](std::uint8_t b) { return b == 0xa5; })); + signal.emit(asio::cancellation_type::terminal); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(calls, 1); + BOOST_TEST(code == asio::error::operation_aborted); + BOOST_TEST((output == std::array{})); + BOOST_TEST_EQ(unwiped_buffers(), 0); + + output.fill(0x77); + BOOST_TEST_EQ(settle_pending_promise(), 1); + asio::steady_timer timer(context, std::chrono::milliseconds(20)); + timer.async_wait([](boost::system::error_code) {}); + context.restart(); + context.run(); // lint-run: the test's event loop, the promise's settlement among it + restore_subtle(); + BOOST_TEST_EQ(calls, 1); + BOOST_TEST(std::ranges::all_of(output, [](std::uint8_t b) { return b == 0x77; })); +} + // An allocator that counts the blocks it has given and not got back. template struct holding_allocator { @@ -864,6 +1735,12 @@ void check_allocator(asio::io_context& context) { int main() { asio::io_context context; + // The seam's program (async_webcrypto_gathered) checks the bound's refusal alone, which the + // seam makes reachable; the others need the bound of 2^53 - 1 bytes. + if (hash::detail::webcrypto_max_gathered == 100) { + check_gathered_bound(context); + return webcpp::test::exit_status(boost::report_errors()); + } check_published_cases(context); check_random_digests(context); check_random_hmacs(context); @@ -880,5 +1757,14 @@ int main() { check_partial_cancellation(context); check_cancellation_between_promises(context); check_allocator(context); + check_published_hkdf_pieces(context); + check_empty_pieces(context); + check_random_hkdf_pieces(context); + check_long_application_info(context); + check_pieces_read_in_call(context); + check_hkdf_pieces_guards(context); + check_secrets_wiped(context); + check_refused_gathering(context); + check_cancellation_in_expand(context); return webcpp::test::exit_status(boost::report_errors()); } diff --git a/test/botan_failure_test.cpp b/test/botan_failure_test.cpp index ff629d8..ecdccd8 100644 --- a/test/botan_failure_test.cpp +++ b/test/botan_failure_test.cpp @@ -6,16 +6,18 @@ // A failure of Botan (spec sections 2.8 and 7.5), provoked through the seam // WEBCPP_HASH_DETAIL_TEST_BOTAN_NAME, which the test's Jamfile defines to "NO-SUCH-HASH", a name -// Botan does not know: its create_or_throw throws Lookup_Error, which the boundary catches, so -// that digest_of, a hasher's make, mac and every key derivation (Botan's KDF and PasswordHashFamily -// are made the same way) answer backend_failure, the output zeroed, and no exception leaves -// webcpp::hash. A guard's refusal still comes first. bcrypt reaches Botan through generate_bcrypt, -// which no name selects: its generator of the caller's salt, detail::botan_salt, throws on a second -// draw or a draw of another size, which the boundary would answer with backend_failure. +// Botan does not know: its create_or_throw throws Lookup_Error, which the boundary catches, so that +// digest_of, a hasher's make, mac and every key derivation (Botan's KDF and PasswordHashFamily are +// made the same way, and the HMAC of HKDF over pieces) answer backend_failure, the output zeroed, +// and no exception leaves webcpp::hash. A guard's refusal still comes first. bcrypt reaches Botan +// through generate_bcrypt, which no name selects: its generator of the caller's salt, +// detail::botan_salt, throws on a second draw or a draw of another size, which the boundary would +// answer with backend_failure. #include #include #include +#include #include #include #include @@ -81,7 +83,8 @@ void mac_fails(std::size_t size, std::size_t key_size) { BOOST_TEST(zeroed(out)); } -// Every key derivation of Botan's KDF and PasswordHashFamily: backend_failure, the output zeroed. +// Every key derivation of Botan's KDF and PasswordHashFamily, and HKDF over pieces on its HMAC: +// backend_failure, the output zeroed. void kdfs_fail() { using hmac = hash::hmac_sha2_256; std::array output{}; @@ -97,11 +100,18 @@ void kdfs_fail() { std::array const key{2}; check(hash::hkdf_expand(output, key, abc)); check(hash::hkdf(output, salt, abc, abc)); + // HKDF over pieces makes Botan's HMAC by the same seam. + using piece = std::span; + std::array const pieces{piece(abc).first(1), piece{}, piece(abc).subspan(1)}; + auto const pieces_prk = hash::hkdf_extract(salt, pieces); + BOOST_TEST(pieces_prk.has_error() && pieces_prk.error() == hash::error::backend_failure); + check(hash::hkdf_expand(output, key, pieces)); + check(hash::hkdf(output, salt, pieces, pieces)); check(hash::pbkdf2(output, abc, salt, 2)); check(hash::argon2id(output, abc, salt, {.passes = 1, .memory = 8192})); check(hash::argon2(output, abc, salt, - {.passes = 1, .memory_kib = 8})); - check(hash::scrypt(output, abc, salt, {.n = 16, .r = 1, .p = 1})); + {.passes = 1, .memory_kibibytes = 8})); + check(hash::scrypt(output, abc, salt, {.cost = 16, .block_size = 1, .parallelism = 1})); check(hash::bcrypt_pbkdf(output, abc, salt, 2)); check(hash::kbkdf(output, abc)); check(hash::sskdf(output, abc)); diff --git a/test/byte_pieces_test.cpp b/test/byte_pieces_test.cpp new file mode 100644 index 0000000..073d7d1 --- /dev/null +++ b/test/byte_pieces_test.cpp @@ -0,0 +1,208 @@ +// 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) + +// byte_pieces and the call of HKDF over pieces, on every target and with each lane's compiler (the +// record of design B2): `{a, b, c}` binds to byte_pieces; a braced list of one span picks the +// single-buffer overload (design D1, B1, ruling R1), and `byte_pieces{x}` the pieces one, which +// has no cap (Review Focus 3); a std::array and a std::vector of spans pass through the range +// constructor (Review Focus 1); `{}` and a braced list of one element of another type are +// ambiguous where every pieces position is braces (rulings R9, R11). And the slicing of a piece +// for a backend whose HMAC update takes a narrower length than a span (detail::for_each_slice, +// Review Focus 4), with a small maximum. + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace hash = webcpp::hash; +namespace detail = webcpp::hash::detail; + +namespace { + +using piece = std::span; + +// The overloads a braced list picks, the counts and sizes of a list, the range constructor. +void binding() { + std::array const x{1, 2, 3}; + piece const a{x}; + piece const b{x}; + piece const c{x}; + static_assert(std::is_same_v(a, {a, b, c})), + boost::system::result>); + BOOST_TEST_EQ(hash::byte_pieces({a, b, c}).size(), 3U); + BOOST_TEST_EQ(hash::byte_pieces({a, b, c}).total_size(), 9U); + BOOST_TEST(!hash::byte_pieces({a, b, c}).empty()); + std::array const named{a, b}; + std::vector const listed{a, b, c}; + BOOST_TEST_EQ(hash::byte_pieces(named).size(), 2U); + BOOST_TEST_EQ(hash::byte_pieces(listed).size(), 3U); + BOOST_TEST_EQ(hash::byte_pieces(listed).total_size(), 9U); + BOOST_TEST(hash::byte_pieces(named).begin() == named.data()); + BOOST_TEST(hash::byte_pieces(named).end() == named.data() + named.size()); + + hash::byte_pieces const none; + BOOST_TEST(none.empty()); + BOOST_TEST_EQ(none.size(), 0U); + BOOST_TEST_EQ(none.total_size(), 0U); + BOOST_TEST(none.begin() == none.end()); + + // A list of empty pieces holds pieces and no byte. + piece const empty; + BOOST_TEST_EQ(hash::byte_pieces({empty, empty}).size(), 2U); + BOOST_TEST_EQ(hash::byte_pieces({empty, empty}).total_size(), 0U); + BOOST_TEST_EQ(hash::byte_pieces({empty, a, empty}).total_size(), 3U); + + // A constant list: the type is a literal one. + static constexpr std::array constant_bytes{1, 2, 3, 4}; + static constexpr std::array constant_pieces{ + piece(constant_bytes), + piece(constant_bytes).first(1), + }; + static_assert(hash::byte_pieces(constant_pieces).total_size() == 5U); +} + +// {x} is the single-buffer form and its cap; byte_pieces{x} the pieces form, uncapped. +void lone_span() { + std::vector const long_info(hash::hkdf_max_application_info_size + 1, 0x5a); + std::array prk{}; + std::array out{}; + BOOST_TEST(hash::hkdf_expand(out, prk, {std::span(long_info)}).error() == + hash::error::input_too_long); + BOOST_TEST( + hash::hkdf_expand(out, prk, hash::byte_pieces{std::span(long_info)})); +} + +// Which calls compile, rulings R1, R9 and R11: in the pieces position, a braced list of one +// std::span is the single-buffer form; `{}` and a braced list of one element of +// another type are ambiguous, so the caller passes the element itself or names byte_pieces. Each +// requirement depends on the hmac, so that an ambiguous call makes it false rather than the program +// ill-formed. +using bytes = std::vector; +using bytes_array = std::array; + +template +constexpr bool extract_empty = requires(piece s) { hash::hkdf_extract(s, {}); }; +template +constexpr bool extract_vector = requires(piece s, bytes v) { hash::hkdf_extract(s, {v}); }; +template +constexpr bool extract_array = + requires(piece s, bytes_array a) { hash::hkdf_extract(s, {a}); }; +template +constexpr bool extract_takes = requires(piece s, bytes v) { + hash::hkdf_extract(s, v); + hash::hkdf_extract(s, {s}); + hash::hkdf_extract(s, hash::byte_pieces{}); + hash::hkdf_extract(s, hash::byte_pieces{piece(v)}); +}; + +template +constexpr bool expand_empty = + requires(std::span o, piece k) { hash::hkdf_expand(o, k, {}); }; +template +constexpr bool expand_vector = + requires(std::span o, piece k, bytes v) { hash::hkdf_expand(o, k, {v}); }; +template +constexpr bool expand_array = requires(std::span o, piece k, bytes_array a) { + hash::hkdf_expand(o, k, {a}); +}; +template +constexpr bool expand_takes = requires(std::span o, piece k, bytes v) { + hash::hkdf_expand(o, k, v); + hash::hkdf_expand(o, k, {k}); + hash::hkdf_expand(o, k, hash::byte_pieces{}); + hash::hkdf_expand(o, k, hash::byte_pieces{piece(v)}); +}; + +template +constexpr bool whole_empty = + requires(std::span o, piece s) { hash::hkdf(o, s, {}, {}); }; +template +constexpr bool whole_vector = + requires(std::span o, piece s, bytes v) { hash::hkdf(o, s, {v}, {v}); }; +template +constexpr bool whole_array = requires(std::span o, piece s, bytes_array a) { + hash::hkdf(o, s, {a}, {a}); +}; +template +constexpr bool whole_takes = requires(std::span o, piece s, bytes v) { + hash::hkdf(o, s, v, v); + hash::hkdf(o, s, {s}, {s}); + hash::hkdf(o, s, hash::byte_pieces{}, hash::byte_pieces{}); + hash::hkdf(o, s, hash::byte_pieces{piece(v)}, hash::byte_pieces{piece(v)}); +}; + +using sha256 = hash::hmac_sha2_256; +static_assert(!extract_empty && !extract_vector && !extract_array); +static_assert(extract_takes); +static_assert(!expand_empty && !expand_vector && !expand_array); +static_assert(expand_takes); +static_assert(!whole_empty && !whole_vector && !whole_array); +static_assert(whole_takes); + +// The slices for_each_slice hands over, as (offset into the concatenation, size). +template +std::vector> slices_of(hash::byte_pieces pieces, + std::uint8_t const* origin) { + std::vector> slices; + detail::for_each_slice(pieces, [&](piece slice) { + slices.push_back({static_cast(slice.data() - origin), slice.size()}); + }); + return slices; +} + +// A slice of no byte would never advance: for_each_slice<0> does not compile. +template +constexpr bool sliceable = + requires(hash::byte_pieces pieces) { detail::for_each_slice(pieces, [](piece) {}); }; +static_assert(!sliceable<0> && sliceable<1>); + +// Each piece in slices of at most the maximum, in order, every byte once; an empty piece in none. +void slicing() { + std::array bytes{}; + piece const all(bytes); + using pairs = std::vector>; + BOOST_TEST((slices_of<3>({all}, bytes.data()) == pairs{{0, 3}, {3, 3}, {6, 3}, {9, 1}})); + BOOST_TEST((slices_of<10>({all}, bytes.data()) == pairs{{0, 10}})); + BOOST_TEST((slices_of<11>({all}, bytes.data()) == pairs{{0, 10}})); + BOOST_TEST((slices_of<4>({all.first(4), piece{}, all.subspan(4)}, bytes.data()) == + pairs{{0, 4}, {4, 4}, {8, 2}})); + BOOST_TEST((slices_of<1>({all.first(2), all.subspan(2, 1)}, bytes.data()) == + pairs{{0, 1}, {1, 1}, {2, 1}})); + BOOST_TEST((slices_of<1>({piece{}, piece{}}, bytes.data()).empty())); + BOOST_TEST((slices_of<1>({}, bytes.data()).empty())); + BOOST_TEST((slices_of::max()>({all}, bytes.data()) == + pairs{{0, 10}})); + + // backends::hash2's HMAC takes a size_t: its slice is a span's whole length (the test seam, + // which lowers it, is hkdf_pieces_sliced's). + BOOST_TEST_EQ(detail::hkdf_pieces_slice, + std::uint64_t{std::numeric_limits::max()}); +} + +} // namespace + +int main() { + binding(); + lone_span(); + slicing(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/capabilities_test.cpp b/test/capabilities_test.cpp index 486e484..0e7bbba 100644 --- a/test/capabilities_test.cpp +++ b/test/capabilities_test.cpp @@ -18,7 +18,9 @@ // builds on Emscripten alone, and is left out of the rows the synchronous refusals name. // backends::botan, which a build without exceptions cannot have ("exceptions_only"), has cells only // in a program that links Botan with exceptions (capabilities_botan): in any other, backend_has_v -// is false on every tag of it, and its targets need not hold this one. +// is false on every tag of it, and its targets need not hold this one. A row of a form of its +// function ("form": "pieces", HKDF over pieces) is keyed as " over
", has its own tag, +// and each of its backends has it over exactly the hmacs whose HMAC that backend has. #include #include @@ -96,7 +98,13 @@ struct joined, std::tuple> { using type = std::tuple; }; -using hmac_functions = joined>::type; +using hmac_functions = + joined>::type; + +// HKDF over pieces (design D4): each a row of its function's name with "form": "pieces". +using pieces_functions = + std::tuple; using plain_functions = std::tuple; @@ -118,6 +126,12 @@ constexpr std::string_view function_name() { return "bcrypt"; } else if constexpr (std::is_same_v) { return "bcrypt_pbkdf"; + } else if constexpr (std::is_same_v) { + return "hkdf_extract over pieces"; + } else if constexpr (std::is_same_v) { + return "hkdf_expand over pieces"; + } else if constexpr (std::is_same_v) { + return "hkdf over pieces"; } else { return test::name_of_operation(); } @@ -134,10 +148,20 @@ std::vector functions_of(json::object const& table) { return functions; } -// The row named `name`, or null when the file has none. +// A row's key: its name, and " over " for a row of a form of its function ("form": "pieces", +// HKDF over pieces), which shares the function's name. +std::string row_key(json::object const& function) { + std::string key(function.at("name").as_string()); + if (auto const* const form = function.if_contains("form")) { + key.append(" over ").append(form->as_string()); + } + return key; +} + +// The row whose key is `name`, or null when the file has none. json::object const* find_row(json::object const& table, std::string_view name) { for (auto const* function : functions_of(table)) { - if (function->at("name").as_string() == name) { + if (row_key(*function) == name) { return function; } } @@ -625,6 +649,16 @@ void report_differences(names const& in_file, names const& known) { } } +// A form is HKDF's pieces alone, on a row of a function the file has without it. +void check_forms(json::object const& table) { + for (auto const* function : functions_of(table)) { + if (auto const* const form = function->if_contains("form")) { + BOOST_TEST(form->is_string() && form->as_string() == "pieces"); + BOOST_TEST(find_row(table, function->at("name").as_string()) != nullptr); + } + } +} + // The file's lists against the test's: its backends, its hmacs, its functions. void check_names(json::object const& table) { std::vector backends; @@ -646,7 +680,7 @@ void check_names(json::object const& table) { names functions; for (auto const* function : functions_of(table)) { - functions.emplace(function->at("name").as_string()); + functions.emplace(row_key(*function)); for (auto const& backend : function->at("backends").as_object()) { BOOST_TEST((std::ranges::find(backends, std::string(backend.key())) != backends.end())); auto const& listed = backend.value().at("hmacs"); @@ -657,8 +691,21 @@ void check_names(json::object const& table) { } } names known_functions{ - "hkdf_extract", "hkdf_expand", "hkdf", "pbkdf2", "argon2id", "scrypt", - "blake2b_subkey", "kbkdf", "sskdf", "x963kdf", "bcrypt", "bcrypt_pbkdf", + "hkdf_extract", + "hkdf_expand", + "hkdf", + "hkdf_extract over pieces", + "hkdf_expand over pieces", + "hkdf over pieces", + "pbkdf2", + "argon2id", + "scrypt", + "blake2b_subkey", + "kbkdf", + "sskdf", + "x963kdf", + "bcrypt", + "bcrypt_pbkdf", }; for (auto const& row : type_rows()) { known_functions.emplace(row.name); @@ -783,6 +830,18 @@ std::vector const& refusals() { .functions = {"hkdf"}, .hmacs = {"*"}, }, + { + .header = "detail/engines.hpp", + .start = "this backend has no HMAC for HKDF over pieces.", + .backend = "", + .functions = + { + "hkdf_extract over pieces", + "hkdf_expand over pieces", + "hkdf over pieces", + }, + .hmacs = {"*"}, + }, { .header = "detail/engines.hpp", .start = "this backend has no PBKDF2.", @@ -919,6 +978,20 @@ std::vector const& refusals() { .functions = {}, .hmacs = {}, }, + { + .header = "async.hpp", + .start = "async_hkdf_extract takes hmac_sha1_160, hmac_sha2_256", + .backend = "", + .functions = {}, + .hmacs = {}, + }, + { + .header = "async.hpp", + .start = "async_hkdf_expand takes hmac_sha1_160, hmac_sha2_256", + .backend = "", + .functions = {}, + .hmacs = {}, + }, { .header = "async.hpp", .start = "async_pbkdf2 runs on another thread", @@ -1318,45 +1391,114 @@ struct hmac_digest> { using type = Digest; }; +// Whether the file's cell of backends::webcrypto in row `name`, column `hmac` ("" for a row +// without hmacs), is `expected`. +void check_webcrypto_cell(json::object const& table, std::string_view name, std::string_view hmac, + bool expected) { + auto const* const row = find_row(table, name); + bool const in_file = row != nullptr && cell(*row, "webcrypto", hmac); + if (!BOOST_TEST_EQ(in_file, expected)) { + std::cerr << " cell " << name << " / webcrypto / " << (hmac.empty() ? "-" : hmac) << '\n'; + } +} + +// The key derivations over an hmac that backends::webcrypto has: HKDF, its two steps, the three +// HKDF functions over pieces and PBKDF2. +using webcrypto_kdfs = + std::tuple; + +// backends::webcrypto's cell of Kdf over Hmac: there exactly for the hmacs of webcrypto_hmac_v, +// and never one of backend_has_v. +template +void check_webcrypto_kdf_cell(json::object const& table) { + check_webcrypto_cell(table, function_name(), test::name_of_hmac(), + hash::detail::webcrypto_hmac_v); + BOOST_TEST((!hash::backend_has_v)); +} + +// backends::webcrypto's cells of Kdf over every hmac column. +template +void check_webcrypto_kdf_cells(json::object const& table) { + [&](std::tuple*) { + (check_webcrypto_kdf_cell(table), ...); + }(static_cast(nullptr)); +} + // backends::webcrypto's cells (ruling R90): the digests and HMACs of async.hpp's -// webcrypto_digest_v, HKDF and PBKDF2 over the hmacs of webcrypto_hmac_v, nothing else; and no -// synchronous function takes it (backend_has_v is false for each of its cells). +// webcrypto_digest_v, HKDF, its two steps, the three HKDF functions over pieces and PBKDF2 over +// the hmacs of webcrypto_hmac_v, nothing else; and no synchronous function takes it +// (backend_has_v is false for each of its cells). void check_webcrypto_cells(json::object const& table) { using hash::backends::webcrypto; - auto const agrees = [&](std::string_view name, std::string_view hmac, bool expected) { - auto const* const row = find_row(table, name); - bool const in_file = row != nullptr && cell(*row, "webcrypto", hmac); - if (!BOOST_TEST_EQ(in_file, expected)) { - std::cerr << " cell " << name << " / webcrypto / " << (hmac.empty() ? "-" : hmac) - << '\n'; - } - }; for_each_tag(digest_names, [&](std::string_view name) { - agrees(name, "", hash::detail::webcrypto_digest_v); + check_webcrypto_cell(table, name, "", hash::detail::webcrypto_digest_v); BOOST_TEST((!hash::backend_has_v)); }); for_each_tag(mac_names, [&](std::string_view name) { - agrees(name, "", hash::detail::webcrypto_digest_v::type>); + check_webcrypto_cell(table, name, "", + hash::detail::webcrypto_digest_v::type>); BOOST_TEST((!hash::backend_has_v)); }); - for_each_tag(argon2_names, - [&](std::string_view name) { agrees(name, "", false); }); + for_each_tag(argon2_names, [&](std::string_view name) { + check_webcrypto_cell(table, name, "", false); + }); + [&](std::tuple*) { + (check_webcrypto_kdf_cells(table), ...); + }(static_cast(nullptr)); + check_webcrypto_cell(table, "argon2id", "", false); + check_webcrypto_cell(table, "scrypt", "", false); +} + +// Whether Backend has the HMAC of Hmac's column: macs::hmac for its digest's tag D; for a +// column without a tag (hmac_ripemd_128, "other"), Boost.Hash2's own hmac, which +// backends::hash2 alone has. +template +constexpr bool has_hmac() { + using digest = hash::detail::digest_tag_of::type; + if constexpr (std::is_void_v) { + return std::is_same_v; + } else { + return hash::backend_has_v, void>; + } +} + +// The pieces row `name` on Backend, where the row has a cell of it: over exactly the hmacs whose +// HMAC Backend has. +template +void check_pieces_cell(json::object const& row, std::string_view name) { + std::string_view const backend = test::name_of(); + auto const& backends = row.at("backends").as_object(); + if (!backends.contains(backend) || !cells_here()) { + return; + } [&](std::tuple*) { ( [&] { std::string_view const hmac = test::name_of_hmac(); - bool const has = hash::detail::webcrypto_hmac_v; - agrees("hkdf", hmac, has); - agrees("pbkdf2", hmac, has); - agrees("hkdf_extract", hmac, false); - agrees("hkdf_expand", hmac, false); - BOOST_TEST((!hash::backend_has_v)); - BOOST_TEST((!hash::backend_has_v)); + if (!BOOST_TEST_EQ(cell(row, backend, hmac), (has_hmac()))) { + std::cerr << " cell " << name << " / " << backend << " / " << hmac + << " against the backend's HMAC\n"; + } }(), ...); }(static_cast(nullptr)); - agrees("argon2id", "", false); - agrees("scrypt", "", false); +} + +// HKDF over pieces is wherever the backend's HMAC is (design D4): each backend of a pieces row has +// it over exactly the hmacs whose HMAC it has. +void check_pieces_cells(json::object const& table) { + [&](std::tuple*) { + ( + [&](F*) { + std::string_view const name = function_name(); + auto const& row = function_row(table, name); + [&](std::tuple*) { + (check_pieces_cell(row, name), ...); + }(static_cast(nullptr)); + }(static_cast(nullptr)), + ...); + }(static_cast(nullptr)); } } // namespace @@ -1369,11 +1511,13 @@ int main() { json::object const& table = parsed.as_object(); check_names(table); + check_forms(table); check_type_rows(table); check_backend_fields(table); check_defaults(table); check_cells(table); check_webcrypto_cells(table); + check_pieces_cells(table); check_refusals(table, include); check_families(table, include); return webcpp::test::exit_status(boost::report_errors()); diff --git a/test/families_test.cpp b/test/families_test.cpp index 70828e3..2d8f193 100644 --- a/test/families_test.cpp +++ b/test/families_test.cpp @@ -175,7 +175,7 @@ void check_argon2_guards() { test::mock_reset(); std::vector const password{1, 2, 3}; std::array const salt{}; - hash::argon2_parameters const fine{.passes = 3, .memory_kib = 64}; + hash::argon2_parameters const fine{.passes = 3, .memory_kibibytes = 64}; std::array output{}; BOOST_TEST((hash::argon2(output, password, salt, fine).has_value())); @@ -190,15 +190,16 @@ void check_argon2_guards() { BOOST_TEST(refuses(tiny, salt, fine, hash::error::invalid_output_size)); std::array short_salt{}; BOOST_TEST(refuses(output, short_salt, fine, hash::error::invalid_salt_size)); - BOOST_TEST( - refuses(output, salt, {.passes = 0, .memory_kib = 64}, hash::error::invalid_parameters)); - BOOST_TEST(refuses(output, salt, {.passes = 3, .memory_kib = 64, .lanes = 0}, + BOOST_TEST(refuses(output, salt, {.passes = 0, .memory_kibibytes = 64}, hash::error::invalid_parameters)); - BOOST_TEST(refuses(output, salt, {.passes = 3, .memory_kib = 1U << 30U, .lanes = 1U << 24U}, + BOOST_TEST(refuses(output, salt, {.passes = 3, .memory_kibibytes = 64, .lanes = 0}, hash::error::invalid_parameters)); - BOOST_TEST( - refuses(output, salt, {.passes = 3, .memory_kib = 7}, hash::error::invalid_parameters)); - BOOST_TEST(refuses(output, salt, {.passes = 3, .memory_kib = 15, .lanes = 2}, + BOOST_TEST(refuses(output, salt, + {.passes = 3, .memory_kibibytes = 1U << 30U, .lanes = 1U << 24U}, + hash::error::invalid_parameters)); + BOOST_TEST(refuses(output, salt, {.passes = 3, .memory_kibibytes = 7}, + hash::error::invalid_parameters)); + BOOST_TEST(refuses(output, salt, {.passes = 3, .memory_kibibytes = 15, .lanes = 2}, hash::error::invalid_parameters)); // Valid for RFC 9106, outside the engine's limits. @@ -206,22 +207,28 @@ void check_argon2_guards() { BOOST_TEST(refuses(rfc_shortest, salt, fine, hash::error::unsupported_by_backend)); std::array rfc_salt{}; BOOST_TEST(refuses(output, rfc_salt, fine, hash::error::unsupported_by_backend)); - BOOST_TEST(refuses(output, salt, {.passes = 2, .memory_kib = 64}, + BOOST_TEST(refuses(output, salt, {.passes = 2, .memory_kibibytes = 64}, hash::error::unsupported_by_backend)); - BOOST_TEST(refuses(output, salt, {.passes = 3, .memory_kib = 64, .lanes = 2}, + BOOST_TEST(refuses(output, salt, {.passes = 3, .memory_kibibytes = 64, .lanes = 2}, hash::error::unsupported_by_backend)); - BOOST_TEST(refuses(output, salt, {.passes = 3, .memory_kib = (1U << 20U) + 1U}, + BOOST_TEST(refuses(output, salt, {.passes = 3, .memory_kibibytes = (1U << 20U) + 1U}, hash::error::unsupported_by_backend)); std::array const extra{1, 2, 3, 4}; - BOOST_TEST(refuses(output, salt, {.passes = 3, .memory_kib = 64, .secret = extra}, + BOOST_TEST(refuses(output, salt, {.passes = 3, .memory_kibibytes = 64, .secret = extra}, hash::error::unsupported_by_backend)); - BOOST_TEST(refuses(output, salt, {.passes = 3, .memory_kib = 64, .associated_data = extra}, + BOOST_TEST(refuses(output, salt, + {.passes = 3, .memory_kibibytes = 64, .associated_data = extra}, hash::error::unsupported_by_backend)); // An engine with every parameter takes them; a failure zeroes the output. - auto const every = hash::argon2( - rfc_shortest, password, rfc_salt, - {.passes = 1, .memory_kib = 16, .lanes = 2, .secret = extra, .associated_data = extra}); + auto const every = hash::argon2(rfc_shortest, password, rfc_salt, + { + .passes = 1, + .memory_kibibytes = 16, + .lanes = 2, + .secret = extra, + .associated_data = extra, + }); BOOST_TEST(every.has_value()); test::mock_control.derive = hash::error::backend_failure; BOOST_TEST(failed_with(hash::argon2(output, password, salt, fine), diff --git a/test/hkdf_bearssl_test.cpp b/test/hkdf_bearssl_test.cpp index 2d1ddb1..3d65121 100644 --- a/test/hkdf_bearssl_test.cpp +++ b/test/hkdf_bearssl_test.cpp @@ -124,8 +124,8 @@ void guards() { constexpr std::uint8_t untouched = 0xaa; constexpr std::size_t most = std::size_t{255} * 32; const std::vector input(16, 0x0b); - const std::vector info_at_limit(hash::hkdf_max_info_size, 0x01); - const std::vector info_past_limit(hash::hkdf_max_info_size + 1, 0x01); + const std::vector info_at_limit(hash::hkdf_max_application_info_size, 0x01); + const std::vector info_past_limit(hash::hkdf_max_application_info_size + 1, 0x01); std::vector buffer(most + 2, untouched); const auto refused = [&](std::size_t size, std::span info) { diff --git a/test/hkdf_openssl_test.cpp b/test/hkdf_openssl_test.cpp index a43bd7c..7e059a7 100644 --- a/test/hkdf_openssl_test.cpp +++ b/test/hkdf_openssl_test.cpp @@ -198,12 +198,12 @@ bool is_untouched(std::span bytes) { return std::ranges::all_of(bytes, [](std::uint8_t b) { return b == untouched; }); } -// The info of hkdf_max_info_size bytes reaches OpenSSL and agrees with backends::hash2. +// The info of hkdf_max_application_info_size bytes reaches OpenSSL and agrees with backends::hash2. void longest_info() { using hmac = hash::hmac_sha2_256; const auto ikm = pattern(22, 2); const auto prk = pattern(32, 4); - const auto info = pattern(hash::hkdf_max_info_size, 3); + const auto info = pattern(hash::hkdf_max_application_info_size, 3); std::vector expected(42); BOOST_TEST((hash::hkdf_expand(expected, prk, info).has_value())); std::vector expanded(42, untouched); @@ -222,7 +222,7 @@ void info_too_long() { using hmac = hash::hmac_sha2_256; const auto ikm = pattern(22, 2); const auto prk = pattern(32, 4); - const auto info = pattern(hash::hkdf_max_info_size + 1, 3); + const auto info = pattern(hash::hkdf_max_application_info_size + 1, 3); std::vector output(42, untouched); auto refused = hash::hkdf_expand(output, prk, info); BOOST_TEST(refused.has_error() && refused.error() == hash::error::input_too_long); diff --git a/test/hkdf_pieces_bearssl_test.cpp b/test/hkdf_pieces_bearssl_test.cpp new file mode 100644 index 0000000..6fdb8c3 --- /dev/null +++ b/test/hkdf_pieces_bearssl_test.cpp @@ -0,0 +1,156 @@ +// 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) + +// HKDF over pieces on backends::bearssl (design D2, D4, D8 of the change hkdf-pieces), over +// BearSSL's br_hmac_key_init, br_hmac_init, br_hmac_update and br_hmac_out: hkdf_extract, +// hkdf_expand and hkdf over byte_pieces give the bytes of backends::hash2's single-buffer forms on +// the concatenation (and of BearSSL's own hkdf), with RFC 5869's cases, random splits, empty pieces +// and lists, many pieces and long inputs, and refuse only RFC 5869's sizes +// (support/hkdf_pieces.hpp), over BearSSL's six hmacs, MD5, SHA-1 and SHA-224 to SHA-512. BearSSL +// gains Extract and Expand over pieces, while its single-buffer hkdf_extract and hkdf_expand stay +// refused (test/messages/extract_on_bearssl and expand_on_bearssl): the spec's scenario +// hkdf_extract(salt, {a, b}). Each step wipes BearSSL's HMAC +// contexts, its key contexts, every block T(i) and the pseudorandom key between the steps, +// reported through the seam WEBCPP_HASH_DETAIL_TEST_WIPE_RECORD; a guard's refusal wipes nothing. +// Built again as hkdf_pieces_bearssl_sliced with the test seam +// WEBCPP_HASH_DETAIL_TEST_HKDF_PIECES_SLICE, which makes the engine feed every piece to BearSSL in +// slices of a few bytes (Review Focus 4), over hmac_sha2_256: the bytes are the same, 1 MiB pieces +// included. + +#include "support/hkdf_pieces.hpp" +#include "support/wipe_record.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +#ifndef WEBCPP_HASH_DETAIL_TEST_WIPE_RECORD +#error "hkdf_pieces_bearssl_test is built with WEBCPP_HASH_DETAIL_TEST_WIPE_RECORD (test/Jamfile)" +#endif + +namespace hash = webcpp::hash; +namespace test = webcpp::test; + +namespace { + +using hash::backends::bearssl; + +// The pieces cells are BearSSL's HMAC cells, its six hmacs, for all three forms: Extract and +// Expand over pieces included, while the single-buffer Extract and Expand stay refused. +template +constexpr bool has_pieces = hash::backend_has_v && + hash::backend_has_v && + hash::backend_has_v; +static_assert(has_pieces); +static_assert(has_pieces); +static_assert(has_pieces); +static_assert(has_pieces); +static_assert(has_pieces); +static_assert(has_pieces); +static_assert(!hash::backend_has_v); +static_assert(!hash::backend_has_v); +static_assert(!hash::backend_has_v); +static_assert(!hash::backend_has_v); +static_assert(!hash::backend_has_v); + +// The spec's scenario "BearSSL's Extract over pieces": hkdf_extract over {a, b} on BearSSL compiles +// and gives backends::hash2's pseudorandom key of a's and b's bytes. +void check_extract_scenario() { + std::vector const salt{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06}; + std::vector const a{0x0b, 0x0b, 0x0b, 0x0b, 0x0b}; + std::vector const b{0x0c, 0x0c, 0x0c}; + auto const by_bearssl = hash::hkdf_extract(salt, {a, b}); + std::vector joined = a; + joined.insert(joined.end(), b.begin(), b.end()); + auto const by_hash2 = + hash::hkdf_extract(salt, joined); + BOOST_TEST(by_bearssl.has_value()); + BOOST_TEST(by_hash2.has_value()); + if (by_bearssl && by_hash2) { + BOOST_TEST(std::ranges::equal(*by_bearssl, *by_hash2)); + } + test::clear_wipes(); +} + +// The wipes of the three steps over Hmac, with an output of two blocks: Extract wipes its HMAC +// context and its key context; Expand each block's HMAC context, then T and the key context of the +// PRK; hkdf both, then the PRK. A guard's refusal wipes nothing. +template +void check_wipes() { + constexpr std::size_t mac = sizeof(br_hmac_context); + constexpr std::size_t key = sizeof(br_hmac_key_context); + constexpr std::size_t digest = typename Hmac::result_type().size(); + using piece = std::span; + std::vector const salt(13, 0x01); + std::vector const ikm(22, 0x0b); + std::vector const info(10, 0xf0); + std::array const ikm_pieces{piece(ikm).first(5), piece{}, piece(ikm).subspan(5)}; + std::array const info_pieces{piece(info).first(3), piece(info).subspan(3)}; + std::vector output(digest + 10); + test::clear_wipes(); + + auto const prk = hash::hkdf_extract(salt, ikm_pieces); + BOOST_TEST(prk.has_value()); + BOOST_TEST((test::wiped_sizes() == std::vector{mac, key})); + + std::vector const pseudorandom_key(prk->begin(), prk->end()); + BOOST_TEST( + (hash::hkdf_expand(output, pseudorandom_key, info_pieces).has_value())); + BOOST_TEST((test::wiped_sizes() == std::vector{mac, mac, digest, key})); + + BOOST_TEST((hash::hkdf(output, salt, ikm_pieces, info_pieces).has_value())); + BOOST_TEST( + (test::wiped_sizes() == std::vector{mac, key, mac, mac, digest, key, digest})); + + BOOST_TEST((hash::hkdf_expand(output, salt, info_pieces).has_error())); + BOOST_TEST((hash::hkdf(std::span{}, salt, ikm_pieces, info_pieces) + .has_error())); + BOOST_TEST(test::wiped_sizes().empty()); +} + +} // namespace + +int main() { + std::cout << "backends::bearssl feeds its HMAC slices of at most " + << hash::detail::hkdf_pieces_slice << " bytes\n"; + check_extract_scenario(); +#ifdef WEBCPP_HASH_DETAIL_TEST_HKDF_PIECES_SLICE + // The slicing is the engine's, whatever the hmac. + BOOST_TEST_EQ(hash::detail::hkdf_pieces_slice, + std::uint64_t{WEBCPP_HASH_DETAIL_TEST_HKDF_PIECES_SLICE}); + test::check_hkdf_pieces("bearssl"); +#else + test::check_hkdf_pieces("bearssl"); + test::check_hkdf_pieces("bearssl"); + test::check_hkdf_pieces("bearssl"); + test::check_hkdf_pieces("bearssl"); + test::check_hkdf_pieces("bearssl"); + test::check_hkdf_pieces("bearssl"); +#endif + check_wipes(); + check_wipes(); + check_wipes(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/hkdf_pieces_botan_test.cpp b/test/hkdf_pieces_botan_test.cpp new file mode 100644 index 0000000..7f7fa71 --- /dev/null +++ b/test/hkdf_pieces_botan_test.cpp @@ -0,0 +1,174 @@ +// 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) + +// HKDF over pieces on backends::botan (design D2, D4, D8 of the change hkdf-pieces), over Botan's +// MessageAuthenticationCode "HMAC()" (set_key, update, final, re-keyed for each block by +// clear and set_key): hkdf_extract, hkdf_expand and hkdf over byte_pieces give the bytes of the +// single-buffer forms on the concatenation, those of backends::hash2 and of Botan's own HKDF, with +// RFC 5869's cases, random splits, empty pieces and lists, many pieces and long inputs, and refuse +// only RFC 5869's sizes (support/hkdf_pieces.hpp), over the 14 hmacs of Botan's HMAC cells, every +// hmac of hmac.hpp but hmac_ripemd_128 and hmac_sha2_512_224. The cells equal those of kdfs::hkdf. +// A salt longer than the 8,192 bytes Botan's HMAC takes as a key is hashed first, as RFC 2104 does, +// and gives the same pseudorandom key. Botan's HMAC object is cleared (its clear()) and freed; hash +// wipes the digest room of a long salt, each block T(i) and the pseudorandom key between the steps, +// reported through the seam WEBCPP_HASH_DETAIL_TEST_WIPE_RECORD; a guard's refusal wipes nothing. +// Built again as hkdf_pieces_botan_sliced with the test seam +// WEBCPP_HASH_DETAIL_TEST_HKDF_PIECES_SLICE, which makes the engine feed every piece to Botan in +// slices of a few bytes (Review Focus 4), over hmac_sha2_256: the bytes are the same, 1 MiB pieces +// included. + +#include "support/hkdf_pieces.hpp" +#include "support/wipe_record.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +#ifndef WEBCPP_HASH_DETAIL_TEST_WIPE_RECORD +#error "hkdf_pieces_botan_test is built with WEBCPP_HASH_DETAIL_TEST_WIPE_RECORD (test/Jamfile)" +#endif + +namespace hash = webcpp::hash; +namespace test = webcpp::test; + +namespace { + +using hash::backends::botan; + +// The pieces cells are Botan's HMAC cells, those of kdfs::hkdf: every hmac of hmac.hpp but +// hmac_ripemd_128 and hmac_sha2_512_224, for all three forms. +template +constexpr bool has_pieces = hash::backend_has_v && + hash::backend_has_v && + hash::backend_has_v; +static_assert(has_pieces); +static_assert(has_pieces); +static_assert(has_pieces); +static_assert(has_pieces); +static_assert(has_pieces); +static_assert(has_pieces); +static_assert(has_pieces); +static_assert(has_pieces); +static_assert(has_pieces); +static_assert(has_pieces); +static_assert(has_pieces); +static_assert(has_pieces); +static_assert(has_pieces); +static_assert(has_pieces); +static_assert(!hash::backend_has_v); +static_assert( + !hash::backend_has_v); +static_assert(!hash::backend_has_v); + +// The room of a long salt's digest (detail::botan_keyed), wiped by every Extract. +constexpr std::size_t hashed_room = 64; + +// The wipes of the three steps over Hmac, with an output of two blocks: Extract wipes the room of a +// long salt's digest, which it always has, and writes the PRK into its result; Expand wipes T after +// its blocks; hkdf both, then the PRK. A guard's refusal wipes nothing. +template +void check_wipes() { + constexpr std::size_t digest = typename Hmac::result_type().size(); + using piece = std::span; + std::vector const salt(13, 0x01); + std::vector const ikm(22, 0x0b); + std::vector const info(10, 0xf0); + std::array const ikm_pieces{piece(ikm).first(5), piece{}, piece(ikm).subspan(5)}; + std::array const info_pieces{piece(info).first(3), piece(info).subspan(3)}; + std::vector output(digest + 10); + test::clear_wipes(); + + auto const prk = hash::hkdf_extract(salt, ikm_pieces); + BOOST_TEST(prk.has_value()); + BOOST_TEST((test::wiped_sizes() == std::vector{hashed_room})); + + std::vector const pseudorandom_key(prk->begin(), prk->end()); + BOOST_TEST((hash::hkdf_expand(output, pseudorandom_key, info_pieces).has_value())); + BOOST_TEST((test::wiped_sizes() == std::vector{digest})); + + BOOST_TEST((hash::hkdf(output, salt, ikm_pieces, info_pieces).has_value())); + BOOST_TEST((test::wiped_sizes() == std::vector{hashed_room, digest, digest})); + + BOOST_TEST((hash::hkdf_expand(output, salt, info_pieces).has_error())); + BOOST_TEST((hash::hkdf(std::span{}, salt, ikm_pieces, info_pieces) + .has_error())); + BOOST_TEST(test::wiped_sizes().empty()); +} + +// A salt longer than Botan's HMAC takes as a key (8,192 bytes) is hashed first, as HMAC hashes +// every key longer than its block: the bytes of backends::hash2, through Extract and hkdf. +template +void check_long_salt() { + using piece = std::span; + std::vector const salt(8193, 0x5a); + std::vector const ikm(22, 0x0b); + std::vector const info(10, 0xf0); + std::array const ikm_pieces{piece(ikm).first(7), piece(ikm).subspan(7)}; + std::array const info_pieces{piece(info).first(4), piece(info).subspan(4)}; + auto const by_botan = hash::hkdf_extract(salt, ikm_pieces); + auto const by_hash2 = hash::hkdf_extract(salt, ikm); + BOOST_TEST(by_botan.has_value() && by_hash2.has_value()); + if (by_botan && by_hash2) { + BOOST_TEST(std::ranges::equal(*by_botan, *by_hash2)); + } + std::vector whole_by_botan(100); + std::vector whole_by_hash2(100); + BOOST_TEST((hash::hkdf(whole_by_botan, salt, ikm_pieces, info_pieces))); + BOOST_TEST((hash::hkdf(whole_by_hash2, salt, ikm, info))); + BOOST_TEST(whole_by_botan == whole_by_hash2); + test::clear_wipes(); +} + +} // namespace + +int main() { + std::cout << "backends::botan feeds its HMAC slices of at most " + << hash::detail::hkdf_pieces_slice << " bytes\n"; +#ifdef WEBCPP_HASH_DETAIL_TEST_HKDF_PIECES_SLICE + // The slicing is the engine's, whatever the hmac. + BOOST_TEST_EQ(hash::detail::hkdf_pieces_slice, + std::uint64_t{WEBCPP_HASH_DETAIL_TEST_HKDF_PIECES_SLICE}); + test::check_hkdf_pieces("botan"); +#else + test::check_hkdf_pieces("botan"); + test::check_hkdf_pieces("botan"); + test::check_hkdf_pieces("botan"); + test::check_hkdf_pieces("botan"); + test::check_hkdf_pieces("botan"); + test::check_hkdf_pieces("botan"); + test::check_hkdf_pieces("botan"); + test::check_hkdf_pieces("botan"); + test::check_hkdf_pieces("botan"); + test::check_hkdf_pieces("botan"); + test::check_hkdf_pieces("botan"); + test::check_hkdf_pieces("botan"); + test::check_hkdf_pieces("botan"); + test::check_hkdf_pieces("botan"); +#endif + check_long_salt(); + check_long_salt(); + check_wipes(); + check_wipes(); + check_wipes(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/hkdf_pieces_openssl_test.cpp b/test/hkdf_pieces_openssl_test.cpp new file mode 100644 index 0000000..937cc8c --- /dev/null +++ b/test/hkdf_pieces_openssl_test.cpp @@ -0,0 +1,150 @@ +// 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) + +// HKDF over pieces on backends::openssl (design D2, D4, D8 of the change hkdf-pieces), over +// OpenSSL's EVP_MAC "HMAC" (EVP_MAC_init with the digest's name, EVP_MAC_update, EVP_MAC_final, +// the context keyed by the pseudorandom key duplicated by EVP_MAC_CTX_dup for each block): +// hkdf_extract, hkdf_expand and hkdf over byte_pieces give the bytes of the single-buffer forms on +// the concatenation, those of backends::hash2 and of OpenSSL's own EVP_KDF "HKDF", with RFC 5869's +// cases, random splits, empty pieces and lists, many pieces and long inputs, and refuse only RFC +// 5869's sizes (support/hkdf_pieces.hpp), over the 15 hmacs of OpenSSL's HMAC cells, every hmac of +// hmac.hpp but hmac_ripemd_128. The cells equal those of kdfs::hkdf. OpenSSL's contexts are its +// own, freed by EVP_MAC_CTX_free; hash wipes each block T(i) and the pseudorandom key between the +// steps, reported through the seam WEBCPP_HASH_DETAIL_TEST_WIPE_RECORD; a guard's refusal wipes +// nothing; the thread's error queue is left empty. Built again as hkdf_pieces_openssl_sliced with +// the test seam WEBCPP_HASH_DETAIL_TEST_HKDF_PIECES_SLICE, which makes the engine feed every piece +// to OpenSSL in slices of a few bytes (Review Focus 4), over hmac_sha2_256: the bytes are the same, +// 1 MiB pieces included. + +#include "support/hkdf_pieces.hpp" +#include "support/wipe_record.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +#include + +#include +#include +#include +#include +#include +#include + +#ifndef WEBCPP_HASH_DETAIL_TEST_WIPE_RECORD +#error "hkdf_pieces_openssl_test is built with WEBCPP_HASH_DETAIL_TEST_WIPE_RECORD (test/Jamfile)" +#endif + +namespace hash = webcpp::hash; +namespace test = webcpp::test; + +namespace { + +using hash::backends::openssl; + +// The pieces cells are OpenSSL's HMAC cells, those of kdfs::hkdf: every hmac of hmac.hpp but +// hmac_ripemd_128, for all three forms. +template +constexpr bool has_pieces = hash::backend_has_v && + hash::backend_has_v && + hash::backend_has_v; +static_assert(has_pieces); +static_assert(has_pieces); +static_assert(has_pieces); +static_assert(has_pieces); +static_assert(has_pieces); +static_assert(has_pieces); +static_assert(has_pieces); +static_assert(has_pieces); +static_assert(has_pieces); +static_assert(has_pieces); +static_assert(has_pieces); +static_assert(has_pieces); +static_assert(has_pieces); +static_assert(has_pieces); +static_assert(has_pieces); +static_assert(!hash::backend_has_v); +static_assert( + !hash::backend_has_v); +static_assert(!hash::backend_has_v); + +// The wipes of the three steps over Hmac, with an output of two blocks: Extract writes the PRK +// into its result and wipes nothing of hash's (OpenSSL's context is freed by EVP_MAC_CTX_free); +// Expand wipes T after its blocks; hkdf wipes T, then the PRK. A guard's refusal wipes nothing. +// The thread's error queue stays empty. +template +void check_wipes() { + constexpr std::size_t digest = typename Hmac::result_type().size(); + using piece = std::span; + std::vector const salt(13, 0x01); + std::vector const ikm(22, 0x0b); + std::vector const info(10, 0xf0); + std::array const ikm_pieces{piece(ikm).first(5), piece{}, piece(ikm).subspan(5)}; + std::array const info_pieces{piece(info).first(3), piece(info).subspan(3)}; + std::vector output(digest + 10); + test::clear_wipes(); + + auto const prk = hash::hkdf_extract(salt, ikm_pieces); + BOOST_TEST(prk.has_value()); + BOOST_TEST(test::wiped_sizes().empty()); + + std::vector const pseudorandom_key(prk->begin(), prk->end()); + BOOST_TEST( + (hash::hkdf_expand(output, pseudorandom_key, info_pieces).has_value())); + BOOST_TEST((test::wiped_sizes() == std::vector{digest})); + + BOOST_TEST((hash::hkdf(output, salt, ikm_pieces, info_pieces).has_value())); + BOOST_TEST((test::wiped_sizes() == std::vector{digest, digest})); + + BOOST_TEST((hash::hkdf_expand(output, salt, info_pieces).has_error())); + BOOST_TEST((hash::hkdf(std::span{}, salt, ikm_pieces, info_pieces) + .has_error())); + BOOST_TEST(test::wiped_sizes().empty()); + BOOST_TEST_EQ(ERR_peek_error(), 0UL); +} + +} // namespace + +int main() { + std::cout << "backends::openssl feeds its HMAC slices of at most " + << hash::detail::hkdf_pieces_slice << " bytes\n"; +#ifdef WEBCPP_HASH_DETAIL_TEST_HKDF_PIECES_SLICE + // The slicing is the engine's, whatever the hmac. + BOOST_TEST_EQ(hash::detail::hkdf_pieces_slice, + std::uint64_t{WEBCPP_HASH_DETAIL_TEST_HKDF_PIECES_SLICE}); + test::check_hkdf_pieces("openssl"); +#else + test::check_hkdf_pieces("openssl"); + test::check_hkdf_pieces("openssl"); + test::check_hkdf_pieces("openssl"); + test::check_hkdf_pieces("openssl"); + test::check_hkdf_pieces("openssl"); + test::check_hkdf_pieces("openssl"); + test::check_hkdf_pieces("openssl"); + test::check_hkdf_pieces("openssl"); + test::check_hkdf_pieces("openssl"); + test::check_hkdf_pieces("openssl"); + test::check_hkdf_pieces("openssl"); + test::check_hkdf_pieces("openssl"); + test::check_hkdf_pieces("openssl"); + test::check_hkdf_pieces("openssl"); + test::check_hkdf_pieces("openssl"); +#endif + check_wipes(); + check_wipes(); + check_wipes(); + BOOST_TEST_EQ(ERR_peek_error(), 0UL); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/hkdf_pieces_sodium_test.cpp b/test/hkdf_pieces_sodium_test.cpp new file mode 100644 index 0000000..eebd0ed --- /dev/null +++ b/test/hkdf_pieces_sodium_test.cpp @@ -0,0 +1,127 @@ +// 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) + +// HKDF over pieces on backends::sodium (design D2, D4, D8 of the change hkdf-pieces), over +// libsodium's crypto_auth_hmacsha256_* and crypto_auth_hmacsha512_*: hkdf_extract, hkdf_expand and +// hkdf over byte_pieces give the bytes of the single-buffer forms on the concatenation, those of +// backends::hash2 and of libsodium's own HKDF, with RFC 5869's cases, random splits, empty pieces +// and lists, many pieces and long inputs, and refuse only RFC 5869's sizes +// (support/hkdf_pieces.hpp), over hmac_sha2_256 and hmac_sha2_512, the hmacs of libsodium's HMAC +// cells. The cells equal those of kdfs::hkdf. Each step wipes libsodium's HMAC states, every +// block T(i) and the pseudorandom key between the steps, reported through the seam +// WEBCPP_HASH_DETAIL_TEST_WIPE_RECORD; a guard's refusal wipes nothing. Built again as +// hkdf_pieces_sodium_sliced with the test seam WEBCPP_HASH_DETAIL_TEST_HKDF_PIECES_SLICE, which +// makes the engine feed every piece to libsodium in slices of a few bytes (Review Focus 4), over +// hmac_sha2_256: the bytes are the same, 1 MiB pieces included. hkdf_pieces_sodium_sha512_sliced +// is the same over hmac_sha2_512 (WEBCPP_HASH_DETAIL_TEST_SLICED_HMAC_SHA2_512), whose 128-byte +// block meets the slice boundaries differently. + +#include "support/hkdf_pieces.hpp" +#include "support/wipe_record.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include + +#ifndef WEBCPP_HASH_DETAIL_TEST_WIPE_RECORD +#error "hkdf_pieces_sodium_test is built with WEBCPP_HASH_DETAIL_TEST_WIPE_RECORD (test/Jamfile)" +#endif + +namespace hash = webcpp::hash; +namespace test = webcpp::test; + +namespace { + +using hash::backends::sodium; + +// The pieces cells are libsodium's HMAC cells, those of kdfs::hkdf: SHA-256 and SHA-512 alone. +template +constexpr bool has_pieces = hash::backend_has_v && + hash::backend_has_v && + hash::backend_has_v; +static_assert(has_pieces); +static_assert(has_pieces); +static_assert(!hash::backend_has_v); +static_assert(!hash::backend_has_v); +static_assert(!hash::backend_has_v); + +// The wipes of the three steps, over Hmac and libsodium's State, with an output of two blocks: +// Extract wipes its HMAC state; Expand each block's state, then T and the state keyed by the PRK; +// hkdf both, then the PRK. A guard's refusal wipes nothing. +template +void check_wipes() { + constexpr std::size_t state = sizeof(State); + constexpr std::size_t digest = typename Hmac::result_type().size(); + using piece = std::span; + std::vector const salt(13, 0x01); + std::vector const ikm(22, 0x0b); + std::vector const info(10, 0xf0); + std::array const ikm_pieces{piece(ikm).first(5), piece{}, piece(ikm).subspan(5)}; + std::array const info_pieces{piece(info).first(3), piece(info).subspan(3)}; + std::vector output(digest + 10); + test::clear_wipes(); + + auto const prk = hash::hkdf_extract(salt, ikm_pieces); + BOOST_TEST(prk.has_value()); + BOOST_TEST((test::wiped_sizes() == std::vector{state})); + + std::vector const pseudorandom_key(prk->begin(), prk->end()); + BOOST_TEST( + (hash::hkdf_expand(output, pseudorandom_key, info_pieces).has_value())); + BOOST_TEST((test::wiped_sizes() == std::vector{state, state, digest, state})); + + BOOST_TEST((hash::hkdf(output, salt, ikm_pieces, info_pieces).has_value())); + BOOST_TEST((test::wiped_sizes() == + std::vector{state, state, state, digest, state, digest})); + + BOOST_TEST((hash::hkdf_expand(output, salt, info_pieces).has_error())); + BOOST_TEST((hash::hkdf(std::span{}, salt, ikm_pieces, info_pieces) + .has_error())); + BOOST_TEST(test::wiped_sizes().empty()); +} + +} // namespace + +int main() { + std::cout << "backends::sodium feeds its HMAC slices of at most " + << hash::detail::hkdf_pieces_slice << " bytes\n"; +#ifdef WEBCPP_HASH_DETAIL_TEST_HKDF_PIECES_SLICE + // The slicing is the engine's, whatever the hmac. + BOOST_TEST_EQ(hash::detail::hkdf_pieces_slice, + std::uint64_t{WEBCPP_HASH_DETAIL_TEST_HKDF_PIECES_SLICE}); +#ifdef WEBCPP_HASH_DETAIL_TEST_SLICED_HMAC_SHA2_512 + // The 128-byte block of SHA-512 against the same slice boundaries. + test::check_hkdf_pieces("sodium"); +#else + test::check_hkdf_pieces("sodium"); +#endif +#else + test::check_hkdf_pieces("sodium"); + test::check_hkdf_pieces("sodium"); +#endif + check_wipes(); + check_wipes(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/hkdf_pieces_test.cpp b/test/hkdf_pieces_test.cpp new file mode 100644 index 0000000..4e50cde --- /dev/null +++ b/test/hkdf_pieces_test.cpp @@ -0,0 +1,53 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// HKDF over pieces on backends::hash2 (design D2, D8): hkdf_extract, hkdf_expand and hkdf over +// byte_pieces give the single-buffer forms' bytes on the concatenation, with RFC 5869's cases, +// random splits, empty pieces and lists, many pieces and long inputs, and refuse only RFC 5869's +// sizes (support/hkdf_pieces.hpp), over SHA-1, SHA-256, SHA-384, SHA-512, SHA3-256, MD5 and an +// hmac over another Hash2 hash. Built again as hkdf_pieces_sliced with the test seam +// WEBCPP_HASH_DETAIL_TEST_HKDF_PIECES_SLICE, which makes the engine feed every piece to the HMAC in +// slices of a few bytes (Review Focus 4), over SHA-256 and the other hash: the bytes are the +// same, 1 MiB pieces included. + +#include "support/hkdf_pieces.hpp" + +#include +#include +#include +#include + +#include + +#include + +#include +#include + +namespace hash = webcpp::hash; +namespace test = webcpp::test; + +int main() { + using hash::backends::hash2; + std::cout << "backends::hash2 feeds its HMAC slices of at most " + << hash::detail::hkdf_pieces_slice << " bytes\n"; +#ifdef WEBCPP_HASH_DETAIL_TEST_HKDF_PIECES_SLICE + // The slicing is the engine's, whatever the hmac: two hmacs, one of an alias and the other's. + BOOST_TEST_EQ(hash::detail::hkdf_pieces_slice, + std::uint64_t{WEBCPP_HASH_DETAIL_TEST_HKDF_PIECES_SLICE}); + test::check_hkdf_pieces("hash2"); + test::check_hkdf_pieces, hash2>("hash2"); +#else + test::check_hkdf_pieces("hash2"); + test::check_hkdf_pieces("hash2"); + test::check_hkdf_pieces("hash2"); + test::check_hkdf_pieces("hash2"); + test::check_hkdf_pieces("hash2"); + test::check_hkdf_pieces("hash2"); + test::check_hkdf_pieces, hash2>("hash2"); +#endif + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/kdfs_botan_test.cpp b/test/kdfs_botan_test.cpp index fbb1c0c..52f8b89 100644 --- a/test/kdfs_botan_test.cpp +++ b/test/kdfs_botan_test.cpp @@ -219,8 +219,8 @@ bytes pattern(std::size_t size, unsigned seed) { } // Spec 2.8: an output of 0 or more than 255 digests, a PRK of another size than the digest's and -// an info of more than hkdf_max_info_size bytes, refused before Botan, the output untouched; the -// longest output and the longest info computed, as backends::hash2 computes them. +// an info of more than hkdf_max_application_info_size bytes, refused before Botan, the output +// untouched; the longest output and the longest info computed, as backends::hash2 computes them. void check_hkdf_guards() { using hmac = hash::hmac_sha2_256; constexpr std::size_t h = digest_size; @@ -242,14 +242,14 @@ void check_hkdf_guards() { hash::error::invalid_key_size)); BOOST_TEST(failed_with(hash::hkdf_expand(output, pattern(h + 1, 4), info), hash::error::invalid_key_size)); - bytes const too_much_info = pattern(hash::hkdf_max_info_size + 1, 3); + bytes const too_much_info = pattern(hash::hkdf_max_application_info_size + 1, 3); BOOST_TEST(failed_with(hash::hkdf(output, salt, ikm, too_much_info), hash::error::input_too_long)); BOOST_TEST(failed_with(hash::hkdf_expand(output, prk, too_much_info), hash::error::input_too_long)); BOOST_TEST(all_of(output, untouched)); - bytes const longest_info = pattern(hash::hkdf_max_info_size, 3); + bytes const longest_info = pattern(hash::hkdf_max_application_info_size, 3); for (std::size_t const size : {std::size_t{1}, 255 * h}) { bytes expected(size); bytes derived(size, untouched); diff --git a/test/messages/Jamfile b/test/messages/Jamfile index f3c0683..bec50c8 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -13,6 +13,7 @@ build-project xkcp_not_linked ; build-project blake3_not_linked ; build-project bearssl_not_linked ; build-project expand_on_bearssl ; +build-project extract_on_bearssl ; build-project bearssl_hmac ; build-project pbkdf2_on_bearssl ; build-project sodium_not_linked ; diff --git a/test/messages/argon2_no_default/argon2_no_default.cpp b/test/messages/argon2_no_default/argon2_no_default.cpp index f768d9f..b874106 100644 --- a/test/messages/argon2_no_default/argon2_no_default.cpp +++ b/test/messages/argon2_no_default/argon2_no_default.cpp @@ -20,6 +20,6 @@ int main() { std::array output{}; std::array salt{}; auto done = webcpp::hash::argon2( - output, {}, salt, {.passes = 3, .memory_kib = 65536}); + output, {}, salt, {.passes = 3, .memory_kibibytes = 65536}); return done ? 0 : 1; } diff --git a/test/messages/argon2_not_a_variant/argon2_not_a_variant.cpp b/test/messages/argon2_not_a_variant/argon2_not_a_variant.cpp index 5e0695f..22846ee 100644 --- a/test/messages/argon2_not_a_variant/argon2_not_a_variant.cpp +++ b/test/messages/argon2_not_a_variant/argon2_not_a_variant.cpp @@ -19,6 +19,7 @@ int main() { std::array output{}; std::array salt{}; - auto done = webcpp::hash::argon2(output, {}, salt, {.passes = 3, .memory_kib = 65536}); + auto done = + webcpp::hash::argon2(output, {}, salt, {.passes = 3, .memory_kibibytes = 65536}); return done ? 0 : 1; } diff --git a/test/messages/argon2d_on_sodium/argon2d_on_sodium.cpp b/test/messages/argon2d_on_sodium/argon2d_on_sodium.cpp index 6d29ae4..0a950c1 100644 --- a/test/messages/argon2d_on_sodium/argon2d_on_sodium.cpp +++ b/test/messages/argon2d_on_sodium/argon2d_on_sodium.cpp @@ -21,6 +21,6 @@ int main() { std::array output{}; std::array salt{}; auto done = webcpp::hash::argon2( - output, {}, salt, {.passes = 3, .memory_kib = 65536}); + output, {}, salt, {.passes = 3, .memory_kibibytes = 65536}); return done ? 0 : 1; } diff --git a/test/messages/async_argon2_without_threads/async_argon2_without_threads.cpp b/test/messages/async_argon2_without_threads/async_argon2_without_threads.cpp index aa7c010..936cf11 100644 --- a/test/messages/async_argon2_without_threads/async_argon2_without_threads.cpp +++ b/test/messages/async_argon2_without_threads/async_argon2_without_threads.cpp @@ -29,7 +29,7 @@ int main() { std::array const salt{}; webcpp::hash::async_argon2( context.get_executor(), output, {}, salt, - webcpp::hash::argon2_parameters{.passes = 3, .memory_kib = 65536}, + webcpp::hash::argon2_parameters{.passes = 3, .memory_kibibytes = 65536}, [](boost::system::error_code /*code*/) {}); return 0; } diff --git a/test/messages/async_hkdf_not_in_webcrypto/async_hkdf_not_in_webcrypto.cpp b/test/messages/async_hkdf_not_in_webcrypto/async_hkdf_not_in_webcrypto.cpp index 7c0e5c7..fec71b4 100644 --- a/test/messages/async_hkdf_not_in_webcrypto/async_hkdf_not_in_webcrypto.cpp +++ b/test/messages/async_hkdf_not_in_webcrypto/async_hkdf_not_in_webcrypto.cpp @@ -25,7 +25,9 @@ int main() { webcpp::asio::io_context context; std::array output{}; + std::array input{}; webcpp::hash::async_hkdf( - context.get_executor(), output, {}, {}, {}, [](boost::system::error_code /*code*/) {}); + context.get_executor(), output, input, input, input, + [](boost::system::error_code /*code*/) {}); return 0; } diff --git a/test/messages/async_scrypt_without_threads/async_scrypt_without_threads.cpp b/test/messages/async_scrypt_without_threads/async_scrypt_without_threads.cpp index 749f08e..493d07e 100644 --- a/test/messages/async_scrypt_without_threads/async_scrypt_without_threads.cpp +++ b/test/messages/async_scrypt_without_threads/async_scrypt_without_threads.cpp @@ -26,8 +26,9 @@ int main() { webcpp::asio::io_context context; std::array output{}; - webcpp::hash::async_scrypt(context.get_executor(), output, {}, {}, - webcpp::hash::scrypt_parameters{.n = 16, .r = 1, .p = 1}, - [](boost::system::error_code /*code*/) {}); + webcpp::hash::async_scrypt( + context.get_executor(), output, {}, {}, + webcpp::hash::scrypt_parameters{.cost = 16, .block_size = 1, .parallelism = 1}, + [](boost::system::error_code /*code*/) {}); return 0; } diff --git a/test/messages/extract_on_bearssl/Jamfile b/test/messages/extract_on_bearssl/Jamfile new file mode 100644 index 0000000..c3bfd12 --- /dev/null +++ b/test/messages/extract_on_bearssl/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/hash//hash /third_party//bearssl ; + +import webcpp ; + +webcpp.compile-diagnostic extract_on_bearssl : extract_on_bearssl.cpp : : native wasip2 wasip3 ; diff --git a/test/messages/extract_on_bearssl/extract_on_bearssl.cpp b/test/messages/extract_on_bearssl/extract_on_bearssl.cpp new file mode 100644 index 0000000..c056b17 --- /dev/null +++ b/test/messages/extract_on_bearssl/extract_on_bearssl.cpp @@ -0,0 +1,31 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The single-buffer hkdf_extract on backends::bearssl, whose br_hkdf_* keeps the PRK inside its +// context, stops with spec section 3.3's text, and with no other error, while hkdf_extract over +// pieces on BearSSL compiles (the change hkdf-pieces, scenario "BearSSL's Extract over pieces"). + +// clang-format off +// expected-error@webcpp/hash/backends/bearssl.hpp:* {{webcpp::hash: hkdf_extract and hkdf_expand are not in backends::bearssl, whose HKDF does both steps together: call hkdf, or name backends::hash2, backends::sodium, backends::openssl or backends::botan.}} +// clang-format on +#include +#include +#include + +#include +#include + +int main() { + std::array salt{}; + std::array ikm{}; + auto pieces = + webcpp::hash::hkdf_extract( + salt, {ikm, ikm}); + auto single = + webcpp::hash::hkdf_extract( + salt, ikm); + return pieces && single ? 0 : 1; +} diff --git a/test/messages/openssl_kdf_not_linked/openssl_kdf_not_linked.cpp b/test/messages/openssl_kdf_not_linked/openssl_kdf_not_linked.cpp index 80bd187..9eed53b 100644 --- a/test/messages/openssl_kdf_not_linked/openssl_kdf_not_linked.cpp +++ b/test/messages/openssl_kdf_not_linked/openssl_kdf_not_linked.cpp @@ -26,7 +26,7 @@ int main() { std::array salt{}; auto const argon2id = hash::argon2id( output, {}, salt, hash::argon2id_parameters{.passes = 2, .memory = 19456 * 1024}); - auto const scrypt = hash::scrypt(output, {}, salt, - hash::scrypt_parameters{1024, 8, 1}); + auto const scrypt = hash::scrypt( + output, {}, salt, hash::scrypt_parameters{.cost = 1024, .block_size = 8, .parallelism = 1}); return argon2id && scrypt ? 0 : 1; } diff --git a/test/messages/scrypt_default_not_linked/scrypt_default_not_linked.cpp b/test/messages/scrypt_default_not_linked/scrypt_default_not_linked.cpp index a4983a4..ad975ad 100644 --- a/test/messages/scrypt_default_not_linked/scrypt_default_not_linked.cpp +++ b/test/messages/scrypt_default_not_linked/scrypt_default_not_linked.cpp @@ -20,6 +20,8 @@ int main() { std::array output{}; std::array salt{}; - auto done = webcpp::hash::scrypt(output, {}, salt, webcpp::hash::scrypt_parameters{1024, 8, 1}); + auto done = webcpp::hash::scrypt( + output, {}, salt, + webcpp::hash::scrypt_parameters{.cost = 1024, .block_size = 8, .parallelism = 1}); return done ? 0 : 1; } diff --git a/test/messages/webcrypto_off_emscripten/webcrypto_off_emscripten.cpp b/test/messages/webcrypto_off_emscripten/webcrypto_off_emscripten.cpp index b32b37d..0d0d951 100644 --- a/test/messages/webcrypto_off_emscripten/webcrypto_off_emscripten.cpp +++ b/test/messages/webcrypto_off_emscripten/webcrypto_off_emscripten.cpp @@ -25,7 +25,9 @@ int main() { webcpp::asio::io_context context; std::array output{}; + std::array input{}; webcpp::hash::async_hkdf( - context.get_executor(), output, {}, {}, {}, [](boost::system::error_code /*code*/) {}); + context.get_executor(), output, input, input, input, + [](boost::system::error_code /*code*/) {}); return 0; } diff --git a/test/messages/webcrypto_synchronous/webcrypto_synchronous.cpp b/test/messages/webcrypto_synchronous/webcrypto_synchronous.cpp index 5fb1e14..5c834a1 100644 --- a/test/messages/webcrypto_synchronous/webcrypto_synchronous.cpp +++ b/test/messages/webcrypto_synchronous/webcrypto_synchronous.cpp @@ -20,7 +20,8 @@ int main() { std::array output{}; + std::array input{}; auto done = webcpp::hash::hkdf( - output, {}, {}, {}); + output, input, input, input); return done ? 0 : 1; } diff --git a/test/names_test.cpp b/test/names_test.cpp new file mode 100644 index 0000000..c44fdff --- /dev/null +++ b/test/names_test.cpp @@ -0,0 +1,52 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The spelled-out names compile (design D7): designated initializers of every renamed field, and +// the renamed constant. + +#include +#include +#include + +#include + +#include + +#include "support/hex.hpp" + +#include +#include +#include +#include + +namespace hash = webcpp::hash; +using webcpp::test::to_hex; + +static_assert(hash::hkdf_max_application_info_size == 32768); + +namespace { + +std::span bytes(std::string_view text) { + return {reinterpret_cast(text.data()), text.size()}; +} + +} // namespace + +int main() { + std::array output{}; + auto const password = bytes("password"); + auto const salt = bytes("NaCl"); + // RFC 7914, section 12, the second vector: N = 1024, r = 8, p = 16. + auto const done = + hash::scrypt(output, password, salt, {.cost = 1024, .block_size = 8, .parallelism = 16}); + BOOST_TEST(done.has_value()); + BOOST_TEST_EQ(to_hex(output), + "fdbabe1c9d3472007856e7190d01e9fe7c6ad7cbc8237830e77376634b373162" + "2eaf30d92e22a3886ff109279d9830dac727afb94a83ee6d8360cbdfa2cc0640"); + hash::argon2_parameters const parameters{.passes = 3, .memory_kibibytes = 32, .lanes = 4}; + BOOST_TEST_EQ(parameters.memory_kibibytes, 32U); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/openssl_error_queue_test.cpp b/test/openssl_error_queue_test.cpp index 75b500b..90fef93 100644 --- a/test/openssl_error_queue_test.cpp +++ b/test/openssl_error_queue_test.cpp @@ -4,17 +4,17 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// OpenSSL's error queue (spec section 3.4): on an empty queue, hkdf_extract, hkdf_expand, hkdf, -// pbkdf2, digest_of, a hasher's make, update and finish, mac (HMAC, KMAC, keyed BLAKE2s and -// SipHash), argon2 (Argon2d with a secret and associated data), argon2id, scrypt, kbkdf, sskdf -// and x963kdf on backends::openssl leave it empty, -// OpenSSL's first fetch and initialisation among them; an entry of the caller's survives each, and -// nothing of webcpp's is left beside it; a mark the caller set on its own entry survives them too, -// and the caller's pop to it still finds it. openssl_failure_test.cpp checks the same around a -// failure. +// OpenSSL's error queue (spec section 3.4): on an empty queue, hkdf_extract, hkdf_expand, hkdf +// (each also over pieces), pbkdf2, digest_of, a hasher's make, update and finish, mac (HMAC, KMAC, +// keyed BLAKE2s and SipHash), argon2 (Argon2d with a secret and associated data), argon2id, scrypt, +// kbkdf, sskdf and x963kdf on backends::openssl leave it empty, OpenSSL's first fetch and +// initialisation among them; an entry of the caller's survives each, and nothing of webcpp's is +// left beside it; a mark the caller set on its own entry survives them too, and the caller's pop to +// it still finds it. openssl_failure_test.cpp checks the same around a failure. #include #include +#include #include #include #include @@ -50,9 +50,24 @@ std::size_t drain(unsigned long& first) { return count; } +/** HKDF's three functions over pieces once, on OpenSSL, each a success. */ +void call_each_over_pieces(std::span salt, std::span ikm) { + using piece = std::span; + std::array output{}; + std::array const pieces{ikm.first(4), piece{}, ikm.subspan(4)}; + auto const prk = hash::hkdf_extract(salt, pieces); + BOOST_TEST(prk.has_value()); + if (prk) { + BOOST_TEST((hash::hkdf_expand( + output, std::span(prk->data(), prk->size()), pieces) + .has_value())); + } + BOOST_TEST((hash::hkdf(output, salt, pieces, pieces).has_value())); +} + /** - Each of the four key derivations, the digest family, the MAC family, Argon2, scrypt and the - key derivations of standards once, on OpenSSL, each a success. + Each of the four key derivations (HKDF's three also over pieces), the digest family, the MAC + family, Argon2, scrypt and the key derivations of standards once, on OpenSSL, each a success. */ void call_each() { std::array const salt{1, 2, 3}; @@ -67,6 +82,7 @@ void call_each() { .has_value())); } BOOST_TEST((hash::hkdf(output, salt, ikm, info).has_value())); + call_each_over_pieces(salt, ikm); BOOST_TEST((hash::pbkdf2(output, ikm, salt, 2).has_value())); std::array digest{}; @@ -89,14 +105,18 @@ void call_each() { BOOST_TEST((hash::mac(short_tag, key, ikm))); std::array const password_salt{1, 2, 3}; - BOOST_TEST( - (hash::argon2( - digest, ikm, password_salt, - {.passes = 1, .memory_kib = 16, .lanes = 2, .secret = key, .associated_data = info}) - .has_value())); + BOOST_TEST((hash::argon2(digest, ikm, password_salt, + {.passes = 1, + .memory_kibibytes = 16, + .lanes = 2, + .secret = key, + .associated_data = info}) + .has_value())); BOOST_TEST((hash::argon2id(digest, ikm, password_salt, {.passes = 1, .memory = 8192}) .has_value())); - BOOST_TEST((hash::scrypt(digest, ikm, salt, {.n = 16, .r = 1, .p = 1}).has_value())); + BOOST_TEST( + (hash::scrypt(digest, ikm, salt, {.cost = 16, .block_size = 1, .parallelism = 1}) + .has_value())); BOOST_TEST( (hash::kbkdf(output, ikm, {.label = salt, .context = info}).has_value())); diff --git a/test/openssl_failure_test.cpp b/test/openssl_failure_test.cpp index eac4f66..f821ebd 100644 --- a/test/openssl_failure_test.cpp +++ b/test/openssl_failure_test.cpp @@ -6,13 +6,14 @@ // A failure of OpenSSL (spec sections 2.8 and 7.5), provoked through the seam // WEBCPP_HASH_DETAIL_TEST_OPENSSL_DIGEST, which the test's Jamfile defines to "NO-SUCH-DIGEST", a -// digest OpenSSL cannot fetch: every function returns backend_failure, hkdf_expand, hkdf, pbkdf2, -// digest_of and mac (HMAC, whose "digest" parameter the seam names) zero their output, -// hasher::make makes no hasher, and the thread's error queue is -// left as it was found, empty or holding an entry of the caller's. A guard's refusal still comes -// first. +// digest OpenSSL cannot fetch: every function returns backend_failure, hkdf_expand, hkdf (each also +// over pieces, whose EVP_MAC "HMAC" the seam's digest name fails), pbkdf2, digest_of and mac (HMAC, +// whose "digest" parameter the seam names) zero their output, hasher::make makes no hasher, and the +// thread's error queue is left as it was found, empty or holding an entry of the caller's. A +// guard's refusal still comes first. #include +#include #include #include #include @@ -75,6 +76,31 @@ void fail_hmac() { BOOST_TEST(all_of(cut, 0)); } +/** HKDF's three functions over pieces, their HMAC named by the same seam, each failing. */ +void fail_each_over_pieces() { + using piece = std::span; + std::array const salt{1, 2, 3}; + std::array const ikm{4, 5, 6}; + std::array const prk{7, 8, 9}; + std::array const info{10, 11, 12}; + std::array output{}; + std::array const ikm_pieces{piece(ikm).first(4), piece{}, piece(ikm).subspan(4)}; + std::array const info_pieces{piece(info).first(3), piece(info).subspan(3)}; + + auto const extracted = hash::hkdf_extract(salt, ikm_pieces); + BOOST_TEST(extracted.has_error() && extracted.error() == hash::error::backend_failure); + + output.fill(untouched); + auto failed = hash::hkdf_expand(output, prk, info_pieces); + BOOST_TEST(failed.has_error() && failed.error() == hash::error::backend_failure); + BOOST_TEST(all_of(output, 0)); + + output.fill(untouched); + failed = hash::hkdf(output, salt, ikm_pieces, info_pieces); + BOOST_TEST(failed.has_error() && failed.error() == hash::error::backend_failure); + BOOST_TEST(all_of(output, 0)); +} + /** Each of the four key derivations, and the digests, once, on OpenSSL, each failing. */ void fail_each() { std::array const salt{1, 2, 3}; @@ -129,6 +155,7 @@ int main() { BOOST_TEST_EQ(ERR_peek_error(), 0UL); fail_each(); + fail_each_over_pieces(); fail_hmac(); BOOST_TEST_EQ(ERR_peek_error(), 0UL); @@ -136,6 +163,7 @@ int main() { ERR_raise(ERR_LIB_USER, ERR_R_PASSED_INVALID_ARGUMENT); unsigned long const ours = ERR_peek_last_error(); fail_each(); + fail_each_over_pieces(); fail_hmac(); unsigned long first = 0; BOOST_TEST_EQ(drain(first), 1U); diff --git a/test/openssl_limits_test.cpp b/test/openssl_limits_test.cpp index 646aacd..11d09ac 100644 --- a/test/openssl_limits_test.cpp +++ b/test/openssl_limits_test.cpp @@ -7,18 +7,19 @@ // backends::openssl's limits: OpenSSL 3.5.9 holds PBKDF2's output and salt lengths // and HMAC's key length (PBKDF2's password, HKDF-Extract's salt, HKDF-Expand's PRK) in an int, so // the public functions refuse more than INT_MAX bytes of them before OpenSSL is called, after the -// spec's own guards, the output untouched. Each long span is INT_MAX + 1 bytes over a buffer of a -// few: the guard refuses it before anything reads or writes it, so OpenSSL's behaviour beyond its -// limit is never exercised. Native only (the Jamfile), as the guard test of PBKDF2's output. mac's -// HMAC on OpenSSL refuses a key of more than INT_MAX bytes alike, with unsupported_by_backend (the -// engine's narrower limit, ruling R41), after the family's guards. scrypt on OpenSSL passes its -// password, its salt and its output to PBKDF2, whose lengths are ints: the same INT_MAX bytes. -// kbkdf's HMAC key alike (unsupported_by_backend); sskdf and x963kdf take at most 2^30 bytes of -// secret, info and output on OpenSSL (unsupported_by_backend), after the standards' own bounds on -// the output (2^32 - 1 blocks), on L (32 bits) and on what the digest hashes (2^61 - 1 bytes for -// SHA-256), which only spans this long reach. +// spec's own guards, the output untouched; HKDF over pieces refuses the salt alike. Each long span +// is INT_MAX + 1 bytes over a buffer of a few: the guard refuses it before anything reads or writes +// it, so OpenSSL's behaviour beyond its limit is never exercised. Native only (the Jamfile), as the +// guard test of PBKDF2's output. mac's HMAC on OpenSSL refuses a key of more than INT_MAX bytes +// alike, with unsupported_by_backend (the engine's narrower limit, ruling R41), after the family's +// guards. scrypt on OpenSSL passes its password, its salt and its output to PBKDF2, whose lengths +// are ints: the same INT_MAX bytes. kbkdf's HMAC key alike (unsupported_by_backend); sskdf and +// x963kdf take at most 2^30 bytes of secret, info and output on OpenSSL (unsupported_by_backend), +// after the standards' own bounds on the output (2^32 - 1 blocks), on L (32 bits) and on what the +// digest hashes (2^61 - 1 bytes for SHA-256), which only spans this long reach. #include +#include #include #include #include @@ -51,14 +52,14 @@ constexpr std::size_t past = static_cast(INT_MAX) + 1; using limits = hash::detail::backend_limits; static_assert(limits::pbkdf2_output == INT_MAX && limits::pbkdf2_password == INT_MAX && limits::pbkdf2_salt == INT_MAX && limits::hkdf_salt == INT_MAX && - limits::hkdf_prk == INT_MAX); + limits::hkdf_pseudorandom_key == INT_MAX); static_assert(limits::scrypt_password == INT_MAX && limits::scrypt_salt == INT_MAX && limits::scrypt_output == INT_MAX); // Argon2's lengths are OpenSSL's uint32_t, RFC 9106's own bound, which argon2id's guards keep. static_assert(limits::argon2id_password == 0xffffffffU && limits::argon2id_salt == 0xffffffffU && limits::argon2id_output == 0xffffffffU); -static_assert(limits::hkdf_ikm == hash::detail::no_limit && - limits::hkdf_info == hash::detail::no_limit && +static_assert(limits::hkdf_input_key_material == hash::detail::no_limit && + limits::hkdf_application_info == hash::detail::no_limit && limits::hkdf_output == hash::detail::no_limit); // backends::hash2 has no limit of its own. static_assert(hash::detail::backend_limits::pbkdf2_output == @@ -113,6 +114,22 @@ void hkdf_limits(std::span few) { refused = hash::hkdf_expand(output, long_input, few); BOOST_TEST(refused.has_error() && refused.error() == hash::error::invalid_key_size); BOOST_TEST(is_untouched(output)); + + // Over pieces, the salt is HMAC's key alike: input_too_long, after the output's size; the + // pieces themselves have no limit. + const auto pieces_prk = hash::hkdf_extract(long_input, {few, few}); + BOOST_TEST(pieces_prk.has_error() && pieces_prk.error() == hash::error::input_too_long); + refused = hash::hkdf(output, long_input, {few, few}, {few, few}); + BOOST_TEST(refused.has_error() && refused.error() == hash::error::input_too_long); + refused = hash::hkdf(std::span(output.data(), 0), long_input, + {few, few}, {few, few}); + BOOST_TEST(refused.has_error() && refused.error() == hash::error::invalid_output_size); + refused = hash::hkdf_expand(output, long_input, {few, few}); + BOOST_TEST(refused.has_error() && refused.error() == hash::error::invalid_key_size); + BOOST_TEST(is_untouched(output)); + // Within the limit, OpenSSL derives over pieces. + BOOST_TEST((hash::hkdf(output, few, {few, few}, {few, few}).has_value())); + BOOST_TEST(!is_untouched(output)); } void mac_limits(std::span few) { @@ -140,7 +157,7 @@ void scrypt_limits(std::span few) { std::array output{}; output.fill(untouched); const std::span long_input(few.data(), past); - constexpr hash::scrypt_parameters cheap{.n = 16, .r = 1, .p = 1}; + constexpr hash::scrypt_parameters cheap{.cost = 16, .block_size = 1, .parallelism = 1}; auto refused = hash::scrypt(std::span(output.data(), past), few, few, cheap); @@ -152,7 +169,8 @@ void scrypt_limits(std::span few) { BOOST_TEST(is_untouched(output)); // The spec's own guards come first: N not a power of two. - refused = hash::scrypt(output, long_input, few, {.n = 15, .r = 1, .p = 1}); + refused = hash::scrypt(output, long_input, few, + {.cost = 15, .block_size = 1, .parallelism = 1}); BOOST_TEST(refused.has_error() && refused.error() == hash::error::invalid_parameters); BOOST_TEST(is_untouched(output)); diff --git a/test/openssl_out_of_memory_test.cpp b/test/openssl_out_of_memory_test.cpp index b1c40a3..c9157d9 100644 --- a/test/openssl_out_of_memory_test.cpp +++ b/test/openssl_out_of_memory_test.cpp @@ -4,17 +4,17 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// OpenSSL running out of memory in the middle of a call of backends::openssl (spec sections 2.8 -// and 7.5): the test sets OpenSSL's allocator with CRYPTO_set_mem_functions before anything, and -// makes each allocation of a call fail in turn, the first, then the second, and so on until the -// call allocates no more than the ones that succeed. Each failing call answers -// errc::not_enough_memory, the allocation's error being among those OpenSSL raised during the call -// even when it is not the last (Argon2's memory adds "invalid memory size" after it), zeroes its -// output, frees every block OpenSSL allocated for it (the live blocks are back to where -// they were), and leaves the thread's error queue empty. The calls: mac over HMAC, KMAC, keyed -// BLAKE2b and SipHash, digest_of, a hasher's make, argon2, argon2id, scrypt, kbkdf, sskdf and -// x963kdf. OpenSSL's Argon2 -// does not check some of its allocations (its first hash and its first and last blocks), and +// OpenSSL running out of memory in the middle of a call of backends::openssl (spec sections 2.8 and +// 7.5): the test sets OpenSSL's allocator with CRYPTO_set_mem_functions before anything, and makes +// each allocation of a call fail in turn, the first, then the second, and so on until the call +// allocates no more than the ones that succeed. Each failing call answers errc::not_enough_memory, +// the allocation's error being among those OpenSSL raised during the call even when it is not the +// last (Argon2's memory adds "invalid memory size" after it), zeroes its output, frees every block +// OpenSSL allocated for it (the live blocks are back to where they were), and leaves the thread's +// error queue empty. The calls: mac over HMAC, KMAC, keyed BLAKE2b and SipHash, digest_of, a +// hasher's make, argon2, argon2id, scrypt, kbkdf, sskdf, x963kdf, and hkdf_extract, hkdf_expand and +// hkdf over pieces (EVP_MAC "HMAC", a context duplicated for each block of Expand). OpenSSL's +// Argon2 does not check some of its allocations (its first hash and its first and last blocks), and // returns success over a wrong tag when one fails: backends::openssl answers a call during which // OpenSSL raised an error as a failure, whatever OpenSSL returned. A hasher's update and finish // allocate nothing on OpenSSL 3.5.9 (counted below), so no allocation can make them fail: the @@ -22,8 +22,10 @@ #include #include +#include #include #include +#include #include #include #include @@ -211,19 +213,25 @@ void check_password_hashing() { std::array const secret{1, 2}; std::array tag{}; fail_each_allocation("argon2 argon2id, two lanes, secret and associated data", tag, [&] { - return hash::argon2( - tag, secret, salt, - {.passes = 1, .memory_kib = 16, .lanes = 2, .secret = secret, .associated_data = salt}); + return hash::argon2(tag, secret, salt, + { + .passes = 1, + .memory_kibibytes = 16, + .lanes = 2, + .secret = secret, + .associated_data = salt, + }); }); fail_each_allocation("argon2 argon2d", tag, [&] { - return hash::argon2(tag, secret, salt, - {.passes = 1, .memory_kib = 8}); + return hash::argon2( + tag, secret, salt, {.passes = 1, .memory_kibibytes = 8}); }); fail_each_allocation("argon2id", tag, [&] { return hash::argon2id(tag, secret, salt, {.passes = 1, .memory = 8192}); }); fail_each_allocation("scrypt", tag, [&] { - return hash::scrypt(tag, secret, salt, {.n = 16, .r = 1, .p = 1}); + return hash::scrypt(tag, secret, salt, + {.cost = 16, .block_size = 1, .parallelism = 1}); }); } @@ -243,6 +251,33 @@ void check_kdf_standards() { }); } +// HKDF over pieces: Extract (whose result is the pseudorandom key, so that its output here is +// empty), Expand of three blocks, each a context duplicated from the keyed one, and both steps. +void check_hkdf_pieces() { + using piece = std::span; + std::array const salt{7, 8, 9}; + std::array const ikm{1, 2, 3}; + std::array const info{4, 5, 6}; + std::array const prk{10, 11, 12}; + std::array const ikm_pieces{piece(ikm).first(5), piece{}, piece(ikm).subspan(5)}; + std::array const info_pieces{piece(info).first(3), piece(info).subspan(3)}; + std::array output{}; + std::array none{}; + fail_each_allocation("hkdf_extract over pieces", none, [&]() -> boost::system::result { + auto const extracted = hash::hkdf_extract(salt, ikm_pieces); + if (!extracted) { + return extracted.error(); + } + return {}; + }); + fail_each_allocation("hkdf_expand over pieces", output, [&] { + return hash::hkdf_expand(output, prk, info_pieces); + }); + fail_each_allocation("hkdf over pieces", output, [&] { + return hash::hkdf(output, salt, ikm_pieces, info_pieces); + }); +} + } // namespace int main() { @@ -254,5 +289,6 @@ int main() { check_digests(); check_password_hashing(); check_kdf_standards(); + check_hkdf_pieces(); return webcpp::test::exit_status(boost::report_errors()); } diff --git a/test/scrypt_botan_large_test.cpp b/test/scrypt_botan_large_test.cpp index 43182a8..efd9fab 100644 --- a/test/scrypt_botan_large_test.cpp +++ b/test/scrypt_botan_large_test.cpp @@ -24,9 +24,9 @@ int main() { namespace test = webcpp::test; auto const& c = test::rfc7914_large; std::array output{}; - BOOST_TEST(hash::scrypt(output, test::bytes_of(c.password), - test::bytes_of(c.salt), - {.n = c.n, .r = c.r, .p = c.p}) + BOOST_TEST(hash::scrypt( + output, test::bytes_of(c.password), test::bytes_of(c.salt), + {.cost = c.n, .block_size = c.r, .parallelism = c.p}) .has_value()); BOOST_TEST_EQ(test::to_hex(output), std::string(c.output)); return webcpp::test::exit_status(boost::report_errors()); diff --git a/test/scrypt_botan_test.cpp b/test/scrypt_botan_test.cpp index b67401e..8bfd2f5 100644 --- a/test/scrypt_botan_test.cpp +++ b/test/scrypt_botan_test.cpp @@ -50,7 +50,7 @@ void check_rfc7914() { std::array output{}; auto const done = hash::scrypt(output, test::bytes_of(c.password), test::bytes_of(c.salt), - {.n = c.n, .r = c.r, .p = c.p}); + {.cost = c.n, .block_size = c.r, .parallelism = c.p}); BOOST_TEST(done.has_value()); BOOST_TEST_EQ(test::to_hex(output), std::string(c.output)); } @@ -58,9 +58,9 @@ void check_rfc7914() { auto const& first = test::rfc7914_cases.front(); std::array output{}; std::span const nothing{}; - BOOST_TEST( - hash::scrypt(output, nothing, nothing, {.n = first.n, .r = first.r, .p = first.p}) - .has_value()); + BOOST_TEST(hash::scrypt(output, nothing, nothing, + {.cost = first.n, .block_size = first.r, .parallelism = first.p}) + .has_value()); BOOST_TEST_EQ(test::to_hex(output), std::string(first.output)); } @@ -75,9 +75,9 @@ void agree_with_sodium() { rnd.bytes(index % 5 == 4 ? rnd.between(8192, 10000) : rnd.between(0, 64)); auto const salt = rnd.bytes(rnd.between(0, 64)); hash::scrypt_parameters const costs{ - .n = std::uint64_t{1} << rnd.between(1, 10), - .r = static_cast(rnd.between(1, 8)), - .p = static_cast(rnd.between(1, 4)), + .cost = std::uint64_t{1} << rnd.between(1, 10), + .block_size = static_cast(rnd.between(1, 8)), + .parallelism = static_cast(rnd.between(1, 4)), }; std::size_t const output_size = rnd.between(1, 100); bytes expected(output_size); @@ -85,9 +85,9 @@ void agree_with_sodium() { bool const both = hash::scrypt(expected, password, salt, costs).has_value() && hash::scrypt(output, password, salt, costs).has_value(); if (!BOOST_TEST(both) || !BOOST_TEST_EQ(test::to_hex(output), test::to_hex(expected))) { - std::cerr << " case " << index << ": password " << password.size() << ", N " << costs.n - << ", r " << costs.r << ", p " << costs.p << ", output " << output_size - << '\n'; + std::cerr << " case " << index << ": password " << password.size() << ", N " + << costs.cost << ", r " << costs.block_size << ", p " << costs.parallelism + << ", output " << output_size << '\n'; } } } @@ -101,8 +101,8 @@ bool refused(hash::scrypt_parameters const& costs) { if (!BOOST_TEST(outcome.has_error() && outcome.error() == hash::error::unsupported_by_backend) || !BOOST_TEST(untouched_output)) { - std::cerr << " not refused: N " << costs.n << ", r " << costs.r << ", p " << costs.p - << '\n'; + std::cerr << " not refused: N " << costs.cost << ", r " << costs.block_size << ", p " + << costs.parallelism << '\n'; return false; } return true; @@ -116,16 +116,23 @@ void check_limits() { static_assert(engine::limits.served_n == std::uint64_t{1} << 22U); static_assert(engine::limits.served_r == 256); static_assert(engine::limits.served_p == 1024); - refused({.n = 2, .r = 257, .p = 1}); - refused({.n = 2, .r = 1, .p = 1025}); - refused({.n = std::uint64_t{1} << 23U, .r = 2, .p = 1}); + refused({.cost = 2, .block_size = 257, .parallelism = 1}); + refused({.cost = 2, .block_size = 1, .parallelism = 1025}); + refused({.cost = std::uint64_t{1} << 23U, .block_size = 2, .parallelism = 1}); // Refused for its memory alone: N 2^22 and r 32 natively, 16 GiB; on wasm32, where the spec's // guard already refuses what does not fit a size_t (invalid_parameters), N 2^22 and r 5, // 2.5 GiB. - refused({.n = std::uint64_t{1} << 22U, .r = sizeof(std::size_t) == 8 ? 32U : 5U, .p = 1}); + refused({ + .cost = std::uint64_t{1} << 22U, + .block_size = sizeof(std::size_t) == 8 ? 32U : 5U, + .parallelism = 1, + }); std::array output{}; - BOOST_TEST(hash::scrypt(output, {}, {}, {.n = 2, .r = 256, .p = 1}).has_value()); - BOOST_TEST(hash::scrypt(output, {}, {}, {.n = 2, .r = 1, .p = 1024}).has_value()); + BOOST_TEST(hash::scrypt(output, {}, {}, {.cost = 2, .block_size = 256, .parallelism = 1}) + .has_value()); + BOOST_TEST( + hash::scrypt(output, {}, {}, {.cost = 2, .block_size = 1, .parallelism = 1024}) + .has_value()); } static_assert(hash::backend_has_v); diff --git a/test/scrypt_openssl_large_test.cpp b/test/scrypt_openssl_large_test.cpp index e7843f8..cf3ab02 100644 --- a/test/scrypt_openssl_large_test.cpp +++ b/test/scrypt_openssl_large_test.cpp @@ -32,14 +32,14 @@ void check_rfc7914_large() { auto const& c = test::rfc7914_large; std::array output{}; BOOST_TEST(hash::scrypt(output, test::bytes_of(c.password), test::bytes_of(c.salt), - {.n = c.n, .r = c.r, .p = c.p}) + {.cost = c.n, .block_size = c.r, .parallelism = c.p}) .has_value()); BOOST_TEST_EQ(test::to_hex(output), std::string(c.output)); } void check_past_default_limit() { auto const& c = test::rfc7914_large; - hash::scrypt_parameters const costs{.n = c.n, .r = 9, .p = 1}; + hash::scrypt_parameters const costs{.cost = c.n, .block_size = 9, .parallelism = 1}; std::array expected{}; std::array output{}; BOOST_TEST( diff --git a/test/scrypt_openssl_test.cpp b/test/scrypt_openssl_test.cpp index 3a2691b..81a5630 100644 --- a/test/scrypt_openssl_test.cpp +++ b/test/scrypt_openssl_test.cpp @@ -52,7 +52,7 @@ void check_rfc7914() { std::array output{}; auto const done = hash::scrypt(output, test::bytes_of(c.password), test::bytes_of(c.salt), - {.n = c.n, .r = c.r, .p = c.p}); + {.cost = c.n, .block_size = c.r, .parallelism = c.p}); BOOST_TEST(done.has_value()); BOOST_TEST_EQ(test::to_hex(output), std::string(c.output)); } @@ -61,7 +61,8 @@ void check_rfc7914() { std::array output{}; std::span const nothing{}; BOOST_TEST( - hash::scrypt(output, nothing, nothing, {.n = first.n, .r = first.r, .p = first.p}) + hash::scrypt(output, nothing, nothing, + {.cost = first.n, .block_size = first.r, .parallelism = first.p}) .has_value()); BOOST_TEST_EQ(test::to_hex(output), std::string(first.output)); } @@ -75,9 +76,9 @@ void agree_with_sodium() { auto const password = rnd.bytes(rnd.between(0, 64)); auto const salt = rnd.bytes(rnd.between(0, 64)); hash::scrypt_parameters const costs{ - .n = std::uint64_t{1} << rnd.between(1, 10), - .r = static_cast(rnd.between(1, 8)), - .p = static_cast(rnd.between(1, 4)), + .cost = std::uint64_t{1} << rnd.between(1, 10), + .block_size = static_cast(rnd.between(1, 8)), + .parallelism = static_cast(rnd.between(1, 4)), }; std::size_t const output_size = rnd.between(1, 100); bytes expected(output_size); @@ -85,8 +86,8 @@ void agree_with_sodium() { bool const both = hash::scrypt(expected, password, salt, costs).has_value() && hash::scrypt(output, password, salt, costs).has_value(); if (!BOOST_TEST(both) || !BOOST_TEST_EQ(test::to_hex(output), test::to_hex(expected))) { - std::cerr << " case " << index << ": N " << costs.n << ", r " << costs.r << ", p " - << costs.p << ", output " << output_size << '\n'; + std::cerr << " case " << index << ": N " << costs.cost << ", r " << costs.block_size + << ", p " << costs.parallelism << ", output " << output_size << '\n'; } } } @@ -100,8 +101,8 @@ void check_limits() { static_assert(engine::limits.n == hash::detail::no_limit); std::array output{}; output.fill(untouched); - auto const refused = - hash::scrypt(output, {}, {}, {.n = 2, .r = 1, .p = std::uint32_t{1} << 24U}); + auto const refused = hash::scrypt( + output, {}, {}, {.cost = 2, .block_size = 1, .parallelism = std::uint32_t{1} << 24U}); BOOST_TEST(refused.has_error() && refused.error() == hash::error::invalid_parameters); BOOST_TEST(std::ranges::all_of(output, [](std::uint8_t byte) { return byte == untouched; })); // The same r p on backends::sodium passes the guards: only the RFC's bound is libsodium's. @@ -117,7 +118,8 @@ void check_memory_limit_exceeded() { std::array output{}; output.fill(untouched); auto const refused = hash::scrypt( - output, {}, {}, {.n = std::uint64_t{1} << 23U, .r = 2, .p = (1U << 23U) - 1}); + output, {}, {}, + {.cost = std::uint64_t{1} << 23U, .block_size = 2, .parallelism = (1U << 23U) - 1}); BOOST_TEST(refused.has_error() && refused.error() == boost::system::errc::make_error_code( boost::system::errc::not_enough_memory)); diff --git a/test/scrypt_rfc7914_large_test.cpp b/test/scrypt_rfc7914_large_test.cpp index c18952d..16aa014 100644 --- a/test/scrypt_rfc7914_large_test.cpp +++ b/test/scrypt_rfc7914_large_test.cpp @@ -30,9 +30,9 @@ void test_large() { auto const& c = webcpp::test::rfc7914_large; std::array output{}; auto const start = std::chrono::steady_clock::now(); - auto const done = - webcpp::hash::scrypt(output, webcpp::test::bytes_of(c.password), - webcpp::test::bytes_of(c.salt), {.n = c.n, .r = c.r, .p = c.p}); + auto const done = webcpp::hash::scrypt(output, webcpp::test::bytes_of(c.password), + webcpp::test::bytes_of(c.salt), + {.cost = c.n, .block_size = c.r, .parallelism = c.p}); auto const elapsed = std::chrono::steady_clock::now() - start; if (!BOOST_TEST(done.has_value())) { auto const message = done.error().message(); diff --git a/test/scrypt_test.cpp b/test/scrypt_test.cpp index d351118..ded6f60 100644 --- a/test/scrypt_test.cpp +++ b/test/scrypt_test.cpp @@ -93,7 +93,7 @@ void test_rfc7914() { std::array output{}; auto const done = hash::scrypt(output, webcpp::test::bytes_of(c.password), webcpp::test::bytes_of(c.salt), - {.n = c.n, .r = c.r, .p = c.p}); + {.cost = c.n, .block_size = c.r, .parallelism = c.p}); BOOST_TEST(done.has_value()); BOOST_TEST_EQ(to_hex(output), std::string(c.output)); } @@ -104,21 +104,21 @@ void test_rfc7914() { std::span const nothing{}; BOOST_TEST(nothing.data() == nullptr); std::array output{}; - auto const done = - hash::scrypt(output, nothing, nothing, {.n = first.n, .r = first.r, .p = first.p}); + auto const done = hash::scrypt( + output, nothing, nothing, {.cost = first.n, .block_size = first.r, .parallelism = first.p}); BOOST_TEST(done.has_value()); BOOST_TEST_EQ(to_hex(output), std::string(first.output)); } -const std::array password{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'}; -const std::array salt{'N', 'a', 'C', 'l'}; +const std::array test_password{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'}; +const std::array test_salt{'N', 'a', 'C', 'l'}; // Whether scrypt refuses `parameters` with `expected` on Backend, the output untouched. template bool refuses(hash::scrypt_parameters const& parameters, hash::error expected) { std::array buffer{}; buffer.fill(untouched); - auto const refused = hash::scrypt(buffer, password, salt, parameters); + auto const refused = hash::scrypt(buffer, test_password, test_salt, parameters); return refused.has_error() && refused.error() == expected && all_of(buffer, untouched); } @@ -126,102 +126,119 @@ bool refuses(hash::scrypt_parameters const& parameters, hash::error expected) { bool passes(hash::scrypt_parameters const& parameters) { std::array buffer{}; int const before = test_backends::recorded_calls; - auto const done = hash::scrypt(buffer, password, salt, parameters); + auto const done = + hash::scrypt(buffer, test_password, test_salt, parameters); return done.has_value() && test_backends::recorded_calls == before + 1; } void test_output_guard() { std::array buffer{}; buffer.fill(untouched); - constexpr hash::scrypt_parameters cheap{.n = 16, .r = 1, .p = 1}; - auto refused = hash::scrypt(std::span(buffer.data(), 0), password, salt, cheap); + constexpr hash::scrypt_parameters cheap{.cost = 16, .block_size = 1, .parallelism = 1}; + auto refused = + hash::scrypt(std::span(buffer.data(), 0), test_password, test_salt, cheap); BOOST_TEST(refused.has_error() && refused.error() == hash::error::invalid_output_size); // Natively a span of (2^32 - 1) 32 + 1 bytes over 33, refused before anything touches it; on // wasm32 no span is that long. constexpr std::uint64_t longest = 0xffffffffULL * 32; if constexpr (std::numeric_limits::max() > longest) { refused = hash::scrypt( - std::span(buffer.data(), static_cast(longest + 1)), password, - salt, cheap); + std::span(buffer.data(), static_cast(longest + 1)), + test_password, test_salt, cheap); BOOST_TEST(refused.has_error() && refused.error() == hash::error::invalid_output_size); } BOOST_TEST(all_of(buffer, untouched)); // One byte, the shortest, then 33, past one block of PBKDF2. BOOST_TEST( - hash::scrypt(std::span(buffer.data(), 1), password, salt, cheap).has_value()); + hash::scrypt(std::span(buffer.data(), 1), test_password, test_salt, cheap) + .has_value()); BOOST_TEST(buffer[1] == untouched); - BOOST_TEST(hash::scrypt(buffer, password, salt, cheap).has_value()); + BOOST_TEST(hash::scrypt(buffer, test_password, test_salt, cheap).has_value()); } void test_parameters_guard_n() { using enum hash::error; // N: a power of two, above 1, below 2^(16 r). for (std::uint64_t const n : {0ULL, 1ULL, 3ULL, 48ULL, 65535ULL, 65536ULL}) { - BOOST_TEST(refuses({.n = n, .r = 1, .p = 1}, invalid_parameters)); + BOOST_TEST(refuses({.cost = n, .block_size = 1, .parallelism = 1}, invalid_parameters)); } - BOOST_TEST(refuses({.n = std::uint64_t{1} << 32U, .r = 2, .p = 1}, invalid_parameters)); - BOOST_TEST(refuses({.n = std::uint64_t{1} << 48U, .r = 3, .p = 1}, invalid_parameters)); - BOOST_TEST(passes({.n = std::uint64_t{1} << 15U, .r = 1, .p = 1})); + BOOST_TEST(refuses({.cost = std::uint64_t{1} << 32U, .block_size = 2, .parallelism = 1}, + invalid_parameters)); + BOOST_TEST(refuses({.cost = std::uint64_t{1} << 48U, .block_size = 3, .parallelism = 1}, + invalid_parameters)); + BOOST_TEST(passes({.cost = std::uint64_t{1} << 15U, .block_size = 1, .parallelism = 1})); // The largest N for r = 2, 2^31, takes 512 GiB: past size_t on wasm32, where the size refuses. if constexpr (std::numeric_limits::max() > 0xffffffffU) { - BOOST_TEST(passes({.n = std::uint64_t{1} << 31U, .r = 2, .p = 1})); + BOOST_TEST(passes({.cost = std::uint64_t{1} << 31U, .block_size = 2, .parallelism = 1})); } else { - BOOST_TEST(refuses({.n = std::uint64_t{1} << 31U, .r = 2, .p = 1}, invalid_parameters)); + BOOST_TEST(refuses({.cost = std::uint64_t{1} << 31U, .block_size = 2, .parallelism = 1}, + invalid_parameters)); } - BOOST_TEST(passes({.n = 2, .r = 1, .p = 1})); + BOOST_TEST(passes({.cost = 2, .block_size = 1, .parallelism = 1})); } void test_parameters_guard_r_and_p() { using enum hash::error; // r and p at least 1. - BOOST_TEST(refuses({.n = 16, .r = 0, .p = 1}, invalid_parameters)); - BOOST_TEST(refuses({.n = 16, .r = 1, .p = 0}, invalid_parameters)); + BOOST_TEST(refuses({.cost = 16, .block_size = 0, .parallelism = 1}, invalid_parameters)); + BOOST_TEST(refuses({.cost = 16, .block_size = 1, .parallelism = 0}, invalid_parameters)); // r p below 2^30. - BOOST_TEST(refuses({.n = 16, .r = 1U << 15U, .p = 1U << 15U}, invalid_parameters)); - BOOST_TEST(refuses({.n = 16, .r = 1, .p = 1U << 30U}, invalid_parameters)); - BOOST_TEST(refuses({.n = 16, .r = 1U << 15U, .p = 1U << 15U}, - invalid_parameters)); + BOOST_TEST(refuses({.cost = 16, .block_size = 1U << 15U, .parallelism = 1U << 15U}, + invalid_parameters)); + BOOST_TEST( + refuses({.cost = 16, .block_size = 1, .parallelism = 1U << 30U}, invalid_parameters)); + BOOST_TEST(refuses( + {.cost = 16, .block_size = 1U << 15U, .parallelism = 1U << 15U}, invalid_parameters)); } void test_parameters_guard_size() { using enum hash::error; // 128 r (N + p) past size_t: on wasm32 4 GiB and a KiB, which passes natively; everywhere // 2^67 bytes. - constexpr hash::scrypt_parameters four_gib{.n = std::uint64_t{1} << 22U, .r = 8, .p = 1}; + constexpr hash::scrypt_parameters four_gib{ + .cost = std::uint64_t{1} << 22U, + .block_size = 8, + .parallelism = 1, + }; if constexpr (std::numeric_limits::max() == 0xffffffffU) { BOOST_TEST(refuses(four_gib, invalid_parameters)); BOOST_TEST(refuses(four_gib, invalid_parameters)); - BOOST_TEST(passes({.n = std::uint64_t{1} << 21U, .r = 8, .p = 1})); + BOOST_TEST(passes({.cost = std::uint64_t{1} << 21U, .block_size = 8, .parallelism = 1})); } else { BOOST_TEST(passes(four_gib)); } - constexpr hash::scrypt_parameters huge{.n = std::uint64_t{1} << 31U, .r = 1U << 29U, .p = 1}; + constexpr hash::scrypt_parameters huge{ + .cost = std::uint64_t{1} << 31U, + .block_size = 1U << 29U, + .parallelism = 1, + }; BOOST_TEST(refuses(huge, invalid_parameters)); // libsodium's N is at most UINT32_MAX, its uint32_t: 2^32 with r = 3 is RFC 7914's, and // refused before the call (natively 1.5 TiB fit size_t; on wasm32 the size refuses first). - BOOST_TEST(refuses({.n = std::uint64_t{1} << 32U, .r = 3, .p = 1}, invalid_parameters)); + BOOST_TEST(refuses({.cost = std::uint64_t{1} << 32U, .block_size = 3, .parallelism = 1}, + invalid_parameters)); BOOST_TEST_EQ(hash::detail::scrypt_engine::limits.n, 0xffffffffULL); if constexpr (std::numeric_limits::max() > 0xffffffffU) { - BOOST_TEST(passes({.n = std::uint64_t{1} << 32U, .r = 3, .p = 1})); + BOOST_TEST(passes({.cost = std::uint64_t{1} << 32U, .block_size = 3, .parallelism = 1})); } // The output's guard comes first. std::array buffer{}; - auto const refused = hash::scrypt(std::span(buffer.data(), 0), password, salt, - {.n = 0, .r = 0, .p = 0}); + auto const refused = hash::scrypt(std::span(buffer.data(), 0), test_password, + test_salt, {.cost = 0, .block_size = 0, .parallelism = 0}); BOOST_TEST(refused.has_error() && refused.error() == invalid_output_size); } void test_backend_failure() { std::array buffer{}; buffer.fill(untouched); - auto const failed = - hash::scrypt(buffer, password, salt, {.n = 16, .r = 1, .p = 1}); + auto const failed = hash::scrypt( + buffer, test_password, test_salt, {.cost = 16, .block_size = 1, .parallelism = 1}); BOOST_TEST(failed.has_error() && failed.error() == hash::error::backend_failure); BOOST_TEST(all_of(buffer, 0)); // A guard's refusal reaches no backend. - BOOST_TEST( - refuses({.n = 3, .r = 1, .p = 1}, hash::error::invalid_parameters)); + BOOST_TEST(refuses({.cost = 3, .block_size = 1, .parallelism = 1}, + hash::error::invalid_parameters)); } // scrypt's default backend is default_backend's choice for kdfs::scrypt: backends::sodium, the one diff --git a/test/sodium_threads_test.cpp b/test/sodium_threads_test.cpp index 45181b9..9af1cb1 100644 --- a/test/sodium_threads_test.cpp +++ b/test/sodium_threads_test.cpp @@ -41,7 +41,7 @@ int main() { auto const password = bytes_of("password"); std::array const salt{0x5a}; hash::argon2id_parameters const costs{.passes = 1, .memory = 32768}; - hash::scrypt_parameters const scrypt_costs{.n = 16, .r = 1, .p = 1}; + hash::scrypt_parameters const scrypt_costs{.cost = 16, .block_size = 1, .parallelism = 1}; std::array first{}; std::array first_scrypt{}; diff --git a/test/support/argon2_reference.hpp b/test/support/argon2_reference.hpp index 9a33e1b..a5114f1 100644 --- a/test/support/argon2_reference.hpp +++ b/test/support/argon2_reference.hpp @@ -30,7 +30,7 @@ struct argon2_reference_case { std::span secret; std::span associated_data; std::uint32_t passes; - std::uint32_t memory_kib; + std::uint32_t memory_kibibytes; std::uint32_t lanes; argon2_type variant = Argon2_id; }; @@ -54,7 +54,7 @@ inline int argon2_reference(std::span tag, argon2_reference_case c .ad = const_cast(c.associated_data.data()), .adlen = static_cast(c.associated_data.size()), .t_cost = c.passes, - .m_cost = c.memory_kib, + .m_cost = c.memory_kibibytes, .lanes = c.lanes, .threads = c.lanes, .flags = ARGON2_DEFAULT_FLAGS, diff --git a/test/support/hkdf_pieces.hpp b/test/support/hkdf_pieces.hpp new file mode 100644 index 0000000..48bbd30 --- /dev/null +++ b/test/support/hkdf_pieces.hpp @@ -0,0 +1,525 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The equality harness of HKDF over pieces, which every backend's pieces test calls: +// check_hkdf_pieces(name) checks that hkdf_extract, hkdf_expand and hkdf +// over byte_pieces on Backend give the bytes of the single-buffer forms on the concatenation of +// the pieces (design D8), those of Oracle (backends::hash2 by default) and, where Backend has +// them, Backend's own: +// - RFC 5869's seven cases (support/rfc5869.hpp) over the hmac of their hash, each input split at +// every byte offset into two pieces, into one piece per byte with an empty piece between every +// two, as {empty, input, empty}, and, where it is empty, as the empty list; +// - the edge output lengths, each a case of its own: 1 byte, a digest less one byte, a digest, a +// digest and one byte, 255 digests less one byte and 255 digests (the counter's last block), +// each input split at random, as {empty, input, empty} and, where it is empty, as the empty list; +// - 1,000 cases from the fixed seed printed below, each input of 0 to 300 bytes split at random +// points into 0 to 16 pieces (empty pieces among them), outputs of 1 byte to 4 digests, except +// every 100th case, whose output is of 1 byte to 255 digests: the edges above reach the long +// outputs, so the random cases spend their time on the splits, not on the blocks; +// - a list of 10,000 one-byte pieces; +// - long inputs, each in four pieces: an application info of 4 KiB, 32 KiB + 1 and 1 MiB, and an +// input keying material of 1 MiB; up to hkdf_max_application_info_size bytes of application info +// against the single-buffer forms, and every one against reference_hkdf below, RFC 5869 written +// over Boost.Hash2's hmac on the concatenated bytes, and against Backend on another split; +// - the guards: an output of no byte or of 255 digests and one byte (invalid_output_size, the +// output untouched), a pseudorandom key of one byte less than the digest (invalid_key_size). + +#ifndef WEBCPP_TEST_HASH_SUPPORT_HKDF_PIECES_HPP +#define WEBCPP_TEST_HASH_SUPPORT_HKDF_PIECES_HPP + +#include +#include +#include +#include + +#include "../require.hpp" +#include "defaults.hpp" +#include "hex.hpp" +#include "rfc5869.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::test { + +/** The seed of the random cases of HKDF over pieces, "hkdf-pie" in ASCII, printed by each run. */ +inline constexpr std::uint64_t hkdf_pieces_seed = 0x686b64662d706965ULL; + +/** The number of random cases per hmac and backend. */ +inline constexpr std::size_t hkdf_pieces_cases = 1000; + +/** The longest output of most random cases, in digests. */ +inline constexpr std::size_t hkdf_pieces_short_blocks = 4; + +/** Every how many random cases one draws its output from the whole range, 1 byte to 255 digests. */ +inline constexpr std::size_t hkdf_pieces_long_every = 100; + +/** A byte span, one piece. */ +using byte_piece = std::span; + +/** The bytes of a list of pieces, one after another. */ +inline std::vector joined_bytes(hash::byte_pieces pieces) { + std::vector bytes; + for (byte_piece const piece : pieces) { + bytes.insert(bytes.end(), piece.begin(), piece.end()); + } + return bytes; +} + +/** + * RFC 5869 over Boost.Hash2's `hmac` (`Hmac`) on contiguous bytes, independent of hash's code: + * the pseudorandom key of section 2.2, then section 2.3's output of `length` bytes. + */ +template +struct reference_hkdf { + std::vector pseudorandom_key; + std::vector output_key_material; + + reference_hkdf(byte_piece salt, byte_piece input_key_material, byte_piece application_info, + std::size_t length) { + std::size_t const hash_length = typename Hmac::result_type().size(); + std::vector const zeros(hash_length, 0); + byte_piece const key = salt.empty() ? byte_piece(zeros) : salt; + Hmac extract(key.data(), key.size()); + extract.update(input_key_material.data(), input_key_material.size()); + auto const prk = extract.result(); + pseudorandom_key.assign(prk.begin(), prk.end()); + std::vector block; + for (unsigned counter = 1; output_key_material.size() < length; ++counter) { + Hmac expand(pseudorandom_key.data(), pseudorandom_key.size()); + expand.update(block.data(), block.size()); + expand.update(application_info.data(), application_info.size()); + auto const octet = static_cast(counter); + expand.update(&octet, 1); + auto const t = expand.result(); + block.assign(t.begin(), t.end()); + std::size_t const taken = std::min(block.size(), length - output_key_material.size()); + output_key_material.insert(output_key_material.end(), block.begin(), + block.begin() + static_cast(taken)); + } + } +}; + +/** + * The random draws of the cases, the same on every standard library: std::mt19937_64's sequence + * is the standard's, and a draw in a range is the modulo of one output. + */ +class pieces_random { +public: + explicit pieces_random(std::uint64_t seed) : engine_(seed) {} + + /** A value in [low, high]. */ + std::size_t between(std::size_t low, std::size_t high) { + return low + static_cast(engine_() % (std::uint64_t{high - low} + 1)); + } + + /** `size` random bytes. */ + std::vector bytes(std::size_t size) { + std::vector out(size); + for (auto& b : out) { + b = static_cast(engine_() >> 56U); + } + return out; + } + + /** + * `input` split at random points into 0 to 16 pieces, at least one when it is not empty; + * points drawn twice, or at an end, make empty pieces. + */ + std::vector split(byte_piece input) { + std::size_t count = between(0, 16); + if (count == 0 && !input.empty()) { + count = 1; + } + std::vector points; + for (std::size_t i = 1; i < count; ++i) { + points.push_back(between(0, input.size())); + } + std::ranges::sort(points); + std::vector pieces; + std::size_t start = 0; + for (std::size_t const point : points) { + pieces.push_back(input.subspan(start, point - start)); + start = point; + } + if (count != 0) { + pieces.push_back(input.subspan(start)); + } + return pieces; + } + +private: + std::mt19937_64 engine_; +}; + +/** `input` in `count` pieces of nearly equal sizes, the last one the longest. */ +inline std::vector even_split(byte_piece input, std::size_t count) { + std::vector pieces; + std::size_t const size = input.size() / count; + for (std::size_t i = 0; i + 1 < count; ++i) { + pieces.push_back(input.subspan(i * size, size)); + } + pieces.push_back(input.subspan((count - 1) * size)); + return pieces; +} + +/** `input` in one piece per byte, with an empty piece between every two. */ +inline std::vector bytewise_split(byte_piece input) { + std::vector pieces; + for (std::size_t i = 0; i != input.size(); ++i) { + if (i != 0) { + pieces.emplace_back(); + } + pieces.push_back(input.subspan(i, 1)); + } + return pieces; +} + +/** Where one check runs, printed on a failure. */ +struct pieces_place { + std::string_view backend; + std::string_view hmac; + std::string_view what; + std::size_t index = 0; +}; + +inline std::ostream& operator<<(std::ostream& out, pieces_place const& place) { + return out << " HKDF over pieces on " << place.backend << " over " << place.hmac << ": " + << place.what << " " << place.index << " (seed 0x" << std::hex << hkdf_pieces_seed + << std::dec << ")\n"; +} + +/** + * The three pieces forms on Backend for one case, against the expected pseudorandom key and output + * keying material: hkdf_extract over `input_key_material`, hkdf_expand over `application_info` + * under the expected key, and hkdf over both. + */ +template +void expect_pieces(pieces_place const& place, byte_piece salt, hash::byte_pieces input_key_material, + hash::byte_pieces application_info, std::vector const& prk, + std::vector const& okm) { + auto const extracted = hash::hkdf_extract(salt, input_key_material); + if (!BOOST_TEST(extracted.has_value()) || !BOOST_TEST(std::ranges::equal(*extracted, prk))) { + std::cerr << "hkdf_extract" << place; + } + std::vector expanded(okm.size()); + auto const expanded_done = hash::hkdf_expand(expanded, prk, application_info); + if (!BOOST_TEST(expanded_done.has_value()) || !BOOST_TEST(expanded == okm)) { + std::cerr << "hkdf_expand" << place; + } + std::vector whole(okm.size()); + auto const whole_done = + hash::hkdf(whole, salt, input_key_material, application_info); + if (!BOOST_TEST(whole_done.has_value()) || !BOOST_TEST(whole == okm)) { + std::cerr << "hkdf" << place; + } +} + +/** + * The single-buffer forms on `Single` over the concatenations, each step where `Single` has it, + * against the expected key and output: the oracle of a pieces case, checked once more. + */ +template +void expect_single(pieces_place const& place, byte_piece salt, byte_piece input_key_material, + byte_piece application_info, std::vector const& prk, + std::vector const& okm) { + if constexpr (hash::backend_has_v) { + auto const extracted = hash::hkdf_extract(salt, input_key_material); + if (!BOOST_TEST(extracted.has_value()) || + !BOOST_TEST(std::ranges::equal(*extracted, prk))) { + std::cerr << "single-buffer hkdf_extract on " << name_of() << place; + } + } + if constexpr (hash::backend_has_v) { + std::vector expanded(okm.size()); + auto const done = hash::hkdf_expand(expanded, prk, application_info); + if (!BOOST_TEST(done.has_value()) || !BOOST_TEST(expanded == okm)) { + std::cerr << "single-buffer hkdf_expand on " << name_of() << place; + } + } + if constexpr (hash::backend_has_v) { + std::vector whole(okm.size()); + auto const done = + hash::hkdf(whole, salt, input_key_material, application_info); + if (!BOOST_TEST(done.has_value()) || !BOOST_TEST(whole == okm)) { + std::cerr << "single-buffer hkdf on " << name_of() << place; + } + } +} + +/** + * One case whose expected bytes the single-buffer forms give: Oracle's computes them, Backend's + * own, where Backend has them and is not Oracle, gives them too, and the pieces forms on Backend + * over every listed split of the inputs give them. + */ +template +void check_case(pieces_place const& place, byte_piece salt, byte_piece input_key_material, + byte_piece application_info, std::size_t length, + std::vector> const& input_splits, + std::vector> const& info_splits) { + auto const oracle_prk = hash::hkdf_extract(salt, input_key_material); + require(oracle_prk.has_value()); + std::vector const prk(oracle_prk->begin(), oracle_prk->end()); + std::vector okm(length); + require(hash::hkdf_expand(okm, prk, application_info).has_value()); + if constexpr (!std::is_same_v && hash::detail::linked_v) { + expect_single(place, salt, input_key_material, application_info, prk, okm); + } + for (std::size_t i = 0; i != std::max(input_splits.size(), info_splits.size()); ++i) { + auto const& ikm = input_splits[i % input_splits.size()]; + auto const& info = info_splits[i % info_splits.size()]; + pieces_place here = place; + here.index = (place.index * 1000) + i; + expect_pieces(here, salt, ikm, info, prk, okm); + } +} + +/** RFC 5869's cases over the hmac of their hash: every split of section D8, and the vector. */ +template +void check_rfc5869(std::string_view backend) { + std::vector const cases = [] { + if constexpr (std::is_same_v) { + return std::vector{a1, a2, a3}; + } else if constexpr (std::is_same_v) { + return std::vector{a4, a5, a6, a7}; + } else { + return std::vector{}; + } + }(); + std::size_t index = 0; + for (rfc5869_case const& c : cases) { + auto const ikm = from_hex(c.ikm); + auto const salt = from_hex(c.salt); + auto const info = from_hex(c.info); + auto const prk = from_hex(c.prk); + auto const okm = from_hex(c.okm); + pieces_place const place{backend, name_of_hmac(), "RFC 5869 case", ++index}; + + // Every split in two, of each input; then one piece per byte, then {empty, input, empty}; + // where an input is empty, also the empty list and {empty}, one empty piece. + std::vector> ikm_splits; + std::vector> info_splits; + for (std::size_t at = 0; at <= ikm.size(); ++at) { + ikm_splits.push_back({byte_piece(ikm).first(at), byte_piece(ikm).subspan(at)}); + } + for (std::size_t at = 0; at <= info.size(); ++at) { + info_splits.push_back({byte_piece(info).first(at), byte_piece(info).subspan(at)}); + } + ikm_splits.push_back(bytewise_split(ikm)); + info_splits.push_back(bytewise_split(info)); + ikm_splits.push_back({byte_piece{}, byte_piece(ikm), byte_piece{}}); + info_splits.push_back({byte_piece{}, byte_piece(info), byte_piece{}}); + if (info.empty()) { + // The empty list, then one empty piece. + info_splits.emplace_back(); + info_splits.push_back(std::vector{byte_piece{}}); + } + if (ikm.empty()) { + ikm_splits.emplace_back(); + ikm_splits.push_back(std::vector{byte_piece{}}); + } + for (std::size_t i = 0; i != std::max(ikm_splits.size(), info_splits.size()); ++i) { + pieces_place here = place; + here.index = (place.index * 1000) + i; + expect_pieces(here, salt, ikm_splits[i % ikm_splits.size()], + info_splits[i % info_splits.size()], prk, okm); + } + // The vector's bytes are also the oracle's. + check_case(place, salt, ikm, info, c.length, {{byte_piece(ikm)}}, + {{byte_piece(info)}}); + expect_single(place, salt, ikm, info, prk, okm); + } +} + +/** + * The edge output lengths, each in a case of its own: 1 byte, a digest less one byte, a digest, a + * digest and one byte, 255 digests less one byte and 255 digests. Each input is split at random, + * as {empty, input, empty} and, where it is empty, as the empty list and as {empty}, one empty + * piece. The refused lengths, no byte and 255 digests and one byte, are check_guards'. + */ +template +void check_edges(std::string_view backend) { + std::size_t const hash_length = typename Hmac::result_type().size(); + std::array const lengths{ + 1, + hash_length - 1, + hash_length, + hash_length + 1, + (255 * hash_length) - 1, + 255 * hash_length, + }; + pieces_random random(hkdf_pieces_seed + 2); + std::size_t index = 0; + for (std::size_t const length : lengths) { + // An empty input keying material and application info once, then random ones. + std::size_t const most = index == 0 ? 0 : 300; + auto const salt = random.bytes(random.between(0, 300)); + auto const ikm = random.bytes(random.between(0, most)); + auto const info = random.bytes(random.between(0, most)); + std::vector> ikm_splits{ + random.split(ikm), + {byte_piece{}, byte_piece(ikm), byte_piece{}}, + }; + std::vector> info_splits{ + random.split(info), + {byte_piece{}, byte_piece(info), byte_piece{}}, + }; + if (ikm.empty()) { + // The empty list, then one empty piece. + ikm_splits.emplace_back(); + ikm_splits.push_back(std::vector{byte_piece{}}); + } + if (info.empty()) { + info_splits.emplace_back(); + info_splits.push_back(std::vector{byte_piece{}}); + } + check_case({backend, name_of_hmac(), "edge length", ++index}, + salt, ikm, info, length, ikm_splits, info_splits); + } +} + +/** + * The random cases: inputs of 0 to 300 bytes in 0 to 16 pieces, outputs of 1 byte to 4 digests, + * of 1 byte to 255 digests in every 100th case. + */ +template +void check_random(std::string_view backend) { + std::size_t const hash_length = typename Hmac::result_type().size(); + pieces_random random(hkdf_pieces_seed); + for (std::size_t index = 0; index != hkdf_pieces_cases; ++index) { + auto const salt = random.bytes(random.between(0, 300)); + auto const ikm = random.bytes(random.between(0, 300)); + auto const info = random.bytes(random.between(0, 300)); + std::size_t const blocks = + index % hkdf_pieces_long_every == 0 ? 255 : hkdf_pieces_short_blocks; + std::size_t const length = random.between(1, blocks * hash_length); + std::vector> const ikm_splits{random.split(ikm)}; + std::vector> const info_splits{random.split(info)}; + check_case({backend, name_of_hmac(), "random case", index}, + salt, ikm, info, length, ikm_splits, info_splits); + } +} + +/** Long inputs and many pieces, against the single-buffer forms where they take the input and + * against reference_hkdf and another split always. */ +template +void check_long(std::string_view backend) { + pieces_random random(hkdf_pieces_seed + 1); + auto const salt = random.bytes(13); + auto const short_input = random.bytes(40); + + // 10,000 one-byte pieces, of each input. + { + auto const many = random.bytes(10000); + std::vector bytes; + for (std::size_t i = 0; i != many.size(); ++i) { + bytes.push_back(byte_piece(many).subspan(i, 1)); + } + check_case({backend, name_of_hmac(), "one-byte pieces", 1}, + salt, many, short_input, 100, {bytes}, {{short_input}}); + check_case({backend, name_of_hmac(), "one-byte pieces", 2}, + salt, short_input, many, 100, {{short_input}}, {bytes}); + } + + // Long inputs in four pieces. + constexpr std::array info_sizes{ + 4096, + hash::hkdf_max_application_info_size + 1, + std::size_t{1} << 20U, + }; + std::size_t index = 0; + for (std::size_t const size : info_sizes) { + auto const info = random.bytes(size); + pieces_place const place{backend, name_of_hmac(), "long application info", ++index}; + reference_hkdf const reference(salt, short_input, info, 42); + if (size <= hash::hkdf_max_application_info_size) { + check_case(place, salt, short_input, info, 42, {{short_input}}, + {even_split(info, 4)}); + } + expect_pieces(place, salt, {byte_piece(short_input)}, even_split(info, 4), + reference.pseudorandom_key, reference.output_key_material); + expect_pieces(place, salt, even_split(short_input, 3), even_split(info, 7), + reference.pseudorandom_key, reference.output_key_material); + } + { + auto const ikm = random.bytes(std::size_t{1} << 20U); + pieces_place const place{backend, name_of_hmac(), "long input keying material", 1}; + reference_hkdf const reference(salt, ikm, short_input, 42); + // The single-buffer forms cap no input keying material. + check_case(place, salt, ikm, short_input, 42, {even_split(ikm, 4)}, + {{short_input}}); + expect_pieces(place, salt, even_split(ikm, 4), {byte_piece(short_input)}, + reference.pseudorandom_key, reference.output_key_material); + expect_pieces(place, salt, even_split(ikm, 9), {byte_piece(short_input)}, + reference.pseudorandom_key, reference.output_key_material); + } +} + +/** The guards: RFC 5869's output and pseudorandom key sizes, the output untouched. */ +template +void check_guards(std::string_view backend) { + std::size_t const hash_length = typename Hmac::result_type().size(); + std::array const bytes{1, 2, 3, 4, 5}; + byte_piece const input(bytes); + std::vector const prk(hash_length, 0x0b); + auto const refused = [&](char const* what, auto const& done, hash::error expected, + std::vector const& output) { + bool const untouched = + std::ranges::all_of(output, [](std::uint8_t b) { return b == 0xa5; }); + if (!BOOST_TEST(!done.has_value() && done.error() == expected) || !BOOST_TEST(untouched)) { + std::cerr << " the guard of " << what << " on " << backend << " over " + << name_of_hmac() << '\n'; + } + }; + for (std::size_t const size : {std::size_t{0}, (255 * hash_length) + 1}) { + std::vector output(size, 0xa5); + refused("hkdf_expand's output size", + hash::hkdf_expand(output, prk, {input, input}), + hash::error::invalid_output_size, output); + refused("hkdf's output size", + hash::hkdf(output, input, {input, input}, {input, input}), + hash::error::invalid_output_size, output); + } + std::vector output(42, 0xa5); + refused("hkdf_expand's pseudorandom key size", + hash::hkdf_expand(output, byte_piece(prk).first(hash_length - 1), + {input, input}), + hash::error::invalid_key_size, output); + // The largest output is taken. + std::vector largest(255 * hash_length); + BOOST_TEST((hash::hkdf_expand(largest, prk, {input, input}).has_value())); +} + +/** + * Every check of the harness over `Hmac` on `Backend`, against `Oracle`'s single-buffer forms. + * + * @param backend Backend's name, as a failure names it. + */ +template +void check_hkdf_pieces(std::string_view backend) { + std::cout << "HKDF over pieces on " << backend << " over " << name_of_hmac() + << ", random cases from the seed 0x" << std::hex << hkdf_pieces_seed << std::dec + << '\n'; + check_rfc5869(backend); + check_edges(backend); + check_random(backend); + check_long(backend); + check_guards(backend); +} + +} // namespace webcpp::test + +#endif // WEBCPP_TEST_HASH_SUPPORT_HKDF_PIECES_HPP diff --git a/test/support/mock_backend.hpp b/test/support/mock_backend.hpp index e5e237e..4ee60ea 100644 --- a/test/support/mock_backend.hpp +++ b/test/support/mock_backend.hpp @@ -256,7 +256,7 @@ template <> struct argon2_engine<::webcpp::test::mock, kdfs::argon2id> { static constexpr argon2_limits limits{ .min_passes = 3, - .max_memory_kib = 1U << 20U, + .max_memory_kibibytes = 1U << 20U, .max_lanes = 1, .min_output = 16, .min_salt = 16, @@ -276,7 +276,7 @@ struct argon2_engine<::webcpp::test::mock, kdfs::argon2id> { } ::webcpp::test::mock_fill(output, ::webcpp::test::mock_sum(password) + ::webcpp::test::mock_sum(salt) + parameters.passes + - parameters.memory_kib); + parameters.memory_kibibytes); return {}; } }; diff --git a/test/support/timing_coverage.hpp b/test/support/timing_coverage.hpp index 1e8502b..dafb464 100644 --- a/test/support/timing_coverage.hpp +++ b/test/support/timing_coverage.hpp @@ -215,7 +215,8 @@ inline constexpr std::string_view bcrypt_verify_cell = "bcrypt_verify"; * * A cell is named as the table names its function: `` (`scrypt`), `<>` * for each hmac the cell lists (`hkdf`, `hkdf`), `mac<>` for a tag of - * `mac` (`mac`), `<>` for a variant (`argon2`). + * `mac` (`mac`), `<>` for a variant (`argon2`); + * a row of a form of its function adds ` over ` (`hkdf over pieces`). * The keyed functions: `digests::blake2b keyed` (digest_of and a hasher round with a key) * wherever the table has a cell of digests::blake2b; `blake3 keyed` (the blake3 type's keyed * modes) wherever it has the blake3 type; `bcrypt_verify` wherever it has bcrypt. @@ -241,6 +242,9 @@ inline std::vector keyed_cells(std::string_view backend) { continue; } std::string const name(function.at("name").as_string()); + auto const* const form_value = function.if_contains("form"); + std::string const form = + form_value == nullptr ? "" : " over " + std::string(form_value->as_string()); std::string base = name; if (kind == "mac") { base = "mac<" + name + ">"; @@ -249,11 +253,13 @@ inline std::vector keyed_cells(std::string_view backend) { } auto const& hmacs = cell->as_object().at("hmacs"); if (hmacs.is_null()) { - cells.push_back(base); + cells.push_back(base.append(form)); continue; } for (auto const& hmac : hmacs.as_array()) { - cells.push_back(base + "<" + std::string(hmac.as_string()) + ">"); + std::string named = base; + named.append("<").append(hmac.as_string()).append(">").append(form); + cells.push_back(std::move(named)); } } } @@ -574,6 +580,63 @@ void cover_hkdf() { }); } +/** Two pieces of coverage_input, and an empty one between them: HKDF's input over pieces. */ +inline std::array, 3> coverage_pieces() { + std::span const input(coverage_input); + return {input.first(5), std::span{}, input.subspan(5)}; +} + +/** + * `hkdf_extract` over pieces, over `Hmac` on `Backend`. No call of it is refused before the + * backend but one past a backend's own key limit, which no backend has small enough to reach here. + */ +template +void cover_hkdf_extract_pieces() { + std::string const on = coverage_over(); + auto const pieces = coverage_pieces(); + covered("hash::hkdf_extract over pieces" + on, "hash::hkdf_extract(byte_pieces", [&] { + BOOST_TEST((hash::hkdf_extract(coverage_salt, pieces)).has_value()); + }); +} + +/** + * `hkdf_expand` over pieces, over `Hmac` on `Backend`, then with an output of no byte. + */ +template +void cover_hkdf_expand_pieces() { + std::string const on = coverage_over(); + std::vector const prk(typename Hmac::result_type().size(), 0x0b); + std::array output{}; + auto const pieces = coverage_pieces(); + covered("hash::hkdf_expand over pieces" + on, "hash::hkdf_expand(byte_pieces", [&] { + BOOST_TEST((hash::hkdf_expand(output, prk, pieces)).has_value()); + }); + covered( + "hash::hkdf_expand over pieces with an output of no byte" + on, + "hash::hkdf_expand(byte_pieces", [&] { + BOOST_TEST((hash::hkdf_expand(std::span{}, prk, pieces)) + .error() == hash::error::invalid_output_size); + }); +} + +/** + * `hkdf` over pieces, over `Hmac` on `Backend`, then with an output of no byte. + */ +template +void cover_hkdf_pieces() { + std::string const on = coverage_over(); + std::array output{}; + auto const pieces = coverage_pieces(); + covered("hash::hkdf over pieces" + on, "hash::hkdf(byte_pieces", [&] { + BOOST_TEST((hash::hkdf(output, coverage_salt, pieces, pieces)).has_value()); + }); + covered("hash::hkdf over pieces with an output of no byte" + on, "hash::hkdf(byte_pieces", [&] { + BOOST_TEST( + (hash::hkdf(std::span{}, coverage_salt, pieces, pieces)) + .error() == hash::error::invalid_output_size); + }); +} + /** * `pbkdf2` over `Hmac` on `Backend`, of one iteration, then of none. */ @@ -612,7 +675,7 @@ void cover_kbkdf() { /** * The calls of the functions over an hmac that `Backend` has over `Hmac`: hkdf_extract, - * hkdf_expand, hkdf, pbkdf2 and kbkdf, each by the name of its cell. + * hkdf_expand, hkdf, each also over pieces, pbkdf2 and kbkdf, each by the name of its cell. * * @param calls Where the calls go. */ @@ -629,6 +692,17 @@ void add_hmac_calls(coverage_calls& calls) { if constexpr (coverage_has_v) { calls.emplace("hkdf" + column, [] { cover_hkdf(); }); } + if constexpr (coverage_has_v) { + calls.emplace("hkdf_extract" + column + " over pieces", + [] { cover_hkdf_extract_pieces(); }); + } + if constexpr (coverage_has_v) { + calls.emplace("hkdf_expand" + column + " over pieces", + [] { cover_hkdf_expand_pieces(); }); + } + if constexpr (coverage_has_v) { + calls.emplace("hkdf" + column + " over pieces", [] { cover_hkdf_pieces(); }); + } if constexpr (coverage_has_v) { calls.emplace("pbkdf2" + column, [] { cover_pbkdf2(); }); } @@ -712,7 +786,7 @@ void cover_argon2id() { template void cover_argon2(std::string_view variant) { std::string const on = " of " + std::string(variant) + coverage_on(); - hash::argon2_parameters const family{.passes = 3, .memory_kib = 8}; + hash::argon2_parameters const family{.passes = 3, .memory_kibibytes = 8}; std::array output{}; covered("hash::argon2" + on, [&] { BOOST_TEST((hash::argon2(output, coverage_key, coverage_salt, family)) @@ -731,14 +805,14 @@ void cover_scrypt() { std::string const on = coverage_on(); std::array output{}; covered("hash::scrypt of N = 16" + on, [&] { - BOOST_TEST( - (hash::scrypt(output, coverage_key, coverage_salt, {.n = 16, .r = 1, .p = 1})) - .has_value()); + BOOST_TEST((hash::scrypt(output, coverage_key, coverage_salt, + {.cost = 16, .block_size = 1, .parallelism = 1})) + .has_value()); }); covered("hash::scrypt of N = 1" + on, [&] { - BOOST_TEST( - (hash::scrypt(output, coverage_key, coverage_salt, {.n = 1, .r = 1, .p = 1})) - .error() == hash::error::invalid_parameters); + BOOST_TEST((hash::scrypt(output, coverage_key, coverage_salt, + {.cost = 1, .block_size = 1, .parallelism = 1})) + .error() == hash::error::invalid_parameters); }); } diff --git a/test/support/wipe_record.hpp b/test/support/wipe_record.hpp new file mode 100644 index 0000000..2c5c3f2 --- /dev/null +++ b/test/support/wipe_record.hpp @@ -0,0 +1,92 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The test seam of detail::wipe, recorded: a program built with +// WEBCPP_HASH_DETAIL_TEST_WIPE_RECORD includes this header once, which defines the seam's function +// detail::test::wipe_record. Each wipe is recorded in wipes, and wiped_sizes() returns the sizes +// of the wipes since its last call, checking that each wipe left only zero bytes; clear_wipes() +// discards them, however many. + +#ifndef WEBCPP_TEST_HASH_SUPPORT_WIPE_RECORD_HPP +#define WEBCPP_TEST_HASH_SUPPORT_WIPE_RECORD_HPP + +#ifndef WEBCPP_HASH_DETAIL_TEST_WIPE_RECORD +#error "support/wipe_record.hpp is for a program built with WEBCPP_HASH_DETAIL_TEST_WIPE_RECORD" +#endif + +#include + +#include + +#include +#include +#include +#include + +namespace webcpp::test { + +/** + * The wipes since the last clear: their sizes in order (the first ones), how many, and how many + * found a byte that was not zero. Fixed storage: the seam is noexcept and allocates nothing, so a + * wipe past the storage is counted but its size is not kept, and wiped_sizes() reports it. + */ +struct wipe_log { + std::array sizes{}; + std::size_t count = 0; + std::size_t not_zero = 0; +}; + +/** The seam's record, which detail::wipe reaches through detail::test::wipe_record. */ +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the seam's record +inline wipe_log wipes; + +/** + * The sizes of the wipes since the last call, which clears the record; every wipe must have left + * only zero bytes, and every size must have fit the record's storage. + */ +inline std::vector wiped_sizes() { + BOOST_TEST_LE(wipes.count, wipes.sizes.size()); + std::vector const sizes( + wipes.sizes.begin(), wipes.sizes.begin() + static_cast( + std::min(wipes.count, wipes.sizes.size()))); + BOOST_TEST_EQ(wipes.not_zero, 0U); + wipes = {}; + return sizes; +} + +/** + * Clears the record without reading the sizes, however many wipes it counted (the work before a + * checked step, which may wipe more often than the record keeps); every wipe must still have left + * only zero bytes. + */ +inline void clear_wipes() { + BOOST_TEST_EQ(wipes.not_zero, 0U); + wipes = {}; +} + +} // namespace webcpp::test + +// The seam's function, declared by detail/wipe.hpp, defined once by the program that includes +// this header. +// NOLINTBEGIN(misc-definitions-in-headers) +void webcpp::hash::detail::test::wipe_record(void const* wiped_data, + std::size_t byte_count) noexcept { + auto& log = ::webcpp::test::wipes; + auto const* const bytes = static_cast(wiped_data); + // Checked here, so that the store cannot throw: the seam is noexcept. A wipe past the storage + // is only counted, and wiped_sizes() fails the test on it. + if (log.count < log.sizes.size()) { + log.sizes[log.count] = byte_count; + } + ++log.count; + if (!std::all_of(bytes, bytes + byte_count, [](unsigned char b) { return b == 0; })) { + ++log.not_zero; + } +} + +// NOLINTEND(misc-definitions-in-headers) + +#endif // WEBCPP_TEST_HASH_SUPPORT_WIPE_RECORD_HPP diff --git a/test/timing_async_test.cpp b/test/timing_async_test.cpp index 77fa733..186163e 100644 --- a/test/timing_async_test.cpp +++ b/test/timing_async_test.cpp @@ -11,8 +11,10 @@ // WEBCPP_TEST_TIMING_ASYNC_BOTAN the same on backends::botan with async_bcrypt, async_bcrypt_verify // and async_bcrypt_pbkdf) on a webcpp::asio::thread_pool of one thread entered the guard of its // synchronous function first on the pool's thread and none on the calling thread; the cheap ones -// (async_hmac, async_hkdf) entered mac's and hkdf's on the calling thread, during the initiation, -// and none on the pool's; async_digest, unkeyed, entered none on either; and a cancellation before +// (async_hmac, async_hkdf_extract, async_hkdf_expand and async_hkdf, each HKDF function also over +// byte pieces) entered mac's, hkdf_extract's, hkdf_expand's and hkdf's on the calling thread, +// during the initiation, each pieces form the guard of its synchronous pieces overload, and none +// on the pool's; async_digest, unkeyed, entered none on either; and a cancellation before // the heavy work starts entered none anywhere. After each completion, the pool's thread and the // calling thread are back to DIT off (where the CPU has it). The threads are synchronised by // futures and by probes posted to the pool and completed through the io_context, never by sleeps; @@ -225,13 +227,14 @@ void check_heavy(asio::io_context& context, asio::thread_pool& pool) { heavy("async_argon2", "hash::argon2", context, pool, [&](auto handler) { hash::async_argon2, kdfs::argon2id, kdfs::argon2i>, - argon2_backend>(work, output, test_password, test_salt, - {.passes = 3, .memory_kib = 64, .lanes = argon2_lanes}, - std::move(handler)); + argon2_backend>( + work, output, test_password, test_salt, + {.passes = 3, .memory_kibibytes = 64, .lanes = argon2_lanes}, std::move(handler)); }); heavy("async_scrypt", "hash::scrypt", context, pool, [&](auto handler) { hash::async_scrypt(work, output, test_password, test_salt, - {.n = 1024, .r = 8, .p = 1}, std::move(handler)); + {.cost = 1024, .block_size = 8, .parallelism = 1}, + std::move(handler)); }); #ifdef WEBCPP_TEST_TIMING_ASYNC_BOTAN std::array stored{}; @@ -274,6 +277,32 @@ void check_cheap(asio::io_context& context, asio::thread_pool& pool) { hash::async_hkdf(loop, output, test_salt, key, test_password, std::move(handler)); }); + std::array, 2> const pieces{ + std::span(test_password).first(3), + std::span(test_password).subspan(3), + }; + cheap("async_hkdf over pieces", "hash::hkdf(byte_pieces", context, pool, [&](auto handler) { + hash::async_hkdf(loop, output, test_salt, pieces, pieces, + std::move(handler)); + }); + cheap("async_hkdf_extract", "hash::hkdf_extract", context, pool, [&](auto handler) { + hash::async_hkdf_extract(loop, output, test_salt, test_password, + std::move(handler)); + }); + cheap("async_hkdf_extract over pieces", "hash::hkdf_extract(byte_pieces", context, pool, + [&](auto handler) { + hash::async_hkdf_extract(loop, output, test_salt, pieces, + std::move(handler)); + }); + cheap("async_hkdf_expand", "hash::hkdf_expand", context, pool, [&](auto handler) { + hash::async_hkdf_expand(loop, output, key, test_password, + std::move(handler)); + }); + cheap("async_hkdf_expand over pieces", "hash::hkdf_expand(byte_pieces", context, pool, + [&](auto handler) { + hash::async_hkdf_expand(loop, output, key, pieces, + std::move(handler)); + }); // async_digest is unkeyed: no thread enters a guard. reset_pool_thread(pool); @@ -328,7 +357,8 @@ void check_cancelled_before(asio::io_context& context) { }); cancelled([&](auto handler) { hash::async_scrypt(work, output, test_password, test_salt, - {.n = 1024, .r = 8, .p = 1}, std::move(handler)); + {.cost = 1024, .block_size = 8, .parallelism = 1}, + std::move(handler)); }); #ifdef WEBCPP_TEST_TIMING_ASYNC_BOTAN std::array stored{}; diff --git a/test/timing_coverage_bearssl_test.cpp b/test/timing_coverage_bearssl_test.cpp index b8e7db1..0526dd4 100644 --- a/test/timing_coverage_bearssl_test.cpp +++ b/test/timing_coverage_bearssl_test.cpp @@ -14,7 +14,8 @@ // to the table; a cell of a family or function the support does not know fails here until its // call is written: // - mac over hmac for MD5, SHA-1, SHA-224, SHA-256, SHA-384 and SHA-512. -// - hkdf over the six hmacs of those digests. +// - hkdf, and hkdf_extract, hkdf_expand and hkdf over pieces, over the six hmacs of those +// digests. // - Not guarded: each digest cell, through digest_of and a hasher round. #include "support/timing_coverage.hpp" diff --git a/test/timing_coverage_botan_test.cpp b/test/timing_coverage_botan_test.cpp index ebcc69c..6902691 100644 --- a/test/timing_coverage_botan_test.cpp +++ b/test/timing_coverage_botan_test.cpp @@ -15,8 +15,8 @@ // call is written: // - mac over siphash_2_4, kmac_128, kmac_256, blake2b_mac and hmac for the 23 digests of // the backend's cells. -// - hkdf_extract, hkdf_expand, hkdf, pbkdf2 and kbkdf over each of the 14 hmacs the cells list; -// sskdf and x963kdf. +// - hkdf_extract, hkdf_expand, hkdf (each also over pieces), pbkdf2 and kbkdf over each of the 14 +// hmacs the cells list; sskdf and x963kdf. // - argon2id; argon2 of argon2d, argon2i and argon2id; scrypt; bcrypt and bcrypt_pbkdf. // - bcrypt_verify (ruling H12) and BLAKE2b with a key, digest_of and a hasher round (design D1), // which the table holds no cell of. diff --git a/test/timing_coverage_hash2_test.cpp b/test/timing_coverage_hash2_test.cpp index 17a9099..a8a1b9b 100644 --- a/test/timing_coverage_hash2_test.cpp +++ b/test/timing_coverage_hash2_test.cpp @@ -15,8 +15,8 @@ // to the table; a cell of a family or function the support does not know fails here until its // call is written: // - mac over siphash_2_4, blake2s_mac and hmac for each digest of the backend's cells. -// - hkdf_extract, hkdf_expand, hkdf and pbkdf2 over each hmac of hmac.hpp and over another Hash2 -// hmac (the column "other"). +// - hkdf_extract, hkdf_expand and hkdf, each also over pieces, and pbkdf2 over each hmac of +// hmac.hpp and over another Hash2 hmac (the column "other"). // - BLAKE2b with a key: digest_of and a hasher round (design D1). // - Not guarded: each digest cell without a key, through digest_of and a hasher round; the Hash2 // types (md5_128 to spooky2_128, siphash_32 and siphash_64, hmac and its aliases). diff --git a/test/timing_coverage_openssl_test.cpp b/test/timing_coverage_openssl_test.cpp index 69bcc43..8d2daed 100644 --- a/test/timing_coverage_openssl_test.cpp +++ b/test/timing_coverage_openssl_test.cpp @@ -15,8 +15,8 @@ // call is written: // - mac over siphash_2_4, siphash_2_4x, kmac_128, kmac_256, blake2b_mac, blake2s_mac and // hmac for each digest of the backend's cells. -// - hkdf_extract, hkdf_expand, hkdf, pbkdf2 and kbkdf over each hmac of hmac.hpp the cells list -// (all but hmac_ripemd_128); sskdf and x963kdf. +// - hkdf_extract, hkdf_expand, hkdf (each also over pieces), pbkdf2 and kbkdf over each hmac of +// hmac.hpp the cells list (all but hmac_ripemd_128); sskdf and x963kdf. // - argon2id; argon2 of argon2d, argon2i and argon2id; scrypt. // - BLAKE2b with a key (design D1): digest_of and hasher::make, which the cell refuses // (unsupported_by_backend) inside the guard. diff --git a/test/timing_coverage_sodium_test.cpp b/test/timing_coverage_sodium_test.cpp index a9cb750..8c73d9b 100644 --- a/test/timing_coverage_sodium_test.cpp +++ b/test/timing_coverage_sodium_test.cpp @@ -14,7 +14,8 @@ // to the table; a cell of a family or function the support does not know fails here until its // call is written: // - mac over siphash_2_4, siphash_2_4x, blake2b_mac, hmac and hmac. -// - hkdf_extract, hkdf_expand and hkdf over hmac_sha2_256 and hmac_sha2_512; blake2b_subkey. +// - hkdf_extract, hkdf_expand and hkdf, each also over pieces, over hmac_sha2_256 and +// hmac_sha2_512; blake2b_subkey. // - argon2id; argon2 of argon2i and argon2id; scrypt. // - BLAKE2b with a key: digest_of and a hasher round (design D1). // - Not guarded: each digest cell without a key, through digest_of and a hasher round. diff --git a/test/timing_during_test.cpp b/test/timing_during_test.cpp index 743101c..8100779 100644 --- a/test/timing_during_test.cpp +++ b/test/timing_during_test.cpp @@ -4,16 +4,19 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// DIT is set while a keyed function computes (design D1; spec scenario "A password derived on -// Apple silicon"): a Boost.Hash2-form hash, dit_probe, records at each update whether DIT was set -// and whether a detail::timing_guard had been entered, and runs as the hash under the hmac of -// hkdf_extract, hkdf_expand, hkdf and pbkdf2 on backends::hash2, and of mac on a stand-in backend -// whose HMAC-SHA-256 is backends::hash2's over the probe. From a thread with DIT clear, every -// update the probe saw ran after a guard was entered and, where the CPU has DIT, with DIT set (and -// clear where it has none); the thread finds DIT clear after the call. A guard that the engine -// call precedes, or one written as a temporary, fails here. With WEBCPP_TEST_TIMING_DURING_ASYNC, -// the same through async_pbkdf2 on a webcpp::asio::thread_pool of one thread, the probe's record -// read on the pool's thread, which computes. +// DIT is set while a keyed function computes (design D1; spec scenario "A password derived on Apple +// silicon"): a Boost.Hash2-form hash, dit_probe, records at each update whether DIT was set and +// whether a detail::timing_guard had been entered, and runs as the hash under the hmac of +// hkdf_extract, hkdf_expand, hkdf (each also over byte pieces) and pbkdf2 on backends::hash2, and +// of mac on a stand-in backend whose HMAC-SHA-256 is backends::hash2's over the probe. From a +// thread with DIT clear, every update the probe saw ran after a guard was entered and, where the +// CPU has DIT, with DIT set (and clear where it has none); the thread finds DIT clear after the +// call. A guard that the engine call precedes, or one written as a temporary, fails here. With +// WEBCPP_TEST_TIMING_DURING_ASYNC, the same through async_pbkdf2 on a webcpp::asio::thread_pool of +// one thread, the probe's record read on the pool's thread, which computes; and through +// async_hkdf_extract, async_hkdf_expand and async_hkdf over pieces on a stand-in backend whose +// HKDF over pieces with HMAC-SHA-256 is backends::hash2's over the probe, which compute in the +// initiating call, on the calling thread. #include "support/timing_dit.hpp" @@ -121,7 +124,7 @@ class dit_probe { boost::hash2::sha2_256 inner_; }; -/** A backend whose HMAC-SHA-256 is backends::hash2's over dit_probe. */ +/** A backend whose HMAC-SHA-256 and HKDF over it are backends::hash2's over dit_probe. */ struct dit_probe_backend {}; } // namespace @@ -134,6 +137,14 @@ template <> struct mac_engine> : hash2_hmac_engine {}; +/** + HKDF over pieces with HMAC-SHA-256 on the probe's backend: backends::hash2's engine, over + dit_probe, so that the asynchronous forms, which take only WebCrypto's hmacs, reach the probe. +*/ +template <> +struct hkdf_pieces_engine + : hkdf_pieces_engine> {}; + } // namespace webcpp::hash::detail namespace { @@ -212,6 +223,34 @@ void synchronous() { BOOST_TEST((hash::hkdf(okm, test_salt, test_key, test_info)) .has_value()); }); + // The pieces forms: the seam's check runs inside the pieces engine of backends::hash2, whose + // HMAC updates over the probe once per piece. + std::span const key_bytes(test_key); + std::span const info_bytes(test_info); + during("hkdf_extract over pieces", [&] { + BOOST_TEST((hash::hkdf_extract( + test_salt, {key_bytes.first(10), key_bytes.subspan(10)})) + .has_value()); + }); + during("hkdf_expand over pieces", [&] { + BOOST_TEST((hash::hkdf_expand( + okm, *prk, {info_bytes.first(3), info_bytes.subspan(3)})) + .has_value()); + }); + during("hkdf over pieces", [&] { + BOOST_TEST((hash::hkdf( + okm, test_salt, {key_bytes.first(10), key_bytes.subspan(10)}, + {info_bytes.first(3), info_bytes.subspan(3)})) + .has_value()); + }); + // The probe computes SHA-256: hkdf over its pieces gives the bytes of hkdf over hmac_sha2_256 + // and the joined inputs. + std::array plain_okm{}; + BOOST_TEST((hash::hkdf(plain_okm, test_salt, test_key, + test_info)) + .has_value()); + BOOST_TEST(okm == plain_okm); + std::array derived{}; during("pbkdf2", [&] { BOOST_TEST((hash::pbkdf2(derived, test_key, test_salt, 3)) @@ -287,6 +326,61 @@ void on_the_pool() { BOOST_TEST(!hash::detail::dit_is_set()); pool.join(); } + +// Runs `initiate(executor, handler)` with an io_context's executor, then the context, and checks +// that the handler ran with no error. +template +void through_the_event_loop(Initiate initiate) { + asio::io_context context; + bool called = false; + boost::system::error_code code; + initiate(context.get_executor(), [&](boost::system::error_code done) { + called = true; + code = done; + }); + context.run(); // lint-run: the test's event loop + BOOST_TEST(called); + BOOST_TEST(!code); +} + +// The asynchronous forms over pieces on a synchronous backend run the synchronous function over +// pieces in the initiating call (ruling R4 of the change hkdf-pieces): the probe ran on the calling +// thread, under the guard, with DIT set where the CPU has it, and the bytes are hkdf's. +void pieces_in_the_call() { + std::span const key_bytes(test_key); + std::span const info_bytes(test_info); + std::array prk{}; + std::array okm{}; + during("async_hkdf_extract over pieces", [&] { + through_the_event_loop([&](auto const& executor, auto handler) { + hash::async_hkdf_extract( + executor, prk, test_salt, {key_bytes.first(10), key_bytes.subspan(10)}, handler); + }); + }); + during("async_hkdf_expand over pieces", [&] { + through_the_event_loop([&](auto const& executor, auto handler) { + hash::async_hkdf_expand( + executor, okm, prk, {info_bytes.first(3), info_bytes.subspan(3)}, handler); + }); + }); + std::array const expanded = okm; + okm = {}; + during("async_hkdf over pieces", [&] { + through_the_event_loop([&](auto const& executor, auto handler) { + hash::async_hkdf( + executor, okm, test_salt, {key_bytes.first(10), key_bytes.subspan(10)}, + {info_bytes.first(3), info_bytes.subspan(3)}, handler); + }); + }); + // The probe computes SHA-256: the bytes are those of hkdf over hmac_sha2_256 and the joined + // inputs. + std::array plain_okm{}; + BOOST_TEST((hash::hkdf(plain_okm, test_salt, test_key, + test_info)) + .has_value()); + BOOST_TEST(okm == plain_okm); + BOOST_TEST(expanded == plain_okm); +} #endif } // namespace @@ -295,6 +389,7 @@ int main() { synchronous(); #ifdef WEBCPP_TEST_TIMING_DURING_ASYNC on_the_pool(); + pieces_in_the_call(); #endif return webcpp::test::exit_status(boost::report_errors()); } diff --git a/test/timing_keyed_botan_test.cpp b/test/timing_keyed_botan_test.cpp index 950b9f5..ae246ee 100644 --- a/test/timing_keyed_botan_test.cpp +++ b/test/timing_keyed_botan_test.cpp @@ -153,7 +153,7 @@ void derivations_enter() { (hash::argon2id(derived, test_key, test_salt, {.passes = 1, .memory = 8192})) .has_value()); }); - hash::argon2_parameters const family{.passes = 1, .memory_kib = 8}; + hash::argon2_parameters const family{.passes = 1, .memory_kibibytes = 8}; test::require_enters("hash::argon2 of argon2d on botan", [&] { BOOST_TEST( (hash::argon2(derived, test_key, test_salt, family)).has_value()); @@ -167,11 +167,13 @@ void derivations_enter() { .has_value()); }); test::require_enters("hash::scrypt of N = 16 on botan", [&] { - BOOST_TEST((hash::scrypt(derived, test_key, test_salt, {.n = 16, .r = 1, .p = 1})) + BOOST_TEST((hash::scrypt(derived, test_key, test_salt, + {.cost = 16, .block_size = 1, .parallelism = 1})) .has_value()); }); test::require_enters("hash::scrypt of N = 1 on botan", [&] { - BOOST_TEST(!(hash::scrypt(derived, test_key, test_salt, {.n = 1, .r = 1, .p = 1})) + BOOST_TEST(!(hash::scrypt(derived, test_key, test_salt, + {.cost = 1, .block_size = 1, .parallelism = 1})) .has_value()); }); } diff --git a/test/timing_keyed_openssl_test.cpp b/test/timing_keyed_openssl_test.cpp index f590fb8..cc56371 100644 --- a/test/timing_keyed_openssl_test.cpp +++ b/test/timing_keyed_openssl_test.cpp @@ -121,7 +121,7 @@ void derivations_enter() { (hash::argon2id(derived, test_key, test_salt, {.passes = 1, .memory = 8192})) .has_value()); }); - hash::argon2_parameters const family{.passes = 1, .memory_kib = 8}; + hash::argon2_parameters const family{.passes = 1, .memory_kibibytes = 8}; test::require_enters("hash::argon2 of argon2d on openssl", [&] { BOOST_TEST((hash::argon2(derived, test_key, test_salt, family)) .has_value()); @@ -135,11 +135,13 @@ void derivations_enter() { .has_value()); }); test::require_enters("hash::scrypt of N = 16 on openssl", [&] { - BOOST_TEST((hash::scrypt(derived, test_key, test_salt, {.n = 16, .r = 1, .p = 1})) + BOOST_TEST((hash::scrypt(derived, test_key, test_salt, + {.cost = 16, .block_size = 1, .parallelism = 1})) .has_value()); }); test::require_enters("hash::scrypt of N = 1 on openssl", [&] { - BOOST_TEST(!(hash::scrypt(derived, test_key, test_salt, {.n = 1, .r = 1, .p = 1})) + BOOST_TEST(!(hash::scrypt(derived, test_key, test_salt, + {.cost = 1, .block_size = 1, .parallelism = 1})) .has_value()); }); } diff --git a/test/timing_keyed_test.cpp b/test/timing_keyed_test.cpp index 3609451..546a55b 100644 --- a/test/timing_keyed_test.cpp +++ b/test/timing_keyed_test.cpp @@ -442,7 +442,7 @@ void sodium_derivations_enter() { .has_value()); }); - hash::argon2_parameters const family{.passes = 3, .memory_kib = 8}; + hash::argon2_parameters const family{.passes = 3, .memory_kibibytes = 8}; test::require_enters("hash::argon2 of argon2id on sodium", [&] { BOOST_TEST((hash::argon2(derived, test_key, salt16, family)) @@ -459,15 +459,15 @@ void sodium_derivations_enter() { .has_value()); }); - hash::scrypt_parameters const small{.n = 16, .r = 1, .p = 1}; + hash::scrypt_parameters const small{.cost = 16, .block_size = 1, .parallelism = 1}; test::require_enters("hash::scrypt of N = 16 on sodium", [&] { BOOST_TEST((hash::scrypt(derived, test_key, salt16, small)).has_value()); }); test::require_enters("hash::scrypt of N = 1 on sodium", [&] { - BOOST_TEST( - !(hash::scrypt(derived, test_key, salt16, - hash::scrypt_parameters{.n = 1, .r = 1, .p = 1})) - .has_value()); + BOOST_TEST(!(hash::scrypt( + derived, test_key, salt16, + hash::scrypt_parameters{.cost = 1, .block_size = 1, .parallelism = 1})) + .has_value()); }); } diff --git a/test/wipe_test.cpp b/test/wipe_test.cpp index 766df92..8a8c1ce 100644 --- a/test/wipe_test.cpp +++ b/test/wipe_test.cpp @@ -7,8 +7,8 @@ // detail::wipe zeroes every byte it is given and none around it; detail::exceeds compares in 64 // bits on every target. Built with WEBCPP_HASH_DETAIL_TEST_WIPE_RECORD, every wipe is reported // to this test once its bytes are zero, so that the test checks the whole sequence of wipes HKDF's -// and PBKDF2's engines on backends::hash2 do (spec section 6.1): each one's size, in order, its -// bytes zero, and the addresses of objects alive at once told apart. +// (also over pieces) and PBKDF2's engines on backends::hash2 do (spec section 6.1): each one's +// size, in order, its bytes zero, and the addresses of objects alive at once told apart. #include #include @@ -159,8 +159,8 @@ void test_hkdf() { BOOST_TEST((taken() == std::vector{mac})); // Each block's mac, T, the keyed hmac (apart from the blocks' macs). - const std::vector prk_bytes(prk->begin(), prk->end()); - BOOST_TEST((hash::hkdf_expand(output, prk_bytes, info).has_value())); + const std::vector pseudorandom_key(prk->begin(), prk->end()); + BOOST_TEST((hash::hkdf_expand(output, pseudorandom_key, info).has_value())); auto entries = taken_entries(); BOOST_TEST((sizes_of(entries) == std::vector{mac, mac, digest, mac})); if (entries.size() == 4) { @@ -178,7 +178,7 @@ void test_hkdf() { // The longest output, 255 blocks: one mac per block, then T and the keyed hmac. std::vector longest(255 * digest); - BOOST_TEST((hash::hkdf_expand(longest, prk_bytes, info).has_value())); + BOOST_TEST((hash::hkdf_expand(longest, pseudorandom_key, info).has_value())); std::vector expected(255, mac); expected.push_back(digest); expected.push_back(mac); @@ -195,6 +195,50 @@ void test_hkdf() { BOOST_TEST(taken().empty()); } +// HKDF over pieces, hmac_sha2_256, an output of two blocks: the same wipes as the single-buffer +// forms, whatever the pieces (design D2 of the change hkdf-pieces); a guard's refusal wipes +// nothing. +void test_hkdf_pieces() { + using hmac = hash::hmac_sha2_256; + using backend = hash::backends::hash2; + using piece = std::span; + constexpr std::size_t mac = sizeof(hmac); + constexpr std::size_t digest = 32; + const std::vector salt(13, 0x01); + const std::vector ikm(22, 0x0b); + const std::vector info(10, 0xf0); + std::array const ikm_pieces{piece(ikm).first(5), piece{}, piece(ikm).subspan(5)}; + std::array const info_pieces{piece(info).first(3), piece(info).subspan(3)}; + std::vector output(42); + static_cast(taken()); + + auto prk = hash::hkdf_extract(salt, ikm_pieces); + webcpp::test::require(BOOST_TEST(prk.has_value())); + BOOST_TEST((taken() == std::vector{mac})); + + const std::vector pseudorandom_key(prk->begin(), prk->end()); + BOOST_TEST( + (hash::hkdf_expand(output, pseudorandom_key, info_pieces).has_value())); + auto entries = taken_entries(); + BOOST_TEST((sizes_of(entries) == std::vector{mac, mac, digest, mac})); + if (entries.size() == 4) { + BOOST_TEST(apart(entries, 3, {0, 1})); + } + + BOOST_TEST((hash::hkdf(output, salt, ikm_pieces, info_pieces).has_value())); + entries = taken_entries(); + BOOST_TEST((sizes_of(entries) == std::vector{mac, mac, mac, digest, mac, digest})); + if (entries.size() == 6) { + BOOST_TEST(apart(entries, 4, {1, 2})); + BOOST_TEST(apart(entries, 5, {3})); + } + + BOOST_TEST((hash::hkdf_expand(output, salt, info_pieces).has_error())); + BOOST_TEST((hash::hkdf(std::span{}, salt, ikm_pieces, info_pieces) + .has_error())); + BOOST_TEST(taken().empty()); +} + // PBKDF2 over hmac_sha2_256 with an output of two blocks (64 bytes) and three iterations: each // block's mac, then U, T and the keyed hmac. void test_pbkdf2() { @@ -226,6 +270,7 @@ int main() { test_wipe(); test_exceeds(); test_hkdf(); + test_hkdf_pieces(); test_pbkdf2(); return webcpp::test::exit_status(boost::report_errors()); }