diff --git a/AGENTS.md b/AGENTS.md index 0211533..b2a35a6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -43,11 +43,12 @@ specific to crypto. ## Cautions -- An algorithm type does every guard; a backend's header supplies only the eight traits of +- An algorithm type does every guard; a backend's header supplies only the eleven traits of `detail/engines.hpp` (`block_state`, `block_engine`, `gcm_state`, `gcm_engine`, `aead_state`, - `aead_engine`, `secretbox_state`, `secretbox_engine`), the two of `detail/p_curves.hpp` per - P-curve (`p_curve_state`, `p_curve_engine`) and, for the other curves, `public_key_encryption` - and `key_exchange`, the functions of its own header. + `aead_engine`, `secretbox_state`, `secretbox_engine`, `stream_state`, `stream_engine`, + `authenticator_engine`), the two of `detail/p_curves.hpp` per P-curve (`p_curve_state`, + `p_curve_engine`) and, for the other curves, `public_key_encryption` and `key_exchange`, the + functions of its own header. - A new public function that calls a backend holds `secure::timing_guard` as its first statement (`secure::timing_guard const timing_scope;`, webcpp::secure's, ``, which sets arm64's DIT for the call) and joins the coverage diff --git a/bench/operations.hpp b/bench/operations.hpp index be4f3af..d2105ac 100644 --- a/bench/operations.hpp +++ b/bench/operations.hpp @@ -18,7 +18,9 @@ #ifndef WEBCPP_CRYPTO_BENCH_OPERATIONS_HPP #define WEBCPP_CRYPTO_BENCH_OPERATIONS_HPP +#include #include +#include #include #include #include @@ -47,7 +49,7 @@ namespace webcpp::crypto::bench { -// The bytes an AEAD seals at once. +// The bytes an AEAD seals, a stream cipher's keystream covers and an authenticator tags at once. inline constexpr std::size_t message_size = std::size_t{16} * 1024; // Ends the program, naming the operation the library refused. @@ -154,6 +156,66 @@ class aead_seal { Aead aead_; }; +// The keystream of 16 KiB XORed in place, from block counter 1, as RFC 8439's AEAD encrypts. +template +class keystream { +public: + static constexpr std::string_view operation = "keystream of 16 KiB"; + + explicit keystream(std::uint8_t seed) + : nonce_(filled(static_cast(seed + 2U))), + data_(filled(seed)), + cipher_(take(Cipher::from_key(filled(seed)), "from_key")) {} + + std::uint8_t run() { + if (!cipher_.apply_keystream(nonce_, data_, 1)) { + refused("apply_keystream"); + } + return data_[0]; + } + + bool check() { + auto const plain = data_; + static_cast(run()); + bool const changed = data_ != plain; + static_cast(run()); + return changed && data_ == plain; + } + +private: + std::array nonce_{}; + std::array data_{}; + Cipher cipher_; +}; + +// The tag of 16 KiB under a one-time key; one key for every repetition, a measurement, never a +// use. +template +class one_time_tag { +public: + static constexpr std::string_view operation = "tag of 16 KiB"; + + explicit one_time_tag(std::uint8_t seed) + : key_(filled(static_cast(seed + 4U))), + message_(filled(seed)) {} + + std::uint8_t run() { + return take(Authenticator::authenticate(key_, message_), "authenticate").data()[0]; + } + + bool check() { + auto const tag = take(Authenticator::authenticate(key_, message_), "authenticate"); + auto forged = tag; + forged.data()[0] ^= 1U; + return Authenticator::verify(key_, message_, tag).has_value() && + !Authenticator::verify(key_, message_, forged).has_value(); + } + +private: + std::array key_{}; + std::array message_{}; +}; + // AES-256-GCM. template using gcm = aead_seal>>; @@ -174,6 +236,14 @@ using chacha20_poly1305_original = aead_seal using xchacha20_poly1305 = aead_seal>; +// ChaCha20, the raw stream cipher (RFC 8439). +template +using chacha20 = keystream>; + +// Poly1305, the one-time authenticator (RFC 8439). +template +using poly1305 = one_time_tag>; + #ifdef WEBCPP_CRYPTO_HAS_SECP256K1 // A BIP340 signature of a 32-byte message on secp256k1. template diff --git a/bench/throughput.cpp b/bench/throughput.cpp index 703b08a..5328b15 100644 --- a/bench/throughput.cpp +++ b/bench/throughput.cpp @@ -7,10 +7,11 @@ // The throughput of each family's fixed operation (bench/operations.hpp) on each backend this build // links: AES-256-GCM on BearSSL and OpenSSL, the AES block cipher on ctaes and OpenSSL, BIP340 // signing on libsecp256k1, P-256's ECDSA signing, its verification and its ECDH's x on BearSSL, -// Ed25519 signing and X25519 agreement on libsodium, and the ChaCha20-Poly1305 family on libsodium, -// BearSSL and OpenSSL (OpenSSL natively and on WASI only). A family's further operation, beside its -// fixed one, is named after it, as crypto.json's `sized_operations` names it (P-256's -// `verify_ecdsa` and `ecdh_x`). +// Ed25519 signing and X25519 agreement on libsodium, the ChaCha20-Poly1305 family and the raw +// ChaCha20's keystream on libsodium, BearSSL and OpenSSL, and Poly1305's tag on libsodium and +// OpenSSL (OpenSSL natively and on WASI only). A family's further operation, beside its fixed one, +// is named after it, as crypto.json's `sized_operations` names it (P-256's `verify_ecdsa` and +// `ecdh_x`). // // Run with a family and a backend, `throughput [] [--runs N]`, it // repeats the operation, the fixed one when none is named, enough times for a run to last at least @@ -19,9 +20,9 @@ // operation and their median. `--list` prints the cells this build has, one " " // per line, with " " after it for a further operation. Run with no argument, it is the // correctness test: each cell's operation is checked once (an open of what it sealed, a -// verification of what it signed, both sides of an agreement), and the program exits 0 only when -// every check holds. A measurement never fails on its time; bench/collect.py runs it and writes -// doc/performance.adoc. +// verification of what it signed, both sides of an agreement, a keystream applied twice, a tag +// verified and a forged one refused), and the program exits 0 only when every check holds. A +// measurement never fails on its time; bench/collect.py runs it and writes doc/performance.adoc. #include #include @@ -181,6 +182,15 @@ constexpr auto cells = std::to_array({ #endif cell_of("chacha20_poly1305_original"), cell_of("xchacha20_poly1305"), + cell_of("chacha20"), + cell_of("chacha20"), +#ifdef WEBCPP_CRYPTO_HAS_OPENSSL + cell_of("chacha20"), +#endif + cell_of("poly1305"), +#ifdef WEBCPP_CRYPTO_HAS_OPENSSL + cell_of("poly1305"), +#endif }); int usage() { diff --git a/build.jam b/build.jam index f8181c0..67b4a1b 100644 --- a/build.jam +++ b/build.jam @@ -161,6 +161,28 @@ rule xchacha20_poly1305-default-linked ( properties * ) } } alias xchacha20_poly1305-default : : : : @xchacha20_poly1305-default-linked ; +rule chacha20-default-linked ( properties * ) +{ + switch [ webcpp-target.target-of $(properties) ] + { + case native : return /third_party//sodium ; + case wasip2 : return /third_party//sodium ; + case wasip3 : return /third_party//sodium ; + case emscripten : return /third_party//sodium ; + } +} +alias chacha20-default : : : : @chacha20-default-linked ; +rule poly1305-default-linked ( properties * ) +{ + switch [ webcpp-target.target-of $(properties) ] + { + case native : return /third_party//sodium ; + case wasip2 : return /third_party//sodium ; + case wasip3 : return /third_party//sodium ; + case emscripten : return /third_party//sodium ; + } +} +alias poly1305-default : : : : @poly1305-default-linked ; rule secretbox_xsalsa20poly1305-default-linked ( properties * ) { switch [ webcpp-target.target-of $(properties) ] diff --git a/doc/async.adoc b/doc/async.adoc index 102e6f2..fd9715a 100644 --- a/doc/async.adoc +++ b/doc/async.adoc @@ -51,6 +51,14 @@ its own, and the handler would run off the program's loop. | `async_from_key(executor, key, token)` for a secret box (a crypto_box is made by `from_keys`), `secret_key_encryption::async_seal(executor, box, nonce, data, token)`, `secret_key_encryption::async_open(executor, box, nonce, data, tag, token)` | `void(error_code, Secretbox)` for `async_from_key`, `void(error_code, tag)` for `async_seal`, `void(error_code)` for `async_open` +| ChaCha20, the raw stream cipher (<>), on a native backend +| `async_from_key(executor, key, token)`, `unauthenticated_encryption::async_apply_keystream(executor, cipher, nonce, data, initial_counter, token)` +| `void(error_code, C)` for `async_from_key`, `void(error_code)` for `async_apply_keystream` + +| Poly1305 (<>), on a native backend +| `single_use_key_authentication::async_authenticate(executor, key, message, token)`, `single_use_key_authentication::async_verify(executor, key, message, tag, token)` +| `void(error_code, tag)` for `async_authenticate`, `void(error_code)` for `async_verify` + | Ed25519 (<>) | `async_from_secret(executor, seed, token)`, `async_generate(executor, token)`, `async_sign(executor, key_pair, crypto::signing_schemes::eddsa, message, token)`, `async_verify(executor, crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, signature, message, public_key, token)`; on a native backend the same under `crypto::signing_schemes::eddsa_prehashed` with `+crypto::signing_schemes::prehashed{digest}+`, the message's SHA-512 (<>), which the browser's backend refuses at compile time | `void(error_code, Keypair)` for `async_from_secret` and `async_generate`, `void(error_code, signature)` for `async_sign`, `void(error_code)` for `async_verify` @@ -71,7 +79,10 @@ same arguments but the object: `Keypair::async_from_secret(executor, bytes, toke `public_key.async_verify(executor, scheme, policy, signature, input, token)`, `key_pair.async_agree(executor, peer, token)` on X25519 and P-256, and every AEAD's and secret box's `C::async_from_key`, `aead.async_seal` and -`aead.async_open`, and a crypto_box's `box.async_seal` and `box.async_open`. +`aead.async_open`, a crypto_box's `box.async_seal` and `box.async_open`, +ChaCha20's `C::async_from_key` and `cipher.async_apply_keystream`, and +Poly1305's static `A::async_authenticate` and `A::async_verify`, which take the +free forms' arguments, as an authenticator has no object. Both forms share one initiation, which runs the synchronous member, so the four forms of an operation give the same bytes, errors and refusals @@ -104,7 +115,8 @@ P-256's own types, the key pair and the validated `public_key`, and The AEADs and boxes WebCrypto lacks (ChaCha20-Poly1305 and its forms, the secret boxes, crypto_box) have their asynchronous seal, open and from_key on a native backend alone, so that a program sealing in an event loop writes one shape for -every AEAD. On a backend that completes by itself, as the browser's will +every AEAD, and so do the raw ChaCha20 and Poly1305, which WebCrypto lacks too. +On a backend that completes by itself, as the browser's will (<>), no form of them runs, synchronous or asynchronous: only AES-GCM seals and opens there, and any other stops the build with a message that says so and names a native backend. The other algorithms of crypto that @@ -115,6 +127,10 @@ as these, and are called inside a handler. include::generated/backends-async_gcm.adoc[] +include::generated/backends-async_stream_cipher.adoc[] + +include::generated/backends-async_single_use_key_authenticator.adoc[] + include::generated/backends-async_ed25519.adoc[] include::generated/backends-async_x25519.adoc[] @@ -189,20 +205,21 @@ HPKE: on the browser's backend they stop the build. *The completion's value on an error.* A value that is a keyed object or a secret has no meaning when the call failed, and the completion gives the -empty object a move leaves: a `gcm` or a key pair without a key, a `secure::secret<32>` -or a signature of zeros, a tag of zeros. A program that reads the object by -mistake gets `invalid_state` from every member of a `gcm` or a key pair, and -zeros from a secret, never a key. Check the error code first. An operation -without a value, `async_open` and `async_verify`, completes with the code -alone. +empty object a move leaves: a `gcm`, a ChaCha20 or a key pair without a key, a +`secure::secret<32>` or a signature of zeros, a tag of zeros. A program that +reads the object by mistake gets `invalid_state` from every member of a `gcm`, +a ChaCha20 or a key pair, and zeros from a secret, never a key. Check the error +code first. An operation without a value, `async_open`, `async_verify` and +`async_apply_keystream`, completes with the code alone. *What the guards say.* The completion's code is the synchronous function's, -unchanged: `invalid_key_size`, `invalid_nonce_size`, `message_too_long`, -`authentication_failed`, `invalid_public_key`, `weak_public_key`, -`invalid_signature`, `entropy_unavailable`, `backend_failure` -(<>). A refusal is posted like a success, and the data a guard -refuses is untouched; a failed `async_seal` or `async_open` zeroes it, as -`seal` and `open` do. +unchanged: `invalid_key_size`, `invalid_nonce_size`, `invalid_tag_size`, +`message_too_long`, `counter_overflow`, `authentication_failed`, +`invalid_public_key`, `weak_public_key`, `invalid_signature`, +`entropy_unavailable`, `backend_failure` (<>). A refusal is +posted like a success, and the data a guard refuses is untouched; a failed +`async_seal`, `async_open` or `async_apply_keystream` zeroes it, as `seal`, +`open` and `apply_keystream` do. *Pitfalls.* diff --git a/doc/chacha.adoc b/doc/chacha.adoc index 540825f..5bb993a 100644 --- a/doc/chacha.adoc +++ b/doc/chacha.adoc @@ -157,3 +157,128 @@ Parts of this section, the limits, are adapted from libsodium's documentation (link:https://github.com/jedisct1/libsodium-doc/tree/6d1ea27b79b853b2a04f09ae9e1a8231c90e3b56[jedisct1/libsodium-doc] at `6d1ea27`, ISC, `LICENSE-LIBSODIUM-DOC.txt`). + +[#crypto-chacha20] +=== ChaCha20, the raw stream cipher + +*ChaCha20* alone is the stream cipher inside ChaCha20-Poly1305: from a 32-byte +key, a 12-byte nonce and a 32-bit block counter it makes a keystream, 64 bytes +for each value of the counter, which is XORed into the data +(link:https://www.rfc-editor.org/rfc/rfc8439#section-2.4[RFC 8439, section +2.4]). It is not authenticated encryption: it adds no tag, a bit flipped in the +ciphertext flips the same bit of the plaintext, and nothing tells the reader. +A program's own messages take `chacha20_poly1305` or `xchacha20_poly1305` +(<>). The raw cipher is for a protocol that fixes its own +construction and authenticates the nonce and the ciphertext itself, as Nostr's +encrypted payloads do with HMAC-SHA256 +(link:https://github.com/nostr-protocol/nips/blob/master/44.md[NIP-44]; +<>), and for a construction a standard writes from the raw +pieces, as RFC 8439's own AEAD (<>). + +`ciphers::chacha20`, in ``, is +`ciphers::basic_chacha20`; `chacha20<>` names the +family's default, libsodium on every target (<>). +`from_key(key_bytes)` makes it from a 32-byte key, which it keeps and wipes when +it is destroyed; `apply_keystream(nonce_bytes, data_bytes, initial_counter)` +XORs into `data_bytes`, in place, the keystream of `nonce_bytes` from the block +of counter `initial_counter`. Encryption and decryption are this one call. The +program names the counter, as the protocol it implements says: RFC 8439's AEAD +starts the message at counter 1, keeping block 0 for Poly1305's key, and NIP-44 +starts at 0. The nonce may lie inside `data_bytes`: the call copies it first. +It is an `unauthenticated_encryption::stream_cipher`, whose free form, +`unauthenticated_encryption::apply_keystream`, its header brings +(<>); it is no AEAD, and a call of `seal` or +`open` on it does not compile. + +*The counter.* The counter is the algorithm's `counter_type`, 32 bits for +ChaCha20, and one call covers at most the blocks the counter has left after +`initial_counter`, that block included: 2^32^ blocks, 256 GiB, from counter 0, +and one block, 64 bytes, from counter 2^32^ - 1. Data that needs more is +refused with `counter_overflow` before a byte is read, and left untouched: the +counter never wraps onto a block already used, which would repeat the +keystream. A stream processed in whole blocks continues at the next counter: +a call from counter c over n blocks, then a call from c + n, give the keystream +of one call over both. + +*The nonce.* A nonce is never repeated under one key: two messages under one +key and one nonce share their keystream, and the XOR of the two ciphertexts is +the XOR of the two plaintexts +(link:https://www.rfc-editor.org/rfc/rfc8439#section-4[RFC 8439, section 4]). +12 bytes are too short to draw at random for many messages under one key; a +protocol derives a fresh key and nonce for each message, as NIP-44 derives +both from 32 random bytes per message. + +*Example.* RFC 8439 section 2.4.2's vector: the key, the nonce and counter 1 +encrypt the section's plaintext, the same call gives it back, and data past the +counter's last block is refused: + +[source,cpp] +---- +include::{examples}/chacha20_keystream.cpp[tag=program] +---- + +[listing] +---- +include::{examples}/chacha20_keystream.expected[] +---- + +*The backends.* libsodium, BearSSL and OpenSSL give the same keystream byte for +byte, which the agreement tests check on random keys, nonces, counters and +lengths: name the backend in the type, as in `chacha20`, and +link its library. On libsodium and BearSSL nothing allocates; on OpenSSL +`from_key` allocates its cipher context and a call does not. + +include::generated/backends-chacha20.adoc[] + +*The four forms.* The member `cipher.apply_keystream(nonce, data, +initial_counter)`; the free `unauthenticated_encryption::apply_keystream(cipher, +nonce, data, initial_counter)`; and, in ``, the member +`cipher.async_apply_keystream(executor, nonce, data, initial_counter, token)` and +the free `unauthenticated_encryption::async_apply_keystream(executor, cipher, +nonce, data, initial_counter, token)`, the object made by `C::async_from_key` or +`crypto::async_from_key` (<>). The four give the same bytes and +the same errors (<>). + +*The browser.* WebCrypto has no ChaCha20: on a backend that completes by +itself, as the browser's will (<>), no form runs, +synchronous or asynchronous, and the build stops with a message that names a +native backend (<>). On Emscripten the default, +libsodium compiled to WebAssembly, runs every form. + +[#crypto-chacha20-guards] +==== The guards + +Each function checks its guards first, in the order of the table, and returns +before it reads a byte of the data; empty data succeeds with no work: + +[cols="3,1"] +|=== +|Condition |Error + +|`from_key`: a key of another size than 32 bytes |`invalid_key_size` +|`apply_keystream`: the object was moved from |`invalid_state` +|a nonce of another size than 12 bytes |`invalid_nonce_size` +|data that needs more blocks than the counter has left after `initial_counter` +|`counter_overflow` +|the backend fails where it should not, the data zeroed |`backend_failure` +|=== + +On OpenSSL, `from_key` also reports `errc::not_enough_memory` when OpenSSL +cannot allocate its context, and, with its memory option, +`memory_functions_not_installed` (<>). + +[#crypto-chacha20-pitfalls] +==== Pitfalls + +* A nonce repeated under one key reveals the XOR of the two plaintexts: a +protocol derives a fresh key or nonce for each message, a restart included. +* A bit flipped in the ciphertext flips the same bit of the plaintext, and the +call cannot tell: a program that acts on what it decrypted without checking a +MAC first acts on bytes an attacker chose. +* A protocol's MAC covers the nonce and the ciphertext, and is checked in +constant time before the data is decrypted or used, as NIP-44's HMAC-SHA256 +is: a MAC over the plaintext alone, or one that leaves the nonce out, lets a +message be changed or replayed under another nonce. +* The counter is the protocol's: counter 1 where the protocol says 0, or the +reverse, gives another keystream, and every message fails with nothing +pointing at the cause. diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 9abcdfd..249a722 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -21,9 +21,9 @@ of every version are on webcpp's index page. * *Breaking change:* Changed the schemes into `crypto::signing_schemes`; every verification, `recover` and `can_verify` takes a policy after the scheme, `low_s_only`, `any_s` or `canonical` (Ed25519's former `strict`). * *Breaking change:* Changed low S into signatures' `is_low_s()` and `low_s()`, free tweak_xonly, span Schnorr verify and `xonly()` bytes into the typed `xonly_public_key`, and secp256k1's SPKI default to uncompressed. * Changed PEM: its label is in its type, its result as long as its longest text, its decode in place through codecs' over, and a hand-built armor fails to build. -* Added crypto, C-backed primitives on webcpp::secure's guard (DIT on arm64): errors 1 to 21, `+[[nodiscard]]+` results, typed signatures, key pair concepts, factories, WEBCPP_CRYPTO_HAS_THREADS, Asio's asynchronous functions. +* Added crypto, C-backed primitives on webcpp::secure's guard (DIT on arm64): errors 1 to 22, `+[[nodiscard]]+` results, typed signatures, key pair concepts, factories, WEBCPP_CRYPTO_HAS_THREADS, Asio's asynchronous functions. * Added random_device, the AES block ciphers, ciphers::gcm, per-target defaults, backends::bearssl (AES-GCM, ChaCha20-Poly1305, curves::p256 keys, low-S ECDSA, agree), backends::openssl and backends::ctaes. * Added curves::secp256k1 (ECDSA, recoverable ECDSA, BIP 340 Schnorr, agree, tweaks, ElligatorSwift, MuSig2, silent payments), and curves::ed25519 and curves::x25519 on libsodium, Ed25519's verification canonical. * Added public_key_encryption::hpke, RFC 9180's HPKE on X25519 or P-256, HKDF, and AES-GCM or ChaCha20-Poly1305. -* Added backends::sodium, ChaCha20-Poly1305 AEADs, secretbox, boxes, sealed boxes, kx_keypair, and the page: chapters per namespace and use case, generated tables, Jamfiles, messages, llms.txt, measurements. +* Added backends::sodium, ChaCha20-Poly1305 AEADs, secretbox, boxes, sealed boxes, kx_keypair; raw ciphers::chacha20 (unauthenticated_encryption, also BearSSL and OpenSSL) and authenticators::poly1305 (single_use_key_authentication, also OpenSSL); the page: chapters, generated tables, Jamfiles, messages, llms.txt, measurements. // end::unreleased[] diff --git a/doc/ciphers.adoc b/doc/ciphers.adoc index 17e7594..a3068fe 100644 --- a/doc/ciphers.adoc +++ b/doc/ciphers.adoc @@ -24,7 +24,12 @@ CPU has AES instructions and the one browsers' WebCrypto offers. ChaCha20-Poly1305 needs no such instructions to be fast and constant time (link:https://www.rfc-editor.org/rfc/rfc8439[RFC 8439]); its XChaCha20 form takes a 24-byte nonce that is safe to draw at random for every message. The raw -AES block cipher is a building block, never encryption of data. NaCl's and +AES block cipher is a building block, never encryption of data, and so is +ChaCha20 alone, the raw stream cipher inside ChaCha20-Poly1305, which +authenticates nothing: it is for a protocol that fixes its own construction and +authenticates the ciphertext itself, as NIP-44 does (<>), and +its contract is in `unauthenticated_encryption` +(<>). NaCl's and libsodium's secret boxes, the same idea without associated data, are in `secret_key_encryption` (<>), with the AEAD contract every cipher here satisfies (<>). diff --git a/doc/crypto.adoc b/doc/crypto.adoc index 970a9fc..2c90ea7 100644 --- a/doc/crypto.adoc +++ b/doc/crypto.adoc @@ -50,6 +50,10 @@ include::block.adoc[] include::secret_key_encryption.adoc[] +include::unauthenticated_encryption.adoc[] + +include::single_use_key_authentication.adoc[] + include::curves.adoc[] include::secp256k1.adoc[] @@ -86,11 +90,12 @@ include::testing.adoc[] == Reference Every name crypto declares, in the namespaces `webcpp::crypto`, `backends`, -`ciphers`, `secret_key_encryption`, `curves`, `public_key_encryption` and -`key_exchange`, from the Doc Comments of its headers: each class, function, -type and enumerator with its declaration, what it does, what it asks of its -caller and how it fails. The other sections teach the library; this one is -where a name is looked up. +`ciphers`, `secret_key_encryption`, `unauthenticated_encryption`, +`authenticators`, `single_use_key_authentication`, `curves`, +`public_key_encryption` and `key_exchange`, from the Doc Comments of its +headers: each class, function, type and enumerator with its declaration, what it +does, what it asks of its caller and how it fails. The other sections teach the +library; this one is where a name is looked up. include::{reference}[leveloffset=+1] diff --git a/doc/errors.adoc b/doc/errors.adoc index 4d89175..98f6a3c 100644 --- a/doc/errors.adoc +++ b/doc/errors.adoc @@ -26,7 +26,8 @@ random value to use: the operation that needed one fails. |1 |`invalid_key_size` |A key of another size than the algorithm's `key_size`, or a secret key not of 32 bytes. |2 |`invalid_nonce_size` |A nonce of a size the algorithm does not accept: a GCM nonce that is -empty or longer than 128 bytes, another AEAD's or a box's nonce of another size than its own. +empty or longer than 128 bytes, another AEAD's, a box's or a stream cipher's nonce of another size +than its own. |3 |`invalid_tag_size` |A tag given to `open` or `verify` that is not of 16 bytes. |4 |`invalid_input_size` |Data given to a block cipher that is not a whole number of blocks, the incremental open's `decrypt` past the authenticated length and `end_open` short of it, or a @@ -61,6 +62,9 @@ armor's own faults are codecs' (below). |20 |`invalid_ciphertext_size` |A KEM or RSA ciphertext of another size than the key's. |21 |`message_limit_reached` |An HPKE context has sealed or opened as many messages as its nonce allows: its 64-bit sequence number reached 2^64^ - 1 (RFC 9180's `MessageLimitReachedError`). +|22 |`counter_overflow` |A stream cipher's data needs more blocks than its counter has left after +the initial counter: RFC 8439's ChaCha20 has a 32-bit block counter, 256 GiB of keystream from +counter 0. The data is left untouched. |=== A value that `error` does not define diff --git a/doc/generated/backends-async_single_use_key_authenticator.adoc b/doc/generated/backends-async_single_use_key_authenticator.adoc new file mode 100644 index 0000000..f3c858d --- /dev/null +++ b/doc/generated/backends-async_single_use_key_authenticator.adoc @@ -0,0 +1,25 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, +// the message tests and the Jamfile fixtures: run it again, never edit this file. + +The backends of `+single_use_key_authentication::async_authenticate+`, `+single_use_key_authentication::async_verify+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|OpenSSL +|`+/webcpp/crypto//openssl+` +|`++` +|native, wasip2, wasip3 (tested by `+async_authenticator_openssl+`, `+timing_coverage_openssl+`); not on emscripten: `+/webcpp/crypto//openssl+` stops the build there + +|libsodium +|`+/third_party//sodium+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+async_authenticator+`, `+timing_coverage_sodium+`) +|=== diff --git a/doc/generated/backends-async_stream_cipher.adoc b/doc/generated/backends-async_stream_cipher.adoc new file mode 100644 index 0000000..b6a0133 --- /dev/null +++ b/doc/generated/backends-async_stream_cipher.adoc @@ -0,0 +1,30 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, +// the message tests and the Jamfile fixtures: run it again, never edit this file. + +The backends of `+async_from_key+`, `+unauthenticated_encryption::async_apply_keystream+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|BearSSL +|`+/third_party//bearssl+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+async_stream_cipher+`) + +|OpenSSL +|`+/webcpp/crypto//openssl+` +|`++` +|native, wasip2, wasip3 (tested by `+async_stream_cipher_openssl+`); not on emscripten: `+/webcpp/crypto//openssl+` stops the build there + +|libsodium +|`+/third_party//sodium+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+async_stream_cipher+`, `+stream_cipher_shape+`) +|=== diff --git a/doc/generated/backends-chacha20.adoc b/doc/generated/backends-chacha20.adoc new file mode 100644 index 0000000..7ff95ff --- /dev/null +++ b/doc/generated/backends-chacha20.adoc @@ -0,0 +1,45 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, +// the message tests and the Jamfile fixtures: run it again, never edit this file. + +The backends of `+ciphers::chacha20+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|BearSSL +|`+/third_party//bearssl+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+chacha20_bearssl+`, `+chacha20_bearssl_portable+`, `+allocation_bearssl+`, `+timing_coverage_bearssl+`, `+agreement_chacha20+`, `+agreement_chacha20_emscripten+`, `+agreement_chacha20_portable+`, `+agreement_chacha20_portable_emscripten+`, `+chacha20_nip44_bearssl+`) + +|OpenSSL +|`+/webcpp/crypto//openssl+` +|`++` +|native, wasip2, wasip3 (tested by `+chacha20_openssl+`, `+allocation_openssl+`, `+timing_coverage_openssl+`, `+agreement_chacha20+`, `+agreement_chacha20_portable+`, `+chacha20_nip44_openssl+`); not on emscripten: `+/webcpp/crypto//openssl+` stops the build there + +|ctaes +|`+/third_party//ctaes+` +|`++` +|refused at compile time (`+chacha20_on_ctaes+`) + +|libsodium +|`+/third_party//sodium+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+chacha20_sodium+`, `+stream_cipher_concepts+`, `+allocation_sodium+`, `+timing_coverage_sodium+`, `+agreement_chacha20+`, `+agreement_chacha20_emscripten+`, `+chacha20_nip44_sodium+`) +|=== + +`+chacha20<>+` names the default backend. The default per target, whatever the program links, as <> gives it with its reasons and tests: + +[cols="1,1",options="header"] +|=== +|Target |Default + +|native, wasip2, wasip3, emscripten +|libsodium +|=== diff --git a/doc/generated/backends-poly1305.adoc b/doc/generated/backends-poly1305.adoc new file mode 100644 index 0000000..7f4edd2 --- /dev/null +++ b/doc/generated/backends-poly1305.adoc @@ -0,0 +1,45 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, +// the message tests and the Jamfile fixtures: run it again, never edit this file. + +The backends of `+authenticators::poly1305+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|BearSSL +|`+/third_party//bearssl+` +|`++` +|refused at compile time (`+poly1305_on_bearssl+`) + +|OpenSSL +|`+/webcpp/crypto//openssl+` +|`++` +|native, wasip2, wasip3 (tested by `+poly1305_openssl+`, `+poly1305_openssl_memory_resource+`, `+allocation_openssl+`, `+timing_coverage_openssl+`, `+agreement_poly1305+`, `+composition_rfc8439+`); not on emscripten: `+/webcpp/crypto//openssl+` stops the build there + +|ctaes +|`+/third_party//ctaes+` +|`++` +|refused at compile time (`+poly1305_on_ctaes+`) + +|libsodium +|`+/third_party//sodium+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+poly1305_sodium+`, `+authenticator_concepts+`, `+allocation_sodium+`, `+timing_coverage_sodium+`, `+agreement_poly1305+`, `+agreement_poly1305_emscripten+`, `+composition_rfc8439+`, `+composition_rfc8439_emscripten+`) +|=== + +`+poly1305<>+` names the default backend. The default per target, whatever the program links, as <> gives it with its reasons and tests: + +[cols="1,1",options="header"] +|=== +|Target |Default + +|native, wasip2, wasip3, emscripten +|libsodium +|=== diff --git a/doc/generated/backends-single_use_key_authenticator.adoc b/doc/generated/backends-single_use_key_authenticator.adoc new file mode 100644 index 0000000..2e8d1e9 --- /dev/null +++ b/doc/generated/backends-single_use_key_authenticator.adoc @@ -0,0 +1,25 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, +// the message tests and the Jamfile fixtures: run it again, never edit this file. + +The backends of `+single_use_key_authentication::single_use_key_authenticator+`, `+single_use_key_authentication::authenticate+`, `+single_use_key_authentication::verify+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|OpenSSL +|`+/webcpp/crypto//openssl+` +|`++` +|native, wasip2, wasip3 (tested by `+poly1305_openssl+`, `+timing_coverage_openssl+`); not on emscripten: `+/webcpp/crypto//openssl+` stops the build there + +|libsodium +|`+/third_party//sodium+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+authenticator_concepts+`, `+poly1305_sodium+`, `+timing_coverage_sodium+`) +|=== diff --git a/doc/generated/backends-stream_cipher.adoc b/doc/generated/backends-stream_cipher.adoc new file mode 100644 index 0000000..b510966 --- /dev/null +++ b/doc/generated/backends-stream_cipher.adoc @@ -0,0 +1,30 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, +// the message tests and the Jamfile fixtures: run it again, never edit this file. + +The backends of `+unauthenticated_encryption::stream_cipher+`, `+unauthenticated_encryption::apply_keystream+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|BearSSL +|`+/third_party//bearssl+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+timing_coverage_bearssl+`) + +|OpenSSL +|`+/webcpp/crypto//openssl+` +|`++` +|native, wasip2, wasip3 (tested by `+timing_coverage_openssl+`); not on emscripten: `+/webcpp/crypto//openssl+` stops the build there + +|libsodium +|`+/third_party//sodium+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+stream_cipher_concepts+`, `+stream_cipher_shape+`, `+timing_coverage_sodium+`) +|=== diff --git a/doc/generated/constant-time.adoc b/doc/generated/constant-time.adoc index 32edb66..2511aa0 100644 --- a/doc/generated/constant-time.adoc +++ b/doc/generated/constant-time.adoc @@ -13,14 +13,14 @@ |BearSSL |by design: `+aes_ct64+` and `+ghash_ctmul64+`, or AES-NI and PCLMUL where the CPU has them; on a 32-bit host a 64-bit multiplication may not be constant time, which BearSSL documents; ECDSA signing at webcpp's pin, whose patch submitted upstream closes upstream's leak of the RFC 6979 nonce's bit length (link:https://www.bearssl.org/gitweb/?p=BearSSL;a=blob;f=src/ec/ecdsa_i31_bits.c;hb=7bea48e5e850ab4cafbe68d3765cdaba13a86d6f#l44[BearSSL's ecdsa_i31_bits.c at upstream 7bea48e, lines 44 and 45: the nonce decoded with its actual bit length in the integer's header, then shifted over the words that length needs]; link:https://minerva.crocs.fi.muni.cz/[Minerva: the leak of an ECDSA nonce's bit length through timing, and the lattice that recovers the key (CVE-2019-15809)]; the patch: link:https://github.com/webcpporg/bearssl/commit/ae63032d9f30bf53674db5445875adf71b8626b7[webcpporg/bearssl, commit ae63032 on its branch upstream/ecdsa-bits2int-constant-time, one of the two patches of webcpp's pin f8a2f3d (upstream 7bea48e plus exactly the patches submitted upstream): br_ecdsa_i31_bits2int and br_ecdsa_i15_bits2int setting the integer's header, before the right shift, to the larger of the decoded bit length and the order's, both public; the pin returns to upstream once upstream applies it]); P-256's `+mul+`, which ECDH calls, at webcpp's pin, whose other patch submitted upstream removes the jump on the secret scalar that Clang makes on x86-64 of upstream's scalar check (link:https://www.bearssl.org/gitweb/?p=BearSSL;a=blob;f=src/ec/ec_p256_m62.c;hb=7bea48e5e850ab4cafbe68d3765cdaba13a86d6f#l1623[BearSSL's ec_p256_m62.c at upstream 7bea48e, lines 1623 to 1627: the scalar compared with the order through masks that Clang on x86-64 compiles into a conditional jump on the comparison so far]; the patch: link:https://github.com/webcpporg/bearssl/commit/ec57f886ee0a0783acfca1b465b43ccd62b71046[webcpporg/bearssl, commit ec57f88 on its branch upstream/ec-p256-check-scalar-constant-time, the other patch of webcpp's pin f8a2f3d: check_scalar in ec_p256_m62.c and ec_p256_m64.c computing 0 < k < n as k - 1 < n - 1 with two borrow chains, no select for a compiler to turn into a jump; the pin returns to upstream once upstream applies it]); link:https://www.bearssl.org/constanttime.html[BearSSL, constant-time crypto]; link:https://www.bearssl.org/ctmul.html[BearSSL, constant-time multiplications] -|Valgrind's memcheck (Linux): AES-GCM, ChaCha20-Poly1305, P-256 (the key pair's making, `+sign+` of a digest (`+crypto::signing_schemes::prehashed+`), which makes its signature low S without a branch, then `+low_s()+` and `+is_low_s()+` of it, `+agree+` and the private formats, `+pkcs8+`, `+raw+` and `+pem(pkcs8)+` both ways; BearSSL's own branches on its signing's verdicts listed in `+bearssl_verdicts.supp+`; nothing found at webcpp's pin f8a2f3d, whose patches submitted upstream close upstream's leak of the nonce's bit length in `+sign+` that this checker found on 2026-11-21 and the jump on the scalar in P-256's scalar check that it found under `+agree+` on the x86-64 runner on 2026-12-03, `+sign+` with its low-S step included (Valgrind 3.22, arm64 Linux container, 2026-12-02; x86-64, `+ctgrind+` and `+ctgrind_space+`, 2026-12-04)); MemorySanitizer (Linux, clang): AES-GCM, ChaCha20-Poly1305, P-256 (the same paths as memcheck's; the same leak in `+sign+` on 2026-11-21 on upstream's BearSSL, nothing at webcpp's pin ae63032, `+sign+` with its low-S step included (clang 18, arm64 Linux container, 2026-12-02); MemorySanitizer checks the select of P-256's scalar check before the code generator makes it a jump, so the second patch changes nothing it sees); dudect (judged; on a runner GitHub hosts, by two of three runs): AES-GCM, ChaCha20-Poly1305, P-256 (`+sign+` of a digest and `+agree+`, each against the key pair's scalar; `+sign+` with its low-S step judged constant time, \|t\| 1.70 on Linux and 1.63 natively on an Apple M5 Max (release, one run each, 2026-11-22; provisional, measured again in the final quiet pass)) -|dudect (printed, not judged: under wasmtime its timing follows the runner's processor): AES-GCM, ChaCha20-Poly1305, P-256 +|Valgrind's memcheck (Linux): AES-GCM, ChaCha20-Poly1305, ChaCha20, P-256 (the key pair's making, `+sign+` of a digest (`+crypto::signing_schemes::prehashed+`), which makes its signature low S without a branch, then `+low_s()+` and `+is_low_s()+` of it, `+agree+` and the private formats, `+pkcs8+`, `+raw+` and `+pem(pkcs8)+` both ways; BearSSL's own branches on its signing's verdicts listed in `+bearssl_verdicts.supp+`; nothing found at webcpp's pin f8a2f3d, whose patches submitted upstream close upstream's leak of the nonce's bit length in `+sign+` that this checker found on 2026-11-21 and the jump on the scalar in P-256's scalar check that it found under `+agree+` on the x86-64 runner on 2026-12-03, `+sign+` with its low-S step included (Valgrind 3.22, arm64 Linux container, 2026-12-02; x86-64, `+ctgrind+` and `+ctgrind_space+`, 2026-12-04)); MemorySanitizer (Linux, clang): AES-GCM, ChaCha20-Poly1305, ChaCha20, P-256 (the same paths as memcheck's; the same leak in `+sign+` on 2026-11-21 on upstream's BearSSL, nothing at webcpp's pin ae63032, `+sign+` with its low-S step included (clang 18, arm64 Linux container, 2026-12-02); MemorySanitizer checks the select of P-256's scalar check before the code generator makes it a jump, so the second patch changes nothing it sees); dudect (judged; on a runner GitHub hosts, by two of three runs): AES-GCM, ChaCha20-Poly1305, ChaCha20, P-256 (`+sign+` of a digest and `+agree+`, each against the key pair's scalar; `+sign+` with its low-S step judged constant time, \|t\| 1.70 on Linux and 1.63 natively on an Apple M5 Max (release, one run each, 2026-11-22; provisional, measured again in the final quiet pass)) +|dudect (printed, not judged: under wasmtime its timing follows the runner's processor): AES-GCM, ChaCha20-Poly1305, ChaCha20, P-256 |not measured yet |not measured yet |OpenSSL |with assembly (native Clang and GCC), AES-NI and carry-less multiplication where the CPU has them; built no-asm (MSVC, wasip2, wasip3), table-based AES and 4-bit GHASH, neither constant time (`+OPENSSL_AES_CONST_TIME+` makes only the AES core constant time; GHASH stays table-based); link:https://github.com/openssl/openssl/blob/master/INSTALL.md[OpenSSL's INSTALL.md, no-asm]; link:https://github.com/openssl/openssl/blob/master/crypto/aes/aes_core.c[OpenSSL's crypto/aes/aes_core.c, OPENSSL_AES_CONST_TIME] -|Valgrind's memcheck (Linux): AES-GCM (seal alone: its open branches on the verdict inside OpenSSL), ChaCha20-Poly1305 (seal alone: its open branches on the verdict inside OpenSSL) +|Valgrind's memcheck (Linux): AES-GCM (seal alone: its open branches on the verdict inside OpenSSL), ChaCha20-Poly1305 (seal alone: its open branches on the verdict inside OpenSSL), ChaCha20, Poly1305 (`+authenticate+` and `+verify+`, as on libsodium) |not measured yet |not measured yet |not measured yet @@ -41,8 +41,8 @@ |libsodium |by its documentation for the paths crypto calls, without a guarantee for the whole library: secrets are compared in constant time (link:https://doc.libsodium.org/internals#branches[libsodium's documentation, internals: branches]), ChaCha20 is not sensitive to timing attacks (link:https://doc.libsodium.org/secret-key_cryptography/aead[libsodium's documentation, AEAD constructions: ChaCha20 and timing attacks]), and Ed25519 and X25519 come from designs with no secret branch and no secret array index (link:https://ed25519.cr.yp.to/[Ed25519's design: no secret branch conditions, no secret array indices]); webcpp's lane checks each path it calls -|Valgrind's memcheck (Linux): Ed25519, X25519, crypto_kx, ChaCha20-Poly1305, original ChaCha20-Poly1305, XChaCha20-Poly1305, XSalsa20-Poly1305 secret box, XChaCha20-Poly1305 secret box, X25519-XSalsa20-Poly1305 box, X25519-XChaCha20-Poly1305 box, X25519-XSalsa20-Poly1305 sealed box; MemorySanitizer (Linux, clang): Ed25519, X25519, crypto_kx, ChaCha20-Poly1305, original ChaCha20-Poly1305, XChaCha20-Poly1305, XSalsa20-Poly1305 secret box, XChaCha20-Poly1305 secret box, X25519-XSalsa20-Poly1305 box, X25519-XChaCha20-Poly1305 box, X25519-XSalsa20-Poly1305 sealed box; dudect (judged; on a runner GitHub hosts, by two of three runs): Ed25519, X25519 (X25519 measured differently, below) -|dudect (judged; on a runner GitHub hosts, by two of three runs): Ed25519, X25519 (X25519 measured differently, below) +|Valgrind's memcheck (Linux): Ed25519, X25519, crypto_kx, ChaCha20-Poly1305, original ChaCha20-Poly1305, XChaCha20-Poly1305, ChaCha20, Poly1305 (`+authenticate+`, then `+verify+` with the right tag and with a wrong one, the key, the message and the tags secret; the verdict of `+verify+` declassified by crypto where it first branches on it), XSalsa20-Poly1305 secret box, XChaCha20-Poly1305 secret box, X25519-XSalsa20-Poly1305 box, X25519-XChaCha20-Poly1305 box, X25519-XSalsa20-Poly1305 sealed box; MemorySanitizer (Linux, clang): Ed25519, X25519, crypto_kx, ChaCha20-Poly1305, original ChaCha20-Poly1305, XChaCha20-Poly1305, ChaCha20, Poly1305 (the same paths as memcheck's), XSalsa20-Poly1305 secret box, XChaCha20-Poly1305 secret box, X25519-XSalsa20-Poly1305 box, X25519-XChaCha20-Poly1305 box, X25519-XSalsa20-Poly1305 sealed box; dudect (judged; on a runner GitHub hosts, by two of three runs): Ed25519, X25519 (X25519 measured differently, below), Poly1305 (`+authenticate+` against its key, the all-zero key against random ones; `+verify+` against its tag, the right tag with its last byte flipped against it with its first byte flipped, both classes failing: a success and a failure return by different paths, about 0.4 ns apart, which dudect finds and which is public, the verdict being reported) +|dudect (judged; on a runner GitHub hosts, by two of three runs): Ed25519, X25519 (X25519 measured differently, below), Poly1305 (`+authenticate+` against its key, the all-zero key against random ones; `+verify+` against its tag, the right tag with its last byte flipped against it with its first byte flipped, both classes failing: a success and a failure return by different paths, about 0.4 ns apart, which dudect finds and which is public, the verdict being reported) |not measured yet |not measured yet diff --git a/doc/generated/default-aliases.adoc b/doc/generated/default-aliases.adoc index 6964eb6..3992052 100644 --- a/doc/generated/default-aliases.adoc +++ b/doc/generated/default-aliases.adoc @@ -56,6 +56,16 @@ |`+/third_party//sodium+` on every target |<> +|`+/webcpp/crypto//chacha20-default+` +|ChaCha20 +|`+/third_party//sodium+` on every target +|<> + +|`+/webcpp/crypto//poly1305-default+` +|Poly1305 +|`+/third_party//sodium+` on every target +|<> + |`+/webcpp/crypto//secretbox_xsalsa20poly1305-default+` |XSalsa20-Poly1305 secret box |`+/third_party//sodium+` on every target diff --git a/doc/generated/defaults.adoc b/doc/generated/defaults.adoc index 62a2f9d..d455e7b 100644 --- a/doc/generated/defaults.adoc +++ b/doc/generated/defaults.adoc @@ -95,6 +95,18 @@ |the only backend that has it: libsodium's own C code, the same on every target (link:https://doc.libsodium.org/secret-key_cryptography/aead/chacha20-poly1305[libsodium's ChaCha20-Poly1305 constructions]) |`+xchacha_sodium+`, `+default_backend_none_linked+` +|ChaCha20 +|native, wasip2, wasip3, emscripten +|libsodium +|ChaCha20-Poly1305's default, so that a program that uses both links one library; libsodium's own C code, constant time, the same on every target (link:https://doc.libsodium.org/advanced/stream_ciphers/chacha20[libsodium's ChaCha20 stream cipher, crypto_stream_chacha20_ietf_xor_ic]) +|`+chacha20_sodium+`, `+default_backend_none_linked+` + +|Poly1305 +|native, wasip2, wasip3, emscripten +|libsodium +|ChaCha20's and ChaCha20-Poly1305's default, so that a program composing them links one library (link:https://doc.libsodium.org/advanced/poly1305[libsodium's one-time authentication, crypto_onetimeauth_poly1305]) +|`+poly1305_sodium+`, `+default_backend_none_linked+` + |XSalsa20-Poly1305 secret box |native, wasip2, wasip3, emscripten |libsodium diff --git a/doc/generated/jamfiles.adoc b/doc/generated/jamfiles.adoc index dd77af3..8cd1eaf 100644 --- a/doc/generated/jamfiles.adoc +++ b/doc/generated/jamfiles.adoc @@ -87,6 +87,22 @@ It prints: include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/box_xsalsa20poly1305_default/box_xsalsa20poly1305_default.outcome[tag=output] ---- +`+chacha20_default+`:: RFC 8439's ChaCha20 example of section 2.4.2, encrypted and decrypted on its default on every target, with the one line `+/webcpp/crypto//chacha20-default+`, which links libsodium. ++ +Its Jamfile, built and run on native, wasip2, wasip3, emscripten: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/chacha20_default/Jamfile[tag=jamfile] +---- ++ +It prints: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/chacha20_default/chacha20_default.outcome[tag=output] +---- + `+chacha20_poly1305_default+`:: RFC 8439's ChaCha20-Poly1305 example, sealed and opened on its default on every target, with the one line `+/webcpp/crypto//chacha20_poly1305-default+`, which links libsodium. + Its Jamfile, built and run on native, wasip2, wasip3, emscripten: @@ -231,6 +247,22 @@ It prints: include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/p256_default/p256_default.outcome[tag=output] ---- +`+poly1305_default+`:: RFC 8439's Poly1305 example of section 2.5.2, authenticated and verified on its default on every target, with the one line `+/webcpp/crypto//poly1305-default+`, which links libsodium. ++ +Its Jamfile, built and run on native, wasip2, wasip3, emscripten: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/poly1305_default/Jamfile[tag=jamfile] +---- ++ +It prints: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/poly1305_default/poly1305_default.outcome[tag=output] +---- + `+sealed_box_default+`:: A message sealed to Bob's public key and opened with his key pair on the default on every target, with the one line `+/webcpp/crypto//sealed_box-default+`, which links libsodium. + Its Jamfile, built and run on native, wasip2, wasip3, emscripten: diff --git a/doc/generated/matrix.adoc b/doc/generated/matrix.adoc index a356d55..0a64b9f 100644 --- a/doc/generated/matrix.adoc +++ b/doc/generated/matrix.adoc @@ -31,6 +31,21 @@ |native, wasip2, wasip3, emscripten |`+async_aead+` +|`+async_from_key+`, `+unauthenticated_encryption::async_apply_keystream+` +|BearSSL +|native, wasip2, wasip3, emscripten +|`+async_stream_cipher+` + +|`+async_from_key+`, `+unauthenticated_encryption::async_apply_keystream+` +|OpenSSL +|native, wasip2, wasip3; not on emscripten: `+/webcpp/crypto//openssl+` stops the build there +|`+async_stream_cipher_openssl+` + +|`+async_from_key+`, `+unauthenticated_encryption::async_apply_keystream+` +|libsodium +|native, wasip2, wasip3, emscripten +|`+async_stream_cipher+`, `+stream_cipher_shape+` + |`+async_from_secret+`, `+async_generate+`, `+async_sign+`, `+async_verify+` |libsodium |native, wasip2, wasip3, emscripten @@ -196,6 +211,81 @@ |native, wasip2, wasip3, emscripten |`+xchacha_sodium+`, `+chacha_wycheproof_sodium+`, `+allocation_sodium+` +|`+ciphers::chacha20+` +|BearSSL +|native, wasip2, wasip3, emscripten +|`+chacha20_bearssl+`, `+chacha20_bearssl_portable+`, `+allocation_bearssl+`, `+timing_coverage_bearssl+`, `+agreement_chacha20+`, `+agreement_chacha20_emscripten+`, `+agreement_chacha20_portable+`, `+agreement_chacha20_portable_emscripten+`, `+chacha20_nip44_bearssl+` + +|`+ciphers::chacha20+` +|OpenSSL +|native, wasip2, wasip3; not on emscripten: `+/webcpp/crypto//openssl+` stops the build there +|`+chacha20_openssl+`, `+allocation_openssl+`, `+timing_coverage_openssl+`, `+agreement_chacha20+`, `+agreement_chacha20_portable+`, `+chacha20_nip44_openssl+` + +|`+ciphers::chacha20+` +|ctaes +|refused at compile time +|`+chacha20_on_ctaes+` + +|`+ciphers::chacha20+` +|libsodium +|native, wasip2, wasip3, emscripten +|`+chacha20_sodium+`, `+stream_cipher_concepts+`, `+allocation_sodium+`, `+timing_coverage_sodium+`, `+agreement_chacha20+`, `+agreement_chacha20_emscripten+`, `+chacha20_nip44_sodium+` + +|`+unauthenticated_encryption::stream_cipher+`, `+unauthenticated_encryption::apply_keystream+` +|BearSSL +|native, wasip2, wasip3, emscripten +|`+timing_coverage_bearssl+` + +|`+unauthenticated_encryption::stream_cipher+`, `+unauthenticated_encryption::apply_keystream+` +|OpenSSL +|native, wasip2, wasip3; not on emscripten: `+/webcpp/crypto//openssl+` stops the build there +|`+timing_coverage_openssl+` + +|`+unauthenticated_encryption::stream_cipher+`, `+unauthenticated_encryption::apply_keystream+` +|libsodium +|native, wasip2, wasip3, emscripten +|`+stream_cipher_concepts+`, `+stream_cipher_shape+`, `+timing_coverage_sodium+` + +|`+authenticators::poly1305+` +|BearSSL +|refused at compile time +|`+poly1305_on_bearssl+` + +|`+authenticators::poly1305+` +|OpenSSL +|native, wasip2, wasip3; not on emscripten: `+/webcpp/crypto//openssl+` stops the build there +|`+poly1305_openssl+`, `+poly1305_openssl_memory_resource+`, `+allocation_openssl+`, `+timing_coverage_openssl+`, `+agreement_poly1305+`, `+composition_rfc8439+` + +|`+authenticators::poly1305+` +|ctaes +|refused at compile time +|`+poly1305_on_ctaes+` + +|`+authenticators::poly1305+` +|libsodium +|native, wasip2, wasip3, emscripten +|`+poly1305_sodium+`, `+authenticator_concepts+`, `+allocation_sodium+`, `+timing_coverage_sodium+`, `+agreement_poly1305+`, `+agreement_poly1305_emscripten+`, `+composition_rfc8439+`, `+composition_rfc8439_emscripten+` + +|`+single_use_key_authentication::single_use_key_authenticator+`, `+single_use_key_authentication::authenticate+`, `+single_use_key_authentication::verify+` +|OpenSSL +|native, wasip2, wasip3; not on emscripten: `+/webcpp/crypto//openssl+` stops the build there +|`+poly1305_openssl+`, `+timing_coverage_openssl+` + +|`+single_use_key_authentication::single_use_key_authenticator+`, `+single_use_key_authentication::authenticate+`, `+single_use_key_authentication::verify+` +|libsodium +|native, wasip2, wasip3, emscripten +|`+authenticator_concepts+`, `+poly1305_sodium+`, `+timing_coverage_sodium+` + +|`+single_use_key_authentication::async_authenticate+`, `+single_use_key_authentication::async_verify+` +|OpenSSL +|native, wasip2, wasip3; not on emscripten: `+/webcpp/crypto//openssl+` stops the build there +|`+async_authenticator_openssl+`, `+timing_coverage_openssl+` + +|`+single_use_key_authentication::async_authenticate+`, `+single_use_key_authentication::async_verify+` +|libsodium +|native, wasip2, wasip3, emscripten +|`+async_authenticator+`, `+timing_coverage_sodium+` + |`+secret_key_encryption::secretbox+` |libsodium |native, wasip2, wasip3, emscripten @@ -335,6 +425,12 @@ The same, by target: the backends each operation runs on. |BearSSL, OpenSSL, libsodium |BearSSL, libsodium +|`+async_from_key+`, `+unauthenticated_encryption::async_apply_keystream+` +|BearSSL, OpenSSL, libsodium +|BearSSL, OpenSSL, libsodium +|BearSSL, OpenSSL, libsodium +|BearSSL, libsodium + |`+async_from_secret+`, `+async_generate+`, `+async_sign+`, `+async_verify+` |libsodium |libsodium @@ -479,6 +575,36 @@ The same, by target: the backends each operation runs on. |libsodium |libsodium +|`+ciphers::chacha20+` +|BearSSL, OpenSSL, libsodium +|BearSSL, OpenSSL, libsodium +|BearSSL, OpenSSL, libsodium +|BearSSL, libsodium + +|`+unauthenticated_encryption::stream_cipher+`, `+unauthenticated_encryption::apply_keystream+` +|BearSSL, OpenSSL, libsodium +|BearSSL, OpenSSL, libsodium +|BearSSL, OpenSSL, libsodium +|BearSSL, libsodium + +|`+authenticators::poly1305+` +|OpenSSL, libsodium +|OpenSSL, libsodium +|OpenSSL, libsodium +|libsodium + +|`+single_use_key_authentication::single_use_key_authenticator+`, `+single_use_key_authentication::authenticate+`, `+single_use_key_authentication::verify+` +|OpenSSL, libsodium +|OpenSSL, libsodium +|OpenSSL, libsodium +|libsodium + +|`+single_use_key_authentication::async_authenticate+`, `+single_use_key_authentication::async_verify+` +|OpenSSL, libsodium +|OpenSSL, libsodium +|OpenSSL, libsodium +|libsodium + |`+secret_key_encryption::secretbox+` |libsodium |libsodium diff --git a/doc/generated/messages.adoc b/doc/generated/messages.adoc index 72b70f7..b668c14 100644 --- a/doc/generated/messages.adoc +++ b/doc/generated/messages.adoc @@ -67,6 +67,18 @@ The fix: Convert the Ed25519 key pair with `+to_x25519()+` and agree with the X2 The fix: Give `+agree+` the peer's typed public key of the key pair's own curve and backend: `+curves::x25519::public_key::from_bytes(bytes)+` for X25519, `+curves::p256::basic_public_key::from_bytes(bytes)+` for P-256, `+curves::secp256k1::public_key::from_bytes(bytes)+` for secp256k1. +|`+apply_keystream_asynchronous_backend+` +|native, wasip2, wasip3 +|`+webcpp::crypto: WebCrypto has no ChaCha20: no form of the raw stream cipher, synchronous or asynchronous, runs on the browser's backend; name a native backend for it.+` + +The fix: Name a native backend, such as `+backends::sodium+`, for ChaCha20: WebCrypto has no ChaCha20, so neither its `+apply_keystream+` nor its `+async_apply_keystream+` completes on the browser's backend. + +|`+apply_keystream_not_a_stream_cipher+` +|native, wasip2, wasip3 +|`+webcpp::crypto: unauthenticated_encryption::apply_keystream takes a stream cipher (ciphers::chacha20); an AEAD seals and opens through secret_key_encryption::aead.+` + +The fix: Give `+unauthenticated_encryption::apply_keystream+` a stream cipher, `+ciphers::chacha20+`; an AEAD seals and opens through `+secret_key_encryption::aead::seal+` and `+aead::open+`. + |`+async_agree_ed25519+` |native, wasip2, wasip3 |`+webcpp::crypto: async_agree: Ed25519 key pairs sign; they do not agree: convert one with to_x25519() and agree with the X25519 key pair.+` @@ -85,12 +97,54 @@ The fix: Call the key pair's own `+agree+`: secp256k1 is not in WebCrypto, so on The fix: As `+agree_free_wrong_peer+`: give `+async_agree+` the peer's typed public key of the key pair's own curve and backend, `+curves::x25519::public_key::from_bytes(bytes)+` for X25519, `+curves::p256::basic_public_key::from_bytes(bytes)+` for P-256. +|`+async_apply_keystream_asynchronous_backend+` +|native, wasip2, wasip3 +|`+webcpp::crypto: WebCrypto has no ChaCha20: no form of the raw stream cipher, synchronous or asynchronous, runs on the browser's backend; name a native backend for it.+` + +The fix: As `+apply_keystream_asynchronous_backend+`: name a native backend, such as `+backends::sodium+`, for ChaCha20's `+async_apply_keystream+`, free or member. + +|`+async_authenticate_asynchronous_backend+` +|native, wasip2, wasip3 +|`+webcpp::crypto: WebCrypto has no Poly1305: no form of the single-use key authenticator, synchronous or asynchronous, runs on the browser's backend; name a native backend for it.+` + +The fix: As `+authenticate_asynchronous_backend+`: name a native backend, such as `+backends::sodium+`, for Poly1305's `+async_authenticate+`, static or free. + +|`+async_authenticate_not_a_single_use_key_authenticator+` +|native, wasip2, wasip3 +|`+webcpp::crypto: single_use_key_authentication::async_authenticate takes a single-use key authenticator (authenticators::poly1305); a reusable key's MAC is webcpp::hash::async_hmac (HMAC).+` + +The fix: Give `+single_use_key_authentication::async_authenticate+` a single-use key authenticator, `+authenticators::poly1305+`; a key used for many messages is authenticated by the HMAC of `+webcpp::hash+`, asynchronously by `+webcpp::hash::async_hmac+`. + +|`+async_from_key_aead_without_member+` +|native, wasip2, wasip3 +|`+webcpp::crypto: async_from_key runs the synchronous from_key of a stream cipher alone: an AEAD or a secret box without the member async_from_key cannot be made asynchronously.+` + +The fix: Give the AEAD or the secret box a static member `+async_from_key+`, as crypto's have, or call its synchronous `+from_key+`: only a stream cipher's `+from_key+` is run and posted by the free `+async_from_key+` itself. + +|`+async_from_key_chacha20_asynchronous_backend+` +|native, wasip2, wasip3 +|`+webcpp::crypto: WebCrypto has no ChaCha20: no form of the raw stream cipher, synchronous or asynchronous, runs on the browser's backend; name a native backend for it.+` + +The fix: Name a native backend, such as `+backends::sodium+`, for `+async_from_key+`: WebCrypto has no ChaCha20, so no form of the raw stream cipher runs on the browser's backend. + +|`+async_from_key_not_a_cipher+` +|native, wasip2, wasip3 +|`+webcpp::crypto: async_from_key takes an AEAD (a secret_key_encryption::aead::cipher), a stream cipher (a unauthenticated_encryption::stream_cipher) or a secret box: a crypto_box is made by from_keys.+` + +The fix: Give `+async_from_key+` an AEAD, a stream cipher or a secret box; make a crypto_box with `+public_key_encryption::box::from_keys+`, synchronously. + |`+async_from_key_secretbox_asynchronous_backend+` |native, wasip2, wasip3 |`+webcpp::crypto: WebCrypto has no ChaCha20-Poly1305, XChaCha20-Poly1305, secret box or crypto_box: no form of them, synchronous or asynchronous, runs on the browser's backend; name a native backend for them. On the browser's backend only AES-GCM seals and opens.+` The fix: Name a native backend, such as `+backends::sodium+`, for the secret box's `+async_from_key+`: WebCrypto has no secret box. +|`+async_from_key_stream_cipher_without_empty+` +|native, wasip2, wasip3 +|`+webcpp::crypto: async_from_key posts a stream cipher's synchronous from_key, whose error completion gives an empty cipher: give the type a noexcept default constructor, public or private with webcpp::crypto::detail::async_access a friend.+` + +The fix: Give the stream cipher a `+noexcept+` default constructor that makes an empty object (public, or private with `+webcpp::crypto::detail::async_access+` a friend), or a static member `+async_from_key+`: the free form's error completion gives the empty cipher. + |`+async_from_key_xchacha+` |native, wasip2, wasip3 |`+webcpp::crypto: WebCrypto has no ChaCha20-Poly1305, XChaCha20-Poly1305, secret box or crypto_box: no form of them, synchronous or asynchronous, runs on the browser's backend; name a native backend for them. On the browser's backend only AES-GCM seals and opens.+` @@ -191,6 +245,12 @@ The fix: Call the key pair's own signing function: secp256k1 is not in WebCrypto The fix: As `+sign_x25519+`: give `+async_sign+` an Ed25519 key pair, which signs; an X25519 key pair agrees, with `+async_agree+`. +|`+async_verify_asynchronous_backend+` +|native, wasip2, wasip3 +|`+webcpp::crypto: WebCrypto has no Poly1305: no form of the single-use key authenticator, synchronous or asynchronous, runs on the browser's backend; name a native backend for it.+` + +The fix: As `+authenticate_asynchronous_backend+`: name a native backend, such as `+backends::sodium+`, for Poly1305's `+async_verify+`, static or free. + |`+async_verify_eddsa_bytes_key+` |native, wasip2, wasip3 |`+webcpp::crypto: async_verify takes crypto::signing_schemes::eddsa or crypto::signing_schemes::eddsa_prehashed with a curves::ed25519::public_key or crypto::signing_schemes::ecdsa_sha256 with a curves::p256::basic_public_key, the algorithms WebCrypto has: call crypto::verify for the others.+` @@ -209,6 +269,12 @@ The fix: As `+verify_eddsa_prehashed_asynchronous_backend+`: `+async_verify+` un The fix: As `+async_verify_wrong_key+`: naming the backend does not add a scheme; call `+crypto::verify+` for `+crypto::signing_schemes::schnorr+` and secp256k1's keys. +|`+async_verify_not_a_single_use_key_authenticator+` +|native, wasip2, wasip3 +|`+webcpp::crypto: single_use_key_authentication::async_verify takes a single-use key authenticator (authenticators::poly1305); a reusable key's MAC is webcpp::hash::async_hmac (HMAC).+` + +The fix: Give `+single_use_key_authentication::async_verify+` a single-use key authenticator, `+authenticators::poly1305+`; a key used for many messages is authenticated by the HMAC of `+webcpp::hash+`, asynchronously by `+webcpp::hash::async_hmac+`. + |`+async_verify_p256_bytes_signature+` |native, wasip2, wasip3 |`+webcpp::crypto: verify: a P-256 key verifies a curves::p256::ecdsa_signature: make one from 64 bytes with curves::p256::ecdsa_signature::from_bytes.+` @@ -233,6 +299,18 @@ The fix: As `+verify_without_policy+`: `+async_verify(executor, crypto::signing_ The fix: Call `+crypto::verify+` for a key the asynchronous family lacks (secp256k1's, Schnorr's x-only key): `+async_verify+` has a `+curves::ed25519::public_key+` with `+crypto::signing_schemes::eddsa+` or `+crypto::signing_schemes::eddsa_prehashed+` and a `+curves::p256::basic_public_key+` with `+crypto::signing_schemes::ecdsa_sha256+`. +|`+authenticate_asynchronous_backend+` +|native, wasip2, wasip3 +|`+webcpp::crypto: WebCrypto has no Poly1305: no form of the single-use key authenticator, synchronous or asynchronous, runs on the browser's backend; name a native backend for it.+` + +The fix: Name a native backend, such as `+backends::sodium+`, for Poly1305: WebCrypto has no Poly1305, so neither its `+authenticate+`, static or free, nor its asynchronous forms run on the browser's backend. + +|`+authenticate_not_a_single_use_key_authenticator+` +|native, wasip2, wasip3 +|`+webcpp::crypto: single_use_key_authentication::authenticate takes a single-use key authenticator (authenticators::poly1305); a reusable key's MAC is webcpp::hash::mac (HMAC).+` + +The fix: Give `+single_use_key_authentication::authenticate+` a single-use key authenticator, `+authenticators::poly1305+`; a key used for many messages is authenticated by the HMAC of `+webcpp::hash+`. + |`+bearssl_not_linked+` |native, wasip2 |`+webcpp::crypto: the backend BearSSL is used and not linked. In the program's Jamfile, add /third_party//bearssl beside /webcpp/crypto//crypto. (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)+` @@ -259,6 +337,36 @@ The fix: The secret boxes', the boxes' and the sealed boxes' default is libsodiu The fix: Name `+families::box_xsalsa20poly1305+` or `+families::box_xchacha20poly1305+`, or use `+public_key_encryption::box+` or `+public_key_encryption::box_xchacha20poly1305+`. +|`+chacha20_default_not_linked+` +|native, wasip2, wasip3 +|`+webcpp::crypto: ChaCha20's default backend on this target is libsodium, which is not linked. Add /webcpp/crypto//chacha20-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//chacha20-default ; or name another backend in the type, as in ciphers::chacha20. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)+` + +The fix: ChaCha20's default is libsodium on every target: add the family's alias, `+/webcpp/crypto//chacha20-default+`, which links `+/third_party//sodium+`, or name another backend in the type, as `+chacha20+`. + +|`+chacha20_header_not_included+` +|native, wasip2, wasip3 +|`+webcpp::crypto: bearssl's ChaCha20 is in , which the program does not include. Include it, and add /third_party//bearssl to the program's Jamfile.+` + +The fix: Include the backend's header the message names, as `++`, and add its library, as `+/third_party//bearssl+`. + +|`+chacha20_not_a_family+` +|native, wasip2, wasip3 +|`+webcpp::crypto: ciphers::basic_chacha20 takes a stream family: families::chacha20.+` + +The fix: Name the family `+families::chacha20+`, or use the alias `+ciphers::chacha20+`; an AEAD's family seals through `+ciphers::chacha20_poly1305+`. + +|`+chacha20_on_ctaes+` +|native, wasip2, wasip3 +|`+webcpp::crypto: ctaes has no ChaCha20. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).+` + +The fix: Name a backend that has ChaCha20, as in `+chacha20+`, or its default, `+chacha20<>+`, and link its library. + +|`+chacha20_unknown_backend+` +|native, wasip2, wasip3 +|`+webcpp::crypto: ChaCha20 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).+` + +The fix: Name a backend of `+webcpp::crypto::backends+` that has ChaCha20, as `+backends::sodium+`, or leave the backend out for the family's default: `+chacha20<>+`. + |`+chacha_default_not_linked+` |native, wasip2, wasip3 |`+webcpp::crypto: ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked. Add /webcpp/crypto//chacha20_poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//chacha20_poly1305-default ; or name another backend in the type, as in ciphers::chacha20_poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)+` @@ -451,6 +559,36 @@ The fix: Include `++`, or the curve's `+::authenticate(key, message)+`, or `+single_use_key_authentication::authenticate>(key, message)+`, with a fresh key for each message. + +|`+from_key_secretbox_asynchronous_backend+` +|native, wasip2, wasip3 +|`+webcpp::crypto: WebCrypto has no ChaCha20-Poly1305, XChaCha20-Poly1305, secret box or crypto_box: no form of them, synchronous or asynchronous, runs on the browser's backend; name a native backend for them. On the browser's backend only AES-GCM seals and opens.+` + +The fix: As `+seal_secretbox_asynchronous_backend+`: name a native backend, such as `+backends::sodium+`, for the `+from_key+` of the secret box. + +|`+from_keys_box_asynchronous_backend+` +|native, wasip2, wasip3 +|`+webcpp::crypto: WebCrypto has no ChaCha20-Poly1305, XChaCha20-Poly1305, secret box or crypto_box: no form of them, synchronous or asynchronous, runs on the browser's backend; name a native backend for them. On the browser's backend only AES-GCM seals and opens.+` + +The fix: As `+seal_box_asynchronous_backend+`: name a native backend, such as `+backends::sodium+`, for the `+from_keys+` of the crypto_box. + |`+gcm_default_openssl_not_linked+` |native |`+webcpp::crypto: AES-GCM's default backend on this target is OpenSSL, which is not linked. Add /webcpp/crypto//gcm-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//gcm-default ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_OPENSSL=1 and link libcrypto)+` @@ -761,6 +899,36 @@ The fix: Export the key pair with WebCrypto's `+exportKey+`, on the backend that The fix: Export the key pair with WebCrypto's `+exportKey+`, on the backend that keeps it, or make the key pair on a backend whose secret is in the program, BearSSL, to encode it in `+crypto::formats::pkcs8+`, `+crypto::formats::raw+` or `+crypto::formats::pem(crypto::formats::pkcs8)+`; its public key's formats are available on every backend. +|`+poly1305_default_not_linked+` +|native, wasip2, wasip3 +|`+webcpp::crypto: Poly1305's default backend on this target is libsodium, which is not linked. Add /webcpp/crypto//poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//poly1305-default ; or name another backend in the type, as in authenticators::poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)+` + +The fix: Poly1305's default is libsodium on every target: add the family's alias, `+/webcpp/crypto//poly1305-default+`, which links `+/third_party//sodium+`, or name another backend in the type, as `+poly1305+`. + +|`+poly1305_header_not_included+` +|native, wasip2, wasip3 +|`+webcpp::crypto: openssl's Poly1305 is in , which the program does not include. Include it, and add /webcpp/crypto//openssl to the program's Jamfile.+` + +The fix: Include the backend's header the message names, as `++`, and add its library, as `+/webcpp/crypto//openssl+`. + +|`+poly1305_on_bearssl+` +|native, wasip2, wasip3 +|`+webcpp::crypto: bearssl has no Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).+` + +The fix: Name a backend that has Poly1305, as in `+poly1305+`, or its default, `+poly1305<>+`, and link its library: BearSSL's Poly1305 is inside its ChaCha20-Poly1305 alone, which derives the key itself. + +|`+poly1305_on_ctaes+` +|native, wasip2, wasip3 +|`+webcpp::crypto: ctaes has no Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).+` + +The fix: Name a backend that has Poly1305, as in `+poly1305+`, or its default, `+poly1305<>+`, and link its library. + +|`+poly1305_unknown_backend+` +|native, wasip2, wasip3 +|`+webcpp::crypto: Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).+` + +The fix: Name a backend of `+webcpp::crypto::backends+` that has Poly1305, as `+backends::sodium+` or `+backends::openssl+`, or leave the backend out for the family's default: `+poly1305<>+`. + |`+prehashed_dynamic+` |native, wasip2, wasip3 |`+webcpp::crypto: crypto::signing_schemes::prehashed takes a digest of a fixed size: a std::array or a std::span.+` @@ -1169,6 +1337,12 @@ The fix: Verify with `+crypto::signing_schemes::ecdsa_sha256+`, P-256's scheme; The fix: Give a recoverable signature to `+curves::secp256k1::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, crypto::verification_policies::low_s_only, signature, input)+`, which gives the signer's key; a public key verifies `+crypto::signing_schemes::ecdsa_sha256+` and `+crypto::signing_schemes::schnorr+`. +|`+verify_not_a_single_use_key_authenticator+` +|native, wasip2, wasip3 +|`+webcpp::crypto: single_use_key_authentication::verify takes a single-use key authenticator (authenticators::poly1305); a reusable key's MAC is webcpp::hash::mac (HMAC).+` + +The fix: Give `+single_use_key_authentication::verify+` a single-use key authenticator, `+authenticators::poly1305+`; a key used for many messages is authenticated by the HMAC of `+webcpp::hash+`. + |`+verify_p256_canonical+` |native, wasip2, wasip3 |`+webcpp::crypto: verify: crypto::signing_schemes::ecdsa_sha256 on a P-256 key takes crypto::verification_policies::low_s_only or any_s.+` @@ -1181,6 +1355,12 @@ The fix: Verify P-256's ECDSA under `+crypto::verification_policies::low_s_only+ The fix: Give a P-256 key a `+curves::p256::ecdsa_signature+`, made from the 64 bytes received with `+curves::p256::ecdsa_signature::from_bytes+`; a secp256k1 signature verifies with a `+curves::secp256k1::public_key+`. +|`+verify_poly1305_asynchronous_backend+` +|native, wasip2, wasip3 +|`+webcpp::crypto: WebCrypto has no Poly1305: no form of the single-use key authenticator, synchronous or asynchronous, runs on the browser's backend; name a native backend for it.+` + +The fix: As `+authenticate_asynchronous_backend+`: name a native backend, such as `+backends::sodium+`, for Poly1305's `+verify+`, static or free. + |`+verify_schnorr_any_s+` |native, wasip2, wasip3 |`+webcpp::crypto: verify: crypto::signing_schemes::schnorr takes crypto::verification_policies::canonical.+` @@ -1930,6 +2110,14 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |Give `+agree+` the peer's typed public key of the key pair's own curve and backend: `+curves::x25519::public_key::from_bytes(bytes)+` for X25519, `+curves::p256::basic_public_key::from_bytes(bytes)+` for P-256, `+curves::secp256k1::public_key::from_bytes(bytes)+` for secp256k1. +|`+apply_keystream_async_backend+` +|the compile +|Name a native backend, such as `+backends::sodium+`, for ChaCha20: WebCrypto has no ChaCha20, so neither its `+apply_keystream+` nor its `+async_apply_keystream+` completes on the browser's backend. + +|`+apply_keystream_not_a_stream_cipher+` +|the compile +|Give `+unauthenticated_encryption::apply_keystream+` a stream cipher, `+ciphers::chacha20+`; an AEAD seals and opens through `+secret_key_encryption::aead::seal+` and `+aead::open+`. + |`+async_agree_ed25519+` |the compile |As `+agree_ed25519+`: give `+async_agree+` the X25519 key pair that the Ed25519 key pair's `+to_x25519()+` gives, and the peer's converted key. @@ -1942,10 +2130,38 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |As `+agree_free_wrong_peer+`: give `+async_agree+` the peer's typed public key of the key pair's own curve and backend, `+curves::x25519::public_key::from_bytes(bytes)+` for X25519, `+curves::p256::basic_public_key::from_bytes(bytes)+` for P-256. +|`+async_apply_keystream_async_bk+` +|the compile +|As `+apply_keystream_asynchronous_backend+`: name a native backend, such as `+backends::sodium+`, for ChaCha20's `+async_apply_keystream+`, free or member. + +|`+async_authenticate_asynchronous_backend+` +|the compile +|As `+authenticate_asynchronous_backend+`: name a native backend, such as `+backends::sodium+`, for Poly1305's `+async_authenticate+`, static or free. + +|`+async_authenticate_not_an_authenticator+` +|the compile +|Give `+single_use_key_authentication::async_authenticate+` a single-use key authenticator, `+authenticators::poly1305+`; a key used for many messages is authenticated by the HMAC of `+webcpp::hash+`, asynchronously by `+webcpp::hash::async_hmac+`. + +|`+async_from_key_aead_without_member+` +|the compile +|Give the AEAD or the secret box a static member `+async_from_key+`, as crypto's have, or call its synchronous `+from_key+`: only a stream cipher's `+from_key+` is run and posted by the free `+async_from_key+` itself. + +|`+async_from_key_chacha20_async_bk+` +|the compile +|Name a native backend, such as `+backends::sodium+`, for `+async_from_key+`: WebCrypto has no ChaCha20, so no form of the raw stream cipher runs on the browser's backend. + +|`+async_from_key_not_a_cipher+` +|the compile +|Give `+async_from_key+` an AEAD, a stream cipher or a secret box; make a crypto_box with `+public_key_encryption::box::from_keys+`, synchronously. + |`+async_from_key_secretbox_async_backend+` |the compile |Name a native backend, such as `+backends::sodium+`, for the secret box's `+async_from_key+`: WebCrypto has no secret box. +|`+async_from_key_stream_cipher_no_empty+` +|the compile +|Give the stream cipher a `+noexcept+` default constructor that makes an empty object (public, or private with `+webcpp::crypto::detail::async_access+` a friend), or a static member `+async_from_key+`: the free form's error completion gives the empty cipher. + |`+async_from_key_xchacha+` |the compile |Name a native backend, such as `+backends::sodium+`, for `+async_from_key+`: WebCrypto has no XChaCha20-Poly1305, so no form of it runs on the browser's backend, where only AES-GCM seals and opens. @@ -2010,6 +2226,10 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |As `+sign_x25519+`: give `+async_sign+` an Ed25519 key pair, which signs; an X25519 key pair agrees, with `+async_agree+`. +|`+async_verify_asynchronous_backend+` +|the compile +|As `+authenticate_asynchronous_backend+`: name a native backend, such as `+backends::sodium+`, for Poly1305's `+async_verify+`, static or free. + |`+async_verify_ed25519ph_on_async_backend+` |the compile |As `+verify_eddsa_prehashed_asynchronous_backend+`: `+async_verify+` under `+crypto::signing_schemes::eddsa_prehashed+`, free and member, runs on a native backend. @@ -2022,6 +2242,10 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |As `+async_verify_wrong_key+`: naming the backend does not add a scheme; call `+crypto::verify+` for `+crypto::signing_schemes::schnorr+` and secp256k1's keys. +|`+async_verify_not_an_authenticator+` +|the compile +|Give `+single_use_key_authentication::async_verify+` a single-use key authenticator, `+authenticators::poly1305+`; a key used for many messages is authenticated by the HMAC of `+webcpp::hash+`, asynchronously by `+webcpp::hash::async_hmac+`. + |`+async_verify_p256_bytes_signature+` |the compile |As `+verify_p256_secp256k1_signature+`: make the 64 bytes received into a `+curves::p256::ecdsa_signature+` with `+from_bytes+`, then give it to `+async_verify+`. @@ -2038,6 +2262,14 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |Call `+crypto::verify+` for a key the asynchronous family lacks (secp256k1's, Schnorr's x-only key): `+async_verify+` has a `+curves::ed25519::public_key+` with `+crypto::signing_schemes::eddsa+` or `+crypto::signing_schemes::eddsa_prehashed+` and a `+curves::p256::basic_public_key+` with `+crypto::signing_schemes::ecdsa_sha256+`. +|`+authenticate_asynchronous_backend+` +|the compile +|Name a native backend, such as `+backends::sodium+`, for Poly1305: WebCrypto has no Poly1305, so neither its `+authenticate+`, static or free, nor its asynchronous forms run on the browser's backend. + +|`+authenticate_not_an_authenticator+` +|the compile +|Give `+single_use_key_authentication::authenticate+` a single-use key authenticator, `+authenticators::poly1305+`; a key used for many messages is authenticated by the HMAC of `+webcpp::hash+`. + |`+bearssl_not_linked+` |the compile |Add `+/third_party//bearssl+`. @@ -2086,6 +2318,26 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the link |Compile every file of the program with the same backend settings. +|`+chacha20_default_not_linked+` +|the compile +|ChaCha20's default is libsodium on every target: add the family's alias, `+/webcpp/crypto//chacha20-default+`, which links `+/third_party//sodium+`, or name another backend in the type, as `+chacha20+`. + +|`+chacha20_header_not_included+` +|the compile +|Include the backend's header the message names, as `++`, and add its library, as `+/third_party//bearssl+`. + +|`+chacha20_not_a_family+` +|the compile +|Name the family `+families::chacha20+`, or use the alias `+ciphers::chacha20+`; an AEAD's family seals through `+ciphers::chacha20_poly1305+`. + +|`+chacha20_on_ctaes+` +|the compile +|Name a backend that has ChaCha20, as in `+chacha20+`, or its default, `+chacha20<>+`, and link its library. + +|`+chacha20_unknown_backend+` +|the compile +|Name a backend of `+webcpp::crypto::backends+` that has ChaCha20, as `+backends::sodium+`, or leave the backend out for the family's default: `+chacha20<>+`. + |`+chacha_default_not_linked+` |the compile |The ChaCha20-Poly1305 AEADs' default is libsodium on every target: add the family's alias, as `+/webcpp/crypto//chacha20_poly1305-default+`, which links `+/third_party//sodium+`. @@ -2210,6 +2462,26 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |List `+crypto::formats::default_form_t+` in each `+detail::forms_of+` specialization, with the other point forms the type accepts. +|`+from_key_chacha20_asynchronous_backend+` +|the compile +|As `+apply_keystream_asynchronous_backend+`: name a native backend, such as `+backends::sodium+`, for the `+from_key+` of ChaCha20. + +|`+from_key_chacha20_poly1305_async_backend+` +|the compile +|Name a native backend, such as `+backends::sodium+`, for ChaCha20-Poly1305: WebCrypto has no ChaCha20-Poly1305, so neither its `+from_key+` nor its `+async_from_key+` completes on the browser's backend; there, use AES-GCM. + +|`+from_key_poly1305+` +|the compile +|Poly1305 has no object and no `+from_key+`: call `+authenticators::poly1305<>::authenticate(key, message)+`, or `+single_use_key_authentication::authenticate>(key, message)+`, with a fresh key for each message. + +|`+from_key_secretbox_asynchronous_backend+` +|the compile +|As `+seal_secretbox_asynchronous_backend+`: name a native backend, such as `+backends::sodium+`, for the `+from_key+` of the secret box. + +|`+from_keys_box_asynchronous_backend+` +|the compile +|As `+seal_box_asynchronous_backend+`: name a native backend, such as `+backends::sodium+`, for the `+from_keys+` of the crypto_box. + |`+gcm_default_openssl_not_linked+` |the compile |Natively the default is OpenSSL: add `+/webcpp/crypto//gcm-default+`, which links `+/webcpp/crypto//openssl+` there, or name BearSSL in the type, as in `+gcm>+`. @@ -2414,6 +2686,26 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |Export the key pair with WebCrypto's `+exportKey+`, on the backend that keeps it, or make the key pair on a backend whose secret is in the program, BearSSL, to encode it in `+crypto::formats::pkcs8+`, `+crypto::formats::raw+` or `+crypto::formats::pem(crypto::formats::pkcs8)+`; its public key's formats are available on every backend. +|`+poly1305_default_not_linked+` +|the compile +|Poly1305's default is libsodium on every target: add the family's alias, `+/webcpp/crypto//poly1305-default+`, which links `+/third_party//sodium+`, or name another backend in the type, as `+poly1305+`. + +|`+poly1305_header_not_included+` +|the compile +|Include the backend's header the message names, as `++`, and add its library, as `+/webcpp/crypto//openssl+`. + +|`+poly1305_on_bearssl+` +|the compile +|Name a backend that has Poly1305, as in `+poly1305+`, or its default, `+poly1305<>+`, and link its library: BearSSL's Poly1305 is inside its ChaCha20-Poly1305 alone, which derives the key itself. + +|`+poly1305_on_ctaes+` +|the compile +|Name a backend that has Poly1305, as in `+poly1305+`, or its default, `+poly1305<>+`, and link its library. + +|`+poly1305_unknown_backend+` +|the compile +|Name a backend of `+webcpp::crypto::backends+` that has Poly1305, as `+backends::sodium+` or `+backends::openssl+`, or leave the backend out for the family's default: `+poly1305<>+`. + |`+prehashed_dynamic+` |the compile |Give `+crypto::signing_schemes::prehashed+` a digest of a fixed size: a `+std::array+`, a `+std::span+` or a `+boost::hash2::digest<32>+`. @@ -2658,6 +2950,10 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |Give a recoverable signature to `+curves::secp256k1::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, crypto::verification_policies::low_s_only, signature, input)+`, which gives the signer's key; a public key verifies `+crypto::signing_schemes::ecdsa_sha256+` and `+crypto::signing_schemes::schnorr+`. +|`+verify_not_an_authenticator+` +|the compile +|Give `+single_use_key_authentication::verify+` a single-use key authenticator, `+authenticators::poly1305+`; a key used for many messages is authenticated by the HMAC of `+webcpp::hash+`. + |`+verify_p256_canonical+` |the compile |Verify P-256's ECDSA under `+crypto::verification_policies::low_s_only+`, for a signature crypto made, or `+any_s+`, for one a browser's WebCrypto or a passkey made, whose S may be high; `+canonical+` is Ed25519's and BIP340's. @@ -2666,6 +2962,10 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |Give a P-256 key a `+curves::p256::ecdsa_signature+`, made from the 64 bytes received with `+curves::p256::ecdsa_signature::from_bytes+`; a secp256k1 signature verifies with a `+curves::secp256k1::public_key+`. +|`+verify_poly1305_asynchronous_backend+` +|the compile +|As `+authenticate_asynchronous_backend+`: name a native backend, such as `+backends::sodium+`, for Poly1305's `+verify+`, static or free. + |`+verify_schnorr_any_s+` |the compile |Verify BIP340 under `+crypto::verification_policies::canonical+`, its only policy; `+low_s_only+` and `+any_s+` are ECDSA's. diff --git a/doc/generated/namespace-ciphers.adoc b/doc/generated/namespace-ciphers.adoc index 18195ae..9d377e5 100644 --- a/doc/generated/namespace-ciphers.adoc +++ b/doc/generated/namespace-ciphers.adoc @@ -126,3 +126,45 @@ |the peer writes libsodium's original construction; otherwise RFC 8439's form or XChaCha20-Poly1305 |you encrypt many messages under one key and want to draw each nonce at random: a chat app, records in a database, on the web and natively alike; when in doubt, this one |=== + +.ChaCha20 +[cols="2h,5",options="header"] +|=== +|Algorithm |ChaCha20, the raw stream cipher + +|Names +|`chacha20` + +|AEAD +|no: it authenticates nothing; a bit flipped in the ciphertext flips the same bit of the plaintext + +|Key +|32 bytes + +|Nonce +|12 bytes, and a 32-bit block counter the caller names + +|Nonce misuse +|not resistant: a repeated nonce under one key reveals the plaintexts' XOR (link:https://www.rfc-editor.org/rfc/rfc8439#section-4[RFC 8439, section 4: a nonce is never repeated under one key]) + +|Speed, with and without hardware support +|not measured yet + +|Constant time, by design +|libsodium, BearSSL and OpenSSL: yes, additions, XORs and rotations with no table indexed by a secret (link:https://www.rfc-editor.org/rfc/rfc8439#section-2.1[RFC 8439, section 2.1: ChaCha's quarter round, additions, XORs and rotations of 32-bit words]; link:https://doc.libsodium.org/secret-key_cryptography/aead[libsodium's documentation, AEAD constructions: ChaCha20 and timing attacks]) + +|Constant time, measured +|libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found; not measured yet on wasip2, wasip3, emscripten. BearSSL: native, Valgrind's memcheck (Linux), MemorySanitizer (Linux, clang) and dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; wasip2, dudect (printed, not judged: under wasmtime its timing follows the runner's processor); not measured yet on wasip3, emscripten. OpenSSL: native, Valgrind's memcheck (Linux), nothing found; not measured yet on wasip2, wasip3 (<>) + +|Standards +|link:https://www.rfc-editor.org/rfc/rfc8439[RFC 8439, ChaCha20 and Poly1305 for IETF Protocols] + +|Where it is used +|NIP-44's encryption, under its HMAC-SHA256 (link:https://github.com/nostr-protocol/nips/blob/master/44.md[Nostr NIP-44, encrypted payloads]) + +|Browsers' WebCrypto +|no (link:https://www.w3.org/TR/WebCryptoAPI/[W3C Web Cryptography API]) + +|Choose it when +|a protocol fixes its own construction over raw ChaCha20 and authenticates the nonce and the ciphertext itself, as NIP-44 does; a program's own messages take `chacha20_poly1305` or `xchacha20_poly1305` +|=== diff --git a/doc/generated/namespace-single_use_key_authentication.adoc b/doc/generated/namespace-single_use_key_authentication.adoc new file mode 100644 index 0000000..3263ef9 --- /dev/null +++ b/doc/generated/namespace-single_use_key_authentication.adoc @@ -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) + +// Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, +// the message tests and the Jamfile fixtures: run it again, never edit this file. + +[cols="2h,5,5",options="header"] +|=== +|Name |Poly1305, the one-time authenticator |The single-use key authenticator contract + +|Names +|`poly1305` +|`single_use_key_authenticator`, `authenticate`, `verify` + +|What it is +|RFC 8439's authenticator, an algorithm of `authenticators`: a 16-byte tag of a message under a key that authenticates that message alone; `authenticate` and `verify` are static, and the key enters every call +|the contract every authenticator whose key is used once satisfies: `single_use_key_authenticator` checks its key and tag sizes, its tag type and its static `authenticate` and `verify`; `authenticate` and `verify` are their free forms + +|Key +|32 bytes, r and s, used for one message +|the authenticator's + +|Tag +|16 bytes +|the authenticator's + +|Key reuse +|forbidden: two messages under one key let the key be recovered and tags be forged (link:https://www.rfc-editor.org/rfc/rfc8439#section-2.5[RFC 8439, section 2.5: the one-time key is used for one message alone; an attacker who sees two tags under it can forge]) +|none: a contract, not an algorithm; each key authenticates one message + +|Speed +|not measured yet +|none: a contract, not an algorithm + +|Constant time, measured +|libsodium: native, Valgrind's memcheck (Linux; `+authenticate+`, then `+verify+` with the right tag and with a wrong one, the key, the message and the tags secret; the verdict of `+verify+` declassified by crypto where it first branches on it), MemorySanitizer (Linux, clang; the same paths as memcheck's) and dudect (judged; on a runner GitHub hosts, by two of three runs; `+authenticate+` against its key, the all-zero key against random ones; `+verify+` against its tag, the right tag with its last byte flipped against it with its first byte flipped, both classes failing: a success and a failure return by different paths, about 0.4 ns apart, which dudect finds and which is public, the verdict being reported), nothing found; wasip2, dudect (judged; on a runner GitHub hosts, by two of three runs; `+authenticate+` against its key, the all-zero key against random ones; `+verify+` against its tag, the right tag with its last byte flipped against it with its first byte flipped, both classes failing: a success and a failure return by different paths, about 0.4 ns apart, which dudect finds and which is public, the verdict being reported), nothing found; not measured yet on wasip3, emscripten. OpenSSL (`+authenticate+` and `+verify+`, as on libsodium): native, Valgrind's memcheck (Linux), nothing found; not measured yet on wasip2, wasip3 (<>) +|none: a contract, not an algorithm + +|Standards and sources +|link:https://www.rfc-editor.org/rfc/rfc8439[RFC 8439, ChaCha20 and Poly1305 for IETF Protocols], link:https://doc.libsodium.org/advanced/poly1305[libsodium's one-time authentication, crypto_onetimeauth_poly1305] +|none: a contract, not an algorithm; Poly1305's is link:https://www.rfc-editor.org/rfc/rfc8439[RFC 8439, ChaCha20 and Poly1305 for IETF Protocols] + +|Where it is used +|inside ChaCha20-Poly1305 and the secret boxes, under a key derived for each message (link:https://www.rfc-editor.org/rfc/rfc8439[RFC 8439, ChaCha20 and Poly1305 for IETF Protocols]) +|none: a contract; Poly1305 is used inside ChaCha20-Poly1305 (link:https://www.rfc-editor.org/rfc/rfc8439[RFC 8439, ChaCha20 and Poly1305 for IETF Protocols]) + +|Choose it when +|a protocol fixes its own construction over raw Poly1305 and derives its key for each message; a key used for many messages takes the HMAC of `webcpp::hash`, and a program's own messages an AEAD +|code is written once for every single-use key authenticator; a reusable key's MAC is the HMAC of `webcpp::hash` +|=== diff --git a/doc/generated/namespace-unauthenticated_encryption.adoc b/doc/generated/namespace-unauthenticated_encryption.adoc new file mode 100644 index 0000000..c088bfd --- /dev/null +++ b/doc/generated/namespace-unauthenticated_encryption.adoc @@ -0,0 +1,37 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, +// the message tests and the Jamfile fixtures: run it again, never edit this file. + +[cols="2h,5",options="header"] +|=== +|Contract |The stream cipher contract + +|Names +|`stream_cipher`, `apply_keystream` + +|What it is +|the contract every raw stream cipher of `ciphers` satisfies: `stream_cipher` checks its key, nonce and block sizes, its counter type, `from_key` and `apply_keystream`, which reads the algorithm's own shape, never ChaCha20's; `apply_keystream` is its free form + +|Key +|the cipher's + +|Nonce +|the cipher's, with its block counter + +|Authentication +|none: the keystream XORed into the data; the protocol authenticates the nonce and the ciphertext itself + +|Standards and sources +|none: a contract, not an algorithm; ChaCha20's is link:https://www.rfc-editor.org/rfc/rfc8439[RFC 8439, ChaCha20 and Poly1305 for IETF Protocols] + +|Where it is used +|NIP-44, whose HMAC-SHA256 covers the nonce and the ciphertext (link:https://github.com/nostr-protocol/nips/blob/master/44.md[Nostr NIP-44, encrypted payloads]) + +|Choose it when +|a protocol fixes its own construction over a raw stream cipher, or code is written once for every stream cipher; a program's own messages take the AEADs of `secret_key_encryption` +|=== diff --git a/doc/generated/sizes.adoc b/doc/generated/sizes.adoc index 87f28f1..1c279c6 100644 --- a/doc/generated/sizes.adoc +++ b/doc/generated/sizes.adoc @@ -7,71 +7,71 @@ // Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, // the message tests and the Jamfile fixtures: run it again, never edit this file. -The lane sizes measured on 2026-11-21, at variant=release: native, clang-21 on Darwin arm64, the Mach-O executable stripped, whose segments are page-aligned: a small cell can add fewer raw bytes than its code, which its gzip -9n bytes show better; wasip2, clang-wasip2, the .wasm; wasip3, clang-wasip3, the .wasm; emscripten, emscripten-6.0.11, the .wasm and its .js. +The lane sizes measured on 2026-12-05, at variant=release: native, clang-21 on Darwin arm64, the Mach-O executable stripped, whose segments are page-aligned: a small cell can add fewer raw bytes than its code, which its gzip -9n bytes show better; wasip2, clang-wasip2, the .wasm; wasip3, clang-wasip3, the .wasm; emscripten, emscripten-6.0.11, the .wasm and its .js. [cols="3,2,2,2,2",options="header"] |=== |Program |Size, native |Size, wasip2 |Size, wasip3 |Size, emscripten |The baseline: the harness of every sized program, calling nothing of crypto -|51,248 B, gzip 3,179 B -|64,422 B, gzip 24,404 B -|74,060 B, gzip 27,432 B -|29,948 B, gzip 12,988 B +|51,248 B, gzip 3,264 B +|64,598 B, gzip 24,482 B +|74,236 B, gzip 27,515 B +|30,124 B, gzip 13,080 B |AES-GCM on BearSSL: seal of 16 KiB, 256-bit key -|+1,680 B, gzip +8,525 B -|+17,489 B, gzip +5,984 B -|+17,528 B, gzip +5,911 B -|+14,210 B, gzip +5,424 B +|+18,144 B, gzip +9,266 B +|+17,993 B, gzip +6,076 B +|+18,016 B, gzip +6,001 B +|+14,560 B, gzip +5,553 B |AES-GCM on OpenSSL: seal of 16 KiB, 256-bit key -|+3,244,928 B, gzip +1,744,819 B -|+2,261,797 B, gzip +754,208 B -|+2,266,672 B, gzip +755,256 B +|+3,244,880 B, gzip +1,745,286 B +|+2,262,788 B, gzip +754,452 B +|+2,267,663 B, gzip +755,509 B |not on this target |AES block cipher on OpenSSL: encryption of one 16-byte block, 256-bit key -|+3,244,936 B, gzip +1,744,087 B -|+2,260,267 B, gzip +753,446 B -|+2,265,118 B, gzip +754,717 B +|+3,244,888 B, gzip +1,744,292 B +|+2,260,268 B, gzip +753,541 B +|+2,265,119 B, gzip +754,749 B |not on this target |AES block cipher on ctaes: encryption of one 16-byte block, 256-bit key -|+1,016 B, gzip +4,064 B -|+7,109 B, gzip +2,438 B -|+7,109 B, gzip +2,391 B -|+5,813 B, gzip +1,952 B +|+968 B, gzip +4,397 B +|+7,109 B, gzip +2,433 B +|+7,109 B, gzip +2,375 B +|+5,813 B, gzip +1,953 B |secp256k1 on libsecp256k1: BIP340 signature of a 32-byte message -|+67,960 B, gzip +56,423 B -|+115,797 B, gzip +55,251 B -|+117,545 B, gzip +56,024 B -|+85,827 B, gzip +34,071 B +|+67,912 B, gzip +56,679 B +|+115,599 B, gzip +55,351 B +|+117,261 B, gzip +56,165 B +|+86,741 B, gzip +34,237 B |secp256k1 on libsecp256k1: x coordinate of the ECDH shared point with a peer's public key -|+117,712 B, gzip +82,352 B -|+214,304 B, gzip +84,102 B -|+216,049 B, gzip +84,945 B -|+175,258 B, gzip +63,047 B +|+84,528 B, gzip +67,799 B +|+154,213 B, gzip +68,442 B +|+155,887 B, gzip +68,996 B +|+121,455 B, gzip +46,045 B |secp256k1 on libsecp256k1: public key recovered from an ECDSA signature of a 32-byte hash -|+1,174,448 B, gzip +1,146,976 B -|+1,293,150 B, gzip +1,142,527 B -|+1,294,892 B, gzip +1,143,152 B -|+203,439 B, gzip +71,668 B +|+1,190,976 B, gzip +1,147,846 B +|+1,294,126 B, gzip +1,143,242 B +|+1,295,794 B, gzip +1,143,715 B +|+205,114 B, gzip +74,249 B |Ed25519 on libsodium: signature of a 32-byte message -|+87,000 B, gzip +64,926 B -|+74,905 B, gzip +44,662 B -|+75,395 B, gzip +44,949 B -|+72,635 B, gzip +45,896 B +|+86,968 B, gzip +65,120 B +|+74,928 B, gzip +44,689 B +|+75,418 B, gzip +44,971 B +|+75,137 B, gzip +46,911 B |X25519 on libsodium: agreement of a secret key and a public key -|+85,352 B, gzip +58,169 B -|+58,624 B, gzip +37,985 B -|+58,838 B, gzip +38,495 B -|+52,474 B, gzip +37,420 B +|+85,320 B, gzip +58,815 B +|+62,535 B, gzip +38,807 B +|+62,765 B, gzip +39,385 B +|+60,473 B, gzip +40,355 B |crypto_kx on libsodium: a client's session keys from a key pair and the server's public key |not measured yet @@ -80,34 +80,64 @@ The lane sizes measured on 2026-11-21, at variant=release: native, clang-21 on D |not measured yet |ChaCha20-Poly1305 on libsodium: seal of 16 KiB, 256-bit key -|+35,984 B, gzip +22,273 B -|+13,788 B, gzip +4,863 B -|+13,997 B, gzip +4,929 B -|+9,520 B, gzip +3,980 B +|+35,952 B, gzip +22,409 B +|+13,906 B, gzip +4,852 B +|+14,115 B, gzip +4,924 B +|+14,418 B, gzip +6,079 B |ChaCha20-Poly1305 on BearSSL: seal of 16 KiB, 256-bit key -|+1,264 B, gzip +6,057 B -|+10,279 B, gzip +3,839 B -|+10,289 B, gzip +3,826 B -|+6,797 B, gzip +2,845 B +|+1,216 B, gzip +6,210 B +|+10,397 B, gzip +3,837 B +|+10,423 B, gzip +3,828 B +|+6,805 B, gzip +2,847 B |ChaCha20-Poly1305 on OpenSSL: seal of 16 KiB, 256-bit key -|+3,244,944 B, gzip +1,744,580 B -|+2,261,304 B, gzip +754,005 B -|+2,266,179 B, gzip +755,104 B +|+3,244,896 B, gzip +1,744,605 B +|+2,261,380 B, gzip +753,986 B +|+2,266,255 B, gzip +755,103 B |not on this target |original ChaCha20-Poly1305 on libsodium: seal of 16 KiB, 256-bit key -|+35,976 B, gzip +22,168 B -|+13,711 B, gzip +4,818 B -|+13,920 B, gzip +4,897 B -|+9,446 B, gzip +3,925 B +|+35,944 B, gzip +22,307 B +|+13,829 B, gzip +4,814 B +|+14,038 B, gzip +4,885 B +|+14,341 B, gzip +6,038 B |XChaCha20-Poly1305 on libsodium: seal of 16 KiB, 256-bit key -|+36,016 B, gzip +22,562 B -|+14,529 B, gzip +5,198 B -|+14,739 B, gzip +5,259 B -|+10,148 B, gzip +4,311 B +|+35,968 B, gzip +22,698 B +|+14,647 B, gzip +5,195 B +|+14,857 B, gzip +5,247 B +|+15,046 B, gzip +6,416 B + +|ChaCha20 on libsodium: keystream of 16 KiB +|+35,768 B, gzip +20,958 B +|+9,964 B, gzip +3,344 B +|+10,176 B, gzip +3,393 B +|+12,231 B, gzip +4,988 B + +|ChaCha20 on BearSSL: keystream of 16 KiB +|+1,032 B, gzip +3,520 B +|+5,383 B, gzip +1,736 B +|+5,383 B, gzip +1,749 B +|+3,893 B, gzip +1,436 B + +|ChaCha20 on OpenSSL: keystream of 16 KiB +|+3,244,888 B, gzip +1,744,535 B +|+2,260,776 B, gzip +753,679 B +|+2,265,627 B, gzip +754,834 B +|not on this target + +|Poly1305 on libsodium: tag of 16 KiB +|+36,344 B, gzip +19,907 B +|+7,194 B, gzip +2,775 B +|+7,400 B, gzip +2,829 B +|+10,072 B, gzip +4,343 B + +|Poly1305 on OpenSSL: tag of 16 KiB +|+3,245,480 B, gzip +1,743,664 B +|+2,257,805 B, gzip +752,215 B +|+2,262,655 B, gzip +753,825 B +|not on this target |XSalsa20-Poly1305 secret box on libsodium: seal of 16 KiB, 256-bit key |not measured yet @@ -140,40 +170,40 @@ The lane sizes measured on 2026-11-21, at variant=release: native, clang-21 on D |not measured yet |ElligatorSwift on libsecp256k1: BIP 324 shared secret of two ElligatorSwift encodings -|+134,104 B, gzip +98,710 B -|+272,419 B, gzip +103,703 B -|+274,172 B, gzip +104,395 B -|+229,445 B, gzip +82,050 B +|+134,056 B, gzip +98,929 B +|+272,040 B, gzip +103,698 B +|+273,716 B, gzip +104,368 B +|+230,221 B, gzip +82,152 B |MuSig2 on libsecp256k1: two-signer MuSig2 signature of a 32-byte message -|+1,207,568 B, gzip +1,168,024 B -|+1,353,199 B, gzip +1,161,626 B -|+1,354,601 B, gzip +1,162,560 B -|+250,718 B, gzip +90,694 B +|+1,190,992 B, gzip +1,155,001 B +|+1,295,157 B, gzip +1,146,970 B +|+1,296,487 B, gzip +1,147,392 B +|+202,608 B, gzip +76,303 B |BIP 352 silent payments on libsecp256k1: a silent payment output for one recipient -|+1,191,000 B, gzip +1,154,698 B -|+1,318,313 B, gzip +1,147,745 B -|+1,320,113 B, gzip +1,148,250 B -|+215,607 B, gzip +77,908 B +|+1,174,408 B, gzip +1,141,196 B +|+1,260,543 B, gzip +1,131,395 B +|+1,262,242 B, gzip +1,131,892 B +|+167,680 B, gzip +63,005 B |P-256 on BearSSL: ECDSA signature of a 32-byte SHA-256 digest -|+51,768 B, gzip +28,902 B -|+39,115 B, gzip +14,758 B -|+39,127 B, gzip +14,842 B -|+26,585 B, gzip +11,798 B +|+51,736 B, gzip +29,541 B +|+41,147 B, gzip +15,412 B +|+41,160 B, gzip +15,494 B +|+28,254 B, gzip +12,391 B |P-256 on BearSSL: ECDSA verification of a 32-byte SHA-256 digest -|+51,792 B, gzip +29,685 B -|+41,341 B, gzip +15,540 B -|+41,360 B, gzip +15,627 B -|+34,990 B, gzip +14,601 B +|+51,760 B, gzip +30,493 B +|+44,190 B, gzip +16,291 B +|+44,202 B, gzip +16,378 B +|+37,227 B, gzip +15,248 B |P-256 on BearSSL: x coordinate of the ECDH shared point with a peer's public key -|+34,312 B, gzip +22,638 B -|+31,377 B, gzip +10,278 B -|+31,391 B, gzip +10,398 B -|+26,580 B, gzip +9,646 B +|+34,312 B, gzip +22,719 B +|+31,399 B, gzip +10,282 B +|+31,413 B, gzip +10,397 B +|+26,584 B, gzip +9,652 B |=== OpenSSL: its cells differ by a few bytes whatever the operation: each fetches its algorithm by name from OpenSSL's default provider (link:https://docs.openssl.org/3.5/man7/crypto/[OpenSSL 3.5's crypto(7), algorithm fetching]), and a static link brings the provider's algorithms with it, not the operation's alone. diff --git a/doc/generated/use-cases.adoc b/doc/generated/use-cases.adoc index 80e1bd3..9c54689 100644 --- a/doc/generated/use-cases.adoc +++ b/doc/generated/use-cases.adoc @@ -236,6 +236,20 @@ `+/webcpp/crypto//xchacha20_poly1305-default+` |<> +|Apply ChaCha20's keystream for a protocol that fixes its own construction (NIP-44) +|In `+ciphers+`: `+chacha20<>+`: `+from_key+`, `+apply_keystream(nonce, data, initial_counter)+`; `+unauthenticated_encryption::apply_keystream+` in code written once for every stream cipher +|libsodium +|`+/webcpp/crypto//crypto+` + +`+/webcpp/crypto//chacha20-default+` +|<> + +|Authenticate one message under a one-time key +|In `+authenticators+`: `+poly1305<>+`: static `+authenticate(key, message)+`, `+verify(key, message, tag)+`; `+single_use_key_authentication::authenticate+` and `+verify+` in code written once for every single-use key authenticator +|libsodium +|`+/webcpp/crypto//crypto+` + +`+/webcpp/crypto//poly1305-default+` +|<> + |Encrypt a record or a file under one secret key, each with a random nonce, in libsodium's secret-box format |In `+secret_key_encryption+`: `+secretbox<>+`, `+secretbox_xchacha20poly1305<>+`: `+from_key+`, `+seal(nonce, data)+`, `+open(nonce, data, tag)+`; the box forms `+seal(box, nonce, data)+`, `+open(box, nonce, data, tag)+` |libsodium diff --git a/doc/llms.txt b/doc/llms.txt index 957700a..c84a9c7 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -13,7 +13,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - max: The largest value `operator()` gives. - entropy: The entropy of a value, in bits: every bit is the system's. - [async_from_key, secret_key_encryption::aead::async_seal, secret_key_encryption::aead::async_open](https://webcpporg.github.io/libs/crypto/#crypto-async): The asynchronous from_key, seal and open of AES-GCM on every backend, and on a native backend of every other AEAD and secret box, with the box forms `secret_key_encryption::async_seal` and `async_open` of a secret box or a crypto_box, each completing through a post to the executor the call gives, with any Asio completion token. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten; OpenSSL (/webcpp/crypto//openssl) on native, wasip2, wasip3; libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Use it to: seal or open a record inside an event loop without waiting. - - async_from_key: Makes an AEAD or a secret box from its key bytes, asynchronously: `Cipher::from_key(key_bytes)` run when the operation is initiated, its result posted to `completion_executor`. + - async_from_key: Makes an AEAD, a stream cipher or a secret box from its key bytes, asynchronously: `Cipher::from_key(key_bytes)` run when the operation is initiated, its result posted to `completion_executor`. - async_seal: Seals a message in place, asynchronously: `aead_cipher.seal` run when the operation is initiated, its result posted to `completion_executor`. - async_open: Opens a message in place, asynchronously: `aead_cipher.open` run when the operation is initiated, its result posted to `completion_executor`. - [async_from_secret, async_generate, async_sign, async_verify](https://webcpporg.github.io/libs/crypto/#crypto-async): Ed25519's asynchronous from_secret, generate, sign and verify with `crypto::signing_schemes::eddsa`, and on a native backend with `crypto::signing_schemes::eddsa_prehashed` (Ed25519ph, which WebCrypto lacks), each completing through a post to the executor the call gives, with any Asio completion token. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Use it to: sign and verify with Ed25519 in a coroutine. @@ -81,6 +81,11 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - async_seal: Seals a message in place, asynchronously: `seal` run when the operation is initiated, its result posted to `completion_executor`; the member form of `secret_key_encryption::aead::async_seal(executor, cipher, nonce_bytes, associated_data_bytes, data_bytes, token)`, which calls it. - open: Opens a message in place: `data_bytes` holds the ciphertext before and the plaintext after. - async_open: Opens a message in place, asynchronously: `open` run when the operation is initiated, its result posted to `completion_executor`; the member form of `secret_key_encryption::aead::async_open`, which calls it with the executor and the object before this function's arguments. +- [ciphers::chacha20](https://webcpporg.github.io/libs/crypto/#crypto-chacha20): RFC 8439's ChaCha20, the raw stream cipher: the keystream XORed into the data in place from a 32-bit block counter the caller names, with a 12-byte nonce and no authentication, for a protocol that brings its own (NIP-44). Header , . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten; OpenSSL (/webcpp/crypto//openssl) on native, wasip2, wasip3; libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. Use it to: apply ChaCha20's keystream for a protocol that fixes its own construction (NIP-44). + - from_key: Makes an object under a key. + - async_from_key: Makes an object under a key, asynchronously: `from_key` run when the operation is initiated, its result posted to `completion_executor`; the member form of `crypto::async_from_key(executor, key_bytes, token)`, which calls it. + - apply_keystream: XORs RFC 8439 section 2.4's keystream into `data_bytes`, in place, its first block the block of counter `initial_counter`: encryption and decryption are this one call. + - async_apply_keystream: XORs the keystream into `data_bytes`, in place, asynchronously: `apply_keystream` run when the operation is initiated, its result posted to `completion_executor`; the member form of `unauthenticated_encryption::async_apply_keystream(executor, cipher, nonce_bytes, data_bytes, initial_counter, token)`, which calls it. ## webcpp::crypto::secret_key_encryption @@ -293,6 +298,27 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - async_open: Opens one message, asynchronously: the single-shot `open` run with the arguments between the executor and the token when the operation is initiated, its result posted to `completion_executor`; the member form of `hpke::async_open`. - async_derive_from_seed: Derives a key pair from a seed, asynchronously: `derive_from_seed` run when the operation is initiated, its result posted to `completion_executor`; the member form of `hpke::async_derive_from_seed(completion_executor, seed, completion_token)`. +## webcpp::crypto::unauthenticated_encryption + +- [async_from_key, unauthenticated_encryption::async_apply_keystream](https://webcpporg.github.io/libs/crypto/#crypto-async): The asynchronous from_key and keystream of ChaCha20, RFC 8439's raw stream cipher, on a native backend, member and free, each completing through a post to the executor the call gives, with any Asio completion token; the free form names no backend, so that a stream cipher of another shape runs through it. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten; OpenSSL (/webcpp/crypto//openssl) on native, wasip2, wasip3; libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. + - async_apply_keystream: XORs a stream cipher's keystream into `data_bytes`, in place, asynchronously: `keyed_cipher.apply_keystream` run when the operation is initiated, its result posted to `completion_executor`. +- [unauthenticated_encryption::stream_cipher, unauthenticated_encryption::apply_keystream](https://webcpporg.github.io/libs/crypto/#crypto-unauthenticated-encryption): The raw stream cipher's contract: the concept `stream_cipher`, which reads the algorithm's own key, nonce and block sizes and counter type, and the free form `apply_keystream(cipher, nonce, data, initial_counter)`, which calls the cipher's member; encryption that authenticates nothing, for a protocol that authenticates the nonce and the ciphertext itself. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten; OpenSSL (/webcpp/crypto//openssl) on native, wasip2, wasip3; libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. + - apply_keystream: XORs the keystream into `data_bytes`, in place, `keyed_cipher.apply_keystream(nonce_bytes, data_bytes, initial_counter)`: the free form of the stream cipher's own `apply_keystream`, which it calls, with its results and its errors. + +## webcpp::crypto::single_use_key_authentication + +- [authenticators::poly1305](https://webcpporg.github.io/libs/crypto/#crypto-poly1305): RFC 8439's Poly1305, the one-time authenticator: a 16-byte tag of a message under a 32-byte key used for one message alone, as a protocol derives it per message; the key enters every call, and no object keeps it. Header . Backends: OpenSSL (/webcpp/crypto//openssl) on native, wasip2, wasip3; libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. Use it to: authenticate one message under a one-time key. + - authenticate: RFC 8439 section 2.5's tag of `message_bytes` under the one-time key `key_bytes`, r and s, r clamped by the algorithm, not by the caller. + - verify: Verifies that `tag_bytes` is RFC 8439 section 2.5's tag of `message_bytes` under the one-time key `key_bytes`. + - async_authenticate: The tag of a message, asynchronously: `authenticate` run when the operation is initiated, its result posted to `completion_executor`; the member form of `single_use_key_authentication::async_authenticate(executor, key_bytes, message_bytes, token)`, which calls it. + - async_verify: Verifies a message's tag, asynchronously: `verify` run when the operation is initiated, its result posted to `completion_executor`; the member form of `single_use_key_authentication::async_verify(executor, key_bytes, message_bytes, tag_bytes, token)`, which calls it. +- [single_use_key_authentication::single_use_key_authenticator, single_use_key_authentication::authenticate, single_use_key_authentication::verify](https://webcpporg.github.io/libs/crypto/#crypto-single-use-key-authentication): The single-use key authenticator's contract: the concept `single_use_key_authenticator`, which reads the algorithm's key and tag sizes, its tag type and its static `authenticate` and `verify`, and their free forms `authenticate(key, message)` and `verify(key, message, tag)`, which call them; a key that authenticates one message and never a second. Header . Backends: OpenSSL (/webcpp/crypto//openssl) on native, wasip2, wasip3; libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. + - authenticate: Authenticates a message under a key used for it alone, `Authenticator::authenticate(key_bytes, message_bytes)`: the free form of the authenticator's static `authenticate`, which it calls, with its results and its errors. + - verify: Verifies a message's tag under a key used for it alone, `Authenticator::verify(key_bytes, message_bytes, tag_bytes)`: the free form of the authenticator's static `verify`, which it calls, with its results and its errors. +- [single_use_key_authentication::async_authenticate, single_use_key_authentication::async_verify](https://webcpporg.github.io/libs/crypto/#crypto-async): The asynchronous tag and verification of a single-use key authenticator, Poly1305, on a native backend, the free forms of the static `async_authenticate` and `async_verify`, which they call, each completing through a post to the executor the call gives, with any Asio completion token; WebCrypto has no Poly1305, and no form runs on the browser's backend. Header . Backends: OpenSSL (/webcpp/crypto//openssl) on native, wasip2, wasip3; libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. + - async_authenticate: Authenticates a message under a key used for it alone, asynchronously: `Authenticator::authenticate(key_bytes, message_bytes)` run when the operation is initiated, its result posted to `completion_executor`. + - async_verify: Verifies a message's tag under a key used for it alone, asynchronously: `Authenticator::verify(key_bytes, message_bytes, tag_bytes)` run when the operation is initiated, its result posted to `completion_executor`. + ## webcpp::crypto::key_exchange - [key_exchange::kx_keypair](https://webcpporg.github.io/libs/crypto/#crypto-kx): libsodium's `crypto_kx` on X25519's typed keys: a key pair that holds an X25519 key pair, taken as is, derived from a 32-byte seed as libsodium does (BLAKE2b-256 of the seed) or drawn from `random_device`, and the two session keys of a client or a server, each a `secure::secret<32>`, from the peer's X25519 public key; a peer key of low order is refused with `weak_public_key`. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. Use it to: give a client and a server a key for each direction from each other's public key, as libsodium's `crypto_kx` does. @@ -320,6 +346,8 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - ChaCha20-Poly1305, native, wasip2, wasip3, emscripten: libsodium; one library for the three ChaCha20-Poly1305 AEADs on every target, where BearSSL and OpenSSL have RFC 8439's alone ([libsodium's ChaCha20-Poly1305 constructions](https://doc.libsodium.org/secret-key_cryptography/aead/chacha20-poly1305)); a program that links BearSSL or OpenSSL alone names it in the type, as in `chacha20_poly1305`. - original ChaCha20-Poly1305, native, wasip2, wasip3, emscripten: libsodium; the only backend that has it: libsodium's own C code, the same on every target ([libsodium's ChaCha20-Poly1305 constructions](https://doc.libsodium.org/secret-key_cryptography/aead/chacha20-poly1305)). - XChaCha20-Poly1305, native, wasip2, wasip3, emscripten: libsodium; the only backend that has it: libsodium's own C code, the same on every target ([libsodium's ChaCha20-Poly1305 constructions](https://doc.libsodium.org/secret-key_cryptography/aead/chacha20-poly1305)). +- ChaCha20, native, wasip2, wasip3, emscripten: libsodium; ChaCha20-Poly1305's default, so that a program that uses both links one library; libsodium's own C code, constant time, the same on every target ([libsodium's ChaCha20 stream cipher, crypto_stream_chacha20_ietf_xor_ic](https://doc.libsodium.org/advanced/stream_ciphers/chacha20)). +- Poly1305, native, wasip2, wasip3, emscripten: libsodium; ChaCha20's and ChaCha20-Poly1305's default, so that a program composing them links one library ([libsodium's one-time authentication, crypto_onetimeauth_poly1305](https://doc.libsodium.org/advanced/poly1305)). - XSalsa20-Poly1305 secret box, native, wasip2, wasip3, emscripten: libsodium; the only backend that has it: libsodium's own C code, NaCl's `crypto_secretbox`, the same on every target ([libsodium's documentation, secret-key authenticated encryption](https://doc.libsodium.org/secret-key_cryptography/secretbox)). - XChaCha20-Poly1305 secret box, native, wasip2, wasip3, emscripten: libsodium; the only backend that has it: libsodium's own C code, the same on every target ([libsodium's documentation, secret-key authenticated encryption](https://doc.libsodium.org/secret-key_cryptography/secretbox)). - X25519-XSalsa20-Poly1305 box, native, wasip2, wasip3, emscripten: libsodium; the only backend that has it: libsodium's own C code, NaCl's `crypto_box`, the same on every target ([libsodium's documentation, public-key authenticated encryption](https://doc.libsodium.org/public-key_cryptography/authenticated_encryption)). @@ -341,6 +369,8 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - ChaCha20-Poly1305: libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found; not measured yet on wasip2, wasip3, emscripten. BearSSL: native, Valgrind's memcheck (Linux), MemorySanitizer (Linux, clang) and dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; wasip2, dudect (printed, not judged: under wasmtime its timing follows the runner's processor); not measured yet on wasip3, emscripten. OpenSSL (seal alone: its open branches on the verdict inside OpenSSL): native, Valgrind's memcheck (Linux), nothing found; not measured yet on wasip2, wasip3. - original ChaCha20-Poly1305: libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found; not measured yet on wasip2, wasip3, emscripten. - XChaCha20-Poly1305: libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found; not measured yet on wasip2, wasip3, emscripten. +- ChaCha20: libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found; not measured yet on wasip2, wasip3, emscripten. BearSSL: native, Valgrind's memcheck (Linux), MemorySanitizer (Linux, clang) and dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; wasip2, dudect (printed, not judged: under wasmtime its timing follows the runner's processor); not measured yet on wasip3, emscripten. OpenSSL: native, Valgrind's memcheck (Linux), nothing found; not measured yet on wasip2, wasip3. +- Poly1305: libsodium: native, Valgrind's memcheck (Linux; `authenticate`, then `verify` with the right tag and with a wrong one, the key, the message and the tags secret; the verdict of `verify` declassified by crypto where it first branches on it), MemorySanitizer (Linux, clang; the same paths as memcheck's) and dudect (judged; on a runner GitHub hosts, by two of three runs; `authenticate` against its key, the all-zero key against random ones; `verify` against its tag, the right tag with its last byte flipped against it with its first byte flipped, both classes failing: a success and a failure return by different paths, about 0.4 ns apart, which dudect finds and which is public, the verdict being reported), nothing found; wasip2, dudect (judged; on a runner GitHub hosts, by two of three runs; `authenticate` against its key, the all-zero key against random ones; `verify` against its tag, the right tag with its last byte flipped against it with its first byte flipped, both classes failing: a success and a failure return by different paths, about 0.4 ns apart, which dudect finds and which is public, the verdict being reported), nothing found; not measured yet on wasip3, emscripten. OpenSSL (`authenticate` and `verify`, as on libsodium): native, Valgrind's memcheck (Linux), nothing found; not measured yet on wasip2, wasip3. - XSalsa20-Poly1305 secret box: libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found; not measured yet on wasip2, wasip3, emscripten. - XChaCha20-Poly1305 secret box: libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found; not measured yet on wasip2, wasip3, emscripten. - X25519-XSalsa20-Poly1305 box: libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found; not measured yet on wasip2, wasip3, emscripten. @@ -363,6 +393,8 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [Compare secrets in constant time](https://webcpporg.github.io/libs/crypto/#crypto-constant-time-equal): compare a tag, a MAC or a token with `secure::constant_time_equal`, never `==` or `memcmp` ([CWE-208, observable timing discrepancy](https://cwe.mitre.org/data/definitions/208.html)). - [Secrets come from random_device](https://webcpporg.github.io/libs/crypto/#crypto-entropy): keys, nonces and tokens are drawn from `random_device`, never `std::mt19937` or `rand` ([CWE-338, a weak generator used for security](https://cwe.mitre.org/data/definitions/338.html)). - [Never reuse a nonce under one ChaCha20-Poly1305 key](https://webcpporg.github.io/libs/crypto/#crypto-chacha): two messages under one key and one nonce reveal the XOR of their plaintexts and let an attacker forge tags ([RFC 8439, section 4: a nonce is never repeated under one key](https://www.rfc-editor.org/rfc/rfc8439#section-4)). `xchacha20_poly1305` and the secret boxes: draw 24 bytes at random per message. `chacha20_poly1305`: number the 12-byte nonces with a counter that never repeats, a restart included, or draw them at random for at most 2^32 messages per key, AES-GCM's bound for random 12-byte nonces ([NIST SP 800-38D, GCM and GMAC](https://csrc.nist.gov/pubs/sp/800/38/d/final)). `chacha20_poly1305_original`: a counter only, its 8 bytes are too short to draw. +- [ChaCha20 authenticates nothing](https://webcpporg.github.io/libs/crypto/#crypto-chacha20): `ciphers::chacha20` and the namespace `unauthenticated_encryption` encrypt without a tag: a bit flipped in the ciphertext flips the same bit of the plaintext, and a nonce repeated under one key reveals the XOR of two plaintexts ([RFC 8439, section 4: a nonce is never repeated under one key](https://www.rfc-editor.org/rfc/rfc8439#section-4)). Use them only where a protocol fixes its own construction and authenticates the nonce and the ciphertext itself, as NIP-44 does with HMAC-SHA256 ([Nostr NIP-44, encrypted payloads](https://github.com/nostr-protocol/nips/blob/master/44.md)); a program's own messages take `chacha20_poly1305` or `xchacha20_poly1305`. +- [A Poly1305 key authenticates one message](https://webcpporg.github.io/libs/crypto/#crypto-single-use-key-authentication): the 32-byte key of `authenticators::poly1305` is used for one message alone: tags of two messages under one key let an attacker forge others ([RFC 8439, section 2.5: the one-time key is used for one message alone; an attacker who sees two tags under it can forge](https://www.rfc-editor.org/rfc/rfc8439#section-2.5)). A protocol derives the key for each message, as RFC 8439's AEAD takes it from ChaCha20's keystream; a key used for many messages takes the HMAC of `webcpp::hash`, and a program's own messages an AEAD. - [A shared secret is not a key](https://webcpporg.github.io/libs/crypto/#crypto-x25519): derive keys from X25519's shared secret and both public keys with a KDF such as webcpp::hash's HKDF, never use its bytes as a cipher's key ([RFC 7748, section 6.1: a KDF over the shared secret and both public keys](https://www.rfc-editor.org/rfc/rfc7748#section-6.1)); `kx_keypair` and the boxes do this themselves. - [The default on MSVC is not constant time](https://webcpporg.github.io/libs/crypto/#crypto-backends-defaults): natively the default is OpenSSL, which MSVC builds no-asm, table-based ([OpenSSL's INSTALL.md, no-asm](https://github.com/openssl/openssl/blob/master/INSTALL.md)); where timing attacks matter, link BearSSL and name `gcm>`, and for the block cipher link ctaes and name `aes256`. @@ -400,6 +432,8 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [Give a client and a server a key for each direction from each other's public key, as libsodium's `crypto_kx` does](https://webcpporg.github.io/libs/crypto/#crypto-kx): `kx_keypair::from_keypair`, `kx_keypair::derive_from_seed`, `kx_keypair::generate`, `client_session_keys`, `server_session_keys` (webcpp::crypto::key_exchange); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//kx-default. Example: example/kx_session.cpp. - [Export or import an Ed25519 or X25519 key in the standard forms OpenSSL and WebCrypto use: SPKI and PKCS#8 (RFC 8410), as DER or PEM text](https://webcpporg.github.io/libs/crypto/#crypto-key-formats): `codecs::encode` and `codecs::decode` with `crypto::formats::raw`, `spki`, `pkcs8` and `pem`, on Ed25519's and X25519's keys (webcpp::crypto::curves); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//ed25519-default /webcpp/crypto//x25519-default. Example: example/key_formats.cpp. - [Encrypt messages in a chat app, on the web and natively, each with a random nonce](https://webcpporg.github.io/libs/crypto/#crypto-chacha): `xchacha20_poly1305<>`: `from_key`, `seal`, `open` (webcpp::crypto::ciphers); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//xchacha20_poly1305-default. Example: example/xchacha_seal.cpp. +- [Apply ChaCha20's keystream for a protocol that fixes its own construction (NIP-44)](https://webcpporg.github.io/libs/crypto/#crypto-chacha20): `chacha20<>`: `from_key`, `apply_keystream(nonce, data, initial_counter)`; `unauthenticated_encryption::apply_keystream` in code written once for every stream cipher (webcpp::crypto::ciphers); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//chacha20-default. Example: example/chacha20_keystream.cpp. +- [Authenticate one message under a one-time key](https://webcpporg.github.io/libs/crypto/#crypto-poly1305): `poly1305<>`: static `authenticate(key, message)`, `verify(key, message, tag)`; `single_use_key_authentication::authenticate` and `verify` in code written once for every single-use key authenticator (webcpp::crypto::authenticators); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//poly1305-default. Example: example/poly1305_one_time_tag.cpp. - [Encrypt a record or a file under one secret key, each with a random nonce, in libsodium's secret-box format](https://webcpporg.github.io/libs/crypto/#crypto-secretbox): `secretbox<>`, `secretbox_xchacha20poly1305<>`: `from_key`, `seal(nonce, data)`, `open(nonce, data, tag)`; the box forms `seal(box, nonce, data)`, `open(box, nonce, data, tag)` (webcpp::crypto::secret_key_encryption); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//secretbox_xsalsa20poly1305-default. Example: example/file_share.cpp. - [Send messages between two people who know each other's public keys, as NaCl's and libsodium's crypto_box](https://webcpporg.github.io/libs/crypto/#crypto-box): `box::from_keys`, `box::seal`, `box::open` (webcpp::crypto::public_key_encryption); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//box_xsalsa20poly1305-default. Example: example/box_messages.cpp. - [Let anyone send a message that only the recipient can read, without saying who sent it (anonymous feedback, a drop box)](https://webcpporg.github.io/libs/crypto/#crypto-sealed-box): `sealed_box::seal`, `sealed_box::open` (webcpp::crypto::public_key_encryption); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//sealed_box-default. Example: example/file_share.cpp. @@ -421,6 +455,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - example/bearssl_prng.cpp: Seeds BearSSL's own HMAC-DRBG from webcpp::crypto::random_device and draws bytes from it. A generator is only as good as its seed: the seed must come from the system's entropy, never from the clock or a counter. - example/bitcoin_sighash.cpp: Signs a Bitcoin legacy or segwit v0 input's sighash: SHA-256d of the transaction's serialization, computed by the program with webcpp::hash, signed as a digest with ECDSA over SHA-256, verified, and written as strict DER for the witness. Crypto computes no sighash: the serialization and its hash are the protocol's, a domain library's work; the sighash is the SHA-256 of a SHA-256, so the second hash is the scheme's own and the digest is honest under crypto::signing_schemes::ecdsa_sha256. A taproot sighash, BIP341's tagged hash, is the message of crypto::signing_schemes::schnorr instead (musig_taproot.cpp, taproot_tweak.cpp). - example/box_messages.cpp: Two people who know each other's X25519 public keys exchange messages in libsodium's box: each makes a box from the own key pair and the other's public key, agreeing one key for the pair, then seals each message with a nonce drawn at random. What one seals the other opens; a stranger's box, from another key pair, does not. Prints what each reads. +- example/chacha20_keystream.cpp: ChaCha20 alone, the raw stream cipher, which authenticates nothing: RFC 8439 section 2.4.2's key, nonce and initial counter 1 encrypt the section's 114-byte plaintext in place, the ciphertext printed in hex and compared with the RFC's; the same call at the same counter gives the plaintext back. Data that needs more blocks than the 32-bit counter has left is refused with counter_overflow and left untouched. A program's own messages take chacha20_poly1305: the raw cipher is for a protocol that fixes its own construction and authentication, as NIP-44 does. - example/constant_time_equal_hmac.cpp: Checks an HMAC-SHA-256 tag from Boost.Hash2 with webcpp::secure::constant_time_equal, the constant-time comparison. Comparing tags with == or memcmp stops at the first difference, and that timing lets an attacker guess a valid tag one byte at a time. - example/ecdh_session.cpp: Two peers agree on a shared secret with ECDH, derive a session key from it with HKDF-SHA-256 and talk over AES-256-GCM. The raw ECDH output is not a key: HKDF turns it into one and ties it to this application with a context string. - example/ecdh_x_coordinate.cpp: Two key pairs agree on the shared point's raw x coordinate with agree, the form Nostr's encrypted messages (NIP-44) take, then derive from it what a NIP-44 library would: the conversation key, HKDF-extract with the salt "nip44-v2". The x coordinate is not a key; the derivation that makes one is the protocol's, and belongs to a domain library. @@ -446,6 +481,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - example/p256_key_formats.cpp: RFC 6979's P-256 key in the files other programs read: its public key written as PEM SPKI with codecs::encode, the text OpenSSL reads and whose DER a WebCrypto peer's importKey("spki") reads, printed and read back with codecs::decode; its compressed point, 33 bytes, printed and read back with formats::raw, which takes either point; its key pair written as PEM PKCS#8 for the program's own key file, a secret result never printed, and read back. The key is RFC 6979's published one, so that the output is fixed: a real program draws its own. - example/p256_keys.cpp: Makes a P-256 key pair from RFC 6979's key, prints its public key as the 65 bytes WebCrypto's exportKey("raw") gives, keeps its scalar and makes the same key pair from it again, then imports that public key as a peer's and refuses the same bytes with one bit changed. Draws a fresh key pair too, whose bytes differ on every run and are not printed. - example/p256_sign.cpp: Signs "sample" with RFC 6979's P-256 key and prints the signature in the raw form WebCrypto uses, low S (the RFC's r, and n minus the RFC's high s); then its DER encoding, which X.509 carries; and verifies the signature read back from DER with the public key alone, given the message and given its SHA-256 digest, and refuses another message. +- example/poly1305_one_time_tag.cpp: Poly1305 alone, the one-time authenticator: RFC 8439 section 2.5.2's key and message give the section's 16-byte tag, printed in hex and compared with the RFC's; verify accepts the tag received and refuses it with one bit flipped. Its key authenticates this one message and never a second: a protocol derives a fresh key per message (RFC 8439's AEAD takes it from ChaCha20's keystream), and a key used for many messages takes webcpp::hash's HMAC. - example/recover_signer.cpp: Finds who signed a message without being sent their key, as Ethereum finds a transaction's signer: a wallet signs a message with a recoverable signature, and a reader that holds no key recovers the signer's public key from the signature and the message, then compares it with the key the wallet published. Recovery always finds some key, so the comparison is the check: a changed message recovers another key. - example/reset_token.cpp: Draws a 32-byte password-reset token and a six-digit one-time code from the system's random generator. Tokens that can be guessed or repeated let an attacker take over accounts, so both come from random_device, never from rand() or the clock. - example/schnorr_sign.cpp: Signs BIP340's first test vector with secp256k1 and verifies it, then tweaks the key pair by a 32-byte tweak, as a domain library derives one, and signs and verifies under the tweaked key. Prints each key and signature in hex. diff --git a/doc/p2p.adoc b/doc/p2p.adoc index 6dfc580..73ce3cd 100644 --- a/doc/p2p.adoc +++ b/doc/p2p.adoc @@ -205,6 +205,43 @@ every message between the two users, in both directions; NIP-44 derives each message's keys from it and a fresh 32-byte nonce, and a program that encrypts with the conversation key itself repeats its keys across messages. +[#crypto-p2p-nip44] +=== NIP-44's payloads, composed from webcpp's pieces + +*The problem.* The conversation key of the section above is where NIP-44 +starts: each direct message is then encrypted and authenticated under keys +derived from it, in a payload every Nostr client must read byte for byte +(link:https://github.com/nostr-protocol/nips/blob/master/44.md[NIP-44]). + +*The idea.* NIP-44 fixes its own construction over the raw pieces rather than +an AEAD: HKDF-Expand with HMAC-SHA256 turns the conversation key and a random +32-byte nonce into a ChaCha20 key, a ChaCha20 nonce and an HMAC key; the +message, its length in two bytes before it, is padded and encrypted with raw +ChaCha20 from counter 0; and HMAC-SHA256 covers the nonce and the ciphertext, +which the reader checks in constant time before it decrypts. Every piece is +webcpp's: `agree` and its x coordinate (<>), webcpp::hash's +HKDF and HMAC, `ciphers::chacha20` (<>) and codecs' base64. +NIP-44 itself is not in crypto: a domain library built on crypto and hash, +such as a future webcpp::nostr, composes it. crypto's tests compose it as the +NIP writes it, and run NIP-44's own vectors on each of ChaCha20's backends +(`chacha20_nip44_sodium`, `chacha20_nip44_bearssl`, `chacha20_nip44_openssl`): +the conversation keys, the message keys, the padding, every message both ways +and the long messages. Their encryption is the worked example: + +[source,cpp] +---- +include::{library-root}/test/support/nip44.hpp[tag=encrypt] +---- + +The test's helpers record a failure with Boost's test macros; a program returns +the error instead, and wipes the keys it derives, as `keys.wipe()` does here. + +*Mistakes to avoid.* Decrypting before the HMAC is checked, or checking it with +`==`: compare with `secure::constant_time_equal` and drop the message on a +mismatch, before ChaCha20 runs. Starting ChaCha20 at counter 1, as RFC 8439's +AEAD does: NIP-44 starts at 0, and every message then fails to read. Leaving the +nonce out of the HMAC: it covers the nonce and the ciphertext, both. + [#crypto-p2p-v2] === A handshake an observer cannot recognise diff --git a/doc/secret_key_encryption.adoc b/doc/secret_key_encryption.adoc index 685202e..af5409c 100644 --- a/doc/secret_key_encryption.adoc +++ b/doc/secret_key_encryption.adoc @@ -33,14 +33,28 @@ forms are the box forms. free factories (<>) | `crypto::ciphers` -| symmetric algorithms: AES, AES-GCM, ChaCha20-Poly1305 in three nonce sizes -(<>) +| symmetric algorithms: AES, AES-GCM, ChaCha20-Poly1305 in three nonce sizes, and +ChaCha20, the raw stream cipher (<>) | `crypto::secret_key_encryption` | constructions under one secret key: `secretbox` and `secretbox_xchacha20poly1305`, the concept `authenticated_box` and the box forms `seal` and `open`; `aead`, the AEAD contract over the AEADs of `ciphers` +| `crypto::unauthenticated_encryption` +| encryption that authenticates nothing, for a protocol that brings its own +authentication (NIP-44): the contract `stream_cipher` over the raw stream +ciphers of `ciphers` and its free forms (<>) + +| `crypto::authenticators` +| the authenticators whose key is used once: Poly1305 (<>) + +| `crypto::single_use_key_authentication` +| a tag of one message under a key used for it alone: the contract +`single_use_key_authenticator` over the authenticators and its free forms +(<>); a reusable key's MAC is +webcpp::hash's HMAC + | `crypto::public_key_encryption` | constructions between key pairs: `box`, `sealed_box`, HPKE's `hpke::suite` (<>) diff --git a/doc/single_use_key_authentication.adoc b/doc/single_use_key_authentication.adoc new file mode 100644 index 0000000..bf1319e --- /dev/null +++ b/doc/single_use_key_authentication.adoc @@ -0,0 +1,187 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +[#crypto-single-use-key-authentication] +== Single-use key authentication: `webcpp::crypto::single_use_key_authentication` + +*The rule: a key is used once, for one message.* A single-use key authenticator +computes a short tag of a message under a key that authenticates that message +alone. Its key is never used for a second message: an attacker who sees the +tags of two messages under one key can forge tags for messages of their own +(link:https://www.rfc-editor.org/rfc/rfc8439#section-2.5[RFC 8439, section +2.5]). A protocol derives a fresh key for each message, as RFC 8439's AEAD takes +it from ChaCha20's keystream and NaCl's secret box from XSalsa20's. A key that +authenticates many messages, a webhook's secret or an API's, is a MAC's key: +webcpp::hash's HMAC +(link:{webcpp-libs}/hash/{webcpp-page}#hash-hmac[webcpp::hash's HMAC]), never +this namespace. One-time passwords, HOTP and TOTP, are not what this namespace +does either: their "one-time" is the code's, which a person types, not the +key's; this page points to no library for them. + +The namespace `webcpp::crypto::single_use_key_authentication` holds the +contract, `single_use_key_authenticator`, and its free forms; the algorithm, +Poly1305, is in `authenticators` under its name (<>), as the +ciphers are in `ciphers`. A program's own messages take an AEAD, which derives +the one-time key, authenticates and checks in one call +(<>); the raw authenticator is for a protocol +that fixes its own construction, and for a construction a standard writes from +the raw pieces (<>). + +include::generated/namespace-single_use_key_authentication.adoc[] + +[#crypto-poly1305] +=== Poly1305, the one-time authenticator + +*Poly1305* is Daniel J. Bernstein's one-time authenticator: a 16-byte tag of a +message of any length under a 32-byte key, r then s, r clamped by the +algorithm, not by the caller +(link:https://www.rfc-editor.org/rfc/rfc8439#section-2.5[RFC 8439, section +2.5]). It is the tag of ChaCha20-Poly1305 and of NaCl's secret boxes, under a +key derived for each message. + +`authenticators::poly1305`, in +``, holds no key and makes no +object: its two functions are static, and the key enters every call. +`poly1305<>` names the family's default, libsodium on every target +(<>). `authenticate(key_bytes, message_bytes)` gives +the tag, a `result_type` of 16 bytes; every message length is accepted, the +empty message too, whose tag is s. `verify(key_bytes, message_bytes, +tag_bytes)` computes the tag again and compares it with the tag received in +constant time (`secure::constant_time_equal`, <>), +its own computed tag wiped before it returns: a mismatch is +`authentication_failed`, as an AEAD's `open` reports it. A program that has a +tag to check calls `verify`, never `==` on two tags. Nothing is written into +the caller's spans, and the caller's key is the caller's to wipe: a +`secure::secret<32>` does it, given by its `bytes()`. + +*Example.* RFC 8439 section 2.5.2's key and message give the section's tag; +`verify` accepts it and refuses it with one bit flipped: + +[source,cpp] +---- +include::{examples}/poly1305_one_time_tag.cpp[tag=program] +---- + +[listing] +---- +include::{examples}/poly1305_one_time_tag.expected[] +---- + +[#crypto-poly1305-guards] +==== The guards + +Each function checks its guards first, in the order of the table, and reads no +byte of the message before them: + +[cols="3,1"] +|=== +|Condition |Error + +|a key of another size than 32 bytes |`invalid_key_size` +|`verify`: a tag of another size than 16 bytes |`invalid_tag_size` +|`verify`: the tag does not match |`authentication_failed` +|the backend fails where it should not, the tag zeroed |`backend_failure` +|=== + +On OpenSSL, `authenticate` and `verify` also report `errc::not_enough_memory` +when OpenSSL cannot allocate the context of the call, and, with its memory +option, `memory_functions_not_installed` (<>). + +*The backends.* libsodium, on every target, and OpenSSL, natively and on WASI, +give the same tag byte for byte, which the agreement test checks on random keys +and lengths. BearSSL has no Poly1305 of its own to call: its Poly1305 lies inside +its ChaCha20-Poly1305, which derives the key itself, so naming +`poly1305` stops the build with a message that names +libsodium and OpenSSL (<>); ctaes has none either. On +libsodium nothing allocates; on OpenSSL each call makes and frees its MAC +context through OpenSSL's memory functions, never through `operator new` +(<>). + +include::generated/backends-poly1305.adoc[] + +*The four forms.* An authenticator has no object, so its "member" forms are the +type's static functions: `poly1305::authenticate(key, message)` and +`verify(key, message, tag)`; the free forms +`single_use_key_authentication::authenticate(key, message)` and +`verify(key, message, tag)`, the type given as the template argument; and, +in ``, `poly1305::async_authenticate(executor, key, +message, token)` and `async_verify(executor, key, message, tag, token)` and +their free forms `single_use_key_authentication::async_authenticate` and +`async_verify`, with the same arguments (<>). The four give the +same tag and the same errors. There is no `from_key`: `crypto::from_key` given +Poly1305 stops the build. + +*The browser.* WebCrypto has no Poly1305: on a backend that completes by itself, +as the browser's will (<>), no form runs, synchronous or +asynchronous, and the build stops with a message that names a native backend. +On Emscripten the default, libsodium compiled to WebAssembly, runs every form. + +[#crypto-single-use-key-authenticator-contract] +=== The contract: `single_use_key_authentication::single_use_key_authenticator` + +``, which +`authenticators/poly1305.hpp` includes and which needs no backend, declares, in +namespace `webcpp::crypto::single_use_key_authentication`: + +* `single_use_key_authenticator`, what every authenticator whose key is used +once is: `A::key_size`, `A::tag_size`, `typename A::result_type`, the tag; +the static `A::authenticate(key, message)` giving `result` and +`A::verify(key, message, tag)` giving `result`; +* `authenticate(key, message)` and `verify(key, message, tag)`, +constrained by the concept, which call the static functions and give their +results and their errors. + +No AEAD, stream cipher or webcpp::hash MAC is a `single_use_key_authenticator`: +a reusable key's MAC given to `authenticate` stops the build with a message +that names webcpp::hash's HMAC. A function written against the concept serves +every single-use key authenticator, as this check of the library's own tests +does: + +[source,cpp] +---- +include::{library-root}/test/authenticator_concepts_test.cpp[tag=generic,indent=0] +---- + +include::generated/backends-single_use_key_authenticator.adoc[] + +[#crypto-single-use-key-authentication-composition] +=== RFC 8439's AEAD from the two raw pieces + +RFC 8439 section 2.8 builds ChaCha20-Poly1305 from the two raw pieces: the +one-time Poly1305 key is the first 32 bytes of ChaCha20's keystream at counter +0, under the message's key and nonce (section 2.6); the plaintext is encrypted +from counter 1; and the tag is Poly1305's over the associated data and the +ciphertext, each padded to 16 bytes, then their lengths as 8-byte little-endian +numbers (link:https://www.rfc-editor.org/rfc/rfc8439#section-2.8[RFC 8439, +section 2.8]). The library's composition test builds it so, from +`ciphers::chacha20` and `authenticators::poly1305`, and checks that every +combination of their backends gives, byte for byte, what the `seal` of +`ciphers::chacha20_poly1305` gives on each of its own, section 2.8.2's vector +first: + +[source,cpp] +---- +include::{library-root}/test/support/composition_checks.hpp[tag=compose] +---- + +`chacha20_poly1305` is the call to use: it does all of this in one call, checks +the tag in constant time before it decrypts a byte, and leaves nothing to get +wrong. The composition shows how the pieces fit, and proves that they are the +same algorithms; a program that builds an AEAD of its own from them takes on +every pitfall below. + +[#crypto-single-use-key-authentication-pitfalls] +==== Pitfalls + +* A key used for two messages lets an attacker forge tags: derive the key for +each message, never store one and reuse it. +* A key that must serve many messages is a MAC's: webcpp::hash's HMAC, not +Poly1305. +* A tag compared with `==` or `memcmp` leaks, through the time the comparison +takes, how many bytes matched: call `verify`, which compares in constant time. +* What the tag does not cover, an attacker changes: a construction +authenticates the ciphertext, its associated data and their lengths, as +section 2.8 does, never the plaintext alone. diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 44aaed0..75d3411 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -104,6 +104,8 @@ "solana-accounts": ["Solana's documentation, accounts and their Ed25519 keys", "https://solana.com/docs/core/accounts"], "rfc8439": ["RFC 8439, ChaCha20 and Poly1305 for IETF Protocols", "https://www.rfc-editor.org/rfc/rfc8439"], "libsodium-aead": ["libsodium's ChaCha20-Poly1305 constructions", "https://doc.libsodium.org/secret-key_cryptography/aead/chacha20-poly1305"], + "libsodium-stream": ["libsodium's ChaCha20 stream cipher, crypto_stream_chacha20_ietf_xor_ic", "https://doc.libsodium.org/advanced/stream_ciphers/chacha20"], + "libsodium-onetimeauth": ["libsodium's one-time authentication, crypto_onetimeauth_poly1305", "https://doc.libsodium.org/advanced/poly1305"], "nacl-box": ["NaCl, public-key authenticated encryption (crypto_box)", "https://nacl.cr.yp.to/box.html"], "nacl-secretbox": ["NaCl, secret-key authenticated encryption (crypto_secretbox)", "https://nacl.cr.yp.to/secretbox.html"], "xsalsa20": ["D. J. Bernstein, Extending the Salsa20 nonce, 2008", "https://cr.yp.to/snuffle/xsalsa-20081128.pdf"], @@ -121,6 +123,7 @@ "ed25519-design": ["Ed25519's design: no secret branch conditions, no secret array indices", "https://ed25519.cr.yp.to/"], "rfc8439-chacha": ["RFC 8439, section 2.1: ChaCha's quarter round, additions, XORs and rotations of 32-bit words", "https://www.rfc-editor.org/rfc/rfc8439#section-2.1"], "rfc8439-nonce": ["RFC 8439, section 4: a nonce is never repeated under one key", "https://www.rfc-editor.org/rfc/rfc8439#section-4"], + "rfc8439-poly-key": ["RFC 8439, section 2.5: the one-time key is used for one message alone; an attacker who sees two tags under it can forge", "https://www.rfc-editor.org/rfc/rfc8439#section-2.5"], "xchacha-draft": ["draft-irtf-cfrg-xchacha, XChaCha20-Poly1305", "https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha"], "libsodium-secretstream": ["libsodium's documentation, encrypted streams (secretstream, on XChaCha20-Poly1305)", "https://doc.libsodium.org/secret-key_cryptography/secretstream"], "rfc7748-kdf": ["RFC 7748, section 6.1: a KDF over the shared secret and both public keys", "https://www.rfc-editor.org/rfc/rfc7748#section-6.1"], @@ -257,7 +260,7 @@ { "id": "async_gcm", "free": true, - "functions": ["async_from_key", "async_seal", "async_open"], + "functions": ["async_from_key", "secret_key_encryption::aead::async_seal", "secret_key_encryption::aead::async_open"], "namespace": "root", "api": "async_from_key, secret_key_encryption::aead::async_seal, secret_key_encryption::aead::async_open", "header": "", @@ -269,10 +272,25 @@ "sodium": {"tests": ["async_aead"]} } }, + { + "id": "async_stream_cipher", + "free": true, + "functions": ["async_apply_keystream"], + "namespace": "unauthenticated_encryption", + "api": "async_from_key, unauthenticated_encryption::async_apply_keystream", + "header": "", + "what": "The asynchronous from_key and keystream of ChaCha20, RFC 8439's raw stream cipher, on a native backend, member and free, each completing through a post to the executor the call gives, with any Asio completion token; the free form names no backend, so that a stream cipher of another shape runs through it.", + "section": "crypto-async", + "backends": { + "bearssl": {"tests": ["async_stream_cipher"]}, + "openssl": {"tests": ["async_stream_cipher_openssl"]}, + "sodium": {"tests": ["async_stream_cipher", "stream_cipher_shape"]} + } + }, { "id": "async_ed25519", "free": true, - "functions": ["async_from_secret", "async_generate", "async_sign", "async_verify"], + "functions": ["async_from_secret", "async_generate", "async_sign", "crypto::async_verify"], "namespace": "root", "api": "async_from_secret, async_generate, async_sign, async_verify", "header": "", @@ -589,6 +607,95 @@ "default": "`xchacha20_poly1305<>` names the default backend.", "backends": {"sodium": {"tests": ["xchacha_sodium", "chacha_wycheproof_sodium", "allocation_sodium"]}} }, + { + "id": "chacha20", + "family": "chacha20", + "functions": ["from_key", "basic_chacha20::async_from_key", "apply_keystream", + "basic_chacha20::async_apply_keystream"], + "namespace": "ciphers", + "api": "ciphers::chacha20", + "header": ", ", + "what": "RFC 8439's ChaCha20, the raw stream cipher: the keystream XORed into the data in place from a 32-bit block counter the caller names, with a 12-byte nonce and no authentication, for a protocol that brings its own (NIP-44).", + "section": "crypto-chacha20", + "default": "`chacha20<>` names the default backend.", + "backends": { + "sodium": {"tests": ["chacha20_sodium", "stream_cipher_concepts", "allocation_sodium", + "timing_coverage_sodium", "agreement_chacha20", + "agreement_chacha20_emscripten", "chacha20_nip44_sodium"]}, + "bearssl": {"tests": ["chacha20_bearssl", "chacha20_bearssl_portable", "allocation_bearssl", + "timing_coverage_bearssl", "agreement_chacha20", + "agreement_chacha20_emscripten", "agreement_chacha20_portable", + "agreement_chacha20_portable_emscripten", + "chacha20_nip44_bearssl"]}, + "openssl": {"tests": ["chacha20_openssl", "allocation_openssl", "timing_coverage_openssl", + "agreement_chacha20", "agreement_chacha20_portable", + "chacha20_nip44_openssl"]}, + "ctaes": {"refused": "chacha20_on_ctaes"} + } + }, + { + "id": "stream_cipher", + "functions": ["apply_keystream"], + "namespace": "unauthenticated_encryption", + "api": "unauthenticated_encryption::stream_cipher, unauthenticated_encryption::apply_keystream", + "header": "", + "what": "The raw stream cipher's contract: the concept `stream_cipher`, which reads the algorithm's own key, nonce and block sizes and counter type, and the free form `apply_keystream(cipher, nonce, data, initial_counter)`, which calls the cipher's member; encryption that authenticates nothing, for a protocol that authenticates the nonce and the ciphertext itself.", + "section": "crypto-unauthenticated-encryption", + "backends": { + "sodium": {"tests": ["stream_cipher_concepts", "stream_cipher_shape", "timing_coverage_sodium"]}, + "bearssl": {"tests": ["timing_coverage_bearssl"]}, + "openssl": {"tests": ["timing_coverage_openssl"]} + } + }, + { + "id": "poly1305", + "family": "poly1305", + "functions": ["authenticate", "verify", "async_authenticate", "async_verify"], + "namespace": "single_use_key_authentication", + "api": "authenticators::poly1305", + "header": "", + "what": "RFC 8439's Poly1305, the one-time authenticator: a 16-byte tag of a message under a 32-byte key used for one message alone, as a protocol derives it per message; the key enters every call, and no object keeps it.", + "section": "crypto-poly1305", + "default": "`poly1305<>` names the default backend.", + "backends": { + "sodium": {"tests": ["poly1305_sodium", "authenticator_concepts", "allocation_sodium", + "timing_coverage_sodium", "agreement_poly1305", + "agreement_poly1305_emscripten", "composition_rfc8439", + "composition_rfc8439_emscripten"]}, + "openssl": {"tests": ["poly1305_openssl", "poly1305_openssl_memory_resource", + "allocation_openssl", "timing_coverage_openssl", + "agreement_poly1305", "composition_rfc8439"]}, + "bearssl": {"refused": "poly1305_on_bearssl"}, + "ctaes": {"refused": "poly1305_on_ctaes"} + } + }, + { + "id": "single_use_key_authenticator", + "functions": ["authenticate", "verify"], + "namespace": "single_use_key_authentication", + "api": "single_use_key_authentication::single_use_key_authenticator, single_use_key_authentication::authenticate, single_use_key_authentication::verify", + "header": "", + "what": "The single-use key authenticator's contract: the concept `single_use_key_authenticator`, which reads the algorithm's key and tag sizes, its tag type and its static `authenticate` and `verify`, and their free forms `authenticate(key, message)` and `verify(key, message, tag)`, which call them; a key that authenticates one message and never a second.", + "section": "crypto-single-use-key-authentication", + "backends": { + "sodium": {"tests": ["authenticator_concepts", "poly1305_sodium", "timing_coverage_sodium"]}, + "openssl": {"tests": ["poly1305_openssl", "timing_coverage_openssl"]} + } + }, + { + "id": "async_single_use_key_authenticator", + "free": true, + "functions": ["single_use_key_authentication::async_authenticate", "single_use_key_authentication::async_verify"], + "namespace": "single_use_key_authentication", + "api": "single_use_key_authentication::async_authenticate, single_use_key_authentication::async_verify", + "header": "", + "what": "The asynchronous tag and verification of a single-use key authenticator, Poly1305, on a native backend, the free forms of the static `async_authenticate` and `async_verify`, which they call, each completing through a post to the executor the call gives, with any Asio completion token; WebCrypto has no Poly1305, and no form runs on the browser's backend.", + "section": "crypto-async", + "backends": { + "sodium": {"tests": ["async_authenticator", "timing_coverage_sodium"]}, + "openssl": {"tests": ["async_authenticator_openssl", "timing_coverage_openssl"]} + } + }, { "id": "secretbox", "family": "secretbox_xsalsa20poly1305", @@ -996,6 +1103,45 @@ "sodium": {"targets": "all", "lane": {"native": ["memcheck", "msan"]}} } }, + { + "name": "chacha20", + "title": "ChaCha20", + "group": "ciphers", + "since": "0.2", + "measured": "keystream of 16 KiB", + "header": "", + "shown": "chacha20", + "names": [ + {"name": "chacha20", "title": "ChaCha20", "type": "ciphers::chacha20<{backend}>"} + ], + "default": [ + {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": ["chacha20_sodium", "default_backend_none_linked"], "why": "ChaCha20-Poly1305's default, so that a program that uses both links one library; libsodium's own C code, constant time, the same on every target ({libsodium-stream})"} + ], + "backends": { + "sodium": {"targets": "all", "lane": {"native": ["memcheck", "msan"]}}, + "bearssl": {"targets": "all", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect_printed"]}}, + "openssl": {"targets": "all", "lane": {"native": ["memcheck"]}} + } + }, + { + "name": "poly1305", + "title": "Poly1305", + "group": "authenticators", + "since": "0.2", + "measured": "tag of 16 KiB", + "header": "", + "shown": "poly1305", + "names": [ + {"name": "poly1305", "title": "Poly1305", "type": "authenticators::poly1305<{backend}>"} + ], + "default": [ + {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": ["poly1305_sodium", "default_backend_none_linked"], "why": "ChaCha20's and ChaCha20-Poly1305's default, so that a program composing them links one library ({libsodium-onetimeauth})"} + ], + "backends": { + "sodium": {"targets": "all", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect"]}, "lane_note": {"memcheck": "`authenticate`, then `verify` with the right tag and with a wrong one, the key, the message and the tags secret; the verdict of `verify` declassified by crypto where it first branches on it", "msan": "the same paths as memcheck's", "dudect": "`authenticate` against its key, the all-zero key against random ones; `verify` against its tag, the right tag with its last byte flipped against it with its first byte flipped, both classes failing: a success and a failure return by different paths, about 0.4 ns apart, which dudect finds and which is public, the verdict being reported"}}, + "openssl": {"targets": "all", "lane": {"native": ["memcheck"]}, "lane_note": "`authenticate` and `verify`, as on libsodium"} + } + }, { "name": "secretbox_xsalsa20poly1305", "title": "XSalsa20-Poly1305 secret box", @@ -1162,6 +1308,8 @@ {"title": "Compare secrets in constant time", "section": "crypto-constant-time-equal", "text": "compare a tag, a MAC or a token with `secure::constant_time_equal`, never `==` or `memcmp` ({cwe208})."}, {"title": "Secrets come from random_device", "section": "crypto-entropy", "text": "keys, nonces and tokens are drawn from `random_device`, never `std::mt19937` or `rand` ({cwe338})."}, {"title": "Never reuse a nonce under one ChaCha20-Poly1305 key", "section": "crypto-chacha", "text": "two messages under one key and one nonce reveal the XOR of their plaintexts and let an attacker forge tags ({rfc8439-nonce}). `xchacha20_poly1305` and the secret boxes: draw 24 bytes at random per message. `chacha20_poly1305`: number the 12-byte nonces with a counter that never repeats, a restart included, or draw them at random for at most 2^32 messages per key, AES-GCM's bound for random 12-byte nonces ({sp800-38d}). `chacha20_poly1305_original`: a counter only, its 8 bytes are too short to draw."}, + {"title": "ChaCha20 authenticates nothing", "section": "crypto-chacha20", "text": "`ciphers::chacha20` and the namespace `unauthenticated_encryption` encrypt without a tag: a bit flipped in the ciphertext flips the same bit of the plaintext, and a nonce repeated under one key reveals the XOR of two plaintexts ({rfc8439-nonce}). Use them only where a protocol fixes its own construction and authenticates the nonce and the ciphertext itself, as NIP-44 does with HMAC-SHA256 ({nip44}); a program's own messages take `chacha20_poly1305` or `xchacha20_poly1305`."}, + {"title": "A Poly1305 key authenticates one message", "section": "crypto-single-use-key-authentication", "text": "the 32-byte key of `authenticators::poly1305` is used for one message alone: tags of two messages under one key let an attacker forge others ({rfc8439-poly-key}). A protocol derives the key for each message, as RFC 8439's AEAD takes it from ChaCha20's keystream; a key used for many messages takes the HMAC of `webcpp::hash`, and a program's own messages an AEAD."}, {"title": "A shared secret is not a key", "section": "crypto-x25519", "text": "derive keys from X25519's shared secret and both public keys with a KDF such as webcpp::hash's HKDF, never use its bytes as a cipher's key ({rfc7748-kdf}); `kx_keypair` and the boxes do this themselves."}, {"title": "The default on MSVC is not constant time", "section": "crypto-backends-defaults", "text": "natively the default is OpenSSL, which MSVC builds no-asm, table-based ({openssl-install}); where timing attacks matter, link BearSSL and name `gcm>`, and for the block cipher link ctaes and name `aes256`."} ], @@ -1201,14 +1349,16 @@ "cited": ["Nonce misuse", "Constant time, by design", "Standards", "Where it is used", "Browsers' WebCrypto"], "parts": [ {"title": "AES", "rows": [0, 1]}, - {"title": "ChaCha20-Poly1305", "rows": [2, 3, 4]} + {"title": "ChaCha20-Poly1305", "rows": [2, 3, 4]}, + {"title": "ChaCha20", "rows": [5]} ], "rows": [ ["`gcm`, `aes128_gcm`, `aes256_gcm`: AES-GCM", "yes", "16, 24 or 32 bytes", "1 to 128 bytes; 12 recommended", "not resistant: a repeated nonce under one key reveals the plaintexts' XOR and lets tags be forged ({joux}, {nonce-reuse})", "{speed:gcm}", "BearSSL and OpenSSL with assembly: yes ({bearssl-ct}; {openssl-armv8}); OpenSSL no-asm (MSVC, wasip2, wasip3): no ({openssl-install})", "{constant_time:gcm}", "{sp800-38d}", "TLS 1.3 ({rfc8446}), SSH ({rfc5647}), IPsec ({rfc4106}), SRTP ({rfc7714}), optional for WebRTC's media ({rfc8827})", "yes, with 16- or 32-byte keys ({webcrypto}; {chromium-aes192})", "a protocol, a browser's WebCrypto or a standard names AES-GCM, or the CPU has AES instructions; at most 2^32 messages per key with random nonces, otherwise a counter"], ["`aes128`, `aes192`, `aes256`: AES block cipher", "no", "16, 24 or 32 bytes", "none", "none: a block cipher takes no nonce, and equal blocks give equal ciphertext", "{speed:aes_block}", "ctaes: yes ({ctaes}); OpenSSL with assembly: yes ({openssl-armv8}); OpenSSL no-asm: no ({openssl-aes-core})", "{constant_time:aes_block}", "{fips197}", "none on its own: every AES mode is built on it", "no raw block cipher ({webcrypto})", "you need one keyed permutation of a 16-byte block, such as an opaque identifier; for data, use an AEAD"], ["`chacha20_poly1305`: ChaCha20-Poly1305", "yes", "32 bytes", "12 bytes", "not resistant: a repeated nonce under one key reveals the plaintexts' XOR and lets tags be forged ({rfc8439-nonce})", "{speed:chacha20_poly1305}", "libsodium, BearSSL and OpenSSL: yes, additions, XORs and rotations with no table indexed by a secret ({rfc8439-chacha}; {libsodium-aead-timing})", "{constant_time:chacha20_poly1305}", "{rfc8439}", "TLS 1.3 ({rfc8446}), WireGuard ({wireguard})", "no: WebCrypto offers AES-GCM, not ChaCha20-Poly1305 ({webcrypto})", "a protocol names RFC 8439's AEAD (TLS 1.3, WireGuard), or the program runs without AES hardware and numbers its nonces with a counter; to draw nonces at random, XChaCha20-Poly1305"], ["`chacha20_poly1305_original`: ChaCha20-Poly1305, original", "yes", "32 bytes", "8 bytes, too short to draw at random: a counter", "not resistant ({libsodium-aead})", "{speed:chacha20_poly1305_original}", "libsodium: yes ({libsodium-aead-timing})", "{constant_time:chacha20_poly1305_original}", "none: libsodium's original construction ({libsodium-aead})", "none in new protocols: the format of libsodium's `crypto_aead_chacha20poly1305` ({libsodium-aead})", "no ({webcrypto})", "the peer writes libsodium's original construction; otherwise RFC 8439's form or XChaCha20-Poly1305"], - ["`xchacha20_poly1305`: XChaCha20-Poly1305", "yes", "32 bytes", "24 bytes, safe to draw at random for every message", "not resistant to a repeated nonce, but 24 random bytes never repeat in practice ({xchacha-draft})", "{speed:xchacha20_poly1305}", "libsodium: yes ({libsodium-aead-timing})", "{constant_time:xchacha20_poly1305}", "{xchacha-draft}", "libsodium's secretstream ({libsodium-secretstream})", "no ({webcrypto})", "you encrypt many messages under one key and want to draw each nonce at random: a chat app, records in a database, on the web and natively alike; when in doubt, this one"] + ["`xchacha20_poly1305`: XChaCha20-Poly1305", "yes", "32 bytes", "24 bytes, safe to draw at random for every message", "not resistant to a repeated nonce, but 24 random bytes never repeat in practice ({xchacha-draft})", "{speed:xchacha20_poly1305}", "libsodium: yes ({libsodium-aead-timing})", "{constant_time:xchacha20_poly1305}", "{xchacha-draft}", "libsodium's secretstream ({libsodium-secretstream})", "no ({webcrypto})", "you encrypt many messages under one key and want to draw each nonce at random: a chat app, records in a database, on the web and natively alike; when in doubt, this one"], + ["`chacha20`: ChaCha20, the raw stream cipher", "no: it authenticates nothing; a bit flipped in the ciphertext flips the same bit of the plaintext", "32 bytes", "12 bytes, and a 32-bit block counter the caller names", "not resistant: a repeated nonce under one key reveals the plaintexts' XOR ({rfc8439-nonce})", "{speed:chacha20}", "libsodium, BearSSL and OpenSSL: yes, additions, XORs and rotations with no table indexed by a secret ({rfc8439-chacha}; {libsodium-aead-timing})", "{constant_time:chacha20}", "{rfc8439}", "NIP-44's encryption, under its HMAC-SHA256 ({nip44})", "no ({webcrypto})", "a protocol fixes its own construction over raw ChaCha20 and authenticates the nonce and the ciphertext itself, as NIP-44 does; a program's own messages take `chacha20_poly1305` or `xchacha20_poly1305`"] ] }, "secret_key_encryption": { @@ -1248,6 +1398,23 @@ ["`hpke::suite`: RFC 9180's HPKE, DHKEM(X25519 or P-256), HKDF-SHA256 or HKDF-SHA512, AES-GCM, ChaCha20-Poly1305 or export-only", "Encryption to a public key by the standard interoperable protocols use (MLS, TLS's Encrypted Client Hello): an ephemeral agreement and a key schedule set up a context that seals messages in order and exports secrets, in four modes (with a pre-shared key, an authenticated sender, or both)", "to seal, the recipient's X25519 or P-256 public key, and in the auth modes the sender's key pair; to open, the recipient's key pair, and in the auth modes the sender's public key", "none: derived from the context's sequence number", "the encapsulated key once per context (32 bytes for X25519, 65 for P-256), then a 16-byte tag per message", "{rfc9180}, {rfc9180-vectors}, {rfc9420}", "the peer speaks RFC 9180 (MLS, Marmot, any HPKE library), or one context carries ordered messages and exported keys; a sealed box when the peer is libsodium"] ] }, + "unauthenticated_encryption": { + "title": "webcpp::crypto::unauthenticated_encryption", + "columns": ["Contract", "What it is", "Key", "Nonce", "Authentication", "Standards and sources", "Where it is used", "Choose it when"], + "cited": ["Standards and sources", "Where it is used"], + "rows": [ + ["`stream_cipher`, `apply_keystream`: The stream cipher contract", "the contract every raw stream cipher of `ciphers` satisfies: `stream_cipher` checks its key, nonce and block sizes, its counter type, `from_key` and `apply_keystream`, which reads the algorithm's own shape, never ChaCha20's; `apply_keystream` is its free form", "the cipher's", "the cipher's, with its block counter", "none: the keystream XORed into the data; the protocol authenticates the nonce and the ciphertext itself", "none: a contract, not an algorithm; ChaCha20's is {rfc8439}", "NIP-44, whose HMAC-SHA256 covers the nonce and the ciphertext ({nip44})", "a protocol fixes its own construction over a raw stream cipher, or code is written once for every stream cipher; a program's own messages take the AEADs of `secret_key_encryption`"] + ] + }, + "single_use_key_authentication": { + "title": "webcpp::crypto::single_use_key_authentication", + "columns": ["Name", "What it is", "Key", "Tag", "Key reuse", "Speed", "Constant time, measured", "Standards and sources", "Where it is used", "Choose it when"], + "cited": ["Key reuse", "Standards and sources", "Where it is used"], + "rows": [ + ["`poly1305`: Poly1305, the one-time authenticator", "RFC 8439's authenticator, an algorithm of `authenticators`: a 16-byte tag of a message under a key that authenticates that message alone; `authenticate` and `verify` are static, and the key enters every call", "32 bytes, r and s, used for one message", "16 bytes", "forbidden: two messages under one key let the key be recovered and tags be forged ({rfc8439-poly-key})", "{speed:poly1305}", "{constant_time:poly1305}", "{rfc8439}, {libsodium-onetimeauth}", "inside ChaCha20-Poly1305 and the secret boxes, under a key derived for each message ({rfc8439})", "a protocol fixes its own construction over raw Poly1305 and derives its key for each message; a key used for many messages takes the HMAC of `webcpp::hash`, and a program's own messages an AEAD"], + ["`single_use_key_authenticator`, `authenticate`, `verify`: The single-use key authenticator contract", "the contract every authenticator whose key is used once satisfies: `single_use_key_authenticator` checks its key and tag sizes, its tag type and its static `authenticate` and `verify`; `authenticate` and `verify` are their free forms", "the authenticator's", "the authenticator's", "none: a contract, not an algorithm; each key authenticates one message", "none: a contract, not an algorithm", "none: a contract, not an algorithm", "none: a contract, not an algorithm; Poly1305's is {rfc8439}", "none: a contract; Poly1305 is used inside ChaCha20-Poly1305 ({rfc8439})", "code is written once for every single-use key authenticator; a reusable key's MAC is the HMAC of `webcpp::hash`"] + ] + }, "key_exchange": { "title": "webcpp::crypto::key_exchange", "columns": ["Construction", "What it does", "Keys", "Output", "Standards and sources", "Choose it when"], @@ -1290,6 +1457,8 @@ {"need": "Give a client and a server a key for each direction from each other's public key, as libsodium's `crypto_kx` does", "namespace": "webcpp::crypto::key_exchange", "api": "`kx_keypair::from_keypair`, `kx_keypair::derive_from_seed`, `kx_keypair::generate`, `client_session_keys`, `server_session_keys`", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//kx-default", "example": "kx_session", "section": "crypto-kx"}, {"need": "Export or import an Ed25519 or X25519 key in the standard forms OpenSSL and WebCrypto use: SPKI and PKCS#8 (RFC 8410), as DER or PEM text", "namespace": "webcpp::crypto::curves", "api": "`codecs::encode` and `codecs::decode` with `crypto::formats::raw`, `spki`, `pkcs8` and `pem`, on Ed25519's and X25519's keys", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//ed25519-default /webcpp/crypto//x25519-default", "example": "key_formats", "section": "crypto-key-formats"}, {"need": "Encrypt messages in a chat app, on the web and natively, each with a random nonce", "namespace": "webcpp::crypto::ciphers", "api": "`xchacha20_poly1305<>`: `from_key`, `seal`, `open`", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//xchacha20_poly1305-default", "example": "xchacha_seal", "section": "crypto-chacha"}, + {"need": "Apply ChaCha20's keystream for a protocol that fixes its own construction (NIP-44)", "namespace": "webcpp::crypto::ciphers", "api": "`chacha20<>`: `from_key`, `apply_keystream(nonce, data, initial_counter)`; `unauthenticated_encryption::apply_keystream` in code written once for every stream cipher", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//chacha20-default", "example": "chacha20_keystream", "section": "crypto-chacha20"}, + {"need": "Authenticate one message under a one-time key", "namespace": "webcpp::crypto::authenticators", "api": "`poly1305<>`: static `authenticate(key, message)`, `verify(key, message, tag)`; `single_use_key_authentication::authenticate` and `verify` in code written once for every single-use key authenticator", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//poly1305-default", "example": "poly1305_one_time_tag", "section": "crypto-poly1305"}, {"need": "Encrypt a record or a file under one secret key, each with a random nonce, in libsodium's secret-box format", "namespace": "webcpp::crypto::secret_key_encryption", "api": "`secretbox<>`, `secretbox_xchacha20poly1305<>`: `from_key`, `seal(nonce, data)`, `open(nonce, data, tag)`; the box forms `seal(box, nonce, data)`, `open(box, nonce, data, tag)`", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//secretbox_xsalsa20poly1305-default", "example": "file_share", "section": "crypto-secretbox"}, {"need": "Send messages between two people who know each other's public keys, as NaCl's and libsodium's crypto_box", "namespace": "webcpp::crypto::public_key_encryption", "api": "`box::from_keys`, `box::seal`, `box::open`", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//box_xsalsa20poly1305-default", "example": "box_messages", "section": "crypto-box"}, {"need": "Let anyone send a message that only the recipient can read, without saying who sent it (anonymous feedback, a drop box)", "namespace": "webcpp::crypto::public_key_encryption", "api": "`sealed_box::seal`, `sealed_box::open`", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//sealed_box-default", "example": "file_share", "section": "crypto-sealed-box"}, @@ -1320,6 +1489,8 @@ "x25519_default": "RFC 7748's shared secret on X25519's default on every target, with the one line `/webcpp/crypto//x25519-default`, which links libsodium.", "kx_default": "libsodium's `crypto_kx` test, the client's and the server's session keys from each other's public key, on its default on every target, with the one line `/webcpp/crypto//kx-default`, which links libsodium.", "chacha20_poly1305_default": "RFC 8439's ChaCha20-Poly1305 example, sealed and opened on its default on every target, with the one line `/webcpp/crypto//chacha20_poly1305-default`, which links libsodium.", + "chacha20_default": "RFC 8439's ChaCha20 example of section 2.4.2, encrypted and decrypted on its default on every target, with the one line `/webcpp/crypto//chacha20-default`, which links libsodium.", + "poly1305_default": "RFC 8439's Poly1305 example of section 2.5.2, authenticated and verified on its default on every target, with the one line `/webcpp/crypto//poly1305-default`, which links libsodium.", "chacha20_poly1305_original_default": "libsodium's case of the original ChaCha20-Poly1305, sealed and opened on its default on every target, with the one line `/webcpp/crypto//chacha20_poly1305_original-default`, which links libsodium.", "xchacha20_poly1305_default": "The XChaCha20-Poly1305 draft's example, sealed and opened on its default on every target, with the one line `/webcpp/crypto//xchacha20_poly1305-default`, which links libsodium.", "secretbox_xsalsa20poly1305_default": "NaCl's secret box, sealed and opened on its default on every target, with the one line `/webcpp/crypto//secretbox_xsalsa20poly1305-default`, which links libsodium.", @@ -1383,6 +1554,26 @@ "box_default_not_linked": "The secret boxes', the boxes' and the sealed boxes' default is libsodium on every target: add the family's alias, as `/webcpp/crypto//box_xsalsa20poly1305-default`, which links `/third_party//sodium`.", "kx_default_not_linked": "Add `/webcpp/crypto//kx-default`, which links `/third_party//sodium` on every target.", "chacha_on_ctaes": "Name a backend that has ChaCha20-Poly1305, as in `chacha20_poly1305`, or its default, `chacha20_poly1305<>`, and link its library.", + "chacha20_not_a_family": "Name the family `families::chacha20`, or use the alias `ciphers::chacha20`; an AEAD's family seals through `ciphers::chacha20_poly1305`.", + "chacha20_unknown_backend": "Name a backend of `webcpp::crypto::backends` that has ChaCha20, as `backends::sodium`, or leave the backend out for the family's default: `chacha20<>`.", + "chacha20_on_ctaes": "Name a backend that has ChaCha20, as in `chacha20`, or its default, `chacha20<>`, and link its library.", + "chacha20_default_not_linked": "ChaCha20's default is libsodium on every target: add the family's alias, `/webcpp/crypto//chacha20-default`, which links `/third_party//sodium`, or name another backend in the type, as `chacha20`.", + "chacha20_header_not_included": "Include the backend's header the message names, as ``, and add its library, as `/third_party//bearssl`.", + "apply_keystream_not_a_stream_cipher": "Give `unauthenticated_encryption::apply_keystream` a stream cipher, `ciphers::chacha20`; an AEAD seals and opens through `secret_key_encryption::aead::seal` and `aead::open`.", + "poly1305_unknown_backend": "Name a backend of `webcpp::crypto::backends` that has Poly1305, as `backends::sodium` or `backends::openssl`, or leave the backend out for the family's default: `poly1305<>`.", + "poly1305_on_bearssl": "Name a backend that has Poly1305, as in `poly1305`, or its default, `poly1305<>`, and link its library: BearSSL's Poly1305 is inside its ChaCha20-Poly1305 alone, which derives the key itself.", + "poly1305_on_ctaes": "Name a backend that has Poly1305, as in `poly1305`, or its default, `poly1305<>`, and link its library.", + "poly1305_default_not_linked": "Poly1305's default is libsodium on every target: add the family's alias, `/webcpp/crypto//poly1305-default`, which links `/third_party//sodium`, or name another backend in the type, as `poly1305`.", + "authenticate_not_a_single_use_key_authenticator": "Give `single_use_key_authentication::authenticate` a single-use key authenticator, `authenticators::poly1305`; a key used for many messages is authenticated by the HMAC of `webcpp::hash`.", + "from_key_poly1305": "Poly1305 has no object and no `from_key`: call `authenticators::poly1305<>::authenticate(key, message)`, or `single_use_key_authentication::authenticate>(key, message)`, with a fresh key for each message.", + "poly1305_header_not_included": "Include the backend's header the message names, as ``, and add its library, as `/webcpp/crypto//openssl`.", + "authenticate_asynchronous_backend": "Name a native backend, such as `backends::sodium`, for Poly1305: WebCrypto has no Poly1305, so neither its `authenticate`, static or free, nor its asynchronous forms run on the browser's backend.", + "verify_poly1305_asynchronous_backend": "As `authenticate_asynchronous_backend`: name a native backend, such as `backends::sodium`, for Poly1305's `verify`, static or free.", + "async_authenticate_asynchronous_backend": "As `authenticate_asynchronous_backend`: name a native backend, such as `backends::sodium`, for Poly1305's `async_authenticate`, static or free.", + "async_verify_asynchronous_backend": "As `authenticate_asynchronous_backend`: name a native backend, such as `backends::sodium`, for Poly1305's `async_verify`, static or free.", + "async_authenticate_not_a_single_use_key_authenticator": "Give `single_use_key_authentication::async_authenticate` a single-use key authenticator, `authenticators::poly1305`; a key used for many messages is authenticated by the HMAC of `webcpp::hash`, asynchronously by `webcpp::hash::async_hmac`.", + "async_verify_not_a_single_use_key_authenticator": "Give `single_use_key_authentication::async_verify` a single-use key authenticator, `authenticators::poly1305`; a key used for many messages is authenticated by the HMAC of `webcpp::hash`, asynchronously by `webcpp::hash::async_hmac`.", + "verify_not_a_single_use_key_authenticator": "Give `single_use_key_authentication::verify` a single-use key authenticator, `authenticators::poly1305`; a key used for many messages is authenticated by the HMAC of `webcpp::hash`.", "x25519_constructions_other_backend": "Name a backend that has X25519 as well, as libsodium, the default of crypto_kx, the boxes and the sealed box on every target: each takes an X25519 key pair of its own backend.", "box_not_a_family": "Name `families::box_xsalsa20poly1305` or `families::box_xchacha20poly1305`, or use `public_key_encryption::box` or `public_key_encryption::box_xchacha20poly1305`.", "aead_not_a_family": "Name one of the three ChaCha20-Poly1305 families; AES-GCM is `ciphers::gcm`, as in `aes256_gcm`, and a secret box `secret_key_encryption::basic_secretbox`, as in `secret_key_encryption::secretbox<>`.", @@ -1430,6 +1621,13 @@ "ed25519_default_not_linked_on_emscripten": "As `ed25519_default_not_linked`.", "heavy_without_threads": "Call the synchronous operation the message names, or build with threads: natively without `WEBCPP_CRYPTO_NO_THREADS`, on Emscripten with `-pthread`; WASI has none.", "heavy_without_threads_first": "As `heavy_without_threads`.", + "async_from_key_chacha20_asynchronous_backend": "Name a native backend, such as `backends::sodium`, for `async_from_key`: WebCrypto has no ChaCha20, so no form of the raw stream cipher runs on the browser's backend.", + "apply_keystream_asynchronous_backend": "Name a native backend, such as `backends::sodium`, for ChaCha20: WebCrypto has no ChaCha20, so neither its `apply_keystream` nor its `async_apply_keystream` completes on the browser's backend.", + "from_key_chacha20_asynchronous_backend": "As `apply_keystream_asynchronous_backend`: name a native backend, such as `backends::sodium`, for the `from_key` of ChaCha20.", + "async_apply_keystream_asynchronous_backend": "As `apply_keystream_asynchronous_backend`: name a native backend, such as `backends::sodium`, for ChaCha20's `async_apply_keystream`, free or member.", + "async_from_key_not_a_cipher": "Give `async_from_key` an AEAD, a stream cipher or a secret box; make a crypto_box with `public_key_encryption::box::from_keys`, synchronously.", + "async_from_key_aead_without_member": "Give the AEAD or the secret box a static member `async_from_key`, as crypto's have, or call its synchronous `from_key`: only a stream cipher's `from_key` is run and posted by the free `async_from_key` itself.", + "async_from_key_stream_cipher_without_empty": "Give the stream cipher a `noexcept` default constructor that makes an empty object (public, or private with `webcpp::crypto::detail::async_access` a friend), or a static member `async_from_key`: the free form's error completion gives the empty cipher.", "async_from_key_xchacha": "Name a native backend, such as `backends::sodium`, for `async_from_key`: WebCrypto has no XChaCha20-Poly1305, so no form of it runs on the browser's backend, where only AES-GCM seals and opens.", "async_from_secret_secp256k1": "Call the synchronous `from_secret`: secp256k1 is not in WebCrypto, so only Ed25519's, X25519's and P-256's key pairs have `async_from_secret`.", "make_removed": "Call the factory named by its input, member or free: `from_secret` for a key pair, `from_bytes` for a public key, `from_key` for a cipher (`crypto::from_secret(bytes)`, `K::from_secret(bytes)`); `make` is gone, with no alias.", @@ -1584,6 +1782,9 @@ "async_from_key_secretbox_asynchronous_backend": "Name a native backend, such as `backends::sodium`, for the secret box's `async_from_key`: WebCrypto has no secret box.", "seal_secretbox_asynchronous_backend": "Name a native backend, such as `backends::sodium`, for the secret box: WebCrypto has no secret box, so neither its `seal` nor its `async_seal` completes on the browser's backend; there, use AES-GCM.", "seal_box_asynchronous_backend": "Name a native backend, such as `backends::sodium`, for the crypto_box: WebCrypto has no crypto_box, so neither its `seal` nor its `async_seal` completes on the browser's backend.", + "from_key_chacha20_poly1305_asynchronous_backend": "Name a native backend, such as `backends::sodium`, for ChaCha20-Poly1305: WebCrypto has no ChaCha20-Poly1305, so neither its `from_key` nor its `async_from_key` completes on the browser's backend; there, use AES-GCM.", + "from_key_secretbox_asynchronous_backend": "As `seal_secretbox_asynchronous_backend`: name a native backend, such as `backends::sodium`, for the `from_key` of the secret box.", + "from_keys_box_asynchronous_backend": "As `seal_box_asynchronous_backend`: name a native backend, such as `backends::sodium`, for the `from_keys` of the crypto_box.", "async_seal_box_associated_data": "Call the box form, `secret_key_encryption::async_seal(executor, box, nonce, data, token)`, or the box's own `async_seal(executor, nonce, data, token)`: a secret box or a crypto_box takes no associated data.", "seal_removed_call_wasi": "As `seal_removed_call`: call crypto::secret_key_encryption::aead::seal and open; clang's offer of the C library's fopen is not the AEAD's open.", "chacha_default_not_linked_on_emscripten": "As `chacha_default_not_linked`.", diff --git a/doc/tables/generate.py b/doc/tables/generate.py index d85cbe1..43db1b2 100644 --- a/doc/tables/generate.py +++ b/doc/tables/generate.py @@ -67,7 +67,7 @@ import sys import textwrap from pathlib import Path -from typing import Any, Dict, List, Optional, Tuple +from typing import Any, Callable, Dict, List, Optional, Tuple HERE = Path(__file__).resolve().parent DOC = HERE.parent @@ -2070,16 +2070,48 @@ def class_body(text: str, name: str) -> str: return text[found.end():] +# A line that opens or closes a namespace, at the start of the line as clang-format writes it. +NAMESPACE_LINE = re.compile(r'^(?:namespace ([\w:]+) \{|\} // namespace ([\w:]+))$', re.M) + + +def namespace_at(text: str) -> Callable[[int], str]: + """The namespace that holds each offset of a header's text, under webcpp::crypto: '' for + webcpp::crypto itself, 'single_use_key_authentication' for a namespace in it.""" + opened: List[Tuple[int, str]] = [] + stack: List[str] = [] + for line in NAMESPACE_LINE.finditer(text): + if line.group(1): + stack.append(line.group(1)) + elif stack: + stack.pop() + opened.append((line.end(), '::'.join(stack))) + + def at(offset: int) -> str: + held = '' + for end, name in opened: + if end > offset: + break + held = name + if held == ROOT_NAMESPACE: + return '' + return held[len(ROOT_NAMESPACE) + 2:] if held.startswith(f'{ROOT_NAMESPACE}::') else held + return at + + def declared_brief(library: Path, operation: Data, function: str) -> str: """The first sentence of the Doc Comment of a function an operation names, read from the operation's headers: the description llms.txt gives it. A function written `class::name` is - read in that class's body alone, for a name that another class of the header declares first. - A function the operation's `function_headers` map to a header is read in that header instead - of the operation's. A function the operation's `overloads` name is read in the first - declaration that holds the text they give it, for a name another family's overload declares - first; a function written `name(text)`, beside `name`, is read in the first declaration that - holds text, so that each of a member's overloads has a line of its own. A function no header - declares is a fault.""" + read in that class's body alone, for a name that another class of the header declares first; + one written `namespace::name`, where no class of that name is defined, is read in that + namespace's own declarations alone (`crypto::name` in webcpp::crypto's, its nested namespaces + left out), for a free function that another namespace of the header also declares. A plain + name that free functions of two namespaces declare is a fault, which names them: the first + is not necessarily the function meant. A function the operation's `function_headers` map to + a header is read in that header instead of the operation's. A function the operation's + `overloads` name is read in the first declaration that holds the text they give it, for a + name another family's overload declares first; a function written `name(text)`, beside + `name`, is read in the first declaration that holds text, so that each of a member's + overloads has a line of its own. A function no header declares is a fault.""" listed = function overload = operation.get('overloads', {}).get(function) if function.endswith(')') and '(' in function: @@ -2093,17 +2125,29 @@ def declared_brief(library: Path, operation: Data, function: str) -> str: # the signature template, names it in `function_headers`. headers = operation.get('function_headers', {}).get( listed, operation.get('function_headers', {}).get(function, operation['header'])) + found_in: List[Tuple[str, str]] = [] for header in HEADER.findall(headers): text = (library / 'include' / header).read_text(encoding='utf-8') + in_namespace: Optional[str] = None if scope: - text = class_body(text, scope) + body = class_body(text, scope) + if body: + text = body + else: + in_namespace = '' if scope == 'crypto' else scope + namespace = namespace_at(text) for comment in DOC_COMMENT.finditer(text): rest = text[comment.end():] declaration = rest[:rest.find('{') if '{' in rest else len(rest)] declaration = declaration.split(';', 1)[0] declaration = '\n'.join(line.split('//', 1)[0] for line in declaration.splitlines()) free = not declaration.lstrip('\n').startswith(' ') - if operation.get('free') and not free and not scope: + unscoped = not scope or in_namespace is not None + if (operation.get('free') or in_namespace is not None) and not free and unscoped: + continue + held = namespace(comment.start()) + if in_namespace is not None and held != in_namespace and \ + not held.endswith(f'::{in_namespace}'): continue if overload is not None and overload not in declaration: continue @@ -2113,7 +2157,15 @@ def declared_brief(library: Path, operation: Data, function: str) -> str: words = ' '.join(line.strip().lstrip('*').strip() for line in comment.group(1).splitlines()).strip() words = LINE_REFERENCE.sub('', words.replace('@ref ', '')) - return re.split(r'(?<=\.)\s', words, maxsplit=1)[0] + found_in.append((held, re.split(r'(?<=\.)\s', words, maxsplit=1)[0])) + if found_in: + namespaces = list(dict.fromkeys(held for held, _ in found_in)) + if not scope and operation.get('free') and len(namespaces) > 1: + named = ', '.join(held or 'crypto' for held in namespaces) + raise Fault(f'crypto.json names {listed} of {operation["id"]}, which free functions of ' + f'the namespaces {named} declare: write it namespace::{name}, ' + f'crypto::{name} for webcpp::crypto\'s own') + return found_in[0][1] held = f' with {overload} in its declaration' if overload is not None else '' raise Fault(f'crypto.json names {listed} of {operation["id"]}, which no Doc Comment of ' f'{operation["header"]} declares{held}') diff --git a/doc/tables/generate_test.py b/doc/tables/generate_test.py index 383e40c..e5cfa60 100644 --- a/doc/tables/generate_test.py +++ b/doc/tables/generate_test.py @@ -8,16 +8,15 @@ """Checks generate.py's readers and writers on small fixtures of their own: the Jamfile reader (a program inside an `if`, a rule's body, the targets a program inherits, the memory option's tests, a name declared twice), a backend's reason for the targets an operation misses (OpenSSL's alone), the -outcome reader (each directive and section), the Doc Comment reader (a line reference left out), the -writers whose output a reader of the page sees (inline code that holds a `+` or a backtick, a -failing fixture's output per target, a comparison table's names of code, the decision table's -Jamfile column, the table of Ed25519's edge cases, a family's measured constant time per target, a -lane note of one checker beside that checker alone, a comparison table's columns, its measured -cells and its refusal of a fact without a source, the decision table's link to its example, -llms.txt's entry of a function, every backend's facts and own suite, every API page's default per -target, the formats table's list read from formats.hpp, a format missing from either list, its -columns and its PEM sizes), -and the capability table's: its checks of +outcome reader (each directive and section), the Doc Comment reader (a line reference left out, a +free function two namespaces declare), the writers whose output a reader of the page sees (inline +code that holds a `+` or a backtick, a failing fixture's output per target, a comparison table's +names of code, the decision table's Jamfile column, the table of Ed25519's edge cases, a family's +measured constant time per target, a lane note of one checker beside that checker alone, a +comparison table's columns, its measured cells and its refusal of a fact without a source, the +decision table's link to its example, llms.txt's entry of a function, every backend's facts and own +suite, every API page's default per target, the formats table's list read from formats.hpp, a format +missing from either list, its columns and its PEM sizes), and the capability table's: its checks of crypto.json's families, the refusals and cells of include/webcpp/crypto/detail/capabilities.hpp, the cells test/capabilities_test.cpp asserts, and the comparison --check makes; and the size matrix's: what each cell adds to the baseline per target, read from the lane sizes' tables (generate.py @@ -1514,6 +1513,41 @@ def test_an_overload_is_read_in_the_declaration_that_holds_its_text(scratch: Pat raise AssertionError('an overload no declaration holds was given a brief') +def test_a_free_function_two_namespaces_declare_is_read_in_the_namespace_named( + scratch: Path) -> None: + # The free async_verify of a namespace declared first does not give its brief to + # webcpp::crypto's own: a plain name two namespaces declare is a fault naming them, and + # `namespace::name` (`crypto::name` for webcpp::crypto's own) reads that namespace alone. + written(scratch, 'include/webcpp/crypto/spaces.hpp', ( + 'namespace webcpp::crypto {\n\n' + 'namespace single_use_key_authentication {\n' + '/** Verifies a tag. */\nint async_verify(int key, int tag);\n' + '} // namespace single_use_key_authentication\n\n' + '/** Verifies an Ed25519 signature. */\nint async_verify(int scheme, int signature);\n' + '} // namespace webcpp::crypto\n')) + operation = {'id': 'spaces', 'header': '', 'free': True} + try: + generate.declared_brief(scratch, operation, 'async_verify') + except generate.Fault as fault: + assert 'single_use_key_authentication, crypto' in str(fault), fault + else: + raise AssertionError('a plain name two namespaces declare was given a brief') + brief = generate.declared_brief(scratch, operation, 'crypto::async_verify') + assert brief == 'Verifies an Ed25519 signature.', brief + brief = generate.declared_brief(scratch, operation, + 'single_use_key_authentication::async_verify') + assert brief == 'Verifies a tag.', brief + line = generate.llms_entry(scratch, dict(operation, functions=['crypto::async_verify']), + 'crypto::async_verify') + assert line == ' - async_verify: Verifies an Ed25519 signature.', line + try: + generate.declared_brief(scratch, operation, 'unauthenticated_encryption::async_verify') + except generate.Fault: + pass + else: + raise AssertionError('a function of a namespace that declares none was given a brief') + + def test_a_function_listed_with_a_text_is_its_overload_of_its_own_line(scratch: Path) -> None: # A member with two overloads gets a line each: `class::name(text)` is the declaration that # holds text, its line named as listed; the plain name is the first declaration. @@ -1930,6 +1964,7 @@ def test_a_namespace_table_is_split_into_its_parts(_: Path) -> None: test_a_use_case_that_lists_its_operations_joins_those_alone, test_a_use_case_listing_an_unknown_operation_is_a_fault, test_an_overload_is_read_in_the_declaration_that_holds_its_text, + test_a_free_function_two_namespaces_declare_is_read_in_the_namespace_named, test_a_function_listed_with_a_text_is_its_overload_of_its_own_line, test_a_measurement_not_built_at_release_is_refused, test_a_speed_cell_names_each_operation_and_refuses_an_unknown_backend, diff --git a/doc/tables/sizes.json b/doc/tables/sizes.json index 56528c9..593d083 100644 --- a/doc/tables/sizes.json +++ b/doc/tables/sizes.json @@ -6,7 +6,7 @@ "target": "emscripten", "toolset": "emscripten-6.0.11", "baseline": "baseline", - "date": "2026-11-21", + "date": "2026-12-05", "host": "Darwin arm64", "format": "WebAssembly", "programs": [ @@ -21,10 +21,10 @@ { "program": "aes_block_ctaes", "file": "wasm", - "bytes": 25997, - "gzip": 11464, + "bytes": 26173, + "gzip": 11557, "over_baseline": 5806, - "gzip_over_baseline": 1948 + "gzip_over_baseline": 1949 }, { "program": "baseline", @@ -37,11 +37,27 @@ { "program": "baseline", "file": "wasm", - "bytes": 20191, - "gzip": 9516, + "bytes": 20367, + "gzip": 9608, "over_baseline": 0, "gzip_over_baseline": 0 }, + { + "program": "chacha20_bearssl", + "file": "js", + "bytes": 9765, + "gzip": 3478, + "over_baseline": 8, + "gzip_over_baseline": 6 + }, + { + "program": "chacha20_bearssl", + "file": "wasm", + "bytes": 24252, + "gzip": 11038, + "over_baseline": 3885, + "gzip_over_baseline": 1430 + }, { "program": "chacha20_poly1305_bearssl", "file": "js", @@ -53,58 +69,74 @@ { "program": "chacha20_poly1305_bearssl", "file": "wasm", - "bytes": 26971, - "gzip": 12347, - "over_baseline": 6780, - "gzip_over_baseline": 2831 + "bytes": 27155, + "gzip": 12441, + "over_baseline": 6788, + "gzip_over_baseline": 2833 }, { "program": "chacha20_poly1305_original_sodium", "file": "js", - "bytes": 11888, - "gzip": 4231, - "over_baseline": 2131, - "gzip_over_baseline": 759 + "bytes": 12289, + "gzip": 4372, + "over_baseline": 2532, + "gzip_over_baseline": 900 }, { "program": "chacha20_poly1305_original_sodium", "file": "wasm", - "bytes": 27506, - "gzip": 12682, - "over_baseline": 7315, - "gzip_over_baseline": 3166 + "bytes": 32176, + "gzip": 14746, + "over_baseline": 11809, + "gzip_over_baseline": 5138 }, { "program": "chacha20_poly1305_sodium", "file": "js", - "bytes": 11879, - "gzip": 4226, - "over_baseline": 2122, - "gzip_over_baseline": 754 + "bytes": 12280, + "gzip": 4368, + "over_baseline": 2523, + "gzip_over_baseline": 896 }, { "program": "chacha20_poly1305_sodium", "file": "wasm", - "bytes": 27589, - "gzip": 12742, - "over_baseline": 7398, - "gzip_over_baseline": 3226 + "bytes": 32262, + "gzip": 14791, + "over_baseline": 11895, + "gzip_over_baseline": 5183 + }, + { + "program": "chacha20_sodium", + "file": "js", + "bytes": 12271, + "gzip": 4359, + "over_baseline": 2514, + "gzip_over_baseline": 887 + }, + { + "program": "chacha20_sodium", + "file": "wasm", + "bytes": 30084, + "gzip": 13709, + "over_baseline": 9717, + "gzip_over_baseline": 4101 }, { "program": "ed25519_sodium", "file": "js", - "bytes": 11870, - "gzip": 4221, - "over_baseline": 2113, - "gzip_over_baseline": 749 + "bytes": 12273, + "gzip": 4361, + "over_baseline": 2516, + "gzip_over_baseline": 889 }, { "program": "ed25519_sodium", "file": "wasm", - "bytes": 90713, - "gzip": 54663, - "over_baseline": 70522, - "gzip_over_baseline": 45147 + "bytes": 92988, + "gzip": 55630, + "over_baseline": 72621, + "gzip_over_baseline": 46022 }, { "program": "gcm_bearssl", @@ -117,10 +149,10 @@ { "program": "gcm_bearssl", "file": "wasm", - "bytes": 34398, - "gzip": 14938, - "over_baseline": 14207, - "gzip_over_baseline": 5422 + "bytes": 34924, + "gzip": 15159, + "over_baseline": 14557, + "gzip_over_baseline": 5551 }, { "program": "p256_bearssl", @@ -133,10 +165,10 @@ { "program": "p256_bearssl", "file": "wasm", - "bytes": 46772, - "gzip": 21310, - "over_baseline": 26581, - "gzip_over_baseline": 11794 + "bytes": 48617, + "gzip": 21995, + "over_baseline": 28250, + "gzip_over_baseline": 12387 }, { "program": "p256_bearssl_ecdh_x", @@ -149,10 +181,10 @@ { "program": "p256_bearssl_ecdh_x", "file": "wasm", - "bytes": 46760, - "gzip": 19152, - "over_baseline": 26569, - "gzip_over_baseline": 9636 + "bytes": 46940, + "gzip": 19250, + "over_baseline": 26573, + "gzip_over_baseline": 9642 }, { "program": "p256_bearssl_verify_ecdsa", @@ -165,138 +197,154 @@ { "program": "p256_bearssl_verify_ecdsa", "file": "wasm", - "bytes": 55164, - "gzip": 24103, - "over_baseline": 34973, - "gzip_over_baseline": 14587 + "bytes": 57577, + "gzip": 24842, + "over_baseline": 37210, + "gzip_over_baseline": 15234 + }, + { + "program": "poly1305_sodium", + "file": "js", + "bytes": 12271, + "gzip": 4359, + "over_baseline": 2514, + "gzip_over_baseline": 887 + }, + { + "program": "poly1305_sodium", + "file": "wasm", + "bytes": 27925, + "gzip": 13064, + "over_baseline": 7558, + "gzip_over_baseline": 3456 }, { "program": "secp256k1_ellswift_secp256k1", "file": "js", - "bytes": 10109, - "gzip": 3595, - "over_baseline": 352, - "gzip_over_baseline": 123 + "bytes": 10869, + "gzip": 3881, + "over_baseline": 1112, + "gzip_over_baseline": 409 }, { "program": "secp256k1_ellswift_secp256k1", "file": "wasm", - "bytes": 249284, - "gzip": 91443, - "over_baseline": 229093, - "gzip_over_baseline": 81927 + "bytes": 249476, + "gzip": 91351, + "over_baseline": 229109, + "gzip_over_baseline": 81743 }, { "program": "secp256k1_musig_secp256k1", "file": "js", - "bytes": 10106, - "gzip": 3593, - "over_baseline": 349, - "gzip_over_baseline": 121 + "bytes": 10866, + "gzip": 3879, + "over_baseline": 1109, + "gzip_over_baseline": 407 }, { "program": "secp256k1_musig_secp256k1", "file": "wasm", - "bytes": 270560, - "gzip": 100089, - "over_baseline": 250369, - "gzip_over_baseline": 90573 + "bytes": 221866, + "gzip": 85504, + "over_baseline": 201499, + "gzip_over_baseline": 75896 }, { "program": "secp256k1_secp256k1", "file": "js", - "bytes": 10100, - "gzip": 3588, - "over_baseline": 343, - "gzip_over_baseline": 116 + "bytes": 10860, + "gzip": 3874, + "over_baseline": 1103, + "gzip_over_baseline": 402 }, { "program": "secp256k1_secp256k1", "file": "wasm", - "bytes": 105675, - "gzip": 43471, - "over_baseline": 85484, - "gzip_over_baseline": 33955 + "bytes": 106005, + "gzip": 43443, + "over_baseline": 85638, + "gzip_over_baseline": 33835 }, { "program": "secp256k1_secp256k1_ecdh_x", "file": "js", - "bytes": 10107, - "gzip": 3593, - "over_baseline": 350, - "gzip_over_baseline": 121 + "bytes": 10867, + "gzip": 3879, + "over_baseline": 1110, + "gzip_over_baseline": 407 }, { "program": "secp256k1_secp256k1_ecdh_x", "file": "wasm", - "bytes": 195099, - "gzip": 72442, - "over_baseline": 174908, - "gzip_over_baseline": 62926 + "bytes": 140712, + "gzip": 55246, + "over_baseline": 120345, + "gzip_over_baseline": 45638 }, { "program": "secp256k1_secp256k1_recover", "file": "js", - "bytes": 10108, - "gzip": 3594, - "over_baseline": 351, - "gzip_over_baseline": 122 + "bytes": 10868, + "gzip": 3880, + "over_baseline": 1111, + "gzip_over_baseline": 408 }, { "program": "secp256k1_secp256k1_recover", "file": "wasm", - "bytes": 223279, - "gzip": 81062, - "over_baseline": 203088, - "gzip_over_baseline": 71546 + "bytes": 224370, + "gzip": 83449, + "over_baseline": 204003, + "gzip_over_baseline": 73841 }, { "program": "secp256k1_silent_payments_secp256k1", "file": "js", - "bytes": 10116, - "gzip": 3600, - "over_baseline": 359, - "gzip_over_baseline": 128 + "bytes": 10876, + "gzip": 3886, + "over_baseline": 1119, + "gzip_over_baseline": 414 }, { "program": "secp256k1_silent_payments_secp256k1", "file": "wasm", - "bytes": 235439, - "gzip": 87296, - "over_baseline": 215248, - "gzip_over_baseline": 77780 + "bytes": 186928, + "gzip": 72199, + "over_baseline": 166561, + "gzip_over_baseline": 62591 }, { "program": "x25519_sodium", "file": "js", - "bytes": 11870, - "gzip": 4221, - "over_baseline": 2113, - "gzip_over_baseline": 749 + "bytes": 12272, + "gzip": 4360, + "over_baseline": 2515, + "gzip_over_baseline": 888 }, { "program": "x25519_sodium", "file": "wasm", - "bytes": 70552, - "gzip": 46187, - "over_baseline": 50361, - "gzip_over_baseline": 36671 + "bytes": 78325, + "gzip": 49075, + "over_baseline": 57958, + "gzip_over_baseline": 39467 }, { "program": "xchacha20_poly1305_sodium", "file": "js", - "bytes": 11880, - "gzip": 4227, - "over_baseline": 2123, - "gzip_over_baseline": 755 + "bytes": 12281, + "gzip": 4369, + "over_baseline": 2524, + "gzip_over_baseline": 897 }, { "program": "xchacha20_poly1305_sodium", "file": "wasm", - "bytes": 28216, - "gzip": 13072, - "over_baseline": 8025, - "gzip_over_baseline": 3556 + "bytes": 32889, + "gzip": 15127, + "over_baseline": 12522, + "gzip_over_baseline": 5519 } ] }, @@ -305,41 +353,57 @@ "target": "native", "toolset": "clang-21", "baseline": "baseline", - "date": "2026-11-21", + "date": "2026-12-05", "host": "Darwin arm64", "format": "Mach-O", "programs": [ { "program": "aes_block_openssl", "file": "executable", - "bytes": 3296184, - "gzip": 1747266, - "over_baseline": 3244936, - "gzip_over_baseline": 1744087 + "bytes": 3296136, + "gzip": 1747556, + "over_baseline": 3244888, + "gzip_over_baseline": 1744292 }, { "program": "baseline", "file": "executable", "bytes": 51248, - "gzip": 3179, + "gzip": 3264, "over_baseline": 0, "gzip_over_baseline": 0 }, + { + "program": "chacha20_openssl", + "file": "executable", + "bytes": 3296136, + "gzip": 1747799, + "over_baseline": 3244888, + "gzip_over_baseline": 1744535 + }, { "program": "chacha20_poly1305_openssl", "file": "executable", - "bytes": 3296192, - "gzip": 1747759, - "over_baseline": 3244944, - "gzip_over_baseline": 1744580 + "bytes": 3296144, + "gzip": 1747869, + "over_baseline": 3244896, + "gzip_over_baseline": 1744605 }, { "program": "gcm_openssl", "file": "executable", - "bytes": 3296176, - "gzip": 1747998, - "over_baseline": 3244928, - "gzip_over_baseline": 1744819 + "bytes": 3296128, + "gzip": 1748550, + "over_baseline": 3244880, + "gzip_over_baseline": 1745286 + }, + { + "program": "poly1305_openssl", + "file": "executable", + "bytes": 3296728, + "gzip": 1746928, + "over_baseline": 3245480, + "gzip_over_baseline": 1743664 } ] }, @@ -348,153 +412,177 @@ "target": "native", "toolset": "clang-21", "baseline": "baseline", - "date": "2026-11-21", + "date": "2026-12-05", "host": "Darwin arm64", "format": "Mach-O", "programs": [ { "program": "aes_block_ctaes", "file": "executable", - "bytes": 52264, - "gzip": 7243, - "over_baseline": 1016, - "gzip_over_baseline": 4064 + "bytes": 52216, + "gzip": 7661, + "over_baseline": 968, + "gzip_over_baseline": 4397 }, { "program": "baseline", "file": "executable", "bytes": 51248, - "gzip": 3179, + "gzip": 3264, "over_baseline": 0, "gzip_over_baseline": 0 }, + { + "program": "chacha20_bearssl", + "file": "executable", + "bytes": 52280, + "gzip": 6784, + "over_baseline": 1032, + "gzip_over_baseline": 3520 + }, { "program": "chacha20_poly1305_bearssl", "file": "executable", - "bytes": 52512, - "gzip": 9236, - "over_baseline": 1264, - "gzip_over_baseline": 6057 + "bytes": 52464, + "gzip": 9474, + "over_baseline": 1216, + "gzip_over_baseline": 6210 }, { "program": "chacha20_poly1305_original_sodium", "file": "executable", - "bytes": 87224, - "gzip": 25347, - "over_baseline": 35976, - "gzip_over_baseline": 22168 + "bytes": 87192, + "gzip": 25571, + "over_baseline": 35944, + "gzip_over_baseline": 22307 }, { "program": "chacha20_poly1305_sodium", "file": "executable", - "bytes": 87232, - "gzip": 25452, - "over_baseline": 35984, - "gzip_over_baseline": 22273 + "bytes": 87200, + "gzip": 25673, + "over_baseline": 35952, + "gzip_over_baseline": 22409 + }, + { + "program": "chacha20_sodium", + "file": "executable", + "bytes": 87016, + "gzip": 24222, + "over_baseline": 35768, + "gzip_over_baseline": 20958 }, { "program": "ed25519_sodium", "file": "executable", - "bytes": 138248, - "gzip": 68105, - "over_baseline": 87000, - "gzip_over_baseline": 64926 + "bytes": 138216, + "gzip": 68384, + "over_baseline": 86968, + "gzip_over_baseline": 65120 }, { "program": "gcm_bearssl", "file": "executable", - "bytes": 52928, - "gzip": 11704, - "over_baseline": 1680, - "gzip_over_baseline": 8525 + "bytes": 69392, + "gzip": 12530, + "over_baseline": 18144, + "gzip_over_baseline": 9266 }, { "program": "p256_bearssl", "file": "executable", - "bytes": 103016, - "gzip": 32081, - "over_baseline": 51768, - "gzip_over_baseline": 28902 + "bytes": 102984, + "gzip": 32805, + "over_baseline": 51736, + "gzip_over_baseline": 29541 }, { "program": "p256_bearssl_ecdh_x", "file": "executable", "bytes": 85560, - "gzip": 25817, + "gzip": 25983, "over_baseline": 34312, - "gzip_over_baseline": 22638 + "gzip_over_baseline": 22719 }, { "program": "p256_bearssl_verify_ecdsa", "file": "executable", - "bytes": 103040, - "gzip": 32864, - "over_baseline": 51792, - "gzip_over_baseline": 29685 + "bytes": 103008, + "gzip": 33757, + "over_baseline": 51760, + "gzip_over_baseline": 30493 + }, + { + "program": "poly1305_sodium", + "file": "executable", + "bytes": 87592, + "gzip": 23171, + "over_baseline": 36344, + "gzip_over_baseline": 19907 }, { "program": "secp256k1_ellswift_secp256k1", "file": "executable", - "bytes": 185352, - "gzip": 101889, - "over_baseline": 134104, - "gzip_over_baseline": 98710 + "bytes": 185304, + "gzip": 102193, + "over_baseline": 134056, + "gzip_over_baseline": 98929 }, { "program": "secp256k1_musig_secp256k1", "file": "executable", - "bytes": 1258816, - "gzip": 1171203, - "over_baseline": 1207568, - "gzip_over_baseline": 1168024 + "bytes": 1242240, + "gzip": 1158265, + "over_baseline": 1190992, + "gzip_over_baseline": 1155001 }, { "program": "secp256k1_secp256k1", "file": "executable", - "bytes": 119208, - "gzip": 59602, - "over_baseline": 67960, - "gzip_over_baseline": 56423 + "bytes": 119160, + "gzip": 59943, + "over_baseline": 67912, + "gzip_over_baseline": 56679 }, { "program": "secp256k1_secp256k1_ecdh_x", "file": "executable", - "bytes": 168960, - "gzip": 85531, - "over_baseline": 117712, - "gzip_over_baseline": 82352 + "bytes": 135776, + "gzip": 71063, + "over_baseline": 84528, + "gzip_over_baseline": 67799 }, { "program": "secp256k1_secp256k1_recover", "file": "executable", - "bytes": 1225696, - "gzip": 1150155, - "over_baseline": 1174448, - "gzip_over_baseline": 1146976 + "bytes": 1242224, + "gzip": 1151110, + "over_baseline": 1190976, + "gzip_over_baseline": 1147846 }, { "program": "secp256k1_silent_payments_secp256k1", "file": "executable", - "bytes": 1242248, - "gzip": 1157877, - "over_baseline": 1191000, - "gzip_over_baseline": 1154698 + "bytes": 1225656, + "gzip": 1144460, + "over_baseline": 1174408, + "gzip_over_baseline": 1141196 }, { "program": "x25519_sodium", "file": "executable", - "bytes": 136600, - "gzip": 61348, - "over_baseline": 85352, - "gzip_over_baseline": 58169 + "bytes": 136568, + "gzip": 62079, + "over_baseline": 85320, + "gzip_over_baseline": 58815 }, { "program": "xchacha20_poly1305_sodium", "file": "executable", - "bytes": 87264, - "gzip": 25741, - "over_baseline": 36016, - "gzip_over_baseline": 22562 + "bytes": 87216, + "gzip": 25962, + "over_baseline": 35968, + "gzip_over_baseline": 22698 } ] }, @@ -503,41 +591,57 @@ "target": "wasip2", "toolset": "clang-wasip2", "baseline": "baseline", - "date": "2026-11-21", + "date": "2026-12-05", "host": "Darwin arm64", "format": "WebAssembly", "programs": [ { "program": "aes_block_openssl", "file": "wasm", - "bytes": 2324689, - "gzip": 777850, - "over_baseline": 2260267, - "gzip_over_baseline": 753446 + "bytes": 2324866, + "gzip": 778023, + "over_baseline": 2260268, + "gzip_over_baseline": 753541 }, { "program": "baseline", "file": "wasm", - "bytes": 64422, - "gzip": 24404, + "bytes": 64598, + "gzip": 24482, "over_baseline": 0, "gzip_over_baseline": 0 }, + { + "program": "chacha20_openssl", + "file": "wasm", + "bytes": 2325374, + "gzip": 778161, + "over_baseline": 2260776, + "gzip_over_baseline": 753679 + }, { "program": "chacha20_poly1305_openssl", "file": "wasm", - "bytes": 2325726, - "gzip": 778409, - "over_baseline": 2261304, - "gzip_over_baseline": 754005 + "bytes": 2325978, + "gzip": 778468, + "over_baseline": 2261380, + "gzip_over_baseline": 753986 }, { "program": "gcm_openssl", "file": "wasm", - "bytes": 2326219, - "gzip": 778612, - "over_baseline": 2261797, - "gzip_over_baseline": 754208 + "bytes": 2327386, + "gzip": 778934, + "over_baseline": 2262788, + "gzip_over_baseline": 754452 + }, + { + "program": "poly1305_openssl", + "file": "wasm", + "bytes": 2322403, + "gzip": 776697, + "over_baseline": 2257805, + "gzip_over_baseline": 752215 } ] }, @@ -546,153 +650,177 @@ "target": "wasip2", "toolset": "clang-wasip2", "baseline": "baseline", - "date": "2026-11-21", + "date": "2026-12-05", "host": "Darwin arm64", "format": "WebAssembly", "programs": [ { "program": "aes_block_ctaes", "file": "wasm", - "bytes": 71531, - "gzip": 26842, + "bytes": 71707, + "gzip": 26915, "over_baseline": 7109, - "gzip_over_baseline": 2438 + "gzip_over_baseline": 2433 }, { "program": "baseline", "file": "wasm", - "bytes": 64422, - "gzip": 24404, + "bytes": 64598, + "gzip": 24482, "over_baseline": 0, "gzip_over_baseline": 0 }, + { + "program": "chacha20_bearssl", + "file": "wasm", + "bytes": 69981, + "gzip": 26218, + "over_baseline": 5383, + "gzip_over_baseline": 1736 + }, { "program": "chacha20_poly1305_bearssl", "file": "wasm", - "bytes": 74701, - "gzip": 28243, - "over_baseline": 10279, - "gzip_over_baseline": 3839 + "bytes": 74995, + "gzip": 28319, + "over_baseline": 10397, + "gzip_over_baseline": 3837 }, { "program": "chacha20_poly1305_original_sodium", "file": "wasm", - "bytes": 78133, - "gzip": 29222, - "over_baseline": 13711, - "gzip_over_baseline": 4818 + "bytes": 78427, + "gzip": 29296, + "over_baseline": 13829, + "gzip_over_baseline": 4814 }, { "program": "chacha20_poly1305_sodium", "file": "wasm", - "bytes": 78210, - "gzip": 29267, - "over_baseline": 13788, - "gzip_over_baseline": 4863 + "bytes": 78504, + "gzip": 29334, + "over_baseline": 13906, + "gzip_over_baseline": 4852 + }, + { + "program": "chacha20_sodium", + "file": "wasm", + "bytes": 74562, + "gzip": 27826, + "over_baseline": 9964, + "gzip_over_baseline": 3344 }, { "program": "ed25519_sodium", "file": "wasm", - "bytes": 139327, - "gzip": 69066, - "over_baseline": 74905, - "gzip_over_baseline": 44662 + "bytes": 139526, + "gzip": 69171, + "over_baseline": 74928, + "gzip_over_baseline": 44689 }, { "program": "gcm_bearssl", "file": "wasm", - "bytes": 81911, - "gzip": 30388, - "over_baseline": 17489, - "gzip_over_baseline": 5984 + "bytes": 82591, + "gzip": 30558, + "over_baseline": 17993, + "gzip_over_baseline": 6076 }, { "program": "p256_bearssl", "file": "wasm", - "bytes": 103537, - "gzip": 39162, - "over_baseline": 39115, - "gzip_over_baseline": 14758 + "bytes": 105745, + "gzip": 39894, + "over_baseline": 41147, + "gzip_over_baseline": 15412 }, { "program": "p256_bearssl_ecdh_x", "file": "wasm", - "bytes": 95799, - "gzip": 34682, - "over_baseline": 31377, - "gzip_over_baseline": 10278 + "bytes": 95997, + "gzip": 34764, + "over_baseline": 31399, + "gzip_over_baseline": 10282 }, { "program": "p256_bearssl_verify_ecdsa", "file": "wasm", - "bytes": 105763, - "gzip": 39944, - "over_baseline": 41341, - "gzip_over_baseline": 15540 + "bytes": 108788, + "gzip": 40773, + "over_baseline": 44190, + "gzip_over_baseline": 16291 + }, + { + "program": "poly1305_sodium", + "file": "wasm", + "bytes": 71792, + "gzip": 27257, + "over_baseline": 7194, + "gzip_over_baseline": 2775 }, { "program": "secp256k1_ellswift_secp256k1", "file": "wasm", - "bytes": 336841, - "gzip": 128107, - "over_baseline": 272419, - "gzip_over_baseline": 103703 + "bytes": 336638, + "gzip": 128180, + "over_baseline": 272040, + "gzip_over_baseline": 103698 }, { "program": "secp256k1_musig_secp256k1", "file": "wasm", - "bytes": 1417621, - "gzip": 1186030, - "over_baseline": 1353199, - "gzip_over_baseline": 1161626 + "bytes": 1359755, + "gzip": 1171452, + "over_baseline": 1295157, + "gzip_over_baseline": 1146970 }, { "program": "secp256k1_secp256k1", "file": "wasm", - "bytes": 180219, - "gzip": 79655, - "over_baseline": 115797, - "gzip_over_baseline": 55251 + "bytes": 180197, + "gzip": 79833, + "over_baseline": 115599, + "gzip_over_baseline": 55351 }, { "program": "secp256k1_secp256k1_ecdh_x", "file": "wasm", - "bytes": 278726, - "gzip": 108506, - "over_baseline": 214304, - "gzip_over_baseline": 84102 + "bytes": 218811, + "gzip": 92924, + "over_baseline": 154213, + "gzip_over_baseline": 68442 }, { "program": "secp256k1_secp256k1_recover", "file": "wasm", - "bytes": 1357572, - "gzip": 1166931, - "over_baseline": 1293150, - "gzip_over_baseline": 1142527 + "bytes": 1358724, + "gzip": 1167724, + "over_baseline": 1294126, + "gzip_over_baseline": 1143242 }, { "program": "secp256k1_silent_payments_secp256k1", "file": "wasm", - "bytes": 1382735, - "gzip": 1172149, - "over_baseline": 1318313, - "gzip_over_baseline": 1147745 + "bytes": 1325141, + "gzip": 1155877, + "over_baseline": 1260543, + "gzip_over_baseline": 1131395 }, { "program": "x25519_sodium", "file": "wasm", - "bytes": 123046, - "gzip": 62389, - "over_baseline": 58624, - "gzip_over_baseline": 37985 + "bytes": 127133, + "gzip": 63289, + "over_baseline": 62535, + "gzip_over_baseline": 38807 }, { "program": "xchacha20_poly1305_sodium", "file": "wasm", - "bytes": 78951, - "gzip": 29602, - "over_baseline": 14529, - "gzip_over_baseline": 5198 + "bytes": 79245, + "gzip": 29677, + "over_baseline": 14647, + "gzip_over_baseline": 5195 } ] }, @@ -701,41 +829,57 @@ "target": "wasip3", "toolset": "clang-wasip3", "baseline": "baseline", - "date": "2026-11-21", + "date": "2026-12-05", "host": "Darwin arm64", "format": "WebAssembly", "programs": [ { "program": "aes_block_openssl", "file": "wasm", - "bytes": 2339178, - "gzip": 782149, - "over_baseline": 2265118, - "gzip_over_baseline": 754717 + "bytes": 2339355, + "gzip": 782264, + "over_baseline": 2265119, + "gzip_over_baseline": 754749 }, { "program": "baseline", "file": "wasm", - "bytes": 74060, - "gzip": 27432, + "bytes": 74236, + "gzip": 27515, "over_baseline": 0, "gzip_over_baseline": 0 }, + { + "program": "chacha20_openssl", + "file": "wasm", + "bytes": 2339863, + "gzip": 782349, + "over_baseline": 2265627, + "gzip_over_baseline": 754834 + }, { "program": "chacha20_poly1305_openssl", "file": "wasm", - "bytes": 2340239, - "gzip": 782536, - "over_baseline": 2266179, - "gzip_over_baseline": 755104 + "bytes": 2340491, + "gzip": 782618, + "over_baseline": 2266255, + "gzip_over_baseline": 755103 }, { "program": "gcm_openssl", "file": "wasm", - "bytes": 2340732, - "gzip": 782688, - "over_baseline": 2266672, - "gzip_over_baseline": 755256 + "bytes": 2341899, + "gzip": 783024, + "over_baseline": 2267663, + "gzip_over_baseline": 755509 + }, + { + "program": "poly1305_openssl", + "file": "wasm", + "bytes": 2336891, + "gzip": 781340, + "over_baseline": 2262655, + "gzip_over_baseline": 753825 } ] }, @@ -744,156 +888,180 @@ "target": "wasip3", "toolset": "clang-wasip3", "baseline": "baseline", - "date": "2026-11-21", + "date": "2026-12-05", "host": "Darwin arm64", "format": "WebAssembly", "programs": [ { "program": "aes_block_ctaes", "file": "wasm", - "bytes": 81169, - "gzip": 29823, + "bytes": 81345, + "gzip": 29890, "over_baseline": 7109, - "gzip_over_baseline": 2391 + "gzip_over_baseline": 2375 }, { "program": "baseline", "file": "wasm", - "bytes": 74060, - "gzip": 27432, + "bytes": 74236, + "gzip": 27515, "over_baseline": 0, "gzip_over_baseline": 0 }, + { + "program": "chacha20_bearssl", + "file": "wasm", + "bytes": 79619, + "gzip": 29264, + "over_baseline": 5383, + "gzip_over_baseline": 1749 + }, { "program": "chacha20_poly1305_bearssl", "file": "wasm", - "bytes": 84349, - "gzip": 31258, - "over_baseline": 10289, - "gzip_over_baseline": 3826 + "bytes": 84659, + "gzip": 31343, + "over_baseline": 10423, + "gzip_over_baseline": 3828 }, { "program": "chacha20_poly1305_original_sodium", "file": "wasm", - "bytes": 87980, - "gzip": 32329, - "over_baseline": 13920, - "gzip_over_baseline": 4897 + "bytes": 88274, + "gzip": 32400, + "over_baseline": 14038, + "gzip_over_baseline": 4885 }, { "program": "chacha20_poly1305_sodium", "file": "wasm", - "bytes": 88057, - "gzip": 32361, - "over_baseline": 13997, - "gzip_over_baseline": 4929 + "bytes": 88351, + "gzip": 32439, + "over_baseline": 14115, + "gzip_over_baseline": 4924 + }, + { + "program": "chacha20_sodium", + "file": "wasm", + "bytes": 84412, + "gzip": 30908, + "over_baseline": 10176, + "gzip_over_baseline": 3393 }, { "program": "ed25519_sodium", "file": "wasm", - "bytes": 149455, - "gzip": 72381, - "over_baseline": 75395, - "gzip_over_baseline": 44949 + "bytes": 149654, + "gzip": 72486, + "over_baseline": 75418, + "gzip_over_baseline": 44971 }, { "program": "gcm_bearssl", "file": "wasm", - "bytes": 91588, - "gzip": 33343, - "over_baseline": 17528, - "gzip_over_baseline": 5911 + "bytes": 92252, + "gzip": 33516, + "over_baseline": 18016, + "gzip_over_baseline": 6001 }, { "program": "p256_bearssl", "file": "wasm", - "bytes": 113187, - "gzip": 42274, - "over_baseline": 39127, - "gzip_over_baseline": 14842 + "bytes": 115396, + "gzip": 43009, + "over_baseline": 41160, + "gzip_over_baseline": 15494 }, { "program": "p256_bearssl_ecdh_x", "file": "wasm", - "bytes": 105451, - "gzip": 37830, - "over_baseline": 31391, - "gzip_over_baseline": 10398 + "bytes": 105649, + "gzip": 37912, + "over_baseline": 31413, + "gzip_over_baseline": 10397 }, { "program": "p256_bearssl_verify_ecdsa", "file": "wasm", - "bytes": 115420, - "gzip": 43059, - "over_baseline": 41360, - "gzip_over_baseline": 15627 + "bytes": 118438, + "gzip": 43893, + "over_baseline": 44202, + "gzip_over_baseline": 16378 + }, + { + "program": "poly1305_sodium", + "file": "wasm", + "bytes": 81636, + "gzip": 30344, + "over_baseline": 7400, + "gzip_over_baseline": 2829 }, { "program": "secp256k1_ellswift_secp256k1", "file": "wasm", - "bytes": 348232, - "gzip": 131827, - "over_baseline": 274172, - "gzip_over_baseline": 104395 + "bytes": 347952, + "gzip": 131883, + "over_baseline": 273716, + "gzip_over_baseline": 104368 }, { "program": "secp256k1_musig_secp256k1", "file": "wasm", - "bytes": 1428661, - "gzip": 1189992, - "over_baseline": 1354601, - "gzip_over_baseline": 1162560 + "bytes": 1370723, + "gzip": 1174907, + "over_baseline": 1296487, + "gzip_over_baseline": 1147392 }, { "program": "secp256k1_secp256k1", "file": "wasm", - "bytes": 191605, - "gzip": 83456, - "over_baseline": 117545, - "gzip_over_baseline": 56024 + "bytes": 191497, + "gzip": 83680, + "over_baseline": 117261, + "gzip_over_baseline": 56165 }, { "program": "secp256k1_secp256k1_ecdh_x", "file": "wasm", - "bytes": 290109, - "gzip": 112377, - "over_baseline": 216049, - "gzip_over_baseline": 84945 + "bytes": 230123, + "gzip": 96511, + "over_baseline": 155887, + "gzip_over_baseline": 68996 }, { "program": "secp256k1_secp256k1_recover", "file": "wasm", - "bytes": 1368952, - "gzip": 1170584, - "over_baseline": 1294892, - "gzip_over_baseline": 1143152 + "bytes": 1370030, + "gzip": 1171230, + "over_baseline": 1295794, + "gzip_over_baseline": 1143715 }, { "program": "secp256k1_silent_payments_secp256k1", "file": "wasm", - "bytes": 1394173, - "gzip": 1175682, - "over_baseline": 1320113, - "gzip_over_baseline": 1148250 + "bytes": 1336478, + "gzip": 1159407, + "over_baseline": 1262242, + "gzip_over_baseline": 1131892 }, { "program": "x25519_sodium", "file": "wasm", - "bytes": 132898, - "gzip": 65927, - "over_baseline": 58838, - "gzip_over_baseline": 38495 + "bytes": 137001, + "gzip": 66900, + "over_baseline": 62765, + "gzip_over_baseline": 39385 }, { "program": "xchacha20_poly1305_sodium", "file": "wasm", - "bytes": 88799, - "gzip": 32691, - "over_baseline": 14739, - "gzip_over_baseline": 5259 + "bytes": 89093, + "gzip": 32762, + "over_baseline": 14857, + "gzip_over_baseline": 5247 } ] } ], - "digest": "cf96aa3224bc57d15f021874bd0507c8ee8a1eac2069bed08560e032289e6426" + "digest": "16989f935d99a8b4425b31ec904fe6cdb8e96fdd1d9d640fcefe9e38d5199b0a" } diff --git a/doc/unauthenticated_encryption.adoc b/doc/unauthenticated_encryption.adoc new file mode 100644 index 0000000..b657b1e --- /dev/null +++ b/doc/unauthenticated_encryption.adoc @@ -0,0 +1,72 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +[#crypto-unauthenticated-encryption] +== Unauthenticated encryption: `webcpp::crypto::unauthenticated_encryption` + +*Unauthenticated encryption* hides data and does nothing else: no tag, no check, +and a change made to the ciphertext on the way changes the plaintext the reader +gets, bit for bit +(link:https://en.wikipedia.org/wiki/Malleability_(cryptography)[Wikipedia, +malleability]). The namespace `webcpp::crypto::unauthenticated_encryption` holds +the contract of a raw stream cipher, `stream_cipher`, and its free forms; the +algorithm, ChaCha20, is in `ciphers` under its name (<>), as +the AEADs are. + +*When to use it.* For a protocol that brings its own authentication and fixes +its own construction over a raw stream cipher, as Nostr's encrypted payloads +do: NIP-44 encrypts with ChaCha20 from counter 0 and authenticates the nonce and +the ciphertext with HMAC-SHA256, which the reader checks first +(link:https://github.com/nostr-protocol/nips/blob/master/44.md[NIP-44]; +<>). Never for a program's own messages, files or records: +those take authenticated encryption, `secret_key_encryption` and the AEADs of +`ciphers`, the normal path (<>), which seals and +checks in one call and cannot be misused this way. The namespace is named by +what it lacks, so that the name says it at every call. + +include::generated/namespace-unauthenticated_encryption.adoc[] + +[#crypto-stream-cipher-contract] +=== The stream cipher contract: `unauthenticated_encryption::stream_cipher` + +``, which +`ciphers/chacha20.hpp` includes and which needs no backend, declares, in namespace +`webcpp::crypto::unauthenticated_encryption`: + +* `stream_cipher`, what every raw stream cipher is: `C::key_size`, +`C::nonce_size` and `C::block_size`; `typename C::counter_type`, a standard +unsigned integer of at most 64 bits; `C::from_key(key_bytes)` giving +`result`; `c.apply_keystream(nonce, data, initial_counter)` giving +`result`, the keystream XORed into the data in place. The concept reads +the algorithm's own shape, never ChaCha20's 12-byte nonce, 64-byte block and +32-bit counter, so that a stream cipher of another shape works through the same +code; +* `apply_keystream(cipher, nonce, data, initial_counter)`, constrained by +`stream_cipher`, which calls the member and gives its results and its errors; +it names no backend. + +`` adds its asynchronous form in the same namespace, +`async_apply_keystream(executor, cipher, nonce, data, initial_counter, token)`, +completing with `void(error_code)`, and `crypto::async_from_key(executor, +key, token)` makes a stream cipher, completing with `void(error_code, C)`. Each +calls the cipher's own asynchronous member where it has one; for a stream cipher +without them, each posts the synchronous call, the empty object of an error +completion made by the type's `noexcept` default constructor (public, or +private with `webcpp::crypto::detail::async_access` a friend). On the browser's +backend no form of ChaCha20 runs (<>). + +No AEAD, box or block cipher is a `stream_cipher`, and `ciphers::chacha20` is +neither an `aead::cipher` nor an `authenticated_box`: a raw stream cipher given +where authenticated encryption is expected does not compile. A function written +against the concept serves every stream cipher, as this check of the library's +own tests does: + +[source,cpp] +---- +include::{library-root}/test/stream_cipher_concepts_test.cpp[tag=generic,indent=0] +---- + +include::generated/backends-stream_cipher.adoc[] diff --git a/example/Jamfile b/example/Jamfile index c2ca3ee..13f1ef8 100644 --- a/example/Jamfile +++ b/example/Jamfile @@ -213,3 +213,12 @@ webcpp.example async_sign.cpp : /webcpp/asio//asio # asynchronous member and its free form, on the default; the four agree. webcpp.example four_forms.cpp : /webcpp/asio//asio /webcpp/crypto//p256-default ; + +# The guide's raw ChaCha20 program: RFC 8439 section 2.4.2's ciphertext in +# hex, the plaintext back, and counter_overflow at the counter's end, on the +# family's default. +webcpp.example chacha20_keystream.cpp : /webcpp/crypto//chacha20-default ; + +# The guide's Poly1305 program: RFC 8439 section 2.5.2's tag, verify +# accepting it and refusing a flipped tag, on the family's default. +webcpp.example poly1305_one_time_tag.cpp : /webcpp/crypto//poly1305-default ; diff --git a/example/chacha20_keystream.cpp b/example/chacha20_keystream.cpp new file mode 100644 index 0000000..90d53cb --- /dev/null +++ b/example/chacha20_keystream.cpp @@ -0,0 +1,107 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// ChaCha20 alone, the raw stream cipher, which authenticates nothing: RFC 8439 section 2.4.2's +// key, nonce and initial counter 1 encrypt the section's 114-byte plaintext in place, the +// ciphertext printed in hex and compared with the RFC's; the same call at the same counter gives +// the plaintext back. Data that needs more blocks than the 32-bit counter has left is refused +// with counter_overflow and left untouched. A program's own messages take chacha20_poly1305: the +// raw cipher is for a protocol that fixes its own construction and authentication, as NIP-44 does. +// +// tag::program[] +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace crypto = webcpp::crypto; +using chacha20 = crypto::ciphers::chacha20<>; + +namespace { + +// The bytes of a hex text, as RFC 8439 prints its vectors. +template +std::array from_hex(std::string_view text) { + auto const nibble = [](char c) { return c <= '9' ? c - '0' : c - 'a' + 10; }; + std::array bytes{}; + for (std::size_t i = 0; i < N && (2 * i) + 1 < text.size(); ++i) { + bytes[i] = + static_cast((nibble(text[2 * i]) * 16) + nibble(text[(2 * i) + 1])); + } + return bytes; +} + +// Prints bytes in hex, 32 to a line. +void print_hex(char const* label, std::span bytes) { + std::printf("%s:", label); + for (std::size_t i = 0; i < bytes.size(); ++i) { + std::printf("%s%02x", i % 32 == 0 ? "\n " : "", static_cast(bytes[i])); + } + std::printf("\n"); +} + +} // namespace + +int main() { + // RFC 8439 section 2.4.2's key (the bytes 0 to 31), nonce and plaintext: public test data, + // never a real key. A real key is drawn for the protocol's use, and a nonce is never repeated + // under it. + std::array key{}; + for (std::size_t i = 0; i < key.size(); ++i) { + key[i] = static_cast(i); + } + auto const nonce = from_hex("000000000000004a00000000"); + auto const plaintext = from_hex<114>( + "4c616469657320616e642047656e746c656d656e206f662074686520636c617373206f66202739393a20" + "4966204920636f756c64206f6666657220796f75206f6e6c79206f6e652074697020666f722074686520" + "6675747572652c2073756e73637265656e20776f756c642062652069742e"); + auto const expected = from_hex<114>( + "6e2e359a2568f98041ba0728dd0d6981e97e7aec1d4360c20a27afccfd9fae0bf91b65c5524733ab8f593d" + "abcd62b3571639d624e65152ab8f530c359f0861d807ca0dbf500d6a6156a38e088a22b65e52bc514d16cc" + "f806818ce91ab77937365af90bbf74a35be6b40b8eedf2785e42874d"); + + auto cipher = chacha20::from_key(key); + if (!cipher) { + return 1; + } + // Encryption: the keystream from block counter 1 XORed into the data, in place. + auto data = plaintext; + if (!cipher->apply_keystream(nonce, data, 1)) { + return 1; + } + print_hex("ciphertext", data); + std::printf("RFC 8439 section 2.4.2's ciphertext: %s\n", data == expected ? "yes" : "no"); + // Decryption is the same call, at the same counter. + if (!cipher->apply_keystream(nonce, data, 1)) { + return 1; + } + print_hex("plaintext back", data); + std::printf("the plaintext given: %s\n", data == plaintext ? "yes" : "no"); + + // The counter's last block holds 64 bytes: a 65th needs a block past it. + std::array tail{}; + tail.fill(0x2a); + auto const kept = tail; + auto const last = std::numeric_limits::max(); + auto const refused = cipher->apply_keystream(nonce, tail, last); + if (refused) { + return 1; + } + std::string const reason = refused.error().message(); + std::printf("65 bytes from counter %lu: %s\n", static_cast(last), + reason.c_str()); + std::printf("the data untouched: %s\n", tail == kept ? "yes" : "no"); + return refused.error() == crypto::error::counter_overflow ? 0 : 1; +} + +// end::program[] diff --git a/example/chacha20_keystream.expected b/example/chacha20_keystream.expected new file mode 100644 index 0000000..58842ca --- /dev/null +++ b/example/chacha20_keystream.expected @@ -0,0 +1,14 @@ +ciphertext: + 6e2e359a2568f98041ba0728dd0d6981e97e7aec1d4360c20a27afccfd9fae0b + f91b65c5524733ab8f593dabcd62b3571639d624e65152ab8f530c359f0861d8 + 07ca0dbf500d6a6156a38e088a22b65e52bc514d16ccf806818ce91ab7793736 + 5af90bbf74a35be6b40b8eedf2785e42874d +RFC 8439 section 2.4.2's ciphertext: yes +plaintext back: + 4c616469657320616e642047656e746c656d656e206f662074686520636c6173 + 73206f66202739393a204966204920636f756c64206f6666657220796f75206f + 6e6c79206f6e652074697020666f7220746865206675747572652c2073756e73 + 637265656e20776f756c642062652069742e +the plaintext given: yes +65 bytes from counter 4294967295: the data needs more blocks than the stream cipher's counter has left after the initial counter +the data untouched: yes diff --git a/example/poly1305_one_time_tag.cpp b/example/poly1305_one_time_tag.cpp new file mode 100644 index 0000000..03c1bbe --- /dev/null +++ b/example/poly1305_one_time_tag.cpp @@ -0,0 +1,82 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Poly1305 alone, the one-time authenticator: RFC 8439 section 2.5.2's key and message give the +// section's 16-byte tag, printed in hex and compared with the RFC's; verify accepts the tag +// received and refuses it with one bit flipped. Its key authenticates this one message and never +// a second: a protocol derives a fresh key per message (RFC 8439's AEAD takes it from ChaCha20's +// keystream), and a key used for many messages takes webcpp::hash's HMAC. +// +// tag::program[] +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace crypto = webcpp::crypto; +using poly1305 = crypto::authenticators::poly1305<>; + +namespace { + +// The bytes of a hex text, as RFC 8439 prints its vectors. +template +std::array from_hex(std::string_view text) { + auto const nibble = [](char c) { return c <= '9' ? c - '0' : c - 'a' + 10; }; + std::array bytes{}; + for (std::size_t i = 0; i < N && (2 * i) + 1 < text.size(); ++i) { + bytes[i] = + static_cast((nibble(text[2 * i]) * 16) + nibble(text[(2 * i) + 1])); + } + return bytes; +} + +// What verify said: accepted, or the error's message. +void print_verdict(char const* label, boost::system::result const& verdict) { + std::string const said = verdict ? "accepted" : verdict.error().message(); + std::printf("verify, %s: %s\n", label, said.c_str()); +} + +} // namespace + +int main() { + // RFC 8439 section 2.5.2's one-time key, r then s, and message: public test data. A real + // key is derived for one message and wiped after it. + auto const key = from_hex( + "85d6be7857556d337f4452fe42d506a80103808afb0db2fd4abff6af4149f51b"); + std::string_view const text = "Cryptographic Forum Research Group"; + std::span const message(reinterpret_cast(text.data()), text.size()); + auto const expected = from_hex("a8061dc1305136c6c22b8baf0c0127a9"); + + // The tag: static, the key given to the call, no object kept. + auto const tag = poly1305::authenticate(key, message); + if (!tag) { + return 1; + } + std::printf("message: %.*s\ntag: ", static_cast(text.size()), text.data()); + for (std::uint8_t const byte : *tag) { + std::printf("%02x", static_cast(byte)); + } + std::printf("\nRFC 8439 section 2.5.2's tag: %s\n", + std::ranges::equal(*tag, expected) ? "yes" : "no"); + + // The receiver recomputes the tag and compares it in constant time. + print_verdict("the tag received", poly1305::verify(key, message, *tag)); + auto forged = *tag; + forged.data()[0] ^= 0x01U; + print_verdict("one bit of the tag flipped", poly1305::verify(key, message, forged)); + return 0; +} + +// end::program[] diff --git a/example/poly1305_one_time_tag.expected b/example/poly1305_one_time_tag.expected new file mode 100644 index 0000000..59055d5 --- /dev/null +++ b/example/poly1305_one_time_tag.expected @@ -0,0 +1,5 @@ +message: Cryptographic Forum Research Group +tag: a8061dc1305136c6c22b8baf0c0127a9 +RFC 8439 section 2.5.2's tag: yes +verify, the tag received: accepted +verify, one bit of the tag flipped: the authentication tag does not match diff --git a/include/webcpp/crypto.hpp b/include/webcpp/crypto.hpp index da73d39..26bdf73 100644 --- a/include/webcpp/crypto.hpp +++ b/include/webcpp/crypto.hpp @@ -10,10 +10,12 @@ with what it alone holds (libsecp256k1's secp256k1; libsodium's Ed25519 and X25519 with their key formats, `crypto_kx`, boxes and sealed boxes), `ciphers/aes256_gcm.hpp`, whose `aes128_gcm` and `aes256_gcm` name AES-GCM's default backend, `ciphers/aes_block.hpp`, whose `aes256<>` names the - block cipher's, `ciphers/chacha20_poly1305.hpp` and `secret_key_encryption/secretbox.hpp`, whose - AEADs and secret boxes name libsodium, `curves/p256.hpp` with its key formats, whose key pairs - name BearSSL, and `public_key_encryption/hpke.hpp`, RFC 9180's HPKE, whose suites take each - family's default: a program that does not link the default names another in the type, as + block cipher's, `ciphers/chacha20_poly1305.hpp`, `ciphers/chacha20.hpp`, + `authenticators/poly1305.hpp` and `secret_key_encryption/secretbox.hpp`, whose AEADs, raw + ChaCha20, Poly1305 and secret boxes name libsodium, + `curves/p256.hpp` with its key formats, whose key pairs name BearSSL, and + `public_key_encryption/hpke.hpp`, RFC 9180's HPKE, whose suites take each family's default: a + program that does not link the default names another in the type, as `ciphers::gcm>` on WebAssembly or `ciphers::chacha20_poly1305`, or, for the original ChaCha20-Poly1305, XChaCha20-Poly1305 and the secret boxes, which libsodium alone has, links libsodium. @@ -26,10 +28,12 @@ #include +#include #include #include #include #include +#include #include #include #include @@ -44,7 +48,9 @@ #include #include #include +#include #include +#include #include #include #include diff --git a/include/webcpp/crypto/async.hpp b/include/webcpp/crypto/async.hpp index 9b24105..f0e31e9 100644 --- a/include/webcpp/crypto/async.hpp +++ b/include/webcpp/crypto/async.hpp @@ -30,6 +30,14 @@ `secret_key_encryption::async_seal` and `async_open` for a secret box and a crypto_box. On a backend that completes by itself each stops the build, as its synchronous form does: only AES-GCM seals and opens there. + - ChaCha20, RFC 8439's raw stream cipher, which WebCrypto lacks, on a native backend: + `async_from_key` and `unauthenticated_encryption::async_apply_keystream`, over + `ciphers::basic_chacha20`; on a backend that completes by itself each stops the build, as + its synchronous form does. + - Poly1305, RFC 8439's one-time authenticator, which WebCrypto lacks, on a native backend: + `single_use_key_authentication::async_authenticate` and `async_verify`, over + `authenticators::poly1305`'s static `authenticate` and `verify`; on a backend that completes + by itself each stops the build, as its synchronous form does. - Ed25519: `async_from_secret` (a key pair from its seed), `async_generate`, `async_sign(executor, key_pair, crypto::signing_schemes::eddsa, message, token)` and `async_verify(executor, crypto::signing_schemes::eddsa, @@ -63,11 +71,14 @@ `C::async_from_key(executor, key_bytes, token)`, `K::async_generate(executor, token)`, `key_pair.async_sign(executor, scheme, input, token)`, `key_pair.async_agree(executor, peer, token)` (X25519, P-256), - `public_key.async_verify(executor, scheme, policy, signature, input, token)`, and every AEAD's - and box's `aead.async_seal` and `aead.async_open`. The classes declare them and this header - defines them, so that a curve's or a cipher's header never includes Asio; the free function calls - the member, which runs the synchronous member, so that the four forms of an operation share their - guards, refusals and errors. + `public_key.async_verify(executor, scheme, policy, signature, input, token)`, every AEAD's + and box's `aead.async_seal` and `aead.async_open`, ChaCha20's + `cipher.async_apply_keystream(executor, nonce, data, initial_counter, token)`, and Poly1305's + static `A::async_authenticate(executor, key, message, token)` and + `A::async_verify(executor, key, message, tag, token)`, which have no object. The classes declare + them and this header defines them, so that a curve's or a cipher's header never includes Asio; the + free function calls the member, which runs the synchronous member, so that the four forms of an + operation share their guards, refusals and errors. The default backend of each is the synchronous function's, `default_async_backend_t`, `default_backend_t` on every target, Emscripten included: the browser's backend is used @@ -108,8 +119,10 @@ #include +#include #include #include +#include #include #include #include @@ -123,6 +136,8 @@ #include #include #include +#include +#include #include #include @@ -332,13 +347,40 @@ inline constexpr bool is_secretbox_v -inline constexpr bool refuses_async_aead_v = +inline constexpr bool refuses_async_aead_v = false; + +template + requires requires { typename std::remove_cvref_t::backend_type; } +inline constexpr bool refuses_async_aead_v = !is_gcm_v> && asynchronous_backend_v::backend_type>; +/** Whether `Type` is ChaCha20, `ciphers::basic_chacha20`. */ +template +inline constexpr bool is_chacha20_v = false; + +template +inline constexpr bool is_chacha20_v> = true; + +/** + * Whether `async_from_key` refuses a stream cipher (design D6, R10): ChaCha20 on a backend that + * completes by itself, which WebCrypto lacks. A stream cipher of another shape names no backend + * (owner decision 7): its own member decides. + * + * @tparam Type A type, its qualifiers and reference ignored. + */ +template +inline constexpr bool refuses_async_stream_cipher_v = false; + +template + requires is_chacha20_v> +inline constexpr bool refuses_async_stream_cipher_v = + asynchronous_backend_v::backend_type>; + /** Whether `Type` is an Ed25519 key pair, `curves::ed25519::basic_keypair`. */ template inline constexpr bool is_ed25519_keypair_v = false; @@ -709,19 +751,25 @@ auto async_from_secret(Executor const& completion_executor, } /** - * Makes an AEAD or a secret box from its key bytes, asynchronously: `Cipher::from_key(key_bytes)` - * run when the operation is initiated, its result posted to `completion_executor`. + * Makes an AEAD, a stream cipher or a secret box from its key bytes, asynchronously: + * `Cipher::from_key(key_bytes)` run when the operation is initiated, its result posted to + * `completion_executor`. * * The free form of `Cipher::async_from_key(completion_executor, key_bytes, completion_token)`, - * which it calls. + * which it calls where the type has it. * * The key is read before the call returns on a synchronous backend, later on the browser's: it is * the caller's until the completion. On a backend that completes by itself only AES-GCM is * offered: any other type stops the build (design D6). * * @tparam Cipher A `secret_key_encryption::aead::cipher` (`ciphers::gcm`, - * ChaCha20-Poly1305 and its forms) or a `secret_key_encryption::basic_secretbox`, on any backend - * that has it; a crypto_box is made by `from_keys`, synchronously. + * ChaCha20-Poly1305 and its forms) or a `secret_key_encryption::basic_secretbox`, with the member + * `async_from_key`, or a `unauthenticated_encryption::stream_cipher` (`ciphers::basic_chacha20`), + * on any backend that has it. A stream cipher without the member has its synchronous `from_key` + * run when the operation is initiated, its result posted to `completion_executor`: its error + * completion needs an empty cipher, made by a `noexcept` default constructor, public or private + * with `detail::async_access` a friend; without one, as for an AEAD or a secret box without the + * member, the build stops. A crypto_box is made by `from_keys`, synchronously. * @tparam Executor The executor's type, an Asio executor (an `io_context`'s or a strand's). * @tparam CompletionToken Any completion token for the signature `completion_token` states. * @param completion_executor The executor the completion is posted to. @@ -735,17 +783,44 @@ template auto async_from_key(Executor const& completion_executor, std::span key_bytes, CompletionToken&& completion_token) { secure::timing_guard const timing_scope; - if constexpr (!secret_key_encryption::aead::cipher && !detail::is_secretbox_v) { + if constexpr (!secret_key_encryption::aead::cipher && !detail::is_secretbox_v && + !unauthenticated_encryption::stream_cipher) { static_assert(detail::refused_v, "webcpp::crypto: async_from_key takes an AEAD (a " - "secret_key_encryption::aead::cipher) or a secret box: a crypto_box is made " - "by from_keys."); - } else if constexpr (detail::refuses_async_aead_v) { + "secret_key_encryption::aead::cipher), a stream cipher (a " + "unauthenticated_encryption::stream_cipher) or a secret box: a crypto_box is " + "made by from_keys."); + } else if constexpr (detail::refuses_async_stream_cipher_v) { + detail::refuse_stream_cipher_on_asynchronous_backend< + typename std::remove_cvref_t::backend_type>(); + } else if constexpr ((secret_key_encryption::aead::cipher || + detail::is_secretbox_v) && + detail::refuses_async_aead_v) { detail::refuse_aead_on_asynchronous_backend< typename std::remove_cvref_t::backend_type>(); - } else { + } else if constexpr (requires { + Cipher::async_from_key( + completion_executor, key_bytes, + std::forward(completion_token)); + }) { return Cipher::async_from_key(completion_executor, key_bytes, std::forward(completion_token)); + } else if constexpr (!unauthenticated_encryption::stream_cipher) { + static_assert(detail::refused_v, + "webcpp::crypto: async_from_key runs the synchronous from_key of a stream " + "cipher alone: an AEAD or a secret box without the member async_from_key " + "cannot be made asynchronously."); + } else if constexpr (!detail::async_access::makes_empty_v) { + static_assert( + detail::refused_v, + "webcpp::crypto: async_from_key posts a stream cipher's synchronous from_key, whose " + "error completion gives an empty cipher: give the type a noexcept default " + "constructor, public or private with webcpp::crypto::detail::async_access a friend."); + } else { + // A stream cipher without the member: its synchronous from_key, posted. + return detail::complete_by_post( + completion_executor, completion_token, + [key_bytes]() noexcept { return Cipher::from_key(key_bytes); }); } } @@ -990,6 +1065,191 @@ auto async_open(Executor const& completion_executor, Box& keyed_box, } // namespace secret_key_encryption +namespace unauthenticated_encryption { + +/** + * XORs a stream cipher's keystream into `data_bytes`, in place, asynchronously: + * `keyed_cipher.apply_keystream` run when the operation is initiated, its result posted to + * `completion_executor`. + * + * The free form of the member `keyed_cipher.async_apply_keystream`, which it calls with the + * arguments after `keyed_cipher` where the type has it. It names no backend and reads only the + * algorithm's `counter_type` (owner decision 7), so that a stream cipher of another shape runs + * through it; on a backend that completes by itself, ChaCha20's member stops the build (design D6). + * + * `keyed_cipher` and the spans are the caller's until the completion: a synchronous backend reads + * and writes them before the call returns. A guard's refusal (`invalid_state`, + * `invalid_nonce_size`, `counter_overflow`) leaves `data_bytes` untouched; a backend's failure + * zeroes it, as `apply_keystream` does. + * + * @tparam Executor The executor's type, an Asio executor (an `io_context`'s or a strand's). + * @tparam Cipher A `stream_cipher`, which the signature requires; one without the member + * `async_apply_keystream` has its synchronous `apply_keystream` run when the operation is + * initiated, its result posted to `completion_executor`. The completion carries no value, so the + * fallback needs nothing beyond the concept. + * @tparam CompletionToken Any completion token for the signature `completion_token` states. + * @param completion_executor The executor the completion is posted to. + * @param keyed_cipher The keyed object. + * @param nonce_bytes The nonce, `Cipher::nonce_size` bytes, never repeated under this key. + * @param data_bytes The data, the plaintext or the ciphertext. + * @param initial_counter The block counter of the first block. + * @param completion_token The completion token, of signature `void(boost::system::error_code)`. + * @return What the completion token's `async_result` gives. + */ +template +auto async_apply_keystream(Executor const& completion_executor, Cipher& keyed_cipher, + std::span nonce_bytes, + std::span data_bytes, + typename Cipher::counter_type initial_counter, + CompletionToken&& completion_token) { + secure::timing_guard const timing_scope; + if constexpr (requires { + keyed_cipher.async_apply_keystream( + completion_executor, nonce_bytes, data_bytes, initial_counter, + std::forward(completion_token)); + }) { + return keyed_cipher.async_apply_keystream(completion_executor, nonce_bytes, data_bytes, + initial_counter, + std::forward(completion_token)); + } else { + // A stream cipher without the member: its synchronous apply_keystream, posted. + return detail::complete_by_post( + completion_executor, completion_token, + [&keyed_cipher, nonce_bytes, data_bytes, initial_counter]() noexcept { + return keyed_cipher.apply_keystream(nonce_bytes, data_bytes, initial_counter); + }); + } +} + +} // namespace unauthenticated_encryption + +namespace single_use_key_authentication { + +/** + * Authenticates a message under a key used for it alone, asynchronously: + * `Authenticator::authenticate(key_bytes, message_bytes)` run when the operation is initiated, its + * result posted to `completion_executor`. + * + * The free form of the static `Authenticator::async_authenticate`, which it calls where the type + * has it; a single-use key authenticator without it has its synchronous `authenticate` run and + * posted. On a backend that completes by itself Poly1305's member stops the build (design D15): + * WebCrypto has no Poly1305. + * + * The spans are the caller's until the completion: a synchronous backend reads them before the + * call returns. + * + * @tparam Authenticator A `single_use_key_authenticator`: `authenticators::poly1305`. + * @tparam Executor The executor's type, an Asio executor (an `io_context`'s or a strand's). + * @tparam CompletionToken Any completion token for the signature `completion_token` states. + * @param completion_executor The executor the completion is posted to. + * @param key_bytes The one-time key, the algorithm's `key_size` bytes, used for this message alone. + * @param message_bytes The message, of any length, empty included. + * @param completion_token The completion token, of signature + * `void(boost::system::error_code, typename Authenticator::result_type)`; on an error the zeroed + * tag (`invalid_key_size`, the backend's). + * @return What the completion token's `async_result` gives. + */ +template +auto async_authenticate(Executor const& completion_executor, + std::span key_bytes, + std::span message_bytes, + CompletionToken&& completion_token) { + secure::timing_guard const timing_scope; + if constexpr (requires { + Authenticator::async_authenticate( + completion_executor, key_bytes, message_bytes, + std::forward(completion_token)); + }) { + return Authenticator::async_authenticate(completion_executor, key_bytes, message_bytes, + std::forward(completion_token)); + } else { + // An authenticator without the member: its synchronous authenticate, posted. + return detail::complete_by_post( + completion_executor, completion_token, [key_bytes, message_bytes]() noexcept { + return Authenticator::authenticate(key_bytes, message_bytes); + }); + } +} + +/** + * Verifies a message's tag under a key used for it alone, asynchronously: + * `Authenticator::verify(key_bytes, message_bytes, tag_bytes)` run when the operation is + * initiated, its result posted to `completion_executor`. + * + * The free form of the static `Authenticator::async_verify`, which it calls where the type has + * it; a single-use key authenticator without it has its synchronous `verify` run and posted. On a + * backend that completes by itself Poly1305's member stops the build (design D15). + * + * The spans are the caller's until the completion: a synchronous backend reads them before the + * call returns. + * + * @tparam Authenticator A `single_use_key_authenticator`: `authenticators::poly1305`. + * @tparam Executor The executor's type, an Asio executor (an `io_context`'s or a strand's). + * @tparam CompletionToken Any completion token for the signature `completion_token` states. + * @param completion_executor The executor the completion is posted to. + * @param key_bytes The one-time key, the algorithm's `key_size` bytes, used for this message alone. + * @param message_bytes The message, of any length, empty included. + * @param tag_bytes The tag to check, the algorithm's `tag_size` bytes. + * @param completion_token The completion token, of signature `void(boost::system::error_code)` + * (`invalid_key_size`, `invalid_tag_size`, `authentication_failed`, the backend's). + * @return What the completion token's `async_result` gives. + */ +template +auto async_verify(Executor const& completion_executor, std::span key_bytes, + std::span message_bytes, + std::span tag_bytes, CompletionToken&& completion_token) { + secure::timing_guard const timing_scope; + if constexpr (requires { + Authenticator::async_verify(completion_executor, key_bytes, message_bytes, + tag_bytes, + std::forward(completion_token)); + }) { + return Authenticator::async_verify(completion_executor, key_bytes, message_bytes, tag_bytes, + std::forward(completion_token)); + } else { + // An authenticator without the member: its synchronous verify, posted. + return detail::complete_by_post(completion_executor, completion_token, + [key_bytes, message_bytes, tag_bytes]() noexcept { + return Authenticator::verify(key_bytes, message_bytes, + tag_bytes); + }); + } +} + +/** + * Refuses a type that is no single-use key authenticator, a `webcpp::hash` MAC or an AEAD among + * them, with one message that says what it takes. + * + * @tparam Authenticator The type given. + * @tparam Arguments The arguments' types. + */ +template + requires(!single_use_key_authenticator) +void async_authenticate(Arguments&&... /*arguments*/) noexcept { + static_assert(detail::dependent_false, + "webcpp::crypto: single_use_key_authentication::async_authenticate takes a " + "single-use key authenticator (authenticators::poly1305); a reusable key's MAC " + "is webcpp::hash::async_hmac (HMAC)."); +} + +/** + * Refuses a type that is no single-use key authenticator, a `webcpp::hash` MAC or an AEAD among + * them, with one message that says what it takes. + * + * @tparam Authenticator The type given. + * @tparam Arguments The arguments' types. + */ +template + requires(!single_use_key_authenticator) +void async_verify(Arguments&&... /*arguments*/) noexcept { + static_assert(detail::dependent_false, + "webcpp::crypto: single_use_key_authentication::async_verify takes a single-use " + "key authenticator (authenticators::poly1305); a reusable key's MAC is " + "webcpp::hash::async_hmac (HMAC)."); +} + +} // namespace single_use_key_authentication + /** * Signs with an Ed25519 or a P-256 key pair, asynchronously: * `key_pair.sign(signing_scheme, signing_input)` run when the operation is initiated, its result @@ -1488,6 +1748,74 @@ auto ciphers::basic_chacha20_poly1305::async_open( } } +template +template +auto ciphers::basic_chacha20::async_from_key( + Executor const& completion_executor, std::span key_bytes, + CompletionToken&& completion_token) { + secure::timing_guard const timing_scope; + if constexpr (detail::asynchronous_backend_v) { + detail::refuse_stream_cipher_on_asynchronous_backend(); + } else { + return detail::complete_by_post( + completion_executor, completion_token, + [key_bytes]() noexcept { return basic_chacha20::from_key(key_bytes); }); + } +} + +template +template +auto ciphers::basic_chacha20::async_apply_keystream( + Executor const& completion_executor, std::span nonce_bytes, + std::span data_bytes, counter_type initial_counter, + CompletionToken&& completion_token) { + secure::timing_guard const timing_scope; + if constexpr (detail::asynchronous_backend_v) { + detail::refuse_stream_cipher_on_asynchronous_backend(); + } else { + return detail::complete_by_post( + completion_executor, completion_token, + [this, nonce_bytes, data_bytes, initial_counter]() noexcept { + return apply_keystream(nonce_bytes, data_bytes, initial_counter); + }); + } +} + +template +template +auto authenticators::poly1305::async_authenticate( + Executor const& completion_executor, std::span key_bytes, + std::span message_bytes, CompletionToken&& completion_token) { + secure::timing_guard const timing_scope; + if constexpr (detail::asynchronous_backend_v) { + detail::refuse_single_use_key_authenticator_on_asynchronous_backend(); + } else { + return detail::complete_by_post(completion_executor, completion_token, + [key_bytes, message_bytes]() noexcept { + return poly1305::authenticate(key_bytes, message_bytes); + }); + } +} + +template +template +auto authenticators::poly1305::async_verify(Executor const& completion_executor, + std::span key_bytes, + std::span message_bytes, + std::span tag_bytes, + CompletionToken&& completion_token) { + secure::timing_guard const timing_scope; + if constexpr (detail::asynchronous_backend_v) { + detail::refuse_single_use_key_authenticator_on_asynchronous_backend(); + } else { + return detail::complete_by_post(completion_executor, completion_token, + [key_bytes, message_bytes, tag_bytes]() noexcept { + return poly1305::verify(key_bytes, message_bytes, + tag_bytes); + }); + } +} + template template auto secret_key_encryption::basic_secretbox::async_from_key( diff --git a/include/webcpp/crypto/authenticators/poly1305.hpp b/include/webcpp/crypto/authenticators/poly1305.hpp new file mode 100644 index 0000000..9354648 --- /dev/null +++ b/include/webcpp/crypto/authenticators/poly1305.hpp @@ -0,0 +1,307 @@ +// 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) + +/** + `authenticators::poly1305`, RFC 8439's one-time authenticator, and its family, + `families::poly1305`: a 16-byte tag of a message under a 32-byte key that authenticates that + message alone (design D11, D12). It is a + `single_use_key_authentication::single_use_key_authenticator`, whose header, which this one + includes, holds its free forms, `single_use_key_authentication::authenticate(key, message)` + and `single_use_key_authentication::verify(key, message, tag)`. + + It is an algorithm, never an object (R21): `authenticate` and `verify` are static, and the key + enters every call. A key authenticates one message and never a second: two tags under one key let + an attacker forge others. A protocol derives the key for each message, as ChaCha20-Poly1305 does + from its nonce; a key used for many messages takes `webcpp::hash`'s HMAC. + + The backend is the family's default, libsodium on every target, unless the type names another, + as OpenSSL on native, wasip2 and wasip3, whose header the program includes; this header includes + the default's header when the program links it (`default_backend_t`). A program that uses the + default without linking it stops where it calls it, with the Jamfile line that links it. + + On Emscripten, every function on libsodium may return `entropy_unavailable`, or + `errc::not_supported` where there is no generator, while libsodium is not yet initialised and + the browser's generator fails, as `backends::sodium` says. + + @see "Single-use key authentication: `webcpp::crypto::single_use_key_authentication`", in the + guide. +*/ +#ifndef WEBCPP_CRYPTO_AUTHENTICATORS_POLY1305_HPP +#define WEBCPP_CRYPTO_AUTHENTICATORS_POLY1305_HPP + +#include + +#include +#include +#include +#include +#include +#include // detail::concept_check_backend +#include // its free forms (D13) +#include +#include +#include +#include + +#include +#include + +#include +#include +#include + +#if defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_POLY1305_SODIUM) && defined(WEBCPP_CRYPTO_HAS_SODIUM) +#include +#endif + +namespace webcpp::crypto::families { + +/** RFC 8439's Poly1305: a 32-byte one-time key, r and s, and a 16-byte tag. */ +struct poly1305 { + /** The key's size: r and s, RFC 8439 section 2.5. */ + static constexpr std::size_t key_size = 32; + /** The tag's size. */ + static constexpr std::size_t tag_size = 16; +}; + +} // namespace webcpp::crypto::families + +namespace webcpp::crypto::detail { + +/** + * The refusal of an authenticator family on a backend whose header does not specialise its + * engine. + */ +template +struct authenticator_refusal {}; + +/** Poly1305's refusal, which names what the program needs (`detail/capabilities.hpp`). */ +template +struct authenticator_refusal { + WEBCPP_CRYPTO_DETAIL_REFUSE_POLY1305(Backend); +}; + +/** + * An authenticator's engine on a backend whose header does not specialise it: the family's + * refusal. Its function is never called: the refusal stops the build where the class is + * instantiated, and it keeps the compiler from adding errors of its own after it; it reports + * `backend_failure`, so that a path the refusal missed fails closed. + */ +template +struct authenticator_engine : authenticator_refusal { + /** Never called; fails closed. */ + template + [[nodiscard]] static boost::system::result authenticate( + Arguments&&... /*arguments*/) noexcept { + return error::backend_failure; + } +}; + +} // namespace webcpp::crypto::detail + +namespace webcpp::crypto::authenticators { + +/** + * RFC 8439's Poly1305 on `Backend`: the 16-byte tag of a message under a 32-byte key that + * authenticates that message alone. + * + * An algorithm, never an object: no object keeps a key, which enters every call, so that each + * call shows the key's single use. Two messages under one key let an attacker forge tags; a + * protocol derives a fresh key for each message, and a key used for many messages takes + * `webcpp::hash`'s HMAC. A key given as a `secure::secret<32>` is given by its `bytes()`. + * + * @tparam Backend The backend; `poly1305<>` names the family's default, libsodium. + */ +template > +class poly1305 { + using engine = detail::authenticator_engine; + +public: + /** The backend. */ + using backend_type = Backend; + /** The family of the capability table, which `supports_v` reads. */ + using family_type = families::poly1305; + /** The algorithm of the capability table: the family's own tag, its one algorithm. */ + using name_type = families::poly1305; + /** The tag, the AEADs' and the boxes' tag type. */ + using result_type = boost::hash2::digest; + /** The key's size. */ + static constexpr std::size_t key_size = families::poly1305::key_size; + /** The tag's size. */ + static constexpr std::size_t tag_size = families::poly1305::tag_size; + + /** + * RFC 8439 section 2.5's tag of `message_bytes` under the one-time key `key_bytes`, r and s, + * r clamped by the algorithm, not by the caller. + * + * The key's size is checked first, reading no byte; every message length is accepted, the + * empty message too, whose tag is s. Nothing is written into the caller's spans, and the key + * and the message may overlap. The key is copied nowhere by crypto; it is the caller's to + * wipe, as a `secure::secret<32>` does. + * + * @param key_bytes The one-time key, `key_size` bytes, used for this message alone. + * @param message_bytes The message, of any length. + * @return The tag; `invalid_key_size`; the backend's error, `backend_failure`. + */ + [[nodiscard]] static boost::system::result authenticate( + std::span key_bytes, + std::span message_bytes) noexcept { + secure::timing_guard const timing_scope; + if constexpr (detail::asynchronous_backend_v) { + // WebCrypto has no Poly1305: the refusal names a native backend (design D15). + detail::refuse_single_use_key_authenticator_on_asynchronous_backend(); + return error::backend_failure; + } else { + if (key_bytes.size() != key_size) { + return error::invalid_key_size; + } + result_type tag_bytes{}; + auto const computed = compute(key_bytes, message_bytes, tag_bytes); + if (!computed) { + return computed.error(); + } + return tag_bytes; + } + } + + /** + * Verifies that `tag_bytes` is RFC 8439 section 2.5's tag of `message_bytes` under the + * one-time key `key_bytes`. + * + * The guards come first, in this order, and neither reads a byte: `invalid_key_size`, then + * `invalid_tag_size`. The tag is computed as `authenticate` computes it, compared in constant + * time, and the computed tag wiped; the verdict is public. A backend's failure returns its + * own error, never `authentication_failed`, so that a broken backend never reads as a forgery. + * Nothing is written into the caller's spans, and the key, the message and the tag may + * overlap. + * + * @param key_bytes The one-time key, `key_size` bytes, used for this message alone. + * @param message_bytes The message, of any length. + * @param tag_bytes The tag to check, `tag_size` bytes. + * @return Nothing when the tag is the message's; `invalid_key_size`; `invalid_tag_size`; + * `authentication_failed`; the backend's error, `backend_failure`. + */ + [[nodiscard]] static boost::system::result verify( + std::span key_bytes, std::span message_bytes, + std::span tag_bytes) noexcept { + secure::timing_guard const timing_scope; + if constexpr (detail::asynchronous_backend_v) { + // WebCrypto has no Poly1305: the refusal names a native backend (design D15). + detail::refuse_single_use_key_authenticator_on_asynchronous_backend(); + return error::backend_failure; + } else { + if (key_bytes.size() != key_size) { + return error::invalid_key_size; + } + if (tag_bytes.size() != tag_size) { + return error::invalid_tag_size; + } + result_type computed_tag{}; + auto const computed = compute(key_bytes, message_bytes, computed_tag); + if (!computed) { + return computed.error(); // the tag zeroed by compute + } + // The verdict is public by design (a failed verification is reported): declassified + // here, where webcpp's code first branches on it, for the constant-time checks. + // Not const: the branch below must read the variable again after the declassifying + // client request, whose memory clobber reaches a mutable object only. + // NOLINTNEXTLINE(misc-const-correctness): see above + bool tag_matches = + secure::constant_time_equal(computed_tag, tag_bytes.first()); + secure::declassify(tag_matches); + secure::erase_secret(computed_tag); + if (!tag_matches) { + return error::authentication_failed; + } + return {}; + } + } + + /** + * The tag of a message, asynchronously: `authenticate` run when the operation is initiated, + * its result posted to `completion_executor`; the member form of + * `single_use_key_authentication::async_authenticate(executor, key_bytes, + * message_bytes, token)`, which calls it. + * + * The spans are the caller's until the completion. On a native backend only: WebCrypto has no + * Poly1305, and on a backend that completes by itself this call stops the build, as every + * other form does (design D15). + * + * Declared here and defined in ``, which a program includes to call + * it, with `/webcpp/asio//asio` in its Jamfile. + * + * @tparam Executor The executor's type, an Asio executor (an `io_context`'s or a strand's). + * @tparam CompletionToken Any completion token for the signature `completion_token` states. + * @param completion_executor The executor the completion is posted to. + * @param key_bytes The one-time key, `key_size` bytes, used for this message alone. + * @param message_bytes The message, of any length. + * @param completion_token The completion token, of signature + * `void(boost::system::error_code, result_type)`; on an error the zeroed tag + * (`authenticate`'s errors). + * @return What the completion token's `async_result` gives. + */ + template + static auto async_authenticate(Executor const& completion_executor, + std::span key_bytes, + std::span message_bytes, + CompletionToken&& completion_token); + + /** + * Verifies a message's tag, asynchronously: `verify` run when the operation is initiated, its + * result posted to `completion_executor`; the member form of + * `single_use_key_authentication::async_verify(executor, key_bytes, message_bytes, + * tag_bytes, token)`, which calls it. + * + * The spans are the caller's until the completion. On a native backend only (design D15). + * + * Declared here and defined in ``, which a program includes to call + * it, with `/webcpp/asio//asio` in its Jamfile. + * + * @tparam Executor The executor's type, an Asio executor (an `io_context`'s or a strand's). + * @tparam CompletionToken Any completion token for the signature `completion_token` states. + * @param completion_executor The executor the completion is posted to. + * @param key_bytes The one-time key, `key_size` bytes, used for this message alone. + * @param message_bytes The message, of any length. + * @param tag_bytes The tag to check, `tag_size` bytes. + * @param completion_token The completion token, of signature + * `void(boost::system::error_code)` (`verify`'s errors). + * @return What the completion token's `async_result` gives. + */ + template + static auto async_verify(Executor const& completion_executor, + std::span key_bytes, + std::span message_bytes, + std::span tag_bytes, + CompletionToken&& completion_token); + + /** An algorithm, never an object (R21): the key enters every call. */ + poly1305() = delete; + +private: + // The engine's call on checked sizes, shared by authenticate and verify, which hold the guard; + // on a backend's failure the tag is zeroed again. + [[nodiscard]] static boost::system::result compute( + std::span key_bytes, std::span message_bytes, + result_type& tag_bytes) noexcept { + auto const authenticated = + engine::authenticate(key_bytes.first(), message_bytes, + std::span(tag_bytes.data(), tag_size)); + if (!authenticated) { + secure::erase_secret(tag_bytes); + return authenticated.error(); + } + return {}; + } +}; + +// A single-use key authenticator, which is no AEAD (design D13). +static_assert(single_use_key_authentication::single_use_key_authenticator< + poly1305>); +static_assert(!secret_key_encryption::aead::cipher>); + +} // namespace webcpp::crypto::authenticators + +#endif // WEBCPP_CRYPTO_AUTHENTICATORS_POLY1305_HPP diff --git a/include/webcpp/crypto/backends/bearssl.hpp b/include/webcpp/crypto/backends/bearssl.hpp index 5dfdac2..d45f230 100644 --- a/include/webcpp/crypto/backends/bearssl.hpp +++ b/include/webcpp/crypto/backends/bearssl.hpp @@ -407,6 +407,78 @@ struct aead_engine { static void reset(state& engine_state) noexcept { secure::erase_secret(engine_state.key); } }; +/** ChaCha20's state on BearSSL: the key, in the object, since BearSSL takes it per call. */ +template <> +struct stream_state { + /** The key. */ + std::array key{}; +}; + +/** + * ChaCha20 on BearSSL: one function over the whole data, which XORs the keystream in place from + * the block counter given (inc/bearssl_block.h, `br_chacha20_run`), SSE2's code where the CPU has + * it, else the constant-time portable code (`bearssl_chacha20`). BearSSL allocates nothing and + * never fails. + */ +template <> +struct stream_engine { + /** The state. */ + using state = stream_state; + + /** + * Keeps the key. + * + * @param engine_state An empty state. + * @param key_bytes 32 bytes (`basic_chacha20` has checked their size). + * @return Nothing. + */ + [[nodiscard]] static boost::system::result init( + state& engine_state, std::span key_bytes) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_BEARSSL_CANARY); + std::ranges::copy(key_bytes, engine_state.key.begin()); + return {}; + } + + /** + * XORs the keystream from the block `initial_counter` into `data_bytes`, in place. The counter + * BearSSL returns, the next block's, is not needed: `basic_chacha20` has checked that the data + * fits before the counter's end. + * + * @param engine_state A keyed state. + * @param nonce_bytes The nonce, a copy of the caller's. + * @param initial_counter The block counter of the first block. + * @param data_bytes The data, not empty, within the counter. + * @return Nothing. + */ + [[nodiscard]] static boost::system::result apply( + state& engine_state, std::span nonce_bytes, + std::uint32_t initial_counter, std::span data_bytes) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_BEARSSL_CANARY); + static_cast(bearssl_chacha20()(engine_state.key.data(), nonce_bytes.data(), + initial_counter, data_bytes.data(), + data_bytes.size())); + return {}; + } + + /** + * Moves the key into an empty state, and wipes the source. + * + * @param target_state An empty state. + * @param source_state A keyed state, wiped. + */ + static void move(state& target_state, state& source_state) noexcept { + target_state.key = source_state.key; + secure::erase_secret(source_state.key); + } + + /** + * Wipes the key; the state is empty. + * + * @param engine_state Any state. + */ + static void reset(state& engine_state) noexcept { secure::erase_secret(engine_state.key); } +}; + /** * BearSSL's P-256 code for this target: natively the 64-bit multiplications of br_ec_p256_m62 * where BearSSL has them (__int128, or MSVC's _umul128), else br_ec_p256_m31; on WebAssembly diff --git a/include/webcpp/crypto/backends/openssl.hpp b/include/webcpp/crypto/backends/openssl.hpp index 878fdbf..c53d552 100644 --- a/include/webcpp/crypto/backends/openssl.hpp +++ b/include/webcpp/crypto/backends/openssl.hpp @@ -7,11 +7,13 @@ /** The backend OpenSSL: OpenSSL 3.5.9 built from `third_party/libs/openssl` by `/webcpp/crypto//openssl`, static, on native, wasip2 and wasip3; never on Emscripten. It - serves `ciphers::aes128/192/256`, `ciphers::gcm<...>` and - `ciphers::chacha20_poly1305`. Its `from_key` allocates through OpenSSL's own - functions, unless a native program sets `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE`, which sends every - allocation of OpenSSL's to `openssl_memory_resource()`. On MSVC, wasip2 and wasip3 OpenSSL is - compiled without assembly: table-driven AES and 4-bit GHASH, no AES-NI, not constant time. + serves `ciphers::aes128/192/256`, `ciphers::gcm<...>`, + `ciphers::chacha20_poly1305`, `ciphers::chacha20` and + `authenticators::poly1305`. Its `from_key`, and each of Poly1305's calls, which + makes and frees its MAC context, allocate through OpenSSL's own functions, unless a native program + sets `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE`, which sends every allocation of OpenSSL's to + `openssl_memory_resource()`. On MSVC, wasip2 and wasip3 OpenSSL is compiled without assembly: + table-driven AES and 4-bit GHASH, no AES-NI, not constant time. OpenSSL's default initialisation reads the configuration file of the directory it was configured with (`/etc/ssl/openssl.cnf`, when the machine has one), as any program of OpenSSL does; what it raises meanwhile is popped with the backend's mark. @@ -268,9 +270,9 @@ inline bool openssl_defaults_installed() noexcept { namespace webcpp::crypto::detail { /** - * The check every OpenSSL `from_key` runs first, before any call into OpenSSL that allocates: - * with `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE`, `memory_functions_not_installed` unless the - * adapter is installed; without it, nothing. + * The check every OpenSSL `from_key`, and Poly1305's engine in each call, runs first, before any + * call into OpenSSL that allocates: with `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE`, + * `memory_functions_not_installed` unless the adapter is installed; without it, nothing. * * @return Nothing, or `memory_functions_not_installed`. */ @@ -332,6 +334,10 @@ namespace webcpp::crypto::detail { /** EVP takes lengths as `int`: a span goes in pieces of at most this many bytes, whole blocks. */ inline constexpr std::size_t openssl_piece = static_cast(INT_MAX) / 16 * 16; +/** ChaCha20's pieces on OpenSSL: 2^30 bytes, whole 64-byte blocks (design R18). */ +inline constexpr std::size_t openssl_chacha20_piece = std::size_t{1} << 30U; +static_assert(openssl_chacha20_piece % 64 == 0 && openssl_chacha20_piece <= openssl_piece); + /** * OpenSSL's name of AES with keys of `key_length` bytes: GCM, or ECB, the block cipher. * @@ -359,10 +365,10 @@ inline constexpr char const* openssl_ecb_name = openssl_aes_name(KeySize, false) /** * Keys a context for `cipher_name`, or gives the error of the call that failed: - * `errc::not_enough_memory` when `EVP_CIPHER_CTX_new` returns null, `backend_failure` when - * `EVP_CIPHER_fetch` returns null or the key's `EVP_CipherInit_ex` fails. The thread's - * error queue is left as it was found, through a mark set before the first call that can - * raise. + * `memory_functions_not_installed` from `openssl_memory_guard`, `errc::not_enough_memory` when + * `EVP_CIPHER_CTX_new` returns null, `backend_failure` when `EVP_CIPHER_fetch` returns null or + * the key's `EVP_CipherInit_ex` fails. The thread's error queue is left as it was found, through + * a mark set before the first call that can raise. * * @param made_context Set to the context, which the caller frees with `EVP_CIPHER_CTX_free`. * @param cipher_name OpenSSL's name of the cipher. @@ -418,13 +424,16 @@ inline boost::system::error_code openssl_failed() noexcept { /** * Runs `EVP_CipherUpdate` over `data_bytes` in place, in pieces EVP's `int` can hold. * + * @param cipher_context The keyed context. + * @param data_bytes The data, in place. + * @param piece_bytes The largest piece, whole blocks of the cipher, at most `openssl_piece`. * @return Nothing, or `backend_failure`. */ [[nodiscard]] inline boost::system::result openssl_update( - EVP_CIPHER_CTX* cipher_context, std::span data_bytes) noexcept { - for (std::size_t piece_start = 0; piece_start < data_bytes.size(); - piece_start += openssl_piece) { - std::size_t const piece_size = (std::min)(openssl_piece, data_bytes.size() - piece_start); + EVP_CIPHER_CTX* cipher_context, std::span data_bytes, + std::size_t piece_bytes = openssl_piece) noexcept { + for (std::size_t piece_start = 0; piece_start < data_bytes.size(); piece_start += piece_bytes) { + std::size_t const piece_size = (std::min)(piece_bytes, data_bytes.size() - piece_start); int written_count = 0; if (EVP_CipherUpdate(cipher_context, data_bytes.data() + piece_start, &written_count, data_bytes.data() + piece_start, static_cast(piece_size)) != 1 || @@ -608,7 +617,9 @@ struct aead_engine { * * @param engine_state An empty state. * @param key_bytes 32 bytes. - * @return Nothing; `errc::not_enough_memory`; `backend_failure`. + * @return Nothing; `memory_functions_not_installed` (with + * `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE`, the adapter not installed); + * `errc::not_enough_memory`; `backend_failure`. */ [[nodiscard]] static boost::system::result init( state& engine_state, std::span key_bytes) noexcept { @@ -692,6 +703,151 @@ struct aead_engine { } }; +/** ChaCha20's state on OpenSSL: one context, keyed once. */ +template <> +struct stream_state { + /** The context, keyed for ChaCha20; null when the object holds no key. */ + EVP_CIPHER_CTX* context = nullptr; +}; + +/** + * ChaCha20 on OpenSSL ("ChaCha20", fetched by name). OpenSSL's IV is 16 bytes, the block counter + * little-endian, then the 12-byte nonce (providers/implementations/ciphers/cipher_chacha20.c): each + * call sets it on the keyed context, then XORs the data in place in pieces of 2^30 bytes, whole + * 64-byte blocks EVP's `int` holds (`openssl_chacha20_piece`). A stream cipher has no final block, + * so no `EVP_CipherFinal` is called. The error queue is left as GCM's engine leaves it. + */ +template <> +struct stream_engine { + /** The state. */ + using state = stream_state; + + /** + * Keys a context for ChaCha20 with the key, and no IV yet. + * + * @param engine_state An empty state. + * @param key_bytes 32 bytes. + * @return Nothing; `memory_functions_not_installed` (with + * `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE`, the adapter not installed); + * `errc::not_enough_memory`; `backend_failure`. + */ + [[nodiscard]] static boost::system::result init( + state& engine_state, std::span key_bytes) noexcept { + EVP_CIPHER_CTX* made_context = nullptr; + if (auto const failure_code = + openssl_context(made_context, "ChaCha20", key_bytes, true, false)) { + return failure_code; + } + engine_state.context = made_context; + return {}; + } + + /** + * Sets the IV, the counter then the nonce, and XORs the keystream into `data_bytes`. + * + * @param engine_state A keyed state. + * @param nonce_bytes The nonce, a copy of the caller's. + * @param initial_counter The block counter of the first block. + * @param data_bytes The data, not empty, within the counter. + * @return Nothing; `backend_failure`. + */ + [[nodiscard]] static boost::system::result apply( + state& engine_state, std::span nonce_bytes, + std::uint32_t initial_counter, std::span data_bytes) noexcept { + std::array iv_bytes{}; + for (std::size_t index = 0; index < 4; ++index) { + iv_bytes[index] = static_cast(initial_counter >> (8U * index)); + } + std::ranges::copy(nonce_bytes, iv_bytes.begin() + 4); + if (EVP_CipherInit_ex(engine_state.context, nullptr, nullptr, nullptr, iv_bytes.data(), + 1) != 1) { + return openssl_failed(); + } + return openssl_update(engine_state.context, data_bytes, openssl_chacha20_piece); + } + + /** + * Moves the context, leaving the source empty. + * + * @param target_state An empty state. + * @param source_state A keyed state, emptied. + */ + static void move(state& target_state, state& source_state) noexcept { + target_state.context = std::exchange(source_state.context, nullptr); + } + + /** + * Frees the context, which `EVP_CIPHER_CTX_free` cleanses first; the pointer is then zeroed. + * + * @param engine_state Any state. + */ + static void reset(state& engine_state) noexcept { + EVP_CIPHER_CTX_free(engine_state.context); + secure::erase_secret(std::span(&engine_state, 1)); + } +}; + +/** + * RFC 8439's Poly1305 on OpenSSL, the MAC "POLY1305" fetched by name, one context per tag (design + * D14, R26): no object keeps a key, so each call fetches the MAC, makes a context, keys it, feeds + * it the message in one `EVP_MAC_update`, whose length is a `size_t` (no pieces), finalises the tag + * and frees what it made, `EVP_MAC_CTX_free` cleansing the key OpenSSL copied into the context. The + * context is allocated through OpenSSL's memory functions, never through `operator new`. The + * thread's error queue is left as it was found, through a mark set before the first call that can + * raise and popped on every path. + */ +template <> +struct authenticator_engine { + /** + * Writes the tag of `message_bytes` under `key_bytes`. An empty message, whose `data()` may be + * null, is passed as a pointer to a byte of the engine's own with length 0, as libsodium's + * engine passes it (R24). + * + * @param key_bytes The one-time key, 32 bytes. + * @param message_bytes The message, of any length. + * @param tag_bytes The tag's 16 bytes, written. + * @return Nothing; `memory_functions_not_installed` (with + * `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE`, the adapter not installed); + * `errc::not_enough_memory` when `EVP_MAC_CTX_new` returns null; `backend_failure` when + * `EVP_MAC_fetch` returns null or a call of the context fails. + */ + [[nodiscard]] static boost::system::result authenticate( + std::span key_bytes, std::span message_bytes, + std::span tag_bytes) noexcept { + if (auto const memory_guard = openssl_memory_guard(); !memory_guard) { + return memory_guard.error(); + } + ERR_set_mark(); + EVP_MAC* const fetched_mac = EVP_MAC_fetch(nullptr, "POLY1305", nullptr); + if (fetched_mac == nullptr) { + ERR_pop_to_mark(); + return error::backend_failure; + } + EVP_MAC_CTX* const mac_context = EVP_MAC_CTX_new(fetched_mac); + if (mac_context == nullptr) { + EVP_MAC_free(fetched_mac); + ERR_pop_to_mark(); + return boost::system::errc::make_error_code(boost::system::errc::not_enough_memory); + } + static constexpr unsigned char empty_byte = 0; + unsigned char const* const message_start = + message_bytes.empty() ? &empty_byte : message_bytes.data(); + std::size_t written_count = 0; + bool const tagged = + EVP_MAC_init(mac_context, key_bytes.data(), key_bytes.size(), nullptr) == 1 && + EVP_MAC_update(mac_context, message_start, message_bytes.size()) == 1 && + EVP_MAC_final(mac_context, tag_bytes.data(), &written_count, tag_bytes.size()) == 1 && + written_count == tag_bytes.size(); + EVP_MAC_CTX_free(mac_context); + EVP_MAC_free(fetched_mac); + ERR_pop_to_mark(); + if (!tagged) { + return error::backend_failure; + } + return {}; + } +}; + /** * The block cipher's state on OpenSSL: a context per direction, since a context keyed for * encryption keeps the encryption schedule only. diff --git a/include/webcpp/crypto/backends/sodium.hpp b/include/webcpp/crypto/backends/sodium.hpp index 75ae919..630d102 100644 --- a/include/webcpp/crypto/backends/sodium.hpp +++ b/include/webcpp/crypto/backends/sodium.hpp @@ -31,8 +31,10 @@ #include // through /third_party//sodium, as webcpp::hash's header does #include #include +#include #include #include +#include #include #include #include @@ -432,6 +434,116 @@ struct aead_engine { static void reset(state& engine_state) noexcept { secure::erase_secret(engine_state.key); } }; +/** ChaCha20's state on libsodium: the key, in the object, since libsodium takes it per call. */ +template <> +struct stream_state { + /** The key. */ + std::array key{}; +}; + +/** + * RFC 8439's raw ChaCha20 on libsodium, `crypto_stream_chacha20_ietf_xor_ic`, in place. + * libsodium's own bound on the counter, past which it aborts the program (`sodium_misuse`), is + * the bound `basic_chacha20` checks before it calls `apply`, so it is never reached (design R6). + */ +template <> +struct stream_engine { + /** The state. */ + using state = stream_state; + + /** + * Initialises libsodium and keeps the key. + * + * @param engine_state The state. + * @param key_bytes The key, 32 bytes (`basic_chacha20` has checked its size). + * @return Nothing; `backend_failure` when libsodium cannot start. + */ + [[nodiscard]] static boost::system::result init( + state& engine_state, std::span key_bytes) noexcept { + auto const library_ready = sodium_ready(); + if (!library_ready) { + return library_ready; + } + std::ranges::copy(key_bytes, engine_state.key.begin()); + return {}; + } + + /** + * XORs the keystream from the block `initial_counter` into `data_bytes`, in place: libsodium's + * xor functions take the output equal to the input. + * + * @param engine_state The state. + * @param nonce_bytes The nonce, a copy of the caller's. + * @param initial_counter The block counter of the first block. + * @param data_bytes The data, not empty, within the counter. + * @return Nothing; `backend_failure` when libsodium fails. + */ + [[nodiscard]] static boost::system::result apply( + state& engine_state, std::span nonce_bytes, + std::uint32_t initial_counter, std::span data_bytes) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); + if (crypto_stream_chacha20_ietf_xor_ic(data_bytes.data(), data_bytes.data(), + data_bytes.size(), nonce_bytes.data(), + initial_counter, engine_state.key.data()) != 0) { + return error::backend_failure; + } + return {}; + } + + /** + * Moves the key into an empty state, and wipes the source. + * + * @param target_state An empty state. + * @param source_state A keyed state, wiped. + */ + static void move(state& target_state, state& source_state) noexcept { + target_state.key = source_state.key; + secure::erase_secret(source_state.key); + } + + /** + * Wipes the key; the state is empty. + * + * @param engine_state Any state. + */ + static void reset(state& engine_state) noexcept { secure::erase_secret(engine_state.key); } +}; + +/** + * RFC 8439's Poly1305 on libsodium, `crypto_onetimeauth_poly1305`, one call per tag: libsodium + * reads the key from the caller's bytes and wipes its own state (design D14). + */ +template <> +struct authenticator_engine { + /** + * Writes the tag of `message_bytes` under `key_bytes`. An empty message, whose `data()` may be + * null, is passed as a pointer to a byte of the engine's own with length 0 (R24). + * + * @param key_bytes The one-time key, 32 bytes. + * @param message_bytes The message, of any length. + * @param tag_bytes The tag's 16 bytes, written. + * @return Nothing; `sodium_ready`'s error when libsodium cannot start (`backend_failure`; on + * Emscripten `entropy_unavailable` or `errc::not_supported`); `backend_failure` when it fails. + */ + [[nodiscard]] static boost::system::result authenticate( + std::span key_bytes, std::span message_bytes, + std::span tag_bytes) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); + auto const library_ready = sodium_ready(); + if (!library_ready) { + return library_ready; + } + static constexpr unsigned char empty_byte = 0; + unsigned char const* const message_start = + message_bytes.empty() ? &empty_byte : message_bytes.data(); + if (crypto_onetimeauth_poly1305(tag_bytes.data(), message_start, message_bytes.size(), + key_bytes.data()) != 0) { + return error::backend_failure; + } + return {}; + } +}; + /** libsodium's detached functions of a secret box family, which differ only by name. */ template struct sodium_secretbox_calls; diff --git a/include/webcpp/crypto/ciphers/aead.hpp b/include/webcpp/crypto/ciphers/aead.hpp index e28e6eb..09b8568 100644 --- a/include/webcpp/crypto/ciphers/aead.hpp +++ b/include/webcpp/crypto/ciphers/aead.hpp @@ -146,25 +146,29 @@ struct aead_sizes { * The refusal of an AEAD family on a backend whose header does not specialise its engine: each * family's below. A type that is no AEAD family has none here: `ciphers::basic_chacha20_poly1305` * refuses it first. + * + * A backend that completes by itself has none here either: every member of the type refuses it + * first (`detail/asynchronous.hpp`), and that text is the build's one message, while the object's + * destructor, which a kept `from_key` result names, reaches this engine after it. */ -template +template > struct aead_refusal {}; /** ChaCha20-Poly1305's refusal, which names what the program needs (`detail/capabilities.hpp`). */ template -struct aead_refusal { +struct aead_refusal { WEBCPP_CRYPTO_DETAIL_REFUSE_CHACHA20_POLY1305(Backend); }; /** The original ChaCha20-Poly1305's refusal (see the first). */ template -struct aead_refusal { +struct aead_refusal { WEBCPP_CRYPTO_DETAIL_REFUSE_CHACHA20_POLY1305_ORIGINAL(Backend); }; /** XChaCha20-Poly1305's refusal (see the first). */ template -struct aead_refusal { +struct aead_refusal { WEBCPP_CRYPTO_DETAIL_REFUSE_XCHACHA20_POLY1305(Backend); }; diff --git a/include/webcpp/crypto/ciphers/chacha20.hpp b/include/webcpp/crypto/ciphers/chacha20.hpp new file mode 100644 index 0000000..286eae5 --- /dev/null +++ b/include/webcpp/crypto/ciphers/chacha20.hpp @@ -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) + +/** + `chacha20`, RFC 8439's raw stream cipher of `stream_cipher.hpp`, an + `unauthenticated_encryption::stream_cipher` (design D3) on its family's default backend unless the + type names another: libsodium on every target, whose header it includes when the program links it + (`default_backend_t`). A program that uses it without linking the default stops where it calls + it, with the Jamfile line that links it. `ciphers/stream_cipher.hpp`, which it includes, brings + its free form, `unauthenticated_encryption::apply_keystream`. + + It authenticates nothing: a program's own messages are sealed by `chacha20_poly1305`. + + On Emscripten, every function on libsodium may return `entropy_unavailable`, or + `errc::not_supported` where there is no generator, while libsodium is not yet initialised and + the browser's generator fails, as `backends::sodium` says. + + @see "ChaCha20, the raw stream cipher", in the guide. +*/ +#ifndef WEBCPP_CRYPTO_CIPHERS_CHACHA20_HPP +#define WEBCPP_CRYPTO_CIPHERS_CHACHA20_HPP + +#include + +#include +#include +#include // detail::concept_check_backend + +#if defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_CHACHA20_SODIUM) && defined(WEBCPP_CRYPTO_HAS_SODIUM) +#include +#endif + +namespace webcpp::crypto::ciphers { + +/** + * RFC 8439's ChaCha20: a 32-byte key, a 12-byte nonce, a 32-bit block counter, no authentication. + * + * @tparam Backend The backend; the default is the family's. + */ +template > +using chacha20 = basic_chacha20; + +// A raw stream cipher, which is no AEAD (design D3). +static_assert(unauthenticated_encryption::stream_cipher>); +static_assert(!secret_key_encryption::aead::cipher>); + +} // namespace webcpp::crypto::ciphers + +#endif // WEBCPP_CRYPTO_CIPHERS_CHACHA20_HPP diff --git a/include/webcpp/crypto/ciphers/stream_cipher.hpp b/include/webcpp/crypto/ciphers/stream_cipher.hpp new file mode 100644 index 0000000..1db4e24 --- /dev/null +++ b/include/webcpp/crypto/ciphers/stream_cipher.hpp @@ -0,0 +1,387 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + `basic_chacha20`, RFC 8439's raw stream cipher, and the family it takes, + `families::chacha20`: the keystream XORed into the data in place from a block counter the caller + names, with no authentication (design D1, D2). It is an + `unauthenticated_encryption::stream_cipher`, whose header, which this one includes, holds its free + form, `unauthenticated_encryption::apply_keystream(cipher, nonce, data, initial_counter)`. + + It authenticates nothing: a program's own messages are sealed by `ciphers::chacha20_poly1305`, + and this cipher is for a protocol that fixes its own construction, as NIP-44 does with + HMAC-SHA256 over the nonce and the ciphertext. + + @see "ChaCha20, the raw stream cipher", in the guide. +*/ +#ifndef WEBCPP_CRYPTO_CIPHERS_STREAM_CIPHER_HPP +#define WEBCPP_CRYPTO_CIPHERS_STREAM_CIPHER_HPP + +#include + +#include +#include +#include +#include +#include +#include // crypto::from_key, which serves its from_key +#include // its free form (design D3) +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +namespace webcpp::crypto::families { + +/** RFC 8439's ChaCha20: a 32-byte key, a 12-byte nonce, a 32-bit block counter. */ +struct chacha20 { + /** The key's size. */ + static constexpr std::size_t key_size = 32; + /** The nonce's size, exactly (RFC 8439 section 2.3). */ + static constexpr std::size_t nonce_size = 12; + /** The block's size: the keystream is made one 64-byte block per counter value. */ + static constexpr std::size_t block_size = 64; + /** The block counter, RFC 8439's 32 bits. */ + using counter_type = std::uint32_t; + /** The longest data from counter 0, 2^38 bytes: 2^32 blocks of 64 bytes. */ + static constexpr std::uint64_t max_message_size = std::uint64_t{1} << 38U; +}; + +} // namespace webcpp::crypto::families + +namespace webcpp::crypto::detail { + +/** + * What a `ciphers::basic_chacha20` stores on a backend whose header does not specialise it: + * nothing, since its engine refuses the backend where the family is called. + */ +template +struct stream_state {}; + +/** Whether `Family` is one of the stream families `ciphers::basic_chacha20` takes. */ +template +inline constexpr bool stream_family = false; + +/** ChaCha20 is a stream family. */ +template <> +inline constexpr bool stream_family = true; + +/** + * The sizes `ciphers::basic_chacha20` reads from its family: the family's own. + * + * @tparam Family A stream family. + */ +template > +struct stream_sizes : Family {}; + +/** + * The sizes of a type that is no stream family, which `ciphers::basic_chacha20` refuses first: + * placeholders, so that the compiler adds no error of its own after the refusal. + */ +template +struct stream_sizes { + /** A placeholder. */ + static constexpr std::size_t key_size = 1; + /** A placeholder. */ + static constexpr std::size_t nonce_size = 1; + /** A placeholder. */ + static constexpr std::size_t block_size = 1; + /** A placeholder. */ + using counter_type = std::uint32_t; + /** A placeholder. */ + static constexpr std::uint64_t max_message_size = 0; +}; + +/** + * The refusal of a stream family on a backend whose header does not specialise its engine. A type + * that is no stream family has none here: `ciphers::basic_chacha20` refuses it first. + * + * A backend that completes by itself has none here either: every member of the type refuses it + * first (`detail/asynchronous.hpp`), and that text is the build's one message, while the object's + * destructor, which a kept `from_key` result names, reaches this engine after it. + */ +template > +struct stream_refusal {}; + +/** ChaCha20's refusal, which names what the program needs (`detail/capabilities.hpp`). */ +template +struct stream_refusal { + WEBCPP_CRYPTO_DETAIL_REFUSE_CHACHA20(Backend); +}; + +/** + * A stream cipher's engine on a backend whose header does not specialise it: the family's + * refusal. Its functions are never called: the refusal stops the build where the class is + * instantiated, and they keep the compiler from adding errors of their own after it; those that + * return report `backend_failure`, so that a path the refusal missed fails closed. + */ +template +struct stream_engine : stream_refusal { + /** Never called; fails closed. */ + template + [[nodiscard]] static boost::system::result init(Arguments&&... /*arguments*/) noexcept { + return error::backend_failure; + } + + /** Never called; fails closed. */ + template + [[nodiscard]] static boost::system::result apply(Arguments&&... /*arguments*/) noexcept { + return error::backend_failure; + } + + /** Never called. */ + template + static void move(Arguments&&... /*arguments*/) noexcept {} + + /** Never called. */ + template + static void reset(Arguments&&... /*arguments*/) noexcept {} +}; + +} // namespace webcpp::crypto::detail + +namespace webcpp::crypto::ciphers { + +/** + * A raw stream cipher of the family `Family` on `Backend`: RFC 8439's ChaCha20, its keystream + * XORed into the data in place from the block counter the caller names. + * + * It authenticates nothing. An object holds a key: it is used by one thread at a time. A nonce is + * never repeated under one key: two messages under one key and one nonce reveal the XOR of their + * plaintexts. A program that needs authenticated encryption uses `chacha20_poly1305`; this cipher + * is for a protocol that fixes its own construction and its own authentication, as NIP-44 does. + * + * @tparam Family `families::chacha20`. + * @tparam Backend The backend; `ciphers::chacha20<>` names the family's default. + */ +template +class basic_chacha20 { + // The first error a program that names another type sees, and its only one. + static_assert(detail::stream_family, + "webcpp::crypto: ciphers::basic_chacha20 takes a stream family: " + "families::chacha20."); + + using sizes = detail::stream_sizes; + using state_type = detail::stream_state; + using engine = detail::stream_engine; + +public: + /** The backend. */ + using backend_type = Backend; + /** The family of the capability table, which `supports_v` reads. */ + using family_type = Family; + /** The algorithm of the capability table: the family's own tag, its one algorithm. */ + using name_type = Family; + /** The block counter's type, RFC 8439's 32 bits. */ + using counter_type = sizes::counter_type; + /** The key's size. */ + static constexpr std::size_t key_size = sizes::key_size; + /** The nonce's size, exactly. */ + static constexpr std::size_t nonce_size = sizes::nonce_size; + /** The block's size. */ + static constexpr std::size_t block_size = sizes::block_size; + /** The longest data from counter 0. */ + static constexpr std::uint64_t max_message_size = sizes::max_message_size; + + /** + * Makes an object under a key. + * + * @param key_bytes `key_size` bytes; a `secure::secret<32>` gives them by `bytes()`. + * @return The object; `invalid_key_size`; `backend_failure` when the backend cannot start. + */ + [[nodiscard]] static boost::system::result from_key( + std::span key_bytes) noexcept { + secure::timing_guard const timing_scope; + if constexpr (detail::asynchronous_backend_v) { + // WebCrypto has no ChaCha20: the refusal names a native backend (design D6). + detail::refuse_stream_cipher_on_asynchronous_backend(); + return error::backend_failure; + } else { + if (key_bytes.size() != key_size) { + return error::invalid_key_size; + } + basic_chacha20 made_object; + auto const key_result = engine::init(made_object.state_, key_bytes); + if (!key_result) { + return key_result.error(); + } + made_object.keyed_ = true; + return made_object; + } + } + + /** + * Makes an object under a key, asynchronously: `from_key` run when the operation is initiated, + * its result posted to `completion_executor`; the member form of + * `crypto::async_from_key(executor, key_bytes, token)`, which calls it. + * + * On a native backend only: WebCrypto has no ChaCha20, and on a backend that completes by + * itself this call stops the build, as every other form does (design D6). + * + * Declared here and defined in ``, which a program includes to call + * it, with `/webcpp/asio//asio` in its Jamfile; without it, the call is the compiler's + * "deduced return type used before it is defined". + * + * @tparam Executor The executor's type, an Asio executor (an `io_context`'s or a strand's). + * @tparam CompletionToken Any completion token for the signature `completion_token` states. + * @param completion_executor The executor the completion is posted to. + * @param key_bytes `key_size` bytes, the caller's until the completion. + * @param completion_token The completion token, of signature + * `void(boost::system::error_code, basic_chacha20)`; on an error the object is empty, and + * `apply_keystream` refuses with `invalid_state` (`invalid_key_size`, `backend_failure`). + * @return What the completion token's `async_result` gives. + */ + template + static auto async_from_key(Executor const& completion_executor, + std::span key_bytes, + CompletionToken&& completion_token); + + /** + * Moves the key; the source is wiped and empty. + * + * Moving an empty object gives an empty one. + * + * @param moved_source The source, empty afterwards. + */ + basic_chacha20(basic_chacha20&& moved_source) noexcept + : keyed_(std::exchange(moved_source.keyed_, false)) { + if (keyed_) { + engine::move(state_, moved_source.state_); + } + } + + /** + * Moves the key over this one, which is wiped first; an empty source gives an empty object. + * + * @param moved_source The source, empty afterwards. + * @return This object. + */ + basic_chacha20& operator=(basic_chacha20&& moved_source) noexcept { + if (this != &moved_source) { + engine::reset(state_); + keyed_ = std::exchange(moved_source.keyed_, false); + if (keyed_) { + engine::move(state_, moved_source.state_); + } + } + return *this; + } + + /** Not copyable: a key has one owner, which wipes it. */ + basic_chacha20(basic_chacha20 const&) = delete; + /** Not copyable: a key has one owner, which wipes it. */ + basic_chacha20& operator=(basic_chacha20 const&) = delete; + + /** Wipes the key. */ + ~basic_chacha20() { engine::reset(state_); } + + /** + * XORs RFC 8439 section 2.4's keystream into `data_bytes`, in place, its first block the block + * of counter `initial_counter`: encryption and decryption are this one call. + * + * It authenticates nothing. The guards come first, in this order, and none reads a byte of the + * spans: `invalid_state` (moved from), `invalid_nonce_size`, then `counter_overflow` when the + * data needs more blocks than the counter has left from `initial_counter`, so that no backend + * wraps the counter (64 bytes at `2^32 - 1` are accepted, 65 refused); a refusal leaves + * `data_bytes` untouched. Empty data then succeeds with no backend call. The nonce is copied + * before the first byte of `data_bytes` is written, so it may lie in `data_bytes`. + * + * Two calls continue one keystream by the counter: `n` whole blocks from `c`, then data from + * `c + n`, give the bytes of one call from `c`. + * + * When the backend fails, `data_bytes` is zeroed: neither the input nor a partial output is + * left. + * + * @param nonce_bytes The nonce, `nonce_size` bytes, never repeated under this key. + * @param data_bytes The data, the plaintext or the ciphertext. + * @param initial_counter The block counter of the first block: 0 for NIP-44, 1 for the + * encryption inside RFC 8439's AEAD. + * @return Nothing; `invalid_state` moved from; `invalid_nonce_size`; `counter_overflow`; + * `backend_failure`. + */ + [[nodiscard]] boost::system::result apply_keystream( + std::span nonce_bytes, std::span data_bytes, + counter_type initial_counter) noexcept { + secure::timing_guard const timing_scope; + if constexpr (detail::asynchronous_backend_v) { + // WebCrypto has no ChaCha20: the refusal names a native backend (design D6). + detail::refuse_stream_cipher_on_asynchronous_backend(); + return error::backend_failure; + } else { + if (!keyed_) { + return error::invalid_state; + } + if (nonce_bytes.size() != nonce_size) { + return error::invalid_nonce_size; + } + if (detail::counter_overflows(data_bytes.size(), initial_counter)) { + return error::counter_overflow; + } + if (data_bytes.empty()) { + return {}; + } + // The nonce may lie in the data, which the backend overwrites: a copy is used. + std::array nonce_copy{}; + std::ranges::copy(nonce_bytes, nonce_copy.begin()); + auto const applied = + engine::apply(state_, std::span(nonce_copy), + initial_counter, data_bytes); + if (!applied) { + secure::erase_secret(data_bytes); + return applied.error(); + } + return {}; + } + } + + /** + * XORs the keystream into `data_bytes`, in place, asynchronously: `apply_keystream` run when + * the operation is initiated, its result posted to `completion_executor`; the member form of + * `unauthenticated_encryption::async_apply_keystream(executor, cipher, nonce_bytes, + * data_bytes, initial_counter, token)`, which calls it. + * + * The object and the spans are the caller's until the completion. On a native backend only: + * on a backend that completes by itself the call stops the build (design D6). + * + * Declared here and defined in ``, which a program includes to call + * it, with `/webcpp/asio//asio` in its Jamfile. + * + * @tparam Executor The executor's type, an Asio executor (an `io_context`'s or a strand's). + * @tparam CompletionToken Any completion token for the signature `completion_token` states. + * @param completion_executor The executor the completion is posted to. + * @param nonce_bytes The nonce, `nonce_size` bytes, never repeated under this key. + * @param data_bytes The data, the plaintext or the ciphertext. + * @param initial_counter The block counter of the first block. + * @param completion_token The completion token, of signature + * `void(boost::system::error_code)` (`apply_keystream`'s errors). + * @return What the completion token's `async_result` gives. + */ + template + auto async_apply_keystream(Executor const& completion_executor, + std::span nonce_bytes, + std::span data_bytes, counter_type initial_counter, + CompletionToken&& completion_token); + +private: + // The asynchronous family's error completions make the empty object a move leaves. + friend struct detail::async_access; + + basic_chacha20() noexcept = default; + + state_type state_{}; + bool keyed_ = false; +}; + +} // namespace webcpp::crypto::ciphers + +#endif // WEBCPP_CRYPTO_CIPHERS_STREAM_CIPHER_HPP diff --git a/include/webcpp/crypto/config.hpp b/include/webcpp/crypto/config.hpp index c0c98f2..80bc939 100644 --- a/include/webcpp/crypto/config.hpp +++ b/include/webcpp/crypto/config.hpp @@ -215,6 +215,31 @@ namespace signing_schemes {} */ namespace verification_policies {} +/** + Encryption that authenticates nothing, for a protocol that brings its own authentication, as + NIP-44 does with HMAC-SHA256 over the nonce and the ciphertext: the stream cipher's concept, + `unauthenticated_encryption::stream_cipher`, and its free forms, declared in + ``. A program's own messages are + sealed by `secret_key_encryption`, whose AEADs authenticate. +*/ +namespace unauthenticated_encryption {} + +/** + The algorithms that authenticate a message, the siblings of `ciphers`: RFC 8439's Poly1305, + `authenticators::poly1305`, declared in ``. Each is + an algorithm, never an object: its key enters every call. +*/ +namespace authenticators {} + +/** + The home of the authenticators whose key is used once, for one message, as a protocol derives it + for each message: the concept `single_use_key_authentication::single_use_key_authenticator` and + its free forms, `authenticate` and `verify`, declared in + ``. A second message under one key + lets an attacker forge tags; a key used for many messages takes `webcpp::hash`'s HMAC. +*/ +namespace single_use_key_authentication {} + } // namespace webcpp::crypto // The backends' tags. webcpp::hash has tags of the same names in webcpp::hash::backends, and a diff --git a/include/webcpp/crypto/detail/async_access.hpp b/include/webcpp/crypto/detail/async_access.hpp index 2c07dee..c9f698c 100644 --- a/include/webcpp/crypto/detail/async_access.hpp +++ b/include/webcpp/crypto/detail/async_access.hpp @@ -54,6 +54,18 @@ struct async_access { "webcpp::crypto: an error completion's empty value is made without failing"); return T{}; } + + /** + * Whether @ref empty makes a `T`: its default constructor, public or private through + * friendship, reachable from this class and `noexcept`. The asynchronous family's fallbacks + * read it before they post a type crypto does not know. + * + * @tparam T The completion's value type. + */ + template + static constexpr bool makes_empty_v = requires { + { T{} } noexcept; + }; }; } // namespace webcpp::crypto::detail diff --git a/include/webcpp/crypto/detail/asynchronous.hpp b/include/webcpp/crypto/detail/asynchronous.hpp index 8462790..4d8652d 100644 --- a/include/webcpp/crypto/detail/asynchronous.hpp +++ b/include/webcpp/crypto/detail/asynchronous.hpp @@ -48,6 +48,42 @@ constexpr void refuse_aead_on_asynchronous_backend() noexcept { "only AES-GCM seals and opens."); } +/** + * Stops the build: RFC 8439's raw stream cipher, which WebCrypto lacks, asked of a backend that + * completes by itself (design D6, R10). + * + * Every member of `ciphers::basic_chacha20`, synchronous or asynchronous, calls it first after its + * guard; the free forms, which name no backend, reach it through the member they call, so that its + * text is the build's one message for every form. + * + * @tparam Backend The backend, whose `asynchronous_backend_v` is true. + */ +template +constexpr void refuse_stream_cipher_on_asynchronous_backend() noexcept { + static_assert(!asynchronous_backend_v, + "webcpp::crypto: WebCrypto has no ChaCha20: no form of the raw stream cipher, " + "synchronous or asynchronous, runs on the browser's backend; name a native " + "backend for it."); +} + +/** + * Stops the build: RFC 8439's Poly1305, which WebCrypto lacks, asked of a backend that completes + * by itself (design D15). + * + * Every static member of `authenticators::poly1305`, synchronous or asynchronous, calls it first + * after its guard; the free forms, which name the algorithm and call its member, reach it through + * the member, so that its text is the build's one message for every form. + * + * @tparam Backend The backend, whose `asynchronous_backend_v` is true. + */ +template +constexpr void refuse_single_use_key_authenticator_on_asynchronous_backend() noexcept { + static_assert(!asynchronous_backend_v, + "webcpp::crypto: WebCrypto has no Poly1305: no form of the single-use key " + "authenticator, synchronous or asynchronous, runs on the browser's backend; " + "name a native backend for it."); +} + } // namespace webcpp::crypto::detail #endif // WEBCPP_CRYPTO_DETAIL_ASYNCHRONOUS_HPP diff --git a/include/webcpp/crypto/detail/capabilities.hpp b/include/webcpp/crypto/detail/capabilities.hpp index fe8ec8b..5004455 100644 --- a/include/webcpp/crypto/detail/capabilities.hpp +++ b/include/webcpp/crypto/detail/capabilities.hpp @@ -53,6 +53,12 @@ struct chacha20_poly1305_original; /** The family XChaCha20-Poly1305, of `ciphers`, also the tag of its one algorithm. */ struct xchacha20_poly1305; +/** The family ChaCha20, of `ciphers`, also the tag of its one algorithm. */ +struct chacha20; + +/** The family Poly1305, of `authenticators`, also the tag of its one algorithm. */ +struct poly1305; + /** * The family XSalsa20-Poly1305 secret box, of `secret_key_encryption`, also the tag of its one * algorithm. @@ -242,6 +248,31 @@ inline constexpr bool supported inline constexpr bool supported = true; #endif +// ChaCha20 on sodium: native, wasip2, wasip3, emscripten. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool supported = true; +#endif +// ChaCha20 on bearssl: native, wasip2, wasip3, emscripten. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool supported = true; +#endif +// ChaCha20 on openssl: native, wasip2, wasip3. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) +template <> +inline constexpr bool supported = true; +#endif +// Poly1305 on sodium: native, wasip2, wasip3, emscripten. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool supported = true; +#endif +// Poly1305 on openssl: native, wasip2, wasip3. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) +template <> +inline constexpr bool supported = true; +#endif // XSalsa20-Poly1305 secret box on sodium: native, wasip2, wasip3, emscripten. #if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) template <> @@ -705,6 +736,88 @@ inline constexpr bool linked = true; static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: XChaCha20-Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten).") #endif #ifdef WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE +/** The refusals of the family ChaCha20's primary engine for `Backend`, on native. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_CHACHA20(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl's ChaCha20 is in , which the program does not include. Include it, and add /third_party//bearssl to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl's ChaCha20 is in , which the program does not include. Include it, and add /webcpp/crypto//openssl to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no ChaCha20. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no ChaCha20. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: ChaCha20's default backend on this target is libsodium, which is not linked. Add /webcpp/crypto//chacha20-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//chacha20-default ; or name another backend in the type, as in ciphers::chacha20. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's ChaCha20 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: ChaCha20 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).") +#elif defined(WEBCPP_TARGET_WASIP2) +/** The refusals of the family ChaCha20's primary engine for `Backend`, on wasip2. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_CHACHA20(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl's ChaCha20 is in , which the program does not include. Include it, and add /third_party//bearssl to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl's ChaCha20 is in , which the program does not include. Include it, and add /webcpp/crypto//openssl to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no ChaCha20. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no ChaCha20. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: ChaCha20's default backend on this target is libsodium, which is not linked. Add /webcpp/crypto//chacha20-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//chacha20-default ; or name another backend in the type, as in ciphers::chacha20. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's ChaCha20 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: ChaCha20 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).") +#elif defined(WEBCPP_TARGET_WASIP3) +/** The refusals of the family ChaCha20's primary engine for `Backend`, on wasip3. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_CHACHA20(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl's ChaCha20 is in , which the program does not include. Include it, and add /third_party//bearssl to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl's ChaCha20 is in , which the program does not include. Include it, and add /webcpp/crypto//openssl to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no ChaCha20. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no ChaCha20. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: ChaCha20's default backend on this target is libsodium, which is not linked. Add /webcpp/crypto//chacha20-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//chacha20-default ; or name another backend in the type, as in ciphers::chacha20. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's ChaCha20 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: ChaCha20 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).") +#elif defined(WEBCPP_TARGET_EMSCRIPTEN) +/** The refusals of the family ChaCha20's primary engine for `Backend`, on emscripten. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_CHACHA20(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl's ChaCha20 is in , which the program does not include. Include it, and add /third_party//bearssl to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no ChaCha20 on emscripten. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no ChaCha20. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no ChaCha20. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: ChaCha20's default backend on this target is libsodium, which is not linked. Add /webcpp/crypto//chacha20-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//chacha20-default ; or name another backend in the type, as in ciphers::chacha20. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's ChaCha20 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: ChaCha20 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).") +#endif +#ifdef WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE +/** The refusals of the family Poly1305's primary engine for `Backend`, on native. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_POLY1305(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl's Poly1305 is in , which the program does not include. Include it, and add /webcpp/crypto//openssl to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: Poly1305's default backend on this target is libsodium, which is not linked. Add /webcpp/crypto//poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//poly1305-default ; or name another backend in the type, as in authenticators::poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's Poly1305 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).") +#elif defined(WEBCPP_TARGET_WASIP2) +/** The refusals of the family Poly1305's primary engine for `Backend`, on wasip2. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_POLY1305(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl's Poly1305 is in , which the program does not include. Include it, and add /webcpp/crypto//openssl to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: Poly1305's default backend on this target is libsodium, which is not linked. Add /webcpp/crypto//poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//poly1305-default ; or name another backend in the type, as in authenticators::poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's Poly1305 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).") +#elif defined(WEBCPP_TARGET_WASIP3) +/** The refusals of the family Poly1305's primary engine for `Backend`, on wasip3. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_POLY1305(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl's Poly1305 is in , which the program does not include. Include it, and add /webcpp/crypto//openssl to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: Poly1305's default backend on this target is libsodium, which is not linked. Add /webcpp/crypto//poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//poly1305-default ; or name another backend in the type, as in authenticators::poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's Poly1305 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).") +#elif defined(WEBCPP_TARGET_EMSCRIPTEN) +/** The refusals of the family Poly1305's primary engine for `Backend`, on emscripten. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_POLY1305(Backend) \ + static_assert(!std::is_same_v, "webcpp::crypto: bearssl has no Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no Poly1305 on emscripten. The backends that have it: sodium (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3)."); \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::sodium>, "webcpp::crypto: sodium's Poly1305 is in , which the program does not include. Include it, and add /third_party//sodium to the program's Jamfile."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).") +#endif +#ifdef WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE /** * The refusals of the family XSalsa20-Poly1305 secret box's primary engine for `Backend`, on * native. diff --git a/include/webcpp/crypto/detail/defaults.hpp b/include/webcpp/crypto/detail/defaults.hpp index 5d25da4..6bfe405 100644 --- a/include/webcpp/crypto/detail/defaults.hpp +++ b/include/webcpp/crypto/detail/defaults.hpp @@ -125,6 +125,22 @@ struct default_backend_of { /** `backends::sodium`. */ using type = backends::sodium; }; +/** Defined where libsodium is the default of ChaCha20. */ +#define WEBCPP_CRYPTO_DETAIL_DEFAULT_CHACHA20_SODIUM 1 +/** The default of ChaCha20 on native, wasip2, wasip3, emscripten: libsodium. */ +template <> +struct default_backend_of { + /** `backends::sodium`. */ + using type = backends::sodium; +}; +/** Defined where libsodium is the default of Poly1305. */ +#define WEBCPP_CRYPTO_DETAIL_DEFAULT_POLY1305_SODIUM 1 +/** The default of Poly1305 on native, wasip2, wasip3, emscripten: libsodium. */ +template <> +struct default_backend_of { + /** `backends::sodium`. */ + using type = backends::sodium; +}; /** Defined where libsodium is the default of XSalsa20-Poly1305 secret box. */ #define WEBCPP_CRYPTO_DETAIL_DEFAULT_SECRETBOX_XSALSA20POLY1305_SODIUM 1 /** The default of XSalsa20-Poly1305 secret box on native, wasip2, wasip3, emscripten: libsodium. */ diff --git a/include/webcpp/crypto/detail/engines.hpp b/include/webcpp/crypto/detail/engines.hpp index fbafa2b..72e7390 100644 --- a/include/webcpp/crypto/detail/engines.hpp +++ b/include/webcpp/crypto/detail/engines.hpp @@ -71,6 +71,28 @@ struct secretbox_state; template struct secretbox_engine; +/** What a `ciphers::basic_chacha20` of the family `Family` stores (see @ref block_state). */ +template +struct stream_state; + +/** + * The work of a `ciphers::basic_chacha20` of the family `Family` on a backend, whose + * specialisation provides `init(state&, key)`, `apply(state&, nonce, initial_counter, data)` (the + * nonce a span of the family's `nonce_size`, the counter its `counter_type`, the data non-empty and + * within the counter), `move(to, from)` and `reset(state&)` (see @ref block_state). + */ +template +struct stream_engine; + +/** + * The work of an `authenticators::poly1305` on a backend, whose specialisation provides one static + * function and no state, since no object keeps a key (design D14, R21): + * `authenticate(key, message, tag)`, `noexcept`, the key a span of 32 bytes, the message of any + * length, the tag a span of 16 bytes it writes, called with checked sizes (see @ref block_state). + */ +template +struct authenticator_engine; + /** * Reads a backend's canary with a volatile load, which no linker can drop: a program built * without the backend's library, or with one of another commit or configuration, then diff --git a/include/webcpp/crypto/error.hpp b/include/webcpp/crypto/error.hpp index b42d4e2..6faa51f 100644 --- a/include/webcpp/crypto/error.hpp +++ b/include/webcpp/crypto/error.hpp @@ -113,6 +113,13 @@ enum class error : int { * sequence number reached 2^64 - 1 (RFC 9180's `MessageLimitReachedError`). */ message_limit_reached = 21, + /** + * A stream cipher's data that needs more blocks than its counter has left after the initial + * counter: RFC 8439's ChaCha20 has a 32-bit block counter, 256 GiB of keystream from counter 0. + * + * The data is left untouched. + */ + counter_overflow = 22, }; namespace detail { @@ -152,6 +159,9 @@ inline const char* message_of(int error_value) noexcept { case error::invalid_ciphertext_size: return "the ciphertext is not of the key's size"; case error::message_limit_reached: return "the context has sealed or opened as many messages as its nonce allows"; + case error::counter_overflow: + return "the data needs more blocks than the stream cipher's counter has left after " + "the initial counter"; } return "unknown webcpp.crypto error"; } diff --git a/include/webcpp/crypto/public_key_encryption/box.hpp b/include/webcpp/crypto/public_key_encryption/box.hpp index ad459f4..039739f 100644 --- a/include/webcpp/crypto/public_key_encryption/box.hpp +++ b/include/webcpp/crypto/public_key_encryption/box.hpp @@ -414,19 +414,25 @@ static_assert(!secret_key_encryption::aead::cipher< namespace webcpp::crypto::detail { -/** The refusal of a box family on a backend whose header does not specialise its engine. */ -template +/** + * The refusal of a box family on a backend whose header does not specialise its engine. + * + * A backend that completes by itself has none here: every member of the box refuses it first + * (`detail/asynchronous.hpp`), and that text is the build's one message, while the box's + * destructor, which a kept `from_keys` result names, reaches this engine after it. + */ +template > struct box_refusal {}; /** X25519-XSalsa20-Poly1305's refusal, which names what the program needs. */ template -struct box_refusal { +struct box_refusal { WEBCPP_CRYPTO_DETAIL_REFUSE_BOX_XSALSA20POLY1305(Backend); }; /** X25519-XChaCha20-Poly1305's refusal (see the first). */ template -struct box_refusal { +struct box_refusal { WEBCPP_CRYPTO_DETAIL_REFUSE_BOX_XCHACHA20POLY1305(Backend); }; diff --git a/include/webcpp/crypto/secret_key_encryption/secretbox.hpp b/include/webcpp/crypto/secret_key_encryption/secretbox.hpp index b4e5b09..6499f33 100644 --- a/include/webcpp/crypto/secret_key_encryption/secretbox.hpp +++ b/include/webcpp/crypto/secret_key_encryption/secretbox.hpp @@ -141,19 +141,23 @@ struct secretbox_sizes { * The refusal of a secret box family on a backend whose header does not specialise its engine: * each family's below. A type that is no secret box family has none here: `basic_secretbox` * refuses it first. + * + * A backend that completes by itself has none here either: every member of the type refuses it + * first (`detail/asynchronous.hpp`), and that text is the build's one message, while the object's + * destructor, which a kept `from_key` result names, reaches this engine after it. */ -template +template > struct secretbox_refusal {}; /** XSalsa20-Poly1305's secret box's refusal, which names what the program needs. */ template -struct secretbox_refusal { +struct secretbox_refusal { WEBCPP_CRYPTO_DETAIL_REFUSE_SECRETBOX_XSALSA20POLY1305(Backend); }; /** XChaCha20-Poly1305's secret box's refusal (see the first). */ template -struct secretbox_refusal { +struct secretbox_refusal { WEBCPP_CRYPTO_DETAIL_REFUSE_SECRETBOX_XCHACHA20POLY1305(Backend); }; diff --git a/include/webcpp/crypto/single_use_key_authentication/authenticator.hpp b/include/webcpp/crypto/single_use_key_authentication/authenticator.hpp new file mode 100644 index 0000000..cb0568d --- /dev/null +++ b/include/webcpp/crypto/single_use_key_authentication/authenticator.hpp @@ -0,0 +1,157 @@ +// 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-use key authenticator's contract (design D13, owner decision 6): the concept + `single_use_key_authentication::single_use_key_authenticator`, what every authenticator whose + key is used for one message is, and the free synchronous forms of its static members, + `single_use_key_authentication::authenticate(key, message)` and + `single_use_key_authentication::verify(key, message, tag)`, which name the algorithm as their + template argument and call it. + + The namespace is named by the rule its reader must keep: a key authenticates one message and + never a second, since two tags under one Poly1305 key let an attacker forge others (RFC 8439 + section 2.5); a protocol derives the key for each message, as ChaCha20-Poly1305 does from its + nonce. A key used for many messages takes `webcpp::hash`'s HMAC. The algorithms that satisfy the + concept stay in `authenticators` under their names; `` + includes this header, so that a program that includes it has the free forms. It needs no backend + and includes no algorithm. The asynchronous free forms, + `single_use_key_authentication::async_authenticate` and `async_verify`, are in + ``, with webcpp::asio. + + There is no keyed object (R21): the key enters every call, and there is no `from_key`. + + @see "Single-use key authentication: `webcpp::crypto::single_use_key_authentication`", in the + guide. +*/ +#ifndef WEBCPP_CRYPTO_SINGLE_USE_KEY_AUTHENTICATION_AUTHENTICATOR_HPP +#define WEBCPP_CRYPTO_SINGLE_USE_KEY_AUTHENTICATION_AUTHENTICATOR_HPP + +#include + +#include // detail::dependent_false +#include + +#include + +#include +#include +#include +#include + +namespace webcpp::crypto::single_use_key_authentication { + +/** + * Whether `Authenticator` is an authenticator whose key is used once, for one message (design + * D13). + * + * `authenticators::poly1305` is: + * - `Authenticator::key_size` and `Authenticator::tag_size`, sizes in bytes, and + * `typename Authenticator::result_type`, the tag; + * - `Authenticator::authenticate(key_bytes, message_bytes)`, static, gives + * `result`, the tag of the message under the key; + * - `Authenticator::verify(key_bytes, message_bytes, tag_bytes)`, static, gives `result`. + * + * No AEAD, secret box, stream cipher or `webcpp::hash` MAC is one: none authenticates through + * static members that take the key. + * + * @tparam Authenticator A type, without its reference and qualifiers. + */ +template +concept single_use_key_authenticator = requires(std::span const& key_bytes, + std::span const& message_bytes, + std::span const& tag_bytes) { + { Authenticator::key_size } -> std::convertible_to; + { Authenticator::tag_size } -> std::convertible_to; + typename Authenticator::result_type; + { + Authenticator::authenticate(key_bytes, message_bytes) + } -> std::same_as>; + { + Authenticator::verify(key_bytes, message_bytes, tag_bytes) + } -> std::same_as>; +}; + +/** + * Authenticates a message under a key used for it alone, + * `Authenticator::authenticate(key_bytes, message_bytes)`: the free form of the authenticator's + * static `authenticate`, which it calls, with its results and its errors. + * + * The key authenticates this message and never another: a protocol derives a fresh key for each + * message. A key used for many messages takes `webcpp::hash`'s HMAC. + * + * @tparam Authenticator A `single_use_key_authenticator`: `authenticators::poly1305`. + * @param key_bytes The one-time key, the algorithm's `key_size` bytes. + * @param message_bytes The message, of any length, empty included. + * @return What `Authenticator::authenticate` returns: the tag, or its error + * (`invalid_key_size`, the backend's). + */ +template +[[nodiscard]] boost::system::result authenticate( + std::span key_bytes, + std::span + message_bytes) noexcept(noexcept(Authenticator::authenticate(key_bytes, message_bytes))) { + secure::timing_guard const timing_scope; + return Authenticator::authenticate(key_bytes, message_bytes); +} + +/** + * Verifies a message's tag under a key used for it alone, + * `Authenticator::verify(key_bytes, message_bytes, tag_bytes)`: the free form of the + * authenticator's static `verify`, which it calls, with its results and its errors. + * + * @tparam Authenticator A `single_use_key_authenticator`: `authenticators::poly1305`. + * @param key_bytes The one-time key, the algorithm's `key_size` bytes. + * @param message_bytes The message, of any length, empty included. + * @param tag_bytes The tag to check, the algorithm's `tag_size` bytes. + * @return What `Authenticator::verify` returns: nothing when the tag is the message's, or its + * error (`invalid_key_size`, `invalid_tag_size`, `authentication_failed`, the backend's). + */ +template +[[nodiscard]] boost::system::result verify( + std::span key_bytes, std::span message_bytes, + std::span tag_bytes) noexcept(noexcept(Authenticator::verify(key_bytes, + message_bytes, + tag_bytes))) { + secure::timing_guard const timing_scope; + return Authenticator::verify(key_bytes, message_bytes, tag_bytes); +} + +/** + * Refuses a type that is no single-use key authenticator, a `webcpp::hash` MAC or an AEAD among + * them, with one message that says what it takes. + * + * @tparam Authenticator The type given. + * @tparam Arguments The arguments' types. + */ +template + requires(!single_use_key_authenticator) +void authenticate(Arguments&&... /*arguments*/) noexcept { + static_assert(detail::dependent_false, + "webcpp::crypto: single_use_key_authentication::authenticate takes a single-use " + "key authenticator (authenticators::poly1305); a reusable key's MAC is " + "webcpp::hash::mac (HMAC)."); +} + +/** + * Refuses a type that is no single-use key authenticator, a `webcpp::hash` MAC or an AEAD among + * them, with one message that says what it takes. + * + * @tparam Authenticator The type given. + * @tparam Arguments The arguments' types. + */ +template + requires(!single_use_key_authenticator) +void verify(Arguments&&... /*arguments*/) noexcept { + static_assert(detail::dependent_false, + "webcpp::crypto: single_use_key_authentication::verify takes a single-use key " + "authenticator (authenticators::poly1305); a reusable key's MAC is " + "webcpp::hash::mac (HMAC)."); +} + +} // namespace webcpp::crypto::single_use_key_authentication + +#endif // WEBCPP_CRYPTO_SINGLE_USE_KEY_AUTHENTICATION_AUTHENTICATOR_HPP diff --git a/include/webcpp/crypto/unauthenticated_encryption/stream_cipher.hpp b/include/webcpp/crypto/unauthenticated_encryption/stream_cipher.hpp new file mode 100644 index 0000000..f540775 --- /dev/null +++ b/include/webcpp/crypto/unauthenticated_encryption/stream_cipher.hpp @@ -0,0 +1,160 @@ +// 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 stream cipher's contract (design D3, owner decision 5): the concept + `unauthenticated_encryption::stream_cipher`, what every raw stream cipher is, and the free + synchronous form of its member, `unauthenticated_encryption::apply_keystream(cipher, nonce, data, + initial_counter)`; and `detail::counter_overflows`, the one check of a counter's end that every + stream cipher's `apply_keystream` makes before its backend runs. + + The namespace is named by what its contract is for and warns its reader: encryption that + authenticates nothing, for a protocol that brings its own authentication (NIP-44, whose + HMAC-SHA256 covers the nonce and the ciphertext). A program's own messages are sealed by + `secret_key_encryption`, whose AEADs authenticate. The algorithms that satisfy the concept stay + in `ciphers` under their names; `` includes this header, + so that a program that includes `ciphers/chacha20.hpp` has the free form. It needs no backend. + + The concept reads the algorithm's own shape, `nonce_size`, `block_size` and `counter_type`, never + ChaCha20's (owner decision 7), so that a stream cipher of another shape, as AES-CTR will be, joins + it unchanged. + + @see "Unauthenticated encryption: `webcpp::crypto::unauthenticated_encryption`", in the guide. +*/ +#ifndef WEBCPP_CRYPTO_UNAUTHENTICATED_ENCRYPTION_STREAM_CIPHER_HPP +#define WEBCPP_CRYPTO_UNAUTHENTICATED_ENCRYPTION_STREAM_CIPHER_HPP + +#include + +#include // detail::dependent_false +#include + +#include + +#include +#include +#include +#include +#include + +namespace webcpp::crypto::detail { + +/** + * Whether `data_size` bytes need more `BlockSize`-byte blocks than a counter of type `Counter` + * has left from `initial_counter`, the first block included (owner decision 7): the counter's end, + * from the algorithm's block size and counter width, which every stream cipher's + * `apply_keystream` checks before its backend runs, so that no backend wraps the counter, carries + * it into the nonce or aborts the program. + * + * Computed in 64 bits, the blocks rounded up after the division, with no sum that can wrap: for + * ChaCha20 (64-byte blocks, a 32-bit counter), true exactly when the blocks exceed + * `2^32 - initial_counter`. + * + * @tparam BlockSize The algorithm's block size, in bytes. + * @tparam Counter The algorithm's counter type, a standard unsigned integer of at most 64 bits. + * @param data_size The data's size, in bytes. + * @param initial_counter The counter of the first block. + * @return Whether the data overflows the counter; never for empty data. + */ +template + requires(BlockSize > 0 && std::numeric_limits::digits <= 64) +[[nodiscard]] constexpr bool counter_overflows(std::uint64_t data_size, + Counter initial_counter) noexcept { + std::uint64_t const blocks = (data_size / BlockSize) + (data_size % BlockSize != 0 ? 1U : 0U); + // The parentheses keep windows.h's max macro out. + // NOLINTBEGIN(readability-redundant-parentheses) + std::uint64_t const blocks_after_first = + std::uint64_t{(std::numeric_limits::max)()} - initial_counter; + // NOLINTEND(readability-redundant-parentheses) + return blocks != 0 && blocks - 1 > blocks_after_first; +} + +} // namespace webcpp::crypto::detail + +namespace webcpp::crypto::unauthenticated_encryption { + +/** + * Whether `Cipher` is a raw stream cipher (design D3): no AEAD, since it authenticates nothing. + * + * `ciphers::chacha20` is, and every stream cipher of another shape will be: + * - `Cipher::key_size`, `Cipher::nonce_size` and `Cipher::block_size` (more than 0), sizes in + * bytes, and `typename Cipher::counter_type`, the algorithm's block counter, a standard unsigned + * integer of at most 64 bits; + * - `Cipher::from_key(key_bytes)` gives `result`; + * - `keyed_cipher.apply_keystream(nonce_bytes, data_bytes, initial_counter)` XORs the keystream + * from the block `initial_counter` into `data_bytes`, in place, and gives `result`. + * + * An AEAD is a `secret_key_encryption::aead::cipher`, a secret box a + * `secret_key_encryption::authenticated_box`; neither is a `stream_cipher`. + * + * @tparam Cipher A type, without its reference and qualifiers. + */ +template +concept stream_cipher = + requires(Cipher& keyed_cipher, std::span& key_bytes, + std::span const& nonce_bytes, std::span& data_bytes, + Cipher::counter_type initial_counter) { + { Cipher::key_size } -> std::convertible_to; + { Cipher::nonce_size } -> std::convertible_to; + { Cipher::block_size } -> std::convertible_to; + typename Cipher::counter_type; + requires std::unsigned_integral; + requires std::numeric_limits::digits <= 64; + requires(Cipher::block_size > 0); + { Cipher::from_key(key_bytes) } -> std::same_as>; + { + keyed_cipher.apply_keystream(nonce_bytes, data_bytes, initial_counter) + } -> std::same_as>; + }; + +/** + * XORs the keystream into `data_bytes`, in place, + * `keyed_cipher.apply_keystream(nonce_bytes, data_bytes, initial_counter)`: the free form of the + * stream cipher's own `apply_keystream`, which it calls, with its results and its errors. + * + * Encryption and decryption are this one call. It authenticates nothing: a bit flipped in the + * ciphertext flips the same bit of the plaintext. A protocol that uses it authenticates the nonce + * and the ciphertext itself, as NIP-44 does with HMAC-SHA256; a program's own messages are sealed + * by `secret_key_encryption`. + * + * @tparam Cipher A `stream_cipher`: `ciphers::chacha20`. + * @param keyed_cipher The keyed object. + * @param nonce_bytes The nonce, the algorithm's `nonce_size` bytes, never reused under this key. + * @param data_bytes The data, the plaintext or the ciphertext, XORed in place. + * @param initial_counter The block counter of the first block, the algorithm's `counter_type`. + * @return What `keyed_cipher.apply_keystream` returns: nothing, or its error (`invalid_state`, + * `invalid_nonce_size`, `counter_overflow`, `backend_failure`). + */ +template +[[nodiscard]] boost::system::result apply_keystream( + Cipher& keyed_cipher, std::span nonce_bytes, + std::span data_bytes, + typename Cipher::counter_type + initial_counter) noexcept(noexcept(keyed_cipher.apply_keystream(nonce_bytes, data_bytes, + initial_counter))) { + secure::timing_guard const timing_scope; + return keyed_cipher.apply_keystream(nonce_bytes, data_bytes, initial_counter); +} + +/** + * Refuses a type that is no stream cipher, an AEAD or a block cipher among them, with one message + * that says what it takes. + * + * @tparam Cipher The type given. + * @tparam Arguments The other arguments' types. + */ +template + requires(!stream_cipher) +void apply_keystream(Cipher& /*keyed_cipher*/, Arguments&&... /*arguments*/) noexcept { + static_assert(detail::dependent_false, + "webcpp::crypto: unauthenticated_encryption::apply_keystream takes a stream " + "cipher (ciphers::chacha20); an AEAD seals and opens through " + "secret_key_encryption::aead."); +} + +} // namespace webcpp::crypto::unauthenticated_encryption + +#endif // WEBCPP_CRYPTO_UNAUTHENTICATED_ENCRYPTION_STREAM_CIPHER_HPP diff --git a/meta/include-boundaries.json b/meta/include-boundaries.json index 983b5a7..e3d0dcc 100644 --- a/meta/include-boundaries.json +++ b/meta/include-boundaries.json @@ -12,10 +12,12 @@ "include/webcpp/crypto/random_device.hpp", "include/webcpp/crypto/secret_key_encryption/aead.hpp", "include/webcpp/crypto/secret_key_encryption/authenticated_box.hpp", - "include/webcpp/crypto/signing.hpp" + "include/webcpp/crypto/signing.hpp", + "include/webcpp/crypto/single_use_key_authentication/authenticator.hpp", + "include/webcpp/crypto/unauthenticated_encryption/stream_cipher.hpp" ], "must-not-include": ["bearssl", "openssl/", "ctaes", "secp256k1", "webcpp/crypto/backends/"], - "why": "a program that only draws random bytes names no backend library (spec section 2.2), nor does the signing vocabulary every curve shares, nor the key pair concepts with their free sign and agree, which give webcpp::secure's self-wiping secret, nor the free factories (from_secret, from_bytes, from_key, generate) every AEAD's header includes, nor the AEAD and box contracts with their free seal and open, which every AEAD's and box's header includes; the detail headers these include are in the boundary too, since the rule is not transitive" + "why": "a program that only draws random bytes names no backend library (spec section 2.2), nor does the signing vocabulary every curve shares, nor the key pair concepts with their free sign and agree, which give webcpp::secure's self-wiping secret, nor the free factories (from_secret, from_bytes, from_key, generate) every AEAD's header includes, nor the AEAD and box contracts with their free seal and open, which every AEAD's and box's header includes, nor the stream cipher contract with its free apply_keystream, which every stream cipher's header includes, nor the single-use key authenticator contract with its free authenticate and verify, which every authenticator's header includes; the detail headers these include are in the boundary too, since the rule is not transitive" }, { "headers": [ diff --git a/test/Jamfile b/test/Jamfile index aefe22a..93fc688 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -36,6 +36,10 @@ webcpp.headers-alone crypto : ../include : crypto.hpp crypto/config.hpp crypto/supports.hpp crypto/detail/capabilities.hpp crypto/detail/defaults.hpp crypto/detail/async_access.hpp crypto/ciphers/aead.hpp crypto/ciphers/chacha20_poly1305.hpp + crypto/ciphers/stream_cipher.hpp crypto/ciphers/chacha20.hpp + crypto/authenticators/poly1305.hpp + crypto/unauthenticated_encryption/stream_cipher.hpp + crypto/single_use_key_authentication/authenticator.hpp crypto/secret_key_encryption/aead.hpp crypto/secret_key_encryption/authenticated_box.hpp crypto/secret_key_encryption/secretbox.hpp @@ -179,6 +183,18 @@ crypto-run async_gcm_openssl : async_gcm_test.cpp # never inline, a wrong tag, a refused key. crypto-run async_aead : async_aead_test.cpp : /third_party//sodium /webcpp/asio//asio ; +# ChaCha20's asynchronous from_key and keystream, member and free, on +# libsodium and BearSSL, every target, and on OpenSSL, on native, wasip2 and +# wasip3: RFC 8439's sunscreen, use_awaitable, deferred, never inline, the +# guards' completions with the data untouched. +crypto-run async_stream_cipher : async_stream_cipher_test.cpp + : /third_party//sodium /third_party//bearssl + /webcpp/asio//asio ; +crypto-run async_stream_cipher_openssl : async_stream_cipher_test.cpp + : /third_party//sodium /third_party//bearssl + /webcpp/crypto//openssl /webcpp/asio//asio + WEBCPP_TEST_ASYNC_STREAM_CIPHER_OPENSSL + : native wasip2 wasip3 ; # HPKE's asynchronous forms on libsodium (X25519, ChaCha20-Poly1305) and on # BearSSL (P-256, AES-128-GCM), every target: setups, contexts and single-shot # calls in a coroutine, member and free, never inline, errors. @@ -852,6 +868,103 @@ crypto-run chacha_wycheproof_sodium : chacha_wycheproof_sodium_test.cpp : /third_party//sodium /third_party//wycheproof /webcpp//boost_json ; crypto-run allocation_sodium : allocation_sodium_test.cpp : /third_party//sodium ; + +# ChaCha20, RFC 8439's raw stream cipher, on libsodium, its default on every +# target: RFC 8439's known answers and every check of +# support/stream_cipher_checks.hpp; the concept stream_cipher on it and on the +# AEADs, boxes and block ciphers it refuses, the member and the free form +# alike; and the contract on a stand-in of another shape, with no backend +# (owner decision 7). +crypto-run chacha20_sodium : chacha20_sodium_test.cpp : /third_party//sodium ; +crypto-run stream_cipher_concepts : stream_cipher_concepts_test.cpp + : /third_party//sodium ; +crypto-run stream_cipher_shape : stream_cipher_shape_test.cpp : /webcpp/asio//asio ; + +# Poly1305, RFC 8439's one-time authenticator, on libsodium, its default on +# every target: RFC 8439's known answers against the test's portable reference +# and every check of support/authenticator_checks.hpp; the concept +# single_use_key_authenticator on it and on the AEADs, boxes, stream ciphers +# and hash MACs it refuses, the static members and the free forms alike. +crypto-run poly1305_sodium : poly1305_sodium_test.cpp : /third_party//sodium ; +crypto-run authenticator_concepts : authenticator_concepts_test.cpp + : /third_party//sodium ; +# Poly1305 on OpenSSL, on native, wasip2 and wasip3: every check of +# support/authenticator_checks.hpp; natively again with +# WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE and the adapter not installed, where +# every form gives memory_functions_not_installed, never authentication_failed. +crypto-run poly1305_openssl : poly1305_openssl_test.cpp : /webcpp/crypto//openssl + : native wasip2 wasip3 ; +crypto-run poly1305_openssl_memory_resource : poly1305_openssl_test.cpp + : /webcpp/crypto//openssl WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE + : native ; +# libsodium and OpenSSL against each other and the test's reference on 2000 +# random keys and messages; on Emscripten, which has no OpenSSL, libsodium +# against the reference. +crypto-run agreement_poly1305 : agreement_poly1305_test.cpp + : /third_party//sodium /webcpp/crypto//openssl + : native wasip2 wasip3 ; +crypto-run agreement_poly1305_emscripten : agreement_poly1305_test.cpp + : /third_party//sodium : emscripten ; +# RFC 8439's AEAD composed from the raw ChaCha20 and Poly1305 against each +# backend's ChaCha20-Poly1305 (design D17): the 18 combinations of libsodium, +# BearSSL and OpenSSL on native, wasip2 and wasip3; on Emscripten, which has no +# OpenSSL, the 4 of libsodium and BearSSL. One program links every backend, a +# cross-backend test, as the agreement tests are. +crypto-run composition_rfc8439 : composition_rfc8439_test.cpp + : /third_party//sodium /third_party//bearssl + /webcpp/crypto//openssl + : native wasip2 wasip3 ; +crypto-run composition_rfc8439_emscripten : composition_rfc8439_emscripten_test.cpp + : /third_party//sodium /third_party//bearssl : emscripten ; +# Poly1305's asynchronous forms, static and free, on libsodium, every target, +# and on OpenSSL, on native, wasip2 and wasip3: the synchronous tag and errors, +# use_awaitable, deferred, never inline, an error's tag zeroed. +crypto-run async_authenticator : async_authenticator_test.cpp + : /third_party//sodium /webcpp/asio//asio ; +crypto-run async_authenticator_openssl : async_authenticator_test.cpp + : /third_party//sodium /webcpp/crypto//openssl /webcpp/asio//asio + WEBCPP_TEST_ASYNC_AUTHENTICATOR_OPENSSL + : native wasip2 wasip3 ; + +# ChaCha20 on BearSSL, on every target, its portable code through the seam +# too, and on OpenSSL, on native, wasip2 and wasip3: every check of +# support/stream_cipher_checks.hpp. The three backends against one another and +# the test's reference on random keys, nonces, counters and lengths; on +# Emscripten, which has no OpenSSL, libsodium against BearSSL. +crypto-run chacha20_bearssl : chacha20_bearssl_test.cpp : /third_party//bearssl ; +crypto-run chacha20_bearssl_portable : chacha20_bearssl_portable_test.cpp + : /third_party//bearssl WEBCPP_CRYPTO_DETAIL_BEARSSL_PORTABLE ; +crypto-run chacha20_openssl : chacha20_openssl_test.cpp : /webcpp/crypto//openssl + : native wasip2 wasip3 ; +crypto-run agreement_chacha20 : agreement_chacha20_test.cpp + : /third_party//sodium /third_party//bearssl + /webcpp/crypto//openssl + : native wasip2 wasip3 ; +crypto-run agreement_chacha20_emscripten : agreement_chacha20_test.cpp + : /third_party//sodium /third_party//bearssl + : emscripten ; +crypto-run agreement_chacha20_portable : agreement_chacha20_portable_test.cpp + : /third_party//sodium /third_party//bearssl + /webcpp/crypto//openssl WEBCPP_CRYPTO_DETAIL_BEARSSL_PORTABLE + : native wasip2 wasip3 ; +crypto-run agreement_chacha20_portable_emscripten : agreement_chacha20_portable_test.cpp + : /third_party//sodium /third_party//bearssl + WEBCPP_CRYPTO_DETAIL_BEARSSL_PORTABLE + : emscripten ; +# NIP-44 version 2's valid vectors end to end through ChaCha20 on each backend, +# NIP-44 composed in the tests alone from secp256k1's agree, webcpp::hash's +# HKDF and HMAC and webcpp::codecs' base64: OpenSSL's on native, wasip2 and +# wasip3, the others' on every target. +crypto-run chacha20_nip44_sodium : chacha20_nip44_sodium_test.cpp + : /third_party//nip44 /third_party//secp256k1 + /third_party//sodium /webcpp//boost_json ; +crypto-run chacha20_nip44_bearssl : chacha20_nip44_bearssl_test.cpp + : /third_party//nip44 /third_party//secp256k1 + /third_party//bearssl /webcpp//boost_json ; +crypto-run chacha20_nip44_openssl : chacha20_nip44_openssl_test.cpp + : /third_party//nip44 /third_party//secp256k1 + /webcpp/crypto//openssl /webcpp//boost_json + : native wasip2 wasip3 ; # HPKE allocates nothing on libsodium and BearSSL, every suite, and caps no # input: long inputs round-trip and match webcpp::hash's HKDF on the joined # labeled inputs. @@ -1039,6 +1152,12 @@ webcpp.compile doc_chacha20_poly1305_original_default_app webcpp.compile doc_xchacha20_poly1305_default_app : ../../../tools/test/fixtures/crypto_jamfiles/xchacha20_poly1305_default/app.cpp : /webcpp/crypto//xchacha20_poly1305-default ; +webcpp.compile doc_chacha20_default_app + : ../../../tools/test/fixtures/crypto_jamfiles/chacha20_default/app.cpp + : /webcpp/crypto//chacha20-default ; +webcpp.compile doc_poly1305_default_app + : ../../../tools/test/fixtures/crypto_jamfiles/poly1305_default/app.cpp + : /webcpp/crypto//poly1305-default ; webcpp.compile doc_secretbox_xsalsa20poly1305_default_app : ../../../tools/test/fixtures/crypto_jamfiles/secretbox_xsalsa20poly1305_default/app.cpp : /webcpp/crypto//secretbox_xsalsa20poly1305-default ; diff --git a/test/agreement_chacha20_portable_test.cpp b/test/agreement_chacha20_portable_test.cpp new file mode 100644 index 0000000..902b860 --- /dev/null +++ b/test/agreement_chacha20_portable_test.cpp @@ -0,0 +1,12 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// agreement_chacha20_test.cpp with WEBCPP_CRYPTO_DETAIL_BEARSSL_PORTABLE, which the Jamfile +// defines: BearSSL on chacha20_ct against libsodium, OpenSSL and the reference. A source of its +// own, so that b2 compiles it with its own defines (spec section 4.3's pitfall); the code is +// shared. + +#include "agreement_chacha20_test.cpp" // NOLINT(bugprone-suspicious-include): one program, twice diff --git a/test/agreement_chacha20_test.cpp b/test/agreement_chacha20_test.cpp new file mode 100644 index 0000000..db596f1 --- /dev/null +++ b/test/agreement_chacha20_test.cpp @@ -0,0 +1,228 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// ChaCha20 on libsodium, BearSSL and OpenSSL against one another and against the test's portable +// reference (design D9), from a fixed seed and from one the system draws, printed first; on +// Emscripten, which has no OpenSSL, libsodium against BearSSL. Each run: 2000 random cases of +// key, nonce, initial counter (0, 1, a random one that fits the data, the last that fits) and +// length (0 to 1024 bytes, or 63, 64, 65, 127, 128, 129 or 64 KiB); two calls that continue by +// the counter equal one; one object reused with several nonces and counters. Natively in a +// release build, one case of 2^30 + 64 bytes, which OpenSSL takes in two pieces, 2^30 bytes then +// 64 (its ChaCha20 pieces are 2^30 bytes, design R18; Review Focus 4). +// agreement_chacha20_portable_test.cpp compiles this source again with +// WEBCPP_CRYPTO_DETAIL_BEARSSL_PORTABLE defined, so that both of BearSSL's code paths meet the +// others'; each program first checks that BearSSL runs the code the seam says. + +#include +#include +#ifdef WEBCPP_CRYPTO_HAS_OPENSSL +#include +#endif +#include +#include + +#include "support/agreement.hpp" +#include "support/stream_cipher_checks.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace crypto = webcpp::crypto; + +using sodium_cipher = crypto::ciphers::chacha20; +using bearssl_cipher = crypto::ciphers::chacha20; +#ifdef WEBCPP_CRYPTO_HAS_OPENSSL +using openssl_cipher = crypto::ciphers::chacha20; +#endif + +/** Checks that BearSSL runs the code the seam selects. */ +void check_code_paths() { +#ifdef WEBCPP_CRYPTO_DETAIL_BEARSSL_PORTABLE + // On every target the seam keeps the constant-time portable code. + BOOST_TEST(crypto::detail::bearssl_chacha20() == &br_chacha20_ct_run); +#else + // Without it, SSE2's ChaCha20 where the CPU and the build have it. + br_chacha20_run const sse2 = br_chacha20_sse2_get(); + BOOST_TEST(crypto::detail::bearssl_chacha20() == + (sse2 != nullptr ? sse2 : &br_chacha20_ct_run)); + std::printf("BearSSL's ChaCha20: %s\n", sse2 != nullptr ? "SSE2" : "ct"); +#endif +} + +/** The reference's keystream XORed into `data`, from the block `counter`. */ +void reference_apply(std::span key, std::span nonce, + std::uint32_t counter, std::span data) { + for (std::size_t offset = 0; offset < data.size(); offset += 64) { + auto const block = webcpp::test::reference_chacha20_block( + key, nonce, static_cast(counter + (offset / 64))); + for (std::size_t i = 0; i < 64 && offset + i < data.size(); ++i) { + data[offset + i] ^= block[i]; + } + } +} + +/** Applies `Cipher`'s keystream to a copy of `message`; empty when a call fails. */ +template +std::vector applied(std::span key, + std::span nonce, std::uint32_t counter, + std::vector message) { + auto made = Cipher::from_key(key); + if (!BOOST_TEST(made.has_value()) || + !BOOST_TEST(made->apply_keystream(nonce, message, counter).has_value())) { + return {}; + } + return message; +} + +/** One case on every backend of the target and the reference; false once they disagree. */ +bool agree_once(std::mt19937_64& generator, std::uint64_t seed) { + constexpr std::array fixed_sizes{63, 64, 65, 127, 128, 129, 65536}; + std::size_t const size = + generator() % 2 == 0 ? generator() % 1025 : fixed_sizes[generator() % fixed_sizes.size()]; + std::uint64_t const blocks = (size + 63) / 64; + // The last counter at which the data still fits: 2^32 - blocks. + std::uint64_t const last_fitting = (std::uint64_t{1} << 32U) - (blocks == 0 ? 1 : blocks); + std::uint32_t counter = 0; + switch (generator() % 4) { + case 0: counter = 0; break; + case 1: counter = 1; break; + case 2: counter = static_cast(generator() % (last_fitting + 1)); break; + default: counter = static_cast(last_fitting); break; + } + auto const key = webcpp::test::random_bytes(generator, 32); + auto const nonce = webcpp::test::random_bytes(generator, 12); + auto const message = webcpp::test::random_bytes(generator, size); + auto expected = message; + reference_apply(key, nonce, counter, expected); + bool same = applied(key, nonce, counter, message) == expected && + applied(key, nonce, counter, message) == expected; +#ifdef WEBCPP_CRYPTO_HAS_OPENSSL + same = same && applied(key, nonce, counter, message) == expected; +#endif + if (!BOOST_TEST(same)) { + webcpp::test::print_disagreement(seed, "ChaCha20", 32, size); + } + return same; +} + +/** Two calls that continue by the counter equal one, and one object takes several nonces. */ +template +void continue_and_reuse(std::mt19937_64& generator) { + auto const key = webcpp::test::random_bytes(generator, 32); + auto made = Cipher::from_key(key); + if (!BOOST_TEST(made.has_value())) { + return; + } + for (int round = 0; round < 8; ++round) { + auto const nonce = webcpp::test::random_bytes(generator, 12); + auto const counter = static_cast(generator() % 1000); + auto const message = webcpp::test::random_bytes(generator, (64 * 5) + 17); + auto whole = message; + auto pieces = message; + auto expected = message; + reference_apply(key, nonce, counter, expected); + BOOST_TEST(made->apply_keystream(nonce, whole, counter).has_value()); + BOOST_TEST(made->apply_keystream(nonce, std::span(pieces).first(128), counter).has_value()); + BOOST_TEST( + made->apply_keystream(nonce, std::span(pieces).subspan(128), counter + 2).has_value()); + BOOST_TEST(whole == expected); + BOOST_TEST(pieces == expected); + } +} + +/** Every backend of the target from one seed. */ +void agree(std::uint64_t seed) { + std::mt19937_64 generator(seed); + for (int index = 0; index < 2000; ++index) { + if (!agree_once(generator, seed)) { + return; + } + } + continue_and_reuse(generator); + continue_and_reuse(generator); +#ifdef WEBCPP_CRYPTO_HAS_OPENSSL + continue_and_reuse(generator); +#endif +} + +#if !defined(__wasi__) && !defined(__EMSCRIPTEN__) && defined(NDEBUG) +/** Applies `Cipher`'s keystream to `data`, in place; false when a call fails. */ +template +bool apply_in_place(std::span key, std::span nonce, + std::uint32_t counter, std::span data) { + auto made = Cipher::from_key(key); + return BOOST_TEST(made.has_value()) && + BOOST_TEST(made->apply_keystream(nonce, data, counter).has_value()); +} +#endif + +/** + * Natively in a release build, one case of 2^30 + 64 bytes, which crosses the end of OpenSSL's + * first piece of 2^30 bytes (`detail::openssl_chacha20_piece`): every backend gives the same bytes. + * One buffer of the message's size, applied in place: libsodium's keystream, whose last block is + * the reference's; then each other backend's keystream over it and libsodium's again, which restore + * the message exactly when the keystreams are equal. + */ +void agree_large() { +#if !defined(__wasi__) && !defined(__EMSCRIPTEN__) && defined(NDEBUG) + if constexpr (sizeof(std::size_t) == 8) { + constexpr std::uint8_t filler = 0x5a; + constexpr std::uint32_t counter = 3; + std::vector const key(32, 0x42); + std::vector const nonce(12, 0x24); + std::vector data((std::size_t{1} << 30U) + 64, filler); + auto const restored = [&data] { + return std::ranges::all_of(data, [](std::uint8_t byte) { return byte == filler; }); + }; + if (!apply_in_place(key, nonce, counter, data)) { + return; + } + auto const last_block = webcpp::test::reference_chacha20_block( + key, nonce, counter + static_cast((data.size() - 64) / 64)); + bool last_is_reference = true; + for (std::size_t i = 0; i < 64; ++i) { + last_is_reference = + last_is_reference && + data[data.size() - 64 + i] == static_cast(filler ^ last_block[i]); + } + BOOST_TEST(last_is_reference); + BOOST_TEST(apply_in_place(key, nonce, counter, data)); + BOOST_TEST(restored()); +#ifdef WEBCPP_CRYPTO_HAS_OPENSSL + BOOST_TEST(apply_in_place(key, nonce, counter, data)); + BOOST_TEST(apply_in_place(key, nonce, counter, data)); + BOOST_TEST(restored()); +#endif + std::printf("2^30 + 64 bytes: agree\n"); + } +#else + std::printf("2^30 + 64 bytes: natively in a release build only\n"); +#endif +} + +} // namespace + +int main() { + check_code_paths(); + // A fixed seed, so that a failure repeats. + agree(20261205); + std::uint64_t const seed = std::random_device{}(); + std::printf("seed %llu\n", static_cast(seed)); + agree(seed); + agree_large(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/agreement_poly1305_test.cpp b/test/agreement_poly1305_test.cpp new file mode 100644 index 0000000..0ec21d4 --- /dev/null +++ b/test/agreement_poly1305_test.cpp @@ -0,0 +1,89 @@ +// 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) + +// Poly1305 on libsodium and OpenSSL against each other and against the test's portable reference +// (design D16), from a fixed seed and from one the system draws, printed first; on Emscripten, +// which has no OpenSSL, libsodium against the reference alone. Each run: 2000 random keys and +// messages (0 to 1024 bytes, or 15, 16, 17 or 64 KiB), each backend's tag equal to the reference's +// and verified by every backend. + +#include +#include +#ifdef WEBCPP_CRYPTO_HAS_OPENSSL +#include +#endif +#include + +#include "support/agreement.hpp" +#include "support/authenticator_checks.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace crypto = webcpp::crypto; + +using sodium_poly1305 = crypto::authenticators::poly1305; +#ifdef WEBCPP_CRYPTO_HAS_OPENSSL +using openssl_poly1305 = crypto::authenticators::poly1305; +#endif + +/** `Authenticator`'s tag equals `expected`, and `Authenticator` verifies it. */ +template +bool tagged_as(std::span key, std::span message, + std::array const& expected) { + auto const tag = Authenticator::authenticate(key, message); + return BOOST_TEST(tag.has_value()) && std::ranges::equal(*tag, expected) && + BOOST_TEST(Authenticator::verify(key, message, expected).has_value()); +} + +/** One case on every backend of the target and the reference; false once they disagree. */ +bool agree_once(std::mt19937_64& generator, std::uint64_t seed) { + constexpr std::array fixed_sizes{15, 16, 17, 65536}; + std::size_t const size = + generator() % 2 == 0 ? generator() % 1025 : fixed_sizes[generator() % fixed_sizes.size()]; + auto const key = webcpp::test::random_bytes(generator, 32); + auto const message = webcpp::test::random_bytes(generator, size); + auto const expected = webcpp::test::reference_poly1305(key, message); + bool same = tagged_as(key, message, expected); +#ifdef WEBCPP_CRYPTO_HAS_OPENSSL + same = tagged_as(key, message, expected) && same; +#endif + if (!BOOST_TEST(same)) { + webcpp::test::print_disagreement(seed, "Poly1305", 32, size); + } + return same; +} + +/** Every backend of the target from one seed. */ +void agree(std::uint64_t seed) { + std::mt19937_64 generator(seed); + for (int index = 0; index < 2000; ++index) { + if (!agree_once(generator, seed)) { + return; + } + } +} + +} // namespace + +int main() { + // A fixed seed, so that a failure repeats. + agree(20261205); + std::uint64_t const seed = std::random_device{}(); + std::printf("seed %llu\n", static_cast(seed)); + agree(seed); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/allocation_bearssl_test.cpp b/test/allocation_bearssl_test.cpp index 66d8daa..26e1a49 100644 --- a/test/allocation_bearssl_test.cpp +++ b/test/allocation_bearssl_test.cpp @@ -6,14 +6,15 @@ // On BearSSL nothing allocates (spec section 3.2): from_key, seal, open, the incremental seal, // equal and random_device's fill, ChaCha20-Poly1305's from_key, seal, open (good and failed) -// and move, and P-256's key pair from_secret and generate, public key from_bytes and -// from_coordinates, sign(ecdsa_sha256, ...) and crypto::verify of a message and of a digest, -// low_s, is_low_s, agree, and the formats (the signature's der both ways, the key's spki and its -// compressed point, the key pair's pkcs8, each encoded into a span and decoded) make no call of -// operator new, nor of the C library's allocator where the target lets a program count it; a -// control proves the counter moves. +// and move, ChaCha20's from_key, apply_keystream and move, and P-256's key pair from_secret and +// generate, public key from_bytes and from_coordinates, sign(ecdsa_sha256, ...) and crypto::verify +// of a message and of a digest, low_s, is_low_s, agree, and the formats (the signature's der both +// ways, the key's spki and its compressed point, the key pair's pkcs8, each encoded into a span and +// decoded) make no call of operator new, nor of the C library's allocator where the target lets a +// program count it; a control proves the counter moves. #include +#include #include #include #include @@ -149,6 +150,11 @@ int main() { BOOST_TEST(sealer->open(nonce, nonce, data, forged).error() == crypto::error::authentication_failed); chacha const moved = std::move(*sealer); + using stream = crypto::ciphers::chacha20; + auto streamer = stream::from_key(key); + BOOST_TEST(streamer.has_value()); + BOOST_TEST(streamer->apply_keystream(nonce, data, 1).has_value()); + stream const moved_stream = std::move(*streamer); p256_calls(); } BOOST_TEST_EQ(webcpp::test::allocations(), before); diff --git a/test/allocation_openssl_test.cpp b/test/allocation_openssl_test.cpp index 5049571..0b89c23 100644 --- a/test/allocation_openssl_test.cpp +++ b/test/allocation_openssl_test.cpp @@ -6,14 +6,19 @@ // On OpenSSL a message allocates nothing (spec section 8.5): after from_key, which allocates // through OpenSSL's functions (counted here and printed, not refused), seal, open (good and -// failed), the incremental seal, encrypt and decrypt, and ChaCha20-Poly1305's seal and open -// (good and failed) make no call of OpenSSL's allocator, of -// operator new, nor of the C library's allocator where the target lets a program count it. -// OpenSSL's allocations are outside the user's allocator (the accepted departure); its count -// is measured per target on OpenSSL 3.5.9 (native with assembly; MSVC, wasip2 and wasip3 -// without it). - +// failed), the incremental seal, encrypt and decrypt, ChaCha20-Poly1305's seal and open +// (good and failed) and ChaCha20's apply_keystream, twice on one object, make no call of OpenSSL's +// allocator, of operator new, nor of the C library's allocator where the target lets a program +// count it. OpenSSL's allocations are outside the user's allocator (the accepted departure); its +// count is measured per target on OpenSSL 3.5.9 (native with assembly; MSVC, wasip2 and wasip3 +// without it). Poly1305, which has no object, makes and frees its MAC context in each call (R26): +// its authenticate and verify (good and failed) allocate through OpenSSL's functions alone +// (counted and printed), never through operator new, and the C library's allocator, where it is +// counted, no more than OpenSSL's functions called it. + +#include #include +#include #include #include @@ -57,6 +62,40 @@ void counting_free(void* p, char const* /*file*/, int /*line*/) { WEBCPP_TEST_OPENSSL_C(free)(p); } +/** + * Poly1305's authenticate and verify, good and failed: OpenSSL's functions allocate the MAC + * context, operator new never, and the C library, where it is counted, no more than OpenSSL's + * functions called it. + */ +void expect_poly1305_through_openssl_alone() { + using poly1305 = webcpp::crypto::authenticators::poly1305; + std::array key{}; + key.fill(3); + std::array message{}; + message.fill(9); + std::array const wrong_tag{}; + std::size_t const own_before = openssl_allocations.load(); + std::size_t const new_before = webcpp::test::counted_new.load(); + std::size_t const c_before = webcpp::test::counted_c.load(); + auto const tag = poly1305::authenticate(key, message); + bool const verified = tag.has_value() && poly1305::verify(key, message, *tag).has_value(); + bool const refused = poly1305::verify(key, message, wrong_tag).error() == + webcpp::crypto::error::authentication_failed; + std::size_t const own_count = openssl_allocations.load() - own_before; + std::size_t const new_count = webcpp::test::counted_new.load() - new_before; + std::size_t const c_count = webcpp::test::counted_c.load() - c_before; + std::printf( + "Poly1305's authenticate and two verify: %zu allocations through OpenSSL's " + "functions\n", + own_count); + BOOST_TEST(tag.has_value()); + BOOST_TEST(verified); + BOOST_TEST(refused); + BOOST_TEST_GT(own_count, 0U); + BOOST_TEST_EQ(new_count, 0U); + BOOST_TEST_LE(c_count, own_count); +} + } // namespace int main() { @@ -85,7 +124,12 @@ int main() { std::size_t const chacha_count = openssl_allocations.load() - chacha_first; BOOST_TEST(chacha.has_value()); std::printf("ChaCha20-Poly1305's from_key: %zu\n", chacha_count); - if (!made.has_value() || !second.has_value() || !chacha.has_value()) { + std::size_t const stream_first = openssl_allocations.load(); + auto stream = crypto::ciphers::chacha20::from_key(key); + std::size_t const stream_count = openssl_allocations.load() - stream_first; + BOOST_TEST(stream.has_value()); + std::printf("ChaCha20's from_key: %zu\n", stream_count); + if (!made.has_value() || !second.has_value() || !chacha.has_value() || !stream.has_value()) { return webcpp::test::exit_status(boost::report_errors()); } @@ -112,6 +156,8 @@ int main() { bool const chacha_opened = chacha_sealed && chacha->open(nonce, nonce, data, *chacha_tag).has_value(); bool const chacha_refused = !chacha->open(nonce, nonce, data, wrong).has_value(); + bool const streamed = stream->apply_keystream(nonce, data, 1).has_value() && + stream->apply_keystream(nonce, data, 7).has_value(); std::size_t const after = webcpp::test::allocations(); std::size_t const own_after = openssl_allocations.load(); BOOST_TEST(sealed); @@ -126,7 +172,9 @@ int main() { BOOST_TEST(chacha_sealed); BOOST_TEST(chacha_opened); BOOST_TEST(chacha_refused); + BOOST_TEST(streamed); BOOST_TEST_EQ(own_after, own_before); BOOST_TEST_EQ(after, before); + expect_poly1305_through_openssl_alone(); return webcpp::test::exit_status(boost::report_errors()); } diff --git a/test/allocation_sodium_test.cpp b/test/allocation_sodium_test.cpp index fb39682..f9b689b 100644 --- a/test/allocation_sodium_test.cpp +++ b/test/allocation_sodium_test.cpp @@ -5,17 +5,20 @@ // https://www.boost.org/LICENSE_1_0.txt) // On libsodium nothing allocates: from_key, seal and open of the three ChaCha20-Poly1305 AEADs and -// of the two secret boxes, a failed open included; Ed25519's key pair, signature, -// verification under canonical, Ed25519ph and the conversion to X25519; X25519's public key and -// agreement, a refused one included; crypto_kx's key pairs, from a seed and from an X25519 key -// pair, and session keys, a refused peer included; RFC 8410's SPKI and PKCS#8 of both curves and -// their PEM, both ways, both key pairs' raw too, through codecs::encode and codecs::decode; -// the two boxes' from_keys, seal and open, a refused peer key and a failed open included; and the -// sealed boxes' seal and open, a failed open included, make no call of operator new, nor of the C -// library's allocator where the target lets a program count it; a control proves the counter moves. -// Each later family on libsodium adds its calls here. +// of the two secret boxes, ChaCha20's from_key and apply_keystream of 1 KiB, Poly1305's +// authenticate and verify of 1 KiB, a failed verification included, a failed open included; +// Ed25519's key pair, signature, verification under canonical, Ed25519ph and the conversion to +// X25519; X25519's public key and agreement, a refused one included; crypto_kx's key pairs, from a +// seed and from an X25519 key pair, and session keys, a refused peer included; RFC 8410's SPKI and +// PKCS#8 of both curves and their PEM, both ways, both key pairs' raw too, through codecs::encode +// and codecs::decode; the two boxes' from_keys, seal and open, a refused peer key and a failed open +// included; and the sealed boxes' seal and open, a failed open included, make no call of operator +// new, nor of the C library's allocator where the target lets a program count it; a control proves +// the counter moves. Each later family on libsodium adds its calls here. +#include #include +#include #include #include #include @@ -402,6 +405,46 @@ void expect_no_allocation_kx() { BOOST_TEST_EQ(webcpp::test::allocations(), before); } +/** Makes a ChaCha20 and applies its keystream to 1 KiB, both ways: none of it allocates. */ +void expect_no_allocation_chacha20() { + std::array key{}; + key.fill(3); + std::array const nonce{}; + std::array data{}; + std::size_t const before = webcpp::test::allocations(); + { + auto made = crypto::ciphers::chacha20::from_key(key); + BOOST_TEST(made.has_value()); + BOOST_TEST(made->apply_keystream(nonce, data, 1).has_value()); + BOOST_TEST(made->apply_keystream(nonce, data, 1).has_value()); + std::array const zeroes{}; + BOOST_TEST(data == zeroes); + } + BOOST_TEST_EQ(webcpp::test::allocations(), before); +} + +/** Authenticates 1 KiB under Poly1305 and verifies its tag and a wrong one: none of it allocates. + */ +void expect_no_allocation_poly1305() { + using poly1305 = crypto::authenticators::poly1305; + std::array key{}; + key.fill(3); + std::array message{}; + message.fill(9); + std::array const wrong_tag{}; + std::size_t const before = webcpp::test::allocations(); + { + auto const tag = poly1305::authenticate(key, message); + BOOST_TEST(tag.has_value()); + if (tag) { + BOOST_TEST(poly1305::verify(key, message, *tag).has_value()); + } + BOOST_TEST(poly1305::verify(key, message, wrong_tag).error() == + crypto::error::authentication_failed); + } + BOOST_TEST_EQ(webcpp::test::allocations(), before); +} + } // namespace int main() { @@ -434,5 +477,7 @@ int main() { expect_no_allocation_formats(); expect_no_allocation_x25519_formats(); expect_no_allocation_kx(); + expect_no_allocation_chacha20(); + expect_no_allocation_poly1305(); return webcpp::test::exit_status(boost::report_errors()); } diff --git a/test/async_authenticator_test.cpp b/test/async_authenticator_test.cpp new file mode 100644 index 0000000..4b5295e --- /dev/null +++ b/test/async_authenticator_test.cpp @@ -0,0 +1,351 @@ +// 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) + +// Poly1305's asynchronous forms (design D15): the static async_authenticate and async_verify and +// the free single_use_key_authentication::async_authenticate and async_verify, on libsodium and, +// where linked, on OpenSSL, synchronous backends: each runs the synchronous call when the +// operation is initiated and completes through a post, never inside the call. +// - callbacks: every form gives RFC 8439 section 2.5.2's tag and verifies it; invalid_key_size, +// invalid_tag_size and authentication_failed complete as the synchronous calls return them, and +// an error's tag is zeroed. +// - coroutine: in a coroutine (use_awaitable), the four forms, the tag and the verification. +// - deferred: with deferred, each form completes nothing before it is launched, then the same tag +// and verdict. +// - never_inline: a callback's flag is unset when each form returns and set after the context +// runs. +// - fallback: a single-use key authenticator without the asynchronous members, through the free +// forms, has its synchronous calls posted. +// - At compile time, on a stand-in backend that completes by itself: authenticators::poly1305 is +// still a single_use_key_authenticator by its shape (its members refuse when instantiated, the +// message tests pin it). + +#include "support/authenticator_checks.hpp" +#include "support/hex.hpp" + +#include +#include +#include +#include +#include +#include +#include +#ifdef WEBCPP_TEST_ASYNC_AUTHENTICATOR_OPENSSL +#include +#endif + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// A backend that completes by itself, as part B's browser backend will: its types are named, never +// made. +namespace { + +struct stand_in_browser {}; + +} // namespace + +template <> +inline constexpr bool webcpp::crypto::detail::asynchronous_backend_v = true; + +namespace asio = webcpp::asio; +namespace crypto = webcpp::crypto; +namespace single_use_key_authentication = crypto::single_use_key_authentication; + +// The concept reads the shape alone: on the stand-in, which completes by itself, the type still has +// it, and each member stops the build only where it is instantiated. +static_assert(crypto::detail::asynchronous_backend_v); +static_assert(single_use_key_authentication::single_use_key_authenticator< + crypto::authenticators::poly1305>); + +namespace { + +using webcpp::test::from_hex; +using webcpp::test::to_hex; + +/** RFC 8439 section 2.5.2's key, message and tag. */ +struct known_answer { + std::vector key = from_hex(webcpp::test::poly1305_cases[0].key); + std::vector message = from_hex(webcpp::test::poly1305_cases[0].message); + std::vector tag = from_hex(webcpp::test::poly1305_cases[0].tag); +}; + +/** What one completion with a tag handed over. */ +struct tag_completion { + int calls = 0; + boost::system::error_code code; + std::string tag; +}; + +/** What one completion of a verification handed over. */ +struct verify_completion { + int calls = 0; + boost::system::error_code code = crypto::error::backend_failure; +}; + +/** Keeps a completion with a tag, which must be the authenticator's `result_type`. */ +template +auto keep_tag(tag_completion& done) { + return [&done](boost::system::error_code code, auto const& tag) { + static_assert(std::is_same_v, + typename Authenticator::result_type>); + ++done.calls; + done.code = code; + done.tag = to_hex(tag); + }; +} + +/** Keeps a completion of a verification. */ +inline auto keep_verdict(verify_completion& done) { + return [&done](boost::system::error_code code) { + ++done.calls; + done.code = code; + }; +} + +void run(asio::io_context& context) { + context.restart(); + context.run(); // lint-run: the test's event loop +} + +// Every form with a callback: the known tag, its verification, and the synchronous errors, an +// error's tag zeroed. +template +void callback_case(asio::io_context& context) { + known_answer const answer; + auto const executor = context.get_executor(); + auto const zeroed = std::string(32, '0'); + std::array tags{}; + Authenticator::async_authenticate(executor, answer.key, answer.message, + keep_tag(tags[0])); + single_use_key_authentication::async_authenticate( + executor, answer.key, answer.message, keep_tag(tags[1])); + Authenticator::async_authenticate(executor, std::span(answer.key).first(31), answer.message, + keep_tag(tags[2])); + single_use_key_authentication::async_authenticate( + executor, std::span(answer.key).first(31), answer.message, + keep_tag(tags[3])); + auto wrong_tag = answer.tag; + wrong_tag.back() ^= 0x01U; + std::array verdicts{}; + Authenticator::async_verify(executor, answer.key, answer.message, answer.tag, + keep_verdict(verdicts[0])); + single_use_key_authentication::async_verify( + executor, answer.key, answer.message, answer.tag, keep_verdict(verdicts[1])); + Authenticator::async_verify(executor, answer.key, answer.message, wrong_tag, + keep_verdict(verdicts[2])); + single_use_key_authentication::async_verify( + executor, answer.key, answer.message, wrong_tag, keep_verdict(verdicts[3])); + Authenticator::async_verify(executor, answer.key, answer.message, + std::span(answer.tag).first(15), keep_verdict(verdicts[4])); + single_use_key_authentication::async_verify(executor, answer.key, answer.message, + std::span(answer.tag).first(15), + keep_verdict(verdicts[5])); + Authenticator::async_verify(executor, std::span(answer.key).first(31), answer.message, + std::span(answer.tag).first(15), keep_verdict(verdicts[6])); + single_use_key_authentication::async_verify( + executor, std::span(answer.key).first(31), answer.message, std::span(answer.tag).first(15), + keep_verdict(verdicts[7])); + // Nothing completes inline, an error included: each completion is posted. + for (auto const& done : tags) { + BOOST_TEST_EQ(done.calls, 0); + } + for (auto const& done : verdicts) { + BOOST_TEST_EQ(done.calls, 0); + } + run(context); + for (auto const& done : tags) { + BOOST_TEST_EQ(done.calls, 1); + } + for (auto const& done : verdicts) { + BOOST_TEST_EQ(done.calls, 1); + } + for (std::size_t const index : {0U, 1U}) { + BOOST_TEST(!tags[index].code); + BOOST_TEST_EQ(tags[index].tag, webcpp::test::poly1305_cases[0].tag); + BOOST_TEST(!verdicts[index].code); + BOOST_TEST(verdicts[2 + index].code == crypto::error::authentication_failed); + BOOST_TEST(verdicts[4 + index].code == crypto::error::invalid_tag_size); + BOOST_TEST(verdicts[6 + index].code == crypto::error::invalid_key_size); + BOOST_TEST(tags[2 + index].code == crypto::error::invalid_key_size); + BOOST_TEST_EQ(tags[2 + index].tag, zeroed); + } +} + +// The four forms in a coroutine: the tag, member and free, and its verification, member and free. +template +asio::awaitable coroutine_round_trip() { + known_answer const answer; + auto const executor = co_await asio::this_coro::executor; + auto const member = co_await Authenticator::async_authenticate( + executor, answer.key, answer.message, asio::use_awaitable); + BOOST_TEST_EQ(to_hex(member), webcpp::test::poly1305_cases[0].tag); + auto const free = co_await single_use_key_authentication::async_authenticate( + executor, answer.key, answer.message, asio::use_awaitable); + BOOST_TEST_EQ(to_hex(free), webcpp::test::poly1305_cases[0].tag); + co_await Authenticator::async_verify(executor, answer.key, answer.message, member, + asio::use_awaitable); + co_await single_use_key_authentication::async_verify( + executor, answer.key, answer.message, free, asio::use_awaitable); +} + +// Runs a coroutine to its end on the context, which it must reach without an exception. +void run_coroutine(asio::io_context& context, asio::awaitable coroutine) { + bool finished = false; + asio::co_spawn(context, std::move(coroutine), [&finished](std::exception_ptr const& failure) { + BOOST_TEST(!failure); + finished = true; + }); + run(context); + BOOST_TEST(finished); +} + +// deferred: each form runs when it is launched, not when it is made, and gives the same tag and +// verdict. +template +void deferred_case(asio::io_context& context) { + known_answer const answer; + auto const executor = context.get_executor(); + for (bool const member : {false, true}) { + tag_completion tagged; + verify_completion verified; + if (member) { + auto authenticating = Authenticator::async_authenticate(executor, answer.key, + answer.message, asio::deferred); + auto verifying = Authenticator::async_verify(executor, answer.key, answer.message, + answer.tag, asio::deferred); + run(context); + BOOST_TEST_EQ(tagged.calls + verified.calls, 0); + std::move(authenticating)(keep_tag(tagged)); + std::move(verifying)(keep_verdict(verified)); + } else { + auto authenticating = single_use_key_authentication::async_authenticate( + executor, answer.key, answer.message, asio::deferred); + auto verifying = single_use_key_authentication::async_verify( + executor, answer.key, answer.message, answer.tag, asio::deferred); + run(context); + BOOST_TEST_EQ(tagged.calls + verified.calls, 0); + std::move(authenticating)(keep_tag(tagged)); + std::move(verifying)(keep_verdict(verified)); + } + BOOST_TEST_EQ(tagged.calls + verified.calls, 0); + run(context); + BOOST_TEST_EQ(tagged.calls, 1); + BOOST_TEST_EQ(verified.calls, 1); + BOOST_TEST(!tagged.code); + BOOST_TEST_EQ(tagged.tag, webcpp::test::poly1305_cases[0].tag); + BOOST_TEST(!verified.code); + } +} + +// A flag a callback sets: unset when the initiating call returns, set once the context runs. +template +void check_never_inline(asio::io_context& context, Start start) { + bool called = false; + start([&called](auto&&...) { called = true; }); + BOOST_TEST(!called); + run(context); + BOOST_TEST(called); +} + +template +void never_inline_case(asio::io_context& context) { + known_answer const answer; + auto const executor = context.get_executor(); + check_never_inline(context, [&](auto handler) { + Authenticator::async_authenticate(executor, answer.key, answer.message, handler); + }); + check_never_inline(context, [&](auto handler) { + single_use_key_authentication::async_authenticate(executor, answer.key, + answer.message, handler); + }); + check_never_inline(context, [&](auto handler) { + Authenticator::async_verify(executor, answer.key, answer.message, answer.tag, handler); + }); + check_never_inline(context, [&](auto handler) { + single_use_key_authentication::async_verify( + executor, answer.key, answer.message, answer.tag, handler); + }); +} + +template +void every_case(asio::io_context& context) { + callback_case(context); + run_coroutine(context, coroutine_round_trip()); + deferred_case(context); + never_inline_case(context); +} + +/** + * A single-use key authenticator without the asynchronous members, over libsodium's Poly1305: + * the free forms post its synchronous calls. + */ +struct synchronous_only { + using inner = crypto::authenticators::poly1305; + using result_type = inner::result_type; + static constexpr std::size_t key_size = inner::key_size; + static constexpr std::size_t tag_size = inner::tag_size; + + static boost::system::result authenticate( + std::span key_bytes, + std::span message_bytes) noexcept { + return inner::authenticate(key_bytes, message_bytes); + } + + static boost::system::result verify(std::span key_bytes, + std::span message_bytes, + std::span tag_bytes) noexcept { + return inner::verify(key_bytes, message_bytes, tag_bytes); + } +}; + +static_assert(single_use_key_authentication::single_use_key_authenticator); + +// The free forms over an authenticator without the members: the same tag and verdict, posted. +void fallback_case(asio::io_context& context) { + known_answer const answer; + tag_completion tagged; + verify_completion verified; + single_use_key_authentication::async_authenticate( + context.get_executor(), answer.key, answer.message, keep_tag(tagged)); + single_use_key_authentication::async_verify( + context.get_executor(), answer.key, answer.message, answer.tag, keep_verdict(verified)); + BOOST_TEST_EQ(tagged.calls + verified.calls, 0); + run(context); + BOOST_TEST_EQ(tagged.calls, 1); + BOOST_TEST_EQ(tagged.tag, webcpp::test::poly1305_cases[0].tag); + BOOST_TEST_EQ(verified.calls, 1); + BOOST_TEST(!verified.code); +} + +} // namespace + +int main() { + asio::io_context context; + every_case>(context); +#ifdef WEBCPP_TEST_ASYNC_AUTHENTICATOR_OPENSSL + every_case>(context); +#endif + fallback_case(context); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/async_stream_cipher_test.cpp b/test/async_stream_cipher_test.cpp new file mode 100644 index 0000000..d7c3c32 --- /dev/null +++ b/test/async_stream_cipher_test.cpp @@ -0,0 +1,355 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// ChaCha20's asynchronous forms (design D6): crypto::async_from_key and the static +// basic_chacha20::async_from_key, the member async_apply_keystream and the free +// unauthenticated_encryption::async_apply_keystream, on libsodium, on BearSSL and, where linked, +// on OpenSSL, synchronous backends: each runs the synchronous call when the operation is +// initiated and completes through a post, never inside the call. +// - from_key_async: async_from_key, free and member, gives an object whose keystream is RFC 8439 +// section 2.4.2's; a short key completes with invalid_key_size and an empty object, which +// refuses with invalid_state, the data untouched. +// - apply_async: in a coroutine (use_awaitable), the member and the free form give the +// synchronous call's bytes, and a second call restores the plaintext; with deferred, launched +// later, the same bytes. +// - deferred_from_key: with deferred, async_from_key, free and member, completes nothing before it +// is launched; then its object gives RFC 8439 section 2.4.2's keystream. +// - never_inline: a callback's flag is unset when each form returns and set after the context +// runs. +// - refusals: counter_overflow and invalid_nonce_size complete with the data untouched, member and +// free. +// - At compile time, on a stand-in backend that completes by itself: basic_chacha20 is still a +// stream_cipher by its shape (its members refuse when instantiated, the message tests pin it). + +#include "support/hex.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef WEBCPP_TEST_ASYNC_STREAM_CIPHER_OPENSSL +#include +#endif + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +// A backend that completes by itself, as part B's browser backend will: its types are named, never +// made. +namespace { + +struct stand_in_browser {}; + +} // namespace + +template <> +inline constexpr bool webcpp::crypto::detail::asynchronous_backend_v = true; + +namespace asio = webcpp::asio; +namespace crypto = webcpp::crypto; +namespace unauthenticated_encryption = crypto::unauthenticated_encryption; + +// The concept reads the shape alone: on the stand-in, the type still has it, and each member +// stops the build only where it is instantiated; crypto::async_from_key refuses it, and none on a +// synchronous backend, whatever the qualifiers. +static_assert( + unauthenticated_encryption::stream_cipher>); +static_assert( + crypto::detail::refuses_async_stream_cipher_v>); +static_assert(crypto::detail::refuses_async_stream_cipher_v< + crypto::ciphers::chacha20 const&>); +static_assert(!crypto::detail::refuses_async_stream_cipher_v< + crypto::ciphers::chacha20>); + +namespace { + +/** RFC 8439 section 2.4.2: the key, the nonce, the counter and the ciphertext of the sunscreen. */ +constexpr std::string_view sunscreen_key = + "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"; +constexpr std::string_view sunscreen_nonce = "000000000000004a00000000"; +constexpr std::uint32_t sunscreen_counter = 1; +constexpr std::string_view sunscreen_plaintext = + "4c616469657320616e642047656e746c656d656e206f662074686520636c617373206f66202739393a20" + "4966204920636f756c64206f6666657220796f75206f6e6c79206f6e652074697020666f722074686520" + "6675747572652c2073756e73637265656e20776f756c642062652069742e"; +constexpr std::string_view sunscreen_ciphertext = + "6e2e359a2568f98041ba0728dd0d6981e97e7aec1d4360c20a27afccfd9fae0bf91b65" + "c5524733ab8f593dabcd62b3571639d624e65152ab8f530c359f0861d807ca0dbf500d" + "6a6156a38e088a22b65e52bc514d16ccf806818ce91ab77937365af90bbf74a35be6b4" + "0b8eedf2785e42874d"; + +using webcpp::test::from_hex; +using webcpp::test::to_hex; + +/** A keyed object under the sunscreen's key. */ +template +Cipher keyed() { + return Cipher::from_key(from_hex(sunscreen_key)).value(); +} + +// What one completion of async_from_key handed over. +template +struct made_completion { + int calls = 0; + boost::system::error_code code; + std::optional value; +}; + +// async_from_key, free and static member: the object made gives the sunscreen's ciphertext; a +// short key completes with invalid_key_size and an empty object that refuses with invalid_state. +template +void from_key_case(asio::io_context& context) { + auto const key = from_hex(sunscreen_key); + made_completion free_made; + made_completion member_made; + made_completion short_made; + auto const keep = [](made_completion& done) { + return [&done](boost::system::error_code code, Cipher value) { + ++done.calls; + done.code = code; + done.value.emplace(std::move(value)); + }; + }; + crypto::async_from_key(context.get_executor(), key, keep(free_made)); + Cipher::async_from_key(context.get_executor(), key, keep(member_made)); + crypto::async_from_key(context.get_executor(), std::span(key).first(31), + keep(short_made)); + BOOST_TEST_EQ(free_made.calls + member_made.calls + short_made.calls, 0); + context.restart(); + context.run(); // lint-run: the test's event loop + auto const nonce = from_hex(sunscreen_nonce); + for (made_completion* done : {&free_made, &member_made}) { + BOOST_TEST_EQ(done->calls, 1); + BOOST_TEST(!done->code); + if (BOOST_TEST(done->value.has_value())) { + auto data = from_hex(sunscreen_plaintext); + BOOST_TEST(done->value->apply_keystream(nonce, data, sunscreen_counter).has_value()); + BOOST_TEST_EQ(to_hex(data), sunscreen_ciphertext); + } + } + BOOST_TEST_EQ(short_made.calls, 1); + BOOST_TEST(short_made.code == crypto::error::invalid_key_size); + if (BOOST_TEST(short_made.value.has_value())) { + auto data = from_hex(sunscreen_plaintext); + auto const untouched = data; + BOOST_TEST(short_made.value->apply_keystream(nonce, data, sunscreen_counter).error() == + crypto::error::invalid_state); + BOOST_TEST(data == untouched); + } +} + +// The member and the free form in a coroutine, each the synchronous call's bytes, a second call +// restoring the plaintext. +template +asio::awaitable apply_round_trip() { + auto const executor = co_await asio::this_coro::executor; + auto cipher = keyed(); + auto const nonce = from_hex(sunscreen_nonce); + auto const plaintext = from_hex(sunscreen_plaintext); + + auto data = plaintext; + co_await unauthenticated_encryption::async_apply_keystream( + executor, cipher, nonce, data, sunscreen_counter, asio::use_awaitable); + BOOST_TEST_EQ(to_hex(data), sunscreen_ciphertext); + co_await cipher.async_apply_keystream(executor, nonce, data, sunscreen_counter, + asio::use_awaitable); + BOOST_TEST(data == plaintext); + + co_await cipher.async_apply_keystream(executor, nonce, data, sunscreen_counter, + asio::use_awaitable); + BOOST_TEST_EQ(to_hex(data), sunscreen_ciphertext); + co_await unauthenticated_encryption::async_apply_keystream( + executor, cipher, nonce, data, sunscreen_counter, asio::use_awaitable); + BOOST_TEST(data == plaintext); +} + +// Runs a coroutine to its end on the context, which it must reach without an exception. +void run_coroutine(asio::io_context& context, asio::awaitable coroutine) { + bool finished = false; + asio::co_spawn(context, std::move(coroutine), [&finished](std::exception_ptr const& failure) { + BOOST_TEST(!failure); + finished = true; + }); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST(finished); +} + +// deferred: the operation runs when it is launched, not when it is made, and gives the same +// bytes, member and free. +template +void deferred_case(asio::io_context& context) { + auto cipher = keyed(); + auto const nonce = from_hex(sunscreen_nonce); + auto const plaintext = from_hex(sunscreen_plaintext); + for (bool const member : {false, true}) { + auto data = plaintext; + boost::system::error_code code = crypto::error::backend_failure; + auto const keep = [&code](boost::system::error_code done) { code = done; }; + if (member) { + auto operation = cipher.async_apply_keystream(context.get_executor(), nonce, data, + sunscreen_counter, asio::deferred); + BOOST_TEST(data == plaintext); + std::move(operation)(keep); + } else { + auto operation = unauthenticated_encryption::async_apply_keystream( + context.get_executor(), cipher, nonce, data, sunscreen_counter, asio::deferred); + BOOST_TEST(data == plaintext); + std::move(operation)(keep); + } + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST(!code); + BOOST_TEST_EQ(to_hex(data), sunscreen_ciphertext); + } +} + +// deferred: async_from_key, free and static member, completes nothing before it is launched, and +// the object it then gives is the sunscreen's. +template +void deferred_from_key_case(asio::io_context& context) { + auto const key = from_hex(sunscreen_key); + auto const nonce = from_hex(sunscreen_nonce); + for (bool const member : {false, true}) { + made_completion made; + auto const keep = [&made](boost::system::error_code code, Cipher value) { + ++made.calls; + made.code = code; + made.value.emplace(std::move(value)); + }; + if (member) { + auto operation = Cipher::async_from_key(context.get_executor(), key, asio::deferred); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(made.calls, 0); + std::move(operation)(keep); + } else { + auto operation = + crypto::async_from_key(context.get_executor(), key, asio::deferred); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(made.calls, 0); + std::move(operation)(keep); + } + BOOST_TEST_EQ(made.calls, 0); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(made.calls, 1); + BOOST_TEST(!made.code); + if (BOOST_TEST(made.value.has_value())) { + auto data = from_hex(sunscreen_plaintext); + BOOST_TEST(made.value->apply_keystream(nonce, data, sunscreen_counter).has_value()); + BOOST_TEST_EQ(to_hex(data), sunscreen_ciphertext); + } + } +} + +// A flag a callback sets: unset when the initiating call returns, set once the context runs. +template +void check_never_inline(asio::io_context& context, Start start) { + bool called = false; + start([&called](auto&&...) { called = true; }); + BOOST_TEST(!called); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST(called); +} + +template +void never_inline_case(asio::io_context& context) { + auto cipher = keyed(); + auto const executor = context.get_executor(); + auto const key = from_hex(sunscreen_key); + auto const nonce = from_hex(sunscreen_nonce); + auto data = from_hex(sunscreen_plaintext); + check_never_inline( + context, [&](auto handler) { crypto::async_from_key(executor, key, handler); }); + check_never_inline(context, + [&](auto handler) { Cipher::async_from_key(executor, key, handler); }); + check_never_inline(context, [&](auto handler) { + unauthenticated_encryption::async_apply_keystream(executor, cipher, nonce, data, + sunscreen_counter, handler); + }); + check_never_inline(context, [&](auto handler) { + cipher.async_apply_keystream(executor, nonce, data, sunscreen_counter, handler); + }); + BOOST_TEST_EQ(to_hex(data), sunscreen_plaintext); +} + +// counter_overflow and invalid_nonce_size complete with the data untouched, member and free. +template +void refusals_case(asio::io_context& context) { + auto cipher = keyed(); + auto const executor = context.get_executor(); + auto const nonce = from_hex(sunscreen_nonce); + std::vector data(65, 0x6c); + auto const untouched = data; + std::array const long_nonce{}; + std::uint32_t const last = 0xffffffffU; + for (bool const member : {false, true}) { + boost::system::error_code overflow_code; + boost::system::error_code nonce_code; + auto const keep = [](boost::system::error_code& code) { + return [&code](boost::system::error_code done) { code = done; }; + }; + if (member) { + cipher.async_apply_keystream(executor, nonce, data, last, keep(overflow_code)); + cipher.async_apply_keystream(executor, long_nonce, data, 0, keep(nonce_code)); + } else { + unauthenticated_encryption::async_apply_keystream(executor, cipher, nonce, data, last, + keep(overflow_code)); + unauthenticated_encryption::async_apply_keystream(executor, cipher, long_nonce, data, 0, + keep(nonce_code)); + } + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST(overflow_code == crypto::error::counter_overflow); + BOOST_TEST(nonce_code == crypto::error::invalid_nonce_size); + BOOST_TEST(data == untouched); + } +} + +template +void every_case(asio::io_context& context) { + from_key_case(context); + run_coroutine(context, apply_round_trip()); + deferred_case(context); + deferred_from_key_case(context); + never_inline_case(context); + refusals_case(context); +} + +} // namespace + +int main() { + asio::io_context context; + every_case>(context); + every_case>(context); +#ifdef WEBCPP_TEST_ASYNC_STREAM_CIPHER_OPENSSL + every_case>(context); +#endif + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/authenticator_concepts_test.cpp b/test/authenticator_concepts_test.cpp new file mode 100644 index 0000000..66d4a2f --- /dev/null +++ b/test/authenticator_concepts_test.cpp @@ -0,0 +1,125 @@ +// 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-use key authenticator's concept (design D13): authenticators::poly1305 is a +// single_use_key_authentication::single_use_key_authenticator, and neither a stream cipher nor an +// AEAD, and no object; no AEAD, secret box, stream cipher or webcpp::hash MAC is a +// single_use_key_authenticator. The static members and the free forms give the same tags and the +// same errors, and a generic function over the concept (the guide's snippet) runs it. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include + +namespace crypto = webcpp::crypto; +namespace hash = webcpp::hash; +namespace single_use_key_authentication = webcpp::crypto::single_use_key_authentication; + +namespace { + +using check = crypto::detail::concept_check_backend; +using poly1305 = crypto::authenticators::poly1305<>; + +static_assert(single_use_key_authentication::single_use_key_authenticator); +static_assert(single_use_key_authentication::single_use_key_authenticator< + crypto::authenticators::poly1305>); +static_assert(!single_use_key_authentication::single_use_key_authenticator< + crypto::ciphers::chacha20_poly1305>); +static_assert( + !single_use_key_authentication::single_use_key_authenticator>); +static_assert(!single_use_key_authentication::single_use_key_authenticator< + crypto::ciphers::gcm>>); +static_assert(!single_use_key_authentication::single_use_key_authenticator< + crypto::secret_key_encryption::secretbox>); +// HMAC-SHA-256 as webcpp::hash names it: the reusable key's MAC that the refusal points to. +static_assert(!single_use_key_authentication::single_use_key_authenticator< + hash::macs::hmac>); +static_assert(!crypto::unauthenticated_encryption::stream_cipher); +static_assert(!crypto::secret_key_encryption::aead::cipher); +static_assert(!std::is_default_constructible_v); + +/** + * Authenticates a message and verifies its tag through the concept alone: a generic program over + * every single-use key authenticator. + * + * @tparam Authenticator A single-use key authenticator. + * @param key_bytes A key derived for this message alone. + * @return Whether the tag verified, and a tag with one bit flipped did not. + */ +// tag::generic[] +template +bool authenticates_once(std::span key_bytes) { + std::array const message{'h', 'e', 'l', 'l', 'o'}; + auto const tag = single_use_key_authentication::authenticate(key_bytes, message); + if (!tag) { + return false; + } + auto forged = *tag; + forged.data()[0] ^= 1U; + return single_use_key_authentication::verify(key_bytes, message, *tag) && + !single_use_key_authentication::verify(key_bytes, message, forged); +} + +// end::generic[] + +/** The static members and the free forms give the same tags and the same errors. */ +void forms_agree() { + std::array key{}; + for (std::size_t i = 0; i < key.size(); ++i) { + key[i] = static_cast((i * 13) + 1); + } + std::array message{}; + message.fill(0x5a); + auto const member = poly1305::authenticate(key, message); + auto const free = single_use_key_authentication::authenticate(key, message); + if (!BOOST_TEST(member.has_value()) || !BOOST_TEST(free.has_value())) { + return; + } + BOOST_TEST(*member == *free); + std::array const zeroes{}; + BOOST_TEST(!std::ranges::equal(*member, zeroes)); + BOOST_TEST(poly1305::verify(key, message, *free).has_value()); + BOOST_TEST(single_use_key_authentication::verify(key, message, *member).has_value()); + auto const short_key = std::span(key).first(31); + BOOST_TEST(poly1305::authenticate(short_key, message).error() == + single_use_key_authentication::authenticate(short_key, message).error()); + BOOST_TEST(poly1305::verify(key, message, zeroes).error() == + crypto::error::authentication_failed); + BOOST_TEST(single_use_key_authentication::verify(key, message, zeroes).error() == + crypto::error::authentication_failed); + BOOST_TEST( + poly1305::verify(key, message, std::span(zeroes).first(15)).error() == + single_use_key_authentication::verify(key, message, std::span(zeroes).first(15)) + .error()); +} + +} // namespace + +int main() { + std::array key{}; + key.fill(7); + BOOST_TEST(authenticates_once(key)); + forms_agree(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/capabilities_test.cpp b/test/capabilities_test.cpp index e40639d..782b7d9 100644 --- a/test/capabilities_test.cpp +++ b/test/capabilities_test.cpp @@ -13,7 +13,9 @@ // the type a program names, which names its family and its algorithm as the table // does; and each family's refusal, parsed. +#include #include +#include #include #include #include @@ -120,6 +122,18 @@ struct refuses_xchacha20_poly1305 { WEBCPP_CRYPTO_DETAIL_REFUSE_XCHACHA20_POLY1305(Backend); }; +/** The refusals of ChaCha20, parsed: nothing instantiates it. */ +template +struct refuses_chacha20 { + WEBCPP_CRYPTO_DETAIL_REFUSE_CHACHA20(Backend); +}; + +/** The refusals of Poly1305, parsed: nothing instantiates it. */ +template +struct refuses_poly1305 { + WEBCPP_CRYPTO_DETAIL_REFUSE_POLY1305(Backend); +}; + /** The refusals of XSalsa20-Poly1305 secret box, parsed: nothing instantiates it. */ template struct refuses_secretbox_xsalsa20poly1305 { @@ -380,6 +394,46 @@ static_assert(crypto::supports_v, backends::sodium>); #endif +// ChaCha20 on bearssl: native, wasip2, wasip3, emscripten. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_v, backends::bearssl>); +#else +static_assert(!crypto::supports_v, backends::bearssl>); +#endif +// ChaCha20 on openssl: native, wasip2, wasip3. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) +static_assert(crypto::supports_v, backends::openssl>); +#else +static_assert(!crypto::supports_v, backends::openssl>); +#endif +// ChaCha20 on ctaes: none. +static_assert(!crypto::supports_v, backends::ctaes>); +// ChaCha20 on secp256k1: none. +static_assert(!crypto::supports_v, backends::secp256k1>); +// ChaCha20 on sodium: native, wasip2, wasip3, emscripten. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_v, backends::sodium>); +#else +static_assert(!crypto::supports_v, backends::sodium>); +#endif +// Poly1305 on bearssl: none. +static_assert(!crypto::supports_v, backends::bearssl>); +// Poly1305 on openssl: native, wasip2, wasip3. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) +static_assert(crypto::supports_v, backends::openssl>); +#else +static_assert(!crypto::supports_v, backends::openssl>); +#endif +// Poly1305 on ctaes: none. +static_assert(!crypto::supports_v, backends::ctaes>); +// Poly1305 on secp256k1: none. +static_assert(!crypto::supports_v, backends::secp256k1>); +// Poly1305 on sodium: native, wasip2, wasip3, emscripten. +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_v, backends::sodium>); +#else +static_assert(!crypto::supports_v, backends::sodium>); +#endif // XSalsa20-Poly1305 secret box on bearssl: none. static_assert(!crypto::supports_v, backends::bearssl>); // XSalsa20-Poly1305 secret box on openssl: none. @@ -577,6 +631,21 @@ int main() { #if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN)) && defined(WEBCPP_CRYPTO_HAS_SODIUM) BOOST_TEST((webcpp::test::made, families::xchacha20_poly1305, families::xchacha20_poly1305, backends::sodium>())); #endif +#if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN)) && defined(WEBCPP_CRYPTO_HAS_BEARSSL) + BOOST_TEST((webcpp::test::made, families::chacha20, families::chacha20, backends::bearssl>())); +#endif +#if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3)) && defined(WEBCPP_CRYPTO_HAS_OPENSSL) + BOOST_TEST((webcpp::test::made, families::chacha20, families::chacha20, backends::openssl>())); +#endif +#if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN)) && defined(WEBCPP_CRYPTO_HAS_SODIUM) + BOOST_TEST((webcpp::test::made, families::chacha20, families::chacha20, backends::sodium>())); +#endif +#if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3)) && defined(WEBCPP_CRYPTO_HAS_OPENSSL) + BOOST_TEST((webcpp::test::made, families::poly1305, families::poly1305, backends::openssl>())); +#endif +#if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN)) && defined(WEBCPP_CRYPTO_HAS_SODIUM) + BOOST_TEST((webcpp::test::made, families::poly1305, families::poly1305, backends::sodium>())); +#endif #if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN)) && defined(WEBCPP_CRYPTO_HAS_SODIUM) BOOST_TEST((webcpp::test::made, families::secretbox_xsalsa20poly1305, families::secretbox_xsalsa20poly1305, backends::sodium>())); #endif diff --git a/test/chacha20_bearssl_portable_test.cpp b/test/chacha20_bearssl_portable_test.cpp new file mode 100644 index 0000000..a8519f1 --- /dev/null +++ b/test/chacha20_bearssl_portable_test.cpp @@ -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) + +// chacha20_bearssl_test.cpp with WEBCPP_CRYPTO_DETAIL_BEARSSL_PORTABLE, which the Jamfile defines: +// BearSSL on chacha20_ct on every CPU. A source of its own, so that b2 compiles it with its own +// defines (spec section 4.3's pitfall); the code is shared. + +#include "chacha20_bearssl_test.cpp" // NOLINT(bugprone-suspicious-include): one program, twice diff --git a/test/chacha20_bearssl_test.cpp b/test/chacha20_bearssl_test.cpp new file mode 100644 index 0000000..1c4ef68 --- /dev/null +++ b/test/chacha20_bearssl_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) + +// ChaCha20, RFC 8439's raw stream cipher, on BearSSL, on every target: RFC 8439's known answers, +// every guard, the counter's end, the stream across calls, the nonce inside the data, empty data, +// the key as a secret and moves (support/stream_cipher_checks.hpp). BearSSL runs SSE2's code where +// the CPU has it; chacha20_bearssl_portable_test.cpp runs the portable code. Each program first +// checks that BearSSL runs the code the seam says. + +#include +#include +#include +#include + +#include "support/stream_cipher_checks.hpp" + +#include + +#include + +namespace crypto = webcpp::crypto; + +using chacha20 = crypto::ciphers::chacha20; + +static_assert(crypto::supports_v); + +namespace { + +/** Checks that BearSSL runs the code the seam selects. */ +void check_code_paths() { +#ifdef WEBCPP_CRYPTO_DETAIL_BEARSSL_PORTABLE + // On every target the seam keeps the constant-time portable code. + BOOST_TEST(crypto::detail::bearssl_chacha20() == &br_chacha20_ct_run); +#else + // Without it, SSE2's ChaCha20 where the CPU and the build have it. + br_chacha20_run const sse2 = br_chacha20_sse2_get(); + BOOST_TEST(crypto::detail::bearssl_chacha20() == + (sse2 != nullptr ? sse2 : &br_chacha20_ct_run)); + std::printf("BearSSL's ChaCha20: %s\n", sse2 != nullptr ? "SSE2" : "ct"); +#endif +} + +} // namespace + +int main() { + check_code_paths(); + webcpp::test::check_stream_cipher(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/chacha20_nip44_bearssl_test.cpp b/test/chacha20_nip44_bearssl_test.cpp new file mode 100644 index 0000000..b232333 --- /dev/null +++ b/test/chacha20_nip44_bearssl_test.cpp @@ -0,0 +1,23 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// NIP-44 version 2's valid vectors end to end through ChaCha20 on BearSSL, NIP-44 composed in the +// test alone (support/nip44.hpp): the conversation keys, the message keys, the padding, every +// message both ways and the long messages. + +#include "support/nip44.hpp" + +#include +#include +#include + +#include + +int main() { + webcpp::test::nip44::run_vectors< + webcpp::crypto::ciphers::chacha20>(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/chacha20_nip44_openssl_test.cpp b/test/chacha20_nip44_openssl_test.cpp new file mode 100644 index 0000000..cdbaf01 --- /dev/null +++ b/test/chacha20_nip44_openssl_test.cpp @@ -0,0 +1,23 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// NIP-44 version 2's valid vectors end to end through ChaCha20 on OpenSSL, NIP-44 composed in the +// test alone (support/nip44.hpp): the conversation keys, the message keys, the padding, every +// message both ways and the long messages. + +#include "support/nip44.hpp" + +#include +#include +#include + +#include + +int main() { + webcpp::test::nip44::run_vectors< + webcpp::crypto::ciphers::chacha20>(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/chacha20_nip44_sodium_test.cpp b/test/chacha20_nip44_sodium_test.cpp new file mode 100644 index 0000000..e396058 --- /dev/null +++ b/test/chacha20_nip44_sodium_test.cpp @@ -0,0 +1,23 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// NIP-44 version 2's valid vectors end to end through ChaCha20 on libsodium, NIP-44 composed in the +// test alone (support/nip44.hpp): the conversation keys, the message keys, the padding, every +// message both ways and the long messages. + +#include "support/nip44.hpp" + +#include +#include +#include + +#include + +int main() { + webcpp::test::nip44::run_vectors< + webcpp::crypto::ciphers::chacha20>(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/chacha20_openssl_test.cpp b/test/chacha20_openssl_test.cpp new file mode 100644 index 0000000..adc3e98 --- /dev/null +++ b/test/chacha20_openssl_test.cpp @@ -0,0 +1,30 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// ChaCha20, RFC 8439's raw stream cipher, on OpenSSL, on native, wasip2 and wasip3: RFC 8439's +// known answers, every guard, the counter's end, the stream across calls (OpenSSL's IV set again +// on the one context for each call), the nonce inside the data, empty data, the key as a secret +// and moves (support/stream_cipher_checks.hpp). + +#include +#include +#include +#include + +#include "support/stream_cipher_checks.hpp" + +#include + +namespace crypto = webcpp::crypto; + +using chacha20 = crypto::ciphers::chacha20; + +static_assert(crypto::supports_v); + +int main() { + webcpp::test::check_stream_cipher(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/chacha20_sodium_test.cpp b/test/chacha20_sodium_test.cpp new file mode 100644 index 0000000..f4804b7 --- /dev/null +++ b/test/chacha20_sodium_test.cpp @@ -0,0 +1,41 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// ChaCha20, RFC 8439's raw stream cipher, on libsodium, through its default type, +// ciphers::chacha20<>, whose backend is libsodium on every target: RFC 8439's known answers, every +// guard, the counter's end, the stream across calls, the nonce inside the data, empty data, the +// key as a secret and moves (support/stream_cipher_checks.hpp). + +#include +#include +#include + +#include "support/stream_cipher_checks.hpp" + +#include + +#include +#include + +namespace crypto = webcpp::crypto; + +using chacha20 = crypto::ciphers::chacha20<>; + +// The default is libsodium on every target, ChaCha20-Poly1305's, and the type names its family as +// the capability table does. +static_assert(std::is_same_v, + crypto::backends::sodium>); +static_assert(std::is_same_v>); +static_assert(std::is_same_v); +static_assert(std::is_same_v); +static_assert(crypto::supports_v); +static_assert(chacha20::max_message_size == std::uint64_t{1} << 38U); + +int main() { + webcpp::test::check_stream_cipher(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/composition_rfc8439_emscripten_test.cpp b/test/composition_rfc8439_emscripten_test.cpp new file mode 100644 index 0000000..6293511 --- /dev/null +++ b/test/composition_rfc8439_emscripten_test.cpp @@ -0,0 +1,34 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// RFC 8439 section 2.8's AEAD composed from the raw pieces on Emscripten, which has no OpenSSL +// (design D17): the raw ChaCha20 on libsodium and BearSSL, Poly1305 on libsodium, ChaCha20-Poly1305 +// on libsodium and BearSSL, the 4 combinations of composition_rfc8439_test.cpp's 18 without +// OpenSSL, each the same cases (support/composition_checks.hpp). + +#include +#include +#include + +#include "support/composition_checks.hpp" + +#include + +#include + +namespace { + +using webcpp::crypto::backends::bearssl; +using webcpp::crypto::backends::sodium; + +} // namespace + +int main() { + webcpp::test::run_composition_matrix< + std::tuple, std::tuple, + std::tuple, std::tuple>(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/composition_rfc8439_test.cpp b/test/composition_rfc8439_test.cpp new file mode 100644 index 0000000..9dea29e --- /dev/null +++ b/test/composition_rfc8439_test.cpp @@ -0,0 +1,46 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// RFC 8439 section 2.8's AEAD composed from the raw pieces as an 18-cell cross-backend matrix +// (design D17, owner decision 6), on native, wasip2 and wasip3: the raw ChaCha20 on libsodium, +// BearSSL and OpenSSL, times Poly1305 on libsodium and OpenSSL, times ChaCha20-Poly1305 on +// libsodium, BearSSL and OpenSSL, each the same cases (support/composition_checks.hpp). One +// program links every backend, as the agreement tests do: crypto's one-backend-per-file rule does +// not apply to a cross-backend test. composition_rfc8439_emscripten_test.cpp runs the 4 +// combinations without OpenSSL on Emscripten. + +#include +#include +#include +#include + +#include "support/composition_checks.hpp" + +#include + +#include + +namespace { + +using webcpp::crypto::backends::bearssl; +using webcpp::crypto::backends::openssl; +using webcpp::crypto::backends::sodium; + +} // namespace + +int main() { + webcpp::test::run_composition_matrix< + std::tuple, std::tuple, + std::tuple, std::tuple, + std::tuple, std::tuple, + std::tuple, std::tuple, + std::tuple, std::tuple, + std::tuple, std::tuple, + std::tuple, std::tuple, + std::tuple, std::tuple, + std::tuple, std::tuple>(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/constant_time/Jamfile b/test/constant_time/Jamfile index 984d639..9e646c1 100644 --- a/test/constant_time/Jamfile +++ b/test/constant_time/Jamfile @@ -11,22 +11,24 @@ # early exit on the key, natively (dudect_planted). The paths: BearSSL's AES-GCM # and ChaCha20-Poly1305 from_key, seal and open, OpenSSL's from_key and seal of # both (its open branches on the verdict inside OpenSSL, where webcpp cannot -# mark it public), ctaes's from_key, encrypt and decrypt, constant_time_equal, -# is_all_zero, erase_secret, secret's wipe, libsodium's Ed25519, X25519 and its -# key pair's wipe, three AEADs, two secret boxes, two boxes, the sealed box and -# kx from a seed and from a key pair (its own branches on a verdict -# listed in sodium_verdicts.supp), libsecp256k1's own ctime_tests.c, and -# webcpp's code around libsecp256k1: the key pair's making and secret(), -# signatures and x-only tweak, ECDH in three forms (agree, agree_hashed and -# agree_point), the secret key's tweaks, PKCS#8, ElligatorSwift, MuSig2's nonce -# and partial signature, and silent payments' outputs, label and scan, and -# BearSSL's P-256: the key pair's making, ECDSA with its low-S normalisation and -# check, ECDH's x and PKCS#8's decoding, and hash's Base58Check, the secret -# encode and decode of a WIF key's payload (hash's design D4: hash has no -# constant-time lane of its own). Both checkers run the same paths, -# paths.hpp, memcheck OpenSSL's besides. BearSSL's own branches on a verdict in -# its ECDSA signing are listed in bearssl_verdicts.supp, as libsodium's are in -# sodium_verdicts.supp. +# mark it public), ChaCha20's from_key and apply_keystream on BearSSL, libsodium +# and OpenSSL (memcheck alone for OpenSSL's), Poly1305's authenticate and verify +# on libsodium and OpenSSL (memcheck alone for OpenSSL's), ctaes's from_key, +# encrypt and decrypt, constant_time_equal, is_all_zero, erase_secret, secret's +# wipe, libsodium's Ed25519, X25519 and its key pair's wipe, three AEADs, two +# secret boxes, two boxes, the sealed box and kx from a seed and from a key pair +# (its own branches on a verdict listed in sodium_verdicts.supp), libsecp256k1's +# own ctime_tests.c, and webcpp's code around libsecp256k1: the key pair's +# making and secret(), signatures and x-only tweak, ECDH in three forms (agree, +# agree_hashed and agree_point), the secret key's tweaks, PKCS#8, +# ElligatorSwift, MuSig2's nonce and partial signature, and silent payments' +# outputs, label and scan, and BearSSL's P-256: the key pair's making, ECDSA +# with its low-S normalisation and check, ECDH's x and PKCS#8's decoding, and +# hash's Base58Check, the secret encode and decode of a WIF key's payload +# (hash's design D4: hash has no constant-time lane of its own). Both checkers +# run the same paths, paths.hpp, memcheck OpenSSL's besides. BearSSL's own +# branches on a verdict in its ECDSA signing are listed in +# bearssl_verdicts.supp, as libsodium's are in sodium_verdicts.supp. # # A later family adds its cases to paths.hpp, which both checkers run, as # libsodium's and libsecp256k1's are there: its secrets marked, its verdicts @@ -241,13 +243,14 @@ webcpp.run secp256k1_ctime_msan : $(SECP256K1_CTIME) off $(MSAN_FLAGS) -fsanitize=memory release on @clang-on-linux : native ; -# dudect's statistics on BearSSL, ctaes, constant_time_equal and hash's -# Base58Check's secret decode of a WIF key, on libsodium's -# X25519 and Ed25519, and on libsecp256k1's agree, natively and under wasmtime. -# The programs never set DIT: they measure what a program gets, the library's -# own guard (webcpp::secure::timing_guard), which sets DIT in each call on -# arm64 under macOS, Linux and Windows where the CPU has it, and fail if it is -# already set outside the calls (dudect.hpp). On a runner GitHub hosts, a +# dudect's statistics on BearSSL (ChaCha20's keystream among them), ctaes, +# constant_time_equal and hash's Base58Check's secret decode of a WIF key, on +# libsodium's X25519, Ed25519 and Poly1305 (authenticate against its key, +# verify against its tag), and on libsecp256k1's agree, natively and under +# wasmtime. The programs never set DIT: they measure what a program gets, +# the library's own guard (webcpp::secure::timing_guard), which sets DIT in each +# call on arm64 under macOS, Linux and Windows where the CPU has it, and fail if +# it is already set outside the calls (dudect.hpp). On a runner GitHub hosts, a # virtual machine shared with other tenants whose processor changes from run to # run, each |t| is printed and the program does not judge it: there it moved # with what the measurement cannot control (dudect.hpp, judged), so the CI's diff --git a/test/constant_time/ctgrind_test.cpp b/test/constant_time/ctgrind_test.cpp index c82fc9e..4d45f8a 100644 --- a/test/constant_time/ctgrind_test.cpp +++ b/test/constant_time/ctgrind_test.cpp @@ -7,15 +7,19 @@ // Under Valgrind's memcheck, the keys, the seeds, the plaintext, the block and the tag are marked // undefined: a branch or a memory index that depends on them is an error, and the run fails // (--error-exitcode). The paths are paths.hpp's, shared with msan_test.cpp, and two of this -// checker alone: from_key, seal and open of BearSSL's AES-GCM, where the planted leak is, and -// from_key and seal of OpenSSL's AES-GCM and ChaCha20-Poly1305. Each path's output is checked to be -// undefined too, the planted leak's path aside: the mark reaches it, so the path is traced. +// checker alone: from_key, seal and open of BearSSL's AES-GCM, where the planted leak is, +// from_key and seal of OpenSSL's AES-GCM and ChaCha20-Poly1305, OpenSSL's ChaCha20 (paths.hpp's +// keystream) and OpenSSL's Poly1305 (paths.hpp's one_time_tag, verify's verdict declassified by +// crypto). Each path's output is checked to be undefined too, the planted leak's path aside: the +// mark reaches it, so the path is traced. #include "paths.hpp" +#include #include #include #include +#include #include #include @@ -134,7 +138,13 @@ int main() { int const failures = webcpp::test::constant_time::common_paths() + bearssl_seal_and_open() + openssl_seal>>("OpenSSL GCM") + - openssl_seal>("OpenSSL ChaCha"); + openssl_seal>("OpenSSL ChaCha") + + webcpp::test::constant_time::keystream>( + "OpenSSL ChaCha20") + + webcpp::test::constant_time::one_time_tag< + memcheck, crypto::authenticators::poly1305>( + "OpenSSL Poly1305"); std::printf("constant time under memcheck: %s\n", failures == 0 ? "ok" : "FAILED"); return failures; } diff --git a/test/constant_time/dudect_sodium_test.cpp b/test/constant_time/dudect_sodium_test.cpp index 060b7d1..cc0efc6 100644 --- a/test/constant_time/dudect_sodium_test.cpp +++ b/test/constant_time/dudect_sodium_test.cpp @@ -11,16 +11,26 @@ // agreement's |t| is printed and not judged, an open finding whose cause is the host's DIT, // which wasmtime does not set (see the end of main). The agreement is measured once more as the // program's A/A control (x25519_agree_aa), both classes the all-zero secret key, prepared by the -// same instructions; `--case ` measures one case alone. The planted build -// (dudect_planted_test.cpp) has the agreement alone, and no control. +// same instructions. Poly1305's authenticate is timed against its one-time key (case +// poly1305_authenticate: the all-zero key against random ones, 64 bytes of message fixed), and its +// verify against the tag (case poly1305_verify: the right tag with its last byte flipped against +// the right tag with its first byte flipped, the probe of a comparison that exits early; the key +// and the message fixed). Both of verify's classes fail: a success and a failure return by +// different paths, a difference of about 0.4 ns that dudect finds (|t| 13.7 to 32.7 natively on an +// Apple M5 Max, 2026-12-05, the matching tag against either wrong one) and that is public by +// design, the verdict being reported; the two failures read |t| 0.87. `--case ` measures +// one case alone. The planted build (dudect_planted_test.cpp) has the agreement alone, and no +// control. #include "dudect.hpp" +#include #include #include #include #include +#include #include #include #include @@ -43,6 +53,10 @@ using x25519_keypair = x25519::basic_keypair; // wasip2 run of the lane may need the same variable. constexpr std::size_t count = 1'000'000; +// Poly1305 of 64 bytes takes some tens of nanoseconds, as an AES block does: dudect_test.cpp's +// 2,000,000 measurements. +constexpr std::size_t poly1305_count = 2'000'000; + /** * Times X25519's agreement against its secret key: all zero, against random ones, or, with * `Control`, all zero for both classes; twice when judged, once when not (`measure_case`). The key @@ -93,8 +107,14 @@ int main(int argc, char** argv) { #ifdef WEBCPP_TEST_CRYPTO_PLANTED_LEAK auto const selection = test::select_case(argc, argv, {"x25519_agree"}); #else - auto const selection = - test::select_case(argc, argv, {"x25519_agree", "ed25519_sign", "x25519_agree_aa"}); + auto const selection = test::select_case(argc, argv, + { + "x25519_agree", + "ed25519_sign", + "poly1305_authenticate", + "poly1305_verify", + "x25519_agree_aa", + }); #endif if (!selection) { return 2; @@ -163,6 +183,40 @@ int main(int argc, char** argv) { {{"secret_key", secret_key.data()}, {"message", message.data()}, {"object", &*signer}}); } + if (selection->runs("poly1305_authenticate") || selection->runs("poly1305_verify")) { + using poly1305 = crypto::authenticators::poly1305; + std::array const zero_key{}; + std::array key{}; + std::array message{}; + message.fill(0x17); + if (selection->runs("poly1305_authenticate")) { + auto const authenticate_t = test::twice( + poly1305_count, + [&](int which, auto& generator) { test::choose(which, generator, zero_key, key); }, + [&] { static_cast(poly1305::authenticate(key, message)); }); + results.record("poly1305_authenticate", "Poly1305 authenticate", authenticate_t, true, + {{"key", key.data()}, {"message", message.data()}}); + } + if (selection->runs("poly1305_verify")) { + key.fill(0x42); + auto const right = *poly1305::authenticate(key, message); + std::array nearly_right{}; + std::copy(right.data(), right.data() + right.size(), nearly_right.begin()); + auto wrong_at_start = nearly_right; + nearly_right[poly1305::tag_size - 1] ^= 1U; + wrong_at_start[0] ^= 1U; + std::array tag{}; + auto const verify_t = test::twice( + poly1305_count, + [&](int which, auto& generator) { + test::choose_between(which, generator, nearly_right, wrong_at_start, tag); + }, + [&] { static_cast(poly1305::verify(key, message, tag)); }); + results.record("poly1305_verify", "Poly1305 verify", verify_t, true, + {{"tag", tag.data()}, {"key", key.data()}, {"message", message.data()}}); + } + } + if (selection->runs("x25519_agree_aa")) { results.record( "x25519_agree_aa", "X25519 agreement A/A", diff --git a/test/constant_time/dudect_test.cpp b/test/constant_time/dudect_test.cpp index dd8183b..5afb92b 100644 --- a/test/constant_time/dudect_test.cpp +++ b/test/constant_time/dudect_test.cpp @@ -6,7 +6,9 @@ // dudect's statistics (spec section 8.3): BearSSL's AES-GCM and ChaCha20-Poly1305 seal's time // against its key, open's against its tag (the failure's zeroing included), ctaes's block -// encryption's against its key, constant_time_equal's against its second argument, and P-256's +// encryption's against its key, ChaCha20's apply_keystream against its key (case +// chacha20_keystream: the all-zero key against random ones, the nonce, the counter and 64 bytes of +// data fixed), constant_time_equal's against its second argument, and P-256's // ECDSA signing and ECDH's x against the key pair's scalar (one fixed scalar, against random ones; // the digest and the peer's public key fixed), each key pair made before its measurement, // unmeasured; natively and under wasmtime, where the engine's compiler decides whether BearSSL's @@ -29,6 +31,7 @@ #include #include #include +#include #include #include #include @@ -342,6 +345,7 @@ int main(int argc, char** argv) { "chacha_seal", "chacha_open", "ctaes_encrypt", + "chacha20_keystream", "constant_time_equal", "chacha_open_aa", "p256_sign", @@ -385,6 +389,25 @@ int main(int argc, char** argv) { {{"block", block.data()}, {"key", key.data()}, {"object", &*block_made}}); } + if (selection->runs("chacha20_keystream")) { + using stream_cipher = crypto::ciphers::chacha20; + std::array const zero_key{}; + std::array key{}; + std::array const nonce{}; + std::array data{}; + std::optional stream_made; + auto const keystream_t = test::measure_case( + results.judges(true), count, + [&](int which, auto& generator) { + test::choose(which, generator, zero_key, key); + stream_made.emplace(*stream_cipher::from_key(key)); + data.fill(0); + }, + [&] { static_cast(stream_made->apply_keystream(nonce, data, 1)); }); + results.record("chacha20_keystream", "chacha20 keystream", keystream_t, true, + {{"data", data.data()}, {"key", key.data()}, {"object", &*stream_made}}); + } + if (selection->runs("constant_time_equal")) { std::array const a{}; std::array b{}; diff --git a/test/constant_time/paths.hpp b/test/constant_time/paths.hpp index c140bf3..a6ddac6 100644 --- a/test/constant_time/paths.hpp +++ b/test/constant_time/paths.hpp @@ -28,11 +28,13 @@ #define WEBCPP_TEST_CRYPTO_CONSTANT_TIME_PATHS_HPP #include +#include #include #include #include #include #include +#include #include #include #include @@ -224,6 +226,59 @@ int seal_and_open(char const* what) { return failures + check(opened_verdict && !none_verdict, what); } +/** + * from_key and apply_keystream of a raw stream cipher from counter 1, with the key and 200 bytes + * of data secret: the keystream XORed in must carry the mark, and the object's wipe runs when it + * is destroyed. ChaCha20 has no verdict: nothing is marked public. + */ +template +int keystream(char const* what) { + std::array key{}; + std::array const nonce{}; + std::array data{}; + key.fill(0x42); + data.fill(0x17); + Checker::mark_secret(key); + Checker::mark_secret(data); + bool applied = false; + { + auto made = Cipher::from_key(key); + applied = made.has_value() && made->apply_keystream(nonce, data, 1).has_value(); + } + return check(applied && carries_mark(data), what); +} + +/** + * authenticate and verify of a single-use key authenticator (Poly1305), with the key, 200 bytes of + * message and the tags secret: the tag must carry the mark; verify with the right tag, then with a + * tag differing in its last byte, which fails. Each verdict must be public: crypto declassifies + * it where it first branches on it (design D12), and only there. + */ +template +int one_time_tag(char const* what) { + std::array key{}; + std::array message{}; + key.fill(0x42); + message.fill(0x17); + Checker::mark_secret(key); + Checker::mark_secret(message); + auto tag = Authenticator::authenticate(key, message); + int const failures = check(tag.has_value() && carries_mark(*tag), what); + if (!tag.has_value()) { + return failures; + } + Checker::mark_secret(*tag); + auto const matched = Authenticator::verify(key, message, *tag); + bool const matched_verdict = matched.has_value(); + Checker::verdict(matched_verdict); + auto other = *tag; + other[Authenticator::tag_size - 1] ^= 0x01U; + auto const differed = Authenticator::verify(key, message, other); + bool const differed_verdict = differed.has_value(); + Checker::verdict(differed_verdict); + return failures + check(matched_verdict && !differed_verdict, what); +} + /** from_key, encrypt and decrypt of ctaes with the key and the block secret. */ template int ctaes_block() { @@ -1220,11 +1275,15 @@ int common_paths() { erase_secret_path() + ctaes_block() + seal_and_open>( "BearSSL ChaCha") + + keystream>("BearSSL ChaCha20") + sodium_ed25519() + sodium_ed25519_formats() + sodium_x25519() + sodium_x25519_formats() + sodium_x25519_keypair_wipe() + seal_and_open>( "ChaCha20-Poly1305 on libsodium") + + keystream>("ChaCha20 on libsodium") + + one_time_tag>( + "Poly1305 on libsodium") + seal_and_open>( "the original on libsodium") + seal_and_open>( diff --git a/test/error_test.cpp b/test/error_test.cpp index e7ca018..7625f36 100644 --- a/test/error_test.cpp +++ b/test/error_test.cpp @@ -44,6 +44,7 @@ int main() { BOOST_TEST_EQ(static_cast(error::invalid_encoding), 19); BOOST_TEST_EQ(static_cast(error::invalid_ciphertext_size), 20); BOOST_TEST_EQ(static_cast(error::message_limit_reached), 21); + BOOST_TEST_EQ(static_cast(error::counter_overflow), 22); boost::system::error_code const code = error::authentication_failed; BOOST_TEST_EQ(std::string_view(code.category().name()), "webcpp.crypto"); @@ -92,16 +93,20 @@ int main() { "the ciphertext is not of the key's size"); BOOST_TEST_EQ(crypto::make_error_code(error::message_limit_reached).message(), "the context has sealed or opened as many messages as its nonce allows"); + BOOST_TEST_EQ(crypto::make_error_code(error::counter_overflow).message(), + "the data needs more blocks than the stream cipher's counter has left after " + "the initial counter"); + BOOST_TEST(crypto::make_error_code(error::counter_overflow) == error::counter_overflow); // Every defined value has its own message, never the unknown one. std::set messages; - for (int value = 1; value <= 21; ++value) { + for (int value = 1; value <= 22; ++value) { std::string const text = crypto::error_category().message(value); BOOST_TEST(!text.empty()); BOOST_TEST_NE(text, "unknown webcpp.crypto error"); messages.insert(text); } - BOOST_TEST_EQ(messages.size(), 21u); + BOOST_TEST_EQ(messages.size(), 22u); // The guards of the buffer form: a null buffer or a size of 0 writes nothing, a size of 1 // writes the terminating zero alone, and a message longer than the buffer is cut with one. diff --git a/test/messages/Jamfile b/test/messages/Jamfile index e327509..33eb20b 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -31,7 +31,14 @@ build-project ed25519_default_not_linked ; build-project heavy_without_threads ; build-project async_seal_xchacha ; build-project async_open_xchacha ; +build-project apply_keystream_asynchronous_backend ; +build-project from_key_chacha20_asynchronous_backend ; +build-project async_apply_keystream_asynchronous_backend ; +build-project async_from_key_chacha20_asynchronous_backend ; build-project async_from_key_xchacha ; +build-project async_from_key_not_a_cipher ; +build-project async_from_key_aead_without_member ; +build-project async_from_key_stream_cipher_without_empty ; build-project async_from_secret_secp256k1 ; build-project make_removed ; build-project async_sign_secp256k1 ; @@ -52,6 +59,26 @@ build-project kx_default_not_linked ; build-project x25519_default_not_linked ; build-project chacha_header_not_included ; build-project chacha_unknown_backend ; +build-project chacha20_not_a_family ; +build-project chacha20_unknown_backend ; +build-project chacha20_on_ctaes ; +build-project chacha20_default_not_linked ; +build-project chacha20_header_not_included ; +build-project apply_keystream_not_a_stream_cipher ; +build-project poly1305_on_bearssl ; +build-project poly1305_on_ctaes ; +build-project poly1305_unknown_backend ; +build-project poly1305_default_not_linked ; +build-project authenticate_not_a_single_use_key_authenticator ; +build-project from_key_poly1305 ; +build-project poly1305_header_not_included ; +build-project authenticate_asynchronous_backend ; +build-project verify_poly1305_asynchronous_backend ; +build-project async_authenticate_asynchronous_backend ; +build-project async_verify_asynchronous_backend ; +build-project async_authenticate_not_a_single_use_key_authenticator ; +build-project async_verify_not_a_single_use_key_authenticator ; +build-project verify_not_a_single_use_key_authenticator ; build-project ed25519_unknown_policy ; build-project equal_header_removed ; build-project equal_removed ; @@ -151,6 +178,9 @@ build-project async_seal_member_asynchronous_backend ; build-project async_from_key_secretbox_asynchronous_backend ; build-project seal_secretbox_asynchronous_backend ; build-project seal_box_asynchronous_backend ; +build-project from_key_chacha20_poly1305_asynchronous_backend ; +build-project from_key_secretbox_asynchronous_backend ; +build-project from_keys_box_asynchronous_backend ; build-project verify_without_policy ; build-project async_verify_without_policy ; build-project verify_secp256k1_any_s ; diff --git a/test/messages/apply_keystream_asynchronous_backend/Jamfile b/test/messages/apply_keystream_asynchronous_backend/Jamfile new file mode 100644 index 0000000..e6e3390 --- /dev/null +++ b/test/messages/apply_keystream_asynchronous_backend/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +# MSVC twin: apply_keystream_async_backend +# (shorter: the twin's object path stays under Windows' 260 characters) +webcpp.compile-diagnostic apply_keystream_asynchronous_backend + : apply_keystream_asynchronous_backend.cpp : : native wasip2 wasip3 : alone ; diff --git a/test/messages/apply_keystream_asynchronous_backend/apply_keystream_asynchronous_backend.cpp b/test/messages/apply_keystream_asynchronous_backend/apply_keystream_asynchronous_backend.cpp new file mode 100644 index 0000000..cf540fe --- /dev/null +++ b/test/messages/apply_keystream_asynchronous_backend/apply_keystream_asynchronous_backend.cpp @@ -0,0 +1,50 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// ChaCha20's own apply_keystream on a backend that completes by itself (a stand-in whose +// detail::asynchronous_backend_v is true) stops with the refusal that sends it to a native backend, +// as its asynchronous forms do (design D6): WebCrypto has no ChaCha20. That error alone: no engine +// is reached. The object is a parameter, since making one would run the stand-in's engine. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/detail/asynchronous.hpp:* {{webcpp::crypto: WebCrypto has no ChaCha20: no form of the raw stream cipher, synchronous or asynchronous, runs on the browser's backend; name a native backend for it.}} +// clang-format on +#include + +#include +#include + +namespace { + +/** A backend that completes by itself, as part B's browser backend will. */ +struct stand_in_browser {}; + +} // namespace + +template <> +inline constexpr bool webcpp::crypto::detail::asynchronous_backend_v = true; + +/** ChaCha20 on the stand-in. */ +using stand_in_chacha20 = webcpp::crypto::ciphers::chacha20; + +namespace { + +/** Applies the keystream with an object of the stand-in's. */ +bool applied(stand_in_chacha20& cipher) { + std::array const nonce{}; + std::array data{'h', 'e', 'l', 'l', 'o'}; + return cipher.apply_keystream(nonce, data, 0).has_value(); +} + +} // namespace + +// The function is compiled, which is the test; it is never run. +int main() { + static_cast(&applied); + return 0; +} diff --git a/test/messages/apply_keystream_not_a_stream_cipher/Jamfile b/test/messages/apply_keystream_not_a_stream_cipher/Jamfile new file mode 100644 index 0000000..c42c17c --- /dev/null +++ b/test/messages/apply_keystream_not_a_stream_cipher/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic apply_keystream_not_a_stream_cipher : apply_keystream_not_a_stream_cipher.cpp + : /third_party//sodium : native wasip2 wasip3 : alone ; diff --git a/test/messages/apply_keystream_not_a_stream_cipher/apply_keystream_not_a_stream_cipher.cpp b/test/messages/apply_keystream_not_a_stream_cipher/apply_keystream_not_a_stream_cipher.cpp new file mode 100644 index 0000000..ada64d6 --- /dev/null +++ b/test/messages/apply_keystream_not_a_stream_cipher/apply_keystream_not_a_stream_cipher.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) + +// unauthenticated_encryption::apply_keystream given an AEAD, ChaCha20-Poly1305, which is no stream +// cipher, stops with what it takes and where an AEAD seals, and with that error alone. + +// clang-format off +// expected-error@webcpp/crypto/unauthenticated_encryption/stream_cipher.hpp:* {{webcpp::crypto: unauthenticated_encryption::apply_keystream takes a stream cipher (ciphers::chacha20); an AEAD seals and opens through secret_key_encryption::aead.}} +// clang-format on +#include +#include +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const key{}; + std::array const nonce{}; + std::array data{}; + auto made = crypto::ciphers::chacha20_poly1305::from_key(key); + if (!made) { + return 1; + } + crypto::unauthenticated_encryption::apply_keystream(*made, nonce, data, 0U); + return 0; +} diff --git a/test/messages/async_apply_keystream_asynchronous_backend/Jamfile b/test/messages/async_apply_keystream_asynchronous_backend/Jamfile new file mode 100644 index 0000000..b1f9932 --- /dev/null +++ b/test/messages/async_apply_keystream_asynchronous_backend/Jamfile @@ -0,0 +1,17 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +# MSVC twin: async_apply_keystream_async_bk +# (shorter: the twin's object path stays under Windows' 260 characters) +webcpp.compile-diagnostic async_apply_keystream_asynchronous_backend + : async_apply_keystream_asynchronous_backend.cpp : /webcpp/asio//asio + : native wasip2 wasip3 : alone ; diff --git a/test/messages/async_apply_keystream_asynchronous_backend/async_apply_keystream_asynchronous_backend.cpp b/test/messages/async_apply_keystream_asynchronous_backend/async_apply_keystream_asynchronous_backend.cpp new file mode 100644 index 0000000..56871c5 --- /dev/null +++ b/test/messages/async_apply_keystream_asynchronous_backend/async_apply_keystream_asynchronous_backend.cpp @@ -0,0 +1,58 @@ +// 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 free unauthenticated_encryption::async_apply_keystream of ChaCha20 on a backend that +// completes by itself (a stand-in whose detail::asynchronous_backend_v is true) stops with the +// refusal that sends it to a native backend (design D6), and with that error alone: the free form +// names no backend and meets the refusal through the member it calls (owner decision 7). The +// object is a parameter, since making one would run the stand-in's engine. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/detail/asynchronous.hpp:* {{webcpp::crypto: WebCrypto has no ChaCha20: no form of the raw stream cipher, synchronous or asynchronous, runs on the browser's backend; name a native backend for it.}} +// clang-format on +#include +#include + +#include + +#include + +#include +#include + +namespace { + +/** A backend that completes by itself, as part B's browser backend will. */ +struct stand_in_browser {}; + +} // namespace + +template <> +inline constexpr bool webcpp::crypto::detail::asynchronous_backend_v = true; + +/** ChaCha20 on the stand-in. */ +using stand_in_chacha20 = webcpp::crypto::ciphers::chacha20; + +namespace { + +/** Applies the keystream asynchronously through the free form. */ +void applied(stand_in_chacha20& cipher) { + std::array const nonce{}; + std::array data{'h', 'e', 'l', 'l', 'o'}; + webcpp::asio::io_context context; + webcpp::crypto::unauthenticated_encryption::async_apply_keystream( + context.get_executor(), cipher, nonce, data, 0, [](boost::system::error_code) {}); +} + +} // namespace + +// The function is compiled, which is the test; it is never run. +int main() { + static_cast(&applied); + return 0; +} diff --git a/test/messages/async_authenticate_asynchronous_backend/Jamfile b/test/messages/async_authenticate_asynchronous_backend/Jamfile new file mode 100644 index 0000000..465b814 --- /dev/null +++ b/test/messages/async_authenticate_asynchronous_backend/Jamfile @@ -0,0 +1,15 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic async_authenticate_asynchronous_backend + : async_authenticate_asynchronous_backend.cpp : /webcpp/asio//asio + : native wasip2 wasip3 : alone ; diff --git a/test/messages/async_authenticate_asynchronous_backend/async_authenticate_asynchronous_backend.cpp b/test/messages/async_authenticate_asynchronous_backend/async_authenticate_asynchronous_backend.cpp new file mode 100644 index 0000000..9c480fc --- /dev/null +++ b/test/messages/async_authenticate_asynchronous_backend/async_authenticate_asynchronous_backend.cpp @@ -0,0 +1,60 @@ +// 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) + +// Poly1305's async_authenticate, the static member and the free +// single_use_key_authentication::async_authenticate, on a backend that completes by itself (a +// stand-in whose detail::asynchronous_backend_v is true) stops with the refusal that sends it to a +// native backend (design D15), and with that error alone: the free form meets the refusal through +// the member it calls, and no engine is named (ruling P12). + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/detail/asynchronous.hpp:* {{webcpp::crypto: WebCrypto has no Poly1305: no form of the single-use key authenticator, synchronous or asynchronous, runs on the browser's backend; name a native backend for it.}} +// clang-format on +#include +#include + +#include + +#include + +#include +#include + +namespace { + +/** A backend that completes by itself, as part B's browser backend will. */ +struct stand_in_browser {}; + +} // namespace + +template <> +inline constexpr bool webcpp::crypto::detail::asynchronous_backend_v = true; + +/** Poly1305 on the stand-in. */ +using stand_in_poly1305 = webcpp::crypto::authenticators::poly1305; + +namespace { + +/** Authenticates asynchronously through the static member and the free form. */ +void authenticated() { + std::array const key{}; + std::array const message{'h', 'e', 'l', 'l', 'o'}; + webcpp::asio::io_context context; + auto const completion = [](boost::system::error_code, stand_in_poly1305::result_type) {}; + stand_in_poly1305::async_authenticate(context.get_executor(), key, message, completion); + webcpp::crypto::single_use_key_authentication::async_authenticate( + context.get_executor(), key, message, completion); +} + +} // namespace + +// The function is compiled, which is the test; it is never run. +int main() { + static_cast(&authenticated); + return 0; +} diff --git a/test/messages/async_authenticate_not_a_single_use_key_authenticator/Jamfile b/test/messages/async_authenticate_not_a_single_use_key_authenticator/Jamfile new file mode 100644 index 0000000..89f1059 --- /dev/null +++ b/test/messages/async_authenticate_not_a_single_use_key_authenticator/Jamfile @@ -0,0 +1,17 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +# MSVC twin: async_authenticate_not_an_authenticator +# (shorter: the twin's object path stays under Windows' 260 characters) +webcpp.compile-diagnostic async_authenticate_not_a_single_use_key_authenticator + : async_authenticate_not_a_single_use_key_authenticator.cpp : /webcpp/asio//asio + : native wasip2 wasip3 : alone ; diff --git a/test/messages/async_authenticate_not_a_single_use_key_authenticator/async_authenticate_not_a_single_use_key_authenticator.cpp b/test/messages/async_authenticate_not_a_single_use_key_authenticator/async_authenticate_not_a_single_use_key_authenticator.cpp new file mode 100644 index 0000000..740d4c2 --- /dev/null +++ b/test/messages/async_authenticate_not_a_single_use_key_authenticator/async_authenticate_not_a_single_use_key_authenticator.cpp @@ -0,0 +1,36 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// single_use_key_authentication::async_authenticate given HMAC-SHA256, webcpp::hash's MAC, whose +// key is used for many messages and which is no single-use key authenticator, stops with what it +// takes and where a reusable key's asynchronous MAC is, and with that error alone. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/async.hpp:* {{webcpp::crypto: single_use_key_authentication::async_authenticate takes a single-use key authenticator (authenticators::poly1305); a reusable key's MAC is webcpp::hash::async_hmac (HMAC).}} +// clang-format on + +#include +#include + +#include + +#include + +#include +#include + +int main() { + namespace hash = webcpp::hash; + std::array const key{}; + std::array const message{}; + webcpp::asio::io_context context; + webcpp::crypto::single_use_key_authentication::async_authenticate< + hash::macs::hmac>(context.get_executor(), key, message, + [](boost::system::error_code) {}); + return 0; +} diff --git a/test/messages/async_from_key_aead_without_member/Jamfile b/test/messages/async_from_key_aead_without_member/Jamfile new file mode 100644 index 0000000..7ca7a0c --- /dev/null +++ b/test/messages/async_from_key_aead_without_member/Jamfile @@ -0,0 +1,15 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic async_from_key_aead_without_member + : async_from_key_aead_without_member.cpp + : /webcpp/asio//asio /third_party//sodium : native wasip2 wasip3 : alone ; diff --git a/test/messages/async_from_key_aead_without_member/async_from_key_aead_without_member.cpp b/test/messages/async_from_key_aead_without_member/async_from_key_aead_without_member.cpp new file mode 100644 index 0000000..97920d8 --- /dev/null +++ b/test/messages/async_from_key_aead_without_member/async_from_key_aead_without_member.cpp @@ -0,0 +1,70 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// crypto::async_from_key given an AEAD of the concept without the member async_from_key stops +// with what it posts (a stream cipher's synchronous from_key alone), and with that error alone. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/async.hpp:* {{webcpp::crypto: async_from_key runs the synchronous from_key of a stream cipher alone: an AEAD or a secret box without the member async_from_key cannot be made asynchronously.}} +// clang-format on +#include +#include + +#include + +#include +#include + +#include +#include +#include +#include + +namespace { + +// An AEAD of the concept without the member async_from_key. +struct stand_in_aead { + static constexpr std::size_t key_size = 16; + static constexpr std::size_t nonce_size = 12; + static constexpr std::size_t tag_size = 16; + using result_type = std::array; + + static boost::system::result from_key( + std::span key_bytes) noexcept { + if (key_bytes.size() != key_size) { + return webcpp::crypto::error::invalid_key_size; + } + return stand_in_aead{}; + } + + boost::system::result seal(std::span /*nonce_bytes*/, + std::span /*associated_data_bytes*/, + std::span /*data_bytes*/) noexcept { + return result_type{}; + } + + boost::system::result open(std::span /*nonce_bytes*/, + std::span /*associated_data_bytes*/, + std::span /*data_bytes*/, + std::span /*tag_bytes*/) noexcept { + return {}; + } +}; + +static_assert(webcpp::crypto::secret_key_encryption::aead::cipher); + +} // namespace + +int main() { + namespace crypto = webcpp::crypto; + std::array const key{}; + webcpp::asio::io_context context; + crypto::async_from_key(context.get_executor(), key, + [](boost::system::error_code, stand_in_aead) {}); + return 0; +} diff --git a/test/messages/async_from_key_chacha20_asynchronous_backend/Jamfile b/test/messages/async_from_key_chacha20_asynchronous_backend/Jamfile new file mode 100644 index 0000000..7371bf5 --- /dev/null +++ b/test/messages/async_from_key_chacha20_asynchronous_backend/Jamfile @@ -0,0 +1,17 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +# MSVC twin: async_from_key_chacha20_async_bk +# (shorter: the twin's object path stays under Windows' 260 characters) +webcpp.compile-diagnostic async_from_key_chacha20_asynchronous_backend + : async_from_key_chacha20_asynchronous_backend.cpp : /webcpp/asio//asio + : native wasip2 wasip3 : alone ; diff --git a/test/messages/async_from_key_chacha20_asynchronous_backend/async_from_key_chacha20_asynchronous_backend.cpp b/test/messages/async_from_key_chacha20_asynchronous_backend/async_from_key_chacha20_asynchronous_backend.cpp new file mode 100644 index 0000000..20cd902 --- /dev/null +++ b/test/messages/async_from_key_chacha20_asynchronous_backend/async_from_key_chacha20_asynchronous_backend.cpp @@ -0,0 +1,56 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// crypto::async_from_key of ChaCha20, which WebCrypto lacks, on a backend that completes by itself +// (a stand-in whose detail::asynchronous_backend_v is true), stops with the refusal that sends it +// to a native backend (design D6), and with that error alone: it fires before any member of the +// engine is named (ruling P12). + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/detail/asynchronous.hpp:* {{webcpp::crypto: WebCrypto has no ChaCha20: no form of the raw stream cipher, synchronous or asynchronous, runs on the browser's backend; name a native backend for it.}} +// clang-format on +#include +#include + +#include + +#include + +#include +#include + +namespace { + +/** A backend that completes by itself, as part B's browser backend will. */ +struct stand_in_browser {}; + +} // namespace + +template <> +inline constexpr bool webcpp::crypto::detail::asynchronous_backend_v = true; + +/** ChaCha20 on the stand-in. */ +using stand_in_chacha20 = webcpp::crypto::ciphers::chacha20; + +namespace { + +/** Makes an object of the stand-in's asynchronously. */ +void made() { + std::array const key{}; + webcpp::asio::io_context context; + webcpp::crypto::async_from_key( + context.get_executor(), key, [](boost::system::error_code, stand_in_chacha20) {}); +} + +} // namespace + +// The function is compiled, which is the test; it is never run. +int main() { + static_cast(&made); + return 0; +} diff --git a/test/messages/async_from_key_not_a_cipher/Jamfile b/test/messages/async_from_key_not_a_cipher/Jamfile new file mode 100644 index 0000000..12ecce9 --- /dev/null +++ b/test/messages/async_from_key_not_a_cipher/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic async_from_key_not_a_cipher : async_from_key_not_a_cipher.cpp + : /webcpp/asio//asio /third_party//sodium : native wasip2 wasip3 : alone ; diff --git a/test/messages/async_from_key_not_a_cipher/async_from_key_not_a_cipher.cpp b/test/messages/async_from_key_not_a_cipher/async_from_key_not_a_cipher.cpp new file mode 100644 index 0000000..5dab4e2 --- /dev/null +++ b/test/messages/async_from_key_not_a_cipher/async_from_key_not_a_cipher.cpp @@ -0,0 +1,33 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// crypto::async_from_key given a type that is no AEAD, no stream cipher and no secret box, a +// crypto_box, stops with what it takes and how a crypto_box is made, and with that error alone. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/async.hpp:* {{webcpp::crypto: async_from_key takes an AEAD (a secret_key_encryption::aead::cipher), a stream cipher (a unauthenticated_encryption::stream_cipher) or a secret box: a crypto_box is made by from_keys.}} +// clang-format on +#include +#include +#include + +#include + +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + using box = crypto::public_key_encryption::box; + std::array const key{}; + webcpp::asio::io_context context; + crypto::async_from_key(context.get_executor(), key, [](boost::system::error_code, box) {}); + return 0; +} diff --git a/test/messages/async_from_key_stream_cipher_without_empty/Jamfile b/test/messages/async_from_key_stream_cipher_without_empty/Jamfile new file mode 100644 index 0000000..9a9043c --- /dev/null +++ b/test/messages/async_from_key_stream_cipher_without_empty/Jamfile @@ -0,0 +1,17 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +# MSVC twin: async_from_key_stream_cipher_no_empty +# (shorter: the twin's object path stays under Windows' 260 characters) +webcpp.compile-diagnostic async_from_key_stream_cipher_without_empty + : async_from_key_stream_cipher_without_empty.cpp + : /webcpp/asio//asio /third_party//sodium : native wasip2 wasip3 : alone ; diff --git a/test/messages/async_from_key_stream_cipher_without_empty/async_from_key_stream_cipher_without_empty.cpp b/test/messages/async_from_key_stream_cipher_without_empty/async_from_key_stream_cipher_without_empty.cpp new file mode 100644 index 0000000..3022936 --- /dev/null +++ b/test/messages/async_from_key_stream_cipher_without_empty/async_from_key_stream_cipher_without_empty.cpp @@ -0,0 +1,78 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// crypto::async_from_key given a stream cipher without the member async_from_key and without a +// default constructor stops with what the posted error completion needs, and with that error alone. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/async.hpp:* {{webcpp::crypto: async_from_key posts a stream cipher's synchronous from_key, whose error completion gives an empty cipher: give the type a noexcept default constructor, public or private with webcpp::crypto::detail::async_access a friend.}} +// clang-format on +#include +#include + +#include + +#include +#include + +#include +#include +#include +#include + +namespace { + +// A stream cipher of the concept without the member async_from_key and without a default +// constructor: its key is its only constructor's argument. +class stand_in_stream_cipher { +public: + static constexpr std::size_t key_size = 16; + static constexpr std::size_t nonce_size = 8; + static constexpr std::size_t block_size = 16; + using counter_type = std::uint8_t; + + explicit stand_in_stream_cipher(std::array const& key) noexcept + : key_(key) {} + + static boost::system::result from_key( + std::span key_bytes) noexcept { + if (key_bytes.size() != key_size) { + return webcpp::crypto::error::invalid_key_size; + } + std::array key{}; + for (std::size_t i = 0; i < key_size; ++i) { + key[i] = key_bytes[i]; + } + return stand_in_stream_cipher{key}; + } + + boost::system::result apply_keystream(std::span /*nonce_bytes*/, + std::span data_bytes, + counter_type /*initial_counter*/) noexcept { + for (std::size_t i = 0; i < data_bytes.size(); ++i) { + data_bytes[i] ^= key_[i % key_size]; + } + return {}; + } + +private: + std::array key_; +}; + +static_assert(webcpp::crypto::unauthenticated_encryption::stream_cipher); + +} // namespace + +int main() { + namespace crypto = webcpp::crypto; + std::array const key{}; + webcpp::asio::io_context context; + crypto::async_from_key( + context.get_executor(), key, [](boost::system::error_code, stand_in_stream_cipher) {}); + return 0; +} diff --git a/test/messages/async_verify_asynchronous_backend/Jamfile b/test/messages/async_verify_asynchronous_backend/Jamfile new file mode 100644 index 0000000..6b1c68c --- /dev/null +++ b/test/messages/async_verify_asynchronous_backend/Jamfile @@ -0,0 +1,15 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic async_verify_asynchronous_backend + : async_verify_asynchronous_backend.cpp : /webcpp/asio//asio + : native wasip2 wasip3 : alone ; diff --git a/test/messages/async_verify_asynchronous_backend/async_verify_asynchronous_backend.cpp b/test/messages/async_verify_asynchronous_backend/async_verify_asynchronous_backend.cpp new file mode 100644 index 0000000..0d0bd5d --- /dev/null +++ b/test/messages/async_verify_asynchronous_backend/async_verify_asynchronous_backend.cpp @@ -0,0 +1,61 @@ +// 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) + +// Poly1305's async_verify, the static member and the free +// single_use_key_authentication::async_verify, on a backend that completes by itself (a stand-in +// whose detail::asynchronous_backend_v is true) stops with the refusal that sends it to a native +// backend (design D15), and with that error alone: the free form meets the refusal through the +// member it calls, and no engine is named (ruling P12). + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/detail/asynchronous.hpp:* {{webcpp::crypto: WebCrypto has no Poly1305: no form of the single-use key authenticator, synchronous or asynchronous, runs on the browser's backend; name a native backend for it.}} +// clang-format on +#include +#include + +#include + +#include + +#include +#include + +namespace { + +/** A backend that completes by itself, as part B's browser backend will. */ +struct stand_in_browser {}; + +} // namespace + +template <> +inline constexpr bool webcpp::crypto::detail::asynchronous_backend_v = true; + +/** Poly1305 on the stand-in. */ +using stand_in_poly1305 = webcpp::crypto::authenticators::poly1305; + +namespace { + +/** Verifies asynchronously through the static member and the free form. */ +void verified() { + std::array const key{}; + std::array const message{'h', 'e', 'l', 'l', 'o'}; + std::array const tag{}; + webcpp::asio::io_context context; + auto const completion = [](boost::system::error_code) {}; + stand_in_poly1305::async_verify(context.get_executor(), key, message, tag, completion); + webcpp::crypto::single_use_key_authentication::async_verify( + context.get_executor(), key, message, tag, completion); +} + +} // namespace + +// The function is compiled, which is the test; it is never run. +int main() { + static_cast(&verified); + return 0; +} diff --git a/test/messages/async_verify_not_a_single_use_key_authenticator/Jamfile b/test/messages/async_verify_not_a_single_use_key_authenticator/Jamfile new file mode 100644 index 0000000..41e88db --- /dev/null +++ b/test/messages/async_verify_not_a_single_use_key_authenticator/Jamfile @@ -0,0 +1,17 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +# MSVC twin: async_verify_not_an_authenticator +# (shorter: the twin's object path stays under Windows' 260 characters) +webcpp.compile-diagnostic async_verify_not_a_single_use_key_authenticator + : async_verify_not_a_single_use_key_authenticator.cpp : /webcpp/asio//asio + : native wasip2 wasip3 : alone ; diff --git a/test/messages/async_verify_not_a_single_use_key_authenticator/async_verify_not_a_single_use_key_authenticator.cpp b/test/messages/async_verify_not_a_single_use_key_authenticator/async_verify_not_a_single_use_key_authenticator.cpp new file mode 100644 index 0000000..4984a8f --- /dev/null +++ b/test/messages/async_verify_not_a_single_use_key_authenticator/async_verify_not_a_single_use_key_authenticator.cpp @@ -0,0 +1,37 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// single_use_key_authentication::async_verify given HMAC-SHA256, webcpp::hash's MAC, whose key is +// used for many messages and which is no single-use key authenticator, stops with what it takes +// and where a reusable key's asynchronous MAC is, and with that error alone. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/async.hpp:* {{webcpp::crypto: single_use_key_authentication::async_verify takes a single-use key authenticator (authenticators::poly1305); a reusable key's MAC is webcpp::hash::async_hmac (HMAC).}} +// clang-format on + +#include +#include + +#include + +#include + +#include +#include + +int main() { + namespace hash = webcpp::hash; + std::array const key{}; + std::array const message{}; + std::array const tag{}; + webcpp::asio::io_context context; + webcpp::crypto::single_use_key_authentication::async_verify< + hash::macs::hmac>(context.get_executor(), key, message, tag, + [](boost::system::error_code) {}); + return 0; +} diff --git a/test/messages/authenticate_asynchronous_backend/Jamfile b/test/messages/authenticate_asynchronous_backend/Jamfile new file mode 100644 index 0000000..fc15e9b --- /dev/null +++ b/test/messages/authenticate_asynchronous_backend/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic authenticate_asynchronous_backend + : authenticate_asynchronous_backend.cpp : : native wasip2 wasip3 : alone ; diff --git a/test/messages/authenticate_asynchronous_backend/authenticate_asynchronous_backend.cpp b/test/messages/authenticate_asynchronous_backend/authenticate_asynchronous_backend.cpp new file mode 100644 index 0000000..4ffa9b3 --- /dev/null +++ b/test/messages/authenticate_asynchronous_backend/authenticate_asynchronous_backend.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) + +// Poly1305's authenticate, the static member and the free form, on a backend that completes by +// itself (a stand-in whose detail::asynchronous_backend_v is true) stops with the refusal that +// sends it to a native backend (design D15): WebCrypto has no Poly1305. That error alone: the free +// form meets the refusal through the member it calls, and no engine is named (ruling P12). + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/detail/asynchronous.hpp:* {{webcpp::crypto: WebCrypto has no Poly1305: no form of the single-use key authenticator, synchronous or asynchronous, runs on the browser's backend; name a native backend for it.}} +// clang-format on +#include + +#include +#include + +namespace { + +/** A backend that completes by itself, as part B's browser backend will. */ +struct stand_in_browser {}; + +} // namespace + +template <> +inline constexpr bool webcpp::crypto::detail::asynchronous_backend_v = true; + +/** Poly1305 on the stand-in. */ +using stand_in_poly1305 = webcpp::crypto::authenticators::poly1305; + +namespace { + +/** Authenticates through the static member and the free form. */ +bool authenticated() { + std::array const key{}; + std::array const message{'h', 'e', 'l', 'l', 'o'}; + return stand_in_poly1305::authenticate(key, message).has_value() && + webcpp::crypto::single_use_key_authentication::authenticate(key, + message) + .has_value(); +} + +} // namespace + +// The function is compiled, which is the test; it is never run. +int main() { + static_cast(&authenticated); + return 0; +} diff --git a/test/messages/authenticate_not_a_single_use_key_authenticator/Jamfile b/test/messages/authenticate_not_a_single_use_key_authenticator/Jamfile new file mode 100644 index 0000000..15d1f02 --- /dev/null +++ b/test/messages/authenticate_not_a_single_use_key_authenticator/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +# MSVC twin: authenticate_not_an_authenticator +# (shorter: the twin's object path stays under Windows' 260 characters) +webcpp.compile-diagnostic authenticate_not_a_single_use_key_authenticator + : authenticate_not_a_single_use_key_authenticator.cpp : : native wasip2 wasip3 : alone ; diff --git a/test/messages/authenticate_not_a_single_use_key_authenticator/authenticate_not_a_single_use_key_authenticator.cpp b/test/messages/authenticate_not_a_single_use_key_authenticator/authenticate_not_a_single_use_key_authenticator.cpp new file mode 100644 index 0000000..fdc0b30 --- /dev/null +++ b/test/messages/authenticate_not_a_single_use_key_authenticator/authenticate_not_a_single_use_key_authenticator.cpp @@ -0,0 +1,30 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// single_use_key_authentication::authenticate given HMAC-SHA256, webcpp::hash's MAC, whose key is +// used for many messages and which is no single-use key authenticator, stops with what it takes and +// where a reusable key's MAC is, and with that error alone. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/single_use_key_authentication/authenticator.hpp:* {{webcpp::crypto: single_use_key_authentication::authenticate takes a single-use key authenticator (authenticators::poly1305); a reusable key's MAC is webcpp::hash::mac (HMAC).}} +// clang-format on + +#include +#include + +#include +#include + +int main() { + namespace hash = webcpp::hash; + std::array const key{}; + std::array const message{}; + webcpp::crypto::single_use_key_authentication::authenticate< + hash::macs::hmac>(key, message); + return 0; +} diff --git a/test/messages/chacha20_default_not_linked/Jamfile b/test/messages/chacha20_default_not_linked/Jamfile new file mode 100644 index 0000000..138bf50 --- /dev/null +++ b/test/messages/chacha20_default_not_linked/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic chacha20_default_not_linked : chacha20_default_not_linked.cpp + : : native wasip2 wasip3 : alone ; diff --git a/test/messages/chacha20_default_not_linked/chacha20_default_not_linked.cpp b/test/messages/chacha20_default_not_linked/chacha20_default_not_linked.cpp new file mode 100644 index 0000000..795cfc5 --- /dev/null +++ b/test/messages/chacha20_default_not_linked/chacha20_default_not_linked.cpp @@ -0,0 +1,24 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A program that calls ChaCha20 on its default backend, libsodium on every target, without +// linking it, stops where it calls it, with the line that links libsodium. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/ciphers/stream_cipher.hpp:* {{webcpp::crypto: ChaCha20's default backend on this target is libsodium, which is not linked. Add /webcpp/crypto//chacha20-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//chacha20-default ; or name another backend in the type, as in ciphers::chacha20. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)}} +// clang-format on + +#include + +#include +#include + +int main() { + std::array const key{}; + return webcpp::crypto::ciphers::chacha20<>::from_key(key) ? 0 : 1; +} diff --git a/test/messages/chacha20_header_not_included/Jamfile b/test/messages/chacha20_header_not_included/Jamfile new file mode 100644 index 0000000..b2000dd --- /dev/null +++ b/test/messages/chacha20_header_not_included/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic chacha20_header_not_included : chacha20_header_not_included.cpp + : : native wasip2 wasip3 : alone ; diff --git a/test/messages/chacha20_header_not_included/chacha20_header_not_included.cpp b/test/messages/chacha20_header_not_included/chacha20_header_not_included.cpp new file mode 100644 index 0000000..f22ff90 --- /dev/null +++ b/test/messages/chacha20_header_not_included/chacha20_header_not_included.cpp @@ -0,0 +1,25 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A program that names BearSSL in ChaCha20's type without including BearSSL's header stops where +// it makes the cipher, with the header to include and the line that links BearSSL. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/ciphers/stream_cipher.hpp:* {{webcpp::crypto: bearssl's ChaCha20 is in , which the program does not include. Include it, and add /third_party//bearssl to the program's Jamfile.}} +// clang-format on + +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const key{}; + return crypto::ciphers::chacha20::from_key(key) ? 0 : 1; +} diff --git a/test/messages/chacha20_not_a_family/Jamfile b/test/messages/chacha20_not_a_family/Jamfile new file mode 100644 index 0000000..87f1296 --- /dev/null +++ b/test/messages/chacha20_not_a_family/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic chacha20_not_a_family : chacha20_not_a_family.cpp + : : native wasip2 wasip3 : alone ; diff --git a/test/messages/chacha20_not_a_family/chacha20_not_a_family.cpp b/test/messages/chacha20_not_a_family/chacha20_not_a_family.cpp new file mode 100644 index 0000000..760ba34 --- /dev/null +++ b/test/messages/chacha20_not_a_family/chacha20_not_a_family.cpp @@ -0,0 +1,24 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// ciphers::basic_chacha20 given a family that is no stream cipher's, ChaCha20-Poly1305's, stops +// with the family it takes, and with that error alone. + +// clang-format off +// expected-error@webcpp/crypto/ciphers/stream_cipher.hpp:* {{webcpp::crypto: ciphers::basic_chacha20 takes a stream family: families::chacha20.}} +// clang-format on +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + using cipher = crypto::ciphers::basic_chacha20; + std::array const key{}; + return cipher::from_key(key) ? 0 : 1; +} diff --git a/test/messages/chacha20_on_ctaes/Jamfile b/test/messages/chacha20_on_ctaes/Jamfile new file mode 100644 index 0000000..17c7d1b --- /dev/null +++ b/test/messages/chacha20_on_ctaes/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic chacha20_on_ctaes : chacha20_on_ctaes.cpp + : /third_party//ctaes : native wasip2 wasip3 : alone ; diff --git a/test/messages/chacha20_on_ctaes/chacha20_on_ctaes.cpp b/test/messages/chacha20_on_ctaes/chacha20_on_ctaes.cpp new file mode 100644 index 0000000..f29fe7f --- /dev/null +++ b/test/messages/chacha20_on_ctaes/chacha20_on_ctaes.cpp @@ -0,0 +1,24 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// ChaCha20 on ctaes, which exports the AES block cipher alone, is refused where it is called, +// with the backends that have it and their targets (the generated refusal, +// detail/capabilities.hpp). + +// clang-format off +// expected-error@webcpp/crypto/ciphers/stream_cipher.hpp:* {{webcpp::crypto: ctaes has no ChaCha20. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).}} +// clang-format on +#include +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const key{}; + return crypto::ciphers::chacha20::from_key(key) ? 0 : 1; +} diff --git a/test/messages/chacha20_unknown_backend/Jamfile b/test/messages/chacha20_unknown_backend/Jamfile new file mode 100644 index 0000000..fef66fd --- /dev/null +++ b/test/messages/chacha20_unknown_backend/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic chacha20_unknown_backend : chacha20_unknown_backend.cpp + : : native wasip2 wasip3 : alone ; diff --git a/test/messages/chacha20_unknown_backend/chacha20_unknown_backend.cpp b/test/messages/chacha20_unknown_backend/chacha20_unknown_backend.cpp new file mode 100644 index 0000000..4b38b41 --- /dev/null +++ b/test/messages/chacha20_unknown_backend/chacha20_unknown_backend.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) + +// A program that names a type of its own as ChaCha20's backend stops where it makes the cipher, +// with the backends that have the family. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/ciphers/stream_cipher.hpp:* {{webcpp::crypto: ChaCha20 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).}} +// clang-format on + +#include + +#include +#include + +namespace { + +/** A type of the program's own, which is no backend. */ +struct my_backend {}; + +} // namespace + +int main() { + std::array const key{}; + return webcpp::crypto::ciphers::chacha20::from_key(key) ? 0 : 1; +} diff --git a/test/messages/from_key_chacha20_asynchronous_backend/Jamfile b/test/messages/from_key_chacha20_asynchronous_backend/Jamfile new file mode 100644 index 0000000..dc75051 --- /dev/null +++ b/test/messages/from_key_chacha20_asynchronous_backend/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic from_key_chacha20_asynchronous_backend + : from_key_chacha20_asynchronous_backend.cpp : : native wasip2 wasip3 : alone ; diff --git a/test/messages/from_key_chacha20_asynchronous_backend/from_key_chacha20_asynchronous_backend.cpp b/test/messages/from_key_chacha20_asynchronous_backend/from_key_chacha20_asynchronous_backend.cpp new file mode 100644 index 0000000..27ae731 --- /dev/null +++ b/test/messages/from_key_chacha20_asynchronous_backend/from_key_chacha20_asynchronous_backend.cpp @@ -0,0 +1,50 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// ChaCha20's own from_key on a backend that completes by itself (a stand-in whose +// detail::asynchronous_backend_v is true) stops with the refusal that sends it to a native backend, +// as its other forms do (design D6): WebCrypto has no ChaCha20. That error alone: the result kept +// destroys an object of the stand-in's, and its engine adds no refusal of its own. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/detail/asynchronous.hpp:* {{webcpp::crypto: WebCrypto has no ChaCha20: no form of the raw stream cipher, synchronous or asynchronous, runs on the browser's backend; name a native backend for it.}} +// clang-format on +#include + +#include +#include + +namespace { + +/** A backend that completes by itself, as part B's browser backend will. */ +struct stand_in_browser {}; + +} // namespace + +template <> +inline constexpr bool webcpp::crypto::detail::asynchronous_backend_v = true; + +/** ChaCha20 on the stand-in. */ +using stand_in_chacha20 = webcpp::crypto::ciphers::chacha20; + +namespace { + +/** Makes an object of the stand-in's and keeps the result. */ +bool made() { + std::array const key{}; + auto const made_cipher = stand_in_chacha20::from_key(key); + return made_cipher.has_value(); +} + +} // namespace + +// The function is compiled, which is the test; it is never run. +int main() { + static_cast(&made); + return 0; +} diff --git a/test/messages/from_key_chacha20_poly1305_asynchronous_backend/Jamfile b/test/messages/from_key_chacha20_poly1305_asynchronous_backend/Jamfile new file mode 100644 index 0000000..054445e --- /dev/null +++ b/test/messages/from_key_chacha20_poly1305_asynchronous_backend/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +# MSVC twin: from_key_chacha20_poly1305_async_backend +# (shorter: the twin's object path stays under Windows' 260 characters) +webcpp.compile-diagnostic from_key_chacha20_poly1305_asynchronous_backend + : from_key_chacha20_poly1305_asynchronous_backend.cpp : : native wasip2 wasip3 : alone ; diff --git a/test/messages/from_key_chacha20_poly1305_asynchronous_backend/from_key_chacha20_poly1305_asynchronous_backend.cpp b/test/messages/from_key_chacha20_poly1305_asynchronous_backend/from_key_chacha20_poly1305_asynchronous_backend.cpp new file mode 100644 index 0000000..6682913 --- /dev/null +++ b/test/messages/from_key_chacha20_poly1305_asynchronous_backend/from_key_chacha20_poly1305_asynchronous_backend.cpp @@ -0,0 +1,50 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// ChaCha20-Poly1305's own from_key on a backend that completes by itself (a stand-in whose +// detail::asynchronous_backend_v is true) stops with the refusal that sends it to a native backend +// (design D6): WebCrypto has no ChaCha20-Poly1305. That error alone: the result kept destroys an +// object of the stand-in's, and its engine adds no refusal of its own. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/detail/asynchronous.hpp:* {{webcpp::crypto: WebCrypto has no ChaCha20-Poly1305, XChaCha20-Poly1305, secret box or crypto_box: no form of them, synchronous or asynchronous, runs on the browser's backend; name a native backend for them. On the browser's backend only AES-GCM seals and opens.}} +// clang-format on +#include + +#include +#include + +namespace { + +/** A backend that completes by itself, as part B's browser backend will. */ +struct stand_in_browser {}; + +} // namespace + +template <> +inline constexpr bool webcpp::crypto::detail::asynchronous_backend_v = true; + +/** ChaCha20-Poly1305 on the stand-in. */ +using stand_in_aead = webcpp::crypto::ciphers::chacha20_poly1305; + +namespace { + +/** Makes an object of the stand-in's and keeps the result. */ +bool made() { + std::array const key{}; + auto const made_aead = stand_in_aead::from_key(key); + return made_aead.has_value(); +} + +} // namespace + +// The function is compiled, which is the test; it is never run. +int main() { + static_cast(&made); + return 0; +} diff --git a/test/messages/from_key_poly1305/Jamfile b/test/messages/from_key_poly1305/Jamfile new file mode 100644 index 0000000..d2b1837 --- /dev/null +++ b/test/messages/from_key_poly1305/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic from_key_poly1305 : from_key_poly1305.cpp + : /third_party//sodium : native wasip2 wasip3 : alone ; diff --git a/test/messages/from_key_poly1305/from_key_poly1305.cpp b/test/messages/from_key_poly1305/from_key_poly1305.cpp new file mode 100644 index 0000000..9b46026 --- /dev/null +++ b/test/messages/from_key_poly1305/from_key_poly1305.cpp @@ -0,0 +1,23 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// crypto::from_key given Poly1305, which has no object and no from_key (design R21), stops with +// factories.hpp's existing refusal, its requirement on a static from_key, and with that error +// alone: the key enters every call of authenticate and verify. + +#include +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const key{}; + // expected-error@+1 {{no matching function for call to 'from_key'}} + static_cast(crypto::from_key>(key)); + return 0; +} diff --git a/test/messages/from_key_secretbox_asynchronous_backend/Jamfile b/test/messages/from_key_secretbox_asynchronous_backend/Jamfile new file mode 100644 index 0000000..0e7cceb --- /dev/null +++ b/test/messages/from_key_secretbox_asynchronous_backend/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic from_key_secretbox_asynchronous_backend + : from_key_secretbox_asynchronous_backend.cpp : : native wasip2 wasip3 : alone ; diff --git a/test/messages/from_key_secretbox_asynchronous_backend/from_key_secretbox_asynchronous_backend.cpp b/test/messages/from_key_secretbox_asynchronous_backend/from_key_secretbox_asynchronous_backend.cpp new file mode 100644 index 0000000..f059248 --- /dev/null +++ b/test/messages/from_key_secretbox_asynchronous_backend/from_key_secretbox_asynchronous_backend.cpp @@ -0,0 +1,50 @@ +// 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 secret box's own from_key on a backend that completes by itself (a stand-in whose +// detail::asynchronous_backend_v is true) stops with the refusal that sends it to a native backend +// (design D6): WebCrypto has no secret box. That error alone: the result kept destroys a box of the +// stand-in's, and its engine adds no refusal of its own. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/detail/asynchronous.hpp:* {{webcpp::crypto: WebCrypto has no ChaCha20-Poly1305, XChaCha20-Poly1305, secret box or crypto_box: no form of them, synchronous or asynchronous, runs on the browser's backend; name a native backend for them. On the browser's backend only AES-GCM seals and opens.}} +// clang-format on +#include + +#include +#include + +namespace { + +/** A backend that completes by itself, as part B's browser backend will. */ +struct stand_in_browser {}; + +} // namespace + +template <> +inline constexpr bool webcpp::crypto::detail::asynchronous_backend_v = true; + +/** The secret box on the stand-in. */ +using stand_in_secretbox = webcpp::crypto::secret_key_encryption::secretbox; + +namespace { + +/** Makes a box of the stand-in's and keeps the result. */ +bool made() { + std::array const key{}; + auto const made_box = stand_in_secretbox::from_key(key); + return made_box.has_value(); +} + +} // namespace + +// The function is compiled, which is the test; it is never run. +int main() { + static_cast(&made); + return 0; +} diff --git a/test/messages/from_keys_box_asynchronous_backend/Jamfile b/test/messages/from_keys_box_asynchronous_backend/Jamfile new file mode 100644 index 0000000..37174cd --- /dev/null +++ b/test/messages/from_keys_box_asynchronous_backend/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic from_keys_box_asynchronous_backend + : from_keys_box_asynchronous_backend.cpp : : native wasip2 wasip3 : alone ; diff --git a/test/messages/from_keys_box_asynchronous_backend/from_keys_box_asynchronous_backend.cpp b/test/messages/from_keys_box_asynchronous_backend/from_keys_box_asynchronous_backend.cpp new file mode 100644 index 0000000..09c9f78 --- /dev/null +++ b/test/messages/from_keys_box_asynchronous_backend/from_keys_box_asynchronous_backend.cpp @@ -0,0 +1,50 @@ +// 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 crypto_box's own from_keys on a backend that completes by itself (a stand-in whose +// detail::asynchronous_backend_v is true) stops with the refusal that sends it to a native backend +// (design D6): WebCrypto has no crypto_box. That error alone: the result kept destroys a box of the +// stand-in's, and its engine adds no refusal of its own. The key pairs are parameters, since making +// them would run the stand-in's X25519. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/detail/asynchronous.hpp:* {{webcpp::crypto: WebCrypto has no ChaCha20-Poly1305, XChaCha20-Poly1305, secret box or crypto_box: no form of them, synchronous or asynchronous, runs on the browser's backend; name a native backend for them. On the browser's backend only AES-GCM seals and opens.}} +// clang-format on +#include + +namespace { + +/** A backend that completes by itself, as part B's browser backend will. */ +struct stand_in_browser {}; + +} // namespace + +template <> +inline constexpr bool webcpp::crypto::detail::asynchronous_backend_v = true; + +/** The crypto_box on the stand-in. */ +using stand_in_box = + webcpp::crypto::public_key_encryption::basic_box; + +namespace { + +/** Makes a box of the stand-in's from key pairs given and keeps the result. */ +bool made(stand_in_box::keypair_type const& own_keypair, + stand_in_box::public_key_type const& peer_public_key) { + auto const made_box = stand_in_box::from_keys(own_keypair, peer_public_key); + return made_box.has_value(); +} + +} // namespace + +// The function is compiled, which is the test; it is never run. +int main() { + static_cast(&made); + return 0; +} diff --git a/test/messages/poly1305_default_not_linked/Jamfile b/test/messages/poly1305_default_not_linked/Jamfile new file mode 100644 index 0000000..6b7be26 --- /dev/null +++ b/test/messages/poly1305_default_not_linked/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic poly1305_default_not_linked : poly1305_default_not_linked.cpp + : : native wasip2 wasip3 : alone ; diff --git a/test/messages/poly1305_default_not_linked/poly1305_default_not_linked.cpp b/test/messages/poly1305_default_not_linked/poly1305_default_not_linked.cpp new file mode 100644 index 0000000..4a6b052 --- /dev/null +++ b/test/messages/poly1305_default_not_linked/poly1305_default_not_linked.cpp @@ -0,0 +1,25 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A program that calls Poly1305 on its default backend, libsodium on every target, without linking +// it, stops where it calls it, with the line that links libsodium. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/authenticators/poly1305.hpp:* {{webcpp::crypto: Poly1305's default backend on this target is libsodium, which is not linked. Add /webcpp/crypto//poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//poly1305-default ; or name another backend in the type, as in authenticators::poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)}} +// clang-format on + +#include + +#include +#include + +int main() { + std::array const key{}; + std::array const message{}; + return webcpp::crypto::authenticators::poly1305<>::authenticate(key, message) ? 0 : 1; +} diff --git a/test/messages/poly1305_header_not_included/Jamfile b/test/messages/poly1305_header_not_included/Jamfile new file mode 100644 index 0000000..0d7af4c --- /dev/null +++ b/test/messages/poly1305_header_not_included/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. OpenSSL is linked and its +# header not included: Poly1305's header includes libsodium's alone, the +# default's, so OpenSSL's is the backend whose header a program can forget. +webcpp.compile-diagnostic poly1305_header_not_included : poly1305_header_not_included.cpp + : /webcpp/crypto//openssl : native wasip2 wasip3 : alone ; diff --git a/test/messages/poly1305_header_not_included/poly1305_header_not_included.cpp b/test/messages/poly1305_header_not_included/poly1305_header_not_included.cpp new file mode 100644 index 0000000..68a9620 --- /dev/null +++ b/test/messages/poly1305_header_not_included/poly1305_header_not_included.cpp @@ -0,0 +1,29 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A program that names OpenSSL in Poly1305's type, links OpenSSL and does not include OpenSSL's +// header stops where it calls the authenticator, with the header to include and the line that +// links OpenSSL. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/authenticators/poly1305.hpp:* {{webcpp::crypto: openssl's Poly1305 is in , which the program does not include. Include it, and add /webcpp/crypto//openssl to the program's Jamfile.}} +// clang-format on + +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const key{}; + std::array const message{}; + return crypto::authenticators::poly1305::authenticate(key, message) + ? 0 + : 1; +} diff --git a/test/messages/poly1305_on_bearssl/Jamfile b/test/messages/poly1305_on_bearssl/Jamfile new file mode 100644 index 0000000..f52565d --- /dev/null +++ b/test/messages/poly1305_on_bearssl/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic poly1305_on_bearssl : poly1305_on_bearssl.cpp + : /third_party//bearssl : native wasip2 wasip3 : alone ; diff --git a/test/messages/poly1305_on_bearssl/poly1305_on_bearssl.cpp b/test/messages/poly1305_on_bearssl/poly1305_on_bearssl.cpp new file mode 100644 index 0000000..2faf033 --- /dev/null +++ b/test/messages/poly1305_on_bearssl/poly1305_on_bearssl.cpp @@ -0,0 +1,30 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Poly1305 on BearSSL, whose Poly1305 is inside its ChaCha20-Poly1305 alone, which derives the key +// itself, is refused where it is called, with the backends that have it and their targets (the +// generated refusal, detail/capabilities.hpp). + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/authenticators/poly1305.hpp:* {{webcpp::crypto: bearssl has no Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).}} +// clang-format on + +#include +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const key{}; + std::array const message{}; + return crypto::authenticators::poly1305::authenticate(key, message) + ? 0 + : 1; +} diff --git a/test/messages/poly1305_on_ctaes/Jamfile b/test/messages/poly1305_on_ctaes/Jamfile new file mode 100644 index 0000000..67f4dd5 --- /dev/null +++ b/test/messages/poly1305_on_ctaes/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic poly1305_on_ctaes : poly1305_on_ctaes.cpp + : /third_party//ctaes : native wasip2 wasip3 : alone ; diff --git a/test/messages/poly1305_on_ctaes/poly1305_on_ctaes.cpp b/test/messages/poly1305_on_ctaes/poly1305_on_ctaes.cpp new file mode 100644 index 0000000..7f335ba --- /dev/null +++ b/test/messages/poly1305_on_ctaes/poly1305_on_ctaes.cpp @@ -0,0 +1,27 @@ +// 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) + +// Poly1305 on ctaes, which exports the AES block cipher alone, is refused where it is called, with +// the backends that have it and their targets (the generated refusal, detail/capabilities.hpp). + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/authenticators/poly1305.hpp:* {{webcpp::crypto: ctaes has no Poly1305. The backends that have it: sodium (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).}} +// clang-format on + +#include +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const key{}; + std::array const tag{}; + return crypto::authenticators::poly1305::verify(key, {}, tag) ? 0 : 1; +} diff --git a/test/messages/poly1305_unknown_backend/Jamfile b/test/messages/poly1305_unknown_backend/Jamfile new file mode 100644 index 0000000..e20ac6a --- /dev/null +++ b/test/messages/poly1305_unknown_backend/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic poly1305_unknown_backend : poly1305_unknown_backend.cpp + : : native wasip2 wasip3 : alone ; diff --git a/test/messages/poly1305_unknown_backend/poly1305_unknown_backend.cpp b/test/messages/poly1305_unknown_backend/poly1305_unknown_backend.cpp new file mode 100644 index 0000000..b4c496e --- /dev/null +++ b/test/messages/poly1305_unknown_backend/poly1305_unknown_backend.cpp @@ -0,0 +1,32 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A program that names a type of its own as Poly1305's backend stops where it authenticates, with +// the backends that have the family. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/authenticators/poly1305.hpp:* {{webcpp::crypto: Poly1305 has no backend of that name. The backends that have it: sodium (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3).}} +// clang-format on + +#include + +#include +#include + +namespace { + +/** A type of the program's own, which is no backend. */ +struct my_backend {}; + +} // namespace + +int main() { + std::array const key{}; + std::array const message{}; + return webcpp::crypto::authenticators::poly1305::authenticate(key, message) ? 0 : 1; +} diff --git a/test/messages/verify_not_a_single_use_key_authenticator/Jamfile b/test/messages/verify_not_a_single_use_key_authenticator/Jamfile new file mode 100644 index 0000000..71d4c6e --- /dev/null +++ b/test/messages/verify_not_a_single_use_key_authenticator/Jamfile @@ -0,0 +1,17 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +# MSVC twin: verify_not_an_authenticator +# (named as its siblings authenticate_not_an_authenticator and +# async_verify_not_an_authenticator) +webcpp.compile-diagnostic verify_not_a_single_use_key_authenticator + : verify_not_a_single_use_key_authenticator.cpp : : native wasip2 wasip3 : alone ; diff --git a/test/messages/verify_not_a_single_use_key_authenticator/verify_not_a_single_use_key_authenticator.cpp b/test/messages/verify_not_a_single_use_key_authenticator/verify_not_a_single_use_key_authenticator.cpp new file mode 100644 index 0000000..e7fd56c --- /dev/null +++ b/test/messages/verify_not_a_single_use_key_authenticator/verify_not_a_single_use_key_authenticator.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) + +// single_use_key_authentication::verify given HMAC-SHA256, webcpp::hash's MAC, whose key is used +// for many messages and which is no single-use key authenticator, stops with what it takes and +// where a reusable key's MAC is, and with that error alone. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/single_use_key_authentication/authenticator.hpp:* {{webcpp::crypto: single_use_key_authentication::verify takes a single-use key authenticator (authenticators::poly1305); a reusable key's MAC is webcpp::hash::mac (HMAC).}} +// clang-format on + +#include +#include + +#include +#include + +int main() { + namespace hash = webcpp::hash; + std::array const key{}; + std::array const message{}; + std::array const tag{}; + webcpp::crypto::single_use_key_authentication::verify< + hash::macs::hmac>(key, message, tag); + return 0; +} diff --git a/test/messages/verify_poly1305_asynchronous_backend/Jamfile b/test/messages/verify_poly1305_asynchronous_backend/Jamfile new file mode 100644 index 0000000..525bb04 --- /dev/null +++ b/test/messages/verify_poly1305_asynchronous_backend/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic verify_poly1305_asynchronous_backend + : verify_poly1305_asynchronous_backend.cpp : : native wasip2 wasip3 : alone ; diff --git a/test/messages/verify_poly1305_asynchronous_backend/verify_poly1305_asynchronous_backend.cpp b/test/messages/verify_poly1305_asynchronous_backend/verify_poly1305_asynchronous_backend.cpp new file mode 100644 index 0000000..ab1f533 --- /dev/null +++ b/test/messages/verify_poly1305_asynchronous_backend/verify_poly1305_asynchronous_backend.cpp @@ -0,0 +1,54 @@ +// 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) + +// Poly1305's verify, the static member and the free form, on a backend that completes by itself +// (a stand-in whose detail::asynchronous_backend_v is true) stops with the refusal that sends it to +// a native backend (design D15): WebCrypto has no Poly1305. That error alone: the free form meets +// the refusal through the member it calls, and no engine is named (ruling P12). + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/detail/asynchronous.hpp:* {{webcpp::crypto: WebCrypto has no Poly1305: no form of the single-use key authenticator, synchronous or asynchronous, runs on the browser's backend; name a native backend for it.}} +// clang-format on +#include + +#include +#include + +namespace { + +/** A backend that completes by itself, as part B's browser backend will. */ +struct stand_in_browser {}; + +} // namespace + +template <> +inline constexpr bool webcpp::crypto::detail::asynchronous_backend_v = true; + +/** Poly1305 on the stand-in. */ +using stand_in_poly1305 = webcpp::crypto::authenticators::poly1305; + +namespace { + +/** Verifies through the static member and the free form. */ +bool verified() { + std::array const key{}; + std::array const message{'h', 'e', 'l', 'l', 'o'}; + std::array const tag{}; + return stand_in_poly1305::verify(key, message, tag).has_value() && + webcpp::crypto::single_use_key_authentication::verify(key, message, + tag) + .has_value(); +} + +} // namespace + +// The function is compiled, which is the test; it is never run. +int main() { + static_cast(&verified); + return 0; +} diff --git a/test/msvc/Jamfile b/test/msvc/Jamfile index cc9d18e..b13a185 100644 --- a/test/msvc/Jamfile +++ b/test/msvc/Jamfile @@ -51,7 +51,14 @@ build-project ed25519_default_not_linked ; build-project heavy_without_threads ; build-project async_seal_xchacha ; build-project async_open_xchacha ; +build-project apply_keystream_async_backend ; +build-project from_key_chacha20_asynchronous_backend ; +build-project async_apply_keystream_async_bk ; +build-project async_from_key_chacha20_async_bk ; build-project async_from_key_xchacha ; +build-project async_from_key_not_a_cipher ; +build-project async_from_key_aead_without_member ; +build-project async_from_key_stream_cipher_no_empty ; build-project async_from_secret_secp256k1 ; build-project async_sign_secp256k1 ; build-project chacha_default_not_linked ; @@ -63,6 +70,26 @@ build-project box_default_not_linked ; build-project x25519_default_not_linked ; build-project chacha_header_not_included ; build-project chacha_unknown_backend ; +build-project chacha20_not_a_family ; +build-project chacha20_unknown_backend ; +build-project chacha20_on_ctaes ; +build-project chacha20_default_not_linked ; +build-project chacha20_header_not_included ; +build-project apply_keystream_not_a_stream_cipher ; +build-project poly1305_on_bearssl ; +build-project poly1305_on_ctaes ; +build-project poly1305_unknown_backend ; +build-project poly1305_default_not_linked ; +build-project authenticate_not_an_authenticator ; +build-project from_key_poly1305 ; +build-project poly1305_header_not_included ; +build-project authenticate_asynchronous_backend ; +build-project verify_poly1305_asynchronous_backend ; +build-project async_authenticate_asynchronous_backend ; +build-project async_verify_asynchronous_backend ; +build-project async_authenticate_not_an_authenticator ; +build-project async_verify_not_an_authenticator ; +build-project verify_not_an_authenticator ; build-project ed25519_unknown_policy ; build-project musig_nonce_copied ; build-project ellswift_other_backend ; @@ -151,6 +178,9 @@ build-project constant_time_equal_moved ; build-project equal_header_removed ; build-project equal_removed ; build-project erase_secret_moved ; +build-project from_key_chacha20_poly1305_async_backend ; +build-project from_key_secretbox_asynchronous_backend ; +build-project from_keys_box_asynchronous_backend ; build-project heavy_without_threads_first ; build-project hybrid_header_removed ; build-project hybrid_names_removed ; diff --git a/test/msvc/apply_keystream_async_backend/Jamfile b/test/msvc/apply_keystream_async_backend/Jamfile new file mode 100644 index 0000000..fdfbc30 --- /dev/null +++ b/test/msvc/apply_keystream_async_backend/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail apply_keystream_async_backend : app.cpp + : /webcpp/crypto//crypto + : native ; diff --git a/test/msvc/apply_keystream_async_backend/app.cpp b/test/msvc/apply_keystream_async_backend/app.cpp new file mode 100644 index 0000000..584af39 --- /dev/null +++ b/test/msvc/apply_keystream_async_backend/app.cpp @@ -0,0 +1,43 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// ChaCha20's own apply_keystream on a backend that completes by itself (a stand-in whose +// detail::asynchronous_backend_v is true) stops where it is called (design D6): on MSVC the compile +// fails. The text is checked on clang, in test/messages/apply_keystream_asynchronous_backend. +#include + +#include +#include + +namespace { + +/** A backend that completes by itself, as part B's browser backend will. */ +struct stand_in_browser {}; + +} // namespace + +template <> +inline constexpr bool webcpp::crypto::detail::asynchronous_backend_v = true; + +/** ChaCha20 on the stand-in. */ +using stand_in_chacha20 = webcpp::crypto::ciphers::chacha20; + +namespace { + +/** Applies the keystream with an object of the stand-in's. */ +bool applied(stand_in_chacha20& cipher) { + std::array const nonce{}; + std::array data{'h', 'e', 'l', 'l', 'o'}; + return cipher.apply_keystream(nonce, data, 0).has_value(); +} + +} // namespace + +// The function is compiled, which is the test; it is never run. +int main() { + static_cast(&applied); + return 0; +} diff --git a/test/msvc/apply_keystream_not_a_stream_cipher/Jamfile b/test/msvc/apply_keystream_not_a_stream_cipher/Jamfile new file mode 100644 index 0000000..56bc6f5 --- /dev/null +++ b/test/msvc/apply_keystream_not_a_stream_cipher/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail apply_keystream_not_a_stream_cipher : app.cpp + : /webcpp/crypto//crypto /third_party//sodium + : native ; diff --git a/test/msvc/apply_keystream_not_a_stream_cipher/app.cpp b/test/msvc/apply_keystream_not_a_stream_cipher/app.cpp new file mode 100644 index 0000000..d71fb53 --- /dev/null +++ b/test/msvc/apply_keystream_not_a_stream_cipher/app.cpp @@ -0,0 +1,28 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// unauthenticated_encryption::apply_keystream given an AEAD, ChaCha20-Poly1305, which is no stream +// cipher, stops with what it takes and where an AEAD seals, and with that error alone. + +#include +#include +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const key{}; + std::array const nonce{}; + std::array data{}; + auto made = crypto::ciphers::chacha20_poly1305::from_key(key); + if (!made) { + return 1; + } + crypto::unauthenticated_encryption::apply_keystream(*made, nonce, data, 0U); + return 0; +} diff --git a/test/msvc/async_apply_keystream_async_bk/Jamfile b/test/msvc/async_apply_keystream_async_bk/Jamfile new file mode 100644 index 0000000..62ea526 --- /dev/null +++ b/test/msvc/async_apply_keystream_async_bk/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail async_apply_keystream_async_bk : app.cpp + : /webcpp/crypto//crypto /webcpp/asio//asio + : native ; diff --git a/test/msvc/async_apply_keystream_async_bk/app.cpp b/test/msvc/async_apply_keystream_async_bk/app.cpp new file mode 100644 index 0000000..d08af9c --- /dev/null +++ b/test/msvc/async_apply_keystream_async_bk/app.cpp @@ -0,0 +1,51 @@ +// 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 free unauthenticated_encryption::async_apply_keystream of ChaCha20 on a backend that +// completes by itself (a stand-in whose detail::asynchronous_backend_v is true) stops where it is +// called (design D6): on MSVC the compile fails. The text is checked on clang, in +// test/messages/async_apply_keystream_asynchronous_backend. +#include +#include + +#include + +#include + +#include +#include + +namespace { + +/** A backend that completes by itself, as part B's browser backend will. */ +struct stand_in_browser {}; + +} // namespace + +template <> +inline constexpr bool webcpp::crypto::detail::asynchronous_backend_v = true; + +/** ChaCha20 on the stand-in. */ +using stand_in_chacha20 = webcpp::crypto::ciphers::chacha20; + +namespace { + +/** Applies the keystream asynchronously through the free form. */ +void applied(stand_in_chacha20& cipher) { + std::array const nonce{}; + std::array data{'h', 'e', 'l', 'l', 'o'}; + webcpp::asio::io_context context; + webcpp::crypto::unauthenticated_encryption::async_apply_keystream( + context.get_executor(), cipher, nonce, data, 0, [](boost::system::error_code) {}); +} + +} // namespace + +// The function is compiled, which is the test; it is never run. +int main() { + static_cast(&applied); + return 0; +} diff --git a/test/msvc/async_authenticate_asynchronous_backend/Jamfile b/test/msvc/async_authenticate_asynchronous_backend/Jamfile new file mode 100644 index 0000000..0ee0725 --- /dev/null +++ b/test/msvc/async_authenticate_asynchronous_backend/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail async_authenticate_asynchronous_backend : app.cpp + : /webcpp/crypto//crypto /webcpp/asio//asio + : native ; diff --git a/test/msvc/async_authenticate_asynchronous_backend/app.cpp b/test/msvc/async_authenticate_asynchronous_backend/app.cpp new file mode 100644 index 0000000..ddad490 --- /dev/null +++ b/test/msvc/async_authenticate_asynchronous_backend/app.cpp @@ -0,0 +1,53 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Poly1305's async_authenticate, the static member and the free form, on a backend that completes +// by itself (a stand-in whose detail::asynchronous_backend_v is true) stops where it is called +// (design D15): on MSVC the compile fails. The text is checked on clang, in +// test/messages/async_authenticate_asynchronous_backend. +#include +#include + +#include + +#include + +#include +#include + +namespace { + +/** A backend that completes by itself, as part B's browser backend will. */ +struct stand_in_browser {}; + +} // namespace + +template <> +inline constexpr bool webcpp::crypto::detail::asynchronous_backend_v = true; + +/** Poly1305 on the stand-in. */ +using stand_in_poly1305 = webcpp::crypto::authenticators::poly1305; + +namespace { + +/** Authenticates asynchronously through the static member and the free form. */ +void authenticated() { + std::array const key{}; + std::array const message{'h', 'e', 'l', 'l', 'o'}; + webcpp::asio::io_context context; + auto const completion = [](boost::system::error_code, stand_in_poly1305::result_type) {}; + stand_in_poly1305::async_authenticate(context.get_executor(), key, message, completion); + webcpp::crypto::single_use_key_authentication::async_authenticate( + context.get_executor(), key, message, completion); +} + +} // namespace + +// The function is compiled, which is the test; it is never run. +int main() { + static_cast(&authenticated); + return 0; +} diff --git a/test/msvc/async_authenticate_not_an_authenticator/Jamfile b/test/msvc/async_authenticate_not_an_authenticator/Jamfile new file mode 100644 index 0000000..3fc644c --- /dev/null +++ b/test/msvc/async_authenticate_not_an_authenticator/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail async_authenticate_not_an_authenticator : app.cpp + : /webcpp/crypto//crypto /webcpp/asio//asio + : native ; diff --git a/test/msvc/async_authenticate_not_an_authenticator/app.cpp b/test/msvc/async_authenticate_not_an_authenticator/app.cpp new file mode 100644 index 0000000..b122177 --- /dev/null +++ b/test/msvc/async_authenticate_not_an_authenticator/app.cpp @@ -0,0 +1,30 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// single_use_key_authentication::async_authenticate given HMAC-SHA256, webcpp::hash's MAC, which is +// no single-use key authenticator, stops where it is called: on MSVC the compile fails. The text is +// checked on clang, in test/messages/async_authenticate_not_a_single_use_key_authenticator. + +#include +#include + +#include + +#include + +#include +#include + +int main() { + namespace hash = webcpp::hash; + std::array const key{}; + std::array const message{}; + webcpp::asio::io_context context; + webcpp::crypto::single_use_key_authentication::async_authenticate< + hash::macs::hmac>(context.get_executor(), key, message, + [](boost::system::error_code) {}); + return 0; +} diff --git a/test/msvc/async_from_key_aead_without_member/Jamfile b/test/msvc/async_from_key_aead_without_member/Jamfile new file mode 100644 index 0000000..a6128d8 --- /dev/null +++ b/test/msvc/async_from_key_aead_without_member/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail async_from_key_aead_without_member : app.cpp + : /webcpp/crypto//crypto /webcpp/asio//asio /third_party//sodium + : native ; diff --git a/test/msvc/async_from_key_aead_without_member/app.cpp b/test/msvc/async_from_key_aead_without_member/app.cpp new file mode 100644 index 0000000..36b801d --- /dev/null +++ b/test/msvc/async_from_key_aead_without_member/app.cpp @@ -0,0 +1,65 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// crypto::async_from_key given an AEAD of the concept without the member async_from_key stops +// where it is called: on MSVC the compile fails. The text is checked on clang, in +// test/messages/async_from_key_aead_without_member. +#include +#include + +#include + +#include +#include + +#include +#include +#include +#include + +namespace { + +// An AEAD of the concept without the member async_from_key. +struct stand_in_aead { + static constexpr std::size_t key_size = 16; + static constexpr std::size_t nonce_size = 12; + static constexpr std::size_t tag_size = 16; + using result_type = std::array; + + static boost::system::result from_key( + std::span key_bytes) noexcept { + if (key_bytes.size() != key_size) { + return webcpp::crypto::error::invalid_key_size; + } + return stand_in_aead{}; + } + + boost::system::result seal(std::span /*nonce_bytes*/, + std::span /*associated_data_bytes*/, + std::span /*data_bytes*/) noexcept { + return result_type{}; + } + + boost::system::result open(std::span /*nonce_bytes*/, + std::span /*associated_data_bytes*/, + std::span /*data_bytes*/, + std::span /*tag_bytes*/) noexcept { + return {}; + } +}; + +static_assert(webcpp::crypto::secret_key_encryption::aead::cipher); + +} // namespace + +int main() { + namespace crypto = webcpp::crypto; + std::array const key{}; + webcpp::asio::io_context context; + crypto::async_from_key(context.get_executor(), key, + [](boost::system::error_code, stand_in_aead) {}); + return 0; +} diff --git a/test/msvc/async_from_key_chacha20_async_bk/Jamfile b/test/msvc/async_from_key_chacha20_async_bk/Jamfile new file mode 100644 index 0000000..a375df6 --- /dev/null +++ b/test/msvc/async_from_key_chacha20_async_bk/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail async_from_key_chacha20_async_bk : app.cpp + : /webcpp/crypto//crypto /webcpp/asio//asio + : native ; diff --git a/test/msvc/async_from_key_chacha20_async_bk/app.cpp b/test/msvc/async_from_key_chacha20_async_bk/app.cpp new file mode 100644 index 0000000..713cc81 --- /dev/null +++ b/test/msvc/async_from_key_chacha20_async_bk/app.cpp @@ -0,0 +1,50 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// crypto::async_from_key of ChaCha20 on a backend that completes by itself (a stand-in whose +// detail::asynchronous_backend_v is true) stops where it is called (design D6): on MSVC the compile +// fails. The text is checked on clang, in +// test/messages/async_from_key_chacha20_asynchronous_backend. +#include +#include + +#include + +#include + +#include +#include + +namespace { + +/** A backend that completes by itself, as part B's browser backend will. */ +struct stand_in_browser {}; + +} // namespace + +template <> +inline constexpr bool webcpp::crypto::detail::asynchronous_backend_v = true; + +/** ChaCha20 on the stand-in. */ +using stand_in_chacha20 = webcpp::crypto::ciphers::chacha20; + +namespace { + +/** Makes an object of the stand-in's asynchronously. */ +void made() { + std::array const key{}; + webcpp::asio::io_context context; + webcpp::crypto::async_from_key( + context.get_executor(), key, [](boost::system::error_code, stand_in_chacha20) {}); +} + +} // namespace + +// The function is compiled, which is the test; it is never run. +int main() { + static_cast(&made); + return 0; +} diff --git a/test/msvc/async_from_key_not_a_cipher/Jamfile b/test/msvc/async_from_key_not_a_cipher/Jamfile new file mode 100644 index 0000000..157b208 --- /dev/null +++ b/test/msvc/async_from_key_not_a_cipher/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail async_from_key_not_a_cipher : app.cpp + : /webcpp/crypto//crypto /webcpp/asio//asio /third_party//sodium + : native ; diff --git a/test/msvc/async_from_key_not_a_cipher/app.cpp b/test/msvc/async_from_key_not_a_cipher/app.cpp new file mode 100644 index 0000000..a154e7c --- /dev/null +++ b/test/msvc/async_from_key_not_a_cipher/app.cpp @@ -0,0 +1,28 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// crypto::async_from_key given a type that is no AEAD, no stream cipher and no secret box, a +// crypto_box, stops where it is called: on MSVC the compile fails. The text is checked on clang, +// in test/messages/async_from_key_not_a_cipher. +#include +#include +#include + +#include + +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + using box = crypto::public_key_encryption::box; + std::array const key{}; + webcpp::asio::io_context context; + crypto::async_from_key(context.get_executor(), key, [](boost::system::error_code, box) {}); + return 0; +} diff --git a/test/msvc/async_from_key_stream_cipher_no_empty/Jamfile b/test/msvc/async_from_key_stream_cipher_no_empty/Jamfile new file mode 100644 index 0000000..7b5decf --- /dev/null +++ b/test/msvc/async_from_key_stream_cipher_no_empty/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail async_from_key_stream_cipher_no_empty : app.cpp + : /webcpp/crypto//crypto /webcpp/asio//asio /third_party//sodium + : native ; diff --git a/test/msvc/async_from_key_stream_cipher_no_empty/app.cpp b/test/msvc/async_from_key_stream_cipher_no_empty/app.cpp new file mode 100644 index 0000000..2bff2d9 --- /dev/null +++ b/test/msvc/async_from_key_stream_cipher_no_empty/app.cpp @@ -0,0 +1,73 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// crypto::async_from_key given a stream cipher without the member async_from_key and without a +// default constructor stops where it is called: on MSVC the compile fails. The text is checked on +// clang, in test/messages/async_from_key_stream_cipher_without_empty. +#include +#include + +#include + +#include +#include + +#include +#include +#include +#include + +namespace { + +// A stream cipher of the concept without the member async_from_key and without a default +// constructor: its key is its only constructor's argument. +class stand_in_stream_cipher { +public: + static constexpr std::size_t key_size = 16; + static constexpr std::size_t nonce_size = 8; + static constexpr std::size_t block_size = 16; + using counter_type = std::uint8_t; + + explicit stand_in_stream_cipher(std::array const& key) noexcept + : key_(key) {} + + static boost::system::result from_key( + std::span key_bytes) noexcept { + if (key_bytes.size() != key_size) { + return webcpp::crypto::error::invalid_key_size; + } + std::array key{}; + for (std::size_t i = 0; i < key_size; ++i) { + key[i] = key_bytes[i]; + } + return stand_in_stream_cipher{key}; + } + + boost::system::result apply_keystream(std::span /*nonce_bytes*/, + std::span data_bytes, + counter_type /*initial_counter*/) noexcept { + for (std::size_t i = 0; i < data_bytes.size(); ++i) { + data_bytes[i] ^= key_[i % key_size]; + } + return {}; + } + +private: + std::array key_; +}; + +static_assert(webcpp::crypto::unauthenticated_encryption::stream_cipher); + +} // namespace + +int main() { + namespace crypto = webcpp::crypto; + std::array const key{}; + webcpp::asio::io_context context; + crypto::async_from_key( + context.get_executor(), key, [](boost::system::error_code, stand_in_stream_cipher) {}); + return 0; +} diff --git a/test/msvc/async_verify_asynchronous_backend/Jamfile b/test/msvc/async_verify_asynchronous_backend/Jamfile new file mode 100644 index 0000000..91130f1 --- /dev/null +++ b/test/msvc/async_verify_asynchronous_backend/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail async_verify_asynchronous_backend : app.cpp + : /webcpp/crypto//crypto /webcpp/asio//asio + : native ; diff --git a/test/msvc/async_verify_asynchronous_backend/app.cpp b/test/msvc/async_verify_asynchronous_backend/app.cpp new file mode 100644 index 0000000..c1a32c2 --- /dev/null +++ b/test/msvc/async_verify_asynchronous_backend/app.cpp @@ -0,0 +1,54 @@ +// 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) + +// Poly1305's async_verify, the static member and the free form, on a backend that completes by +// itself (a stand-in whose detail::asynchronous_backend_v is true) stops where it is called +// (design D15): on MSVC the compile fails. The text is checked on clang, in +// test/messages/async_verify_asynchronous_backend. +#include +#include + +#include + +#include + +#include +#include + +namespace { + +/** A backend that completes by itself, as part B's browser backend will. */ +struct stand_in_browser {}; + +} // namespace + +template <> +inline constexpr bool webcpp::crypto::detail::asynchronous_backend_v = true; + +/** Poly1305 on the stand-in. */ +using stand_in_poly1305 = webcpp::crypto::authenticators::poly1305; + +namespace { + +/** Verifies asynchronously through the static member and the free form. */ +void verified() { + std::array const key{}; + std::array const message{'h', 'e', 'l', 'l', 'o'}; + std::array const tag{}; + webcpp::asio::io_context context; + auto const completion = [](boost::system::error_code) {}; + stand_in_poly1305::async_verify(context.get_executor(), key, message, tag, completion); + webcpp::crypto::single_use_key_authentication::async_verify( + context.get_executor(), key, message, tag, completion); +} + +} // namespace + +// The function is compiled, which is the test; it is never run. +int main() { + static_cast(&verified); + return 0; +} diff --git a/test/msvc/async_verify_not_an_authenticator/Jamfile b/test/msvc/async_verify_not_an_authenticator/Jamfile new file mode 100644 index 0000000..294aa67 --- /dev/null +++ b/test/msvc/async_verify_not_an_authenticator/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail async_verify_not_an_authenticator : app.cpp + : /webcpp/crypto//crypto /webcpp/asio//asio + : native ; diff --git a/test/msvc/async_verify_not_an_authenticator/app.cpp b/test/msvc/async_verify_not_an_authenticator/app.cpp new file mode 100644 index 0000000..e3c3012 --- /dev/null +++ b/test/msvc/async_verify_not_an_authenticator/app.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) + +// single_use_key_authentication::async_verify given HMAC-SHA256, webcpp::hash's MAC, which is no +// single-use key authenticator, stops where it is called: on MSVC the compile fails. The text is +// checked on clang, in test/messages/async_verify_not_a_single_use_key_authenticator. + +#include +#include + +#include + +#include + +#include +#include + +int main() { + namespace hash = webcpp::hash; + std::array const key{}; + std::array const message{}; + std::array const tag{}; + webcpp::asio::io_context context; + webcpp::crypto::single_use_key_authentication::async_verify< + hash::macs::hmac>(context.get_executor(), key, message, tag, + [](boost::system::error_code) {}); + return 0; +} diff --git a/test/msvc/authenticate_asynchronous_backend/Jamfile b/test/msvc/authenticate_asynchronous_backend/Jamfile new file mode 100644 index 0000000..20eb5c3 --- /dev/null +++ b/test/msvc/authenticate_asynchronous_backend/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail authenticate_asynchronous_backend : app.cpp + : /webcpp/crypto//crypto + : native ; diff --git a/test/msvc/authenticate_asynchronous_backend/app.cpp b/test/msvc/authenticate_asynchronous_backend/app.cpp new file mode 100644 index 0000000..f9aa581 --- /dev/null +++ b/test/msvc/authenticate_asynchronous_backend/app.cpp @@ -0,0 +1,47 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Poly1305's authenticate, the static member and the free form, on a backend that completes by +// itself (a stand-in whose detail::asynchronous_backend_v is true) stops where it is called +// (design D15): on MSVC the compile fails. The text is checked on clang, in +// test/messages/authenticate_asynchronous_backend. +#include + +#include +#include + +namespace { + +/** A backend that completes by itself, as part B's browser backend will. */ +struct stand_in_browser {}; + +} // namespace + +template <> +inline constexpr bool webcpp::crypto::detail::asynchronous_backend_v = true; + +/** Poly1305 on the stand-in. */ +using stand_in_poly1305 = webcpp::crypto::authenticators::poly1305; + +namespace { + +/** Authenticates through the static member and the free form. */ +bool authenticated() { + std::array const key{}; + std::array const message{'h', 'e', 'l', 'l', 'o'}; + return stand_in_poly1305::authenticate(key, message).has_value() && + webcpp::crypto::single_use_key_authentication::authenticate(key, + message) + .has_value(); +} + +} // namespace + +// The function is compiled, which is the test; it is never run. +int main() { + static_cast(&authenticated); + return 0; +} diff --git a/test/msvc/authenticate_not_an_authenticator/Jamfile b/test/msvc/authenticate_not_an_authenticator/Jamfile new file mode 100644 index 0000000..c4c1ef9 --- /dev/null +++ b/test/msvc/authenticate_not_an_authenticator/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail authenticate_not_an_authenticator : app.cpp + : /webcpp/crypto//crypto + : native ; diff --git a/test/msvc/authenticate_not_an_authenticator/app.cpp b/test/msvc/authenticate_not_an_authenticator/app.cpp new file mode 100644 index 0000000..65c6c16 --- /dev/null +++ b/test/msvc/authenticate_not_an_authenticator/app.cpp @@ -0,0 +1,24 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// single_use_key_authentication::authenticate given HMAC-SHA256, webcpp::hash's MAC, whose key is +// used for many messages and which is no single-use key authenticator, stops with what it takes and +// where a reusable key's MAC is, and with that error alone. + +#include +#include + +#include +#include + +int main() { + namespace hash = webcpp::hash; + std::array const key{}; + std::array const message{}; + webcpp::crypto::single_use_key_authentication::authenticate< + hash::macs::hmac>(key, message); + return 0; +} diff --git a/test/msvc/chacha20_default_not_linked/Jamfile b/test/msvc/chacha20_default_not_linked/Jamfile new file mode 100644 index 0000000..d47c1fb --- /dev/null +++ b/test/msvc/chacha20_default_not_linked/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail chacha20_default_not_linked : app.cpp + : /webcpp/crypto//crypto + : native ; diff --git a/test/msvc/chacha20_default_not_linked/app.cpp b/test/msvc/chacha20_default_not_linked/app.cpp new file mode 100644 index 0000000..257f2a2 --- /dev/null +++ b/test/msvc/chacha20_default_not_linked/app.cpp @@ -0,0 +1,18 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A program that calls ChaCha20 on its default backend, libsodium on every target, without +// linking it, stops where it calls it, with the line that links libsodium. + +#include + +#include +#include + +int main() { + std::array const key{}; + return webcpp::crypto::ciphers::chacha20<>::from_key(key) ? 0 : 1; +} diff --git a/test/msvc/chacha20_header_not_included/Jamfile b/test/msvc/chacha20_header_not_included/Jamfile new file mode 100644 index 0000000..6fcfbb3 --- /dev/null +++ b/test/msvc/chacha20_header_not_included/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail chacha20_header_not_included : app.cpp + : /webcpp/crypto//crypto + : native ; diff --git a/test/msvc/chacha20_header_not_included/app.cpp b/test/msvc/chacha20_header_not_included/app.cpp new file mode 100644 index 0000000..15c251a --- /dev/null +++ b/test/msvc/chacha20_header_not_included/app.cpp @@ -0,0 +1,19 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A program that names BearSSL in ChaCha20's type without including BearSSL's header stops where +// it makes the cipher, with the header to include and the line that links BearSSL. + +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const key{}; + return crypto::ciphers::chacha20::from_key(key) ? 0 : 1; +} diff --git a/test/msvc/chacha20_not_a_family/Jamfile b/test/msvc/chacha20_not_a_family/Jamfile new file mode 100644 index 0000000..d342393 --- /dev/null +++ b/test/msvc/chacha20_not_a_family/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail chacha20_not_a_family : app.cpp + : /webcpp/crypto//crypto + : native ; diff --git a/test/msvc/chacha20_not_a_family/app.cpp b/test/msvc/chacha20_not_a_family/app.cpp new file mode 100644 index 0000000..3fda937 --- /dev/null +++ b/test/msvc/chacha20_not_a_family/app.cpp @@ -0,0 +1,21 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// ciphers::basic_chacha20 given a family that is no stream cipher's, ChaCha20-Poly1305's, stops +// with the family it takes, and with that error alone. + +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + using cipher = crypto::ciphers::basic_chacha20; + std::array const key{}; + return cipher::from_key(key) ? 0 : 1; +} diff --git a/test/msvc/chacha20_on_ctaes/Jamfile b/test/msvc/chacha20_on_ctaes/Jamfile new file mode 100644 index 0000000..e5a64fd --- /dev/null +++ b/test/msvc/chacha20_on_ctaes/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail chacha20_on_ctaes : app.cpp + : /webcpp/crypto//crypto /third_party//ctaes + : native ; diff --git a/test/msvc/chacha20_on_ctaes/app.cpp b/test/msvc/chacha20_on_ctaes/app.cpp new file mode 100644 index 0000000..10bb0b8 --- /dev/null +++ b/test/msvc/chacha20_on_ctaes/app.cpp @@ -0,0 +1,21 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// ChaCha20 on ctaes, which exports the AES block cipher alone, is refused where it is called, +// with the backends that have it and their targets (the generated refusal, +// detail/capabilities.hpp). + +#include +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const key{}; + return crypto::ciphers::chacha20::from_key(key) ? 0 : 1; +} diff --git a/test/msvc/chacha20_unknown_backend/Jamfile b/test/msvc/chacha20_unknown_backend/Jamfile new file mode 100644 index 0000000..8dab7a5 --- /dev/null +++ b/test/msvc/chacha20_unknown_backend/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail chacha20_unknown_backend : app.cpp + : /webcpp/crypto//crypto + : native ; diff --git a/test/msvc/chacha20_unknown_backend/app.cpp b/test/msvc/chacha20_unknown_backend/app.cpp new file mode 100644 index 0000000..c5c2749 --- /dev/null +++ b/test/msvc/chacha20_unknown_backend/app.cpp @@ -0,0 +1,25 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A program that names a type of its own as ChaCha20's backend stops where it makes the cipher, +// with the backends that have the family. + +#include + +#include +#include + +namespace { + +/** A type of the program's own, which is no backend. */ +struct my_backend {}; + +} // namespace + +int main() { + std::array const key{}; + return webcpp::crypto::ciphers::chacha20::from_key(key) ? 0 : 1; +} diff --git a/test/msvc/from_key_chacha20_asynchronous_backend/Jamfile b/test/msvc/from_key_chacha20_asynchronous_backend/Jamfile new file mode 100644 index 0000000..8ba4a9d --- /dev/null +++ b/test/msvc/from_key_chacha20_asynchronous_backend/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail from_key_chacha20_asynchronous_backend : app.cpp + : /webcpp/crypto//crypto + : native ; diff --git a/test/msvc/from_key_chacha20_asynchronous_backend/app.cpp b/test/msvc/from_key_chacha20_asynchronous_backend/app.cpp new file mode 100644 index 0000000..bf8341d --- /dev/null +++ b/test/msvc/from_key_chacha20_asynchronous_backend/app.cpp @@ -0,0 +1,43 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// ChaCha20's own from_key, its result kept, on a backend that completes by itself (a stand-in whose +// detail::asynchronous_backend_v is true) stops where it is called (design D6): on MSVC the compile +// fails. The text is checked on clang, in test/messages/from_key_chacha20_asynchronous_backend. +#include + +#include +#include + +namespace { + +/** A backend that completes by itself, as part B's browser backend will. */ +struct stand_in_browser {}; + +} // namespace + +template <> +inline constexpr bool webcpp::crypto::detail::asynchronous_backend_v = true; + +/** ChaCha20 on the stand-in. */ +using stand_in_chacha20 = webcpp::crypto::ciphers::chacha20; + +namespace { + +/** Makes an object of the stand-in's and keeps the result. */ +bool made() { + std::array const key{}; + auto const made_cipher = stand_in_chacha20::from_key(key); + return made_cipher.has_value(); +} + +} // namespace + +// The function is compiled, which is the test; it is never run. +int main() { + static_cast(&made); + return 0; +} diff --git a/test/msvc/from_key_chacha20_poly1305_async_backend/Jamfile b/test/msvc/from_key_chacha20_poly1305_async_backend/Jamfile new file mode 100644 index 0000000..7e54ecb --- /dev/null +++ b/test/msvc/from_key_chacha20_poly1305_async_backend/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail from_key_chacha20_poly1305_async_backend : app.cpp + : /webcpp/crypto//crypto + : native ; diff --git a/test/msvc/from_key_chacha20_poly1305_async_backend/app.cpp b/test/msvc/from_key_chacha20_poly1305_async_backend/app.cpp new file mode 100644 index 0000000..5a7b449 --- /dev/null +++ b/test/msvc/from_key_chacha20_poly1305_async_backend/app.cpp @@ -0,0 +1,44 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// ChaCha20-Poly1305's own from_key, its result kept, on a backend that completes by itself (a +// stand-in whose detail::asynchronous_backend_v is true) stops where it is called (design D6): on +// MSVC the compile fails. The text is checked on clang, in +// test/messages/from_key_chacha20_poly1305_asynchronous_backend. +#include + +#include +#include + +namespace { + +/** A backend that completes by itself, as part B's browser backend will. */ +struct stand_in_browser {}; + +} // namespace + +template <> +inline constexpr bool webcpp::crypto::detail::asynchronous_backend_v = true; + +/** ChaCha20-Poly1305 on the stand-in. */ +using stand_in_aead = webcpp::crypto::ciphers::chacha20_poly1305; + +namespace { + +/** Makes an object of the stand-in's and keeps the result. */ +bool made() { + std::array const key{}; + auto const made_aead = stand_in_aead::from_key(key); + return made_aead.has_value(); +} + +} // namespace + +// The function is compiled, which is the test; it is never run. +int main() { + static_cast(&made); + return 0; +} diff --git a/test/msvc/from_key_poly1305/Jamfile b/test/msvc/from_key_poly1305/Jamfile new file mode 100644 index 0000000..aee5430 --- /dev/null +++ b/test/msvc/from_key_poly1305/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail from_key_poly1305 : app.cpp + : /webcpp/crypto//crypto /third_party//sodium + : native ; diff --git a/test/msvc/from_key_poly1305/app.cpp b/test/msvc/from_key_poly1305/app.cpp new file mode 100644 index 0000000..5da38b8 --- /dev/null +++ b/test/msvc/from_key_poly1305/app.cpp @@ -0,0 +1,22 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// crypto::from_key given Poly1305, which has no object and no from_key (design R21), stops with +// factories.hpp's existing refusal, its requirement on a static from_key, and with that error +// alone: the key enters every call of authenticate and verify. + +#include +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const key{}; + static_cast(crypto::from_key>(key)); + return 0; +} diff --git a/test/msvc/from_key_secretbox_asynchronous_backend/Jamfile b/test/msvc/from_key_secretbox_asynchronous_backend/Jamfile new file mode 100644 index 0000000..f2c5728 --- /dev/null +++ b/test/msvc/from_key_secretbox_asynchronous_backend/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail from_key_secretbox_asynchronous_backend : app.cpp + : /webcpp/crypto//crypto + : native ; diff --git a/test/msvc/from_key_secretbox_asynchronous_backend/app.cpp b/test/msvc/from_key_secretbox_asynchronous_backend/app.cpp new file mode 100644 index 0000000..f88c8f3 --- /dev/null +++ b/test/msvc/from_key_secretbox_asynchronous_backend/app.cpp @@ -0,0 +1,44 @@ +// 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 secret box's own from_key, its result kept, on a backend that completes by itself (a stand-in +// whose detail::asynchronous_backend_v is true) stops where it is called (design D6): on MSVC the +// compile fails. The text is checked on clang, in +// test/messages/from_key_secretbox_asynchronous_backend. +#include + +#include +#include + +namespace { + +/** A backend that completes by itself, as part B's browser backend will. */ +struct stand_in_browser {}; + +} // namespace + +template <> +inline constexpr bool webcpp::crypto::detail::asynchronous_backend_v = true; + +/** The secret box on the stand-in. */ +using stand_in_secretbox = webcpp::crypto::secret_key_encryption::secretbox; + +namespace { + +/** Makes a box of the stand-in's and keeps the result. */ +bool made() { + std::array const key{}; + auto const made_box = stand_in_secretbox::from_key(key); + return made_box.has_value(); +} + +} // namespace + +// The function is compiled, which is the test; it is never run. +int main() { + static_cast(&made); + return 0; +} diff --git a/test/msvc/from_keys_box_asynchronous_backend/Jamfile b/test/msvc/from_keys_box_asynchronous_backend/Jamfile new file mode 100644 index 0000000..c9aa68f --- /dev/null +++ b/test/msvc/from_keys_box_asynchronous_backend/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail from_keys_box_asynchronous_backend : app.cpp + : /webcpp/crypto//crypto + : native ; diff --git a/test/msvc/from_keys_box_asynchronous_backend/app.cpp b/test/msvc/from_keys_box_asynchronous_backend/app.cpp new file mode 100644 index 0000000..2f0ddca --- /dev/null +++ b/test/msvc/from_keys_box_asynchronous_backend/app.cpp @@ -0,0 +1,43 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The crypto_box's own from_keys, its result kept, on a backend that completes by itself (a +// stand-in whose detail::asynchronous_backend_v is true) stops where it is called (design D6): on +// MSVC the compile fails. The text is checked on clang, in +// test/messages/from_keys_box_asynchronous_backend. +#include + +namespace { + +/** A backend that completes by itself, as part B's browser backend will. */ +struct stand_in_browser {}; + +} // namespace + +template <> +inline constexpr bool webcpp::crypto::detail::asynchronous_backend_v = true; + +/** The crypto_box on the stand-in. */ +using stand_in_box = + webcpp::crypto::public_key_encryption::basic_box; + +namespace { + +/** Makes a box of the stand-in's from key pairs given and keeps the result. */ +bool made(stand_in_box::keypair_type const& own_keypair, + stand_in_box::public_key_type const& peer_public_key) { + auto const made_box = stand_in_box::from_keys(own_keypair, peer_public_key); + return made_box.has_value(); +} + +} // namespace + +// The function is compiled, which is the test; it is never run. +int main() { + static_cast(&made); + return 0; +} diff --git a/test/msvc/poly1305_default_not_linked/Jamfile b/test/msvc/poly1305_default_not_linked/Jamfile new file mode 100644 index 0000000..73dd854 --- /dev/null +++ b/test/msvc/poly1305_default_not_linked/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail poly1305_default_not_linked : app.cpp + : /webcpp/crypto//crypto + : native ; diff --git a/test/msvc/poly1305_default_not_linked/app.cpp b/test/msvc/poly1305_default_not_linked/app.cpp new file mode 100644 index 0000000..8f016a0 --- /dev/null +++ b/test/msvc/poly1305_default_not_linked/app.cpp @@ -0,0 +1,19 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A program that calls Poly1305 on its default backend, libsodium on every target, without linking +// it, stops where it calls it, with the line that links libsodium. + +#include + +#include +#include + +int main() { + std::array const key{}; + std::array const message{}; + return webcpp::crypto::authenticators::poly1305<>::authenticate(key, message) ? 0 : 1; +} diff --git a/test/msvc/poly1305_header_not_included/Jamfile b/test/msvc/poly1305_header_not_included/Jamfile new file mode 100644 index 0000000..30d270e --- /dev/null +++ b/test/msvc/poly1305_header_not_included/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail poly1305_header_not_included : app.cpp + : /webcpp/crypto//crypto /webcpp/crypto//openssl + : native ; diff --git a/test/msvc/poly1305_header_not_included/app.cpp b/test/msvc/poly1305_header_not_included/app.cpp new file mode 100644 index 0000000..7883141 --- /dev/null +++ b/test/msvc/poly1305_header_not_included/app.cpp @@ -0,0 +1,23 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A program that names OpenSSL in Poly1305's type, links OpenSSL and does not include OpenSSL's +// header stops where it calls the authenticator, with the header to include and the line that +// links OpenSSL. + +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const key{}; + std::array const message{}; + return crypto::authenticators::poly1305::authenticate(key, message) + ? 0 + : 1; +} diff --git a/test/msvc/poly1305_on_bearssl/Jamfile b/test/msvc/poly1305_on_bearssl/Jamfile new file mode 100644 index 0000000..606f4e6 --- /dev/null +++ b/test/msvc/poly1305_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) + +import webcpp ; + +webcpp.compile-fail poly1305_on_bearssl : app.cpp + : /webcpp/crypto//crypto /third_party//bearssl + : native ; diff --git a/test/msvc/poly1305_on_bearssl/app.cpp b/test/msvc/poly1305_on_bearssl/app.cpp new file mode 100644 index 0000000..11f4668 --- /dev/null +++ b/test/msvc/poly1305_on_bearssl/app.cpp @@ -0,0 +1,24 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Poly1305 on BearSSL, whose Poly1305 is inside its ChaCha20-Poly1305 alone, which derives the key +// itself, is refused where it is called, with the backends that have it and their targets (the +// generated refusal, detail/capabilities.hpp). + +#include +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const key{}; + std::array const message{}; + return crypto::authenticators::poly1305::authenticate(key, message) + ? 0 + : 1; +} diff --git a/test/msvc/poly1305_on_ctaes/Jamfile b/test/msvc/poly1305_on_ctaes/Jamfile new file mode 100644 index 0000000..2780aaa --- /dev/null +++ b/test/msvc/poly1305_on_ctaes/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail poly1305_on_ctaes : app.cpp + : /webcpp/crypto//crypto /third_party//ctaes + : native ; diff --git a/test/msvc/poly1305_on_ctaes/app.cpp b/test/msvc/poly1305_on_ctaes/app.cpp new file mode 100644 index 0000000..7a1bb60 --- /dev/null +++ b/test/msvc/poly1305_on_ctaes/app.cpp @@ -0,0 +1,21 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Poly1305 on ctaes, which exports the AES block cipher alone, is refused where it is called, with +// the backends that have it and their targets (the generated refusal, detail/capabilities.hpp). + +#include +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const key{}; + std::array const tag{}; + return crypto::authenticators::poly1305::verify(key, {}, tag) ? 0 : 1; +} diff --git a/test/msvc/poly1305_unknown_backend/Jamfile b/test/msvc/poly1305_unknown_backend/Jamfile new file mode 100644 index 0000000..f20c6bd --- /dev/null +++ b/test/msvc/poly1305_unknown_backend/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail poly1305_unknown_backend : app.cpp + : /webcpp/crypto//crypto + : native ; diff --git a/test/msvc/poly1305_unknown_backend/app.cpp b/test/msvc/poly1305_unknown_backend/app.cpp new file mode 100644 index 0000000..9d944ee --- /dev/null +++ b/test/msvc/poly1305_unknown_backend/app.cpp @@ -0,0 +1,26 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A program that names a type of its own as Poly1305's backend stops where it authenticates, with +// the backends that have the family. + +#include + +#include +#include + +namespace { + +/** A type of the program's own, which is no backend. */ +struct my_backend {}; + +} // namespace + +int main() { + std::array const key{}; + std::array const message{}; + return webcpp::crypto::authenticators::poly1305::authenticate(key, message) ? 0 : 1; +} diff --git a/test/msvc/verify_not_an_authenticator/Jamfile b/test/msvc/verify_not_an_authenticator/Jamfile new file mode 100644 index 0000000..83e49d5 --- /dev/null +++ b/test/msvc/verify_not_an_authenticator/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail verify_not_an_authenticator : app.cpp + : /webcpp/crypto//crypto + : native ; diff --git a/test/msvc/verify_not_an_authenticator/app.cpp b/test/msvc/verify_not_an_authenticator/app.cpp new file mode 100644 index 0000000..349b34f --- /dev/null +++ b/test/msvc/verify_not_an_authenticator/app.cpp @@ -0,0 +1,25 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// single_use_key_authentication::verify given HMAC-SHA256, webcpp::hash's MAC, whose key is used +// for many messages and which is no single-use key authenticator, stops with what it takes and +// where a reusable key's MAC is, and with that error alone. + +#include +#include + +#include +#include + +int main() { + namespace hash = webcpp::hash; + std::array const key{}; + std::array const message{}; + std::array const tag{}; + webcpp::crypto::single_use_key_authentication::verify< + hash::macs::hmac>(key, message, tag); + return 0; +} diff --git a/test/msvc/verify_poly1305_asynchronous_backend/Jamfile b/test/msvc/verify_poly1305_asynchronous_backend/Jamfile new file mode 100644 index 0000000..9621c7c --- /dev/null +++ b/test/msvc/verify_poly1305_asynchronous_backend/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail verify_poly1305_asynchronous_backend : app.cpp + : /webcpp/crypto//crypto + : native ; diff --git a/test/msvc/verify_poly1305_asynchronous_backend/app.cpp b/test/msvc/verify_poly1305_asynchronous_backend/app.cpp new file mode 100644 index 0000000..e88a976 --- /dev/null +++ b/test/msvc/verify_poly1305_asynchronous_backend/app.cpp @@ -0,0 +1,48 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Poly1305's verify, the static member and the free form, on a backend that completes by itself +// (a stand-in whose detail::asynchronous_backend_v is true) stops where it is called (design D15): +// on MSVC the compile fails. The text is checked on clang, in +// test/messages/verify_poly1305_asynchronous_backend. +#include + +#include +#include + +namespace { + +/** A backend that completes by itself, as part B's browser backend will. */ +struct stand_in_browser {}; + +} // namespace + +template <> +inline constexpr bool webcpp::crypto::detail::asynchronous_backend_v = true; + +/** Poly1305 on the stand-in. */ +using stand_in_poly1305 = webcpp::crypto::authenticators::poly1305; + +namespace { + +/** Verifies through the static member and the free form. */ +bool verified() { + std::array const key{}; + std::array const message{'h', 'e', 'l', 'l', 'o'}; + std::array const tag{}; + return stand_in_poly1305::verify(key, message, tag).has_value() && + webcpp::crypto::single_use_key_authentication::verify(key, message, + tag) + .has_value(); +} + +} // namespace + +// The function is compiled, which is the test; it is never run. +int main() { + static_cast(&verified); + return 0; +} diff --git a/test/poly1305_openssl_test.cpp b/test/poly1305_openssl_test.cpp new file mode 100644 index 0000000..d600742 --- /dev/null +++ b/test/poly1305_openssl_test.cpp @@ -0,0 +1,87 @@ +// 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) + +// Poly1305, RFC 8439's one-time authenticator, on OpenSSL, on native, wasip2 and wasip3: RFC 8439's +// known answers against the test's portable reference, every guard, forgeries, the empty message, +// the key as a secret and overlapping spans (support/authenticator_checks.hpp). +// poly1305_openssl_memory_resource compiles this source again natively with +// WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE and never installs the adapter: every form, static and +// free, authenticate and verify, gives memory_functions_not_installed, a matching tag's verify +// included, never authentication_failed (Review Focus 6), and no tag. + +#include +#include +#include +#include + +#include "support/authenticator_checks.hpp" + +#include + +#include + +#ifdef WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE +#include +#include +#include + +/** The program's resource, which the adapter would send OpenSSL's allocations to: never installed. + */ +std::pmr::memory_resource& webcpp::crypto::openssl_memory_resource() noexcept { + return *std::pmr::new_delete_resource(); +} +#endif + +namespace crypto = webcpp::crypto; + +using poly1305 = crypto::authenticators::poly1305; + +static_assert(std::is_same_v); +static_assert(std::is_same_v); +static_assert(crypto::supports_v); +static_assert(noexcept(poly1305::authenticate({}, {}))); +static_assert(noexcept(poly1305::verify({}, {}, {}))); + +namespace { + +#ifdef WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE +/** + * Without the adapter, every form gives memory_functions_not_installed, a matching tag included, + * which a broken backend never turns into authentication_failed. + */ +void check_memory_functions_not_installed() { + namespace single_use_key_authentication = crypto::single_use_key_authentication; + // RFC 8439 section 2.5.2's key and message, and its tag, which matches them. + auto const key = webcpp::test::from_hex(webcpp::test::poly1305_cases[0].key); + auto const message = webcpp::test::from_hex(webcpp::test::poly1305_cases[0].message); + auto const tag = webcpp::test::from_hex(webcpp::test::poly1305_cases[0].tag); + auto const expected = crypto::error::memory_functions_not_installed; + BOOST_TEST(poly1305::authenticate(key, message).error() == expected); + BOOST_TEST(single_use_key_authentication::authenticate(key, message).error() == + expected); + BOOST_TEST(poly1305::verify(key, message, tag).error() == expected); + BOOST_TEST(single_use_key_authentication::verify(key, message, tag).error() == + expected); + std::array wrong_tag{}; + BOOST_TEST(poly1305::verify(key, message, wrong_tag).error() == expected); + // The guards still come first, reading no byte. + BOOST_TEST(poly1305::authenticate(std::span(key).first(31), message).error() == + crypto::error::invalid_key_size); + BOOST_TEST(poly1305::verify(key, message, std::span(tag).first(15)).error() == + crypto::error::invalid_tag_size); +} +#endif + +} // namespace + +int main() { +#ifdef WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE + check_memory_functions_not_installed(); +#else + webcpp::test::check_single_use_key_authenticator(); +#endif + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/poly1305_sodium_test.cpp b/test/poly1305_sodium_test.cpp new file mode 100644 index 0000000..21a184e --- /dev/null +++ b/test/poly1305_sodium_test.cpp @@ -0,0 +1,41 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Poly1305, RFC 8439's one-time authenticator, on libsodium, through its default type, +// authenticators::poly1305<>, whose backend is libsodium on every target: RFC 8439's known answers +// against the test's portable reference, every guard, forgeries, the empty message, the key as a +// secret and overlapping spans (support/authenticator_checks.hpp). + +#include +#include +#include + +#include "support/authenticator_checks.hpp" + +#include + +#include + +namespace crypto = webcpp::crypto; + +using poly1305 = crypto::authenticators::poly1305<>; + +// The default is libsodium on every target, ChaCha20's and ChaCha20-Poly1305's, and the type names +// its family as the capability table does. +static_assert(std::is_same_v, + crypto::backends::sodium>); +static_assert(std::is_same_v>); +static_assert(std::is_same_v); +static_assert(std::is_same_v); +static_assert(std::is_same_v); +static_assert(crypto::supports_v); +static_assert(noexcept(poly1305::authenticate({}, {}))); +static_assert(noexcept(crypto::single_use_key_authentication::authenticate({}, {}))); + +int main() { + webcpp::test::check_single_use_key_authenticator(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/sizes/Jamfile b/test/sizes/Jamfile index 396a25f..98b68b6 100644 --- a/test/sizes/Jamfile +++ b/test/sizes/Jamfile @@ -73,14 +73,21 @@ webcpp.link chacha20_poly1305_original_sodium : chacha20_poly1305_original_sodiu : /third_party//sodium ; webcpp.link xchacha20_poly1305_sodium : xchacha20_poly1305_sodium.cpp : /third_party//sodium ; +webcpp.link chacha20_sodium : chacha20_sodium.cpp : /third_party//sodium ; +webcpp.link chacha20_bearssl : chacha20_bearssl.cpp : /third_party//bearssl ; +webcpp.link chacha20_openssl : chacha20_openssl.cpp : /webcpp/crypto//openssl + : native wasip2 wasip3 ; +webcpp.link poly1305_sodium : poly1305_sodium.cpp : /third_party//sodium ; +webcpp.link poly1305_openssl : poly1305_openssl.cpp : /webcpp/crypto//openssl + : native wasip2 wasip3 ; webcpp.program-sizes crypto : baseline : gcm_bearssl aes_block_ctaes secp256k1_secp256k1 secp256k1_secp256k1_ecdh_x secp256k1_secp256k1_recover ed25519_sodium x25519_sodium chacha20_poly1305_sodium chacha20_poly1305_bearssl chacha20_poly1305_original_sodium xchacha20_poly1305_sodium secp256k1_ellswift_secp256k1 secp256k1_musig_secp256k1 secp256k1_silent_payments_secp256k1 p256_bearssl p256_bearssl_verify_ecdsa - p256_bearssl_ecdh_x ; + p256_bearssl_ecdh_x chacha20_sodium chacha20_bearssl poly1305_sodium ; webcpp.program-sizes crypto_openssl : baseline : gcm_openssl aes_block_openssl - chacha20_poly1305_openssl : native wasip2 wasip3 ; + chacha20_poly1305_openssl chacha20_openssl poly1305_openssl : native wasip2 wasip3 ; webcpp.lane sizes : crypto.sizes.md crypto_openssl.sizes.md : native wasip2 wasip3 emscripten ; diff --git a/test/sizes/chacha20_bearssl.cpp b/test/sizes/chacha20_bearssl.cpp new file mode 100644 index 0000000..dfea4ad --- /dev/null +++ b/test/sizes/chacha20_bearssl.cpp @@ -0,0 +1,17 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The size of ChaCha20, the raw stream cipher, on BearSSL: bench/operations.hpp's chacha20, once +// (test/sizes/Jamfile). + +#include + +#include "sized.hpp" + +int main(int argument_count, char** /*arguments*/) { + return webcpp::crypto::test::sized< + webcpp::crypto::bench::chacha20>(argument_count); +} diff --git a/test/sizes/chacha20_openssl.cpp b/test/sizes/chacha20_openssl.cpp new file mode 100644 index 0000000..507d6eb --- /dev/null +++ b/test/sizes/chacha20_openssl.cpp @@ -0,0 +1,17 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The size of ChaCha20, the raw stream cipher, on OpenSSL: bench/operations.hpp's chacha20, once +// (test/sizes/Jamfile). + +#include + +#include "sized.hpp" + +int main(int argument_count, char** /*arguments*/) { + return webcpp::crypto::test::sized< + webcpp::crypto::bench::chacha20>(argument_count); +} diff --git a/test/sizes/chacha20_sodium.cpp b/test/sizes/chacha20_sodium.cpp new file mode 100644 index 0000000..3714507 --- /dev/null +++ b/test/sizes/chacha20_sodium.cpp @@ -0,0 +1,17 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The size of ChaCha20, the raw stream cipher, on libsodium: bench/operations.hpp's chacha20, once +// (test/sizes/Jamfile). + +#include + +#include "sized.hpp" + +int main(int argument_count, char** /*arguments*/) { + return webcpp::crypto::test::sized< + webcpp::crypto::bench::chacha20>(argument_count); +} diff --git a/test/sizes/poly1305_openssl.cpp b/test/sizes/poly1305_openssl.cpp new file mode 100644 index 0000000..30cc81f --- /dev/null +++ b/test/sizes/poly1305_openssl.cpp @@ -0,0 +1,17 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The size of Poly1305, the one-time authenticator, on OpenSSL: bench/operations.hpp's poly1305, +// once (test/sizes/Jamfile). + +#include + +#include "sized.hpp" + +int main(int argument_count, char** /*arguments*/) { + return webcpp::crypto::test::sized< + webcpp::crypto::bench::poly1305>(argument_count); +} diff --git a/test/sizes/poly1305_sodium.cpp b/test/sizes/poly1305_sodium.cpp new file mode 100644 index 0000000..f8a765b --- /dev/null +++ b/test/sizes/poly1305_sodium.cpp @@ -0,0 +1,17 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The size of Poly1305, the one-time authenticator, on libsodium: bench/operations.hpp's poly1305, +// once (test/sizes/Jamfile). + +#include + +#include "sized.hpp" + +int main(int argument_count, char** /*arguments*/) { + return webcpp::crypto::test::sized< + webcpp::crypto::bench::poly1305>(argument_count); +} diff --git a/test/stream_cipher_concepts_test.cpp b/test/stream_cipher_concepts_test.cpp new file mode 100644 index 0000000..4977d3b --- /dev/null +++ b/test/stream_cipher_concepts_test.cpp @@ -0,0 +1,105 @@ +// 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 stream cipher's concept (design D3): ciphers::chacha20 is an +// unauthenticated_encryption::stream_cipher and neither an AEAD nor an authenticated box; no AEAD, +// secret box or block cipher is a stream_cipher. crypto::from_key and the static from_key make +// objects whose member apply_keystream and the free unauthenticated_encryption::apply_keystream +// give the same bytes, and a generic function over the concept (the guide's snippet) runs it. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include + +namespace crypto = webcpp::crypto; +namespace unauthenticated_encryption = webcpp::crypto::unauthenticated_encryption; +namespace secret_key_encryption = webcpp::crypto::secret_key_encryption; + +namespace { + +using check = crypto::detail::concept_check_backend; +using chacha20 = crypto::ciphers::chacha20<>; + +static_assert(unauthenticated_encryption::stream_cipher); +static_assert(unauthenticated_encryption::stream_cipher>); +static_assert(!secret_key_encryption::aead::cipher); +static_assert(!secret_key_encryption::authenticated_box); +static_assert( + !unauthenticated_encryption::stream_cipher>); +static_assert(!unauthenticated_encryption::stream_cipher< + crypto::ciphers::gcm>>); +static_assert(!unauthenticated_encryption::stream_cipher>); +static_assert(!unauthenticated_encryption::stream_cipher>); + +/** + * Encrypts and decrypts through the concept alone: a generic program over every stream cipher. + * + * @tparam Cipher A stream cipher. + * @return Whether the message came back, and changed in between. + */ +// tag::generic[] +template +bool round_trip_stream() { + std::array key{}; + key.fill(7); + std::array const nonce{1}; + auto made = Cipher::from_key(key); + if (!made) { + return false; + } + std::array data{'h', 'e', 'l', 'l', 'o'}; + auto const original = data; + typename Cipher::counter_type const initial_counter = 1; + if (!unauthenticated_encryption::apply_keystream(*made, nonce, data, initial_counter) || + data == original) { + return false; + } + return unauthenticated_encryption::apply_keystream(*made, nonce, data, initial_counter) && + data == original; +} + +// end::generic[] + +/** crypto::from_key and the member make objects whose member and free form agree. */ +void forms_agree() { + std::array key{}; + key.fill(5); + std::array const nonce{9}; + auto from_factory = crypto::from_key(key); + auto from_member = chacha20::from_key(key); + if (!BOOST_TEST(from_factory.has_value()) || !BOOST_TEST(from_member.has_value())) { + return; + } + std::array member_data{}; + std::array free_data{}; + BOOST_TEST(from_member->apply_keystream(nonce, member_data, 3).has_value()); + BOOST_TEST(unauthenticated_encryption::apply_keystream(*from_factory, nonce, free_data, 3) + .has_value()); + BOOST_TEST(member_data == free_data); + std::array const zeroes{}; + BOOST_TEST(member_data != zeroes); +} + +} // namespace + +int main() { + BOOST_TEST(round_trip_stream()); + forms_agree(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/stream_cipher_shape_test.cpp b/test/stream_cipher_shape_test.cpp new file mode 100644 index 0000000..529b8fd --- /dev/null +++ b/test/stream_cipher_shape_test.cpp @@ -0,0 +1,384 @@ +// 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 stream cipher's contract reads the algorithm's own shape, never ChaCha20's (owner decision +// 7, design D3, D9): a test-only stand-in of another shape, a 16-byte key, an 8-byte nonce, +// 16-byte blocks and an 8-bit counter, is an unauthenticated_encryption::stream_cipher, its free +// form runs it, and detail::counter_overflows gives its counter's end, as it gives ChaCha20's and +// a 64-bit counter's; its asynchronous free forms, crypto::async_from_key and +// unauthenticated_encryption::async_apply_keystream, run it too: through the stand-in's members +// made with detail::complete_by_post where it has them, and over its synchronous from_key and +// apply_keystream, posted, where it has none, a private noexcept default constructor that +// befriends detail::async_access giving the error completion's empty object. No backend is linked. + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace crypto = webcpp::crypto; +namespace unauthenticated_encryption = webcpp::crypto::unauthenticated_encryption; + +namespace webcpp::test { +namespace { + +/** + * A stream cipher of another shape than ChaCha20's, for the contract's tests alone: its keystream + * is no cipher, each byte a function of the key, the nonce, the block's counter and the byte's + * place. + * + * @tparam AsyncMembers Whether it has the members `async_from_key` and `async_apply_keystream`. + */ +template +class stand_in_stream_cipher { +public: + /** The key's size. */ + static constexpr std::size_t key_size = 16; + /** The nonce's size. */ + static constexpr std::size_t nonce_size = 8; + /** The block's size. */ + static constexpr std::size_t block_size = 16; + /** The block counter: 8 bits. */ + using counter_type = std::uint8_t; + + /** + * Keys a stand-in. + * + * @param key_bytes The key, `key_size` bytes. + * @return The keyed object, or `invalid_key_size`. + */ + [[nodiscard]] static boost::system::result from_key( + std::span key_bytes) noexcept { + if (key_bytes.size() != key_size) { + return crypto::error::invalid_key_size; + } + stand_in_stream_cipher made; + for (std::size_t i = 0; i < key_size; ++i) { + made.key_[i] = key_bytes[i]; + } + return made; + } + + /** + * XORs the stand-in's keystream into `data_bytes`. + * + * @param nonce_bytes The nonce, `nonce_size` bytes. + * @param data_bytes The data. + * @param initial_counter The first block's counter. + * @return Nothing, or `invalid_nonce_size`, or `counter_overflow`. + */ + [[nodiscard]] boost::system::result apply_keystream( + std::span nonce_bytes, std::span data_bytes, + counter_type initial_counter) noexcept { + if (nonce_bytes.size() != nonce_size) { + return crypto::error::invalid_nonce_size; + } + if (crypto::detail::counter_overflows(data_bytes.size(), initial_counter)) { + return crypto::error::counter_overflow; + } + for (std::size_t i = 0; i < data_bytes.size(); ++i) { + auto const block = static_cast(initial_counter + (i / block_size)); + auto const place = i % block_size; + data_bytes[i] ^= static_cast( + static_cast(key_[place]) ^ + static_cast(nonce_bytes[place % nonce_size]) ^ (block * 31U) ^ place); + } + return {}; + } + + /** + * Keys a stand-in asynchronously: `from_key` run when the operation is initiated, its result + * posted to `completion_executor`. + * + * @tparam Executor The executor's type. + * @tparam CompletionToken The completion token's type. + * @param completion_executor The executor the completion is posted to. + * @param key_bytes The key, `key_size` bytes. + * @param completion_token The completion token, of signature + * `void(boost::system::error_code, stand_in_stream_cipher)`. + * @return What the completion token's `async_result` gives. + */ + template + requires AsyncMembers + static auto async_from_key(Executor const& completion_executor, + std::span key_bytes, + CompletionToken&& completion_token) { + return crypto::detail::complete_by_post( + completion_executor, completion_token, + [key_bytes]() noexcept { return from_key(key_bytes); }); + } + + /** + * XORs the keystream asynchronously: `apply_keystream` run when the operation is initiated, + * its result posted to `completion_executor`. + * + * @tparam Executor The executor's type. + * @tparam CompletionToken The completion token's type. + * @param completion_executor The executor the completion is posted to. + * @param nonce_bytes The nonce, `nonce_size` bytes. + * @param data_bytes The data. + * @param initial_counter The first block's counter. + * @param completion_token The completion token, of signature `void(boost::system::error_code)`. + * @return What the completion token's `async_result` gives. + */ + template + requires AsyncMembers + auto async_apply_keystream(Executor const& completion_executor, + std::span nonce_bytes, + std::span data_bytes, counter_type initial_counter, + CompletionToken&& completion_token) { + return crypto::detail::complete_by_post( + completion_executor, completion_token, + [this, nonce_bytes, data_bytes, initial_counter]() noexcept { + return apply_keystream(nonce_bytes, data_bytes, initial_counter); + }); + } + +private: + std::array key_{}; +}; + +/** No friend of the stand-in below: makes_empty_v finds its constructor out of reach. */ +struct nobody {}; + +/** + * The stand-in without the asynchronous members, with a private `noexcept` default constructor + * that `Friend` reaches: through `crypto::detail::async_access`, the free `async_from_key` posts + * its synchronous `from_key` and gives the empty object on an error. + * + * @tparam Friend The class befriended. + */ +template +class private_empty_stream_cipher { + friend Friend; + using inner_type = stand_in_stream_cipher; + +public: + /** The key's size. */ + static constexpr std::size_t key_size = inner_type::key_size; + /** The nonce's size. */ + static constexpr std::size_t nonce_size = inner_type::nonce_size; + /** The block's size. */ + static constexpr std::size_t block_size = inner_type::block_size; + /** The block counter: the inner stand-in's. */ + using counter_type = inner_type::counter_type; + + /** + * Keys a stand-in. + * + * @param key_bytes The key, `key_size` bytes. + * @return The keyed object, or `invalid_key_size`. + */ + [[nodiscard]] static boost::system::result from_key( + std::span key_bytes) noexcept { + auto inner = inner_type::from_key(key_bytes); + if (!inner) { + return inner.error(); + } + private_empty_stream_cipher made; + made.inner_ = inner.unsafe_value(); + return made; + } + + /** + * XORs the inner stand-in's keystream into `data_bytes`. + * + * @param nonce_bytes The nonce, `nonce_size` bytes. + * @param data_bytes The data. + * @param initial_counter The first block's counter. + * @return Nothing, or `invalid_nonce_size`, or `counter_overflow`. + */ + [[nodiscard]] boost::system::result apply_keystream( + std::span nonce_bytes, std::span data_bytes, + counter_type initial_counter) noexcept { + return inner_.apply_keystream(nonce_bytes, data_bytes, initial_counter); + } + +private: + private_empty_stream_cipher() noexcept = default; + + inner_type inner_; +}; + +} // namespace +} // namespace webcpp::test + +namespace { + +/** The stand-in with the asynchronous members. */ +using stand_in = webcpp::test::stand_in_stream_cipher; +/** The stand-in without them, which the free forms run over its synchronous members. */ +using bare_stand_in = webcpp::test::stand_in_stream_cipher; + +/** The stand-in whose private default constructor `crypto::detail::async_access` reaches. */ +using befriended_stand_in = webcpp::test::private_empty_stream_cipher; +/** The same stand-in, its private default constructor reached by no class of crypto's. */ +using unfriended_stand_in = webcpp::test::private_empty_stream_cipher; + +/** Whether `Cipher` has the members `async_from_key` and `async_apply_keystream`. */ +template +concept has_async_members = requires(Cipher& cipher, webcpp::asio::io_context& context, + std::span bytes, + std::span data) { + Cipher::async_from_key(context.get_executor(), bytes, [](boost::system::error_code, Cipher) {}); + cipher.async_apply_keystream(context.get_executor(), bytes, data, + typename Cipher::counter_type{}, [](boost::system::error_code) {}); +}; + +static_assert(unauthenticated_encryption::stream_cipher); +static_assert(unauthenticated_encryption::stream_cipher); +static_assert(unauthenticated_encryption::stream_cipher); +// The fallback's empty object: a private noexcept default constructor counts through friendship +// alone, so the free async_from_key posts the befriended stand-in and refuses the other. +static_assert(crypto::detail::async_access::makes_empty_v); +static_assert(!crypto::detail::async_access::makes_empty_v); +static_assert(!std::is_default_constructible_v); +static_assert(has_async_members); +static_assert(!has_async_members); +static_assert(requires(stand_in& cipher, std::array const& nonce, + std::array& data) { + { + unauthenticated_encryption::apply_keystream(cipher, nonce, data, std::uint8_t{}) + } -> std::same_as>; +}); + +static_assert(requires(stand_in& cipher, webcpp::asio::io_context& context, + std::array const& nonce, + std::array& data) { + unauthenticated_encryption::async_apply_keystream(context.get_executor(), cipher, nonce, data, + std::uint8_t{}, + [](boost::system::error_code) {}); +}); + +// The counter's end of the stand-in's shape, 16-byte blocks and an 8-bit counter. +static_assert(!crypto::detail::counter_overflows<16>(16, std::uint8_t{255})); +static_assert(crypto::detail::counter_overflows<16>(17, std::uint8_t{255})); +static_assert(!crypto::detail::counter_overflows<16>(4096, std::uint8_t{0})); +static_assert(crypto::detail::counter_overflows<16>(4097, std::uint8_t{0})); +// ChaCha20's: 64-byte blocks, a 32-bit counter. +constexpr std::uint32_t last32 = std::numeric_limits::max(); +static_assert(!crypto::detail::counter_overflows<64>(64, last32)); +static_assert(crypto::detail::counter_overflows<64>(65, last32)); +static_assert(!crypto::detail::counter_overflows<64>(128, last32 - 1)); +static_assert(!crypto::detail::counter_overflows<64>(0, last32)); +// A 64-bit counter, whose end no sum may wrap. +constexpr std::uint64_t last64 = std::numeric_limits::max(); +static_assert(crypto::detail::counter_overflows<64>(65, last64)); +static_assert(!crypto::detail::counter_overflows<64>(last64, std::uint64_t{0})); + +/** The free form and the member agree, and the guards leave the data untouched. */ +void stand_in_runs() { + std::array key{}; + key.fill(4); + std::array const nonce{1, 2, 3}; + auto made = crypto::from_key(key); + if (!BOOST_TEST(made.has_value())) { + return; + } + std::array member_data{}; + std::array free_data{}; + BOOST_TEST(made->apply_keystream(nonce, member_data, 7).has_value()); + BOOST_TEST(unauthenticated_encryption::apply_keystream(*made, nonce, free_data, 7).has_value()); + BOOST_TEST(member_data == free_data); + std::array data{}; + data.fill(0x6c); + auto const untouched = data; + BOOST_TEST( + unauthenticated_encryption::apply_keystream(*made, nonce, std::span(data).first(16), 255) + .has_value()); + data = untouched; + BOOST_TEST(unauthenticated_encryption::apply_keystream(*made, nonce, data, 255).error() == + crypto::error::counter_overflow); + BOOST_TEST(data == untouched); + std::array const long_nonce{}; + BOOST_TEST(unauthenticated_encryption::apply_keystream(*made, long_nonce, data, 0).error() == + crypto::error::invalid_nonce_size); + BOOST_TEST(data == untouched); +} + +/** + * The asynchronous free forms with a callback: async_from_key gives an object whose keystream is + * the synchronous one's, and a short key completes with invalid_key_size; 16 bytes at counter + * 255 give the synchronous bytes, 17 complete with counter_overflow, the data untouched. Each + * completes through a post, never inside the call. + * + * @tparam StandIn The stand-in, with or without the asynchronous members. + */ +template +void stand_in_runs_asynchronously() { + std::array key{}; + key.fill(4); + std::array const nonce{1, 2, 3}; + webcpp::asio::io_context context; + std::optional made; + boost::system::error_code made_code = crypto::error::backend_failure; + boost::system::error_code short_code; + crypto::async_from_key( + context.get_executor(), key, + [&made, &made_code](boost::system::error_code code, StandIn value) { + made_code = code; + made.emplace(std::move(value)); + }); + crypto::async_from_key( + context.get_executor(), std::span(key).first(15), + [&short_code](boost::system::error_code code, StandIn) { short_code = code; }); + BOOST_TEST(!made.has_value()); + context.run(); // lint-run: the test's event loop + BOOST_TEST(!made_code); + BOOST_TEST(short_code == crypto::error::invalid_key_size); + if (!BOOST_TEST(made.has_value())) { + return; + } + std::array expected{}; + BOOST_TEST(made->apply_keystream(nonce, expected, 255).has_value()); + std::array data{}; + boost::system::error_code code = crypto::error::backend_failure; + unauthenticated_encryption::async_apply_keystream( + context.get_executor(), *made, nonce, data, std::uint8_t{255}, + [&code](boost::system::error_code done) { code = done; }); + BOOST_TEST(code == crypto::error::backend_failure); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST(!code); + BOOST_TEST(data == expected); + std::array long_data{}; + long_data.fill(0x6c); + auto const untouched = long_data; + unauthenticated_encryption::async_apply_keystream( + context.get_executor(), *made, nonce, long_data, std::uint8_t{255}, + [&code](boost::system::error_code done) { code = done; }); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST(code == crypto::error::counter_overflow); + BOOST_TEST(long_data == untouched); +} + +} // namespace + +int main() { + stand_in_runs(); + stand_in_runs_asynchronously(); + stand_in_runs_asynchronously(); + stand_in_runs_asynchronously(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/support/agreement.hpp b/test/support/agreement.hpp index 2bcc84a..7a208b5 100644 --- a/test/support/agreement.hpp +++ b/test/support/agreement.hpp @@ -91,9 +91,9 @@ inline std::vector gcm_message_sizes(std::mt19937_64& generator) { constexpr std::size_t largest = 4096; std::vector sizes; for (std::size_t size = 0; size <= largest; size += 16) { - for (std::size_t const near : {size == 0 ? 0 : size - 1, size, size + 1}) { - if (near <= largest && (sizes.empty() || near != sizes.back())) { - sizes.push_back(near); + for (std::size_t const neighbour : {size == 0 ? 0 : size - 1, size, size + 1}) { + if (neighbour <= largest && (sizes.empty() || neighbour != sizes.back())) { + sizes.push_back(neighbour); } } } @@ -205,8 +205,8 @@ void agree_chacha(std::uint64_t seed) { constexpr std::size_t largest = 4096; std::mt19937_64 generator(seed); for (std::size_t size = 0; size <= largest; ++size) { - bool const near = size % 64 <= 1 || size % 64 == 63; - if (!near && generator() % 16 != 0) { + bool const near_block_edge = size % 64 <= 1 || size % 64 == 63; + if (!near_block_edge && generator() % 16 != 0) { continue; } if (!agree_chacha_once(generator, size, seed)) { diff --git a/test/support/authenticator_checks.hpp b/test/support/authenticator_checks.hpp new file mode 100644 index 0000000..2834e10 --- /dev/null +++ b/test/support/authenticator_checks.hpp @@ -0,0 +1,420 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The checks of a single-use key authenticator on one backend (design D16): RFC 8439's known +// answers (section 2.5.2 and appendix A.3's test vectors 1 to 11), each through the static +// members and the free forms, verify accepting each tag, and each against a portable Poly1305 +// written here from RFC 8439 section 2.5's pseudocode; every guard in its order; forgeries (each +// tag byte with its low and its high bit flipped, a message bit flipped, the message one byte +// shorter); the empty message with a null data(), whose tag is s; the key as a +// secure::secret<32>; and key, message and tag spans that overlap. + +#ifndef WEBCPP_TEST_CRYPTO_SUPPORT_AUTHENTICATOR_CHECKS_HPP +#define WEBCPP_TEST_CRYPTO_SUPPORT_AUTHENTICATOR_CHECKS_HPP + +#include "hex.hpp" + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::test { + +/** One known answer of Poly1305, every field in hex. */ +struct authenticator_case { + /** Where the case is from. */ + std::string_view name; + /** The 32-byte one-time key, r and s. */ + std::string_view key; + /** The message. */ + std::string_view message; + /** The 16-byte tag. */ + std::string_view tag; +}; + +/** The text of RFC 8439 appendix A.3's test vectors 2 and 3, 375 bytes. */ +inline constexpr std::string_view ietf_contribution = + "416e79207375626d697373696f6e20746f20746865204945544620696e74656e6465642062792074686520436f" + "6e7472696275746f7220666f72207075626c69636174696f6e20617320616c6c206f722070617274206f662061" + "6e204945544620496e7465726e65742d4472616674206f722052464320616e6420616e792073746174656d656e" + "74206d6164652077697468696e2074686520636f6e74657874206f6620616e2049455446206163746976697479" + "20697320636f6e7369646572656420616e20224945544620436f6e747269627574696f6e222e20537563682073" + "746174656d656e747320696e636c756465206f72616c2073746174656d656e747320696e204945544620736573" + "73696f6e732c2061732077656c6c206173207772697474656e20616e6420656c656374726f6e696320636f6d6d" + "756e69636174696f6e73206d61646520617420616e792074696d65206f7220706c6163652c2077686963682061" + "72652061646472657373656420746f"; + +/** RFC 8439's known answers of Poly1305: section 2.5.2 and appendix A.3's vectors 1 to 11. */ +inline constexpr std::array poly1305_cases{ + authenticator_case{ + .name = "RFC 8439 section 2.5.2", + .key = "85d6be7857556d337f4452fe42d506a80103808afb0db2fd4abff6af4149f51b", + // "Cryptographic Forum Research Group" + .message = "43727970746f6772617068696320466f72756d2052657365617263682047726f7570", + .tag = "a8061dc1305136c6c22b8baf0c0127a9", + }, + authenticator_case{ + .name = "RFC 8439 appendix A.3, test vector 1", + .key = "0000000000000000000000000000000000000000000000000000000000000000", + .message = "0000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000", + .tag = "00000000000000000000000000000000", + }, + authenticator_case{ + .name = "RFC 8439 appendix A.3, test vector 2", + .key = "0000000000000000000000000000000036e5f6b5c5e06070f0efca96227a863e", + .message = ietf_contribution, + .tag = "36e5f6b5c5e06070f0efca96227a863e", + }, + authenticator_case{ + .name = "RFC 8439 appendix A.3, test vector 3", + .key = "36e5f6b5c5e06070f0efca96227a863e00000000000000000000000000000000", + .message = ietf_contribution, + .tag = "f3477e7cd95417af89a6b8794c310cf0", + }, + authenticator_case{ + .name = "RFC 8439 appendix A.3, test vector 4", + .key = "1c9240a5eb55d38af333888604f6b5f0473917c1402b80099dca5cbc207075c0", + .message = "2754776173206272696c6c69672c20616e642074686520736c6974687920746f7665730a446964" + "206779726520616e642067696d626c6520696e2074686520776162653a0a416c6c206d696d73" + "7920776572652074686520626f726f676f7665732c0a416e6420746865206d6f6d6520726174" + "6873206f757467726162652e", + .tag = "4541669a7eaaee61e708dc7cbcc5eb62", + }, + authenticator_case{ + .name = "RFC 8439 appendix A.3, test vector 5", + .key = "0200000000000000000000000000000000000000000000000000000000000000", + .message = "ffffffffffffffffffffffffffffffff", + .tag = "03000000000000000000000000000000", + }, + authenticator_case{ + .name = "RFC 8439 appendix A.3, test vector 6", + .key = "02000000000000000000000000000000ffffffffffffffffffffffffffffffff", + .message = "02000000000000000000000000000000", + .tag = "03000000000000000000000000000000", + }, + authenticator_case{ + .name = "RFC 8439 appendix A.3, test vector 7", + .key = "0100000000000000000000000000000000000000000000000000000000000000", + .message = "fffffffffffffffffffffffffffffffff0ffffffffffffffffffffffffffffff" + "11000000000000000000000000000000", + .tag = "05000000000000000000000000000000", + }, + authenticator_case{ + .name = "RFC 8439 appendix A.3, test vector 8", + .key = "0100000000000000000000000000000000000000000000000000000000000000", + .message = "fffffffffffffffffffffffffffffffffbfefefefefefefefefefefefefefefe" + "01010101010101010101010101010101", + .tag = "00000000000000000000000000000000", + }, + authenticator_case{ + .name = "RFC 8439 appendix A.3, test vector 9", + .key = "0200000000000000000000000000000000000000000000000000000000000000", + .message = "fdffffffffffffffffffffffffffffff", + .tag = "faffffffffffffffffffffffffffffff", + }, + authenticator_case{ + .name = "RFC 8439 appendix A.3, test vector 10", + .key = "0100000000000000040000000000000000000000000000000000000000000000", + .message = "e33594d7505e43b900000000000000003394d7505e4379cd0100000000000000" + "0000000000000000000000000000000001000000000000000000000000000000", + .tag = "14000000000000005500000000000000", + }, + authenticator_case{ + .name = "RFC 8439 appendix A.3, test vector 11", + .key = "0100000000000000040000000000000000000000000000000000000000000000", + .message = "e33594d7505e43b900000000000000003394d7505e4379cd0100000000000000" + "00000000000000000000000000000000", + .tag = "13000000000000000000000000000000", + }, +}; + +/** + * Poly1305, RFC 8439 section 2.5's pseudocode, portable and slow: the test's own reference, its + * 130-bit accumulator in five 26-bit limbs, as poly1305-donna's 32-bit form keeps it. Not constant + * time: the final reduction branches. + * + * @param key The 32-byte one-time key, r and s. + * @param message The message. + * @return The 16-byte tag. + */ +inline std::array reference_poly1305(std::span key, + std::span message) { + auto const word = [](std::span bytes, std::size_t at) { + return std::uint32_t{bytes[at]} | (std::uint32_t{bytes[at + 1]} << 8U) | + (std::uint32_t{bytes[at + 2]} << 16U) | (std::uint32_t{bytes[at + 3]} << 24U); + }; + constexpr std::uint32_t mask = 0x3ffffffU; + // r, clamped (section 2.5.1), in 26-bit limbs. + std::array const r{ + word(key, 0) & 0x3ffffffU, (word(key, 3) >> 2U) & 0x3ffff03U, + (word(key, 6) >> 4U) & 0x3ffc0ffU, (word(key, 9) >> 6U) & 0x3f03fffU, + (word(key, 12) >> 8U) & 0x00fffffU, + }; + std::array h{}; + for (std::size_t at = 0; at < message.size(); at += 16) { + // The block, with its byte 0x01 appended, as a number of up to 129 bits. + std::array block{}; + std::size_t const size = std::min(16, message.size() - at); + std::ranges::copy(message.subspan(at, size), block.begin()); + block[size] = 1; + h[0] += word(block, 0) & mask; + h[1] += (word(block, 3) >> 2U) & mask; + h[2] += (word(block, 6) >> 4U) & mask; + h[3] += (word(block, 9) >> 6U) & mask; + h[4] += (word(block, 12) >> 8U) | (std::uint64_t{block[16]} << 24U); + // h times r, modulo 2^130 - 5: a limb past the fifth wraps around times 5. + std::array product{}; + for (std::size_t i = 0; i < 5; ++i) { + for (std::size_t j = 0; j < 5; ++j) { + std::uint64_t const term = h[i] * r[j]; + product[(i + j) % 5] += i + j < 5 ? term : term * 5; + } + } + std::uint64_t carry = 0; + for (std::size_t i = 0; i < 5; ++i) { + product[i] += carry; + h[i] = product[i] & mask; + carry = product[i] >> 26U; + } + h[0] += carry * 5; + h[1] += h[0] >> 26U; + h[0] &= mask; + } + // The full carry, then h minus p when h is p or more. + for (int round = 0; round < 2; ++round) { + std::uint64_t carry = 0; + for (std::size_t i = 0; i < 5; ++i) { + h[i] += carry; + carry = h[i] >> 26U; + h[i] &= mask; + } + h[0] += carry * 5; + } + std::array g{}; + std::uint64_t carry = 5; + for (std::size_t i = 0; i < 5; ++i) { + g[i] = h[i] + carry; + carry = g[i] >> 26U; + g[i] &= mask; + } + if (carry != 0) { // h + 5 reached 2^130: h is p or more + h = g; + } + // h modulo 2^128, plus s, modulo 2^128, little-endian. + std::array const words{ + (h[0] | (h[1] << 26U)) & 0xffffffffU, + ((h[1] >> 6U) | (h[2] << 20U)) & 0xffffffffU, + ((h[2] >> 12U) | (h[3] << 14U)) & 0xffffffffU, + ((h[3] >> 18U) | (h[4] << 8U)) & 0xffffffffU, + }; + std::array tag{}; + std::uint64_t sum = 0; + for (std::size_t i = 0; i < 4; ++i) { + sum = (sum >> 32U) + words[i] + word(key, 16 + (4 * i)); + for (std::size_t j = 0; j < 4; ++j) { + tag[(4 * i) + j] = static_cast(sum >> (8U * j)); + } + } + return tag; +} + +/** + * The known answers: each case through the static members and the free forms, `verify` accepting + * each tag, and the reference agreeing with each. + */ +template +void check_authenticator_cases() { + namespace single_use_key_authentication = webcpp::crypto::single_use_key_authentication; + for (auto const& c : poly1305_cases) { + auto const key = from_hex(c.key); + auto const message = from_hex(c.message); + auto const tag = from_hex(c.tag); + auto const member = Authenticator::authenticate(key, message); + auto const free = single_use_key_authentication::authenticate(key, message); + if (!BOOST_TEST(member.has_value()) || !BOOST_TEST(free.has_value())) { + continue; + } + BOOST_TEST_EQ(to_hex(*member), c.tag); + BOOST_TEST_EQ(to_hex(*free), c.tag); + BOOST_TEST(Authenticator::verify(key, message, tag).has_value()); + BOOST_TEST( + single_use_key_authentication::verify(key, message, tag).has_value()); + BOOST_TEST_EQ(to_hex(reference_poly1305(key, message)), c.tag); + } +} + +/** + * The guards in their order, neither reading a byte: keys of 0, 31 and 33 bytes + * `invalid_key_size`; tags of 0, 15 and 17 bytes `invalid_tag_size`; both wrong + * `invalid_key_size`; each through the static members and the free forms. + */ +template +void check_authenticator_guards() { + namespace crypto = webcpp::crypto; + namespace single_use_key_authentication = crypto::single_use_key_authentication; + std::array const long_key{}; + std::array const long_tag{}; + std::array const message{1, 2, 3, 4, 5}; + auto const key = std::span(long_key).first(32); + auto const tag = std::span(long_tag).first(16); + for (std::size_t const size : {0U, 31U, 33U}) { + auto const wrong_key = std::span(long_key).first(size); + BOOST_TEST(Authenticator::authenticate(wrong_key, message).error() == + crypto::error::invalid_key_size); + BOOST_TEST(single_use_key_authentication::authenticate(wrong_key, message) + .error() == crypto::error::invalid_key_size); + BOOST_TEST(Authenticator::verify(wrong_key, message, tag).error() == + crypto::error::invalid_key_size); + BOOST_TEST( + single_use_key_authentication::verify(wrong_key, message, tag).error() == + crypto::error::invalid_key_size); + } + for (std::size_t const size : {0U, 15U, 17U}) { + auto const wrong_tag = std::span(long_tag).first(size); + BOOST_TEST(Authenticator::verify(key, message, wrong_tag).error() == + crypto::error::invalid_tag_size); + BOOST_TEST( + single_use_key_authentication::verify(key, message, wrong_tag).error() == + crypto::error::invalid_tag_size); + // Both wrong: the key's size first. + BOOST_TEST(Authenticator::verify(std::span(long_key), message, wrong_tag).error() == + crypto::error::invalid_key_size); + BOOST_TEST(single_use_key_authentication::verify(std::span(long_key), + message, wrong_tag) + .error() == crypto::error::invalid_key_size); + } +} + +/** + * Forgeries, each `authentication_failed`: each of the 16 tag bytes with its low and its high bit + * flipped, a message bit flipped, the message one byte shorter. + */ +template +void check_authenticator_forgeries() { + namespace crypto = webcpp::crypto; + namespace single_use_key_authentication = crypto::single_use_key_authentication; + auto const& c = poly1305_cases[0]; + auto const key = from_hex(c.key); + auto message = from_hex(c.message); + auto const tag = from_hex(c.tag); + for (std::size_t at = 0; at < tag.size(); ++at) { + for (std::uint8_t const bit : {std::uint8_t{0x01}, std::uint8_t{0x80}}) { + auto forged = tag; + forged[at] ^= bit; + BOOST_TEST(Authenticator::verify(key, message, forged).error() == + crypto::error::authentication_failed); + BOOST_TEST(single_use_key_authentication::verify(key, message, forged) + .error() == crypto::error::authentication_failed); + } + } + message[7] ^= 0x10U; + BOOST_TEST(Authenticator::verify(key, message, tag).error() == + crypto::error::authentication_failed); + message[7] ^= 0x10U; + BOOST_TEST( + Authenticator::verify(key, std::span(message).first(message.size() - 1), tag).error() == + crypto::error::authentication_failed); + BOOST_TEST(Authenticator::verify(key, message, tag).has_value()); +} + +/** + * The empty message with a null data(), whose tag is s, and the key as a secure::secret<32>, by its + * bytes(). + */ +template +void check_authenticator_uses() { + namespace crypto = webcpp::crypto; + namespace single_use_key_authentication = crypto::single_use_key_authentication; + auto const& c = poly1305_cases[0]; + auto const key = from_hex(c.key); + auto const message = from_hex(c.message); + // The empty message: its tag is s, the key's last 16 bytes, member and free. + std::span const empty; + auto const empty_tag = Authenticator::authenticate(key, empty); + if (BOOST_TEST(empty_tag.has_value())) { + BOOST_TEST(std::ranges::equal(*empty_tag, std::span(key).subspan(16))); + BOOST_TEST(Authenticator::verify(key, empty, *empty_tag).has_value()); + BOOST_TEST(single_use_key_authentication::verify(key, empty, *empty_tag) + .has_value()); + } + auto const free_empty = single_use_key_authentication::authenticate(key, empty); + BOOST_TEST(free_empty.has_value() && + std::ranges::equal(*free_empty, std::span(key).subspan(16))); + BOOST_TEST_EQ(to_hex(reference_poly1305(key, empty)), to_hex(std::span(key).subspan(16))); + // The key as a secure::secret<32>, an HKDF's or a cipher's output, by its bytes(). + webcpp::secure::secret<32> key_secret; + std::ranges::copy(key, key_secret.writable().begin()); + auto const from_secret = Authenticator::authenticate(key_secret.bytes(), message); + BOOST_TEST(from_secret.has_value() && to_hex(*from_secret) == c.tag); + BOOST_TEST(Authenticator::verify(key_secret.bytes(), message, from_hex(c.tag)).has_value()); + BOOST_TEST(single_use_key_authentication::verify(key_secret.bytes(), message, + from_hex(c.tag)) + .has_value()); +} + +/** + * Key, message and tag spans that overlap: the key inside the message gives the tag of copies, and + * a tag inside both is refused; nothing is written into them. + */ +template +void check_authenticator_overlaps() { + namespace crypto = webcpp::crypto; + std::array shared{}; + for (std::size_t i = 0; i < shared.size(); ++i) { + shared[i] = static_cast((i * 37) + 11); + } + auto const untouched = shared; + std::span const shared_bytes(shared); + auto const overlapping_key = shared_bytes.subspan(8, 32); + auto const overlapping_message = shared_bytes.first(80); + std::vector const key_copy(overlapping_key.begin(), overlapping_key.end()); + std::vector const message_copy(overlapping_message.begin(), + overlapping_message.end()); + auto const overlapped = Authenticator::authenticate(overlapping_key, overlapping_message); + auto const copied = Authenticator::authenticate(key_copy, message_copy); + if (BOOST_TEST(overlapped.has_value()) && BOOST_TEST(copied.has_value())) { + BOOST_TEST(std::ranges::equal(*overlapped, *copied)); + BOOST_TEST( + Authenticator::verify(overlapping_key, overlapping_message, *copied).has_value()); + BOOST_TEST(Authenticator::verify(overlapping_key, overlapping_message, + shared_bytes.subspan(24, 16)) + .error() == crypto::error::authentication_failed); + } + BOOST_TEST(shared == untouched); +} + +/** + * Every check of a single-use key authenticator on one backend. + * + * @tparam Authenticator `authenticators::poly1305`. + */ +template +void check_single_use_key_authenticator() { + static_assert(Authenticator::key_size == 32 && Authenticator::tag_size == 16); + static_assert( + webcpp::crypto::single_use_key_authentication::single_use_key_authenticator); + check_authenticator_cases(); + check_authenticator_guards(); + check_authenticator_forgeries(); + check_authenticator_uses(); + check_authenticator_overlaps(); +} + +} // namespace webcpp::test + +#endif // WEBCPP_TEST_CRYPTO_SUPPORT_AUTHENTICATOR_CHECKS_HPP diff --git a/test/support/capabilities.hpp b/test/support/capabilities.hpp index 86b2e5c..7208c51 100644 --- a/test/support/capabilities.hpp +++ b/test/support/capabilities.hpp @@ -12,6 +12,7 @@ #include #include #include +#include #include namespace webcpp::test { @@ -33,7 +34,8 @@ constexpr std::size_t key_size_of() { * `from_key`, a key pair's `from_secret`, `crypto_kx`'s `derive_from_seed`), or, for one made of * an X25519 key pair and a peer's public key (a box, `from_keys`), from the key pair of that key * as its secret and that key as the peer's, or, for one keyed by no key of its own (Ed25519ph's - * signer), begins it, or, for sealed boxes, seals an empty message to that key as a public key: + * signer), begins it, or, for an algorithm that is no object (Poly1305), authenticates the empty + * message under that key, or, for sealed boxes, seals an empty message to that key as a public key: * a cell the capability table marks present whose engine is missing fails to compile here. The type * names its family and its algorithm as the table does, and `supports_v` says that the backend has * it. @@ -42,7 +44,7 @@ constexpr std::size_t key_size_of() { * @tparam Family Its family's tag. * @tparam Name Its algorithm's tag. * @tparam Backend Its backend. - * @return Whether the factory, `begin` or `seal` succeeded. + * @return Whether the factory, `begin`, `authenticate` or `seal` succeeded. */ template [[nodiscard]] bool made() { @@ -59,6 +61,10 @@ template return Algorithm::from_secret(key_bytes).has_value(); } else if constexpr (requires { Algorithm::derive_from_seed(key_bytes); }) { return Algorithm::derive_from_seed(key_bytes).has_value(); + } else if constexpr (requires { + Algorithm::authenticate(key_bytes, std::span()); + }) { + return Algorithm::authenticate(key_bytes, std::span()).has_value(); } else { static_assert( requires { diff --git a/test/support/composition_checks.hpp b/test/support/composition_checks.hpp new file mode 100644 index 0000000..1d6df9c --- /dev/null +++ b/test/support/composition_checks.hpp @@ -0,0 +1,247 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// RFC 8439 section 2.8's AEAD composed from the raw pieces, against each backend's +// ChaCha20-Poly1305 (design D17): check_rfc8439_composition derives the one-time Poly1305 +// key from ciphers::chacha20's keystream at counter 0 (section 2.6), encrypts the plaintext +// through apply_keystream from counter 1, authenticates aad || pad16 || ciphertext || pad16 || +// le64(aad length) || le64(ciphertext length) with authenticators::poly1305

, and asserts that +// the ciphertext and the tag equal, byte for byte, ciphers::chacha20_poly1305's seal of the same +// key, nonce, aad and plaintext. Every combination runs the same cases, drawn once: section 2.8.2's +// vector, its ciphertext and tag also checked against the RFC's bytes, then random keys and nonces +// over every pair of message lengths (0, 1, 15, 16, 17, 63, 64, 65, 255, 1024) and aad lengths (0, +// 1, 12, 16, 17). A failure's message names the combination, "//", the +// case and the lengths. The derived key is wiped after each case. + +#ifndef WEBCPP_TEST_CRYPTO_SUPPORT_COMPOSITION_CHECKS_HPP +#define WEBCPP_TEST_CRYPTO_SUPPORT_COMPOSITION_CHECKS_HPP + +#include "aead_checks.hpp" +#include "agreement.hpp" +#include "hex.hpp" + +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::test { + +/** One case of the composition: what every combination seals. */ +struct composition_case { + /** What the case is, as a failure names it. */ + std::string name; + /** The 32-byte key. */ + std::vector key; + /** The 12-byte nonce. */ + std::vector nonce; + /** The additional data. */ + std::vector associated_data; + /** The plaintext. */ + std::vector plaintext; +}; + +/** The message lengths of the random cases. */ +inline constexpr auto composition_message_sizes = + std::to_array({0, 1, 15, 16, 17, 63, 64, 65, 255, 1024}); +/** The additional data's lengths of the random cases. */ +inline constexpr auto composition_aad_sizes = std::to_array({0, 1, 12, 16, 17}); + +/** + * The cases every combination runs, drawn once by `run_composition_matrix`: section 2.8.2's vector + * first, then one random key, nonce, aad and plaintext for every pair of lengths, from a fixed + * seed, so that a failure repeats. + */ +inline std::vector composition_cases() { + std::vector drawn; + auto const& vector = chacha20_poly1305_cases[0]; + drawn.push_back({ + .name = "RFC 8439 section 2.8.2", + .key = from_hex(vector.key), + .nonce = from_hex(vector.nonce), + .associated_data = from_hex(vector.associated_data), + .plaintext = from_hex(vector.plaintext), + }); + // NOLINTNEXTLINE(bugprone-random-generator-seed,cert-msc32-c,cert-msc51-cpp): reproducible + std::mt19937_64 generator(20261205); + for (std::size_t const message_size : composition_message_sizes) { + for (std::size_t const aad_size : composition_aad_sizes) { + drawn.push_back({ + .name = "a random case", + .key = random_bytes(generator, 32), + .nonce = random_bytes(generator, 12), + .associated_data = random_bytes(generator, aad_size), + .plaintext = random_bytes(generator, message_size), + }); + } + } + return drawn; +} + +/** Appends zeros to `bytes` up to a multiple of 16 (RFC 8439 section 2.8's pad16). */ +inline void pad16(std::vector& bytes) { + bytes.resize((bytes.size() + 15) / 16 * 16, 0); +} + +/** Appends `value` to `bytes` as 8 bytes, little-endian. */ +inline void append_le64(std::vector& bytes, std::uint64_t value) { + for (unsigned index = 0; index < 8; ++index) { + bytes.push_back(static_cast(value >> (8U * index))); + } +} + +/** + * What Poly1305 authenticates in RFC 8439 section 2.8: aad || pad16 || ciphertext || pad16 || + * le64(aad length) || le64(ciphertext length). + */ +inline std::vector rfc8439_mac_data(std::span associated_data, + std::span ciphertext) { + std::vector mac_data(associated_data.begin(), associated_data.end()); + pad16(mac_data); + mac_data.insert(mac_data.end(), ciphertext.begin(), ciphertext.end()); + pad16(mac_data); + append_le64(mac_data, associated_data.size()); + append_le64(mac_data, ciphertext.size()); + return mac_data; +} + +/** Reports a failure of one combination and case, naming them and the lengths. */ +inline void report_composition(std::string const& combination, composition_case const& c, + std::string const& what) { + std::string const message = combination + ", " + c.name + " (message of " + + std::to_string(c.plaintext.size()) + " bytes, aad of " + + std::to_string(c.associated_data.size()) + " bytes): " + what; + BOOST_ERROR(message.c_str()); +} + +/** The AEAD composed from the raw pieces: its ciphertext and its tag, in hex, or why it failed. */ +struct composed_aead { + /** The ciphertext. */ + std::string ciphertext; + /** The tag. */ + std::string tag; + /** What failed, or empty. */ + std::string failure; +}; + +// tag::compose[] +/** + * RFC 8439 section 2.8's AEAD of one case composed from `ciphers::chacha20` and + * `authenticators::poly1305`; the one-time key is wiped before it returns. + */ +template +composed_aead compose(composition_case const& c) { + namespace crypto = webcpp::crypto; + auto cipher = crypto::ciphers::chacha20::from_key(c.key); + if (!cipher) { + return {.ciphertext = {}, .tag = {}, .failure = "the stream cipher's from_key failed"}; + } + // Section 2.6: the one-time key, the first 32 bytes of the keystream at counter 0. + std::array poly_key{}; + auto ciphertext = c.plaintext; + bool const encrypted = cipher->apply_keystream(c.nonce, poly_key, 0).has_value() && + cipher->apply_keystream(c.nonce, ciphertext, 1).has_value(); + auto const tag = crypto::authenticators::poly1305::authenticate( + std::span(poly_key).first(32), rfc8439_mac_data(c.associated_data, ciphertext)); + webcpp::secure::erase_secret(poly_key); + if (!encrypted || !tag) { + return {.ciphertext = {}, .tag = {}, .failure = "the raw pieces failed"}; + } + return {.ciphertext = to_hex(ciphertext), .tag = to_hex(*tag), .failure = {}}; +} + +// end::compose[] + +/** `ciphers::chacha20_poly1305`'s seal of one case, in hex, or why it failed. */ +template +composed_aead sealed_by_aead(composition_case const& c) { + auto aead = webcpp::crypto::ciphers::chacha20_poly1305::from_key(c.key); + if (!aead) { + return {.ciphertext = {}, .tag = {}, .failure = "the AEAD's from_key failed"}; + } + auto data = c.plaintext; + auto const tag = aead->seal(c.nonce, c.associated_data, data); + if (!tag) { + return {.ciphertext = {}, .tag = {}, .failure = "the AEAD's seal failed"}; + } + return {.ciphertext = to_hex(data), .tag = to_hex(*tag), .failure = {}}; +} + +/** + * RFC 8439 section 2.8's AEAD composed from `ciphers::chacha20` and + * `authenticators::poly1305`, against + * `ciphers::chacha20_poly1305`'s seal, byte for byte, over every case; section + * 2.8.2's vector, the first case, also against the RFC's bytes. A failure names + * "//", the case and the lengths. + */ +template +void check_rfc8439_composition(std::span cases) { + std::string const combination = std::string(StreamBackend::name) + "/" + + std::string(AuthenticatorBackend::name) + "/" + + std::string(AeadBackend::name); + std::size_t agreed = 0; + for (auto const& c : cases) { + auto const composed = compose(c); + auto const sealed = sealed_by_aead(c); + bool same = composed.failure.empty() && sealed.failure.empty(); + if (!composed.failure.empty() || !sealed.failure.empty()) { + report_composition(combination, c, composed.failure + sealed.failure); + } + if (same && composed.ciphertext != sealed.ciphertext) { + report_composition(combination, c, + "the composed ciphertext " + composed.ciphertext + + " is not the AEAD's " + sealed.ciphertext); + same = false; + } + if (same && composed.tag != sealed.tag) { + report_composition( + combination, c, + "the composed tag " + composed.tag + " is not the AEAD's " + sealed.tag); + same = false; + } + if (same && &c == &cases.front()) { + auto const& vector = chacha20_poly1305_cases[0]; + if (composed.ciphertext != vector.ciphertext || composed.tag != vector.tag) { + report_composition(combination, c, "the ciphertext or the tag is not the RFC's"); + same = false; + } + } + if (same) { + ++agreed; + } + } + BOOST_TEST_EQ(agreed, cases.size()); +} + +/** + * `check_rfc8439_composition` over every combination given, each a + * `std::tuple`, on the same cases, drawn once. + */ +template +void run_composition_matrix() { + auto const cases = composition_cases(); + ( + [&cases]( + std::tuple* /*combination*/) { + check_rfc8439_composition(cases); + }(static_cast(nullptr)), + ...); +} + +} // namespace webcpp::test + +#endif // WEBCPP_TEST_CRYPTO_SUPPORT_COMPOSITION_CHECKS_HPP diff --git a/test/support/nip44.hpp b/test/support/nip44.hpp new file mode 100644 index 0000000..59d15ec --- /dev/null +++ b/test/support/nip44.hpp @@ -0,0 +1,428 @@ +// 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) + +// NIP-44 version 2, composed in the tests alone from webcpp's pieces as the NIP writes it (design +// D9, R13): the conversation key, HKDF-Extract with the salt "nip44-v2" over secp256k1's shared x +// (crypto's agree); the message keys, HKDF-Expand of 76 bytes under the message's nonce +// (webcpp::hash); the padding; ChaCha20 from counter 0 (the cipher under test); HMAC-SHA256 over +// the nonce and the ciphertext; base64 (webcpp::codecs). run_vectors reads NIP-44's own +// nip44.vectors.json and checks its four valid sections and the long messages, each section's +// count printed and checked nonzero, so that a renamed key in the file fails the test instead of +// passing it empty. The invalid sections are not run (R13): they test a decoder's refusals, which +// are NIP-44's, not the cipher's. The vectors' keys are public test data; the helpers still wipe +// the keys they derive and hold in arrays (the conversation key, the message keys), as a program +// would, but not the HMAC's state, which Boost.Hash2's hmac gives no way to wipe. + +#ifndef WEBCPP_TEST_CRYPTO_SUPPORT_NIP44_HPP +#define WEBCPP_TEST_CRYPTO_SUPPORT_NIP44_HPP + +#include "hex.hpp" +#include "test_data.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::test::nip44 { + +/** The conversation key's salt, NIP-44's "nip44-v2". */ +inline constexpr std::array salt{'n', 'i', 'p', '4', '4', '-', 'v', '2'}; + +/** The payload's version byte. */ +inline constexpr std::uint8_t version = 2; + +/** + * The conversation key of a secret key and a peer's x-only public key: secp256k1's shared x + * (`agree` on the peer's even point, `02 || x`), extracted with HKDF-SHA256 under the salt + * "nip44-v2". + * + * @param secret_key The secret key. + * @param peer_xonly The peer's x-only public key. + * @return The conversation key, which the caller wipes; the curve's error for a key it refuses. + */ +inline boost::system::result> conversation_key( + std::span secret_key, std::span peer_xonly) { + namespace secp256k1 = webcpp::crypto::curves::secp256k1; + auto const pair = secp256k1::keypair::from_secret(secret_key); + if (!pair) { + return pair.error(); + } + std::array even_point{}; + even_point[0] = 2; + std::ranges::copy(peer_xonly, even_point.begin() + 1); + auto const peer = secp256k1::public_key::from_bytes(even_point); + if (!peer) { + return peer.error(); + } + auto const shared_x = pair->agree(*peer); + if (!shared_x) { + return shared_x.error(); + } + auto extracted = + webcpp::hash::hkdf_extract(salt, shared_x->bytes()); + if (!extracted) { + return extracted.error(); + } + std::array key{}; + std::ranges::copy(*extracted, key.begin()); + webcpp::secure::erase_secret(std::span(extracted->data(), extracted->size())); + return key; +} + +/** A message's keys, which the caller wipes. */ +struct message_keys { + /** ChaCha20's key. */ + std::array chacha_key{}; + /** ChaCha20's nonce. */ + std::array chacha_nonce{}; + /** HMAC-SHA256's key. */ + std::array hmac_key{}; + + /** Wipes the three keys. */ + void wipe() noexcept { + webcpp::secure::erase_secret(std::span(chacha_key)); + webcpp::secure::erase_secret(std::span(chacha_nonce)); + webcpp::secure::erase_secret(std::span(hmac_key)); + } +}; + +/** + * A message's keys: HKDF-Expand with HMAC-SHA256 of 76 bytes, the conversation key the + * pseudorandom key and the message's nonce the information, cut 32, 12, 32. + * + * @param conversation The conversation key. + * @param nonce The message's nonce. + * @return The keys. + */ +inline message_keys derive_message_keys(std::span conversation, + std::span nonce) { + std::array expanded{}; + BOOST_TEST(webcpp::hash::hkdf_expand(expanded, conversation, nonce) + .has_value()); + message_keys keys; + std::ranges::copy(std::span(expanded).first(32), keys.chacha_key.begin()); + std::ranges::copy(std::span(expanded).subspan(32, 12), keys.chacha_nonce.begin()); + std::ranges::copy(std::span(expanded).subspan(44, 32), keys.hmac_key.begin()); + webcpp::secure::erase_secret(std::span(expanded)); + return keys; +} + +/** + * NIP-44's calc_padded_len: 32 bytes up to 32, then the next multiple of a chunk, the chunk 32 + * bytes up to 256 and an eighth of the next power of two above that. + * + * @param plaintext_length The plaintext's length, 1 to 65535. + * @return The padded length. + */ +inline std::size_t padded_length(std::size_t plaintext_length) { + if (plaintext_length <= 32) { + return 32; + } + std::size_t next_power = 1; + while (next_power < plaintext_length) { + next_power <<= 1U; + } + std::size_t const chunk = next_power <= 256 ? 32 : next_power / 8; + return chunk * (((plaintext_length - 1) / chunk) + 1); +} + +/** + * HMAC-SHA256 under `key` over `nonce || ciphertext`. The hmac's state, which holds the key's + * pads, is not wiped: Boost.Hash2's hmac has no wipe, and the vectors' keys are public. + * + * @param key The HMAC key. + * @param nonce The message's nonce. + * @param ciphertext The ciphertext. + * @return The tag. + */ +inline webcpp::hash::hmac_sha2_256::result_type message_mac( + std::span key, std::span nonce, + std::span ciphertext) { + webcpp::hash::hmac_sha2_256 mac(key.data(), key.size()); + mac.update(nonce.data(), nonce.size()); + mac.update(ciphertext.data(), ciphertext.size()); + return mac.result(); +} + +// tag::encrypt[] +/** + * Encrypts a message: its length as two big-endian bytes, the plaintext and zeroes to the padded + * length, ChaCha20 from counter 0, then `2 || nonce || ciphertext || mac` in base64. + * + * @tparam Cipher `ciphers::chacha20`. + * @param conversation The conversation key. + * @param nonce The message's nonce. + * @param plaintext The message, 1 to 65535 bytes. + * @return The payload; empty, a failure recorded, for a plaintext of another length. + */ +template +std::string encrypt(std::span conversation, + std::span nonce, std::string_view plaintext) { + if (!BOOST_TEST(!plaintext.empty() && plaintext.size() <= 65535)) { + return {}; + } + auto keys = derive_message_keys(conversation, nonce); + std::vector padded(2 + padded_length(plaintext.size()), 0); + padded[0] = static_cast(plaintext.size() >> 8U); + padded[1] = static_cast(plaintext.size() & 0xffU); + std::ranges::copy(plaintext, padded.begin() + 2); + auto cipher = Cipher::from_key(keys.chacha_key); + BOOST_TEST(cipher.has_value() && + cipher->apply_keystream(keys.chacha_nonce, padded, 0).has_value()); + auto const mac = message_mac(keys.hmac_key, nonce, padded); + keys.wipe(); + std::vector payload; + payload.reserve(1 + nonce.size() + padded.size() + mac.size()); + payload.push_back(version); + payload.insert(payload.end(), nonce.begin(), nonce.end()); + payload.insert(payload.end(), padded.begin(), padded.end()); + payload.insert(payload.end(), mac.begin(), mac.end()); + return std::string(webcpp::codecs::encode(webcpp::codecs::formats::base64, payload, + webcpp::codecs::tokens::return_string) + .value()); +} + +// end::encrypt[] + +/** + * Decrypts a payload: the MAC checked first, in constant time, then ChaCha20 from counter 0 and + * the length read from the first two bytes. + * + * @tparam Cipher `ciphers::chacha20`. + * @param conversation The conversation key. + * @param payload The payload in base64. + * @return The plaintext; `authentication_failed` for a wrong MAC; `invalid_encoding` for a payload + * that is no version 2 payload. + */ +template +boost::system::result decrypt(std::span conversation, + std::string_view payload) { + std::vector bytes(((payload.size() / 4) + 1) * 3); + auto const decoded = webcpp::codecs::decode(webcpp::codecs::formats::base64, payload, bytes); + if (!decoded || *decoded < 1 + 32 + 34 + 32 || bytes[0] != version) { + return webcpp::crypto::error::invalid_encoding; + } + bytes.resize(*decoded); + auto const nonce = std::span(bytes.data() + 1, 32); + auto const ciphertext = std::span(bytes).subspan(33, bytes.size() - 33 - 32); + auto const received_mac = std::span(bytes).last(32); + auto keys = derive_message_keys(conversation, nonce); + auto const mac = message_mac(keys.hmac_key, nonce, ciphertext); + if (!webcpp::secure::constant_time_equal(std::span(mac.data(), mac.size()), + received_mac)) { + keys.wipe(); + return webcpp::crypto::error::authentication_failed; + } + auto cipher = Cipher::from_key(keys.chacha_key); + if (!cipher) { + keys.wipe(); + return cipher.error(); + } + auto const applied = cipher->apply_keystream(keys.chacha_nonce, ciphertext, 0); + keys.wipe(); + if (!applied) { + return applied.error(); + } + std::size_t const length = (std::size_t{ciphertext[0]} << 8U) | ciphertext[1]; + if (length == 0 || length + 2 > ciphertext.size() || + ciphertext.size() != 2 + padded_length(length)) { + return webcpp::crypto::error::invalid_encoding; + } + auto const message = ciphertext.subspan(2, length); + return std::string(message.begin(), message.end()); +} + +/** The bytes of a 32-byte hex field of the vectors. */ +inline std::array field32(boost::json::value const& entry, char const* key) { + std::array bytes{}; + auto const decoded = from_hex(std::string_view(entry.at(key).as_string())); + BOOST_TEST_EQ(decoded.size(), 32U); + std::ranges::copy(std::span(decoded).first(std::min(32, decoded.size())), + bytes.begin()); + return bytes; +} + +/** The SHA-256 of the bytes, in hex. */ +inline std::string sha256_hex(std::string_view text) { + boost::hash2::sha2_256 hasher; + hasher.update(text.data(), text.size()); + auto const digest = hasher.result(); + return to_hex(std::span(digest.data(), digest.size())); +} + +/** The x-only public key of a secret key. */ +inline std::array xonly_of(std::span secret_key) { + namespace secp256k1 = webcpp::crypto::curves::secp256k1; + std::array xonly{}; + auto const pair = secp256k1::keypair::from_secret(secret_key); + if (!BOOST_TEST(pair.has_value())) { + return xonly; + } + auto const point = pair->public_key(); + if (!BOOST_TEST(point.has_value())) { + return xonly; + } + auto const compressed = point->compressed(); + std::ranges::copy(std::span(compressed).subspan(1, 32), xonly.begin()); + return xonly; +} + +/** The section get_conversation_key: each secret key and peer give the conversation key. */ +inline std::size_t check_conversation_keys(boost::json::value const& valid) { + std::size_t entries = 0; + for (auto const& entry : valid.at("get_conversation_key").as_array()) { + auto key = conversation_key(field32(entry, "sec1"), field32(entry, "pub2")); + if (BOOST_TEST(key.has_value())) { + BOOST_TEST_EQ(to_hex(*key), std::string_view(entry.at("conversation_key").as_string())); + webcpp::secure::erase_secret(std::span(*key)); + } + ++entries; + } + return entries; +} + +/** The section get_message_keys: each nonce gives the three keys under the conversation key. */ +inline std::size_t check_message_keys(boost::json::value const& valid) { + std::size_t entries = 0; + auto const& section = valid.at("get_message_keys"); + auto conversation = field32(section, "conversation_key"); + for (auto const& entry : section.at("keys").as_array()) { + auto keys = derive_message_keys(conversation, field32(entry, "nonce")); + BOOST_TEST_EQ(to_hex(keys.chacha_key), + std::string_view(entry.at("chacha_key").as_string())); + BOOST_TEST_EQ(to_hex(keys.chacha_nonce), + std::string_view(entry.at("chacha_nonce").as_string())); + BOOST_TEST_EQ(to_hex(keys.hmac_key), std::string_view(entry.at("hmac_key").as_string())); + keys.wipe(); + ++entries; + } + webcpp::secure::erase_secret(std::span(conversation)); + return entries; +} + +/** The section calc_padded_len: each length's padded length. */ +inline std::size_t check_paddings(boost::json::value const& valid) { + std::size_t entries = 0; + for (auto const& pair : valid.at("calc_padded_len").as_array()) { + auto const& lengths = pair.as_array(); + BOOST_TEST_EQ( + padded_length(static_cast(lengths.at(0).to_number())), + static_cast(lengths.at(1).to_number())); + ++entries; + } + return entries; +} + +/** + * The section encrypt_decrypt: each message encrypts to its payload and decrypts back, and both + * sides' secret keys give its conversation key. + */ +template +std::size_t check_messages(boost::json::value const& valid) { + std::size_t entries = 0; + for (auto const& entry : valid.at("encrypt_decrypt").as_array()) { + auto key = field32(entry, "conversation_key"); + std::string_view const plaintext(entry.at("plaintext").as_string()); + std::string_view const payload(entry.at("payload").as_string()); + BOOST_TEST_EQ(encrypt(key, field32(entry, "nonce"), plaintext), payload); + auto const opened = decrypt(key, payload); + BOOST_TEST(opened.has_value() && *opened == plaintext); + auto from_first = + conversation_key(field32(entry, "sec1"), xonly_of(field32(entry, "sec2"))); + auto from_second = + conversation_key(field32(entry, "sec2"), xonly_of(field32(entry, "sec1"))); + BOOST_TEST(from_first.has_value() && *from_first == key); + BOOST_TEST(from_second.has_value() && *from_second == key); + for (auto* derived : {&from_first, &from_second}) { + if (derived->has_value()) { + webcpp::secure::erase_secret(std::span(**derived)); + } + } + webcpp::secure::erase_secret(std::span(key)); + ++entries; + } + return entries; +} + +/** + * The section encrypt_decrypt_long_msg: each pattern repeated gives the plaintext's SHA-256 and + * the payload's, and decrypts back. + */ +template +std::size_t check_long_messages(boost::json::value const& valid) { + std::size_t entries = 0; + for (auto const& entry : valid.at("encrypt_decrypt_long_msg").as_array()) { + auto key = field32(entry, "conversation_key"); + std::string const pattern(entry.at("pattern").as_string()); + auto const repeat = static_cast(entry.at("repeat").to_number()); + std::string plaintext; + plaintext.reserve(pattern.size() * repeat); + for (std::size_t i = 0; i < repeat; ++i) { + plaintext += pattern; + } + BOOST_TEST_EQ(sha256_hex(plaintext), + std::string_view(entry.at("plaintext_sha256").as_string())); + auto const payload = encrypt(key, field32(entry, "nonce"), plaintext); + BOOST_TEST_EQ(sha256_hex(payload), + std::string_view(entry.at("payload_sha256").as_string())); + auto const opened = decrypt(key, payload); + BOOST_TEST(opened.has_value() && *opened == plaintext); + webcpp::secure::erase_secret(std::span(key)); + ++entries; + } + return entries; +} + +/** + * NIP-44's valid vectors through `Cipher`: every section's entries, each section's count printed + * and checked nonzero. + * + * @tparam Cipher `ciphers::chacha20`. + */ +template +void run_vectors() { + auto const document = + boost::json::parse(read_file(std::string(WEBCPP_TEST_NIP44) + "/nip44.vectors.json")); + auto const& valid = document.at("v2").at("valid"); + std::size_t const conversation_keys = check_conversation_keys(valid); + std::size_t const message_key_sets = check_message_keys(valid); + std::size_t const paddings = check_paddings(valid); + std::size_t const messages = check_messages(valid); + std::size_t const long_messages = check_long_messages(valid); + static_cast(std::printf( + "nip44: %zu conversation keys, %zu message key sets, %zu paddings, %zu messages, %zu long " + "messages\n", + conversation_keys, message_key_sets, paddings, messages, long_messages)); + BOOST_TEST(conversation_keys > 0); + BOOST_TEST(message_key_sets > 0); + BOOST_TEST(paddings > 0); + BOOST_TEST(messages > 0); + BOOST_TEST(long_messages > 0); +} + +} // namespace webcpp::test::nip44 + +#endif // WEBCPP_TEST_CRYPTO_SUPPORT_NIP44_HPP diff --git a/test/support/stream_cipher_checks.hpp b/test/support/stream_cipher_checks.hpp new file mode 100644 index 0000000..cb02153 --- /dev/null +++ b/test/support/stream_cipher_checks.hpp @@ -0,0 +1,457 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The checks of a ciphers::basic_chacha20 on one backend (design D9): RFC 8439's known answers +// (section 2.3.2's block, section 2.4.2's sunscreen both ways, appendix A.1's test vectors 1 to 5 +// and A.2's 1 to 3), member and free form alike; every guard in its order (the state, the +// nonce's size, the counter's end), each leaving the data untouched; the counter's end, where the +// RFC has no vector, against a portable ChaCha20 block function written here from RFC 8439 +// section 2.3's pseudocode; the stream continued across calls; the nonce inside the data; empty +// data with a null data(); the key as a secure::secret<32>; and moves. + +#ifndef WEBCPP_TEST_CRYPTO_SUPPORT_STREAM_CIPHER_CHECKS_HPP +#define WEBCPP_TEST_CRYPTO_SUPPORT_STREAM_CIPHER_CHECKS_HPP + +#include "hex.hpp" + +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::test { + +/** One known answer of ChaCha20, every field in hex but the counter. */ +struct stream_case { + /** The key. */ + std::string_view key; + /** The nonce. */ + std::string_view nonce; + /** The block counter of the first block. */ + std::uint32_t initial_counter; + /** The plaintext; empty for a keystream, the ciphertext's size of zero bytes. */ + std::string_view plaintext; + /** The ciphertext. */ + std::string_view ciphertext; +}; + +/** "Ladies and Gentlemen of the class of '99: ...", the plaintext of RFC 8439 section 2.4.2. */ +inline constexpr std::string_view keystream_sunscreen = + "4c616469657320616e642047656e746c656d656e206f662074686520636c617373206f66202739393a20" + "4966204920636f756c64206f6666657220796f75206f6e6c79206f6e652074697020666f722074686520" + "6675747572652c2073756e73637265656e20776f756c642062652069742e"; + +/** RFC 8439's known answers of ChaCha20: sections 2.3.2 and 2.4.2, appendix A.1 and A.2. */ +inline constexpr std::array chacha20_cases{ + // RFC 8439 section 2.3.2: the block function. + stream_case{ + .key = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + .nonce = "000000090000004a00000000", + .initial_counter = 1, + .plaintext = "", + .ciphertext = "10f1e7e4d13b5915500fdd1fa32071c4c7d1f4c733c068030422aa9ac3d46c4ed28264" + "46079faa0914c2d705d98b02a2b5129cd1de164eb9cbd083e8a2503c4e", + }, + // RFC 8439 section 2.4.2: the sunscreen. + stream_case{ + .key = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + .nonce = "000000000000004a00000000", + .initial_counter = 1, + .plaintext = keystream_sunscreen, + .ciphertext = "6e2e359a2568f98041ba0728dd0d6981e97e7aec1d4360c20a27afccfd9fae0bf91b65" + "c5524733ab8f593dabcd62b3571639d624e65152ab8f530c359f0861d807ca0dbf500d" + "6a6156a38e088a22b65e52bc514d16ccf806818ce91ab77937365af90bbf74a35be6b4" + "0b8eedf2785e42874d", + }, + // appendix A.1, test vector 1. + stream_case{ + .key = "0000000000000000000000000000000000000000000000000000000000000000", + .nonce = "000000000000000000000000", + .initial_counter = 0, + .plaintext = "", + .ciphertext = "76b8e0ada0f13d90405d6ae55386bd28bdd219b8a08ded1aa836efcc8b770dc7da4159" + "7c5157488d7724e03fb8d84a376a43b8f41518a11cc387b669b2ee6586", + }, + // appendix A.1, test vector 2. + stream_case{ + .key = "0000000000000000000000000000000000000000000000000000000000000000", + .nonce = "000000000000000000000000", + .initial_counter = 1, + .plaintext = "", + .ciphertext = "9f07e7be5551387a98ba977c732d080dcb0f29a048e3656912c6533e32ee7aed29b721" + "769ce64e43d57133b074d839d531ed1f28510afb45ace10a1f4b794d6f", + }, + // appendix A.1, test vector 3. + stream_case{ + .key = "0000000000000000000000000000000000000000000000000000000000000001", + .nonce = "000000000000000000000000", + .initial_counter = 1, + .plaintext = "", + .ciphertext = "3aeb5224ecf849929b9d828db1ced4dd832025e8018b8160b82284f3c949aa5a8eca00" + "bbb4a73bdad192b5c42f73f2fd4e273644c8b36125a64addeb006c13a0", + }, + // appendix A.1, test vector 4. + stream_case{ + .key = "00ff000000000000000000000000000000000000000000000000000000000000", + .nonce = "000000000000000000000000", + .initial_counter = 2, + .plaintext = "", + .ciphertext = "72d54dfbf12ec44b362692df94137f328fea8da73990265ec1bbbea1ae9af0ca13b25a" + "a26cb4a648cb9b9d1be65b2c0924a66c54d545ec1b7374f4872e99f096", + }, + // appendix A.1, test vector 5. + stream_case{ + .key = "0000000000000000000000000000000000000000000000000000000000000000", + .nonce = "000000000000000000000002", + .initial_counter = 0, + .plaintext = "", + .ciphertext = "c2c64d378cd536374ae204b9ef933fcd1a8b2288b3dfa49672ab765b54ee27c78a970e" + "0e955c14f3a88e741b97c286f75f8fc299e8148362fa198a39531bed6d", + }, + // appendix A.2, test vector 1. + stream_case{ + .key = "0000000000000000000000000000000000000000000000000000000000000000", + .nonce = "000000000000000000000000", + .initial_counter = 0, + .plaintext = "00000000000000000000000000000000000000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000000000", + .ciphertext = "76b8e0ada0f13d90405d6ae55386bd28bdd219b8a08ded1aa836efcc8b770dc7da4159" + "7c5157488d7724e03fb8d84a376a43b8f41518a11cc387b669b2ee6586", + }, + // appendix A.2, test vector 2. + stream_case{ + .key = "0000000000000000000000000000000000000000000000000000000000000001", + .nonce = "000000000000000000000002", + .initial_counter = 1, + .plaintext = "416e79207375626d697373696f6e20746f20746865204945544620696e74656e6465" + "642062792074686520436f6e7472696275746f7220666f72207075626c6963617469" + "6f6e20617320616c6c206f722070617274206f6620616e204945544620496e746572" + "6e65742d4472616674206f722052464320616e6420616e792073746174656d656e74" + "206d6164652077697468696e2074686520636f6e74657874206f6620616e20494554" + "4620616374697669747920697320636f6e7369646572656420616e20224945544620" + "436f6e747269627574696f6e222e20537563682073746174656d656e747320696e63" + "6c756465206f72616c2073746174656d656e747320696e2049455446207365737369" + "6f6e732c2061732077656c6c206173207772697474656e20616e6420656c65637472" + "6f6e696320636f6d6d756e69636174696f6e73206d61646520617420616e79207469" + "6d65206f7220706c6163652c20776869636820617265206164647265737365642074" + "6f", + .ciphertext = "a3fbf07df3fa2fde4f376ca23e82737041605d9f4f4f57bd8cff2c1d4b7955ec2a9794" + "8bd3722915c8f3d337f7d370050e9e96d647b7c39f56e031ca5eb6250d4042e02785ec" + "ecfa4b4bb5e8ead0440e20b6e8db09d881a7c6132f420e52795042bdfa7773d8a90514" + "47b3291ce1411c680465552aa6c405b7764d5e87bea85ad00f8449ed8f72d0d662ab05" + "2691ca66424bc86d2df80ea41f43abf937d3259dc4b2d0dfb48a6c9139ddd7f76966e9" + "28e635553ba76c5c879d7b35d49eb2e62b0871cdac638939e25e8a1e0ef9d5280fa8ca" + "328b351c3c765989cbcf3daa8b6ccc3aaf9f3979c92b3720fc88dc95ed84a1be059c64" + "99b9fda236e7e818b04b0bc39c1e876b193bfe5569753f88128cc08aaa9b63d1a16f80" + "ef2554d7189c411f5869ca52c5b83fa36ff216b9c1d30062bebcfd2dc5bce0911934fd" + "a79a86f6e698ced759c3ff9b6477338f3da4f9cd8514ea9982ccafb341b2384dd902f3" + "d1ab7ac61dd29c6f21ba5b862f3730e37cfdc4fd806c22f221", + }, + // appendix A.2, test vector 3. + stream_case{ + .key = "1c9240a5eb55d38af333888604f6b5f0473917c1402b80099dca5cbc207075c0", + .nonce = "000000000000000000000002", + .initial_counter = 42, + .plaintext = "2754776173206272696c6c69672c20616e642074686520736c6974687920746f7665" + "730a446964206779726520616e642067696d626c6520696e2074686520776162653a" + "0a416c6c206d696d737920776572652074686520626f726f676f7665732c0a416e64" + "20746865206d6f6d65207261746873206f757467726162652e", + .ciphertext = "62e6347f95ed87a45ffae7426f27a1df5fb69110044c0d73118effa95b01e5cf166d3d" + "f2d721caf9b21e5fb14c616871fd84c54f9d65b283196c7fe4f60553ebf39c6402c422" + "34e32a356b3e764312a61a5532055716ead6962568f87d3f3f7704c6a8d1bcd1bf4d50" + "d6154b6da731b187b58dfd728afa36757a797ac188d1", + }, +}; + +/** + * ChaCha20's block function, RFC 8439 section 2.3's pseudocode, portable and slow: the test's own + * reference for the counters the RFC has no vector for. + * + * @param key The 32-byte key. + * @param nonce The 12-byte nonce. + * @param counter The block counter. + * @return The 64-byte serialized block. + */ +inline std::array reference_chacha20_block(std::span key, + std::span nonce, + std::uint32_t counter) { + auto const word = [](std::span bytes, std::size_t at) { + return std::uint32_t{bytes[at]} | (std::uint32_t{bytes[at + 1]} << 8U) | + (std::uint32_t{bytes[at + 2]} << 16U) | (std::uint32_t{bytes[at + 3]} << 24U); + }; + std::array state{0x61707865U, 0x3320646eU, 0x79622d32U, 0x6b206574U}; + for (std::size_t i = 0; i < 8; ++i) { + state[4 + i] = word(key, 4 * i); + } + state[12] = counter; + for (std::size_t i = 0; i < 3; ++i) { + state[13 + i] = word(nonce, 4 * i); + } + auto working = state; + auto const quarter_round = [&working](std::size_t a, std::size_t b, std::size_t c, + std::size_t d) { + auto const rotate = [](std::uint32_t value, unsigned bits) { + return (value << bits) | (value >> (32U - bits)); + }; + working[a] += working[b]; + working[d] = rotate(working[d] ^ working[a], 16U); + working[c] += working[d]; + working[b] = rotate(working[b] ^ working[c], 12U); + working[a] += working[b]; + working[d] = rotate(working[d] ^ working[a], 8U); + working[c] += working[d]; + working[b] = rotate(working[b] ^ working[c], 7U); + }; + for (int round = 0; round < 10; ++round) { + quarter_round(0, 4, 8, 12); + quarter_round(1, 5, 9, 13); + quarter_round(2, 6, 10, 14); + quarter_round(3, 7, 11, 15); + quarter_round(0, 5, 10, 15); + quarter_round(1, 6, 11, 12); + quarter_round(2, 7, 8, 13); + quarter_round(3, 4, 9, 14); + } + std::array block{}; + for (std::size_t i = 0; i < 16; ++i) { + std::uint32_t const sum = working[i] + state[i]; + for (std::size_t j = 0; j < 4; ++j) { + block[(4 * i) + j] = static_cast(sum >> (8U * j)); + } + } + return block; +} + +/** The known answers: each case both ways, through the member and the free form. */ +template +void check_stream_cipher_cases() { + namespace crypto = webcpp::crypto; + for (auto const& c : chacha20_cases) { + auto made = Cipher::from_key(from_hex(c.key)); + if (!BOOST_TEST(made.has_value())) { + continue; + } + auto const nonce = from_hex(c.nonce); + auto const plaintext = c.plaintext.empty() + ? std::vector(c.ciphertext.size() / 2) + : from_hex(c.plaintext); + auto data = plaintext; + BOOST_TEST(made->apply_keystream(nonce, data, c.initial_counter).has_value()); + BOOST_TEST_EQ(to_hex(data), c.ciphertext); + BOOST_TEST(crypto::unauthenticated_encryption::apply_keystream(*made, nonce, data, + c.initial_counter) + .has_value()); + BOOST_TEST(data == plaintext); + } +} + +/** + * The guards in their order, each leaving the data untouched: a key of another size, a nonce of + * another size, a moved-from object (before the nonce's size), the counter's end. + */ +template +void check_stream_cipher_guards() { + namespace crypto = webcpp::crypto; + std::array long_key{}; + BOOST_TEST(Cipher::from_key(std::span(long_key).first(31)).error() == + crypto::error::invalid_key_size); + BOOST_TEST(Cipher::from_key(long_key).error() == crypto::error::invalid_key_size); + BOOST_TEST(Cipher::from_key({}).error() == crypto::error::invalid_key_size); + auto made = Cipher::from_key(std::span(long_key).first(32)); + if (!BOOST_TEST(made.has_value())) { + return; + } + std::array const nonce{}; + std::array data{}; + data.fill(0x6c); // a guard's refusal leaves this pattern, not only zeroes, untouched + auto const untouched = data; + for (std::size_t const size : {0U, 8U, 11U, 13U, 24U}) { + BOOST_TEST(made->apply_keystream(std::span(nonce).first(size), data, 0).error() == + crypto::error::invalid_nonce_size); + BOOST_TEST(crypto::unauthenticated_encryption::apply_keystream( + *made, std::span(nonce).first(size), data, 0) + .error() == crypto::error::invalid_nonce_size); + } + BOOST_TEST(data == untouched); + Cipher const moved = std::move(*made); + BOOST_TEST(made->apply_keystream(std::span(nonce).first(12), data, 0).error() == + crypto::error::invalid_state); + // The state before the nonce's size, both wrong. + BOOST_TEST(made->apply_keystream(std::span(nonce).first(8), data, 0).error() == + crypto::error::invalid_state); + BOOST_TEST(crypto::unauthenticated_encryption::apply_keystream(*made, std::span(nonce).first(8), + data, 0) + .error() == crypto::error::invalid_state); + BOOST_TEST(data == untouched); +} + +/** + * The counter's end (owner decision 7): 64 bytes at 2^32 - 1 run, as the reference's block; 65 + * there overflow, the data untouched; 128 at 2^32 - 2 run, as two of the reference's blocks; + * nothing at 2^32 - 1 runs. + */ +template +void check_stream_cipher_counter_end() { + namespace crypto = webcpp::crypto; + auto const key = from_hex(chacha20_cases[1].key); + auto const nonce = from_hex(chacha20_cases[1].nonce); + auto made = Cipher::from_key(key); + if (!BOOST_TEST(made.has_value())) { + return; + } + constexpr std::uint32_t last = std::numeric_limits::max(); + std::array data{}; + BOOST_TEST(made->apply_keystream(nonce, std::span(data).first(64), last).has_value()); + BOOST_TEST( + std::ranges::equal(std::span(data).first(64), reference_chacha20_block(key, nonce, last))); + data.fill(0x6c); + auto const untouched = data; + BOOST_TEST(made->apply_keystream(nonce, std::span(data).first(65), last).error() == + crypto::error::counter_overflow); + BOOST_TEST(crypto::unauthenticated_encryption::apply_keystream(*made, nonce, + std::span(data).first(65), last) + .error() == crypto::error::counter_overflow); + BOOST_TEST(made->apply_keystream(nonce, data, last).error() == crypto::error::counter_overflow); + BOOST_TEST(data == untouched); + data.fill(0); + BOOST_TEST(made->apply_keystream(nonce, data, last - 1).has_value()); + BOOST_TEST(std::ranges::equal(std::span(data).first(64), + reference_chacha20_block(key, nonce, last - 1))); + BOOST_TEST(std::ranges::equal(std::span(data).subspan(64), + reference_chacha20_block(key, nonce, last))); + BOOST_TEST(made->apply_keystream(nonce, std::span(), last).has_value()); + // The reference agrees with the RFC where the RFC has a vector. + BOOST_TEST_EQ(to_hex(reference_chacha20_block(from_hex(chacha20_cases[0].key), + from_hex(chacha20_cases[0].nonce), 1)), + chacha20_cases[0].ciphertext); +} + +/** + * The stream across calls, the nonce inside the data, empty data with a null data(), and the key + * as a secure::secret<32>. + */ +template +void check_stream_cipher_uses() { + namespace crypto = webcpp::crypto; + auto const key = from_hex(chacha20_cases[1].key); + auto const nonce = from_hex(chacha20_cases[1].nonce); + auto made = Cipher::from_key(key); + if (!BOOST_TEST(made.has_value())) { + return; + } + // 128 bytes from 7 are 64 from 7, then 64 from 8. + std::array whole{}; + std::array pieces{}; + BOOST_TEST(made->apply_keystream(nonce, whole, 7).has_value()); + BOOST_TEST(made->apply_keystream(nonce, std::span(pieces).first(64), 7).has_value()); + BOOST_TEST(made->apply_keystream(nonce, std::span(pieces).subspan(64), 8).has_value()); + BOOST_TEST(whole == pieces); + // A partial block, then a later block: the keystream of each block is the block's own. + std::array partial{}; + BOOST_TEST(made->apply_keystream(nonce, partial, 7).has_value()); + BOOST_TEST(std::ranges::equal(partial, std::span(whole).first(100))); + // The nonce inside the data, which the call overwrites: the nonce read is the one given. + std::array inside{}; + std::ranges::copy(nonce, inside.begin()); + std::array expected = inside; + BOOST_TEST(made->apply_keystream(nonce, expected, 1).has_value()); + BOOST_TEST(made->apply_keystream(std::span(inside).first(12), inside, 1).has_value()); + BOOST_TEST(inside == expected); + // Empty data whose data() is null runs, member and free. + BOOST_TEST(made->apply_keystream(nonce, std::span(), 0).has_value()); + BOOST_TEST(crypto::unauthenticated_encryption::apply_keystream(*made, nonce, + std::span(), 0) + .has_value()); + // The key as a secure::secret<32>, an HKDF's or an agreement's output, by its bytes(), as HPKE + // keys its AEAD, and crypto::from_key. + webcpp::secure::secret<32> key_secret; + std::ranges::copy(key, key_secret.writable().begin()); + auto from_secret = Cipher::from_key(key_secret.bytes()); + auto from_factory = crypto::from_key(key_secret.bytes()); + std::array again{}; + std::array factory{}; + BOOST_TEST(from_secret.has_value() && from_secret->apply_keystream(nonce, again, 7)); + BOOST_TEST(from_factory.has_value() && from_factory->apply_keystream(nonce, factory, 7)); + BOOST_TEST(again == whole); + BOOST_TEST(factory == whole); +} + +/** + * Moves (Review Focus 6): the target works, the source refuses with invalid_state, moving an + * empty object gives an empty one, an assignment back carries the key, a self-move keeps it. + */ +template +void check_stream_cipher_moves() { + namespace crypto = webcpp::crypto; + auto const& c = chacha20_cases[1]; + auto const key = from_hex(c.key); + auto const nonce = from_hex(c.nonce); + auto const plaintext = from_hex(c.plaintext); + auto const encrypts_the_case = [&](Cipher& cipher) { + auto data = plaintext; + return cipher.apply_keystream(nonce, data, c.initial_counter).has_value() && + to_hex(data) == c.ciphertext; + }; + auto const refused = [&](Cipher& cipher) { + std::array data{1, 2, 3, 4}; + return cipher.apply_keystream(nonce, data, 0).error() == crypto::error::invalid_state && + data == std::array{1, 2, 3, 4}; + }; + auto made = Cipher::from_key(key); + if (!BOOST_TEST(made.has_value())) { + return; + } + Cipher moved = std::move(*made); + BOOST_TEST(encrypts_the_case(moved)); + BOOST_TEST(refused(*made)); + Cipher empty = std::move(*made); + BOOST_TEST(refused(empty)); + *made = std::move(moved); + BOOST_TEST(encrypts_the_case(*made)); + BOOST_TEST(refused(moved)); + auto& self = *made; + *made = std::move(self); + BOOST_TEST(encrypts_the_case(*made)); + // An assignment over a live object from an empty one leaves it empty. + auto other = Cipher::from_key(key); + if (BOOST_TEST(other.has_value())) { + *other = std::move(empty); + BOOST_TEST(refused(*other)); + } +} + +/** + * Every check of a ChaCha20 on one backend. + * + * @tparam Cipher `ciphers::chacha20`. + */ +template +void check_stream_cipher() { + static_assert(Cipher::key_size == 32 && Cipher::nonce_size == 12 && Cipher::block_size == 64); + static_assert(std::is_same_v); + check_stream_cipher_cases(); + check_stream_cipher_guards(); + check_stream_cipher_counter_end(); + check_stream_cipher_uses(); + check_stream_cipher_moves(); +} + +} // namespace webcpp::test + +#endif // WEBCPP_TEST_CRYPTO_SUPPORT_STREAM_CIPHER_CHECKS_HPP diff --git a/test/support/timing_coverage.hpp b/test/support/timing_coverage.hpp index 7d05c09..40090e2 100644 --- a/test/support/timing_coverage.hpp +++ b/test/support/timing_coverage.hpp @@ -5,14 +5,16 @@ // https://www.boost.org/LICENSE_1_0.txt) // The coverage of webcpp::secure::timing_guard by the families every backend shares: each public -// function of the AES block cipher, gcm and ciphers::basic_chacha20_poly1305, and the free -// crypto::from_key, secret_key_encryption::aead::seal and secret_key_encryption::aead::open that -// call theirs, called once with valid input and once with input refused before the backend is -// reached, must enter a guard and leave the thread's DIT as it found it. Each backend's -// timing_coverage__test.cpp calls these on the algorithms it builds; a test includes -// support/timing_seam.hpp before any webcpp header, then this one. covered and uncovered count -// crypto's own guards, timing_entries (support/timing_seam.hpp), so that a guard of hash's or of -// secure's a call enters inside crypto's is not taken for crypto's. +// function of the AES block cipher, gcm, ciphers::basic_chacha20_poly1305, ciphers::basic_chacha20 +// and authenticators::poly1305, and the free crypto::from_key, secret_key_encryption::aead::seal, +// secret_key_encryption::aead::open, unauthenticated_encryption::apply_keystream, +// single_use_key_authentication::authenticate and single_use_key_authentication::verify that call +// theirs, and their asynchronous forms, called once with valid input and once with input refused +// before the backend is reached, must enter a guard and leave the thread's DIT as it found it. Each +// backend's timing_coverage__test.cpp calls these on the algorithms it builds; a test +// includes support/timing_seam.hpp before any webcpp header, then this one. covered and uncovered +// count crypto's own guards, timing_entries (support/timing_seam.hpp), so that a guard of hash's or +// of secure's a call enters inside crypto's is not taken for crypto's. #ifndef WEBCPP_TEST_CRYPTO_SUPPORT_TIMING_COVERAGE_HPP #define WEBCPP_TEST_CRYPTO_SUPPORT_TIMING_COVERAGE_HPP @@ -23,11 +25,13 @@ #include #include #include +#include #include #include #include #include #include +#include #include #include @@ -38,6 +42,7 @@ #include #include #include +#include #include #include #include @@ -933,6 +938,347 @@ void cover_aead(std::string const& family, std::string const& backend) { cover_async_aead(family, on); } +/** + * A stream cipher's free forms (design D3): `crypto::from_key`, a key of the wrong size included, + * and `unauthenticated_encryption::apply_keystream`, a nonce of the wrong size and an overflowing + * counter included. The first guard each enters is its own. + * + * @tparam Cipher `basic_chacha20`. + * @param family The family's name, as the public alias spells it. + * @param on ` on `, which ends each name. + */ +template +void cover_stream_cipher_free_forms(std::string const& family, std::string const& on) { + namespace unauthenticated_encryption = webcpp::crypto::unauthenticated_encryption; + auto const key = coverage_key(); + covered(family + " crypto::from_key" + on, "crypto::from_key", + [&key] { BOOST_TEST(webcpp::crypto::from_key(key).has_value()); }); + covered(family + " crypto::from_key with a short key" + on, "crypto::from_key", [&key] { + BOOST_TEST( + webcpp::crypto::from_key(std::span(key).first(Cipher::key_size - 1)).error() == + webcpp::crypto::error::invalid_key_size); + }); + auto made = Cipher::from_key(key); + if (!BOOST_TEST(made.has_value())) { + return; + } + std::array const nonce{}; + std::array data{}; + auto const last = std::numeric_limits::max(); + covered(family + " unauthenticated_encryption::apply_keystream" + on, + "unauthenticated_encryption::apply_keystream", [&] { + BOOST_TEST( + unauthenticated_encryption::apply_keystream(*made, nonce, data, 1).has_value()); + }); + covered(family + " unauthenticated_encryption::apply_keystream with a short nonce" + on, + "unauthenticated_encryption::apply_keystream", [&] { + BOOST_TEST(unauthenticated_encryption::apply_keystream( + *made, std::span(nonce).first(Cipher::nonce_size - 1), data, 1) + .error() == webcpp::crypto::error::invalid_nonce_size); + }); + covered(family + " unauthenticated_encryption::apply_keystream past the counter's end" + on, + "unauthenticated_encryption::apply_keystream", [&] { + BOOST_TEST( + unauthenticated_encryption::apply_keystream(*made, nonce, data, last).error() == + webcpp::crypto::error::counter_overflow); + }); +} + +/** + * A stream cipher's asynchronous functions, `crypto::async_from_key` and the static + * `async_from_key`, a key of the wrong size included, and `async_apply_keystream`, free and + * member, a nonce of the wrong size and an overflowing counter included, an `io_context` run after + * each call so that its completion is delivered. The first guard each enters is its own. + * + * @tparam Cipher `basic_chacha20`. + * @param family The family's name, as the public alias spells it. + * @param on ` on `, which ends each name. + */ +template +void cover_async_stream_cipher(std::string const& family, std::string const& on) { + namespace unauthenticated_encryption = webcpp::crypto::unauthenticated_encryption; + webcpp::asio::io_context context; + auto const executor = context.get_executor(); + auto const key = coverage_key(); + auto const short_key = std::span(key).first(Cipher::key_size - 1); + int completions = 0; + async_completion_counter<> const counted{.completions = &completions}; + auto const deliver = [&context] { + context.restart(); + context.run(); // lint-run: the test's event loop + }; + covered(family + " crypto::async_from_key" + on, "crypto::async_from_key", [&] { + webcpp::crypto::async_from_key(executor, key, counted); + deliver(); + }); + covered(family + " crypto::async_from_key with a short key" + on, "crypto::async_from_key", + [&] { + webcpp::crypto::async_from_key(executor, short_key, counted); + deliver(); + }); + covered(family + "::async_from_key" + on, "ciphers::basic_chacha20::async_from_key", [&] { + Cipher::async_from_key(executor, key, counted); + deliver(); + }); + covered(family + "::async_from_key with a short key" + on, + "ciphers::basic_chacha20::async_from_key", [&] { + Cipher::async_from_key(executor, short_key, counted); + deliver(); + }); + auto made = Cipher::from_key(key); + if (!BOOST_TEST(made.has_value())) { + return; + } + std::array const nonce{}; + auto const short_nonce = std::span(nonce).first(Cipher::nonce_size - 1); + std::array data{}; + auto const last = std::numeric_limits::max(); + covered(family + " unauthenticated_encryption::async_apply_keystream" + on, + "unauthenticated_encryption::async_apply_keystream", [&] { + unauthenticated_encryption::async_apply_keystream(executor, *made, nonce, data, 1, + counted); + deliver(); + }); + covered(family + " unauthenticated_encryption::async_apply_keystream with a short nonce" + on, + "unauthenticated_encryption::async_apply_keystream", [&] { + unauthenticated_encryption::async_apply_keystream(executor, *made, short_nonce, + data, 1, counted); + deliver(); + }); + covered( + family + " unauthenticated_encryption::async_apply_keystream past the counter's end" + on, + "unauthenticated_encryption::async_apply_keystream", [&] { + unauthenticated_encryption::async_apply_keystream(executor, *made, nonce, data, last, + counted); + deliver(); + }); + covered(family + "::async_apply_keystream" + on, + "ciphers::basic_chacha20::async_apply_keystream", [&] { + made->async_apply_keystream(executor, nonce, data, 1, counted); + deliver(); + }); + covered(family + "::async_apply_keystream with a short nonce" + on, + "ciphers::basic_chacha20::async_apply_keystream", [&] { + made->async_apply_keystream(executor, short_nonce, data, 1, counted); + deliver(); + }); + covered(family + "::async_apply_keystream past the counter's end" + on, + "ciphers::basic_chacha20::async_apply_keystream", [&] { + made->async_apply_keystream(executor, nonce, data, last, counted); + deliver(); + }); + BOOST_TEST_EQ(completions, 10); +} + +/** + * Every function of a stream cipher (design D9): the static `from_key`, a key of the wrong size + * included, and the member `apply_keystream`, a nonce of the wrong size and an overflowing + * counter included; then the free forms that call them (`cover_stream_cipher_free_forms`), and + * their asynchronous forms (`cover_async_stream_cipher`). + * + * @tparam Cipher `basic_chacha20`: ChaCha20. + * @param family The family's name, as the public alias spells it. + * @param backend The backend's name. + */ +template +void cover_stream_cipher(std::string const& family, std::string const& backend) { + std::string const on = " on " + backend; + auto const key = coverage_key(); + covered(family + "::from_key" + on, "ciphers::basic_chacha20::from_key", + [&key] { BOOST_TEST(Cipher::from_key(key).has_value()); }); + covered(family + "::from_key with a short key" + on, "ciphers::basic_chacha20::from_key", + [&key] { + BOOST_TEST(Cipher::from_key(std::span(key).first(Cipher::key_size - 1)).error() == + webcpp::crypto::error::invalid_key_size); + }); + auto made = Cipher::from_key(key); + if (!BOOST_TEST(made.has_value())) { + return; + } + std::array const nonce{}; + std::array data{}; + auto const last = std::numeric_limits::max(); + covered(family + "::apply_keystream" + on, "ciphers::basic_chacha20::apply_keystream", + [&] { BOOST_TEST(made->apply_keystream(nonce, data, 1).has_value()); }); + covered(family + "::apply_keystream with a short nonce" + on, + "ciphers::basic_chacha20::apply_keystream", [&] { + BOOST_TEST( + made->apply_keystream(std::span(nonce).first(Cipher::nonce_size - 1), data, 1) + .error() == webcpp::crypto::error::invalid_nonce_size); + }); + covered(family + "::apply_keystream past the counter's end" + on, + "ciphers::basic_chacha20::apply_keystream", [&] { + BOOST_TEST(made->apply_keystream(nonce, data, last).error() == + webcpp::crypto::error::counter_overflow); + }); + cover_stream_cipher_free_forms(family, on); + cover_async_stream_cipher(family, on); +} + +/** + * A single-use key authenticator's asynchronous functions, the static `async_authenticate`, a key + * of the wrong size included, and the static `async_verify`, with a matching and a mismatching tag + * and a tag of the wrong size; then the free forms + * `single_use_key_authentication::async_authenticate` and `async_verify` that call them, the same + * calls; an `io_context` run after each call so that its completion is delivered. The first guard + * each enters is its own. + * + * @tparam Authenticator `authenticators::poly1305`. + * @param family The family's name, as the public alias spells it. + * @param on ` on `, which ends each name. + */ +template +void cover_async_single_use_key_authenticator(std::string const& family, std::string const& on) { + namespace single_use_key_authentication = webcpp::crypto::single_use_key_authentication; + webcpp::asio::io_context context; + auto const executor = context.get_executor(); + auto const key = coverage_key(); + auto const short_key = std::span(key).first(Authenticator::key_size - 1); + std::array message{}; + message.fill(0x2d); + auto const made = Authenticator::authenticate(key, message); + if (!BOOST_TEST(made.has_value())) { + return; + } + auto const tag = *made; + auto mismatching = tag; + mismatching.data()[0] ^= 1U; + auto const short_tag = std::span(tag.data(), Authenticator::tag_size - 1); + int completions = 0; + async_completion_counter<> const counted{.completions = &completions}; + auto const deliver = [&context] { + context.restart(); + context.run(); // lint-run: the test's event loop + }; + std::string const member = "authenticators::" + family; + covered(family + "::async_authenticate" + on, member + "::async_authenticate", [&] { + Authenticator::async_authenticate(executor, key, message, counted); + deliver(); + }); + covered(family + "::async_authenticate with a short key" + on, member + "::async_authenticate", + [&] { + Authenticator::async_authenticate(executor, short_key, message, counted); + deliver(); + }); + covered(family + "::async_verify with a matching tag" + on, member + "::async_verify", [&] { + Authenticator::async_verify(executor, key, message, tag, counted); + deliver(); + }); + covered(family + "::async_verify with a mismatching tag" + on, member + "::async_verify", [&] { + Authenticator::async_verify(executor, key, message, mismatching, counted); + deliver(); + }); + covered(family + "::async_verify with a short tag" + on, member + "::async_verify", [&] { + Authenticator::async_verify(executor, key, message, short_tag, counted); + deliver(); + }); + std::string const free = "single_use_key_authentication::"; + covered(family + " " + free + "async_authenticate" + on, free + "async_authenticate", [&] { + single_use_key_authentication::async_authenticate(executor, key, message, + counted); + deliver(); + }); + covered(family + " " + free + "async_authenticate with a short key" + on, + free + "async_authenticate", [&] { + single_use_key_authentication::async_authenticate( + executor, short_key, message, counted); + deliver(); + }); + covered(family + " " + free + "async_verify with a matching tag" + on, free + "async_verify", + [&] { + single_use_key_authentication::async_verify(executor, key, message, + tag, counted); + deliver(); + }); + covered(family + " " + free + "async_verify with a mismatching tag" + on, free + "async_verify", + [&] { + single_use_key_authentication::async_verify(executor, key, message, + mismatching, counted); + deliver(); + }); + covered(family + " " + free + "async_verify with a short tag" + on, free + "async_verify", [&] { + single_use_key_authentication::async_verify(executor, key, message, + short_tag, counted); + deliver(); + }); + BOOST_TEST_EQ(completions, 10); +} + +/** + * Every function of a single-use key authenticator (design D16): the static `authenticate`, a key + * of the wrong size included, and the static `verify`, with a matching and a mismatching tag and a + * tag of the wrong size; then the free forms `single_use_key_authentication::authenticate` and + * `verify` that call them, the same calls; then their asynchronous forms + * (`cover_async_single_use_key_authenticator`). The first guard each enters is its own. + * + * @tparam Authenticator `authenticators::poly1305`. + * @param family The family's name, as the public alias spells it. + * @param backend The backend's name. + */ +template +void cover_single_use_key_authenticator(std::string const& family, std::string const& backend) { + namespace single_use_key_authentication = webcpp::crypto::single_use_key_authentication; + std::string const on = " on " + backend; + auto const key = coverage_key(); + auto const short_key = std::span(key).first(Authenticator::key_size - 1); + std::array message{}; + message.fill(0x2d); + auto const made = Authenticator::authenticate(key, message); + if (!BOOST_TEST(made.has_value())) { + return; + } + auto const tag = *made; + auto mismatching = tag; + mismatching.data()[0] ^= 1U; + auto const short_tag = std::span(tag.data(), Authenticator::tag_size - 1); + std::string const member = "authenticators::" + family; + covered(family + "::authenticate" + on, member + "::authenticate", + [&] { BOOST_TEST(Authenticator::authenticate(key, message).has_value()); }); + covered(family + "::authenticate with a short key" + on, member + "::authenticate", [&] { + BOOST_TEST(Authenticator::authenticate(short_key, message).error() == + webcpp::crypto::error::invalid_key_size); + }); + covered(family + "::verify with a matching tag" + on, member + "::verify", + [&] { BOOST_TEST(Authenticator::verify(key, message, tag).has_value()); }); + covered(family + "::verify with a mismatching tag" + on, member + "::verify", [&] { + BOOST_TEST(Authenticator::verify(key, message, mismatching).error() == + webcpp::crypto::error::authentication_failed); + }); + covered(family + "::verify with a short tag" + on, member + "::verify", [&] { + BOOST_TEST(Authenticator::verify(key, message, short_tag).error() == + webcpp::crypto::error::invalid_tag_size); + }); + covered(family + " single_use_key_authentication::authenticate" + on, + "single_use_key_authentication::authenticate", [&] { + BOOST_TEST(single_use_key_authentication::authenticate(key, message) + .has_value()); + }); + covered(family + " single_use_key_authentication::authenticate with a short key" + on, + "single_use_key_authentication::authenticate", [&] { + BOOST_TEST( + single_use_key_authentication::authenticate(short_key, message) + .error() == webcpp::crypto::error::invalid_key_size); + }); + covered(family + " single_use_key_authentication::verify with a matching tag" + on, + "single_use_key_authentication::verify", [&] { + BOOST_TEST(single_use_key_authentication::verify(key, message, tag) + .has_value()); + }); + covered(family + " single_use_key_authentication::verify with a mismatching tag" + on, + "single_use_key_authentication::verify", [&] { + BOOST_TEST( + single_use_key_authentication::verify(key, message, mismatching) + .error() == webcpp::crypto::error::authentication_failed); + }); + covered( + family + " single_use_key_authentication::verify with a short tag" + on, + "single_use_key_authentication::verify", [&] { + BOOST_TEST(single_use_key_authentication::verify(key, message, short_tag) + .error() == webcpp::crypto::error::invalid_tag_size); + }); + cover_async_single_use_key_authenticator(family, on); +} + } // namespace webcpp::test #endif // WEBCPP_TEST_CRYPTO_SUPPORT_TIMING_COVERAGE_HPP diff --git a/test/timing_coverage_bearssl_test.cpp b/test/timing_coverage_bearssl_test.cpp index b17eb7a..a26ca46 100644 --- a/test/timing_coverage_bearssl_test.cpp +++ b/test/timing_coverage_bearssl_test.cpp @@ -49,6 +49,7 @@ #include #include #include +#include #include #include #include @@ -109,6 +110,7 @@ void cover_ciphers() { "aes256_gcm", "bearssl"); webcpp::test::cover_aead>("chacha20_poly1305", "bearssl"); + webcpp::test::cover_stream_cipher>("chacha20", "bearssl"); } // P-256: the key pair's from_secret and generate, the public key's from_bytes and diff --git a/test/timing_coverage_openssl_test.cpp b/test/timing_coverage_openssl_test.cpp index 8a46f06..fc1e0bc 100644 --- a/test/timing_coverage_openssl_test.cpp +++ b/test/timing_coverage_openssl_test.cpp @@ -21,11 +21,18 @@ // - ChaCha20-Poly1305, aead: from_key, seal, open; the free crypto::from_key, // secret_key_encryption::aead::seal and secret_key_encryption::aead::open; the asynchronous // async_from_key, async_seal and async_open, member and free. +// - ChaCha20, chacha20: from_key, apply_keystream, the free forms and the asynchronous forms. +// - Poly1305, authenticators::poly1305: authenticate, a short key included, and verify, a matching, +// a mismatching and a short tag included; the free single_use_key_authentication::authenticate +// and verify; the asynchronous async_authenticate and async_verify, static and free, the same +// calls. #include "support/timing_seam.hpp" +#include #include #include +#include #include #include #include @@ -39,7 +46,8 @@ namespace { namespace crypto = webcpp::crypto; using crypto::backends::openssl; -// The ciphers: the AES block cipher, AES-GCM and ChaCha20-Poly1305. +// The ciphers and the authenticator: the AES block cipher, AES-GCM, ChaCha20-Poly1305, ChaCha20 +// and Poly1305. void cover_ciphers() { webcpp::test::cover_aes>("aes128", "openssl"); webcpp::test::cover_aes>("aes192", "openssl"); @@ -58,6 +66,9 @@ void cover_ciphers() { "aes256_gcm", "openssl"); webcpp::test::cover_aead>("chacha20_poly1305", "openssl"); + webcpp::test::cover_stream_cipher>("chacha20", "openssl"); + webcpp::test::cover_single_use_key_authenticator>( + "poly1305", "openssl"); } } // namespace diff --git a/test/timing_coverage_sodium_test.cpp b/test/timing_coverage_sodium_test.cpp index 5db8c16..43e5064 100644 --- a/test/timing_coverage_sodium_test.cpp +++ b/test/timing_coverage_sodium_test.cpp @@ -16,6 +16,14 @@ // - ChaCha20-Poly1305, its original form and XChaCha20-Poly1305, aead: from_key, seal, open; the // free crypto::from_key, secret_key_encryption::aead::seal and secret_key_encryption::aead::open; // the asynchronous async_from_key, async_seal and async_open, member and free. +// - ChaCha20, basic_chacha20: from_key, apply_keystream, a short key, a short nonce and an +// overflowing counter included; the free crypto::from_key and +// unauthenticated_encryption::apply_keystream; the asynchronous async_from_key and +// async_apply_keystream, member and free. +// - Poly1305, authenticators::poly1305: authenticate, a short key included, and verify, a matching, +// a mismatching and a short tag included; the free single_use_key_authentication::authenticate +// and single_use_key_authentication::verify; the asynchronous async_authenticate and +// async_verify, static and free, the same calls. // - Both secret boxes, basic_secretbox: from_key, seal, open; the free crypto::from_key and the // box forms secret_key_encryption::seal and secret_key_encryption::open; the asynchronous // async_from_key, async_seal and async_open, member and free. @@ -57,7 +65,9 @@ #include #include +#include #include +#include #include #include #include @@ -307,7 +317,10 @@ void cover_secretbox(std::string const& family) { cover_async_secretbox_from_key(family, on); } -/** ChaCha20-Poly1305, its original form, XChaCha20-Poly1305 and both secret boxes. */ +/** + * ChaCha20-Poly1305, its original form, XChaCha20-Poly1305, both secret boxes, ChaCha20 and + * Poly1305. + */ void cover_ciphers() { webcpp::test::cover_aead>("chacha20_poly1305", "sodium"); @@ -318,6 +331,9 @@ void cover_ciphers() { cover_secretbox>("secretbox"); cover_secretbox>( "secretbox_xchacha20poly1305"); + webcpp::test::cover_stream_cipher>("chacha20", "sodium"); + webcpp::test::cover_single_use_key_authenticator>( + "poly1305", "sodium"); } // --------------------------------------------------------------------------------------------- diff --git a/test/user_globals_test.cpp b/test/user_globals_test.cpp index 3aab9ce..509077d 100644 --- a/test/user_globals_test.cpp +++ b/test/user_globals_test.cpp @@ -146,6 +146,7 @@ extern int const encrypt; // crypto's public headers by name: those includes, with every backend linked, // but the formats headers, and the headers it leaves out. #include +#include #include #include #include @@ -155,6 +156,7 @@ extern int const encrypt; #include #include #include +#include #include #include #include @@ -180,7 +182,9 @@ extern int const encrypt; #include #include #include +#include #include +#include int main() { return 0;