diff --git a/AGENTS.md b/AGENTS.md index 7664c986..5b8bddf4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,10 +38,11 @@ specific to crypto. ## Cautions -- An algorithm type does every guard; a backend's header supplies only the six traits of +- An algorithm type does every guard; a backend's header supplies only the eight traits of `detail/engines.hpp` (`block_state`, `block_engine`, `gcm_state`, `gcm_engine`, `aead_state`, - `aead_engine`), the two of `detail/p_curves.hpp` per P-curve (`p_curve_state`, - `p_curve_engine`) and, for the other curves and `hybrid`, the functions of its own header. + `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. - A new public function that calls a backend holds `detail::timing_guard` as its first statement (it sets arm64's DIT for the call, `detail/timing.hpp`) and joins the coverage test of its backend, `test/timing_coverage__test.cpp`, which checks through the seam diff --git a/README.md b/README.md index c2dc799a..c19d32ed 100644 --- a/README.md +++ b/README.md @@ -5,22 +5,27 @@ target [webcpp](https://github.com/webcpporg/webcpp) has: native (Linux, macOS, MSVC), wasip2, wasip3 and Emscripten. - `webcpp::crypto`: a `random_device` that reads the operating system's or the browser's - generator, a constant-time `equal` for tags and MACs, and `error`, every failure's value. + generator, `constant_time_equal` for tags and MACs, `erase_secret`, which zeroes a buffer of + the program's with stores the optimiser keeps, and `error`, every failure's value. - `webcpp::crypto::ciphers`: AES-GCM (`gcm`, `aes128_gcm`, `aes256_gcm`) with keys of 16, 24 and - 32 bytes, the AES block cipher (`aes128`, `aes192`, `aes256`), the ChaCha20-Poly1305 AEADs, and - NaCl's and libsodium's secret boxes (`secretbox`, `secretbox_xchacha20poly1305`). + 32 bytes, the AES block cipher (`aes128`, `aes192`, `aes256`) and the ChaCha20-Poly1305 AEADs. +- `webcpp::crypto::secret_key_encryption`: NaCl's and libsodium's secret boxes (`secretbox`, + `secretbox_xchacha20poly1305`), and the AEAD contract, `aead::cipher` and the free + `aead::seal` and `aead::open` of every AEAD. - `webcpp::crypto::curves::secp256k1`: BIP 340 Schnorr and ECDSA signatures, their verification, ECDH, ECDSA's strict DER and low-S forms, and the x-only tweak. - `webcpp::crypto::curves::ed25519`: Ed25519 signatures (RFC 8032) with strict verification, the - X25519 secret key of a key pair, and Ed25519ph over SHA-512 for a message given in pieces. + conversion of a key pair and of a public key to X25519's typed keys, `to_x25519()`, and + Ed25519ph over SHA-512 for a message given in pieces. - `webcpp::crypto::curves::x25519`: X25519 key agreement (RFC 7748), refusing an all-zero shared - secret, `curves::ed25519::to_x25519_public` for a peer known by its Ed25519 key, and - `kx_keypair`, libsodium's `crypto_kx`, a session key for each direction of a client and a server. + secret, with a peer known by its Ed25519 key once its `to_x25519()` converts it. - Ed25519's and X25519's keys in RFC 8410's SPKI and PKCS#8, as OpenSSL and WebCrypto write them, and `webcpp::crypto::pem` for their PEM text, each decoded strictly. -- `webcpp::crypto::hybrid`: NaCl's and libsodium's boxes between two key pairs (`box`, - `box_xchacha20poly1305`), refusing a peer key of small order, and sealed boxes (`sealed_box`), - anonymous encryption to a public key. +- `webcpp::crypto::public_key_encryption`: NaCl's and libsodium's boxes between two key pairs + (`box`, `box_xchacha20poly1305`), refusing a peer key of small order, and sealed boxes + (`sealed_box`), anonymous encryption to a public key. +- `webcpp::crypto::key_exchange`: `kx_keypair`, libsodium's `crypto_kx`, a session key for each + direction of a client and a server. The algorithms are those of widely used, reviewed C libraries, each a backend that a program names in its own Jamfile and that webcpp builds from its sources: BearSSL diff --git a/bench/operations.hpp b/bench/operations.hpp index ebff8c18..16e62201 100644 --- a/bench/operations.hpp +++ b/bench/operations.hpp @@ -12,7 +12,8 @@ // of what it sealed, a verification of what it signed, both sides of an agreement). An operation // the library refuses ends the program: a figure measured on a failure would be a wrong one. // `operation` names what is measured, the text crypto.json's family states (bench/collect.py -// checks that the two agree). A seal repeats under one key and one IV: a measurement, never a use. +// checks that the two agree). A seal repeats under one key and one nonce: a measurement, never a +// use. #ifndef WEBCPP_CRYPTO_BENCH_OPERATIONS_HPP #define WEBCPP_CRYPTO_BENCH_OPERATIONS_HPP @@ -103,7 +104,7 @@ class block_encryption { explicit block_encryption(std::uint8_t seed) : block_(filled(static_cast(seed + 1U))), - cipher_(take(Cipher::make(filled(seed)), "make")) {} + cipher_(take(Cipher::from_key(filled(seed)), "from_key")) {} std::uint8_t run() { if (!cipher_.encrypt(block_)) { @@ -127,28 +128,28 @@ class block_encryption { Cipher cipher_; }; -// The seal of 16 KiB, in place, without additional data. +// The seal of 16 KiB, in place, without associated data. template class aead_seal { public: static constexpr std::string_view operation = "seal of 16 KiB, 256-bit key"; explicit aead_seal(std::uint8_t seed) - : iv_(filled(static_cast(seed + 2U))), + : nonce_(filled(static_cast(seed + 2U))), data_(filled(seed)), - aead_(take(Aead::make(filled(seed)), "make")) {} + aead_(take(Aead::from_key(filled(seed)), "from_key")) {} - std::uint8_t run() { return take(aead_.seal(iv_, {}, data_), "seal").data()[0]; } + std::uint8_t run() { return take(aead_.seal(nonce_, {}, data_), "seal").data()[0]; } bool check() { auto const plain = data_; - auto const tag = take(aead_.seal(iv_, {}, data_), "seal"); + auto const tag = take(aead_.seal(nonce_, {}, data_), "seal"); bool const changed = data_ != plain; - return changed && aead_.open(iv_, {}, data_, tag).has_value() && data_ == plain; + return changed && aead_.open(nonce_, {}, data_, tag).has_value() && data_ == plain; } private: - std::array iv_{}; + std::array nonce_{}; std::array data_{}; Aead aead_; }; @@ -182,11 +183,11 @@ class secp256k1 { explicit secp256k1(std::uint8_t seed) : message_(filled<32>(static_cast(seed + 3U))), - key_(take(curves::secp256k1::basic_keypair::make( + key_(take(curves::secp256k1::basic_keypair::from_secret( filled<32>(static_cast(seed | 1U))), - "make")) {} + "from_secret")) {} - std::uint8_t run() { return take(key_.sign(schnorr, message_, aux_), "sign")[0]; } + std::uint8_t run() { return take(key_.sign(schnorr, message_, aux_), "sign").bytes()[0]; } bool check() { auto const signature = take(key_.sign(schnorr, message_, aux_), "sign"); @@ -209,12 +210,12 @@ class secp256k1_ecdh_x { "x coordinate of the ECDH shared point with a peer's public key"; explicit secp256k1_ecdh_x(std::uint8_t seed) - : key_(take(curves::secp256k1::basic_keypair::make( + : key_(take(curves::secp256k1::basic_keypair::from_secret( filled<32>(static_cast(seed | 1U))), - "make")), - peer_(take(curves::secp256k1::basic_keypair::make( + "from_secret")), + peer_(take(curves::secp256k1::basic_keypair::from_secret( filled<32>(static_cast(seed + 6U))), - "make")), + "from_secret")), peer_public_(take(peer_.public_key(), "public_key")) {} std::uint8_t run() { @@ -245,9 +246,9 @@ class secp256k1_recover { explicit secp256k1_recover(std::uint8_t seed) : hash_(filled<32>(static_cast(seed + 3U))), - key_(take(curves::secp256k1::basic_keypair::make( + key_(take(curves::secp256k1::basic_keypair::from_secret( filled<32>(static_cast(seed | 1U))), - "make")), + "from_secret")), signature_(take(key_.sign(ecdsa_sha256_recoverable, prehashed{hash_}), "sign")) {} std::uint8_t run() { @@ -267,7 +268,7 @@ class secp256k1_recover { private: std::array hash_{}; curves::secp256k1::basic_keypair key_; - std::array signature_{}; + curves::secp256k1::recoverable_signature signature_; }; // BIP 324's shared secret of a key pair and a peer, each known by its ElligatorSwift encoding. @@ -278,12 +279,12 @@ class secp256k1_ellswift { "BIP 324 shared secret of two ElligatorSwift encodings"; explicit secp256k1_ellswift(std::uint8_t seed) - : key_(take(curves::secp256k1::basic_keypair::make( + : key_(take(curves::secp256k1::basic_keypair::from_secret( filled<32>(static_cast(seed | 1U))), - "make")), - peer_(take(curves::secp256k1::basic_keypair::make( + "from_secret")), + peer_(take(curves::secp256k1::basic_keypair::from_secret( filled<32>(static_cast(seed + 6U))), - "make")), + "from_secret")), own_encoding_( take(curves::secp256k1::ellswift_create(key_, filled<32>(seed)), "ellswift_create")), peer_encoding_(take(curves::secp256k1::ellswift_create( @@ -327,15 +328,15 @@ class secp256k1_musig { explicit secp256k1_musig(std::uint8_t seed) : message_(filled<32>(static_cast(seed + 3U))), - first_(take(curves::secp256k1::basic_keypair::make( + first_(take(curves::secp256k1::basic_keypair::from_secret( filled<32>(static_cast(seed | 1U))), - "make")), - second_(take(curves::secp256k1::basic_keypair::make( + "from_secret")), + second_(take(curves::secp256k1::basic_keypair::from_secret( filled<32>(static_cast(seed + 6U))), - "make")), + "from_secret")), signers_key_(aggregate(first_, second_, space_)) {} - std::uint8_t run() { return sign()[0]; } + std::uint8_t run() { return sign().bytes()[0]; } bool check() { return crypto::verify(schnorr, sign(), message_, signers_key_.xonly_public_key()) @@ -355,10 +356,12 @@ class secp256k1_musig { return take(curves::secp256k1::musig::key_aggregate(keys, space), "key_aggregate"); } - std::array sign() { + curves::secp256k1::schnorr_signature sign() { namespace musig = curves::secp256k1::musig; - auto first_nonce = take(musig::nonce_gen(first_, signers_key_, message_), "nonce_gen"); - auto second_nonce = take(musig::nonce_gen(second_, signers_key_, message_), "nonce_gen"); + auto first_nonce = + take(musig::generate_nonce(first_, signers_key_, message_), "generate_nonce"); + auto second_nonce = + take(musig::generate_nonce(second_, signers_key_, message_), "generate_nonce"); std::array const nonces{first_nonce.public_part, second_nonce.public_part}; auto const nonce_sum = take(musig::nonce_aggregate(nonces, space_), "nonce_sum"); @@ -390,15 +393,15 @@ class secp256k1_silent_payments { static constexpr std::string_view operation = "a silent payment output for one recipient"; explicit secp256k1_silent_payments(std::uint8_t seed) - : scan_(take(curves::secp256k1::basic_keypair::make( + : scan_(take(curves::secp256k1::basic_keypair::from_secret( filled<32>(static_cast(seed | 1U))), - "make")), - spend_key_(public_of(take(curves::secp256k1::basic_keypair::make( + "from_secret")), + spend_key_(public_of(take(curves::secp256k1::basic_keypair::from_secret( filled<32>(static_cast(seed + 6U))), - "make"))), - input_(take(curves::secp256k1::basic_keypair::make( + "from_secret"))), + input_(take(curves::secp256k1::basic_keypair::from_secret( filled<32>(static_cast(seed + 8U))), - "make")), + "from_secret")), outpoint_(filled(seed)) {} std::uint8_t run() { return send()[0]; } @@ -410,9 +413,9 @@ class secp256k1_silent_payments { alignas(std::max_align_t) std::array summary_space{}; - auto const summary = take(silent_payments::make_prevouts_summary( + auto const summary = take(silent_payments::make_previous_outputs_summary( outpoint_, {}, input_keys, summary_space), - "make_prevouts_summary"); + "make_previous_outputs_summary"); std::array found{}; alignas(std::max_align_t) std::array scan_space{}; @@ -458,11 +461,13 @@ class p256 { explicit p256(std::uint8_t seed) : digest_(filled<32>(static_cast(seed + 3U))), - key_(take(curves::p256::basic_keypair::make( + key_(take(curves::p256::basic_keypair::from_secret( filled<32>(static_cast(seed | 1U))), - "make")) {} + "from_secret")) {} - std::uint8_t run() { return take(key_.sign(ecdsa_sha256, prehashed{digest_}), "sign")[0]; } + std::uint8_t run() { + return take(key_.sign(ecdsa_sha256, prehashed{digest_}), "sign").bytes()[0]; + } bool check() { auto const signature = take(key_.sign(ecdsa_sha256, prehashed{digest_}), "sign"); @@ -487,20 +492,22 @@ class p256_verify_ecdsa { explicit p256_verify_ecdsa(std::uint8_t seed) : digest_(filled<32>(static_cast(seed + 3U))), - key_(take(curves::p256::basic_keypair::make( + key_(take(curves::p256::basic_keypair::from_secret( filled<32>(static_cast(seed | 1U))), - "make")), + "from_secret")), public_key_(take(key_.public_key(), "public_key")), signature_(take(key_.sign(ecdsa_sha256, prehashed{digest_}), "sign")) {} std::uint8_t run() { take(crypto::verify(ecdsa_sha256, signature_, prehashed{digest_}, public_key_), "verify"); - return signature_[0]; + return signature_.bytes()[0]; } bool check() { - auto other = signature_; - other[63] ^= 1U; + auto other_bytes = signature_.bytes(); + other_bytes[63] ^= 1U; + auto const other = + take(curves::p256::ecdsa_signature::from_bytes(other_bytes), "from_bytes"); return crypto::verify(ecdsa_sha256, signature_, prehashed{digest_}, public_key_) .has_value() && !crypto::verify(ecdsa_sha256, other, prehashed{digest_}, public_key_).has_value(); @@ -510,7 +517,7 @@ class p256_verify_ecdsa { std::array digest_{}; curves::p256::basic_keypair key_; curves::p256::basic_public_key public_key_; - std::array signature_{}; + curves::p256::ecdsa_signature signature_; }; // The x coordinate of the ECDH shared point of a P-256 key pair and a peer's public key, agree. @@ -521,12 +528,12 @@ class p256_ecdh_x { "x coordinate of the ECDH shared point with a peer's public key"; explicit p256_ecdh_x(std::uint8_t seed) - : key_(take(curves::p256::basic_keypair::make( + : key_(take(curves::p256::basic_keypair::from_secret( filled<32>(static_cast(seed | 1U))), - "make")), - peer_(take(curves::p256::basic_keypair::make( + "from_secret")), + peer_(take(curves::p256::basic_keypair::from_secret( filled<32>(static_cast(seed + 6U))), - "make")), + "from_secret")), peer_public_(take(peer_.public_key(), "public_key")) {} std::uint8_t run() { @@ -555,9 +562,10 @@ class ed25519 { explicit ed25519(std::uint8_t seed) : message_(filled<32>(static_cast(seed + 4U))), - key_(take(curves::ed25519::basic_keypair::make(filled<32>(seed)), "make")) {} + key_(take(curves::ed25519::basic_keypair::from_secret(filled<32>(seed)), + "from_secret")) {} - std::uint8_t run() { return take(key_.sign(eddsa, message_), "sign")[0]; } + std::uint8_t run() { return take(key_.sign(eddsa, message_), "sign").bytes()[0]; } bool check() { auto const signature = take(key_.sign(eddsa, message_), "sign"); @@ -572,35 +580,36 @@ class ed25519 { curves::ed25519::basic_keypair key_; }; -// An X25519 agreement of a secret key with a peer's public key. +// An X25519 agreement of a key pair with a peer's public key. template class x25519 { public: static constexpr std::string_view operation = "agreement of a secret key and a public key"; - explicit x25519(std::uint8_t seed) { - secret_.fill(seed); - peer_secret_.fill(static_cast(seed + 5U)); - peer_public_ = take(curves::x25519::public_key(peer_secret_), "public_key"); - } + explicit x25519(std::uint8_t seed) + : key_(take(curves::x25519::basic_keypair::from_secret(filled<32>(seed)), + "from_secret")), + peer_key_(take(curves::x25519::basic_keypair::from_secret( + filled<32>(static_cast(seed + 5U))), + "from_secret")), + peer_public_(take(peer_key_.public_key(), "public_key")) {} std::uint8_t run() { - auto const shared = take(curves::x25519::agree(secret_, peer_public_), "agree"); + auto const shared = take(key_.agree(peer_public_), "agree"); return shared.bytes()[0]; } bool check() { - auto const own_public = take(curves::x25519::public_key(secret_), "public_key"); - auto const shared = take(curves::x25519::agree(secret_, peer_public_), "agree"); - auto const peer_shared = - take(curves::x25519::agree(peer_secret_, own_public), "agree"); + auto const own_public = take(key_.public_key(), "public_key"); + auto const shared = take(key_.agree(peer_public_), "agree"); + auto const peer_shared = take(peer_key_.agree(own_public), "agree"); return std::ranges::equal(shared.bytes(), peer_shared.bytes()); } private: - std::array secret_{}; - std::array peer_secret_{}; - std::array peer_public_{}; + curves::x25519::basic_keypair key_; + curves::x25519::basic_keypair peer_key_; + curves::x25519::public_key peer_public_; }; } // namespace webcpp::crypto::bench diff --git a/doc/aead.adoc b/doc/aead.adoc index 0ccdda29..401d911c 100644 --- a/doc/aead.adoc +++ b/doc/aead.adoc @@ -13,7 +13,7 @@ Encryption alone does not: with counter mode alone, flipping a bit of a ciphertext flips the same bit of the plaintext, and the receiver cannot tell; a forged "amount" field in an encrypted cookie goes through. *AES-GCM* (Galois/Counter Mode) encrypts with AES in counter mode and computes a 16-byte -*tag* over the ciphertext and over *additional data* that travels in clear +*tag* over the ciphertext and over *associated data* that travels in clear (link:https://en.wikipedia.org/wiki/Galois/Counter_Mode[Wikipedia]; link:https://csrc.nist.gov/pubs/sp/800/38/d/final[NIST SP 800-38D]). Opening recomputes the tag and returns the plaintext only if it matches; on a mismatch @@ -27,22 +27,24 @@ size of `Cipher`, on the backend of `Cipher`, which must export GCM over its own AES: BearSSL or OpenSSL. `aes128_gcm` and `aes256_gcm`, in ``, name it on the default backend, OpenSSL natively and BearSSL on WebAssembly. It is -made with `make(key_bytes)`, and works in place: +made with `from_key(key_bytes)`, and works in place: -* `seal(iv_bytes, additional_data_bytes, data_bytes)` encrypts `data_bytes` +* `seal(nonce_bytes, associated_data_bytes, data_bytes)` encrypts `data_bytes` in place and returns its 16-byte tag, a `boost::hash2::digest<16>`; -* `open(iv_bytes, additional_data_bytes, data_bytes, tag_bytes)` checks the +* `open(nonce_bytes, associated_data_bytes, data_bytes, tag_bytes)` checks the tag and decrypts `data_bytes` in place; -* `begin_seal(iv_bytes, additional_data_bytes)`, `update(data_bytes)` and +* `begin_seal(nonce_bytes, associated_data_bytes)`, `update(data_bytes)` and `result()` seal a message in pieces; * `begin_open`, `authenticate`, `verify`, `decrypt` and `end_open` open a message in pieces, in two passes (<>). -`make`, `seal` and `open` have four forms each, the member and its free form, -synchronous and asynchronous, with the same work, errors and refusals -(<>); the pieces' functions are members alone. An -asynchronous form needs `` and -`/webcpp/asio//asio` in the Jamfile (<>): +`from_key`, `seal` and `open` have four forms each, the member and its free +form, synchronous and asynchronous, with the same work, errors and refusals +(<>); the pieces' functions are members alone. +AES-GCM is a `secret_key_encryption::aead::streaming_cipher`, whose free `seal` +and `open` its header brings (<>). An asynchronous form +needs `` and `/webcpp/asio//asio` in the +Jamfile (<>): .AES-GCM's operations in their four forms [cols="1,3,3",options="header"] @@ -50,28 +52,47 @@ asynchronous form needs `` and | Operation | Synchronous: the member; its free form | Asynchronous: the member; its free form | Make -| `aes256_gcm::make(key_bytes)` + -`crypto::make(key_bytes)` -| `aes256_gcm::async_make(executor, key_bytes, token)` + -`crypto::async_make(executor, key_bytes, token)` +| `aes256_gcm::from_key(key_bytes)` + +`crypto::from_key(key_bytes)` +| `aes256_gcm::async_from_key(executor, key_bytes, token)` + +`crypto::async_from_key(executor, key_bytes, token)` | Seal -| `aead.seal(iv, additional_data, data)` + -`crypto::seal(aead, iv, additional_data, data)` -| `aead.async_seal(executor, iv, additional_data, data, token)` + -`crypto::async_seal(executor, aead, iv, additional_data, data, token)` +| `aead.seal(nonce, associated_data, data)` + +`secret_key_encryption::aead::seal(aead, nonce, associated_data, data)` +| `aead.async_seal(executor, nonce, associated_data, data, token)` + +`secret_key_encryption::aead::async_seal(executor, aead, nonce, associated_data, data, token)` | Open -| `aead.open(iv, additional_data, data, tag)` + -`crypto::open(aead, iv, additional_data, data, tag)` -| `aead.async_open(executor, iv, additional_data, data, tag, token)` + -`crypto::async_open(executor, aead, iv, additional_data, data, tag, token)` +| `aead.open(nonce, associated_data, data, tag)` + +`secret_key_encryption::aead::open(aead, nonce, associated_data, data, tag)` +| `aead.async_open(executor, nonce, associated_data, data, tag, token)` + +`secret_key_encryption::aead::async_open(executor, aead, nonce, associated_data, data, tag, token)` |=== +*On the web and natively.* AES-GCM is the one AEAD browsers' WebCrypto has. +On a native backend, and on every backend of this version, its four forms all +run, the asynchronous ones completing through the event loop. On the browser's +backend, once it is built (<>), its seal and open are +asynchronous alone, and each synchronous form stops the build naming its +`async_` form. The other AEADs of `ciphers` and the boxes have their +asynchronous forms too, on a native backend, so that a program that seals in +an event loop writes one shape for every AEAD; on the browser's backend no form +of them runs, synchronous or asynchronous, and each stops the build with one +text: + +[listing] +---- +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. +---- + include::generated/backends-gcm.adoc[] *Example.* A program stores users' API tokens in a database. Each token is -sealed under a storage key with the user's id as additional data, so that the +sealed under a storage key with the user's id as associated data, so that the row opens only for that user: a row copied onto another user's record does not open. @@ -111,18 +132,18 @@ include::{examples}/aes256_gcm_bearssl.expected[] Each rule is how crypto behaves, and what it asks of the program. -* *Never reuse an IV under one key.* Two messages under one key and one IV +* *Never reuse a nonce under one key.* Two messages under one key and one nonce reveal the XOR of their plaintexts, and let an attacker recover the authentication key and forge tags for every later message (link:https://csrc.nist.gov/csrc/media/projects/block-cipher-techniques/documents/bcm/comments/800-38-series-drafts/gcm/joux_comments.pdf[Joux, 2006]; link:https://eprint.iacr.org/2016/475[Boeck et al., 2016]; link:https://cwe.mitre.org/data/definitions/323.html[CWE-323]). AES-GCM does not resist this misuse: the program must prevent it. -* *The usage limit.* With random IVs, or IVs other than 12 bytes, at most 2^32^ -messages are sealed under one key (NIST SP 800-38D, section 8.3). A counter IV -(message 0, 1, 2 ...) is safe until the counter repeats, which it must never -do, a restart included. Rotate the key before either limit. -* *IVs of 1 to 128 bytes; 12 recommended.* An IV of another size than 12 +* *The usage limit.* With random nonces, or nonces other than 12 bytes, at +most 2^32^ messages are sealed under one key (NIST SP 800-38D, section 8.3). A +counter nonce (message 0, 1, 2 ...) is safe until the counter repeats, which it +must never do, a restart included. Rotate the key before either limit. +* *Nonces of 1 to 128 bytes; 12 recommended.* A nonce of another size than 12 bytes is hashed into the first counter block, as every backend does; the cap of 128 bytes is OpenSSL's, applied on every backend so that a call succeeds or fails the same way everywhere. @@ -138,7 +159,7 @@ tag in one pass; when the tag does not match, crypto zeroes the whole of `update` that fails in the backend zeroes its data too, so that no message without a tag can be sent. A caller who needs the ciphertext after a failure keeps a copy. A guard's refusal -(`invalid_state`, `invalid_iv_size`, `invalid_tag_size`, `message_too_long`) +(`invalid_state`, `invalid_nonce_size`, `invalid_tag_size`, `message_too_long`) comes before any work and leaves `data_bytes` untouched. Whether the tag matched is the one value derived from the key that crypto treats as public (<>). @@ -169,21 +190,21 @@ itself, which come after the guards: |=== |Condition |Error -|`make`: a key of another size than `key_size` |`invalid_key_size` +|`from_key`: a key of another size than `key_size` |`invalid_key_size` |any other function: the object was moved from |`invalid_state` |`begin_seal` or `begin_open` while a message is in progress; `update` or `result` outside a seal; `authenticate` or `verify` outside the open's first pass; `decrypt` or `end_open` before `verify` matched |`invalid_state` -|an empty IV, or one longer than `max_iv_size`, 128 bytes |`invalid_iv_size` +|an empty nonce, or one longer than `max_nonce_size`, 128 bytes |`invalid_nonce_size` |`open` or `verify`: a tag of another size than 16 |`invalid_tag_size` |a message longer than `max_message_size`, 2^36^ - 32 bytes, in one call or -summed over `update` or `authenticate`, or additional data longer than 2^61^ - +summed over `update` or `authenticate`, or associated data longer than 2^61^ - 1 bytes (NIST SP 800-38D, section 5.2.1.1) |`message_too_long` |`decrypt`: more bytes than `authenticate` read; `end_open`: fewer |`invalid_input_size` |`open` or `verify`: the tag does not match |`authentication_failed` |the backend fails where it should not |`backend_failure` -|`make`: OpenSSL cannot allocate its context |`errc::not_enough_memory` +|`from_key`: OpenSSL cannot allocate its context |`errc::not_enough_memory` |=== [#crypto-gcm-arm] @@ -204,8 +225,8 @@ machine. A server on ARM keeps the default and links `/webcpp/crypto//openssl` ==== Encrypting what does not fit in memory A 2 GB video before an upload, or a log as it is written, cannot be held whole. -`begin_seal` takes the IV and the additional data, `update` encrypts each piece -in place as it arrives, and `result` returns the tag at the end. The object +`begin_seal` takes the nonce and the associated data, `update` encrypts each +piece in place as it arrives, and `result` returns the tag at the end. The object refuses another message while one is in progress, and any error abandons the message: its pieces have no tag and are not to be sent. @@ -217,8 +238,8 @@ include::{examples}/sealed_records.cpp[tag=incremental,indent=0] What is sealed in pieces is opened whole, or, when the receiver can read the ciphertext twice, in two passes (<>). To open a stream piece by piece as it arrives, split it into *records*, each sealed alone -with its own IV, and with two things -in its additional data: its number, so that a record cannot be reordered or +with its own nonce, and with two things +in its associated data: its number, so that a record cannot be reordered or replayed at another position, and a flag that is 1 for the last record and 0 for every other, so that a stream cut after any record does not open: the receiver opens the last record it got as the last, and a record that was not @@ -226,15 +247,15 @@ sealed as the last fails. The STREAM construction binds the same two (link:https://eprint.iacr.org/2015/189[Hoang, Reyhanitabar, Rogaway and Vizár, 2015]). -The record's number is its IV, so *each stream has a key of its own*. Every +The record's number is its nonce, so *each stream has a key of its own*. Every stream numbers its records from 0: two files sealed under one key would both -seal record 0 with the same IV, which reveals the XOR of the two records and +seal record 0 with the same nonce, which reveals the XOR of the two records and lets an attacker forge tags under that key (<>), and a record of one file could be spliced into the other at the same position. The example draws a fresh random key per stream. A program that keeps one long-lived storage key derives the stream's key from it, for example with HKDF of the storage key and a random salt of 32 bytes stored in the file's header -(link:https://www.rfc-editor.org/rfc/rfc5869[RFC 5869]); or it makes the IV's +(link:https://www.rfc-editor.org/rfc/rfc5869[RFC 5869]); or it makes the nonce's first 8 bytes a random identifier drawn for the stream and its last 4 the record number, and counts every record against the key's usage limit of 2^32^ messages, since the identifiers are random. @@ -258,7 +279,7 @@ Never send the pieces of an abandoned message. A message sealed whole, too large to hold in memory, is opened in two passes when its ciphertext lies where the program can read it twice: a file on the -program's own disk. `begin_open` takes the IV and the additional data; +program's own disk. `begin_open` takes the nonce and the associated data; `authenticate` reads each piece of the ciphertext and writes none of it; `verify` checks the tag. Only once the tag matched does `decrypt` turn the same pieces into plaintext, in place, and `end_open` ends the message. No byte of @@ -282,8 +303,8 @@ backends compute GCM's hash only while they decrypt. An open in two passes costs about two one-shot opens. *The second pass reads the bytes the first read.* GCM's keystream is the key's -and the IV's alone: a byte changed between the passes is decrypted without ever -being authenticated, and whoever changes it chooses the change in the +and the nonce's alone: a byte changed between the passes is decrypted without +ever being authenticated, and whoever changes it chooses the change in the plaintext, bit for bit. Only the program can keep the bytes the same: it reads a file that no other process writes during the open, never a file another party can reach. The object checks only the length: `decrypt` refuses more diff --git a/doc/async.adoc b/doc/async.adoc index db80e3a7..380ddcc2 100644 --- a/doc/async.adoc +++ b/doc/async.adoc @@ -18,8 +18,9 @@ and the answer arrives later. A program written for it, and a program that wants one shape for its code on every target, needs the same shape from the library. -`` gives the functions of crypto that WebCrypto has -an asynchronous form in webcpp::asio's model: each returns at once, and its +`` gives the functions of crypto that WebCrypto has, +and, on a native backend, the seal and open of every AEAD and box, an +asynchronous form in webcpp::asio's model: each returns at once, and its completion arrives later through the event loop, with a `boost::system::error_code` and, for an operation that returns a value, the value. Each takes any completion token: a callback, `use_awaitable` for @@ -39,30 +40,39 @@ its own, and the handler would run off the program's loop. | Algorithm | Functions | Completion | AES-GCM (<>) -| `async_make(executor, key, token)`, `async_seal(executor, aead, iv, additional_data, data, token)`, `async_open(executor, aead, iv, additional_data, data, tag, token)` -| `void(error_code, Gcm)` for `async_make`, `void(error_code, tag)` for `async_seal`, `void(error_code)` for `async_open` +| `async_from_key(executor, key, token)`, `secret_key_encryption::aead::async_seal(executor, aead, nonce, associated_data, data, token)`, `secret_key_encryption::aead::async_open(executor, aead, nonce, associated_data, data, tag, token)` +| `void(error_code, Gcm)` for `async_from_key`, `void(error_code, tag)` for `async_seal`, `void(error_code)` for `async_open` + +| ChaCha20-Poly1305 and its forms (<>), on a native backend +| `async_from_key(executor, key, token)`, `secret_key_encryption::aead::async_seal` and `async_open`, as AES-GCM's +| as AES-GCM's + +| The secret boxes (<>) and crypto_boxes (<>), on a native backend +| `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` | Ed25519 (<>) -| `async_make(executor, seed, token)`, `async_generate(executor, token)`, `async_sign(executor, key_pair, crypto::eddsa, message, token)`, `async_verify(executor, crypto::eddsa, signature, message, public_key, token)`, the policy optional before the token -| `void(error_code, Keypair)` for `async_make` and `async_generate`, `void(error_code, signature)` for `async_sign`, `void(error_code)` for `async_verify` +| `async_from_secret(executor, seed, token)`, `async_generate(executor, token)`, `async_sign(executor, key_pair, crypto::eddsa, message, token)`, `async_verify(executor, crypto::eddsa, signature, message, public_key, token)`, the policy optional before the token; on a native backend the same under `crypto::eddsa_prehashed` with `+crypto::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` | X25519 (<>) -| `async_agree(executor, secret_key, peer_public_key, token)` -| `void(error_code, secret<32>)` +| `async_from_secret(executor, secret_key, token)`, `async_generate(executor, token)`, `async_agree(executor, key_pair, peer_public_key, token)`, the peer's key a `curves::x25519::public_key` +| `void(error_code, Keypair)` for `async_from_secret` and `async_generate`, `void(error_code, secret<32>)` for `async_agree` | P-256 (<>) -| `async_make(executor, scalar, token)`, `async_generate(executor, token)`, `async_sign(executor, key_pair, crypto::ecdsa_sha256, input, token)`, `async_verify(executor, crypto::ecdsa_sha256, signature, input, public_key, token)`, `async_agree(executor, key_pair, peer_public_key, token)` -| `void(error_code, Keypair)` for `async_make` and `async_generate`, `void(error_code, signature)` for `async_sign`, `void(error_code)` for `async_verify`, `void(error_code, secret<32>)` for `async_agree` +| `async_from_secret(executor, scalar, token)`, `async_generate(executor, token)`, `async_sign(executor, key_pair, crypto::ecdsa_sha256, input, token)`, `async_verify(executor, crypto::ecdsa_sha256, signature, input, public_key, token)`, `async_agree(executor, key_pair, peer_public_key, token)` +| `void(error_code, Keypair)` for `async_from_secret` and `async_generate`, `void(error_code, signature)` for `async_sign`, `void(error_code)` for `async_verify`, `void(error_code, secret<32>)` for `async_agree` |=== -Each function but X25519's `async_agree`, X25519 having no key pair class, has -its member form, which the free function calls, with the same arguments but -the object: `Keypair::async_make(executor, bytes, token)`, +Each function has its member form, which the free function calls, with the +same arguments but the object: `Keypair::async_from_secret(executor, bytes, token)`, `Keypair::async_generate(executor, token)`, `key_pair.async_sign(executor, scheme, input, token)`, `public_key.async_verify(executor, scheme, signature, input, token)`, -`key_pair.async_agree(executor, peer, token)` on P-256, and AES-GCM's -`Gcm::async_make`, `aead.async_seal` and `aead.async_open`. Both forms share +`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`. +Both forms share one initiation, which runs the synchronous member, so the four forms of an operation give the same bytes, errors and refusals (<>). The members are declared in their classes and @@ -88,10 +98,16 @@ P-256's own types, the key pair and the validated `public_key`, and `async_agree` gives the shared point's raw x, as WebCrypto's `deriveBits` does (<>). -The other algorithms of crypto (the ChaCha20-Poly1305 AEADs, the secret boxes, -secp256k1) are not in WebCrypto, and have no asynchronous function: naming one -stops the build with a message that names the synchronous function to call, whose text -and fix are in <>. Their synchronous functions are as cheap +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 +(<>), 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 +WebCrypto lacks (secp256k1) have no asynchronous function: naming one stops the +build with a message that names the synchronous function to call. The texts and +fixes are in <>. The synchronous functions are as cheap as these, and are called inside a handler. include::generated/backends-async_gcm.adoc[] @@ -170,7 +186,7 @@ without a value, `async_open` and `async_verify`, completes with the code alone. *What the guards say.* The completion's code is the synchronous function's, -unchanged: `invalid_key_size`, `invalid_iv_size`, `message_too_long`, +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 @@ -180,7 +196,7 @@ refuses is untouched; a failed `async_seal` or `async_open` zeroes it, as *Pitfalls.* * *The object and the spans are the caller's until the completion.* The -key, the IV, the additional data, the data, the message and the signature are +key, the nonce, the associated data, the data, the message and the signature are read and written by the call, which on a synchronous backend finishes before it returns; the browser's backend reads them later. A program written for either keeps them alive, and does not touch the data, until the handler @@ -198,7 +214,7 @@ touches the loop's state from it races with it. associated allocator (`bind_allocator`), as every Asio operation does; a program that counts or pools its allocations binds its own. webcpp's own code calls neither `operator new` nor the C allocator in this family; a backend that allocates at -`make` (OpenSSL) does so here too, as the synchronous `make` does (see <>). +`from_key` (OpenSSL) does so here too, as the synchronous `from_key` does (see <>). * *`use_future` without exceptions.* An error completes a future with an exception; a program built without exceptions reads errors with a callback or `as_tuple`. diff --git a/doc/backends.adoc b/doc/backends.adoc index 6f26c793..cdef7007 100644 --- a/doc/backends.adoc +++ b/doc/backends.adoc @@ -120,34 +120,40 @@ tag secret under Valgrind's memcheck, as link:https://github.com/agl/ctgrind[ctgrind] does, and, in a clang build, under MemorySanitizer, which only clang has (a gcc build runs memcheck alone): any branch or memory index that depends on them fails the run. The lane covers -`equal`, `is_all_zero` and the wipe of `secret`; BearSSL's AES-GCM and -ChaCha20-Poly1305 `make`, `seal` and `open`; OpenSSL's `make` and `seal` of -both; ctaes's AES; libsodium's Ed25519 key pair and signature, X25519's public -key and agreement, its three ChaCha20-Poly1305 AEADs and two secret boxes, -`hybrid::box` in both families, the sealed box's `seal` and `open`, and `kx`; -libsecp256k1's own `ctime_tests.c`; and webcpp's code around libsecp256k1: -the key pair's making, its BIP 340, recoverable and hedged ECDSA signatures and -x-only tweak, ECDH in its three forms, the secret key's tweaks and negation, -PKCS#8's encoding and decoding, ElligatorSwift's `ellswift_create` and -`ellswift_xdh`, MuSig2's `nonce_gen` and `partial_sign`, and silent payments' -`create_outputs`, `create_label` and `scan_outputs`, with the wipe of their -workspaces; and BearSSL's P-256: the key pair's making, `sign` of a digest -(`crypto::prehashed`), which makes its signature low S without a branch, then -`normalize_low_s` and `is_low_s` on the fresh signature, `agree` and -`decode_pkcs8`. Both checkers run the same paths, written once (`paths.hpp`), -memcheck OpenSSL's besides. Each check is shown to fail on a planted branch on -a key byte, and on a copy of P-256's range check of a scalar that returns at -the first byte that differs, and each path's output is checked to carry the mark, so that the -path is traced, where the checker's shadow keeps it: MemorySanitizer's loses +`constant_time_equal`, `is_all_zero`, `erase_secret` and the wipe of +`secret`; BearSSL's AES-GCM and ChaCha20-Poly1305 `from_key`, `seal` and +`open`; OpenSSL's +`from_key` and `seal` of both; ctaes's AES; libsodium's Ed25519 key pair and +signature, X25519's public key, agreement and the key pair's wipe by a move, a +move assignment and the destructor, its three ChaCha20-Poly1305 AEADs +and the two secret boxes of `secret_key_encryption`, `public_key_encryption::box` +in both families, the sealed box's `seal` and `open`, and `kx` from a seed and +from an X25519 key pair (`from_keypair`); libsecp256k1's own +`ctime_tests.c`; and +webcpp's code around libsecp256k1: the key pair's making, its BIP 340, +recoverable and hedged ECDSA signatures and x-only tweak, ECDH in its three +forms, the secret key's tweaks and negation, PKCS#8's encoding and decoding, +ElligatorSwift's `ellswift_create` and `ellswift_xdh`, MuSig2's +`generate_nonce` and `partial_sign`, and silent payments' `create_outputs`, +`create_label` and +`scan_outputs`, with the wipe of their workspaces; and BearSSL's P-256: the key +pair's making, `sign` of a digest (`crypto::prehashed`), which makes its +signature low S without a branch, then `normalize_low_s` and `is_low_s` on the +fresh signature, `agree` and `decode_pkcs8`. Both checkers run the same paths, +written once (`paths.hpp`), memcheck OpenSSL's besides. Each check is shown to +fail on a planted branch on a key byte, and on a copy of P-256's range check of +a scalar that returns at the first byte that differs, and each path's output is +checked to carry the mark, so that the path is traced, where the checker's +shadow keeps it: MemorySanitizer's loses the mark through a constant-time reduction to one bit, so the result of `is_all_zero`, X25519's public key, P-256's public key and `agree` (BearSSL selects a window's points with masks of that form) and the bytes a destructor wiped are checked by memcheck alone. dudect's statistics (link:https://eprint.iacr.org/2016/1123[Reparaz, Balasch and Verbauwhede]) time BearSSL's two AEADs' seal and open, BearSSL's P-256 `sign` of a digest and -`agree` against the key pair's scalar, ctaes, `equal`, libsodium's X25519 -agreement and Ed25519 signing, and libsecp256k1's `agree` natively, on Linux -and macOS, and under wasmtime. +`agree` against the key pair's scalar, ctaes, `constant_time_equal`, libsodium's +X25519 agreement and Ed25519 signing, and libsecp256k1's `agree` natively, on +Linux and macOS, and under wasmtime. dudect's programs set nothing themselves: they measure what a program gets, which on 64-bit ARM is the DIT webcpp sets in each call (<>). Each prints whether the CPU has DIT, and fails where DIT is set on its thread @@ -236,9 +242,9 @@ instructions Arm lists take a time independent of their data, and Apple requires it of constant-time code (link:https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Enable-DIT-for-constant-time-cryptographic-operations[Apple, enable DIT for constant-time cryptographic operations]). None of the C libraries sets it, so webcpp does: every public function that -runs a backend's cryptographic code, and `equal`, runs its whole body with DIT -set on 64-bit ARM under macOS, iOS, Linux and Android where the CPU has -FEAT_DIT (`hw.optional.arm.FEAT_DIT` on Apple's systems, `HWCAP_DIT` on +runs a backend's cryptographic code, and `constant_time_equal`, runs its whole +body with DIT set on 64-bit ARM under macOS, iOS, Linux and Android where the +CPU has FEAT_DIT (`hw.optional.arm.FEAT_DIT` on Apple's systems, `HWCAP_DIT` on Linux), and returns with the thread's DIT as it found it: clear when it was clear, set when the program set it itself (Apple's `timingsafe_enable_if_supported`, from macOS 15.2) or an outer call did. An diff --git a/doc/block.adoc b/doc/block.adoc index c3f0d1aa..80bfeae3 100644 --- a/doc/block.adoc +++ b/doc/block.adoc @@ -20,14 +20,14 @@ shape of the data shows through, the mode called ECB AES block cipher with keys of 16, 24 and 32 bytes. They work in place on whole blocks: `encrypt` and `decrypt` take a span whose size is a multiple of `block_size`, 16, and give `invalid_input_size` for a partial block. Each is -made with `make(key_bytes)`, which gives `invalid_key_size` for a key of another size; +made with `from_key(key_bytes)`, which gives `invalid_key_size` for a key of another size; an object moved from is wiped and empty, and returns `invalid_state`. include::generated/backends-aes_block.adoc[] BearSSL exports AES only inside its modes, with no single-block class, so `aes256` is a complete type, which `gcm` needs to name its -cipher, but its `make` does not compile, and a `static_assert` says which +cipher, but its `from_key` does not compile, and a `static_assert` says which backends to use (<>). `aes256<>` names the block cipher's default, OpenSSL natively and ctaes on WebAssembly (<>), and `` diff --git a/doc/chacha.adoc b/doc/chacha.adoc index ee370ef8..540825f1 100644 --- a/doc/chacha.adoc +++ b/doc/chacha.adoc @@ -10,7 +10,7 @@ *ChaCha20-Poly1305* is authenticated encryption built from two of Daniel J. Bernstein's designs: the stream cipher ChaCha20 encrypts, and the one-time authenticator Poly1305 computes a 16-byte tag over the ciphertext and the -additional data +associated data (link:https://en.wikipedia.org/wiki/ChaCha20-Poly1305[Wikipedia]; link:https://www.rfc-editor.org/rfc/rfc8439[RFC 8439]). A chat app seals each message with it, a password manager each entry of its vault: whoever copies @@ -26,8 +26,9 @@ the safe choice. It is a cipher suite of TLS 1.3 (link:https://www.rfc-editor.org/rfc/rfc8446#section-9.1[RFC 8446]) and the AEAD of WireGuard (link:https://www.wireguard.com/protocol/[WireGuard]). -`ciphers::aead`, in ``, is -one-shot authenticated encryption in place over a family; three aliases, in +`ciphers::basic_chacha20_poly1305`, in +``, is one-shot authenticated encryption in +place over a family, named for its algorithm; three aliases, in ``, name its three ChaCha20-Poly1305 families on their default backend, libsodium on every target: @@ -43,18 +44,21 @@ XChaCha draft]). When in doubt, this one, as <> says: a program that draws each nonce at random has nothing to count and nothing to store, on the web and natively alike. -Each is made with `make(key_bytes)` and works in place, as AES-GCM's one-shot -calls do: `seal(iv_bytes, additional_data_bytes, data_bytes)` encrypts -`data_bytes` and returns the 16-byte tag; `open(iv_bytes, -additional_data_bytes, data_bytes, tag_bytes)` checks the tag and decrypts. +Each is made with `from_key(key_bytes)` and works in place, as AES-GCM's one-shot +calls do: `seal(nonce_bytes, associated_data_bytes, data_bytes)` encrypts +`data_bytes` and returns the 16-byte tag; `open(nonce_bytes, +associated_data_bytes, data_bytes, tag_bytes)` checks the tag and decrypts. A failed `open` zeroes `data_bytes`; a guard's refusal leaves it untouched. -The nonce may lie in `data_bytes`, and the additional data may touch it, as a +The nonce may lie in `data_bytes`, and the associated data may touch it, as a wire format that puts it just before the message does, but not overlap it. +Each is a `secret_key_encryption::aead::cipher`, whose free forms, +`secret_key_encryption::aead::seal` and `open`, its header brings +(<>). RFC 8439's form also runs on BearSSL, on every target, and on OpenSSL, natively and on WASI, with the same results byte for byte: name the backend in the type, as in `chacha20_poly1305`, and link its library. -On BearSSL nothing allocates; on OpenSSL `make` allocates and a message does +On BearSSL nothing allocates; on OpenSSL `from_key` allocates and a message does not. *Limits.* Each form bounds how much one key may seal, and how many messages @@ -72,7 +76,7 @@ would reveal both plaintexts' XOR and let tags be forged: A program changes keys periodically. A large message is no reason to improvise: splitting a message into chunks is safe only when each chunk's tag also -covers its number and a flag marking the last chunk, in the additional data or +covers its number and a flag marking the last chunk, in the associated data or in a nonce built from them, and a reader refuses chunks out of order and a stream that ends without the last flag: otherwise whoever holds the ciphertext reorders, drops, repeats or truncates chunks and each one still opens. The @@ -82,7 +86,7 @@ Rogaway and Vizár, 2015]) and libsodium's secretstream documentation]) do this; this version of crypto offers neither. *Example.* A chat app's messages under one conversation key, each sealed with -a nonce drawn for it and the conversation's id as additional data, so that a +a nonce drawn for it and the conversation's id as associated data, so that a message moved to another conversation does not open: [source,cpp] @@ -124,9 +128,9 @@ work itself: |=== |Condition |Error -|`make`: a key of another size than 32 bytes |`invalid_key_size` +|`from_key`: a key of another size than 32 bytes |`invalid_key_size` |any other function: the object was moved from |`invalid_state` -|a nonce of another size than the family's, 12, 8 or 24 bytes |`invalid_iv_size` +|a nonce of another size than the family's, 12, 8 or 24 bytes |`invalid_nonce_size` |`open`: a tag of another size than 16 |`invalid_tag_size` |a message longer than `max_message_size` |`message_too_long` |`open`: the tag does not match |`authentication_failed` @@ -143,9 +147,9 @@ every later message With `xchacha20_poly1305` draw 24 bytes at random per message; with `chacha20_poly1305` count, a restart included, or draw at random within the limit above; with the original form, count. -* The tag covers the ciphertext and the additional data, nothing else: what +* The tag covers the ciphertext and the associated data, nothing else: what the message belongs to (a conversation, a user, a record's id) goes in the -additional data, or a message can be moved there unnoticed. +associated data, or a message can be moved there unnoticed. * A failed `open` zeroes the data: keep the ciphertext if it is needed after a failure, and never act on a message before `open` succeeds. diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 86709cfa..327bc145 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -17,13 +17,13 @@ of every version are on webcpp's index page. // tag::unreleased[] * Added crypto, C-backed primitives setting DIT on arm64 macOS, iOS, Linux and Android: ciphers, curves, randomness, self-wiping secret, errors 1 to 20, `+[[nodiscard]]+` results, WEBCPP_CRYPTO_HAS_THREADS, asynchronous functions on Asio. -* Added equal, random_device, pem on libsodium, the AES block cipher ciphers::aes128, aes192 and aes256 with a per-target default, and ciphers::gcm, aes128_gcm and aes256_gcm: incremental seal, two-pass open, failures zeroing data. +* Added constant_time_equal, random_device, pem on libsodium, the AES block cipher ciphers::aes128, aes192 and aes256 with a per-target default, and ciphers::gcm, aes128_gcm and aes256_gcm: incremental seal, two-pass open, failures zeroing data. * Added supports_v with its family tags, the capability table per target, default_backend_t and /webcpp/crypto//-default per family and target (secp256k1's modules among them), and refusals naming their Jamfile line. -* Added backends::bearssl (AES-GCM, ChaCha20-Poly1305, curves::p256: keys, low-S ECDSA, agree, SPKI/PKCS#8; allocating nothing), backends::openssl natively and on WASI (allocating at make only, or in openssl_memory_resource with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE), and backends::ctaes. -* Added curves::secp256k1: key pairs signing with crypto::ecdsa_sha256 (hedged too), ecdsa_sha256_recoverable and schnorr, agree in three forms, strict DER, low-S, tweaks, SPKI, PKCS#8, PEM, ElligatorSwift, MuSig2, silent payments. -* Added curves::ed25519 and curves::x25519 on libsodium: strict verification over twelve edge cases, Ed25519ph over hash's sha2_512 (/webcpp/crypto//crypto brings hash), the conversion, agree refusing all-zero secrets, RFC 8410's SPKI and PKCS#8. -* Added backends::sodium on /third_party//sodium, shared with webcpp::hash, every backend's link-time canary and C suite, and ciphers::aead: chacha20_poly1305 (also BearSSL, OpenSSL), the original form, xchacha20_poly1305, failed seals and opens zeroing data. -* Added ciphers::secretbox and secretbox_xchacha20poly1305, without additional data, hybrid::box, box_xchacha20poly1305 and sealed_box (failed seals and opens zeroing data), and curves::x25519::kx_keypair (crypto_kx) on libsodium, refusing peer keys of small order. +* Added backends::bearssl (AES-GCM, ChaCha20-Poly1305, curves::p256: keys, low-S ECDSA, agree, SPKI/PKCS#8; allocating nothing), backends::openssl natively and on WASI (allocating at from_key only, or in openssl_memory_resource with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE), and backends::ctaes. +* Added curves::secp256k1: key pairs signing with crypto::ecdsa_sha256 (hedged too), ecdsa_sha256_recoverable, ecdsa_keccak256_recoverable (Ethereum's recoverable ECDSA) and schnorr, agree's three forms, strict DER, low-S, tweaks, SPKI, PKCS#8, PEM, ElligatorSwift, MuSig2, silent payments. +* Added curves::ed25519 and curves::x25519 on libsodium: strict verification (twelve edge cases), Ed25519ph as crypto::eddsa_prehashed and the streaming prehashed_signer over hash's sha2_512, the conversion, all-zero agreements refused, RFC 8410's SPKI, PKCS#8. +* Added backends::sodium on /third_party//sodium, shared with webcpp::hash, every backend's link-time canary and C suite, and ciphers::basic_chacha20_poly1305: chacha20_poly1305 (also BearSSL, OpenSSL), the original form, xchacha20_poly1305, failed seals and opens zeroing data. +* Added secret_key_encryption's secretbox and secretbox_xchacha20poly1305 without associated data, public_key_encryption's box, box_xchacha20poly1305 and sealed_box, key_exchange::kx_keypair on libsodium, on typed X25519 keys. * Added the page: chapters per namespace and use case, the memory option's guide, generated tables, Jamfiles, messages, llms.txt, release-built sizes and throughput, X25519 timing findings (wasip2, DIT). -* Added signing.hpp, keypair.hpp and make.hpp: sign(scheme, input) and crypto::verify, digests only as crypto::prehashed; typed public keys, secret(), agree; member and free forms, synchronous and asynchronous on Ed25519, P-256, AES-GCM. +* Added signing.hpp, keypair.hpp, factories.hpp, secret_key_encryption/aead.hpp, erase_secret.hpp: typed signatures, sign(scheme, input), verify; keypair, signing_keypair, agreement_keypair; aead::cipher, authenticated_box; from_secret, from_bytes, from_key. // end::unreleased[] diff --git a/doc/ciphers.adoc b/doc/ciphers.adoc index 5078dac9..17e75940 100644 --- a/doc/ciphers.adoc +++ b/doc/ciphers.adoc @@ -23,16 +23,18 @@ link:https://csrc.nist.gov/pubs/sp/800/38/d/final[SP 800-38D]), fast where the 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, and -libsodium's secret boxes are the same idea in NaCl's format. The raw AES block -cipher is a building block, never encryption of data. +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 +libsodium's secret boxes, the same idea without associated data, are in +`secret_key_encryption` (<>), with the AEAD +contract every cipher here satisfies (<>). *Which one.* When in doubt, `xchacha20_poly1305<>`: a random nonce per message and nothing to count, the same code and the same bytes on the web and natively. AES-GCM when a protocol, a standard or a browser's WebCrypto names it, or to read what such a party wrote; RFC 8439's ChaCha20-Poly1305 when a protocol names it, TLS 1.3 or WireGuard; a secret box to read or write libsodium's -`crypto_secretbox`. The table compares them; each row's "choose it when" is +`crypto_secretbox` (<>). The table compares them; each row's "choose it when" is the rule. include::generated/namespace-ciphers.adoc[] diff --git a/doc/equal.adoc b/doc/constant_time_equal.adoc similarity index 59% rename from doc/equal.adoc rename to doc/constant_time_equal.adoc index 69cc088d..cd20e8af 100644 --- a/doc/equal.adoc +++ b/doc/constant_time_equal.adoc @@ -4,8 +4,8 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -[#crypto-equal] -=== Comparing tags +[#crypto-constant-time-equal] +==== Comparing tags in constant time A *timing attack* recovers a secret by measuring how long a program takes to handle different inputs @@ -17,36 +17,36 @@ bytes of a forged MAC are right; with enough requests the attacker builds a valid one byte by byte (link:https://cwe.mitre.org/data/definitions/208.html[CWE-208]). -`equal`, in ``, compares in constant time: it reads -every byte, combines the differences without a branch, and its running time -depends only on the length. It takes two Hash2 digests of one size, or two -spans; spans of different sizes compare unequal without reading their contents, -since a size is public. HMAC itself -(link:https://www.rfc-editor.org/rfc/rfc2104[RFC 2104]) is Boost.Hash2's; -crypto adds the comparison that makes it safe to check. +`constant_time_equal`, in ``, compares in +constant time: it reads every byte, combines the differences without a branch, +and its running time depends only on the length. It takes two Hash2 digests of +one size, or two spans; spans of different sizes compare unequal without reading +their contents, since a size is public. HMAC itself +(link:https://www.rfc-editor.org/rfc/rfc2104[RFC 2104]) is Boost.Hash2's; crypto +adds the comparison that makes it safe to check. -include::generated/backends-equal.adoc[] +include::generated/backends-constant_time_equal.adoc[] *Example.* A payment provider signs each webhook call with HMAC-SHA-256 under a -shared secret. The program recomputes the MAC over the body and compares it -with `equal`; here the key, the body and the MAC are RFC 4231's test case 2 -(link:https://www.rfc-editor.org/rfc/rfc4231[RFC 4231]): +shared secret. The program recomputes the MAC over the body and compares it with +`constant_time_equal`; here the key, the body and the MAC are RFC 4231's test +case 2 (link:https://www.rfc-editor.org/rfc/rfc4231[RFC 4231]): [source,cpp] ---- -include::{examples}/equal_hmac.cpp[tag=check,indent=0] +include::{examples}/constant_time_equal_hmac.cpp[tag=check,indent=0] ---- [listing] ---- -include::{examples}/equal_hmac.expected[] +include::{examples}/constant_time_equal_hmac.expected[] ---- The whole program: [source,cpp] ---- -include::{examples}/equal_hmac.cpp[tag=program] +include::{examples}/constant_time_equal_hmac.cpp[tag=program] ---- *Pitfalls.* diff --git a/doc/crypto.adoc b/doc/crypto.adoc index 2203bf68..970a9fcc 100644 --- a/doc/crypto.adoc +++ b/doc/crypto.adoc @@ -36,9 +36,7 @@ include::jamfile.adoc[] include::root.adoc[] -include::entropy.adoc[] - -include::equal.adoc[] +include::protecting_secrets.adoc[] include::errors.adoc[] @@ -48,10 +46,10 @@ include::aead.adoc[] include::chacha.adoc[] -include::secretbox.adoc[] - include::block.adoc[] +include::secret_key_encryption.adoc[] + include::curves.adoc[] include::secp256k1.adoc[] @@ -60,13 +58,13 @@ include::ed25519.adoc[] include::x25519.adoc[] -include::kx.adoc[] - include::p256.adoc[] include::formats.adoc[] -include::hybrid.adoc[] +include::public_key_encryption.adoc[] + +include::kx.adoc[] include::async.adoc[] @@ -88,10 +86,11 @@ include::testing.adoc[] == Reference Every name crypto declares, in the namespaces `webcpp::crypto`, `backends`, -`ciphers`, `curves` and `hybrid`, from the Doc Comments of its headers: each -class, function, type and enumerator with its declaration, what it does, what -it asks of its caller and how it fails. The other sections teach the library; -this one is where a name is looked up. +`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. include::{reference}[leveloffset=+1] diff --git a/doc/curves.adoc b/doc/curves.adoc index f3c37b42..bf913647 100644 --- a/doc/curves.adoc +++ b/doc/curves.adoc @@ -16,70 +16,73 @@ on a key*, so that two parties who only exchanged public keys share a secret (link:https://en.wikipedia.org/wiki/Elliptic-curve_Diffie%E2%80%93Hellman[Wikipedia]). The namespace `webcpp::crypto::curves` holds four curves in this version, the -columns of the table below. The first is secp256k1 (link:https://www.secg.org/sec2-v2.pdf[SEC 2]; -link:https://en.bitcoin.it/wiki/Secp256k1[Bitcoin Wiki]), the curve of -Bitcoin, Ethereum and Nostr (<>). This version covers -Bitcoin's keys and signatures, Nostr's event signatures (NIP-01) and the raw -x-coordinate ECDH of its encrypted messages (NIP-44, <>), -and Ethereum's ECDSA: recoverable signatures, the recovery of a signer's public -key from a signature, and the uncompressed key -(<>). Its functions, by header: - -* `secp256k1.hpp`, the key pair and its signatures and ECDH: `keypair::make`, `generate`, -and the key pair's `public_key`, `secret`, `sign` with `crypto::schnorr`, -`crypto::ecdsa_sha256` and `crypto::ecdsa_sha256_recoverable`, `agree`, -`agree_hashed`, `agree_point` and `tweak_xonly`; the `public_key` type's `make`, -`compressed`, `uncompressed` and `xonly`; `crypto::verify` with `crypto::schnorr` -and `crypto::ecdsa_sha256`, `recover`, `to_der`, `from_der`, `normalize_low_s`, -`is_low_s` and the x-only key's `tweak_xonly`; +columns of the table below. The first is secp256k1 +(link:https://www.secg.org/sec2-v2.pdf[SEC 2]; +link:https://en.bitcoin.it/wiki/Secp256k1[Bitcoin Wiki]), the curve of Bitcoin, +Ethereum and Nostr (<>). This version covers Bitcoin's keys +and signatures, Nostr's event signatures (NIP-01) and the raw x-coordinate ECDH +of its encrypted messages (NIP-44, <>), and Ethereum's +ECDSA: recoverable signatures over SHA-256 or over Keccak-256, Ethereum's own, +the recovery of a signer's public key from a signature, and the uncompressed key +(<>, <>). Its functions, +by header: + +* `secp256k1.hpp`, the key pair and its signatures and ECDH: +`keypair::from_secret`, `generate`, and the key pair's `public_key`, `secret`, +`sign` with `crypto::schnorr`, `crypto::ecdsa_sha256`, +`crypto::ecdsa_sha256_recoverable` and `crypto::ecdsa_keccak256_recoverable`, +`agree`, `agree_hashed`, `agree_point` and `tweak_xonly`; the `public_key` +type's `from_bytes`, `compressed`, `uncompressed` and `xonly`; `crypto::verify` +with `crypto::schnorr` and `crypto::ecdsa_sha256`, `recover`, `to_der`, +`from_der`, `normalize_low_s`, `is_low_s` and the x-only key's `tweak_xonly`; * `secp256k1/tweak.hpp`, tweaks of whole keys, the arithmetic of BIP 32's -derivation and of watch-only wallets: `seckey_tweak_add`, `seckey_tweak_mul`, -`seckey_negate`, `pubkey_tweak_add`, `pubkey_tweak_mul`, `pubkey_negate` and -`pubkey_combine` (<>); +derivation and of watch-only wallets: `secret_key_tweak_add`, +`secret_key_tweak_mul`, `secret_key_negate`, `public_key_tweak_add`, +`public_key_tweak_mul`, `public_key_negate` and `public_key_combine` +(<>); * `secp256k1/formats.hpp`, keys in the SPKI and PKCS#8 files that OpenSSL exchanges: `encode_spki`, `decode_spki`, `encode_pkcs8` and `decode_pkcs8` (<>); * `secp256k1/ellswift.hpp`, keys sent as random-looking bytes, BIP 324's ElligatorSwift: `ellswift_create`, `ellswift_encode`, `ellswift_decode` and `ellswift_xdh` (<>); -* `secp256k1/musig.hpp`, many signers' keys and signatures aggregated into -one, BIP 327's MuSig2: `key_aggregate`, `nonce_gen`, `nonce_aggregate`, +* `secp256k1/musig.hpp`, many signers' keys and signatures aggregated into one, +BIP 327's MuSig2: `key_aggregate`, `generate_nonce`, `nonce_aggregate`, `nonce_process`, `partial_sign`, `partial_signature_verify`, `partial_signature_aggregate`, and the `parse_` and `serialize_` functions of what the signers send (<>); * `secp256k1/silent_payments.hpp`, one reusable address whose payments look unrelated, BIP 352's silent payments: `create_outputs`, `create_label`, -`create_labeled_spend_key`, `make_prevouts_summary` and `scan_outputs` +`create_labeled_spend_key`, `make_previous_outputs_summary` and `scan_outputs` (<>). -Ethereum's `v` encoding of the recovery id, the hash it signs, its -transactions and its addresses are a domain library's, and so is BIP 32's -derivation, its HMAC-SHA-512 and its paths, which only adds a tweak computed -there to a whole key -(link:https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki[BIP 32]). -The second is Ed25519, -RFC 8032's signatures on edwards25519, with Ed25519ph for a message given in -pieces (link:https://www.rfc-editor.org/rfc/rfc8032[RFC 8032]; -<>). The third is X25519, RFC 7748's key agreement on -Curve25519, the same curve in another form, with the conversion of an Ed25519 -key to it (link:https://www.rfc-editor.org/rfc/rfc7748[RFC 7748]; -<>), and libsodium's key exchange on it, `crypto_kx` -(<>). The fourth is P-256, NIST's curve of FIPS 186-5, the curve of -browsers' WebCrypto, of passkeys and of TLS certificates, on BearSSL: key pairs -made from a scalar or drawn, public keys validated once, ECDSA over SHA-256 -with RFC 6979's nonce, signed low S, raw and DER, ECDH's raw x +Ethereum's `v` encoding of the recovery id, the hash it signs, its transactions +and its addresses are a domain library's, and so is BIP 32's derivation, its +HMAC-SHA-512 and its paths, which only adds a tweak computed there to a whole +key (link:https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki[BIP +32]). The second is Ed25519, RFC 8032's signatures on edwards25519, with +Ed25519ph for a message's SHA-512 or a message given in pieces +(link:https://www.rfc-editor.org/rfc/rfc8032[RFC 8032]; <>). The +third is X25519, RFC 7748's key agreement on Curve25519, the same curve in +another form, with the conversion of an Ed25519 key to it +(link:https://www.rfc-editor.org/rfc/rfc7748[RFC 7748]; <>), on +which libsodium's key exchange, `crypto_kx`, is built in `key_exchange` +(<>). The fourth is P-256, NIST's curve of FIPS 186-5, the +curve of browsers' WebCrypto, of passkeys and of TLS certificates, on BearSSL: +key pairs made from a scalar or drawn, public keys validated once, ECDSA over +SHA-256 with RFC 6979's nonce, signed low S, raw and DER, ECDH's raw x coordinate, as WebCrypto's `deriveBits` gives it, and its keys as SPKI and PKCS#8 (link:https://csrc.nist.gov/pubs/fips/186-5/final[FIPS 186-5]; <>, <>, <>, -<>). A program chooses a curve for compatibility: a signature on -one curve is checked only with that curve, and a browser's peer needs P-256. -Ed25519's, X25519's and P-256's keys leave a program, and enter it, in the standard forms -OpenSSL and WebCrypto use, SPKI and PKCS#8, as DER or PEM text (<>). -Every curve signs and verifies by the same two names, the scheme named at every -call, and its key pair keeps one contract (<>); each -operation has the member and its free form, and, where WebCrypto has the -algorithm (Ed25519 and P-256), their asynchronous forms -(<>). +<>). A program chooses a curve for compatibility: a +signature on one curve is checked only with that curve, and a browser's peer +needs P-256. Ed25519's, X25519's and P-256's keys leave a program, and enter it, +in the standard forms OpenSSL and WebCrypto use, SPKI and PKCS#8, as DER or PEM +text (<>). Every curve signs and verifies by the same two +names, the scheme named at every call, and its key pair keeps one contract +(<>); each operation has the member and its free form, +and, where WebCrypto has the algorithm (Ed25519, X25519 and P-256), their +asynchronous forms (<>). include::generated/namespace-curves.adoc[] @@ -93,22 +96,24 @@ verify. A key pair signs with `key.sign(scheme, input)`, and tag object that names the algorithm and, for ECDSA, its hash, as WebCrypto's `+{name: "ECDSA", hash: "SHA-256"}+` does (link:https://www.w3.org/TR/WebCryptoAPI/#ecdsa-operations[W3C, ECDSA's -operations]): `crypto::eddsa`, `crypto::ecdsa_sha256`, -`crypto::ecdsa_sha256_recoverable` and `crypto::schnorr`. It is named at every -call, on every curve, so that the call says what it signs; a tag's constructor -is explicit, so that `+{}+` never stands for a scheme. +operations]): `crypto::eddsa`, `crypto::eddsa_prehashed`, +`crypto::ecdsa_sha256`, `crypto::ecdsa_sha256_recoverable`, +`crypto::ecdsa_keccak256_recoverable` and `crypto::schnorr`. It is named at +every call, on every curve, so that the call says what it signs; a tag's +constructor is explicit, so that `+{}+` never stands for a scheme. The input is a message or a digest, and the program says which: * A *message* is any bytes that convert to `std::span`: a span, a `std::array`, a `std::vector`, of any size, the empty one included. -ECDSA hashes it with SHA-256 inside the call, as WebCrypto does; EdDSA and -Schnorr sign it as given. +ECDSA hashes it with SHA-256 inside the call, as WebCrypto does, and Ethereum's +`crypto::ecdsa_keccak256_recoverable` with Keccak-256; EdDSA and Schnorr sign it +as given; Ed25519ph, `crypto::eddsa_prehashed`, takes none. * A *digest* is `+crypto::prehashed{digest}+`, made from a `std::array`, a span of the fixed size N, or a Boost.Hash2 digest such as the result of `webcpp::hash::sha2_256`. ECDSA signs it as -given. The marker refers to its digest, as a span does, and must not outlive -it. +given, and so does Ed25519ph, `crypto::eddsa_prehashed`, a message's SHA-512. +The marker refers to its digest, as a span does, and must not outlive it. The hazard this removes is the 32-byte message. A SHA-256 digest is 32 bytes, and so is many a message: a key, a protocol's hash, a nonce. Where a function @@ -123,59 +128,70 @@ so. .The schemes, their keys and their inputs [cols="2,3,2,2,2",options="header"] |=== -| Scheme | Key pair; the public key `crypto::verify` takes | A message | `+crypto::prehashed{digest}+` | Signature +| Scheme | Key pair; the public key `crypto::verify` takes | A message +| `+crypto::prehashed{digest}+` | Signature | `crypto::eddsa` | Ed25519: `curves::ed25519::keypair`; `curves::ed25519::public_key` | signed as given (RFC 8032's PureEdDSA) | does not compile -| 64 bytes +| `curves::ed25519::signature`, 64 bytes + +| `crypto::eddsa_prehashed` +| Ed25519: `curves::ed25519::keypair`; `curves::ed25519::public_key` (native +backends) +| does not compile +| 64 bytes, the message's SHA-512 (RFC 8032's Ed25519ph) +| `curves::ed25519::signature`, 64 bytes, not interchangeable with a signature +of `crypto::eddsa` | `crypto::ecdsa_sha256` | P-256: `curves::p256::keypair`; `curves::p256::public_key` | hashed with SHA-256 inside the call | 32 bytes, signed as given -| 64 bytes, r then s, low S +| `curves::p256::ecdsa_signature`, 64 bytes, r then s, low S | `crypto::ecdsa_sha256` | secp256k1: `curves::secp256k1::keypair`; `curves::secp256k1::public_key` | hashed with SHA-256 inside the call | 32 bytes, signed as given -| 64 bytes, r then s, low S +| `curves::secp256k1::ecdsa_signature`, 64 bytes, r then s, low S | `crypto::ecdsa_sha256_recoverable` | secp256k1: `curves::secp256k1::keypair`; none: `recover` gives the key | hashed with SHA-256 inside the call | 32 bytes, signed as given -| 65 bytes, r, s and the recovery id +| `curves::secp256k1::recoverable_signature`, 65 bytes, r, s and the recovery id + +| `crypto::ecdsa_keccak256_recoverable` +| secp256k1: `curves::secp256k1::keypair`; none: `recover` gives the key +| hashed with Keccak-256 inside the call (`/third_party//xkcp` linked) +| 32 bytes, signed as given +| `curves::secp256k1::recoverable_signature`, 65 bytes, r, s and the recovery id | `crypto::schnorr` -| secp256k1: `curves::secp256k1::keypair`; `curves::secp256k1::public_key`, or its 32-byte x-only form +| secp256k1: `curves::secp256k1::keypair`; `curves::secp256k1::public_key`, or +its 32-byte x-only form | signed as given (BIP 340) | does not compile -| 64 bytes +| `curves::secp256k1::schnorr_signature`, 64 bytes |=== -Every other pair stops the build in a `static_assert` whose message says why: -a scheme the key's curve does not have, `crypto::eddsa` or `crypto::schnorr` -with a marker, a marker whose digest is not 32 bytes, a marker made from a span -whose size the type does not know, a marker on a backend that cannot sign a -digest; <> gives each with its -fix. The +Every other pair stops the build in a `static_assert` whose message says why: a +scheme the key's curve does not have, `crypto::eddsa` or `crypto::schnorr` with +a marker, `crypto::eddsa_prehashed` with a message, a marker whose digest is not +the scheme's size (32 bytes, or Ed25519ph's 64), a marker made from a span whose +size the type does not know, a marker on a backend that cannot sign a digest; +<> gives each with its fix. The concepts `crypto::can_sign` and -`crypto::can_verify` give a program's own templates -the same answer. A public key's type says its curve: ECDSA's key is a +`crypto::can_verify` give a program's own +templates the same answer. A public key's type says its curve: ECDSA's key is a validated object on both curves, never bytes, so that `crypto::ecdsa_sha256` never infers its curve from a number of bytes. BIP 340's keys are bytes on the wire, so `crypto::schnorr` also takes the 32-byte x-only key. -The signature is bytes, as it arrives from the network or a file: every -`verify`, member and free, synchronous and asynchronous, on every curve, and -secp256k1's `recover` take it as `std::span`, so a -`std::array`, a `std::vector` or a span of a received buffer goes to every -form unchanged. Its size is checked first, before the key and the backend: a -signature of another size than the table's is `invalid_signature`, never a -build error. +The signature is a type of its curve and scheme, the table's last column, and +nothing else is taken where one is expected (<>). ECDSA signs low S on both curves, s at most (n - 1) / 2: libsecp256k1 signs so, and P-256's RFC 6979 signature is normalized after it is made, n - s @@ -187,24 +203,16 @@ Bitcoin's policy do signatures may be high. A protocol that requires low S from a P-256 peer checks `is_low_s` before `crypto::verify` (<>). -DER, low S and the 64-byte form are formats of a signature, not schemes, and -they need the curve's order: each ECDSA curve's namespace has the same four -functions. `to_der(signature, output)` writes strict DER into at least -`max_der_size` bytes and returns its length, allocating nothing; -`from_der(der)` reads strict DER back into the 64 bytes; -`normalize_low_s(signature)` returns the low-S form, and `invalid_signature` -for an r or an s that is 0 or not below n; `is_low_s(signature)` is true -exactly when r is between 1 and n - 1 and s between 1 and (n - 1) / 2, and -does not verify. - -secp256k1 keeps a third argument where it has a reason of its own: hedged -ECDSA, `sign(crypto::ecdsa_sha256, input, extra_entropy)`, mixes 32 fresh bytes -of the caller's into the nonce, and `sign(crypto::schnorr, message, -aux_random)` takes BIP 340's auxiliary randomness from the caller, for test -vectors; `sign(crypto::schnorr, message)` draws it from `random_device`, and -returns `entropy_unavailable` when it cannot. `recover` takes the scheme and -the inputs of signing, `recover(crypto::ecdsa_sha256_recoverable, signature, -input)` (<>). +secp256k1 keeps a third argument where it has a reason of its own: hedged ECDSA, +`sign(crypto::ecdsa_sha256, input, extra_entropy)`, mixes 32 fresh bytes of the +caller's into the nonce, and `sign(crypto::schnorr, message, +auxiliary_random_bytes)` takes BIP 340's auxiliary randomness from the caller, +for test vectors; `sign(crypto::schnorr, message)` draws it from +`random_device`, and returns `entropy_unavailable` when it cannot. `recover` +takes the scheme and the inputs of signing, +`recover(crypto::ecdsa_sha256_recoverable, signature, input)` or +`recover(crypto::ecdsa_keccak256_recoverable, signature, input)` +(<>). Every `crypto::verify` takes its backend as its first template parameter, `crypto::verify(scheme, signature, input, public_key)`, so that the @@ -221,52 +229,248 @@ schemes and inputs on the curves WebCrypto has, Ed25519 and P-256, and check them as `crypto::can_sign` and `crypto::can_verify` do (<>, <>). +[#crypto-curves-signature-types] +==== Signatures as values + +A signature is a type of its curve and scheme, five in all, each in its curve's +namespace: + +.The signature types +[cols="3,2,3,3",options="header"] +|=== +| Type | Bytes | Given by `sign` under | Taken by + +| `curves::ed25519::signature` +| 64 +| `crypto::eddsa` and `crypto::eddsa_prehashed`; Ed25519ph's streaming +`prehashed_signer` +| `verify` under the scheme that made it, `crypto::eddsa` or +`crypto::eddsa_prehashed`: the two are not interchangeable + +| `curves::p256::ecdsa_signature` +| 64, r then s +| `crypto::ecdsa_sha256` +| `verify` under `crypto::ecdsa_sha256`; P-256's format functions + +| `curves::secp256k1::ecdsa_signature` +| 64, r then s +| `crypto::ecdsa_sha256` +| `verify` under `crypto::ecdsa_sha256`; secp256k1's format functions + +| `curves::secp256k1::recoverable_signature` +| 65, r, s and the recovery id +| `crypto::ecdsa_sha256_recoverable` and +`crypto::ecdsa_keccak256_recoverable` +| `recover` under the scheme that made it + +| `curves::secp256k1::schnorr_signature` +| 64 +| `crypto::schnorr` +| `verify` under `crypto::schnorr` +|=== + +`sign` returns its scheme's type, and every `verify`, member and free, +synchronous and asynchronous, on every curve, and secp256k1's `recover` take +it and nothing else: a signature of another curve or scheme, or bytes, stops +the build with a message naming the type expected. No two of the types convert +into each other, and none converts from or to bytes implicitly. Each is a +value, copied and compared with `==`; `size` is its number of bytes, and +`bytes()` gives them, a `std::array` to send or store. The `recovery_id()` of +a `recoverable_signature` reads its last byte, 0 to 3 in what `sign` gives, +which Ethereum writes as `v` (<>). + +A signature that `sign` gave goes to `verify` as it is, here a Schnorr +signature of a message: + +[source,cpp] +---- +include::{examples}/signed_message.cpp[tag=sign,indent=0] +---- + +[source,cpp] +---- +include::{examples}/signed_message.cpp[tag=verify,indent=0] +---- + +A signature that arrives from the network or a file is made first, at the +wire, by its type's `from_bytes(bytes)` or `crypto::from_bytes(bytes)`, from +a `std::array`, a `std::vector` or a span of a received buffer. Its size alone +is checked there, and another size than the table's is `invalid_signature`; +whether its numbers are in range, or a recovery id above 3, is the judgment of +`verify` and `recover`. A peer's handshake signature, made from its 64 bytes +before it is checked (<>): + +[source,cpp] +---- +include::{examples}/p256_handshake.cpp[tag=receive,indent=0] +---- + +Ed25519's two schemes share `curves::ed25519::signature`, which Ed25519ph's +streaming signer gives too: the type does not tell them apart, and each +verifies only its own scheme's, a signature of the other being +`invalid_signature` at run time, as RFC 8032's domain separation makes it. +Which of the two a protocol uses is the protocol's choice, and the program +passes the same scheme to `sign` and to `verify`. + +DER, low S and the 64-byte form are formats of a signature, not schemes, and +they need the curve's order: each ECDSA curve's namespace has the same four +functions, typed by its `ecdsa_signature`. `to_der(signature, output)` writes +strict DER into at least `max_der_size` bytes and returns its length, +allocating nothing; `from_der(der)` reads strict DER back into the curve's +`ecdsa_signature`; `normalize_low_s(signature)` returns the low-S form, and +`invalid_signature` for an r or an s that is 0 or not below n; +`is_low_s(signature)` is true exactly when r is between 1 and n - 1 and s +between 1 and (n - 1) / 2, and does not verify. A P-256 signature given to +secp256k1's functions, or the reverse, stops the build. + +[#crypto-curves-factories] +==== Factories named by their input + +Every object that holds a key or a validated value is made by a static +function that returns `result`, never by a constructor, and the function is +named by what it is given, so that the call says where the secret comes from: + +.The factories +[cols="3,4,3",options="header"] +|=== +| Type | Made by | Free form + +| every key pair: `ed25519`, `x25519`, `p256`, `secp256k1` +| `K::from_secret(secret_bytes)`, the secret it gives back as `secret()`; +`K::generate()`, drawn from `random_device` +| `crypto::from_secret(secret_bytes)`, `crypto::generate()` + +| every public key +| `T::from_bytes(bytes)`, the bytes `bytes()` or its encodings give; P-256's +also `from_coordinates(x, y)` +| `crypto::from_bytes(bytes)` + +| every signature type +| `T::from_bytes(bytes)` +| `crypto::from_bytes(bytes)` + +| `ciphers::gcm`, `ciphers::basic_chacha20_poly1305`, +`secret_key_encryption::basic_secretbox`, the AES block cipher +| `C::from_key(key)` +| `crypto::from_key(key)` + +| `public_key_encryption::basic_box` +| `from_keys(own_key_pair, peer_public_key)` +| none + +| `key_exchange::kx_keypair` +| `from_keypair(x25519_key_pair)`, `derive_from_seed(seed)`, `generate()` +(<>) +| none +|=== + +The asynchronous family makes what WebCrypto makes: +`K::async_from_secret` and `K::async_generate`, `C::async_from_key`, and their +free forms `crypto::async_from_secret`, `crypto::async_generate` and +`crypto::async_from_key` (<>). The free synchronous forms are +in ``. A key pair's `from_secret` and its +`secret()` are inverses by name, as a public value's `from_bytes` and its +`bytes()` are. + +*The hazard the names remove.* A factory called `make` reads as "make a key": +a program that passes fixed bytes to it, a constant, a hash of a user's name, a +buffer never filled, believing that a key is drawn, gets a private key anyone +who knows those bytes can compute, and nothing fails. `from_secret(bytes)` says +that the bytes are the secret: a new key is `generate()`, and `from_secret` +takes only a secret the program drew or kept itself, from `random_device`, a +`secret()` stored before, or a PKCS#8 file. No `make` remains, with no alias. + [#crypto-curves-keypair] -==== The key pair contract +==== Key pairs by what they do -`` declares the concept `crypto::keypair`, which -every curve's key pair meets, each curve's header checking its own with a -`static_assert`: +`` declares three concepts, by what a key pair +does, so that code written once serves every curve that does it. The concept +`crypto::keypair`, which every curve's key pair meets: -* `make(secret_bytes)` makes it from its secret, and `generate()` draws one -from `random_device`, each giving `result`; +* `from_secret(secret_bytes)` makes it from its secret, and `generate()` draws +one from `random_device`, each giving `result` +(<>); * `public_key()` gives `result`, the curve's typed public -key, whose value goes straight into `crypto::verify`: `curves::ed25519::public_key`, -`curves::p256::public_key` or `curves::secp256k1::public_key`; -* `secret()` gives `result>`, the bytes `make` takes, in a -`secret` that wipes itself: Ed25519's seed, P-256's scalar, secp256k1's secret key. It is the -export a PKCS#8 file or a backup takes; -* `sign(scheme, input)` signs with every scheme its curve has, at least one. - -Each public key type is made from bytes by its own `make`, and gives its byte -forms as members named after the encoding: Ed25519's `bytes()` (32 bytes), -P-256's `uncompressed()` (65), and secp256k1's `compressed()` (33), -`uncompressed()` (65) and `xonly()` (32). P-256's and secp256k1's `make` check -the point; Ed25519's checks the size alone, whether the point is canonical -and not of small order being its verification policy's judgment. +key: `curves::ed25519::public_key`, `curves::x25519::public_key`, +`curves::p256::public_key` or `curves::secp256k1::public_key`, whose value +goes straight into `crypto::verify` or a peer's `agree`; +* `secret()` gives `result>`, the bytes `from_secret` takes, in a +`secret` that wipes itself (<>): Ed25519's seed, X25519's +secret key, P-256's scalar, secp256k1's secret key. It is the export a PKCS#8 +file or a backup takes. + +`crypto::signing_keypair` adds `sign(scheme, input)`, with every scheme its +curve has, at least one, each giving the scheme's signature type +(<>). `crypto::agreement_keypair` adds +`agree(peer)`, the peer a `K::public_key_type`, giving a `secret`. Each +curve's header checks its row of the table with a `static_assert` each: + +.The key pairs and the concepts they meet +[cols="3,2,2,3",options="header"] +|=== +| Key pair | `crypto::keypair` | `crypto::signing_keypair` +| `crypto::agreement_keypair` + +| `curves::ed25519::basic_keypair` +| yes +| yes +| no: `to_x25519()` converts it (<>) + +| `curves::x25519::basic_keypair` +| yes +| no +| yes + +| `curves::p256::basic_keypair` +| yes +| yes +| yes + +| `curves::secp256k1::basic_keypair` +| yes +| yes +| yes +|=== + +`crypto::sign` and `async_sign` take a signing key pair, `crypto::agree` and +`async_agree` an agreement key pair, and another stops the build saying what +it does: an X25519 key pair agrees and does not sign, an Ed25519 key pair signs +and does not agree. A template of the program's takes the concept it needs, +`template `, and is then called with any of +the curves of that column. + +Each public key type is made from bytes by its own `from_bytes`, and gives +its byte forms as members named after the encoding: Ed25519's `bytes()` (32 +bytes), P-256's `uncompressed()` (65), and secp256k1's `compressed()` (33), +`uncompressed()` (65) and `xonly()` (32). P-256's and secp256k1's +`from_bytes` check the point, as P-256's `from_coordinates(x, y)` does; +Ed25519's checks the size alone, whether the point is canonical and not of +small order being its verification policy's judgment. ECDH is `agree(peer)` on every curve that has it, the peer a typed public key, -and gives the shared point's raw x coordinate as a `secret<32>`, as +and gives a `secret<32>`: X25519's gives RFC 7748's shared secret +(<>), and the others the shared point's raw x coordinate, as WebCrypto's `deriveBits` does: P-256's (<>) and secp256k1's, whose two other forms keep names of their own, `agree_hashed` and -`agree_point` (<>). `async_agree` gives P-256's through -a completion. Ed25519's `x25519_secret()` is a conversion, not an agreement -(<>). +`agree_point` (<>). `async_agree` gives X25519's and +P-256's through a completion. Ed25519's `to_x25519()` is a conversion, not an +agreement (<>). [#crypto-curves-four-forms] ==== Four forms of every operation An operation of a key pair, a public key and an AEAD has up to four forms and one implementation: the member and its free form everywhere, and their -asynchronous forms where WebCrypto has the algorithm. The member does the work; its free form, in the namespace -`webcpp::crypto`, calls the member in one line (`crypto::verify` calls the -work the public key's `verify` calls); the asynchronous member and -its free form share one initiation, which runs the synchronous member when the -operation is initiated and completes through the event loop -(<>). The forms take the same arguments and give the same bytes, -the same errors and the same refusals, one set of concepts gating them all, so a program picks the form -that reads best where it calls: the member beside the object, the free form in -generic code, an asynchronous form in an event loop. +asynchronous forms where WebCrypto has the algorithm. The member does the work; +its free form, in the namespace `webcpp::crypto`, calls the member in one line +(`crypto::verify` calls the work the public key's `verify` calls); the +asynchronous member and its free form share one initiation, which runs the +synchronous member when the operation is initiated and completes through the +event loop (<>). The forms take the same arguments and give the +same bytes, the same errors and the same refusals, one set of concepts gating +them all, so a program picks the form that reads best where it calls: the member +beside the object, the free form in generic code, an asynchronous form in an +event loop. .The four forms of each operation [cols="1,4,4",options="header"] @@ -274,55 +478,70 @@ generic code, an asynchronous form in an event loop. | | Synchronous | Asynchronous | Member -| `K::make(bytes)`, `K::generate()`, `key_pair.sign(scheme, input)`, +| `K::from_secret(secret_bytes)`, `T::from_bytes(bytes)`, `C::from_key(key)`, +`K::generate()`, `key_pair.sign(scheme, input)`, `key_pair.agree(peer)`, `public_key.verify(scheme, signature, input)`, -`aead.seal(iv, additional_data, data)`, `aead.open(iv, additional_data, data, tag)` -| `K::async_make(executor, bytes, token)`, `K::async_generate(executor, token)`, +`aead.seal(nonce, associated_data, data)`, +`aead.open(nonce, associated_data, data, tag)` +| `K::async_from_secret(executor, secret_bytes, token)`, +`C::async_from_key(executor, key, token)`, `K::async_generate(executor, token)`, `key_pair.async_sign(executor, scheme, input, token)`, `key_pair.async_agree(executor, peer, token)`, `public_key.async_verify(executor, scheme, signature, input, token)`, -`aead.async_seal(executor, iv, additional_data, data, token)`, -`aead.async_open(executor, iv, additional_data, data, tag, token)` +`aead.async_seal(executor, nonce, associated_data, data, token)`, +`aead.async_open(executor, nonce, associated_data, data, tag, token)` -| Free, in `webcpp::crypto` -| `crypto::make(bytes)`, `crypto::generate()`, +| Free, in `webcpp::crypto`; an AEAD's in `secret_key_encryption::aead` +| `crypto::from_secret(secret_bytes)`, `crypto::from_bytes(bytes)`, +`crypto::from_key(key)`, `crypto::generate()`, `crypto::sign(key_pair, scheme, input)`, `crypto::agree(key_pair, peer)`, `crypto::verify(scheme, signature, input, public_key)`, -`crypto::seal(aead, iv, additional_data, data)`, -`crypto::open(aead, iv, additional_data, data, tag)` -| `crypto::async_make(executor, bytes, token)`, +`secret_key_encryption::aead::seal(aead, nonce, associated_data, data)`, +`secret_key_encryption::aead::open(aead, nonce, associated_data, data, tag)` +| `crypto::async_from_secret(executor, secret_bytes, token)`, +`crypto::async_from_key(executor, key, token)`, `crypto::async_generate(executor, token)`, `crypto::async_sign(executor, key_pair, scheme, input, token)`, `crypto::async_agree(executor, key_pair, peer, token)`, `crypto::async_verify(executor, scheme, signature, input, public_key, token)`, -`crypto::async_seal(executor, aead, iv, additional_data, data, token)`, -`crypto::async_open(executor, aead, iv, additional_data, data, tag, token)` +`secret_key_encryption::aead::async_seal(executor, aead, nonce, +associated_data, data, token)`, +`secret_key_encryption::aead::async_open(executor, aead, nonce, +associated_data, data, tag, token)` |=== -The synchronous forms exist wherever the member does: on Ed25519's, P-256's -and secp256k1's key pairs and public keys (`agree` on P-256 and secp256k1), -and on AES-GCM and every AEAD of `ciphers::aead`, the ChaCha20-Poly1305 forms -and the secret boxes. The asynchronous forms exist for what WebCrypto has: -Ed25519's and P-256's key pairs and public keys (`async_agree` on P-256), and -AES-GCM. A public key has no `async_make`: the asynchronous family makes key -pairs and AES-GCM objects only. -Ed25519's verification policy is an optional argument of all four, before the -token in the asynchronous ones; secp256k1's 32 bytes of extra entropy or -auxiliary randomness follow the input of `sign` and `crypto::sign`. +The synchronous forms exist wherever the member does: on Ed25519's, X25519's, +P-256's and secp256k1's key pairs and public keys (`agree` on X25519, P-256 and +secp256k1), and on AES-GCM and every AEAD of `ciphers::basic_chacha20_poly1305`, +the ChaCha20-Poly1305 forms; the secret boxes and the crypto_boxes, which take +no associated data, have the box forms instead (<>), +asynchronous too. The asynchronous forms exist for what WebCrypto has: +Ed25519's, X25519's and P-256's key pairs and public keys (`async_agree` on +X25519 and P-256), and AES-GCM; and, on a native backend, every other AEAD and +box (<>). A public key has no `async_from_bytes`: the asynchronous +family makes key pairs (`async_from_secret`), AEADs and secret boxes +(`async_from_key`) only. Ed25519's verification policy is an optional argument +of all four, before the token in the asynchronous ones; secp256k1's 32 bytes of +extra entropy or auxiliary randomness follow the input of `sign` and +`crypto::sign`. Each free synchronous form is declared in the header of what it gates: -`crypto::sign` in ``, beside the catch-all of -`crypto::verify`, whose overloads each curve's header declares; -`crypto::agree` in ``; `crypto::make` and -`crypto::generate` in ``, which `keypair.hpp` and the -AEAD headers include; `crypto::seal` and `crypto::open` in -``, which `gcm.hpp` includes. Every free form -holds its own timing guard before it calls the member, which holds one too. -`crypto::make` holds it for every type it makes, being generic, while -Ed25519's `public_key::make`, which copies 32 bytes and calls no backend, -holds none, as no function without a backend call does: the extra guard only -sets DIT around the copy (<>), at the guard's own cost -(<>). +`crypto::sign` and `crypto::agree` in ``, beside +the concepts that constrain them; the catch-all of `crypto::verify` in +``, whose overloads each curve's header declares; +`crypto::from_secret`, +`crypto::from_bytes`, `crypto::from_key` and `crypto::generate` in +``, which `keypair.hpp` and the +AEAD headers include; `secret_key_encryption::aead::seal` and `open` in +``, which every AEAD's header +includes (<>). Every free form +holds its own timing guard before it calls the member, which holds one too, +except `crypto::from_bytes`: a public value's `from_bytes` holds a guard only +where it calls a backend (P-256's and secp256k1's check the point), and +Ed25519's `public_key::from_bytes`, which copies 32 bytes, holds none, as no +function without a backend call does, so the free form adds none either: a +guard there would only set DIT around a copy (<>), at the +guard's own cost (<>). An unqualified call finds the free forms by argument-dependent lookup, a scheme tag being of the namespace `webcpp::crypto`: `verify(crypto::eddsa, signature, @@ -344,17 +563,20 @@ cannot be used before it is defined", gcc's "use of ... before deduction of 'auto'", MSVC's C3779; the message and its fix are in <>. On a backend that completes by itself, as the browser's will be (<>), every synchronous form refuses -at compile time with a message that names its `async_` form: the refusal is in +at compile time with a message that names its `async_` form, but for the +constructions WebCrypto lacks (ChaCha20-Poly1305 and its forms, the secret +boxes, crypto_box), whose synchronous and asynchronous forms alike name a native +backend, since neither completes there (<>): the refusals are in place already, tested with a stand-in backend, since no such backend exists yet. -*Example.* P-256's key pair made by `make` and by `crypto::make`, then a -message signed and the signature verified in the four forms. RFC 6979's nonce -makes the four signatures the same bytes: +*Example.* P-256's key pair made by `from_secret` and by `crypto::from_secret`, +then a message signed and the signature verified in the four forms. RFC 6979's +nonce makes the four signatures the same bytes: [source,cpp] ---- -include::{examples}/four_forms.cpp[tag=make,indent=0] +include::{examples}/four_forms.cpp[tag=from_secret,indent=0] ---- [source,cpp] @@ -398,10 +620,13 @@ message of `crypto::schnorr` instead, signed as given ==== Ethereum's digest Ethereum signs Keccak-256 digests with recoverable ECDSA -(link:https://ethereum.github.io/yellowpaper/paper.pdf[Ethereum's yellow -paper, appendix F]). A message given to `crypto::ecdsa_sha256_recoverable` is -hashed with SHA-256, which no Ethereum node computes, so an Ethereum library -gives its Keccak-256 digest as `+crypto::prehashed{digest}+`. The scheme cannot -tell it from a SHA-256 digest: it signs and recovers correctly, while the -tag's name says SHA-256. A scheme `ecdsa_keccak256_recoverable` would be the -honest name; it is an open question, not part of this version. +(link:https://ethereum.github.io/yellowpaper/paper.pdf[Ethereum's yellow paper, +appendix F]), and its scheme says so: `crypto::ecdsa_keccak256_recoverable` +hashes a message with Keccak-256, the original padding Ethereum uses and never +SHA3-256, and signs a digest the program builds, EIP-191's, EIP-712's or a +transaction's, given as `+crypto::prehashed{digest}+`. Its signature is the +`curves::secp256k1::recoverable_signature` of +`crypto::ecdsa_sha256_recoverable`, and a message recovered under the other +scheme, hashed with the other hash, gives another key, which the program's +comparison refuses. <> shows the digest, `v` and the +address, which the program computes. diff --git a/doc/ed25519.adoc b/doc/ed25519.adoc index 86dd987b..61d86184 100644 --- a/doc/ed25519.adoc +++ b/doc/ed25519.adoc @@ -22,27 +22,27 @@ specifications]) and of Solana's accounts WebCrypto has it too (link:https://www.w3.org/TR/WebCryptoAPI/[W3C]). Bitcoin, Ethereum and Nostr sign on secp256k1 instead (<>). -A `keypair` is made from a seed with `make(seed)`, or drawn from +A `keypair` is made from a seed with `from_secret(seed)`, or drawn from `random_device` with `generate()`; it gives its public key (`public_key()`), its seed back (`secret()`, a `secret<32>`), signs -(`sign(crypto::eddsa, message)`), and gives its X25519 secret key -(`x25519_secret`, a `secret<32>`), so that one seed serves for signatures and +(`sign(crypto::eddsa, message)`), and converts itself to an X25519 key pair +(`to_x25519()`, <>), so that one seed serves for signatures and for key agreement. The key pair wipes its secret key when it is moved from and destroyed. `crypto::verify(crypto::eddsa, signature, message, public_key)` checks a signature with the public key alone. The scheme `crypto::eddsa` signs the message itself, of any length: a `crypto::prehashed` digest does not -compile, and the key pair is a `crypto::keypair`, as every curve's is -(<>). +compile, and the key pair is a `crypto::signing_keypair` and no +`crypto::agreement_keypair` (<>). -A `public_key` is the 32 bytes of RFC 8032's encoded point: `public_key::make` +A `public_key` is the 32 bytes of RFC 8032's encoded point: `public_key::from_bytes` makes one from them, checking their size alone, and `bytes()` gives them back. Whether the point is canonical and not of small order is the verification policy's to judge, so a key that `crypto::verify` refuses can still be made. Each operation has its four forms, the member and its free form, synchronous and asynchronous, with the same work, errors and refusals -(<>); `public_key::make(bytes)` and -`crypto::make(bytes)` make the public key, synchronously only. +(<>); `public_key::from_bytes(bytes)` and +`crypto::from_bytes(bytes)` make the public key, synchronously only. Verification takes the policy as an optional last argument, before the token in the asynchronous forms. An asynchronous form needs `` and `/webcpp/asio//asio` in the Jamfile: @@ -53,10 +53,10 @@ in the asynchronous forms. An asynchronous form needs | Operation | Synchronous: the member; its free form | Asynchronous: the member; its free form | Make -| `keypair::make(seed)` + -`crypto::make(seed)` -| `keypair::async_make(executor, seed, token)` + -`crypto::async_make(executor, seed, token)` +| `keypair::from_secret(seed)` + +`crypto::from_secret(seed)` +| `keypair::async_from_secret(executor, seed, token)` + +`crypto::async_from_secret(executor, seed, token)` | Generate | `keypair::generate()` + @@ -77,15 +77,62 @@ in the asynchronous forms. An asynchronous form needs `crypto::async_verify(executor, crypto::eddsa, signature, message, public_key, token)` |=== -*Ed25519ph* signs the SHA-512 of a message instead of the message: a program -that signs a large file reads it in pieces, gives each to `update`, and signs -once at the end. Its type names the hash, `ph`, which -the header brings with it, since RFC 8032 fixes it; another hash does not -compile. It signs with a key pair, `sign(key_pair)`, and verifies with -`verify(signature, public_key)`, the signature first, as in every `verify`. -An Ed25519ph signature is not an Ed25519 signature of the -same message, and neither verifies as the other: a protocol says which of the -two it uses. +*Ed25519ph* signs the SHA-512 of a message instead of the message (RFC 8032's +prehashed form). A program that has the digest already signs it under the +scheme `crypto::eddsa_prehashed`, marked as one: +`+key_pair.sign(crypto::eddsa_prehashed, crypto::prehashed{digest})+`, `digest` +the 64 bytes of the message's SHA-512 (webcpp::hash's `sha2_512` computes it), +and `+crypto::verify(crypto::eddsa_prehashed, signature, crypto::prehashed{digest}, +public_key)+` or `+public_key.verify(crypto::eddsa_prehashed, signature, +crypto::prehashed{digest})+` checks it, strictly, as `crypto::eddsa` does. The +scheme takes the digest alone: a message, even one of 64 bytes, and a digest of +another size do not compile. + +A program that signs a large file it reads in pieces gives each to the +streaming signer, `prehashed_signer`, which hashes them, +and signs once at the end. Its type names the hash, which the header brings +with it, since RFC 8032 fixes it; another hash does not compile. It signs with a +key pair, `sign(key_pair)`, and verifies with `verify(signature, public_key)`, +the signature first, as in every `verify`; over the same message it gives the +signature the scheme gives of the message's SHA-512, and each verifies the +other's. + +Both give a `curves::ed25519::signature`, the type `crypto::eddsa` gives, but the +two schemes are not interchangeable: RFC 8032 separates their domains, so an +Ed25519ph signature is not an Ed25519 signature of the same message, and +neither verifies under the other scheme, which reports `invalid_signature`. A +protocol says which of the two it uses. + +Ed25519ph runs on a native backend: WebCrypto has no Ed25519ph, and on the +browser's backend every function under `crypto::eddsa_prehashed`, `sign`, +`verify` and their asynchronous forms, stops the build with that reason; sign +the message with `crypto::eddsa` there. On libsodium, the scheme calls the +internal Ed25519 function that libsodium's own Ed25519ph ends in, since its +public functions sign only a digest they computed; webcpp builds libsodium from +its sources, and RFC 8032's Ed25519ph vectors check the result on every target. + +.Ed25519ph's operations in their forms (native backends) +[cols="1,3,3",options="header"] +|=== +| Operation | Synchronous: the member; its free form | Asynchronous: the member; its free form + +| Sign a digest +| `+key_pair.sign(crypto::eddsa_prehashed, crypto::prehashed{digest})+` + +`+crypto::sign(key_pair, crypto::eddsa_prehashed, crypto::prehashed{digest})+` +| `+key_pair.async_sign(executor, crypto::eddsa_prehashed, crypto::prehashed{digest}, token)+` + +`+crypto::async_sign(executor, key_pair, crypto::eddsa_prehashed, crypto::prehashed{digest}, token)+` + +| Verify a digest +| `+public_key.verify(crypto::eddsa_prehashed, signature, crypto::prehashed{digest})+` + +`+crypto::verify(crypto::eddsa_prehashed, signature, crypto::prehashed{digest}, public_key)+` +| `+public_key.async_verify(executor, crypto::eddsa_prehashed, signature, crypto::prehashed{digest}, token)+` + +`+crypto::async_verify(executor, crypto::eddsa_prehashed, signature, crypto::prehashed{digest}, public_key, token)+` + +| A message in pieces +| `prehashed_signer::begin()`, `update(piece)`, then +`sign(key_pair)` or `verify(signature, public_key)` +| none +|=== include::generated/backends-ed25519_keypair.adoc[] @@ -96,7 +143,8 @@ include::generated/backends-ed25519_verify.adoc[] include::generated/backends-ed25519ph.adoc[] *Example.* RFC 8032's second test signed and verified, then its Ed25519ph test, -the message given in two pieces: +the message given in two pieces to the streaming signer, and its SHA-512 signed +under `crypto::eddsa_prehashed` into the same signature: [source,cpp] ---- diff --git a/doc/entropy.adoc b/doc/entropy.adoc index 627136ff..5b456df4 100644 --- a/doc/entropy.adoc +++ b/doc/entropy.adoc @@ -5,12 +5,12 @@ // https://www.boost.org/LICENSE_1_0.txt) [#crypto-entropy] -=== Entropy +==== Entropy A *cryptographically secure random number generator* produces numbers that an attacker cannot predict, even after seeing many of them (link:https://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator[Wikipedia]). -Every secret a program makes starts there: a key, an IV, a session token, a +Every secret a program makes starts there: a key, a nonce, a session token, a password-reset link. A general-purpose generator such as `std::mt19937` or `rand` is built to look random, not to resist an attacker: a few outputs reveal its state and every output after them @@ -36,8 +36,34 @@ There is no weaker fallback, ever: no clock, no `rand`, no address. When the source fails, `fill` returns `entropy_unavailable` and zeroes its output, so that nothing the caller could use by mistake is left in it; where there is no source at all (an Emscripten audio worklet, which has no `crypto`), it returns -`errc::not_supported`. The function asks in pieces of at most 256 bytes, the -limit of `getentropy`, and checks every call. +`errc::not_supported`. In the browser and in node, a `crypto.getRandomValues` +that throws (replaced by a script of the page, or refused by its host) gives +`entropy_unavailable` too, and the program runs on: crypto calls it itself and +catches the exception, where Emscripten's `getentropy` would let it unwind +through WebAssembly and terminate the program. Node 18, which Emscripten still +supports, has no global `crypto` without `--experimental-global-webcrypto`: +there crypto draws from `require('node:crypto').webcrypto`, the same +generator under another name, not a weaker one. The function asks in pieces +of at most 256 bytes, the limit of `getentropy`, and checks every call. + +On Emscripten, libsodium draws through crypto too. Its own JavaScript generator +throws when `crypto.getRandomValues` and node's `randomBytes` both fail, and +the exception terminates the program; crypto installs its generator in its +place (`randombytes_set_implementation`) before its first libsodium call. +Until libsodium is initialised, every function on libsodium first draws a few +bytes, and returns `entropy_unavailable` when the source fails, or +`errc::not_supported` where there is none, without initialising libsodium: the +canary `sodium_init` draws guards the program's own `sodium_malloc` +allocations, and a source that already fails never leaves it zero (only one +that fails between that first draw and the one of `sodium_init` could, and the +call then returns its error too). The next call tries again; once libsodium is +initialised, a function that draws nothing (a signature, a key pair from its +secret) runs whatever the source does. A sealed box whose ephemeral key cannot +be drawn returns the same errors, its output zeroed. A draw that fails in a +libsodium function the program calls itself, which no crypto call observes, +ends the program through `sodium_misuse`, as libsodium does natively, rather +than hand on zeros. A program that sets its own libsodium generator sets it +after crypto's first libsodium call, or crypto's replaces it. `fill(bytes)` is the interface. With exceptions, `random_device` is also a standard random bit generator, shaped as `std::random_device`: its @@ -78,7 +104,7 @@ favours small codes. `std::uniform_int_distribution` does not. to use, and the operation that needed one fails. [#crypto-entropy-bearssl] -==== Seeding BearSSL's own generator +===== Seeding BearSSL's own generator A program that calls BearSSL's C API directly, for something crypto does not wrap, seeds BearSSL's generators from `random_device`: crypto builds BearSSL diff --git a/doc/erase_secret.adoc b/doc/erase_secret.adoc new file mode 100644 index 00000000..ed7ea38d --- /dev/null +++ b/doc/erase_secret.adoc @@ -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-erase-secret] +==== Erasing a secret from a buffer + +A password read from a form, a key loaded from a file or a plaintext just +decrypted sits in a buffer of the program's own: a `std::string`, a +`std::vector`, an array. Once the program is done with it, the secret should +not stay in memory, where a crash dump, a swapped page or a later bug that reads +freed memory would find it. + +`memset` does not do that reliably. A buffer that is zeroed and then never read +again is a dead store, and an optimising compiler removes it: the zeroes are +never written and the secret stays +(link:https://cwe.mitre.org/data/definitions/14.html[CWE-14]). +`erase_secret`, in ``, writes through a +volatile pointer and then a signal fence, as `secret` does when it is +destroyed, so the stores are kept: + +[source,cpp] +---- +include::{library-root}/test/erase_secret_test.cpp[tag=erase,indent=0] +---- + +It takes any contiguous sized range of elements the program may write and that +are trivially copyable: a `std::vector`, a `std::string`, a +`std::array`, a `std::span`, a C array. It erases +`size() * sizeof(element)` bytes from the first element: a string's size, not +its capacity. A const range, or one of elements that are not trivially +copyable, stops the build with a message naming the ranges it takes; a range +that is not contiguous, such as a `std::list`, has no `erase_secret`. It calls +no backend and never fails. + +include::generated/backends-erase_secret.adoc[] + +*What it is not.* + +* It erases the bytes it is given, and only those. A `std::string` or a + `std::vector` that grew has left earlier copies in the memory it freed, and a + copy, a move or a temporary may hold the secret in another object or a + register: reserve the buffer's size first, and keep the secret in one place. +* It does not lock the memory: the page may still be swapped to disk before the + call. Locking it (`mlock`, `VirtualLock`) is the program's, and has no + equivalent on WebAssembly. +* A secret that crypto returns is already a `secret`, which erases itself: + `erase_secret` is for the buffers the program fills itself. diff --git a/doc/errors.adoc b/doc/errors.adoc index 5d835830..1add13d1 100644 --- a/doc/errors.adoc +++ b/doc/errors.adoc @@ -13,7 +13,7 @@ reports the failure with an `error` of the category `webcpp.crypto`, as a and never reused, so a program may store them. A program tells failures apart because they call for different answers. -`authentication_failed` means the data, its additional data or its tag changed +`authentication_failed` means the data, its associated data or its tag changed since it was sealed, or the key is another: someone may be attacking, and the message is dropped. A size error means the caller or the wire format is wrong: a bug to fix, not an attack. `entropy_unavailable` means there is no safe @@ -25,13 +25,14 @@ 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_iv_size` |A GCM IV that is empty or longer than 128 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. |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, a DER output shorter than `max_der_size`, or the incremental open's `decrypt` past the authenticated length and `end_open` short of it. -|5 |`message_too_long` |A message or additional data longer than the algorithm allows. -|6 |`authentication_failed` |The tag does not match: the message or its additional data changed, or +|5 |`message_too_long` |A message or associated data longer than the algorithm allows. +|6 |`authentication_failed` |The tag does not match: the message or its associated data changed, or the key differs. |7 |`invalid_state` |An object moved from, or the incremental seal or open called out of order. |8 |`entropy_unavailable` |The system's or the browser's generator failed, or secp256k1's `generate` @@ -47,7 +48,7 @@ DER, or an r or an s that is zero or not below the group order. already allocated, or another party installed its own. From `backends::openssl::install_memory_functions`, with `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE`. |14 |`memory_functions_not_installed` |OpenSSL's memory functions are not webcpp::crypto's. From -every `make` of the OpenSSL backend, with `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE`. +every `from_key` of the OpenSSL backend, with `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE`. |15 |`weak_public_key` |A public key of small order, or one that gives an all-zero shared secret. |16 |`invalid_point` |An encoding that is not a canonical element of the group. |17 |`invalid_scalar` |A scalar that is not reduced, or zero where zero is refused. @@ -60,7 +61,7 @@ not the one encoding the format allows. A value that `error` does not define has the message "unknown webcpp.crypto error". `random_device` also returns -`errc::not_supported` where there is no generator at all, and OpenSSL's `make` +`errc::not_supported` where there is no generator at all, and OpenSSL's `from_key` `errc::not_enough_memory` when OpenSSL cannot allocate its context. `memory_functions_refused` and `memory_functions_not_installed` come only with OpenSSL's memory option, natively: <> says what each @@ -69,7 +70,7 @@ means and what to do. include::generated/backends-error.adoc[] *Example.* A message is sealed, then opened three ways: with a flipped bit, -with an empty IV and with a short tag. Only the first is an attack, and only +with an empty nonce and with a short tag. Only the first is an attack, and only the first decrypted anything, which `open` has zeroed: [source,cpp] @@ -108,5 +109,5 @@ exceptions (the compiler has none, or the program defined for crypto alone. One function throws: `random_device::operator()`, through `boost::throw_exception`, because the standard's random bit generator has no other way to report a failure; it is declared only when the macro is not -defined. `keypair::make` lets the program's memory resource report a failed +defined. `keypair::from_secret` lets the program's memory resource report a failed allocation as the resource does. diff --git a/doc/everyday.adoc b/doc/everyday.adoc index 1a737011..00570f92 100644 --- a/doc/everyday.adoc +++ b/doc/everyday.adoc @@ -26,8 +26,9 @@ and the recipient are never online together. encrypted once under a key drawn for that file alone, and that file key is encrypted to each recipient's X25519 public key, with a key pair drawn for the purpose, so that the recipient's secret key alone recovers it. webcpp's -primitives do the same in libsodium's formats: the file in a secret box -(<>) under a fresh 32-byte key, and the key in a sealed box +primitives do the same in libsodium's formats: the file in a secret box, +`secret_key_encryption::secretbox<>` (<>), under a fresh +32-byte key, and the key in a sealed box to the recipient (<>). Each file has its own key, so a leaked key opens one file; the tag of each box makes any change to the upload fail to open, never decrypt to something else. age's own steps, its header, @@ -63,7 +64,7 @@ back on an unencrypted copy. A sealed box says nothing of who sent it: an app where the sender matters signs the upload (<>) or uses a box between the two key pairs (<>). A large file cut into separate boxes is safe only when each chunk's tag also covers its number and a -flag marking the last chunk, in the additional data or in a nonce built from +flag marking the last chunk, in the associated data or in a nonce built from them, and a reader refuses chunks out of order and a stream that ends without the last flag: otherwise whoever holds the ciphertext reorders, drops, repeats or truncates chunks and each one still opens. The @@ -82,8 +83,8 @@ when the token comes back, so that a leaked database hands out no live session or reset link (OWASP asks that reset tokens be stored securely, link:https://cheatsheetseries.owasp.org/cheatsheets/Forgot_Password_Cheat_Sheet.html[Forgot Password Cheat Sheet]); a random token of 32 bytes needs no slow password hash. -`equal` is for a token or a MAC checked against one value the program already -knows. <> shows the program, `reset_token`. +`constant_time_equal` is for a token or a MAC checked against one value the +program already knows. <> shows the program, `reset_token`. A password itself is never encrypted: it is hashed with a slow password hash, Argon2id or scrypt, which link:{webcpp-libs}/hash/{webcpp-page}#hash-password-hashing[webcpp::hash's password hashing] gives, not @@ -94,14 +95,15 @@ crypto. A payment provider or a source-code host signs each call to a program's webhook with an HMAC under a shared secret. The program recomputes it with -Boost.Hash2 and compares with `equal`, never `==`: <>. +Boost.Hash2 and compares with `constant_time_equal`, never `==`: +<>. [#crypto-everyday-storage] === A database field, a cookie, a file Data stored where someone else may read it, a database, a cookie, a cloud bucket, is sealed with AES-GCM, with what it belongs to (the user's id, the -cookie's name, the file's path) as additional data, so that it cannot be moved +cookie's name, the file's path) as associated data, so that it cannot be moved to another place: <>. A large file is sealed in records: <>. diff --git a/doc/generated/backend-facts.adoc b/doc/generated/backend-facts.adoc index 5addc5a4..37d8dd65 100644 --- a/doc/generated/backend-facts.adoc +++ b/doc/generated/backend-facts.adoc @@ -43,7 +43,7 @@ |no backend |`+/webcpp/crypto//crypto+` -|`++`, `++` +|`++`, `++`, `++` |native, wasip2, wasip3, emscripten |=== @@ -63,7 +63,7 @@ The library behind each, and what it costs a program: |OpenSSL 3.5.9's libcrypto, built from source and static |Apache-2.0 |`++` -|`+make+` allocates the cipher's context through OpenSSL's own allocator, outside the program's resource, unless a native program sets `+WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE+`, which sends every allocation of OpenSSL's in the process to `+openssl_memory_resource()+`; a message allocates nothing after `+make+` +|`+from_key+` allocates the cipher's context through OpenSSL's own allocator, outside the program's resource, unless a native program sets `+WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE+`, which sends every allocation of OpenSSL's in the process to `+openssl_memory_resource()+`; a message allocates nothing after `+from_key+` |ctaes |ctaes as Bitcoin Core v31.1 ships it (`+src/crypto/ctaes+`), built from source @@ -75,7 +75,7 @@ The library behind each, and what it costs a program: |libsecp256k1 v0.8.0, built from source with every module on |MIT |`++` and its modules -|`+keypair::make+` allocates the signing context, once, in the `+std::pmr::memory_resource+` it is given; nothing else allocates +|`+keypair::from_secret+` allocates the signing context, once, in the `+std::pmr::memory_resource+` it is given; nothing else allocates |libsodium |libsodium 1.0.22, built from source diff --git a/doc/generated/backends-async_ed25519.adoc b/doc/generated/backends-async_ed25519.adoc index 0e9c9831..7dd0bdda 100644 --- a/doc/generated/backends-async_ed25519.adoc +++ b/doc/generated/backends-async_ed25519.adoc @@ -7,7 +7,7 @@ // 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_make+`, `+async_generate+`, `+async_sign+`, `+async_verify+`, from the test programs that run it: +The backends of `+async_from_secret+`, `+async_generate+`, `+async_sign+`, `+async_verify+`, from the test programs that run it: [cols="1,2,2,4",options="header"] |=== diff --git a/doc/generated/backends-async_gcm.adoc b/doc/generated/backends-async_gcm.adoc index c76e3122..d78077d9 100644 --- a/doc/generated/backends-async_gcm.adoc +++ b/doc/generated/backends-async_gcm.adoc @@ -7,7 +7,7 @@ // 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_make+`, `+async_seal+`, `+async_open+`, from the test programs that run it: +The backends of `+async_from_key+`, `+secret_key_encryption::aead::async_seal+`, `+secret_key_encryption::aead::async_open+`, from the test programs that run it: [cols="1,2,2,4",options="header"] |=== @@ -22,4 +22,9 @@ The backends of `+async_make+`, `+async_seal+`, `+async_open+`, from the test pr |`+/webcpp/crypto//openssl+` |`++` |native, wasip2, wasip3 (tested by `+async_gcm_openssl+`); not on emscripten: `+/webcpp/crypto//openssl+` stops the build there + +|libsodium +|`+/third_party//sodium+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+async_aead+`) |=== diff --git a/doc/generated/backends-async_p256.adoc b/doc/generated/backends-async_p256.adoc index b75657f6..983ffbb8 100644 --- a/doc/generated/backends-async_p256.adoc +++ b/doc/generated/backends-async_p256.adoc @@ -7,7 +7,7 @@ // 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_make+`, `+async_generate+`, `+async_sign+`, `+async_verify+`, `+async_agree+`, from the test programs that run it: +The backends of `+async_from_secret+`, `+async_generate+`, `+async_sign+`, `+async_verify+`, `+async_agree+`, from the test programs that run it: [cols="1,2,2,4",options="header"] |=== diff --git a/doc/generated/backends-async_x25519.adoc b/doc/generated/backends-async_x25519.adoc index 6dabaafc..658e787e 100644 --- a/doc/generated/backends-async_x25519.adoc +++ b/doc/generated/backends-async_x25519.adoc @@ -7,7 +7,7 @@ // 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_agree+`, from the test programs that run it: +The backends of `+async_from_secret+`, `+async_generate+`, `+async_agree+`, from the test programs that run it: [cols="1,2,2,4",options="header"] |=== diff --git a/doc/generated/backends-box.adoc b/doc/generated/backends-box.adoc index 1084cf66..5e7b9214 100644 --- a/doc/generated/backends-box.adoc +++ b/doc/generated/backends-box.adoc @@ -7,7 +7,7 @@ // Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, // the message tests and the Jamfile fixtures: run it again, never edit this file. -The backends of `+hybrid::box+`, from the test programs that run it: +The backends of `+public_key_encryption::box+`, from the test programs that run it: [cols="1,2,2,4",options="header"] |=== diff --git a/doc/generated/backends-box_xchacha20poly1305.adoc b/doc/generated/backends-box_xchacha20poly1305.adoc index e5fb2085..caa11063 100644 --- a/doc/generated/backends-box_xchacha20poly1305.adoc +++ b/doc/generated/backends-box_xchacha20poly1305.adoc @@ -7,7 +7,7 @@ // Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, // the message tests and the Jamfile fixtures: run it again, never edit this file. -The backends of `+hybrid::box_xchacha20poly1305+`, from the test programs that run it: +The backends of `+public_key_encryption::box_xchacha20poly1305+`, from the test programs that run it: [cols="1,2,2,4",options="header"] |=== diff --git a/doc/generated/backends-constant_time_equal.adoc b/doc/generated/backends-constant_time_equal.adoc new file mode 100644 index 00000000..4ce07b37 --- /dev/null +++ b/doc/generated/backends-constant_time_equal.adoc @@ -0,0 +1,20 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, +// the message tests and the Jamfile fixtures: run it again, never edit this file. + +The backends of `+constant_time_equal+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|no backend +|`+/webcpp/crypto//crypto+` +|`++`, `++`, `++` +|native, wasip2, wasip3, emscripten (tested by `+constant_time_equal+`) +|=== diff --git a/doc/generated/backends-ed25519_to_x25519_public.adoc b/doc/generated/backends-ed25519_to_x25519.adoc similarity index 83% rename from doc/generated/backends-ed25519_to_x25519_public.adoc rename to doc/generated/backends-ed25519_to_x25519.adoc index 523c412a..e5b79db7 100644 --- a/doc/generated/backends-ed25519_to_x25519_public.adoc +++ b/doc/generated/backends-ed25519_to_x25519.adoc @@ -7,7 +7,7 @@ // Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, // the message tests and the Jamfile fixtures: run it again, never edit this file. -The backends of `+curves::ed25519::to_x25519_public+`, from the test programs that run it: +The backends of `+crypto::to_x25519+`, from the test programs that run it: [cols="1,2,2,4",options="header"] |=== @@ -16,7 +16,7 @@ The backends of `+curves::ed25519::to_x25519_public+`, from the test programs th |libsodium |`+/third_party//sodium+` |`++` -|native, wasip2, wasip3, emscripten (tested by `+x25519_sodium+`) +|native, wasip2, wasip3, emscripten (tested by `+ed25519_sodium+`, `+x25519_sodium+`) |=== A call that names no backend takes the family's default on each target, whatever the program links, as <> gives it with its reasons and tests: diff --git a/doc/generated/backends-ed25519ph.adoc b/doc/generated/backends-ed25519ph.adoc index 3e1330dc..917309bd 100644 --- a/doc/generated/backends-ed25519ph.adoc +++ b/doc/generated/backends-ed25519ph.adoc @@ -7,7 +7,7 @@ // Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, // the message tests and the Jamfile fixtures: run it again, never edit this file. -The backends of `+curves::ed25519::ph+`, from the test programs that run it: +The backends of `+curves::ed25519::prehashed_signer+`, from the test programs that run it: [cols="1,2,2,4",options="header"] |=== diff --git a/doc/generated/backends-equal.adoc b/doc/generated/backends-erase_secret.adoc similarity index 66% rename from doc/generated/backends-equal.adoc rename to doc/generated/backends-erase_secret.adoc index 953e9102..22872a0d 100644 --- a/doc/generated/backends-equal.adoc +++ b/doc/generated/backends-erase_secret.adoc @@ -7,7 +7,7 @@ // 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 `+equal+`, from the test programs that run it: +The backends of `+erase_secret+`, from the test programs that run it: [cols="1,2,2,4",options="header"] |=== @@ -15,6 +15,6 @@ The backends of `+equal+`, from the test programs that run it: |no backend |`+/webcpp/crypto//crypto+` -|`++`, `++` -|native, wasip2, wasip3, emscripten (tested by `+equal+`) +|`++`, `++`, `++` +|native, wasip2, wasip3, emscripten (tested by `+erase_secret+`) |=== diff --git a/doc/generated/backends-error.adoc b/doc/generated/backends-error.adoc index 68980720..6f8c9b6c 100644 --- a/doc/generated/backends-error.adoc +++ b/doc/generated/backends-error.adoc @@ -15,6 +15,6 @@ The backends of `+error+`, from the test programs that run it: |no backend |`+/webcpp/crypto//crypto+` -|`++`, `++` +|`++`, `++`, `++` |native, wasip2, wasip3, emscripten (tested by `+error+`) |=== diff --git a/doc/generated/backends-key_tweaks.adoc b/doc/generated/backends-key_tweaks.adoc index d47d8092..dafebf48 100644 --- a/doc/generated/backends-key_tweaks.adoc +++ b/doc/generated/backends-key_tweaks.adoc @@ -7,7 +7,7 @@ // Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, // the message tests and the Jamfile fixtures: run it again, never edit this file. -The backends of `+curves::secp256k1::seckey_tweak_add+`, `+seckey_tweak_mul+`, `+seckey_negate+`, `+pubkey_tweak_add+`, `+pubkey_tweak_mul+`, `+pubkey_negate+`, `+pubkey_combine+`, from the test programs that run it: +The backends of `+curves::secp256k1::secret_key_tweak_add+`, `+secret_key_tweak_mul+`, `+secret_key_negate+`, `+public_key_tweak_add+`, `+public_key_tweak_mul+`, `+public_key_negate+`, `+public_key_combine+`, from the test programs that run it: [cols="1,2,2,4",options="header"] |=== diff --git a/doc/generated/backends-kx_keypair.adoc b/doc/generated/backends-kx_keypair.adoc index d9b87ed1..6e43a9ee 100644 --- a/doc/generated/backends-kx_keypair.adoc +++ b/doc/generated/backends-kx_keypair.adoc @@ -7,7 +7,7 @@ // Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, // the message tests and the Jamfile fixtures: run it again, never edit this file. -The backends of `+curves::x25519::kx_keypair+`, from the test programs that run it: +The backends of `+key_exchange::kx_keypair+`, from the test programs that run it: [cols="1,2,2,4",options="header"] |=== diff --git a/doc/generated/backends-musig.adoc b/doc/generated/backends-musig.adoc index b1ff2f21..71459516 100644 --- a/doc/generated/backends-musig.adoc +++ b/doc/generated/backends-musig.adoc @@ -7,7 +7,7 @@ // Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, // the message tests and the Jamfile fixtures: run it again, never edit this file. -The backends of `+curves::secp256k1::musig::aggregate_key+`, `+key_aggregate+`, `+nonce_gen+`, `+nonce_aggregate+`, `+nonce_process+`, `+partial_sign+`, `+partial_signature_verify+`, `+partial_signature_aggregate+`, `+parse_public_nonce+`, `+serialize_public_nonce+`, `+parse_aggregate_nonce+`, `+serialize_aggregate_nonce+`, `+parse_partial_signature+`, `+serialize_partial_signature+`, from the test programs that run it: +The backends of `+curves::secp256k1::musig::aggregate_key+`, `+key_aggregate+`, `+generate_nonce+`, `+nonce_aggregate+`, `+nonce_process+`, `+partial_sign+`, `+partial_signature_verify+`, `+partial_signature_aggregate+`, `+parse_public_nonce+`, `+serialize_public_nonce+`, `+parse_aggregate_nonce+`, `+serialize_aggregate_nonce+`, `+parse_partial_signature+`, `+serialize_partial_signature+`, from the test programs that run it: [cols="1,2,2,4",options="header"] |=== diff --git a/doc/generated/backends-sealed_box.adoc b/doc/generated/backends-sealed_box.adoc index 9bd50659..e5ee2938 100644 --- a/doc/generated/backends-sealed_box.adoc +++ b/doc/generated/backends-sealed_box.adoc @@ -7,7 +7,7 @@ // Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, // the message tests and the Jamfile fixtures: run it again, never edit this file. -The backends of `+hybrid::sealed_box+`, from the test programs that run it: +The backends of `+public_key_encryption::sealed_box+`, from the test programs that run it: [cols="1,2,2,4",options="header"] |=== diff --git a/doc/generated/backends-secretbox.adoc b/doc/generated/backends-secretbox.adoc index 8a1dc1aa..3d260ce4 100644 --- a/doc/generated/backends-secretbox.adoc +++ b/doc/generated/backends-secretbox.adoc @@ -7,7 +7,7 @@ // Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, // the message tests and the Jamfile fixtures: run it again, never edit this file. -The backends of `+ciphers::secretbox+`, from the test programs that run it: +The backends of `+secret_key_encryption::secretbox+`, from the test programs that run it: [cols="1,2,2,4",options="header"] |=== @@ -16,7 +16,7 @@ The backends of `+ciphers::secretbox+`, from the test programs that run it: |libsodium |`+/third_party//sodium+` |`++` -|native, wasip2, wasip3, emscripten (tested by `+secretbox_sodium+`, `+box_sodium+`, `+allocation_sodium+`) +|native, wasip2, wasip3, emscripten (tested by `+secretbox_sodium+`, `+box_sodium+`, `+allocation_sodium+`, `+aead_concepts+`) |=== `+secretbox<>+` names the default backend. The default per target, whatever the program links, as <> gives it with its reasons and tests: diff --git a/doc/generated/backends-secretbox_xchacha20poly1305.adoc b/doc/generated/backends-secretbox_xchacha20poly1305.adoc index 3b5cc94c..e8ef52fe 100644 --- a/doc/generated/backends-secretbox_xchacha20poly1305.adoc +++ b/doc/generated/backends-secretbox_xchacha20poly1305.adoc @@ -7,7 +7,7 @@ // Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, // the message tests and the Jamfile fixtures: run it again, never edit this file. -The backends of `+ciphers::secretbox_xchacha20poly1305+`, from the test programs that run it: +The backends of `+secret_key_encryption::secretbox_xchacha20poly1305+`, from the test programs that run it: [cols="1,2,2,4",options="header"] |=== @@ -16,7 +16,7 @@ The backends of `+ciphers::secretbox_xchacha20poly1305+`, from the test programs |libsodium |`+/third_party//sodium+` |`++` -|native, wasip2, wasip3, emscripten (tested by `+secretbox_sodium+`, `+box_sodium+`, `+allocation_sodium+`) +|native, wasip2, wasip3, emscripten (tested by `+secretbox_sodium+`, `+box_sodium+`, `+allocation_sodium+`, `+aead_concepts+`) |=== `+secretbox_xchacha20poly1305<>+` names the default backend. The default per target, whatever the program links, as <> gives it with its reasons and tests: diff --git a/doc/generated/backends-silent_payments.adoc b/doc/generated/backends-silent_payments.adoc index bf6dbaeb..d37c930b 100644 --- a/doc/generated/backends-silent_payments.adoc +++ b/doc/generated/backends-silent_payments.adoc @@ -7,7 +7,7 @@ // Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, // the message tests and the Jamfile fixtures: run it again, never edit this file. -The backends of `+curves::secp256k1::silent_payments::create_outputs+`, `+create_label+`, `+create_labeled_spend_key+`, `+make_prevouts_summary+`, `+scan_outputs+`, `+send_workspace_size+`, `+summary_workspace_size+`, `+scan_workspace_size+`, from the test programs that run it: +The backends of `+curves::secp256k1::silent_payments::create_outputs+`, `+create_label+`, `+create_labeled_spend_key+`, `+make_previous_outputs_summary+`, `+scan_outputs+`, `+send_workspace_size+`, `+summary_workspace_size+`, `+scan_workspace_size+`, from the test programs that run it: [cols="1,2,2,4",options="header"] |=== diff --git a/doc/generated/backends-x25519_agree.adoc b/doc/generated/backends-x25519_keypair.adoc similarity index 91% rename from doc/generated/backends-x25519_agree.adoc rename to doc/generated/backends-x25519_keypair.adoc index 668b5958..1d96c63f 100644 --- a/doc/generated/backends-x25519_agree.adoc +++ b/doc/generated/backends-x25519_keypair.adoc @@ -7,7 +7,7 @@ // Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, // the message tests and the Jamfile fixtures: run it again, never edit this file. -The backends of `+curves::x25519::agree+`, from the test programs that run it: +The backends of `+curves::x25519::keypair+`, from the test programs that run it: [cols="1,2,2,4",options="header"] |=== diff --git a/doc/generated/constant-time.adoc b/doc/generated/constant-time.adoc index 89f34a55..2f2179ff 100644 --- a/doc/generated/constant-time.adoc +++ b/doc/generated/constant-time.adoc @@ -13,8 +13,8 @@ |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 with webcpp's fix, since upstream's decoding of the RFC 6979 nonce branches on its 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 fix: link:https://github.com/webcpporg/bearssl/commit/32381d6e787a32cbb7a687246349200d78b8ff7c[webcpporg/bearssl, commit 32381d6 on its branch webcpp: the header set back to the order's length before the shift, in ecdsa_i31_bits.c and ecdsa_i15_bits.c]); 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::prehashed+`), which makes its signature low S without a branch, then `+normalize_low_s+` and `+is_low_s+` on it, `+agree+` and `+decode_pkcs8+`; BearSSL's own branches on its signing's verdicts listed in `+bearssl_verdicts.supp+`; nothing found with webcpp's fix to BearSSL's decoding of the nonce, whose leak of the nonce's bit length this checker found on 2026-11-21, including `+sign+` with its low-S step (Valgrind 3.22, arm64 Linux container, 2026-11-22)); MemorySanitizer (Linux, clang): AES-GCM, ChaCha20-Poly1305, P-256 (the same paths as memcheck's; for the previous signing, found the same leak, nothing after the fix, including `+sign+` with its low-S step (clang 18, arm64 Linux container, 2026-11-22)); 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 (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)) +|Valgrind's memcheck (Linux): AES-GCM, ChaCha20-Poly1305, P-256 (the key pair's making, `+sign+` of a digest (`+crypto::prehashed+`), which makes its signature low S without a branch, then `+normalize_low_s+` and `+is_low_s+` on it, `+agree+` and `+decode_pkcs8+`; BearSSL's own branches on its signing's verdicts listed in `+bearssl_verdicts.supp+`; nothing found with webcpp's fix to BearSSL's decoding of the nonce, whose leak of the nonce's bit length this checker found on 2026-11-21, including `+sign+` with its low-S step (Valgrind 3.22, arm64 Linux container, 2026-11-22)); MemorySanitizer (Linux, clang): AES-GCM, ChaCha20-Poly1305, P-256 (the same paths as memcheck's; for the previous signing, found the same leak, nothing after the fix, including `+sign+` with its low-S step (clang 18, arm64 Linux container, 2026-11-22)); 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 (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)) |not measured yet |not measured yet @@ -34,7 +34,7 @@ |libsecp256k1 |by design: signing and key generation are constant time and constant memory access; link:https://github.com/bitcoin-core/secp256k1#readme[libsecp256k1's README] -|Valgrind's memcheck (Linux): secp256k1 (libsecp256k1's own `+ctime_tests.c+`, and webcpp's code around it: the key pair's making and `+secret()+`, its signatures and x-only tweak, ECDH in three forms (`+agree+`, `+agree_hashed+` and `+agree_point+`), the secret key's tweaks and negation, and PKCS#8), ElligatorSwift (libsecp256k1's own `+ctime_tests.c+`, and webcpp's `+ellswift_create+` and `+ellswift_xdh+` around it), MuSig2 (libsecp256k1's own `+ctime_tests.c+`, and webcpp's `+nonce_gen+` and `+partial_sign+` around it), BIP 352 silent payments (libsecp256k1's own `+ctime_tests.c+`, and webcpp's `+create_outputs+`, `+create_label+` and `+scan_outputs+` around it, each workspace's wipe included); MemorySanitizer (Linux, clang): secp256k1 (the same paths as memcheck's), ElligatorSwift (the same paths as memcheck's), MuSig2 (the same paths as memcheck's), BIP 352 silent payments (the same paths as memcheck's); dudect (judged; on a runner GitHub hosts, by two of three runs): secp256k1 (`+agree+`) +|Valgrind's memcheck (Linux): secp256k1 (libsecp256k1's own `+ctime_tests.c+`, and webcpp's code around it: the key pair's making and `+secret()+`, its signatures and x-only tweak, ECDH in three forms (`+agree+`, `+agree_hashed+` and `+agree_point+`), the secret key's tweaks and negation, and PKCS#8), ElligatorSwift (libsecp256k1's own `+ctime_tests.c+`, and webcpp's `+ellswift_create+` and `+ellswift_xdh+` around it), MuSig2 (libsecp256k1's own `+ctime_tests.c+`, and webcpp's `+generate_nonce+` and `+partial_sign+` around it), BIP 352 silent payments (libsecp256k1's own `+ctime_tests.c+`, and webcpp's `+create_outputs+`, `+create_label+` and `+scan_outputs+` around it, each workspace's wipe included); MemorySanitizer (Linux, clang): secp256k1 (the same paths as memcheck's), ElligatorSwift (the same paths as memcheck's), MuSig2 (the same paths as memcheck's), BIP 352 silent payments (the same paths as memcheck's); dudect (judged; on a runner GitHub hosts, by two of three runs): secp256k1 (`+agree+`) |dudect (judged; on a runner GitHub hosts, by two of three runs): secp256k1 (`+agree+`) |not measured yet |not measured yet @@ -54,9 +54,9 @@ |not measured yet |no backend -|`+equal+` is constant time in the contents: every byte is read, no branch and no index depends on one -|Valgrind's memcheck (Linux): `+equal+`, `+is_all_zero+` and the wipe of `+secret+`; MemorySanitizer (Linux, clang): `+equal+`, `+is_all_zero+` and the wipe of `+secret+`; dudect (judged; on a runner GitHub hosts, by two of three runs): `+equal+` -|dudect (judged; on a runner GitHub hosts, by two of three runs): `+equal+` +|`+constant_time_equal+` is constant time in the contents: every byte is read, no branch and no index depends on one +|Valgrind's memcheck (Linux): `+constant_time_equal+`, `+is_all_zero+` and the wipe of `+secret+`; MemorySanitizer (Linux, clang): `+constant_time_equal+`, `+is_all_zero+` and the wipe of `+secret+`; dudect (judged; on a runner GitHub hosts, by two of three runs): `+constant_time_equal+` +|dudect (judged; on a runner GitHub hosts, by two of three runs): `+constant_time_equal+` |not measured yet |not measured yet |=== diff --git a/doc/generated/matrix.adoc b/doc/generated/matrix.adoc index ca6fc360..fbeea4fe 100644 --- a/doc/generated/matrix.adoc +++ b/doc/generated/matrix.adoc @@ -16,35 +16,45 @@ |native, wasip2, wasip3, emscripten |`+random_device+` -|`+async_make+`, `+async_seal+`, `+async_open+` +|`+async_from_key+`, `+secret_key_encryption::aead::async_seal+`, `+secret_key_encryption::aead::async_open+` |BearSSL |native, wasip2, wasip3, emscripten |`+async_gcm+` -|`+async_make+`, `+async_seal+`, `+async_open+` +|`+async_from_key+`, `+secret_key_encryption::aead::async_seal+`, `+secret_key_encryption::aead::async_open+` |OpenSSL |native, wasip2, wasip3; not on emscripten: `+/webcpp/crypto//openssl+` stops the build there |`+async_gcm_openssl+` -|`+async_make+`, `+async_generate+`, `+async_sign+`, `+async_verify+` +|`+async_from_key+`, `+secret_key_encryption::aead::async_seal+`, `+secret_key_encryption::aead::async_open+` +|libsodium +|native, wasip2, wasip3, emscripten +|`+async_aead+` + +|`+async_from_secret+`, `+async_generate+`, `+async_sign+`, `+async_verify+` |libsodium |native, wasip2, wasip3, emscripten |`+async_25519+`, `+async_post+` -|`+async_agree+` +|`+async_from_secret+`, `+async_generate+`, `+async_agree+` |libsodium |native, wasip2, wasip3, emscripten |`+async_25519+` -|`+async_make+`, `+async_generate+`, `+async_sign+`, `+async_verify+`, `+async_agree+` +|`+async_from_secret+`, `+async_generate+`, `+async_sign+`, `+async_verify+`, `+async_agree+` |BearSSL |native, wasip2, wasip3, emscripten |`+async_p256+` -|`+equal+` +|`+constant_time_equal+` |no backend |native, wasip2, wasip3, emscripten -|`+equal+` +|`+constant_time_equal+` + +|`+erase_secret+` +|no backend +|native, wasip2, wasip3, emscripten +|`+erase_secret+` |`+error+` |no backend @@ -131,25 +141,25 @@ |native, wasip2, wasip3, emscripten |`+ed25519_sodium+`, `+ed25519_wycheproof_sodium+`, `+ed25519_speccheck+`, `+oracle_25519+` -|`+curves::ed25519::ph+` +|`+curves::ed25519::prehashed_signer+` |libsodium |native, wasip2, wasip3, emscripten |`+ed25519ph_sodium+` -|`+curves::ed25519::to_x25519_public+` +|`+crypto::to_x25519+` |libsodium |native, wasip2, wasip3, emscripten -|`+x25519_sodium+` +|`+ed25519_sodium+`, `+x25519_sodium+` -|`+curves::x25519::public_key+` +|`+curves::x25519::keypair+` |libsodium |native, wasip2, wasip3, emscripten -|`+x25519_sodium+`, `+oracle_25519+` +|`+x25519_sodium+`, `+x25519_wycheproof_sodium+`, `+oracle_25519+` -|`+curves::x25519::agree+` +|`+curves::x25519::public_key+` |libsodium |native, wasip2, wasip3, emscripten -|`+x25519_sodium+`, `+x25519_wycheproof_sodium+`, `+oracle_25519+` +|`+x25519_sodium+`, `+oracle_25519+` |`+curves::ed25519::encode_spki+`, `+decode_spki+`, `+encode_pkcs8+`, `+decode_pkcs8+` |libsodium @@ -166,7 +176,7 @@ |native, wasip2, wasip3, emscripten |`+formats_25519_sodium+`, `+formats_25519_openssl_oracle+`, `+allocation_sodium+`, `+p256_formats_bearssl+` -|`+curves::x25519::kx_keypair+` +|`+key_exchange::kx_keypair+` |libsodium |native, wasip2, wasip3, emscripten |`+kx_sodium+`, `+kx_wipe_sodium+`, `+allocation_sodium+` @@ -201,27 +211,27 @@ |native, wasip2, wasip3, emscripten |`+xchacha_sodium+`, `+chacha_wycheproof_sodium+`, `+allocation_sodium+` -|`+ciphers::secretbox+` +|`+secret_key_encryption::secretbox+` |libsodium |native, wasip2, wasip3, emscripten -|`+secretbox_sodium+`, `+box_sodium+`, `+allocation_sodium+` +|`+secretbox_sodium+`, `+box_sodium+`, `+allocation_sodium+`, `+aead_concepts+` -|`+ciphers::secretbox_xchacha20poly1305+` +|`+secret_key_encryption::secretbox_xchacha20poly1305+` |libsodium |native, wasip2, wasip3, emscripten -|`+secretbox_sodium+`, `+box_sodium+`, `+allocation_sodium+` +|`+secretbox_sodium+`, `+box_sodium+`, `+allocation_sodium+`, `+aead_concepts+` -|`+hybrid::box+` +|`+public_key_encryption::box+` |libsodium |native, wasip2, wasip3, emscripten |`+box_sodium+`, `+allocation_sodium+` -|`+hybrid::box_xchacha20poly1305+` +|`+public_key_encryption::box_xchacha20poly1305+` |libsodium |native, wasip2, wasip3, emscripten |`+box_sodium+`, `+allocation_sodium+` -|`+hybrid::sealed_box+` +|`+public_key_encryption::sealed_box+` |libsodium |native, wasip2, wasip3, emscripten |`+box_sodium+`, `+allocation_sodium+` @@ -236,7 +246,7 @@ |native, wasip2, wasip3, emscripten |`+secp256k1_keys+` -|`+curves::secp256k1::seckey_tweak_add+`, `+seckey_tweak_mul+`, `+seckey_negate+`, `+pubkey_tweak_add+`, `+pubkey_tweak_mul+`, `+pubkey_negate+`, `+pubkey_combine+` +|`+curves::secp256k1::secret_key_tweak_add+`, `+secret_key_tweak_mul+`, `+secret_key_negate+`, `+public_key_tweak_add+`, `+public_key_tweak_mul+`, `+public_key_negate+`, `+public_key_combine+` |libsecp256k1 |native, wasip2, wasip3, emscripten |`+secp256k1_tweak+` @@ -251,12 +261,12 @@ |native, wasip2, wasip3, emscripten |`+secp256k1_ellswift+` -|`+curves::secp256k1::musig::aggregate_key+`, `+key_aggregate+`, `+nonce_gen+`, `+nonce_aggregate+`, `+nonce_process+`, `+partial_sign+`, `+partial_signature_verify+`, `+partial_signature_aggregate+`, `+parse_public_nonce+`, `+serialize_public_nonce+`, `+parse_aggregate_nonce+`, `+serialize_aggregate_nonce+`, `+parse_partial_signature+`, `+serialize_partial_signature+` +|`+curves::secp256k1::musig::aggregate_key+`, `+key_aggregate+`, `+generate_nonce+`, `+nonce_aggregate+`, `+nonce_process+`, `+partial_sign+`, `+partial_signature_verify+`, `+partial_signature_aggregate+`, `+parse_public_nonce+`, `+serialize_public_nonce+`, `+parse_aggregate_nonce+`, `+serialize_aggregate_nonce+`, `+parse_partial_signature+`, `+serialize_partial_signature+` |libsecp256k1 |native, wasip2, wasip3, emscripten |`+secp256k1_musig+`, `+secp256k1_musig_entropy+` -|`+curves::secp256k1::silent_payments::create_outputs+`, `+create_label+`, `+create_labeled_spend_key+`, `+make_prevouts_summary+`, `+scan_outputs+`, `+send_workspace_size+`, `+summary_workspace_size+`, `+scan_workspace_size+` +|`+curves::secp256k1::silent_payments::create_outputs+`, `+create_label+`, `+create_labeled_spend_key+`, `+make_previous_outputs_summary+`, `+scan_outputs+`, `+send_workspace_size+`, `+summary_workspace_size+`, `+scan_workspace_size+` |libsecp256k1 |native, wasip2, wasip3, emscripten |`+secp256k1_silent_payments+` @@ -324,31 +334,37 @@ The same, by target: the backends each operation runs on. |the system's generator |the system's generator -|`+async_make+`, `+async_seal+`, `+async_open+` -|BearSSL, OpenSSL -|BearSSL, OpenSSL -|BearSSL, OpenSSL -|BearSSL +|`+async_from_key+`, `+secret_key_encryption::aead::async_seal+`, `+secret_key_encryption::aead::async_open+` +|BearSSL, OpenSSL, libsodium +|BearSSL, OpenSSL, libsodium +|BearSSL, OpenSSL, libsodium +|BearSSL, libsodium -|`+async_make+`, `+async_generate+`, `+async_sign+`, `+async_verify+` +|`+async_from_secret+`, `+async_generate+`, `+async_sign+`, `+async_verify+` |libsodium |libsodium |libsodium |libsodium -|`+async_agree+` +|`+async_from_secret+`, `+async_generate+`, `+async_agree+` |libsodium |libsodium |libsodium |libsodium -|`+async_make+`, `+async_generate+`, `+async_sign+`, `+async_verify+`, `+async_agree+` +|`+async_from_secret+`, `+async_generate+`, `+async_sign+`, `+async_verify+`, `+async_agree+` |BearSSL |BearSSL |BearSSL |BearSSL -|`+equal+` +|`+constant_time_equal+` +|no backend +|no backend +|no backend +|no backend + +|`+erase_secret+` |no backend |no backend |no backend @@ -420,25 +436,25 @@ The same, by target: the backends each operation runs on. |libsodium |libsodium -|`+curves::ed25519::ph+` +|`+curves::ed25519::prehashed_signer+` |libsodium |libsodium |libsodium |libsodium -|`+curves::ed25519::to_x25519_public+` +|`+crypto::to_x25519+` |libsodium |libsodium |libsodium |libsodium -|`+curves::x25519::public_key+` +|`+curves::x25519::keypair+` |libsodium |libsodium |libsodium |libsodium -|`+curves::x25519::agree+` +|`+curves::x25519::public_key+` |libsodium |libsodium |libsodium @@ -462,7 +478,7 @@ The same, by target: the backends each operation runs on. |libsodium |libsodium -|`+curves::x25519::kx_keypair+` +|`+key_exchange::kx_keypair+` |libsodium |libsodium |libsodium @@ -486,31 +502,31 @@ The same, by target: the backends each operation runs on. |libsodium |libsodium -|`+ciphers::secretbox+` +|`+secret_key_encryption::secretbox+` |libsodium |libsodium |libsodium |libsodium -|`+ciphers::secretbox_xchacha20poly1305+` +|`+secret_key_encryption::secretbox_xchacha20poly1305+` |libsodium |libsodium |libsodium |libsodium -|`+hybrid::box+` +|`+public_key_encryption::box+` |libsodium |libsodium |libsodium |libsodium -|`+hybrid::box_xchacha20poly1305+` +|`+public_key_encryption::box_xchacha20poly1305+` |libsodium |libsodium |libsodium |libsodium -|`+hybrid::sealed_box+` +|`+public_key_encryption::sealed_box+` |libsodium |libsodium |libsodium @@ -528,7 +544,7 @@ The same, by target: the backends each operation runs on. |libsecp256k1 |libsecp256k1 -|`+curves::secp256k1::seckey_tweak_add+`, `+seckey_tweak_mul+`, `+seckey_negate+`, `+pubkey_tweak_add+`, `+pubkey_tweak_mul+`, `+pubkey_negate+`, `+pubkey_combine+` +|`+curves::secp256k1::secret_key_tweak_add+`, `+secret_key_tweak_mul+`, `+secret_key_negate+`, `+public_key_tweak_add+`, `+public_key_tweak_mul+`, `+public_key_negate+`, `+public_key_combine+` |libsecp256k1 |libsecp256k1 |libsecp256k1 @@ -546,13 +562,13 @@ The same, by target: the backends each operation runs on. |libsecp256k1 |libsecp256k1 -|`+curves::secp256k1::musig::aggregate_key+`, `+key_aggregate+`, `+nonce_gen+`, `+nonce_aggregate+`, `+nonce_process+`, `+partial_sign+`, `+partial_signature_verify+`, `+partial_signature_aggregate+`, `+parse_public_nonce+`, `+serialize_public_nonce+`, `+parse_aggregate_nonce+`, `+serialize_aggregate_nonce+`, `+parse_partial_signature+`, `+serialize_partial_signature+` +|`+curves::secp256k1::musig::aggregate_key+`, `+key_aggregate+`, `+generate_nonce+`, `+nonce_aggregate+`, `+nonce_process+`, `+partial_sign+`, `+partial_signature_verify+`, `+partial_signature_aggregate+`, `+parse_public_nonce+`, `+serialize_public_nonce+`, `+parse_aggregate_nonce+`, `+serialize_aggregate_nonce+`, `+parse_partial_signature+`, `+serialize_partial_signature+` |libsecp256k1 |libsecp256k1 |libsecp256k1 |libsecp256k1 -|`+curves::secp256k1::silent_payments::create_outputs+`, `+create_label+`, `+create_labeled_spend_key+`, `+make_prevouts_summary+`, `+scan_outputs+`, `+send_workspace_size+`, `+summary_workspace_size+`, `+scan_workspace_size+` +|`+curves::secp256k1::silent_payments::create_outputs+`, `+create_label+`, `+create_labeled_spend_key+`, `+make_previous_outputs_summary+`, `+scan_outputs+`, `+send_workspace_size+`, `+summary_workspace_size+`, `+scan_workspace_size+` |libsecp256k1 |libsecp256k1 |libsecp256k1 diff --git a/doc/generated/messages.adoc b/doc/generated/messages.adoc index 5f90a779..4828d0ef 100644 --- a/doc/generated/messages.adoc +++ b/doc/generated/messages.adoc @@ -15,9 +15,21 @@ At compile time, checked word for word by the message tests of `test/messages` w |`+aead_not_a_family+` |native, wasip2, wasip3 -|`+webcpp::crypto: ciphers::aead takes an AEAD family: families::chacha20_poly1305, families::chacha20_poly1305_original, families::xchacha20_poly1305, families::secretbox_xsalsa20poly1305 or families::secretbox_xchacha20poly1305.+` +|`+webcpp::crypto: ciphers::basic_chacha20_poly1305 takes an AEAD family: families::chacha20_poly1305, families::chacha20_poly1305_original or families::xchacha20_poly1305.+` -The fix: Name one of the three ChaCha20-Poly1305 families or the two secret boxes'; AES-GCM is `+ciphers::gcm+`, as in `+aes256_gcm+`. +The fix: 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<>+`. + +|`+aead_template_removed+` +|native, wasip2, wasip3 +|`+no member named 'aead' in namespace 'webcpp::crypto::ciphers'+` + +The fix: Name `+ciphers::basic_chacha20_poly1305+`, or its aliases `+chacha20_poly1305+`, `+chacha20_poly1305_original+` and `+xchacha20_poly1305+`: the template is named for its algorithm, with no alias. + +|`+aead_template_removed_call+` +|native, wasip2, wasip3 +|`+no template named 'aead' in namespace 'webcpp::crypto::ciphers'+` + +The fix: As `+aead_template_removed+`: name `+ciphers::basic_chacha20_poly1305+`. |`+aes_block_default_not_linked+` |native @@ -43,17 +55,53 @@ The fix: Name `+ciphers::aes256+`, include `+::from_bytes(bytes)+` for P-256, `+curves::secp256k1::public_key::from_bytes(bytes)+` for secp256k1. + +|`+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.+` + +The fix: 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. + +|`+async_agree_secp256k1+` +|native, wasip2, wasip3 +|`+webcpp::crypto: async_agree takes a key pair of an algorithm WebCrypto has (X25519, P-256): call the key pair's synchronous agree for the others.+` -The fix: Give `+agree+` the peer's typed public key of the key pair's own curve and backend: `+curves::p256::basic_public_key::make(bytes)+` for P-256, `+curves::secp256k1::public_key::make(bytes)+` for secp256k1. +The fix: Call the key pair's own `+agree+`: secp256k1 is not in WebCrypto, so only X25519's and P-256's key pairs have `+async_agree+`. -|`+async_make_xchacha+` +|`+async_agree_wrong_peer+` |native, wasip2, wasip3 -|`+webcpp::crypto: async_make takes AES-GCM or a key pair of an algorithm WebCrypto has (Ed25519, P-256): call the synchronous make for the others.+` +|`+webcpp::crypto: async_agree: this key pair does not agree with this peer: an X25519 key pair agrees with a curves::x25519::public_key, a P-256 key pair with a curves::p256::basic_public_key of its backend.+` -The fix: Call the synchronous `+make+`: XChaCha20-Poly1305 is not in WebCrypto, so it has no asynchronous form. +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_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_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.+` + +The fix: 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+` +|native, wasip2, wasip3 +|`+webcpp::crypto: async_from_secret takes a key pair of an algorithm WebCrypto has (Ed25519, X25519, P-256): call the synchronous from_secret for the others.+` + +The fix: 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+`. |`+async_member_without_async_hpp+` |native, wasip2, wasip3 @@ -61,29 +109,75 @@ The fix: Call the synchronous `+make+`: XChaCha20-Poly1305 is not in WebCrypto, The fix: Include `++`, which defines the asynchronous members, and add `+/webcpp/asio//asio+` to the program's Jamfile. +|`+async_open_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: Name a native backend, such as `+backends::sodium+`, for the crypto_box: WebCrypto has no crypto_box, so no form of it runs on the browser's backend, where only AES-GCM seals and opens. + |`+async_open_xchacha+` |native, wasip2, wasip3 -|`+webcpp::crypto: async_open takes AES-GCM, the AEAD WebCrypto has: call open for the others.+` +|`+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 `+async_open+`, or open with AES-GCM on the browser's backend: WebCrypto has no XChaCha20-Poly1305. + +|`+async_seal_box_associated_data+` +|native, wasip2, wasip3 +|`+webcpp::crypto: async_seal: a secret box or a crypto_box takes no associated data: secret_key_encryption::async_seal(executor, box, nonce, data, token).+` + +The fix: 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. + +|`+async_seal_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: Name a native backend, such as `+backends::sodium+`, for the secret box: WebCrypto has no secret box, so no form of it runs on the browser's backend, where only AES-GCM seals and opens. + +|`+async_seal_member_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 `+async_seal_xchacha+`: name a native backend, such as `+backends::sodium+`, for XChaCha20-Poly1305's `+async_seal+`. + +|`+async_seal_removed+` +|native, wasip2, wasip3 +|`+no member named 'async_seal' in namespace 'webcpp::crypto'; did you mean 'webcpp::crypto::secret_key_encryption::async_seal'?+` + +`+no member named 'async_open' in namespace 'webcpp::crypto'; did you mean 'webcpp::crypto::secret_key_encryption::async_open'?+` + +The fix: Call crypto::secret_key_encryption::aead::async_seal and async_open. clang's suggestion, `+secret_key_encryption::async_seal+` and `+async_open+`, is the box form, which takes no associated data and is wrong for an AES-GCM or ChaCha20-Poly1305 user. + +|`+async_seal_removed_declaration+` +|native, wasip2, wasip3 +|`+no member named 'async_seal' in namespace 'webcpp::crypto'+` + +`+no member named 'async_open' in namespace 'webcpp::crypto'+` -The fix: Call the AEAD's own `+open+`: only AES-GCM has `+async_open+`. +The fix: As `+async_seal_removed+`: call crypto::secret_key_encryption::aead::async_seal and async_open, in . |`+async_seal_xchacha+` |native, wasip2, wasip3 -|`+webcpp::crypto: async_seal takes AES-GCM, the AEAD WebCrypto has: call seal for the others.+` +|`+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: Call the AEAD's own `+seal+`: only AES-GCM has `+async_seal+`. +The fix: Name a native backend, such as `+backends::sodium+`, for `+async_seal+`, or seal with AES-GCM on the browser's backend: WebCrypto has no XChaCha20-Poly1305. |`+async_sign_ed25519_prehashed+` |native, wasip2, wasip3 -|`+webcpp::crypto: crypto::eddsa signs the message itself (RFC 8032's pure Ed25519) and takes no digest; Ed25519ph, which hashes the message, is curves::ed25519::ph.+` +|`+webcpp::crypto: crypto::eddsa signs the message itself (RFC 8032's pure Ed25519) and takes no digest; a message's SHA-512 is signed with crypto::eddsa_prehashed (Ed25519ph).+` -The fix: Give `+async_sign+` the message itself with `+crypto::eddsa+`, RFC 8032's pure Ed25519, which takes no digest, as the synchronous `+sign+` does. +The fix: Give `+async_sign+` the message itself with `+crypto::eddsa+`, RFC 8032's pure Ed25519, which takes no digest, as the synchronous `+sign+` does; a message's SHA-512 is signed with `+crypto::eddsa_prehashed+` (Ed25519ph), on a native backend. + +|`+async_sign_eddsa_prehashed_asynchronous_backend+` +|native, wasip2, wasip3 +|`+webcpp::crypto: WebCrypto has no Ed25519ph: crypto::eddsa_prehashed's sign, verify, async_sign and async_verify run on a native backend.+` + +The fix: As `+sign_eddsa_prehashed_asynchronous_backend+`: `+async_sign+` under `+crypto::eddsa_prehashed+` runs on a native backend. |`+async_sign_p256_eddsa+` |native, wasip2, wasip3 -|`+webcpp::crypto: async_sign: this key pair does not sign with this scheme: an Ed25519 key pair signs with crypto::eddsa, a P-256 key pair with crypto::ecdsa_sha256.+` +|`+webcpp::crypto: async_sign: this key pair does not sign with this scheme: an Ed25519 key pair signs with crypto::eddsa or crypto::eddsa_prehashed, a P-256 key pair with crypto::ecdsa_sha256.+` -The fix: Give `+async_sign+` the key pair's own scheme: `+crypto::ecdsa_sha256+` for a P-256 key pair, `+crypto::eddsa+` for an Ed25519 key pair. +The fix: Give `+async_sign+` the key pair's own scheme: `+crypto::ecdsa_sha256+` for a P-256 key pair, `+crypto::eddsa+` or `+crypto::eddsa_prehashed+` for an Ed25519 key pair. |`+async_sign_secp256k1+` |native, wasip2, wasip3 @@ -91,23 +185,41 @@ The fix: Give `+async_sign+` the key pair's own scheme: `+crypto::ecdsa_sha256+` The fix: Call the key pair's own signing function: secp256k1 is not in WebCrypto, so only Ed25519's and P-256's key pairs have `+async_sign+`. +|`+async_sign_x25519+` +|native, wasip2, wasip3 +|`+webcpp::crypto: async_sign: X25519 key pairs agree; they do not sign: sign with an Ed25519 key pair, which to_x25519() converts for agreement.+` + +The fix: As `+sign_x25519+`: give `+async_sign+` an Ed25519 key pair, which signs; an X25519 key pair agrees, with `+async_agree+`. + |`+async_verify_eddsa_bytes_key+` |native, wasip2, wasip3 -|`+webcpp::crypto: async_verify takes crypto::eddsa with a curves::ed25519::public_key or crypto::ecdsa_sha256 with a curves::p256::basic_public_key, the algorithms WebCrypto has: call crypto::verify for the others.+` +|`+webcpp::crypto: async_verify takes crypto::eddsa or crypto::eddsa_prehashed with a curves::ed25519::public_key or crypto::ecdsa_sha256 with a curves::p256::basic_public_key, the algorithms WebCrypto has: call crypto::verify for the others.+` + +The fix: Give `+async_verify+` with `+crypto::eddsa+` the public key as a `+curves::ed25519::public_key+`, as `+crypto::verify+` takes it: `+key_pair.public_key()+`, or `+curves::ed25519::public_key::from_bytes(bytes)+`. + +|`+async_verify_eddsa_prehashed_asynchronous_backend+` +|native, wasip2, wasip3 +|`+webcpp::crypto: WebCrypto has no Ed25519ph: crypto::eddsa_prehashed's sign, verify, async_sign and async_verify run on a native backend.+` -The fix: Give `+async_verify+` with `+crypto::eddsa+` the public key as a `+curves::ed25519::public_key+`, as `+crypto::verify+` takes it: `+key_pair.public_key()+`, or `+curves::ed25519::public_key::make(bytes)+`. +The fix: As `+verify_eddsa_prehashed_asynchronous_backend+`: `+async_verify+` under `+crypto::eddsa_prehashed+`, free and member, runs on a native backend. |`+async_verify_named_backend+` |native, wasip2, wasip3 -|`+webcpp::crypto: async_verify takes crypto::eddsa with a curves::ed25519::public_key or crypto::ecdsa_sha256 with a curves::p256::basic_public_key, the algorithms WebCrypto has: call crypto::verify for the others.+` +|`+webcpp::crypto: async_verify takes crypto::eddsa or crypto::eddsa_prehashed with a curves::ed25519::public_key or crypto::ecdsa_sha256 with a curves::p256::basic_public_key, the algorithms WebCrypto has: call crypto::verify for the others.+` The fix: As `+async_verify_wrong_key+`: naming the backend does not add a scheme; call `+crypto::verify+` for `+crypto::schnorr+` and secp256k1's keys. +|`+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.+` + +The fix: 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+`. + |`+async_verify_wrong_key+` |native, wasip2, wasip3 -|`+webcpp::crypto: async_verify takes crypto::eddsa with a curves::ed25519::public_key or crypto::ecdsa_sha256 with a curves::p256::basic_public_key, the algorithms WebCrypto has: call crypto::verify for the others.+` +|`+webcpp::crypto: async_verify takes crypto::eddsa or crypto::eddsa_prehashed with a curves::ed25519::public_key or crypto::ecdsa_sha256 with a curves::p256::basic_public_key, the algorithms WebCrypto has: call crypto::verify for the others.+` -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::eddsa+` and a `+curves::p256::basic_public_key+` with `+crypto::ecdsa_sha256+`. +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::eddsa+` or `+crypto::eddsa_prehashed+` and a `+curves::p256::basic_public_key+` with `+crypto::ecdsa_sha256+`. |`+bearssl_not_linked+` |native, wasip2 @@ -117,19 +229,31 @@ The fix: Add `+/third_party//bearssl+`. |`+box_default_not_linked+` |native, wasip2, wasip3 -|`+webcpp::crypto: X25519-XSalsa20-Poly1305 sealed box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//sealed_box-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//sealed_box-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)+` +|`+webcpp::crypto: XSalsa20-Poly1305 secret box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//secretbox_xsalsa20poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//secretbox_xsalsa20poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)+` + +`+webcpp::crypto: XChaCha20-Poly1305 secret box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//secretbox_xchacha20poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//secretbox_xchacha20poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)+` + +`+webcpp::crypto: X25519-XSalsa20-Poly1305 box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//box_xsalsa20poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//box_xsalsa20poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)+` + +`+webcpp::crypto: X25519-XChaCha20-Poly1305 box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//box_xchacha20poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//box_xchacha20poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)+` + +`+webcpp::crypto: X25519-XSalsa20-Poly1305 sealed box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//sealed_box-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//sealed_box-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)+` The fix: 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+`. |`+box_not_a_family+` |native, wasip2, wasip3 -|`+webcpp::crypto: hybrid::basic_box takes a box family: families::box_xsalsa20poly1305 or families::box_xchacha20poly1305.+` +|`+webcpp::crypto: public_key_encryption::basic_box takes a box family: families::box_xsalsa20poly1305 or families::box_xchacha20poly1305.+` -The fix: Name `+families::box_xsalsa20poly1305+` or `+families::box_xchacha20poly1305+`, or use `+hybrid::box+` or `+hybrid::box_xchacha20poly1305+`. +The fix: Name `+families::box_xsalsa20poly1305+` or `+families::box_xchacha20poly1305+`, or use `+public_key_encryption::box+` or `+public_key_encryption::box_xchacha20poly1305+`. |`+chacha_default_not_linked+` |native, wasip2, wasip3 -|`+webcpp::crypto: XChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//xchacha20_poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//xchacha20_poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)+` +|`+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)+` + +`+webcpp::crypto: original ChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//chacha20_poly1305_original-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//chacha20_poly1305_original-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)+` + +`+webcpp::crypto: XChaCha20-Poly1305's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//xchacha20_poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//xchacha20_poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)+` The fix: The ChaCha20-Poly1305 AEADs' default is libsodium on every target: add the family's alias, as `+/webcpp/crypto//chacha20_poly1305-default+`, which links `+/third_party//sodium+`. @@ -189,9 +313,9 @@ The fix: Leave the policy out, as in `+crypto::verify(crypto::eddsa, signature, |`+ed25519ph_sha256+` |native, wasip2, wasip3 -|`+webcpp::crypto: Ed25519ph is defined over SHA-512 (RFC 8032 section 5.1); name curves::ed25519::ph.+` +|`+webcpp::crypto: Ed25519ph is defined over SHA-512 (RFC 8032 section 5.1); name curves::ed25519::prehashed_signer.+` -The fix: Name `+curves::ed25519::ph+`: RFC 8032 defines Ed25519ph over SHA-512. +The fix: Name `+curves::ed25519::prehashed_signer+`: RFC 8032 defines Ed25519ph over SHA-512. |`+ellswift_other_backend+` |native, wasip2 @@ -199,6 +323,24 @@ The fix: Name `+curves::ed25519::ph+`: RFC 8032 defines The fix: Name `+backends::secp256k1+`, or leave the backend out: `+curves::secp256k1::ellswift_decode(encoded_key)+`. +|`+equal_header_removed+` +|native, wasip2, wasip3 +|`+'webcpp/crypto/equal.hpp' file not found+` + +The fix: Include `++`, the header of `+constant_time_equal+`; `+equal.hpp+` is gone, with no header left at its path. + +|`+equal_removed+` +|native, wasip2, wasip3 +|`+no member named 'equal' in namespace 'webcpp::crypto'+` + +The fix: Call `+crypto::constant_time_equal+`, the same comparison of two spans or two digests in constant time; `+crypto::equal+` is gone, with no alias. + +|`+erase_secret_const_range+` +|native, wasip2, wasip3 +|`+webcpp::crypto: erase_secret zeroes a buffer the program may write, of trivially copyable elements: a std::vector, a std::string, a std::array, a std::span; this range's elements are const or not trivially copyable.+` + +The fix: Erase the buffer the secret was written to, through a non-const reference to it (`+std::string&+`, `+std::span+`): a const view cannot be erased. Its elements must be trivially copyable, bytes or integers; a range of `+std::string+` or of another type with its own storage cannot be erased as bytes, so erase each element's buffer instead. + |`+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)+` @@ -223,6 +365,28 @@ The fix: Call the synchronous operation the message names, or build with threads The fix: As `+heavy_without_threads+`. +|`+hybrid_header_removed+` +|native, wasip2, wasip3 +|`+'webcpp/crypto/hybrid/box.hpp' file not found+` + +The fix: Include `++` for `+box+` and `+box_xchacha20poly1305+`, `++` for `+sealed_box+`, `++` for `+kx_keypair+`; the old directory is kept free for post-quantum hybrids. + +|`+hybrid_names_removed+` +|native, wasip2, wasip3 +|`+no member named 'hybrid'+` + +`+no member named 'kx_keypair'+` + +The fix: Name `+crypto::public_key_encryption::box+`, `+box_xchacha20poly1305+` and `+sealed_box+`, and `+crypto::key_exchange::kx_keypair+` and `+session_keys+`; `+crypto::hybrid+` and the names in `+curves::x25519+` are gone, with no alias. + +|`+iv_size_removed+` +|native, wasip2, wasip3 +|`+no member named 'iv_size' in+` + +`+no member named 'invalid_iv_size' in+` + +The fix: Name nonce_size, max_nonce_size and error::invalid_nonce_size: crypto spells its names out. + |`+kx_default_not_linked+` |native, wasip2, wasip3 |`+webcpp::crypto: crypto_kx's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//kx-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//kx-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)+` @@ -235,12 +399,30 @@ The fix: Add `+/webcpp/crypto//kx-default+`, which links `+/third_party//sodium+ The fix: Return `+std::optional>+`, a span over a tweak the lookup keeps, such as a map's entry; never the tweak by value. +|`+make_removed+` +|native, wasip2, wasip3 +|`+no member named 'make' in+` + +The fix: 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. + |`+musig_nonce_copied+` |native, wasip2 |`+call to deleted constructor of+` The fix: Pass the nonce with std::move, once: a secret nonce signs one message. +|`+musig_nonce_gen_removed+` +|native, wasip2 +|`+no member named 'nonce_gen' in namespace 'webcpp::crypto::curves::secp256k1::musig'+` + +The fix: Call musig::generate_nonce: crypto spells out the names libsecp256k1 abbreviates. + +|`+musig_nonce_gen_removed_call+` +|native, wasip2 +|`+no member named 'nonce_gen' in namespace 'webcpp::crypto::curves::secp256k1::musig'+` + +The fix: As `+musig_nonce_gen_removed+`. + |`+musig_other_backend+` |native, wasip2 |`+webcpp::crypto: bearssl has no MuSig2. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten).+` @@ -255,9 +437,9 @@ The fix: On WASI the default is BearSSL: add `+/webcpp/crypto//gcm-default+`, wh |`+open_asynchronous_backend+` |native, wasip2, wasip3 -|`+webcpp::crypto: open on this backend completes asynchronously: call async_open.+` +|`+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: Call `+async_open+` on a backend that completes by itself: its synchronous forms cannot wait for it. +The fix: Name a native backend, such as `+backends::sodium+`, for ChaCha20-Poly1305: WebCrypto has no ChaCha20-Poly1305, so neither its `+open+` nor its `+async_open+` completes on the browser's backend; there, use AES-GCM. |`+openssl_memory_not_linked+` |native @@ -307,18 +489,86 @@ The fix: Leave the backend out, as in `+curves::p256::keypair+`, or name `+backe The fix: Add `+/webcpp/crypto//pem-default+`, which links `+/third_party//sodium+` on every target. +|`+ph_removed+` +|native, wasip2, wasip3 +|`+no member named 'ph' in namespace+` + +The fix: Name Ed25519ph's streaming signer `+curves::ed25519::prehashed_signer+`, the same `+begin+`, `+update+`, `+sign+` and `+verify+`; `+curves::ed25519::ph+` is gone, with no alias. + |`+prehashed_dynamic+` |native, wasip2, wasip3 |`+webcpp::crypto: crypto::prehashed takes a digest of a fixed size: a std::array or a std::span.+` The fix: Give `+crypto::prehashed+` a digest of a fixed size: a `+std::array+`, a `+std::span+` or a `+boost::hash2::digest<32>+`. +|`+prevouts_summary_removed+` +|native, wasip2 +|`+no member named 'prevouts_summary' in namespace 'webcpp::crypto::curves::secp256k1::silent_payments'+` + +`+no member named 'make_prevouts_summary' in namespace 'webcpp::crypto::curves::secp256k1::silent_payments'+` + +The fix: Name silent_payments::previous_outputs_summary and make_previous_outputs_summary: crypto spells out libsecp256k1's prevouts. + +|`+prevouts_summary_removed_call+` +|native, wasip2 +|`+no member named 'make_prevouts_summary' in namespace 'webcpp::crypto::curves::secp256k1::silent_payments'+` + +The fix: As `+prevouts_summary_removed+`. + +|`+recover_ecdsa_signature+` +|native, wasip2, wasip3 +|`+webcpp::crypto: recover takes a curves::secp256k1::recoverable_signature: make one from 65 bytes with curves::secp256k1::recoverable_signature::from_bytes.+` + +The fix: Give `+recover+` a `+curves::secp256k1::recoverable_signature+`, which `+sign(crypto::ecdsa_sha256_recoverable, input)+` gives, or made from 65 bytes with `+from_bytes+`; an ECDSA signature without its recovery id verifies with `+crypto::verify+` and the signer's public key. + |`+seal_asynchronous_backend+` |native, wasip2, wasip3 |`+webcpp::crypto: seal on this backend completes asynchronously: call async_seal.+` The fix: Call `+async_seal+` on a backend that completes by itself: its synchronous forms cannot wait for it. +|`+seal_box_associated_data+` +|native, wasip2, wasip3 +|`+webcpp::crypto: seal: a secret box or a crypto_box takes no associated data: secret_key_encryption::seal(box, nonce, data).+` + +The fix: Call the box form, `+secret_key_encryption::seal(box, nonce, data)+` or the box's own `+seal(nonce, data)+`: a secret box or a crypto_box takes no associated data; authenticate it with an AEAD, as `+ciphers::xchacha20_poly1305<>+`. + +|`+seal_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: 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. + +|`+seal_removed+` +|native, wasip2, wasip3 +|`+no member named 'seal' in namespace 'webcpp::crypto'+` + +`+no member named 'open' in namespace 'webcpp::crypto'+` + +The fix: Call crypto::secret_key_encryption::aead::seal and open, in , which every AEAD's header includes. + +|`+seal_removed_call+` +|native +|`+no member named 'seal' in namespace 'webcpp::crypto'+` + +`+no member named 'open' in namespace 'webcpp::crypto'+` + +The fix: As `+seal_removed+`: call crypto::secret_key_encryption::aead::seal and open, which the cipher's header brings. + +|`+seal_removed_call_wasi+` +|wasip2, wasip3 +|`+no member named 'seal' in namespace 'webcpp::crypto'+` + +`+no member named 'open' in namespace 'webcpp::crypto'; did you mean 'fopen'?+` + +The fix: 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. + +|`+seal_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: WebCrypto has no secret box, so neither its `+seal+` nor its `+async_seal+` completes on the browser's backend; there, use AES-GCM. + |`+secp256k1_not_linked+` |native, wasip2 |`+webcpp::crypto: needs libsecp256k1, which is not linked. In the program's Jamfile, add /third_party//secp256k1 beside /webcpp/crypto//crypto. (without b2: define WEBCPP_CRYPTO_HAS_SECP256K1=1 and link libsecp256k1 built with webcpp's src/canary_secp256k1.c)+` @@ -331,12 +581,76 @@ The fix: Add `+/third_party//secp256k1+`. The fix: Name `+backends::secp256k1+`, or leave the backend out: `+curves::secp256k1::keypair+`. +|`+secp256k1_tweak_names_removed+` +|native, wasip2 +|`+no member named 'pubkey_tweak_add' in namespace 'webcpp::crypto::curves::secp256k1'+` + +`+no member named 'pubkey_tweak_mul' in namespace 'webcpp::crypto::curves::secp256k1'+` + +`+no member named 'pubkey_negate' in namespace 'webcpp::crypto::curves::secp256k1'+` + +`+no member named 'pubkey_combine' in namespace 'webcpp::crypto::curves::secp256k1'+` + +`+no member named 'seckey_tweak_add' in namespace 'webcpp::crypto::curves::secp256k1'+` + +`+no member named 'seckey_tweak_mul' in namespace 'webcpp::crypto::curves::secp256k1'+` + +`+no member named 'seckey_negate' in namespace 'webcpp::crypto::curves::secp256k1'+` + +The fix: Call public_key_tweak_add, public_key_tweak_mul, public_key_negate, public_key_combine, secret_key_tweak_add, secret_key_tweak_mul and secret_key_negate: crypto spells out the names libsecp256k1 abbreviates. + +|`+secp256k1_tweak_names_removed_call+` +|native, wasip2 +|`+no member named 'pubkey_tweak_add' in namespace 'webcpp::crypto::curves::secp256k1'+` + +`+no member named 'pubkey_tweak_mul' in namespace 'webcpp::crypto::curves::secp256k1'+` + +`+no member named 'pubkey_negate' in namespace 'webcpp::crypto::curves::secp256k1'+` + +`+no member named 'pubkey_combine' in namespace 'webcpp::crypto::curves::secp256k1'+` + +`+no member named 'seckey_tweak_add' in namespace 'webcpp::crypto::curves::secp256k1'+` + +`+no member named 'seckey_tweak_mul' in namespace 'webcpp::crypto::curves::secp256k1'+` + +`+no member named 'seckey_negate' in namespace 'webcpp::crypto::curves::secp256k1'+` + +The fix: As `+secp256k1_tweak_names_removed+`. + |`+secret_of_no_bytes+` |native, wasip2, wasip3 |`+webcpp::crypto: a secret of no bytes holds nothing.+` The fix: Give `+secret+` the number of bytes it holds, at least one, as in `+secret<32>+`. +|`+secretbox_header_removed+` +|native, wasip2, wasip3 +|`+'webcpp/crypto/ciphers/secretbox.hpp' file not found+` + +The fix: Include `++`, the secret boxes' header; `+ciphers/secretbox.hpp+` is gone, with no header left at its path. + +|`+secretbox_not_a_family+` +|native, wasip2, wasip3 +|`+webcpp::crypto: secret_key_encryption::basic_secretbox takes a secret box family: families::secretbox_xsalsa20poly1305 or families::secretbox_xchacha20poly1305.+` + +The fix: Name `+families::secretbox_xsalsa20poly1305+` or `+families::secretbox_xchacha20poly1305+`, or use `+secret_key_encryption::secretbox<>+` or `+secret_key_encryption::secretbox_xchacha20poly1305<>+`; an AEAD is `+ciphers::basic_chacha20_poly1305+`, as in `+ciphers::xchacha20_poly1305<>+`. + +|`+secretbox_removed+` +|native, wasip2, wasip3 +|`+no member named 'secretbox' in namespace 'webcpp::crypto::ciphers'+` + +`+no member named 'secretbox_xchacha20poly1305' in namespace 'webcpp::crypto::ciphers'+` + +The fix: Name `+crypto::secret_key_encryption::secretbox+` and `+secretbox_xchacha20poly1305+`, the secret boxes' namespace; `+ciphers::secretbox+` is gone, with no alias. + +|`+secretbox_removed_call+` +|native, wasip2, wasip3 +|`+no template named 'secretbox' in namespace 'webcpp::crypto::ciphers'; did you mean 'webcpp::crypto::secret_key_encryption::secretbox'?+` + +`+no template named 'secretbox_xchacha20poly1305' in namespace 'webcpp::crypto::ciphers'; did you mean 'webcpp::crypto::secret_key_encryption::secretbox_xchacha20poly1305'?+` + +The fix: As `+secretbox_removed+`: name `+crypto::secret_key_encryption::secretbox<>+` and `+secretbox_xchacha20poly1305<>+`, the names clang offers. + |`+sign_asynchronous_backend+` |native, wasip2, wasip3 |`+webcpp::crypto: sign on this backend completes asynchronously: call async_sign.+` @@ -345,21 +659,45 @@ The fix: Call `+async_sign+` on a backend that completes by itself: its synchron |`+sign_ed25519_ecdsa+` |native, wasip2, wasip3 -|`+webcpp::crypto: an Ed25519 key signs with crypto::eddsa.+` +|`+webcpp::crypto: an Ed25519 key signs with crypto::eddsa or crypto::eddsa_prehashed.+` + +The fix: Sign with `+crypto::eddsa+` or `+crypto::eddsa_prehashed+`, Ed25519's schemes; `+crypto::ecdsa_sha256+` is P-256's and secp256k1's. + +|`+sign_ed25519_keccak+` +|native, wasip2, wasip3 +|`+webcpp::crypto: an Ed25519 key signs with crypto::eddsa or crypto::eddsa_prehashed.+` -The fix: Sign with `+crypto::eddsa+`, Ed25519's scheme; `+crypto::ecdsa_sha256+` is P-256's and secp256k1's. +The fix: Sign with `+crypto::eddsa+` or `+crypto::eddsa_prehashed+`, Ed25519's schemes; Ethereum's `+crypto::ecdsa_keccak256_recoverable+` is secp256k1's. |`+sign_ed25519_prehashed+` |native, wasip2, wasip3 -|`+webcpp::crypto: crypto::eddsa signs the message itself (RFC 8032's pure Ed25519) and takes no digest; Ed25519ph, which hashes the message, is curves::ed25519::ph.+` +|`+webcpp::crypto: crypto::eddsa signs the message itself (RFC 8032's pure Ed25519) and takes no digest; a message's SHA-512 is signed with crypto::eddsa_prehashed (Ed25519ph).+` + +The fix: Sign the message itself with `+crypto::eddsa+`, RFC 8032's pure Ed25519, which takes no digest; to sign a message's SHA-512, use Ed25519ph, `+crypto::eddsa_prehashed+`, or for a message given in pieces `+curves::ed25519::prehashed_signer+`. + +|`+sign_eddsa_prehashed_asynchronous_backend+` +|native, wasip2, wasip3 +|`+webcpp::crypto: WebCrypto has no Ed25519ph: crypto::eddsa_prehashed's sign, verify, async_sign and async_verify run on a native backend.+` + +The fix: Sign under `+crypto::eddsa_prehashed+` with a key pair of a native backend: WebCrypto has no Ed25519ph; on the browser's backend, sign the message with `+crypto::eddsa+`. + +|`+sign_eddsa_prehashed_digest_32+` +|native, wasip2, wasip3 +|`+webcpp::crypto: crypto::eddsa_prehashed takes a 64-byte digest, SHA-512's: crypto::prehashed{digest} of a std::array.+` + +The fix: Give `+crypto::eddsa_prehashed+` SHA-512's 64-byte digest, `+crypto::prehashed{digest}+` of a `+std::array+`: RFC 8032 defines Ed25519ph over SHA-512. + +|`+sign_eddsa_prehashed_message+` +|native, wasip2, wasip3 +|`+webcpp::crypto: crypto::eddsa_prehashed (RFC 8032's Ed25519ph) signs a digest, the message's SHA-512: crypto::prehashed{digest} of a std::array; sign the message itself with crypto::eddsa, or give it in pieces to curves::ed25519::prehashed_signer.+` -The fix: Sign the message itself with `+crypto::eddsa+`, RFC 8032's pure Ed25519, which takes no digest; to sign a message given in pieces, use Ed25519ph, `+curves::ed25519::ph+`. +The fix: Give `+crypto::eddsa_prehashed+` the message's SHA-512 marked as a digest, `+crypto::prehashed{digest}+` of a `+std::array+`; sign the message itself with `+crypto::eddsa+`, or give it in pieces to `+curves::ed25519::prehashed_signer+`. |`+sign_free_ed25519_ecdsa+` |native, wasip2, wasip3 -|`+webcpp::crypto: an Ed25519 key signs with crypto::eddsa.+` +|`+webcpp::crypto: an Ed25519 key signs with crypto::eddsa or crypto::eddsa_prehashed.+` -The fix: As `+sign_ed25519_ecdsa+`: `+crypto::sign+` calls the key pair's own `+sign+`, so sign with `+crypto::eddsa+`, Ed25519's scheme. +The fix: As `+sign_ed25519_ecdsa+`: `+crypto::sign+` calls the key pair's own `+sign+`, so sign with `+crypto::eddsa+` or `+crypto::eddsa_prehashed+`, Ed25519's schemes. |`+sign_free_public_key+` |native, wasip2, wasip3 @@ -367,12 +705,30 @@ The fix: As `+sign_ed25519_ecdsa+`: `+crypto::sign+` calls the key pair's own `+ The fix: Give `+crypto::sign+` the key pair, whose public key verifies: `+crypto::sign(key_pair, scheme, input)+`, then `+crypto::verify(scheme, signature, input, public_key)+` or `+public_key.verify(scheme, signature, input)+`. +|`+sign_keccak_digest_20+` +|native, wasip2, wasip3 +|`+webcpp::crypto: crypto::ecdsa_keccak256_recoverable takes a 32-byte digest, Keccak-256's: crypto::prehashed{digest} of a std::array.+` + +The fix: As `+sign_p256_digest_48+`: give `+crypto::ecdsa_keccak256_recoverable+` Keccak-256's 32-byte digest, or the message itself, which it hashes with Keccak-256. + +|`+sign_keccak_without_xkcp+` +|native, wasip2, wasip3 +|`+webcpp::crypto: crypto::ecdsa_keccak256_recoverable hashes a message with webcpp::hash's keccak_256, which needs XKCP: add /third_party//xkcp to the program's Jamfile, or sign crypto::prehashed{digest}.+` + +The fix: Add `+/third_party//xkcp+` to the program's Jamfile, whose Keccak-256 hashes the message, or build the 32-byte digest elsewhere and sign `+crypto::prehashed{digest}+`, which needs no XKCP. + |`+sign_p256_digest_48+` |native, wasip2, wasip3 |`+webcpp::crypto: crypto::ecdsa_sha256 takes a 32-byte digest, SHA-256's: crypto::prehashed{digest} of a std::array.+` The fix: Give `+crypto::ecdsa_sha256+` SHA-256's 32-byte digest, `+crypto::prehashed{digest}+` of a `+std::array+`, or the message itself, which it hashes. +|`+sign_p256_keccak+` +|native, wasip2, wasip3 +|`+webcpp::crypto: a P-256 key signs with crypto::ecdsa_sha256.+` + +The fix: Sign with `+crypto::ecdsa_sha256+`, P-256's scheme; Ethereum's `+crypto::ecdsa_keccak256_recoverable+` is secp256k1's. + |`+sign_p256_schnorr+` |native, wasip2, wasip3 |`+webcpp::crypto: a P-256 key signs with crypto::ecdsa_sha256.+` @@ -387,15 +743,15 @@ The fix: Sign the message itself with `+crypto::schnorr+`, BIP340's, which has n |`+sign_secp256k1_eddsa+` |native, wasip2, wasip3 -|`+webcpp::crypto: a secp256k1 key signs with crypto::ecdsa_sha256, crypto::ecdsa_sha256_recoverable or crypto::schnorr.+` +|`+webcpp::crypto: a secp256k1 key signs with crypto::ecdsa_sha256, crypto::ecdsa_sha256_recoverable, crypto::ecdsa_keccak256_recoverable or crypto::schnorr.+` -The fix: Sign with `+crypto::ecdsa_sha256+`, `+crypto::ecdsa_sha256_recoverable+` or `+crypto::schnorr+`, secp256k1's schemes; `+crypto::eddsa+` is Ed25519's. +The fix: Sign with `+crypto::ecdsa_sha256+`, `+crypto::ecdsa_sha256_recoverable+`, `+crypto::ecdsa_keccak256_recoverable+` or `+crypto::schnorr+`, secp256k1's schemes; `+crypto::eddsa+` is Ed25519's. |`+sign_secp256k1_not_a_scheme+` |native, wasip2, wasip3 -|`+webcpp::crypto: a secp256k1 key signs with crypto::ecdsa_sha256, crypto::ecdsa_sha256_recoverable or crypto::schnorr.+` +|`+webcpp::crypto: a secp256k1 key signs with crypto::ecdsa_sha256, crypto::ecdsa_sha256_recoverable, crypto::ecdsa_keccak256_recoverable or crypto::schnorr.+` -The fix: Name the scheme with its tag: `+crypto::ecdsa_sha256+`, `+crypto::ecdsa_sha256_recoverable+` or `+crypto::schnorr+`. +The fix: Name the scheme with its tag: `+crypto::ecdsa_sha256+`, `+crypto::ecdsa_sha256_recoverable+`, `+crypto::ecdsa_keccak256_recoverable+` or `+crypto::schnorr+`. |`+sign_secp256k1_recoverable_digest_48+` |native, wasip2, wasip3 @@ -403,11 +759,17 @@ The fix: Name the scheme with its tag: `+crypto::ecdsa_sha256+`, `+crypto::ecdsa The fix: As `+sign_p256_digest_48+`: give `+crypto::ecdsa_sha256_recoverable+` SHA-256's 32-byte digest, or the message itself, which it hashes. +|`+sign_x25519+` +|native, wasip2, wasip3 +|`+webcpp::crypto: sign: X25519 key pairs agree; they do not sign: sign with an Ed25519 key pair, which to_x25519() converts for agreement.+` + +The fix: Sign with an Ed25519 key pair, a `+crypto::signing_keypair+`: an X25519 key pair agrees and does not sign. One Ed25519 key pair can do both: `+to_x25519()+` gives the X25519 key pair that agrees. + |`+silent_payments_other_backend+` |native, wasip2 |`+webcpp::crypto: bearssl has no BIP 352 silent payments. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten).+` -The fix: Name `+backends::secp256k1+`, or leave the backend out: `+curves::secp256k1::silent_payments::make_prevouts_summary(...)+`. +The fix: Name `+backends::secp256k1+`, or leave the backend out: `+curves::secp256k1::silent_payments::make_previous_outputs_summary(...)+`. |`+sodium_not_linked+` |native, wasip2, wasip3 @@ -423,15 +785,33 @@ The fix: Call `+async_verify+` on a backend that completes by itself: its synchr |`+verify_ecdsa_bytes_key+` |native, wasip2, wasip3 -|`+webcpp::crypto: verify: this public key does not go with this scheme: crypto::eddsa takes a curves::ed25519::public_key, crypto::ecdsa_sha256 a curves::p256::basic_public_key or a curves::secp256k1::public_key, crypto::schnorr a curves::secp256k1::public_key or a 32-byte x-only key; a crypto::ecdsa_sha256_recoverable signature gives its key to curves::secp256k1::recover.+` +|`+webcpp::crypto: verify: this public key does not go with this scheme: crypto::eddsa and crypto::eddsa_prehashed take a curves::ed25519::public_key, crypto::ecdsa_sha256 a curves::p256::basic_public_key or a curves::secp256k1::public_key, crypto::schnorr a curves::secp256k1::public_key or a 32-byte x-only key; a crypto::ecdsa_sha256_recoverable or a crypto::ecdsa_keccak256_recoverable signature gives its key to curves::secp256k1::recover.+` -The fix: Give `+crypto::ecdsa_sha256+` the public key as a typed object, `+curves::secp256k1::public_key::make(bytes)+` or `+curves::p256::public_key::make(bytes)+`: bytes never choose the curve. +The fix: Give `+crypto::ecdsa_sha256+` the public key as a typed object, `+curves::secp256k1::public_key::from_bytes(bytes)+` or `+curves::p256::public_key::from_bytes(bytes)+`: bytes never choose the curve. + +|`+verify_ed25519_bytes_signature+` +|native, wasip2, wasip3 +|`+webcpp::crypto: verify: an Ed25519 key verifies a curves::ed25519::signature under crypto::eddsa: make one from 64 bytes with curves::ed25519::signature::from_bytes.+` + +The fix: Make the 64 bytes received into a `+curves::ed25519::signature+` with `+curves::ed25519::signature::from_bytes+`, which checks their size, and verify that. |`+verify_eddsa_bytes_key+` |native, wasip2, wasip3 -|`+webcpp::crypto: verify: this public key does not go with this scheme: crypto::eddsa takes a curves::ed25519::public_key, crypto::ecdsa_sha256 a curves::p256::basic_public_key or a curves::secp256k1::public_key, crypto::schnorr a curves::secp256k1::public_key or a 32-byte x-only key; a crypto::ecdsa_sha256_recoverable signature gives its key to curves::secp256k1::recover.+` +|`+webcpp::crypto: verify: this public key does not go with this scheme: crypto::eddsa and crypto::eddsa_prehashed take a curves::ed25519::public_key, crypto::ecdsa_sha256 a curves::p256::basic_public_key or a curves::secp256k1::public_key, crypto::schnorr a curves::secp256k1::public_key or a 32-byte x-only key; a crypto::ecdsa_sha256_recoverable or a crypto::ecdsa_keccak256_recoverable signature gives its key to curves::secp256k1::recover.+` + +The fix: Give `+crypto::eddsa+` (or `+crypto::eddsa_prehashed+`) the public key as a `+curves::ed25519::public_key+`: `+key_pair.public_key()+`, or `+curves::ed25519::public_key::from_bytes(bytes)+` for a key received as bytes. -The fix: Give `+crypto::eddsa+` the public key as a `+curves::ed25519::public_key+`: `+key_pair.public_key()+`, or `+curves::ed25519::public_key::make(bytes)+` for a key received as bytes. +|`+verify_eddsa_prehashed_asynchronous_backend+` +|native, wasip2, wasip3 +|`+webcpp::crypto: WebCrypto has no Ed25519ph: crypto::eddsa_prehashed's sign, verify, async_sign and async_verify run on a native backend.+` + +The fix: Verify under `+crypto::eddsa_prehashed+` on a native backend, `+crypto::verify+` and the key's `+verify+` alike: WebCrypto has no Ed25519ph; on the browser's backend, verify a signature of the message with `+crypto::eddsa+`. + +|`+verify_eddsa_prehashed_message+` +|native, wasip2, wasip3 +|`+webcpp::crypto: crypto::eddsa_prehashed (RFC 8032's Ed25519ph) signs a digest, the message's SHA-512: crypto::prehashed{digest} of a std::array; sign the message itself with crypto::eddsa, or give it in pieces to curves::ed25519::prehashed_signer.+` + +The fix: As `+sign_eddsa_prehashed_message+`: verify under `+crypto::eddsa_prehashed+` the marker of the message's SHA-512, or the message itself under `+crypto::eddsa+`. |`+verify_free_asynchronous_backend+` |native, wasip2, wasip3 @@ -441,21 +821,27 @@ The fix: As `+verify_asynchronous_backend+`. |`+verify_free_secp256k1_recoverable+` |native, wasip2, wasip3 -|`+webcpp::crypto: verify: this public key does not go with this scheme: crypto::eddsa takes a curves::ed25519::public_key, crypto::ecdsa_sha256 a curves::p256::basic_public_key or a curves::secp256k1::public_key, crypto::schnorr a curves::secp256k1::public_key or a 32-byte x-only key; a crypto::ecdsa_sha256_recoverable signature gives its key to curves::secp256k1::recover.+` +|`+webcpp::crypto: verify: this public key does not go with this scheme: crypto::eddsa and crypto::eddsa_prehashed take a curves::ed25519::public_key, crypto::ecdsa_sha256 a curves::p256::basic_public_key or a curves::secp256k1::public_key, crypto::schnorr a curves::secp256k1::public_key or a 32-byte x-only key; a crypto::ecdsa_sha256_recoverable or a crypto::ecdsa_keccak256_recoverable signature gives its key to curves::secp256k1::recover.+` The fix: As `+verify_member_secp256k1_recoverable+`: give a recoverable signature to `+curves::secp256k1::recover+`, which gives the signer's key; `+crypto::verify+` takes `+crypto::ecdsa_sha256+` and `+crypto::schnorr+` with a secp256k1 key. +|`+verify_keccak_recoverable+` +|native, wasip2, wasip3 +|`+webcpp::crypto: verify: this public key does not go with this scheme: crypto::eddsa and crypto::eddsa_prehashed take a curves::ed25519::public_key, crypto::ecdsa_sha256 a curves::p256::basic_public_key or a curves::secp256k1::public_key, crypto::schnorr a curves::secp256k1::public_key or a 32-byte x-only key; a crypto::ecdsa_sha256_recoverable or a crypto::ecdsa_keccak256_recoverable signature gives its key to curves::secp256k1::recover.+` + +The fix: Give the signature to `+curves::secp256k1::recover(crypto::ecdsa_keccak256_recoverable, signature, input)+`, which gives the signer's key, and compare that key, or its address, with the one expected: Ethereum's recoverable ECDSA has no `+verify+`. + |`+verify_member_ed25519_ecdsa+` |native, wasip2, wasip3 -|`+webcpp::crypto: an Ed25519 public key verifies crypto::eddsa.+` +|`+webcpp::crypto: an Ed25519 public key verifies crypto::eddsa or crypto::eddsa_prehashed.+` -The fix: Verify with `+crypto::eddsa+`, Ed25519's scheme; `+crypto::ecdsa_sha256+` is P-256's and secp256k1's, whose keys are `+curves::p256::basic_public_key+` and `+curves::secp256k1::public_key+`. +The fix: Verify with `+crypto::eddsa+` or `+crypto::eddsa_prehashed+`, Ed25519's schemes; `+crypto::ecdsa_sha256+` is P-256's and secp256k1's, whose keys are `+curves::p256::basic_public_key+` and `+curves::secp256k1::public_key+`. |`+verify_member_eddsa_prehashed+` |native, wasip2, wasip3 -|`+webcpp::crypto: crypto::eddsa signs the message itself (RFC 8032's pure Ed25519) and takes no digest; Ed25519ph, which hashes the message, is curves::ed25519::ph.+` +|`+webcpp::crypto: crypto::eddsa signs the message itself (RFC 8032's pure Ed25519) and takes no digest; a message's SHA-512 is signed with crypto::eddsa_prehashed (Ed25519ph).+` -The fix: Verify the message itself with `+crypto::eddsa+`, RFC 8032's pure Ed25519, which takes no digest, as `+crypto::verify+` does; a message given in pieces is Ed25519ph's, `+curves::ed25519::ph+`. +The fix: Verify the message itself with `+crypto::eddsa+`, RFC 8032's pure Ed25519, which takes no digest, as `+crypto::verify+` does; a signature of a message's SHA-512 is Ed25519ph's, verified with `+crypto::eddsa_prehashed+`, or for a message given in pieces with `+curves::ed25519::prehashed_signer+`. |`+verify_member_p256_eddsa+` |native, wasip2, wasip3 @@ -465,20 +851,66 @@ The fix: Verify with `+crypto::ecdsa_sha256+`, P-256's scheme; `+crypto::eddsa+` |`+verify_member_secp256k1_recoverable+` |native, wasip2, wasip3 -|`+webcpp::crypto: a secp256k1 public key verifies crypto::ecdsa_sha256 or crypto::schnorr; a crypto::ecdsa_sha256_recoverable signature gives its key to curves::secp256k1::recover.+` +|`+webcpp::crypto: a secp256k1 public key verifies crypto::ecdsa_sha256 or crypto::schnorr; a crypto::ecdsa_sha256_recoverable or a crypto::ecdsa_keccak256_recoverable signature gives its key to curves::secp256k1::recover.+` The fix: Give a recoverable signature to `+curves::secp256k1::recover(crypto::ecdsa_sha256_recoverable, signature, input)+`, which gives the signer's key; a public key verifies `+crypto::ecdsa_sha256+` and `+crypto::schnorr+`. +|`+verify_p256_secp256k1_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.+` + +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_schnorr_as_ecdsa+` +|native, wasip2, wasip3 +|`+webcpp::crypto: verify: a secp256k1 key verifies a curves::secp256k1::ecdsa_signature under crypto::ecdsa_sha256: make one from 64 bytes with curves::secp256k1::ecdsa_signature::from_bytes.+` + +The fix: Verify a BIP340 signature with `+crypto::schnorr+`, its scheme; `+crypto::ecdsa_sha256+` takes a `+curves::secp256k1::ecdsa_signature+`, which `+sign(crypto::ecdsa_sha256, input)+` gives. + +|`+wipe_removed+` +|native, wasip2, wasip3 +|`+no type named 'wipe' in namespace 'webcpp::crypto'+` + +The fix: Call `+crypto::erase_secret+`, which zeroes a contiguous range the program owns (a `+std::string&+`, a `+std::span+`) with stores the optimiser keeps; `+crypto::wipe+` is gone, with no alias. + +|`+x25519_asynchronous_backend+` +|native, wasip2, wasip3 +|`+webcpp::crypto: from_secret on this backend completes asynchronously: call async_from_secret.+` + +`+webcpp::crypto: generate on this backend completes asynchronously: call async_generate.+` + +`+webcpp::crypto: agree on this backend completes asynchronously: call async_agree.+` + +The fix: Call `+async_from_secret+`, `+async_generate+` or `+async_agree+` on a backend that completes by itself: an X25519 key pair's synchronous forms cannot wait for it. + +|`+x25519_constructions_other_backend+` +|native, wasip2, wasip3 +|`+webcpp::crypto: key_exchange::kx_keypair holds an X25519 key pair of its own backend, which has no X25519.+` + +`+webcpp::crypto: public_key_encryption::basic_box takes an X25519 key pair of its own backend, which has no X25519.+` + +`+webcpp::crypto: public_key_encryption::basic_sealed_box takes an X25519 key pair of its own backend, which has no X25519.+` + +The fix: 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. + |`+x25519_default_not_linked+` |native, wasip2, wasip3 |`+webcpp::crypto: X25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//x25519-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//x25519-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)+` The fix: Add `+/webcpp/crypto//x25519-default+`, which links `+/third_party//sodium+` on every target. + +|`+x25519_free_functions_removed+` +|native, wasip2, wasip3 +|`+no member named 'agree' in namespace 'webcpp::crypto::curves::x25519'+` + +`+no matching conversion for functional-style cast+` + +The fix: Make the key pair with `+curves::x25519::keypair::from_secret(secret)+`, then call its `+public_key()+`, and its `+agree+` with the peer's `+curves::x25519::public_key+` from `+from_bytes+`; the free functions over bytes are gone, with no alias. The `+x25519::public_key(secret)+` half pins clang's generic "no matching conversion for functional-style cast", since `+public_key+` now names the type. |=== At build and link time, from the fixtures of the user's Jamfiles, each built on a scratch superproject: the texts the build's output contains, per target and linker, as each fixture checks them. -`+aead_not_a_family_on_emscripten+`:: A program for Emscripten that gives `+ciphers::aead+` AES-GCM's family, which `+ciphers::gcm+` serves instead. The fix: As `+aead_not_a_family+`. +`+aead_not_a_family_on_emscripten+`:: A program for Emscripten that gives `+ciphers::basic_chacha20_poly1305+` AES-GCM's family, which `+ciphers::gcm+` serves instead. The fix: As `+aead_not_a_family+`. + Its Jamfile: + @@ -490,7 +922,7 @@ include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/aead_not_a_family_on_ On each target, the build's output contains: + * emscripten: -** `+webcpp::crypto: ciphers::aead takes an AEAD family: families::chacha20_poly1305, families::chacha20_poly1305_original, families::xchacha20_poly1305, families::secretbox_xsalsa20poly1305 or families::secretbox_xchacha20poly1305.+` +** `+webcpp::crypto: ciphers::basic_chacha20_poly1305 takes an AEAD family: families::chacha20_poly1305, families::chacha20_poly1305_original or families::xchacha20_poly1305.+` `+aes_block_default_not_linked_on_emscripten+`:: A program for Emscripten that calls the AES block cipher on its default, ctaes, and links none. The fix: Add `+/webcpp/crypto//aes_block-default+`, which links `+/third_party//ctaes+` there, to the program's sources. + @@ -524,7 +956,7 @@ On each target, the build's output contains: ** `+webcpp::crypto: X25519-XChaCha20-Poly1305 box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//box_xchacha20poly1305-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//box_xchacha20poly1305-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)+` ** `+webcpp::crypto: X25519-XSalsa20-Poly1305 sealed box's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//sealed_box-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//sealed_box-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)+` -`+box_not_a_family_on_emscripten+`:: A program for Emscripten that gives `+hybrid::basic_box+` a type that is no box family. The fix: As `+box_not_a_family+`. +`+box_not_a_family_on_emscripten+`:: A program for Emscripten that gives `+public_key_encryption::basic_box+` a type that is no box family. The fix: As `+box_not_a_family+`. + Its Jamfile: + @@ -536,7 +968,7 @@ include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/box_not_a_family_on_e On each target, the build's output contains: + * emscripten: -** `+webcpp::crypto: hybrid::basic_box takes a box family: families::box_xsalsa20poly1305 or families::box_xchacha20poly1305.+` +** `+webcpp::crypto: public_key_encryption::basic_box takes a box family: families::box_xsalsa20poly1305 or families::box_xchacha20poly1305.+` `+canary_ctaes_missing+`:: ctaes's headers used without its library. The fix: Link `+/third_party//ctaes+`. + @@ -904,7 +1336,7 @@ On each target, the build's output contains: * emscripten: ** `+webcpp::crypto: Ed25519's only verification policy is curves::ed25519::strict.+` -`+ed25519ph_sha256_on_emscripten+`:: A program for Emscripten that names SHA-256 in Ed25519ph's type, which RFC 8032 defines over SHA-512. The fix: As `+ed25519ph_sha256+`. +`+ed25519ph_sha256_on_emscripten+`:: A program for Emscripten that names SHA-256 in Ed25519ph's streaming signer, `+curves::ed25519::prehashed_signer+`, which RFC 8032 defines over SHA-512. The fix: As `+ed25519ph_sha256+`. + Its Jamfile: + @@ -916,7 +1348,7 @@ include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/ed25519ph_sha256_on_e On each target, the build's output contains: + * emscripten: -** `+webcpp::crypto: Ed25519ph is defined over SHA-512 (RFC 8032 section 5.1); name curves::ed25519::ph.+` +** `+webcpp::crypto: Ed25519ph is defined over SHA-512 (RFC 8032 section 5.1); name curves::ed25519::prehashed_signer.+` `+has_openssl_on_emscripten+`:: OpenSSL declared linked, without b2, in a build for Emscripten. The fix: Replace `+/webcpp/crypto//openssl+` with `+/third_party//bearssl+`. + @@ -960,13 +1392,13 @@ On each target, the build's output contains: * emscripten: ** `+webcpp::crypto: crypto_kx's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//kx-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//kx-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)+` -`+memory_missing_definition_install+`:: The memory option set in the program's project, the install called, and `+openssl_memory_resource()+` not defined. The fix: Define `+std::pmr::memory_resource& webcpp::crypto::openssl_memory_resource() noexcept+` once in the program, returning a resource that is never destroyed. +`+memory_missing_definition_from_key+`:: The memory option set in the program's project, a `+from_key+` on OpenSSL, and `+openssl_memory_resource()+` not defined. The fix: Define `+std::pmr::memory_resource& webcpp::crypto::openssl_memory_resource() noexcept+` once in the program, returning a resource that is never destroyed. + Its Jamfile: + [listing] ---- -include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/memory_missing_definition_install/Jamfile[tag=jamfile] +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/memory_missing_definition_from_key/Jamfile[tag=jamfile] ---- + On each target, the build's output contains: @@ -977,13 +1409,13 @@ On each target, the build's output contains: * native, Linux: ** `pass:[undefined reference to `webcpp::crypto::openssl_memory_resource()']` -`+memory_missing_definition_make+`:: The memory option set in the program's project, a `+make+` on OpenSSL, and `+openssl_memory_resource()+` not defined. The fix: Define `+std::pmr::memory_resource& webcpp::crypto::openssl_memory_resource() noexcept+` once in the program, returning a resource that is never destroyed. +`+memory_missing_definition_install+`:: The memory option set in the program's project, the install called, and `+openssl_memory_resource()+` not defined. The fix: Define `+std::pmr::memory_resource& webcpp::crypto::openssl_memory_resource() noexcept+` once in the program, returning a resource that is never destroyed. + Its Jamfile: + [listing] ---- -include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/memory_missing_definition_make/Jamfile[tag=jamfile] +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/memory_missing_definition_install/Jamfile[tag=jamfile] ---- + On each target, the build's output contains: @@ -1106,7 +1538,7 @@ On each target, the build's output contains: * emscripten: ** `+webcpp::crypto: the backend libsodium is used and not linked. In the program's Jamfile, add /third_party//sodium beside /webcpp/crypto//crypto, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)+` -`+x25519_default_not_linked_on_emscripten+`:: A program for Emscripten that agrees an X25519 shared secret on its default, libsodium, and links none. The fix: As `+x25519_default_not_linked+`. +`+x25519_default_not_linked_on_emscripten+`:: A program for Emscripten that makes an X25519 key pair and agrees a shared secret on its default, libsodium, and links none. The fix: As `+x25519_default_not_linked+`. + Its Jamfile: + @@ -1128,7 +1560,7 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |`+aead_not_a_family+` |the compile -|Name one of the three ChaCha20-Poly1305 families or the two secret boxes'; AES-GCM is `+ciphers::gcm+`, as in `+aes256_gcm+`. +|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<>+`. |`+aes_block_default_not_linked+` |the compile @@ -1138,17 +1570,21 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |Name `+ciphers::aes256+`, include `++` and add `+/third_party//ctaes+`. -|`+async_make_xchacha+` +|`+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. + +|`+async_from_secret_secp256k1+` |the compile -|Call the synchronous `+make+`: XChaCha20-Poly1305 is not in WebCrypto, so it has no asynchronous form. +|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+`. |`+async_open_xchacha+` |the compile -|Call the AEAD's own `+open+`: only AES-GCM has `+async_open+`. +|Name a native backend, such as `+backends::sodium+`, for `+async_open+`, or open with AES-GCM on the browser's backend: WebCrypto has no XChaCha20-Poly1305. |`+async_seal_xchacha+` |the compile -|Call the AEAD's own `+seal+`: only AES-GCM has `+async_seal+`. +|Name a native backend, such as `+backends::sodium+`, for `+async_seal+`, or seal with AES-GCM on the browser's backend: WebCrypto has no XChaCha20-Poly1305. |`+async_sign_secp256k1+` |the compile @@ -1164,7 +1600,7 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |`+box_not_a_family+` |the compile -|Name `+families::box_xsalsa20poly1305+` or `+families::box_xchacha20poly1305+`, or use `+hybrid::box+` or `+hybrid::box_xchacha20poly1305+`. +|Name `+families::box_xsalsa20poly1305+` or `+families::box_xchacha20poly1305+`, or use `+public_key_encryption::box+` or `+public_key_encryption::box_xchacha20poly1305+`. |`+canary_ctaes_missing+` |the link @@ -1244,7 +1680,7 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |`+ed25519ph_sha256+` |the compile -|Name `+curves::ed25519::ph+`: RFC 8032 defines Ed25519ph over SHA-512. +|Name `+curves::ed25519::prehashed_signer+`: RFC 8032 defines Ed25519ph over SHA-512. |`+ellswift_other_backend+` |the compile @@ -1270,11 +1706,11 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |Return `+std::optional>+`, a span over a tweak the lookup keeps, such as a map's entry; never the tweak by value. -|`+memory_missing_definition_install+` +|`+memory_missing_definition_from_key+` |the link |Define `+std::pmr::memory_resource& webcpp::crypto::openssl_memory_resource() noexcept+` once in the program, returning a resource that is never destroyed. -|`+memory_missing_definition_make+` +|`+memory_missing_definition_install+` |the link |Define `+std::pmr::memory_resource& webcpp::crypto::openssl_memory_resource() noexcept+` once in the program, returning a resource that is never destroyed. @@ -1326,9 +1762,17 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |Give `+secret+` the number of bytes it holds, at least one, as in `+secret<32>+`. +|`+sign_eddsa_prehashed_message+` +|the compile +|Give `+crypto::eddsa_prehashed+` the message's SHA-512 marked as a digest, `+crypto::prehashed{digest}+` of a `+std::array+`; sign the message itself with `+crypto::eddsa+`, or give it in pieces to `+curves::ed25519::prehashed_signer+`. + +|`+sign_keccak_without_xkcp+` +|the compile +|Add `+/third_party//xkcp+` to the program's Jamfile, whose Keccak-256 hashes the message, or build the 32-byte digest elsewhere and sign `+crypto::prehashed{digest}+`, which needs no XKCP. + |`+silent_payments_other_backend+` |the compile -|Name `+backends::secp256k1+`, or leave the backend out: `+curves::secp256k1::silent_payments::make_prevouts_summary(...)+`. +|Name `+backends::secp256k1+`, or leave the backend out: `+curves::secp256k1::silent_payments::make_previous_outputs_summary(...)+`. |`+sodium_not_linked+` |the compile diff --git a/doc/generated/namespace-ciphers.adoc b/doc/generated/namespace-ciphers.adoc index 56bbde52..ddafec70 100644 --- a/doc/generated/namespace-ciphers.adoc +++ b/doc/generated/namespace-ciphers.adoc @@ -24,12 +24,12 @@ |16, 24 or 32 bytes |16, 24 or 32 bytes -|Nonce (IV) +|Nonce |1 to 128 bytes; 12 recommended |none |Nonce misuse -|not resistant: a repeated IV under one key reveals the plaintexts' XOR and lets tags be forged (link:https://csrc.nist.gov/csrc/media/projects/block-cipher-techniques/documents/bcm/comments/800-38-series-drafts/gcm/joux_comments.pdf[A. Joux, Authentication Failures in NIST version of GCM, 2006], link:https://eprint.iacr.org/2016/475[H. Boeck et al., Nonce-Disrespecting Adversaries, 2016]) +|not resistant: a repeated nonce under one key reveals the plaintexts' XOR and lets tags be forged (link:https://csrc.nist.gov/csrc/media/projects/block-cipher-techniques/documents/bcm/comments/800-38-series-drafts/gcm/joux_comments.pdf[A. Joux, Authentication Failures in NIST version of GCM, 2006], link:https://eprint.iacr.org/2016/475[H. Boeck et al., Nonce-Disrespecting Adversaries, 2016]) |none: a block cipher takes no nonce, and equal blocks give equal ciphertext |Speed, with and without hardware support @@ -57,7 +57,7 @@ |no raw block cipher (link:https://www.w3.org/TR/WebCryptoAPI/[W3C Web Cryptography API]) |Choose it when -|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 IVs, otherwise a counter +|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 |you need one keyed permutation of a 16-byte block, such as an opaque identifier; for data, use an AEAD |=== @@ -81,7 +81,7 @@ |32 bytes |32 bytes -|Nonce (IV) +|Nonce |12 bytes |8 bytes, too short to draw at random: a counter |24 bytes, safe to draw at random for every message @@ -126,57 +126,3 @@ |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 |=== - -.Secret boxes -[cols="2h,5,5",options="header"] -|=== -|Algorithm |XSalsa20-Poly1305 (NaCl's secret box) |XChaCha20-Poly1305 secret box - -|Names -|`secretbox` -|`secretbox_xchacha20poly1305` - -|AEAD -|yes, without additional data -|yes, without additional data - -|Key -|32 bytes -|32 bytes - -|Nonce (IV) -|24 bytes, safe to draw at random -|24 bytes, safe to draw at random - -|Nonce misuse -|not resistant to a repeated nonce; random ones never repeat in practice (link:https://cr.yp.to/snuffle/xsalsa-20081128.pdf[D. J. Bernstein, Extending the Salsa20 nonce, 2008]) -|not resistant to a repeated nonce; random ones never repeat in practice (link:https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha[draft-irtf-cfrg-xchacha, XChaCha20-Poly1305]) - -|Speed, with and without hardware support -|not measured yet -|not measured yet - -|Constant time, by design -|libsodium: yes, additions, XORs and rotations with no table lookup (link:https://cr.yp.to/snuffle/design.pdf[D. J. Bernstein, Salsa20 design: why add-rotate-xor]) -|libsodium: yes (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 (<>) -|libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found; not measured yet on wasip2, wasip3, emscripten (<>) - -|Standards -|none: NaCl's construction (link:https://nacl.cr.yp.to/secretbox.html[NaCl, secret-key authenticated encryption (crypto_secretbox)]) -|none: libsodium's construction (link:https://doc.libsodium.org/secret-key_cryptography/secretbox[libsodium's documentation, secret-key authenticated encryption]) - -|Where it is used -|programs that read or write NaCl's and libsodium's `crypto_secretbox` (link:https://doc.libsodium.org/secret-key_cryptography/secretbox[libsodium's documentation, secret-key authenticated encryption]) -|programs on libsodium's `crypto_secretbox_xchacha20poly1305` (link:https://doc.libsodium.org/secret-key_cryptography/secretbox[libsodium's documentation, secret-key authenticated encryption]) - -|Browsers' WebCrypto -|no (link:https://www.w3.org/TR/WebCryptoAPI/[W3C Web Cryptography API]) -|no (link:https://www.w3.org/TR/WebCryptoAPI/[W3C Web Cryptography API]) - -|Choose it when -|the data must be read by a program on NaCl's or libsodium's `crypto_secretbox`; otherwise XChaCha20-Poly1305, which also authenticates additional data -|the peer writes libsodium's `crypto_secretbox_xchacha20poly1305`; otherwise `xchacha20_poly1305` -|=== diff --git a/doc/generated/namespace-curves.adoc b/doc/generated/namespace-curves.adoc index be5401a2..3b8e3bb0 100644 --- a/doc/generated/namespace-curves.adoc +++ b/doc/generated/namespace-curves.adoc @@ -13,8 +13,8 @@ |What it does |BIP 340 Schnorr and ECDSA signatures, recoverable signatures, ECDH in three forms, tweaks, ElligatorSwift, MuSig2, silent payments, SPKI and PKCS#8 -|Ed25519 signatures, and Ed25519ph over SHA-512 for a message given in pieces; the X25519 secret key of a key pair -|Key agreement (Diffie-Hellman on Curve25519): two parties who exchanged public keys share a 32-byte secret; `kx_keypair`, libsodium's `crypto_kx`, gives a client and a server a session key for each direction +|Ed25519 signatures, and Ed25519ph over SHA-512, of a digest (`crypto::eddsa_prehashed`) or of a message given in pieces; a key pair's and a public key's conversion to X25519's typed keys +|Key agreement (Diffie-Hellman on Curve25519): two parties who exchanged public keys share a 32-byte secret, which `key_exchange::kx_keypair` and the boxes of `public_key_encryption` build on |Key pairs made from a 32-byte scalar or drawn from `random_device`, public keys validated once, as SEC 1's uncompressed point or two coordinates, ECDSA over SHA-256 of a message or a digest with RFC 6979's nonce, signed low S, raw and DER, and low S checked or normalized, ECDH's raw x coordinate, SPKI and PKCS#8 |Security level @@ -68,6 +68,6 @@ |Choose it for compatibility with |Bitcoin's keys and signatures; Nostr's event signatures (link:https://github.com/nostr-protocol/nips/blob/master/01.md[Nostr NIP-01, events signed with BIP 340 on secp256k1]); Ethereum's ECDSA verification with a known key; ECDH in the raw x-coordinate form of Nostr's encrypted messages (link:https://github.com/nostr-protocol/nips/blob/master/44.md[Nostr NIP-44, encrypted payloads]); Ethereum's recoverable signatures and uncompressed keys (link:https://ethereum.github.io/yellowpaper/paper.pdf[The Ethereum yellow paper, appendix F: ECDSA on secp256k1]), the address hashing being a domain library's; BIP 32's tweaks of the full key, its derivation of the tweak being a domain library's (link:https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki[BIP 32, hierarchical deterministic wallets]); keys exchanged with OpenSSL as SPKI or PKCS#8 (link:https://www.rfc-editor.org/rfc/rfc5480[RFC 5480, Elliptic Curve Cryptography Subject Public Key Information], link:https://www.rfc-editor.org/rfc/rfc5915[RFC 5915, Elliptic Curve Private Key Structure]), in DER or PEM (link:https://www.rfc-editor.org/rfc/rfc7468[RFC 7468, textual encodings of PKIX, PKCS and CMS structures (PEM)]); Bitcoin's version 2 transport, whose keys are ElligatorSwift encodings (link:https://github.com/bitcoin/bips/blob/master/bip-0324.mediawiki[BIP 324, version 2 P2P encrypted transport protocol]); MuSig2's multisignatures (link:https://github.com/bitcoin/bips/blob/master/bip-0327.mediawiki[BIP 327, MuSig2 for BIP340-compatible multi-signatures]); silent payments (link:https://github.com/bitcoin/bips/blob/master/bip-0352.mediawiki[BIP 352, Silent Payments]), the addresses and transactions being a domain library's |SSH, Tor and Solana keys and signatures, and any protocol that names RFC 8032's Ed25519 or Ed25519ph; verification is strict (libsodium's rules), which some lenient verifiers are not. Not Bitcoin, Ethereum or Nostr, whose keys are secp256k1's -|TLS 1.3's and SSH's key exchange, WireGuard, Signal; libsodium's `crypto_box` keys, and the session keys of `crypto_kx` with `kx_keypair` (link:https://doc.libsodium.org/key_exchange[libsodium's documentation, key exchange]). The Ed25519 public key of a peer converts with `curves::ed25519::to_x25519_public`. A shared secret goes through a KDF before it keys a cipher. Every case of Wycheproof's X25519 file is tested (link:https://github.com/C2SP/wycheproof[Project Wycheproof, test vectors for cryptographic libraries]) -|Browsers' WebCrypto, whose raw export of a P-256 public key is the uncompressed point `public_key::make` takes (link:https://www.w3.org/TR/WebCryptoAPI/[W3C Web Cryptography API]) and whose ECDH `deriveBits` is the raw x `agree` gives (link:https://www.w3.org/TR/WebCryptoAPI/#ecdh-operations[W3C Web Cryptography API, ECDH's deriveBits: the shared point's x coordinate, its first length bits]); passkeys and TLS. Not Bitcoin, Ethereum or Nostr, whose keys are secp256k1's +|TLS 1.3's and SSH's key exchange, WireGuard, Signal; libsodium's `crypto_box` keys, and the session keys of `crypto_kx` with `key_exchange::kx_keypair` (link:https://doc.libsodium.org/key_exchange[libsodium's documentation, key exchange]). The Ed25519 public key of a peer converts with its `to_x25519()`. A shared secret goes through a KDF before it keys a cipher. Every case of Wycheproof's X25519 file is tested (link:https://github.com/C2SP/wycheproof[Project Wycheproof, test vectors for cryptographic libraries]) +|Browsers' WebCrypto, whose raw export of a P-256 public key is the uncompressed point `public_key::from_bytes` takes (link:https://www.w3.org/TR/WebCryptoAPI/[W3C Web Cryptography API]) and whose ECDH `deriveBits` is the raw x `agree` gives (link:https://www.w3.org/TR/WebCryptoAPI/#ecdh-operations[W3C Web Cryptography API, ECDH's deriveBits: the shared point's x coordinate, its first length bits]); passkeys and TLS. Not Bitcoin, Ethereum or Nostr, whose keys are secp256k1's |=== diff --git a/doc/generated/namespace-key_exchange.adoc b/doc/generated/namespace-key_exchange.adoc new file mode 100644 index 00000000..1ab77ffb --- /dev/null +++ b/doc/generated/namespace-key_exchange.adoc @@ -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) + +// 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"] +|=== +|Construction |crypto_kx + +|Names +|`kx_keypair` + +|What it does +|Session keys for a client and a server: X25519 agrees a secret, and BLAKE2b-512 of it and both public keys gives each side a key to receive with and one to transmit with + +|Keys +|a key pair that holds an X25519 key pair, taken as is, derived from a 32-byte seed or drawn, and the peer's X25519 public key + +|Output +|two 32-byte `secret<32>` per side, the client's `transmit` the server's `receive` + +|Standards and sources +|link:https://doc.libsodium.org/key_exchange[libsodium's documentation, key exchange] + +|Choose it when +|a client and a server that swapped public keys need a key for each direction, as libsodium's `crypto_kx` gives them; a peer key of low order is refused; a protocol with a KDF of its own uses X25519's `agree` instead +|=== diff --git a/doc/generated/namespace-hybrid.adoc b/doc/generated/namespace-public_key_encryption.adoc similarity index 93% rename from doc/generated/namespace-hybrid.adoc rename to doc/generated/namespace-public_key_encryption.adoc index 1395c2d4..6f6b4a0e 100644 --- a/doc/generated/namespace-hybrid.adoc +++ b/doc/generated/namespace-public_key_encryption.adoc @@ -22,11 +22,11 @@ |Encryption to a public key alone: a key pair drawn per message, whose public key travels with it; the recipient cannot tell who sealed it, and the sender cannot open it afterwards |Keys -|the own 32-byte secret key and the peer's 32-byte X25519 public key +|the own X25519 key pair and the peer's X25519 public key |the same -|to seal, the recipient's 32-byte public key; to open, the recipient's key pair +|to seal, the recipient's X25519 public key; to open, the recipient's X25519 key pair -|Nonce (IV) +|Nonce |24 bytes, safe to draw at random (link:https://cr.yp.to/snuffle/xsalsa-20081128.pdf[D. J. Bernstein, Extending the Salsa20 nonce, 2008]) |24 bytes, safe to draw at random |none: derived from the two public keys diff --git a/doc/generated/namespace-root.adoc b/doc/generated/namespace-root.adoc index bfdd5839..f5f09200 100644 --- a/doc/generated/namespace-root.adoc +++ b/doc/generated/namespace-root.adoc @@ -7,9 +7,9 @@ // Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, // the message tests and the Jamfile fixtures: run it again, never edit this file. -[cols="2h,5,5,5,5,5,5,5,5",options="header"] +[cols="2h,5,5,5,5,5,5,5,5,5,5",options="header"] |=== -|Name |`random_device` |`equal` |`error` |`pem` |`openssl_memory_resource` |Signatures |The key pair contract |Making by type +|Name |`random_device` |`constant_time_equal` |`erase_secret` |`secret` |`error` |`pem` |`openssl_memory_resource` |Signatures |The key pair concepts |Making by type |Names | @@ -17,57 +17,69 @@ | | | -|`eddsa`, `ecdsa_sha256`, `ecdsa_sha256_recoverable`, `schnorr`, `prehashed`, `can_sign`, `can_verify`, `sign`, `verify` -|`keypair`, `agree` -|`make`, `generate` +| +| +|`eddsa`, `eddsa_prehashed`, `ecdsa_sha256`, `ecdsa_sha256_recoverable`, `ecdsa_keccak256_recoverable`, `schnorr`, `prehashed`, `can_sign`, `can_verify`, `verify` +|`keypair`, `signing_keypair`, `agreement_keypair`, `sign`, `agree` +|`from_secret`, `from_bytes`, `from_key`, `generate` |What it is for -|Keys, IVs, tokens, nonces: every secret a program draws +|Keys, nonces, tokens: every secret a program draws |Checking a tag, a MAC or a token +|Erasing a password, a key or a plaintext from a buffer the program owns +|Holding a secret crypto gives back: a key pair's `secret()`, a shared secret, a session key |Telling failures apart |A key's SPKI or PKCS#8 as text, to paste, store or exchange with OpenSSL |Keeping every allocation of OpenSSL's in the program's own resource, natively -|Naming the scheme of every signature, and a digest as a digest, on every curve -|Code written once for every curve's key pair -|Making a key pair, a public key or an AEAD from its bytes, or drawing a key pair, the type named once +|Naming the scheme of every signature, a digest as a digest, and a signature as a value of its curve and scheme, on every curve +|Code written once for every curve's key pair, by what it does +|Making a key pair from its secret, a public key or a signature from its bytes, or an AEAD or a secret box from its key, or drawing a key pair, the type named once |Header |`` -|`` +|`` +|`` +|`` |`` |`` |`` |`` |`` -|`` +|`` |Errors |`entropy_unavailable`, `errc::not_supported` |none: it returns `bool` +|none +|none |its values are the errors |`invalid_encoding`, `invalid_input_size` |`memory_functions_refused`, `memory_functions_not_installed` |`verify`: `invalid_signature`, and `invalid_public_key` for 32 x-only bytes that are no point; `sign`: `invalid_state`, `entropy_unavailable` (Schnorr's drawn randomness), `backend_failure`; a scheme and an input that do not go together stop the build -|`keypair`: none, a concept checked at compile time; `agree`: what the key pair's `agree` returns, and a peer it does not take stops the build -|the member's: `make(bytes)` returns what `A::make(bytes)` returns, `generate()` what `K::generate()` returns +|the concepts: none, checked at compile time; `sign` and `agree`: what the key pair's own returns, and a key pair that does not do the operation, or arguments it does not take, stop the build +|the member's: `from_secret(bytes)` returns what `K::from_secret(bytes)` returns, `from_bytes(bytes)` what `T::from_bytes(bytes)` returns, `from_key(key)` what `C::from_key(key)` returns, `generate()` what `K::generate()` returns |Standards and sources |link:https://pubs.opengroup.org/onlinepubs/9799919799/functions/getentropy.html[POSIX.1-2024, getentropy], link:https://learn.microsoft.com/en-us/windows/win32/api/bcrypt/nf-bcrypt-bcryptgenrandom[Microsoft, BCryptGenRandom], link:https://www.w3.org/TR/WebCryptoAPI/#Crypto-method-getRandomValues[W3C Web Cryptography API, getRandomValues], link:https://github.com/WebAssembly/wasi-random[WASI, wasi:random] |link:https://cwe.mitre.org/data/definitions/208.html[CWE-208, observable timing discrepancy] +|link:https://cwe.mitre.org/data/definitions/14.html[CWE-14, compiler removal of code to clear buffers] +|link:https://cwe.mitre.org/data/definitions/14.html[CWE-14, compiler removal of code to clear buffers] |none |link:https://www.rfc-editor.org/rfc/rfc7468[RFC 7468, textual encodings of PKIX, PKCS and CMS structures (PEM)], link:https://doc.libsodium.org/helpers#base64-encoding-decoding[libsodium's documentation, helpers: base64 encoding and decoding] |link:https://docs.openssl.org/3.5/man3/OPENSSL_malloc/[OpenSSL 3.5's OPENSSL_malloc(3), CRYPTO_set_mem_functions] |link:https://www.rfc-editor.org/rfc/rfc8032[RFC 8032, the Edwards-curve Digital Signature Algorithm (EdDSA)], link:https://csrc.nist.gov/pubs/fips/186-5/final[FIPS 186-5, the Digital Signature Standard], link:https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki[BIP 340, Schnorr signatures for secp256k1], link:https://www.w3.org/TR/WebCryptoAPI/[W3C Web Cryptography API] -|link:https://www.rfc-editor.org/rfc/rfc8032[RFC 8032, the Edwards-curve Digital Signature Algorithm (EdDSA)], link:https://csrc.nist.gov/pubs/fips/186-5/final[FIPS 186-5, the Digital Signature Standard], link:https://www.secg.org/sec1-v2.pdf[SEC 1 version 2, Elliptic Curve Cryptography, sections 2.3.3 and 2.3.4: a point's encodings] +|link:https://www.rfc-editor.org/rfc/rfc8032[RFC 8032, the Edwards-curve Digital Signature Algorithm (EdDSA)], link:https://www.rfc-editor.org/rfc/rfc7748[RFC 7748, Elliptic Curves for Security (X25519 and X448)], link:https://csrc.nist.gov/pubs/fips/186-5/final[FIPS 186-5, the Digital Signature Standard], link:https://www.secg.org/sec1-v2.pdf[SEC 1 version 2, Elliptic Curve Cryptography, sections 2.3.3 and 2.3.4: a point's encodings] |none |Choose it when -|you need a random number an attacker must not predict; never `std::mt19937` or `rand` (link:https://cwe.mitre.org/data/definitions/338.html[CWE-338, a weak generator used for security]) -|you compare anything secret; never `==` or `memcmp` on a MAC +|you need a random number an attacker must not predict; never `std::mt19937` or `rand` (link:https://cwe.mitre.org/data/definitions/338.html[CWE-338, a weak generator used for security]); <> +|you compare anything secret; never `==` or `memcmp` on a MAC; <> +|a secret sits in a `std::string`, a `std::vector` or an array of the program's and must not outlive its use; never `memset`, which the optimiser may drop; <> +|crypto returns a secret: it wipes itself when destroyed or moved from, is copied only by `clone()`, and gives its bytes with `bytes()`; keep it in one variable; <> |you branch on a failure: forged data, a wrong size, no entropy |a key goes to or comes from a file, a form or a tool as `-----BEGIN PUBLIC KEY-----` text; with the `encode_spki` and `encode_pkcs8` of `curves::ed25519`, `curves::x25519`, `curves::secp256k1` or `curves::p256` |a native program on OpenSSL must allocate only from its own arena; on WebAssembly, BearSSL allocates nothing -|a key pair signs with `key_pair.sign(scheme, input)` or `sign(key_pair, scheme, input)`, and a signature is checked with `public_key.verify(scheme, signature, input)` or `verify(scheme, signature, input, public_key)`; a digest computed elsewhere, such as a Bitcoin sighash, goes in marked as `prehashed`, never as a bare span -|a template takes any curve's key pair: `make`, `generate`, a typed `public_key()` that `verify` takes, `secret()`, and `sign(scheme, input)`; `agree(key_pair, peer)` is the free form of `key_pair.agree(peer)` -|generic code makes any key pair, public key or AEAD by its type, `make(bytes)`, or draws a key pair, `generate()`; the free forms of the static members `make` and `generate` +|a key pair signs with `key_pair.sign(scheme, input)` or `sign(key_pair, scheme, input)`, and a signature is checked with `public_key.verify(scheme, signature, input)` or `verify(scheme, signature, input, public_key)`; a digest computed elsewhere, such as a Bitcoin sighash, an Ethereum EIP-191 digest or the SHA-512 Ed25519ph signs, goes in marked as `prehashed`, never as a bare span; the two recoverable schemes have no `verify`: their signature gives its key to `curves::secp256k1::recover`; a signature is a type of its curve and scheme, made from received bytes by `from_bytes` (<>) +|a template takes any curve's key pair: `from_secret`, `generate`, a typed `public_key()`, `secret()`; a `signing_keypair` (Ed25519, P-256, secp256k1) adds `sign(scheme, input)`, whose `crypto::sign(key_pair, scheme, input)` is the free form, an `agreement_keypair` (X25519, P-256, secp256k1) `agree(peer)`, whose free form is `agree(key_pair, peer)` (<>) +|generic code makes any key pair, public key, signature or AEAD by its type, each factory named by its input, or draws a key pair, `generate()`; the free forms of the static members `from_secret`, `from_bytes`, `from_key` and `generate`; a new key is drawn by `generate`, never made by `from_secret` from fixed bytes (<>) |=== diff --git a/doc/generated/namespace-secret_key_encryption.adoc b/doc/generated/namespace-secret_key_encryption.adoc new file mode 100644 index 00000000..829adae8 --- /dev/null +++ b/doc/generated/namespace-secret_key_encryption.adoc @@ -0,0 +1,116 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the 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. + +.Secret boxes +[cols="2h,5,5",options="header"] +|=== +|Algorithm |XSalsa20-Poly1305 (NaCl's secret box) |XChaCha20-Poly1305 secret box + +|Names +|`secretbox` +|`secretbox_xchacha20poly1305` + +|AEAD +|no: authenticated encryption without associated data, an `authenticated_box` +|no: authenticated encryption without associated data, an `authenticated_box` + +|Key +|32 bytes +|32 bytes + +|Nonce +|24 bytes, safe to draw at random +|24 bytes, safe to draw at random + +|Nonce misuse +|not resistant to a repeated nonce; random ones never repeat in practice (link:https://cr.yp.to/snuffle/xsalsa-20081128.pdf[D. J. Bernstein, Extending the Salsa20 nonce, 2008]) +|not resistant to a repeated nonce; random ones never repeat in practice (link:https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha[draft-irtf-cfrg-xchacha, XChaCha20-Poly1305]) + +|Speed, with and without hardware support +|not measured yet +|not measured yet + +|Constant time, by design +|libsodium: yes, additions, XORs and rotations with no table lookup (link:https://cr.yp.to/snuffle/design.pdf[D. J. Bernstein, Salsa20 design: why add-rotate-xor]) +|libsodium: yes (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 (<>) +|libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found; not measured yet on wasip2, wasip3, emscripten (<>) + +|Standards +|none: NaCl's construction (link:https://nacl.cr.yp.to/secretbox.html[NaCl, secret-key authenticated encryption (crypto_secretbox)]) +|none: libsodium's construction (link:https://doc.libsodium.org/secret-key_cryptography/secretbox[libsodium's documentation, secret-key authenticated encryption]) + +|Where it is used +|programs that read or write NaCl's and libsodium's `crypto_secretbox` (link:https://doc.libsodium.org/secret-key_cryptography/secretbox[libsodium's documentation, secret-key authenticated encryption]) +|programs on libsodium's `crypto_secretbox_xchacha20poly1305` (link:https://doc.libsodium.org/secret-key_cryptography/secretbox[libsodium's documentation, secret-key authenticated encryption]) + +|Browsers' WebCrypto +|no (link:https://www.w3.org/TR/WebCryptoAPI/[W3C Web Cryptography API]) +|no (link:https://www.w3.org/TR/WebCryptoAPI/[W3C Web Cryptography API]) + +|Choose it when +|the data must be read by a program on NaCl's or libsodium's `crypto_secretbox`; otherwise `ciphers::xchacha20_poly1305`, which also authenticates associated data +|the peer writes libsodium's `crypto_secretbox_xchacha20poly1305`; otherwise `ciphers::xchacha20_poly1305` +|=== + +.The contracts +[cols="2h,5,5",options="header"] +|=== +|Algorithm |The AEAD contract |The box contract + +|Names +|`aead`, `aead::cipher`, `aead::streaming_cipher`, `aead::seal`, `aead::open` +|`authenticated_box`, `seal`, `open` + +|AEAD +|the contract every AEAD of `ciphers` satisfies: `cipher` checks a one-shot AEAD's members, `streaming_cipher` the incremental ones of AES-GCM, and `aead::seal` and `aead::open` are their free forms +|no: the contract of authenticated encryption in place without associated data, which the secret boxes and the crypto_boxes of `public_key_encryption` satisfy; `seal` and `open` are their free forms + +|Key +|the cipher's +|the box's: a secret box's 32 bytes, or a crypto_box's two X25519 keys + +|Nonce +|the cipher's +|the box's + +|Nonce misuse +|none: a contract, not an algorithm; each cipher's row in `ciphers` says its own +|none: a contract, not an algorithm; each box's row says its own + +|Speed, with and without hardware support +|none: the free forms call the cipher's members +|none: the free forms call the box's members + +|Constant time, by design +|none: the cipher's own +|none: the box's own + +|Constant time, measured +|none: the cipher's own +|none: the box's own + +|Standards +|the interface of link:https://www.rfc-editor.org/rfc/rfc5116[RFC 5116, An Interface and Algorithms for Authenticated Encryption]: a key, a nonce, associated data and a message +|none: NaCl's interface (link:https://nacl.cr.yp.to/secretbox.html[NaCl, secret-key authenticated encryption (crypto_secretbox)]; link:https://nacl.cr.yp.to/box.html[NaCl, public-key authenticated encryption (crypto_box)]) + +|Where it is used +|none: a contract of types; each cipher's row says where it is used +|none: a contract of types; each box's row says where it is used + +|Browsers' WebCrypto +|none: WebCrypto names algorithms, not a contract (link:https://www.w3.org/TR/WebCryptoAPI/[W3C Web Cryptography API]) +|no: WebCrypto has neither box (link:https://www.w3.org/TR/WebCryptoAPI/[W3C Web Cryptography API]) + +|Choose it when +|code written once for every AEAD, or a cipher chosen by a template argument; a secret box takes no associated data and is an `authenticated_box`, sealed by `secret_key_encryption::seal` +|code written once for a secret box and a crypto_box; a crypto_box, of `public_key_encryption`, is sealed by `secret_key_encryption::seal(box, nonce, data)` named in full; an AEAD takes associated data and is an `aead::cipher` +|=== diff --git a/doc/generated/use-cases.adoc b/doc/generated/use-cases.adoc index 27deccd2..a11e11ab 100644 --- a/doc/generated/use-cases.adoc +++ b/doc/generated/use-cases.adoc @@ -12,7 +12,7 @@ |I need to |Use |Backend |Jamfile |Example |Seal or open a record inside an event loop without waiting -|`+async_seal+`, `+async_open+` +|`+secret_key_encryption::aead::async_seal+`, `+async_open+` |the default of AES-GCM |`+/webcpp/crypto//crypto+` + `+/webcpp/crypto//gcm-default+` + @@ -40,10 +40,10 @@ |<> |Check a webhook's or an API's HMAC signature -|`+equal+`, with Boost.Hash2's `+hmac+` +|`+constant_time_equal+`, with Boost.Hash2's `+hmac+` |none |`+/webcpp/crypto//crypto+` -|<> +|<> |Encrypt a database field, a cookie or a token at rest |In `+ciphers+`: `+aes256_gcm+` @@ -80,7 +80,7 @@ |<> |Check a software update or a licence file -|In `+curves::secp256k1+`: `+keypair::sign(crypto::ecdsa_sha256, message)+`, `+public_key::make+`, `+crypto::verify+` +|In `+curves::secp256k1+`: `+keypair::sign(crypto::ecdsa_sha256, message)+`, `+public_key::from_bytes+`, `+crypto::verify+` |libsecp256k1 |`+/webcpp/crypto//crypto+` + `+/third_party//secp256k1+` @@ -102,14 +102,15 @@ |<> |Find who signed a message or a transaction without being sent their key (Ethereum's signatures) -|In `+curves::secp256k1+`: `+keypair::sign(crypto::ecdsa_sha256_recoverable, message)+`, `+recover+` +|In `+curves::secp256k1+`: `+keypair::sign(crypto::ecdsa_keccak256_recoverable, message)+`, `+recover+` |libsecp256k1 |`+/webcpp/crypto//crypto+` + -`+/third_party//secp256k1+` -|<> +`+/third_party//secp256k1+` + +`+/third_party//xkcp+` +|<> |Derive child keys for a watch-only wallet (BIP 32's derivation is a domain library's) -|In `+curves::secp256k1+`: `+seckey_tweak_add+`, `+pubkey_tweak_add+` +|In `+curves::secp256k1+`: `+secret_key_tweak_add+`, `+public_key_tweak_add+` |libsecp256k1 |`+/webcpp/crypto//crypto+` + `+/third_party//secp256k1+` @@ -131,21 +132,21 @@ |<> |Publish one donation address that never shows two payments as related (BIP 352's addresses and transactions are a domain library's) -|In `+curves::secp256k1::silent_payments+`: `+create_outputs+`, `+make_prevouts_summary+`, `+scan_outputs+` +|In `+curves::secp256k1::silent_payments+`: `+create_outputs+`, `+make_previous_outputs_summary+`, `+scan_outputs+` |libsecp256k1 |`+/webcpp/crypto//crypto+` + `+/third_party//secp256k1+` |<> |Require two devices to sign for a wallet, with one ordinary signature on the chain -|In `+curves::secp256k1::musig+`: `+key_aggregate+`, `+nonce_gen+`, `+partial_sign+`, `+partial_signature_aggregate+` +|In `+curves::secp256k1::musig+`: `+key_aggregate+`, `+generate_nonce+`, `+partial_sign+`, `+partial_signature_aggregate+` |libsecp256k1 |`+/webcpp/crypto//crypto+` + `+/third_party//secp256k1+` |<> |Make and keep a wallet's key -|In `+curves::secp256k1+`: `+keypair::make+`, `+keypair::public_key+`, `+public_key::xonly+`, `+public_key::compressed+`; `+aes256_gcm+` at rest +|In `+curves::secp256k1+`: `+keypair::from_secret+`, `+keypair::public_key+`, `+public_key::xonly+`, `+public_key::compressed+`; `+aes256_gcm+` at rest |libsecp256k1, and AES-GCM's default |`+/webcpp/crypto//crypto+` + `+/third_party//secp256k1+` + @@ -167,7 +168,7 @@ |<> |Sign where allocation is restricted to the program's arena -|In `+curves::secp256k1+`: `+keypair::make(secret, resource)+` +|In `+curves::secp256k1+`: `+keypair::from_secret(secret, resource)+` |libsecp256k1 |`+/webcpp/crypto//crypto+` + `+/third_party//secp256k1+` @@ -190,24 +191,24 @@ |Boost.Hash2, not this library: `+boost::hash2::sha2_256+`, `+hmac_sha2_256+` |none |`+/webcpp/crypto//crypto+` brings Boost's headers -|<> +|<> -|Sign and verify with Ed25519 (RFC 8032), or sign a large message in pieces with Ed25519ph -|In `+curves::ed25519+`: `+keypair::make+`, `+keypair::generate+`, `+keypair::sign(crypto::eddsa, message)+`, `+crypto::verify+`; `+ph+` +|Sign and verify with Ed25519 (RFC 8032), or with Ed25519ph a message's SHA-512 or a large message in pieces +|In `+curves::ed25519+`: `+keypair::from_secret+`, `+keypair::generate+`, `+keypair::sign(crypto::eddsa, message)+`, `+keypair::sign(crypto::eddsa_prehashed, crypto::prehashed{digest})+`, `+crypto::verify+`; `+prehashed_signer+` |libsodium |`+/webcpp/crypto//crypto+` + `+/webcpp/crypto//ed25519-default+` |<> |Agree a shared secret with a peer's public key (X25519, RFC 7748), or with the X25519 form of an Ed25519 key -|In `+curves::x25519+`: `+public_key+`, `+agree+`; `+curves::ed25519::to_x25519_public+`, `+curves::ed25519::keypair::x25519_secret+` +|In `+curves::x25519+`: `+keypair::from_secret+`, `+keypair::generate+`, `+public_key::from_bytes+`, `+keypair::agree+`; `+curves::ed25519::keypair::to_x25519+`, `+curves::ed25519::public_key::to_x25519+`, `+crypto::to_x25519+` |libsodium |`+/webcpp/crypto//crypto+` + `+/webcpp/crypto//x25519-default+` |<> |Give a client and a server a key for each direction from each other's public key, as libsodium's `crypto_kx` does -|In `+curves::x25519+`: `+kx_keypair::make+`, `+kx_keypair::generate+`, `+client_session_keys+`, `+server_session_keys+` +|In `+key_exchange+`: `+kx_keypair::from_keypair+`, `+kx_keypair::derive_from_seed+`, `+kx_keypair::generate+`, `+client_session_keys+`, `+server_session_keys+` |libsodium |`+/webcpp/crypto//crypto+` + `+/webcpp/crypto//kx-default+` @@ -223,35 +224,35 @@ |<> |Encrypt messages in a chat app, on the web and natively, each with a random nonce -|In `+ciphers+`: `+xchacha20_poly1305<>+`: `+make+`, `+seal+`, `+open+` +|In `+ciphers+`: `+xchacha20_poly1305<>+`: `+from_key+`, `+seal+`, `+open+` |libsodium |`+/webcpp/crypto//crypto+` + `+/webcpp/crypto//xchacha20_poly1305-default+` |<> |Encrypt a record or a file under one secret key, each with a random nonce, in libsodium's secret-box format -|In `+ciphers+`: `+secretbox<>+`, `+secretbox_xchacha20poly1305<>+`: `+make+`, `+seal+`, `+open+` +|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 |`+/webcpp/crypto//crypto+` + `+/webcpp/crypto//secretbox_xsalsa20poly1305-default+` |<> |Send messages between two people who know each other's public keys, as NaCl's and libsodium's crypto_box -|In `+hybrid+`: `+box::make+`, `+box::seal+`, `+box::open+` +|In `+public_key_encryption+`: `+box::from_keys+`, `+box::seal+`, `+box::open+` |libsodium |`+/webcpp/crypto//crypto+` + `+/webcpp/crypto//box_xsalsa20poly1305-default+` |<> |Let anyone send a message that only the recipient can read, without saying who sent it (anonymous feedback, a drop box) -|In `+hybrid+`: `+sealed_box::seal+`, `+sealed_box::open+` +|In `+public_key_encryption+`: `+sealed_box::seal+`, `+sealed_box::open+` |libsodium |`+/webcpp/crypto//crypto+` + `+/webcpp/crypto//sealed_box-default+` |<> |Share a file with someone known only by a public key, as a file-sharing app does -|`+ciphers::secretbox<>+` for the file under a key drawn for it, `+hybrid::sealed_box::seal+` for that key +|`+secret_key_encryption::secretbox<>+` for the file under a key drawn for it, `+public_key_encryption::sealed_box::seal+` for that key |libsodium |`+/webcpp/crypto//crypto+` + `+/webcpp/crypto//secretbox_xsalsa20poly1305-default+` + @@ -260,7 +261,7 @@ |<> |Make and keep a P-256 key pair, and import a browser's public key (WebCrypto's raw form), as webcpp::trystero's peers do -|In `+curves::p256+`: `+keypair::make+`, `+keypair::generate+`, `+keypair::public_key+`, `+keypair::secret+`, `+public_key::make+` +|In `+curves::p256+`: `+keypair::from_secret+`, `+keypair::generate+`, `+keypair::public_key+`, `+keypair::secret+`, `+public_key::from_bytes+` |BearSSL |`+/webcpp/crypto//crypto+` + `+/webcpp/crypto//p256-default+` diff --git a/doc/hybrid.adoc b/doc/hybrid.adoc deleted file mode 100644 index 73ee9b8a..00000000 --- a/doc/hybrid.adoc +++ /dev/null @@ -1,141 +0,0 @@ -// Copyright (c) 2026 WebCpp.org -// -// Distributed under the Boost Software License, Version 1.0. (See -// accompanying file LICENSE_1_0.txt or copy at -// https://www.boost.org/LICENSE_1_0.txt) - -[#crypto-hybrid] -== Hybrid encryption: `webcpp::crypto::hybrid` - -*Hybrid encryption* joins a key agreement and a cipher: the agreement, on -public keys, gives a secret key, and a fast cipher encrypts the data under it -(link:https://en.wikipedia.org/wiki/Hybrid_cryptosystem[Wikipedia]). A chat app -encrypts a message to a contact whose public key it knows; a feedback form -encrypts a report to a key whose owner alone may read it. The namespace -`webcpp::crypto::hybrid` holds NaCl's and libsodium's constructions in this -version: the box, between two key pairs, and the sealed box, from anyone to -a public key. Both agree with X25519 (<>) and seal with -XSalsa20-Poly1305, the secret box's cipher (<>), or, for -`box_xchacha20poly1305`, XChaCha20-Poly1305, on libsodium, their default on -every target. - -*Which one.* A box when the two parties know each other's public keys and the -recipient must know the message came from the other: a chat between two -contacts. A sealed box when anyone may write and the recipient alone reads: a -feedback form, a drop box, a file key sent to a recipient known by a public key -(<>). `box_xchacha20poly1305` only when the peer uses -libsodium's XChaCha20 form; otherwise `box`, NaCl's format, which libsodium -and its bindings in every language read. Without either, a program that -encrypts to a public key by hand, an agreement and a cipher of its own -choosing, risks the mistakes these constructions settle: a shared secret used -as a key, a nonce reused, a weak public key accepted. - -include::generated/namespace-hybrid.adoc[] - -[#crypto-box] -=== Boxes - -`hybrid::box`, in ``, is NaCl's `crypto_box` -(link:https://nacl.cr.yp.to/box.html[NaCl]; -link:https://doc.libsodium.org/public-key_cryptography/authenticated_encryption[libsodium's documentation]). -`box::make(secret_key, peer_public_key)` agrees a key from the own X25519 -secret key and the peer's public key, once for the pair (libsodium's -`beforenm`); the box then works in place, as an AEAD without additional data: -`seal(iv_bytes, data_bytes)` encrypts and returns the 16-byte tag, and -`open(iv_bytes, data_bytes, tag_bytes)` checks it and decrypts, zeroing the -data when it does not match. Alice's box made from her secret key and Bob's -public key, and Bob's made from his secret key and Alice's public key, hold -the same key: what one seals the other opens. `box_xchacha20poly1305` is -libsodium's `crypto_box_curve25519xchacha20poly1305`, the same with -XChaCha20-Poly1305. A box is moved and not copied, and wipes its key when -moved from and destroyed. - -A peer's public key of small order makes the shared secret one an attacker -knows: `make` refuses it with `weak_public_key`, as libsodium's `beforenm` -does. - -include::generated/backends-box.adoc[] - -include::generated/backends-box_xchacha20poly1305.adoc[] - -[cols="3,1"] -|=== -|Condition |Error - -|`make`: a secret key of another size than 32 bytes |`invalid_key_size` -|`make`: a peer key of another size than 32 bytes |`invalid_public_key` -|`make`: a peer key of small order |`weak_public_key` -|`seal`, `open`: the object was moved from |`invalid_state` -|a nonce of another size than 24 bytes |`invalid_iv_size` -|`open`: a tag of another size than 16 |`invalid_tag_size` -|a message longer than `max_message_size` |`message_too_long` -|`open`: the tag does not match |`authentication_failed` -|the backend fails where it should not |`backend_failure` -|=== - -*Example.* Alice and Bob, each with an X25519 key pair, make their boxes from -the own secret key and the other's public key; what one seals the other opens, -and Mallory, who knows Alice's public key but not Bob's secret key, cannot: - -[source,cpp] ----- -include::{examples}/box_messages.cpp[tag=boxes,indent=0] ----- - -[source,cpp] ----- -include::{examples}/box_messages.cpp[tag=exchange] ----- - -[listing] ----- -include::{examples}/box_messages.expected[] ----- - -The whole program: - -[source,cpp] ----- -include::{examples}/box_messages.cpp[tag=program] ----- - -*Pitfalls.* - -* A box proves that one of the two key pairs wrote a message, not which one: -a protocol that needs to know says so inside the message, or signs it. -* A nonce is never repeated for one pair of keys, in either direction: draw -24 bytes at random for every message. - -[#crypto-sealed-box] -=== Sealed boxes - -`hybrid::sealed_box`, in ``, is -libsodium's sealed box, `crypto_box_seal` -(link:https://doc.libsodium.org/public-key_cryptography/sealed_boxes[libsodium's documentation]): -anyone who knows a public key can seal a message to it, and only the key pair -opens it. `seal(recipient_public_key, message, out)` writes to `out`, of the -message's size plus `overhead`, 48 bytes, a key pair libsodium draws for the -message, its public key, the tag and the ciphertext, and wipes the drawn -secret key; the nonce comes from the two public keys. `open(recipient_public_key, -recipient_secret_key, sealed, out)` writes the message to `out`, of the sealed -box's size less 48 bytes, and zeroes `out` when the box does not open: sealed to -another key pair, or changed. The sizes are checked first -(`invalid_input_size`), then the keys (`invalid_public_key`, -`invalid_key_size`). - -include::generated/backends-sealed_box.adoc[] - -*Pitfalls.* - -* A sealed box is anonymous: the recipient cannot tell who sealed it, nor -whether an attacker did. Where the sender matters, use a box or a signature. -* The sender cannot open what it sealed: it keeps its own copy of the -message if it needs one. - -*Example.* A file-sharing app seals each file's key to its recipient: -<>. - -Parts of this chapter, the boxes' and the sealed boxes' descriptions and -pitfalls, are adapted from libsodium's documentation -(link:https://github.com/jedisct1/libsodium-doc/tree/6d1ea27b79b853b2a04f09ae9e1a8231c90e3b56[jedisct1/libsodium-doc] -at `6d1ea27`, ISC, `LICENSE-LIBSODIUM-DOC.txt`). diff --git a/doc/jamfile.adoc b/doc/jamfile.adoc index ac9548e0..fc64cf31 100644 --- a/doc/jamfile.adoc +++ b/doc/jamfile.adoc @@ -80,8 +80,9 @@ A native program that sends OpenSSL's allocations to its own resource `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE` and `/webcpp/crypto//openssl` together, in the requirements of its project, not of one target. Every target of the program then gets both: its own libraries, and a tool that only calls -`random_device` or `equal`, which would otherwise have the define without -OpenSSL. The fixture `memory_option` builds and runs this Jamfile natively: +`random_device` or `constant_time_equal`, which would otherwise have the define +without OpenSSL. The fixture `memory_option` builds and runs this Jamfile +natively: [listing] ---- diff --git a/doc/kx.adoc b/doc/kx.adoc index 9cb583b0..b5fa665a 100644 --- a/doc/kx.adoc +++ b/doc/kx.adoc @@ -4,16 +4,30 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) +[#crypto-key-exchange] +== Key exchange: `webcpp::crypto::key_exchange` + +*Key exchange* gives two parties who swapped public keys the keys a cipher +needs, without sending any of them. The namespace +`webcpp::crypto::key_exchange` holds libsodium's `crypto_kx` in this version: a +construction over X25519 (<>) and BLAKE2b rather than a curve +primitive, so it is not in `curves`, and named by the problem it solves. + +include::generated/namespace-key_exchange.adoc[] + [#crypto-kx] -=== Key exchange: crypto_kx +=== crypto_kx -`` is libsodium's key exchange, +`` is libsodium's key exchange, `crypto_kx`, on libsodium (`/third_party//sodium`, or `/webcpp/crypto//kx-default`, which links it on every target), in the namespace -`webcpp::crypto::curves::x25519`. It turns X25519 (<>) into what +`webcpp::crypto::key_exchange`. It turns X25519 (<>) into what a program that talks to one peer needs: two keys ready for a cipher, one for each direction. A chat app's client and its server each hold a -`kx_keypair`; they send each other their public keys; the client calls +`kx_keypair`, which holds an X25519 key pair (`curves::x25519::basic_keypair`, +given back by `keypair()`); they send each other their public keys, each an +`x25519::public_key` (`public_key()`, or `x25519::public_key::from_bytes` of +the 32 bytes received); the client calls `client_session_keys(server_public_key)` and the server `server_session_keys(client_public_key)`. Each gets a `session_keys`, a `receive` and a `transmit` key, both `secret<32>` that wipe themselves; the @@ -29,11 +43,21 @@ names X25519 and a KDF of its own, as TLS 1.3's key schedule does (link:https://www.rfc-editor.org/rfc/rfc8446#section-7.1[RFC 8446, section 7.1]), uses `agree` instead. -`kx_keypair<>::generate()` draws the key pair's 32-byte seed with -`random_device`; `kx_keypair<>::make(seed)` makes the same key pair from the -same seed, as a program that keeps its seed does. A peer's public key of low -order makes the X25519 secret all zero, whatever the secret key: both -functions refuse it with `weak_public_key`, as libsodium does (design D8). +A key pair is made three ways. `kx_keypair<>::generate()` draws a 32-byte +seed with `random_device`. `kx_keypair<>::derive_from_seed(seed)` is +libsodium's `crypto_kx_seed_keypair`: it hashes the seed, its secret key +BLAKE2b-256 of the 32 bytes, and makes the same key pair from the same seed, +as libsodium does in any language: a program that keeps its seed calls it. +`kx_keypair<>::from_keypair(key_pair)` takes +an X25519 key pair (<>) as it is, its secret key used with no +hash, moved in: the key pair a program already holds, made by +`x25519::keypair::from_secret(bytes)` from a secret key it keeps. The same 32 +bytes therefore give two key pairs: `derive_from_seed(bytes)` hashes them, +`from_keypair(*x25519::keypair::from_secret(bytes))` takes them as the secret +key, and their public keys differ. A key pair moved from is refused with +`invalid_state`, by `from_keypair` too. A peer's public key of low order +makes the X25519 secret all zero, whatever the secret key: both functions +refuse it with `weak_public_key`, as libsodium does (design D8). include::generated/backends-kx_keypair.adoc[] diff --git a/doc/llms.txt b/doc/llms.txt index fc07f555..413acc60 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -1,6 +1,6 @@ # webcpp::crypto -> Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA and recoverable signatures, ECDH, tweaks, ElligatorSwift, MuSig2, silent payments), Ed25519 and Ed25519ph (RFC 8032), X25519 (RFC 7748), their keys in SPKI, PKCS#8 (RFC 8410) and PEM, P-256 key pairs, ECDSA and ECDH on BearSSL, libsodium's crypto_kx, the ChaCha20-Poly1305 AEADs, libsodium's secret boxes, boxes and sealed boxes, a random_device on the system's generator and a constant-time equal, each over a widely used, reviewed C library (BearSSL, OpenSSL, ctaes, libsecp256k1, libsodium) that the program names in its Jamfile. Hashing and HMAC are Boost.Hash2's; HKDF and password hashing are webcpp::hash's. Every failure is a boost::system::result value. Protocols (Bitcoin, Ethereum, Nostr) belong to domain libraries built on these primitives. +> Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA and recoverable signatures, ECDH, tweaks, ElligatorSwift, MuSig2, silent payments), Ed25519 and Ed25519ph (RFC 8032), X25519 (RFC 7748), their keys in SPKI, PKCS#8 (RFC 8410) and PEM, P-256 key pairs, ECDSA and ECDH on BearSSL, libsodium's crypto_kx, the ChaCha20-Poly1305 AEADs, libsodium's secret boxes, boxes and sealed boxes, a random_device on the system's generator, a constant_time_equal and an erase_secret whose stores the optimiser keeps, each over a widely used, reviewed C library (BearSSL, OpenSSL, ctaes, libsecp256k1, libsodium) that the program names in its Jamfile. Hashing and HMAC are Boost.Hash2's; HKDF and password hashing are webcpp::hash's. Every failure is a boost::system::result value. Protocols (Bitcoin, Ethereum, Nostr) belong to domain libraries built on these primitives. Generated by doc/tables/generate.py with the page's tables. Page: https://webcpporg.github.io/libs/crypto/ @@ -12,25 +12,29 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - min: The smallest value `operator()` gives. - max: The largest value `operator()` gives. - entropy: The entropy of a value, in bits: every bit is the system's. -- [async_make, async_seal, async_open](https://webcpporg.github.io/libs/crypto/#crypto-async): AES-GCM's asynchronous make, seal and open, 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. Use it to: seal or open a record inside an event loop without waiting. - - async_make: Makes an AES-GCM object, an Ed25519 key pair or a P-256 key pair from its key bytes, asynchronously: `Algorithm::make(key_bytes)` run when the operation is initiated, its result posted to `executor`. - - async_seal: Seals a message in place, asynchronously: `aead.seal` run when the operation is initiated, its result posted to `executor`. - - async_open: Opens a message in place, asynchronously: `aead.open` run when the operation is initiated, its result posted to `executor`. -- [async_make, async_generate, async_sign, async_verify](https://webcpporg.github.io/libs/crypto/#crypto-async): Ed25519's asynchronous make, generate, sign and verify with `crypto::eddsa`, 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. - - async_make: Makes an AES-GCM object, an Ed25519 key pair or a P-256 key pair from its key bytes, asynchronously: `Algorithm::make(key_bytes)` run when the operation is initiated, its result posted to `executor`. - - async_generate: Makes an Ed25519 or a P-256 key pair from a fresh seed or scalar, asynchronously: `Keypair::generate()` run when the operation is initiated (the system's generator is drawn from then), its result posted to `executor`. - - async_sign: Signs with an Ed25519 or a P-256 key pair, asynchronously: `key_pair.sign(scheme, input)` run when the operation is initiated, its result posted to `executor`. - - async_verify: Verifies an Ed25519 signature (RFC 8032's pure Ed25519), asynchronously, strictly: `crypto::verify(crypto::eddsa, signature, message, public_key)` run when the operation is initiated, its result posted to `executor`. -- [async_agree](https://webcpporg.github.io/libs/crypto/#crypto-async): X25519's asynchronous agree, 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. - - async_agree: Agrees an X25519 shared secret, asynchronously: `curves::x25519::agree` run when the operation is initiated, its result posted to `executor`. -- [async_make, async_generate, async_sign, async_verify, async_agree](https://webcpporg.github.io/libs/crypto/#crypto-async): P-256's asynchronous make, generate, ECDSA sign and verify with `crypto::ecdsa_sha256`, of a message hashed with SHA-256 or `crypto::prehashed{digest}`, and ECDH's raw x, 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. - - async_make: Makes an AES-GCM object, an Ed25519 key pair or a P-256 key pair from its key bytes, asynchronously: `Algorithm::make(key_bytes)` run when the operation is initiated, its result posted to `executor`. - - async_generate: Makes an Ed25519 or a P-256 key pair from a fresh seed or scalar, asynchronously: `Keypair::generate()` run when the operation is initiated (the system's generator is drawn from then), its result posted to `executor`. - - async_sign: Signs with an Ed25519 or a P-256 key pair, asynchronously: `key_pair.sign(scheme, input)` run when the operation is initiated, its result posted to `executor`. - - async_verify: Verifies a P-256 ECDSA signature over SHA-256, asynchronously: `crypto::verify(crypto::ecdsa_sha256, signature, input, public_key)` run when the operation is initiated, its result posted to `executor`; the message is hashed with SHA-256, as WebCrypto's ECDSA with SHA-256 verifies, or `crypto::prehashed{digest}` gives its digest. - - async_agree: Agrees a P-256 shared secret, ECDH's raw x coordinate, asynchronously: `key_pair.agree(peer_public_key)` run when the operation is initiated, its result posted to `executor`, as WebCrypto's `deriveBits` with ECDH on P-256 gives its 256 bits. -- [equal](https://webcpporg.github.io/libs/crypto/#crypto-equal): Compares two tags or MACs in constant time. Header . Backends: no backend (/webcpp/crypto//crypto) on native, wasip2, wasip3, emscripten. Use it to: check a webhook's or an API's HMAC signature. - - equal: Whether two byte sequences are equal, in a time that does not depend on their contents. +- [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_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::eddsa`, and on a native backend with `crypto::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. + - async_from_secret: Makes an Ed25519, an X25519 or a P-256 key pair from its secret bytes, asynchronously: `Keypair::from_secret(secret_bytes)` run when the operation is initiated, its result posted to `completion_executor`. + - async_generate: Makes an Ed25519, an X25519 or a P-256 key pair from a fresh secret, asynchronously: `Keypair::generate()` run when the operation is initiated (the system's generator is drawn from then), its result posted to `completion_executor`. + - async_sign: 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 posted to `completion_executor`. + - async_verify: Verifies an Ed25519 signature (RFC 8032's pure Ed25519), asynchronously, strictly: `crypto::verify(crypto::eddsa, signature_value, message_bytes, public_key)` run when the operation is initiated, its result posted to `completion_executor`. +- [async_from_secret, async_generate, async_agree](https://webcpporg.github.io/libs/crypto/#crypto-async): X25519's asynchronous from_secret, generate and agree, of a key pair and a peer's `curves::x25519::public_key`, 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. + - async_from_secret: Makes an Ed25519, an X25519 or a P-256 key pair from its secret bytes, asynchronously: `Keypair::from_secret(secret_bytes)` run when the operation is initiated, its result posted to `completion_executor`. + - async_generate: Makes an Ed25519, an X25519 or a P-256 key pair from a fresh secret, asynchronously: `Keypair::generate()` run when the operation is initiated (the system's generator is drawn from then), its result posted to `completion_executor`. + - async_agree: Agrees a shared secret, asynchronously: `key_pair.agree(peer_public_key)` run when the operation is initiated, its result posted to `completion_executor`: X25519's (RFC 7748), or P-256's ECDH raw x coordinate, as WebCrypto's `deriveBits` with ECDH on P-256 gives its 256 bits. +- [async_from_secret, async_generate, async_sign, async_verify, async_agree](https://webcpporg.github.io/libs/crypto/#crypto-async): P-256's asynchronous from_secret, generate, ECDSA sign and verify with `crypto::ecdsa_sha256`, of a message hashed with SHA-256 or `crypto::prehashed{digest}`, and ECDH's raw x, 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. + - async_from_secret: Makes an Ed25519, an X25519 or a P-256 key pair from its secret bytes, asynchronously: `Keypair::from_secret(secret_bytes)` run when the operation is initiated, its result posted to `completion_executor`. + - async_generate: Makes an Ed25519, an X25519 or a P-256 key pair from a fresh secret, asynchronously: `Keypair::generate()` run when the operation is initiated (the system's generator is drawn from then), its result posted to `completion_executor`. + - async_sign: 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 posted to `completion_executor`. + - async_verify: Verifies a P-256 ECDSA signature over SHA-256, asynchronously: `crypto::verify(crypto::ecdsa_sha256, signature_value, signing_input, public_key)` run when the operation is initiated, its result posted to `completion_executor`; the message is hashed with SHA-256, as WebCrypto's ECDSA with SHA-256 verifies, or `crypto::prehashed{digest}` gives its digest. + - async_agree: Agrees a shared secret, asynchronously: `key_pair.agree(peer_public_key)` run when the operation is initiated, its result posted to `completion_executor`: X25519's (RFC 7748), or P-256's ECDH raw x coordinate, as WebCrypto's `deriveBits` with ECDH on P-256 gives its 256 bits. +- [constant_time_equal](https://webcpporg.github.io/libs/crypto/#crypto-constant-time-equal): Compares two tags or MACs in constant time. Header . Backends: no backend (/webcpp/crypto//crypto) on native, wasip2, wasip3, emscripten. Use it to: check a webhook's or an API's HMAC signature. + - constant_time_equal: Whether two byte sequences are equal, in a time that does not depend on their contents. +- [erase_secret](https://webcpporg.github.io/libs/crypto/#crypto-erase-secret): Zeroes a buffer the program owns, a password, a key or a plaintext, with stores the optimiser keeps. Header . Backends: no backend (/webcpp/crypto//crypto) on native, wasip2, wasip3, emscripten. + - erase_secret: Zeroes every byte of a buffer the program owns, with stores the optimiser keeps. - [error](https://webcpporg.github.io/libs/crypto/#crypto-errors): Every failure's value, fixed and never reused, in the category webcpp.crypto. Header . Backends: no backend (/webcpp/crypto//crypto) on native, wasip2, wasip3, emscripten. Use it to: tell a forged message from a malformed one. - error_category: The category of every error. - make_error_code: Makes the `error_code` of an error, as its implicit conversion does. @@ -46,60 +50,78 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp ## webcpp::crypto::ciphers - [ciphers::aes128, aes192, aes256](https://webcpporg.github.io/libs/crypto/#crypto-block): The AES block cipher on whole 16-byte blocks: a building block, not encryption of data. Header , . Backends: OpenSSL (/webcpp/crypto//openssl) on native, wasip2, wasip3; ctaes (/third_party//ctaes) on native, wasip2, wasip3, emscripten. Default: OpenSSL on native, Clang and GCC; OpenSSL on native, MSVC; ctaes on wasip2, wasip3, emscripten. Use it to: turn a sequential id into an opaque reference. - - make: Expands a key. + - from_key: Expands a key. - encrypt: Encrypts whole blocks in place. - decrypt: Decrypts whole blocks in place. - [ciphers::gcm, aes128_gcm, aes256_gcm](https://webcpporg.github.io/libs/crypto/#crypto-gcm): AES-GCM, authenticated encryption in place with an incremental seal and an incremental open in two passes. Header , . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten; OpenSSL (/webcpp/crypto//openssl) on native, wasip2, wasip3. Default: OpenSSL on native, Clang and GCC; OpenSSL on native, MSVC; BearSSL on wasip2, wasip3; BearSSL on emscripten. Use it to: encrypt a database field, a cookie or a token at rest. - - make: Expands a key into a new object. - - async_make: Expands a key into a new object, asynchronously: `make` run when the operation is initiated, its result posted to `executor`; the member form of `crypto::async_make(executor, key_bytes, token)`, which calls it. + - from_key: Expands a key into a new object. + - async_from_key: Expands a key into a new object, 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. - seal: Seals a message in place: `data_bytes` holds the plaintext before and the ciphertext after. - - async_seal: Seals a message in place, asynchronously: `seal` run when the operation is initiated, its result posted to `executor`; the member form of `crypto::async_seal(executor, aead, iv_bytes, additional_data_bytes, data_bytes, token)`, which calls it. + - 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, aead, 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 `executor`; the member form of `crypto::async_open`, which calls it with the executor and the object before this function's arguments. - - begin_seal: Begins an incremental seal: the IV and the whole additional data first, both read before this returns. + - 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. + - begin_seal: Begins an incremental seal: the nonce and the whole associated data first, both read before this returns. - update: Encrypts the next piece of the message in place. - result: Ends the message with its tag. - - begin_open: Begins an incremental open: the IV and the whole additional data first, both read before this returns, the IV kept for the second pass. + - begin_open: Begins an incremental open: the nonce and the whole associated data first, both read before this returns, the nonce kept for the second pass. - authenticate: The first pass: authenticates the next piece of the ciphertext, which is read and never written. - verify: Ends the first pass: checks the tag of the pieces authenticated, and on a match begins the second pass. - decrypt: The second pass: decrypts the next piece in place, the bytes `authenticate` read in the same place of the message. - end_open: Ends the open, whose message's state is wiped. - [ciphers::chacha20_poly1305](https://webcpporg.github.io/libs/crypto/#crypto-chacha): RFC 8439's ChaCha20-Poly1305, authenticated encryption in place with a 12-byte nonce. Header , . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten; OpenSSL (/webcpp/crypto//openssl) on native, wasip2, wasip3; libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. - - make: Makes an object under a key. + - 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. - seal: Seals a message in place: `data_bytes` holds the plaintext before and the ciphertext after. + - 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_poly1305_original](https://webcpporg.github.io/libs/crypto/#crypto-chacha): The original ChaCha20-Poly1305, authenticated encryption in place with an 8-byte nonce a counter numbers. Header , . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. - - make: Makes an object under a key. + - 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. - seal: Seals a message in place: `data_bytes` holds the plaintext before and the ciphertext after. + - 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::xchacha20_poly1305](https://webcpporg.github.io/libs/crypto/#crypto-chacha): XChaCha20-Poly1305, authenticated encryption in place with a 24-byte nonce safe to draw at random. Header , . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. Use it to: encrypt messages in a chat app, on the web and natively, each with a random nonce. - - make: Makes an object under a key. + - 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. - seal: Seals a message in place: `data_bytes` holds the plaintext before and the ciphertext after. + - 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. -- [ciphers::secretbox](https://webcpporg.github.io/libs/crypto/#crypto-secretbox): NaCl's and libsodium's `crypto_secretbox`, XSalsa20-Poly1305: authenticated encryption in place under a 32-byte key, with a 24-byte nonce safe to draw at random and no additional data. Header , . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. Use it to: encrypt a record or a file under one secret key, each with a random nonce, in libsodium's secret-box format. - - make: Makes an object under a key. + - 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. + +## webcpp::crypto::secret_key_encryption + +- [secret_key_encryption::secretbox](https://webcpporg.github.io/libs/crypto/#crypto-secretbox): NaCl's and libsodium's `crypto_secretbox`, XSalsa20-Poly1305: authenticated encryption in place under a 32-byte key, with a 24-byte nonce safe to draw at random and no associated data, an `authenticated_box` whose free forms are `secret_key_encryption::seal` and `open`. Header , . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. Use it to: encrypt a record or a file under one secret key, each with a random nonce, in libsodium's secret-box format. + - from_key: Makes a box under a key. + - async_from_key: Makes a box 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. - seal: Seals a message in place: `data_bytes` holds the plaintext before and the ciphertext after. + - 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::async_seal(executor, box, nonce_bytes, data_bytes, token)`, which calls it. - open: Opens a message in place: `data_bytes` holds the ciphertext before and the plaintext after. -- [ciphers::secretbox_xchacha20poly1305](https://webcpporg.github.io/libs/crypto/#crypto-secretbox): libsodium's `crypto_secretbox_xchacha20poly1305`: the secret box with XChaCha20 in place of XSalsa20. Header , . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. Use it to: encrypt a record or a file under one secret key, each with a random nonce, in libsodium's secret-box format. - - make: Makes an object under a key. + - 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::async_open(executor, box, nonce_bytes, data_bytes, tag_bytes, token)`, which calls it. +- [secret_key_encryption::secretbox_xchacha20poly1305](https://webcpporg.github.io/libs/crypto/#crypto-secretbox): libsodium's `crypto_secretbox_xchacha20poly1305`: the secret box with XChaCha20 in place of XSalsa20. Header , . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. Use it to: encrypt a record or a file under one secret key, each with a random nonce, in libsodium's secret-box format. + - from_key: Makes a box under a key. + - async_from_key: Makes a box 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. - seal: Seals a message in place: `data_bytes` holds the plaintext before and the ciphertext after. + - 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::async_seal(executor, box, nonce_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::async_open(executor, box, nonce_bytes, data_bytes, tag_bytes, token)`, which calls it. ## webcpp::crypto::curves -- [curves::secp256k1::keypair](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1): A secp256k1 key pair: made from its 32-byte secret key, which `secret()` gives back, or drawn from `random_device`; its public key, a `curves::secp256k1::public_key`; `sign(crypto::schnorr, message)` (BIP 340, its auxiliary randomness drawn or given), `sign(crypto::ecdsa_sha256, input)` (hedged too) and `sign(crypto::ecdsa_sha256_recoverable, input)`, the input a message hashed inside or `crypto::prehashed{digest}`; ECDH in three forms, `agree` (the shared x), `agree_hashed` and `agree_point`, each with a peer's `public_key`; and the x-only tweak. Header . Backends: libsecp256k1 (/third_party//secp256k1) on native, wasip2, wasip3, emscripten. Default: libsecp256k1 on native, wasip2, wasip3, emscripten. - - make: Makes a key pair from a secret key, as a program that kept `secret()` loads it again. +- [curves::secp256k1::keypair](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1): A secp256k1 key pair: made from its 32-byte secret key, which `secret()` gives back, or drawn from `random_device`; its public key, a `curves::secp256k1::public_key`; `sign(crypto::schnorr, message)` (BIP 340, its auxiliary randomness drawn or given), `sign(crypto::ecdsa_sha256, input)` (hedged too), `sign(crypto::ecdsa_sha256_recoverable, input)` and Ethereum's `sign(crypto::ecdsa_keccak256_recoverable, input)`, the input a message hashed inside (with Keccak-256 for Ethereum's, which needs `/third_party//xkcp`) or `crypto::prehashed{digest}`; ECDH in three forms, `agree` (the shared x), `agree_hashed` and `agree_point`, each with a peer's `public_key`; and the x-only tweak. Header . Backends: libsecp256k1 (/third_party//secp256k1) on native, wasip2, wasip3, emscripten. Default: libsecp256k1 on native, wasip2, wasip3, emscripten. + - from_secret: Makes a key pair from a secret key, as a program that kept `secret()` loads it again. - generate: Generates a key pair from the system's source: draws a 32-byte secret key from the system's generator and makes the key pair from it, drawing again when the 32 bytes are not a secret key (zero or not below the group order, which happens with a probability near 2^-128), at most `max_draws` (four) draws in all. - public_key: The public key, which `crypto::verify` takes, and `agree` as a peer's; its `compressed()`, `uncompressed()` and `xonly()` give its bytes. - - secret: The secret key (`secp256k1_keypair_sec`), for a program that keeps the key pair and makes it again with `make`, or exports it. - - sign: Signs with one of secp256k1's three schemes: ECDSA over SHA-256 with RFC 6979's nonce, low S, as libsecp256k1 signs; the same with the recovery id; or BIP340's Schnorr, with 32 bytes of auxiliary randomness drawn from the system's generator, as BIP340 recommends. + - secret: The secret key (`secp256k1_keypair_sec`), for a program that keeps the key pair and makes it again with `from_secret`, or exports it. + - sign: Signs with one of secp256k1's four schemes: ECDSA over SHA-256 with RFC 6979's nonce, low S, as libsecp256k1 signs; the same with the recovery id; Ethereum's recoverable ECDSA, the same over Keccak-256 (EIP-2's low S); or BIP340's Schnorr, with 32 bytes of auxiliary randomness drawn from the system's generator, as BIP340 recommends. - agree: ECDH with a peer's public key: the shared point's x coordinate, unhashed, as P-256's `agree` and WebCrypto's `deriveBits` give it, and what Wycheproof's ECDH vectors, Nostr's NIP-44 and other protocols that hash it themselves take. - agree_hashed: ECDH with a peer's public key, hashed as libsecp256k1 hashes it by default: the SHA-256 of the compressed shared point. - agree_point: ECDH with a peer's public key: the shared point itself, SEC1 uncompressed (0x04, x, y). - tweak_xonly: Tweaks this key pair in place by a 32-byte tweak t: its x-only public key P becomes P + t*G, and its secret key follows (`secp256k1_keypair_xonly_tweak_add`). -- [crypto::verify, curves::secp256k1::recover](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1): Verifies a BIP 340 signature against a `curves::secp256k1::public_key` or its 32-byte x-only form, `crypto::verify(crypto::schnorr, signature, message, key)`, or an ECDSA one against a `curves::secp256k1::public_key`, `crypto::verify(crypto::ecdsa_sha256, signature, input, public_key)`, refusing a high S; `recover(crypto::ecdsa_sha256_recoverable, signature, input)` gives the signer's key. Header . Backends: libsecp256k1 (/third_party//secp256k1) on native, wasip2, wasip3, emscripten. Default: libsecp256k1 on native, wasip2, wasip3, emscripten. +- [crypto::verify, curves::secp256k1::recover](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1): Verifies a BIP 340 signature against a `curves::secp256k1::public_key` or its 32-byte x-only form, `crypto::verify(crypto::schnorr, signature, message, key)`, or an ECDSA one against a `curves::secp256k1::public_key`, `crypto::verify(crypto::ecdsa_sha256, signature, input, public_key)`, refusing a high S; `recover(crypto::ecdsa_sha256_recoverable, signature, input)` and `recover(crypto::ecdsa_keccak256_recoverable, signature, input)` give the signer's key. Header . Backends: libsecp256k1 (/third_party//secp256k1) on native, wasip2, wasip3, emscripten. Default: libsecp256k1 on native, wasip2, wasip3, emscripten. - verify: Verifies an ECDSA signature over SHA-256 with a secp256k1 public key, with libsecp256k1's static context, which allocates nothing, after its self-test. - - recover: The public key that made a recoverable signature (`secp256k1_ecdsa_recover`), as Ethereum identifies a transaction's signer: the same inputs as `sign(crypto::ecdsa_sha256_recoverable, signing_input)`. + - recover: The public key that made a recoverable signature (`secp256k1_ecdsa_recover`) of ECDSA over SHA-256: the same inputs as `sign(crypto::ecdsa_sha256_recoverable, signing_input)`. - [curves::secp256k1::to_der, from_der, normalize_low_s, is_low_s](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1): ECDSA's strict DER encoding, and low S as two functions, `normalize_low_s` and `is_low_s`. Header . Backends: libsecp256k1 (/third_party//secp256k1) on native, wasip2, wasip3, emscripten. Default: libsecp256k1 on native, wasip2, wasip3, emscripten. - to_der: Encodes a compact ECDSA signature as strict DER (BIP66), with libsecp256k1's own encoder. - from_der: Decodes a strict DER ECDSA signature (BIP66, `secp256k1_ecdsa_signature_parse_der`) to its compact form. @@ -107,34 +129,43 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - is_low_s: Whether a compact ECDSA signature is in its low-S form, the only form `crypto::verify` accepts on secp256k1, as a protocol checks what it relays (Bitcoin's standardness); `sign` gives the low form. - [curves::secp256k1::tweak_xonly](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1): Tweaks an x-only public key by a 32-byte tweak a protocol computes. Header . Backends: libsecp256k1 (/third_party//secp256k1) on native, wasip2, wasip3, emscripten. Default: libsecp256k1 on native, wasip2, wasip3, emscripten. - tweak_xonly: Tweaks an x-only public key by a 32-byte tweak t: P + t*G, with libsecp256k1's static context, which allocates nothing (`secp256k1_xonly_pubkey_tweak_add`). -- [curves::ed25519::keypair](https://webcpporg.github.io/libs/crypto/#crypto-ed25519): An Ed25519 key pair (RFC 8032): made from a 32-byte seed, which `secret()` gives back, or drawn from `random_device`; its public key, a `curves::ed25519::public_key`; 64-byte signatures of a message with `sign(crypto::eddsa, message)`; and its X25519 secret key. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. Use it to: sign and verify with Ed25519 (RFC 8032), or sign a large message in pieces with Ed25519ph. - - make: Makes a key pair from a seed, RFC 8032's secret key. +- [curves::ed25519::keypair](https://webcpporg.github.io/libs/crypto/#crypto-ed25519): An Ed25519 key pair (RFC 8032): made from a 32-byte seed, which `secret()` gives back, or drawn from `random_device`; its public key, a `curves::ed25519::public_key`; 64-byte signatures of a message with `sign(crypto::eddsa, message)`, and of a message's SHA-512 with `sign(crypto::eddsa_prehashed, crypto::prehashed{digest})` (Ed25519ph, native backends); and its X25519 key pair, `to_x25519()`. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. Use it to: sign and verify with Ed25519 (RFC 8032), or with Ed25519ph a message's SHA-512 or a large message in pieces. + - from_secret: Makes a key pair from a seed, RFC 8032's secret key. - generate: Makes a key pair from a fresh seed, drawn from the system's generator. - - async_make: Makes a key pair from a seed, asynchronously: `make` run when the operation is initiated, its result posted to `completion_executor`; the member form of `crypto::async_make(completion_executor, seed_bytes, completion_token)`, which calls it. + - async_from_secret: Makes a key pair from a seed, asynchronously: `from_secret` run when the operation is initiated, its result posted to `completion_executor`; the member form of the free `crypto::async_from_secret`, with the same arguments, which calls it. - async_generate: Makes a key pair from a fresh seed, asynchronously: `generate` run when the operation is initiated, its result posted to `completion_executor`; the member form of `crypto::async_generate(completion_executor, completion_token)`, which calls it. - public_key: The public key, which `crypto::verify` takes. - - secret: The seed, RFC 8032's secret key, for a program that keeps the key pair and makes it again with `make`, or exports it (PKCS#8 holds the seed alone). - - sign: Signs a message with Ed25519 (RFC 8032's pure Ed25519: the message itself, of any length, empty included, is signed; no digest is taken). - - async_sign: Signs a message with Ed25519, asynchronously: `sign` run when the operation is initiated, its result posted to `completion_executor`; the member form of `crypto::async_sign(completion_executor, key_pair, signing_scheme, message_input, completion_token)`, which calls it. - - x25519_secret: The X25519 secret key of this key pair, RFC 7748's form of the clamped first half of the seed's SHA-512. -- [curves::ed25519::public_key](https://webcpporg.github.io/libs/crypto/#crypto-ed25519): An Ed25519 public key, its 32 bytes, which `crypto::verify(crypto::eddsa, ...)` takes: made from bytes with only their size checked, since whether the point is canonical and not of small order is the verification policy's judgment. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. - - make: Makes a public key from its 32 bytes, as RFC 8032 encodes it and WebCrypto's `exportKey("raw")` writes it. + - secret: The seed, RFC 8032's secret key, for a program that keeps the key pair and makes it again with `from_secret`, or exports it (PKCS#8 holds the seed alone). + - sign: Signs with Ed25519 (RFC 8032): under `crypto::eddsa`, the pure form, a message, the message itself, of any length, empty included, with no digest taken; under `crypto::eddsa_prehashed`, Ed25519ph, the 64 bytes of a message's SHA-512, `crypto::prehashed{digest}` (a message given in pieces is prehashed_signer's). + - async_sign: Signs with Ed25519, asynchronously: `sign` run when the operation is initiated, its result posted to `completion_executor`; the member form of the free `crypto::async_sign`, with the same arguments and this key pair, which calls it. + - to_x25519: The X25519 key pair of this key pair, on its backend: its secret key the clamped first half of the seed's SHA-512, its public key `public_key()->to_x25519()`, so that one seed serves for signatures and for agreement. +- [curves::ed25519::public_key](https://webcpporg.github.io/libs/crypto/#crypto-ed25519): An Ed25519 public key, its 32 bytes, which `crypto::verify(crypto::eddsa, ...)` takes: made from bytes with only their size checked, since whether the point is canonical and not of small order is the verification policy's judgment; and its X25519 public key, `to_x25519()`. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. + - from_bytes: Makes a public key from its 32 bytes, as RFC 8032 encodes it and WebCrypto's `exportKey("raw")` writes it. - bytes: The key's bytes. - - verify: Verifies an Ed25519 signature (RFC 8032's pure Ed25519) with this key, under a verification policy (design D31): `crypto::verify(crypto::eddsa, signature_bytes, message_input, key, verify_policy)`, of which it is the member form, with the same work, results and refusals. - - async_verify: Verifies an Ed25519 signature with this key, asynchronously, strictly: `verify` run when the operation is initiated, its result posted to `completion_executor`; the member form of `crypto::async_verify(completion_executor, crypto::eddsa, signature_bytes, message_input, key, completion_token)`, which calls it. -- [crypto::verify](https://webcpporg.github.io/libs/crypto/#crypto-ed25519): Verifies an Ed25519 signature with a public key alone, `crypto::verify(crypto::eddsa, signature, message, public_key)`, under the policy `strict`: libsodium's rules, which refuse non-canonical encodings and keys of small order. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. Use it to: sign and verify with Ed25519 (RFC 8032), or sign a large message in pieces with Ed25519ph. + - verify: Verifies an Ed25519 signature (RFC 8032's pure Ed25519) with this key, under a verification policy (design D31): `crypto::verify(crypto::eddsa, signature_value, message_input, key, verify_policy)`, of which it is the member form, with the same work, results and refusals. + - async_verify: Verifies an Ed25519 signature with this key, asynchronously, strictly: `verify` run when the operation is initiated, its result posted to `completion_executor`; the member form of the free `crypto::async_verify`, with the same arguments and this key, which calls it. + - to_x25519: The X25519 public key of this key (the birational map from edwards25519 to Curve25519), so that a peer known by its Ed25519 key is agreed with by an X25519 key pair's `agree`; the key pair's own side is `basic_keypair::to_x25519`. +- [crypto::verify](https://webcpporg.github.io/libs/crypto/#crypto-ed25519): Verifies an Ed25519 signature with a public key alone, `crypto::verify(crypto::eddsa, signature, message, public_key)`, or an Ed25519ph one, `crypto::verify(crypto::eddsa_prehashed, signature, crypto::prehashed{digest}, public_key)`, under the policy `strict`: libsodium's rules, which refuse non-canonical encodings and keys of small order. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. Use it to: sign and verify with Ed25519 (RFC 8032), or with Ed25519ph a message's SHA-512 or a large message in pieces. - verify: Verifies an Ed25519 signature (RFC 8032's pure Ed25519) under a verification policy (design D31). -- [curves::ed25519::ph](https://webcpporg.github.io/libs/crypto/#crypto-ed25519): Ed25519ph (RFC 8032): a message given in pieces, hashed with SHA-512, then signed with a key pair or verified with `verify(signature, public_key)`. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. Use it to: sign and verify with Ed25519 (RFC 8032), or sign a large message in pieces with Ed25519ph. +- [curves::ed25519::prehashed_signer](https://webcpporg.github.io/libs/crypto/#crypto-ed25519): Ed25519ph (RFC 8032), the streaming form of the scheme `crypto::eddsa_prehashed`: a message given in pieces, hashed with SHA-512, then signed with a key pair or verified with `verify(signature, public_key)`, the signature `sign(crypto::eddsa_prehashed, crypto::prehashed{digest})` gives of its SHA-512. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. Use it to: sign and verify with Ed25519 (RFC 8032), or with Ed25519ph a message's SHA-512 or a large message in pieces. - begin: Begins a message. - update: Adds a piece of the message. - sign: Signs the message given, which it ends. - verify: Verifies a signature of the message given, which it ends, strictly (design D31). -- [curves::ed25519::to_x25519_public](https://webcpporg.github.io/libs/crypto/#crypto-x25519): The X25519 public key of an Ed25519 public key (the birational map), refusing a key of small order or not canonical with `invalid_public_key`. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. Use it to: agree a shared secret with a peer's public key (X25519, RFC 7748), or with the X25519 form of an Ed25519 key. - - to_x25519_public: The X25519 public key of an Ed25519 public key (the birational map from edwards25519 to Curve25519), so that a peer known by its Ed25519 key can be agreed with by `curves::x25519::agree`; the key pair's own side is `basic_keypair::x25519_secret`. -- [curves::x25519::public_key](https://webcpporg.github.io/libs/crypto/#crypto-x25519): The 32-byte X25519 public key of a 32-byte secret key (RFC 7748). Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. Use it to: agree a shared secret with a peer's public key (X25519, RFC 7748), or with the X25519 form of an Ed25519 key. - - public_key: The public key of a secret key: `algorithm::public_key`. -- [curves::x25519::agree](https://webcpporg.github.io/libs/crypto/#crypto-x25519): The 32-byte shared secret of a secret key and a peer's public key, a `secret<32>`, refused with `weak_public_key` when it is all zero (a peer key of low order). Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. Use it to: agree a shared secret with a peer's public key (X25519, RFC 7748), or with the X25519 form of an Ed25519 key. - - agree: The shared secret, refused when all zero: `algorithm::agree`. +- [crypto::to_x25519](https://webcpporg.github.io/libs/crypto/#crypto-x25519): Converts an Ed25519 key pair to an X25519 key pair of its backend, and an Ed25519 public key to an X25519 public key (the birational map), refusing a key of small order or not canonical with `invalid_public_key`: the free form of both members, `to_x25519()`, synchronous on every backend. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. Use it to: agree a shared secret with a peer's public key (X25519, RFC 7748), or with the X25519 form of an Ed25519 key. + - to_x25519: Converts an Ed25519 key pair or public key to X25519's, `converted_value.to_x25519()`: the free form of the member, which it calls, with its results and its errors. +- [curves::x25519::keypair](https://webcpporg.github.io/libs/crypto/#crypto-x25519): An X25519 key pair (RFC 7748): made from its 32-byte secret key, which `secret()` gives back, or drawn from `random_device`; its public key, a `curves::x25519::public_key`, computed once; and `agree(peer)`, the 32-byte shared secret with a peer's public key, a `secret<32>`, refused with `weak_public_key` when it is all zero (a peer key of low order). Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. Use it to: agree a shared secret with a peer's public key (X25519, RFC 7748), or with the X25519 form of an Ed25519 key. + - from_secret: Makes a key pair from its secret key; its public key is computed here, once. + - generate: Makes a key pair from a fresh secret key, drawn from the system's generator. + - async_from_secret: Makes a key pair from its secret key, asynchronously: `from_secret` run when the operation is initiated, its result posted to `completion_executor`; the member form of the free `crypto::async_from_secret`, with the same arguments, which calls it. + - async_generate: Makes a key pair from a fresh secret key, asynchronously: `generate` run when the operation is initiated, its result posted to `completion_executor`; the member form of `crypto::async_generate(completion_executor, completion_token)`, which calls it. + - public_key: The public key, which a peer's `agree` takes: a copy of the one computed when the key pair was made. + - secret: The secret key, for a program that keeps the key pair and makes it again with `from_secret`, or exports it: a copy. + - agree: The shared secret of this key pair and a peer's public key (RFC 7748's X25519), refused when it is all zero, on every backend. + - async_agree: The shared secret of this key pair and a peer's public key, asynchronously: `agree` run when the operation is initiated, its result posted to `completion_executor`; the member form of `crypto::async_agree(completion_executor, key_pair, peer_key, completion_token)`, which calls it. +- [curves::x25519::public_key](https://webcpporg.github.io/libs/crypto/#crypto-x25519): An X25519 public key, its 32 bytes, which a key pair's `agree` takes: made from bytes with only their size checked, since a key of low order is `agree`'s refusal, `weak_public_key`. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. Use it to: agree a shared secret with a peer's public key (X25519, RFC 7748), or with the X25519 form of an Ed25519 key. + - from_bytes: Makes a public key from its 32 bytes, as RFC 7748 encodes it and WebCrypto's `exportKey("raw")` writes it. + - bytes: The key's bytes. - [curves::ed25519::encode_spki, decode_spki, encode_pkcs8, decode_pkcs8](https://webcpporg.github.io/libs/crypto/#crypto-key-formats): RFC 8410's SPKI of an Ed25519 public key (44 bytes) and PKCS#8 of a key pair (version 1, the seed alone, 48 bytes), the forms OpenSSL and WebCrypto write, decoded strictly: any other bytes are `invalid_encoding`. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. Use it to: 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. - encode_spki: Writes a public key's SPKI (RFC 8410) into `output_bytes`. - decode_spki: The public key of an SPKI, refused unless it is exactly RFC 8410's form: the 12 bytes of Ed25519's prefix, then the key, and nothing after. @@ -145,46 +176,40 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - decode_spki: The public key of an SPKI, refused unless it is exactly RFC 8410's form: the 12 bytes of X25519's prefix, then the key, and nothing after. - encode_pkcs8: Writes a secret key's PKCS#8 (RFC 8410, version 1: the secret key, without the public key) into `output_bytes`, which then holds the secret key: a program wipes it, or seals it, when it is done. - decode_pkcs8: The secret key of a PKCS#8, refused unless it is exactly RFC 8410's version 1 form: the 16 bytes of X25519's prefix, then the secret key, and nothing after. -- [curves::x25519::kx_keypair](https://webcpporg.github.io/libs/crypto/#crypto-kx): libsodium's `crypto_kx`: a key pair made from a 32-byte seed or drawn from `random_device`, and the two session keys of a client or a server, each a `secret<32>`, from the peer's 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. - - make: Makes a key pair from a seed, `crypto_kx_seed_keypair`: the same seed gives the same key pair. - - generate: Makes a key pair from a fresh seed, drawn from the system's generator. - - public_key: The public key, which the peer needs. - - client_session_keys: The client's keys, from the server's public key, `crypto_kx_client_session_keys`. - - server_session_keys: The server's keys, from the client's public key, `crypto_kx_server_session_keys`. -- [curves::secp256k1::recover](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-recovery): The public key that made a recoverable ECDSA signature, `recover(crypto::ecdsa_sha256_recoverable, signature, input)`, the input as signing took it: a message hashed inside or `crypto::prehashed{digest}`. Header . Backends: libsecp256k1 (/third_party//secp256k1) on native, wasip2, wasip3, emscripten. Default: libsecp256k1 on native, wasip2, wasip3, emscripten. Use it to: find who signed a message or a transaction without being sent their key (Ethereum's signatures). - - recover: The public key that made a recoverable signature (`secp256k1_ecdsa_recover`), as Ethereum identifies a transaction's signer: the same inputs as `sign(crypto::ecdsa_sha256_recoverable, signing_input)`. +- [curves::secp256k1::recover](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-recovery): The public key that made a recoverable ECDSA signature, `recover(crypto::ecdsa_sha256_recoverable, signature, input)` or Ethereum's `recover(crypto::ecdsa_keccak256_recoverable, signature, input)`, the input as signing took it: a message hashed inside (with SHA-256, or Keccak-256) or `crypto::prehashed{digest}`. Header . Backends: libsecp256k1 (/third_party//secp256k1) on native, wasip2, wasip3, emscripten. Default: libsecp256k1 on native, wasip2, wasip3, emscripten. Use it to: find who signed a message or a transaction without being sent their key (Ethereum's signatures). + - recover: The public key that made a recoverable signature (`secp256k1_ecdsa_recover`) of ECDSA over SHA-256: the same inputs as `sign(crypto::ecdsa_sha256_recoverable, signing_input)`. - [curves::secp256k1::public_key](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-keys): A secp256k1 public key, a point checked on the curve, which `crypto::verify` and a key pair's `agree` take: made from its compressed or uncompressed SEC 1 form, and giving its compressed, uncompressed and x-only forms. Header . Backends: libsecp256k1 (/third_party//secp256k1) on native, wasip2, wasip3, emscripten. Default: libsecp256k1 on native, wasip2, wasip3, emscripten. - - make: Makes a public key from SEC1 bytes, 33 with prefix 02 or 03, or 65 with prefix 04. + - from_bytes: Makes a public key from SEC1 bytes, 33 with prefix 02 or 03, or 65 with prefix 04. - compressed: The key, SEC1 compressed: 02 or 03 by the parity of y, then x; Bitcoin's form. - uncompressed: The key, SEC1 uncompressed: 04, x, y; Ethereum's form, and OpenSSL's default. - xonly: The key's BIP340 x-only form, its x coordinate, which `crypto::verify(crypto::schnorr, ...)` takes as the key itself does; the parity of y is dropped. - - verify: Verifies a signature with this key, of ECDSA over SHA-256 or of BIP340's Schnorr (design R22): `crypto::verify(signing_scheme, signature_bytes, signing_input, key)`, of which it is the member form, with the same work, results and refusals. -- [curves::secp256k1::seckey_tweak_add, seckey_tweak_mul, seckey_negate, pubkey_tweak_add, pubkey_tweak_mul, pubkey_negate, pubkey_combine](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-tweaks): A secret or public key plus or times a tweak, its negation, and the sum of public keys. Header . Backends: libsecp256k1 (/third_party//secp256k1) on native, wasip2, wasip3, emscripten. Default: libsecp256k1 on native, wasip2, wasip3, emscripten. Use it to: derive child keys for a watch-only wallet (BIP 32's derivation is a domain library's). - - seckey_tweak_add: A secret key plus a tweak modulo the group order (`secp256k1_ec_seckey_tweak_add`). - - seckey_tweak_mul: A secret key times a tweak modulo the group order (`secp256k1_ec_seckey_tweak_mul`). - - seckey_negate: The group order minus a secret key (`secp256k1_ec_seckey_negate`). - - pubkey_tweak_add: A public key P plus t times the generator (`secp256k1_ec_pubkey_tweak_add`). - - pubkey_tweak_mul: A public key P times t (`secp256k1_ec_pubkey_tweak_mul`). - - pubkey_negate: The negation -P of a public key (`secp256k1_ec_pubkey_negate`). - - pubkey_combine: The sum of public keys (`secp256k1_ec_pubkey_combine`), in a workspace the caller lends for libsecp256k1's array of pointers. + - verify: Verifies a signature with this key, of ECDSA over SHA-256 or of BIP340's Schnorr (design R22): `crypto::verify(signing_scheme, signature_value, signing_input, key)`, of which it is the member form, with the same work, results and refusals. +- [curves::secp256k1::secret_key_tweak_add, secret_key_tweak_mul, secret_key_negate, public_key_tweak_add, public_key_tweak_mul, public_key_negate, public_key_combine](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-tweaks): A secret or public key plus or times a tweak, its negation, and the sum of public keys. Header . Backends: libsecp256k1 (/third_party//secp256k1) on native, wasip2, wasip3, emscripten. Default: libsecp256k1 on native, wasip2, wasip3, emscripten. Use it to: derive child keys for a watch-only wallet (BIP 32's derivation is a domain library's). + - secret_key_tweak_add: A secret key plus a tweak modulo the group order (`secp256k1_ec_seckey_tweak_add`). + - secret_key_tweak_mul: A secret key times a tweak modulo the group order (`secp256k1_ec_seckey_tweak_mul`). + - secret_key_negate: The group order minus a secret key (`secp256k1_ec_seckey_negate`). + - public_key_tweak_add: A public key P plus t times the generator (`secp256k1_ec_pubkey_tweak_add`). + - public_key_tweak_mul: A public key P times t (`secp256k1_ec_pubkey_tweak_mul`). + - public_key_negate: The negation -P of a public key (`secp256k1_ec_pubkey_negate`). + - public_key_combine: The sum of public keys (`secp256k1_ec_pubkey_combine`), in a workspace the caller lends for libsecp256k1's array of pointers. - [curves::secp256k1::encode_spki, decode_spki, encode_pkcs8, decode_pkcs8](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-formats): A public key's SPKI and a key pair's PKCS#8, in OpenSSL's forms, decoded strictly; `pem::armour` makes either PEM text. Header . Backends: libsecp256k1 (/third_party//secp256k1) on native, wasip2, wasip3, emscripten. Default: libsecp256k1 on native, wasip2, wasip3, emscripten. Use it to: store or exchange a secp256k1 key with OpenSSL or a config file. - encode_spki: Writes a public key's SPKI (RFC 5480, the secp256k1 OID) into `output_bytes`. - decode_spki: The public key of an SPKI in exactly one of the two forms `encode_spki` writes. - encode_pkcs8: Writes a key pair's PKCS#8 into `output_bytes`, in OpenSSL's form: version 0, and RFC 5915's ECPrivateKey of version 1 with the uncompressed public key and no parameters inside. - - decode_pkcs8: The key pair of a PKCS#8 that is exactly what `encode_pkcs8` writes for its secret, made as `basic_keypair::make` makes it. + - decode_pkcs8: The key pair of a PKCS#8 that is exactly what `encode_pkcs8` writes for its secret, made as `basic_keypair::from_secret` makes it. - [curves::secp256k1::ellswift_encode, ellswift_decode, ellswift_create, ellswift_xdh](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-ellswift): A public key written as 64 bytes that look random, and BIP 324's key exchange of two such encodings. Header . Backends: libsecp256k1 (/third_party//secp256k1) on native, wasip2, wasip3, emscripten. Default: libsecp256k1 on native, wasip2, wasip3, emscripten. Use it to: make a peer-to-peer connection's key exchange look like random bytes (BIP 324's transport; its packets are a domain library's). - ellswift_encode: A public key's ElligatorSwift encoding (`secp256k1_ellswift_encode`): one of many, chosen by the randomness, each of which decodes to the key. - ellswift_decode: The public key of any 64 bytes (`secp256k1_ellswift_decode`): every input decodes. - ellswift_create: The encoding of a key pair's public key, made from its secret with the key pair's context (`secp256k1_ellswift_create`), so that the public key is never computed apart. - ellswift_xdh: The shared secret of an ElligatorSwift key exchange, hashed as BIP 324 hashes it (`secp256k1_ellswift_xdh` with `secp256k1_ellswift_xdh_hash_function_bip324`): a tagged hash of both encodings and the shared point's x coordinate. -- [curves::secp256k1::musig::aggregate_key, key_aggregate, nonce_gen, nonce_aggregate, nonce_process, partial_sign, partial_signature_verify, partial_signature_aggregate, parse_public_nonce, serialize_public_nonce, parse_aggregate_nonce, serialize_aggregate_nonce, parse_partial_signature, serialize_partial_signature](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-musig): BIP 327's MuSig2: many signers' keys aggregated into one, and their two rounds into one BIP 340 signature, each secret nonce consumed by its partial signature. Header . Backends: libsecp256k1 (/third_party//secp256k1) on native, wasip2, wasip3, emscripten. Default: libsecp256k1 on native, wasip2, wasip3, emscripten. Use it to: require two devices to sign for a wallet, with one ordinary signature on the chain. +- [curves::secp256k1::musig::aggregate_key, key_aggregate, generate_nonce, nonce_aggregate, nonce_process, partial_sign, partial_signature_verify, partial_signature_aggregate, parse_public_nonce, serialize_public_nonce, parse_aggregate_nonce, serialize_aggregate_nonce, parse_partial_signature, serialize_partial_signature](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-musig): BIP 327's MuSig2: many signers' keys aggregated into one, and their two rounds into one BIP 340 signature, each secret nonce consumed by its partial signature. Header . Backends: libsecp256k1 (/third_party//secp256k1) on native, wasip2, wasip3, emscripten. Default: libsecp256k1 on native, wasip2, wasip3, emscripten. Use it to: require two devices to sign for a wallet, with one ordinary signature on the chain. - xonly_public_key: The BIP 340 x-only key the final signature verifies under. - full_public_key: The aggregate as a full point (`secp256k1_musig_pubkey_get`), which a plain tweak acts on. - tweak_add: Adds t times G as a plain tweak (BIP 327's ApplyTweak, is_xonly false, `secp256k1_musig_pubkey_ec_tweak_add`). - tweak_xonly_add: Adds t times G as an x-only tweak (BIP 327's ApplyTweak, is_xonly true, `secp256k1_musig_pubkey_xonly_tweak_add`), as Taproot tweaks an output key. - workspace_size: The workspace `key_aggregate`, `nonce_aggregate` and `partial_signature_aggregate` need for `item_count` items, in bytes. - key_aggregate: Aggregates the signers' keys in the order given (`secp256k1_musig_pubkey_agg`). - - nonce_gen: A fresh nonce for one signature (`secp256k1_musig_nonce_gen`), its 32 bytes of session randomness drawn inside from crypto's random device, with the key pair's secret, its public key and the aggregate key. + - generate_nonce: A fresh nonce for one signature (`secp256k1_musig_nonce_gen`), its 32 bytes of session randomness drawn inside from crypto's random device, with the key pair's secret, its public key and the aggregate key. - nonce_aggregate: Sums the signers' public nonces (`secp256k1_musig_nonce_agg`), as one of them or a coordinator does once every public nonce is in. - nonce_process: The session of one message (`secp256k1_musig_nonce_process`): the final nonce and the challenge every signer signs. - partial_sign: This signer's partial signature (`secp256k1_musig_partial_sign`), consuming the nonce: it is taken by value, wiped by the call and destroyed at its end. @@ -196,30 +221,31 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - serialize_aggregate_nonce: Serialises an aggregate nonce (`secp256k1_musig_aggnonce_serialize`). - parse_partial_signature: Parses a partial signature (`secp256k1_musig_partial_sig_parse`). - serialize_partial_signature: Serialises a partial signature (`secp256k1_musig_partial_sig_serialize`). -- [curves::secp256k1::silent_payments::create_outputs, create_label, create_labeled_spend_key, make_prevouts_summary, scan_outputs, send_workspace_size, summary_workspace_size, scan_workspace_size](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-silent-payments): BIP 352's silent payments: the sender's outputs to a reusable address of a scan and a spend key, the recipient's labels, and its scan of a transaction's outputs. Header . Backends: libsecp256k1 (/third_party//secp256k1) on native, wasip2, wasip3, emscripten. Default: libsecp256k1 on native, wasip2, wasip3, emscripten. Use it to: publish one donation address that never shows two payments as related (BIP 352's addresses and transactions are a domain library's). +- [curves::secp256k1::silent_payments::create_outputs, create_label, create_labeled_spend_key, make_previous_outputs_summary, scan_outputs, send_workspace_size, summary_workspace_size, scan_workspace_size](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-silent-payments): BIP 352's silent payments: the sender's outputs to a reusable address of a scan and a spend key, the recipient's labels, and its scan of a transaction's outputs. Header . Backends: libsecp256k1 (/third_party//secp256k1) on native, wasip2, wasip3, emscripten. Default: libsecp256k1 on native, wasip2, wasip3, emscripten. Use it to: publish one donation address that never shows two payments as related (BIP 352's addresses and transactions are a domain library's). - send_workspace_size: The workspace `create_outputs` needs, in bytes. - - summary_workspace_size: The workspace `make_prevouts_summary` needs, in bytes. + - summary_workspace_size: The workspace `make_previous_outputs_summary` needs, in bytes. - scan_workspace_size: The workspace `scan_outputs` needs, in bytes. - create_outputs: The sender's outputs (`secp256k1_silentpayments_sender_create_outputs`): one x-only key per recipient, in the recipients' order, from the secret keys of the transaction's eligible inputs, Taproot inputs (their keys negated for an odd y, as BIP 352 says) apart from the others, and the smallest outpoint, which the caller determines. - create_label: The `m`-th label of a scan key (`secp256k1_silentpayments_recipient_label_create`); 0 is BIP 352's change label. - create_labeled_spend_key: The spend key of a labelled address (`..._create_labeled_spend_pubkey`). - - make_prevouts_summary: The prevouts' summary (`..._recipient_prevouts_summary_create`) from the eligible inputs' public keys. + - make_previous_outputs_summary: The previous outputs' summary (`secp256k1_silentpayments_recipient_prevouts_summary_create`) from the eligible inputs' public keys. - scan_outputs: Scans a transaction's x-only outputs (`..._recipient_scan_outputs`) with the scan key pair and the unlabelled spend key; `label_lookup` is called with a candidate label's 33 bytes and returns a span over its tweak, in bytes the lookup owns, or `std::nullopt`, noexcept (no labels: the default). - [curves::p256::keypair](https://webcpporg.github.io/libs/crypto/#crypto-p256-keys): A P-256 key pair: made from its 32-byte scalar, refused unless 0 < d < n, or drawn from `random_device`; its validated public key and its scalar, `secret()`, a `secret<32>`. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten. Default: BearSSL on native, wasip2, wasip3, emscripten. Use it to: make and keep a P-256 key pair, and import a browser's public key (WebCrypto's raw form), as webcpp::trystero's peers do. - - make: Makes a key pair from its secret scalar, as a program that kept `secret()` loads it again. + - from_secret: Makes a key pair from its secret scalar, as a program that kept `secret()` loads it again. - generate: Makes a key pair from a fresh scalar, drawn from the system's generator until it is below the group order (a draw is refused about once in 2^32). - - async_make: Makes a key pair from its secret scalar, asynchronously: `make` run when the operation is initiated, its result posted to `completion_executor`; the member form of `crypto::async_make(completion_executor, secret_scalar, completion_token)`, which calls it. + - async_from_secret: Makes a key pair from its secret scalar, asynchronously: `from_secret` run when the operation is initiated, its result posted to `completion_executor`; the member form of the free `crypto::async_from_secret`, with the same arguments, which calls it. - async_generate: Makes a key pair from a fresh scalar, asynchronously: `generate` run when the operation is initiated, its result posted to `completion_executor`; the member form of `crypto::async_generate(completion_executor, completion_token)`, which calls it. - public_key: The public key, computed when the key pair was made. - - secret: The secret scalar, for a program that keeps the key pair and makes it again with `make`. + - secret: The secret scalar, for a program that keeps the key pair and makes it again with `from_secret`. - [curves::p256::public_key](https://webcpporg.github.io/libs/crypto/#crypto-p256-keys): A validated P-256 public key, made from SEC 1's 65-byte uncompressed point or from its two coordinates; a point off the curve, a coordinate not below p or another form is `invalid_public_key`. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten. Default: BearSSL on native, wasip2, wasip3, emscripten. Use it to: make and keep a P-256 key pair, and import a browser's public key (WebCrypto's raw form), as webcpp::trystero's peers do. - - make: Makes a public key from SEC 1's uncompressed point, as WebCrypto's `exportKey("raw")` writes it. + - from_bytes: Makes a public key from SEC 1's uncompressed point, as WebCrypto's `exportKey("raw")` writes it. + - from_coordinates: Makes a public key from its two coordinates, as a JSON Web Key's `x` and `y` carry them. - uncompressed: The point, as WebCrypto's `exportKey("raw")` writes it. - - verify: Verifies an ECDSA signature over SHA-256 with this key: `crypto::verify(crypto::ecdsa_sha256, signature_bytes, signing_input, key)`, of which it is the member form, with the same work, results and refusals. - - async_verify: Verifies an ECDSA signature over SHA-256 with this key, asynchronously: `verify` run when the operation is initiated, its result posted to `completion_executor`; the member form of `crypto::async_verify(completion_executor, crypto::ecdsa_sha256, signature_bytes, signing_input, key, completion_token)`, which calls it. -- [curves::p256::keypair::sign; crypto::verify, to_der, from_der, normalize_low_s, is_low_s](https://webcpporg.github.io/libs/crypto/#crypto-p256-ecdsa): ECDSA over SHA-256 with RFC 6979's nonce, `sign(crypto::ecdsa_sha256, input)` and `crypto::verify(crypto::ecdsa_sha256, signature, input, public_key)`, the input a message hashed inside or `crypto::prehashed{digest}`; r and s as 64 bytes, signed low S, verified whatever its S; strict DER both ways; `normalize_low_s` and `is_low_s` for a signature made elsewhere. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten. Default: BearSSL on native, wasip2, wasip3, emscripten. Use it to: sign what a browser's WebCrypto verifies and verify what it signs (ECDSA on P-256 with SHA-256), low S where a protocol requires it, as webcpp::trystero's handshakes. + - verify: Verifies an ECDSA signature over SHA-256 with this key: `crypto::verify(crypto::ecdsa_sha256, signature_value, signing_input, key)`, of which it is the member form, with the same work, results and refusals. + - async_verify: Verifies an ECDSA signature over SHA-256 with this key, asynchronously: `verify` run when the operation is initiated, its result posted to `completion_executor`; the member form of the free `crypto::async_verify`, with the same arguments and this key, which calls it. +- [curves::p256::keypair::sign; crypto::verify, to_der, from_der, normalize_low_s, is_low_s](https://webcpporg.github.io/libs/crypto/#crypto-p256-ecdsa): ECDSA over SHA-256 with RFC 6979's nonce, `sign(crypto::ecdsa_sha256, input)` and `crypto::verify(crypto::ecdsa_sha256, signature, input, public_key)`, the input a message hashed inside or `crypto::prehashed{digest}`; the signature a `curves::p256::ecdsa_signature`, r and s, signed low S, verified whatever its S; strict DER both ways; `normalize_low_s` and `is_low_s` for a signature made elsewhere. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten. Default: BearSSL on native, wasip2, wasip3, emscripten. Use it to: sign what a browser's WebCrypto verifies and verify what it signs (ECDSA on P-256 with SHA-256), low S where a protocol requires it, as webcpp::trystero's handshakes. - sign: Signs with ECDSA over SHA-256 and RFC 6979's deterministic nonce (no random number is drawn: the same key and input give the same signature), S always low, at most (n - 1) / 2, as libsecp256k1 signs: the signature is normalized after it is made. - - async_sign: Signs with ECDSA over SHA-256, asynchronously: `sign` run when the operation is initiated, its result posted to `completion_executor`; the member form of `crypto::async_sign(completion_executor, key_pair, signing_scheme, signing_input, completion_token)`, which calls it. + - async_sign: Signs with ECDSA over SHA-256, asynchronously: `sign` run when the operation is initiated, its result posted to `completion_executor`; the member form of the free `crypto::async_sign`, with the same arguments and this key pair, which calls it. - verify: Verifies an ECDSA signature over SHA-256 with a P-256 public key. - to_der: Encodes a signature as strict DER, the ECDSA-Sig-Value SEQUENCE of two INTEGERs that X.509 and OpenSSL carry. - from_der: Decodes a strict DER signature to its raw form: only the encoding `to_der` writes is accepted. @@ -230,23 +256,38 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - async_agree: ECDH with a peer's public key, asynchronously: `agree` run when the operation is initiated, its result posted to `completion_executor`; the member form of `crypto::async_agree(completion_executor, key_pair, peer_key, completion_token)`, which calls it. - [curves::p256::encode_spki, decode_spki, encode_pkcs8, decode_pkcs8](https://webcpporg.github.io/libs/crypto/#crypto-p256-formats): A public key's SPKI (RFC 5480, the uncompressed point, 91 bytes) and a key pair's PKCS#8 (RFC 5915's ECPrivateKey with its public key and no parameters, 138 bytes), by fixed layouts, decoded strictly: any other bytes are `invalid_encoding`; `pem::armour` makes either PEM text. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten. Default: BearSSL on native, wasip2, wasip3, emscripten. Use it to: export or import a P-256 key in the forms OpenSSL and WebCrypto's spki and pkcs8 use (SPKI, PKCS#8), as DER or PEM text. - encode_spki: Writes a public key's SPKI (RFC 5480, the secp256r1 OID, the uncompressed point) into `output_bytes`: the bytes WebCrypto's `exportKey("spki")` and OpenSSL's `i2d_PUBKEY` write. - - decode_spki: The public key of an SPKI that is exactly what `encode_spki` writes, its point checked as `basic_public_key::make` checks it. + - decode_spki: The public key of an SPKI that is exactly what `encode_spki` writes, its point checked as `basic_public_key::from_bytes` checks it. - encode_pkcs8: Writes a key pair's PKCS#8 into `output_bytes`: version 0, and RFC 5915's ECPrivateKey of version 1 with the uncompressed public key and no parameters inside, the form OpenSSL's and BearSSL's encoders write. - - decode_pkcs8: The key pair of a PKCS#8 that is exactly what `encode_pkcs8` writes for its scalar, made as `basic_keypair::make` makes it. + - decode_pkcs8: The key pair of a PKCS#8 that is exactly what `encode_pkcs8` writes for its scalar, made as `basic_keypair::from_secret` makes it. -## webcpp::crypto::hybrid +## webcpp::crypto::public_key_encryption -- [hybrid::box](https://webcpporg.github.io/libs/crypto/#crypto-box): NaCl's and libsodium's `crypto_box`: X25519 agrees a key once per pair of keys, refusing a peer key of small order, then XSalsa20-Poly1305 seals and opens each message in place, with a 24-byte nonce safe to draw at random. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. Use it to: send messages between two people who know each other's public keys, as NaCl's and libsodium's crypto_box. - - make: Agrees the box's key from the own secret key and the peer's public key. +- [public_key_encryption::box](https://webcpporg.github.io/libs/crypto/#crypto-box): NaCl's and libsodium's `crypto_box`: X25519 agrees a key once per pair of keys, from the own X25519 key pair and the peer's X25519 public key, refusing a peer key of small order, then XSalsa20-Poly1305 seals and opens each message in place, with a 24-byte nonce safe to draw at random. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. Use it to: send messages between two people who know each other's public keys, as NaCl's and libsodium's crypto_box. + - from_keys: Agrees the box's key from the own key pair and the peer's public key. - seal: Seals a message in place: `data_bytes` holds the plaintext before and the ciphertext after. + - 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::async_seal(executor, box, nonce_bytes, data_bytes, token)`, which calls it. - open: Opens a message in place: `data_bytes` holds the ciphertext before and the plaintext after. -- [hybrid::box_xchacha20poly1305](https://webcpporg.github.io/libs/crypto/#crypto-box): libsodium's `crypto_box_curve25519xchacha20poly1305`: the box with XChaCha20 in place of XSalsa20. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. - - make: Agrees the box's key from the own secret key and the peer's public key. + - 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::async_open(executor, box, nonce_bytes, data_bytes, tag_bytes, token)`, which calls it. +- [public_key_encryption::box_xchacha20poly1305](https://webcpporg.github.io/libs/crypto/#crypto-box): libsodium's `crypto_box_curve25519xchacha20poly1305`: the box with XChaCha20 in place of XSalsa20. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. + - from_keys: Agrees the box's key from the own key pair and the peer's public key. - seal: Seals a message in place: `data_bytes` holds the plaintext before and the ciphertext after. + - 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::async_seal(executor, box, nonce_bytes, data_bytes, token)`, which calls it. - open: Opens a message in place: `data_bytes` holds the ciphertext before and the plaintext after. -- [hybrid::sealed_box](https://webcpporg.github.io/libs/crypto/#crypto-sealed-box): libsodium's sealed boxes, `crypto_box_seal`: anonymous encryption to a public key under a key pair drawn per message, 48 bytes longer than the message, which only the recipient's key pair opens. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. Use it to: let anyone send a message that only the recipient can read, without saying who sent it (anonymous feedback, a drop box). - - seal: Seals `message` into `out`, of `message.size() + overhead` bytes: the drawn public key, the tag, then the ciphertext. - - open: Opens `sealed` into `out`, of `sealed.size() - overhead` bytes, with the recipient's keys. + - 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::async_open(executor, box, nonce_bytes, data_bytes, tag_bytes, token)`, which calls it. +- [public_key_encryption::sealed_box](https://webcpporg.github.io/libs/crypto/#crypto-sealed-box): libsodium's sealed boxes, `crypto_box_seal`: anonymous encryption to an X25519 public key under a key pair drawn per message, 48 bytes longer than the message, which only the recipient's X25519 key pair opens. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. Use it to: let anyone send a message that only the recipient can read, without saying who sent it (anonymous feedback, a drop box). + - seal: Seals `message_bytes` into `output_bytes`, of `message_bytes.size() + overhead` bytes: the drawn public key, the tag, then the ciphertext. + - open: Opens `sealed_bytes` into `output_bytes`, of `sealed_bytes.size() - overhead` bytes, with the recipient's key pair. + +## 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 `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. + - from_keypair: Takes an X25519 key pair as it is: its secret key is the key pair's, as `crypto_kx` uses it, with no hash (`derive_from_seed` hashes its seed). + - derive_from_seed: Derives a key pair from a seed, `crypto_kx_seed_keypair`: the same seed gives the same key pair, its secret key BLAKE2b-256 of the seed, not the seed itself. + - generate: Makes a key pair from a fresh seed, drawn from the system's generator. + - keypair: The X25519 key pair it holds, for a program that keeps its secret key (`secret()`) or agrees with it through X25519 itself. + - public_key: The public key, which the peer needs: the X25519 key pair's. + - client_session_keys: The client's keys, from the server's public key, `crypto_kx_client_session_keys`. + - server_session_keys: The server's keys, from the client's public key, `crypto_kx_server_session_keys`. ## Default backend per family @@ -293,63 +334,63 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - X25519-XChaCha20-Poly1305 box: libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found; not measured yet on wasip2, wasip3, emscripten. - X25519-XSalsa20-Poly1305 sealed box: libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found; not measured yet on wasip2, wasip3, emscripten. - ElligatorSwift: libsecp256k1: native, Valgrind's memcheck (Linux; libsecp256k1's own `ctime_tests.c`, and webcpp's `ellswift_create` and `ellswift_xdh` around it) and MemorySanitizer (Linux, clang; the same paths as memcheck's), nothing found; not measured yet on wasip2, wasip3, emscripten. -- MuSig2: libsecp256k1: native, Valgrind's memcheck (Linux; libsecp256k1's own `ctime_tests.c`, and webcpp's `nonce_gen` and `partial_sign` around it) and MemorySanitizer (Linux, clang; the same paths as memcheck's), nothing found; not measured yet on wasip2, wasip3, emscripten. +- MuSig2: libsecp256k1: native, Valgrind's memcheck (Linux; libsecp256k1's own `ctime_tests.c`, and webcpp's `generate_nonce` and `partial_sign` around it) and MemorySanitizer (Linux, clang; the same paths as memcheck's), nothing found; not measured yet on wasip2, wasip3, emscripten. - BIP 352 silent payments: libsecp256k1: native, Valgrind's memcheck (Linux; libsecp256k1's own `ctime_tests.c`, and webcpp's `create_outputs`, `create_label` and `scan_outputs` around it, each workspace's wipe included) and MemorySanitizer (Linux, clang; the same paths as memcheck's), nothing found; not measured yet on wasip2, wasip3, emscripten. - P-256: BearSSL: native, Valgrind's memcheck (Linux; the key pair's making, `sign` of a digest (`crypto::prehashed`), which makes its signature low S without a branch, then `normalize_low_s` and `is_low_s` on it, `agree` and `decode_pkcs8`; BearSSL's own branches on its signing's verdicts listed in `bearssl_verdicts.supp`; nothing found with webcpp's fix to BearSSL's decoding of the nonce, whose leak of the nonce's bit length this checker found on 2026-11-21, including `sign` with its low-S step (Valgrind 3.22, arm64 Linux container, 2026-11-22)), MemorySanitizer (Linux, clang; the same paths as memcheck's; for the previous signing, found the same leak, nothing after the fix, including `sign` with its low-S step (clang 18, arm64 Linux container, 2026-11-22)) and dudect (judged; on a runner GitHub hosts, by two of three runs; `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)), nothing found; wasip2, dudect (judged; on a runner GitHub hosts, by two of three runs; `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)), nothing found; not measured yet on wasip3, emscripten. ## Rules of use -- [Never reuse an IV under one key](https://webcpporg.github.io/libs/crypto/#crypto-gcm-rules): two AES-GCM messages under one key and one IV reveal the XOR of their plaintexts and let an attacker forge tags for every later message ([A. Joux, Authentication Failures in NIST version of GCM, 2006](https://csrc.nist.gov/csrc/media/projects/block-cipher-techniques/documents/bcm/comments/800-38-series-drafts/gcm/joux_comments.pdf); [H. Boeck et al., Nonce-Disrespecting Adversaries, 2016](https://eprint.iacr.org/2016/475)); draw a random 12-byte IV per message, or use a counter that never repeats, a restart included. -- [The usage limit](https://webcpporg.github.io/libs/crypto/#crypto-gcm-rules): with random IVs, at most 2^32 messages under one key ([NIST SP 800-38D, GCM and GMAC](https://csrc.nist.gov/pubs/sp/800/38/d/final), section 8.3); rotate the key before. +- [Never reuse a nonce under one key](https://webcpporg.github.io/libs/crypto/#crypto-gcm-rules): two AES-GCM messages under one key and one nonce reveal the XOR of their plaintexts and let an attacker forge tags for every later message ([A. Joux, Authentication Failures in NIST version of GCM, 2006](https://csrc.nist.gov/csrc/media/projects/block-cipher-techniques/documents/bcm/comments/800-38-series-drafts/gcm/joux_comments.pdf); [H. Boeck et al., Nonce-Disrespecting Adversaries, 2016](https://eprint.iacr.org/2016/475)); draw a random 12-byte nonce per message, or use a counter that never repeats, a restart included. +- [The usage limit](https://webcpporg.github.io/libs/crypto/#crypto-gcm-rules): with random nonces, at most 2^32 messages under one key ([NIST SP 800-38D, GCM and GMAC](https://csrc.nist.gov/pubs/sp/800/38/d/final), section 8.3); rotate the key before. - [A failed open zeroes data](https://webcpporg.github.io/libs/crypto/#crypto-gcm-rules): when the tag does not match, `open` returns `authentication_failed` and zeroes the whole of `data`; keep a copy of the ciphertext if it is needed after a failure. the incremental open authenticates every piece and verifies the tag before it decrypts any; a stream read only once is sealed in records. -- [Records: each stream its own key](https://webcpporg.github.io/libs/crypto/#crypto-gcm-incremental): records numbered from 0 with the number as IV are safe only under a key used for that one stream: derive a key per stream (HKDF of the storage key with a random salt) or draw one; never number two streams' records under one key. +- [Records: each stream its own key](https://webcpporg.github.io/libs/crypto/#crypto-gcm-incremental): records numbered from 0 with the number as nonce are safe only under a key used for that one stream: derive a key per stream (HKDF of the storage key with a random salt) or draw one; never number two streams' records under one key. - [ECDH's form](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-ecdh): `keypair::agree` returns the raw x coordinate of the shared point, which protocols such as Nostr's NIP-44 ([Nostr NIP-44, encrypted payloads](https://github.com/nostr-protocol/nips/blob/master/44.md)) take; `keypair::agree_hashed` returns libsecp256k1's hashed form, the SHA-256 of the compressed shared point. Both sides must use the same form, or they derive different keys. Derive keys with a KDF, never use a shared secret directly. -- [The x-only tweak is not BIP 32](https://webcpporg.github.io/libs/crypto/#crypto-wallets-taproot): `tweak_xonly` is BIP 341's even-y arithmetic ([BIP 341, Taproot](https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki)); BIP 32's child derivation tweaks the full key, with `seckey_tweak_add` and `pubkey_tweak_add`, and computes the tweak with HMAC-SHA-512, a domain library's ([BIP 32, hierarchical deterministic wallets](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki)). -- [Ethereum](https://webcpporg.github.io/libs/crypto/#crypto-curves): this version signs and verifies Ethereum's ECDSA, recoverable signatures included (`keypair::sign(crypto::ecdsa_sha256_recoverable, input)`), recovers a signer's public key from a signature and the same input (`recover`), and writes the uncompressed key ([The Ethereum yellow paper, appendix F: ECDSA on secp256k1](https://ethereum.github.io/yellowpaper/paper.pdf)); the recovery id's `v` encoding, the hash Ethereum signs, transactions and addresses are a domain library's. -- [Compare secrets in constant time](https://webcpporg.github.io/libs/crypto/#crypto-equal): compare a tag, a MAC or a token with `equal`, never `==` or `memcmp` ([CWE-208, observable timing discrepancy](https://cwe.mitre.org/data/definitions/208.html)). -- [Secrets come from random_device](https://webcpporg.github.io/libs/crypto/#crypto-entropy): keys, IVs and tokens are drawn from `random_device`, never `std::mt19937` or `rand` ([CWE-338, a weak generator used for security](https://cwe.mitre.org/data/definitions/338.html)). -- [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 IVs ([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. +- [The x-only tweak is not BIP 32](https://webcpporg.github.io/libs/crypto/#crypto-wallets-taproot): `tweak_xonly` is BIP 341's even-y arithmetic ([BIP 341, Taproot](https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki)); BIP 32's child derivation tweaks the full key, with `secret_key_tweak_add` and `public_key_tweak_add`, and computes the tweak with HMAC-SHA-512, a domain library's ([BIP 32, hierarchical deterministic wallets](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki)). +- [Ethereum](https://webcpporg.github.io/libs/crypto/#crypto-curves): this version signs Ethereum's recoverable ECDSA over Keccak-256 (`keypair::sign(crypto::ecdsa_keccak256_recoverable, input)`, a message hashed inside or the 32-byte digest a program builds), recovers a signer's public key from a signature and the same input (`recover`), and writes the uncompressed key ([The Ethereum yellow paper, appendix F: ECDSA on secp256k1](https://ethereum.github.io/yellowpaper/paper.pdf)); the recovery id's `v` encoding, the digests Ethereum signs (EIP-191, EIP-712, a transaction's), transactions and addresses are a domain library's, which the guide shows over webcpp::hash. +- [Compare secrets in constant time](https://webcpporg.github.io/libs/crypto/#crypto-constant-time-equal): compare a tag, a MAC or a token with `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. - [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`. ## Choose by use case -- [Seal or open a record inside an event loop without waiting](https://webcpporg.github.io/libs/crypto/#crypto-async): `async_seal`, `async_open` (webcpp::crypto); backend the default of AES-GCM; Jamfile /webcpp/crypto//crypto /webcpp/crypto//gcm-default /webcpp/asio//asio. Example: example/async_seal.cpp. +- [Seal or open a record inside an event loop without waiting](https://webcpporg.github.io/libs/crypto/#crypto-async): `secret_key_encryption::aead::async_seal`, `async_open` (webcpp::crypto); backend the default of AES-GCM; Jamfile /webcpp/crypto//crypto /webcpp/crypto//gcm-default /webcpp/asio//asio. Example: example/async_seal.cpp. - [Sign and verify with Ed25519 in a coroutine](https://webcpporg.github.io/libs/crypto/#crypto-async): `async_sign`, `async_verify` (webcpp::crypto); backend the default of Ed25519; Jamfile /webcpp/crypto//crypto /webcpp/crypto//ed25519-default /webcpp/asio//asio. Example: example/async_sign.cpp. - [Generate a session token, a password-reset link or an API key](https://webcpporg.github.io/libs/crypto/#crypto-entropy): `random_device::fill` (webcpp::crypto); backend the system's generator; Jamfile /webcpp/crypto//crypto. Example: example/reset_token.cpp. - [Draw an unbiased number in a range, such as a six-digit code](https://webcpporg.github.io/libs/crypto/#crypto-entropy): `random_device` with `std::uniform_int_distribution` (webcpp::crypto); backend the system's generator; Jamfile /webcpp/crypto//crypto. Example: example/reset_token.cpp. -- [Check a webhook's or an API's HMAC signature](https://webcpporg.github.io/libs/crypto/#crypto-equal): `equal`, with Boost.Hash2's `hmac` (webcpp::crypto); backend none; Jamfile /webcpp/crypto//crypto. Example: example/equal_hmac.cpp. +- [Check a webhook's or an API's HMAC signature](https://webcpporg.github.io/libs/crypto/#crypto-constant-time-equal): `constant_time_equal`, with Boost.Hash2's `hmac` (webcpp::crypto); backend none; Jamfile /webcpp/crypto//crypto. Example: example/constant_time_equal_hmac.cpp. - [Encrypt a database field, a cookie or a token at rest](https://webcpporg.github.io/libs/crypto/#crypto-gcm): `aes256_gcm` (webcpp::crypto::ciphers); backend the default: OpenSSL natively, BearSSL on WebAssembly; Jamfile /webcpp/crypto//crypto /webcpp/crypto//gcm-default. Example: example/store_token.cpp. - [Encrypt a large file or a stream](https://webcpporg.github.io/libs/crypto/#crypto-gcm-incremental): `aes256_gcm`: records, or `begin_seal`, `update` and `result` (webcpp::crypto::ciphers); backend the default; Jamfile /webcpp/crypto//crypto /webcpp/crypto//gcm-default. Example: example/sealed_records.cpp. - [Tell a forged message from a malformed one](https://webcpporg.github.io/libs/crypto/#crypto-errors): `error` (webcpp::crypto); backend any; Jamfile /webcpp/crypto//crypto. Example: example/failure_reasons.cpp. - [Turn a sequential id into an opaque reference](https://webcpporg.github.io/libs/crypto/#crypto-block): `aes256` (webcpp::crypto::ciphers); backend ctaes, or OpenSSL natively and on WASI; Jamfile /webcpp/crypto//crypto /third_party//ctaes. Example: example/order_reference.cpp. - [Prove who wrote a message posted to a relay](https://webcpporg.github.io/libs/crypto/#crypto-p2p-signed): `keypair::sign(crypto::schnorr, message)`, `crypto::verify` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/signed_message.cpp. -- [Check a software update or a licence file](https://webcpporg.github.io/libs/crypto/#crypto-everyday-update): `keypair::sign(crypto::ecdsa_sha256, message)`, `public_key::make`, `crypto::verify` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/signed_update.cpp. +- [Check a software update or a licence file](https://webcpporg.github.io/libs/crypto/#crypto-everyday-update): `keypair::sign(crypto::ecdsa_sha256, message)`, `public_key::from_bytes`, `crypto::verify` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/signed_update.cpp. - [Agree on a key with a peer through a relay that sees everything](https://webcpporg.github.io/libs/crypto/#crypto-p2p-session): `keypair::agree_hashed` (SHA-256 of the shared point), then HKDF on Boost.Hash2 and `aes256_gcm` (webcpp::crypto::curves::secp256k1); backend libsecp256k1, and AES-GCM's default; Jamfile /webcpp/crypto//crypto /third_party//secp256k1 /webcpp/crypto//gcm-default. Example: example/ecdh_session.cpp. - [Derive a Nostr direct message's conversation key (NIP-44; the format is a domain library's)](https://webcpporg.github.io/libs/crypto/#crypto-p2p-nostr-dm): `keypair::agree`, then HKDF on Boost.Hash2 (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/ecdh_x_coordinate.cpp. -- [Find who signed a message or a transaction without being sent their key (Ethereum's signatures)](https://webcpporg.github.io/libs/crypto/#crypto-wallets-recovery): `keypair::sign(crypto::ecdsa_sha256_recoverable, message)`, `recover` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/recover_signer.cpp. -- [Derive child keys for a watch-only wallet (BIP 32's derivation is a domain library's)](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-tweaks): `seckey_tweak_add`, `pubkey_tweak_add` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/key_tweak.cpp. +- [Find who signed a message or a transaction without being sent their key (Ethereum's signatures)](https://webcpporg.github.io/libs/crypto/#crypto-wallets-recovery): `keypair::sign(crypto::ecdsa_keccak256_recoverable, message)`, `recover` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1 /third_party//xkcp. Example: example/ethereum_personal_sign.cpp. +- [Derive child keys for a watch-only wallet (BIP 32's derivation is a domain library's)](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-tweaks): `secret_key_tweak_add`, `public_key_tweak_add` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/key_tweak.cpp. - [Store or exchange a secp256k1 key with OpenSSL or a config file](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-formats): `encode_spki`, `decode_spki`, `encode_pkcs8`, `decode_pkcs8`; `webcpp::crypto::pem::armour`, `unarmour` (webcpp::crypto::curves::secp256k1); backend libsecp256k1, libsodium for PEM; Jamfile /webcpp/crypto//crypto /third_party//secp256k1 /webcpp/crypto//pem-default. Example: example/secp256k1_key_formats.cpp. - [Make a peer-to-peer connection's key exchange look like random bytes (BIP 324's transport; its packets are a domain library's)](https://webcpporg.github.io/libs/crypto/#crypto-p2p-v2): `ellswift_create`, `ellswift_decode`, `ellswift_xdh` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/ellswift_handshake.cpp. -- [Publish one donation address that never shows two payments as related (BIP 352's addresses and transactions are a domain library's)](https://webcpporg.github.io/libs/crypto/#crypto-wallets-silent): `create_outputs`, `make_prevouts_summary`, `scan_outputs` (webcpp::crypto::curves::secp256k1::silent_payments); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/silent_payment.cpp. -- [Require two devices to sign for a wallet, with one ordinary signature on the chain](https://webcpporg.github.io/libs/crypto/#crypto-wallets-musig): `key_aggregate`, `nonce_gen`, `partial_sign`, `partial_signature_aggregate` (webcpp::crypto::curves::secp256k1::musig); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/musig_wallet.cpp. -- [Make and keep a wallet's key](https://webcpporg.github.io/libs/crypto/#crypto-wallets-key): `keypair::make`, `keypair::public_key`, `public_key::xonly`, `public_key::compressed`; `aes256_gcm` at rest (webcpp::crypto::curves::secp256k1); backend libsecp256k1, and AES-GCM's default; Jamfile /webcpp/crypto//crypto /third_party//secp256k1 /webcpp/crypto//gcm-default. Example: example/wallet_key.cpp. +- [Publish one donation address that never shows two payments as related (BIP 352's addresses and transactions are a domain library's)](https://webcpporg.github.io/libs/crypto/#crypto-wallets-silent): `create_outputs`, `make_previous_outputs_summary`, `scan_outputs` (webcpp::crypto::curves::secp256k1::silent_payments); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/silent_payment.cpp. +- [Require two devices to sign for a wallet, with one ordinary signature on the chain](https://webcpporg.github.io/libs/crypto/#crypto-wallets-musig): `key_aggregate`, `generate_nonce`, `partial_sign`, `partial_signature_aggregate` (webcpp::crypto::curves::secp256k1::musig); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/musig_wallet.cpp. +- [Make and keep a wallet's key](https://webcpporg.github.io/libs/crypto/#crypto-wallets-key): `keypair::from_secret`, `keypair::public_key`, `public_key::xonly`, `public_key::compressed`; `aes256_gcm` at rest (webcpp::crypto::curves::secp256k1); backend libsecp256k1, and AES-GCM's default; Jamfile /webcpp/crypto//crypto /third_party//secp256k1 /webcpp/crypto//gcm-default. Example: example/wallet_key.cpp. - [Sign a Bitcoin SegWit v0 input (a domain library's job)](https://webcpporg.github.io/libs/crypto/#crypto-wallets-der): `keypair::sign(crypto::ecdsa_sha256, crypto::prehashed{sighash})`, `to_der`, `is_low_s`, `normalize_low_s` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/bitcoin_sighash.cpp. - [Derive a Bitcoin Taproot output key and spend by key path (a domain library's job)](https://webcpporg.github.io/libs/crypto/#crypto-wallets-taproot): `tweak_xonly`, `keypair::tweak_xonly` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/taproot_tweak.cpp. -- [Sign where allocation is restricted to the program's arena](https://webcpporg.github.io/libs/crypto/#crypto-memory): `keypair::make(secret, resource)` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/arena_signer.cpp. +- [Sign where allocation is restricted to the program's arena](https://webcpporg.github.io/libs/crypto/#crypto-memory): `keypair::from_secret(secret, resource)` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/arena_signer.cpp. - [Keep every allocation of OpenSSL's in the program's arena](https://webcpporg.github.io/libs/crypto/#crypto-memory-openssl): `openssl_memory_resource`, `backends::openssl::install_memory_functions` (webcpp::crypto); backend OpenSSL, natively; Jamfile `/webcpp/crypto//crypto` in the program; in the project requirements, `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE` and `/webcpp/crypto//openssl`. Example: example/openssl_memory.cpp. - [Seed BearSSL's own generator for code that calls BearSSL directly](https://webcpporg.github.io/libs/crypto/#crypto-entropy-bearssl): `random_device::fill` (webcpp::crypto); backend BearSSL's C API; Jamfile /webcpp/crypto//crypto /third_party//bearssl. Example: example/bearssl_prng.cpp. -- [Hash, or compute an HMAC](https://webcpporg.github.io/libs/crypto/#crypto-overview-hash2): `boost::hash2::sha2_256`, `hmac_sha2_256` (Boost.Hash2, not this library); backend none; Jamfile `/webcpp/crypto//crypto` brings Boost's headers. Example: example/equal_hmac.cpp. -- [Sign and verify with Ed25519 (RFC 8032), or sign a large message in pieces with Ed25519ph](https://webcpporg.github.io/libs/crypto/#crypto-ed25519): `keypair::make`, `keypair::generate`, `keypair::sign(crypto::eddsa, message)`, `crypto::verify`; `ph` (webcpp::crypto::curves::ed25519); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//ed25519-default. Example: example/ed25519_sign.cpp. -- [Agree a shared secret with a peer's public key (X25519, RFC 7748), or with the X25519 form of an Ed25519 key](https://webcpporg.github.io/libs/crypto/#crypto-x25519): `public_key`, `agree`; `curves::ed25519::to_x25519_public`, `curves::ed25519::keypair::x25519_secret` (webcpp::crypto::curves::x25519); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//x25519-default. Example: example/x25519_agree.cpp. -- [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::make`, `kx_keypair::generate`, `client_session_keys`, `server_session_keys` (webcpp::crypto::curves::x25519); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//kx-default. Example: example/kx_session.cpp. +- [Hash, or compute an HMAC](https://webcpporg.github.io/libs/crypto/#crypto-overview-hash2): `boost::hash2::sha2_256`, `hmac_sha2_256` (Boost.Hash2, not this library); backend none; Jamfile `/webcpp/crypto//crypto` brings Boost's headers. Example: example/constant_time_equal_hmac.cpp. +- [Sign and verify with Ed25519 (RFC 8032), or with Ed25519ph a message's SHA-512 or a large message in pieces](https://webcpporg.github.io/libs/crypto/#crypto-ed25519): `keypair::from_secret`, `keypair::generate`, `keypair::sign(crypto::eddsa, message)`, `keypair::sign(crypto::eddsa_prehashed, crypto::prehashed{digest})`, `crypto::verify`; `prehashed_signer` (webcpp::crypto::curves::ed25519); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//ed25519-default. Example: example/ed25519_sign.cpp. +- [Agree a shared secret with a peer's public key (X25519, RFC 7748), or with the X25519 form of an Ed25519 key](https://webcpporg.github.io/libs/crypto/#crypto-x25519): `keypair::from_secret`, `keypair::generate`, `public_key::from_bytes`, `keypair::agree`; `curves::ed25519::keypair::to_x25519`, `curves::ed25519::public_key::to_x25519`, `crypto::to_x25519` (webcpp::crypto::curves::x25519); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//x25519-default. Example: example/x25519_agree.cpp. +- [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): `ed25519::encode_spki`, `decode_spki`, `encode_pkcs8`, `decode_pkcs8`, the same in `x25519`; `webcpp::crypto::pem::armour`, `unarmour` (webcpp::crypto::curves); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//ed25519-default /webcpp/crypto//x25519-default /webcpp/crypto//pem-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<>`: `make`, `seal`, `open` (webcpp::crypto::ciphers); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//xchacha20_poly1305-default. Example: example/xchacha_seal.cpp. -- [Encrypt a record or a file under one secret key, each with a random nonce, in libsodium's secret-box format](https://webcpporg.github.io/libs/crypto/#crypto-secretbox): `secretbox<>`, `secretbox_xchacha20poly1305<>`: `make`, `seal`, `open` (webcpp::crypto::ciphers); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//secretbox_xsalsa20poly1305-default. 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::make`, `box::seal`, `box::open` (webcpp::crypto::hybrid); 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::hybrid); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//sealed_box-default. Example: example/file_share.cpp. -- [Share a file with someone known only by a public key, as a file-sharing app does](https://webcpporg.github.io/libs/crypto/#crypto-everyday-files): `ciphers::secretbox<>` for the file under a key drawn for it, `hybrid::sealed_box::seal` for that key (webcpp::crypto); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//secretbox_xsalsa20poly1305-default /webcpp/crypto//sealed_box-default /webcpp/crypto//x25519-default. Example: example/file_share.cpp. -- [Make and keep a P-256 key pair, and import a browser's public key (WebCrypto's raw form), as webcpp::trystero's peers do](https://webcpporg.github.io/libs/crypto/#crypto-p256-keys): `keypair::make`, `keypair::generate`, `keypair::public_key`, `keypair::secret`, `public_key::make` (webcpp::crypto::curves::p256); backend BearSSL; Jamfile /webcpp/crypto//crypto /webcpp/crypto//p256-default. Example: example/p256_keys.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. +- [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. +- [Share a file with someone known only by a public key, as a file-sharing app does](https://webcpporg.github.io/libs/crypto/#crypto-everyday-files): `secret_key_encryption::secretbox<>` for the file under a key drawn for it, `public_key_encryption::sealed_box::seal` for that key (webcpp::crypto); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//secretbox_xsalsa20poly1305-default /webcpp/crypto//sealed_box-default /webcpp/crypto//x25519-default. Example: example/file_share.cpp. +- [Make and keep a P-256 key pair, and import a browser's public key (WebCrypto's raw form), as webcpp::trystero's peers do](https://webcpporg.github.io/libs/crypto/#crypto-p256-keys): `keypair::from_secret`, `keypair::generate`, `keypair::public_key`, `keypair::secret`, `public_key::from_bytes` (webcpp::crypto::curves::p256); backend BearSSL; Jamfile /webcpp/crypto//crypto /webcpp/crypto//p256-default. Example: example/p256_keys.cpp. - [Sign what a browser's WebCrypto verifies and verify what it signs (ECDSA on P-256 with SHA-256), low S where a protocol requires it, as webcpp::trystero's handshakes](https://webcpporg.github.io/libs/crypto/#crypto-p256-ecdsa): `keypair::sign(crypto::ecdsa_sha256, message)`, `crypto::verify`, `is_low_s`, `normalize_low_s`; `to_der`, `from_der` for X.509 (webcpp::crypto::curves::p256); backend BearSSL; Jamfile /webcpp/crypto//crypto /webcpp/crypto//p256-default. Example: example/p256_sign.cpp. - [Agree on a key with a browser's WebCrypto (ECDH on P-256, deriveBits), then derive the session's keys with HKDF, as Trystero 0.27.0's pairwise keys are derived](https://webcpporg.github.io/libs/crypto/#crypto-p256-ecdh): `keypair::agree`; `webcpp::hash::hkdf` for the keys (webcpp::crypto::curves::p256); backend BearSSL; Jamfile /webcpp/crypto//crypto /webcpp/crypto//p256-default. Example: example/p256_ecdh.cpp. - [Export or import a P-256 key in the forms OpenSSL and WebCrypto's spki and pkcs8 use (SPKI, PKCS#8), as DER or PEM text](https://webcpporg.github.io/libs/crypto/#crypto-p256-formats): `encode_spki`, `decode_spki`, `encode_pkcs8`, `decode_pkcs8`; `webcpp::crypto::pem::armour`, `unarmour` (webcpp::crypto::curves::p256); backend BearSSL, libsodium for PEM; Jamfile /webcpp/crypto//crypto /webcpp/crypto//p256-default /webcpp/crypto//pem-default. Example: example/p256_key_formats.cpp. @@ -359,26 +400,27 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - example/aes256_gcm_bearssl.cpp: Seals one zero block with AES-256-GCM on BearSSL, names the backend in the type, checks the result against test case 14 of the GCM specification, and opens it again. Naming the backend pins the implementation, so the same bytes and the same code run on every target. - example/arena_signer.cpp: Gives the secp256k1 key pair its one allocation from a fixed buffer owned by the program, and counts it. With a null upstream nothing else can allocate, so a program with strict memory limits knows exactly what the library needs and that it never reaches for the heap. -- example/async_seal.cpp: An audit record sealed and opened through an event loop: the GCM specification's test case 16 (AES-256, 12-byte IV, additional data), a published key, never a real one. Each completion runs from the loop's run, after the call that started it has returned, on every target; the handler of the seal prints the tag and starts the open, the handler of the open compares the plaintext. The loop ends when no operation is pending: nothing waits for a time. +- example/async_seal.cpp: An audit record sealed and opened through an event loop: the GCM specification's test case 16 (AES-256, 12-byte nonce, associated data), a published key, never a real one. Each completion runs from the loop's run, after the call that started it has returned, on every target; the handler of the seal prints the tag and starts the open, the handler of the open compares the plaintext. The loop ends when no operation is pending: nothing waits for a time. tag::program[] - example/async_sign.cpp: A coroutine on an event loop makes an Ed25519 key pair from RFC 8032's second test seed (a published seed, never a real key), signs the test's message with crypto::eddsa, and verifies the signature with the public key alone, each step a co_await of an asynchronous function with use_awaitable. The coroutine ends, and the loop with it, when the last completion has run: nothing waits for a time. - 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::ecdsa_sha256. A taproot sighash, BIP341's tagged hash, is the message of crypto::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 secret key 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/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/constant_time_equal_hmac.cpp: Checks an HMAC-SHA-256 tag from Boost.Hash2 with webcpp::crypto::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. - example/ecdsa_der.cpp: Signs with ECDSA the way a domain library does: a sighash computed by the library, a 64-byte signature, its strict DER form for the wire, and the low-S rule. The same signature has a twin with S replaced by n - S; accepting both makes transaction ids malleable, so verifiers refuse the high-S twin. -- example/ed25519_sign.cpp: Signs RFC 8032's second Ed25519 test with a key pair made from its seed and verifies the signature with the public key alone, `key.sign(crypto::eddsa, message)` and `crypto::verify(crypto::eddsa, signature, message, public_key)`; then signs the message "abc" given in two pieces with Ed25519ph, as RFC 8032's Ed25519ph test does, and verifies it with `verify(signature, public_key)`. Prints each key and signature in hex. +- example/ed25519_sign.cpp: Signs RFC 8032's second Ed25519 test with a key pair made from its seed and verifies the signature with the public key alone, `key.sign(crypto::eddsa, message)` and `crypto::verify(crypto::eddsa, signature, message, public_key)`; then signs the message "abc" given in two pieces with Ed25519ph's streaming signer, `curves::ed25519::prehashed_signer`, as RFC 8032's Ed25519ph test does, and verifies it with `verify(signature, public_key)`; then signs the message's SHA-512, a digest the program has, under the scheme `crypto::eddsa_prehashed`, which gives the same signature, and verifies it with `crypto::verify(crypto::eddsa_prehashed, signature, crypto::prehashed{digest}, public_key)`. Prints each key and signature in hex, and whether the two Ed25519ph signatures are equal. - example/ellswift_handshake.cpp: The first messages of a peer-to-peer connection whose key exchange looks like random bytes, as BIP 324's transport starts: each peer sends its public key as an ElligatorSwift encoding, 64 bytes with no recognisable prefix, and both compute the same shared secret from the two encodings. The secrets and the randomness are fixed here, so that the program runs the same each time; a real program draws all four from random_device. Nothing random is printed. -- example/equal_hmac.cpp: Checks an HMAC-SHA-256 tag from Boost.Hash2 with webcpp::crypto::equal, the constant-time comparison. Comparing tags with == or memcmp stops at the first difference, and that timing lets an attacker guess a valid tag one byte at a time. -- example/failure_reasons.cpp: Shows the three ways AES-GCM can refuse a message: a tampered ciphertext, an IV of the wrong size and a tag of the wrong size. A program must tell the first from the others: only authentication_failed means someone changed the data, and open then wipes the plaintext so that no unauthenticated bytes are ever used. -- example/file_share.cpp: A file-sharing app shares a file with a recipient it knows only by an X25519 public key: the file is sealed once in a secret box under a key drawn for this file, and that file key is sealed to the recipient's public key in a sealed box. The upload holds both; only the recipient's secret key opens the file key, and the file key opens the file. Prints what the recipient reads, the sizes on the wire, and the refusals of a changed upload and of another key pair. +- example/ethereum_personal_sign.cpp: Signs a message as an Ethereum wallet's personal_sign does, then finds the signer's address from the signature alone. The program builds EIP-191's digest itself with webcpp::hash's Keccak-256, signs it as crypto::prehashed with crypto::ecdsa_keccak256_recoverable, prints r, s and v, recovers the key and prints its address. crypto computes none of the protocol's encodings: not the digest (EIP-191's here, EIP-712's or a transaction's elsewhere), not v (27 + the recovery id for personal_sign, 35 + 2 x chain_id + the id for EIP-155, the id itself as a typed transaction's yParity), not the address. The key and the message are web3.js's documented example (web3.eth.accounts.sign('Some data', ...)), whose signature this prints. +- example/failure_reasons.cpp: Shows the three ways AES-GCM can refuse a message: a tampered ciphertext, a nonce of the wrong size and a tag of the wrong size. A program must tell the first from the others: only authentication_failed means someone changed the data, and open then wipes the plaintext so that no unauthenticated bytes are ever used. +- example/file_share.cpp: A file-sharing app shares a file with a recipient it knows only by an X25519 public key: the file is sealed once in a secret box under a key drawn for this file, and that file key is sealed to the recipient's public key in a sealed box. The upload holds both; only the recipient's key pair opens the file key, and the file key opens the file. Prints what the recipient reads, the sizes on the wire, and the refusals of a changed upload and of another key pair. - example/four_forms.cpp: Makes RFC 6979's P-256 key pair (a published scalar, never a real key), signs "sample" with crypto::ecdsa_sha256 and verifies the signature, each operation in its four forms: the member, its free form, and the asynchronous member and its free form, which complete through an event loop. RFC 6979's nonce makes the four signatures the same bytes, and the four verifications agree. - example/key_formats.cpp: Reads RFC 8410's Ed25519 private key in PEM (section 10.3), as OpenSSL or WebCrypto export it, writes its public key as PEM, which is the RFC's section 10.1 to the character, and signs with it; writes an X25519 key pair's public key the same way; and refuses the RFC's version 2 of the private key, which carries the public key too. Prints the PEM texts and each verdict. - example/key_tweak.cpp: A watch-only wallet: a server that holds the wallet's public key and no secret gives each payment a fresh key, and the signing device, which holds the secret, derives the same keys' secrets. Both add the same tweak, one to the public key and one to the secret key; the device's tweaked key pair signs (BIP 340), and the signature verifies under the server's tweaked public key. The tweak here is an HMAC-SHA-256 of the public key and the payment's number under a chain code both sides share and no one else sees; BIP 32 derives such tweaks its own way, with HMAC-SHA-512, and is a domain library's. - example/kx_session.cpp: A chat app's client and server, each with a crypto_kx key pair made from libsodium's kx test's seeds, exchange public keys and compute their session keys; the client seals a message with its transmit key and the server opens it with its receive key, on ChaCha20-Poly1305; a peer key of low order is refused. Prints the public keys and the client's session keys in hex. - example/musig_network.cpp: The wallet of musig_wallet.cpp with its two devices apart: every public piece of BIP 327's MuSig2 crosses the network as bytes. Each device sends its public nonce, 66 bytes, to a coordinator, which holds no secret: it sums the nonces and sends the aggregate nonce, 66 bytes, back. Each device then signs and sends its partial signature, 32 bytes; the coordinator parses each part and checks it with partial_signature_verify before it adds the parts, so that a part damaged on the way, or a faulty signer's, is refused by name rather than spoiling the signature. The devices' secrets are fixed here, so that the program runs the same each time; the nonces are fresh in every run, and nothing random is printed. -- example/musig_taproot.cpp: The wallet of musig_wallet.cpp receiving to a Taproot output (BIP 341) with a key path only: the two signers' aggregate key is the internal key, and the output key on the chain is that key tweaked by its TapTweak tagged hash. The tweak is applied to the aggregate key with tweak_xonly_add before any nonce is made, since the session and the partial signatures need the key as tweaked, and nonce_gen mixes in the key it is given (BIP 327's NonceGen takes it only as an optional input); then the signers run MuSig2's two rounds as before, and the signature verifies under the output key and not under the internal one. The tweak's hash is the protocol's, which a domain library computes; it is shown here with webcpp::hash's SHA-256. The devices' secrets are fixed here, so that the program runs the same each time; the nonces are fresh in every run, and nothing random is printed. -- example/musig_wallet.cpp: A wallet split across two devices, a phone and a laptop, whose coins move only when both sign (BIP 327's MuSig2): the two public keys are sorted and aggregated into one; each device makes a nonce and sends its public half; each signs its part once every public nonce is in; the parts add up to one BIP 340 signature under the one x-only key, which on the chain looks like any single signer's. The devices' secrets are fixed here, so that the program runs the same each time; a real wallet draws them from crypto's random device. The nonces are fresh in every run, drawn inside nonce_gen; nothing random is printed. +- example/musig_taproot.cpp: The wallet of musig_wallet.cpp receiving to a Taproot output (BIP 341) with a key path only: the two signers' aggregate key is the internal key, and the output key on the chain is that key tweaked by its TapTweak tagged hash. The tweak is applied to the aggregate key with tweak_xonly_add before any nonce is made, since the session and the partial signatures need the key as tweaked, and generate_nonce mixes in the key it is given (BIP 327's NonceGen takes it only as an optional input); then the signers run MuSig2's two rounds as before, and the signature verifies under the output key and not under the internal one. The tweak's hash is the protocol's, which a domain library computes; it is shown here with webcpp::hash's SHA-256. The devices' secrets are fixed here, so that the program runs the same each time; the nonces are fresh in every run, and nothing random is printed. +- example/musig_wallet.cpp: A wallet split across two devices, a phone and a laptop, whose coins move only when both sign (BIP 327's MuSig2): the two public keys are sorted and aggregated into one; each device makes a nonce and sends its public half; each signs its part once every public nonce is in; the parts add up to one BIP 340 signature under the one x-only key, which on the chain looks like any single signer's. The devices' secrets are fixed here, so that the program runs the same each time; a real wallet draws them from crypto's random device. The nonces are fresh in every run, drawn inside generate_nonce; nothing random is printed. - example/opened_in_two_passes.cpp: Opens a sealed file of 1 MiB without holding it whole, in two passes over the file: the first authenticates every piece of 64 KiB and verifies the tag, the second decrypts the same pieces. No byte of plaintext leaves the object before the tag matched. The file is any std::istream read twice: a program reads its own disk through a std::ifstream; this one keeps the file in a std::stringstream, so that it runs where the program has no directory (WASI). - example/openssl_memory.cpp: Sends every allocation of OpenSSL's to the program's own memory resource, natively, then seals and opens one block with AES-256-GCM on OpenSSL, on a worker thread as an audio engine's or a server's would. Built with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE, /webcpp/crypto//openssl and threads (example/Jamfile). - example/order_reference.cpp: Turns a sequential order id into an opaque 16-byte reference with the raw AES block cipher, and back. Customers then cannot guess other orders' numbers. This is NOT authenticated encryption: a forged reference still decrypts, to garbage, so the program checks the padding. @@ -390,16 +432,16 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - 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. -- example/sealed_records.cpp: Seals data in pieces two ways: one message in chunks with the incremental seal, and a stream as separate records, each bound to its position and to whether it is the last. The number in the additional data stops records from being reordered or replayed at another position, and the last-record flag stops a stream from being cut short without being noticed. Each stream has a key of its own, drawn when the stream starts: the counter IVs 0, 1, 2 of one stream are safe only because no other stream seals under its key. +- example/sealed_records.cpp: Seals data in pieces two ways: one message in chunks with the incremental seal, and a stream as separate records, each bound to its position and to whether it is the last. The number in the associated data stops records from being reordered or replayed at another position, and the last-record flag stops a stream from being cut short without being noticed. Each stream has a key of its own, drawn when the stream starts: the counter nonces 0, 1, 2 of one stream are safe only because no other stream seals under its key. - example/secp256k1_key_formats.cpp: A server's secp256k1 key in files that OpenSSL also reads: its public key written as PEM SPKI for a configuration file that its clients read, and read back; its key pair written as PEM PKCS#8 for the server's own key file, which is never printed, and read back. The secret is the fixed 0x11 repeated, so that the output is fixed: a real server draws its own. - example/signed_message.cpp: An author signs a message with a BIP340 Schnorr signature and a reader verifies it with the author's public key alone. No server vouches for the message: any change to the text breaks the signature, so peers can trust what they receive from untrusted relays. - example/signed_update.cpp: Checks an update with the publisher's ECDSA signature before installing it. The public key is shipped inside the program, so a tampered download, or one from a mirror that is not the publisher, fails the check and is never run. -- example/silent_payment.cpp: A donation page that publishes one reusable address (BIP 352's silent payments): a pair of public keys, scan and spend. A donor's wallet with one input pays it: the output key it makes is new, tied to the donor's input. The recipient scans the transaction's outputs with its scan key pair, finds the payment, and makes the key pair that spends it with seckey_tweak_add. A second donation to the same address gives an output key unrelated to the first, so that an onlooker sees no two payments to one address. The address's encoding, the transaction and the smallest outpoint's choice are a wallet's (a domain library's); the keys are fixed here, so that the program runs the same each time, where a real wallet draws them from crypto's random device. -- example/store_token.cpp: Stores a user's API token encrypted in a database row, bound to the user's id. The id is additional data: authenticated but not encrypted, so a row copied to another user's record no longer opens. Without that binding a database writer could swap the rows of two users. +- example/silent_payment.cpp: A donation page that publishes one reusable address (BIP 352's silent payments): a pair of public keys, scan and spend. A donor's wallet with one input pays it: the output key it makes is new, tied to the donor's input. The recipient scans the transaction's outputs with its scan key pair, finds the payment, and makes the key pair that spends it with secret_key_tweak_add. A second donation to the same address gives an output key unrelated to the first, so that an onlooker sees no two payments to one address. The address's encoding, the transaction and the smallest outpoint's choice are a wallet's (a domain library's); the keys are fixed here, so that the program runs the same each time, where a real wallet draws them from crypto's random device. +- example/store_token.cpp: Stores a user's API token encrypted in a database row, bound to the user's id. The id is associated data: authenticated but not encrypted, so a row copied to another user's record no longer opens. Without that binding a database writer could swap the rows of two users. - example/taproot_tweak.cpp: Tweaks an internal key as Bitcoin's Taproot does for a key-path-only output (BIP341): the tweak is a tagged hash of the internal key, and the output key commits to it. The same tweak applied to the key pair lets the owner sign for the output key, so spending needs no script. - example/wallet_key.cpp: Makes a wallet's key pair from a random secret, then seals the secret at rest with AES-256-GCM and restores it. A secret that sits unencrypted on disk, or lingers in memory after use, is the first thing an attacker looks for, so the copies are wiped as soon as they are not needed. -- example/x25519_agree.cpp: Alice and Bob of RFC 7748 section 6.1 agree a shared secret from each other's public keys; then two Ed25519 key pairs, made from RFC 8032's seeds, agree one through their X25519 forms; and a peer key of low order is refused. Prints each public key and the shared secrets in hex. -- example/xchacha_seal.cpp: A chat app, in the browser and natively alike, encrypts each message of a conversation under the conversation's key with XChaCha20-Poly1305, a fresh 24-byte nonce drawn at random per message and the conversation's id as additional data; a message changed on the way, or moved to another conversation, does not open. Prints what the recipient reads. +- example/x25519_agree.cpp: Alice and Bob of RFC 7748 section 6.1, each an X25519 key pair made from a secret key, agree a shared secret from each other's public keys; then two Ed25519 key pairs, made from RFC 8032's seeds, agree one through their X25519 forms; and a peer key of low order is refused. Prints each public key and the shared secrets in hex. +- example/xchacha_seal.cpp: A chat app, in the browser and natively alike, encrypts each message of a conversation under the conversation's key with XChaCha20-Poly1305, a fresh 24-byte nonce drawn at random per message and the conversation's id as associated data; a message changed on the way, or moved to another conversation, does not open. Prints what the recipient reads. ## Optional diff --git a/doc/memory.adoc b/doc/memory.adoc index 737f688b..7901d0b3 100644 --- a/doc/memory.adoc +++ b/doc/memory.adoc @@ -9,11 +9,11 @@ An audio worklet, a game loop or an embedded device must not allocate on its hot path, or must allocate only from its own arena. crypto's own code allocates -one thing: a secp256k1 key pair's signing context, once, in `keypair::make` -and in `generate`, which allocates through `make`, +one thing: a secp256k1 key pair's signing context, once, in `keypair::from_secret` +and in `generate`, which allocates through `from_secret`, from the `std::pmr::memory_resource` the program passes, which must outlive the key pair. A resource that cannot allocate throws, as the standard has it, and -`make` lets the exception through; without exceptions such a resource ends the +`from_secret` lets the exception through; without exceptions such a resource ends the process. It never returns null (<> says why). Every buffer is the caller's. @@ -21,18 +21,18 @@ buffer is the caller's. `begin_seal`, `update`, `result`, `begin_open`, `authenticate`, `verify`, `end_open`, `encrypt`, `decrypt` (the block cipher's and the incremental open's), `fill`, the signatures (hedged and recoverable too), `agree`, -`agree_hashed`, `agree_point`, the verifications, `recover`, `public_key::make` +`agree_hashed`, `agree_point`, the verifications, `recover`, `public_key::from_bytes` and the public key's byte forms, the tweaks and negations, -`pubkey_combine` (in a `workspace` the caller lends), the SPKI and PKCS#8 +`public_key_combine` (in a `workspace` the caller lends), the SPKI and PKCS#8 encoders and decoders (`decode_pkcs8` makes a key pair, whose context is the one allocation above), and `ellswift_*`, MuSig2's functions and silent payments' (each over a `workspace` the caller lends, where it takes one). The counting tests of `test/` prove it, every `operator new` and the C library's allocator counted. -* *BearSSL and ctaes allocate nothing,* `make` included: the key schedule lives +* *BearSSL and ctaes allocate nothing,* `from_key` included: the key schedule lives inside the object. -* *OpenSSL's `make` allocates its cipher context through OpenSSL's own -allocator,* outside the program's resource; the first `make` of a process also +* *OpenSSL's `from_key` allocates its cipher context through OpenSSL's own +allocator,* outside the program's resource; the first `from_key` of a process also initialises OpenSSL. The test `allocation_openssl` counts and prints these allocations on each target at every run, and fails if a message allocates; the count depends on the target and on OpenSSL's build, so the page does not copy @@ -71,7 +71,7 @@ By default OpenSSL allocates with the C library's `malloc`, outside every allocator of the program's. A native program that keeps its memory in its own arena, such as an audio engine whose real-time thread may not touch the system's heap, or an embedded server that gives each part a fixed budget, -finds OpenSSL bypassing that arena: its first `make` initialises OpenSSL, which +finds OpenSSL bypassing that arena: its first `from_key` initialises OpenSSL, which takes many blocks from the system's heap, and Beast's TLS and libdatachannel's DTLS, which link the same OpenSSL, allocate there for every connection. The arena's accounting is then wrong, a budget is exceeded with no @@ -136,33 +136,33 @@ the whole exchange: the key, the certificate, both contexts, the handshake, a record each way and every free. * *Nothing else may call `CRYPTO_set_mem_functions`.* If another library has called it before, `install_memory_functions()` returns -`memory_functions_refused`; if it calls it after the install, the next `make` +`memory_functions_refused`; if it calls it after the install, the next `from_key` returns `memory_functions_not_installed`, and only when that call has finished -before the `make`. The damage is done by then: OpenSSL accepts the replacement +before the `from_key`. The damage is done by then: OpenSSL accepts the replacement after the install, and from then on frees the blocks it took from the resource through the other party's `free`, which corrupts that party's heap; the -error that `make` then returns does not undo it. +error that `from_key` then returns does not undo it. * *`memory_functions_refused` although the install is the first statement of `main`* means that something used OpenSSL before `main`: a static object of another library. OpenSSL then keeps its own `malloc` for the rest of the process. A libcrypto DLL, which webcpp never builds (a program built without b2), is refused the same way. -* *`memory_functions_not_installed` from a `make`* means that the install was +* *`memory_functions_not_installed` from a `from_key`* means that the install was not called, or that something replaced OpenSSL's functions after it. * *One module.* The program's code that uses crypto's OpenSSL backend lives in one module: a DLL, or a shared library of the program's that hides its symbols, that includes the backend's header has its own copy of crypto's -functions, and its `make` returns `memory_functions_not_installed`. An ELF +functions, and its `from_key` returns `memory_functions_not_installed`. An ELF shared library with default visibility usually binds to the executable's copy instead, but nothing guarantees it. * *Threads on Windows.* OpenSSL gives a thread's own blocks back when the thread ends, except on Windows, where the static libcrypto that webcpp always builds is never told that a thread ends. Every thread that used OpenSSL, a -`make`, Beast's TLS or libdatachannel's DTLS, leaves its error queue and its +`from_key`, Beast's TLS or libdatachannel's DTLS, leaves its error queue and its list of handlers in the resource, never given back, not even at exit, unless it calls `OPENSSL_thread_stop()` before it ends. A resource of a fixed size under a thread pool that replaces its threads, or a thread per connection, -then runs out over time, and the failure lands in a later `make` or inside a +then runs out over time, and the failure lands in a later `from_key` or inside a TLS handshake. The example's worker thread ends so, and so does the second thread of the test `everything`, whose exit check fails on Windows without it: + @@ -172,23 +172,23 @@ include::{examples}/openssl_memory.cpp[tag=thread,indent=0] ---- * *When the resource cannot allocate.* The resource must serve OpenSSL's initialisation, which the first use of OpenSSL in the process runs, usually the -first `make`. On an OpenSSL built with threads, which is MSVC's only build and +first `from_key`. On an OpenSSL built with threads, which is MSVC's only build and b2's `threading=multi` elsewhere, a failure during OpenSSL's base initialisation is not recoverable: OpenSSL reports it through its error queue, whose state needs the initialisation that is running, so OpenSSL re-enters its own initialisation and that call never returns. The process aborts on macOS, deadlocks on Linux and spins on Windows. Only an OpenSSL built without threads, b2's default on macOS and Linux, returns from that failure, and OpenSSL stays -unusable for the rest of the process: `make` gives `backend_failure` from then +unusable for the rest of the process: `from_key` gives `backend_failure` from then on. When the failing allocation is OpenSSL's base initialisation (with OpenSSL 3.5.9, its first lock), OpenSSL never registers its cleanup, and `OPENSSL_cleanup` frees nothing: the blocks it took meanwhile stay in the resource until the process ends, and the thread's error queue takes no entry from then on. The test `fail_init` pins this on an OpenSSL without threads and prints how many blocks stay; with threads, as `fail_init_threads`, it prints how -many blocks the first `make` took instead. After the initialisation, `make` +many blocks the first `from_key` took instead. After the initialisation, `from_key` gives `not_enough_memory` or `backend_failure`. `seal` and `open` allocate -nothing. A resource of a fixed size needs room for the first `make`, whose +nothing. A resource of a fixed size needs room for the first `from_key`, whose allocations the test `allocation_openssl` prints on each run. A resource reports that it cannot allocate as the standard has `do_allocate` report it, by throwing, `std::bad_alloc` or another exception, which the adapter turns diff --git a/doc/overview.adoc b/doc/overview.adoc index 08646c97..d66eb697 100644 --- a/doc/overview.adoc +++ b/doc/overview.adoc @@ -33,7 +33,9 @@ the scheme named at every call and a digest given only as has the member and its free form, and, where WebCrypto has the algorithm, their asynchronous forms, with one implementation (<>). -* *A constant-time `equal`* for tags and MACs, Boost.Hash2's included. +* *`constant_time_equal`* for tags and MACs, Boost.Hash2's included, and +*`erase_secret`*, which zeroes a buffer of the program's with stores the +optimiser keeps. * *The AES block cipher,* a building block for the rare case that needs one. The algorithms are not webcpp's. Each runs on a backend, a C library that @@ -68,19 +70,34 @@ Nostr rule) belongs to a domain library, which <> shows how to build. Its names are grouped by kind, one chapter each, and the headers mirror the namespaces as `/.hpp>`: -* `webcpp::crypto`: `random_device`, `equal`, `error` and the configuration; -the signatures' schemes, `prehashed`, `sign` and `verify` -(``), the key pair contract and `agree` -(``), `make` and `generate` -(``), and the asynchronous family -(``; <>, <>, -<>); -* `webcpp::crypto::ciphers`: `aes128`, `aes192`, `aes256`, `gcm`, `aes128_gcm` -and `aes256_gcm` (<>); +* `webcpp::crypto`: `random_device`, `constant_time_equal`, `erase_secret`, +`secret`, `error` and the configuration (<>); the +signatures' schemes, `prehashed` and `verify` (``), +the key pair concepts, `sign` and `agree` (``), the +factories `from_secret`, `from_bytes`, `from_key` and `generate` +(``), `supports_v`, whether a backend has an +algorithm on the target (``; <>), +and the asynchronous family (``; <>, +<>, <>); +* `webcpp::crypto::pem`: `armour`, `unarmour`, `armoured_size` and the labels, +a key's DER as PEM text (``; <>); +* `webcpp::crypto::ciphers`: `aes128`, `aes192`, `aes256`, `gcm`, `aes128_gcm`, +`aes256_gcm`, `chacha20_poly1305`, `chacha20_poly1305_original` and +`xchacha20_poly1305` (<>); +* `webcpp::crypto::secret_key_encryption`: `secretbox`, +`secretbox_xchacha20poly1305`, the box forms and `aead`, the AEAD contract +(<>); * `webcpp::crypto::curves::secp256k1`: key pairs, signatures, ECDH, the encodings and the x-only tweak on secp256k1 (<>); +* `webcpp::crypto::curves::ed25519` and `curves::x25519`: Ed25519's key pairs +and signatures, X25519's key pairs and agreement, and the conversion between +them (<>, <>); * `webcpp::crypto::curves::p256`: key pairs, ECDSA, ECDH and the encodings on P-256 (<>); +* `webcpp::crypto::public_key_encryption`: `box`, `box_xchacha20poly1305` and +`sealed_box` (<>); +* `webcpp::crypto::key_exchange`: `kx_keypair`, libsodium's `crypto_kx` +(<>); * `webcpp::crypto::backends`: the backends (<>). `` includes every header whose backend the program links. @@ -93,5 +110,6 @@ Hashing and HMAC are Boost.Hash2's: SHA-1, SHA-2, SHA-3, RIPEMD, BLAKE2 and examples use Hash2 wherever a hash is needed: a key derived with HKDF (link:https://www.rfc-editor.org/rfc/rfc5869[RFC 5869]) is written on Hash2's `hmac` in a few lines (<>). What crypto adds for Hash2's -users is `equal`: the `operator==` of Hash2's digests is `memcmp`, which is not -constant time, so a MAC is never checked with it (<>). +users is `constant_time_equal`: the `operator==` of Hash2's digests is `memcmp`, +which is not constant time, so a MAC is never checked with it +(<>). diff --git a/doc/p256.adoc b/doc/p256.adoc index 6e448538..8a4636f7 100644 --- a/doc/p256.adoc +++ b/doc/p256.adoc @@ -60,23 +60,24 @@ shared x, and passes only when WebCrypto disagrees on exactly those two. A P-256 secret key is a number, the *scalar* d, 32 bytes big-endian, between 1 and the group order n minus 1; the public key is the point d times the curve's generator (link:https://csrc.nist.gov/pubs/fips/186-5/final[FIPS -186-5]). `keypair::make(scalar)` makes a key pair from a scalar a program kept, +186-5]). `keypair::from_secret(scalar)` makes a key pair from a scalar a program kept, and refuses a scalar of another size with `invalid_key_size` and a scalar 0, n or above with `invalid_secret_key`: that check runs in webcpp, in time independent of the scalar, before BearSSL sees it. `keypair::generate()` draws the scalar from `random_device`. `secret()` gives the scalar back as a -`secret<32>`, which wipes itself, and `make` of it gives the same key pair: the +`secret<32>`, which wipes itself, and `from_secret` of it gives the same key pair: the way a program stores a key pair and loads it again. The key pair computes its public point once, when it is made, wipes the scalar when it is moved from and -destroyed, and answers `invalid_state` moved from. It is a `crypto::keypair`, -as every curve's is (<>). +destroyed, and answers `invalid_state` moved from. It is a +`crypto::signing_keypair` and a `crypto::agreement_keypair` +(<>). A `public_key` is a point that the type guarantees valid, kept as SEC 1's *uncompressed* form, 65 bytes: 04, then x and y (link:https://www.secg.org/sec1-v2.pdf[SEC 1, section 2.3.3]), the bytes WebCrypto's `exportKey("raw")` writes and `importKey("raw")` reads -(link:https://www.w3.org/TR/WebCryptoAPI/[W3C]). `public_key::make(bytes)` -makes one from those 65 bytes, `public_key::make(x, y)` from the two +(link:https://www.w3.org/TR/WebCryptoAPI/[W3C]). `public_key::from_bytes(bytes)` +makes one from those 65 bytes, `public_key::from_coordinates(x, y)` from the two coordinates, as a JSON Web Key carries them, and `uncompressed()` writes the 65 bytes back; the key pair's `public_key()` gives its own. A point refused is `invalid_public_key`: another size, another first byte, a coordinate not below @@ -85,8 +86,8 @@ and is copied freely. Each operation has its four forms, the member and its free form, synchronous and asynchronous, with the same work, errors and refusals -(<>); `public_key::make` and -`crypto::make` make the public key, synchronously only. An +(<>); `public_key::from_bytes` and +`crypto::from_bytes` make the public key, synchronously only. An asynchronous form needs `` and `/webcpp/asio//asio` in the Jamfile: @@ -96,10 +97,10 @@ asynchronous form needs `` and | Operation | Synchronous: the member; its free form | Asynchronous: the member; its free form | Make -| `keypair::make(scalar)` + -`crypto::make(scalar)` -| `keypair::async_make(executor, scalar, token)` + -`crypto::async_make(executor, scalar, token)` +| `keypair::from_secret(scalar)` + +`crypto::from_secret(scalar)` +| `keypair::async_from_secret(executor, scalar, token)` + +`crypto::async_from_secret(executor, scalar, token)` | Generate | `keypair::generate()` + @@ -165,8 +166,9 @@ begin, which is why SEC 1 has a peer's public key validated before it is used * The compressed form, 33 bytes that start with 02 or 03 (link:https://www.secg.org/sec1-v2.pdf[SEC 1, section 2.3.3]), is refused with `invalid_public_key`: BearSSL decodes uncompressed points alone. WebCrypto's -raw export is uncompressed, so a browser's key arrives in the form `make` -takes; a key a tool sends compressed is decompressed by that tool first. +raw export is uncompressed, so a browser's key arrives in the form +`from_bytes` takes; a key a tool sends compressed is decompressed by that tool +first. [#crypto-p256-ecdsa] ==== ECDSA @@ -205,15 +207,18 @@ public_key, token)` do the same through a completion, with the same inputs (<>). A signature has two forms. The *raw* form, 64 bytes, r then s at 32 bytes each -(link:https://standards.ieee.org/ieee/1363/2049/[IEEE 1363]), is the one -`sign` gives and `crypto::verify` takes: what WebCrypto signs and verifies +(link:https://standards.ieee.org/ieee/1363/2049/[IEEE 1363]), is the one a +`curves::p256::ecdsa_signature` holds, which `sign` gives and `crypto::verify` +takes, and `ecdsa_signature::from_bytes` makes from 64 bytes received: what +WebCrypto signs and verifies (link:https://www.w3.org/TR/WebCryptoAPI/[W3C]) and what a JSON Web Token's ES256 carries (link:https://www.rfc-editor.org/rfc/rfc7518#section-3.4[RFC 7518, section 3.4]). *DER*, 8 to 72 bytes: a SEQUENCE of two INTEGERs, is the form of X.509 certificates and OpenSSL (link:https://www.rfc-editor.org/rfc/rfc3279#section-2.2.3[RFC 3279, section 2.2.3]): `to_der(signature, output)` writes it into at least `max_der_size` -bytes and returns its length, and `from_der(bytes)` reads it back, accepting +bytes and returns its length, and `from_der(bytes)` reads it back into an +`ecdsa_signature`, accepting strict DER only, the encoding `to_der` writes, and refusing anything else with `invalid_signature`. @@ -394,7 +399,7 @@ uncompressed point. That is the SPKI WebCrypto exports, the named curve and the uncompressed form (link:https://www.w3.org/TR/WebCryptoAPI/#ecdsa-operations-export-key[W3C, ECDSA's export]); `decode_spki(bytes)` reads it back into a `public_key`, its -point checked as `public_key::make` checks it. +point checked as `public_key::from_bytes` checks it. * `encode_pkcs8(keypair, output)` writes 138 bytes: version 0, the same algorithm, and an ECPrivateKey of version 1 with the scalar and the uncompressed public key, without the curve inside it. That is the form OpenSSL @@ -402,7 +407,7 @@ writes for a key in its default uncompressed form (link:https://docs.openssl.org/master/man7/EVP_PKEY-EC/[OpenSSL's EVP_PKEY-EC]), and BearSSL's own encoder, `br_encode_ec_pkcs8_der`, writes the same bytes, which the tests compare; `decode_pkcs8(bytes)` reads it into a key pair, made -as `keypair::make` makes one. +as `keypair::from_secret` makes one. `max_spki_size` and `max_pkcs8_size`, 91 and 138, size the caller's buffers. The encoders copy what the key and the key pair hold, call no BearSSL code, diff --git a/doc/protecting_secrets.adoc b/doc/protecting_secrets.adoc new file mode 100644 index 00000000..8497c415 --- /dev/null +++ b/doc/protecting_secrets.adoc @@ -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) + +[#crypto-protecting-secrets] +=== Protecting secrets outside the primitives + +A cipher or a curve keeps its own secrets: it compares its tags in constant +time, wipes its keys when it is destroyed and draws what it needs from the +system's generator. A program also handles secrets of its own around them: it +checks a MAC a request carries, holds a key or a password in a buffer, and +draws a token. Four utilities serve that, each named by what it does. They are +at the top of `webcpp::crypto`, beside the rest of the root, with no namespace +of their own, and need no backend: `random_device` reads the system's +generator, and the other three are code of crypto's. + +.What each utility guards against +[cols="2,2,5,3",options="header"] +|=== +| Utility | Hygiene | What it guards against | Header + +| `constant_time_equal` +| timing +| a comparison whose time tells how many bytes of a forged MAC or token are +right +(link:https://cwe.mitre.org/data/definitions/208.html[CWE-208]; +<>) +| `` + +| `erase_secret` +| memory +| a secret left in a buffer the program owns, a string, a vector or an array, +after its use, where a `memset` the optimiser removed did not erase it +(link:https://cwe.mitre.org/data/definitions/14.html[CWE-14]; +<>) +| `` + +| `secret` +| memory +| a secret crypto returns outliving its use: it wipes itself when it is +destroyed or moved from +(link:https://cwe.mitre.org/data/definitions/14.html[CWE-14]; +<>) +| `` + +| `random_device` +| drawing +| a key, a nonce or a token drawn from a generator an attacker can predict +(link:https://cwe.mitre.org/data/definitions/338.html[CWE-338]; +<>) +| `` +|=== + +include::constant_time_equal.adoc[] + +include::erase_secret.adoc[] + +[#crypto-secret] +==== Secrets that wipe themselves: `secret` + +Every secret crypto gives back is a `secret`, `N` its size in bytes: a key +pair's `secret()`, the shared secret of `agree`, the session keys of +`crypto_kx`, a tweaked secret key, the secret key read from a PKCS#8 file. It +holds its bytes in an array of its own and wipes them, with the volatile stores +and the fence of `erase_secret`, when it is destroyed and when it is moved +from, so that the secret lives in one object and leaves memory with it. + +It is not copyable: a copy is asked for by name, `clone()`, and the caller owns +it. `bytes()` gives a `std::span` to read, which a +cipher's `from_key`, a key pair's `from_secret` or an HKDF takes as its input +without a copy (`from_key(session_keys.transmit.bytes())`), and a `secret` +converts to that span where a function takes it. Neither is offered on a +temporary `secret`, whose bytes would be wiped before the span is read: the +program keeps the secret in a variable first. + +*What it is not.* + +* It wipes its own storage, and only that. A copy of `bytes()` into a string, + a vector or a log is the program's, to erase with `erase_secret`, and a move + or a `clone` may leave copies in registers or temporaries that no library + reaches. +* It does not lock the memory, as `erase_secret` does not: the page may be + swapped to disk while the secret is in it. + +include::entropy.adoc[] diff --git a/doc/public_key_encryption.adoc b/doc/public_key_encryption.adoc new file mode 100644 index 00000000..fbbdddcc --- /dev/null +++ b/doc/public_key_encryption.adoc @@ -0,0 +1,155 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the 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-public-key-encryption] +== Public-key encryption: `webcpp::crypto::public_key_encryption` + +*Public-key encryption* encrypts to a public key: a key agreement, on public +keys, gives a secret key, and a fast cipher encrypts the data under it, the +construction textbooks call hybrid encryption +(link:https://en.wikipedia.org/wiki/Hybrid_cryptosystem[Wikipedia]). A chat app +encrypts a message to a contact whose public key it knows; a feedback form +encrypts a report to a key whose owner alone may read it. The namespace +`webcpp::crypto::public_key_encryption` holds NaCl's and libsodium's +constructions in this version: the box, between two key pairs, and the sealed +box, from anyone to a public key. Both agree with X25519 (<>) and +seal with XSalsa20-Poly1305, the secret box's cipher (<>), or, +for `box_xchacha20poly1305`, XChaCha20-Poly1305, on libsodium, their default on +every target. The namespace is named by the problem it solves: the word hybrid +now names the post-quantum hybrids, as X25519MLKEM768 and X-Wing, for which +`webcpp::crypto::hybrid` is kept free, and a later HPKE +(link:https://www.rfc-editor.org/rfc/rfc9180[RFC 9180]) joins the boxes here. +The namespaces of crypto are named by purpose, as +<> lists them: what +encrypts under one secret key is in `secret_key_encryption`, what encrypts +between key pairs here, and libsodium's session keys in `key_exchange`. + +*Which one.* A box when the two parties know each other's public keys and the +recipient must know the message came from the other: a chat between two +contacts. A sealed box when anyone may write and the recipient alone reads: a +feedback form, a drop box, a file key sent to a recipient known by a public key +(<>). `box_xchacha20poly1305` only when the peer uses +libsodium's XChaCha20 form; otherwise `box`, NaCl's format, which libsodium +and its bindings in every language read. Without either, a program that +encrypts to a public key by hand, an agreement and a cipher of its own +choosing, risks the mistakes these constructions settle: a shared secret used +as a key, a nonce reused, a weak public key accepted. + +include::generated/namespace-public_key_encryption.adoc[] + +[#crypto-box] +=== Boxes + +`public_key_encryption::box`, in +``, is NaCl's `crypto_box` +(link:https://nacl.cr.yp.to/box.html[NaCl]; +link:https://doc.libsodium.org/public-key_cryptography/authenticated_encryption[libsodium's +documentation]). `box::from_keys(own_keypair, peer_public_key)` agrees a key +from the own X25519 key pair (`curves::x25519::basic_keypair`, +<>) and the peer's `x25519::public_key`, once for the pair +(libsodium's `beforenm`), and keeps that key alone, not the key pair; the box +then works in place, without associated data: `seal(nonce_bytes, data_bytes)` +encrypts and returns the 16-byte tag, and `open(nonce_bytes, data_bytes, +tag_bytes)` checks it and decrypts, zeroing the data when it does not match. A +box is an `authenticated_box`, as a secret box is: its free forms are the box +forms, `secret_key_encryption::seal(box, nonce, data)` and +`secret_key_encryption::open(box, nonce, data, tag)`, named in full +(<>); no free `seal` or `open` is in this namespace. Alice's +box made from her key pair and Bob's public key, and Bob's made from his key +pair and Alice's public key, hold the same key: what one seals the other opens. +`box_xchacha20poly1305` is libsodium's `crypto_box_curve25519xchacha20poly1305`, +the same with XChaCha20-Poly1305. A box is moved and not copied, and wipes its +key when moved from and destroyed. + +A peer's public key of small order makes the shared secret one an attacker +knows: `from_keys` refuses it with `weak_public_key`, as libsodium's `beforenm` +does. + +include::generated/backends-box.adoc[] + +include::generated/backends-box_xchacha20poly1305.adoc[] + +[cols="3,1"] +|=== +|Condition |Error + +|`from_keys`: a key pair moved from |`invalid_state` +|`from_keys`: a peer key of small order |`weak_public_key` +|`seal`, `open`: the object was moved from |`invalid_state` +|a nonce of another size than 24 bytes |`invalid_nonce_size` +|`open`: a tag of another size than 16 |`invalid_tag_size` +|a message longer than `max_message_size` |`message_too_long` +|`open`: the tag does not match |`authentication_failed` +|the backend fails where it should not |`backend_failure` +|=== + +*Example.* Alice and Bob, each with an X25519 key pair, make their boxes from +the own key pair and the other's public key; what one seals the other opens, +and Mallory, who knows Alice's public key but not Bob's secret key, cannot: + +[source,cpp] +---- +include::{examples}/box_messages.cpp[tag=boxes,indent=0] +---- + +[source,cpp] +---- +include::{examples}/box_messages.cpp[tag=exchange] +---- + +[listing] +---- +include::{examples}/box_messages.expected[] +---- + +The whole program: + +[source,cpp] +---- +include::{examples}/box_messages.cpp[tag=program] +---- + +*Pitfalls.* + +* A box proves that one of the two key pairs wrote a message, not which one: +a protocol that needs to know says so inside the message, or signs it. +* A nonce is never repeated for one pair of keys, in either direction: draw +24 bytes at random for every message. + +[#crypto-sealed-box] +=== Sealed boxes + +`public_key_encryption::sealed_box`, in +``, is libsodium's sealed +box, `crypto_box_seal` +(link:https://doc.libsodium.org/public-key_cryptography/sealed_boxes[libsodium's +documentation]): anyone who knows a public key can seal a message to it, and +only the key pair opens it. `seal(recipient_public_key, message, out)`, the +recipient's key an `x25519::public_key`, writes to `out`, of the message's size +plus `overhead`, 48 bytes, a key pair libsodium draws for the message, its +public key, the tag and the ciphertext, and wipes the drawn secret key; the +nonce comes from the two public keys. `open(recipient_keypair, sealed, out)`, +the recipient's `x25519::basic_keypair`, writes the message to `out`, of the +sealed box's size less 48 bytes, and zeroes `out` when the box does not open: +sealed to another key pair, or changed. The sizes are checked first +(`invalid_input_size`), then the key pair (`invalid_state` for one moved from). + +include::generated/backends-sealed_box.adoc[] + +*Pitfalls.* + +* A sealed box is anonymous: the recipient cannot tell who sealed it, nor +whether an attacker did. Where the sender matters, use a box or a signature. +* The sender cannot open what it sealed: it keeps its own copy of the +message if it needs one. + +*Example.* A file-sharing app seals each file's key to its recipient: +<>. + +Parts of this chapter, the boxes' and the sealed boxes' descriptions and +pitfalls, are adapted from libsodium's documentation +(link:https://github.com/jedisct1/libsodium-doc/tree/6d1ea27b79b853b2a04f09ae9e1a8231c90e3b56[jedisct1/libsodium-doc] +at `6d1ea27`, ISC, `LICENSE-LIBSODIUM-DOC.txt`). diff --git a/doc/root.adoc b/doc/root.adoc index 28137fbb..dab5ae58 100644 --- a/doc/root.adoc +++ b/doc/root.adoc @@ -8,17 +8,23 @@ == The root utilities: `webcpp::crypto` The namespace `webcpp::crypto` holds what every other chapter relies on: where -secrets come from (`random_device`), how a secret is checked (`equal`) and how -a failure is told apart (`error`), none of which needs a backend; and how a -key's standard form becomes text and back (`pem`, on libsodium; -<>). It also declares, for a native program on OpenSSL that -turns the memory option on, the resource every allocation of OpenSSL's goes to -(`openssl_memory_resource`, <>). And it holds what every -curve's signatures share: the schemes, the `prehashed` marker, `crypto::sign` -and `crypto::verify` (``), and the key pair -contract, the concept `crypto::keypair`, with `crypto::agree` -(``; <>); and the free -forms that make an object by its type, `crypto::make` and `crypto::generate` -(``; <>). +secrets come from (`random_device`), how a secret is checked +(`constant_time_equal`), erased from a buffer of the program's +(`erase_secret`) and held so that it wipes itself (`secret`), the four +utilities of <>, and how a failure is told apart +(`error`), none of which needs a backend; and how a key's standard form +becomes text and back (`pem`, on libsodium; <>). It also +declares, for a native program on OpenSSL that turns the memory option on, the +resource every allocation of OpenSSL's goes to (`openssl_memory_resource`, +<>). And it holds what every curve's signatures share: +the schemes, the `prehashed` marker and `crypto::verify` +(``; <>); the key pair +concepts, `crypto::keypair`, `crypto::signing_keypair` and +`crypto::agreement_keypair`, with `crypto::sign` and `crypto::agree` +(``; <>); and the free forms +that make an object by its type, each named by its input, +`crypto::from_secret`, `crypto::from_bytes`, `crypto::from_key` and +`crypto::generate` (``; +<>). include::generated/namespace-root.adoc[] diff --git a/doc/secp256k1.adoc b/doc/secp256k1.adoc index ced358b8..304183de 100644 --- a/doc/secp256k1.adoc +++ b/doc/secp256k1.adoc @@ -54,8 +54,8 @@ takes `crypto::ecdsa_sha256` and `crypto::schnorr`, and `crypto::verify` with | Operation | The member | Its free form | Make -| `keypair::make(secret_key)` -| `crypto::make(secret_key)` +| `keypair::from_secret(secret_key)` +| `crypto::from_secret(secret_key)` | Generate | `keypair::generate()` @@ -74,30 +74,32 @@ takes `crypto::ecdsa_sha256` and `crypto::schnorr`, and `crypto::verify` with | `crypto::agree(key_pair, peer)` |=== -A `keypair` is made from a 32-byte secret key with `make(secret)`, or +A `keypair` is made from a 32-byte secret key with `from_secret(secret)`, or generated with `generate()`, which draws the secret key from `random_device` and draws again, at most four times in all, for 32 bytes that are not one. Either allocates its signing context in the `std::pmr::memory_resource` it is given, and randomises it from `random_device`; crypto's own code allocates nothing else (<>). The namespace's functions, by header: -* ``: the key pair's `make` and +* ``: the key pair's `from_secret` and `generate`, its `public_key()` and its `secret()`, its signatures (`sign` with `crypto::schnorr`, its auxiliary randomness drawn or given, with -`crypto::ecdsa_sha256`, hedged or not, and with -`crypto::ecdsa_sha256_recoverable`), its ECDH (`agree`, `agree_hashed`, +`crypto::ecdsa_sha256`, hedged or not, with +`crypto::ecdsa_sha256_recoverable`, and with Ethereum's +`crypto::ecdsa_keccak256_recoverable`), its ECDH (`agree`, `agree_hashed`, `agree_point`) and its tweak in place (`tweak_xonly`); `crypto::verify` with `crypto::schnorr` and `crypto::ecdsa_sha256`, which checks a signature with a public key alone; `recover`, which finds the key of a recoverable signature -(<>); the `public_key` type, made from its bytes by -`public_key::make` and written by `compressed()`, `uncompressed()` and +(<>, <>); the +`public_key` type, made from its bytes by +`public_key::from_bytes` and written by `compressed()`, `uncompressed()` and `xonly()` (<>); `to_der`, `from_der` (strict DER), `normalize_low_s` and `is_low_s`, ECDSA's DER and low-S forms; and `tweak_xonly`, the tweak of an x-only public key; -* ``: `seckey_tweak_add`, -`seckey_tweak_mul` and `seckey_negate`, `pubkey_tweak_add`, -`pubkey_tweak_mul` and `pubkey_negate`, and `pubkey_combine` with its -`combine_workspace_size`: the tweaks, negation and combination of whole keys +* ``: `secret_key_tweak_add`, +`secret_key_tweak_mul` and `secret_key_negate`, `public_key_tweak_add`, +`public_key_tweak_mul` and `public_key_negate`, and `public_key_combine` with +its `combine_workspace_size`: the tweaks, negation and combination of whole keys (<>); * ``: `encode_spki`, `decode_spki`, `encode_pkcs8` and `decode_pkcs8`, the keys' SPKI and PKCS#8, @@ -107,18 +109,17 @@ which `pem` writes as PEM text (<>); random-looking bytes (<>); * ``, namespace `musig`: `key_aggregate` (and the aggregate key's `xonly_public_key`, -`full_public_key`, `tweak_add` and `tweak_xonly_add`), `nonce_gen`, +`full_public_key`, `tweak_add` and `tweak_xonly_add`), `generate_nonce`, `nonce_aggregate`, `nonce_process`, `partial_sign`, `partial_signature_verify` and `partial_signature_aggregate`, the `parse_` and `serialize_` functions of the public nonce, the aggregate nonce and the partial signature, and `workspace_size`: many signers' one signature (<>); * ``, namespace -`silent_payments`: `create_outputs`, `create_label`, -`create_labeled_spend_key`, `make_prevouts_summary` and `scan_outputs`, with -`send_workspace_size`, `summary_workspace_size` and `scan_workspace_size`: -one reusable address whose payments look unrelated -(<>). +`silent_payments`: `create_outputs`, `create_label`, `create_labeled_spend_key`, +`make_previous_outputs_summary` and `scan_outputs`, with `send_workspace_size`, +`summary_workspace_size` and `scan_workspace_size`: one reusable address whose +payments look unrelated (<>). Every function reads libsecp256k1's canary, so that a program linked with another build of the library does not link. @@ -152,7 +153,7 @@ which computes the tweak from its own hash and passes it here *Pitfalls.* * A secret key drawn from `random_device` is below the group order with -overwhelming probability, but not always: `make` returns +overwhelming probability, but not always: `from_secret` returns `invalid_secret_key` then, and the program draws again (<>). * Keep the secret key out of logs, crash reports and source control: the key @@ -160,9 +161,9 @@ pair wipes its copy, the program wipes its own. * BIP 340's auxiliary randomness is fresh for each signature: `sign(crypto::schnorr, message)` draws it from `random_device`, and returns `entropy_unavailable` when it cannot. `sign(crypto::schnorr, message, -aux_random)` takes the caller's 32 bytes; a fixed value is safe only because -the nonce also depends on the key and the message, and the examples pass zeros -only to print fixed signatures. +auxiliary_random_bytes)` takes the caller's 32 bytes; a fixed value is safe +only because the nonce also depends on the key and the message, and the +examples pass zeros only to print fixed signatures. * `+crypto::verify(crypto::ecdsa_sha256, ...)+` refuses a high-S signature, as libsecp256k1 does: `normalize_low_s` gives the low-S form of a signature from a signer that does not enforce it. A verifier that normalizes before verifying @@ -252,7 +253,7 @@ curve is how invalid-curve attacks begin, in which a key off the curve, combined with a secret key, leaks that secret bit by bit, which is why the holder of a long-lived secret key validates the other side's public key (link:https://en.wikipedia.org/wiki/Elliptic-curve_Diffie%E2%80%93Hellman[Wikipedia]). -`public_key::make` makes a `public_key` from bytes, and the functions that +`public_key::from_bytes` makes a `public_key` from bytes, and the functions that return one (a key pair's `public_key()`, `recover`, the tweaks) make the others, so a program that holds one holds a valid point. It is the key that `crypto::verify` and a key pair's `agree` take. @@ -267,7 +268,7 @@ keys this way, and its SegWit outputs take no other form by default the uncompressed form without its prefix (link:https://ethereum.github.io/yellowpaper/paper.pdf[Ethereum's yellow paper]). -`public_key::make` reads either, and a `public_key` writes itself in each: +`public_key::from_bytes` reads either, and a `public_key` writes itself in each: `compressed()`, `uncompressed()`, and BIP 340's x-only form, `xonly()`, its x coordinate alone, 32 bytes, which `+crypto::verify(crypto::schnorr, ...)+` takes as it takes the `public_key` itself. Two `public_key` values compare @@ -290,7 +291,7 @@ form. the same key compressed and uncompressed are different bytes. Parse both and compare the `public_key` values. * Ethereum's 64-byte key is the uncompressed form without its 04: add the -prefix before `public_key::make`, and drop it from what `uncompressed()` +prefix before `public_key::from_bytes`, and drop it from what `uncompressed()` gives. [#crypto-secp256k1-recovery] @@ -303,14 +304,16 @@ made it paper, appendix F]). An ECDSA signature fits up to four keys, and the recovery id, 0 to 3, names the one that made it (link:https://www.secg.org/sec1-v2.pdf[SEC 1, section 4.1.6]). -`sign(crypto::ecdsa_sha256_recoverable, input)` writes 65 bytes, r, s and the -id, with the same r and s as `sign(crypto::ecdsa_sha256, input)`, and +`sign(crypto::ecdsa_sha256_recoverable, input)` gives a +`recoverable_signature`, 65 bytes, r, s and the id, with the same r and s as +`sign(crypto::ecdsa_sha256, input)`, and `recover(crypto::ecdsa_sha256_recoverable, signature, input)` returns the -`public_key` from those 65 bytes and the same input, the message it hashes or +`public_key` from that signature (65 bytes received are made into one with +`recoverable_signature::from_bytes`) and the same input, the message it hashes or a digest marked `crypto::prehashed`. It refuses with `invalid_signature` an id above 3, an r or an s not below the group order, and a signature from which no -key is recovered. Ethereum's digest is Keccak-256's, not SHA-256's (how it is -signed under this scheme: <>). +key is recovered. Ethereum's digest is Keccak-256's, not SHA-256's: its scheme +is `crypto::ecdsa_keccak256_recoverable` (<>). include::generated/backends-recovery.adoc[] @@ -346,7 +349,8 @@ account the key's hash must name. * Ethereum's `v` is the recovery id plus 27, or plus an offset of the chain's (link:https://ethereum.github.io/yellowpaper/paper.pdf[Ethereum's yellow paper, appendix F]): passing `v` as the id makes `recover` refuse it. That -encoding, and the message hash Ethereum signs, are a domain library's. +encoding, and the digest Ethereum signs, are the program's +(<>). * The hedged form gives a different signature each time, so a test that compares signatures with fixed bytes uses the unhedged form. Use the hedged form where the signer runs on hardware an attacker can fault or observe: the @@ -354,6 +358,100 @@ nonce then no longer depends on the key and the hash alone, so two signings of one hash do not repeat the same computation. Never reuse the 32 bytes: fixed extra data leaves the signature deterministic, as plain RFC 6979. +[#crypto-secp256k1-ethereum] +==== Ethereum + +Ethereum signs with recoverable ECDSA over Keccak-256 +(link:https://ethereum.github.io/yellowpaper/paper.pdf[Ethereum's yellow +paper, appendix F]), the scheme `crypto::ecdsa_keccak256_recoverable`. +`sign(crypto::ecdsa_keccak256_recoverable, input)` gives the +`recoverable_signature` of <>, r, s with a low S as +EIP-2 requires (link:https://eips.ethereum.org/EIPS/eip-2[EIP-2]) and the +recovery id, and `recover(crypto::ecdsa_keccak256_recoverable, signature, +input)` gives the signer's `public_key`. The input is a message, which the call +hashes with Keccak-256 (`webcpp::hash::keccak_256`, the original padding, never +SHA3-256), or the 32-byte digest the program builds, given as +`+crypto::prehashed{digest}+`. The scheme has no `crypto::verify`, as +`crypto::ecdsa_sha256_recoverable` has none: Ethereum compares the key +recovered, or its address, with the one expected. It has no asynchronous form, +as no operation of secp256k1's has one. + +Keccak-256 is XKCP's: a program that signs or recovers a message adds +`/third_party//xkcp` to its Jamfile, and without it the build stops with that +line (<>). A digest marker needs no XKCP. + +[source,bash] +---- +exe wallet : wallet.cpp /webcpp/crypto//crypto /third_party//secp256k1 + /third_party//xkcp ; +---- + +crypto computes none of the protocol's encodings: not the digest a wallet +signs, not `v`, not the address. The digest is EIP-191's for a signed message +(link:https://eips.ethereum.org/EIPS/eip-191[EIP-191]), EIP-712's for typed +data (link:https://eips.ethereum.org/EIPS/eip-712[EIP-712]), or a transaction's +hash; `v` encodes the recovery id, and the address is the last 20 bytes of the +Keccak-256 of the uncompressed key without its 0x04: + +.Ethereum's `v`, from `recovery_id()` +[cols="2,2,3",options="header"] +|=== +| Where | `v` | Back to the recovery id + +| `personal_sign` (EIP-191), a legacy transaction before EIP-155 +| 27 + id +| `v - 27` + +| A legacy transaction with EIP-155's replay protection +(link:https://eips.ethereum.org/EIPS/eip-155[EIP-155]) +| 35 + 2 x chain id + id +| `v - 35 - 2 x chain id` + +| A typed transaction (EIP-2930, EIP-1559 and later), its `yParity` +| id +| `yParity` +|=== + +*Example.* A wallet signs "Some data" as `personal_sign` does, with web3.js's +documented key, and the reader recovers its address: EIP-191's digest, built +over webcpp::hash, + +[source,cpp] +---- +include::{examples}/ethereum_personal_sign.cpp[tag=digest,indent=0] +---- + +signed as a digest, with `v` made from the recovery id, + +[source,cpp] +---- +include::{examples}/ethereum_personal_sign.cpp[tag=sign,indent=0] +---- + +and the signer's key recovered from the same digest, then its address: + +[source,cpp] +---- +include::{examples}/ethereum_personal_sign.cpp[tag=recover,indent=0] +---- + +[listing] +---- +include::{examples}/ethereum_personal_sign.expected[] +---- + +*Pitfalls.* + +* A message signed with `crypto::ecdsa_keccak256_recoverable` and recovered +under `crypto::ecdsa_sha256_recoverable`, or the other way round, is hashed +with the other hash and gives another key, not an error: both schemes give one +signature type, and the comparison with the key expected is the check. +* Give the scheme the digest the protocol signs: a message passed in place of +EIP-191's digest is hashed without its prefix and recovers another key. +* `recover` accepts a high S, as libsecp256k1's recovery and Ethereum's +`ecrecover` do; `sign` gives a low S always. A node that applies EIP-2 to a +transaction checks `is_low_s` of its r and s itself. + [#crypto-secp256k1-tweaks] ==== Tweaks, negation and combination @@ -371,21 +469,21 @@ key pair without the server ever holding a secret. `` offers that arithmetic on whole keys, each function a call of libsecp256k1: -* `seckey_tweak_add` and `seckey_tweak_mul`: a secret key plus or times a -32-byte tweak, modulo the group order, returned as a `secret<32>`; -`pubkey_tweak_add` and `pubkey_tweak_mul`: P + tG and tP, the public keys of -those two secrets; -* `seckey_negate` and `pubkey_negate`: the negation of either, n - d and -P, -each a `result` like the other tweaks; -* `pubkey_combine`: the sum of public keys, the public key of the sum of their -secrets. libsecp256k1 takes an array of pointers to the keys, which crypto +* `secret_key_tweak_add` and `secret_key_tweak_mul`: a secret key plus or times +a 32-byte tweak, modulo the group order, returned as a `secret<32>`; +`public_key_tweak_add` and `public_key_tweak_mul`: P + tG and tP, the public +keys of those two secrets; +* `secret_key_negate` and `public_key_negate`: the negation of either, n - d and +-P, each a `result` like the other tweaks; +* `public_key_combine`: the sum of public keys, the public key of the sum of +their secrets. libsecp256k1 takes an array of pointers to the keys, which crypto builds in a `workspace` the caller lends, of `combine_workspace_size(n)` bytes, so that nothing is allocated; the workspace is wiped before the call returns. A secret key that is zero or not below the group order is refused with `invalid_secret_key` before the tweak runs; so are a tweak not below the order, a zero multiplier, and a result that is no key (a zero secret, the -point at infinity). `pubkey_combine` refuses no keys and a short workspace +point at infinity). `public_key_combine` refuses no keys and a short workspace with `invalid_input_size`, and a sum at infinity with `invalid_public_key`. include::generated/backends-key_tweaks.adoc[] @@ -454,7 +552,7 @@ writes for a key in its default uncompressed form: OpenSSL's point form is uncompressed unless a program sets it, and it includes the public key when it encodes a private key unless told not to (link:https://docs.openssl.org/master/man7/EVP_PKEY-EC/[OpenSSL's EVP_PKEY-EC]); -`decode_pkcs8` reads it into a key pair, made as `keypair::make` makes one. +`decode_pkcs8` reads it into a key pair, made as `keypair::from_secret` makes one. The decoders are strict: they accept exactly the bytes the encoders write, and refuse anything else with `invalid_encoding`. The point must be on the curve, @@ -615,8 +713,9 @@ signature. ``, namespace `public_key` is BIP 327's KeySort. Its `xonly_public_key` is the key the signature verifies under; `tweak_add` and `tweak_xonly_add` tweak it as a protocol asks; -* `nonce_gen` makes one signer's nonce for one signature from its key pair, its -randomness drawn inside: a `secret_nonce` to keep and a `public_nonce` to send; +* `generate_nonce` makes one signer's nonce for one signature from its key pair, +its randomness drawn inside: a `secret_nonce` to keep and a `public_nonce` to +send; * `nonce_aggregate` sums the public nonces, and `nonce_process` makes the `session` of the 32-byte message; * `partial_sign` signs this signer's part, consuming its secret nonce; @@ -634,7 +733,7 @@ is allocated, and wipe it before they return; no items or a short workspace is `invalid_signature`, a tweak out of range `invalid_secret_key`, and a moved-from key pair or a used nonce `invalid_state`. The tests check BIP 327's own vectors, those that need no secret nonce of the vector's: a `secret_nonce` -exists only from `nonce_gen`, and libsecp256k1's own tests, run in the +exists only from `generate_nonce`, and libsecp256k1's own tests, run in the `c-suites` lane, check the rest. include::generated/backends-musig.adoc[] @@ -674,12 +773,11 @@ include::{examples}/musig_network.expected[] spent by its key path (link:https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki[BIP 341]). `tweak_xonly_add` tweaks it by its TapTweak tagged hash before any nonce is -made, since the session and the partial signatures need the key as tweaked, -and `nonce_gen` mixes in the key it is given (BIP 327's NonceGen takes it only -as an optional input); the signature then verifies under the output key and -not under the internal one. -The hash is the protocol's, a domain library's to compute; the example shows -it with webcpp::hash's SHA-256: +made, since the session and the partial signatures need the key as tweaked, and +`generate_nonce` mixes in the key it is given (BIP 327's NonceGen takes it only +as an optional input); the signature then verifies under the output key and not +under the internal one. The hash is the protocol's, a domain library's to +compute; the example shows it with webcpp::hash's SHA-256: [source,cpp] ---- @@ -708,7 +806,7 @@ two-round design exists to prevent * A key aggregated with an attacker's key that the attacker chose after seeing yours is safe here: MuSig2 weighs each key with a coefficient hashed from all of them, so that no signer can cancel another's. The plain sum of keys, -`pubkey_combine` (<>), has no such weight, and is +`public_key_combine` (<>), has no such weight, and is not a multisignature (link:https://github.com/bitcoin/bips/blob/master/bip-0327.mediawiki[BIP 327]). * The tweaks belong to a protocol. Taproot's output key is the aggregate key @@ -745,11 +843,11 @@ the same secret, and recognises its outputs and a spend `public_key`, which the sender decodes from the address), from the key pairs of the Taproot inputs and of the other eligible inputs, apart, and the smallest outpoint's 36 bytes; -* `make_prevouts_summary` sums the eligible inputs' public keys for the -recipient, into a `prevouts_summary`, and `scan_outputs` scans a transaction's -x-only outputs with the scan key pair and the spend key: each `found_output` -holds the output's key, its `spend_tweak` (a `secret<32>`, which -`seckey_tweak_add` adds to the spend secret key to spend the output, +* `make_previous_outputs_summary` sums the eligible inputs' public keys for the +recipient, into a `previous_outputs_summary`, and `scan_outputs` scans a +transaction's x-only outputs with the scan key pair and the spend key: each +`found_output` holds the output's key, its `spend_tweak` (a `secret<32>`, which +`secret_key_tweak_add` adds to the spend secret key to spend the output, <>) and the label it was sent to; * `create_label` makes the scan key's `m`-th label, 0 being BIP 352's change label, and `create_labeled_spend_key` the spend key of the address with that @@ -760,7 +858,7 @@ tweak, in bytes the lookup owns for the call, since libsecp256k1 reads them after it returns, or `std::nullopt`. A tweak returned by value is refused at compile time. -`create_outputs`, `make_prevouts_summary` and `scan_outputs` take a +`create_outputs`, `make_previous_outputs_summary` and `scan_outputs` take a `workspace` for libsecp256k1's arrays (`send_workspace_size`, `summary_workspace_size` and `scan_workspace_size` say how many bytes), so that nothing is allocated, and wipe it, the inputs' secrets and the found diff --git a/doc/secret_key_encryption.adoc b/doc/secret_key_encryption.adoc new file mode 100644 index 00000000..2fd6d74e --- /dev/null +++ b/doc/secret_key_encryption.adoc @@ -0,0 +1,167 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the 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-secret-key-encryption] +== Secret-key encryption: `webcpp::crypto::secret_key_encryption` + +*Secret-key encryption* encrypts and authenticates data under one key that every +party who reads it holds, as a password manager's vault key or a file's key does +(link:https://en.wikipedia.org/wiki/Symmetric-key_algorithm[Wikipedia]). The +namespace `webcpp::crypto::secret_key_encryption` holds two things in this +version: NaCl's and libsodium's secret boxes, `secretbox` and +`secretbox_xchacha20poly1305`, and `aead`, the contract every AEAD of `ciphers` +satisfies, with the free forms of their `seal` and `open`. The namespace is +named by the problem it solves, encryption under one secret key, as +`public_key_encryption` holds encryption between key pairs +(<>); the algorithms stay in `ciphers` under their +names (<>). A secret box is no AEAD, since it takes no +associated data: it is an `authenticated_box`, as a crypto_box is, and its free +forms are the box forms. + +[#crypto-namespaces-by-purpose] +.The namespaces by purpose +[cols="2,5",options="header"] +|=== +| Namespace | Holds + +| `webcpp::crypto` +| the root: `random_device`, `constant_time_equal`, `erase_secret`, +`secret`, `error`, the signing vocabulary, the key pair concepts and the +free factories (<>) + +| `crypto::ciphers` +| symmetric algorithms: AES, AES-GCM, ChaCha20-Poly1305 in three nonce sizes +(<>) + +| `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::public_key_encryption` +| constructions between key pairs: `box`, `sealed_box` +(<>) + +| `crypto::key_exchange` +| libsodium's `crypto_kx`: `kx_keypair`, `session_keys` +(<>) + +| `crypto::curves` +| the curve primitives: secp256k1, Ed25519, X25519, P-256 (<>) +|=== + +A construction is placed by the problem it solves, and an algorithm by what it +is: a program that encrypts under one key looks in `secret_key_encryption`, +whatever cipher it ends up with, and finds the algorithms named there in +`ciphers`. + +*Which one.* An AEAD of `ciphers` for new data, `xchacha20_poly1305<>` when in +doubt: it authenticates associated data too, a record's id or a header that +travels in clear. A secret box to read or write what libsodium's +`crypto_secretbox` wrote. Code written once for every AEAD takes an +`aead::cipher`; code written once for every box an `authenticated_box`. + +include::generated/namespace-secret_key_encryption.adoc[] + +[#crypto-aead-contract] +=== The AEAD contract: `secret_key_encryption::aead` + +``, which every AEAD's header +includes and which needs no backend, declares two concepts and the free +synchronous forms of an AEAD's `seal` and `open`, in namespace +`webcpp::crypto::secret_key_encryption::aead`: + +* `aead::cipher`, what every one-shot AEAD is: `C::key_size`, +`C::nonce_size` and `C::tag_size`, `typename C::result_type`, the tag; +`C::from_key(key_bytes)` giving `result`; +`c.seal(nonce, associated_data, data)` giving `result`, the data +sealed in place; `c.open(nonce, associated_data, data, tag)` giving +`result`, the data opened in place and zeroed when it fails; +* `aead::streaming_cipher`, a `cipher` that also seals and opens a message +in pieces, with AES-GCM's members: `begin_seal`, `update`, `result`, +`begin_open`, `authenticate`, `decrypt`, `verify` and `end_open` +(<>); +* `aead::seal(cipher, nonce, associated_data, data)` and +`aead::open(cipher, nonce, associated_data, data, tag)`, constrained by +`cipher`, which call the member and give its results and its errors. + +`` adds their asynchronous forms in the same namespace, +`aead::async_seal(executor, cipher, nonce, associated_data, data, token)` and +`aead::async_open(executor, cipher, nonce, associated_data, data, tag, token)`, +and the members `cipher.async_seal` and `cipher.async_open`, for every +`cipher`: on a native backend each runs the synchronous member and completes +through the event loop; on the browser's backend only AES-GCM has them +(<>). + +Each type's header checks its row of this table with a `static_assert`: + +.The AEAD and box concepts +[cols="3,2",options="header"] +|=== +| Type | Concept + +| `ciphers::gcm`: `aes128_gcm`, `aes256_gcm` +| `aead::streaming_cipher` + +| `ciphers::chacha20_poly1305`, `chacha20_poly1305_original`, +`xchacha20_poly1305` +| `aead::cipher` + +| `secret_key_encryption::secretbox`, `secretbox_xchacha20poly1305` +| `authenticated_box` + +| `public_key_encryption::box`, `box_xchacha20poly1305` +| `authenticated_box` +|=== + +A function written against the concept serves every AEAD, as this check of the +library's own tests does, made once for each cipher of the table: + +[source,cpp] +---- +include::{library-root}/test/aead_concepts_test.cpp[tag=generic,indent=0] +---- + +No free `seal` or `open` is in `webcpp::crypto`: the AEADs' are in +`secret_key_encryption::aead`, and the boxes' in `secret_key_encryption`. An +unqualified call on a secret box, `seal(box, nonce, data)` or +`open(box, nonce, data, tag)`, goes to `secret_key_encryption::seal` or `open`, +which argument-dependent lookup finds in the box's namespace. + +[#crypto-box-forms] +=== The box forms: `secret_key_encryption::seal` and `open` + +``, which the secret +boxes' header and `public_key_encryption/box.hpp` include and which needs no +backend, declares the concept `authenticated_box`, authenticated encryption +in place without associated data: `C::key_size`, `C::nonce_size` and +`C::tag_size`, `typename C::result_type`; `c.seal(nonce, data)` giving +`result`; `c.open(nonce, data, tag)` giving `result`, the +data zeroed when it fails. The factory is not part of it: a secret box is made +by `from_key`, a crypto_box by `from_keys` from two X25519 keys. + +Its free forms, `secret_key_encryption::seal(box, nonce, data)` and +`secret_key_encryption::open(box, nonce, data, tag)`, serve a secret box and a +crypto_box alike: argument-dependent lookup finds them for a secret box, and a +crypto_box, of `public_key_encryption`, is sealed by +`secret_key_encryption::seal` named in full, or by its member. A box given to +the AEAD forms stops the build, naming the box form: + +[listing] +---- +webcpp::crypto: seal: a secret box or a crypto_box takes no associated data: +secret_key_encryption::seal(box, nonce, data). +---- + +Their asynchronous forms, `secret_key_encryption::async_seal(executor, box, +nonce, data, token)` and `secret_key_encryption::async_open(executor, box, +nonce, data, tag, token)`, and the members `box.async_seal` and +`box.async_open`, are in ``, on a native backend: +WebCrypto has neither box (<>). A secret box is also made +asynchronously, by `crypto::async_from_key` or its static +`async_from_key`; a crypto_box has no asynchronous `from_keys`. + +include::secretbox.adoc[] diff --git a/doc/secretbox.adoc b/doc/secretbox.adoc index 1882db5c..07cb51f9 100644 --- a/doc/secretbox.adoc +++ b/doc/secretbox.adoc @@ -8,7 +8,7 @@ === Secret boxes A *secret box* is NaCl's name for authenticated encryption under one secret -key, with no additional data: the box hides the message and its tag proves it +key, with no associated data: the box hides the message and its tag proves it unchanged (link:https://nacl.cr.yp.to/secretbox.html[NaCl]; link:https://doc.libsodium.org/secret-key_cryptography/secretbox[libsodium's documentation]). Its cipher is XSalsa20, Salsa20 with a 24-byte nonce @@ -17,15 +17,25 @@ and its authenticator Poly1305. A program that stores records or files under one key, each with a nonce drawn at random, and a program that must read what libsodium's `crypto_secretbox` wrote, use it. -`ciphers::secretbox<>` and `ciphers::secretbox_xchacha20poly1305<>`, in -``, are `ciphers::aead` over libsodium's -`crypto_secretbox` and its XChaCha20 twin, `crypto_secretbox_xchacha20poly1305`, -on libsodium, their default on every target: a 32-byte key, a 24-byte nonce -safe to draw at random for every message, a 16-byte tag. -They are made and used as the ChaCha20-Poly1305 AEADs are (<>), -with one difference: a secret box has no additional data, so their -`max_additional_data_size` is 0 and `seal` and `open` refuse a non-empty one -with `invalid_input_size`, after the nonce and the tag are checked and before +`secret_key_encryption::secretbox<>` and +`secret_key_encryption::secretbox_xchacha20poly1305<>`, in +``, name +`secret_key_encryption::basic_secretbox` over libsodium's `crypto_secretbox` +and its XChaCha20 twin, `crypto_secretbox_xchacha20poly1305`, on libsodium, +their default on every target: a 32-byte key, a 24-byte nonce safe to draw at +random for every message, a 16-byte tag. Each is made by `from_key(key_bytes)` +and works in place, with no associated data, an `authenticated_box` +(<>): + +* `seal(nonce_bytes, data_bytes)` encrypts `data_bytes` in place and returns +its 16-byte tag, a `boost::hash2::digest<16>`; +* `open(nonce_bytes, data_bytes, tag_bytes)` checks the tag and decrypts +`data_bytes` in place, which a failed open zeroes. + +Their free forms are the box forms, `secret_key_encryption::seal(box, nonce, +data)` and `secret_key_encryption::open(box, nonce, data, tag)`, and the free +`crypto::from_key>(key_bytes)`. The guards are the AEADs' +(<>), in order: a box moved from, the nonce's size, the tag's, the length. The nonce may lie in the data: libsodium reads it again after it writes the first bytes of the ciphertext, so it is copied first. @@ -37,7 +47,7 @@ include::generated/backends-secretbox_xchacha20poly1305.adoc[] * The secret box's tag covers the ciphertext alone: a field that travels in clear and must not change, a record's id for instance, belongs in an AEAD's -additional data (<>), not beside a secret box. +associated data (<>), not beside a secret box. * A nonce is never repeated under one key: draw 24 bytes at random for every message, which never collide in practice. diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 969205de..411a4b6e 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -1,7 +1,7 @@ { "comment": "The data of crypto's generated tables and of llms.txt; doc/tables/generate.py reads it with the test Jamfiles, the message tests and the superproject's Jamfile fixtures, and writes doc/generated/, doc/llms.txt, include/webcpp/crypto/detail/capabilities.hpp, include/webcpp/crypto/detail/defaults.hpp and test/capabilities_test.cpp. The capability table is `families`: per family its algorithms, the targets on which each backend has it (each claimed only where a test of the family's operations on that backend runs), constant time per target where it differs from the backend's own `constant_time` (X25519 on wasip2, an open finding, and natively without arm64's DIT, the cause of both), with `constant_time_checker` naming the checker that measured it where that is not every checker of the target, and the default per target, one whatever the program links (design D32), with its reason and the tests that fix it (a row of some of `compilers` restates its target's default for them, with a reason of their own, and each compiler of a target has one row), from which come include/webcpp/crypto/detail/defaults.hpp and the refusal that says what a program whose default is not linked needs; a backend with `targets`, where it is built, is a tag of `backends`. A name in a text is written between backticks, as Markdown writes code: the tables show it as code and llms.txt keeps the backticks. A comparison table's cell {speed:} or {constant_time:} is written from doc/performance.json or from the family's `constant_time`, and each cell of a column a namespace lists in `cited` cites a source or begins with \"none\". Edit this file, then run python3 libs/crypto/doc/tables/generate.py; the doc build runs it with --check.", "page": "https://webcpporg.github.io/libs/crypto/", - "llms": "Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA and recoverable signatures, ECDH, tweaks, ElligatorSwift, MuSig2, silent payments), Ed25519 and Ed25519ph (RFC 8032), X25519 (RFC 7748), their keys in SPKI, PKCS#8 (RFC 8410) and PEM, P-256 key pairs, ECDSA and ECDH on BearSSL, libsodium's crypto_kx, the ChaCha20-Poly1305 AEADs, libsodium's secret boxes, boxes and sealed boxes, a random_device on the system's generator and a constant-time equal, each over a widely used, reviewed C library (BearSSL, OpenSSL, ctaes, libsecp256k1, libsodium) that the program names in its Jamfile. Hashing and HMAC are Boost.Hash2's; HKDF and password hashing are webcpp::hash's. Every failure is a boost::system::result value. Protocols (Bitcoin, Ethereum, Nostr) belong to domain libraries built on these primitives.", + "llms": "Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA and recoverable signatures, ECDH, tweaks, ElligatorSwift, MuSig2, silent payments), Ed25519 and Ed25519ph (RFC 8032), X25519 (RFC 7748), their keys in SPKI, PKCS#8 (RFC 8410) and PEM, P-256 key pairs, ECDSA and ECDH on BearSSL, libsodium's crypto_kx, the ChaCha20-Poly1305 AEADs, libsodium's secret boxes, boxes and sealed boxes, a random_device on the system's generator, a constant_time_equal and an erase_secret whose stores the optimiser keeps, each over a widely used, reviewed C library (BearSSL, OpenSSL, ctaes, libsecp256k1, libsodium) that the program names in its Jamfile. Hashing and HMAC are Boost.Hash2's; HKDF and password hashing are webcpp::hash's. Every failure is a boost::system::result value. Protocols (Bitcoin, Ethereum, Nostr) belong to domain libraries built on these primitives.", "targets": ["native", "wasip2", "wasip3", "emscripten"], "compilers": {"clang": "Clang", "gcc": "GCC", "msvc": "MSVC"}, "checkers": {"memcheck": "Valgrind's memcheck (Linux)", "msan": "MemorySanitizer (Linux, clang)", "dudect": "dudect (judged; on a runner GitHub hosts, by two of three runs)"}, @@ -17,6 +17,7 @@ "openssl-armv8": ["OpenSSL's AES assembly for ARMv8 and x86-64", "https://github.com/openssl/openssl/tree/master/crypto/aes/asm"], "openssl-ghash-asm": ["OpenSSL's GHASH and AES-GCM assembly", "https://github.com/openssl/openssl/tree/master/crypto/modes/asm"], "webcrypto": ["W3C Web Cryptography API", "https://www.w3.org/TR/WebCryptoAPI/"], + "rfc5116": ["RFC 5116, An Interface and Algorithms for Authenticated Encryption", "https://www.rfc-editor.org/rfc/rfc5116"], "chromium-aes192": ["Chromium's WebCrypto refuses 192-bit AES keys", "https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/webcrypto/status.cc"], "joux": ["A. Joux, Authentication Failures in NIST version of GCM, 2006", "https://csrc.nist.gov/csrc/media/projects/block-cipher-techniques/documents/bcm/comments/800-38-series-drafts/gcm/joux_comments.pdf"], "nonce-reuse": ["H. Boeck et al., Nonce-Disrespecting Adversaries, 2016", "https://eprint.iacr.org/2016/475"], @@ -33,6 +34,7 @@ "rfc2104": ["RFC 2104, HMAC", "https://www.rfc-editor.org/rfc/rfc2104"], "rfc4231": ["RFC 4231, HMAC-SHA-256 test vectors", "https://www.rfc-editor.org/rfc/rfc4231"], "cwe208": ["CWE-208, observable timing discrepancy", "https://cwe.mitre.org/data/definitions/208.html"], + "cwe14": ["CWE-14, compiler removal of code to clear buffers", "https://cwe.mitre.org/data/definitions/14.html"], "cwe338": ["CWE-338, a weak generator used for security", "https://cwe.mitre.org/data/definitions/338.html"], "cwe323": ["CWE-323, a nonce reused in encryption", "https://cwe.mitre.org/data/definitions/323.html"], "getentropy": ["POSIX.1-2024, getentropy", "https://pubs.opengroup.org/onlinepubs/9799919799/functions/getentropy.html"], @@ -159,7 +161,7 @@ "library": "OpenSSL 3.5.9's libcrypto, built from source and static", "licence": "Apache-2.0", "own_api": "``", - "allocation": "`make` allocates the cipher's context through OpenSSL's own allocator, outside the program's resource, unless a native program sets `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE`, which sends every allocation of OpenSSL's in the process to `openssl_memory_resource()`; a message allocates nothing after `make`", + "allocation": "`from_key` allocates the cipher's context through OpenSSL's own allocator, outside the program's resource, unless a native program sets `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE`, which sends every allocation of OpenSSL's in the process to `openssl_memory_resource()`; a message allocates nothing after `from_key`", "constant_time": "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)", "constant_time_sources": ["openssl-install", "openssl-aes-core"], "size_note": "its cells differ by a few bytes whatever the operation: each fetches its algorithm by name from OpenSSL's default provider ({openssl-fetch}), and a static link brings the provider's algorithms with it, not the operation's alone." @@ -186,7 +188,7 @@ "library": "libsecp256k1 v0.8.0, built from source with every module on", "licence": "MIT", "own_api": "`` and its modules", - "allocation": "`keypair::make` allocates the signing context, once, in the `std::pmr::memory_resource` it is given; nothing else allocates", + "allocation": "`keypair::from_secret` allocates the signing context, once, in the `std::pmr::memory_resource` it is given; nothing else allocates", "constant_time": "by design: signing and key generation are constant time and constant memory access", "constant_time_sources": ["libsecp256k1"], "size_note": "a row that recovers a key or computes with a public point other than the generator (`recover`, MuSig2's session, a silent payment's output) links the precomputed table of libsecp256k1's variable-time multiplication too, built at window 15 natively and on WASI and at window 2 on Emscripten, the small tables ({secp256k1-configure})." @@ -222,15 +224,15 @@ "none": { "title": "no backend", "jamfile": "/webcpp/crypto//crypto", - "header": ", ", + "header": ", , ", "library": "webcpp's own header-only code", "licence": "BSL-1.0", "own_api": "none", "allocation": "none", - "constant_time": "`equal` is constant time in the contents: every byte is read, no branch and no index depends on one", + "constant_time": "`constant_time_equal` is constant time in the contents: every byte is read, no branch and no index depends on one", "constant_time_sources": [], "lane_paths": [ - {"what": "`equal`", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect"]}}, + {"what": "`constant_time_equal`", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect"]}}, {"what": "`is_all_zero` and the wipe of `secret`", "lane": {"native": ["memcheck", "msan"]}} ] } @@ -249,25 +251,26 @@ { "id": "async_gcm", "free": true, - "functions": ["async_make", "async_seal", "async_open"], + "functions": ["async_from_key", "async_seal", "async_open"], "namespace": "root", - "api": "async_make, async_seal, async_open", + "api": "async_from_key, secret_key_encryption::aead::async_seal, secret_key_encryption::aead::async_open", "header": "", - "what": "AES-GCM's asynchronous make, seal and open, each completing through a post to the executor the call gives, with any Asio completion token.", + "what": "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.", "section": "crypto-async", "backends": { "bearssl": {"tests": ["async_gcm"]}, - "openssl": {"tests": ["async_gcm_openssl"]} + "openssl": {"tests": ["async_gcm_openssl"]}, + "sodium": {"tests": ["async_aead"]} } }, { "id": "async_ed25519", "free": true, - "functions": ["async_make", "async_generate", "async_sign", "async_verify"], + "functions": ["async_from_secret", "async_generate", "async_sign", "async_verify"], "namespace": "root", - "api": "async_make, async_generate, async_sign, async_verify", + "api": "async_from_secret, async_generate, async_sign, async_verify", "header": "", - "what": "Ed25519's asynchronous make, generate, sign and verify with `crypto::eddsa`, each completing through a post to the executor the call gives, with any Asio completion token.", + "what": "Ed25519's asynchronous from_secret, generate, sign and verify with `crypto::eddsa`, and on a native backend with `crypto::eddsa_prehashed` (Ed25519ph, which WebCrypto lacks), each completing through a post to the executor the call gives, with any Asio completion token.", "section": "crypto-async", "backends": { "sodium": {"tests": ["async_25519", "async_post"]} @@ -276,11 +279,12 @@ { "id": "async_x25519", "free": true, - "functions": ["async_agree"], + "functions": ["async_from_secret", "async_generate", "async_agree"], "namespace": "root", - "api": "async_agree", + "api": "async_from_secret, async_generate, async_agree", + "overloads": {"async_agree": "requires detail::agrees_with_peer"}, "header": "", - "what": "X25519's asynchronous agree, completing through a post to the executor the call gives, with any Asio completion token.", + "what": "X25519's asynchronous from_secret, generate and agree, of a key pair and a peer's `curves::x25519::public_key`, each completing through a post to the executor the call gives, with any Asio completion token.", "section": "crypto-async", "backends": { "sodium": {"tests": ["async_25519"]} @@ -289,26 +293,36 @@ { "id": "async_p256", "free": true, - "functions": ["async_make", "async_generate", "async_sign", "async_verify", "async_agree"], + "functions": ["async_from_secret", "async_generate", "async_sign", "async_verify", "async_agree"], "namespace": "root", - "api": "async_make, async_generate, async_sign, async_verify, async_agree", - "overloads": {"async_verify": "p256::basic_public_key", "async_agree": "p256::basic_keypair"}, + "api": "async_from_secret, async_generate, async_sign, async_verify, async_agree", + "overloads": {"async_verify": "p256::basic_public_key", "async_agree": "requires detail::agrees_with_peer"}, "header": "", - "what": "P-256's asynchronous make, generate, ECDSA sign and verify with `crypto::ecdsa_sha256`, of a message hashed with SHA-256 or `crypto::prehashed{digest}`, and ECDH's raw x, each completing through a post to the executor the call gives, with any Asio completion token.", + "what": "P-256's asynchronous from_secret, generate, ECDSA sign and verify with `crypto::ecdsa_sha256`, of a message hashed with SHA-256 or `crypto::prehashed{digest}`, and ECDH's raw x, each completing through a post to the executor the call gives, with any Asio completion token.", "section": "crypto-async", "backends": { "bearssl": {"tests": ["async_p256"]} } }, { - "id": "equal", - "functions": ["equal"], + "id": "constant_time_equal", + "functions": ["constant_time_equal"], "namespace": "root", - "api": "equal", - "header": "", + "api": "constant_time_equal", + "header": "", "what": "Compares two tags or MACs in constant time.", - "section": "crypto-equal", - "backends": {"none": {"tests": ["equal"]}} + "section": "crypto-constant-time-equal", + "backends": {"none": {"tests": ["constant_time_equal"]}} + }, + { + "id": "erase_secret", + "functions": ["erase_secret"], + "namespace": "root", + "api": "erase_secret", + "header": "", + "what": "Zeroes a buffer the program owns, a password, a key or a plaintext, with stores the optimiser keeps.", + "section": "crypto-erase-secret", + "backends": {"none": {"tests": ["erase_secret"]}} }, { "id": "error", @@ -323,7 +337,7 @@ { "id": "aes_block", "family": "aes_block", - "functions": ["make", "encrypt", "decrypt"], + "functions": ["from_key", "encrypt", "decrypt"], "namespace": "ciphers", "api": "ciphers::aes128, aes192, aes256", "header": ", ", @@ -339,7 +353,7 @@ { "id": "gcm", "family": "gcm", - "functions": ["make", "gcm::async_make", "seal", "gcm::async_seal", "open", + "functions": ["from_key", "gcm::async_from_key", "seal", "gcm::async_seal", "open", "gcm::async_open", "begin_seal", "update", "result", "begin_open", "authenticate", "verify", "decrypt", "end_open"], "namespace": "ciphers", @@ -359,11 +373,11 @@ { "id": "keypair", "family": "secp256k1", - "functions": ["basic_keypair::make", "generate", "basic_keypair::public_key", "basic_keypair::secret", "sign", "agree", "agree_hashed", "agree_point", "basic_keypair::tweak_xonly"], + "functions": ["basic_keypair::from_secret", "generate", "basic_keypair::public_key", "basic_keypair::secret", "sign", "agree", "agree_hashed", "agree_point", "basic_keypair::tweak_xonly"], "namespace": "curves", "api": "curves::secp256k1::keypair", "header": "", - "what": "A secp256k1 key pair: made from its 32-byte secret key, which `secret()` gives back, or drawn from `random_device`; its public key, a `curves::secp256k1::public_key`; `sign(crypto::schnorr, message)` (BIP 340, its auxiliary randomness drawn or given), `sign(crypto::ecdsa_sha256, input)` (hedged too) and `sign(crypto::ecdsa_sha256_recoverable, input)`, the input a message hashed inside or `crypto::prehashed{digest}`; ECDH in three forms, `agree` (the shared x), `agree_hashed` and `agree_point`, each with a peer's `public_key`; and the x-only tweak.", + "what": "A secp256k1 key pair: made from its 32-byte secret key, which `secret()` gives back, or drawn from `random_device`; its public key, a `curves::secp256k1::public_key`; `sign(crypto::schnorr, message)` (BIP 340, its auxiliary randomness drawn or given), `sign(crypto::ecdsa_sha256, input)` (hedged too), `sign(crypto::ecdsa_sha256_recoverable, input)` and Ethereum's `sign(crypto::ecdsa_keccak256_recoverable, input)`, the input a message hashed inside (with Keccak-256 for Ethereum's, which needs `/third_party//xkcp`) or `crypto::prehashed{digest}`; ECDH in three forms, `agree` (the shared x), `agree_hashed` and `agree_point`, each with a peer's `public_key`; and the x-only tweak.", "section": "crypto-secp256k1", "backends": {"secp256k1": {"tests": ["secp256k1", "secp256k1_generate", "secp256k1_bip340", "secp256k1_xonly_tweak", "secp256k1_ecdh", "secp256k1_recovery"]}} }, @@ -375,7 +389,7 @@ "namespace": "curves", "api": "crypto::verify, curves::secp256k1::recover", "header": "", - "what": "Verifies a BIP 340 signature against a `curves::secp256k1::public_key` or its 32-byte x-only form, `crypto::verify(crypto::schnorr, signature, message, key)`, or an ECDSA one against a `curves::secp256k1::public_key`, `crypto::verify(crypto::ecdsa_sha256, signature, input, public_key)`, refusing a high S; `recover(crypto::ecdsa_sha256_recoverable, signature, input)` gives the signer's key.", + "what": "Verifies a BIP 340 signature against a `curves::secp256k1::public_key` or its 32-byte x-only form, `crypto::verify(crypto::schnorr, signature, message, key)`, or an ECDSA one against a `curves::secp256k1::public_key`, `crypto::verify(crypto::ecdsa_sha256, signature, input, public_key)`, refusing a high S; `recover(crypto::ecdsa_sha256_recoverable, signature, input)` and `recover(crypto::ecdsa_keccak256_recoverable, signature, input)` give the signer's key.", "section": "crypto-secp256k1", "backends": {"secp256k1": {"tests": ["secp256k1_bip340", "secp256k1_wycheproof", "secp256k1_recovery", "signing_curves"]}} }, @@ -415,13 +429,13 @@ { "id": "ed25519_keypair", "family": "ed25519", - "functions": ["basic_keypair::make", "generate", "basic_keypair::async_make", + "functions": ["basic_keypair::from_secret", "generate", "basic_keypair::async_from_secret", "basic_keypair::async_generate", "basic_keypair::public_key", "secret", - "sign", "basic_keypair::async_sign", "x25519_secret"], + "sign", "basic_keypair::async_sign", "basic_keypair::to_x25519"], "namespace": "curves", "api": "curves::ed25519::keypair", "header": "", - "what": "An Ed25519 key pair (RFC 8032): made from a 32-byte seed, which `secret()` gives back, or drawn from `random_device`; its public key, a `curves::ed25519::public_key`; 64-byte signatures of a message with `sign(crypto::eddsa, message)`; and its X25519 secret key.", + "what": "An Ed25519 key pair (RFC 8032): made from a 32-byte seed, which `secret()` gives back, or drawn from `random_device`; its public key, a `curves::ed25519::public_key`; 64-byte signatures of a message with `sign(crypto::eddsa, message)`, and of a message's SHA-512 with `sign(crypto::eddsa_prehashed, crypto::prehashed{digest})` (Ed25519ph, native backends); and its X25519 key pair, `to_x25519()`.", "section": "crypto-ed25519", "backends": { "sodium": {"tests": ["ed25519_sodium", "oracle_25519"]}, @@ -431,11 +445,12 @@ { "id": "ed25519_public_key", "family": "ed25519", - "functions": ["public_key::make", "bytes", "public_key::verify", "public_key::async_verify"], + "functions": ["public_key::from_bytes", "bytes", "public_key::verify", "public_key::async_verify", + "public_key::to_x25519"], "namespace": "curves", "api": "curves::ed25519::public_key", "header": "", - "what": "An Ed25519 public key, its 32 bytes, which `crypto::verify(crypto::eddsa, ...)` takes: made from bytes with only their size checked, since whether the point is canonical and not of small order is the verification policy's judgment.", + "what": "An Ed25519 public key, its 32 bytes, which `crypto::verify(crypto::eddsa, ...)` takes: made from bytes with only their size checked, since whether the point is canonical and not of small order is the verification policy's judgment; and its X25519 public key, `to_x25519()`.", "section": "crypto-ed25519", "backends": { "sodium": {"tests": ["ed25519_sodium", "oracle_25519"]}, @@ -450,56 +465,57 @@ "namespace": "curves", "api": "crypto::verify", "header": "", - "what": "Verifies an Ed25519 signature with a public key alone, `crypto::verify(crypto::eddsa, signature, message, public_key)`, under the policy `strict`: libsodium's rules, which refuse non-canonical encodings and keys of small order.", + "what": "Verifies an Ed25519 signature with a public key alone, `crypto::verify(crypto::eddsa, signature, message, public_key)`, or an Ed25519ph one, `crypto::verify(crypto::eddsa_prehashed, signature, crypto::prehashed{digest}, public_key)`, under the policy `strict`: libsodium's rules, which refuse non-canonical encodings and keys of small order.", "section": "crypto-ed25519", "backends": {"sodium": {"tests": ["ed25519_sodium", "ed25519_wycheproof_sodium", "ed25519_speccheck", "oracle_25519"]}} }, { "id": "ed25519ph", "family": "ed25519", - "functions": ["begin", "update", "ph::sign", "ph::verify"], + "functions": ["begin", "update", "prehashed_signer::sign", "prehashed_signer::verify"], "namespace": "curves", - "api": "curves::ed25519::ph", + "api": "curves::ed25519::prehashed_signer", "header": "", - "what": "Ed25519ph (RFC 8032): a message given in pieces, hashed with SHA-512, then signed with a key pair or verified with `verify(signature, public_key)`.", + "what": "Ed25519ph (RFC 8032), the streaming form of the scheme `crypto::eddsa_prehashed`: a message given in pieces, hashed with SHA-512, then signed with a key pair or verified with `verify(signature, public_key)`, the signature `sign(crypto::eddsa_prehashed, crypto::prehashed{digest})` gives of its SHA-512.", "section": "crypto-ed25519", "backends": {"sodium": {"tests": ["ed25519ph_sodium"]}} }, { - "id": "ed25519_to_x25519_public", + "id": "ed25519_to_x25519", "family": "ed25519", "free": true, - "functions": ["to_x25519_public"], + "functions": ["to_x25519"], "namespace": "curves", - "api": "curves::ed25519::to_x25519_public", + "api": "crypto::to_x25519", "header": "", - "what": "The X25519 public key of an Ed25519 public key (the birational map), refusing a key of small order or not canonical with `invalid_public_key`.", + "what": "Converts an Ed25519 key pair to an X25519 key pair of its backend, and an Ed25519 public key to an X25519 public key (the birational map), refusing a key of small order or not canonical with `invalid_public_key`: the free form of both members, `to_x25519()`, synchronous on every backend.", "section": "crypto-x25519", - "backends": {"sodium": {"tests": ["x25519_sodium"]}} + "backends": {"sodium": {"tests": ["ed25519_sodium", "x25519_sodium"]}} }, { - "id": "x25519_public_key", + "id": "x25519_keypair", "family": "x25519", - "free": true, - "functions": ["public_key"], + "functions": ["basic_keypair::from_secret", "generate", "basic_keypair::async_from_secret", + "basic_keypair::async_generate", "basic_keypair::public_key", + "basic_keypair::secret", "basic_keypair::agree", + "basic_keypair::async_agree"], "namespace": "curves", - "api": "curves::x25519::public_key", + "api": "curves::x25519::keypair", "header": "", - "what": "The 32-byte X25519 public key of a 32-byte secret key (RFC 7748).", + "what": "An X25519 key pair (RFC 7748): made from its 32-byte secret key, which `secret()` gives back, or drawn from `random_device`; its public key, a `curves::x25519::public_key`, computed once; and `agree(peer)`, the 32-byte shared secret with a peer's public key, a `secret<32>`, refused with `weak_public_key` when it is all zero (a peer key of low order).", "section": "crypto-x25519", - "backends": {"sodium": {"tests": ["x25519_sodium", "oracle_25519"]}} + "backends": {"sodium": {"tests": ["x25519_sodium", "x25519_wycheproof_sodium", "oracle_25519"]}} }, { - "id": "x25519_agree", + "id": "x25519_public_key", "family": "x25519", - "free": true, - "functions": ["agree"], + "functions": ["public_key::from_bytes", "public_key::bytes"], "namespace": "curves", - "api": "curves::x25519::agree", + "api": "curves::x25519::public_key", "header": "", - "what": "The 32-byte shared secret of a secret key and a peer's public key, a `secret<32>`, refused with `weak_public_key` when it is all zero (a peer key of low order).", + "what": "An X25519 public key, its 32 bytes, which a key pair's `agree` takes: made from bytes with only their size checked, since a key of low order is `agree`'s refusal, `weak_public_key`.", "section": "crypto-x25519", - "backends": {"sodium": {"tests": ["x25519_sodium", "x25519_wycheproof_sodium", "oracle_25519"]}} + "backends": {"sodium": {"tests": ["x25519_sodium", "oracle_25519"]}} }, { "id": "ed25519_formats", @@ -540,18 +556,20 @@ { "id": "kx_keypair", "family": "kx", - "functions": ["make", "generate", "public_key", "client_session_keys", "server_session_keys"], - "namespace": "curves", - "api": "curves::x25519::kx_keypair", - "header": "", - "what": "libsodium's `crypto_kx`: a key pair made from a 32-byte seed or drawn from `random_device`, and the two session keys of a client or a server, each a `secret<32>`, from the peer's public key; a peer key of low order is refused with `weak_public_key`.", + "functions": ["from_keypair", "derive_from_seed", "generate", "keypair", "public_key", "client_session_keys", "server_session_keys"], + "namespace": "key_exchange", + "api": "key_exchange::kx_keypair", + "header": "", + "what": "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 `secret<32>`, from the peer's X25519 public key; a peer key of low order is refused with `weak_public_key`.", "section": "crypto-kx", "backends": {"sodium": {"tests": ["kx_sodium", "kx_wipe_sodium", "allocation_sodium"]}} }, { "id": "chacha20_poly1305", "family": "chacha20_poly1305", - "functions": ["make", "seal", "open"], + "functions": ["from_key", "basic_chacha20_poly1305::async_from_key", "seal", + "basic_chacha20_poly1305::async_seal", "open", + "basic_chacha20_poly1305::async_open"], "namespace": "ciphers", "api": "ciphers::chacha20_poly1305", "header": ", ", @@ -572,7 +590,9 @@ { "id": "chacha20_poly1305_original", "family": "chacha20_poly1305_original", - "functions": ["make", "seal", "open"], + "functions": ["from_key", "basic_chacha20_poly1305::async_from_key", "seal", + "basic_chacha20_poly1305::async_seal", "open", + "basic_chacha20_poly1305::async_open"], "namespace": "ciphers", "api": "ciphers::chacha20_poly1305_original", "header": ", ", @@ -584,7 +604,9 @@ { "id": "xchacha20_poly1305", "family": "xchacha20_poly1305", - "functions": ["make", "seal", "open"], + "functions": ["from_key", "basic_chacha20_poly1305::async_from_key", "seal", + "basic_chacha20_poly1305::async_seal", "open", + "basic_chacha20_poly1305::async_open"], "namespace": "ciphers", "api": "ciphers::xchacha20_poly1305", "header": ", ", @@ -596,35 +618,37 @@ { "id": "secretbox", "family": "secretbox_xsalsa20poly1305", - "functions": ["make", "seal", "open"], - "namespace": "ciphers", - "api": "ciphers::secretbox", - "header": ", ", - "what": "NaCl's and libsodium's `crypto_secretbox`, XSalsa20-Poly1305: authenticated encryption in place under a 32-byte key, with a 24-byte nonce safe to draw at random and no additional data.", + "functions": ["from_key", "basic_secretbox::async_from_key", "seal", + "basic_secretbox::async_seal", "open", "basic_secretbox::async_open"], + "namespace": "secret_key_encryption", + "api": "secret_key_encryption::secretbox", + "header": ", ", + "what": "NaCl's and libsodium's `crypto_secretbox`, XSalsa20-Poly1305: authenticated encryption in place under a 32-byte key, with a 24-byte nonce safe to draw at random and no associated data, an `authenticated_box` whose free forms are `secret_key_encryption::seal` and `open`.", "section": "crypto-secretbox", "default": "`secretbox<>` names the default backend.", - "backends": {"sodium": {"tests": ["secretbox_sodium", "box_sodium", "allocation_sodium"]}} + "backends": {"sodium": {"tests": ["secretbox_sodium", "box_sodium", "allocation_sodium", "aead_concepts"]}} }, { "id": "secretbox_xchacha20poly1305", "family": "secretbox_xchacha20poly1305", - "functions": ["make", "seal", "open"], - "namespace": "ciphers", - "api": "ciphers::secretbox_xchacha20poly1305", - "header": ", ", + "functions": ["from_key", "basic_secretbox::async_from_key", "seal", + "basic_secretbox::async_seal", "open", "basic_secretbox::async_open"], + "namespace": "secret_key_encryption", + "api": "secret_key_encryption::secretbox_xchacha20poly1305", + "header": ", ", "what": "libsodium's `crypto_secretbox_xchacha20poly1305`: the secret box with XChaCha20 in place of XSalsa20.", "section": "crypto-secretbox", "default": "`secretbox_xchacha20poly1305<>` names the default backend.", - "backends": {"sodium": {"tests": ["secretbox_sodium", "box_sodium", "allocation_sodium"]}} + "backends": {"sodium": {"tests": ["secretbox_sodium", "box_sodium", "allocation_sodium", "aead_concepts"]}} }, { "id": "box", "family": "box_xsalsa20poly1305", - "functions": ["make", "seal", "open"], - "namespace": "hybrid", - "api": "hybrid::box", - "header": "", - "what": "NaCl's and libsodium's `crypto_box`: X25519 agrees a key once per pair of keys, refusing a peer key of small order, then XSalsa20-Poly1305 seals and opens each message in place, with a 24-byte nonce safe to draw at random.", + "functions": ["from_keys", "seal", "basic_box::async_seal", "open", "basic_box::async_open"], + "namespace": "public_key_encryption", + "api": "public_key_encryption::box", + "header": "", + "what": "NaCl's and libsodium's `crypto_box`: X25519 agrees a key once per pair of keys, from the own X25519 key pair and the peer's X25519 public key, refusing a peer key of small order, then XSalsa20-Poly1305 seals and opens each message in place, with a 24-byte nonce safe to draw at random.", "section": "crypto-box", "default": "`box` names the default backend.", "backends": {"sodium": {"tests": ["box_sodium", "allocation_sodium"]}} @@ -632,10 +656,10 @@ { "id": "box_xchacha20poly1305", "family": "box_xchacha20poly1305", - "functions": ["make", "seal", "open"], - "namespace": "hybrid", - "api": "hybrid::box_xchacha20poly1305", - "header": "", + "functions": ["from_keys", "seal", "basic_box::async_seal", "open", "basic_box::async_open"], + "namespace": "public_key_encryption", + "api": "public_key_encryption::box_xchacha20poly1305", + "header": "", "what": "libsodium's `crypto_box_curve25519xchacha20poly1305`: the box with XChaCha20 in place of XSalsa20.", "section": "crypto-box", "default": "`box_xchacha20poly1305` names the default backend.", @@ -645,10 +669,10 @@ "id": "sealed_box", "family": "sealed_box", "functions": ["seal", "open"], - "namespace": "hybrid", - "api": "hybrid::sealed_box", - "header": "", - "what": "libsodium's sealed boxes, `crypto_box_seal`: anonymous encryption to a public key under a key pair drawn per message, 48 bytes longer than the message, which only the recipient's key pair opens.", + "namespace": "public_key_encryption", + "api": "public_key_encryption::sealed_box", + "header": "", + "what": "libsodium's sealed boxes, `crypto_box_seal`: anonymous encryption to an X25519 public key under a key pair drawn per message, 48 bytes longer than the message, which only the recipient's X25519 key pair opens.", "section": "crypto-sealed-box", "default": "`sealed_box` names the default backend.", "backends": {"sodium": {"tests": ["box_sodium", "allocation_sodium"]}} @@ -661,14 +685,14 @@ "namespace": "curves", "api": "curves::secp256k1::recover", "header": "", - "what": "The public key that made a recoverable ECDSA signature, `recover(crypto::ecdsa_sha256_recoverable, signature, input)`, the input as signing took it: a message hashed inside or `crypto::prehashed{digest}`.", + "what": "The public key that made a recoverable ECDSA signature, `recover(crypto::ecdsa_sha256_recoverable, signature, input)` or Ethereum's `recover(crypto::ecdsa_keccak256_recoverable, signature, input)`, the input as signing took it: a message hashed inside (with SHA-256, or Keccak-256) or `crypto::prehashed{digest}`.", "section": "crypto-secp256k1-recovery", "backends": {"secp256k1": {"tests": ["secp256k1_recovery"]}} }, { "id": "public_key", "family": "secp256k1", - "functions": ["public_key::make", "compressed", "uncompressed", "xonly", "public_key::verify"], + "functions": ["public_key::from_bytes", "compressed", "uncompressed", "xonly", "public_key::verify"], "namespace": "curves", "api": "curves::secp256k1::public_key", "header": "", @@ -680,9 +704,9 @@ "id": "key_tweaks", "family": "secp256k1", "free": true, - "functions": ["seckey_tweak_add", "seckey_tweak_mul", "seckey_negate", "pubkey_tweak_add", "pubkey_tweak_mul", "pubkey_negate", "pubkey_combine"], + "functions": ["secret_key_tweak_add", "secret_key_tweak_mul", "secret_key_negate", "public_key_tweak_add", "public_key_tweak_mul", "public_key_negate", "public_key_combine"], "namespace": "curves", - "api": "curves::secp256k1::seckey_tweak_add, seckey_tweak_mul, seckey_negate, pubkey_tweak_add, pubkey_tweak_mul, pubkey_negate, pubkey_combine", + "api": "curves::secp256k1::secret_key_tweak_add, secret_key_tweak_mul, secret_key_negate, public_key_tweak_add, public_key_tweak_mul, public_key_negate, public_key_combine", "header": "", "what": "A secret or public key plus or times a tweak, its negation, and the sum of public keys.", "section": "crypto-secp256k1-tweaks", @@ -715,9 +739,9 @@ { "id": "musig", "family": "secp256k1_musig", - "functions": ["xonly_public_key", "full_public_key", "tweak_add", "tweak_xonly_add", "workspace_size", "key_aggregate", "nonce_gen", "nonce_aggregate", "nonce_process", "partial_sign", "partial_signature_verify", "partial_signature_aggregate", "parse_public_nonce", "serialize_public_nonce", "parse_aggregate_nonce", "serialize_aggregate_nonce", "parse_partial_signature", "serialize_partial_signature"], + "functions": ["xonly_public_key", "full_public_key", "tweak_add", "tweak_xonly_add", "workspace_size", "key_aggregate", "generate_nonce", "nonce_aggregate", "nonce_process", "partial_sign", "partial_signature_verify", "partial_signature_aggregate", "parse_public_nonce", "serialize_public_nonce", "parse_aggregate_nonce", "serialize_aggregate_nonce", "parse_partial_signature", "serialize_partial_signature"], "namespace": "curves", - "api": "curves::secp256k1::musig::aggregate_key, key_aggregate, nonce_gen, nonce_aggregate, nonce_process, partial_sign, partial_signature_verify, partial_signature_aggregate, parse_public_nonce, serialize_public_nonce, parse_aggregate_nonce, serialize_aggregate_nonce, parse_partial_signature, serialize_partial_signature", + "api": "curves::secp256k1::musig::aggregate_key, key_aggregate, generate_nonce, nonce_aggregate, nonce_process, partial_sign, partial_signature_verify, partial_signature_aggregate, parse_public_nonce, serialize_public_nonce, parse_aggregate_nonce, serialize_aggregate_nonce, parse_partial_signature, serialize_partial_signature", "header": "", "what": "BIP 327's MuSig2: many signers' keys aggregated into one, and their two rounds into one BIP 340 signature, each secret nonce consumed by its partial signature.", "section": "crypto-secp256k1-musig", @@ -727,9 +751,9 @@ "id": "silent_payments", "family": "secp256k1_silent_payments", "free": true, - "functions": ["send_workspace_size", "summary_workspace_size", "scan_workspace_size", "create_outputs", "create_label", "create_labeled_spend_key", "make_prevouts_summary", "scan_outputs"], + "functions": ["send_workspace_size", "summary_workspace_size", "scan_workspace_size", "create_outputs", "create_label", "create_labeled_spend_key", "make_previous_outputs_summary", "scan_outputs"], "namespace": "curves", - "api": "curves::secp256k1::silent_payments::create_outputs, create_label, create_labeled_spend_key, make_prevouts_summary, scan_outputs, send_workspace_size, summary_workspace_size, scan_workspace_size", + "api": "curves::secp256k1::silent_payments::create_outputs, create_label, create_labeled_spend_key, make_previous_outputs_summary, scan_outputs, send_workspace_size, summary_workspace_size, scan_workspace_size", "header": "", "what": "BIP 352's silent payments: the sender's outputs to a reusable address of a scan and a spend key, the recipient's labels, and its scan of a transaction's outputs.", "section": "crypto-secp256k1-silent-payments", @@ -738,7 +762,7 @@ { "id": "p256_keypair", "family": "p256", - "functions": ["basic_keypair::make", "generate", "basic_keypair::async_make", + "functions": ["basic_keypair::from_secret", "generate", "basic_keypair::async_from_secret", "basic_keypair::async_generate", "public_key", "secret"], "namespace": "curves", "api": "curves::p256::keypair", @@ -753,7 +777,8 @@ { "id": "p256_public_key", "family": "p256", - "functions": ["basic_public_key::make", "uncompressed", "basic_public_key::verify", + "functions": ["basic_public_key::from_bytes", "from_coordinates", "uncompressed", + "basic_public_key::verify", "basic_public_key::async_verify"], "namespace": "curves", "api": "curves::p256::public_key", @@ -774,7 +799,7 @@ "namespace": "curves", "api": "curves::p256::keypair::sign; crypto::verify, to_der, from_der, normalize_low_s, is_low_s", "header": "", - "what": "ECDSA over SHA-256 with RFC 6979's nonce, `sign(crypto::ecdsa_sha256, input)` and `crypto::verify(crypto::ecdsa_sha256, signature, input, public_key)`, the input a message hashed inside or `crypto::prehashed{digest}`; r and s as 64 bytes, signed low S, verified whatever its S; strict DER both ways; `normalize_low_s` and `is_low_s` for a signature made elsewhere.", + "what": "ECDSA over SHA-256 with RFC 6979's nonce, `sign(crypto::ecdsa_sha256, input)` and `crypto::verify(crypto::ecdsa_sha256, signature, input, public_key)`, the input a message hashed inside or `crypto::prehashed{digest}`; the signature a `curves::p256::ecdsa_signature`, r and s, signed low S, verified whatever its S; strict DER both ways; `normalize_low_s` and `is_low_s` for a signature made elsewhere.", "section": "crypto-p256-ecdsa", "backends": { "bearssl": {"tests": ["p256_ecdsa_bearssl", "p256_wycheproof_bearssl", "p256_openssl_oracle", "p256_webcrypto_oracle", "allocation_bearssl"]}, @@ -886,7 +911,7 @@ "header": "", "names": [ {"name": "ed25519", "title": "Ed25519", "type": "curves::ed25519::basic_keypair<{backend}>"}, - {"name": "ed25519ph", "title": "Ed25519ph", "type": "curves::ed25519::ph"} + {"name": "ed25519ph", "title": "Ed25519ph", "type": "curves::ed25519::prehashed_signer"} ], "default": [ {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": ["ed25519_sodium", "default_backend_none_linked"], "why": "the only backend in this version, on every target, and its verification is the policy `strict` ({libsodium-signatures}; {rfc8032})"} @@ -903,7 +928,7 @@ "measured": "agreement of a secret key and a public key", "header": "", "names": [ - {"name": "x25519", "title": "X25519", "type": "curves::x25519::algorithm<{backend}>"} + {"name": "x25519", "title": "X25519", "type": "curves::x25519::basic_keypair<{backend}>"} ], "default": [ {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": ["x25519_sodium", "default_backend_none_linked"], "why": "the only backend in this version, on every target; it refuses an all-zero shared secret itself ({rfc7748})"} @@ -915,12 +940,12 @@ { "name": "kx", "title": "crypto_kx", - "group": "curves::x25519", + "group": "key_exchange", "since": "0.2", "measured": "a client's session keys from a key pair and the server's public key", - "header": "", + "header": "", "names": [ - {"name": "kx", "title": "crypto_kx", "type": "curves::x25519::kx_keypair<{backend}>"} + {"name": "kx", "title": "crypto_kx", "type": "key_exchange::kx_keypair<{backend}>"} ], "default": [ {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": ["kx_sodium", "default_backend_none_linked"], "why": "the only backend that has it: libsodium's own construction, whose session keys only another `crypto_kx` derives ({libsodium-kx})"} @@ -1005,12 +1030,12 @@ { "name": "secretbox_xsalsa20poly1305", "title": "XSalsa20-Poly1305 secret box", - "group": "ciphers", + "group": "secret_key_encryption", "since": "0.2", "measured": "seal of 16 KiB, 256-bit key", - "header": "", + "header": "", "names": [ - {"name": "secretbox_xsalsa20poly1305", "title": "XSalsa20-Poly1305 secret box", "type": "ciphers::secretbox<{backend}>"} + {"name": "secretbox_xsalsa20poly1305", "title": "XSalsa20-Poly1305 secret box", "type": "secret_key_encryption::secretbox<{backend}>"} ], "default": [ {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": ["secretbox_sodium", "default_backend_none_linked"], "why": "the only backend that has it: libsodium's own C code, NaCl's `crypto_secretbox`, the same on every target ({libsodium-secretbox})"} @@ -1022,12 +1047,12 @@ { "name": "secretbox_xchacha20poly1305", "title": "XChaCha20-Poly1305 secret box", - "group": "ciphers", + "group": "secret_key_encryption", "since": "0.2", "measured": "seal of 16 KiB, 256-bit key", - "header": "", + "header": "", "names": [ - {"name": "secretbox_xchacha20poly1305", "title": "XChaCha20-Poly1305 secret box", "type": "ciphers::secretbox_xchacha20poly1305<{backend}>"} + {"name": "secretbox_xchacha20poly1305", "title": "XChaCha20-Poly1305 secret box", "type": "secret_key_encryption::secretbox_xchacha20poly1305<{backend}>"} ], "default": [ {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": ["secretbox_sodium", "default_backend_none_linked"], "why": "the only backend that has it: libsodium's own C code, the same on every target ({libsodium-secretbox})"} @@ -1039,12 +1064,12 @@ { "name": "box_xsalsa20poly1305", "title": "X25519-XSalsa20-Poly1305 box", - "group": "hybrid", + "group": "public_key_encryption", "since": "0.2", "measured": "seal of 16 KiB between two key pairs", - "header": "", + "header": "", "names": [ - {"name": "box_xsalsa20poly1305", "title": "X25519-XSalsa20-Poly1305 box", "type": "hybrid::basic_box"} + {"name": "box_xsalsa20poly1305", "title": "X25519-XSalsa20-Poly1305 box", "type": "public_key_encryption::basic_box"} ], "default": [ {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": ["box_sodium", "default_backend_none_linked"], "why": "the only backend that has it: libsodium's own C code, NaCl's `crypto_box`, the same on every target ({libsodium-box})"} @@ -1056,12 +1081,12 @@ { "name": "box_xchacha20poly1305", "title": "X25519-XChaCha20-Poly1305 box", - "group": "hybrid", + "group": "public_key_encryption", "since": "0.2", "measured": "seal of 16 KiB between two key pairs", - "header": "", + "header": "", "names": [ - {"name": "box_xchacha20poly1305", "title": "X25519-XChaCha20-Poly1305 box", "type": "hybrid::basic_box"} + {"name": "box_xchacha20poly1305", "title": "X25519-XChaCha20-Poly1305 box", "type": "public_key_encryption::basic_box"} ], "default": [ {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": ["box_sodium", "default_backend_none_linked"], "why": "the only backend that has it: libsodium's own C code, the same on every target ({libsodium-box})"} @@ -1073,12 +1098,12 @@ { "name": "sealed_box", "title": "X25519-XSalsa20-Poly1305 sealed box", - "group": "hybrid", + "group": "public_key_encryption", "since": "0.2", "measured": "seal of 16 KiB to a public key", - "header": "", + "header": "", "names": [ - {"name": "sealed_box", "title": "X25519-XSalsa20-Poly1305 sealed box", "type": "hybrid::basic_sealed_box<{backend}>"} + {"name": "sealed_box", "title": "X25519-XSalsa20-Poly1305 sealed box", "type": "public_key_encryption::basic_sealed_box<{backend}>"} ], "default": [ {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": ["box_sodium", "default_backend_none_linked"], "why": "the only backend that has it: libsodium's own C code, which draws the key pair of each message from its own generator, the same on every target ({libsodium-sealed})"} @@ -1118,7 +1143,7 @@ {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "secp256k1", "tests": ["secp256k1_musig", "default_backend_none_linked"], "why": "the only backend ({libsecp256k1})"} ], "backends": { - "secp256k1": {"targets": "all", "runtime": false, "lane": {"native": ["memcheck", "msan"]}, "lane_note": {"memcheck": "libsecp256k1's own `ctime_tests.c`, and webcpp's `nonce_gen` and `partial_sign` around it", "msan": "the same paths as memcheck's"}} + "secp256k1": {"targets": "all", "runtime": false, "lane": {"native": ["memcheck", "msan"]}, "lane_note": {"memcheck": "libsecp256k1's own `ctime_tests.c`, and webcpp's `generate_nonce` and `partial_sign` around it", "msan": "the same paths as memcheck's"}} } }, { @@ -1158,16 +1183,16 @@ } ], "rules": [ - {"title": "Never reuse an IV under one key", "section": "crypto-gcm-rules", "text": "two AES-GCM messages under one key and one IV reveal the XOR of their plaintexts and let an attacker forge tags for every later message ({joux}; {nonce-reuse}); draw a random 12-byte IV per message, or use a counter that never repeats, a restart included."}, - {"title": "The usage limit", "section": "crypto-gcm-rules", "text": "with random IVs, at most 2^32 messages under one key ({sp800-38d}, section 8.3); rotate the key before."}, + {"title": "Never reuse a nonce under one key", "section": "crypto-gcm-rules", "text": "two AES-GCM messages under one key and one nonce reveal the XOR of their plaintexts and let an attacker forge tags for every later message ({joux}; {nonce-reuse}); draw a random 12-byte nonce per message, or use a counter that never repeats, a restart included."}, + {"title": "The usage limit", "section": "crypto-gcm-rules", "text": "with random nonces, at most 2^32 messages under one key ({sp800-38d}, section 8.3); rotate the key before."}, {"title": "A failed open zeroes data", "section": "crypto-gcm-rules", "text": "when the tag does not match, `open` returns `authentication_failed` and zeroes the whole of `data`; keep a copy of the ciphertext if it is needed after a failure. the incremental open authenticates every piece and verifies the tag before it decrypts any; a stream read only once is sealed in records."}, - {"title": "Records: each stream its own key", "section": "crypto-gcm-incremental", "text": "records numbered from 0 with the number as IV are safe only under a key used for that one stream: derive a key per stream (HKDF of the storage key with a random salt) or draw one; never number two streams' records under one key."}, + {"title": "Records: each stream its own key", "section": "crypto-gcm-incremental", "text": "records numbered from 0 with the number as nonce are safe only under a key used for that one stream: derive a key per stream (HKDF of the storage key with a random salt) or draw one; never number two streams' records under one key."}, {"title": "ECDH's form", "section": "crypto-secp256k1-ecdh", "text": "`keypair::agree` returns the raw x coordinate of the shared point, which protocols such as Nostr's NIP-44 ({nip44}) take; `keypair::agree_hashed` returns libsecp256k1's hashed form, the SHA-256 of the compressed shared point. Both sides must use the same form, or they derive different keys. Derive keys with a KDF, never use a shared secret directly."}, - {"title": "The x-only tweak is not BIP 32", "section": "crypto-wallets-taproot", "text": "`tweak_xonly` is BIP 341's even-y arithmetic ({bip341}); BIP 32's child derivation tweaks the full key, with `seckey_tweak_add` and `pubkey_tweak_add`, and computes the tweak with HMAC-SHA-512, a domain library's ({bip32})."}, - {"title": "Ethereum", "section": "crypto-curves", "text": "this version signs and verifies Ethereum's ECDSA, recoverable signatures included (`keypair::sign(crypto::ecdsa_sha256_recoverable, input)`), recovers a signer's public key from a signature and the same input (`recover`), and writes the uncompressed key ({ethereum}); the recovery id's `v` encoding, the hash Ethereum signs, transactions and addresses are a domain library's."}, - {"title": "Compare secrets in constant time", "section": "crypto-equal", "text": "compare a tag, a MAC or a token with `equal`, never `==` or `memcmp` ({cwe208})."}, - {"title": "Secrets come from random_device", "section": "crypto-entropy", "text": "keys, IVs and tokens are drawn from `random_device`, never `std::mt19937` or `rand` ({cwe338})."}, - {"title": "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 IVs ({sp800-38d}). `chacha20_poly1305_original`: a counter only, its 8 bytes are too short to draw."}, + {"title": "The x-only tweak is not BIP 32", "section": "crypto-wallets-taproot", "text": "`tweak_xonly` is BIP 341's even-y arithmetic ({bip341}); BIP 32's child derivation tweaks the full key, with `secret_key_tweak_add` and `public_key_tweak_add`, and computes the tweak with HMAC-SHA-512, a domain library's ({bip32})."}, + {"title": "Ethereum", "section": "crypto-curves", "text": "this version signs Ethereum's recoverable ECDSA over Keccak-256 (`keypair::sign(crypto::ecdsa_keccak256_recoverable, input)`, a message hashed inside or the 32-byte digest a program builds), recovers a signer's public key from a signature and the same input (`recover`), and writes the uncompressed key ({ethereum}); the recovery id's `v` encoding, the digests Ethereum signs (EIP-191, EIP-712, a transaction's), transactions and addresses are a domain library's, which the guide shows over webcpp::hash."}, + {"title": "Compare secrets in constant time", "section": "crypto-constant-time-equal", "text": "compare a tag, a MAC or a token with `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": "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`."} ], @@ -1189,33 +1214,47 @@ "title": "webcpp::crypto", "columns": ["Name", "What it is for", "Header", "Errors", "Standards and sources", "Choose it when"], "rows": [ - ["`random_device`", "Keys, IVs, tokens, nonces: every secret a program draws", "``", "`entropy_unavailable`, `errc::not_supported`", "{getentropy}, {bcryptgenrandom}, {getrandomvalues}, {wasi-random}", "you need a random number an attacker must not predict; never `std::mt19937` or `rand` ({cwe338})"], - ["`equal`", "Checking a tag, a MAC or a token", "``", "none: it returns `bool`", "{cwe208}", "you compare anything secret; never `==` or `memcmp` on a MAC"], + ["`random_device`", "Keys, nonces, tokens: every secret a program draws", "``", "`entropy_unavailable`, `errc::not_supported`", "{getentropy}, {bcryptgenrandom}, {getrandomvalues}, {wasi-random}", "you need a random number an attacker must not predict; never `std::mt19937` or `rand` ({cwe338}); <>"], + ["`constant_time_equal`", "Checking a tag, a MAC or a token", "``", "none: it returns `bool`", "{cwe208}", "you compare anything secret; never `==` or `memcmp` on a MAC; <>"], + ["`erase_secret`", "Erasing a password, a key or a plaintext from a buffer the program owns", "``", "none", "{cwe14}", "a secret sits in a `std::string`, a `std::vector` or an array of the program's and must not outlive its use; never `memset`, which the optimiser may drop; <>"], + ["`secret`", "Holding a secret crypto gives back: a key pair's `secret()`, a shared secret, a session key", "``", "none", "{cwe14}", "crypto returns a secret: it wipes itself when destroyed or moved from, is copied only by `clone()`, and gives its bytes with `bytes()`; keep it in one variable; <>"], ["`error`", "Telling failures apart", "``", "its values are the errors", "none", "you branch on a failure: forged data, a wrong size, no entropy"], ["`pem`", "A key's SPKI or PKCS#8 as text, to paste, store or exchange with OpenSSL", "``", "`invalid_encoding`, `invalid_input_size`", "{rfc7468}, {libsodium-base64}", "a key goes to or comes from a file, a form or a tool as `-----BEGIN PUBLIC KEY-----` text; with the `encode_spki` and `encode_pkcs8` of `curves::ed25519`, `curves::x25519`, `curves::secp256k1` or `curves::p256`"], ["`openssl_memory_resource`", "Keeping every allocation of OpenSSL's in the program's own resource, natively", "``", "`memory_functions_refused`, `memory_functions_not_installed`", "{openssl-mem}", "a native program on OpenSSL must allocate only from its own arena; on WebAssembly, BearSSL allocates nothing"], - ["`eddsa`, `ecdsa_sha256`, `ecdsa_sha256_recoverable`, `schnorr`, `prehashed`, `can_sign`, `can_verify`, `sign`, `verify`: Signatures", "Naming the scheme of every signature, and a digest as a digest, on every curve", "``", "`verify`: `invalid_signature`, and `invalid_public_key` for 32 x-only bytes that are no point; `sign`: `invalid_state`, `entropy_unavailable` (Schnorr's drawn randomness), `backend_failure`; a scheme and an input that do not go together stop the build", "{rfc8032}, {fips186-5}, {bip340}, {webcrypto}", "a key pair signs with `key_pair.sign(scheme, input)` or `sign(key_pair, scheme, input)`, and a signature is checked with `public_key.verify(scheme, signature, input)` or `verify(scheme, signature, input, public_key)`; a digest computed elsewhere, such as a Bitcoin sighash, goes in marked as `prehashed`, never as a bare span"], - ["`keypair`, `agree`: The key pair contract", "Code written once for every curve's key pair", "``", "`keypair`: none, a concept checked at compile time; `agree`: what the key pair's `agree` returns, and a peer it does not take stops the build", "{rfc8032}, {fips186-5}, {sec1}", "a template takes any curve's key pair: `make`, `generate`, a typed `public_key()` that `verify` takes, `secret()`, and `sign(scheme, input)`; `agree(key_pair, peer)` is the free form of `key_pair.agree(peer)`"], - ["`make`, `generate`: Making by type", "Making a key pair, a public key or an AEAD from its bytes, or drawing a key pair, the type named once", "``", "the member's: `make(bytes)` returns what `A::make(bytes)` returns, `generate()` what `K::generate()` returns", "none", "generic code makes any key pair, public key or AEAD by its type, `make(bytes)`, or draws a key pair, `generate()`; the free forms of the static members `make` and `generate`"] + ["`eddsa`, `eddsa_prehashed`, `ecdsa_sha256`, `ecdsa_sha256_recoverable`, `ecdsa_keccak256_recoverable`, `schnorr`, `prehashed`, `can_sign`, `can_verify`, `verify`: Signatures", "Naming the scheme of every signature, a digest as a digest, and a signature as a value of its curve and scheme, on every curve", "``", "`verify`: `invalid_signature`, and `invalid_public_key` for 32 x-only bytes that are no point; `sign`: `invalid_state`, `entropy_unavailable` (Schnorr's drawn randomness), `backend_failure`; a scheme and an input that do not go together stop the build", "{rfc8032}, {fips186-5}, {bip340}, {webcrypto}", "a key pair signs with `key_pair.sign(scheme, input)` or `sign(key_pair, scheme, input)`, and a signature is checked with `public_key.verify(scheme, signature, input)` or `verify(scheme, signature, input, public_key)`; a digest computed elsewhere, such as a Bitcoin sighash, an Ethereum EIP-191 digest or the SHA-512 Ed25519ph signs, goes in marked as `prehashed`, never as a bare span; the two recoverable schemes have no `verify`: their signature gives its key to `curves::secp256k1::recover`; a signature is a type of its curve and scheme, made from received bytes by `from_bytes` (<>)"], + ["`keypair`, `signing_keypair`, `agreement_keypair`, `sign`, `agree`: The key pair concepts", "Code written once for every curve's key pair, by what it does", "``", "the concepts: none, checked at compile time; `sign` and `agree`: what the key pair's own returns, and a key pair that does not do the operation, or arguments it does not take, stop the build", "{rfc8032}, {rfc7748}, {fips186-5}, {sec1}", "a template takes any curve's key pair: `from_secret`, `generate`, a typed `public_key()`, `secret()`; a `signing_keypair` (Ed25519, P-256, secp256k1) adds `sign(scheme, input)`, whose `crypto::sign(key_pair, scheme, input)` is the free form, an `agreement_keypair` (X25519, P-256, secp256k1) `agree(peer)`, whose free form is `agree(key_pair, peer)` (<>)"], + ["`from_secret`, `from_bytes`, `from_key`, `generate`: Making by type", "Making a key pair from its secret, a public key or a signature from its bytes, or an AEAD or a secret box from its key, or drawing a key pair, the type named once", "``", "the member's: `from_secret(bytes)` returns what `K::from_secret(bytes)` returns, `from_bytes(bytes)` what `T::from_bytes(bytes)` returns, `from_key(key)` what `C::from_key(key)` returns, `generate()` what `K::generate()` returns", "none", "generic code makes any key pair, public key, signature or AEAD by its type, each factory named by its input, or draws a key pair, `generate()`; the free forms of the static members `from_secret`, `from_bytes`, `from_key` and `generate`; a new key is drawn by `generate`, never made by `from_secret` from fixed bytes (<>)"] ] }, "ciphers": { "title": "webcpp::crypto::ciphers", - "columns": ["Algorithm", "AEAD", "Key", "Nonce (IV)", "Nonce misuse", "Speed, with and without hardware support", "Constant time, by design", "Constant time, measured", "Standards", "Where it is used", "Browsers' WebCrypto", "Choose it when"], + "columns": ["Algorithm", "AEAD", "Key", "Nonce", "Nonce misuse", "Speed, with and without hardware support", "Constant time, by design", "Constant time, measured", "Standards", "Where it is used", "Browsers' WebCrypto", "Choose it when"], "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": "Secret boxes", "rows": [5, 6]} + {"title": "ChaCha20-Poly1305", "rows": [2, 3, 4]} ], "rows": [ - ["`gcm`, `aes128_gcm`, `aes256_gcm`: AES-GCM", "yes", "16, 24 or 32 bytes", "1 to 128 bytes; 12 recommended", "not resistant: a repeated IV 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 IVs, otherwise a counter"], + ["`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"], - ["`secretbox`: XSalsa20-Poly1305 (NaCl's secret box)", "yes, without additional data", "32 bytes", "24 bytes, safe to draw at random", "not resistant to a repeated nonce; random ones never repeat in practice ({xsalsa20})", "{speed:secretbox_xsalsa20poly1305}", "libsodium: yes, additions, XORs and rotations with no table lookup ({salsa20-design})", "{constant_time:secretbox_xsalsa20poly1305}", "none: NaCl's construction ({nacl-secretbox})", "programs that read or write NaCl's and libsodium's `crypto_secretbox` ({libsodium-secretbox})", "no ({webcrypto})", "the data must be read by a program on NaCl's or libsodium's `crypto_secretbox`; otherwise XChaCha20-Poly1305, which also authenticates additional data"], - ["`secretbox_xchacha20poly1305`: XChaCha20-Poly1305 secret box", "yes, without additional data", "32 bytes", "24 bytes, safe to draw at random", "not resistant to a repeated nonce; random ones never repeat in practice ({xchacha-draft})", "{speed:secretbox_xchacha20poly1305}", "libsodium: yes ({libsodium-aead-timing})", "{constant_time:secretbox_xchacha20poly1305}", "none: libsodium's construction ({libsodium-secretbox})", "programs on libsodium's `crypto_secretbox_xchacha20poly1305` ({libsodium-secretbox})", "no ({webcrypto})", "the peer writes libsodium's `crypto_secretbox_xchacha20poly1305`; otherwise `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"] + ] + }, + "secret_key_encryption": { + "title": "webcpp::crypto::secret_key_encryption", + "columns": ["Algorithm", "AEAD", "Key", "Nonce", "Nonce misuse", "Speed, with and without hardware support", "Constant time, by design", "Constant time, measured", "Standards", "Where it is used", "Browsers' WebCrypto", "Choose it when"], + "cited": ["Nonce misuse", "Constant time, by design", "Standards", "Where it is used", "Browsers' WebCrypto"], + "parts": [ + {"title": "Secret boxes", "rows": [0, 1]}, + {"title": "The contracts", "rows": [2, 3]} + ], + "rows": [ + ["`secretbox`: XSalsa20-Poly1305 (NaCl's secret box)", "no: authenticated encryption without associated data, an `authenticated_box`", "32 bytes", "24 bytes, safe to draw at random", "not resistant to a repeated nonce; random ones never repeat in practice ({xsalsa20})", "{speed:secretbox_xsalsa20poly1305}", "libsodium: yes, additions, XORs and rotations with no table lookup ({salsa20-design})", "{constant_time:secretbox_xsalsa20poly1305}", "none: NaCl's construction ({nacl-secretbox})", "programs that read or write NaCl's and libsodium's `crypto_secretbox` ({libsodium-secretbox})", "no ({webcrypto})", "the data must be read by a program on NaCl's or libsodium's `crypto_secretbox`; otherwise `ciphers::xchacha20_poly1305`, which also authenticates associated data"], + ["`secretbox_xchacha20poly1305`: XChaCha20-Poly1305 secret box", "no: authenticated encryption without associated data, an `authenticated_box`", "32 bytes", "24 bytes, safe to draw at random", "not resistant to a repeated nonce; random ones never repeat in practice ({xchacha-draft})", "{speed:secretbox_xchacha20poly1305}", "libsodium: yes ({libsodium-aead-timing})", "{constant_time:secretbox_xchacha20poly1305}", "none: libsodium's construction ({libsodium-secretbox})", "programs on libsodium's `crypto_secretbox_xchacha20poly1305` ({libsodium-secretbox})", "no ({webcrypto})", "the peer writes libsodium's `crypto_secretbox_xchacha20poly1305`; otherwise `ciphers::xchacha20_poly1305`"], + ["`aead`, `aead::cipher`, `aead::streaming_cipher`, `aead::seal`, `aead::open`: The AEAD contract", "the contract every AEAD of `ciphers` satisfies: `cipher` checks a one-shot AEAD's members, `streaming_cipher` the incremental ones of AES-GCM, and `aead::seal` and `aead::open` are their free forms", "the cipher's", "the cipher's", "none: a contract, not an algorithm; each cipher's row in `ciphers` says its own", "none: the free forms call the cipher's members", "none: the cipher's own", "none: the cipher's own", "the interface of {rfc5116}: a key, a nonce, associated data and a message", "none: a contract of types; each cipher's row says where it is used", "none: WebCrypto names algorithms, not a contract ({webcrypto})", "code written once for every AEAD, or a cipher chosen by a template argument; a secret box takes no associated data and is an `authenticated_box`, sealed by `secret_key_encryption::seal`"], + ["`authenticated_box`, `seal`, `open`: The box contract", "no: the contract of authenticated encryption in place without associated data, which the secret boxes and the crypto_boxes of `public_key_encryption` satisfy; `seal` and `open` are their free forms", "the box's: a secret box's 32 bytes, or a crypto_box's two X25519 keys", "the box's", "none: a contract, not an algorithm; each box's row says its own", "none: the free forms call the box's members", "none: the box's own", "none: the box's own", "none: NaCl's interface ({nacl-secretbox}; {nacl-box})", "none: a contract of types; each box's row says where it is used", "no: WebCrypto has neither box ({webcrypto})", "code written once for a secret box and a crypto_box; a crypto_box, of `public_key_encryption`, is sealed by `secret_key_encryption::seal(box, nonce, data)` named in full; an AEAD takes associated data and is an `aead::cipher`"] ] }, "curves": { @@ -1224,59 +1263,67 @@ "cited": ["Standards", "Ecosystems that require it", "Browsers' WebCrypto"], "rows": [ ["`secp256k1`", "BIP 340 Schnorr and ECDSA signatures, recoverable signatures, ECDH in three forms, tweaks, ElligatorSwift, MuSig2, silent payments, SPKI and PKCS#8", "about 128 bits ({sec2})", "secret 32 bytes; public 33 bytes compressed, 65 bytes uncompressed ({sec1}), 32 bytes x-only, 64 bytes as ElligatorSwift ({bip324}); SPKI 56 or 88 bytes ({rfc5480}), PKCS#8 135 bytes ({rfc5208}, {rfc5915})", "64 bytes, MuSig2's aggregate too ({bip327}); 65 bytes recoverable; ECDSA in DER up to 72", "{speed:secp256k1}", "{constant_time:secp256k1}", "{sec2}, {bip340}, {rfc6979}, {bip324}, {bip327}, {bip352}", "Bitcoin ({bip340}), Ethereum ({ethereum}), Nostr ({nip01})", "no: WebCrypto offers P-256, P-384, P-521, Ed25519 and X25519, not secp256k1 ({webcrypto})", "Bitcoin's keys and signatures; Nostr's event signatures ({nip01}); Ethereum's ECDSA verification with a known key; ECDH in the raw x-coordinate form of Nostr's encrypted messages ({nip44}); Ethereum's recoverable signatures and uncompressed keys ({ethereum}), the address hashing being a domain library's; BIP 32's tweaks of the full key, its derivation of the tweak being a domain library's ({bip32}); keys exchanged with OpenSSL as SPKI or PKCS#8 ({rfc5480}, {rfc5915}), in DER or PEM ({rfc7468}); Bitcoin's version 2 transport, whose keys are ElligatorSwift encodings ({bip324}); MuSig2's multisignatures ({bip327}); silent payments ({bip352}), the addresses and transactions being a domain library's"], - ["`ed25519`", "Ed25519 signatures, and Ed25519ph over SHA-512 for a message given in pieces; the X25519 secret key of a key pair", "about 128 bits ({rfc8032})", "secret 32 bytes (the seed); public 32 bytes", "64 bytes", "{speed:ed25519}", "{constant_time:ed25519}", "{rfc8032}, {fips186-5}", "SSH keys ({rfc8709}), Signal's signatures on its Curve25519 keys ({signal-xeddsa}), Tor's identity keys ({tor-cert-spec}), Solana's accounts ({solana-accounts})", "yes: Ed25519 ({webcrypto})", "SSH, Tor and Solana keys and signatures, and any protocol that names RFC 8032's Ed25519 or Ed25519ph; verification is strict (libsodium's rules), which some lenient verifiers are not. Not Bitcoin, Ethereum or Nostr, whose keys are secp256k1's"], - ["`x25519`", "Key agreement (Diffie-Hellman on Curve25519): two parties who exchanged public keys share a 32-byte secret; `kx_keypair`, libsodium's `crypto_kx`, gives a client and a server a session key for each direction", "about 128 bits ({rfc7748})", "secret 32 bytes; public 32 bytes", "none: no signatures", "{speed:x25519}", "{constant_time:x25519}", "{rfc7748}", "TLS 1.3 ({rfc8446-groups}), SSH ({rfc8731}), WireGuard ({wireguard}), Signal ({x3dh})", "yes: X25519 ({webcrypto})", "TLS 1.3's and SSH's key exchange, WireGuard, Signal; libsodium's `crypto_box` keys, and the session keys of `crypto_kx` with `kx_keypair` ({libsodium-kx}). The Ed25519 public key of a peer converts with `curves::ed25519::to_x25519_public`. A shared secret goes through a KDF before it keys a cipher. Every case of Wycheproof's X25519 file is tested ({wycheproof})"], - ["`p256`", "Key pairs made from a 32-byte scalar or drawn from `random_device`, public keys validated once, as SEC 1's uncompressed point or two coordinates, ECDSA over SHA-256 of a message or a digest with RFC 6979's nonce, signed low S, raw and DER, and low S checked or normalized, ECDH's raw x coordinate, SPKI and PKCS#8", "about 128 bits ({sec2})", "secret 32 bytes (the scalar); public 65 bytes uncompressed ({sec1}); SPKI 91 bytes ({rfc5480}), PKCS#8 138 bytes ({rfc5208}, {rfc5915})", "ECDSA: 64 bytes, r and s ({ieee1363}); in DER up to 72 ({rfc3279})", "{speed:p256}", "{constant_time:p256}", "{fips186-5}, {sec2}, {sec1}, {rfc6979}", "passkeys' ES256 ({webauthn}), TLS 1.3 ({rfc8446-groups})", "yes: P-256, for ECDSA and ECDH ({webcrypto})", "Browsers' WebCrypto, whose raw export of a P-256 public key is the uncompressed point `public_key::make` takes ({webcrypto}) and whose ECDH `deriveBits` is the raw x `agree` gives ({webcrypto-ecdh}); passkeys and TLS. Not Bitcoin, Ethereum or Nostr, whose keys are secp256k1's"] + ["`ed25519`", "Ed25519 signatures, and Ed25519ph over SHA-512, of a digest (`crypto::eddsa_prehashed`) or of a message given in pieces; a key pair's and a public key's conversion to X25519's typed keys", "about 128 bits ({rfc8032})", "secret 32 bytes (the seed); public 32 bytes", "64 bytes", "{speed:ed25519}", "{constant_time:ed25519}", "{rfc8032}, {fips186-5}", "SSH keys ({rfc8709}), Signal's signatures on its Curve25519 keys ({signal-xeddsa}), Tor's identity keys ({tor-cert-spec}), Solana's accounts ({solana-accounts})", "yes: Ed25519 ({webcrypto})", "SSH, Tor and Solana keys and signatures, and any protocol that names RFC 8032's Ed25519 or Ed25519ph; verification is strict (libsodium's rules), which some lenient verifiers are not. Not Bitcoin, Ethereum or Nostr, whose keys are secp256k1's"], + ["`x25519`", "Key agreement (Diffie-Hellman on Curve25519): two parties who exchanged public keys share a 32-byte secret, which `key_exchange::kx_keypair` and the boxes of `public_key_encryption` build on", "about 128 bits ({rfc7748})", "secret 32 bytes; public 32 bytes", "none: no signatures", "{speed:x25519}", "{constant_time:x25519}", "{rfc7748}", "TLS 1.3 ({rfc8446-groups}), SSH ({rfc8731}), WireGuard ({wireguard}), Signal ({x3dh})", "yes: X25519 ({webcrypto})", "TLS 1.3's and SSH's key exchange, WireGuard, Signal; libsodium's `crypto_box` keys, and the session keys of `crypto_kx` with `key_exchange::kx_keypair` ({libsodium-kx}). The Ed25519 public key of a peer converts with its `to_x25519()`. A shared secret goes through a KDF before it keys a cipher. Every case of Wycheproof's X25519 file is tested ({wycheproof})"], + ["`p256`", "Key pairs made from a 32-byte scalar or drawn from `random_device`, public keys validated once, as SEC 1's uncompressed point or two coordinates, ECDSA over SHA-256 of a message or a digest with RFC 6979's nonce, signed low S, raw and DER, and low S checked or normalized, ECDH's raw x coordinate, SPKI and PKCS#8", "about 128 bits ({sec2})", "secret 32 bytes (the scalar); public 65 bytes uncompressed ({sec1}); SPKI 91 bytes ({rfc5480}), PKCS#8 138 bytes ({rfc5208}, {rfc5915})", "ECDSA: 64 bytes, r and s ({ieee1363}); in DER up to 72 ({rfc3279})", "{speed:p256}", "{constant_time:p256}", "{fips186-5}, {sec2}, {sec1}, {rfc6979}", "passkeys' ES256 ({webauthn}), TLS 1.3 ({rfc8446-groups})", "yes: P-256, for ECDSA and ECDH ({webcrypto})", "Browsers' WebCrypto, whose raw export of a P-256 public key is the uncompressed point `public_key::from_bytes` takes ({webcrypto}) and whose ECDH `deriveBits` is the raw x `agree` gives ({webcrypto-ecdh}); passkeys and TLS. Not Bitcoin, Ethereum or Nostr, whose keys are secp256k1's"] ] }, - "hybrid": { - "title": "webcpp::crypto::hybrid", - "columns": ["Construction", "What it does", "Keys", "Nonce (IV)", "Overhead per message", "Standards and sources", "Choose it when"], + "public_key_encryption": { + "title": "webcpp::crypto::public_key_encryption", + "columns": ["Construction", "What it does", "Keys", "Nonce", "Overhead per message", "Standards and sources", "Choose it when"], "cited": ["Standards and sources"], "rows": [ - ["`box`: X25519-XSalsa20-Poly1305", "Authenticated encryption between two key pairs: X25519 agrees a key once per pair, then XSalsa20-Poly1305 seals each message; either party can have written it", "the own 32-byte secret key and the peer's 32-byte X25519 public key", "24 bytes, safe to draw at random ({xsalsa20})", "a 16-byte tag", "{nacl-box}, {libsodium-box}", "two parties who know each other's public keys exchange messages, in NaCl's and libsodium's format; a peer key of small order is refused"], + ["`box`: X25519-XSalsa20-Poly1305", "Authenticated encryption between two key pairs: X25519 agrees a key once per pair, then XSalsa20-Poly1305 seals each message; either party can have written it", "the own X25519 key pair and the peer's X25519 public key", "24 bytes, safe to draw at random ({xsalsa20})", "a 16-byte tag", "{nacl-box}, {libsodium-box}", "two parties who know each other's public keys exchange messages, in NaCl's and libsodium's format; a peer key of small order is refused"], ["`box_xchacha20poly1305`: X25519-XChaCha20-Poly1305", "The same, with XChaCha20-Poly1305 sealing each message", "the same", "24 bytes, safe to draw at random", "a 16-byte tag", "{libsodium-box}", "the peer uses libsodium's `crypto_box_curve25519xchacha20poly1305`; otherwise `box`, NaCl's format"], - ["`sealed_box`: X25519-XSalsa20-Poly1305, anonymous", "Encryption to a public key alone: a key pair drawn per message, whose public key travels with it; the recipient cannot tell who sealed it, and the sender cannot open it afterwards", "to seal, the recipient's 32-byte public key; to open, the recipient's key pair", "none: derived from the two public keys", "48 bytes: the ephemeral public key and the tag", "{libsodium-sealed}", "anyone may write to a recipient who must not learn who wrote: anonymous feedback, a drop box; it proves nothing about the sender"] + ["`sealed_box`: X25519-XSalsa20-Poly1305, anonymous", "Encryption to a public key alone: a key pair drawn per message, whose public key travels with it; the recipient cannot tell who sealed it, and the sender cannot open it afterwards", "to seal, the recipient's X25519 public key; to open, the recipient's X25519 key pair", "none: derived from the two public keys", "48 bytes: the ephemeral public key and the tag", "{libsodium-sealed}", "anyone may write to a recipient who must not learn who wrote: anonymous feedback, a drop box; it proves nothing about the sender"] + ] + }, + "key_exchange": { + "title": "webcpp::crypto::key_exchange", + "columns": ["Construction", "What it does", "Keys", "Output", "Standards and sources", "Choose it when"], + "cited": ["Standards and sources"], + "rows": [ + ["`kx_keypair`: crypto_kx", "Session keys for a client and a server: X25519 agrees a secret, and BLAKE2b-512 of it and both public keys gives each side a key to receive with and one to transmit with", "a key pair that holds an X25519 key pair, taken as is, derived from a 32-byte seed or drawn, and the peer's X25519 public key", "two 32-byte `secret<32>` per side, the client's `transmit` the server's `receive`", "{libsodium-kx}", "a client and a server that swapped public keys need a key for each direction, as libsodium's `crypto_kx` gives them; a peer key of low order is refused; a protocol with a KDF of its own uses X25519's `agree` instead"] ] } }, "use_cases": [ - {"need": "Seal or open a record inside an event loop without waiting", "namespace": "webcpp::crypto", "api": "`async_seal`, `async_open`", "backend": "the default of AES-GCM", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//gcm-default /webcpp/asio//asio", "example": "async_seal", "section": "crypto-async", "operations": ["async_gcm"]}, + {"need": "Seal or open a record inside an event loop without waiting", "namespace": "webcpp::crypto", "api": "`secret_key_encryption::aead::async_seal`, `async_open`", "backend": "the default of AES-GCM", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//gcm-default /webcpp/asio//asio", "example": "async_seal", "section": "crypto-async", "operations": ["async_gcm"]}, {"need": "Sign and verify with Ed25519 in a coroutine", "namespace": "webcpp::crypto", "api": "`async_sign`, `async_verify`", "backend": "the default of Ed25519", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//ed25519-default /webcpp/asio//asio", "example": "async_sign", "section": "crypto-async", "operations": ["async_ed25519"]}, {"need": "Generate a session token, a password-reset link or an API key", "namespace": "webcpp::crypto", "api": "`random_device::fill`", "backend": "the system's generator", "jamfile": "/webcpp/crypto//crypto", "example": "reset_token", "section": "crypto-entropy"}, {"need": "Draw an unbiased number in a range, such as a six-digit code", "namespace": "webcpp::crypto", "api": "`random_device` with `std::uniform_int_distribution`", "backend": "the system's generator", "jamfile": "/webcpp/crypto//crypto", "example": "reset_token", "section": "crypto-entropy"}, - {"need": "Check a webhook's or an API's HMAC signature", "namespace": "webcpp::crypto", "api": "`equal`, with Boost.Hash2's `hmac`", "backend": "none", "jamfile": "/webcpp/crypto//crypto", "example": "equal_hmac", "section": "crypto-equal"}, + {"need": "Check a webhook's or an API's HMAC signature", "namespace": "webcpp::crypto", "api": "`constant_time_equal`, with Boost.Hash2's `hmac`", "backend": "none", "jamfile": "/webcpp/crypto//crypto", "example": "constant_time_equal_hmac", "section": "crypto-constant-time-equal"}, {"need": "Encrypt a database field, a cookie or a token at rest", "namespace": "webcpp::crypto::ciphers", "api": "`aes256_gcm`", "backend": "the default: OpenSSL natively, BearSSL on WebAssembly", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//gcm-default", "example": "store_token", "section": "crypto-gcm"}, {"need": "Encrypt a large file or a stream", "namespace": "webcpp::crypto::ciphers", "api": "`aes256_gcm`: records, or `begin_seal`, `update` and `result`", "backend": "the default", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//gcm-default", "example": "sealed_records", "section": "crypto-gcm-incremental"}, {"need": "Tell a forged message from a malformed one", "namespace": "webcpp::crypto", "api": "`error`", "backend": "any", "jamfile": "/webcpp/crypto//crypto", "example": "failure_reasons", "section": "crypto-errors"}, {"need": "Turn a sequential id into an opaque reference", "namespace": "webcpp::crypto::ciphers", "api": "`aes256`", "backend": "ctaes, or OpenSSL natively and on WASI", "jamfile": "/webcpp/crypto//crypto /third_party//ctaes", "example": "order_reference", "section": "crypto-block"}, {"need": "Prove who wrote a message posted to a relay", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::sign(crypto::schnorr, message)`, `crypto::verify`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "signed_message", "section": "crypto-p2p-signed"}, - {"need": "Check a software update or a licence file", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::sign(crypto::ecdsa_sha256, message)`, `public_key::make`, `crypto::verify`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "signed_update", "section": "crypto-everyday-update"}, + {"need": "Check a software update or a licence file", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::sign(crypto::ecdsa_sha256, message)`, `public_key::from_bytes`, `crypto::verify`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "signed_update", "section": "crypto-everyday-update"}, {"need": "Agree on a key with a peer through a relay that sees everything", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::agree_hashed` (SHA-256 of the shared point), then HKDF on Boost.Hash2 and `aes256_gcm`", "backend": "libsecp256k1, and AES-GCM's default", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1 /webcpp/crypto//gcm-default", "example": "ecdh_session", "section": "crypto-p2p-session"}, {"need": "Derive a Nostr direct message's conversation key (NIP-44; the format is a domain library's)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::agree`, then HKDF on Boost.Hash2", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "ecdh_x_coordinate", "section": "crypto-p2p-nostr-dm", "answers": "crypto-secp256k1-ecdh"}, - {"need": "Find who signed a message or a transaction without being sent their key (Ethereum's signatures)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::sign(crypto::ecdsa_sha256_recoverable, message)`, `recover`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "recover_signer", "section": "crypto-wallets-recovery", "answers": "crypto-secp256k1-recovery"}, - {"need": "Derive child keys for a watch-only wallet (BIP 32's derivation is a domain library's)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`seckey_tweak_add`, `pubkey_tweak_add`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "key_tweak", "section": "crypto-secp256k1-tweaks"}, + {"need": "Find who signed a message or a transaction without being sent their key (Ethereum's signatures)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::sign(crypto::ecdsa_keccak256_recoverable, message)`, `recover`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1 /third_party//xkcp", "example": "ethereum_personal_sign", "section": "crypto-wallets-recovery", "answers": "crypto-secp256k1-recovery"}, + {"need": "Derive child keys for a watch-only wallet (BIP 32's derivation is a domain library's)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`secret_key_tweak_add`, `public_key_tweak_add`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "key_tweak", "section": "crypto-secp256k1-tweaks"}, {"need": "Store or exchange a secp256k1 key with OpenSSL or a config file", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`encode_spki`, `decode_spki`, `encode_pkcs8`, `decode_pkcs8`; `webcpp::crypto::pem::armour`, `unarmour`", "backend": "libsecp256k1, libsodium for PEM", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1 /webcpp/crypto//pem-default", "example": "secp256k1_key_formats", "section": "crypto-secp256k1-formats"}, {"need": "Make a peer-to-peer connection's key exchange look like random bytes (BIP 324's transport; its packets are a domain library's)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`ellswift_create`, `ellswift_decode`, `ellswift_xdh`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "ellswift_handshake", "section": "crypto-p2p-v2", "answers": "crypto-secp256k1-ellswift"}, - {"need": "Publish one donation address that never shows two payments as related (BIP 352's addresses and transactions are a domain library's)", "namespace": "webcpp::crypto::curves::secp256k1::silent_payments", "api": "`create_outputs`, `make_prevouts_summary`, `scan_outputs`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "silent_payment", "section": "crypto-wallets-silent", "answers": "crypto-secp256k1-silent-payments"}, - {"need": "Require two devices to sign for a wallet, with one ordinary signature on the chain", "namespace": "webcpp::crypto::curves::secp256k1::musig", "api": "`key_aggregate`, `nonce_gen`, `partial_sign`, `partial_signature_aggregate`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "musig_wallet", "section": "crypto-wallets-musig", "answers": "crypto-secp256k1-musig"}, - {"need": "Make and keep a wallet's key", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::make`, `keypair::public_key`, `public_key::xonly`, `public_key::compressed`; `aes256_gcm` at rest", "backend": "libsecp256k1, and AES-GCM's default", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1 /webcpp/crypto//gcm-default", "example": "wallet_key", "section": "crypto-wallets-key"}, + {"need": "Publish one donation address that never shows two payments as related (BIP 352's addresses and transactions are a domain library's)", "namespace": "webcpp::crypto::curves::secp256k1::silent_payments", "api": "`create_outputs`, `make_previous_outputs_summary`, `scan_outputs`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "silent_payment", "section": "crypto-wallets-silent", "answers": "crypto-secp256k1-silent-payments"}, + {"need": "Require two devices to sign for a wallet, with one ordinary signature on the chain", "namespace": "webcpp::crypto::curves::secp256k1::musig", "api": "`key_aggregate`, `generate_nonce`, `partial_sign`, `partial_signature_aggregate`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "musig_wallet", "section": "crypto-wallets-musig", "answers": "crypto-secp256k1-musig"}, + {"need": "Make and keep a wallet's key", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::from_secret`, `keypair::public_key`, `public_key::xonly`, `public_key::compressed`; `aes256_gcm` at rest", "backend": "libsecp256k1, and AES-GCM's default", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1 /webcpp/crypto//gcm-default", "example": "wallet_key", "section": "crypto-wallets-key"}, {"need": "Sign a Bitcoin SegWit v0 input (a domain library's job)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::sign(crypto::ecdsa_sha256, crypto::prehashed{sighash})`, `to_der`, `is_low_s`, `normalize_low_s`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "bitcoin_sighash", "section": "crypto-wallets-der"}, {"need": "Derive a Bitcoin Taproot output key and spend by key path (a domain library's job)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`tweak_xonly`, `keypair::tweak_xonly`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "taproot_tweak", "section": "crypto-wallets-taproot"}, - {"need": "Sign where allocation is restricted to the program's arena", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::make(secret, resource)`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "arena_signer", "section": "crypto-memory"}, + {"need": "Sign where allocation is restricted to the program's arena", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::from_secret(secret, resource)`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "arena_signer", "section": "crypto-memory"}, {"need": "Keep every allocation of OpenSSL's in the program's arena", "namespace": "webcpp::crypto", "api": "`openssl_memory_resource`, `backends::openssl::install_memory_functions`", "backend": "OpenSSL, natively", "jamfile": "`/webcpp/crypto//crypto` in the program; in the project requirements, `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE` and `/webcpp/crypto//openssl`", "example": "openssl_memory", "section": "crypto-memory-openssl"}, {"need": "Seed BearSSL's own generator for code that calls BearSSL directly", "namespace": "webcpp::crypto", "api": "`random_device::fill`", "backend": "BearSSL's C API", "jamfile": "/webcpp/crypto//crypto /third_party//bearssl", "example": "bearssl_prng", "section": "crypto-entropy-bearssl"}, - {"need": "Hash, or compute an HMAC", "namespace": "Boost.Hash2, not this library", "api": "`boost::hash2::sha2_256`, `hmac_sha2_256`", "backend": "none", "jamfile": "`/webcpp/crypto//crypto` brings Boost's headers", "example": "equal_hmac", "section": "crypto-overview-hash2"}, - {"need": "Sign and verify with Ed25519 (RFC 8032), or sign a large message in pieces with Ed25519ph", "namespace": "webcpp::crypto::curves::ed25519", "api": "`keypair::make`, `keypair::generate`, `keypair::sign(crypto::eddsa, message)`, `crypto::verify`; `ph`", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//ed25519-default", "example": "ed25519_sign", "section": "crypto-ed25519"}, - {"need": "Agree a shared secret with a peer's public key (X25519, RFC 7748), or with the X25519 form of an Ed25519 key", "namespace": "webcpp::crypto::curves::x25519", "api": "`public_key`, `agree`; `curves::ed25519::to_x25519_public`, `curves::ed25519::keypair::x25519_secret`", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//x25519-default", "example": "x25519_agree", "section": "crypto-x25519"}, - {"need": "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::curves::x25519", "api": "`kx_keypair::make`, `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": "Hash, or compute an HMAC", "namespace": "Boost.Hash2, not this library", "api": "`boost::hash2::sha2_256`, `hmac_sha2_256`", "backend": "none", "jamfile": "`/webcpp/crypto//crypto` brings Boost's headers", "example": "constant_time_equal_hmac", "section": "crypto-overview-hash2"}, + {"need": "Sign and verify with Ed25519 (RFC 8032), or with Ed25519ph a message's SHA-512 or a large message in pieces", "namespace": "webcpp::crypto::curves::ed25519", "api": "`keypair::from_secret`, `keypair::generate`, `keypair::sign(crypto::eddsa, message)`, `keypair::sign(crypto::eddsa_prehashed, crypto::prehashed{digest})`, `crypto::verify`; `prehashed_signer`", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//ed25519-default", "example": "ed25519_sign", "section": "crypto-ed25519"}, + {"need": "Agree a shared secret with a peer's public key (X25519, RFC 7748), or with the X25519 form of an Ed25519 key", "namespace": "webcpp::crypto::curves::x25519", "api": "`keypair::from_secret`, `keypair::generate`, `public_key::from_bytes`, `keypair::agree`; `curves::ed25519::keypair::to_x25519`, `curves::ed25519::public_key::to_x25519`, `crypto::to_x25519`", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//x25519-default", "example": "x25519_agree", "section": "crypto-x25519"}, + {"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": "`ed25519::encode_spki`, `decode_spki`, `encode_pkcs8`, `decode_pkcs8`, the same in `x25519`; `webcpp::crypto::pem::armour`, `unarmour`", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//ed25519-default /webcpp/crypto//x25519-default /webcpp/crypto//pem-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<>`: `make`, `seal`, `open`", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//xchacha20_poly1305-default", "example": "xchacha_seal", "section": "crypto-chacha"}, - {"need": "Encrypt a record or a file under one secret key, each with a random nonce, in libsodium's secret-box format", "namespace": "webcpp::crypto::ciphers", "api": "`secretbox<>`, `secretbox_xchacha20poly1305<>`: `make`, `seal`, `open`", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//secretbox_xsalsa20poly1305-default", "example": "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::hybrid", "api": "`box::make`, `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::hybrid", "api": "`sealed_box::seal`, `sealed_box::open`", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//sealed_box-default", "example": "file_share", "section": "crypto-sealed-box"}, - {"need": "Share a file with someone known only by a public key, as a file-sharing app does", "namespace": "webcpp::crypto", "api": "`ciphers::secretbox<>` for the file under a key drawn for it, `hybrid::sealed_box::seal` for that key", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//secretbox_xsalsa20poly1305-default /webcpp/crypto//sealed_box-default /webcpp/crypto//x25519-default", "example": "file_share", "section": "crypto-everyday-files"}, - {"need": "Make and keep a P-256 key pair, and import a browser's public key (WebCrypto's raw form), as webcpp::trystero's peers do", "namespace": "webcpp::crypto::curves::p256", "api": "`keypair::make`, `keypair::generate`, `keypair::public_key`, `keypair::secret`, `public_key::make`", "backend": "BearSSL", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//p256-default", "example": "p256_keys", "section": "crypto-p256-keys"}, + {"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": "Encrypt a record or a file under one secret key, each with a random nonce, in libsodium's secret-box format", "namespace": "webcpp::crypto::secret_key_encryption", "api": "`secretbox<>`, `secretbox_xchacha20poly1305<>`: `from_key`, `seal(nonce, data)`, `open(nonce, data, tag)`; the box forms `seal(box, nonce, data)`, `open(box, nonce, data, tag)`", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//secretbox_xsalsa20poly1305-default", "example": "file_share", "section": "crypto-secretbox"}, + {"need": "Send messages between two people who know each other's public keys, as NaCl's and libsodium's crypto_box", "namespace": "webcpp::crypto::public_key_encryption", "api": "`box::from_keys`, `box::seal`, `box::open`", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//box_xsalsa20poly1305-default", "example": "box_messages", "section": "crypto-box"}, + {"need": "Let anyone send a message that only the recipient can read, without saying who sent it (anonymous feedback, a drop box)", "namespace": "webcpp::crypto::public_key_encryption", "api": "`sealed_box::seal`, `sealed_box::open`", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//sealed_box-default", "example": "file_share", "section": "crypto-sealed-box"}, + {"need": "Share a file with someone known only by a public key, as a file-sharing app does", "namespace": "webcpp::crypto", "api": "`secret_key_encryption::secretbox<>` for the file under a key drawn for it, `public_key_encryption::sealed_box::seal` for that key", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//secretbox_xsalsa20poly1305-default /webcpp/crypto//sealed_box-default /webcpp/crypto//x25519-default", "example": "file_share", "section": "crypto-everyday-files"}, + {"need": "Make and keep a P-256 key pair, and import a browser's public key (WebCrypto's raw form), as webcpp::trystero's peers do", "namespace": "webcpp::crypto::curves::p256", "api": "`keypair::from_secret`, `keypair::generate`, `keypair::public_key`, `keypair::secret`, `public_key::from_bytes`", "backend": "BearSSL", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//p256-default", "example": "p256_keys", "section": "crypto-p256-keys"}, {"need": "Sign what a browser's WebCrypto verifies and verify what it signs (ECDSA on P-256 with SHA-256), low S where a protocol requires it, as webcpp::trystero's handshakes", "namespace": "webcpp::crypto::curves::p256", "api": "`keypair::sign(crypto::ecdsa_sha256, message)`, `crypto::verify`, `is_low_s`, `normalize_low_s`; `to_der`, `from_der` for X.509", "backend": "BearSSL", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//p256-default", "example": "p256_sign", "section": "crypto-p256-ecdsa"}, {"need": "Agree on a key with a browser's WebCrypto (ECDH on P-256, deriveBits), then derive the session's keys with HKDF, as Trystero 0.27.0's pairwise keys are derived", "namespace": "webcpp::crypto::curves::p256", "api": "`keypair::agree`; `webcpp::hash::hkdf` for the keys", "backend": "BearSSL", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//p256-default", "example": "p256_ecdh", "section": "crypto-p256-ecdh"}, {"need": "Export or import a P-256 key in the forms OpenSSL and WebCrypto's spki and pkcs8 use (SPKI, PKCS#8), as DER or PEM text", "namespace": "webcpp::crypto::curves::p256", "api": "`encode_spki`, `decode_spki`, `encode_pkcs8`, `decode_pkcs8`; `webcpp::crypto::pem::armour`, `unarmour`", "backend": "BearSSL, libsodium for PEM", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//p256-default /webcpp/crypto//pem-default", "example": "p256_key_formats", "section": "crypto-p256-formats"}, @@ -1323,7 +1370,7 @@ "openssl_on_emscripten": "`/webcpp/crypto//openssl` named in a build for Emscripten.", "openssl_memory_on_emscripten": "The memory option of the OpenSSL backend set in a build for Emscripten.", "memory_missing_definition_install": "The memory option set in the program's project, the install called, and `openssl_memory_resource()` not defined.", - "memory_missing_definition_make": "The memory option set in the program's project, a `make` on OpenSSL, and `openssl_memory_resource()` not defined.", + "memory_missing_definition_from_key": "The memory option set in the program's project, a `from_key` on OpenSSL, and `openssl_memory_resource()` not defined.", "memory_two_files": "Two files of one program, one compiled with the memory option and one without.", "memory_option": "OpenSSL's allocations in the program's own resource: the define and OpenSSL in the requirements of the program's project, the resource defined once, the install first in `main`.", "no_backend_on_emscripten": "A program for Emscripten that uses the default backend and links none.", @@ -1332,18 +1379,18 @@ "sodium_not_linked_on_emscripten": "A program for Emscripten that names libsodium and links none.", "ed25519_default_not_linked_on_emscripten": "A program for Emscripten that makes an Ed25519 key pair on its default, libsodium, and links none.", "ed25519_on_bearssl_on_emscripten": "A program for Emscripten that names BearSSL, which has no Ed25519, in an Ed25519 key pair's type.", - "ed25519ph_sha256_on_emscripten": "A program for Emscripten that names SHA-256 in Ed25519ph's type, which RFC 8032 defines over SHA-512.", + "ed25519ph_sha256_on_emscripten": "A program for Emscripten that names SHA-256 in Ed25519ph's streaming signer, `curves::ed25519::prehashed_signer`, which RFC 8032 defines over SHA-512.", "heavy_without_threads_on_emscripten": "A program for Emscripten without `-pthread` that calls a heavy operation's `async_` variant (a test's own).", "threads_on_emscripten": "A program for Emscripten built with `multi`, which is `-pthread`: the build has threads.", "chacha_on_ctaes_on_emscripten": "A program for Emscripten that names ctaes, which has no ChaCha20-Poly1305, in the AEAD's type.", - "aead_not_a_family_on_emscripten": "A program for Emscripten that gives `ciphers::aead` AES-GCM's family, which `ciphers::gcm` serves instead.", + "aead_not_a_family_on_emscripten": "A program for Emscripten that gives `ciphers::basic_chacha20_poly1305` AES-GCM's family, which `ciphers::gcm` serves instead.", "chacha_default_not_linked_on_emscripten": "A program for Emscripten that calls the three ChaCha20-Poly1305 AEADs on their default, libsodium, and links none.", "box_default_not_linked_on_emscripten": "A program for Emscripten that calls the secret boxes, the boxes and the sealed box on their default, libsodium, and links none.", "kx_default_not_linked_on_emscripten": "A program for Emscripten that makes a `crypto_kx` key pair on its default, libsodium, and links none.", - "box_not_a_family_on_emscripten": "A program for Emscripten that gives `hybrid::basic_box` a type that is no box family.", + "box_not_a_family_on_emscripten": "A program for Emscripten that gives `public_key_encryption::basic_box` a type that is no box family.", "p256_default_not_linked_on_emscripten": "A program for Emscripten that makes a P-256 key pair on its default, BearSSL, and links none.", "p256_on_sodium_on_emscripten": "A program for Emscripten that names libsodium, which has no P-256, in a P-256 key pair's type.", - "x25519_default_not_linked_on_emscripten": "A program for Emscripten that agrees an X25519 shared secret on its default, libsodium, and links none.", + "x25519_default_not_linked_on_emscripten": "A program for Emscripten that makes an X25519 key pair and agrees a shared secret on its default, libsodium, and links none.", "pem_default_not_linked_on_emscripten": "A program for Emscripten that armours DER as PEM on its default, libsodium, and links none.", "chacha_header_not_included_on_emscripten": "A program for Emscripten that names BearSSL in ChaCha20-Poly1305's type without including BearSSL's header.", "chacha_unknown_backend_on_emscripten": "A program for Emscripten that names a type of its own as ChaCha20-Poly1305's backend.", @@ -1366,8 +1413,10 @@ "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.", - "box_not_a_family": "Name `families::box_xsalsa20poly1305` or `families::box_xchacha20poly1305`, or use `hybrid::box` or `hybrid::box_xchacha20poly1305`.", - "aead_not_a_family": "Name one of the three ChaCha20-Poly1305 families or the two secret boxes'; AES-GCM is `ciphers::gcm`, as in `aes256_gcm`.", + "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<>`.", + "secretbox_not_a_family": "Name `families::secretbox_xsalsa20poly1305` or `families::secretbox_xchacha20poly1305`, or use `secret_key_encryption::secretbox<>` or `secret_key_encryption::secretbox_xchacha20poly1305<>`; an AEAD is `ciphers::basic_chacha20_poly1305`, as in `ciphers::xchacha20_poly1305<>`.", "sodium_not_linked_on_emscripten": "Add `/third_party//sodium` to the program's sources.", "canary_sodium_other_commit": "Build the library at the commit of webcpp's submodule, or link it through b2.", "secp256k1_not_linked": "Add `/third_party//secp256k1`.", @@ -1376,7 +1425,7 @@ "musig_nonce_copied": "Pass the nonce with std::move, once: a secret nonce signs one message.", "ellswift_other_backend": "Name `backends::secp256k1`, or leave the backend out: `curves::secp256k1::ellswift_decode(encoded_key)`.", "musig_other_backend": "Name `backends::secp256k1`, or leave the backend out: `curves::secp256k1::musig::parse_public_nonce(encoded_nonce)`.", - "silent_payments_other_backend": "Name `backends::secp256k1`, or leave the backend out: `curves::secp256k1::silent_payments::make_prevouts_summary(...)`.", + "silent_payments_other_backend": "Name `backends::secp256k1`, or leave the backend out: `curves::secp256k1::silent_payments::make_previous_outputs_summary(...)`.", "label_lookup_by_value": "Return `std::optional>`, a span over a tweak the lookup keeps, such as a map's entry; never the tweak by value.", "aes_on_bearssl": "Name `ciphers::aes256`, include `` and add `/third_party//ctaes`.", "default_selected": "Remove the define, and name `gcm>` where the program wants BearSSL.", @@ -1388,7 +1437,7 @@ "openssl_memory_on_emscripten": "Remove `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE` from the WebAssembly build: give that build a project of its own, without the define and OpenSSL, naming `/third_party//bearssl`. On WebAssembly the backend is BearSSL, which allocates nothing.", "openssl_memory_on_webassembly": "Remove `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE` from the WebAssembly build: give that build a project of its own, without the define and OpenSSL, naming `/third_party//bearssl`. On WebAssembly the backend is BearSSL, which allocates nothing.", "memory_missing_definition_install": "Define `std::pmr::memory_resource& webcpp::crypto::openssl_memory_resource() noexcept` once in the program, returning a resource that is never destroyed.", - "memory_missing_definition_make": "Define `std::pmr::memory_resource& webcpp::crypto::openssl_memory_resource() noexcept` once in the program, returning a resource that is never destroyed.", + "memory_missing_definition_from_key": "Define `std::pmr::memory_resource& webcpp::crypto::openssl_memory_resource() noexcept` once in the program, returning a resource that is never destroyed.", "memory_two_files": "Give the define in the requirements of the program's project, with OpenSSL beside it, `project app : requirements WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE /webcpp/crypto//openssl ;`, so that every target of the program gets both.", "openssl_memory_not_linked": "A target has the define and not OpenSSL: put `/webcpp/crypto//openssl` in the same project requirements as the define, or remove the define.", "canary_missing": "Link the library through b2, `/third_party//bearssl`; built by other means, it must be the pinned commit, with webcpp's `src/canary_bearssl.c`.", @@ -1405,47 +1454,76 @@ "openssl_not_linked_msvc": "As `openssl_not_linked`.", "ed25519_on_bearssl": "Leave the backend out, as in `curves::ed25519::keypair`, or name `backends::sodium`, and add `/third_party//sodium`.", "ed25519_on_bearssl_on_emscripten": "As `ed25519_on_bearssl`.", - "ed25519ph_sha256": "Name `curves::ed25519::ph`: RFC 8032 defines Ed25519ph over SHA-512.", + "ed25519ph_sha256": "Name `curves::ed25519::prehashed_signer`: RFC 8032 defines Ed25519ph over SHA-512.", "ed25519ph_sha256_on_emscripten": "As `ed25519ph_sha256`.", "ed25519_default_not_linked": "Add `/webcpp/crypto//ed25519-default`, which links `/third_party//sodium` on every target.", "ed25519_default_not_linked_on_emscripten": "As `ed25519_default_not_linked`.", "heavy_without_threads": "Call the synchronous operation the message names, or build with threads: natively without `WEBCPP_CRYPTO_NO_THREADS`, on Emscripten with `-pthread`; WASI has none.", "heavy_without_threads_first": "As `heavy_without_threads`.", - "async_make_xchacha": "Call the synchronous `make`: XChaCha20-Poly1305 is not in WebCrypto, so it has no asynchronous form.", - "async_seal_xchacha": "Call the AEAD's own `seal`: only AES-GCM has `async_seal`.", - "async_open_xchacha": "Call the AEAD's own `open`: only AES-GCM has `async_open`.", + "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.", + "hybrid_header_removed": "Include `` for `box` and `box_xchacha20poly1305`, `` for `sealed_box`, `` for `kx_keypair`; the old directory is kept free for post-quantum hybrids.", + "hybrid_names_removed": "Name `crypto::public_key_encryption::box`, `box_xchacha20poly1305` and `sealed_box`, and `crypto::key_exchange::kx_keypair` and `session_keys`; `crypto::hybrid` and the names in `curves::x25519` are gone, with no alias.", + "async_seal_xchacha": "Name a native backend, such as `backends::sodium`, for `async_seal`, or seal with AES-GCM on the browser's backend: WebCrypto has no XChaCha20-Poly1305.", + "async_open_xchacha": "Name a native backend, such as `backends::sodium`, for `async_open`, or open with AES-GCM on the browser's backend: WebCrypto has no XChaCha20-Poly1305.", "async_sign_secp256k1": "Call the key pair's own signing function: secp256k1 is not in WebCrypto, so only Ed25519's and P-256's key pairs have `async_sign`.", - "async_sign_ed25519_prehashed": "Give `async_sign` the message itself with `crypto::eddsa`, RFC 8032's pure Ed25519, which takes no digest, as the synchronous `sign` does.", - "async_sign_p256_eddsa": "Give `async_sign` the key pair's own scheme: `crypto::ecdsa_sha256` for a P-256 key pair, `crypto::eddsa` for an Ed25519 key pair.", + "async_sign_ed25519_prehashed": "Give `async_sign` the message itself with `crypto::eddsa`, RFC 8032's pure Ed25519, which takes no digest, as the synchronous `sign` does; a message's SHA-512 is signed with `crypto::eddsa_prehashed` (Ed25519ph), on a native backend.", + "async_sign_p256_eddsa": "Give `async_sign` the key pair's own scheme: `crypto::ecdsa_sha256` for a P-256 key pair, `crypto::eddsa` or `crypto::eddsa_prehashed` for an Ed25519 key pair.", "async_verify_named_backend": "As `async_verify_wrong_key`: naming the backend does not add a scheme; call `crypto::verify` for `crypto::schnorr` and secp256k1's keys.", - "async_verify_wrong_key": "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::eddsa` and a `curves::p256::basic_public_key` with `crypto::ecdsa_sha256`.", + "async_verify_wrong_key": "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::eddsa` or `crypto::eddsa_prehashed` and a `curves::p256::basic_public_key` with `crypto::ecdsa_sha256`.", "prehashed_dynamic": "Give `crypto::prehashed` a digest of a fixed size: a `std::array`, a `std::span` or a `boost::hash2::digest<32>`.", "sign_p256_schnorr": "Sign with `crypto::ecdsa_sha256`, P-256's scheme; BIP340's `crypto::schnorr` is secp256k1's.", - "sign_ed25519_ecdsa": "Sign with `crypto::eddsa`, Ed25519's scheme; `crypto::ecdsa_sha256` is P-256's and secp256k1's.", - "sign_ed25519_prehashed": "Sign the message itself with `crypto::eddsa`, RFC 8032's pure Ed25519, which takes no digest; to sign a message given in pieces, use Ed25519ph, `curves::ed25519::ph`.", + "sign_ed25519_ecdsa": "Sign with `crypto::eddsa` or `crypto::eddsa_prehashed`, Ed25519's schemes; `crypto::ecdsa_sha256` is P-256's and secp256k1's.", + "sign_ed25519_prehashed": "Sign the message itself with `crypto::eddsa`, RFC 8032's pure Ed25519, which takes no digest; to sign a message's SHA-512, use Ed25519ph, `crypto::eddsa_prehashed`, or for a message given in pieces `curves::ed25519::prehashed_signer`.", "sign_schnorr_prehashed": "Sign the message itself with `crypto::schnorr`, BIP340's, which has no prehash mode; a taproot sighash, BIP341's tagged hash, is that message.", - "sign_secp256k1_eddsa": "Sign with `crypto::ecdsa_sha256`, `crypto::ecdsa_sha256_recoverable` or `crypto::schnorr`, secp256k1's schemes; `crypto::eddsa` is Ed25519's.", - "sign_secp256k1_not_a_scheme": "Name the scheme with its tag: `crypto::ecdsa_sha256`, `crypto::ecdsa_sha256_recoverable` or `crypto::schnorr`.", - "verify_ecdsa_bytes_key": "Give `crypto::ecdsa_sha256` the public key as a typed object, `curves::secp256k1::public_key::make(bytes)` or `curves::p256::public_key::make(bytes)`: bytes never choose the curve.", - "verify_eddsa_bytes_key": "Give `crypto::eddsa` the public key as a `curves::ed25519::public_key`: `key_pair.public_key()`, or `curves::ed25519::public_key::make(bytes)` for a key received as bytes.", - "async_verify_eddsa_bytes_key": "Give `async_verify` with `crypto::eddsa` the public key as a `curves::ed25519::public_key`, as `crypto::verify` takes it: `key_pair.public_key()`, or `curves::ed25519::public_key::make(bytes)`.", - "sign_free_ed25519_ecdsa": "As `sign_ed25519_ecdsa`: `crypto::sign` calls the key pair's own `sign`, so sign with `crypto::eddsa`, Ed25519's scheme.", + "sign_secp256k1_eddsa": "Sign with `crypto::ecdsa_sha256`, `crypto::ecdsa_sha256_recoverable`, `crypto::ecdsa_keccak256_recoverable` or `crypto::schnorr`, secp256k1's schemes; `crypto::eddsa` is Ed25519's.", + "sign_secp256k1_not_a_scheme": "Name the scheme with its tag: `crypto::ecdsa_sha256`, `crypto::ecdsa_sha256_recoverable`, `crypto::ecdsa_keccak256_recoverable` or `crypto::schnorr`.", + "verify_ecdsa_bytes_key": "Give `crypto::ecdsa_sha256` the public key as a typed object, `curves::secp256k1::public_key::from_bytes(bytes)` or `curves::p256::public_key::from_bytes(bytes)`: bytes never choose the curve.", + "verify_eddsa_bytes_key": "Give `crypto::eddsa` (or `crypto::eddsa_prehashed`) the public key as a `curves::ed25519::public_key`: `key_pair.public_key()`, or `curves::ed25519::public_key::from_bytes(bytes)` for a key received as bytes.", + "async_verify_eddsa_bytes_key": "Give `async_verify` with `crypto::eddsa` the public key as a `curves::ed25519::public_key`, as `crypto::verify` takes it: `key_pair.public_key()`, or `curves::ed25519::public_key::from_bytes(bytes)`.", + "sign_free_ed25519_ecdsa": "As `sign_ed25519_ecdsa`: `crypto::sign` calls the key pair's own `sign`, so sign with `crypto::eddsa` or `crypto::eddsa_prehashed`, Ed25519's schemes.", "sign_free_public_key": "Give `crypto::sign` the key pair, whose public key verifies: `crypto::sign(key_pair, scheme, input)`, then `crypto::verify(scheme, signature, input, public_key)` or `public_key.verify(scheme, signature, input)`.", - "verify_member_eddsa_prehashed": "Verify the message itself with `crypto::eddsa`, RFC 8032's pure Ed25519, which takes no digest, as `crypto::verify` does; a message given in pieces is Ed25519ph's, `curves::ed25519::ph`.", - "verify_member_ed25519_ecdsa": "Verify with `crypto::eddsa`, Ed25519's scheme; `crypto::ecdsa_sha256` is P-256's and secp256k1's, whose keys are `curves::p256::basic_public_key` and `curves::secp256k1::public_key`.", + "verify_member_eddsa_prehashed": "Verify the message itself with `crypto::eddsa`, RFC 8032's pure Ed25519, which takes no digest, as `crypto::verify` does; a signature of a message's SHA-512 is Ed25519ph's, verified with `crypto::eddsa_prehashed`, or for a message given in pieces with `curves::ed25519::prehashed_signer`.", + "verify_member_ed25519_ecdsa": "Verify with `crypto::eddsa` or `crypto::eddsa_prehashed`, Ed25519's schemes; `crypto::ecdsa_sha256` is P-256's and secp256k1's, whose keys are `curves::p256::basic_public_key` and `curves::secp256k1::public_key`.", "verify_member_secp256k1_recoverable": "Give a recoverable signature to `curves::secp256k1::recover(crypto::ecdsa_sha256_recoverable, signature, input)`, which gives the signer's key; a public key verifies `crypto::ecdsa_sha256` and `crypto::schnorr`.", "verify_free_secp256k1_recoverable": "As `verify_member_secp256k1_recoverable`: give a recoverable signature to `curves::secp256k1::recover`, which gives the signer's key; `crypto::verify` takes `crypto::ecdsa_sha256` and `crypto::schnorr` with a secp256k1 key.", "verify_member_p256_eddsa": "Verify with `crypto::ecdsa_sha256`, P-256's scheme; `crypto::eddsa` is Ed25519's, whose key is a `curves::ed25519::public_key`.", - "agree_free_wrong_peer": "Give `agree` the peer's typed public key of the key pair's own curve and backend: `curves::p256::basic_public_key::make(bytes)` for P-256, `curves::secp256k1::public_key::make(bytes)` for secp256k1.", + "verify_p256_secp256k1_signature": "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_schnorr_as_ecdsa": "Verify a BIP340 signature with `crypto::schnorr`, its scheme; `crypto::ecdsa_sha256` takes a `curves::secp256k1::ecdsa_signature`, which `sign(crypto::ecdsa_sha256, input)` gives.", + "verify_ed25519_bytes_signature": "Make the 64 bytes received into a `curves::ed25519::signature` with `curves::ed25519::signature::from_bytes`, which checks their size, and verify that.", + "recover_ecdsa_signature": "Give `recover` a `curves::secp256k1::recoverable_signature`, which `sign(crypto::ecdsa_sha256_recoverable, input)` gives, or made from 65 bytes with `from_bytes`; an ECDSA signature without its recovery id verifies with `crypto::verify` and the signer's public key.", + "async_verify_p256_bytes_signature": "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`.", + "agree_free_wrong_peer": "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.", + "async_agree_wrong_peer": "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.", + "sign_x25519": "Sign with an Ed25519 key pair, a `crypto::signing_keypair`: an X25519 key pair agrees and does not sign. One Ed25519 key pair can do both: `to_x25519()` gives the X25519 key pair that agrees.", + "agree_ed25519": "Convert the Ed25519 key pair with `to_x25519()` and agree with the X25519 key pair it gives, and the peer's key converted with `public_key.to_x25519()`: an Ed25519 key pair signs and does not agree.", + "async_sign_x25519": "As `sign_x25519`: give `async_sign` an Ed25519 key pair, which signs; an X25519 key pair agrees, with `async_agree`.", + "async_agree_ed25519": "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.", + "async_agree_secp256k1": "Call the key pair's own `agree`: secp256k1 is not in WebCrypto, so only X25519's and P-256's key pairs have `async_agree`.", "verify_asynchronous_backend": "Call `async_verify` on a backend that completes by itself: its synchronous forms cannot wait for it.", "verify_free_asynchronous_backend": "As `verify_asynchronous_backend`.", "sign_asynchronous_backend": "Call `async_sign` on a backend that completes by itself: its synchronous forms cannot wait for it.", "agree_asynchronous_backend": "Call `async_agree` on a backend that completes by itself: its synchronous forms cannot wait for it.", + "x25519_asynchronous_backend": "Call `async_from_secret`, `async_generate` or `async_agree` on a backend that completes by itself: an X25519 key pair's synchronous forms cannot wait for it.", "seal_asynchronous_backend": "Call `async_seal` on a backend that completes by itself: its synchronous forms cannot wait for it.", - "open_asynchronous_backend": "Call `async_open` on a backend that completes by itself: its synchronous forms cannot wait for it.", + "open_asynchronous_backend": "Name a native backend, such as `backends::sodium`, for ChaCha20-Poly1305: WebCrypto has no ChaCha20-Poly1305, so neither its `open` nor its `async_open` completes on the browser's backend; there, use AES-GCM.", "async_member_without_async_hpp": "Include ``, which defines the asynchronous members, and add `/webcpp/asio//asio` to the program's Jamfile.", "sign_p256_digest_48": "Give `crypto::ecdsa_sha256` SHA-256's 32-byte digest, `crypto::prehashed{digest}` of a `std::array`, or the message itself, which it hashes.", "sign_secp256k1_recoverable_digest_48": "As `sign_p256_digest_48`: give `crypto::ecdsa_sha256_recoverable` SHA-256's 32-byte digest, or the message itself, which it hashes.", + "sign_keccak_digest_20": "As `sign_p256_digest_48`: give `crypto::ecdsa_keccak256_recoverable` Keccak-256's 32-byte digest, or the message itself, which it hashes with Keccak-256.", + "sign_p256_keccak": "Sign with `crypto::ecdsa_sha256`, P-256's scheme; Ethereum's `crypto::ecdsa_keccak256_recoverable` is secp256k1's.", + "sign_ed25519_keccak": "Sign with `crypto::eddsa` or `crypto::eddsa_prehashed`, Ed25519's schemes; Ethereum's `crypto::ecdsa_keccak256_recoverable` is secp256k1's.", + "verify_keccak_recoverable": "Give the signature to `curves::secp256k1::recover(crypto::ecdsa_keccak256_recoverable, signature, input)`, which gives the signer's key, and compare that key, or its address, with the one expected: Ethereum's recoverable ECDSA has no `verify`.", + "sign_keccak_without_xkcp": "Add `/third_party//xkcp` to the program's Jamfile, whose Keccak-256 hashes the message, or build the 32-byte digest elsewhere and sign `crypto::prehashed{digest}`, which needs no XKCP.", + "sign_eddsa_prehashed_message": "Give `crypto::eddsa_prehashed` the message's SHA-512 marked as a digest, `crypto::prehashed{digest}` of a `std::array`; sign the message itself with `crypto::eddsa`, or give it in pieces to `curves::ed25519::prehashed_signer`.", + "sign_eddsa_prehashed_digest_32": "Give `crypto::eddsa_prehashed` SHA-512's 64-byte digest, `crypto::prehashed{digest}` of a `std::array`: RFC 8032 defines Ed25519ph over SHA-512.", + "verify_eddsa_prehashed_message": "As `sign_eddsa_prehashed_message`: verify under `crypto::eddsa_prehashed` the marker of the message's SHA-512, or the message itself under `crypto::eddsa`.", + "sign_eddsa_prehashed_asynchronous_backend": "Sign under `crypto::eddsa_prehashed` with a key pair of a native backend: WebCrypto has no Ed25519ph; on the browser's backend, sign the message with `crypto::eddsa`.", + "async_sign_eddsa_prehashed_asynchronous_backend": "As `sign_eddsa_prehashed_asynchronous_backend`: `async_sign` under `crypto::eddsa_prehashed` runs on a native backend.", + "verify_eddsa_prehashed_asynchronous_backend": "Verify under `crypto::eddsa_prehashed` on a native backend, `crypto::verify` and the key's `verify` alike: WebCrypto has no Ed25519ph; on the browser's backend, verify a signature of the message with `crypto::eddsa`.", + "async_verify_eddsa_prehashed_asynchronous_backend": "As `verify_eddsa_prehashed_asynchronous_backend`: `async_verify` under `crypto::eddsa_prehashed`, free and member, runs on a native backend.", + "ph_removed": "Name Ed25519ph's streaming signer `curves::ed25519::prehashed_signer`, the same `begin`, `update`, `sign` and `verify`; `curves::ed25519::ph` is gone, with no alias.", "heavy_without_threads_on_emscripten": "As `heavy_without_threads`: on Emscripten, add `multi`.", "chacha_on_ctaes_on_emscripten": "As `chacha_on_ctaes`.", "aead_not_a_family_on_emscripten": "As `aead_not_a_family`.", @@ -1459,6 +1537,36 @@ "chacha_unknown_backend": "Name a backend of `webcpp::crypto::backends` that has the family, as `backends::bearssl`, or leave the backend out for the family's default: `chacha20_poly1305<>`.", "ed25519_unknown_policy": "Leave the policy out, as in `crypto::verify(crypto::eddsa, signature, message, public_key)`, or name `curves::ed25519::strict`.", "secret_of_no_bytes": "Give `secret` the number of bytes it holds, at least one, as in `secret<32>`.", + "equal_header_removed": "Include ``, the header of `constant_time_equal`; `equal.hpp` is gone, with no header left at its path.", + "equal_removed": "Call `crypto::constant_time_equal`, the same comparison of two spans or two digests in constant time; `crypto::equal` is gone, with no alias.", + "wipe_removed": "Call `crypto::erase_secret`, which zeroes a contiguous range the program owns (a `std::string&`, a `std::span`) with stores the optimiser keeps; `crypto::wipe` is gone, with no alias.", + "x25519_free_functions_removed": "Make the key pair with `curves::x25519::keypair::from_secret(secret)`, then call its `public_key()`, and its `agree` with the peer's `curves::x25519::public_key` from `from_bytes`; the free functions over bytes are gone, with no alias. The `x25519::public_key(secret)` half pins clang's generic \"no matching conversion for functional-style cast\", since `public_key` now names the type.", + "iv_size_removed": "Name nonce_size, max_nonce_size and error::invalid_nonce_size: crypto spells its names out.", + "aead_template_removed": "Name `ciphers::basic_chacha20_poly1305`, or its aliases `chacha20_poly1305`, `chacha20_poly1305_original` and `xchacha20_poly1305`: the template is named for its algorithm, with no alias.", + "aead_template_removed_call": "As `aead_template_removed`: name `ciphers::basic_chacha20_poly1305`.", + "secp256k1_tweak_names_removed": "Call public_key_tweak_add, public_key_tweak_mul, public_key_negate, public_key_combine, secret_key_tweak_add, secret_key_tweak_mul and secret_key_negate: crypto spells out the names libsecp256k1 abbreviates.", + "secp256k1_tweak_names_removed_call": "As `secp256k1_tweak_names_removed`.", + "musig_nonce_gen_removed": "Call musig::generate_nonce: crypto spells out the names libsecp256k1 abbreviates.", + "musig_nonce_gen_removed_call": "As `musig_nonce_gen_removed`.", + "prevouts_summary_removed": "Name silent_payments::previous_outputs_summary and make_previous_outputs_summary: crypto spells out libsecp256k1's prevouts.", + "prevouts_summary_removed_call": "As `prevouts_summary_removed`.", + "seal_box_associated_data": "Call the box form, `secret_key_encryption::seal(box, nonce, data)` or the box's own `seal(nonce, data)`: a secret box or a crypto_box takes no associated data; authenticate it with an AEAD, as `ciphers::xchacha20_poly1305<>`.", + "seal_removed": "Call crypto::secret_key_encryption::aead::seal and open, in , which every AEAD's header includes.", + "secretbox_header_removed": "Include ``, the secret boxes' header; `ciphers/secretbox.hpp` is gone, with no header left at its path.", + "secretbox_removed": "Name `crypto::secret_key_encryption::secretbox` and `secretbox_xchacha20poly1305`, the secret boxes' namespace; `ciphers::secretbox` is gone, with no alias.", + "secretbox_removed_call": "As `secretbox_removed`: name `crypto::secret_key_encryption::secretbox<>` and `secretbox_xchacha20poly1305<>`, the names clang offers.", + "seal_removed_call": "As `seal_removed`: call crypto::secret_key_encryption::aead::seal and open, which the cipher's header brings.", + "async_seal_removed": "Call crypto::secret_key_encryption::aead::async_seal and async_open. clang's suggestion, `secret_key_encryption::async_seal` and `async_open`, is the box form, which takes no associated data and is wrong for an AES-GCM or ChaCha20-Poly1305 user.", + "async_seal_removed_declaration": "As `async_seal_removed`: call crypto::secret_key_encryption::aead::async_seal and async_open, in .", + "async_seal_box_asynchronous_backend": "Name a native backend, such as `backends::sodium`, for the secret box: WebCrypto has no secret box, so no form of it runs on the browser's backend, where only AES-GCM seals and opens.", + "async_open_box_asynchronous_backend": "Name a native backend, such as `backends::sodium`, for the crypto_box: WebCrypto has no crypto_box, so no form of it runs on the browser's backend, where only AES-GCM seals and opens.", + "async_seal_member_asynchronous_backend": "As `async_seal_xchacha`: name a native backend, such as `backends::sodium`, for XChaCha20-Poly1305's `async_seal`.", + "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.", + "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.", + "erase_secret_const_range": "Erase the buffer the secret was written to, through a non-const reference to it (`std::string&`, `std::span`): a const view cannot be erased. Its elements must be trivially copyable, bytes or integers; a range of `std::string` or of another type with its own storage cannot be erased as bytes, so erase each element's buffer instead.", "chacha_default_not_linked_on_emscripten": "As `chacha_default_not_linked`.", "box_default_not_linked_on_emscripten": "As `box_default_not_linked`.", "kx_default_not_linked_on_emscripten": "As `kx_default_not_linked`.", diff --git a/doc/tables/generate.py b/doc/tables/generate.py index 3af7d3df..d4df791f 100644 --- a/doc/tables/generate.py +++ b/doc/tables/generate.py @@ -86,7 +86,12 @@ RUN_RULES = ('crypto-run', 'memory-run', 'webcpp.run', 'webcpp.compile', 'webcpp.compile-diagnostic', 'webcpp.compile-fail', 'webcpp.link-fail', 'webcpp.example') -EXPECTED_ERROR = re.compile(r'expected-error@\S+ \{\{(.*)\}\}') +# A message test's text: clang's -verify directive, with the count it takes when two calls raise +# the same text (`expected-error@:* 2 {{text}}`). A directive that ends with `(knock-on)` +# after its text pins an error clang adds because of another (an undeclared name the first error +# left, a call it corrected): the test checks it, and the page leaves it out. clang's -verify +# ignores the words after a directive. +EXPECTED_ERROR = re.compile(r'expected-error@\S+(?: \d+)? \{\{(.*)\}\}(\s*\(knock-on\))?') SOURCE = re.compile(r'\{([a-z0-9-]+)\}') # A comparison table's cell that the data writes: {speed:}, the family's throughput from # doc/performance.json, or {constant_time:}, its measured constant time from crypto.json. @@ -206,18 +211,25 @@ def tests(library: Path) -> Dict[str, List[str]]: return found -def messages(library: Path) -> Dict[str, Tuple[str, List[str]]]: - """Each message test's case: the text its source states, and its targets.""" - found: Dict[str, Tuple[str, List[str]]] = {} +def messages(library: Path) -> Dict[str, Tuple[List[str], List[str]]]: + """Each message test's case: every text its source states, each once, in the source's order + (a test that pins several removed names lists them all, the first error first), but a + knock-on error's, and its targets.""" + found: Dict[str, Tuple[List[str], List[str]]] = {} for directory in sorted((library / 'test' / 'messages').iterdir()): if not directory.is_dir(): continue declared = programs(directory / 'Jamfile') for source in sorted(directory.glob('*.cpp')): + if source.stem not in declared: + continue + texts: List[str] = [] for line in source.read_text(encoding='utf-8').splitlines(): text = EXPECTED_ERROR.search(line) - if text and source.stem in declared: - found[source.stem] = (text.group(1), declared[source.stem]) + if text and not text.group(2) and text.group(1) not in texts: + texts.append(text.group(1)) + if texts: + found[source.stem] = (texts, declared[source.stem]) return found @@ -364,7 +376,7 @@ class Matrix: """The support of each operation on each backend and target, from the tests' targets.""" def __init__(self, data: Data, declared: Dict[str, List[str]], - refusals: Dict[str, Tuple[str, List[str]]]) -> None: + refusals: Dict[str, Tuple[List[str], List[str]]]) -> None: self.data = data self.supported: Dict[Tuple[str, str], List[str]] = {} self.proofs: Dict[Tuple[str, str], List[str]] = {} @@ -1373,13 +1385,14 @@ def listed(items: List[Tuple[str, List[str], bool]]) -> str: def constant_time_page(data: Data) -> str: """Constant time per backend: by its library's design, and per target what the lane runs, - from the same `lane` entries as the comparison tables.""" + from the same `lane` entries as the comparison tables, each cell's bars escaped, as a + finding's or a note's |t| would otherwise end the cell.""" rows: List[List[str]] = [] for backend in libraries(data): facts = data['backends'][backend] sources = ''.join(f'; {{{source}}}' for source in facts['constant_time_sources']) - rows.append([facts['title'], marked(cite(data, facts['constant_time'] + sources))] - + [lane_cell(data, backend, target) for target in data['targets']]) + rows.append([facts['title'], cell(marked(cite(data, facts['constant_time'] + sources)))] + + [cell(lane_cell(data, backend, target)) for target in data['targets']]) return table(['Backend', 'By design'] + [f'Measured, {target}' for target in data['targets']], rows) + constant_time_notes(data) @@ -1641,20 +1654,21 @@ def jamfiles_page(data: Data, cases: Dict[str, Tuple[List[str], Outcome]]) -> st return case_list(entries) -def messages_page(data: Data, refusals: Dict[str, Tuple[str, List[str]]], +def messages_page(data: Data, refusals: Dict[str, Tuple[List[str], List[str]]], cases: Dict[str, Tuple[List[str], Outcome]], msvc: Dict[str, str]) -> str: """Every message: the compiler's, checked by a message test; the build's, from a fixture.""" fixes: Dict[str, str] = data['fixes'] rows: List[List[str]] = [] - for name, (text, targets) in refusals.items(): + for name, (texts, targets) in refusals.items(): if name not in fixes: raise Fault(f'the message test {name} has no fix in crypto.json') # The message as a sentence of code, which breaks between its words as the cell # does: one line of hundreds of characters would make the table scroll for all of it. # Its fix is the cell's second paragraph, so that the longest name of each does not - # widen a column of its own. + # widen a column of its own. A test that pins several messages has a paragraph each. + messages_text = '\n\n'.join(cell(code(text)) for text in texts) rows.append([code(name), ', '.join(targets), - f'{cell(code(text))}\n\nThe fix: {marked(fixes[name])}']) + f'{messages_text}\n\nThe fix: {marked(fixes[name])}']) text = ('At compile time, checked word for word by the message tests of `test/messages` ' 'with clang:\n\n') text += table(['Case', 'Checked on', 'The message, and its fix'], rows, 'cols="2,1,7",') diff --git a/doc/tables/generate_test.py b/doc/tables/generate_test.py index 67352fa5..8cdc8eec 100644 --- a/doc/tables/generate_test.py +++ b/doc/tables/generate_test.py @@ -75,6 +75,50 @@ def test_a_program_inside_an_if_is_a_fault(scratch: Path) -> None: raise AssertionError('a program inside an if was read as declared everywhere') +def test_a_message_expected_more_than_once_is_read(scratch: Path) -> None: + # clang's -verify counts a text that two calls raise: `expected-error@:* 2 {{text}}`. + # The case is a message test all the same, whose text the page lists and whose fix it needs. + written(scratch, 'test/messages/twice/Jamfile', + 'webcpp.compile-diagnostic twice : twice.cpp : : native : alone ;\n') + written(scratch, 'test/messages/twice/twice.cpp', + '// expected-error@webcpp/crypto/signing.hpp:* 2 {{webcpp::crypto: refused.}}\n') + found = generate.messages(scratch) + assert found == {'twice': (['webcpp::crypto: refused.'], ['native'])}, found + + +def test_a_message_test_s_first_error_is_its_message(scratch: Path) -> None: + # A removed name's alias stops the build, and every use of the alias adds clang's own + # error after it: the page lists the first, and leaves out the one marked as a knock-on. + written(scratch, 'test/messages/alias/Jamfile', + 'webcpp.compile-diagnostic alias : alias.cpp : : native : alone ;\n') + written(scratch, 'test/messages/alias/alias.cpp', ( + "// expected-error@+1 {{no template named 'old' in namespace 'n'}}\n" + 'using cipher = n::old;\n' + "// expected-error@+1 {{use of undeclared identifier 'cipher'}} (knock-on)\n" + 'int x = cipher::size;\n')) + found = generate.messages(scratch) + assert found == {'alias': (["no template named 'old' in namespace 'n'"], ['native'])}, found + + +def test_a_test_of_several_removed_names_lists_each(scratch: Path) -> None: + # A test that pins several removed names lists every one, in the source's order, each once. + written(scratch, 'test/messages/names/Jamfile', + 'webcpp.compile-diagnostic names : names.cpp : : native wasip2 : alone ;\n') + written(scratch, 'test/messages/names/names.cpp', ( + "// expected-error@+1 {{no member named 'a' in namespace 'n'}}\n" + 'using n::a;\n' + "// expected-error@+1 {{no member named 'b' in namespace 'n'}}\n" + 'using n::b;\n' + "// expected-error@+1 {{no member named 'a' in namespace 'n'}}\n" + 'using n::a;\n')) + found = generate.messages(scratch) + assert found == {'names': (["no member named 'a' in namespace 'n'", + "no member named 'b' in namespace 'n'"], + ['native', 'wasip2'])}, found + page = generate.messages_page({'fixes': {'names': 'Name m.'}}, found, {}, {}) + assert "`+no member named 'a' in namespace 'n'+`\n\n`+no member named 'b'" in page, page + + def test_the_memory_option_s_tests_are_declared(scratch: Path) -> None: # The OpenSSL memory option's programs live in test/openssl_memory, each through its own # rule; a name that two Jamfiles declare is a fault, since a table would cite one of them. @@ -1223,12 +1267,31 @@ def test_the_constant_time_page_fills_each_target_from_the_lane(_: Path) -> None backend.update({'library': 'l', 'constant_time': 'by design', 'constant_time_sources': []}) data['backends']['none'] = {'title': 'no backend', 'library': 'own', 'constant_time': 'yes', 'constant_time_sources': [], 'lane_paths': [ - {'what': '`equal`', 'lane': {'native': ['memcheck']}}]} + {'what': '`constant_time_equal`', + 'lane': {'native': ['memcheck']}}]} page = generate.constant_time_page(data) assert ('|libsodium\n|by design\n|memcheck (Linux): ChaCha20-Poly1305; dudect: ' 'ChaCha20-Poly1305\n|dudect: ChaCha20-Poly1305 (measured differently, below)\n' '|not measured yet\n|not measured yet\n') in page, page - assert '|no backend\n|yes\n|memcheck (Linux): `+equal+`\n|not measured yet\n' in page, page + assert ('|no backend\n|yes\n|memcheck (Linux): `+constant_time_equal+`\n' + '|not measured yet\n') in page, page + + +def test_the_constant_time_page_escapes_the_bars_of_a_lane_note(_: Path) -> None: + data = two_ciphers() + for backend in data['backends'].values(): + backend.update({'library': 'l', 'constant_time': 'by design, |t| below 10', + 'constant_time_sources': []}) + entry = data['families'][0]['backends']['sodium'] + entry['lane_note'] = {'dudect': 'judged constant time, |t| 1.70'} + page = generate.constant_time_page(data) + # A bar in a table's cell ends the cell: |t| would split the note over two cells, and + # Asciidoctor then drops the incomplete row. + assert ('|by design, \\|t\\| below 10\n' + '|memcheck (Linux): ChaCha20-Poly1305; dudect: ChaCha20-Poly1305 (judged constant ' + 'time, \\|t\\| 1.70)\n' + '|dudect: ChaCha20-Poly1305 (judged constant time, \\|t\\| 1.70; measured ' + 'differently, below)\n') in page, page def test_a_note_on_one_family_of_a_cell_names_that_family(_: Path) -> None: @@ -1447,6 +1510,7 @@ def test_a_namespace_table_is_split_into_its_parts(_: Path) -> None: test_a_rule_body_declares_nothing, test_a_program_inside_an_if_is_a_fault, test_the_memory_option_s_tests_are_declared, + test_a_message_expected_more_than_once_is_read, test_a_backend_says_why_it_is_missing_elsewhere, test_a_reason_elsewhere_is_openssl_s_alone, test_an_outcome_reads_each_directive, @@ -1506,6 +1570,7 @@ def test_a_namespace_table_is_split_into_its_parts(_: Path) -> None: test_a_speed_cell_names_each_operation_and_refuses_an_unknown_backend, test_a_measured_cell_escapes_the_bars_of_its_finding, test_the_constant_time_page_fills_each_target_from_the_lane, + test_the_constant_time_page_escapes_the_bars_of_a_lane_note, test_a_note_on_one_family_of_a_cell_names_that_family, test_a_lane_entry_the_family_does_not_claim_is_a_fault, test_a_finding_of_one_checker_marks_that_checker_alone, diff --git a/doc/testing.adoc b/doc/testing.adoc index 27aaa922..8a26819a 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -76,7 +76,7 @@ keys' `spki`, `pkcs8` and `raw` exports (`p256_webcrypto_oracle`, `oracle ok 800`, and its corrupted twin); and against OpenSSL natively and on WASI, 200 cases each of RFC 6979 signatures, ECDH and SPKI and PKCS#8 (`p256_openssl_oracle`, `oracle ok 600`) (<>). -* *The backends against each other,* on random keys, IVs, additional data and +* *The backends against each other,* on random keys, nonces, associated data and messages of every size around a block's: BearSSL and OpenSSL seal the same bytes with AES-GCM and each opens what the other sealed, with BearSSL on its x86-64 instructions and on its portable code; ctaes and OpenSSL encrypt the diff --git a/doc/wallets.adoc b/doc/wallets.adoc index e964c364..b07a44b0 100644 --- a/doc/wallets.adoc +++ b/doc/wallets.adoc @@ -28,11 +28,11 @@ of the curve, and must survive on disk without being readable there. *The idea.* 32 bytes from `random_device` are a valid secp256k1 secret key with overwhelming probability; when they are not (zero, or not below the group -order), `make` says so and the wallet draws again. At rest, the secret is sealed +order), `from_secret` says so and the wallet draws again. At rest, the secret is sealed with AES-GCM under a key the device keeps elsewhere (a platform keystore, or a key derived from the user's passphrase by a password hash, a hashing library's job rather than crypto's), with the wallet's format version as -additional data. +associated data. [source,cpp] ---- @@ -136,14 +136,14 @@ and wipes the pair if the tweak gives no valid key; what the tweak means is the domain library's. The x-only tweak is BIP 341's arithmetic: it lifts the key to the point with an -even y, and the key pair's version negates the secret key when the public -key's y is odd. It serves the protocols built on x-only keys, such as Taproot's -output key or a pay-to-contract commitment to an x-only key. It is not BIP 32's -child derivation, which adds to the parent's full point and secret key without -that negation: for the half of the parents whose public key has an odd y, an -x-only tweak derives another child than every BIP 32 wallet, whose addresses a -wallet restored from the same seed never finds. BIP 32 tweaks the full key, -with `seckey_tweak_add` and `pubkey_tweak_add` (<>), +even y, and the key pair's version negates the secret key when the public key's +y is odd. It serves the protocols built on x-only keys, such as Taproot's output +key or a pay-to-contract commitment to an x-only key. It is not BIP 32's child +derivation, which adds to the parent's full point and secret key without that +negation: for the half of the parents whose public key has an odd y, an x-only +tweak derives another child than every BIP 32 wallet, whose addresses a wallet +restored from the same seed never finds. BIP 32 tweaks the full key, with +`secret_key_tweak_add` and `public_key_tweak_add` (<>), and computes its tweak with HMAC-SHA-512, which is a domain library's (link:https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki[BIP 32]). @@ -165,9 +165,9 @@ candidates; a recoverable signature adds the id, 0 to 3, of the one that verifies, so that a reader computes the signer's key from the signature and the hash alone. Ethereum finds a transaction's sender this way (link:https://ethereum.github.io/yellowpaper/paper.pdf[Ethereum's yellow paper, -appendix F]). `sign(crypto::ecdsa_sha256_recoverable, input)` makes the 65 -bytes, and `recover(crypto::ecdsa_sha256_recoverable, signature, input)` finds -the key (<>). Recovery finds some key for almost any +appendix F]). `sign(crypto::ecdsa_sha256_recoverable, input)` makes the +65-byte `recoverable_signature`, and +`recover(crypto::ecdsa_sha256_recoverable, signature, input)` finds the key (<>). Recovery finds some key for almost any signature and any hash: what makes it a check is the comparison with the key the reader expects. @@ -185,10 +185,12 @@ Ethereum compares addresses rather than keys, the last 20 bytes of the Keccak-256 of the uncompressed key (the yellow paper, appendix F), and a wallet signs a message after EIP-191's prefix (link:https://eips.ethereum.org/EIPS/eip-191[EIP-191]), whose digest is -Keccak-256's: the library passes it as `+crypto::prehashed{digest}+`, which the -scheme signs and recovers as given (<>). -Both are the protocol's rules, which a domain library built on crypto, such as -a future webcpp::ethereum, computes; crypto holds the signature and the recovery. This +Keccak-256's: Ethereum's scheme is `crypto::ecdsa_keccak256_recoverable`, which +signs and recovers that digest given as `+crypto::prehashed{digest}+` +(<>, with a `personal_sign` example that prints `v` +and the address). The digest, `v` and the address are the protocol's rules, +which the program, or a domain library built on crypto, such as a future +webcpp::ethereum, computes; crypto holds the signature and the recovery. This section names no application. *Mistakes to avoid.* Never trust a recovered key on its own: a changed or @@ -227,17 +229,16 @@ include::{examples}/musig_wallet.expected[] The wallet's address, its transactions and the hash each device signs are a domain library's. This section names no application. -*Mistakes to avoid.* Reusing a nonce: two partial signatures with one nonce -give away the secret key, so a nonce is made when the signature is made, never +*Mistakes to avoid.* Reusing a nonce: two partial signatures with one nonce give +away the secret key, so a nonce is made when the signature is made, never stored, and never restored from a backup; `partial_sign` takes it by value and -refuses one already used. Signing before every nonce is in: a device that -signs while the other can still choose its nonce lets it steer the final nonce, -which the two rounds exist to prevent -(link:https://eprint.iacr.org/2020/1261[Nick, Ruffing and Seurin, MuSig2]). A -naive key sum: the plain sum of the two public keys, `pubkey_combine`, is not -a multisignature, since a device that announces its key after seeing the -other's can choose one that cancels it and spend alone; `key_aggregate` weighs -each key by a hash of all of them (BIP 327). +refuses one already used. Signing before every nonce is in: a device that signs +while the other can still choose its nonce lets it steer the final nonce, which +the two rounds exist to prevent (link:https://eprint.iacr.org/2020/1261[Nick, +Ruffing and Seurin, MuSig2]). A naive key sum: the plain sum of the two public +keys, `public_key_combine`, is not a multisignature, since a device that +announces its key after seeing the other's can choose one that cancels it and +spend alone; `key_aggregate` weighs each key by a hash of all of them (BIP 327). [#crypto-wallets-silent] === A reusable address: silent payments diff --git a/doc/x25519.adoc b/doc/x25519.adoc index 8b8c098f..67451bb0 100644 --- a/doc/x25519.adoc +++ b/doc/x25519.adoc @@ -22,28 +22,55 @@ link:https://www.rfc-editor.org/rfc/rfc8731[RFC 8731]; link:https://www.wireguard.com/protocol/[WireGuard]; link:https://signal.org/docs/specifications/x3dh/[X3DH]). -`public_key(secret_key)` gives the public key of any 32 bytes, which a program -draws with `random_device`; `agree(secret_key, peer_public_key)` gives the -shared secret, a `secret<32>` that wipes itself. A peer's public key of low -order makes the shared secret all zero, whatever the secret key: `agree` -refuses it with `weak_public_key`, so that an attacker who sends such a key -cannot make both sides use a secret it knows (design D8). Every case of -Wycheproof's X25519 file gives its shared secret, and its 31 all-zero cases -give `weak_public_key` (`x25519_wycheproof_sodium`). +A key pair, `keypair`, is made from its 32-byte secret key by +`keypair::from_secret(secret_bytes)`, any 32 bytes, or drawn from +`random_device` by `keypair::generate()`; its public key, computed once when it +is made, is `public_key()`, a `curves::x25519::public_key`, whose `bytes()` a +program sends, and `secret()` gives the secret key back, to keep. A peer's key +arrives as bytes and is made by `public_key::from_bytes(bytes)`, which checks +their size alone. `key_pair.agree(peer_key)` gives the shared secret, a +`secret<32>` that wipes itself. A moved-from key pair refuses every call with +`invalid_state`. A peer's public key of low order makes the shared secret all +zero, whatever the secret key: `agree` refuses it with `weak_public_key`, so +that an attacker who sends such a key cannot make both sides use a secret it +knows (design D8). Every case of Wycheproof's X25519 file gives its shared +secret, and its 31 all-zero cases give `weak_public_key` +(`x25519_wycheproof_sodium`). -include::generated/backends-x25519_public_key.adoc[] +The keys are typed: a key pair is a `keypair`, a public key a +`curves::x25519::public_key`, and no operation takes either as bytes, so that a +peer's key is never mistaken for the program's own secret, nor an Ed25519 key's +bytes for an X25519 key. Each operation has the four forms of every key pair +(<>): the members above; their free forms +`crypto::from_secret(secret_bytes)`, `crypto::generate()` +and `crypto::agree(key_pair, peer_key)`; and, X25519 being in WebCrypto, their +asynchronous forms, `keypair::async_from_secret`, `keypair::async_generate` +and `key_pair.async_agree`, and the free `crypto::async_from_secret`, +`crypto::async_generate` and `crypto::async_agree`, in +`` (<>). A public key is made by +`public_key::from_bytes` or `crypto::from_bytes`, synchronously +alone, as every public key is. The key pair is a `crypto::agreement_keypair` +and not a `crypto::signing_keypair`: X25519 agrees and does not sign +(<>). + +include::generated/backends-x25519_keypair.adoc[] -include::generated/backends-x25519_agree.adoc[] +include::generated/backends-x25519_public_key.adoc[] -*From Ed25519.* A program that already holds an Ed25519 key pair (<>) -agrees with the same seed: `keypair::x25519_secret()` is its X25519 secret key, -and `curves::ed25519::to_x25519_public(public_key)` converts a peer's Ed25519 -public key to its X25519 public key, the birational map between the two forms -of the curve. The conversion refuses with `invalid_public_key` a key of small -order, off the curve or outside the main subgroup, as libsodium does +*From Ed25519.* A program that already holds an Ed25519 key pair +(<>) agrees with the same seed: its `to_x25519()` gives its +X25519 key pair, of the same backend, and a peer's Ed25519 public key's +`to_x25519()` gives that peer's X25519 public key, the birational map between +the two forms of the curve; the free `crypto::to_x25519(value)` calls either. +The converted key pair's public key is its Ed25519 public key's conversion. The +conversion of a public key refuses with `invalid_public_key` a key of small +order, not canonical, off the curve or outside the main subgroup, as libsodium +does (link:https://doc.libsodium.org/advanced/ed25519-curve25519[libsodium's documentation]). +Both are synchronous on every backend: WebCrypto converts nothing between the +two. -include::generated/backends-ed25519_to_x25519_public.adoc[] +include::generated/backends-ed25519_to_x25519.adoc[] *Example.* RFC 7748's Alice and Bob, then two Ed25519 key pairs that agree through their X25519 forms, then a peer key of low order refused: diff --git a/example/Jamfile b/example/Jamfile index bd79c081..16d7c7e5 100644 --- a/example/Jamfile +++ b/example/Jamfile @@ -19,8 +19,9 @@ webcpp.example schnorr_sign.cpp : /third_party//secp256k1 ; webcpp.example aes256_gcm_bearssl.cpp : /third_party//bearssl ; # end::aes256_gcm_bearssl[] -# A Boost.Hash2 HMAC tag compared in constant time with equal; no backend. -webcpp.example equal_hmac.cpp ; +# A Boost.Hash2 HMAC tag compared in constant time with constant_time_equal; no +# backend. +webcpp.example constant_time_equal_hmac.cpp ; # BearSSL's HMAC-DRBG seeded from random_device. webcpp.example bearssl_prng.cpp : /third_party//bearssl ; @@ -31,7 +32,7 @@ webcpp.example failure_reasons.cpp : /webcpp/crypto//gcm-default ; # A reset token and a one-time code from random_device; no backend. webcpp.example reset_token.cpp ; -# An API token stored in a row, bound to the user id as additional data. +# An API token stored in a row, bound to the user id as associated data. webcpp.example store_token.cpp : /webcpp/crypto//gcm-default ; # The incremental seal, and records bound to their numbers. @@ -61,6 +62,12 @@ webcpp.example ecdh_x_coordinate.cpp : /third_party//secp256k1 ; # and the hash. webcpp.example recover_signer.cpp : /third_party//secp256k1 ; +# Ethereum's personal_sign: EIP-191's digest built over webcpp::hash's +# Keccak-256, signed with crypto::ecdsa_keccak256_recoverable, r, s and v +# printed, and the signer's address recovered (web3.js's documented vector). +webcpp.example ethereum_personal_sign.cpp + : /third_party//secp256k1 /third_party//xkcp ; + # A watch-only wallet: the same tweak on the public key and on the secret key, # and a signature of the tweaked key pair verified under the tweaked public key. webcpp.example key_tweak.cpp : /third_party//secp256k1 ; diff --git a/example/aes256_gcm_bearssl.cpp b/example/aes256_gcm_bearssl.cpp index d3b809a4..6d215cc3 100644 --- a/example/aes256_gcm_bearssl.cpp +++ b/example/aes256_gcm_bearssl.cpp @@ -11,7 +11,7 @@ #include #include #include -#include +#include #include #include @@ -23,10 +23,10 @@ namespace crypto = webcpp::crypto; using aead_type = crypto::ciphers::gcm>; int main() { - // The test vector's zero key and IV: a real program draws its key from random_device and - // never reuses an IV under it. + // The test vector's zero key and nonce: a real program draws its key from random_device and + // never reuses a nonce under it. std::array const key{}; - std::array const iv{}; + std::array const nonce{}; std::array data{}; std::array const expected_cipher{ 0xce, 0xa7, 0x40, 0x3d, 0x4d, 0x60, 0x6b, 0x6e, @@ -37,18 +37,18 @@ int main() { 0x26, 0x5b, 0x98, 0xb5, 0xd4, 0x8a, 0xb9, 0x19, }; - auto aead = aead_type::make(key); + auto aead = aead_type::from_key(key); if (!aead) { return 1; } // Seal encrypts in place and returns the tag. - auto const tag = aead->seal(iv, {}, data); - if (!tag || data != expected_cipher || !crypto::equal(*tag, expected_tag)) { + auto const tag = aead->seal(nonce, {}, data); + if (!tag || data != expected_cipher || !crypto::constant_time_equal(*tag, expected_tag)) { return 1; } // Open decrypts in place and checks the tag; on a mismatch it zeroes data and returns // authentication_failed. - if (!aead->open(iv, {}, data, expected_tag) || data != std::array{}) { + if (!aead->open(nonce, {}, data, expected_tag) || data != std::array{}) { return 1; } auto const name = aead_type::backend_type::name; diff --git a/example/arena_signer.cpp b/example/arena_signer.cpp index fa3951f5..8f1a5b65 100644 --- a/example/arena_signer.cpp +++ b/example/arena_signer.cpp @@ -74,7 +74,7 @@ int main() { // from random_device. std::array secret{}; secret.fill(0x42); - auto key = secp256k1::keypair::make(secret, &counting); + auto key = secp256k1::keypair::from_secret(secret, &counting); wipe(std::as_writable_bytes(std::span(secret))); if (!key) { return 1; diff --git a/example/async_seal.cpp b/example/async_seal.cpp index fb847739..c2320627 100644 --- a/example/async_seal.cpp +++ b/example/async_seal.cpp @@ -5,11 +5,10 @@ // https://www.boost.org/LICENSE_1_0.txt) // An audit record sealed and opened through an event loop: the GCM specification's test case 16 -// (AES-256, 12-byte IV, additional data), a published key, never a real one. Each completion runs -// from the loop's run, after the call that started it has returned, on every target; the handler -// of the seal prints the tag and starts the open, the handler of the open compares the plaintext. -// The loop ends when no operation is pending: nothing waits for a time. -// tag::program[] +// (AES-256, 12-byte nonce, associated data), a published key, never a real one. Each completion +// runs from the loop's run, after the call that started it has returned, on every target; the +// handler of the seal prints the tag and starts the open, the handler of the open compares the +// plaintext. The loop ends when no operation is pending: nothing waits for a time. tag::program[] #include #include @@ -58,30 +57,30 @@ void print(char const* name, std::span bytes) { int main() { auto const key = bytes_of("feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308"); - auto const iv = bytes_of("cafebabefacedbaddecaf888"); - auto const additional_data = bytes_of("feedfacedeadbeeffeedfacedeadbeefabaddad2"); + auto const nonce = bytes_of("cafebabefacedbaddecaf888"); + auto const associated_data = bytes_of("feedfacedeadbeeffeedfacedeadbeefabaddad2"); auto const record = bytes_of( "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449" "a6b525b16aedf5aa0de657ba637b39"); asio::io_context loop; - // What a call reads and writes is the program's until the completion: the key, the IV, the - // additional data and the record outlive the loop's run. The record is sealed in place. + // What a call reads and writes is the program's until the completion: the key, the nonce, the + // associated data and the record outlive the loop's run. The record is sealed in place. std::vector data = record; std::optional aead; bool returned = false; int status = 1; - crypto::async_make( + crypto::async_from_key( loop.get_executor(), key, [&](boost::system::error_code made, aead_type keyed) { if (made) { - std::printf("make: %s\n", made.message().c_str()); + std::printf("from_key: %s\n", made.message().c_str()); return; } aead.emplace(std::move(keyed)); std::printf("made after the call returned: %s\n", returned ? "yes" : "no"); - crypto::async_seal( - loop.get_executor(), *aead, iv, additional_data, data, + crypto::secret_key_encryption::aead::async_seal( + loop.get_executor(), *aead, nonce, associated_data, data, [&](boost::system::error_code sealed, aead_type::result_type digest) { if (sealed) { std::printf("seal: %s\n", sealed.message().c_str()); @@ -91,17 +90,17 @@ int main() { std::ranges::copy(digest, tag.begin()); print("tag", tag); // The ciphertext replaced the record, and the tag opens it back. - crypto::async_open(loop.get_executor(), *aead, iv, additional_data, data, tag, - [&](boost::system::error_code opened) { - if (opened) { - std::printf("open: %s\n", opened.message().c_str()); - return; - } - bool const same = std::ranges::equal(data, record); - std::printf("opened, the record is back: %s\n", - same ? "yes" : "no"); - status = same ? 0 : 1; - }); + crypto::secret_key_encryption::aead::async_open( + loop.get_executor(), *aead, nonce, associated_data, data, tag, + [&](boost::system::error_code opened) { + if (opened) { + std::printf("open: %s\n", opened.message().c_str()); + return; + } + bool const same = std::ranges::equal(data, record); + std::printf("opened, the record is back: %s\n", same ? "yes" : "no"); + status = same ? 0 : 1; + }); }); }); returned = true; diff --git a/example/async_sign.cpp b/example/async_sign.cpp index 80ceedbc..10d185f0 100644 --- a/example/async_sign.cpp +++ b/example/async_sign.cpp @@ -59,11 +59,11 @@ asio::awaitable sign_and_verify() { auto const executor = co_await asio::this_coro::executor; auto const use = asio::as_tuple(asio::use_awaitable); - auto made_result = co_await crypto::async_make(executor, seed, use); + auto made_result = co_await crypto::async_from_secret(executor, seed, use); auto& [made, key] = made_result; if (made) { - std::printf("make: %s\n", made.message().c_str()); + std::printf("from_secret: %s\n", made.message().c_str()); co_return false; } auto const public_key = key.public_key(); @@ -79,7 +79,7 @@ asio::awaitable sign_and_verify() { co_return false; } print("public key", public_key->bytes()); - print("signature ", signature); + print("signature ", signature.bytes()); // The verifier holds the public key, the message and the signature; nothing secret. auto [verified] = co_await crypto::async_verify(executor, crypto::eddsa, signature, message, *public_key, use); diff --git a/example/bitcoin_sighash.cpp b/example/bitcoin_sighash.cpp index c13adae3..fa5e1ac5 100644 --- a/example/bitcoin_sighash.cpp +++ b/example/bitcoin_sighash.cpp @@ -57,7 +57,7 @@ int main() { // (RFC 6979), so the same key and sighash always give the same signature. std::array secret{}; secret.fill(0x11); - auto key = secp256k1::keypair::make(secret); + auto key = secp256k1::keypair::from_secret(secret); wipe(std::as_writable_bytes(std::span(secret))); if (!key) { return 1; diff --git a/example/box_messages.cpp b/example/box_messages.cpp index ecdb8393..7f3fc482 100644 --- a/example/box_messages.cpp +++ b/example/box_messages.cpp @@ -5,15 +5,14 @@ // https://www.boost.org/LICENSE_1_0.txt) // Two people who know each other's X25519 public keys exchange messages in libsodium's box: -// each makes a box from the own secret key and the other's public key, agreeing one key for the +// 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. // tag::program[] #include #include -#include +#include #include -#include #include #include @@ -21,35 +20,35 @@ #include #include #include +#include #include namespace crypto = webcpp::crypto; -using crypto::hybrid::box; +using crypto::public_key_encryption::box; namespace { -// A person's X25519 key pair: the secret key stays, the public key is published. +// A person's X25519 key pair: the secret key stays in it, the public key is published. struct person { - crypto::secret<32> secret_key; - std::array public_key{}; + crypto::curves::x25519::keypair key_pair; + crypto::curves::x25519::public_key public_key; - static std::optional make(crypto::random_device& device) { - person made; - if (!device.fill(made.secret_key.writable())) { + static std::optional generate() { + auto key_pair = crypto::curves::x25519::keypair::generate(); + if (!key_pair) { return std::nullopt; } - auto const public_key = crypto::curves::x25519::public_key(made.secret_key.bytes()); + auto const public_key = key_pair->public_key(); if (!public_key) { return std::nullopt; } - made.public_key = *public_key; - return made; + return person{.key_pair = std::move(*key_pair), .public_key = *public_key}; } }; // A message as it travels: the nonce, the tag and the ciphertext. struct sealed_message { - std::array nonce{}; + std::array nonce{}; box::result_type tag{}; std::vector ciphertext; }; @@ -85,18 +84,18 @@ void read(char const* who, box& recipient, sealed_message message) { int main() { crypto::random_device device; - auto alice = person::make(device); - auto bob = person::make(device); - auto mallory = person::make(device); + auto const alice = person::generate(); + auto const bob = person::generate(); + auto const mallory = person::generate(); if (!alice || !bob || !mallory) { return 1; } // tag::boxes[] - // Each side's box: the own secret key and the other's public key give the same key. - auto alice_box = box::make(alice->secret_key.bytes(), bob->public_key); - auto bob_box = box::make(bob->secret_key.bytes(), alice->public_key); + // Each side's box: the own key pair and the other's public key give the same key. + auto alice_box = box::from_keys(alice->key_pair, bob->public_key); + auto bob_box = box::from_keys(bob->key_pair, alice->public_key); // end::boxes[] - auto mallory_box = box::make(mallory->secret_key.bytes(), alice->public_key); + auto mallory_box = box::from_keys(mallory->key_pair, alice->public_key); if (!alice_box || !bob_box || !mallory_box) { return 1; } diff --git a/example/equal_hmac.cpp b/example/constant_time_equal_hmac.cpp similarity index 70% rename from example/equal_hmac.cpp rename to example/constant_time_equal_hmac.cpp index a3fe5160..51ff9af7 100644 --- a/example/equal_hmac.cpp +++ b/example/constant_time_equal_hmac.cpp @@ -4,11 +4,11 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// Checks an HMAC-SHA-256 tag from Boost.Hash2 with webcpp::crypto::equal, the constant-time -// comparison. Comparing tags with == or memcmp stops at the first difference, and that timing -// lets an attacker guess a valid tag one byte at a time. +// Checks an HMAC-SHA-256 tag from Boost.Hash2 with webcpp::crypto::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. // tag::program[] -#include +#include #include #include @@ -37,18 +37,19 @@ int main() { hash2::hmac_sha2_256 mac(key.data(), key.size()); mac.update(data.data(), data.size()); auto const computed = mac.result(); - bool const valid = - crypto::equal(std::span(computed.data(), computed.size()), sent_tag); + bool const valid = crypto::constant_time_equal( + std::span(computed.data(), computed.size()), sent_tag); // end::check[] if (!valid) { return 1; } - std::printf("hmac verified with equal\n"); + std::printf("hmac verified with constant_time_equal\n"); // A tag with one changed byte must be refused. auto altered = sent_tag; altered[31] ^= 1U; - if (crypto::equal(std::span(computed.data(), computed.size()), altered)) { + if (crypto::constant_time_equal(std::span(computed.data(), computed.size()), + altered)) { return 1; } std::printf("altered tag refused\n"); diff --git a/example/constant_time_equal_hmac.expected b/example/constant_time_equal_hmac.expected new file mode 100644 index 00000000..d27983f4 --- /dev/null +++ b/example/constant_time_equal_hmac.expected @@ -0,0 +1,2 @@ +hmac verified with constant_time_equal +altered tag refused diff --git a/example/ecdh_session.cpp b/example/ecdh_session.cpp index 48fbea5d..5a1345d0 100644 --- a/example/ecdh_session.cpp +++ b/example/ecdh_session.cpp @@ -9,8 +9,8 @@ // it to this application with a context string. // tag::program[] #include +#include #include -#include #include #include #include @@ -120,7 +120,7 @@ boost::system::result generate_key() { if (!filled) { return filled.error(); } - auto key = secp256k1::keypair::make(secret); + auto key = secp256k1::keypair::from_secret(secret); if (key || key.error() != crypto::error::invalid_secret_key) { // The key pair keeps its own copy, which it wipes; this one goes now. wipe(std::as_writable_bytes(std::span(secret))); @@ -134,7 +134,7 @@ boost::system::result generate_key() { boost::system::result session_cipher( crypto::secret<32> const& shared) { auto key = hkdf_sha256<32>(shared.bytes(), {}, bytes_of("example chat v1 session key")); - auto cipher = crypto::ciphers::aes256_gcm::make(key); + auto cipher = crypto::ciphers::aes256_gcm::from_key(key); // The cipher keeps its own copy of the key, which it wipes; this one goes now. wipe(std::as_writable_bytes(std::span(key))); return cipher; @@ -148,7 +148,7 @@ bool hkdf_is_correct() { auto const info = from_hex<10>("f0f1f2f3f4f5f6f7f8f9"); auto const expected = from_hex<42>( "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865"); - return crypto::equal(hkdf_sha256<42>(input, salt, info), expected); + return crypto::constant_time_equal(hkdf_sha256<42>(input, salt, info), expected); } } // namespace @@ -179,7 +179,7 @@ int main() { auto const alice_shared = alice->agree_hashed(*bob_public); auto const bob_shared = bob->agree_hashed(*alice_public); if (!alice_shared || !bob_shared || - !crypto::equal(alice_shared->bytes(), bob_shared->bytes())) { + !crypto::constant_time_equal(alice_shared->bytes(), bob_shared->bytes())) { return 1; } std::printf("shared secrets match\n"); @@ -193,15 +193,15 @@ int main() { } // end::agree[] - std::array iv{}; - if (!crypto::random_device().fill(iv)) { + std::array nonce{}; + if (!crypto::random_device().fill(nonce)) { return 1; } std::string_view const text = "hello bob"; std::array message{}; std::ranges::copy(text, message.begin()); - auto const tag = alice_cipher->seal(iv, {}, message); - if (!tag || !bob_cipher->open(iv, {}, message, std::span(*tag))) { + auto const tag = alice_cipher->seal(nonce, {}, message); + if (!tag || !bob_cipher->open(nonce, {}, message, std::span(*tag))) { return 1; } std::printf("bob read: %.*s\n", static_cast(message.size()), diff --git a/example/ecdh_x_coordinate.cpp b/example/ecdh_x_coordinate.cpp index bb2a1b87..5bfe52c3 100644 --- a/example/ecdh_x_coordinate.cpp +++ b/example/ecdh_x_coordinate.cpp @@ -9,8 +9,8 @@ // 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. // tag::program[] +#include #include -#include #include #include @@ -80,7 +80,7 @@ std::array conversation_key(crypto::secret<32> const& shared_x boost::system::result from_secret(std::uint8_t fill) { std::array secret{}; secret.fill(fill); - auto made = secp256k1::keypair::make(secret); + auto made = secp256k1::keypair::from_secret(secret); // The key pair keeps its own copy, which it wipes; this one goes now. wipe(std::as_writable_bytes(std::span(secret))); return made; @@ -105,7 +105,7 @@ int main() { // a secret<32> that wipes itself. auto const alice_x = alice->agree(*bob_public); auto const bob_x = bob->agree(*alice_public); - if (!alice_x || !bob_x || !crypto::equal(alice_x->bytes(), bob_x->bytes())) { + if (!alice_x || !bob_x || !crypto::constant_time_equal(alice_x->bytes(), bob_x->bytes())) { return 1; } std::printf("shared x coordinates match\n"); diff --git a/example/ecdsa_der.cpp b/example/ecdsa_der.cpp index 74ae4d31..d053bf48 100644 --- a/example/ecdsa_der.cpp +++ b/example/ecdsa_der.cpp @@ -84,7 +84,7 @@ int main() { // (RFC 6979), so the same key and hash always give the same signature. std::array secret{}; secret.fill(0x11); - auto key = secp256k1::keypair::make(secret); + auto key = secp256k1::keypair::from_secret(secret); wipe(std::as_writable_bytes(std::span(secret))); if (!key) { return 1; @@ -127,10 +127,15 @@ int main() { std::printf("verified\n"); // tag::normalize[] - // The high-S twin: same r, s replaced by n - s. - auto high = *signature; - auto const flipped = order_minus(std::span(high).last<32>()); - std::ranges::copy(flipped, high.begin() + 32); + // The high-S twin: same r, s replaced by n - s, as a signature from elsewhere arrives. + auto high_bytes = signature->bytes(); + auto const flipped = order_minus(std::span(high_bytes).last<32>()); + std::ranges::copy(flipped, high_bytes.begin() + 32); + auto const received = secp256k1::ecdsa_signature::from_bytes(high_bytes); + if (!received) { + return 1; + } + auto const& high = *received; auto const refused = crypto::verify(crypto::ecdsa_sha256, high, crypto::prehashed{sighash}, *public_key); if (refused || refused.error() != crypto::error::invalid_signature) { diff --git a/example/ed25519_sign.cpp b/example/ed25519_sign.cpp index 5f64c143..45a92e5a 100644 --- a/example/ed25519_sign.cpp +++ b/example/ed25519_sign.cpp @@ -7,8 +7,12 @@ // Signs RFC 8032's second Ed25519 test with a key pair made from its seed and verifies the // signature with the public key alone, `key.sign(crypto::eddsa, message)` and // `crypto::verify(crypto::eddsa, signature, message, public_key)`; then signs the message "abc" -// given in two pieces with Ed25519ph, as RFC 8032's Ed25519ph test does, and verifies it with -// `verify(signature, public_key)`. Prints each key and signature in hex. +// given in two pieces with Ed25519ph's streaming signer, `curves::ed25519::prehashed_signer`, as +// RFC 8032's Ed25519ph test does, and verifies it with `verify(signature, public_key)`; then signs +// the message's SHA-512, a digest the program has, under the scheme `crypto::eddsa_prehashed`, +// which gives the same signature, and verifies it with +// `crypto::verify(crypto::eddsa_prehashed, signature, crypto::prehashed{digest}, public_key)`. +// Prints each key and signature in hex, and whether the two Ed25519ph signatures are equal. // tag::program[] #include #include @@ -49,7 +53,7 @@ bool sign_whole() { 0xa6, 0x24, 0xda, 0x8c, 0xf6, 0xed, 0x4f, 0xb8, 0xa6, 0xfb, }; std::array const message{0x72}; - auto const key = ed25519::keypair::make(seed); + auto const key = ed25519::keypair::from_secret(seed); if (!key) { return false; } @@ -59,13 +63,14 @@ bool sign_whole() { return false; } print("public key", public_key->bytes()); - print("signature ", *signature); + print("signature ", signature->bytes()); // The verifier holds the public key, the message and the signature; nothing secret. return crypto::verify(crypto::eddsa, *signature, message, *public_key).has_value(); } // Ed25519ph: the message given in pieces, as a large file is read, signed once at the end, -// over SHA-512, the hash RFC 8032 fixes. +// over SHA-512, the hash RFC 8032 fixes; then the same message's SHA-512 signed under the scheme +// crypto::eddsa_prehashed, as a program that has the digest already signs it. bool sign_in_pieces() { std::array const seed{ 0x83, 0x3f, 0xe6, 0x24, 0x09, 0x23, 0x7b, 0x9d, 0x62, 0xec, 0x77, @@ -74,8 +79,8 @@ bool sign_in_pieces() { }; std::array const first{'a'}; std::array const second{'b', 'c'}; - using signer = ed25519::ph; - auto const key = ed25519::keypair::make(seed); + using signer = ed25519::prehashed_signer; + auto const key = ed25519::keypair::from_secret(seed); auto signing = signer::begin(); if (!key || !signing || !signing->update(first) || !signing->update(second)) { return false; @@ -86,10 +91,28 @@ bool sign_in_pieces() { return false; } print("public key", public_key->bytes()); - print("signature ", *signature); + print("signature ", signature->bytes()); auto verifying = signer::begin(); - return verifying && verifying->update(first) && verifying->update(second) && - verifying->verify(*signature, *public_key).has_value(); + if (!verifying || !verifying->update(first) || !verifying->update(second) || + !verifying->verify(*signature, *public_key)) { + return false; + } + + // The digest the signer hashed inside, computed here: the scheme signs it into the same + // signature, which crypto::verify checks under the same scheme. + webcpp::hash::sha2_512 hasher; + hasher.update(first.data(), first.size()); + hasher.update(second.data(), second.size()); + auto const digest = hasher.result(); + auto const from_digest = key->sign(crypto::eddsa_prehashed, crypto::prehashed{digest}); + if (!from_digest) { + return false; + } + std::printf("eddsa_prehashed gives the same signature: %s\n", + *from_digest == *signature ? "yes" : "no"); + return *from_digest == *signature && crypto::verify(crypto::eddsa_prehashed, *from_digest, + crypto::prehashed{digest}, *public_key) + .has_value(); } } // namespace diff --git a/example/ed25519_sign.expected b/example/ed25519_sign.expected index 7bccf783..f3ec37a9 100644 --- a/example/ed25519_sign.expected +++ b/example/ed25519_sign.expected @@ -4,4 +4,5 @@ signature 92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da public key ec172b93ad5e563bf4932c70e1245034c35467ef2efd4d64ebf819683467e2bf signature 98a70222f0b8121aa9d30f813d683f809e462b469c7ff87639499bb94e6dae41 31f85042463c2a355a2003d062adf5aaa10b8c61e636062aaad11c2a26083406 +eddsa_prehashed gives the same signature: yes verified diff --git a/example/ellswift_handshake.cpp b/example/ellswift_handshake.cpp index 4962dbfa..b441ebd4 100644 --- a/example/ellswift_handshake.cpp +++ b/example/ellswift_handshake.cpp @@ -10,9 +10,9 @@ // encodings. The secrets and the randomness are fixed here, so that the program runs the same // each time; a real program draws all four from random_device. Nothing random is printed. // tag::program[] +#include #include #include -#include #include #include @@ -34,8 +34,8 @@ std::array repeated(std::uint8_t value) { int main() { // Each peer's key pair and the randomness of its encoding (random_device in a real program). - auto const initiator = secp256k1::keypair::make(repeated(0x11)); - auto const responder = secp256k1::keypair::make(repeated(0x22)); + auto const initiator = secp256k1::keypair::from_secret(repeated(0x11)); + auto const responder = secp256k1::keypair::from_secret(repeated(0x22)); if (!initiator || !responder) { return 1; } @@ -64,7 +64,7 @@ int main() { auto const responder_secret = secp256k1::ellswift_xdh( *responder, *initiator_message, *responder_message, secp256k1::ellswift_party::responder); if (!initiator_secret || !responder_secret || - !crypto::equal(initiator_secret->bytes(), responder_secret->bytes())) { + !crypto::constant_time_equal(initiator_secret->bytes(), responder_secret->bytes())) { return 1; } std::printf("initiator and responder agree\n"); diff --git a/example/equal_hmac.expected b/example/equal_hmac.expected deleted file mode 100644 index b36b6fc3..00000000 --- a/example/equal_hmac.expected +++ /dev/null @@ -1,2 +0,0 @@ -hmac verified with equal -altered tag refused diff --git a/example/ethereum_personal_sign.cpp b/example/ethereum_personal_sign.cpp new file mode 100644 index 00000000..8b8d41b5 --- /dev/null +++ b/example/ethereum_personal_sign.cpp @@ -0,0 +1,111 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Signs a message as an Ethereum wallet's personal_sign does, then finds the signer's address +// from the signature alone. The program builds EIP-191's digest itself with webcpp::hash's +// Keccak-256, signs it as crypto::prehashed with crypto::ecdsa_keccak256_recoverable, prints r, +// s and v, recovers the key and prints its address. crypto computes none of the protocol's +// encodings: not the digest (EIP-191's here, EIP-712's or a transaction's elsewhere), not v +// (27 + the recovery id for personal_sign, 35 + 2 x chain_id + the id for EIP-155, the id itself +// as a typed transaction's yParity), not the address. The key and the message are web3.js's +// documented example (web3.eth.accounts.sign('Some data', ...)), whose signature this prints. +// tag::program[] +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace crypto = webcpp::crypto; +namespace secp256k1 = webcpp::crypto::curves::secp256k1; + +namespace { + +// Keccak-256 of bytes, Ethereum's hash (the original padding, not SHA3-256's). +std::array keccak_256(std::span bytes) { + webcpp::hash::keccak_256 hasher; + hasher.update(bytes.data(), bytes.size()); + auto const hash_result = hasher.result(); + std::array digest{}; + std::copy_n(hash_result.data(), digest.size(), digest.begin()); + return digest; +} + +// tag::digest[] +// EIP-191's personal_sign digest: Keccak-256 of "\x19Ethereum Signed Message:\n", the message's +// length in decimal, and the message. The protocol's rule, computed here, not by crypto. +std::array personal_sign_digest(std::string_view message) { + std::string prefixed = + "\x19" + "Ethereum Signed Message:\n"; + prefixed += std::to_string(message.size()); + prefixed += message; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): a text's bytes + return keccak_256({reinterpret_cast(prefixed.data()), prefixed.size()}); +} + +// end::digest[] + +void print_hex(char const* label, std::span bytes) { + std::printf("%s0x", label); + for (std::uint8_t const octet : bytes) { + std::printf("%02x", static_cast(octet)); + } + std::printf("\n"); +} + +} // namespace + +int main() { + // web3.js's documented key; a wallet's own comes from its secret storage. + constexpr std::array secret{ + 0x4c, 0x08, 0x83, 0xa6, 0x91, 0x02, 0x93, 0x7d, 0x62, 0x31, 0x47, + 0x1b, 0x5d, 0xbb, 0x62, 0x04, 0xfe, 0x51, 0x29, 0x61, 0x70, 0x82, + 0x79, 0x2a, 0xe4, 0x68, 0xd0, 0x1a, 0x3f, 0x36, 0x23, 0x18, + }; + auto const wallet = secp256k1::keypair::from_secret(secret); + if (!wallet) { + return 1; + } + + // tag::sign[] + // The wallet signs EIP-191's digest as given: crypto::prehashed, never hashed again. + auto const digest = personal_sign_digest("Some data"); + auto const signature = + wallet->sign(crypto::ecdsa_keccak256_recoverable, crypto::prehashed{digest}); + if (!signature) { + return 1; + } + std::span const signed_bytes = signature->bytes(); + print_hex("r: ", signed_bytes.first<32>()); + print_hex("s: ", signed_bytes.subspan<32, 32>()); + // personal_sign's v is 27 + the recovery id; EIP-155's and a typed transaction's differ. + std::printf("v: %u\n", 27U + signature->recovery_id()); + // end::sign[] + + // tag::recover[] + // The reader recovers the key from the signature and the same digest, and makes its address: + // the last 20 bytes of Keccak-256 over the uncompressed key without its 0x04. + auto const signer = secp256k1::recover(crypto::ecdsa_keccak256_recoverable, *signature, + crypto::prehashed{digest}); + if (!signer) { + return 1; + } + auto const uncompressed = signer->uncompressed(); + auto const key_hash = keccak_256(std::span(uncompressed).subspan<1>()); + print_hex("address: ", std::span(key_hash).last<20>()); + // end::recover[] + return 0; +} + +// end::program[] diff --git a/example/ethereum_personal_sign.expected b/example/ethereum_personal_sign.expected new file mode 100644 index 00000000..bb6dc852 --- /dev/null +++ b/example/ethereum_personal_sign.expected @@ -0,0 +1,4 @@ +r: 0xb91467e570a6466aa9e9876cbcd013baba02900b8979d43fe208a4a4f339f5fd +s: 0x6007e74cd82e037b800186422fc2da167c747ef045e5d18a5f5d4300f8e1a029 +v: 28 +address: 0x2c7536e3605d9c16a7a3d7b1898e529396a65c23 diff --git a/example/failure_reasons.cpp b/example/failure_reasons.cpp index 044789e7..45e7119f 100644 --- a/example/failure_reasons.cpp +++ b/example/failure_reasons.cpp @@ -4,7 +4,7 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// Shows the three ways AES-GCM can refuse a message: a tampered ciphertext, an IV of the wrong +// Shows the three ways AES-GCM can refuse a message: a tampered ciphertext, a nonce of the wrong // size and a tag of the wrong size. A program must tell the first from the others: only // authentication_failed means someone changed the data, and open then wipes the plaintext so // that no unauthenticated bytes are ever used. @@ -42,22 +42,22 @@ bool all_zero(std::span bytes) { } // namespace int main() { - // A demonstration key and IV, so that the output is the same on every run; a real program - // draws the key from random_device and never reuses an IV under it. + // A demonstration key and nonce, so that the output is the same on every run; a real program + // draws the key from random_device and never reuses a nonce under it. std::array key{}; key.fill(0x2a); - std::array iv{}; - iv.fill(0x07); + std::array nonce{}; + nonce.fill(0x07); std::string_view const text = "attack at dawn!"; std::array sealed{}; std::ranges::copy(text, sealed.begin()); - auto aead = aead_type::make(key); + auto aead = aead_type::from_key(key); wipe(std::as_writable_bytes(std::span(key))); if (!aead) { return 1; } - auto const tag = aead->seal(iv, {}, sealed); + auto const tag = aead->seal(nonce, {}, sealed); if (!tag) { return 1; } @@ -66,7 +66,7 @@ int main() { // (a) One flipped bit in the ciphertext. auto tampered = sealed; tampered[3] ^= 1U; - auto const opened = aead->open(iv, {}, tampered, tag_bytes); + auto const opened = aead->open(nonce, {}, tampered, tag_bytes); // tag::branch[] if (opened) { return 1; @@ -86,16 +86,16 @@ int main() { return 1; } - // (b) An empty IV is refused before anything is touched. + // (b) An empty nonce is refused before anything is touched. auto copy = sealed; - auto const no_iv = aead->open({}, {}, copy, tag_bytes); - if (no_iv || no_iv.error() != crypto::error::invalid_iv_size || copy != sealed) { + auto const no_nonce = aead->open({}, {}, copy, tag_bytes); + if (no_nonce || no_nonce.error() != crypto::error::invalid_nonce_size || copy != sealed) { return 1; } - std::printf("empty iv: invalid_iv_size, data untouched\n"); + std::printf("empty nonce: invalid_nonce_size, data untouched\n"); // (c) A tag of 15 bytes instead of 16. - auto const short_tag = aead->open(iv, {}, copy, tag_bytes.first(15)); + auto const short_tag = aead->open(nonce, {}, copy, tag_bytes.first(15)); if (short_tag || short_tag.error() != crypto::error::invalid_tag_size) { return 1; } diff --git a/example/failure_reasons.expected b/example/failure_reasons.expected index a2bdbc01..e42943cc 100644 --- a/example/failure_reasons.expected +++ b/example/failure_reasons.expected @@ -1,4 +1,4 @@ tampered: authentication_failed, data zeroed message: the authentication tag does not match -empty iv: invalid_iv_size, data untouched +empty nonce: invalid_nonce_size, data untouched short tag: invalid_tag_size diff --git a/example/file_share.cpp b/example/file_share.cpp index b8b2ea10..abbb9975 100644 --- a/example/file_share.cpp +++ b/example/file_share.cpp @@ -7,36 +7,35 @@ // A file-sharing app shares a file with a recipient it knows only by an X25519 public key: the // file is sealed once in a secret box under a key drawn for this file, and that file key is // sealed to the recipient's public key in a sealed box. The upload holds both; only the -// recipient's secret key opens the file key, and the file key opens the file. Prints what the +// recipient's key pair opens the file key, and the file key opens the file. Prints what the // recipient reads, the sizes on the wire, and the refusals of a changed upload and of another // key pair. // tag::program[] -#include #include #include -#include +#include #include #include +#include #include #include #include #include -#include #include #include #include namespace crypto = webcpp::crypto; -using crypto::ciphers::secretbox; -using crypto::hybrid::sealed_box; +using crypto::public_key_encryption::sealed_box; +using crypto::secret_key_encryption::secretbox; namespace { // What the app uploads: the sealed file key, the file's nonce and tag, and the sealed file. struct upload { std::array sealed_key{}; - std::array::iv_size> nonce{}; + std::array::nonce_size> nonce{}; secretbox<>::result_type tag{}; std::vector file; }; @@ -44,18 +43,19 @@ struct upload { // tag::share[] // The sender: a key for this file alone, the file in a secret box under it, the key sealed to // the recipient. -bool share(crypto::random_device& device, std::span recipient_public_key, +bool share(crypto::random_device& device, + crypto::curves::x25519::public_key const& recipient_public_key, std::string_view contents, upload& out) { crypto::secret<32> file_key; if (!device.fill(file_key.writable()) || !device.fill(out.nonce)) { return false; } - auto box = secretbox<>::make(file_key.bytes()); + auto box = secretbox<>::from_key(file_key.bytes()); if (!box) { return false; } out.file.assign(contents.begin(), contents.end()); - auto const tag = box->seal(out.nonce, {}, out.file); + auto const tag = box->seal(out.nonce, out.file); if (!tag) { return false; } @@ -67,21 +67,19 @@ bool share(crypto::random_device& device, std::span recipien // tag::receive[] // The recipient: the file key out of the sealed box, then the file out of the secret box. -void receive(char const* who, std::span public_key, - std::span secret_key, upload received) { +void receive(char const* who, crypto::curves::x25519::keypair const& key_pair, upload received) { crypto::secret<32> file_key; - auto const key_opened = - sealed_box::open(public_key, secret_key, received.sealed_key, file_key.writable()); + auto const key_opened = sealed_box::open(key_pair, received.sealed_key, file_key.writable()); if (!key_opened) { std::string const reason = key_opened.error().message(); std::printf("%s: the file key refused: %s\n", who, reason.c_str()); return; } - auto box = secretbox<>::make(file_key.bytes()); + auto box = secretbox<>::from_key(file_key.bytes()); if (!box) { return; } - auto const opened = box->open(received.nonce, {}, received.file, received.tag); + auto const opened = box->open(received.nonce, received.file, received.tag); if (!opened) { std::string const reason = opened.error().message(); std::printf("%s: the file refused: %s\n", who, reason.c_str()); @@ -99,11 +97,11 @@ int main() { crypto::random_device device; // The recipient's key pair, made once on the recipient's device; only the public key is // published. - crypto::secret<32> secret_key; - if (!device.fill(secret_key.writable())) { + auto const key_pair = crypto::curves::x25519::keypair::generate(); + if (!key_pair) { return 1; } - auto const public_key = crypto::curves::x25519::public_key(secret_key.bytes()); + auto const public_key = key_pair->public_key(); if (!public_key) { return 1; } @@ -114,22 +112,18 @@ int main() { } std::printf("on the wire: %zu bytes of sealed key, %zu of nonce, %zu of tag, %zu of file\n", sent.sealed_key.size(), sent.nonce.size(), sent.tag.size(), sent.file.size()); - receive("the recipient", *public_key, secret_key.bytes(), sent); + receive("the recipient", *key_pair, sent); // The storage service changes the file. upload changed = sent; changed.file[0] ^= 0x01U; - receive("the recipient, the upload changed", *public_key, secret_key.bytes(), changed); + receive("the recipient, the upload changed", *key_pair, changed); // Someone else's key pair cannot open the file key. - crypto::secret<32> other_secret; - if (!device.fill(other_secret.writable())) { + auto const other_pair = crypto::curves::x25519::keypair::generate(); + if (!other_pair) { return 1; } - auto const other_public = crypto::curves::x25519::public_key(other_secret.bytes()); - if (!other_public) { - return 1; - } - receive("another key pair", *other_public, other_secret.bytes(), sent); + receive("another key pair", *other_pair, sent); return 0; } diff --git a/example/four_forms.cpp b/example/four_forms.cpp index 2afae683..2b0568bd 100644 --- a/example/four_forms.cpp +++ b/example/four_forms.cpp @@ -12,7 +12,7 @@ // tag::program[] #include #include -#include +#include #include #include @@ -67,18 +67,18 @@ int main() { }; auto const message = bytes_of("sample"); - // tag::make[] + // tag::from_secret[] // The member and its free form make the same key pair from the same scalar. - auto const key = p256::keypair::make(scalar); - auto const same_key = crypto::make(scalar); - // end::make[] + auto const key = p256::keypair::from_secret(scalar); + auto const same_key = crypto::from_secret(scalar); + // end::from_secret[] auto const public_key = key ? key->public_key() : key.error(); auto const same_public_key = same_key ? same_key->public_key() : same_key.error(); if (!public_key || !same_public_key) { std::printf("failed\n"); return 1; } - report("make: free = member", public_key->uncompressed() == same_public_key->uncompressed()); + report("from_secret: free", public_key->uncompressed() == same_public_key->uncompressed()); // tag::sign[] // Synchronous: the member, and its free form, which calls it. @@ -89,16 +89,16 @@ int main() { // member when it is initiated and completes through the loop, never inside the call. asio::io_context loop; auto const executor = loop.get_executor(); - std::array async_signature{}; - std::array free_async_signature{}; + p256::ecdsa_signature async_signature; + p256::ecdsa_signature free_async_signature; key->async_sign(executor, crypto::ecdsa_sha256, message, - [&](boost::system::error_code code, std::array made) { + [&](boost::system::error_code code, p256::ecdsa_signature made) { if (!code) { async_signature = made; } }); crypto::async_sign(executor, *key, crypto::ecdsa_sha256, message, - [&](boost::system::error_code code, std::array made) { + [&](boost::system::error_code code, p256::ecdsa_signature made) { if (!code) { free_async_signature = made; } @@ -109,7 +109,7 @@ int main() { std::printf("failed\n"); return 1; } - print("signature", *signature); + print("signature", signature->bytes()); report("sign: free", *free_signature == *signature); report("sign: async member", async_signature == *signature); report("sign: async free", free_async_signature == *signature); diff --git a/example/four_forms.expected b/example/four_forms.expected index 841d845e..0ce65a45 100644 --- a/example/four_forms.expected +++ b/example/four_forms.expected @@ -1,4 +1,4 @@ -make: free = member yes +from_secret: free yes signature efd48b2aacb6a8fd1140dd9cd45e81d69d2c877b56aaf991c34d0ea84eaf3716 0834e36ad29a83bf2bc9385e491d6099c8fdf9d1ed67aa7ea5f51f93782857a9 sign: free yes diff --git a/example/key_formats.cpp b/example/key_formats.cpp index 46aaed9f..dc64e84e 100644 --- a/example/key_formats.cpp +++ b/example/key_formats.cpp @@ -85,9 +85,13 @@ bool x25519_to_pem() { 0x72, 0x51, 0xb2, 0x66, 0x45, 0xdf, 0x4c, 0x2f, 0x87, 0xeb, 0xc0, 0x99, 0x2a, 0xb1, 0x77, 0xfb, 0xa5, 0x1d, 0xb9, 0x2c, 0x2a, }; - auto const public_key = x25519::public_key(alice_secret); + auto const alice = x25519::keypair::from_secret(alice_secret); + if (!alice) { + return false; + } + auto const public_key = alice->public_key(); std::array spki{}; - return public_key && x25519::encode_spki(*public_key, spki) && print_public_pem(spki); + return public_key && x25519::encode_spki(public_key->bytes(), spki) && print_public_pem(spki); } // Version 2 decodes from PEM, then the PKCS#8 is refused: strict decoding takes one form. diff --git a/example/key_tweak.cpp b/example/key_tweak.cpp index 8ec6f299..56df582a 100644 --- a/example/key_tweak.cpp +++ b/example/key_tweak.cpp @@ -90,7 +90,7 @@ int main() { if (!device.fill(secret.bytes) || !device.fill(chain_code.bytes)) { return 1; } - auto const wallet = secp256k1::keypair::make(secret.bytes); + auto const wallet = secp256k1::keypair::from_secret(secret.bytes); if (!wallet) { // A secret not below the group order: negligible, and a real wallet draws again. return 1; @@ -104,14 +104,14 @@ int main() { payment_tweak(chain_code.bytes, wallet_public->compressed(), 7, tweak); // The server: the wallet's public key plus the tweak, with no secret anywhere. - auto const watched = secp256k1::pubkey_tweak_add(*wallet_public, tweak.bytes); + auto const watched = secp256k1::public_key_tweak_add(*wallet_public, tweak.bytes); // The device: the secret key plus the same tweak, a secret<32> it makes a key pair of. - auto const tweaked_secret = secp256k1::seckey_tweak_add(secret.bytes, tweak.bytes); + auto const tweaked_secret = secp256k1::secret_key_tweak_add(secret.bytes, tweak.bytes); if (!watched || !tweaked_secret) { return 1; } - auto const payment_key = secp256k1::keypair::make(tweaked_secret->bytes()); + auto const payment_key = secp256k1::keypair::from_secret(tweaked_secret->bytes()); if (!payment_key) { return 1; } diff --git a/example/kx_session.cpp b/example/kx_session.cpp index de63c3cc..e256b9a7 100644 --- a/example/kx_session.cpp +++ b/example/kx_session.cpp @@ -10,9 +10,10 @@ // of low order is refused. Prints the public keys and the client's session keys in hex. // tag::program[] #include -#include -#include +#include +#include #include +#include #include #include @@ -21,7 +22,7 @@ #include namespace crypto = webcpp::crypto; -namespace x25519 = webcpp::crypto::curves::x25519; +namespace key_exchange = webcpp::crypto::key_exchange; namespace { @@ -36,9 +37,9 @@ void print(char const* name, std::span bytes) { // The client sends "hello" to the server, sealed with the client's transmit key and opened with // the server's receive key, the same key. -bool message(x25519::session_keys const& client, x25519::session_keys const& server) { - auto sealer = crypto::ciphers::chacha20_poly1305<>::make(client.transmit.bytes()); - auto opener = crypto::ciphers::chacha20_poly1305<>::make(server.receive.bytes()); +bool message(key_exchange::session_keys const& client, key_exchange::session_keys const& server) { + auto sealer = crypto::ciphers::chacha20_poly1305<>::from_key(client.transmit.bytes()); + auto opener = crypto::ciphers::chacha20_poly1305<>::from_key(server.receive.bytes()); if (!sealer || !opener) { return false; } @@ -67,8 +68,8 @@ bool client_and_server() { } std::array server_seed = client_seed; server_seed[0] = 1; - auto const client = x25519::kx_keypair<>::make(client_seed); - auto const server = x25519::kx_keypair<>::make(server_seed); + auto const client = key_exchange::kx_keypair<>::derive_from_seed(client_seed); + auto const server = key_exchange::kx_keypair<>::derive_from_seed(server_seed); if (!client || !server) { return false; } @@ -78,8 +79,8 @@ bool client_and_server() { if (!client_public || !server_public) { return false; } - print("client public", *client_public); - print("server public", *server_public); + print("client public", client_public->bytes()); + print("server public", server_public->bytes()); auto const client_keys = client->client_session_keys(*server_public); auto const server_keys = server->server_session_keys(*client_public); if (!client_keys || !server_keys) { @@ -88,19 +89,22 @@ bool client_and_server() { // Printed here only because libsodium's test publishes them; a program never prints a key. print("client rx ", client_keys->receive.bytes()); print("client tx ", client_keys->transmit.bytes()); - return crypto::equal(client_keys->transmit.bytes(), server_keys->receive.bytes()) && - crypto::equal(client_keys->receive.bytes(), server_keys->transmit.bytes()) && + return crypto::constant_time_equal(client_keys->transmit.bytes(), + server_keys->receive.bytes()) && + crypto::constant_time_equal(client_keys->receive.bytes(), + server_keys->transmit.bytes()) && message(*client_keys, *server_keys); } // A peer key of low order gives an all-zero X25519 secret, which crypto_kx refuses. bool low_order_refused() { - auto const key = x25519::kx_keypair<>::make(std::array{}); - std::array const zero_point{}; - if (!key) { + auto const key = key_exchange::kx_keypair<>::derive_from_seed(std::array{}); + auto const zero_point = + crypto::curves::x25519::public_key::from_bytes(std::array{}); + if (!key || !zero_point) { return false; } - auto const keys = key->server_session_keys(zero_point); + auto const keys = key->server_session_keys(*zero_point); if (!keys && keys.error() == crypto::error::weak_public_key) { std::printf("low order refused: weak_public_key\n"); return true; diff --git a/example/musig_network.cpp b/example/musig_network.cpp index c9afe5be..2857abef 100644 --- a/example/musig_network.cpp +++ b/example/musig_network.cpp @@ -81,8 +81,8 @@ boost::system::result received_part( int main() { // Each device's key pair; each publishes its public key, which every party reads. - auto const phone = secp256k1::keypair::make(repeated(0x11)); - auto const laptop = secp256k1::keypair::make(repeated(0x22)); + auto const phone = secp256k1::keypair::from_secret(repeated(0x11)); + auto const laptop = secp256k1::keypair::from_secret(repeated(0x22)); if (!phone || !laptop) { return 1; } @@ -100,8 +100,8 @@ int main() { auto const message = repeated(0x5a); // Round one, on each device: a nonce for this signature, its public half sent as bytes. - auto phone_nonce = musig::nonce_gen(*phone, *wallet_key, message); - auto laptop_nonce = musig::nonce_gen(*laptop, *wallet_key, message); + auto phone_nonce = musig::generate_nonce(*phone, *wallet_key, message); + auto laptop_nonce = musig::generate_nonce(*laptop, *wallet_key, message); if (!phone_nonce || !laptop_nonce) { return 1; } @@ -182,7 +182,7 @@ int main() { return 1; } std::printf("the aggregate signature verifies as one BIP 340 signature: %zu bytes\n", - signature->size()); + signature->bytes().size()); return 0; } diff --git a/example/musig_taproot.cpp b/example/musig_taproot.cpp index 18964fc9..f88e606c 100644 --- a/example/musig_taproot.cpp +++ b/example/musig_taproot.cpp @@ -8,7 +8,7 @@ // the two signers' aggregate key is the internal key, and the output key on the chain is that // key tweaked by its TapTweak tagged hash. The tweak is applied to the aggregate key with // tweak_xonly_add before any nonce is made, since the session and the partial signatures need -// the key as tweaked, and nonce_gen mixes in the key it is given (BIP 327's NonceGen takes it +// the key as tweaked, and generate_nonce mixes in the key it is given (BIP 327's NonceGen takes it // only as an optional input); then the signers run MuSig2's two rounds as before, and the // signature verifies under the output key and not under the internal one. The tweak's hash is // the protocol's, which a domain library computes; it is shown here with webcpp::hash's SHA-256. @@ -64,8 +64,8 @@ std::array tagged_hash(std::string_view tag, std::span #include @@ -40,8 +40,8 @@ std::array repeated(std::uint8_t value) { int main() { // Each device's key pair; each sends the other its public key. - auto const phone = secp256k1::keypair::make(repeated(0x11)); - auto const laptop = secp256k1::keypair::make(repeated(0x22)); + auto const phone = secp256k1::keypair::from_secret(repeated(0x11)); + auto const laptop = secp256k1::keypair::from_secret(repeated(0x22)); if (!phone || !laptop) { return 1; } @@ -66,8 +66,8 @@ int main() { auto const message = repeated(0x5a); // Round one: each device makes a nonce for this signature and sends its public half. - auto phone_nonce = musig::nonce_gen(*phone, *wallet_key, message); - auto laptop_nonce = musig::nonce_gen(*laptop, *wallet_key, message); + auto phone_nonce = musig::generate_nonce(*phone, *wallet_key, message); + auto laptop_nonce = musig::generate_nonce(*laptop, *wallet_key, message); if (!phone_nonce || !laptop_nonce) { return 1; } diff --git a/example/opened_in_two_passes.cpp b/example/opened_in_two_passes.cpp index cb773666..662e08f5 100644 --- a/example/opened_in_two_passes.cpp +++ b/example/opened_in_two_passes.cpp @@ -52,10 +52,10 @@ std::span read_piece(std::istream& file, std::vector // Seals a copy of `plain` in pieces into `file`, and returns the tag, which is stored beside the // file. boost::system::result seal_file(aead_type& aead, - std::span iv, + std::span nonce, std::vector plain, std::ostream& file) { - if (auto const begun = aead.begin_seal(iv, {}); !begun) { + if (auto const begun = aead.begin_seal(nonce, {}); !begun) { return begun.error(); } for (std::size_t at = 0; at < plain.size(); at += file_piece_size) { @@ -73,12 +73,12 @@ boost::system::result seal_file(aead_type& aead, // tag::open[] // Opens the file in two passes, writing its plaintext to `plain`. The file must hold the same // bytes in both: a program reads a file of its own disk that no one else writes meanwhile. -boost::system::result open_file(aead_type& aead, std::span iv, +boost::system::result open_file(aead_type& aead, std::span nonce, std::span tag, std::istream& file, std::ostream& plain) { std::vector piece(file_piece_size); // The first pass reads every piece, and writes none. - if (auto const begun = aead.begin_open(iv, {}); !begun) { + if (auto const begun = aead.begin_open(nonce, {}); !begun) { return begun.error(); } std::size_t authenticated = 0; @@ -118,11 +118,11 @@ boost::system::result open_file(aead_type& aead, std::span key{}; - std::array iv{}; - if (!crypto::random_device().fill(key) || !crypto::random_device().fill(iv)) { + std::array nonce{}; + if (!crypto::random_device().fill(key) || !crypto::random_device().fill(nonce)) { return 1; } - auto aead = aead_type::make(key); + auto aead = aead_type::from_key(key); wipe(std::as_writable_bytes(std::span(key))); if (!aead) { return 1; @@ -133,13 +133,13 @@ int main() { } std::stringstream file; // a std::fstream of the program's own disk - auto const tag = seal_file(*aead, iv, original, file); + auto const tag = seal_file(*aead, nonce, original, file); if (!tag) { return 1; } file.seekg(0); std::stringstream plain; // another file of the program's own disk - if (!open_file(*aead, iv, std::span(tag->data(), tag->size()), file, plain)) { + if (!open_file(*aead, nonce, std::span(tag->data(), tag->size()), file, plain)) { return 1; } auto const text = plain.str(); diff --git a/example/openssl_memory.cpp b/example/openssl_memory.cpp index e8ae4cd9..fefd74ac 100644 --- a/example/openssl_memory.cpp +++ b/example/openssl_memory.cpp @@ -49,20 +49,20 @@ int main() { bool ok = false; std::thread worker([&ok] { - // A zero key and IV keep the output stable: a real program draws its key from - // random_device and never reuses an IV under it. + // A zero key and nonce keep the output stable: a real program draws its key from + // random_device and never reuses a nonce under it. std::array const key{}; - std::array const iv{}; + std::array const nonce{}; std::array data{}; { - auto aead = crypto::ciphers::aes256_gcm::make(key); + auto aead = crypto::ciphers::aes256_gcm::from_key(key); if (aead) { - auto const tag = aead->seal(iv, {}, data); - ok = - tag && aead->open(iv, {}, data, *tag) && data == std::array{}; + auto const tag = aead->seal(nonce, {}, data); + ok = tag && aead->open(nonce, {}, data, *tag) && + data == std::array{}; } else { std::string const message = aead.error().message(); - std::printf("make: %s\n", message.c_str()); + std::printf("from_key: %s\n", message.c_str()); } } // tag::thread[] diff --git a/example/order_reference.cpp b/example/order_reference.cpp index 66d1ed18..e84b8c5f 100644 --- a/example/order_reference.cpp +++ b/example/order_reference.cpp @@ -45,7 +45,7 @@ int main() { for (std::size_t i = 0; i < key.size(); ++i) { key[i] = static_cast(i); } - auto cipher = cipher_type::make(key); + auto cipher = cipher_type::from_key(key); wipe(std::as_writable_bytes(std::span(key))); if (!cipher) { return 1; diff --git a/example/p256_ecdh.cpp b/example/p256_ecdh.cpp index d544a746..63a4261e 100644 --- a/example/p256_ecdh.cpp +++ b/example/p256_ecdh.cpp @@ -19,8 +19,8 @@ // -kdfopt salt:"example salt" -kdfopt info:"example chat v1 key" HKDF (one line) // which print the x and the key of p256_ecdh.expected. // tag::program[] +#include #include -#include #include #include @@ -59,7 +59,7 @@ std::span bytes_of(std::string_view text) { boost::system::result from_byte(std::uint8_t fill) { std::array scalar{}; scalar.fill(fill); - return p256::keypair::make(scalar); + return p256::keypair::from_secret(scalar); } } // namespace @@ -84,7 +84,7 @@ int main() { auto const alice_x = alice->agree(*bob_public); auto const bob_x = bob->agree(*alice_public); // end::agree[] - if (!alice_x || !bob_x || !crypto::equal(alice_x->bytes(), bob_x->bytes())) { + if (!alice_x || !bob_x || !crypto::constant_time_equal(alice_x->bytes(), bob_x->bytes())) { std::printf("failed\n"); return 1; } diff --git a/example/p256_handshake.cpp b/example/p256_handshake.cpp index 1905fae2..0fac9b3f 100644 --- a/example/p256_handshake.cpp +++ b/example/p256_handshake.cpp @@ -13,8 +13,8 @@ // a real program draws its key pairs with keypair::generate(). What is signed, when, and the // low-S rule are a protocol's: this one is an example, not webcpp::trystero's. // tag::program[] +#include #include -#include #include #include @@ -60,7 +60,7 @@ std::span bytes_of(std::string_view text) { boost::system::result from_byte(std::uint8_t fill) { std::array scalar{}; scalar.fill(fill); - return p256::keypair::make(scalar); + return p256::keypair::from_secret(scalar); } // What a peer sends: its identity's public key and its session key pair's, raw, as WebCrypto's @@ -91,16 +91,15 @@ char const* text_of(verdict found) { // The high-S form of a low-S signature, r || (n - s): as another implementation, a browser's // WebCrypto among them, may sign the same digest. -std::array high_s_form( - std::span signature) { +boost::system::result high_s_form(p256::ecdsa_signature const& low) { // FIPS 186-5 / SEC 2: P-256's group order n. constexpr std::array order{ 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xbc, 0xe6, 0xfa, 0xad, 0xa7, 0x17, 0x9e, 0x84, 0xf3, 0xb9, 0xca, 0xc2, 0xfc, 0x63, 0x25, 0x51, }; - std::array high{}; - std::ranges::copy(signature, high.begin()); + auto const& signature = low.bytes(); + std::array high = signature; unsigned borrow = 0; for (std::size_t i = order.size(); i-- > 0;) { unsigned const difference = @@ -108,7 +107,7 @@ std::array high_s_form( high[order.size() + i] = static_cast(difference); borrow = (difference >> 8U) & 1U; } - return high; + return p256::ecdsa_signature::from_bytes(high); } // tag::transcript[] @@ -153,7 +152,7 @@ struct peer { // tag::sign[] // Signs the transcript's digest with the identity; sign gives the low-S form the protocol // requires. - [[nodiscard]] boost::system::result> sign( + [[nodiscard]] boost::system::result sign( std::span digest) const { return identity.sign(crypto::ecdsa_sha256, crypto::prehashed{digest}); } @@ -161,21 +160,26 @@ struct peer { // end::sign[] // tag::receive[] - // Checks the other peer's signature of the transcript: low S first, as the protocol requires + // Checks the other peer's signature of the transcript, its bytes as they arrive, made into a + // p256::ecdsa_signature (64 bytes, r then s): low S first, as the protocol requires // (crypto::verify accepts both forms, as WebCrypto does), then the signature itself, with the // identity key the peer sent, made into a public_key. A real protocol also checks that this // identity is the one it expects. static verdict check(hello const& other, std::span digest, - std::span signature) { - auto const identity_key = p256::public_key::make(other.identity); + std::span received_signature) { + auto const identity_key = p256::public_key::from_bytes(other.identity); if (!identity_key) { return verdict::bad_identity; } - if (!p256::is_low_s(signature)) { + auto const signature = p256::ecdsa_signature::from_bytes(received_signature); + if (!signature) { + return verdict::bad_signature; + } + if (!p256::is_low_s(*signature)) { return verdict::high_s; } - if (!crypto::verify(crypto::ecdsa_sha256, signature, crypto::prehashed{digest}, + if (!crypto::verify(crypto::ecdsa_sha256, *signature, crypto::prehashed{digest}, *identity_key)) { return verdict::bad_signature; } @@ -189,7 +193,7 @@ struct peer { // transcript's digest as the salt, so that the key is bound to this handshake. [[nodiscard]] boost::system::result> session_key( hello const& other, std::span digest) const { - auto const other_key = p256::public_key::make(other.session); + auto const other_key = p256::public_key::from_bytes(other.session); if (!other_key) { return other_key.error(); } @@ -217,7 +221,7 @@ boost::system::result peer_from(std::uint8_t identity_fill, std::uint8_t s if (!kept) { return kept.error(); } - auto identity = p256::keypair::make(kept->bytes()); + auto identity = p256::keypair::from_secret(kept->bytes()); auto session = from_byte(session_fill); if (!identity || !session) { return crypto::error::backend_failure; @@ -251,31 +255,36 @@ int main() { std::printf("failed\n"); return 1; } - print("alice signs", *alice_signature); - print("bob signs ", *bob_signature); + print("alice signs", alice_signature->bytes()); + print("bob signs ", bob_signature->bytes()); std::printf("bob checks alice: %s; alice checks bob: %s\n", - text_of(peer::check(*alice_hello, *digest, *alice_signature)), - text_of(peer::check(*bob_hello, *digest, *bob_signature))); + text_of(peer::check(*alice_hello, *digest, alice_signature->bytes())), + text_of(peer::check(*bob_hello, *digest, bob_signature->bytes()))); // Alice's signature with one bit of s flipped on the way: refused by the verification. - auto tampered = *alice_signature; + auto tampered = alice_signature->bytes(); tampered[40] ^= 0x01U; std::printf("tampered: %s\n", text_of(peer::check(*alice_hello, *digest, tampered))); // The same digest signed by another implementation in the high-S form: refused by the // protocol's rule before it is verified, though crypto::verify alone accepts it. auto const high = high_s_form(*alice_signature); - auto const alice_identity = p256::public_key::make(alice_hello->identity); + auto const alice_identity = p256::public_key::from_bytes(alice_hello->identity); + if (!high || !alice_identity) { + std::printf("failed\n"); + return 1; + } bool const verifies_alone = - alice_identity && - crypto::verify(crypto::ecdsa_sha256, high, crypto::prehashed{*digest}, *alice_identity); + crypto::verify(crypto::ecdsa_sha256, *high, crypto::prehashed{*digest}, *alice_identity) + .has_value(); std::printf("high S: %s; crypto::verify alone: %s\n", - text_of(peer::check(*alice_hello, *digest, high)), + text_of(peer::check(*alice_hello, *digest, high->bytes())), verifies_alone ? "verified" : "refused"); auto const alice_key = alice->session_key(*bob_hello, *digest); auto const bob_key = bob->session_key(*alice_hello, *digest); - if (!alice_key || !bob_key || !crypto::equal(alice_key->bytes(), bob_key->bytes())) { + if (!alice_key || !bob_key || + !crypto::constant_time_equal(alice_key->bytes(), bob_key->bytes())) { std::printf("failed\n"); return 1; } diff --git a/example/p256_key_formats.cpp b/example/p256_key_formats.cpp index 1e6f5a07..96a7fa48 100644 --- a/example/p256_key_formats.cpp +++ b/example/p256_key_formats.cpp @@ -96,7 +96,7 @@ int main() { 0x57, 0x67, 0xb1, 0xd6, 0x93, 0x4e, 0x50, 0xc3, 0xdb, 0x36, 0xe8, 0x9b, 0x12, 0x7b, 0x8a, 0x62, 0x2b, 0x12, 0x0f, 0x67, 0x21, }; - auto const key_pair = p256::keypair::make(scalar); + auto const key_pair = p256::keypair::from_secret(scalar); auto const key = key_pair ? key_pair->public_key() : key_pair.error(); if (!key || !public_key_to_pem(*key) || !key_pair_to_pem(*key_pair)) { std::printf("failed\n"); diff --git a/example/p256_keys.cpp b/example/p256_keys.cpp index 0bc8ce26..727c4134 100644 --- a/example/p256_keys.cpp +++ b/example/p256_keys.cpp @@ -44,7 +44,7 @@ int main() { 0x57, 0x67, 0xb1, 0xd6, 0x93, 0x4e, 0x50, 0xc3, 0xdb, 0x36, 0xe8, 0x9b, 0x12, 0x7b, 0x8a, 0x62, 0x2b, 0x12, 0x0f, 0x67, 0x21, }; - auto const key = p256::keypair::make(scalar); + auto const key = p256::keypair::from_secret(scalar); if (!key) { std::printf("failed\n"); return 1; @@ -61,17 +61,17 @@ int main() { std::printf("public key %02x, then x and y\n", exported[0]); print("x ", std::span(exported).subspan(1, p256::coordinate_size)); print("y ", std::span(exported).subspan(1 + p256::coordinate_size)); - auto const reloaded = p256::keypair::make(kept->bytes()); + auto const reloaded = p256::keypair::from_secret(kept->bytes()); auto const reloaded_public = reloaded ? reloaded->public_key() : reloaded.error(); bool const same = reloaded_public && reloaded_public->uncompressed() == exported; std::printf("reloaded %s\n", same ? "same key" : "FAILED"); // A peer's key arrives as bytes: made once into a public_key, which checks the point. - auto const peer = p256::public_key::make(exported); + auto const peer = p256::public_key::from_bytes(exported); std::printf("peer key %s\n", peer ? "valid" : "refused"); std::array tampered = exported; tampered.back() ^= 0x01U; - auto const forged = p256::public_key::make(tampered); + auto const forged = p256::public_key::from_bytes(tampered); std::string const reason = forged ? std::string() : forged.error().message(); std::printf("tampered %s: %s\n", forged ? "valid" : "refused", reason.c_str()); diff --git a/example/p256_sign.cpp b/example/p256_sign.cpp index 72e7e8ee..96f57425 100644 --- a/example/p256_sign.cpp +++ b/example/p256_sign.cpp @@ -55,7 +55,7 @@ int main() { 0x57, 0x67, 0xb1, 0xd6, 0x93, 0x4e, 0x50, 0xc3, 0xdb, 0x36, 0xe8, 0x9b, 0x12, 0x7b, 0x8a, 0x62, 0x2b, 0x12, 0x0f, 0x67, 0x21, }; - auto const key = p256::keypair::make(scalar); + auto const key = p256::keypair::from_secret(scalar); auto const public_key = key ? key->public_key() : key.error(); if (!public_key) { std::printf("failed\n"); @@ -70,7 +70,7 @@ int main() { std::printf("failed\n"); return 1; } - print("signature ", *signature); + print("signature ", signature->bytes()); // Always low S: the RFC's own S is high, and sign gives n - s. std::printf("low S %s\n", p256::is_low_s(*signature) ? "yes" : "no"); diff --git a/example/recover_signer.cpp b/example/recover_signer.cpp index 938ba40d..5d106797 100644 --- a/example/recover_signer.cpp +++ b/example/recover_signer.cpp @@ -55,7 +55,7 @@ boost::system::result generate_key() { if (!filled) { return filled.error(); } - auto key = secp256k1::keypair::make(secret); + auto key = secp256k1::keypair::from_secret(secret); if (key || key.error() != crypto::error::invalid_secret_key) { // The key pair keeps its own copy, which it wipes; this one goes now. wipe(std::as_writable_bytes(std::span(secret))); @@ -83,7 +83,7 @@ int main() { // tag::recover[] // The reader holds no key of the wallet's: it makes the published key once, recovers the // signer's key from the 65-byte signature and the message, and compares the two. - auto const expected = secp256k1::public_key::make(published); + auto const expected = secp256k1::public_key::from_bytes(published); auto const signer = secp256k1::recover(crypto::ecdsa_sha256_recoverable, *signature, bytes_of(message)); if (!expected || !signer || *signer != *expected) { diff --git a/example/schnorr_sign.cpp b/example/schnorr_sign.cpp index 49172eb0..0d09b80d 100644 --- a/example/schnorr_sign.cpp +++ b/example/schnorr_sign.cpp @@ -55,7 +55,7 @@ bool sign_and_verify(secp256k1::keypair const& key, std::spanxonly()); - print("signature ", *signature); + print("signature ", signature->bytes()); return crypto::verify(crypto::schnorr, *signature, message, *public_key).has_value(); } @@ -67,7 +67,7 @@ int main() { std::array secret{}; secret.back() = 3; std::array const message{}; - auto key = secp256k1::keypair::make(secret); + auto key = secp256k1::keypair::from_secret(secret); wipe(std::as_writable_bytes(std::span(secret))); if (!key || !sign_and_verify(*key, message)) { return 1; diff --git a/example/sealed_records.cpp b/example/sealed_records.cpp index 83c51311..f2b9aec1 100644 --- a/example/sealed_records.cpp +++ b/example/sealed_records.cpp @@ -6,9 +6,9 @@ // Seals data in pieces two ways: one message in chunks with the incremental seal, and a stream // as separate records, each bound to its position and to whether it is the last. The number in -// the additional data stops records from being reordered or replayed at another position, and +// the associated data stops records from being reordered or replayed at another position, and // the last-record flag stops a stream from being cut short without being noticed. Each stream has -// a key of its own, drawn when the stream starts: the counter IVs 0, 1, 2 of one stream are safe +// a key of its own, drawn when the stream starts: the counter nonces 0, 1, 2 of one stream are safe // only because no other stream seals under its key. // tag::program[] #include @@ -47,7 +47,7 @@ struct record { std::array tag{}; }; -// The record number, big-endian: the IV's last 8 bytes, and the additional data's first 8. +// The record number, big-endian: the nonce's last 8 bytes, and the associated data's first 8. std::array number_bytes(std::uint64_t number) { std::array out{}; for (std::size_t i = 0; i < out.size(); ++i) { @@ -56,15 +56,15 @@ std::array number_bytes(std::uint64_t number) { return out; } -// A counter IV is safe because no number is ever used twice under one key. +// A counter nonce is safe because no number is ever used twice under one key. std::array counter_iv(std::uint64_t number) { - std::array iv{}; + std::array nonce{}; auto const bytes = number_bytes(number); - std::ranges::copy(bytes, iv.begin() + 4); - return iv; + std::ranges::copy(bytes, nonce.begin() + 4); + return nonce; } -// The additional data of a record: its number, then 1 for the last record of the stream and 0 +// The associated data of a record: its number, then 1 for the last record of the stream and 0 // for every other, so that a stream cut after any record fails to open. std::array record_data(std::uint64_t number, bool last) { std::array out{}; @@ -92,11 +92,11 @@ boost::system::result open_stream(aead_type& aead, std::span key{}; - std::array iv{}; - if (!crypto::random_device().fill(key) || !crypto::random_device().fill(iv)) { + std::array nonce{}; + if (!crypto::random_device().fill(key) || !crypto::random_device().fill(nonce)) { return false; } - auto aead = aead_type::make(key); + auto aead = aead_type::from_key(key); wipe(std::as_writable_bytes(std::span(key))); if (!aead) { return false; @@ -109,7 +109,7 @@ bool incremental() { // tag::incremental[] // The header is authenticated up front, then the buffer is encrypted chunk by chunk in place. - if (!aead->begin_seal(iv, header)) { + if (!aead->begin_seal(nonce, header)) { return false; } std::span const whole(buffer); @@ -125,7 +125,7 @@ bool incremental() { } // The receiver has no need of the chunks: one open does the whole buffer. std::span const tag_bytes(tag->data(), tag->size()); - if (!aead->open(iv, header, buffer, tag_bytes) || buffer != original) { + if (!aead->open(nonce, header, buffer, tag_bytes) || buffer != original) { return false; } std::printf("incremental seal opened whole: 3 chunks\n"); @@ -137,13 +137,13 @@ bool records() { // tag::records[] // The stream's own key, drawn for it alone: every stream numbers its records from 0, so two - // streams under one key would seal record 0 twice with one IV. The receiver gets this key + // streams under one key would seal record 0 twice with one nonce. The receiver gets this key // from the protocol, for example sealed under a long-lived key or agreed with ECDH. std::array key{}; if (!crypto::random_device().fill(key)) { return false; } - auto aead = aead_type::make(key); + auto aead = aead_type::from_key(key); wipe(std::as_writable_bytes(std::span(key))); if (!aead) { return false; diff --git a/example/secp256k1_key_formats.cpp b/example/secp256k1_key_formats.cpp index 4330535b..3f465df9 100644 --- a/example/secp256k1_key_formats.cpp +++ b/example/secp256k1_key_formats.cpp @@ -96,7 +96,7 @@ bool store_and_read(secp256k1::keypair const& key_pair) { int main() { std::array secret_key{}; secret_key.fill(0x11); - auto const key_pair = secp256k1::keypair::make(secret_key); + auto const key_pair = secp256k1::keypair::from_secret(secret_key); if (!key_pair || !store_and_read(*key_pair)) { std::printf("failed\n"); return 1; diff --git a/example/signed_message.cpp b/example/signed_message.cpp index 21192d00..0dbb54bc 100644 --- a/example/signed_message.cpp +++ b/example/signed_message.cpp @@ -56,7 +56,7 @@ boost::system::result generate_key() { if (!filled) { return filled.error(); } - auto key = secp256k1::keypair::make(secret); + auto key = secp256k1::keypair::from_secret(secret); // Not every 32 bytes are a key (zero, or too large), which is astronomically rare: // draw again. Any other error is real. if (key || key.error() != crypto::error::invalid_secret_key) { diff --git a/example/signed_update.cpp b/example/signed_update.cpp index 7281e42c..36ebbe9c 100644 --- a/example/signed_update.cpp +++ b/example/signed_update.cpp @@ -51,7 +51,7 @@ boost::system::result generate_key() { if (!filled) { return filled.error(); } - auto key = secp256k1::keypair::make(secret); + auto key = secp256k1::keypair::from_secret(secret); if (key || key.error() != crypto::error::invalid_secret_key) { // The key pair keeps its own copy, which it wipes; this one goes now. wipe(std::as_writable_bytes(std::span(secret))); @@ -80,7 +80,7 @@ int main() { // tag::verify[] // The program makes the key it ships with once, then checks the signature against the bytes // it downloaded, which crypto::verify hashes with SHA-256. - auto const publisher_key = secp256k1::public_key::make(shipped_key); + auto const publisher_key = secp256k1::public_key::from_bytes(shipped_key); if (!publisher_key || !crypto::verify(crypto::ecdsa_sha256, *signature, bytes_of(update), *publisher_key)) { return 1; diff --git a/example/silent_payment.cpp b/example/silent_payment.cpp index 928799d1..fbf9cbe0 100644 --- a/example/silent_payment.cpp +++ b/example/silent_payment.cpp @@ -7,7 +7,7 @@ // A donation page that publishes one reusable address (BIP 352's silent payments): a pair of // public keys, scan and spend. A donor's wallet with one input pays it: the output key it makes // is new, tied to the donor's input. The recipient scans the transaction's outputs with its scan -// key pair, finds the payment, and makes the key pair that spends it with seckey_tweak_add. A +// key pair, finds the payment, and makes the key pair that spends it with secret_key_tweak_add. A // second donation to the same address gives an output key unrelated to the first, so that an // onlooker sees no two payments to one address. The address's encoding, the transaction and the // smallest outpoint's choice are a wallet's (a domain library's); the keys are fixed here, so @@ -61,12 +61,12 @@ bool pay(silent_payments::recipient const& address, secp256k1::keypair const& do int main() { // The donation page: its scan and spend key pairs stay with the recipient; the address is // their two public keys. - auto const scan_pair = secp256k1::keypair::make(repeated(0x51)); + auto const scan_pair = secp256k1::keypair::from_secret(repeated(0x51)); // The spend secret is kept, in a secret<32> that wipes itself, to spend what is found. webcpp::crypto::secret<32> spend_secret; std::ranges::fill(spend_secret.writable(), std::uint8_t{0x52}); - auto const spend_pair = secp256k1::keypair::make(spend_secret.bytes()); - auto const donor = secp256k1::keypair::make(repeated(0x53)); + auto const spend_pair = secp256k1::keypair::from_secret(spend_secret.bytes()); + auto const donor = secp256k1::keypair::from_secret(repeated(0x53)); if (!scan_pair || !spend_pair || !donor) { return 1; } @@ -91,8 +91,8 @@ int main() { std::array const input_keys{*donor_key}; alignas(std::max_align_t) std::array summary_space{}; - auto const summary = - silent_payments::make_prevouts_summary(first_outpoint, {}, input_keys, summary_space); + auto const summary = silent_payments::make_previous_outputs_summary(first_outpoint, {}, + input_keys, summary_space); if (!summary) { return 1; } @@ -108,11 +108,11 @@ int main() { std::printf("the recipient found %zu output\n", *found_count); // The spend secret plus the found tweak is the output's secret key. - auto const output_secret = secp256k1::seckey_tweak_add(spend_secret, found[0].spend_tweak); + auto const output_secret = secp256k1::secret_key_tweak_add(spend_secret, found[0].spend_tweak); if (!output_secret) { return 1; } - auto const spending_pair = secp256k1::keypair::make(output_secret->bytes()); + auto const spending_pair = secp256k1::keypair::from_secret(output_secret->bytes()); if (!spending_pair) { return 1; } diff --git a/example/store_token.cpp b/example/store_token.cpp index 90520a76..ba4c3328 100644 --- a/example/store_token.cpp +++ b/example/store_token.cpp @@ -5,7 +5,7 @@ // https://www.boost.org/LICENSE_1_0.txt) // Stores a user's API token encrypted in a database row, bound to the user's id. The id is -// additional data: authenticated but not encrypted, so a row copied to another user's record +// associated data: authenticated but not encrypted, so a row copied to another user's record // no longer opens. Without that binding a database writer could swap the rows of two users. // tag::program[] #include @@ -35,9 +35,9 @@ void wipe(std::span secret) { } } -// What the database holds: the IV and the tag are not secret, only the key is. +// What the database holds: the nonce and the tag are not secret, only the key is. struct row { - std::array iv{}; + std::array nonce{}; std::vector ciphertext; std::array tag{}; }; @@ -57,7 +57,7 @@ int main() { if (!device.fill(storage_key)) { return 1; } - auto aead = aead_type::make(storage_key); + auto aead = aead_type::from_key(storage_key); // The object keeps its own key schedule, which it wipes; this copy goes now. wipe(std::as_writable_bytes(std::span(storage_key))); if (!aead) { @@ -67,12 +67,12 @@ int main() { // tag::seal[] std::string_view const token = "api-token-0123456789"; row stored; - // A fresh IV for every row: reusing one under the same key breaks GCM. - if (!device.fill(stored.iv)) { + // A fresh nonce for every row: reusing one under the same key breaks GCM. + if (!device.fill(stored.nonce)) { return 1; } stored.ciphertext.assign(token.begin(), token.end()); - auto const tag = aead->seal(stored.iv, bytes_of("user-42"), stored.ciphertext); + auto const tag = aead->seal(stored.nonce, bytes_of("user-42"), stored.ciphertext); if (!tag) { return 1; } @@ -82,7 +82,7 @@ int main() { // tag::open[] // Reading the row back: the id comes from the session, not from the row. auto plain = stored.ciphertext; - if (!aead->open(stored.iv, bytes_of("user-42"), plain, stored.tag)) { + if (!aead->open(stored.nonce, bytes_of("user-42"), plain, stored.tag)) { return 1; } std::printf("opened for user-42: %.*s\n", static_cast(plain.size()), @@ -93,7 +93,7 @@ int main() { // The same row copied to user 43's record does not open. plain = stored.ciphertext; - auto const stolen = aead->open(stored.iv, bytes_of("user-43"), plain, stored.tag); + auto const stolen = aead->open(stored.nonce, bytes_of("user-43"), plain, stored.tag); if (stolen || stolen.error() != crypto::error::authentication_failed) { return 1; } diff --git a/example/taproot_tweak.cpp b/example/taproot_tweak.cpp index 73e04847..d0086a50 100644 --- a/example/taproot_tweak.cpp +++ b/example/taproot_tweak.cpp @@ -8,8 +8,8 @@ // tweak is a tagged hash of the internal key, and the output key commits to it. The same tweak // applied to the key pair lets the owner sign for the output key, so spending needs no script. // tag::program[] +#include #include -#include #include #include @@ -68,7 +68,7 @@ int main() { // random_device. std::array secret{}; secret.back() = 0x03; - auto key = secp256k1::keypair::make(secret); + auto key = secp256k1::keypair::from_secret(secret); wipe(std::as_writable_bytes(std::span(secret))); if (!key) { return 1; @@ -96,7 +96,7 @@ int main() { return 1; } auto const tweaked_public = key->public_key(); - if (!tweaked_public || !crypto::equal(tweaked_public->xonly(), output->key)) { + if (!tweaked_public || !crypto::constant_time_equal(tweaked_public->xonly(), output->key)) { return 1; } std::printf("key pair tweaked: same output key\n"); diff --git a/example/wallet_key.cpp b/example/wallet_key.cpp index fc451da9..4ca19cf6 100644 --- a/example/wallet_key.cpp +++ b/example/wallet_key.cpp @@ -9,8 +9,8 @@ // the first thing an attacker looks for, so the copies are wiped as soon as they are not needed. // tag::program[] #include +#include #include -#include #include #include @@ -54,7 +54,7 @@ int main() { if (!device.fill(secret)) { return 1; } - wallet = secp256k1::keypair::make(secret); + wallet = secp256k1::keypair::from_secret(secret); // A secret that is zero or too large is refused: draw again. Other errors are real. if (wallet) { break; @@ -83,11 +83,11 @@ int main() { // tag::seal[] // The device key is separate from the wallet and lives elsewhere, such as the OS keystore. std::array device_key{}; - std::array iv{}; - if (!device.fill(device_key) || !device.fill(iv)) { + std::array nonce{}; + if (!device.fill(device_key) || !device.fill(nonce)) { return 1; } - auto aead = crypto::ciphers::aes256_gcm::make(device_key); + auto aead = crypto::ciphers::aes256_gcm::from_key(device_key); wipe(std::as_writable_bytes(std::span(device_key))); if (!aead) { return 1; @@ -95,17 +95,17 @@ int main() { auto stored = secret; wipe(std::as_writable_bytes(std::span(secret))); // "wallet v1" ties the ciphertext to its purpose and format version. - auto const tag = aead->seal(iv, bytes_of("wallet v1"), stored); + auto const tag = aead->seal(nonce, bytes_of("wallet v1"), stored); if (!tag) { return 1; } // Later: open the stored secret and make the key pair again. - if (!aead->open(iv, bytes_of("wallet v1"), stored, + if (!aead->open(nonce, bytes_of("wallet v1"), stored, std::span(tag->data(), tag->size()))) { return 1; } - auto restored = secp256k1::keypair::make(stored); + auto restored = secp256k1::keypair::from_secret(stored); wipe(std::as_writable_bytes(std::span(stored))); if (!restored) { return 1; diff --git a/example/x25519_agree.cpp b/example/x25519_agree.cpp index 54c16779..3ec099d4 100644 --- a/example/x25519_agree.cpp +++ b/example/x25519_agree.cpp @@ -4,13 +4,14 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// Alice and Bob of RFC 7748 section 6.1 agree a shared secret from each other's public keys; -// then two Ed25519 key pairs, made from RFC 8032's seeds, agree one through their X25519 forms; -// and a peer key of low order is refused. Prints each public key and the shared secrets in hex. +// Alice and Bob of RFC 7748 section 6.1, each an X25519 key pair made from a secret key, agree a +// shared secret from each other's public keys; then two Ed25519 key pairs, made from RFC 8032's +// seeds, agree one through their X25519 forms; and a peer key of low order is refused. Prints +// each public key and the shared secrets in hex. // tag::program[] +#include #include #include -#include #include #include @@ -33,7 +34,7 @@ void print(char const* name, std::span bytes) { std::printf("\n"); } -// X25519: each side sends its public key and keeps its secret key. +// X25519: each side sends its public key and keeps its key pair. bool alice_and_bob() { // RFC 7748 section 6.1's secret keys: published, never real keys; a program draws its own // 32 bytes with random_device. @@ -47,22 +48,27 @@ bool alice_and_bob() { 0x8b, 0x83, 0x80, 0x0e, 0xe6, 0x6f, 0x3b, 0xb1, 0x29, 0x26, 0x18, 0xb6, 0xfd, 0x1c, 0x2f, 0x8b, 0x27, 0xff, 0x88, 0xe0, 0xeb, }; - auto const alice_public = x25519::public_key(alice_secret); - auto const bob_public = x25519::public_key(bob_secret); + auto const alice = x25519::keypair::from_secret(alice_secret); + auto const bob = x25519::keypair::from_secret(bob_secret); + if (!alice || !bob) { + return false; + } + auto const alice_public = alice->public_key(); + auto const bob_public = bob->public_key(); if (!alice_public || !bob_public) { return false; } - print("alice public", *alice_public); - print("bob public ", *bob_public); - auto const alice_shared = x25519::agree(alice_secret, *bob_public); - auto const bob_shared = x25519::agree(bob_secret, *alice_public); + print("alice public", alice_public->bytes()); + print("bob public ", bob_public->bytes()); + auto const alice_shared = alice->agree(*bob_public); + auto const bob_shared = bob->agree(*alice_public); if (!alice_shared || !bob_shared) { return false; } // Printed here only because RFC 7748 publishes it; a program never prints a shared secret, // and derives its keys from it with a KDF. print("shared ", alice_shared->bytes()); - return crypto::equal(alice_shared->bytes(), bob_shared->bytes()); + return crypto::constant_time_equal(alice_shared->bytes(), bob_shared->bytes()); } // The same agreement from Ed25519 key pairs: one seed for signatures and key agreement. @@ -77,36 +83,43 @@ bool from_ed25519() { 0x46, 0xec, 0x11, 0x4e, 0x0f, 0x5b, 0x8a, 0x31, 0x9f, 0x35, 0xab, 0xa6, 0x24, 0xda, 0x8c, 0xf6, 0xed, 0x4f, 0xb8, 0xa6, 0xfb, }; - auto const first = ed25519::keypair::make(first_seed); - auto const second = ed25519::keypair::make(second_seed); + auto const first = ed25519::keypair::from_secret(first_seed); + auto const second = ed25519::keypair::from_secret(second_seed); if (!first || !second) { return false; } - auto const first_secret = first->x25519_secret(); - auto const second_secret = second->x25519_secret(); + // Each side converts its own key pair to X25519's. + auto const first_x25519 = first->to_x25519(); + auto const second_x25519 = second->to_x25519(); auto const first_signing = first->public_key(); auto const second_signing = second->public_key(); - if (!first_secret || !second_secret || !first_signing || !second_signing) { + if (!first_x25519 || !second_x25519 || !first_signing || !second_signing) { return false; } // Each side knows the other by its Ed25519 public key, and converts it. - auto const first_peer = ed25519::to_x25519_public(*second_signing); - auto const second_peer = ed25519::to_x25519_public(*first_signing); + auto const first_peer = second_signing->to_x25519(); + auto const second_peer = first_signing->to_x25519(); if (!first_peer || !second_peer) { return false; } - print("converted ", *second_peer); - auto const first_shared = x25519::agree(first_secret->bytes(), *first_peer); - auto const second_shared = x25519::agree(second_secret->bytes(), *second_peer); + print("converted ", second_peer->bytes()); + auto const first_shared = first_x25519->agree(*first_peer); + auto const second_shared = second_x25519->agree(*second_peer); return first_shared && second_shared && - crypto::equal(first_shared->bytes(), second_shared->bytes()); + crypto::constant_time_equal(first_shared->bytes(), second_shared->bytes()); } // A peer key of low order gives an all-zero secret, which agree refuses. bool low_order_refused() { std::array const secret_key{1}; std::array const zero_point{}; - auto const shared = x25519::agree(secret_key, zero_point); + auto const key = x25519::keypair::from_secret(secret_key); + // Made, since its size is right: agree judges the point. + auto const peer = x25519::public_key::from_bytes(zero_point); + if (!key || !peer) { + return false; + } + auto const shared = key->agree(*peer); if (!shared && shared.error() == crypto::error::weak_public_key) { std::printf("low order refused: weak_public_key\n"); return true; diff --git a/example/xchacha_seal.cpp b/example/xchacha_seal.cpp index fb879209..21c59200 100644 --- a/example/xchacha_seal.cpp +++ b/example/xchacha_seal.cpp @@ -6,7 +6,7 @@ // A chat app, in the browser and natively alike, encrypts each message of a conversation under // the conversation's key with XChaCha20-Poly1305, a fresh 24-byte nonce drawn at random per -// message and the conversation's id as additional data; a message changed on the way, or moved +// message and the conversation's id as associated data; a message changed on the way, or moved // to another conversation, does not open. Prints what the recipient reads. // tag::program[] #include @@ -29,7 +29,7 @@ namespace { // A message as it travels: the nonce, the tag and the ciphertext, all public. struct sealed_message { - std::array nonce{}; + std::array nonce{}; xchacha::result_type tag{}; std::vector ciphertext; }; @@ -77,7 +77,7 @@ int main() { if (!device.fill(key.writable())) { return 1; } - auto cipher = xchacha::make(key.bytes()); + auto cipher = xchacha::from_key(key.bytes()); if (!cipher) { return 1; } diff --git a/include/webcpp/crypto.hpp b/include/webcpp/crypto.hpp index 1b2b79b8..dbdb306e 100644 --- a/include/webcpp/crypto.hpp +++ b/include/webcpp/crypto.hpp @@ -9,10 +9,10 @@ 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`, `ciphers/secretbox.hpp` and `pem.hpp`, whose - AEADs and PEM name libsodium, and `curves/p256.hpp` with its key formats, whose key pairs name - BearSSL: a program that does not link the default names another in the type, as - `ciphers::gcm>` on WebAssembly or + block cipher's, `ciphers/chacha20_poly1305.hpp`, `secret_key_encryption/secretbox.hpp` and + `pem.hpp`, whose AEADs, secret boxes and PEM name libsodium, and `curves/p256.hpp` with its key + formats, whose key pairs name BearSSL: a program that does not link the default names another in + the type, as `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. @@ -30,16 +30,19 @@ #include #include #include -#include +#include #include #include -#include +#include #include +#include #include -#include #include #include // lint-world: the system's entropy, a purpose of crypto #include +#include +#include +#include #include #include @@ -60,9 +63,9 @@ #include #include #include -#include -#include -#include +#include +#include +#include #endif #ifdef WEBCPP_CRYPTO_HAS_SECP256K1 diff --git a/include/webcpp/crypto/async.hpp b/include/webcpp/crypto/async.hpp index f857c085..1887f759 100644 --- a/include/webcpp/crypto/async.hpp +++ b/include/webcpp/crypto/async.hpp @@ -10,31 +10,44 @@ `async_initiate`, so that one call works with a callback, `use_awaitable`, Cobalt's `use_op`, `deferred`, `as_tuple`, `use_future` and every other completion token. An operation that returns a value completes with `void(boost::system::error_code, T)`, the value second, and on an error - the empty object a move leaves (a `secret` or an array of zeros, a `gcm` or a key pair without - a key, whose every member refuses with `invalid_state`); one without a value completes with - `void(boost::system::error_code)`. + the empty object a move leaves (a `secret`, a signature or an array of zeros, a `gcm` or a key + pair without a key, whose every member refuses with `invalid_state`); one without a value completes + with `void(boost::system::error_code)`. - - The cheap functions exist on every target, for the algorithms the browser's WebCrypto has. - Each takes the executor its completion is posted to first. On a synchronous backend, their + - The cheap functions exist on every target, for the algorithms the browser's WebCrypto has, + and, on a native backend, for every AEAD and box (design D6). Each takes the executor its + completion is posted to first. On a synchronous backend, their default, they run the synchronous call when the operation is initiated (its guards and its work, on the thread that initiates it: the caller's for a callback or `use_awaitable`, the one that launches the operation for `deferred`) and complete through a post to that executor, whence the completion reaches the handler's associated executor, never inside the initiating call. - - AES-GCM: `async_make`, `async_seal` and `async_open`, over `ciphers::gcm`. The other AEADs - (ChaCha20-Poly1305 and its forms, the secret boxes) are not in WebCrypto: call their `seal`. - - Ed25519: `async_make` (a key pair from its seed), `async_generate`, + - AES-GCM: `async_from_key`, `secret_key_encryption::aead::async_seal` and `async_open`, over + `ciphers::gcm`, on every backend, the browser's included. + - The AEADs and boxes WebCrypto lacks, on a native backend: `async_from_key`, + `secret_key_encryption::aead::async_seal` and `async_open` for ChaCha20-Poly1305 and its + forms; `async_from_key` for a secret box, and the box forms + `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. + - Ed25519: `async_from_secret` (a key pair from its seed), `async_generate`, `async_sign(executor, key_pair, crypto::eddsa, message, token)` and `async_verify(executor, crypto::eddsa, signature, message, public_key[, policy], token)`, over `curves::ed25519::basic_keypair::sign` and `crypto::verify`, with their inputs: the - message itself, never a digest, and the typed `curves::ed25519::public_key`. A key pair of + message itself, never a digest, the typed `curves::ed25519::signature` and the typed + `curves::ed25519::public_key`. Under `crypto::eddsa_prehashed` (Ed25519ph), the same + functions take `crypto::prehashed{digest}`, the message's SHA-512, on a native backend + alone: WebCrypto has no Ed25519ph, and the browser's backend stops the build. A key pair of an algorithm WebCrypto lacks (secp256k1) is not here: call its own `sign`. - - X25519: `async_agree`, over `curves::x25519::agree`. - - P-256: `async_make` (a key pair from its secret scalar), `async_generate`, + - X25519: `async_from_secret` (a key pair from its secret key), `async_generate` and + `async_agree(executor, key_pair, peer_public_key, token)`, over + `curves::x25519::basic_keypair::agree`, the peer's key a `curves::x25519::public_key`. + - P-256: `async_from_secret` (a key pair from its secret scalar), `async_generate`, `async_sign(executor, key_pair, crypto::ecdsa_sha256, input, token)` and `async_verify(executor, crypto::ecdsa_sha256, signature, input, public_key, token)`, ECDSA - over `curves::p256::basic_keypair::sign` and `crypto::verify`, with their inputs: the message, - hashed with SHA-256, as WebCrypto's ECDSA with SHA-256 hashes it, or + over `curves::p256::basic_keypair::sign` and `crypto::verify`, with their inputs: the typed + `curves::p256::ecdsa_signature`, and the message, hashed with SHA-256, as WebCrypto's ECDSA + with SHA-256 hashes it, or `crypto::prehashed{digest}` (which the browser's backend, with no prehash mode, will refuse at compile time); and `async_agree`, ECDH's raw x coordinate (WebCrypto's `deriveBits`), over `curves::p256::basic_keypair::agree`. @@ -44,14 +57,16 @@ cancellation rules (`detail/heavy.hpp`). They exist only where the build has threads (`WEBCPP_CRYPTO_HAS_THREADS`); elsewhere each name refuses at compile time. - Each cheap function has its member form (design D9): `K::async_make(executor, bytes, token)`, - `K::async_generate(executor, token)`, `key_pair.async_sign(executor, scheme, input, token)`, - `key_pair.async_agree(executor, peer, token)` (P-256), `public_key.async_verify(executor, scheme, - signature, input[, policy], token)` and AES-GCM'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. X25519's `async_agree` has no - member: X25519 has no key pair class. + Each cheap function has its member form (design D9): + `K::async_from_secret(executor, secret_bytes, token)`, + `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, signature, input[, policy], 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. 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 @@ -72,15 +87,15 @@ // A coroutine makes a key and seals in place on the default backend; each completion, the error // code and the value, is posted to the coroutine's executor. asio::awaitable seal_message(std::span key, - std::span iv, - std::span additional_data, + std::span nonce, + std::span associated_data, std::span data) { auto const executor = co_await asio::this_coro::executor; auto [made_code, aead] = - co_await crypto::async_make(executor, key, asio::as_tuple(asio::use_awaitable)); + co_await crypto::async_from_key(executor, key, asio::as_tuple(asio::use_awaitable)); if (made_code) { co_return; } - auto [code, tag] = co_await crypto::async_seal(executor, aead, iv, additional_data, data, - asio::as_tuple(asio::use_awaitable)); + auto [code, tag] = co_await crypto::secret_key_encryption::aead::async_seal( + executor, aead, nonce, associated_data, data, asio::as_tuple(asio::use_awaitable)); // `data` holds the ciphertext and `tag` the tag when `code` is clear. } @endcode @@ -92,6 +107,7 @@ #include +#include #include #include #include @@ -100,7 +116,12 @@ #include #include #include +#include +#include #include +#include +#include +#include #include #include @@ -111,6 +132,7 @@ #include #include +#include #include #include #include @@ -130,23 +152,25 @@ namespace detail { * first, the function's other arguments as the public function takes them, the completion token * last, forwarded (`std::forward(token)`); the function's explicit template * arguments, other than the backend, go to a member template of the same name: - * - `make(executor, key_bytes, token)`: AES-GCM or a key pair from its bytes; + * - `from_secret(executor, secret_bytes, token)`: a key pair from its secret bytes; + * - `from_key(executor, key_bytes, token)`: AES-GCM from its key; * - `generate(executor, token)`; - * - `seal(executor, aead, iv_bytes, additional_data_bytes, data_bytes, token)` and - * `open(executor, aead, iv_bytes, additional_data_bytes, data_bytes, tag_bytes, token)`; + * - `seal(executor, aead, nonce_bytes, associated_data_bytes, data_bytes, token)` and + * `open(executor, aead, nonce_bytes, associated_data_bytes, data_bytes, tag_bytes, token)`, + * for AES-GCM, the one AEAD WebCrypto has: every other AEAD and box refuses a backend that + * completes by itself before it names this struct (design D6); * - `sign(executor, key_pair, scheme, input, token)`: the scheme tag (`eddsa_t` for Ed25519, * `ecdsa_sha256_t` for P-256) and the message itself, as `std::span`, * which for P-256 the engine hashes with SHA-256, as WebCrypto's ECDSA does (a marker never * reaches it: `can_sign` refuses one on a backend that completes by itself); * - `verify(executor, scheme, signature, input, public_key, policy, token)` for Ed25519, its - * signature and its message spans, its key `curves::ed25519::public_key`, by value, and its - * policy `curves::ed25519::strict_t`, and - * `verify(executor, scheme, signature, input, public_key, token)` for P-256, its key P-256's - * `basic_public_key`, the signature a span of any size and the message itself, as - * `std::span`, which the engine hashes with SHA-256; - * - `agree(executor, secret_key, peer_public_key, token)` for X25519, and - * `agree(executor, key_pair, peer_public_key, token)` for P-256, its key pair and its peer's - * key P-256's types. + * signature `curves::ed25519::signature`, its message span, its key + * `curves::ed25519::public_key`, by value, and its policy `curves::ed25519::strict_t`, and + * `verify(executor, scheme, signature, input, public_key, token)` for P-256, its signature + * `curves::p256::ecdsa_signature`, by value, its key P-256's `basic_public_key` and the message + * itself, as `std::span`, which the engine hashes with SHA-256; + * - `agree(executor, key_pair, peer_public_key, token)` for X25519 and for P-256, its key pair + * and its peer's key the curve's types. * A signature's input reaches the engine as a view, by value (`detail::kept_input`), never as a * reference to the caller's argument, which may be a temporary that a `deferred` operation * outlives; the engine keeps by reference only the objects the public function takes by reference @@ -164,71 +188,78 @@ struct async_engine; /** * The initiation of a cheap function on a synchronous backend: runs the synchronous call (its * guards first) when the operation is initiated and posts the completion, its result split by @ref - * completion_of, to `executor`, whence it reaches the handler's associated executor; the post's - * storage is the handler's associated allocator's. + * completion_of, to `completion_executor`, whence it reaches the handler's associated executor; the + * post's storage is the handler's associated allocator's. */ struct post_initiation { /** - * Runs `operation` and posts `handler` with its error code and, for a call that returns a - * value, the value, or on an error the empty one (ruling R-A3). + * Runs `bound_call` and posts `completion_handler` with its error code and, for a call that + * returns a value, the value, or on an error the empty one (ruling R-A3). * - * @param handler The completion handler. - * @param executor The executor the completion is posted to. - * @param operation The synchronous call, bound to its arguments. + * @param completion_handler The completion handler. + * @param completion_executor The executor the completion is posted to. + * @param bound_call The synchronous call, bound to its arguments. */ template - void operator()(Handler&& handler, Executor const& executor, Operation operation) const { - deliver(std::forward(handler), executor, operation()); + void operator()(Handler&& completion_handler, Executor const& completion_executor, + Operation bound_call) const { + deliver(std::forward(completion_handler), completion_executor, bound_call()); } private: // A call without a value completes with its error code alone. template - static void deliver(Handler&& handler, Executor const& executor, - boost::system::result const& done) { - boost::system::error_code const code = done ? boost::system::error_code{} : done.error(); - webcpp::asio::post(executor, webcpp::asio::append(std::forward(handler), code)); + static void deliver(Handler&& completion_handler, Executor const& completion_executor, + boost::system::result const& call_result) { + boost::system::error_code const completion_code = + call_result ? boost::system::error_code{} : call_result.error(); + webcpp::asio::post( + completion_executor, + webcpp::asio::append(std::forward(completion_handler), completion_code)); } // A call with a value completes with it, or on an error with the empty one. template requires(!std::is_void_v) - static void deliver(Handler&& handler, Executor const& executor, - boost::system::result&& done) { - if (done) { - webcpp::asio::post(executor, - webcpp::asio::append(std::forward(handler), - boost::system::error_code{}, *std::move(done))); + static void deliver(Handler&& completion_handler, Executor const& completion_executor, + boost::system::result&& call_result) { + if (call_result) { + webcpp::asio::post( + completion_executor, + webcpp::asio::append(std::forward(completion_handler), + boost::system::error_code{}, *std::move(call_result))); } else { - webcpp::asio::post(executor, - webcpp::asio::append(std::forward(handler), done.error(), - async_access::empty())); + webcpp::asio::post( + completion_executor, + webcpp::asio::append(std::forward(completion_handler), call_result.error(), + async_access::empty())); } } }; /** - * Initiates a cheap function on a synchronous backend (design D23): runs `operation()` when the + * Initiates a cheap function on a synchronous backend (design D23): runs `bound_call()` when the * operation is initiated (on the initiating thread; for `deferred`, when the deferred operation - * is launched), and completes through a post to `executor`, never inside the call, - * with `operation()`'s result split into its error code and its value. + * is launched), and completes through a post to `completion_executor`, never inside the call, + * with `bound_call()`'s result split into its error code and its value. * * @tparam CompletionToken Any completion token, of signature `completion_of::type`, `R` - * `operation()`'s result. - * @param executor The executor the completion is posted to, whence it reaches the handler's - * associated executor. - * @param token The completion token. - * @param operation The synchronous call, bound to its arguments: a `noexcept` call without + * `bound_call()`'s result. + * @param completion_executor The executor the completion is posted to, whence it reaches the + * handler's associated executor. + * @param completion_token The completion token. + * @param bound_call The synchronous call, bound to its arguments: a `noexcept` call without * arguments returning `boost::system::result` or `boost::system::result`, called once. * @return What the completion token's `async_result` gives. */ template -auto complete_by_post(Executor const& executor, CompletionToken& token, Operation operation) { +auto complete_by_post(Executor const& completion_executor, CompletionToken& completion_token, + Operation bound_call) { static_assert(std::is_nothrow_invocable_v, "webcpp::crypto: an asynchronous operation's call reports its errors as values"); using signature = completion_of>::type; return webcpp::asio_backend::async_initiate( - post_initiation{}, token, executor, std::move(operation)); + post_initiation{}, completion_token, completion_executor, std::move(bound_call)); } /** Whether `Type` is an AES-GCM, `ciphers::gcm`. */ @@ -238,6 +269,28 @@ inline constexpr bool is_gcm_v = false; template inline constexpr bool is_gcm_v> = true; +/** Whether `Type` is a secret box, `secret_key_encryption::basic_secretbox`. */ +template +inline constexpr bool is_secretbox_v = false; + +template +inline constexpr bool is_secretbox_v> = + true; + +/** + * Whether the asynchronous forms of an AEAD or a box refuse it (design D6, ruling P12): its + * backend completes by itself, as the browser's does, and it is not AES-GCM, the one AEAD + * WebCrypto has. + * + * @tparam Type A `secret_key_encryption::aead::cipher` or a + * `secret_key_encryption::authenticated_box`, its qualifiers and reference ignored (a const + * `gcm` is AES-GCM). + */ +template +inline constexpr bool refuses_async_aead_v = + !is_gcm_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; @@ -252,10 +305,17 @@ inline constexpr bool is_p256_keypair_v = false; template inline constexpr bool is_p256_keypair_v> = true; -/** Whether `Type` is a key pair of an algorithm WebCrypto has: Ed25519's or P-256's. */ +/** Whether `Type` is an X25519 key pair, `curves::x25519::basic_keypair`. */ +template +inline constexpr bool is_x25519_keypair_v = false; + +template +inline constexpr bool is_x25519_keypair_v> = true; + +/** Whether `Type` is a key pair of an algorithm WebCrypto has: Ed25519's, X25519's or P-256's. */ template inline constexpr bool is_webcrypto_keypair_v = - is_ed25519_keypair_v || is_p256_keypair_v; + is_ed25519_keypair_v || is_x25519_keypair_v || is_p256_keypair_v; /** Whether `Type` is a P-256 public key, `curves::p256::basic_public_key`. */ template @@ -265,16 +325,17 @@ template inline constexpr bool is_p256_public_key_v> = true; /** - * Whether an `async_verify` of `Scheme` against the public key `Key` exists: `eddsa_t` against - * an Ed25519 public key, `ecdsa_sha256_t` against a P-256 public key; the catch-all - * `async_verify` steps aside where it is true. + * Whether an `async_verify` of `Scheme` against the public key `Key` exists: `eddsa_t` and + * `eddsa_prehashed_t` against an Ed25519 public key, `ecdsa_sha256_t` against a P-256 public key; + * the catch-all `async_verify` steps aside where it is true. * * @tparam Scheme A scheme tag. * @tparam Key The public key's type, without its reference and qualifiers. */ template inline constexpr bool has_async_verifier_v = - (std::is_same_v && std::is_same_v) || + ((std::is_same_v || std::is_same_v) && + std::is_same_v) || (std::is_same_v && is_p256_public_key_v); /** @@ -291,13 +352,71 @@ constexpr void refuse_async_sign() noexcept { if constexpr (!signs_with_v) { static_assert(refused_v, "webcpp::crypto: async_sign: this key pair does not sign with this scheme: " - "an Ed25519 key pair signs with crypto::eddsa, a P-256 key pair with " - "crypto::ecdsa_sha256."); + "an Ed25519 key pair signs with crypto::eddsa or crypto::eddsa_prehashed, a " + "P-256 key pair with crypto::ecdsa_sha256."); } else { check_input::type>(); } } +/** + * Stops the build with the one reason `async_sign` does not take `Keypair`: an X25519 key pair, + * which agrees and does not sign, or a key pair of an algorithm WebCrypto lacks (secp256k1), or + * anything that is not a key pair. + * + * @tparam Keypair Any type but an Ed25519 or a P-256 key pair. + */ +template +constexpr void refuse_async_sign_keypair() noexcept { + if constexpr (agreement_keypair && !signing_keypair) { + static_assert(refused_v, + "webcpp::crypto: async_sign: X25519 key pairs agree; they do not sign: sign " + "with an Ed25519 key pair, which to_x25519() converts for agreement."); + } else { + static_assert(refused_v, + "webcpp::crypto: async_sign takes a key pair of an algorithm WebCrypto has " + "(Ed25519, P-256): call the key pair's synchronous signing function for the " + "others."); + } +} + +/** + * Whether `Keypair` agrees with a peer of the type `PublicKey`, as `async_agree` takes them: an + * agreement key pair and a peer of its own `public_key_type`, exactly, so that the operation keeps + * the caller's peer and never a temporary converted from it. + * + * @tparam Keypair A key pair's type, or any type. + * @tparam PublicKey The peer's type. + */ +template +concept agrees_with_peer = + agreement_keypair && std::same_as; + +/** + * Stops the build: `async_agree` was given an agreement key pair of an algorithm WebCrypto lacks + * (secp256k1), whose own synchronous `agree` the program calls instead. + * + * @tparam Keypair An agreement key pair's type other than X25519's and P-256's. + */ +template +constexpr void refuse_async_agree_keypair() noexcept { + static_assert(refused_v, + "webcpp::crypto: async_agree takes a key pair of an algorithm WebCrypto has " + "(X25519, P-256): call the key pair's synchronous agree for the others."); +} + +/** + * Whether `Keypair` is an Ed25519 key pair asked to sign under `eddsa_prehashed` on a backend that + * completes by itself: what every Ed25519ph function refuses first, WebCrypto having no Ed25519ph. + * + * @tparam Keypair Any type. + * @tparam Scheme Any type. + */ +template +inline constexpr bool ed25519ph_on_browser_v = + is_ed25519_keypair_v && std::is_same_v && + asynchronous_backend_v::type>; + /** * A valid input as the operation keeps it until it runs: a message as the view of its bytes, a * marker as itself, a view too. Neither copies the bytes, which are the caller's until the @@ -305,39 +424,65 @@ constexpr void refuse_async_sign() noexcept { * argument list, does not have to outlive the call, which a `deferred` operation launches later. * * @tparam Input A message's type or `prehashed`. - * @param input The message or the marker. + * @param signing_input The message or the marker. * @return The view the operation keeps. */ template -[[nodiscard]] constexpr auto kept_input(Input const& input) noexcept { +[[nodiscard]] constexpr auto kept_input(Input const& signing_input) noexcept { if constexpr (is_prehashed_v) { - return input; + return signing_input; } else { - return message_bytes(input); + return message_bytes(signing_input); } } /** - * The initiation of `async_make` once its guard is held, for the free function and the member: - * the engine of a backend that completes by itself, or `Algorithm::make` run when the operation is - * initiated. + * The initiation of `async_from_secret` once its guard is held, for the free function and the + * member: the engine of a backend that completes by itself, or `Keypair::from_secret` run when the + * operation is initiated. * - * @tparam Algorithm AES-GCM or a key pair of an algorithm WebCrypto has. - * @param executor The executor the completion is posted to. + * @tparam Keypair A key pair of an algorithm WebCrypto has. + * @param completion_executor The executor the completion is posted to. + * @param secret_bytes The key pair's secret bytes. + * @param completion_token The completion token. + * @return What the completion token's `async_result` gives. + */ +template +auto initiate_from_secret(Executor const& completion_executor, + std::span secret_bytes, + CompletionToken&& completion_token) { + using backend = Keypair::backend_type; + if constexpr (asynchronous_backend_v) { + return async_engine::template from_secret( + completion_executor, secret_bytes, std::forward(completion_token)); + } else { + return complete_by_post(completion_executor, completion_token, [secret_bytes]() noexcept { + return Keypair::from_secret(secret_bytes); + }); + } +} + +/** + * The initiation of `async_from_key` once its guard is held, for the free function and the + * member: the engine of a backend that completes by itself, or `Cipher::from_key` run when the + * operation is initiated. + * + * @tparam Cipher AES-GCM. + * @param completion_executor The executor the completion is posted to. * @param key_bytes The key's bytes. - * @param token The completion token. + * @param completion_token The completion token. * @return What the completion token's `async_result` gives. */ -template -auto initiate_make(Executor const& executor, std::span key_bytes, - CompletionToken&& token) { - using backend = Algorithm::backend_type; +template +auto initiate_from_key(Executor const& completion_executor, std::span key_bytes, + CompletionToken&& completion_token) { + using backend = Cipher::backend_type; if constexpr (asynchronous_backend_v) { - return async_engine::template make( - executor, key_bytes, std::forward(token)); + return async_engine::template from_key( + completion_executor, key_bytes, std::forward(completion_token)); } else { - return complete_by_post(executor, token, - [key_bytes]() noexcept { return Algorithm::make(key_bytes); }); + return complete_by_post(completion_executor, completion_token, + [key_bytes]() noexcept { return Cipher::from_key(key_bytes); }); } } @@ -347,18 +492,19 @@ auto initiate_make(Executor const& executor, std::span key_b * operation is initiated. * * @tparam Keypair A key pair of an algorithm WebCrypto has. - * @param executor The executor the completion is posted to. - * @param token The completion token. + * @param completion_executor The executor the completion is posted to. + * @param completion_token The completion token. * @return What the completion token's `async_result` gives. */ template -auto initiate_generate(Executor const& executor, CompletionToken&& token) { +auto initiate_generate(Executor const& completion_executor, CompletionToken&& completion_token) { using backend = Keypair::backend_type; if constexpr (asynchronous_backend_v) { return async_engine::template generate( - executor, std::forward(token)); + completion_executor, std::forward(completion_token)); } else { - return complete_by_post(executor, token, []() noexcept { return Keypair::generate(); }); + return complete_by_post(completion_executor, completion_token, + []() noexcept { return Keypair::generate(); }); } } @@ -369,230 +515,424 @@ auto initiate_generate(Executor const& executor, CompletionToken&& token) { * initiated. * * @tparam Keypair An Ed25519 or a P-256 key pair. - * @param executor The executor the completion is posted to. + * @param completion_executor The executor the completion is posted to. * @param key_pair The key pair, the caller's until the completion. - * @param scheme The scheme. - * @param input The message or the marker. - * @param token The completion token. + * @param signing_scheme The scheme. + * @param signing_input The message or the marker. + * @param completion_token The completion token. * @return What the completion token's `async_result` gives. */ template -auto initiate_sign(Executor const& executor, Keypair const& key_pair, Scheme scheme, - Input const& input, CompletionToken&& token) { +auto initiate_sign(Executor const& completion_executor, Keypair const& key_pair, + Scheme signing_scheme, Input const& signing_input, + CompletionToken&& completion_token) { if constexpr (!can_sign) { refuse_async_sign(); } else { using backend = Keypair::backend_type; if constexpr (asynchronous_backend_v) { - return async_engine::sign(executor, key_pair, scheme, kept_input(input), - std::forward(token)); + return async_engine::sign(completion_executor, key_pair, signing_scheme, + kept_input(signing_input), + std::forward(completion_token)); } else { - return complete_by_post(executor, token, - [&key_pair, scheme, kept = kept_input(input)]() noexcept { - return key_pair.sign(scheme, kept); - }); + return complete_by_post( + completion_executor, completion_token, + [&key_pair, signing_scheme, kept = kept_input(signing_input)]() noexcept { + return key_pair.sign(signing_scheme, kept); + }); } } } /** * Ed25519's `async_verify` once its guard is held, for the free functions and the members, with - * and without the policy: the scheme and the input checked as `crypto::can_verify` checks them, - * then the engine of a backend that completes by itself, or the key's `verify` run when the - * operation is initiated. + * and without the policy, under `eddsa` and `eddsa_prehashed`: the scheme, the signature and the + * input checked as `crypto::can_verify` checks them, then the engine of a backend that completes + * by itself (`eddsa` alone: the public functions refuse `eddsa_prehashed` there first), or the + * key's `verify` run when the operation is initiated. * * @tparam Backend The backend. - * @tparam Scheme `eddsa_t`; another scheme stops the build. - * @param executor The executor the completion is posted to. - * @param signature The signature. - * @param message The message. + * @tparam Scheme `eddsa_t` or `eddsa_prehashed_t`; another scheme stops the build. + * @tparam Signature `curves::ed25519::signature`; another type stops the build. + * @param completion_executor The executor the completion is posted to. + * @param signature_value The signature, copied into the operation. + * @param signing_input The message, or under `eddsa_prehashed` the marker of its SHA-512. * @param public_key The public key, copied into the operation. - * @param policy `curves::ed25519::strict`. - * @param token The completion token. + * @param verification_policy `curves::ed25519::strict`. + * @param completion_token The completion token. * @return What the completion token's `async_result` gives. */ -template -auto initiate_verify_ed25519(Executor const& executor, std::span signature, - Input const& message, curves::ed25519::public_key const& public_key, - [[maybe_unused]] curves::ed25519::strict_t policy, - CompletionToken&& token) { - if constexpr (!std::is_same_v) { +template +auto initiate_verify_ed25519(Executor const& completion_executor, Signature const& signature_value, + Input const& signing_input, + curves::ed25519::public_key const& public_key, + [[maybe_unused]] curves::ed25519::strict_t verification_policy, + CompletionToken&& completion_token) { + if constexpr (!std::is_same_v && !std::is_same_v) { static_assert(refused_v, - "webcpp::crypto: an Ed25519 public key verifies crypto::eddsa."); - } else if constexpr (!can_verify) { - check_input(); + "webcpp::crypto: an Ed25519 public key verifies crypto::eddsa or " + "crypto::eddsa_prehashed."); + } else if constexpr (!check_signature()) { + // Never compiled into a program: check_signature stopped the build. + } else if constexpr (!input_valid_v) { + check_input(); } else if constexpr (asynchronous_backend_v) { - return async_engine::verify(executor, eddsa, signature, kept_input(message), - public_key, policy, - std::forward(token)); + return async_engine::verify( + completion_executor, eddsa, signature_value, kept_input(signing_input), public_key, + verification_policy, std::forward(completion_token)); } else { - return complete_by_post(executor, token, - [signature, kept = kept_input(message), public_key]() noexcept { - return public_key.template verify( - eddsa, signature, kept, curves::ed25519::strict); - }); + return complete_by_post( + completion_executor, completion_token, + [signature_value, kept = kept_input(signing_input), public_key]() noexcept { + return public_key.template verify(Scheme{}, signature_value, kept, + curves::ed25519::strict); + }); } } } // namespace detail /** - * Makes an AES-GCM object, an Ed25519 key pair or a P-256 key pair from its key bytes, - * asynchronously: `Algorithm::make(key_bytes)` run when the operation is initiated, its result - * posted to `executor`. + * Makes an Ed25519, an X25519 or a P-256 key pair from its secret bytes, asynchronously: + * `Keypair::from_secret(secret_bytes)` run when the operation is initiated, its result posted to + * `completion_executor`. + * + * The free form of + * `Keypair::async_from_secret(completion_executor, secret_bytes, completion_token)`, which it + * calls. + * + * The secret is read before the call returns on a synchronous backend, later on the browser's: it + * is the caller's until the completion. + * + * @tparam Keypair A `curves::ed25519::basic_keypair`, a + * `curves::x25519::basic_keypair` or a `curves::p256::basic_keypair`, on any + * backend that has it; the other key pairs crypto has are not in WebCrypto: call their + * `from_secret`. + * @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 secret_bytes The seed's `seed_size` bytes for an Ed25519 key pair, the secret key's + * 32 bytes for an X25519 key pair, the secret scalar's `secret_key_size` (32 bytes, big-endian) + * for a P-256 key pair. + * @param completion_token The completion token, of signature + * `void(boost::system::error_code, Keypair)`; on an error the key pair is empty, and every member + * refuses with `invalid_state` (`invalid_key_size`, `invalid_secret_key` for a P-256 scalar 0 or + * not below the group order, `backend_failure`). + * @return What the completion token's `async_result` gives. + */ +template +auto async_from_secret(Executor const& completion_executor, + std::span secret_bytes, + CompletionToken&& completion_token) { + detail::timing_guard const timing_scope; + if constexpr (!detail::is_webcrypto_keypair_v) { + static_assert(detail::refused_v, + "webcpp::crypto: async_from_secret takes a key pair of an algorithm " + "WebCrypto has (Ed25519, X25519, P-256): call the synchronous from_secret " + "for the others."); + } else { + return Keypair::async_from_secret(completion_executor, secret_bytes, + std::forward(completion_token)); + } +} + +/** + * 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`. * - * The free form of `Algorithm::async_make(executor, key_bytes, token)`, which it calls. + * The free form of `Cipher::async_from_key(completion_executor, key_bytes, completion_token)`, + * which it calls. * * 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. + * 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 Algorithm A `ciphers::gcm`, a `curves::ed25519::basic_keypair` or a - * `curves::p256::basic_keypair`, on any backend that has it; the other algorithms crypto - * has are not in WebCrypto: call their `make`. + * @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. * @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 `token` states. - * @param executor The executor the completion is posted to. - * @param key_bytes `Algorithm::key_size` bytes for AES-GCM, the seed's `seed_size` for an - * Ed25519 key pair, the secret scalar's `secret_key_size` (32 bytes, big-endian) for a P-256 key - * pair. - * @param token The completion token, of signature `void(boost::system::error_code, Algorithm)`; - * on an error the object is empty, and every member refuses with `invalid_state` - * (`invalid_key_size`, `invalid_secret_key` for a P-256 scalar 0 or not below the group order, - * `errc::not_enough_memory`, `backend_failure`). + * @tparam CompletionToken Any completion token for the signature `completion_token` states. + * @param completion_executor The executor the completion is posted to. + * @param key_bytes `Cipher::key_size` bytes. + * @param completion_token The completion token, of signature + * `void(boost::system::error_code, Cipher)`; on an error the object is empty, and every member + * refuses with `invalid_state` (`invalid_key_size`, `errc::not_enough_memory`, `backend_failure`). * @return What the completion token's `async_result` gives. */ -template -auto async_make(Executor const& executor, std::span key_bytes, - CompletionToken&& token) { - detail::timing_guard const timing; - if constexpr (!detail::is_gcm_v && !detail::is_webcrypto_keypair_v) { - static_assert(detail::refused_v, - "webcpp::crypto: async_make takes AES-GCM or a key pair of an algorithm " - "WebCrypto has (Ed25519, P-256): call the synchronous make for the others."); +template +auto async_from_key(Executor const& completion_executor, std::span key_bytes, + CompletionToken&& completion_token) { + detail::timing_guard const timing_scope; + if constexpr (!secret_key_encryption::aead::cipher && !detail::is_secretbox_v) { + 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) { + detail::refuse_aead_on_asynchronous_backend< + typename std::remove_cvref_t::backend_type>(); } else { - return Algorithm::async_make(executor, key_bytes, std::forward(token)); + return Cipher::async_from_key(completion_executor, key_bytes, + std::forward(completion_token)); } } /** - * Makes an Ed25519 or a P-256 key pair from a fresh seed or scalar, asynchronously: + * Makes an Ed25519, an X25519 or a P-256 key pair from a fresh secret, asynchronously: * `Keypair::generate()` run when the operation is initiated (the system's generator is drawn from - * then), its result posted to `executor`. + * then), its result posted to `completion_executor`. * - * The free form of `Keypair::async_generate(executor, token)`, which it calls. + * The free form of `Keypair::async_generate(completion_executor, completion_token)`, which it + * calls. * * @tparam Keypair A `curves::ed25519::basic_keypair`, by default the family's - * `curves::ed25519::keypair`, or a `curves::p256::basic_keypair`; the other key pairs - * are not in WebCrypto: call their `generate`. + * `curves::ed25519::keypair`, a `curves::x25519::basic_keypair` or a + * `curves::p256::basic_keypair`; the other key pairs are not in WebCrypto: call their + * `generate`. * @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 `token` states. - * @param executor The executor the completion is posted to. - * @param token The completion token, of signature `void(boost::system::error_code, Keypair)`; - * on an error the key pair is empty, and every member refuses with `invalid_state` - * (`entropy_unavailable`, `backend_failure`). + * @tparam CompletionToken Any completion token for the signature `completion_token` states. + * @param completion_executor The executor the completion is posted to. + * @param completion_token The completion token, of signature + * `void(boost::system::error_code, Keypair)`; on an error the key pair is empty, and every member + * refuses with `invalid_state` (`entropy_unavailable`, `backend_failure`). * @return What the completion token's `async_result` gives. */ template -auto async_generate(Executor const& executor, CompletionToken&& token) { - detail::timing_guard const timing; +auto async_generate(Executor const& completion_executor, CompletionToken&& completion_token) { + detail::timing_guard const timing_scope; if constexpr (!detail::is_webcrypto_keypair_v) { static_assert(detail::refused_v, "webcpp::crypto: async_generate takes a key pair of an algorithm WebCrypto " - "has (Ed25519, P-256): call the synchronous generate for the others."); + "has (Ed25519, X25519, P-256): call the synchronous generate for the " + "others."); } else { - return Keypair::async_generate(executor, std::forward(token)); + return Keypair::async_generate(completion_executor, + std::forward(completion_token)); } } +namespace secret_key_encryption::aead { + /** - * Seals a message in place, asynchronously: `aead.seal` run when the operation is initiated, its - * result posted to `executor`. + * Seals a message in place, asynchronously: `aead_cipher.seal` run when the operation is + * initiated, its result posted to `completion_executor`. * - * The free form of - * `aead.async_seal(executor, iv_bytes, additional_data_bytes, data_bytes, token)`, which it calls. + * The free form of the member `aead_cipher.async_seal`, which it calls with the arguments after + * `aead_cipher`. * - * `aead` and the spans are the caller's until the completion: a synchronous backend reads and - * writes them before the call returns, the browser's later. `data_bytes` holds the ciphertext at - * the completion. A guard's refusal (`invalid_iv_size`, `message_too_long`, `invalid_state`) - * leaves it untouched, a backend's failure zeroes it, as `seal` does. + * `aead_cipher` and the spans are the caller's until the completion: a synchronous backend reads + * and writes them before the call returns, the browser's later. `data_bytes` holds the ciphertext + * at the completion. A guard's refusal (`invalid_nonce_size`, `message_too_long`, `invalid_state`) + * leaves it untouched, a backend's failure zeroes it, as `seal` does. On a backend that completes + * by itself only AES-GCM is offered: any other AEAD stops the build (design D6). * - * @tparam Gcm A `ciphers::gcm`; the other AEADs are not in WebCrypto: call their `seal`. + * @tparam Cipher A `cipher`: AES-GCM, ChaCha20-Poly1305 or one of its forms. * @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 `token` states. - * @param executor The executor the completion is posted to. - * @param aead The keyed object. - * @param iv_bytes 1 to `max_iv_size` bytes, never reused under this key. - * @param additional_data_bytes Authenticated, not encrypted. + * @tparam CompletionToken Any completion token for the signature `completion_token` states. + * @param completion_executor The executor the completion is posted to. + * @param aead_cipher The keyed object. + * @param nonce_bytes The nonce, of a size the AEAD accepts, never reused under this key. + * @param associated_data_bytes Authenticated, not encrypted. * @param data_bytes The message. - * @param token The completion token, of signature - * `void(boost::system::error_code, Gcm::result_type)`: the tag; on an error the zeroed tag. + * @param completion_token The completion token, of signature + * `void(boost::system::error_code, Cipher::result_type)`: the tag; on an error the zeroed tag. * @return What the completion token's `async_result` gives. */ -template -auto async_seal(Executor const& executor, Gcm& aead, std::span iv_bytes, - std::span additional_data_bytes, - std::span data_bytes, CompletionToken&& token) { - detail::timing_guard const timing; - if constexpr (!detail::is_gcm_v>) { - static_assert(detail::refused_v, - "webcpp::crypto: async_seal takes AES-GCM, the AEAD WebCrypto has: call seal " - "for the others."); +template +auto async_seal(Executor const& completion_executor, Cipher& aead_cipher, + std::span nonce_bytes, + std::span associated_data_bytes, + std::span data_bytes, CompletionToken&& completion_token) { + detail::timing_guard const timing_scope; + if constexpr (detail::refuses_async_aead_v) { + detail::refuse_aead_on_asynchronous_backend< + typename std::remove_cvref_t::backend_type>(); } else { - return aead.async_seal(executor, iv_bytes, additional_data_bytes, data_bytes, - std::forward(token)); + return aead_cipher.async_seal(completion_executor, nonce_bytes, associated_data_bytes, + data_bytes, std::forward(completion_token)); } } /** - * Opens a message in place, asynchronously: `aead.open` run when the operation is initiated, its - * result posted to `executor`. + * Opens a message in place, asynchronously: `aead_cipher.open` run when the operation is + * initiated, its result posted to `completion_executor`. * - * The free form of - * `aead.async_open(executor, iv_bytes, additional_data_bytes, data_bytes, tag_bytes, token)`, which - * it calls. + * The free form of the member `aead_cipher.async_open`, which it calls with the arguments after + * `aead_cipher`. * - * `aead` and the spans are the caller's until the completion. `data_bytes` holds the plaintext at - * a successful completion; a wrong tag (`authentication_failed`) or a backend's failure zeroes - * it, a guard's refusal leaves it untouched, as `open` does. + * `aead_cipher` and the spans are the caller's until the completion. `data_bytes` holds the + * plaintext at a successful completion; a wrong tag (`authentication_failed`) or a backend's + * failure zeroes it, a guard's refusal leaves it untouched, as `open` does. On a backend that + * completes by itself only AES-GCM is offered: any other AEAD stops the build (design D6). * - * @tparam Gcm A `ciphers::gcm`; the other AEADs are not in WebCrypto: call their `open`. + * @tparam Cipher A `cipher`: AES-GCM, ChaCha20-Poly1305 or one of its forms. * @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 `token` states. - * @param executor The executor the completion is posted to. - * @param aead The keyed object. - * @param iv_bytes The IV of the seal. - * @param additional_data_bytes The additional data of the seal. + * @tparam CompletionToken Any completion token for the signature `completion_token` states. + * @param completion_executor The executor the completion is posted to. + * @param aead_cipher The keyed object. + * @param nonce_bytes The nonce of the seal. + * @param associated_data_bytes The associated data of the seal. * @param data_bytes The ciphertext. * @param tag_bytes The seal's tag, 16 bytes. - * @param token The completion token, of signature `void(boost::system::error_code)`. + * @param completion_token The completion token, of signature `void(boost::system::error_code)`. * @return What the completion token's `async_result` gives. */ -template -auto async_open(Executor const& executor, Gcm& aead, std::span iv_bytes, - std::span additional_data_bytes, +template +auto async_open(Executor const& completion_executor, Cipher& aead_cipher, + std::span nonce_bytes, + std::span associated_data_bytes, std::span data_bytes, std::span tag_bytes, - CompletionToken&& token) { - detail::timing_guard const timing; - if constexpr (!detail::is_gcm_v>) { - static_assert(detail::refused_v, - "webcpp::crypto: async_open takes AES-GCM, the AEAD WebCrypto has: call open " - "for the others."); + CompletionToken&& completion_token) { + detail::timing_guard const timing_scope; + if constexpr (detail::refuses_async_aead_v) { + detail::refuse_aead_on_asynchronous_backend< + typename std::remove_cvref_t::backend_type>(); } else { - return aead.async_open(executor, iv_bytes, additional_data_bytes, data_bytes, tag_bytes, - std::forward(token)); + return aead_cipher.async_open(completion_executor, nonce_bytes, associated_data_bytes, + data_bytes, tag_bytes, + std::forward(completion_token)); } } /** - * Signs with an Ed25519 or a P-256 key pair, asynchronously: `key_pair.sign(scheme, input)` run - * when the operation is initiated, its result posted to `executor`. + * A box given to the AEAD form of `async_seal`, which takes associated data: refused, naming the + * box form. + * + * Never called: the refusal stops the build where it is instantiated. + * + * @tparam Executor The executor's type. + * @tparam Box An `authenticated_box`, which is no `cipher`. + * @tparam CompletionToken The completion token's type. + * @return Never returns to a program: it does not compile. + */ +template +void async_seal(Executor const& /*completion_executor*/, Box& /*keyed_box*/, + std::span /*nonce_bytes*/, + std::span /*associated_data_bytes*/, + std::span /*data_bytes*/, CompletionToken&& /*completion_token*/) { + static_assert(detail::dependent_false, + "webcpp::crypto: async_seal: a secret box or a crypto_box takes no associated " + "data: secret_key_encryption::async_seal(executor, box, nonce, data, token)."); +} + +/** + * A box given to the AEAD form of `async_open`, which takes associated data: refused, naming the + * box form. + * + * Never called: the refusal stops the build where it is instantiated. + * + * @tparam Executor The executor's type. + * @tparam Box An `authenticated_box`, which is no `cipher`. + * @tparam CompletionToken The completion token's type. + * @return Never returns to a program: it does not compile. + */ +template +void async_open(Executor const& /*completion_executor*/, Box& /*keyed_box*/, + std::span /*nonce_bytes*/, + std::span /*associated_data_bytes*/, + std::span /*data_bytes*/, std::span /*tag_bytes*/, + CompletionToken&& /*completion_token*/) { + static_assert(detail::dependent_false, + "webcpp::crypto: async_open: a secret box or a crypto_box takes no associated " + "data: secret_key_encryption::async_open(executor, box, nonce, data, tag, " + "token)."); +} + +} // namespace secret_key_encryption::aead + +namespace secret_key_encryption { + +/** + * Seals a message in place with a box, asynchronously: `keyed_box.seal` run when the operation is + * initiated, its result posted to `completion_executor`. + * + * The free form of the member `keyed_box.async_seal`, which it calls with the arguments after + * `keyed_box`, for a secret box and a crypto_box alike (design R21). * - * The free form of `key_pair.async_sign(executor, scheme, input, token)`, which it calls. + * `keyed_box` and the spans are the caller's until the completion. `data_bytes` holds the + * ciphertext at the completion; a guard's refusal leaves it untouched, a backend's failure zeroes + * it, as `seal` does. WebCrypto has neither: on a backend that completes by itself the call stops + * the build (design D6). + * + * @tparam Box An `authenticated_box`: a secret box or a crypto_box. + * @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 keyed_box The keyed box. + * @param nonce_bytes The nonce, `Box::nonce_size` bytes, never reused under this key. + * @param data_bytes The message. + * @param completion_token The completion token, of signature + * `void(boost::system::error_code, Box::result_type)`: the tag; on an error the zeroed tag. + * @return What the completion token's `async_result` gives. + */ +template +auto async_seal(Executor const& completion_executor, Box& keyed_box, + std::span nonce_bytes, std::span data_bytes, + CompletionToken&& completion_token) { + detail::timing_guard const timing_scope; + if constexpr (detail::refuses_async_aead_v) { + detail::refuse_aead_on_asynchronous_backend< + typename std::remove_cvref_t::backend_type>(); + } else { + return keyed_box.async_seal(completion_executor, nonce_bytes, data_bytes, + std::forward(completion_token)); + } +} + +/** + * Opens a message in place with a box, asynchronously: `keyed_box.open` run when the operation is + * initiated, its result posted to `completion_executor`. * - * Ed25519 signs the message with `crypto::eddsa`; P-256 signs with `crypto::ecdsa_sha256` the - * message, which it hashes with SHA-256, as WebCrypto's ECDSA with SHA-256 signs, or - * `crypto::prehashed{digest}` (RFC 6979's nonce: the same key and input give the same signature; - * S low). + * The free form of the member `keyed_box.async_open`, which it calls with the arguments after + * `keyed_box`, for a secret box and a crypto_box alike (design R21). + * + * `keyed_box` and the spans are the caller's until the completion. `data_bytes` holds the + * plaintext at a successful completion; a wrong tag (`authentication_failed`) or a backend's + * failure zeroes it, a guard's refusal leaves it untouched, as `open` does. WebCrypto has neither: + * on a backend that completes by itself the call stops the build (design D6). + * + * @tparam Box An `authenticated_box`: a secret box or a crypto_box. + * @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 keyed_box The keyed box. + * @param nonce_bytes The nonce of the seal. + * @param data_bytes The ciphertext. + * @param tag_bytes The seal's tag, `Box::tag_size` bytes. + * @param completion_token The completion token, of signature `void(boost::system::error_code)`. + * @return What the completion token's `async_result` gives. + */ +template +auto async_open(Executor const& completion_executor, Box& keyed_box, + std::span nonce_bytes, std::span data_bytes, + std::span tag_bytes, CompletionToken&& completion_token) { + detail::timing_guard const timing_scope; + if constexpr (detail::refuses_async_aead_v) { + detail::refuse_aead_on_asynchronous_backend< + typename std::remove_cvref_t::backend_type>(); + } else { + return keyed_box.async_open(completion_executor, nonce_bytes, data_bytes, tag_bytes, + std::forward(completion_token)); + } +} + +} // namespace secret_key_encryption + +/** + * 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 + * posted to `completion_executor`. + * + * The free form of the member `key_pair.async_sign`, which it calls with the arguments after + * `key_pair`. + * + * Ed25519 signs the message with `crypto::eddsa`, or with `crypto::eddsa_prehashed` (Ed25519ph) + * `crypto::prehashed{digest}`, the message's 64-byte SHA-512, on a native backend alone (WebCrypto + * has no Ed25519ph: the browser's backend stops the build first); P-256 signs with + * `crypto::ecdsa_sha256` the message, which it hashes with SHA-256, as WebCrypto's ECDSA with + * SHA-256 signs, or `crypto::prehashed{digest}` (RFC 6979's nonce: the same key and input give the + * same signature; S low). * * The key pair, the scheme and the input are checked as `crypto::can_sign` checks them, before * anything else: another pair stops the build with its reason, and so does a marker on a backend @@ -603,68 +943,105 @@ auto async_open(Executor const& executor, Gcm& aead, std::span`; the other key pairs are not in WebCrypto: call the key * pair's own `sign`. * @tparam Executor The executor's type, an Asio executor (an `io_context`'s or a strand's). - * @tparam Scheme `crypto::eddsa_t` for Ed25519, `crypto::ecdsa_sha256_t` for P-256. + * @tparam Scheme `crypto::eddsa_t` or `crypto::eddsa_prehashed_t` for Ed25519, + * `crypto::ecdsa_sha256_t` for P-256. * @tparam Input A message, bytes that convert to `std::span`, of any size, - * empty included, or for P-256 `crypto::prehashed<32>`. - * @tparam CompletionToken Any completion token for the signature `token` states. - * @param executor The executor the completion is posted to. + * empty included, or for P-256 `crypto::prehashed<32>`; under `crypto::eddsa_prehashed`, + * `crypto::prehashed<64>` alone. + * @tparam CompletionToken Any completion token for the signature `completion_token` states. + * @param completion_executor The executor the completion is posted to. * @param key_pair The key pair. - * @param scheme `crypto::eddsa` or `crypto::ecdsa_sha256`. - * @param input The message, or for P-256 `crypto::prehashed{digest}`, its 32-byte SHA-256 digest. - * @param token The completion token, of signature `void(error_code, signature)`, the signature - * a `std::array` of 64 bytes (P-256's r then s, IEEE P1363's form, WebCrypto's); on an error it - * is 64 zeros (`invalid_state`, `backend_failure`). + * @param signing_scheme `crypto::eddsa`, `crypto::eddsa_prehashed` or `crypto::ecdsa_sha256`. + * @param signing_input The message, or for P-256 `crypto::prehashed{digest}`, its 32-byte SHA-256 + * digest, or under `crypto::eddsa_prehashed` `crypto::prehashed{digest}`, its 64-byte SHA-512 + * digest. + * @param completion_token The completion token, of signature `void(error_code, signature)`, the + * signature the key pair's type, `curves::ed25519::signature` or `curves::p256::ecdsa_signature` + * (r then s, IEEE P1363's form, WebCrypto's); on an error the signature of zeros + * (`invalid_state`, `backend_failure`). * @return What the completion token's `async_result` gives. */ template -auto async_sign(Executor const& executor, Keypair const& key_pair, Scheme scheme, - Input const& input, CompletionToken&& token) { - detail::timing_guard const timing; - if constexpr (!detail::is_webcrypto_keypair_v) { - static_assert( - detail::refused_v, - "webcpp::crypto: async_sign takes a key pair of an algorithm WebCrypto has " - "(Ed25519, P-256): call the key pair's synchronous signing function for the others."); + requires signing_keypair +auto async_sign(Executor const& completion_executor, Keypair const& key_pair, Scheme signing_scheme, + Input const& signing_input, CompletionToken&& completion_token) { + detail::timing_guard const timing_scope; + if constexpr (detail::ed25519ph_on_browser_v) { + detail::refuse_ed25519ph_on_asynchronous_backend< + typename detail::key_backend::type>(); + } else if constexpr (!detail::is_ed25519_keypair_v && + !detail::is_p256_keypair_v) { + detail::refuse_async_sign_keypair(); } else { - return key_pair.async_sign(executor, scheme, input, std::forward(token)); + return key_pair.async_sign(completion_executor, signing_scheme, signing_input, + std::forward(completion_token)); } } +/** + * Stops the build: `async_sign` takes a signing key pair (`crypto::signing_keypair`), and the + * second argument is not one: an X25519 key pair, which agrees and does not sign, or anything that + * is not a key pair. + * + * @tparam Keypair The second argument's type. + * @tparam Executor The executor's type. + * @tparam Scheme The scheme's type. + * @tparam Input The input's type. + * @tparam CompletionToken The completion token's type. + * @param completion_executor The executor. + * @param key_pair The second argument. + * @param signing_scheme The scheme. + * @param signing_input The input. + * @param completion_token The completion token. + */ +template + requires(!signing_keypair) +void async_sign([[maybe_unused]] Executor const& completion_executor, + [[maybe_unused]] Keypair const& key_pair, [[maybe_unused]] Scheme signing_scheme, + [[maybe_unused]] Input const& signing_input, + [[maybe_unused]] CompletionToken&& completion_token) { + detail::refuse_async_sign_keypair(); +} + /** * Verifies an Ed25519 signature (RFC 8032's pure Ed25519), asynchronously, strictly: - * `crypto::verify(crypto::eddsa, signature, message, public_key)` run when the operation - * is initiated, its result posted to `executor`. + * `crypto::verify(crypto::eddsa, signature_value, message_bytes, public_key)` run when the + * operation is initiated, its result posted to `completion_executor`. * - * The free form of - * `public_key.async_verify(executor, crypto::eddsa, signature, message, token)`, which it - * calls, and which runs the key's `verify`, with the same work. + * The free form of the member `public_key.async_verify`, which it calls with the + * arguments other than `public_key`, the scheme `crypto::eddsa` among them, and which runs the + * key's `verify`, with the same work. * - * The input is checked as `crypto::can_verify` checks it, before anything else: a marker stops - * the build (Ed25519 signs the message itself). The signature's and the message's bytes are the - * caller's until the completion; the public key is copied. + * The signature and the input are checked as `crypto::can_verify` checks them, before anything + * else: a signature of another type, bytes included, stops the build, and so does a marker + * (Ed25519 signs the message itself). The message's bytes are the caller's until the completion; + * the signature and the public key are copied. * * @tparam Backend The backend; by default the asynchronous family's. * @tparam Executor The executor's type, an Asio executor (an `io_context`'s or a strand's). + * @tparam Signature `curves::ed25519::signature`; another type stops the build. * @tparam Input A message, bytes that convert to `std::span`. - * @tparam CompletionToken Any completion token for the signature `token` states. - * @param executor The executor the completion is posted to. - * @param scheme `crypto::eddsa`. - * @param signature 64 bytes. - * @param message The signed bytes. + * @tparam CompletionToken Any completion token for the signature `completion_token` states. + * @param completion_executor The executor the completion is posted to. + * @param signing_scheme `crypto::eddsa`. + * @param signature_value The signature; bytes from a peer are made into one by + * `curves::ed25519::signature::from_bytes`. + * @param message_bytes The signed bytes. * @param public_key The signer's public key. - * @param token The completion token, of signature `void(boost::system::error_code)`: - * `invalid_signature` for a signature of another size, and for one that does not verify; - * `backend_failure`. + * @param completion_token The completion token, of signature `void(boost::system::error_code)`: + * `invalid_signature` for a signature that does not verify; `backend_failure`. * @return What the completion token's `async_result` gives. */ -template , class Executor, class Input, - class CompletionToken> -auto async_verify(Executor const& executor, eddsa_t scheme, std::span signature, - Input const& message, curves::ed25519::public_key const& public_key, - CompletionToken&& token) { - detail::timing_guard const timing; - return public_key.template async_verify(executor, scheme, signature, message, - std::forward(token)); +template , class Executor, + class Signature, class Input, class CompletionToken> +auto async_verify(Executor const& completion_executor, eddsa_t signing_scheme, + Signature const& signature_value, Input const& message_bytes, + curves::ed25519::public_key const& public_key, + CompletionToken&& completion_token) { + detail::timing_guard const timing_scope; + return public_key.template async_verify( + completion_executor, signing_scheme, signature_value, message_bytes, + std::forward(completion_token)); } /** @@ -676,75 +1053,172 @@ auto async_verify(Executor const& executor, eddsa_t scheme, std::span`. - * @tparam CompletionToken Any completion token for the signature `token` states. - * @param executor The executor the completion is posted to. - * @param scheme `crypto::eddsa`. - * @param signature 64 bytes. - * @param message The signed bytes. + * @tparam CompletionToken Any completion token for the signature `completion_token` states. + * @param completion_executor The executor the completion is posted to. + * @param signing_scheme `crypto::eddsa`. + * @param signature_value The signature. + * @param message_bytes The signed bytes. * @param public_key The signer's public key. - * @param policy `curves::ed25519::strict` (libsodium's rules), the only policy declared. - * @param token The completion token, of signature `void(boost::system::error_code)`, as the - * overload without a policy completes. + * @param verification_policy `curves::ed25519::strict` (libsodium's rules), the only policy + * declared. + * @param completion_token The completion token, of signature `void(boost::system::error_code)`, as + * the overload without a policy completes. * @return What the completion token's `async_result` gives. */ -template , class Executor, class Input, - class CompletionToken> -auto async_verify(Executor const& executor, eddsa_t scheme, std::span signature, - Input const& message, curves::ed25519::public_key const& public_key, - curves::ed25519::strict_t policy, CompletionToken&& token) { - detail::timing_guard const timing; - return public_key.template async_verify(executor, scheme, signature, message, policy, - std::forward(token)); +template , class Executor, + class Signature, class Input, class CompletionToken> +auto async_verify(Executor const& completion_executor, eddsa_t signing_scheme, + Signature const& signature_value, Input const& message_bytes, + curves::ed25519::public_key const& public_key, + curves::ed25519::strict_t verification_policy, + CompletionToken&& completion_token) { + detail::timing_guard const timing_scope; + return public_key.template async_verify( + completion_executor, signing_scheme, signature_value, message_bytes, verification_policy, + std::forward(completion_token)); +} + +/** + * Verifies an Ed25519ph signature (RFC 8032's Ed25519 over a message's SHA-512), asynchronously, + * strictly: `crypto::verify` of `crypto::eddsa_prehashed` run when the operation is + * initiated, its result posted to `completion_executor`. + * + * The free form of the member `public_key.async_verify`, which it calls with the + * arguments other than `public_key`, the scheme `crypto::eddsa_prehashed` among them, and which + * runs the key's `verify`, with the same work. It runs on a native backend: on one that completes + * by itself it stops the build first (WebCrypto has no Ed25519ph). + * + * The signature and the input are checked as `crypto::can_verify` checks them, before anything + * else: a signature of another type, bytes included, stops the build, and so do a message and a + * digest of another size. The digest's bytes are the caller's until the completion; the signature + * and the public key are copied. + * + * @tparam Backend The backend; by default the asynchronous family's. + * @tparam Executor The executor's type, an Asio executor (an `io_context`'s or a strand's). + * @tparam Signature `curves::ed25519::signature`; another type stops the build. + * @tparam Input `crypto::prehashed<64>`, the message's SHA-512. + * @tparam CompletionToken Any completion token for the signature `completion_token` states. + * @param completion_executor The executor the completion is posted to. + * @param signing_scheme `crypto::eddsa_prehashed`. + * @param signature_value The signature; bytes from a peer are made into one by + * `curves::ed25519::signature::from_bytes`. + * @param digest_input `crypto::prehashed{digest}`, the 64 bytes of the message's SHA-512. + * @param public_key The signer's public key. + * @param completion_token The completion token, of signature `void(boost::system::error_code)`: + * `invalid_signature` for a signature that does not verify, an `eddsa` signature included; + * `backend_failure`. + * @return What the completion token's `async_result` gives. + */ +template , class Executor, + class Signature, class Input, class CompletionToken> +auto async_verify(Executor const& completion_executor, eddsa_prehashed_t signing_scheme, + Signature const& signature_value, Input const& digest_input, + curves::ed25519::public_key const& public_key, + CompletionToken&& completion_token) { + detail::timing_guard const timing_scope; + if constexpr (detail::asynchronous_backend_v) { + detail::refuse_ed25519ph_on_asynchronous_backend(); + } else { + return public_key.template async_verify( + completion_executor, signing_scheme, signature_value, digest_input, + std::forward(completion_token)); + } +} + +/** + * Verifies an Ed25519ph signature under the verification policy given, asynchronously: as the + * overload without it, with `crypto::verify`'s policy argument before the token. + * + * The policy is a policy tag, never deduced from another argument, so that a completion token is + * never read as one. + * + * @tparam Backend The backend; by default the asynchronous family's. + * @tparam Executor The executor's type, an Asio executor (an `io_context`'s or a strand's). + * @tparam Signature `curves::ed25519::signature`; another type stops the build. + * @tparam Input `crypto::prehashed<64>`, the message's SHA-512. + * @tparam CompletionToken Any completion token for the signature `completion_token` states. + * @param completion_executor The executor the completion is posted to. + * @param signing_scheme `crypto::eddsa_prehashed`. + * @param signature_value The signature. + * @param digest_input `crypto::prehashed{digest}`, the 64 bytes of the message's SHA-512. + * @param public_key The signer's public key. + * @param verification_policy `curves::ed25519::strict` (libsodium's rules), the only policy + * declared. + * @param completion_token The completion token, of signature `void(boost::system::error_code)`, as + * the overload without a policy completes. + * @return What the completion token's `async_result` gives. + */ +template , class Executor, + class Signature, class Input, class CompletionToken> +auto async_verify(Executor const& completion_executor, eddsa_prehashed_t signing_scheme, + Signature const& signature_value, Input const& digest_input, + curves::ed25519::public_key const& public_key, + curves::ed25519::strict_t verification_policy, + CompletionToken&& completion_token) { + detail::timing_guard const timing_scope; + if constexpr (detail::asynchronous_backend_v) { + detail::refuse_ed25519ph_on_asynchronous_backend(); + } else { + return public_key.template async_verify( + completion_executor, signing_scheme, signature_value, digest_input, verification_policy, + std::forward(completion_token)); + } } /** * Verifies a P-256 ECDSA signature over SHA-256, asynchronously: - * `crypto::verify(crypto::ecdsa_sha256, signature, input, public_key)` run when the operation is - * initiated, its result posted to `executor`; the message is hashed with SHA-256, as WebCrypto's - * ECDSA with SHA-256 verifies, or `crypto::prehashed{digest}` gives its digest. + * `crypto::verify(crypto::ecdsa_sha256, signature_value, signing_input, public_key)` run when the + * operation is initiated, its result posted to `completion_executor`; the message is hashed with + * SHA-256, as WebCrypto's ECDSA with SHA-256 verifies, or `crypto::prehashed{digest}` gives its + * digest. * - * The free form of - * `public_key.async_verify(executor, crypto::ecdsa_sha256, signature, input, token)`, which it - * calls, and which runs the key's `verify`, with the same work. + * The free form of the member `public_key.async_verify`, which it calls with the arguments + * other than `public_key`, the scheme `crypto::ecdsa_sha256` among them, and which runs the key's + * `verify`, with the same work. * * A high S and a low S are both accepted, as `crypto::verify` and WebCrypto accept them. The - * input is checked as `crypto::can_verify` checks it, before anything else: a marker on a backend - * that completes by itself stops the build. The key and the bytes are the caller's until the - * completion. + * signature and the input are checked as `crypto::can_verify` checks them, before anything else: + * a signature of another type, bytes included, stops the build, and so does a marker on a backend + * that completes by itself. The key and the bytes the input views are the caller's until the + * completion; the signature is copied. * * @tparam Backend The key's backend, which verifies: deduced from the key, or named first, as on * every curve. * @tparam Executor The executor's type, an Asio executor (an `io_context`'s or a strand's). + * @tparam Signature `curves::p256::ecdsa_signature`; another type stops the build. * @tparam Input A message, bytes that convert to `std::span`, of any size, * empty included, or `crypto::prehashed<32>`. - * @tparam CompletionToken Any completion token for the signature `token` states. - * @param executor The executor the completion is posted to. - * @param scheme `crypto::ecdsa_sha256`. - * @param signature 64 bytes, r then s (IEEE P1363's form, WebCrypto's); `curves::p256::from_der` - * reads DER. - * @param input The signed message, or `crypto::prehashed{digest}`, its 32-byte SHA-256 digest. + * @tparam CompletionToken Any completion token for the signature `completion_token` states. + * @param completion_executor The executor the completion is posted to. + * @param signing_scheme `crypto::ecdsa_sha256`. + * @param signature_value The signature, r then s (IEEE P1363's form, WebCrypto's); bytes from a + * peer are made into one by `curves::p256::ecdsa_signature::from_bytes`, and DER by + * `curves::p256::from_der`. + * @param signing_input The signed message, or `crypto::prehashed{digest}`, its 32-byte SHA-256 + * digest. * @param public_key The signer's public key, validated when it was made. - * @param token The completion token, of signature `void(boost::system::error_code)`: - * `invalid_signature` for a signature of another size, an r or an s that is 0 or not below n, and - * one that does not verify. + * @param completion_token The completion token, of signature `void(boost::system::error_code)`: + * `invalid_signature` for an r or an s that is 0 or not below n, and one that does not verify. * @return What the completion token's `async_result` gives. */ -template -auto async_verify(Executor const& executor, ecdsa_sha256_t scheme, - std::span signature, Input const& input, +template +auto async_verify(Executor const& completion_executor, ecdsa_sha256_t signing_scheme, + Signature const& signature_value, Input const& signing_input, curves::p256::basic_public_key const& public_key, - CompletionToken&& token) { - detail::timing_guard const timing; - return public_key.async_verify(executor, scheme, signature, input, - std::forward(token)); + CompletionToken&& completion_token) { + detail::timing_guard const timing_scope; + return public_key.async_verify(completion_executor, signing_scheme, signature_value, + signing_input, std::forward(completion_token)); } /** * Stops the build: no `async_verify` checks a signature of `Scheme` against this public key. * - * The asynchronous family has the algorithms WebCrypto has: Ed25519's and P-256's overloads above - * are chosen for their keys; this one only when neither is, and it names them. + * The asynchronous family has the algorithms WebCrypto has, and Ed25519ph on a native backend: + * Ed25519's and P-256's overloads above are chosen for their keys; this one only when neither is, + * and it names them. * * @tparam Backend Ignored: the first template parameter, as on every `async_verify`. * @tparam Executor The executor's type. @@ -753,87 +1227,106 @@ auto async_verify(Executor const& executor, ecdsa_sha256_t scheme, * @tparam Input The input's type. * @tparam PublicKey The public key's type. * @tparam CompletionToken The completion token's type. - * @param executor The executor. - * @param scheme The scheme. - * @param signature The signature. - * @param input The message or the marker. + * @param completion_executor The executor. + * @param signing_scheme The scheme. + * @param signature_value The signature. + * @param signing_input The message or the marker. * @param public_key The public key. - * @param token The completion token. + * @param completion_token The completion token. */ template requires(detail::is_scheme_v && !detail::has_async_verifier_v>) -void async_verify([[maybe_unused]] Executor const& executor, [[maybe_unused]] Scheme scheme, - [[maybe_unused]] Signature const& signature, [[maybe_unused]] Input const& input, +void async_verify([[maybe_unused]] Executor const& completion_executor, + [[maybe_unused]] Scheme signing_scheme, + [[maybe_unused]] Signature const& signature_value, + [[maybe_unused]] Input const& signing_input, [[maybe_unused]] PublicKey const& public_key, - [[maybe_unused]] CompletionToken&& token) { + [[maybe_unused]] CompletionToken&& completion_token) { static_assert(detail::refused_v, - "webcpp::crypto: async_verify takes crypto::eddsa with a " - "curves::ed25519::public_key or crypto::ecdsa_sha256 with a " + "webcpp::crypto: async_verify takes crypto::eddsa or crypto::eddsa_prehashed " + "with a curves::ed25519::public_key or crypto::ecdsa_sha256 with a " "curves::p256::basic_public_key, the algorithms WebCrypto has: call " "crypto::verify for the others."); } /** - * Agrees an X25519 shared secret, asynchronously: `curves::x25519::agree` run when the - * operation is initiated, its result posted to `executor`. + * Agrees a shared secret, asynchronously: `key_pair.agree(peer_public_key)` run when the operation + * is initiated, its result posted to `completion_executor`: X25519's (RFC 7748), or P-256's ECDH + * raw x coordinate, as WebCrypto's `deriveBits` with ECDH on P-256 gives its 256 bits. * - * The spans are the caller's until the completion. + * The free form of `key_pair.async_agree(completion_executor, peer_public_key, completion_token)`, + * which it calls. * - * @tparam Backend The backend; by default the asynchronous family's. + * P-256's x coordinate is not a key: a protocol hashes it into its keys (with HKDF, for instance). + * The key pair and the peer's key are the caller's until the completion. A key pair of an + * algorithm WebCrypto lacks (secp256k1) stops the build: call its own `agree`. + * + * @tparam Keypair An `agreement_keypair` of an algorithm WebCrypto has: a + * `curves::x25519::basic_keypair` or a `curves::p256::basic_keypair`. * @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 `token` states. - * @param executor The executor the completion is posted to. - * @param secret_key 32 bytes. - * @param peer_public_key 32 bytes. - * @param token The completion token, of signature `void(boost::system::error_code, secret<32>)`: - * the shared secret; on an error a secret of zeros (`invalid_key_size`, `invalid_public_key`, - * `weak_public_key`, `backend_failure`). + * @tparam PublicKey The peer's public key's type, the key pair's own `public_key_type`. + * @tparam CompletionToken Any completion token for the signature `completion_token` states. + * @param completion_executor The executor the completion is posted to. + * @param key_pair This side's key pair. + * @param peer_public_key The peer's public key, of the key pair's `public_key_type`: a + * `curves::x25519::public_key`, or a `curves::p256::basic_public_key` of the key pair's backend, + * validated when it was made. + * @param completion_token The completion token, of signature + * `void(boost::system::error_code, secret<32>)`: the shared secret, or P-256's shared x, + * big-endian; on an error a secret of zeros (`invalid_state` for an empty key pair, + * `weak_public_key` on X25519, `backend_failure`). * @return What the completion token's `async_result` gives. */ -template , class Executor, - class CompletionToken> -auto async_agree(Executor const& executor, std::span secret_key, - std::span peer_public_key, CompletionToken&& token) { - detail::timing_guard const timing; - if constexpr (detail::asynchronous_backend_v) { - return detail::async_engine::agree(executor, secret_key, peer_public_key, - std::forward(token)); +template + requires detail::agrees_with_peer +auto async_agree(Executor const& completion_executor, Keypair const& key_pair, + PublicKey const& peer_public_key, CompletionToken&& completion_token) { + detail::timing_guard const timing_scope; + if constexpr (!detail::is_x25519_keypair_v && !detail::is_p256_keypair_v) { + detail::refuse_async_agree_keypair(); } else { - return detail::complete_by_post(executor, token, [secret_key, peer_public_key]() noexcept { - return curves::x25519::agree(secret_key, peer_public_key); - }); + return key_pair.async_agree(completion_executor, peer_public_key, + std::forward(completion_token)); } } /** - * Agrees a P-256 shared secret, ECDH's raw x coordinate, asynchronously: - * `key_pair.agree(peer_public_key)` run when the operation is initiated, its result posted to - * `executor`, as WebCrypto's `deriveBits` with ECDH on P-256 gives its 256 bits. - * - * The free form of `key_pair.async_agree(executor, peer_public_key, token)`, which it calls. - * - * The x coordinate is not a key: a protocol hashes it into its keys (with HKDF, for instance). - * The key pair and the peer's key are the caller's until the completion. + * Stops the build: `async_agree` takes an agreement key pair (`crypto::agreement_keypair`) and a + * peer of its own `public_key_type`, and this call does not: an Ed25519 key pair, which signs and + * does not agree, a key pair of an algorithm WebCrypto lacks (secp256k1), or a peer of another + * curve, another backend, or bytes, each with its own message. * - * @tparam Backend The backend of the key pair and of the peer's key. - * @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 `token` states. - * @param executor The executor the completion is posted to. - * @param key_pair This side's key pair. - * @param peer_public_key The peer's public key, validated when it was made. - * @param token The completion token, of signature `void(boost::system::error_code, secret<32>)`: - * the shared x, big-endian; on an error a secret of zeros (`invalid_state` for an empty key pair, - * `backend_failure`). - * @return What the completion token's `async_result` gives. + * @tparam Keypair The key pair's type, a `keypair`. + * @tparam Executor The executor's type. + * @tparam PublicKey The peer's type. + * @tparam CompletionToken The completion token's type. + * @param completion_executor The executor. + * @param key_pair The key pair. + * @param peer_public_key The peer. + * @param completion_token The completion token. */ -template -auto async_agree(Executor const& executor, curves::p256::basic_keypair const& key_pair, - curves::p256::basic_public_key const& peer_public_key, - CompletionToken&& token) { - detail::timing_guard const timing; - return key_pair.async_agree(executor, peer_public_key, std::forward(token)); +template + requires(keypair && !detail::agrees_with_peer) +void async_agree([[maybe_unused]] Executor const& completion_executor, + [[maybe_unused]] Keypair const& key_pair, + [[maybe_unused]] PublicKey const& peer_public_key, + [[maybe_unused]] CompletionToken&& completion_token) { + if constexpr (signing_keypair && !agreement_keypair) { + static_assert(detail::refused_v, + "webcpp::crypto: async_agree: Ed25519 key pairs sign; they do not agree: " + "convert one with to_x25519() and agree with the X25519 key pair."); + } else if constexpr (!detail::is_x25519_keypair_v && + !detail::is_p256_keypair_v) { + detail::refuse_async_agree_keypair(); + } else { + static_assert( + detail::refused_v, + "webcpp::crypto: async_agree: this key pair does not agree with this peer: an " + "X25519 key pair agrees with a curves::x25519::public_key, a P-256 key pair " + "with a curves::p256::basic_public_key of its backend."); + } } // The asynchronous members (design D9), declared in their classes and defined here, so that a @@ -842,169 +1335,362 @@ auto async_agree(Executor const& executor, curves::p256::basic_keypair template template -auto ciphers::gcm::async_make(Executor const& executor, - std::span key_bytes, - CompletionToken&& token) { - detail::timing_guard const timing; - return detail::initiate_make(executor, key_bytes, std::forward(token)); +auto ciphers::gcm::async_from_key(Executor const& completion_executor, + std::span key_bytes, + CompletionToken&& completion_token) { + detail::timing_guard const timing_scope; + return detail::initiate_from_key(completion_executor, key_bytes, + std::forward(completion_token)); } template template -auto ciphers::gcm::async_seal(Executor const& executor, - std::span iv_bytes, - std::span additional_data_bytes, - std::span data_bytes, CompletionToken&& token) { - detail::timing_guard const timing; +auto ciphers::gcm::async_seal(Executor const& completion_executor, + std::span nonce_bytes, + std::span associated_data_bytes, + std::span data_bytes, + CompletionToken&& completion_token) { + detail::timing_guard const timing_scope; if constexpr (detail::asynchronous_backend_v) { - return detail::async_engine::seal(executor, *this, iv_bytes, additional_data_bytes, - data_bytes, - std::forward(token)); + return detail::async_engine::seal(completion_executor, *this, nonce_bytes, + associated_data_bytes, data_bytes, + std::forward(completion_token)); } else { return detail::complete_by_post( - executor, token, [this, iv_bytes, additional_data_bytes, data_bytes]() noexcept { - return seal(iv_bytes, additional_data_bytes, data_bytes); + completion_executor, completion_token, + [this, nonce_bytes, associated_data_bytes, data_bytes]() noexcept { + return seal(nonce_bytes, associated_data_bytes, data_bytes); }); } } template template -auto ciphers::gcm::async_open(Executor const& executor, - std::span iv_bytes, - std::span additional_data_bytes, +auto ciphers::gcm::async_open(Executor const& completion_executor, + std::span nonce_bytes, + std::span associated_data_bytes, std::span data_bytes, std::span tag_bytes, - CompletionToken&& token) { - detail::timing_guard const timing; + CompletionToken&& completion_token) { + detail::timing_guard const timing_scope; if constexpr (detail::asynchronous_backend_v) { - return detail::async_engine::open(executor, *this, iv_bytes, additional_data_bytes, - data_bytes, tag_bytes, - std::forward(token)); + return detail::async_engine::open(completion_executor, *this, nonce_bytes, + associated_data_bytes, data_bytes, tag_bytes, + std::forward(completion_token)); + } else { + return detail::complete_by_post( + completion_executor, completion_token, + [this, nonce_bytes, associated_data_bytes, data_bytes, tag_bytes]() noexcept { + return open(nonce_bytes, associated_data_bytes, data_bytes, tag_bytes); + }); + } +} + +template +template +auto ciphers::basic_chacha20_poly1305::async_from_key( + Executor const& completion_executor, std::span key_bytes, + CompletionToken&& completion_token) { + detail::timing_guard const timing_scope; + if constexpr (detail::asynchronous_backend_v) { + detail::refuse_aead_on_asynchronous_backend(); + } else { + return detail::complete_by_post( + completion_executor, completion_token, + [key_bytes]() noexcept { return basic_chacha20_poly1305::from_key(key_bytes); }); + } +} + +template +template +auto ciphers::basic_chacha20_poly1305::async_seal( + Executor const& completion_executor, std::span nonce_bytes, + std::span associated_data_bytes, std::span data_bytes, + CompletionToken&& completion_token) { + detail::timing_guard const timing_scope; + if constexpr (detail::asynchronous_backend_v) { + detail::refuse_aead_on_asynchronous_backend(); + } else { + return detail::complete_by_post( + completion_executor, completion_token, + [this, nonce_bytes, associated_data_bytes, data_bytes]() noexcept { + return seal(nonce_bytes, associated_data_bytes, data_bytes); + }); + } +} + +template +template +auto ciphers::basic_chacha20_poly1305::async_open( + Executor const& completion_executor, std::span nonce_bytes, + std::span associated_data_bytes, std::span data_bytes, + std::span tag_bytes, CompletionToken&& completion_token) { + detail::timing_guard const timing_scope; + if constexpr (detail::asynchronous_backend_v) { + detail::refuse_aead_on_asynchronous_backend(); } else { return detail::complete_by_post( - executor, token, - [this, iv_bytes, additional_data_bytes, data_bytes, tag_bytes]() noexcept { - return open(iv_bytes, additional_data_bytes, data_bytes, tag_bytes); + completion_executor, completion_token, + [this, nonce_bytes, associated_data_bytes, data_bytes, tag_bytes]() noexcept { + return open(nonce_bytes, associated_data_bytes, data_bytes, tag_bytes); }); } } +template +template +auto secret_key_encryption::basic_secretbox::async_from_key( + Executor const& completion_executor, std::span key_bytes, + CompletionToken&& completion_token) { + detail::timing_guard const timing_scope; + if constexpr (detail::asynchronous_backend_v) { + detail::refuse_aead_on_asynchronous_backend(); + } else { + return detail::complete_by_post( + completion_executor, completion_token, + [key_bytes]() noexcept { return basic_secretbox::from_key(key_bytes); }); + } +} + +template +template +auto secret_key_encryption::basic_secretbox::async_seal( + Executor const& completion_executor, std::span nonce_bytes, + std::span data_bytes, CompletionToken&& completion_token) { + detail::timing_guard const timing_scope; + if constexpr (detail::asynchronous_backend_v) { + detail::refuse_aead_on_asynchronous_backend(); + } else { + return detail::complete_by_post( + completion_executor, completion_token, + [this, nonce_bytes, data_bytes]() noexcept { return seal(nonce_bytes, data_bytes); }); + } +} + +template +template +auto secret_key_encryption::basic_secretbox::async_open( + Executor const& completion_executor, std::span nonce_bytes, + std::span data_bytes, std::span tag_bytes, + CompletionToken&& completion_token) { + detail::timing_guard const timing_scope; + if constexpr (detail::asynchronous_backend_v) { + detail::refuse_aead_on_asynchronous_backend(); + } else { + return detail::complete_by_post(completion_executor, completion_token, + [this, nonce_bytes, data_bytes, tag_bytes]() noexcept { + return open(nonce_bytes, data_bytes, tag_bytes); + }); + } +} + +template +template +auto public_key_encryption::basic_box::async_seal( + Executor const& completion_executor, std::span nonce_bytes, + std::span data_bytes, CompletionToken&& completion_token) { + detail::timing_guard const timing_scope; + if constexpr (detail::asynchronous_backend_v) { + detail::refuse_aead_on_asynchronous_backend(); + } else { + return detail::complete_by_post( + completion_executor, completion_token, + [this, nonce_bytes, data_bytes]() noexcept { return seal(nonce_bytes, data_bytes); }); + } +} + +template +template +auto public_key_encryption::basic_box::async_open( + Executor const& completion_executor, std::span nonce_bytes, + std::span data_bytes, std::span tag_bytes, + CompletionToken&& completion_token) { + detail::timing_guard const timing_scope; + if constexpr (detail::asynchronous_backend_v) { + detail::refuse_aead_on_asynchronous_backend(); + } else { + return detail::complete_by_post(completion_executor, completion_token, + [this, nonce_bytes, data_bytes, tag_bytes]() noexcept { + return open(nonce_bytes, data_bytes, tag_bytes); + }); + } +} + template template -auto curves::ed25519::basic_keypair::async_make(Executor const& executor, - std::span seed, - CompletionToken&& token) { - detail::timing_guard const timing; - return detail::initiate_make(executor, seed, - std::forward(token)); +auto curves::ed25519::basic_keypair::async_from_secret( + Executor const& completion_executor, std::span seed_bytes, + CompletionToken&& completion_token) { + detail::timing_guard const timing_scope; + return detail::initiate_from_secret( + completion_executor, seed_bytes, std::forward(completion_token)); } template template -auto curves::ed25519::basic_keypair::async_generate(Executor const& executor, - CompletionToken&& token) { - detail::timing_guard const timing; - return detail::initiate_generate(executor, std::forward(token)); +auto curves::ed25519::basic_keypair::async_generate(Executor const& completion_executor, + CompletionToken&& completion_token) { + detail::timing_guard const timing_scope; + return detail::initiate_generate( + completion_executor, std::forward(completion_token)); } template template -auto curves::ed25519::basic_keypair::async_sign(Executor const& executor, Scheme scheme, - Input const& message, - CompletionToken&& token) const { - detail::timing_guard const timing; - return detail::initiate_sign(executor, *this, scheme, message, - std::forward(token)); -} - -template -auto curves::ed25519::public_key::async_verify(Executor const& executor, - [[maybe_unused]] Scheme scheme, - std::span signature, - Input const& message, - CompletionToken&& token) const { - detail::timing_guard const timing; - return detail::initiate_verify_ed25519( - executor, signature, message, *this, strict, std::forward(token)); -} - -template -auto curves::ed25519::public_key::async_verify(Executor const& executor, - [[maybe_unused]] Scheme scheme, - std::span signature, - Input const& message, strict_t policy, - CompletionToken&& token) const { - detail::timing_guard const timing; - return detail::initiate_verify_ed25519( - executor, signature, message, *this, policy, std::forward(token)); +auto curves::ed25519::basic_keypair::async_sign(Executor const& completion_executor, + Scheme signing_scheme, + Input const& message_input, + CompletionToken&& completion_token) const { + detail::timing_guard const timing_scope; + if constexpr (detail::ed25519ph_on_browser_v) { + detail::refuse_ed25519ph_on_asynchronous_backend(); + } else { + return detail::initiate_sign(completion_executor, *this, signing_scheme, message_input, + std::forward(completion_token)); + } +} + +template +auto curves::ed25519::public_key::async_verify(Executor const& completion_executor, + [[maybe_unused]] Scheme signing_scheme, + Signature const& signature_value, + Input const& message_input, + CompletionToken&& completion_token) const { + detail::timing_guard const timing_scope; + if constexpr (std::is_same_v && + detail::asynchronous_backend_v) { + detail::refuse_ed25519ph_on_asynchronous_backend(); + } else { + return detail::initiate_verify_ed25519( + completion_executor, signature_value, message_input, *this, strict, + std::forward(completion_token)); + } +} + +template +auto curves::ed25519::public_key::async_verify(Executor const& completion_executor, + [[maybe_unused]] Scheme signing_scheme, + Signature const& signature_value, + Input const& message_input, strict_t verify_policy, + CompletionToken&& completion_token) const { + detail::timing_guard const timing_scope; + if constexpr (std::is_same_v && + detail::asynchronous_backend_v) { + detail::refuse_ed25519ph_on_asynchronous_backend(); + } else { + return detail::initiate_verify_ed25519( + completion_executor, signature_value, message_input, *this, verify_policy, + std::forward(completion_token)); + } } template template -auto curves::p256::basic_keypair::async_make(Executor const& executor, - std::span secret_scalar, - CompletionToken&& token) { - detail::timing_guard const timing; - return detail::initiate_make(executor, secret_scalar, - std::forward(token)); +auto curves::x25519::basic_keypair::async_from_secret( + Executor const& completion_executor, std::span secret_bytes, + CompletionToken&& completion_token) { + detail::timing_guard const timing_scope; + return detail::initiate_from_secret( + completion_executor, secret_bytes, std::forward(completion_token)); } template template -auto curves::p256::basic_keypair::async_generate(Executor const& executor, - CompletionToken&& token) { - detail::timing_guard const timing; - return detail::initiate_generate(executor, std::forward(token)); +auto curves::x25519::basic_keypair::async_generate(Executor const& completion_executor, + CompletionToken&& completion_token) { + detail::timing_guard const timing_scope; + return detail::initiate_generate( + completion_executor, std::forward(completion_token)); +} + +template +template +// NOLINTNEXTLINE(modernize-use-nodiscard): a callback's completion token makes it return void +auto curves::x25519::basic_keypair::async_agree(Executor const& completion_executor, + public_key_type const& peer_key, + CompletionToken&& completion_token) const { + detail::timing_guard const timing_scope; + if constexpr (detail::asynchronous_backend_v) { + return detail::async_engine::agree( + completion_executor, *this, peer_key, std::forward(completion_token)); + } else { + return detail::complete_by_post(completion_executor, completion_token, + [this, &peer_key]() noexcept { return agree(peer_key); }); + } +} + +template +template +auto curves::p256::basic_keypair::async_from_secret( + Executor const& completion_executor, std::span secret_scalar, + CompletionToken&& completion_token) { + detail::timing_guard const timing_scope; + return detail::initiate_from_secret( + completion_executor, secret_scalar, std::forward(completion_token)); +} + +template +template +auto curves::p256::basic_keypair::async_generate(Executor const& completion_executor, + CompletionToken&& completion_token) { + detail::timing_guard const timing_scope; + return detail::initiate_generate( + completion_executor, std::forward(completion_token)); } template template -auto curves::p256::basic_keypair::async_sign(Executor const& executor, Scheme scheme, - Input const& input, - CompletionToken&& token) const { - detail::timing_guard const timing; - return detail::initiate_sign(executor, *this, scheme, input, - std::forward(token)); +auto curves::p256::basic_keypair::async_sign(Executor const& completion_executor, + Scheme signing_scheme, + Input const& signing_input, + CompletionToken&& completion_token) const { + detail::timing_guard const timing_scope; + return detail::initiate_sign(completion_executor, *this, signing_scheme, signing_input, + std::forward(completion_token)); } template template -auto curves::p256::basic_keypair::async_agree(Executor const& executor, - basic_public_key const& peer, - CompletionToken&& token) const { - detail::timing_guard const timing; +auto curves::p256::basic_keypair::async_agree(Executor const& completion_executor, + basic_public_key const& peer_key, + CompletionToken&& completion_token) const { + detail::timing_guard const timing_scope; if constexpr (detail::asynchronous_backend_v) { - return detail::async_engine::agree(executor, *this, peer, - std::forward(token)); + return detail::async_engine::agree( + completion_executor, *this, peer_key, std::forward(completion_token)); } else { - return detail::complete_by_post(executor, token, - [this, &peer]() noexcept { return agree(peer); }); + return detail::complete_by_post(completion_executor, completion_token, + [this, &peer_key]() noexcept { return agree(peer_key); }); } } template -template -auto curves::p256::basic_public_key::async_verify(Executor const& executor, - [[maybe_unused]] Scheme scheme, - std::span signature, - Input const& input, - CompletionToken&& token) const { - detail::timing_guard const timing; +template +auto curves::p256::basic_public_key::async_verify( + Executor const& completion_executor, [[maybe_unused]] Scheme signing_scheme, + Signature const& signature_value, Input const& signing_input, + CompletionToken&& completion_token) const { + detail::timing_guard const timing_scope; if constexpr (!std::is_same_v) { static_assert(detail::refused_v, "webcpp::crypto: a P-256 public key verifies crypto::ecdsa_sha256."); - } else if constexpr (!can_verify) { + } else if constexpr (!detail::check_signature()) { + // Never compiled into a program: check_signature stopped the build. + } else if constexpr (!detail::input_valid_v) { detail::check_input(); } else if constexpr (detail::asynchronous_backend_v) { - return detail::async_engine::verify(executor, ecdsa_sha256, signature, - detail::kept_input(input), *this, - std::forward(token)); + return detail::async_engine::verify( + completion_executor, ecdsa_sha256, signature_value, detail::kept_input(signing_input), + *this, std::forward(completion_token)); } else { return detail::complete_by_post( - executor, token, - [this, signature, kept = detail::kept_input(input)]() noexcept - -> boost::system::result { return verify(ecdsa_sha256, signature, kept); }); + completion_executor, completion_token, + [this, signature_value, + kept = detail::kept_input(signing_input)]() noexcept -> boost::system::result { + return verify(ecdsa_sha256, signature_value, kept); + }); } } diff --git a/include/webcpp/crypto/backends/bearssl.hpp b/include/webcpp/crypto/backends/bearssl.hpp index 19e875e3..41d496ae 100644 --- a/include/webcpp/crypto/backends/bearssl.hpp +++ b/include/webcpp/crypto/backends/bearssl.hpp @@ -25,12 +25,12 @@ #else #include +#include #include #include #include #include #include -#include #include #include @@ -155,22 +155,22 @@ struct gcm_engine { } /** - * Starts a message: the IV, then the whole additional data. + * Starts a message: the nonce, then the whole associated data. * * @param engine_state A keyed state. * @param is_sealing Whether the message is sealed or opened. - * @param iv_bytes 1 to 128 bytes. - * @param additional_data_bytes Read whole before this returns. + * @param nonce_bytes 1 to 128 bytes. + * @param associated_data_bytes Read whole before this returns. * @return Nothing. */ [[nodiscard]] static boost::system::result start( - state& engine_state, bool is_sealing, std::span iv_bytes, - std::span additional_data_bytes) noexcept { + state& engine_state, bool is_sealing, std::span nonce_bytes, + std::span associated_data_bytes) noexcept { read_canary(WEBCPP_CRYPTO_DETAIL_BEARSSL_CANARY); engine_state.sealing = is_sealing; - br_gcm_reset(&engine_state.context, iv_bytes.data(), iv_bytes.size()); - br_gcm_aad_inject(&engine_state.context, additional_data_bytes.data(), - additional_data_bytes.size()); + br_gcm_reset(&engine_state.context, nonce_bytes.data(), nonce_bytes.size()); + br_gcm_aad_inject(&engine_state.context, associated_data_bytes.data(), + associated_data_bytes.size()); br_gcm_flip(&engine_state.context); return {}; } @@ -306,7 +306,7 @@ struct aead_state { /** * ChaCha20-Poly1305 on BearSSL: one function over the whole message, which encrypts or decrypts * and computes the tag (inc/bearssl_block.h, `br_poly1305_run`). BearSSL leaves the tag's check - * to its caller: `equal` does it. BearSSL allocates nothing and never fails. + * to its caller: `constant_time_equal` does it. BearSSL allocates nothing and never fails. */ template <> struct aead_engine { @@ -329,24 +329,24 @@ struct aead_engine { /** * Encrypts `data_bytes` in place and writes the tag. BearSSL reads the nonce before it - * writes a byte of the data, and the additional data after it encrypts (`aead` forbids + * writes a byte of the data, and the associated data after it encrypts (`aead` forbids * their overlap). * * @param engine_state A keyed state. - * @param iv_bytes 12 bytes. - * @param additional_data_bytes Authenticated, not encrypted. + * @param nonce_bytes 12 bytes. + * @param associated_data_bytes Authenticated, not encrypted. * @param data_bytes The message. * @param tag_bytes The tag. * @return Nothing. */ [[nodiscard]] static boost::system::result seal( - state& engine_state, std::span iv_bytes, - std::span additional_data_bytes, std::span data_bytes, + state& engine_state, std::span nonce_bytes, + std::span associated_data_bytes, std::span data_bytes, boost::hash2::digest<16>& tag_bytes) noexcept { read_canary(WEBCPP_CRYPTO_DETAIL_BEARSSL_CANARY); - bearssl_poly1305()(engine_state.key.data(), iv_bytes.data(), data_bytes.data(), - data_bytes.size(), additional_data_bytes.data(), - additional_data_bytes.size(), tag_bytes.data(), bearssl_chacha20(), 1); + bearssl_poly1305()(engine_state.key.data(), nonce_bytes.data(), data_bytes.data(), + data_bytes.size(), associated_data_bytes.data(), + associated_data_bytes.size(), tag_bytes.data(), bearssl_chacha20(), 1); return {}; } @@ -355,28 +355,28 @@ struct aead_engine { * constant time; `aead` zeroes the data when they differ. * * @param engine_state A keyed state. - * @param iv_bytes 12 bytes. - * @param additional_data_bytes The additional data of the seal. + * @param nonce_bytes 12 bytes. + * @param associated_data_bytes The associated data of the seal. * @param data_bytes The ciphertext. * @param tag_bytes The expected tag. * @return Nothing; `authentication_failed`. */ [[nodiscard]] static boost::system::result open( - state& engine_state, std::span iv_bytes, - std::span additional_data_bytes, std::span data_bytes, + state& engine_state, std::span nonce_bytes, + std::span associated_data_bytes, std::span data_bytes, std::array const& tag_bytes) noexcept { read_canary(WEBCPP_CRYPTO_DETAIL_BEARSSL_CANARY); std::array computed_tag{}; - bearssl_poly1305()(engine_state.key.data(), iv_bytes.data(), data_bytes.data(), - data_bytes.size(), additional_data_bytes.data(), - additional_data_bytes.size(), computed_tag.data(), bearssl_chacha20(), + bearssl_poly1305()(engine_state.key.data(), nonce_bytes.data(), data_bytes.data(), + data_bytes.size(), associated_data_bytes.data(), + associated_data_bytes.size(), computed_tag.data(), bearssl_chacha20(), 0); // The verdict is public by design (a failed open is reported): declassified here, // where webcpp's code first branches on it, for the constant-time checks. // Not const: the branch below must read the variable again after the declassifying // client request, whose memory clobber reaches a mutable object only. // NOLINTNEXTLINE(misc-const-correctness): see above - bool tag_matches = equal(computed_tag, tag_bytes); + bool tag_matches = constant_time_equal(computed_tag, tag_bytes); WEBCPP_CRYPTO_DETAIL_DECLASSIFY(&tag_matches, sizeof tag_matches); wipe(computed_tag.data(), computed_tag.size()); if (!tag_matches) { @@ -414,8 +414,8 @@ struct aead_engine { */ [[nodiscard]] inline br_ec_impl const* bearssl_p256() noexcept { #ifndef WEBCPP_CRYPTO_WEBASSEMBLY - if (br_ec_impl const* wide = br_ec_p256_m62_get()) { - return wide; + if (br_ec_impl const* wide_impl = br_ec_p256_m62_get()) { + return wide_impl; } #endif return &br_ec_p256_m31; @@ -443,18 +443,19 @@ struct p_curve_engine { /** * Keeps the scalar and computes its public point. * - * @param keyed An empty state. - * @param scalar 32 bytes, 0 < d < n (the family's header has checked them). + * @param keyed_state An empty state. + * @param scalar_bytes 32 bytes, 0 < d < n (the family's header has checked them). * @return Nothing; `backend_failure`, which a valid scalar cannot cause. */ - [[nodiscard]] static boost::system::result make( - state& keyed, std::span scalar) noexcept { + [[nodiscard]] static boost::system::result import_secret( + state& keyed_state, std::span scalar_bytes) noexcept { WEBCPP_CRYPTO_DETAIL_P_CURVE_ENGINE_ENTERED(); read_canary(WEBCPP_CRYPTO_DETAIL_BEARSSL_CANARY); - std::ranges::copy(scalar, keyed.scalar.begin()); - if (bearssl_p256()->mulgen(keyed.point.data(), keyed.scalar.data(), keyed.scalar.size(), - BR_EC_secp256r1) != keyed.point.size()) { - reset(keyed); + std::ranges::copy(scalar_bytes, keyed_state.scalar.begin()); + if (bearssl_p256()->mulgen(keyed_state.point.data(), keyed_state.scalar.data(), + keyed_state.scalar.size(), + BR_EC_secp256r1) != keyed_state.point.size()) { + reset(keyed_state); return error::backend_failure; } return {}; @@ -463,47 +464,47 @@ struct p_curve_engine { /** * Whether an uncompressed point is on the curve, its coordinates below p. * - * @param point 65 bytes, whose first byte is 04 (the family's header has checked it). + * @param point_bytes 65 bytes, whose first byte is 04 (the family's header has checked it). * @return Whether BearSSL decodes it. */ - [[nodiscard]] static bool valid_point(std::span point) noexcept { + [[nodiscard]] static bool valid_point(std::span point_bytes) noexcept { WEBCPP_CRYPTO_DETAIL_P_CURVE_ENGINE_ENTERED(); read_canary(WEBCPP_CRYPTO_DETAIL_BEARSSL_CANARY); // BearSSL decodes, and so checks, a point only to multiply it: by 1 it comes back as it // was, re-encoded, when its coordinates are below p and on the curve (design D36). - std::array decoded{}; - std::ranges::copy(point, decoded.begin()); - constexpr std::array one{1}; - return bearssl_p256()->mul(decoded.data(), decoded.size(), one.data(), one.size(), - BR_EC_secp256r1) == 1 && - std::ranges::equal(decoded, point); + std::array decoded_point{}; + std::ranges::copy(point_bytes, decoded_point.begin()); + constexpr std::array one_scalar{1}; + return bearssl_p256()->mul(decoded_point.data(), decoded_point.size(), one_scalar.data(), + one_scalar.size(), BR_EC_secp256r1) == 1 && + std::ranges::equal(decoded_point, point_bytes); } /** * Signs a digest with ECDSA and RFC 6979's nonce, S as BearSSL computes it (design D36). * - * @param keyed A keyed state. - * @param digest The 32-byte SHA-256 digest. - * @param output 64 bytes, r then s. + * @param keyed_state A keyed state. + * @param digest_bytes The 32-byte SHA-256 digest. + * @param output_bytes 64 bytes, r then s. * @return Nothing; `backend_failure`, which a valid key cannot cause. */ [[nodiscard]] static boost::system::result sign( - state const& keyed, std::span digest, - std::span output) noexcept { + state const& keyed_state, std::span digest_bytes, + std::span output_bytes) noexcept { WEBCPP_CRYPTO_DETAIL_P_CURVE_ENGINE_ENTERED(); read_canary(WEBCPP_CRYPTO_DETAIL_BEARSSL_CANARY); // BearSSL's struct is not const-correct: it only reads the scalar. // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast): see above - auto* const scalar = const_cast(keyed.scalar.data()); - br_ec_private_key const key{ + auto* const scalar_bytes = const_cast(keyed_state.scalar.data()); + br_ec_private_key const bearssl_key{ .curve = BR_EC_secp256r1, - .x = scalar, - .xlen = keyed.scalar.size(), + .x = scalar_bytes, + .xlen = keyed_state.scalar.size(), }; // RFC 6979's nonce, from HMAC-DRBG over SHA-256: br_sha256_vtable is the hash of the // nonce's derivation, which RFC 6979 makes the digest's own. No random number is drawn. - if (br_ecdsa_i31_sign_raw(bearssl_p256(), &br_sha256_vtable, digest.data(), &key, - output.data()) != output.size()) { + if (br_ecdsa_i31_sign_raw(bearssl_p256(), &br_sha256_vtable, digest_bytes.data(), + &bearssl_key, output_bytes.data()) != output_bytes.size()) { return error::backend_failure; } return {}; @@ -512,155 +513,164 @@ struct p_curve_engine { /** * ECDH: the peer's point multiplied by the scalar, and the product's x coordinate. * - * @param keyed A keyed state. - * @param peer The peer's uncompressed point, valid (its public key was made by BearSSL's + * @param keyed_state A keyed state. + * @param peer_key The peer's uncompressed point, valid (its public key was made by BearSSL's * decoding). - * @param output 32 bytes, a `secret<32>`'s. + * @param output_bytes 32 bytes, a `secret<32>`'s. * @return Nothing; `backend_failure`, which a valid point and a scalar in range cannot cause. */ [[nodiscard]] static boost::system::result ecdh_x( - state const& keyed, std::span peer, - std::span output) noexcept { + state const& keyed_state, std::span peer_key, + std::span output_bytes) noexcept { WEBCPP_CRYPTO_DETAIL_P_CURVE_ENGINE_ENTERED(); read_canary(WEBCPP_CRYPTO_DETAIL_BEARSSL_CANARY); // BearSSL multiplies in place: the copy becomes d * Q, uncompressed, and is wiped after. - std::array shared{}; - std::ranges::copy(peer, shared.begin()); + std::array shared_point{}; + std::ranges::copy(peer_key, shared_point.begin()); // BearSSL's verdict: on br_ec_p256_m62, the point's decoding, its own check of the // scalar's range and whether the product is the point at infinity, so a constant-time // checker holds it secret; on br_ec_p256_m31, the decoding alone. Whether a valid point // and a valid scalar multiply is public. // Not const: the branch reads it again after the mark (detail/declassify.hpp's tip). // NOLINTNEXTLINE(misc-const-correctness): see above - std::uint32_t multiplied = - bearssl_p256()->mul(shared.data(), shared.size(), keyed.scalar.data(), - keyed.scalar.size(), BR_EC_secp256r1); - WEBCPP_CRYPTO_DETAIL_DECLASSIFY(&multiplied, sizeof multiplied); - if (multiplied != 1) { - wipe_object(shared); + std::uint32_t multiplied_flag = + bearssl_p256()->mul(shared_point.data(), shared_point.size(), keyed_state.scalar.data(), + keyed_state.scalar.size(), BR_EC_secp256r1); + WEBCPP_CRYPTO_DETAIL_DECLASSIFY(&multiplied_flag, sizeof multiplied_flag); + if (multiplied_flag != 1) { + wipe_object(shared_point); return error::backend_failure; // a validated point and a scalar in range never fail } std::size_t x_size = 0; std::size_t const x_offset = bearssl_p256()->xoff(BR_EC_secp256r1, &x_size); - std::ranges::copy(std::span(shared).subspan(x_offset, x_size), - output.begin()); - wipe_object(shared); + std::ranges::copy(std::span(shared_point).subspan(x_offset, x_size), + output_bytes.begin()); + wipe_object(shared_point); return {}; } /** * Verifies an ECDSA signature; a high S is accepted (design D36). * - * @param point The public key's uncompressed point, valid. - * @param digest The 32-byte SHA-256 digest. - * @param signature 64 bytes, r then s, each in range (the family's header has checked them). + * @param point_bytes The public key's uncompressed point, valid. + * @param digest_bytes The 32-byte SHA-256 digest. + * @param signature_bytes 64 bytes, r then s, each in range (the family's header has checked + * them). * @return Whether the signature verifies. */ - [[nodiscard]] static bool verify(std::span point, - std::span digest, - std::span signature) noexcept { + [[nodiscard]] static bool verify(std::span point_bytes, + std::span digest_bytes, + std::span signature_bytes) noexcept { WEBCPP_CRYPTO_DETAIL_P_CURVE_ENGINE_ENTERED(); read_canary(WEBCPP_CRYPTO_DETAIL_BEARSSL_CANARY); // BearSSL's struct holds a pointer to non-const bytes, which it only reads: a copy keeps // the key's own bytes const without a cast. std::array key_point{}; - std::ranges::copy(point, key_point.begin()); - br_ec_public_key const key{ + std::ranges::copy(point_bytes, key_point.begin()); + br_ec_public_key const bearssl_key{ .curve = BR_EC_secp256r1, .q = key_point.data(), .qlen = key_point.size(), }; - return br_ecdsa_i31_vrfy_raw(bearssl_p256(), digest.data(), digest.size(), &key, - signature.data(), signature.size()) == 1; + return br_ecdsa_i31_vrfy_raw(bearssl_p256(), digest_bytes.data(), digest_bytes.size(), + &bearssl_key, signature_bytes.data(), + signature_bytes.size()) == 1; } /** * Encodes a signature as strict DER. * - * @param signature 64 bytes, r then s, each in range (the family's header has checked them). - * @param output 72 bytes, room for the longest encoding. + * @param signature_bytes 64 bytes, r then s, each in range (the family's header has checked + * them). + * @param output_bytes 72 bytes, room for the longest encoding. * @return The encoding's length, at most 72: 2 + 2 * (2 + 33). */ - [[nodiscard]] static std::size_t to_der(std::span signature, - std::span output) noexcept { + [[nodiscard]] static std::size_t to_der(std::span signature_bytes, + std::span output_bytes) noexcept { WEBCPP_CRYPTO_DETAIL_P_CURVE_ENGINE_ENTERED(); read_canary(WEBCPP_CRYPTO_DETAIL_BEARSSL_CANARY); // In place, and "by no more than 9 bytes" larger (bearssl_ec.h): room for 64 + 9. - std::array work{}; - std::ranges::copy(signature, work.begin()); - std::size_t const length = br_ecdsa_raw_to_asn1(work.data(), signature.size()); - std::ranges::copy(std::span(work).first(length), output.begin()); - return length; + std::array work_bytes{}; + std::ranges::copy(signature_bytes, work_bytes.begin()); + std::size_t const der_length = + br_ecdsa_raw_to_asn1(work_bytes.data(), signature_bytes.size()); + std::ranges::copy(std::span(work_bytes).first(der_length), + output_bytes.begin()); + return der_length; } /** * Decodes a strict DER signature: BearSSL's decoder, then the re-encoding compared with the * input, since BearSSL accepts a few forms strict DER refuses. * - * @param der The encoding, not empty. - * @param output 64 bytes, r then s, padded to 32 bytes each; the caller keeps them only on - * success and checks their range. + * @param der_bytes The encoding, not empty. + * @param output_bytes 64 bytes, r then s, padded to 32 bytes each; the caller keeps them only + * on success and checks their range. * @return Whether the input is strict DER of two integers of at most 32 bytes. */ - [[nodiscard]] static bool from_der(std::span der, - std::span output) noexcept { + [[nodiscard]] static bool from_der(std::span der_bytes, + std::span output_bytes) noexcept { WEBCPP_CRYPTO_DETAIL_P_CURVE_ENGINE_ENTERED(); read_canary(WEBCPP_CRYPTO_DETAIL_BEARSSL_CANARY); - constexpr std::size_t longest = 72; - if (der.size() > longest) { + constexpr std::size_t longest_der = 72; + if (der_bytes.size() > longest_der) { return false; } // In place, and up to twice the source's length (bearssl_ec.h): room for 2 * 72. - std::array work{}; - std::ranges::copy(der, work.begin()); + std::array work_bytes{}; + std::ranges::copy(der_bytes, work_bytes.begin()); // BearSSL strips the integers' leading zeros and writes r and s at the longer one's // length (ecdsa_atr.c), so a raw form shorter than 64 bytes is padded back to 32 each. - std::size_t const raw_size = br_ecdsa_asn1_to_raw(work.data(), der.size()); - std::size_t const half = raw_size / 2; - if (raw_size == 0 || half > 32) { + std::size_t const raw_size = br_ecdsa_asn1_to_raw(work_bytes.data(), der_bytes.size()); + std::size_t const half_size = raw_size / 2; + if (raw_size == 0 || half_size > 32) { return false; } - std::array raw{}; - std::ranges::copy(std::span(work).first(half), - raw.begin() + static_cast(32 - half)); - std::ranges::copy(std::span(work).subspan(half, half), - raw.begin() + static_cast(64 - half)); - std::ranges::copy(std::span(raw).first<64>(), output.begin()); + std::array raw_signature{}; + std::ranges::copy(std::span(work_bytes).first(half_size), + raw_signature.begin() + static_cast(32 - half_size)); + std::ranges::copy(std::span(work_bytes).subspan(half_size, half_size), + raw_signature.begin() + static_cast(64 - half_size)); + std::ranges::copy(std::span(raw_signature).first<64>(), + output_bytes.begin()); // BearSSL's decoder accepts a long SEQUENCE length, needless zero bytes and a negative // integer; strict DER is what re-encodes to the same bytes (design D12). - std::size_t const length = br_ecdsa_raw_to_asn1(raw.data(), 64); - return length == der.size() && - std::ranges::equal(std::span(raw).first(length), der); + std::size_t const der_length = br_ecdsa_raw_to_asn1(raw_signature.data(), 64); + return der_length == der_bytes.size() && + std::ranges::equal(std::span(raw_signature).first(der_length), + der_bytes); } /** * Copies the public point; no BearSSL call. * - * @param keyed A keyed state. - * @param output 65 bytes. + * @param keyed_state A keyed state. + * @param output_bytes 65 bytes. */ - static void public_point(state const& keyed, std::span output) noexcept { - std::ranges::copy(keyed.point, output.begin()); + static void public_point(state const& keyed_state, + std::span output_bytes) noexcept { + std::ranges::copy(keyed_state.point, output_bytes.begin()); } /** * Copies the secret scalar; no BearSSL call. * - * @param keyed A keyed state. - * @param output 32 bytes, a `secret<32>`'s. + * @param keyed_state A keyed state. + * @param output_bytes 32 bytes, a `secret<32>`'s. */ - static void scalar(state const& keyed, std::span output) noexcept { - std::ranges::copy(keyed.scalar, output.begin()); + static void scalar(state const& keyed_state, + std::span output_bytes) noexcept { + std::ranges::copy(keyed_state.scalar, output_bytes.begin()); } /** * Wipes the scalar and the point; the state is empty. * - * @param keyed Any state. + * @param keyed_state Any state. */ - static void reset(state& keyed) noexcept { - wipe_object(keyed.scalar); - wipe_object(keyed.point); + static void reset(state& keyed_state) noexcept { + wipe_object(keyed_state.scalar); + wipe_object(keyed_state.point); } }; @@ -673,7 +683,7 @@ struct block_state {}; /** * BearSSL's refusal of the block cipher. The assertions sit in member - * templates, which only `make`, `encrypt` and `decrypt` instantiate: the class's moves and + * templates, which only `from_key`, `encrypt` and `decrypt` instantiate: the class's moves and * destructor, which `ciphers::gcm>` needs, never fire them. */ template diff --git a/include/webcpp/crypto/backends/openssl.hpp b/include/webcpp/crypto/backends/openssl.hpp index 758ab230..59b7f578 100644 --- a/include/webcpp/crypto/backends/openssl.hpp +++ b/include/webcpp/crypto/backends/openssl.hpp @@ -8,7 +8,7 @@ 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 `make` allocates through OpenSSL's own + `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. @@ -82,12 +82,12 @@ namespace webcpp::crypto { * two threads at once: OpenSSL frees through it after `main` returns. * * It must serve OpenSSL's initialisation, which the first use of OpenSSL in the process runs, - * usually the first `make`: on an OpenSSL built with threads, which MSVC always builds, a + * usually the first `from_key`: on an OpenSSL built with threads, which MSVC always builds, a * resource that fails during OpenSSL's base initialisation makes OpenSSL re-enter it, and that * call never returns: the process aborts on macOS, deadlocks on Linux and spins on Windows. Only on - * an OpenSSL built without threads does it return, and every `make` then gives `backend_failure`. - * On Windows a thread that used OpenSSL keeps its blocks in the resource until the process ends - * unless it calls `OPENSSL_thread_stop()` before it ends. + * an OpenSSL built without threads does it return, and every `from_key` then gives + * `backend_failure`. On Windows a thread that used OpenSSL keeps its blocks in the resource until + * the process ends unless it calls `OPENSSL_thread_stop()` before it ends. * * A resource that cannot allocate fails as the standard has `do_allocate` fail, by throwing, * never by returning null: libc++ and libstdc++ declare `allocate` never to return null, so an @@ -115,32 +115,32 @@ inline constexpr std::size_t openssl_block_alignment = // The adapter: three C functions given to OpenSSL, with C linkage since OpenSSL calls // them as C, inline with external linkage so that every file of the program sees one -// function, which the install and make recognise by its address. +// function, which the install and from_key recognise by its address. extern "C" { /** * OpenSSL's `malloc` under the option: a block of the program's resource, after a header * that holds its size. * - * @param size The bytes OpenSSL asks for; 0, or a size whose header overflows, gives null. + * @param byte_count The bytes OpenSSL asks for; 0, or a size whose header overflows, gives null. * @return The block, or null, which OpenSSL takes as a failure: for those sizes, and with * exceptions for a resource that throws. */ -inline void* webcpp_crypto_openssl_malloc(std::size_t size, char const* /*file*/, +inline void* webcpp_crypto_openssl_malloc(std::size_t byte_count, char const* /*file*/, int /*line*/) noexcept { - constexpr std::size_t header = webcpp::crypto::detail::openssl_block_alignment; + constexpr std::size_t header_size = webcpp::crypto::detail::openssl_block_alignment; // NOLINTNEXTLINE(readability-redundant-parentheses) - if (size == 0 || size > (std::numeric_limits::max)() - header) { + if (byte_count == 0 || byte_count > (std::numeric_limits::max)() - header_size) { return nullptr; } #ifndef WEBCPP_CRYPTO_NO_EXCEPTIONS try { #endif // Never null: a resource fails by throwing (openssl_memory_resource()). - void* const block = - webcpp::crypto::openssl_memory_resource().allocate(header + size, header); - std::memcpy(block, &size, sizeof size); - return static_cast(block) + header; + void* const raw_block = webcpp::crypto::openssl_memory_resource().allocate( + header_size + byte_count, header_size); + std::memcpy(raw_block, &byte_count, sizeof byte_count); + return static_cast(raw_block) + header_size; #ifndef WEBCPP_CRYPTO_NO_EXCEPTIONS } catch (...) { // OpenSSL is C: no exception may cross it return nullptr; @@ -151,20 +151,22 @@ inline void* webcpp_crypto_openssl_malloc(std::size_t size, char const* /*file*/ /** * OpenSSL's `free` under the option: the block back to the program's resource. * - * @param address A block of the adapter's, or null. + * @param block_address A block of the adapter's, or null. */ -inline void webcpp_crypto_openssl_free(void* address, char const* /*file*/, int /*line*/) noexcept { - if (address == nullptr) { +inline void webcpp_crypto_openssl_free(void* block_address, char const* /*file*/, + int /*line*/) noexcept { + if (block_address == nullptr) { return; } - constexpr std::size_t header = webcpp::crypto::detail::openssl_block_alignment; - auto* const block = static_cast(address) - header; - std::size_t size = 0; - std::memcpy(&size, block, sizeof size); + constexpr std::size_t header_size = webcpp::crypto::detail::openssl_block_alignment; + auto* const raw_block = static_cast(block_address) - header_size; + std::size_t byte_count = 0; + std::memcpy(&byte_count, raw_block, sizeof byte_count); #ifndef WEBCPP_CRYPTO_NO_EXCEPTIONS try { #endif - webcpp::crypto::openssl_memory_resource().deallocate(block, header + size, header); + webcpp::crypto::openssl_memory_resource().deallocate(raw_block, header_size + byte_count, + header_size); #ifndef WEBCPP_CRYPTO_NO_EXCEPTIONS // NOLINTNEXTLINE(bugprone-empty-catch): no exception may cross OpenSSL } catch (...) { @@ -176,29 +178,30 @@ inline void webcpp_crypto_openssl_free(void* address, char const* /*file*/, int * OpenSSL's `realloc` under the option, as C's: null is `malloc`, 0 frees and gives null, * and a failure gives null and leaves the old block valid. * - * @param address The block, or null. - * @param size The new size. + * @param block_address The block, or null. + * @param byte_count The new size. * @return The new block, or null. */ -inline void* webcpp_crypto_openssl_realloc(void* address, std::size_t size, char const* file, - int line) noexcept { - if (address == nullptr) { - return webcpp_crypto_openssl_malloc(size, file, line); +inline void* webcpp_crypto_openssl_realloc(void* block_address, std::size_t byte_count, + char const* source_file, int source_line) noexcept { + if (block_address == nullptr) { + return webcpp_crypto_openssl_malloc(byte_count, source_file, source_line); } - if (size == 0) { - webcpp_crypto_openssl_free(address, file, line); + if (byte_count == 0) { + webcpp_crypto_openssl_free(block_address, source_file, source_line); return nullptr; } - void* const moved = webcpp_crypto_openssl_malloc(size, file, line); - if (moved == nullptr) { + void* const moved_block = webcpp_crypto_openssl_malloc(byte_count, source_file, source_line); + if (moved_block == nullptr) { return nullptr; } - constexpr std::size_t header = webcpp::crypto::detail::openssl_block_alignment; - std::size_t old = 0; - std::memcpy(&old, static_cast(address) - header, sizeof old); - std::memcpy(moved, address, (std::min)(old, size)); - webcpp_crypto_openssl_free(address, file, line); - return moved; + constexpr std::size_t header_size = webcpp::crypto::detail::openssl_block_alignment; + std::size_t old_size = 0; + std::memcpy(&old_size, static_cast(block_address) - header_size, + sizeof old_size); + std::memcpy(moved_block, block_address, (std::min)(old_size, byte_count)); + webcpp_crypto_openssl_free(block_address, source_file, source_line); + return moved_block; } } // extern "C" @@ -207,12 +210,13 @@ namespace webcpp::crypto::detail { /** Whether OpenSSL's functions are the adapter's: three loads, no call into OpenSSL's heap. */ inline bool openssl_adapter_installed() noexcept { - CRYPTO_malloc_fn m = nullptr; - CRYPTO_realloc_fn r = nullptr; - CRYPTO_free_fn f = nullptr; - CRYPTO_get_mem_functions(&m, &r, &f); - return m == &webcpp_crypto_openssl_malloc && r == &webcpp_crypto_openssl_realloc && - f == &webcpp_crypto_openssl_free; + CRYPTO_malloc_fn malloc_function = nullptr; + CRYPTO_realloc_fn realloc_function = nullptr; + CRYPTO_free_fn free_function = nullptr; + CRYPTO_get_mem_functions(&malloc_function, &realloc_function, &free_function); + return malloc_function == &webcpp_crypto_openssl_malloc && + realloc_function == &webcpp_crypto_openssl_realloc && + free_function == &webcpp_crypto_openssl_free; } /** @@ -221,11 +225,12 @@ inline bool openssl_adapter_installed() noexcept { * webcpp never builds, is refused by this comparison. */ inline bool openssl_defaults_installed() noexcept { - CRYPTO_malloc_fn m = nullptr; - CRYPTO_realloc_fn r = nullptr; - CRYPTO_free_fn f = nullptr; - CRYPTO_get_mem_functions(&m, &r, &f); - return m == &CRYPTO_malloc && r == &CRYPTO_realloc && f == &CRYPTO_free; + CRYPTO_malloc_fn malloc_function = nullptr; + CRYPTO_realloc_fn realloc_function = nullptr; + CRYPTO_free_fn free_function = nullptr; + CRYPTO_get_mem_functions(&malloc_function, &realloc_function, &free_function); + return malloc_function == &CRYPTO_malloc && realloc_function == &CRYPTO_realloc && + free_function == &CRYPTO_free; } } // namespace webcpp::crypto::detail @@ -241,7 +246,7 @@ inline bool openssl_defaults_installed() noexcept { namespace webcpp::crypto::detail { /** - * The check every OpenSSL `make` runs first, before any call into OpenSSL that allocates: + * 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. * @@ -271,10 +276,10 @@ struct openssl { * OpenSSL's in the process goes to `openssl_memory_resource()`. * * Called as the first statement of `main`, before any thread starts and anything uses - * OpenSSL. The first use of OpenSSL after it, usually the first `make`, runs OpenSSL's + * OpenSSL. The first use of OpenSSL after it, usually the first `from_key`, runs OpenSSL's * initialisation through the resource: on an OpenSSL built with threads (MSVC's only build) * a failure during its base initialisation makes that call never return; on one built - * without threads every `make` then gives `backend_failure`. + * without threads every `from_key` then gives `backend_failure`. * * @return Nothing, also when the adapter is installed already; * `memory_functions_refused` when another party installed its own functions, or OpenSSL @@ -348,8 +353,8 @@ inline boost::system::error_code openssl_context(EVP_CIPHER_CTX*& made_context, char const* cipher_name, std::span key_bytes, bool is_encrypting, bool use_padding) noexcept { - if (auto const guard = openssl_memory_guard(); !guard) { - return guard.error(); + if (auto const memory_guard = openssl_memory_guard(); !memory_guard) { + return memory_guard.error(); } ERR_set_mark(); EVP_CIPHER* const fetched_cipher = EVP_CIPHER_fetch(nullptr, cipher_name, nullptr); @@ -435,27 +440,27 @@ struct gcm_engine { // Each message re-initialises the context with a null key, which keeps the expanded one, // and switches its direction. - /** Starts a message: its direction, its IV and its additional data. */ + /** Starts a message: its direction, its nonce and its associated data. */ [[nodiscard]] static boost::system::result start( - state& engine_state, bool is_sealing, std::span iv_bytes, - std::span additional_data_bytes) noexcept { + state& engine_state, bool is_sealing, std::span nonce_bytes, + std::span associated_data_bytes) noexcept { int const cipher_direction = is_sealing ? 1 : 0; if (EVP_CipherInit_ex(engine_state.context, nullptr, nullptr, nullptr, nullptr, cipher_direction) != 1 || EVP_CIPHER_CTX_ctrl(engine_state.context, EVP_CTRL_GCM_SET_IVLEN, - static_cast(iv_bytes.size()), nullptr) != 1 || - EVP_CipherInit_ex(engine_state.context, nullptr, nullptr, nullptr, iv_bytes.data(), + static_cast(nonce_bytes.size()), nullptr) != 1 || + EVP_CipherInit_ex(engine_state.context, nullptr, nullptr, nullptr, nonce_bytes.data(), cipher_direction) != 1) { return openssl_failed(); } // A null output makes EVP_CipherUpdate take additional data; none is fed as no call. - for (std::size_t piece_start = 0; piece_start < additional_data_bytes.size(); + for (std::size_t piece_start = 0; piece_start < associated_data_bytes.size(); piece_start += openssl_piece) { std::size_t const piece_size = - (std::min)(openssl_piece, additional_data_bytes.size() - piece_start); + (std::min)(openssl_piece, associated_data_bytes.size() - piece_start); int written_count = 0; if (EVP_CipherUpdate(engine_state.context, nullptr, &written_count, - additional_data_bytes.data() + piece_start, + associated_data_bytes.data() + piece_start, static_cast(piece_size)) != 1) { return openssl_failed(); } @@ -519,13 +524,13 @@ struct gcm_engine { // every failure of a message does (openssl_failed). /** Ends a message without its tag, leaving nothing of it in the context. */ static void abandon(state& engine_state) noexcept { - std::array const zero_iv_bytes{}; + std::array const zero_nonce_bytes{}; std::array padding_byte{}; int written_count = 0; if (EVP_CipherInit_ex(engine_state.context, nullptr, nullptr, nullptr, nullptr, 1) != 1 || EVP_CIPHER_CTX_ctrl(engine_state.context, EVP_CTRL_GCM_SET_IVLEN, 12, nullptr) != 1 || - EVP_CipherInit_ex(engine_state.context, nullptr, nullptr, nullptr, zero_iv_bytes.data(), - 1) != 1 || + EVP_CipherInit_ex(engine_state.context, nullptr, nullptr, nullptr, + zero_nonce_bytes.data(), 1) != 1 || EVP_CipherUpdate(engine_state.context, padding_byte.data(), &written_count, padding_byte.data(), 1) != 1) { ERR_clear_error(); // as openssl_failed does for every failure of a message @@ -598,26 +603,27 @@ struct aead_engine { * Encrypts `data_bytes` in place and gives the tag. * * @param engine_state A keyed state. - * @param iv_bytes 12 bytes. - * @param additional_data_bytes Authenticated, not encrypted. + * @param nonce_bytes 12 bytes. + * @param associated_data_bytes Authenticated, not encrypted. * @param data_bytes The message. * @param tag_bytes The tag. * @return Nothing; `backend_failure`. */ [[nodiscard]] static boost::system::result seal( - state& engine_state, std::span iv_bytes, - std::span additional_data_bytes, std::span data_bytes, + state& engine_state, std::span nonce_bytes, + std::span associated_data_bytes, std::span data_bytes, boost::hash2::digest<16>& tag_bytes) noexcept { - sequence::state view{engine_state.context}; - auto const started = sequence::start(view, true, iv_bytes, additional_data_bytes); - if (!started) { - return started; + sequence::state sequence_view{engine_state.context}; + auto const start_result = + sequence::start(sequence_view, true, nonce_bytes, associated_data_bytes); + if (!start_result) { + return start_result; } - auto const ran = sequence::run(view, data_bytes); - if (!ran) { - return ran; + auto const run_result = sequence::run(sequence_view, data_bytes); + if (!run_result) { + return run_result; } - return sequence::tag(view, tag_bytes); + return sequence::tag(sequence_view, tag_bytes); } /** @@ -625,28 +631,29 @@ struct aead_engine { * match. * * @param engine_state A keyed state. - * @param iv_bytes 12 bytes. - * @param additional_data_bytes The additional data of the seal. + * @param nonce_bytes 12 bytes. + * @param associated_data_bytes The associated data of the seal. * @param data_bytes The ciphertext. * @param tag_bytes The expected tag. * @return Nothing; `authentication_failed`; `backend_failure`. */ [[nodiscard]] static boost::system::result open( - state& engine_state, std::span iv_bytes, - std::span additional_data_bytes, std::span data_bytes, + state& engine_state, std::span nonce_bytes, + std::span associated_data_bytes, std::span data_bytes, std::array const& tag_bytes) noexcept { - sequence::state view{engine_state.context}; - auto const started = sequence::start(view, false, iv_bytes, additional_data_bytes); - if (!started) { - return started; + sequence::state sequence_view{engine_state.context}; + auto const start_result = + sequence::start(sequence_view, false, nonce_bytes, associated_data_bytes); + if (!start_result) { + return start_result; } - auto const ran = sequence::run(view, data_bytes); - if (!ran) { - return ran; + auto const run_result = sequence::run(sequence_view, data_bytes); + if (!run_result) { + return run_result; } // GCM's check sets the 16-byte tag before the final, without which the provider would // compare 0 bytes (see the class's comment). - return sequence::check(view, tag_bytes); + return sequence::check(sequence_view, tag_bytes); } /** Moves the context, leaving the source empty. */ diff --git a/include/webcpp/crypto/backends/sodium.hpp b/include/webcpp/crypto/backends/sodium.hpp index 793c1e4f..592cb272 100644 --- a/include/webcpp/crypto/backends/sodium.hpp +++ b/include/webcpp/crypto/backends/sodium.hpp @@ -34,6 +34,7 @@ #include #include #include +#include #include #include @@ -42,6 +43,17 @@ #include #include +#ifdef __EMSCRIPTEN__ // crypto's entropy, libsodium's generator there +#include + +#include + +#include +#include +#include +#include +#endif + /** The canary's name, which every libsodium function of webcpp::crypto reads. */ #define WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY \ WEBCPP_CRYPTO_DETAIL_CANARY(sodium, WEBCPP_CRYPTO_SODIUM_COMMIT, portable) @@ -58,7 +70,16 @@ extern "C" constinit const char WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY; namespace webcpp::crypto::backends { -/** The backend libsodium (design D7). */ +/** + * The backend libsodium (design D7). + * + * On Emscripten libsodium draws from crypto's entropy, `crypto.getRandomValues`. Until crypto + * has initialised libsodium, every function on libsodium first draws a few bytes from it, and + * returns `entropy_unavailable` when the draw fails, or `errc::not_supported` where there is no + * generator at all, libsodium then left uninitialised for the next call; a function that draws + * nothing (a signature, a key pair from its secret) then runs whatever the generator does. A sealed + * box returns the same errors whenever its ephemeral key cannot be drawn. + */ struct sodium { /** The backend's name, which the examples print. */ static constexpr std::string_view name = "sodium"; @@ -68,17 +89,206 @@ struct sodium { namespace webcpp::crypto::detail { +#ifdef __EMSCRIPTEN__ +// On Emscripten libsodium draws through its own JavaScript (randombytes.c): its stir, which +// sodium_init runs, throws "No secure random number generator found" when +// crypto.getRandomValues and node's randomBytes throw, and the throw unwinds through +// WebAssembly. crypto installs its own implementation instead, before the first sodium_init, +// which reads crypto's entropy (detail/entropy.hpp). Its buf returns void, so a failed draw is +// reported through the watch's state. + +/** The state of the watches of one thread. */ +struct sodium_draw_state { + /** How many calls crypto observes are running: the depth of the watches. */ + int watched_depth = 0; + /** + * The error of a draw that failed inside the innermost watch that is running, or none: + * `entropy_unavailable`, or `errc::not_supported` where there is no generator at all. + */ + boost::system::error_code draw_error{}; +}; + +/** + * The state of this thread's watches, constant-initialised. + * + * @return This thread's state. + */ +[[nodiscard]] inline sodium_draw_state& sodium_draws() noexcept { + thread_local sodium_draw_state thread_state; + return thread_state; +} + +/** + * Watches the libsodium draws of one call crypto makes: while it lives, a failed draw is recorded + * rather than fatal. A watch inside another keeps the outer one's failure. + */ +class sodium_draw_watch { +public: + /** Starts watching, with no failure seen yet. */ + sodium_draw_watch() noexcept : state_(&sodium_draws()), outer_error_(state_->draw_error) { + ++state_->watched_depth; + state_->draw_error = {}; + } + + sodium_draw_watch(sodium_draw_watch const&) = delete; + sodium_draw_watch& operator=(sodium_draw_watch const&) = delete; + sodium_draw_watch(sodium_draw_watch&&) = delete; + sodium_draw_watch& operator=(sodium_draw_watch&&) = delete; + + /** Stops watching; an outer watch still sees its own failure, and this one's. */ + ~sodium_draw_watch() { + --state_->watched_depth; + if (outer_error_) { + state_->draw_error = outer_error_; + } + } + + /** + * The error of a draw that failed since the watch started. + * + * @return The source's error, or none. + */ + [[nodiscard]] boost::system::error_code draw_error() const noexcept { + return state_->draw_error; + } + +private: + sodium_draw_state* state_; + boost::system::error_code outer_error_; +}; + +/** + * Fills `output_data` from crypto's entropy: libsodium's `randombytes_buf`. When the draw fails + * the bytes are zeroed; inside a watched call the failure is recorded for its caller, outside one + * no caller could see it, so it ends the program through `sodium_misuse`, libsodium's own + * reaction to a draw that cannot be made, rather than hand zeros on. + * + * @param output_data Where to write. + * @param byte_count How many bytes. + */ +inline void sodium_entropy_buf(void* const output_data, std::size_t const byte_count) noexcept { + auto const drawn = fill_from_system({static_cast(output_data), byte_count}); + if (!drawn) { + sodium_draw_state& thread_state = sodium_draws(); + if (thread_state.watched_depth == 0) { + sodium_misuse(); + } + thread_state.draw_error = drawn.error(); + } +} + +/** + * libsodium's `randombytes_random`, which draws 4 bytes through @ref sodium_entropy_buf; their + * copy on the stack is wiped before it returns. + * + * @return The bytes, read in the machine's order. + */ +inline std::uint32_t sodium_entropy_random() noexcept { + std::array drawn_bytes{}; + sodium_entropy_buf(drawn_bytes.data(), drawn_bytes.size()); + auto const drawn_value = std::bit_cast(drawn_bytes); + wipe_object(drawn_bytes); + return drawn_value; +} + +/** Does nothing: crypto's entropy has no state to stir. libsodium's `randombytes_stir`. */ +inline void sodium_entropy_stir() noexcept {} + +/** + * The implementation's name, libsodium's `randombytes_implementation_name`. + * + * @return "webcpp-crypto". + */ +inline char const* sodium_entropy_name() noexcept { + return "webcpp-crypto"; +} + +/** + * crypto's entropy as libsodium's generator. `uniform` and `close` are null: libsodium derives + * `randombytes_uniform` from `random`, and there is nothing to close. + * + * Tip: no call crypto watches reaches `randombytes_uniform` (crypto_box_seal and sodium_init + * draw through `buf` alone). libsodium's derived `uniform` draws until a value is not below + * 2^32 mod its bound, so inside a watch, where a failed draw returns 0, it would loop for as long + * as draws fail; outside one, the first failed draw ends the program before it loops. + */ +inline randombytes_implementation const sodium_entropy{ + .implementation_name = &sodium_entropy_name, + .random = &sodium_entropy_random, + .stir = &sodium_entropy_stir, + .uniform = nullptr, + .buf = &sodium_entropy_buf, + .close = nullptr, +}; +#else +/** + * Off Emscripten libsodium draws from the system's generator itself, which ends the program when + * it cannot: a watch sees no failure. No thread-local state either, whose first access on a + * thread allocates on some platforms (macOS). + */ +class sodium_draw_watch { +public: + /** + * The error of a draw that failed since the watch started. + * + * @return None. + */ + [[nodiscard]] boost::system::error_code draw_error() const noexcept { return draw_error_; } + +private: + boost::system::error_code draw_error_{}; +}; +#endif + /** Reads libsodium's canary and initialises libsodium, which every engine calls first. `sodium_init` is idempotent and takes libsodium's own lock; its state is libsodium's. - @return Nothing; `backend_failure` when `sodium_init` returns -1. + On Emscripten, it first installs crypto's entropy as libsodium's generator, once. Then, until + crypto has seen `sodium_init` succeed, it probes crypto's entropy with a small draw and, when + the probe fails, returns its error without calling `sodium_init`: libsodium stays uninitialised + and the next call tries again, so that libsodium never keeps a zero canary for the program's own + `sodium_malloc` allocations (`sodium_init` draws that canary). In the narrow case where the probe + succeeds and the canary's draw then fails, the watch around `sodium_init` returns that draw's + error; libsodium is then initialised with a zero canary. + + @return Nothing; `backend_failure` when `sodium_init` returns -1; on Emscripten, + `entropy_unavailable`, or `errc::not_supported` where there is no generator, when the probe or + `sodium_init`'s draw failed. */ [[nodiscard]] inline boost::system::result sodium_ready() noexcept { read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); +#ifdef __EMSCRIPTEN__ + // Before the first sodium_init, whose stir would otherwise run libsodium's JavaScript; a + // once_flag is constant-initialised, and a second thread waits until the first has set it. + // Inside noexcept: libc++'s call_once throws only what its callable throws (it reports no + // error of its own lock), and the callable, a C function that stores a pointer, throws + // nothing. + static std::once_flag installed_once; + std::call_once(installed_once, + [] { static_cast(randombytes_set_implementation(&sodium_entropy)); }); + // Whether crypto has seen sodium_init succeed, after which no probe is needed: a call that + // draws nothing (a signature, a key pair from its secret) then runs whatever the source does. + static std::atomic initialised_seen{false}; + if (!initialised_seen.load(std::memory_order_acquire)) { + std::array probe_bytes{}; + auto const probed = fill_from_system(probe_bytes); + wipe_object(probe_bytes); + if (!probed) { + return probed.error(); + } + } +#endif + sodium_draw_watch const init_draws; if (sodium_init() < 0) { return error::backend_failure; } + if (auto const init_error = init_draws.draw_error()) { + return init_error; + } +#ifdef __EMSCRIPTEN__ + initialised_seen.store(true, std::memory_order_release); +#endif return {}; } @@ -87,15 +297,15 @@ namespace webcpp::crypto::detail { match or an all-zero shared secret, which webcpp reports and so branches on, here, where it is marked public for the constant-time checks (`WEBCPP_CRYPTO_DETAIL_DECLASSIFY`). - @param returned What the function returned: 0, or -1 when it refused. + @param returned_code What the function returned: 0, or -1 when it refused. @return Whether it refused. */ -[[nodiscard]] inline bool sodium_refused(int returned) noexcept { +[[nodiscard]] inline bool sodium_refused(int returned_code) noexcept { // Not const: the comparison reads it again after the mark (detail/declassify.hpp's tip). // NOLINTNEXTLINE(misc-const-correctness): see above - int verdict = returned; - WEBCPP_CRYPTO_DETAIL_DECLASSIFY(&verdict, sizeof verdict); - return verdict != 0; + int call_verdict = returned_code; + WEBCPP_CRYPTO_DETAIL_DECLASSIFY(&call_verdict, sizeof call_verdict); + return call_verdict != 0; } /** libsodium's detached functions of an AEAD family, which differ only by name. */ @@ -106,32 +316,32 @@ struct sodium_aead_calls; template <> struct sodium_aead_calls { /** Encrypts and computes the tag apart. */ - static constexpr auto encrypt = &crypto_aead_chacha20poly1305_ietf_encrypt_detached; + static constexpr auto encrypt_call = &crypto_aead_chacha20poly1305_ietf_encrypt_detached; /** Checks the tag apart, then decrypts. */ - static constexpr auto decrypt = &crypto_aead_chacha20poly1305_ietf_decrypt_detached; + static constexpr auto decrypt_call = &crypto_aead_chacha20poly1305_ietf_decrypt_detached; }; /** The original ChaCha20-Poly1305: libsodium's functions without a suffix. */ template <> struct sodium_aead_calls { /** Encrypts and computes the tag apart. */ - static constexpr auto encrypt = &crypto_aead_chacha20poly1305_encrypt_detached; + static constexpr auto encrypt_call = &crypto_aead_chacha20poly1305_encrypt_detached; /** Checks the tag apart, then decrypts. */ - static constexpr auto decrypt = &crypto_aead_chacha20poly1305_decrypt_detached; + static constexpr auto decrypt_call = &crypto_aead_chacha20poly1305_decrypt_detached; }; /** XChaCha20-Poly1305: libsodium's `xchacha20poly1305_ietf` functions. */ template <> struct sodium_aead_calls { /** Encrypts and computes the tag apart. */ - static constexpr auto encrypt = &crypto_aead_xchacha20poly1305_ietf_encrypt_detached; + static constexpr auto encrypt_call = &crypto_aead_xchacha20poly1305_ietf_encrypt_detached; /** Checks the tag apart, then decrypts. */ - static constexpr auto decrypt = &crypto_aead_xchacha20poly1305_ietf_decrypt_detached; + static constexpr auto decrypt_call = &crypto_aead_xchacha20poly1305_ietf_decrypt_detached; }; /** An AEAD's state on libsodium: the key, in the object, since libsodium takes it per call. */ template - requires requires { sodium_aead_calls::encrypt; } + requires requires { sodium_aead_calls::encrypt_call; } struct aead_state { /** The key. */ std::array key{}; @@ -143,7 +353,7 @@ struct aead_state { * does not match; `aead` zeroes it too. */ template - requires requires { sodium_aead_calls::encrypt; } + requires requires { sodium_aead_calls::encrypt_call; } struct aead_engine { /** The state. */ using state = aead_state; @@ -153,70 +363,73 @@ struct aead_engine { /** * Initialises libsodium and keeps the key. * - * @param s The state. - * @param key The key, 32 bytes (`aead` has checked its size). + * @param engine_state The state. + * @param key_bytes The key, 32 bytes (`aead` has checked its size). * @return Nothing; `backend_failure` when libsodium cannot start. */ [[nodiscard]] static boost::system::result init( - state& s, std::span key) noexcept { - auto const ready = sodium_ready(); - if (!ready) { - return ready; + state& engine_state, std::span key_bytes) noexcept { + auto const library_ready = sodium_ready(); + if (!library_ready) { + return library_ready; } - std::ranges::copy(key, s.key.begin()); + std::ranges::copy(key_bytes, engine_state.key.begin()); return {}; } /** - * Encrypts `data` in place and writes the tag; libsodium reads the nonce and the - * additional data before it writes a byte of the ciphertext. + * Encrypts `data_bytes` in place and writes the tag; libsodium reads the nonce and the + * associated data before it writes a byte of the ciphertext. * * @return Nothing; `backend_failure` when libsodium fails. */ [[nodiscard]] static boost::system::result seal( - state& s, std::span iv, std::span additional_data, - std::span data, boost::hash2::digest<16>& tag) noexcept { + state& engine_state, std::span nonce_bytes, + std::span associated_data, std::span data_bytes, + boost::hash2::digest<16>& tag_bytes) noexcept { read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); unsigned long long tag_length = 0; // libsodium encrypts in place when the output is the input (its documented contract); // an empty span's null data() is never read or written, since every stream of // ChaCha20 returns at once on no byte. - if (calls::encrypt(data.data(), tag.data(), &tag_length, data.data(), data.size(), - additional_data.data(), additional_data.size(), nullptr, iv.data(), - s.key.data()) != 0) { + if (calls::encrypt_call(data_bytes.data(), tag_bytes.data(), &tag_length, data_bytes.data(), + data_bytes.size(), associated_data.data(), associated_data.size(), + nullptr, nonce_bytes.data(), engine_state.key.data()) != 0) { return error::backend_failure; } return {}; } /** - * Checks the tag, then decrypts `data` in place. + * Checks the tag, then decrypts `data_bytes` in place. * * @return Nothing; `authentication_failed` when the tag does not match. */ [[nodiscard]] static boost::system::result open( - state& s, std::span iv, std::span additional_data, - std::span data, std::array const& tag) noexcept { + state& engine_state, std::span nonce_bytes, + std::span associated_data, std::span data_bytes, + std::array const& tag_bytes) noexcept { read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); // An empty span's null data() makes libsodium check the tag alone: its detached // decryptions return the verdict when the output is null, before clearing or decrypting // it. - if (sodium_refused(calls::decrypt(data.data(), nullptr, data.data(), data.size(), - tag.data(), additional_data.data(), - additional_data.size(), iv.data(), s.key.data()))) { + if (sodium_refused(calls::decrypt_call(data_bytes.data(), nullptr, data_bytes.data(), + data_bytes.size(), tag_bytes.data(), + associated_data.data(), associated_data.size(), + nonce_bytes.data(), engine_state.key.data()))) { return error::authentication_failed; } return {}; } /** Moves the key; the source is wiped. */ - static void move(state& to, state& from) noexcept { - to.key = from.key; - wipe_object(from.key); + static void move(state& target_state, state& source_state) noexcept { + target_state.key = source_state.key; + wipe_object(source_state.key); } /** Wipes the key. */ - static void reset(state& s) noexcept { wipe_object(s.key); } + static void reset(state& engine_state) noexcept { wipe_object(engine_state.key); } }; /** libsodium's detached functions of a secret box family, which differ only by name. */ @@ -227,41 +440,43 @@ struct sodium_secretbox_calls; template <> struct sodium_secretbox_calls { /** Encrypts and computes the tag apart. */ - static constexpr auto encrypt = &crypto_secretbox_detached; + static constexpr auto encrypt_call = &crypto_secretbox_detached; /** Checks the tag apart, then decrypts. */ - static constexpr auto decrypt = &crypto_secretbox_open_detached; + static constexpr auto decrypt_call = &crypto_secretbox_open_detached; }; /** `crypto_secretbox_xchacha20poly1305`. */ template <> struct sodium_secretbox_calls { /** Encrypts and computes the tag apart. */ - static constexpr auto encrypt = &crypto_secretbox_xchacha20poly1305_detached; + static constexpr auto encrypt_call = &crypto_secretbox_xchacha20poly1305_detached; /** Checks the tag apart, then decrypts. */ - static constexpr auto decrypt = &crypto_secretbox_xchacha20poly1305_open_detached; + static constexpr auto decrypt_call = &crypto_secretbox_xchacha20poly1305_open_detached; }; /** - * Seals `data` in place with a secret box's detached function under a 32-byte key. libsodium + * Seals `data_bytes` in place with a secret box's detached function under a 32-byte key. libsodium * reads the nonce again after it writes the first bytes of the ciphertext, so a nonce that - * lies in `data` is copied first; an empty span's null data() is never read or written. + * lies in `data_bytes` is copied first; an empty span's null data() is never read or written. * * @return Nothing; `backend_failure` when libsodium fails. */ template [[nodiscard]] boost::system::result sodium_secretbox_seal( - Encrypt encrypt, std::span key, std::span iv, - std::span data, boost::hash2::digest<16>& tag) noexcept { - std::array nonce{}; - std::ranges::copy(iv, nonce.begin()); - if (encrypt(data.data(), tag.data(), data.data(), data.size(), nonce.data(), key.data()) != 0) { + Encrypt encrypt_call, std::span key_bytes, + std::span nonce_bytes, std::span data_bytes, + boost::hash2::digest<16>& tag_bytes) noexcept { + std::array nonce_copy{}; + std::ranges::copy(nonce_bytes, nonce_copy.begin()); + if (encrypt_call(data_bytes.data(), tag_bytes.data(), data_bytes.data(), data_bytes.size(), + nonce_copy.data(), key_bytes.data()) != 0) { return error::backend_failure; } return {}; } /** - * Checks the tag, then decrypts `data` in place, with a secret box's detached function; the + * Checks the tag, then decrypts `data_bytes` in place, with a secret box's detached function; the * nonce is copied first, as `sodium_secretbox_seal` says. An empty span's null data() makes * libsodium check the tag alone. * @@ -269,12 +484,13 @@ template */ template [[nodiscard]] boost::system::result sodium_secretbox_open( - Decrypt decrypt, std::span key, std::span iv, - std::span data, std::array const& tag) noexcept { - std::array nonce{}; - std::ranges::copy(iv, nonce.begin()); - if (sodium_refused( - decrypt(data.data(), data.data(), tag.data(), data.size(), nonce.data(), key.data()))) { + Decrypt decrypt_call, std::span key_bytes, + std::span nonce_bytes, std::span data_bytes, + std::array const& tag_bytes) noexcept { + std::array nonce_copy{}; + std::ranges::copy(nonce_bytes, nonce_copy.begin()); + if (sodium_refused(decrypt_call(data_bytes.data(), data_bytes.data(), tag_bytes.data(), + data_bytes.size(), nonce_copy.data(), key_bytes.data()))) { return error::authentication_failed; } return {}; @@ -282,22 +498,22 @@ template /** A secret box's state on libsodium: the key, in the object, since libsodium takes it per call. */ template - requires requires { sodium_secretbox_calls::encrypt; } -struct aead_state { + requires requires { sodium_secretbox_calls::encrypt_call; } +struct secretbox_state { /** The key. */ std::array key{}; }; /** - * A secret box on libsodium, `crypto_secretbox` and its XChaCha20 twin, as an `aead` without - * additional data (`aead` has refused a non-empty one). libsodium's detached decryption checks - * the tag before it writes a byte; `aead` zeroes the data when it does not match. + * A secret box on libsodium, `crypto_secretbox` and its XChaCha20 twin, without associated data. + * libsodium's detached decryption checks the tag before it writes a byte; `basic_secretbox` + * zeroes the data when it does not match. */ template - requires requires { sodium_secretbox_calls::encrypt; } -struct aead_engine { + requires requires { sodium_secretbox_calls::encrypt_call; } +struct secretbox_engine { /** The state. */ - using state = aead_state; + using state = secretbox_state; /** libsodium's functions of the family. */ using calls = sodium_secretbox_calls; @@ -307,51 +523,52 @@ struct aead_engine { * @return Nothing; `backend_failure` when libsodium cannot start. */ [[nodiscard]] static boost::system::result init( - state& s, std::span key) noexcept { - auto const ready = sodium_ready(); - if (!ready) { - return ready; + state& engine_state, std::span key_bytes) noexcept { + auto const library_ready = sodium_ready(); + if (!library_ready) { + return library_ready; } - std::ranges::copy(key, s.key.begin()); + std::ranges::copy(key_bytes, engine_state.key.begin()); return {}; } /** - * Encrypts `data` in place and writes the tag. + * Encrypts `data_bytes` in place and writes the tag. * * @return Nothing; `backend_failure` when libsodium fails. */ [[nodiscard]] static boost::system::result seal( - state& s, std::span iv, - std::span /*additional_data*/, std::span data, - boost::hash2::digest<16>& tag) noexcept { + state& engine_state, std::span nonce_bytes, + std::span data_bytes, boost::hash2::digest<16>& tag_bytes) noexcept { read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); - return sodium_secretbox_seal(calls::encrypt, std::span(s.key), - iv.first<24>(), data, tag); + return sodium_secretbox_seal(calls::encrypt_call, + std::span(engine_state.key), + nonce_bytes, data_bytes, tag_bytes); } /** - * Checks the tag, then decrypts `data` in place. + * Checks the tag, then decrypts `data_bytes` in place. * * @return Nothing; `authentication_failed` when the tag does not match. */ [[nodiscard]] static boost::system::result open( - state& s, std::span iv, - std::span /*additional_data*/, std::span data, - std::array const& tag) noexcept { + state& engine_state, std::span nonce_bytes, + std::span data_bytes, + std::array const& tag_bytes) noexcept { read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); - return sodium_secretbox_open(calls::decrypt, std::span(s.key), - iv.first<24>(), data, tag); + return sodium_secretbox_open(calls::decrypt_call, + std::span(engine_state.key), + nonce_bytes, data_bytes, tag_bytes); } /** Moves the key; the source is wiped. */ - static void move(state& to, state& from) noexcept { - to.key = from.key; - wipe_object(from.key); + static void move(state& target_state, state& source_state) noexcept { + target_state.key = source_state.key; + wipe_object(source_state.key); } /** Wipes the key. */ - static void reset(state& s) noexcept { wipe_object(s.key); } + static void reset(state& engine_state) noexcept { wipe_object(engine_state.key); } }; } // namespace webcpp::crypto::detail @@ -362,7 +579,9 @@ struct aead_engine { // Ed25519 and Ed25519ph on libsodium, for a program that includes curves/ed25519.hpp, before // this header or after it: outside the guard above, so that curves/ed25519.hpp, which includes // this header last, gets them either way; a program that does not include it pays nothing. -#if defined(WEBCPP_CRYPTO_CURVES_ED25519_HPP) && defined(WEBCPP_CRYPTO_HAS_SODIUM) && \ +// curves/ed25519.hpp defines WEBCPP_CRYPTO_DETAIL_ED25519_DECLARED once its declarations are, +// since it includes curves/x25519.hpp, which may include this header, before them. +#if defined(WEBCPP_CRYPTO_DETAIL_ED25519_DECLARED) && defined(WEBCPP_CRYPTO_HAS_SODIUM) && \ !defined(WEBCPP_CRYPTO_BACKENDS_SODIUM_ED25519) /** Defined once libsodium's Ed25519 engines are. */ #define WEBCPP_CRYPTO_BACKENDS_SODIUM_ED25519 @@ -375,6 +594,30 @@ struct aead_engine { #include #include +// libsodium's internal Ed25519, which its Ed25519ph calls with `prehashed` 1 once its own SHA-512 +// state is final (crypto_sign/ed25519/sign_ed25519.c's crypto_sign_ed25519ph_final_create and +// _final_verify): declared with the signatures libsodium's private +// crypto_sign/ed25519/ref10/sign_ed25519_ref10.h gives them, since its public API cannot sign a +// digest the program already has (design D9, ruling P27). They link because webcpp builds libsodium +// from its sources, a static library, on every target; a libsodium that renamed them, or a prebuilt +// one that hid them, fails at the link, and RFC 8032's Ed25519ph vectors +// (test/ed25519ph_sodium_test.cpp) check what they compute. +extern "C" { +// libsodium's own names, which it reserves for itself and which no C++ name of webcpp's style +// spells: +// NOLINTBEGIN(bugprone-reserved-identifier,readability-identifier-naming) +int _crypto_sign_ed25519_detached(unsigned char* signature_bytes, + unsigned long long* signature_size, + unsigned char const* message_bytes, + unsigned long long message_size, unsigned char const* secret_key, + int prehashed_flag); +int _crypto_sign_ed25519_verify_detached(unsigned char const* signature_bytes, + unsigned char const* message_bytes, + unsigned long long message_size, + unsigned char const* public_key, int prehashed_flag); +// NOLINTEND(bugprone-reserved-identifier,readability-identifier-naming) +} + namespace webcpp::crypto::detail { /** What an Ed25519 key pair stores on libsodium. */ @@ -395,30 +638,33 @@ struct ed25519_engine { * * @return Nothing; `backend_failure`. */ - [[nodiscard]] static boost::system::result make( - state& keyed, std::span seed) noexcept { - auto const ready = sodium_ready(); - if (!ready) { - return ready; + [[nodiscard]] static boost::system::result seed_keypair( + state& keyed_state, std::span seed_bytes) noexcept { + auto const library_ready = sodium_ready(); + if (!library_ready) { + return library_ready; } std::array public_key{}; - if (crypto_sign_ed25519_seed_keypair(public_key.data(), keyed.secret_key.data(), - seed.data()) != 0) { + if (crypto_sign_ed25519_seed_keypair(public_key.data(), keyed_state.secret_key.data(), + seed_bytes.data()) != 0) { return error::backend_failure; } return {}; } /** The public key, the secret key's second half. */ - static void public_key(state const& keyed, std::span out) noexcept { + static void public_key(state const& keyed_state, + std::span output_bytes) noexcept { read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); - static_cast(crypto_sign_ed25519_sk_to_pk(out.data(), keyed.secret_key.data())); + static_cast( + crypto_sign_ed25519_sk_to_pk(output_bytes.data(), keyed_state.secret_key.data())); } /** The seed, the secret key's first half, `crypto_sign_ed25519_sk_to_seed`. */ - static void seed(state const& keyed, std::span out) noexcept { + static void seed(state const& keyed_state, std::span output_bytes) noexcept { read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); - static_cast(crypto_sign_ed25519_sk_to_seed(out.data(), keyed.secret_key.data())); + static_cast( + crypto_sign_ed25519_sk_to_seed(output_bytes.data(), keyed_state.secret_key.data())); } /** @@ -427,11 +673,12 @@ struct ed25519_engine { * @return Nothing; `backend_failure`. */ [[nodiscard]] static boost::system::result sign( - state const& keyed, std::span message, - std::span out) noexcept { + state const& keyed_state, std::span message_bytes, + std::span output_bytes) noexcept { read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); - if (crypto_sign_ed25519_detached(out.data(), nullptr, message.data(), message.size(), - keyed.secret_key.data()) != 0) { + if (crypto_sign_ed25519_detached(output_bytes.data(), nullptr, message_bytes.data(), + message_bytes.size(), + keyed_state.secret_key.data()) != 0) { return error::backend_failure; } return {}; @@ -443,14 +690,14 @@ struct ed25519_engine { * @return Nothing; `invalid_signature`; `backend_failure`. */ [[nodiscard]] static boost::system::result verify( - std::span public_key, std::span message, - std::span signature) noexcept { - auto const ready = sodium_ready(); - if (!ready) { - return ready; + std::span public_key, std::span message_bytes, + std::span signature_bytes) noexcept { + auto const library_ready = sodium_ready(); + if (!library_ready) { + return library_ready; } - if (crypto_sign_ed25519_verify_detached(signature.data(), message.data(), message.size(), - public_key.data()) != 0) { + if (crypto_sign_ed25519_verify_detached(signature_bytes.data(), message_bytes.data(), + message_bytes.size(), public_key.data()) != 0) { return error::invalid_signature; } return {}; @@ -462,9 +709,10 @@ struct ed25519_engine { * @return Nothing; `backend_failure`. */ [[nodiscard]] static boost::system::result x25519_secret( - state const& keyed, std::span out) noexcept { + state const& keyed_state, std::span output_bytes) noexcept { read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); - if (crypto_sign_ed25519_sk_to_curve25519(out.data(), keyed.secret_key.data()) != 0) { + if (crypto_sign_ed25519_sk_to_curve25519(output_bytes.data(), + keyed_state.secret_key.data()) != 0) { return error::backend_failure; } return {}; @@ -477,19 +725,20 @@ struct ed25519_engine { * @return Nothing; `invalid_public_key`; `backend_failure`. */ [[nodiscard]] static boost::system::result to_x25519_public( - std::span public_key, std::span out) noexcept { - auto const ready = sodium_ready(); - if (!ready) { - return ready; + std::span public_key, + std::span output_bytes) noexcept { + auto const library_ready = sodium_ready(); + if (!library_ready) { + return library_ready; } - if (crypto_sign_ed25519_pk_to_curve25519(out.data(), public_key.data()) != 0) { + if (crypto_sign_ed25519_pk_to_curve25519(output_bytes.data(), public_key.data()) != 0) { return error::invalid_public_key; } return {}; } /** Wipes the secret key. */ - static void reset(state& keyed) noexcept { wipe_object(keyed.secret_key); } + static void reset(state& keyed_state) noexcept { wipe_object(keyed_state.secret_key); } }; /** What an Ed25519ph signer stores on libsodium: the message's SHA-512 state. */ @@ -499,7 +748,10 @@ struct ed25519ph_state { crypto_sign_ed25519ph_state hashing{}; }; -/** Ed25519ph on libsodium, `crypto_sign_ed25519ph_*`. */ +/** + * Ed25519ph on libsodium: a message given in pieces through `crypto_sign_ed25519ph_*`, and a + * digest the program has through the internal Ed25519 those functions end in. + */ template <> struct ed25519ph_engine { /** The signer's state. */ @@ -510,21 +762,22 @@ struct ed25519ph_engine { * * @return Nothing; `backend_failure`. */ - [[nodiscard]] static boost::system::result begin(state& begun) noexcept { - auto const ready = sodium_ready(); - if (!ready) { - return ready; + [[nodiscard]] static boost::system::result begin(state& begun_state) noexcept { + auto const library_ready = sodium_ready(); + if (!library_ready) { + return library_ready; } - if (crypto_sign_ed25519ph_init(&begun.hashing) != 0) { + if (crypto_sign_ed25519ph_init(&begun_state.hashing) != 0) { return error::backend_failure; } return {}; } /** Adds a piece, `crypto_sign_ed25519ph_update`, which cannot fail. */ - static void update(state& begun, std::span piece) noexcept { + static void update(state& begun_state, std::span piece_bytes) noexcept { read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); - static_cast(crypto_sign_ed25519ph_update(&begun.hashing, piece.data(), piece.size())); + static_cast(crypto_sign_ed25519ph_update(&begun_state.hashing, piece_bytes.data(), + piece_bytes.size())); } /** @@ -533,11 +786,11 @@ struct ed25519ph_engine { * @return Nothing; `backend_failure`. */ [[nodiscard]] static boost::system::result sign( - state& begun, ed25519_state const& keyed, - std::span out) noexcept { + state& begun_state, ed25519_state const& keyed_state, + std::span output_bytes) noexcept { read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); - if (crypto_sign_ed25519ph_final_create(&begun.hashing, out.data(), nullptr, - keyed.secret_key.data()) != 0) { + if (crypto_sign_ed25519ph_final_create(&begun_state.hashing, output_bytes.data(), nullptr, + keyed_state.secret_key.data()) != 0) { return error::backend_failure; } return {}; @@ -549,18 +802,64 @@ struct ed25519ph_engine { * @return Nothing; `invalid_signature`. */ [[nodiscard]] static boost::system::result verify( - state& begun, std::span public_key, - std::span signature) noexcept { + state& begun_state, std::span public_key, + std::span signature_bytes) noexcept { read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); - if (crypto_sign_ed25519ph_final_verify(&begun.hashing, signature.data(), + if (crypto_sign_ed25519ph_final_verify(&begun_state.hashing, signature_bytes.data(), public_key.data()) != 0) { return error::invalid_signature; } return {}; } + /** + * Signs a message's SHA-512, Ed25519ph's digest, with a key pair: libsodium's internal + * `_crypto_sign_ed25519_detached` with `prehashed` 1, the call + * `crypto_sign_ed25519ph_final_create` makes with its state's digest (ruling P27; RFC 8032's + * Ed25519ph vectors guard this dependency on libsodium's internals). + * + * @return Nothing; `backend_failure`. + */ + [[nodiscard]] static boost::system::result sign_digest( + ed25519_state const& keyed_state, + std::span digest_bytes, + std::span output_bytes) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); + // libsodium's internal function (ruling P27); the RFC 8032 Ed25519ph vectors guard it. + if (_crypto_sign_ed25519_detached(output_bytes.data(), nullptr, digest_bytes.data(), + digest_bytes.size(), keyed_state.secret_key.data(), + 1) != 0) { + return error::backend_failure; + } + return {}; + } + + /** + * Verifies Ed25519ph's signature of a message's SHA-512, strictly: libsodium's internal + * `_crypto_sign_ed25519_verify_detached` with `prehashed` 1, the call + * `crypto_sign_ed25519ph_final_verify` makes with its state's digest (ruling P27; RFC 8032's + * Ed25519ph vectors guard this dependency on libsodium's internals). + * + * @return Nothing; `invalid_signature`; `backend_failure`. + */ + [[nodiscard]] static boost::system::result verify_digest( + std::span public_key, + std::span digest_bytes, + std::span signature_bytes) noexcept { + auto const library_ready = sodium_ready(); + if (!library_ready) { + return library_ready; + } + // libsodium's internal function (ruling P27); the RFC 8032 Ed25519ph vectors guard it. + if (_crypto_sign_ed25519_verify_detached(signature_bytes.data(), digest_bytes.data(), + digest_bytes.size(), public_key.data(), 1) != 0) { + return error::invalid_signature; + } + return {}; + } + /** Wipes the message's state. */ - static void reset(state& begun) noexcept { wipe_object(begun.hashing); } + static void reset(state& begun_state) noexcept { wipe_object(begun_state.hashing); } }; } // namespace webcpp::crypto::detail @@ -590,12 +889,13 @@ struct x25519_engine { * @return Nothing; `backend_failure`. */ [[nodiscard]] static boost::system::result base( - std::span secret_key, std::span out) noexcept { - auto const ready = sodium_ready(); - if (!ready) { - return ready; + std::span secret_key, + std::span output_bytes) noexcept { + auto const library_ready = sodium_ready(); + if (!library_ready) { + return library_ready; } - if (crypto_scalarmult_curve25519_base(out.data(), secret_key.data()) != 0) { + if (crypto_scalarmult_curve25519_base(output_bytes.data(), secret_key.data()) != 0) { return error::backend_failure; } return {}; @@ -610,12 +910,12 @@ struct x25519_engine { [[nodiscard]] static boost::system::result agree( std::span secret_key, std::span peer_public_key, - std::span out) noexcept { - auto const ready = sodium_ready(); - if (!ready) { - return ready; + std::span output_bytes) noexcept { + auto const library_ready = sodium_ready(); + if (!library_ready) { + return library_ready; } - if (sodium_refused(crypto_scalarmult_curve25519(out.data(), secret_key.data(), + if (sodium_refused(crypto_scalarmult_curve25519(output_bytes.data(), secret_key.data(), peer_public_key.data()))) { return error::weak_public_key; } @@ -627,9 +927,10 @@ struct x25519_engine { #endif // X25519 on libsodium -// The boxes on libsodium, for a program that includes hybrid/box.hpp, before this header or -// after it, as Ed25519's above. -#if defined(WEBCPP_CRYPTO_HYBRID_BOX_HPP) && defined(WEBCPP_CRYPTO_HAS_SODIUM) && \ +// The boxes on libsodium, for a program that includes public_key_encryption/box.hpp, before this +// header or after it: box.hpp defines WEBCPP_CRYPTO_DETAIL_BOX_DECLARED once its declarations +// are, since it includes curves/x25519.hpp, which may include this header, before them. +#if defined(WEBCPP_CRYPTO_DETAIL_BOX_DECLARED) && defined(WEBCPP_CRYPTO_HAS_SODIUM) && \ !defined(WEBCPP_CRYPTO_BACKENDS_SODIUM_BOX) /** Defined once libsodium's box engines are. */ #define WEBCPP_CRYPTO_BACKENDS_SODIUM_BOX @@ -653,27 +954,28 @@ struct sodium_box_calls; template <> struct sodium_box_calls { /** Agrees the key. */ - static constexpr auto beforenm = &crypto_box_beforenm; + static constexpr auto beforenm_call = &crypto_box_beforenm; /** Encrypts and computes the tag apart. */ - static constexpr auto encrypt = &crypto_box_detached_afternm; + static constexpr auto encrypt_call = &crypto_box_detached_afternm; /** Checks the tag apart, then decrypts. */ - static constexpr auto decrypt = &crypto_box_open_detached_afternm; + static constexpr auto decrypt_call = &crypto_box_open_detached_afternm; }; /** `crypto_box_curve25519xchacha20poly1305`, X25519-XChaCha20-Poly1305. */ template <> struct sodium_box_calls { /** Agrees the key. */ - static constexpr auto beforenm = &crypto_box_curve25519xchacha20poly1305_beforenm; + static constexpr auto beforenm_call = &crypto_box_curve25519xchacha20poly1305_beforenm; /** Encrypts and computes the tag apart. */ - static constexpr auto encrypt = &crypto_box_curve25519xchacha20poly1305_detached_afternm; + static constexpr auto encrypt_call = &crypto_box_curve25519xchacha20poly1305_detached_afternm; /** Checks the tag apart, then decrypts. */ - static constexpr auto decrypt = &crypto_box_curve25519xchacha20poly1305_open_detached_afternm; + static constexpr auto decrypt_call = + &crypto_box_curve25519xchacha20poly1305_open_detached_afternm; }; /** What a box stores on libsodium: the key `beforenm` agreed. */ template - requires requires { sodium_box_calls::beforenm; } + requires requires { sodium_box_calls::beforenm_call; } struct box_state { /** The agreed key. */ std::array key{}; @@ -681,7 +983,7 @@ struct box_state { /** A box on libsodium: `beforenm` once, then the `afternm` functions per message. */ template - requires requires { sodium_box_calls::beforenm; } + requires requires { sodium_box_calls::beforenm_call; } struct box_engine { /** The state. */ using state = box_state; @@ -695,64 +997,67 @@ struct box_engine { * @return Nothing; `weak_public_key`; `backend_failure` when libsodium cannot start. */ [[nodiscard]] static boost::system::result init( - state& s, std::span secret_key, + state& engine_state, std::span secret_key, std::span peer_public_key) noexcept { - auto const ready = sodium_ready(); - if (!ready) { - return ready; + auto const library_ready = sodium_ready(); + if (!library_ready) { + return library_ready; } - if (sodium_refused( - calls::beforenm(s.key.data(), peer_public_key.data(), secret_key.data()))) { - wipe_object(s.key); + if (sodium_refused(calls::beforenm_call(engine_state.key.data(), peer_public_key.data(), + secret_key.data()))) { + wipe_object(engine_state.key); return error::weak_public_key; } return {}; } /** - * Encrypts `data` in place and writes the tag. + * Encrypts `data_bytes` in place and writes the tag. * * @return Nothing; `backend_failure` when libsodium fails. */ - [[nodiscard]] static boost::system::result seal(state& s, - std::span iv, - std::span data, - boost::hash2::digest<16>& tag) noexcept { + [[nodiscard]] static boost::system::result seal( + state& engine_state, std::span nonce_bytes, + std::span data_bytes, boost::hash2::digest<16>& tag_bytes) noexcept { read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); - return sodium_secretbox_seal(calls::encrypt, std::span(s.key), iv, - data, tag); + return sodium_secretbox_seal(calls::encrypt_call, + std::span(engine_state.key), + nonce_bytes, data_bytes, tag_bytes); } /** - * Checks the tag, then decrypts `data` in place. + * Checks the tag, then decrypts `data_bytes` in place. * * @return Nothing; `authentication_failed` when the tag does not match. */ [[nodiscard]] static boost::system::result open( - state& s, std::span iv, std::span data, - std::array const& tag) noexcept { + state& engine_state, std::span nonce_bytes, + std::span data_bytes, + std::array const& tag_bytes) noexcept { read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); - return sodium_secretbox_open(calls::decrypt, std::span(s.key), iv, - data, tag); + return sodium_secretbox_open(calls::decrypt_call, + std::span(engine_state.key), + nonce_bytes, data_bytes, tag_bytes); } /** Moves the key; the source is wiped. */ - static void move(state& to, state& from) noexcept { - to.key = from.key; - wipe_object(from.key); + static void move(state& target_state, state& source_state) noexcept { + target_state.key = source_state.key; + wipe_object(source_state.key); } /** Wipes the key. */ - static void reset(state& s) noexcept { wipe_object(s.key); } + static void reset(state& engine_state) noexcept { wipe_object(engine_state.key); } }; } // namespace webcpp::crypto::detail #endif // the boxes on libsodium -// Sealed boxes on libsodium, for a program that includes hybrid/sealed_box.hpp, before this -// header or after it, as Ed25519's above. -#if defined(WEBCPP_CRYPTO_HYBRID_SEALED_BOX_HPP) && defined(WEBCPP_CRYPTO_HAS_SODIUM) && \ +// Sealed boxes on libsodium, for a program that includes public_key_encryption/sealed_box.hpp, +// before this header or after it, as the boxes above: sealed_box.hpp defines +// WEBCPP_CRYPTO_DETAIL_SEALED_BOX_DECLARED once its declarations are. +#if defined(WEBCPP_CRYPTO_DETAIL_SEALED_BOX_DECLARED) && defined(WEBCPP_CRYPTO_HAS_SODIUM) && \ !defined(WEBCPP_CRYPTO_BACKENDS_SODIUM_SEALED_BOX) /** Defined once libsodium's sealed box engine is. */ #define WEBCPP_CRYPTO_BACKENDS_SODIUM_SEALED_BOX @@ -768,41 +1073,50 @@ namespace webcpp::crypto::detail { template <> struct sealed_box_engine { /** - * Seals `message` into `out` (`basic_sealed_box` has checked the sizes): libsodium draws - * the key pair from its own generator and wipes its secret key. + * Seals `message_bytes` into `output_bytes` (`basic_sealed_box` has checked the sizes): + * libsodium draws the key pair from its generator, crypto's entropy on Emscripten, and wipes + * its secret key. When that draw failed, `output_bytes` is zeroed. * * @return Nothing; `weak_public_key` for a recipient key of small order, which libsodium's - * box refuses; `backend_failure` when libsodium cannot start. + * box refuses; `entropy_unavailable`, or `errc::not_supported` where there is no generator, + * when the draw failed; `backend_failure` when libsodium cannot start. */ [[nodiscard]] static boost::system::result seal( std::span recipient_public_key, - std::span message, std::span out) noexcept { - auto const ready = sodium_ready(); - if (!ready) { - return ready; + std::span message_bytes, + std::span output_bytes) noexcept { + auto const library_ready = sodium_ready(); + if (!library_ready) { + return library_ready; + } + sodium_draw_watch const seal_draws; + int const seal_code = crypto_box_seal(output_bytes.data(), message_bytes.data(), + message_bytes.size(), recipient_public_key.data()); + if (auto const draw_error = seal_draws.draw_error()) { + wipe(output_bytes.data(), output_bytes.size()); + return draw_error; } - if (crypto_box_seal(out.data(), message.data(), message.size(), - recipient_public_key.data()) != 0) { + if (seal_code != 0) { return error::weak_public_key; } return {}; } /** - * Opens `sealed` into `out` (`basic_sealed_box` has checked the sizes). + * Opens `sealed_bytes` into `output_bytes` (`basic_sealed_box` has checked the sizes). * * @return Nothing; `authentication_failed`; `backend_failure` when libsodium cannot start. */ [[nodiscard]] static boost::system::result open( std::span recipient_public_key, std::span recipient_secret_key, - std::span sealed, std::span out) noexcept { - auto const ready = sodium_ready(); - if (!ready) { - return ready; + std::span sealed_bytes, std::span output_bytes) noexcept { + auto const library_ready = sodium_ready(); + if (!library_ready) { + return library_ready; } - if (sodium_refused(crypto_box_seal_open(out.data(), sealed.data(), sealed.size(), - recipient_public_key.data(), + if (sodium_refused(crypto_box_seal_open(output_bytes.data(), sealed_bytes.data(), + sealed_bytes.size(), recipient_public_key.data(), recipient_secret_key.data()))) { return error::authentication_failed; } @@ -824,7 +1138,7 @@ struct sealed_box_engine { /** Defined once libsodium's RFC 8410 layouts are. */ #define WEBCPP_CRYPTO_BACKENDS_SODIUM_RFC8410 -#include +#include #include #include @@ -836,43 +1150,44 @@ namespace webcpp::crypto::detail { /** * RFC 8410's fixed layouts on libsodium: a prefix, then 32 key bytes. A decoding is accepted - * only where its prefix is the one encoding the key gives, compared with `equal`, and its size - * the one size (the callers check it), which is design D30's re-encoding test for a fixed layout. + * only where its prefix is the one encoding the key gives, compared with `constant_time_equal`, and + * its size the one size (the callers check it), which is design D30's re-encoding test for a fixed + * layout. */ struct sodium_rfc8410 { /** * Writes the prefix, then the key. * - * @param prefix The format's prefix. - * @param key 32 bytes. - * @param out The prefix's size and 32 bytes. + * @param prefix_bytes The format's prefix. + * @param key_bytes 32 bytes. + * @param output_bytes The prefix's size and 32 bytes. */ template - static void encode(std::array const& prefix, - std::span key, - std::span out) noexcept { + static void encode(std::array const& prefix_bytes, + std::span key_bytes, + std::span output_bytes) noexcept { read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); - std::ranges::copy(key, std::ranges::copy(prefix, out.begin()).out); + std::ranges::copy(key_bytes, std::ranges::copy(prefix_bytes, output_bytes.begin()).out); } /** * Copies the key out of an encoding whose prefix is the format's. * - * @param prefix The format's prefix. - * @param der The prefix's size and 32 bytes. - * @param key 32 bytes, written only when the prefix is the format's. + * @param prefix_bytes The format's prefix. + * @param der_bytes The prefix's size and 32 bytes. + * @param key_bytes 32 bytes, written only when the prefix is the format's. * @return Nothing; `invalid_encoding`. */ template [[nodiscard]] static boost::system::result decode( - std::array const& prefix, - std::span der, - std::span key) noexcept { + std::array const& prefix_bytes, + std::span der_bytes, + std::span key_bytes) noexcept { read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); - if (!equal(der.template first(), prefix)) { + if (!constant_time_equal(der_bytes.template first(), prefix_bytes)) { return error::invalid_encoding; } - std::ranges::copy(der.template last<32>(), key.begin()); + std::ranges::copy(der_bytes.template last<32>(), key_bytes.begin()); return {}; } }; @@ -893,8 +1208,8 @@ template <> struct ed25519_formats_engine { /** Writes the SPKI. */ static void encode_spki(std::span public_key, - std::span out) noexcept { - sodium_rfc8410::encode(ed25519_spki_prefix, public_key, out); + std::span output_bytes) noexcept { + sodium_rfc8410::encode(ed25519_spki_prefix, public_key, output_bytes); } /** @@ -903,15 +1218,17 @@ struct ed25519_formats_engine { * @return Nothing; `invalid_encoding`. */ [[nodiscard]] static boost::system::result decode_spki( - std::span spki, std::span public_key) noexcept { - return sodium_rfc8410::decode(ed25519_spki_prefix, spki, public_key); + std::span spki_bytes, + std::span public_key) noexcept { + return sodium_rfc8410::decode(ed25519_spki_prefix, spki_bytes, public_key); } /** Writes the PKCS#8 of the seed, the first half of libsodium's secret key. */ - static void encode_pkcs8(ed25519_state const& keyed, - std::span out) noexcept { + static void encode_pkcs8(ed25519_state const& keyed_state, + std::span output_bytes) noexcept { sodium_rfc8410::encode(ed25519_pkcs8_prefix, - std::span(keyed.secret_key).first<32>(), out); + std::span(keyed_state.secret_key).first<32>(), + output_bytes); } /** @@ -920,8 +1237,9 @@ struct ed25519_formats_engine { * @return Nothing; `invalid_encoding`. */ [[nodiscard]] static boost::system::result decode_pkcs8( - std::span pkcs8, std::span seed) noexcept { - return sodium_rfc8410::decode(ed25519_pkcs8_prefix, pkcs8, seed); + std::span pkcs8_bytes, + std::span seed_bytes) noexcept { + return sodium_rfc8410::decode(ed25519_pkcs8_prefix, pkcs8_bytes, seed_bytes); } }; @@ -941,8 +1259,8 @@ template <> struct x25519_formats_engine { /** Writes the SPKI. */ static void encode_spki(std::span public_key, - std::span out) noexcept { - sodium_rfc8410::encode(x25519_spki_prefix, public_key, out); + std::span output_bytes) noexcept { + sodium_rfc8410::encode(x25519_spki_prefix, public_key, output_bytes); } /** @@ -951,14 +1269,15 @@ struct x25519_formats_engine { * @return Nothing; `invalid_encoding`. */ [[nodiscard]] static boost::system::result decode_spki( - std::span spki, std::span public_key) noexcept { - return sodium_rfc8410::decode(x25519_spki_prefix, spki, public_key); + std::span spki_bytes, + std::span public_key) noexcept { + return sodium_rfc8410::decode(x25519_spki_prefix, spki_bytes, public_key); } /** Writes the PKCS#8 of a secret key. */ static void encode_pkcs8(std::span secret_key, - std::span out) noexcept { - sodium_rfc8410::encode(x25519_pkcs8_prefix, secret_key, out); + std::span output_bytes) noexcept { + sodium_rfc8410::encode(x25519_pkcs8_prefix, secret_key, output_bytes); } /** @@ -967,8 +1286,9 @@ struct x25519_formats_engine { * @return Nothing; `invalid_encoding`. */ [[nodiscard]] static boost::system::result decode_pkcs8( - std::span pkcs8, std::span secret_key) noexcept { - return sodium_rfc8410::decode(x25519_pkcs8_prefix, pkcs8, secret_key); + std::span pkcs8_bytes, + std::span secret_key) noexcept { + return sodium_rfc8410::decode(x25519_pkcs8_prefix, pkcs8_bytes, secret_key); } }; @@ -1013,48 +1333,54 @@ struct pem_engine { /** * The base64 of at most 48 bytes, with padding. * - * @param bytes 1 to 48 bytes. - * @param out Exactly the base64's characters, four per three bytes begun. + * @param input_bytes 1 to 48 bytes. + * @param output_characters Exactly the base64's characters, four per three bytes begun. */ - static void encode(std::span bytes, std::span out) noexcept { + static void encode(std::span input_bytes, + std::span output_characters) noexcept { read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); - // libsodium ends the text with a NUL, which out does not hold. + // libsodium ends the text with a NUL, which `output_characters` does not hold. // NOLINTNEXTLINE(readability-math-missing-parentheses,bugprone-signed-bitwise): its macro - std::array text{}; - static_cast(sodium_bin2base64(text.data(), text.size(), bytes.data(), bytes.size(), + std::array + base64_text{}; + static_cast(sodium_bin2base64(base64_text.data(), base64_text.size(), + input_bytes.data(), input_bytes.size(), sodium_base64_VARIANT_ORIGINAL)); - std::ranges::copy(std::span(text).first(out.size()), out.begin()); - wipe_object(text); + std::ranges::copy(std::span(base64_text).first(output_characters.size()), + output_characters.begin()); + wipe_object(base64_text); } /** * The bytes of at most 64 characters of base64 with padding. * - * @param text 1 to 64 characters. - * @param out 48 bytes, of which the decoded are written. + * @param base64_text 1 to 64 characters. + * @param output_bytes 48 bytes, of which the decoded are written. * @return The bytes' count; `invalid_encoding` for a character outside the alphabet, padding * missing or misplaced, or characters left over. */ [[nodiscard]] static boost::system::result decode( - std::string_view text, std::span out) noexcept { + std::string_view base64_text, std::span output_bytes) noexcept { read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); - std::size_t written = 0; - char const* end = nullptr; - if (sodium_base642bin(out.data(), out.size(), text.data(), text.size(), nullptr, &written, - &end, sodium_base64_VARIANT_ORIGINAL) != 0 || - end != text.data() + text.size()) { + std::size_t written_count = 0; + char const* parse_end = nullptr; + if (sodium_base642bin(output_bytes.data(), output_bytes.size(), base64_text.data(), + base64_text.size(), nullptr, &written_count, &parse_end, + sodium_base64_VARIANT_ORIGINAL) != 0 || + parse_end != base64_text.data() + base64_text.size()) { return error::invalid_encoding; } - return written; + return written_count; } }; } // namespace webcpp::crypto::detail #endif // PEM on libsodium -// crypto_kx on libsodium, for a program that includes curves/x25519/kx.hpp, before this header or -// after it, as Ed25519's above. -#if defined(WEBCPP_CRYPTO_CURVES_X25519_KX_HPP) && defined(WEBCPP_CRYPTO_HAS_SODIUM) && \ +// crypto_kx on libsodium, for a program that includes key_exchange/kx.hpp, before this header or +// after it, as the boxes above: kx.hpp defines WEBCPP_CRYPTO_DETAIL_KX_DECLARED once its +// declarations are. +#if defined(WEBCPP_CRYPTO_DETAIL_KX_DECLARED) && defined(WEBCPP_CRYPTO_HAS_SODIUM) && \ !defined(WEBCPP_CRYPTO_BACKENDS_SODIUM_KX) /** Defined once libsodium's crypto_kx engine is. */ #define WEBCPP_CRYPTO_BACKENDS_SODIUM_KX @@ -1063,52 +1389,42 @@ struct pem_engine { #include -#include #include #include #include namespace webcpp::crypto::detail { -/** What a crypto_kx key pair stores on libsodium. */ -template <> -struct kx_state { - /** libsodium's secret key, first, where the wipe test reads it. */ - std::array secret_key{}; - /** The public key. */ - std::array public_key{}; -}; - -/** crypto_kx on libsodium, `crypto_kx_*`. */ +/** + * crypto_kx on libsodium, `crypto_kx_*`, over the bytes of the X25519 key pair that + * `key_exchange::kx_keypair` holds. + */ template <> struct kx_engine { - /** The key pair's state. */ - using state = kx_state; - /** - * Makes the key pair of a seed, `crypto_kx_seed_keypair`. + * The secret key of a seed, `crypto_kx_seed_keypair`: BLAKE2b-256 of the seed. The public + * key libsodium computes beside it is wiped: the X25519 key pair made from the secret + * computes it again. * * @return Nothing; `backend_failure`. */ - [[nodiscard]] static boost::system::result make( - state& keyed, std::span seed) noexcept { - auto const ready = sodium_ready(); - if (!ready) { - return ready; + [[nodiscard]] static boost::system::result seed_keypair( + std::span seed_bytes, + std::span secret_key) noexcept { + auto const library_ready = sodium_ready(); + if (!library_ready) { + return library_ready; } - if (crypto_kx_seed_keypair(keyed.public_key.data(), keyed.secret_key.data(), seed.data()) != - 0) { + std::array public_key{}; + int const seed_result = + crypto_kx_seed_keypair(public_key.data(), secret_key.data(), seed_bytes.data()); + wipe_object(public_key); + if (seed_result != 0) { return error::backend_failure; } return {}; } - /** The public key. */ - static void public_key(state const& keyed, - std::span out) noexcept { - std::ranges::copy(keyed.public_key, out.begin()); - } - /** * The client's session keys, `crypto_kx_client_session_keys`, which returns -1 for a server * key whose X25519 shared secret is all zero. @@ -1116,13 +1432,15 @@ struct kx_engine { * @return Nothing; `weak_public_key`. */ [[nodiscard]] static boost::system::result client( - state const& keyed, std::span server_key, - std::span receive, - std::span transmit) noexcept { + std::span secret_key, + std::span public_key, + std::span server_key, + std::span receive_key, + std::span transmit_key) noexcept { read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); - if (sodium_refused(crypto_kx_client_session_keys( - receive.data(), transmit.data(), keyed.public_key.data(), keyed.secret_key.data(), - server_key.data()))) { + if (sodium_refused(crypto_kx_client_session_keys(receive_key.data(), transmit_key.data(), + public_key.data(), secret_key.data(), + server_key.data()))) { return error::weak_public_key; } return {}; @@ -1135,20 +1453,19 @@ struct kx_engine { * @return Nothing; `weak_public_key`. */ [[nodiscard]] static boost::system::result server( - state const& keyed, std::span client_key, - std::span receive, - std::span transmit) noexcept { + std::span secret_key, + std::span public_key, + std::span client_key, + std::span receive_key, + std::span transmit_key) noexcept { read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); - if (sodium_refused(crypto_kx_server_session_keys( - receive.data(), transmit.data(), keyed.public_key.data(), keyed.secret_key.data(), - client_key.data()))) { + if (sodium_refused(crypto_kx_server_session_keys(receive_key.data(), transmit_key.data(), + public_key.data(), secret_key.data(), + client_key.data()))) { return error::weak_public_key; } return {}; } - - /** Wipes the key pair. */ - static void reset(state& keyed) noexcept { wipe_object(keyed); } }; } // namespace webcpp::crypto::detail diff --git a/include/webcpp/crypto/ciphers/aead.hpp b/include/webcpp/crypto/ciphers/aead.hpp index fcb47307..e06f320e 100644 --- a/include/webcpp/crypto/ciphers/aead.hpp +++ b/include/webcpp/crypto/ciphers/aead.hpp @@ -5,20 +5,23 @@ // https://www.boost.org/LICENSE_1_0.txt) /** - `aead`, one-shot authenticated encryption in place, and the families it - takes: ChaCha20-Poly1305, its original form and XChaCha20-Poly1305, and libsodium's - `crypto_secretbox`, XSalsa20-Poly1305 and XChaCha20-Poly1305 without additional data; and the - free synchronous forms of every AEAD's members, AES-GCM's included (design D9, R23), - `crypto::seal(aead, iv, additional_data, data)` and - `crypto::open(aead, iv, additional_data, data, tag)`. - - @see "ChaCha20-Poly1305" and "Secret boxes", in the guide. + `basic_chacha20_poly1305`, one-shot authenticated encryption in place with + associated data, and the families it takes: ChaCha20-Poly1305, its original form and + XChaCha20-Poly1305. Each is a `secret_key_encryption::aead::cipher` (design D5), whose header, + which this one includes, holds the free synchronous forms of every AEAD's members, AES-GCM's + included (design D9, D11), + `secret_key_encryption::aead::seal(cipher, nonce, associated_data, data)` and + `secret_key_encryption::aead::open(cipher, nonce, associated_data, data, tag)`. The secret boxes, + which take no associated data, are `secret_key_encryption::basic_secretbox`. + + @see "ChaCha20-Poly1305" and "The AEAD contract", in the guide. */ #ifndef WEBCPP_CRYPTO_CIPHERS_AEAD_HPP #define WEBCPP_CRYPTO_CIPHERS_AEAD_HPP #include +#include #include #include #include @@ -26,7 +29,8 @@ #include #include #include -#include // crypto::make, which serves its make (design R23) +#include // crypto::from_key, which serves its from_key (design R23) +#include // its free seal and open (design D11) #include #include @@ -45,13 +49,13 @@ struct chacha20_poly1305 { /** The key's size. */ static constexpr std::size_t key_size = 32; /** The nonce's size, exactly (RFC 8439 section 2.8). */ - static constexpr std::size_t iv_size = 12; + static constexpr std::size_t nonce_size = 12; /** The tag's size. */ static constexpr std::size_t tag_size = 16; /** The longest message, 2^38 - 64 bytes: ChaCha20's 32-bit block counter (section 2.8). */ static constexpr std::uint64_t max_message_size = (std::uint64_t{1} << 38U) - 64; - /** The longest additional data, 2^64 - 1 bytes (section 2.8). */ - static constexpr std::uint64_t max_additional_data_size = ~std::uint64_t{0}; + /** The longest associated data, 2^64 - 1 bytes (section 2.8). */ + static constexpr std::uint64_t max_associated_data_size = ~std::uint64_t{0}; }; /** @@ -62,13 +66,13 @@ struct chacha20_poly1305_original { /** The key's size. */ static constexpr std::size_t key_size = 32; /** The nonce's size, exactly. */ - static constexpr std::size_t iv_size = 8; + static constexpr std::size_t nonce_size = 8; /** The tag's size. */ static constexpr std::size_t tag_size = 16; /** The longest message, 2^64 - 17 bytes. */ static constexpr std::uint64_t max_message_size = ~std::uint64_t{0} - 16; - /** The longest additional data, 2^64 - 1 bytes. */ - static constexpr std::uint64_t max_additional_data_size = ~std::uint64_t{0}; + /** The longest associated data, 2^64 - 1 bytes. */ + static constexpr std::uint64_t max_associated_data_size = ~std::uint64_t{0}; }; /** XChaCha20-Poly1305, a 24-byte nonce safe to draw at random. */ @@ -76,53 +80,13 @@ struct xchacha20_poly1305 { /** The key's size. */ static constexpr std::size_t key_size = 32; /** The nonce's size, exactly. */ - static constexpr std::size_t iv_size = 24; + static constexpr std::size_t nonce_size = 24; /** The tag's size. */ static constexpr std::size_t tag_size = 16; /** The longest message, 2^64 - 17 bytes. */ static constexpr std::uint64_t max_message_size = ~std::uint64_t{0} - 16; - /** The longest additional data, 2^64 - 1 bytes. */ - static constexpr std::uint64_t max_additional_data_size = ~std::uint64_t{0}; -}; - -/** - * NaCl's and libsodium's `crypto_secretbox`, XSalsa20-Poly1305: a 32-byte key, a 24-byte nonce - * safe to draw at random, a 16-byte tag, and no additional data. - */ -struct secretbox_xsalsa20poly1305 { - /** The key's size. */ - static constexpr std::size_t key_size = 32; - /** The nonce's size, exactly. */ - static constexpr std::size_t iv_size = 24; - /** The tag's size. */ - static constexpr std::size_t tag_size = 16; - /** - * The longest message, 2^64 - 17 bytes: libsodium's `crypto_secretbox_MESSAGEBYTES_MAX` on a - * 64-bit target. - * - * On a 32-bit target, wasm32 among them, libsodium's is 2^32 - 17 bytes, more than a - * message there can be, since the 4 GiB of memory also hold the program. - */ - static constexpr std::uint64_t max_message_size = ~std::uint64_t{0} - 16; - /** No additional data: `aead` refuses a non-empty one with `invalid_input_size`. */ - static constexpr std::uint64_t max_additional_data_size = 0; -}; - -/** - * libsodium's `crypto_secretbox_xchacha20poly1305`: `crypto_secretbox` with XChaCha20 in place - * of XSalsa20, a 24-byte nonce safe to draw at random, and no additional data. - */ -struct secretbox_xchacha20poly1305 { - /** The key's size. */ - static constexpr std::size_t key_size = 32; - /** The nonce's size, exactly. */ - static constexpr std::size_t iv_size = 24; - /** The tag's size. */ - static constexpr std::size_t tag_size = 16; - /** The longest message, 2^64 - 17 bytes. */ - static constexpr std::uint64_t max_message_size = ~std::uint64_t{0} - 16; - /** No additional data: `aead` refuses a non-empty one with `invalid_input_size`. */ - static constexpr std::uint64_t max_additional_data_size = 0; + /** The longest associated data, 2^64 - 1 bytes. */ + static constexpr std::uint64_t max_associated_data_size = ~std::uint64_t{0}; }; } // namespace webcpp::crypto::families @@ -130,13 +94,13 @@ struct secretbox_xchacha20poly1305 { namespace webcpp::crypto::detail { /** - * What a `ciphers::aead` stores on a backend whose header does not specialise it: nothing, - * since its engine refuses the backend where the family is called. + * What a `ciphers::basic_chacha20_poly1305` stores on a backend whose header does not specialise + * it: nothing, since its engine refuses the backend where the family is called. */ template struct aead_state {}; -/** Whether `Family` is one of the AEAD families `ciphers::aead` takes. */ +/** Whether `Family` is one of the AEAD families `ciphers::basic_chacha20_poly1305` takes. */ template inline constexpr bool aead_family = false; @@ -152,16 +116,8 @@ inline constexpr bool aead_family = true; template <> inline constexpr bool aead_family = true; -/** `crypto_secretbox`, XSalsa20-Poly1305, is an AEAD family without additional data. */ -template <> -inline constexpr bool aead_family = true; - -/** `crypto_secretbox_xchacha20poly1305` is an AEAD family without additional data. */ -template <> -inline constexpr bool aead_family = true; - /** - * The sizes and limits `ciphers::aead` reads from its family: the family's own. + * The sizes and limits `ciphers::basic_chacha20_poly1305` reads from its family: the family's own. * * @tparam Family An AEAD family. */ @@ -169,26 +125,27 @@ template > struct aead_sizes : Family {}; /** - * The sizes of a type that is no AEAD family, which `ciphers::aead` refuses first: placeholders, - * so that the compiler adds no error of its own after the refusal. + * The sizes of a type that is no AEAD family, which `ciphers::basic_chacha20_poly1305` refuses + * first: placeholders, so that the compiler adds no error of its own after the refusal. */ template struct aead_sizes { /** A placeholder. */ static constexpr std::size_t key_size = 1; /** A placeholder. */ - static constexpr std::size_t iv_size = 1; + static constexpr std::size_t nonce_size = 1; /** A placeholder. */ static constexpr std::size_t tag_size = 1; /** A placeholder. */ static constexpr std::uint64_t max_message_size = 0; /** A placeholder. */ - static constexpr std::uint64_t max_additional_data_size = 0; + static constexpr std::uint64_t max_associated_data_size = 0; }; /** * The refusal of an AEAD family on a backend whose header does not specialise its engine: each - * family's below. A type that is no AEAD family has none here: `ciphers::aead` refuses it first. + * family's below. A type that is no AEAD family has none here: `ciphers::basic_chacha20_poly1305` + * refuses it first. */ template struct aead_refusal {}; @@ -211,18 +168,6 @@ struct aead_refusal { WEBCPP_CRYPTO_DETAIL_REFUSE_XCHACHA20_POLY1305(Backend); }; -/** XSalsa20-Poly1305's secret box's refusal (see the first). */ -template -struct aead_refusal { - WEBCPP_CRYPTO_DETAIL_REFUSE_SECRETBOX_XSALSA20POLY1305(Backend); -}; - -/** XChaCha20-Poly1305's secret box's refusal (see the first). */ -template -struct aead_refusal { - WEBCPP_CRYPTO_DETAIL_REFUSE_SECRETBOX_XCHACHA20POLY1305(Backend); -}; - /** * An AEAD's engine on a backend whose header does not specialise it: the family's refusal. * Its functions are never called: the refusal stops the build where the class is @@ -263,30 +208,27 @@ struct aead_engine : aead_refusal { namespace webcpp::crypto::ciphers { /** - * An AEAD of the family `Family` on `Backend`, one shot: authenticated encryption in place, - * the tag apart. + * An AEAD of the family `Family` on `Backend`, one shot: authenticated encryption in place with + * associated data, the tag apart. * - * An object holds a key: it is used by one thread at a time. A nonce (the IV) is never + * 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 and let an attacker forge tags. Drawn at random, ChaCha20-Poly1305's 12-byte * nonce lets a key seal at most 2^32 messages, and the original's 8 bytes are too few: a - * counter numbers them. XChaCha20-Poly1305's 24-byte nonce, and the secret boxes', are safe - * to draw at random. + * counter numbers them. XChaCha20-Poly1305's 24-byte nonce is safe to draw at random. * - * @tparam Family `families::chacha20_poly1305`, `families::chacha20_poly1305_original`, - * `families::xchacha20_poly1305`, or the secret boxes' `families::secretbox_xsalsa20poly1305` - * and `families::secretbox_xchacha20poly1305`, which take no additional data. - * @tparam Backend The backend; `ciphers::chacha20_poly1305<>`, its two siblings and - * `ciphers::secretbox<>` and its twin name the family's default. + * @tparam Family `families::chacha20_poly1305`, `families::chacha20_poly1305_original` or + * `families::xchacha20_poly1305`. + * @tparam Backend The backend; `ciphers::chacha20_poly1305<>` and its two siblings name the + * family's default. */ template -class aead { +class basic_chacha20_poly1305 { // The first error a program that names another type sees, and its only one. static_assert(detail::aead_family, - "webcpp::crypto: ciphers::aead takes an AEAD family: " - "families::chacha20_poly1305, families::chacha20_poly1305_original, " - "families::xchacha20_poly1305, families::secretbox_xsalsa20poly1305 or " - "families::secretbox_xchacha20poly1305."); + "webcpp::crypto: ciphers::basic_chacha20_poly1305 takes an AEAD family: " + "families::chacha20_poly1305, families::chacha20_poly1305_original or " + "families::xchacha20_poly1305."); using sizes = detail::aead_sizes; using state_type = detail::aead_state; @@ -304,13 +246,13 @@ class aead { /** The key's size. */ static constexpr std::size_t key_size = sizes::key_size; /** The nonce's size, exactly. */ - static constexpr std::size_t iv_size = sizes::iv_size; + static constexpr std::size_t nonce_size = sizes::nonce_size; /** The tag's size. */ static constexpr std::size_t tag_size = sizes::tag_size; /** The longest message. */ static constexpr std::uint64_t max_message_size = sizes::max_message_size; - /** The longest additional data; 0 for a family that takes none. */ - static constexpr std::uint64_t max_additional_data_size = sizes::max_additional_data_size; + /** The longest associated data. */ + static constexpr std::uint64_t max_associated_data_size = sizes::max_associated_data_size; /** * Makes an object under a key. @@ -318,20 +260,18 @@ class aead { * @param key_bytes `key_size` bytes. * @return The object; `invalid_key_size`; `backend_failure` when the backend cannot start. */ - [[nodiscard]] static boost::system::result make( + [[nodiscard]] static boost::system::result from_key( std::span key_bytes) noexcept { - detail::timing_guard const timing; - static_assert( - !detail::asynchronous_backend_v, - "webcpp::crypto: make on this backend completes asynchronously: call async_make."); + detail::timing_guard const timing_scope; if constexpr (detail::asynchronous_backend_v) { - // Never compiled into a program: the assertion above stopped the build. + // WebCrypto has no such construction: the refusal names a native backend (design D6). + detail::refuse_aead_on_asynchronous_backend(); return error::backend_failure; } else { if (key_bytes.size() != key_size) { return error::invalid_key_size; } - aead made_object; + basic_chacha20_poly1305 made_object; auto const key_result = engine::init(made_object.state_, key_bytes); if (!key_result) { return key_result.error(); @@ -341,6 +281,34 @@ class aead { } } + /** + * 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-Poly1305, and on a backend that + * completes by itself this call stops the build, as `from_key`, `seal`, `open` and the other + * asynchronous forms do (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_poly1305)`; on an error the object is empty, + * and every member 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. * @@ -348,7 +316,8 @@ class aead { * * @param moved_source The source, empty afterwards. */ - aead(aead&& moved_source) noexcept : keyed_(std::exchange(moved_source.keyed_, false)) { + basic_chacha20_poly1305(basic_chacha20_poly1305&& moved_source) noexcept + : keyed_(std::exchange(moved_source.keyed_, false)) { if (keyed_) { engine::move(state_, moved_source.state_); } @@ -360,7 +329,7 @@ class aead { * @param moved_source The source, empty afterwards. * @return This object. */ - aead& operator=(aead&& moved_source) noexcept { + basic_chacha20_poly1305& operator=(basic_chacha20_poly1305&& moved_source) noexcept { if (this != &moved_source) { engine::reset(state_); keyed_ = std::exchange(moved_source.keyed_, false); @@ -372,54 +341,52 @@ class aead { } /** Not copyable: a key has one owner, which wipes it. */ - aead(aead const&) = delete; + basic_chacha20_poly1305(basic_chacha20_poly1305 const&) = delete; /** Not copyable: a key has one owner, which wipes it. */ - aead& operator=(aead const&) = delete; + basic_chacha20_poly1305& operator=(basic_chacha20_poly1305 const&) = delete; /** Wipes the key. */ - ~aead() { engine::reset(state_); } + ~basic_chacha20_poly1305() { engine::reset(state_); } /** * Seals a message in place: `data_bytes` holds the plaintext before and the ciphertext * after. * * The nonce is read before the first byte of `data_bytes` is written, so it may lie in - * `data_bytes`. The additional data may touch `data_bytes`, as a wire format that puts it + * `data_bytes`. The associated data may touch `data_bytes`, as a wire format that puts it * just before the message does, but not overlap it: BearSSL's ChaCha20-Poly1305 reads it * after it encrypts, in one call over the whole message, so an overlap would authenticate - * other bytes than the caller's additional data; the backends would give different tags, - * and an open with the original additional data would fail. + * other bytes than the caller's associated data; the backends would give different tags, + * and an open with the original associated data would fail. * * When the backend fails, `data_bytes` is zeroed, as a failed open's is: a backend may fail * after it began to encrypt, and neither the plaintext nor bytes that look sealed are left; * a guard's refusal leaves it untouched. * - * @param iv_bytes The nonce, `iv_size` bytes, never repeated under this key. - * @param additional_data_bytes Authenticated, not encrypted; empty for a family that takes - * none (`max_additional_data_size` 0). + * @param nonce_bytes The nonce, `nonce_size` bytes, never repeated under this key. + * @param associated_data_bytes Authenticated, not encrypted. * @param data_bytes The message. - * @return The tag; `invalid_state` moved from; `invalid_iv_size`; `invalid_input_size` for - * additional data given to a family that takes none; `message_too_long`; `backend_failure`. + * @return The tag; `invalid_state` moved from; `invalid_nonce_size`; `message_too_long`; + * `backend_failure`. */ [[nodiscard]] boost::system::result seal( - std::span iv_bytes, std::span additional_data_bytes, + std::span nonce_bytes, + std::span associated_data_bytes, std::span data_bytes) noexcept { - detail::timing_guard const timing; - static_assert( - !detail::asynchronous_backend_v, - "webcpp::crypto: seal on this backend completes asynchronously: call async_seal."); + detail::timing_guard const timing_scope; if constexpr (detail::asynchronous_backend_v) { - // Never compiled into a program: the assertion above stopped the build. + // WebCrypto has no such construction: the refusal names a native backend (design D6). + detail::refuse_aead_on_asynchronous_backend(); return error::backend_failure; } else { auto const guard_result = - guard_message(iv_bytes, additional_data_bytes, data_bytes.size(), tag_size); + guard_message(nonce_bytes, associated_data_bytes, data_bytes.size(), tag_size); if (!guard_result) { return guard_result.error(); } result_type tag_bytes{}; auto const seal_result = - engine::seal(state_, iv_bytes, additional_data_bytes, data_bytes, tag_bytes); + engine::seal(state_, nonce_bytes, associated_data_bytes, data_bytes, tag_bytes); if (!seal_result) { detail::wipe(data_bytes.data(), data_bytes.size()); return seal_result.error(); @@ -428,6 +395,35 @@ class aead { } } + /** + * 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. + * + * The object and the spans are the caller's until the completion; `data_bytes` holds the + * ciphertext at 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 associated_data_bytes Authenticated, not encrypted. + * @param data_bytes The message. + * @param completion_token The completion token, of signature + * `void(boost::system::error_code, result_type)`: the tag; on an error the zeroed tag (the + * errors of `seal`). + * @return What the completion token's `async_result` gives. + */ + template + auto async_seal(Executor const& completion_executor, std::span nonce_bytes, + std::span associated_data_bytes, + std::span data_bytes, CompletionToken&& completion_token); + /** * Opens a message in place: `data_bytes` holds the ciphertext before and the plaintext * after. @@ -435,28 +431,26 @@ class aead { * When the tag does not match, or the backend fails, `data_bytes` is zeroed; a guard's * refusal leaves it untouched. * - * @param iv_bytes The nonce of the seal. - * @param additional_data_bytes The additional data of the seal. + * @param nonce_bytes The nonce of the seal. + * @param associated_data_bytes The associated data of the seal. * @param data_bytes The ciphertext. * @param tag_bytes The seal's tag, `tag_size` bytes, which may lie anywhere, `data_bytes` * included. - * @return Nothing; `invalid_state` moved from; `invalid_iv_size`; `invalid_tag_size`; - * `invalid_input_size` for additional data given to a family that takes none; + * @return Nothing; `invalid_state` moved from; `invalid_nonce_size`; `invalid_tag_size`; * `message_too_long`; `authentication_failed`; `backend_failure`. */ [[nodiscard]] boost::system::result open( - std::span iv_bytes, std::span additional_data_bytes, - std::span data_bytes, std::span tag_bytes) noexcept { - detail::timing_guard const timing; - static_assert( - !detail::asynchronous_backend_v, - "webcpp::crypto: open on this backend completes asynchronously: call async_open."); + std::span nonce_bytes, + std::span associated_data_bytes, std::span data_bytes, + std::span tag_bytes) noexcept { + detail::timing_guard const timing_scope; if constexpr (detail::asynchronous_backend_v) { - // Never compiled into a program: the assertion above stopped the build. + // WebCrypto has no such construction: the refusal names a native backend (design D6). + detail::refuse_aead_on_asynchronous_backend(); return error::backend_failure; } else { - auto const guard_result = - guard_message(iv_bytes, additional_data_bytes, data_bytes.size(), tag_bytes.size()); + auto const guard_result = guard_message(nonce_bytes, associated_data_bytes, + data_bytes.size(), tag_bytes.size()); if (!guard_result) { return guard_result.error(); } @@ -464,7 +458,7 @@ class aead { std::array expected_tag{}; std::ranges::copy(tag_bytes, expected_tag.begin()); auto const open_result = - engine::open(state_, iv_bytes, additional_data_bytes, data_bytes, expected_tag); + engine::open(state_, nonce_bytes, associated_data_bytes, data_bytes, expected_tag); if (!open_result) { detail::wipe(data_bytes.data(), data_bytes.size()); return open_result.error(); @@ -473,31 +467,59 @@ class aead { } } + /** + * 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. + * + * The object and the spans are the caller's until the completion; `data_bytes` holds the + * plaintext at a successful completion, and is zeroed by a wrong tag. 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 of the seal. + * @param associated_data_bytes The associated data of the seal. + * @param data_bytes The ciphertext. + * @param tag_bytes The seal's tag, `tag_size` bytes. + * @param completion_token The completion token, of signature `void(boost::system::error_code)` + * (`open`'s errors). + * @return What the completion token's `async_result` gives. + */ + template + auto async_open(Executor const& completion_executor, std::span nonce_bytes, + std::span associated_data_bytes, + std::span data_bytes, std::span tag_bytes, + CompletionToken&& completion_token); + private: - aead() noexcept = default; + // The asynchronous family's error completions make the empty object a move leaves. + friend struct detail::async_access; + + basic_chacha20_poly1305() noexcept = default; // Every guard of a message, in the documented order: the state, the nonce, the tag - // (open's; seal passes tag_size), additional data given to a family that takes none, the - // lengths. None reads a byte of the spans. + // (open's; seal passes tag_size), the lengths. None reads a byte of the spans. [[nodiscard]] boost::system::result guard_message( - std::span iv_bytes, std::span additional_data_bytes, - std::size_t byte_count, std::size_t tag_bytes) const noexcept { + std::span nonce_bytes, + std::span associated_data_bytes, std::size_t byte_count, + std::size_t tag_bytes) const noexcept { if (!keyed_) { return error::invalid_state; } - if (iv_bytes.size() != iv_size) { - return error::invalid_iv_size; + if (nonce_bytes.size() != nonce_size) { + return error::invalid_nonce_size; } if (tag_bytes != tag_size) { return error::invalid_tag_size; } - if constexpr (max_additional_data_size == 0) { - if (!additional_data_bytes.empty()) { - return error::invalid_input_size; - } - } if (detail::exceeds(byte_count, max_message_size) || - detail::exceeds(additional_data_bytes.size(), max_additional_data_size)) { + detail::exceeds(associated_data_bytes.size(), max_associated_data_size)) { return error::message_too_long; } return {}; @@ -509,71 +531,4 @@ class aead { } // namespace webcpp::crypto::ciphers -namespace webcpp::crypto { - -/** - * Seals a message in place, `keyed_aead.seal(iv_bytes, additional_data_bytes, data_bytes)`: the - * free form of the AEAD's own `seal`, which it calls, with its results and its errors. - * - * @tparam Aead A type whose `seal` takes these arguments: `ciphers::gcm` or - * `ciphers::aead`. - * @param keyed_aead The keyed object. - * @param iv_bytes The IV or nonce, never reused under this key. - * @param additional_data_bytes Authenticated, not encrypted. - * @param data_bytes The message, the ciphertext after. - * @return What `keyed_aead.seal` returns: the tag, or its error. - */ -template - requires requires { - std::declval().seal(std::declval&>(), - std::declval&>(), - std::declval&>()); - } -[[nodiscard]] auto seal( - Aead& keyed_aead, std::span iv_bytes, - std::span additional_data_bytes, - std::span data_bytes) noexcept(noexcept(keyed_aead.seal(iv_bytes, - additional_data_bytes, - data_bytes))) - -> decltype(keyed_aead.seal(iv_bytes, additional_data_bytes, data_bytes)) { - detail::timing_guard const timing; - return keyed_aead.seal(iv_bytes, additional_data_bytes, data_bytes); -} - -/** - * Opens a message in place, `keyed_aead.open(iv_bytes, additional_data_bytes, data_bytes, - * tag_bytes)`: the free form of the AEAD's own `open`, which it calls, with its results and its - * errors. - * - * @tparam Aead A type whose `open` takes these arguments: `ciphers::gcm` or - * `ciphers::aead`. - * @param keyed_aead The keyed object. - * @param iv_bytes The IV or nonce of the seal. - * @param additional_data_bytes The additional data of the seal. - * @param data_bytes The ciphertext, the plaintext after. - * @param tag_bytes The seal's tag. - * @return What `keyed_aead.open` returns: nothing, or its error (`authentication_failed`, which - * zeroes `data_bytes`). - */ -template - requires requires { - std::declval().open(std::declval&>(), - std::declval&>(), - std::declval&>(), - std::declval&>()); - } -[[nodiscard]] auto open(Aead& keyed_aead, std::span iv_bytes, - std::span additional_data_bytes, - std::span data_bytes, - std::span - tag_bytes) noexcept(noexcept(keyed_aead.open(iv_bytes, - additional_data_bytes, - data_bytes, tag_bytes))) - -> decltype(keyed_aead.open(iv_bytes, additional_data_bytes, data_bytes, tag_bytes)) { - detail::timing_guard const timing; - return keyed_aead.open(iv_bytes, additional_data_bytes, data_bytes, tag_bytes); -} - -} // namespace webcpp::crypto - #endif // WEBCPP_CRYPTO_CIPHERS_AEAD_HPP diff --git a/include/webcpp/crypto/ciphers/aes.hpp b/include/webcpp/crypto/ciphers/aes.hpp index 8931225f..98d4b30f 100644 --- a/include/webcpp/crypto/ciphers/aes.hpp +++ b/include/webcpp/crypto/ciphers/aes.hpp @@ -200,7 +200,7 @@ class basic_aes { */ [[nodiscard]] boost::system::result encrypt( std::span block_bytes) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; if (!keyed_) { return error::invalid_state; } @@ -219,7 +219,7 @@ class basic_aes { */ [[nodiscard]] boost::system::result decrypt( std::span block_bytes) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; if (!keyed_) { return error::invalid_state; } @@ -230,18 +230,18 @@ class basic_aes { } protected: - /** An empty object, which `make_as` keys. */ + /** An empty object, which `keyed_as` keys. */ basic_aes() noexcept = default; /** - * The work of `make`, after which the derived type is the result. + * The work of `from_key`, after which the derived type is the result. * * @tparam Derived `aes128`, `aes192` or `aes256`. * @param key_bytes The key. * @return The cipher; `invalid_key_size`; the backend's errors. */ template - [[nodiscard]] static boost::system::result make_as( + [[nodiscard]] static boost::system::result keyed_as( std::span key_bytes) noexcept { if (key_bytes.size() != key_size) { return error::invalid_key_size; @@ -279,10 +279,10 @@ class aes128 : public detail::basic_aes<16, Backend> { * @param key_bytes 16 bytes. * @return The cipher; `invalid_key_size`; the backend's errors. */ - [[nodiscard]] static boost::system::result make( + [[nodiscard]] static boost::system::result from_key( std::span key_bytes) noexcept { - detail::timing_guard const timing; - return detail::basic_aes<16, Backend>::template make_as(key_bytes); + detail::timing_guard const timing_scope; + return detail::basic_aes<16, Backend>::template keyed_as(key_bytes); } private: @@ -305,10 +305,10 @@ class aes192 : public detail::basic_aes<24, Backend> { * @param key_bytes 24 bytes. * @return The cipher; `invalid_key_size`; the backend's errors. */ - [[nodiscard]] static boost::system::result make( + [[nodiscard]] static boost::system::result from_key( std::span key_bytes) noexcept { - detail::timing_guard const timing; - return detail::basic_aes<24, Backend>::template make_as(key_bytes); + detail::timing_guard const timing_scope; + return detail::basic_aes<24, Backend>::template keyed_as(key_bytes); } private: @@ -331,10 +331,10 @@ class aes256 : public detail::basic_aes<32, Backend> { * @param key_bytes 32 bytes. * @return The cipher; `invalid_key_size`; the backend's errors. */ - [[nodiscard]] static boost::system::result make( + [[nodiscard]] static boost::system::result from_key( std::span key_bytes) noexcept { - detail::timing_guard const timing; - return detail::basic_aes<32, Backend>::template make_as(key_bytes); + detail::timing_guard const timing_scope; + return detail::basic_aes<32, Backend>::template keyed_as(key_bytes); } private: diff --git a/include/webcpp/crypto/ciphers/chacha20_poly1305.hpp b/include/webcpp/crypto/ciphers/chacha20_poly1305.hpp index bd7cd3b6..120cbc98 100644 --- a/include/webcpp/crypto/ciphers/chacha20_poly1305.hpp +++ b/include/webcpp/crypto/ciphers/chacha20_poly1305.hpp @@ -6,10 +6,16 @@ /** `chacha20_poly1305`, `chacha20_poly1305_original` and `xchacha20_poly1305`, the - ChaCha20-Poly1305 AEADs of `aead`, each on its family's default backend unless the type names - another: libsodium on every target, whose header it includes when the program links it - (`default_backend_t`). A program that uses them without linking the default stops where it - calls them, with the Jamfile line that links it. + ChaCha20-Poly1305 AEADs of `aead`, each a `secret_key_encryption::aead::cipher` (design D5) on + its family's default backend unless the type names another: libsodium on every target, whose + header it includes when the program links it (`default_backend_t`). A program that uses them + without linking the default stops where it calls them, with the Jamfile line that links it. + `ciphers/aead.hpp`, which it includes, brings their free forms, `secret_key_encryption::aead::seal` + and `open`. + + 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-Poly1305", in the guide. */ @@ -36,7 +42,7 @@ namespace webcpp::crypto::ciphers { * @tparam Backend The backend; the default is the family's. */ template > -using chacha20_poly1305 = aead; +using chacha20_poly1305 = basic_chacha20_poly1305; /** * The original ChaCha20-Poly1305: a 32-byte key, an 8-byte nonce, a 16-byte tag. @@ -44,7 +50,8 @@ using chacha20_poly1305 = aead; * @tparam Backend The backend; the default is the family's. */ template > -using chacha20_poly1305_original = aead; +using chacha20_poly1305_original = + basic_chacha20_poly1305; /** * XChaCha20-Poly1305: a 32-byte key, a 24-byte nonce safe to draw at random, a 16-byte tag. @@ -52,7 +59,17 @@ using chacha20_poly1305_original = aead> -using xchacha20_poly1305 = aead; +using xchacha20_poly1305 = basic_chacha20_poly1305; + +// Each is a one-shot AEAD, which seals no message in pieces (design D5's table). +static_assert( + secret_key_encryption::aead::cipher>); +static_assert( + secret_key_encryption::aead::cipher>); +static_assert( + secret_key_encryption::aead::cipher>); +static_assert(!secret_key_encryption::aead::streaming_cipher< + chacha20_poly1305>); } // namespace webcpp::crypto::ciphers diff --git a/include/webcpp/crypto/ciphers/gcm.hpp b/include/webcpp/crypto/ciphers/gcm.hpp index 67b7f2b6..d2596ee9 100644 --- a/include/webcpp/crypto/ciphers/gcm.hpp +++ b/include/webcpp/crypto/ciphers/gcm.hpp @@ -7,8 +7,10 @@ /** `gcm`, AES-GCM over the cipher's backend. - Its free synchronous forms (design D9, R23), `crypto::make(key)`, `crypto::seal` and - `crypto::open`, are declared in `make.hpp` and `ciphers/aead.hpp`, which it includes. + A `secret_key_encryption::aead::streaming_cipher` (design D5). Its free synchronous forms + (design D9, D11), `crypto::from_key(key)`, `secret_key_encryption::aead::seal` and + `secret_key_encryption::aead::open`, are declared in `factories.hpp` and + `secret_key_encryption/aead.hpp`, which it includes. @see "AES-GCM", in the guide. */ @@ -17,7 +19,6 @@ #include -#include // crypto::seal and crypto::open (design R23) #include #include #include @@ -27,7 +28,8 @@ #include #include #include -#include // crypto::make, which serves its make (design R23) +#include // crypto::from_key, which serves its from_key (design R23) +#include // its free seal and open (design D11) #include #include @@ -115,8 +117,8 @@ namespace webcpp::crypto::ciphers { * (`default_backend_t`), not the block cipher's. * * An object holds a key and the state of one message: it is used by one thread at a time, - * and it is not shareable. An IV is never reused under one key, and with random IVs, or IVs - * other than 12 bytes, a key seals at most 2^32 messages (NIST SP 800-38D section 8.3). + * and it is not shareable. A nonce is never reused under one key, and with random nonces, or + * nonces other than 12 bytes, a key seals at most 2^32 messages (NIST SP 800-38D section 8.3). * * The incremental open reads the ciphertext twice: `authenticate` every piece, `verify` the * tag, then `decrypt` the same pieces; no plaintext reaches the caller before the tag matched. @@ -150,14 +152,14 @@ class gcm { static constexpr std::size_t key_size = Cipher::key_size; /** The tag's size. */ static constexpr std::size_t tag_size = 16; - /** The recommended IV size. */ - static constexpr std::size_t iv_size = 12; - /** The longest IV accepted, OpenSSL's limit, applied on every backend. */ - static constexpr std::size_t max_iv_size = 128; + /** The recommended nonce size. */ + static constexpr std::size_t nonce_size = 12; + /** The longest nonce accepted, OpenSSL's limit, applied on every backend. */ + static constexpr std::size_t max_nonce_size = 128; /** The longest message, 2^36 - 32 bytes (NIST SP 800-38D section 5.2.1.1). */ static constexpr std::uint64_t max_message_size = (std::uint64_t{1} << 36U) - 32; - /** The longest additional data, 2^61 - 1 bytes (the same section, 2^64 - 1 bits). */ - static constexpr std::uint64_t max_additional_data_size = (std::uint64_t{1} << 61U) - 1; + /** The longest associated data, 2^61 - 1 bytes (the same section, 2^64 - 1 bits). */ + static constexpr std::uint64_t max_associated_data_size = (std::uint64_t{1} << 61U) - 1; /** * Expands a key into a new object. @@ -165,12 +167,12 @@ class gcm { * @param key_bytes `key_size` bytes. * @return The object; `invalid_key_size`, `errc::not_enough_memory` or `backend_failure`. */ - [[nodiscard]] static boost::system::result make( + [[nodiscard]] static boost::system::result from_key( std::span key_bytes) noexcept { - detail::timing_guard const timing; - static_assert( - !detail::asynchronous_backend_v, - "webcpp::crypto: make on this backend completes asynchronously: call async_make."); + detail::timing_guard const timing_scope; + static_assert(!detail::asynchronous_backend_v, + "webcpp::crypto: from_key on this backend completes asynchronously: call " + "async_from_key."); if constexpr (detail::asynchronous_backend_v) { // Never compiled into a program: the assertion above stopped the build. return error::backend_failure; @@ -189,26 +191,28 @@ class gcm { } /** - * Expands a key into a new object, asynchronously: `make` run when the operation is - * initiated, its result posted to `executor`; the member form of - * `crypto::async_make(executor, key_bytes, token)`, which calls it. + * Expands a key into a new object, 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. * * 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 `token` states. - * @param executor The executor the completion is posted to. + * @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 token The completion token, of signature `void(boost::system::error_code, gcm)`; on - * an error the object is empty, and every member refuses with `invalid_state` - * (`invalid_key_size`, `errc::not_enough_memory`, `backend_failure`). + * @param completion_token The completion token, of signature + * `void(boost::system::error_code, gcm)`; on an error the object is empty, and every member + * refuses with `invalid_state` (`invalid_key_size`, `errc::not_enough_memory`, + * `backend_failure`). * @return What the completion token's `async_result` gives. */ template - static auto async_make(Executor const& executor, std::span key_bytes, - CompletionToken&& token); + static auto async_from_key(Executor const& completion_executor, + std::span key_bytes, + CompletionToken&& completion_token); /** * Moves the key; a message in progress is abandoned, and the source is wiped and empty. @@ -219,7 +223,7 @@ class gcm { * @param moved_source The source, empty afterwards. */ gcm(gcm&& moved_source) noexcept : keyed_(std::exchange(moved_source.keyed_, false)) { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; if (keyed_) { moved_source.abandon_message(); engine::move(state_, moved_source.state_); @@ -235,7 +239,7 @@ class gcm { * @return This object. */ gcm& operator=(gcm&& moved_source) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; if (this != &moved_source) { engine::reset(state_); keyed_ = std::exchange(moved_source.keyed_, false); @@ -260,22 +264,23 @@ class gcm { /** * Seals a message in place: `data_bytes` holds the plaintext before and the ciphertext after. * - * The IV and the additional data are read before the first byte of `data_bytes` is written, so - * they may lie in `data_bytes`. + * The nonce and the associated data are read before the first byte of `data_bytes` is written, + * so they may lie in `data_bytes`. * * When the backend fails, `data_bytes` is zeroed, as a failed open's is; a guard's refusal * leaves it untouched. * - * @param iv_bytes 1 to `max_iv_size` bytes, never reused under this key; 12 recommended. - * @param additional_data_bytes Authenticated, not encrypted. + * @param nonce_bytes 1 to `max_nonce_size` bytes, never reused under this key; 12 recommended. + * @param associated_data_bytes Authenticated, not encrypted. * @param data_bytes The message. * @return The tag; `invalid_state` moved from or during an incremental message, which - * goes on; `invalid_iv_size`; `message_too_long`; `backend_failure`. + * goes on; `invalid_nonce_size`; `message_too_long`; `backend_failure`. */ [[nodiscard]] boost::system::result seal( - std::span iv_bytes, std::span additional_data_bytes, + std::span nonce_bytes, + std::span associated_data_bytes, std::span data_bytes) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert( !detail::asynchronous_backend_v, "webcpp::crypto: seal on this backend completes asynchronously: call async_seal."); @@ -284,11 +289,12 @@ class gcm { return error::backend_failure; } else { auto const guard_result = - guard_message(iv_bytes, additional_data_bytes, data_bytes.size(), tag_size); + guard_message(nonce_bytes, associated_data_bytes, data_bytes.size(), tag_size); if (!guard_result) { return guard_result.error(); } - auto const start_result = engine::start(state_, true, iv_bytes, additional_data_bytes); + auto const start_result = + engine::start(state_, true, nonce_bytes, associated_data_bytes); auto const run_result = start_result ? engine::run(state_, data_bytes) : start_result; result_type tag_bytes{}; auto const tag_result = run_result ? engine::tag(state_, tag_bytes) : run_result; @@ -305,9 +311,9 @@ class gcm { /** * Seals a message in place, asynchronously: `seal` run when the operation is initiated, its - * result posted to `executor`; the member form of - * `crypto::async_seal(executor, aead, iv_bytes, additional_data_bytes, data_bytes, token)`, - * which calls it. + * result posted to `completion_executor`; the member form of + * `secret_key_encryption::aead::async_seal(executor, aead, nonce_bytes, associated_data_bytes, + * data_bytes, token)`, which calls it. * * The object and the spans are the caller's until the completion; `data_bytes` holds the * ciphertext at the completion. @@ -317,20 +323,20 @@ class gcm { * "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 `token` states. - * @param executor The executor the completion is posted to. - * @param iv_bytes 1 to `max_iv_size` bytes, never reused under this key. - * @param additional_data_bytes Authenticated, not encrypted. + * @tparam CompletionToken Any completion token for the signature `completion_token` states. + * @param completion_executor The executor the completion is posted to. + * @param nonce_bytes 1 to `max_nonce_size` bytes, never reused under this key. + * @param associated_data_bytes Authenticated, not encrypted. * @param data_bytes The message. - * @param token The completion token, of signature + * @param completion_token The completion token, of signature * `void(boost::system::error_code, result_type)`: the tag; on an error the zeroed tag (the * errors of `seal`). * @return What the completion token's `async_result` gives. */ template - auto async_seal(Executor const& executor, std::span iv_bytes, - std::span additional_data_bytes, - std::span data_bytes, CompletionToken&& token); + auto async_seal(Executor const& completion_executor, std::span nonce_bytes, + std::span associated_data_bytes, + std::span data_bytes, CompletionToken&& completion_token); /** * Opens a message in place: `data_bytes` holds the ciphertext before and the plaintext after. @@ -339,18 +345,19 @@ class gcm { * tag does not match, or the backend fails, `data_bytes` is zeroed. A guard's refusal leaves it * untouched. * - * @param iv_bytes The IV of the seal. - * @param additional_data_bytes The additional data of the seal. + * @param nonce_bytes The nonce of the seal. + * @param associated_data_bytes The associated data of the seal. * @param data_bytes The ciphertext. * @param tag_bytes The seal's tag, 16 bytes, which may lie anywhere, `data_bytes` included. * @return Nothing; `invalid_state` moved from or during an incremental message, which - * goes on; `invalid_iv_size`; `invalid_tag_size`; `message_too_long`; + * goes on; `invalid_nonce_size`; `invalid_tag_size`; `message_too_long`; * `authentication_failed`; `backend_failure`. */ [[nodiscard]] boost::system::result open( - std::span iv_bytes, std::span additional_data_bytes, - std::span data_bytes, std::span tag_bytes) noexcept { - detail::timing_guard const timing; + std::span nonce_bytes, + std::span associated_data_bytes, std::span data_bytes, + std::span tag_bytes) noexcept { + detail::timing_guard const timing_scope; static_assert( !detail::asynchronous_backend_v, "webcpp::crypto: open on this backend completes asynchronously: call async_open."); @@ -358,15 +365,16 @@ class gcm { // Never compiled into a program: the assertion above stopped the build. return error::backend_failure; } else { - auto const guard_result = - guard_message(iv_bytes, additional_data_bytes, data_bytes.size(), tag_bytes.size()); + auto const guard_result = guard_message(nonce_bytes, associated_data_bytes, + data_bytes.size(), tag_bytes.size()); if (!guard_result) { return guard_result.error(); } // The tag may lie in data, which decryption overwrites: a copy is checked. std::array expected_tag{}; std::ranges::copy(tag_bytes, expected_tag.begin()); - auto const start_result = engine::start(state_, false, iv_bytes, additional_data_bytes); + auto const start_result = + engine::start(state_, false, nonce_bytes, associated_data_bytes); auto const open_result = start_result ? engine::run(state_, data_bytes) : start_result; auto const tag_check_result = open_result ? engine::check(state_, expected_tag) : open_result; @@ -381,8 +389,9 @@ class gcm { /** * Opens a message in place, asynchronously: `open` run when the operation is initiated, its - * result posted to `executor`; the member form of `crypto::async_open`, which calls it with the - * executor and the object before this function's arguments. + * 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. * * The object and the spans are the caller's until the completion; `data_bytes` holds the * plaintext at a successful completion. @@ -392,38 +401,38 @@ class gcm { * "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 `token` states. - * @param executor The executor the completion is posted to. - * @param iv_bytes The IV of the seal. - * @param additional_data_bytes The additional data of the seal. + * @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 of the seal. + * @param associated_data_bytes The associated data of the seal. * @param data_bytes The ciphertext. * @param tag_bytes The seal's tag, 16 bytes. - * @param token The completion token, of signature `void(boost::system::error_code)` (`open`'s - * errors). + * @param completion_token The completion token, of signature `void(boost::system::error_code)` + * (`open`'s errors). * @return What the completion token's `async_result` gives. */ template - auto async_open(Executor const& executor, std::span iv_bytes, - std::span additional_data_bytes, + auto async_open(Executor const& completion_executor, std::span nonce_bytes, + std::span associated_data_bytes, std::span data_bytes, std::span tag_bytes, - CompletionToken&& token); + CompletionToken&& completion_token); /** - * Begins an incremental seal: the IV and the whole additional data first, both read + * Begins an incremental seal: the nonce and the whole associated data first, both read * before this returns. * * Any error of `begin_seal`, `update` or `result` ends the message, which is abandoned: * the pieces already encrypted have no tag and are not to be sent. * - * @param iv_bytes 1 to `max_iv_size` bytes, never reused under this key. - * @param additional_data_bytes Authenticated, not encrypted. + * @param nonce_bytes 1 to `max_nonce_size` bytes, never reused under this key. + * @param associated_data_bytes Authenticated, not encrypted. * @return Nothing; `invalid_state` moved from or with a message in progress, which ends - * it; `invalid_iv_size`; `message_too_long`; `backend_failure`. + * it; `invalid_nonce_size`; `message_too_long`; `backend_failure`. */ [[nodiscard]] boost::system::result begin_seal( - std::span iv_bytes, - std::span additional_data_bytes) noexcept { - detail::timing_guard const timing; + std::span nonce_bytes, + std::span associated_data_bytes) noexcept { + detail::timing_guard const timing_scope; if (!keyed_) { return error::invalid_state; } @@ -431,11 +440,11 @@ class gcm { abandon(); return error::invalid_state; } - auto const guard_result = guard_message(iv_bytes, additional_data_bytes, 0, tag_size); + auto const guard_result = guard_message(nonce_bytes, associated_data_bytes, 0, tag_size); if (!guard_result) { return guard_result.error(); } - auto const start_result = engine::start(state_, true, iv_bytes, additional_data_bytes); + auto const start_result = engine::start(state_, true, nonce_bytes, associated_data_bytes); if (!start_result) { engine::abandon(state_); return start_result.error(); @@ -457,7 +466,7 @@ class gcm { * `backend_failure`, which ends it. */ [[nodiscard]] boost::system::result update(std::span data_bytes) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; auto const phase_result = require_phase(phase::sealing); if (!phase_result) { return phase_result.error(); @@ -483,7 +492,7 @@ class gcm { * `backend_failure`, which ends the seal too. */ [[nodiscard]] boost::system::result result() noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; auto const phase_result = require_phase(phase::sealing); if (!phase_result) { return phase_result.error(); @@ -499,22 +508,22 @@ class gcm { } /** - * Begins an incremental open: the IV and the whole additional data first, both read before - * this returns, the IV kept for the second pass. + * Begins an incremental open: the nonce and the whole associated data first, both read before + * this returns, the nonce kept for the second pass. * * The open takes two passes over the ciphertext: `authenticate` reads every piece, `verify` * checks the tag, and only then `decrypt` turns the same pieces into plaintext, which * `end_open` ends. Any error of these calls ends the message. * - * @param iv_bytes The IV of the seal, 1 to `max_iv_size` bytes. - * @param additional_data_bytes The additional data of the seal. + * @param nonce_bytes The nonce of the seal, 1 to `max_nonce_size` bytes. + * @param associated_data_bytes The associated data of the seal. * @return Nothing; `invalid_state` moved from or with a message in progress, which ends - * it; `invalid_iv_size`; `message_too_long`; `backend_failure`. + * it; `invalid_nonce_size`; `message_too_long`; `backend_failure`. */ [[nodiscard]] boost::system::result begin_open( - std::span iv_bytes, - std::span additional_data_bytes) noexcept { - detail::timing_guard const timing; + std::span nonce_bytes, + std::span associated_data_bytes) noexcept { + detail::timing_guard const timing_scope; if (!keyed_) { return error::invalid_state; } @@ -522,13 +531,13 @@ class gcm { abandon(); return error::invalid_state; } - auto const guard_result = guard_message(iv_bytes, additional_data_bytes, 0, tag_size); + auto const guard_result = guard_message(nonce_bytes, associated_data_bytes, 0, tag_size); if (!guard_result) { return guard_result.error(); } - std::ranges::copy(iv_bytes, iv_.begin()); - iv_size_ = iv_bytes.size(); - auto const start_result = engine::start(state_, false, iv_bytes, additional_data_bytes); + std::ranges::copy(nonce_bytes, nonce_.begin()); + nonce_size_ = nonce_bytes.size(); + auto const start_result = engine::start(state_, false, nonce_bytes, associated_data_bytes); if (!start_result) { engine::abandon(state_); end_message(); @@ -554,7 +563,7 @@ class gcm { */ [[nodiscard]] boost::system::result authenticate( std::span ciphertext_piece) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; auto const phase_result = require_phase(phase::authenticating); if (!phase_result) { return phase_result.error(); @@ -563,14 +572,14 @@ class gcm { abandon(); return error::message_too_long; } - std::array scratch{}; + std::array scratch_bytes{}; for (std::size_t piece_start = 0; piece_start < ciphertext_piece.size(); piece_start += scratch_size) { std::size_t const block_size = (std::min)(scratch_size, ciphertext_piece.size() - piece_start); - std::copy_n(ciphertext_piece.data() + piece_start, block_size, scratch.data()); - auto const run_result = engine::run(state_, std::span(scratch).first(block_size)); - detail::wipe(scratch.data(), block_size); + std::copy_n(ciphertext_piece.data() + piece_start, block_size, scratch_bytes.data()); + auto const run_result = engine::run(state_, std::span(scratch_bytes).first(block_size)); + detail::wipe(scratch_bytes.data(), block_size); if (!run_result) { abandon(); return run_result.error(); @@ -591,7 +600,7 @@ class gcm { */ [[nodiscard]] boost::system::result verify( std::span tag_bytes) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; auto const phase_result = require_phase(phase::authenticating); if (!phase_result) { return phase_result.error(); @@ -607,10 +616,11 @@ class gcm { abandon(); return check_result.error(); } - // GCM's keystream depends on the key and the IV alone: the second pass needs no - // additional data, and the tag the engine computes in it is never read. + // GCM's keystream depends on the key and the nonce alone: the second pass needs no + // associated data, and the tag the engine computes in it is never read. engine::abandon(state_); - auto const start_result = engine::start(state_, false, std::span(iv_).first(iv_size_), {}); + auto const start_result = + engine::start(state_, false, std::span(nonce_).first(nonce_size_), {}); if (!start_result) { abandon(); return start_result.error(); @@ -633,7 +643,7 @@ class gcm { * the message; `backend_failure`, which ends it. */ [[nodiscard]] boost::system::result decrypt(std::span data_piece) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; auto const phase_result = require_phase(phase::decrypting); if (!phase_result) { return phase_result.error(); @@ -660,14 +670,14 @@ class gcm { * which ends the message too. */ [[nodiscard]] boost::system::result end_open() noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; auto const phase_result = require_phase(phase::decrypting); if (!phase_result) { return phase_result.error(); } - bool const whole = decrypted_bytes_ == message_bytes_; + bool const whole_message = decrypted_bytes_ == message_bytes_; abandon(); - if (!whole) { + if (!whole_message) { return error::invalid_input_size; } return {}; @@ -685,13 +695,13 @@ class gcm { gcm() noexcept = default; - // A call of the incremental machine in `expected`: outside it, `invalid_state`, which ends - // a message in another phase. - [[nodiscard]] boost::system::result require_phase(phase expected) noexcept { + // A call of the incremental machine in `expected_phase`: outside it, `invalid_state`, which + // ends a message in another phase. + [[nodiscard]] boost::system::result require_phase(phase expected_phase) noexcept { if (!keyed_) { return error::invalid_state; } - if (phase_ != expected) { + if (phase_ != expected_phase) { if (phase_ != phase::none) { abandon(); } @@ -715,32 +725,33 @@ class gcm { } } - // Every guard of a message, in the documented order: the state, the IV, the tag + // Every guard of a message, in the documented order: the state, the nonce, the tag // (open's; seal passes tag_size), the lengths. None reads a byte of the spans. [[nodiscard]] boost::system::result guard_message( - std::span iv_bytes, std::span additional_data_bytes, - std::size_t byte_count, std::size_t tag_bytes) const noexcept { + std::span nonce_bytes, + std::span associated_data_bytes, std::size_t byte_count, + std::size_t tag_bytes) const noexcept { if (!keyed_ || phase_ != phase::none) { return error::invalid_state; } - if (iv_bytes.empty() || iv_bytes.size() > max_iv_size) { - return error::invalid_iv_size; + if (nonce_bytes.empty() || nonce_bytes.size() > max_nonce_size) { + return error::invalid_nonce_size; } if (tag_bytes != tag_size) { return error::invalid_tag_size; } if (detail::exceeds(byte_count, max_message_size) || - detail::exceeds(additional_data_bytes.size(), max_additional_data_size)) { + detail::exceeds(associated_data_bytes.size(), max_associated_data_size)) { return error::message_too_long; } return {}; } - // No message is in progress; the kept IV is wiped and the counters zeroed. + // No message is in progress; the kept nonce is wiped and the counters zeroed. void end_message() noexcept { phase_ = phase::none; - detail::wipe(iv_.data(), iv_.size()); - iv_size_ = 0; + detail::wipe(nonce_.data(), nonce_.size()); + nonce_size_ = 0; message_bytes_ = 0; decrypted_bytes_ = 0; } @@ -748,15 +759,21 @@ class gcm { state_type state_{}; bool keyed_ = false; phase phase_ = phase::none; - // The open's IV, kept for its second pass. - std::array iv_{}; - std::size_t iv_size_ = 0; + // The open's nonce, kept for its second pass. + std::array nonce_{}; + std::size_t nonce_size_ = 0; // The bytes sealed, or authenticated by the open's first pass. std::uint64_t message_bytes_ = 0; // The bytes decrypted by the open's second pass. std::uint64_t decrypted_bytes_ = 0; }; +// AES-GCM is an AEAD that also seals and opens in pieces (design D5's table). +static_assert( + secret_key_encryption::aead::streaming_cipher>>); +static_assert( + secret_key_encryption::aead::streaming_cipher>>); + } // namespace webcpp::crypto::ciphers #endif // WEBCPP_CRYPTO_CIPHERS_GCM_HPP diff --git a/include/webcpp/crypto/ciphers/secretbox.hpp b/include/webcpp/crypto/ciphers/secretbox.hpp deleted file mode 100644 index 77594928..00000000 --- a/include/webcpp/crypto/ciphers/secretbox.hpp +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) 2026 WebCpp.org -// -// Distributed under the Boost Software License, Version 1.0. (See -// accompanying file LICENSE_1_0.txt or copy at -// https://www.boost.org/LICENSE_1_0.txt) - -/** - `secretbox` and `secretbox_xchacha20poly1305`, NaCl's and libsodium's secret boxes as `aead`s - without additional data, each on its family's default backend unless the type names another: - libsodium on every target, whose header it includes when the program links it - (`default_backend_t`). A program that uses them without linking the default stops where it - calls them, with the Jamfile line that links it. - - @see "Secret boxes", in the guide. -*/ -#ifndef WEBCPP_CRYPTO_CIPHERS_SECRETBOX_HPP -#define WEBCPP_CRYPTO_CIPHERS_SECRETBOX_HPP - -#include - -#include -#include - -#if (defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_SECRETBOX_XSALSA20POLY1305_SODIUM) || \ - defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_SECRETBOX_XCHACHA20POLY1305_SODIUM)) && \ - defined(WEBCPP_CRYPTO_HAS_SODIUM) -#include -#endif - -namespace webcpp::crypto::ciphers { - -/** - * NaCl's and libsodium's `crypto_secretbox`, XSalsa20-Poly1305: a 32-byte key, a 24-byte nonce - * safe to draw at random, a 16-byte tag, and no additional data, which `seal` and `open` refuse - * unless empty (`invalid_input_size`). - * - * @tparam Backend The backend; the default is the family's. - */ -template > -using secretbox = aead; - -/** - * libsodium's `crypto_secretbox_xchacha20poly1305`: the secret box with XChaCha20 in place of - * XSalsa20, of the same sizes and without additional data. - * - * @tparam Backend The backend; the default is the family's. - */ -template > -using secretbox_xchacha20poly1305 = aead; - -} // namespace webcpp::crypto::ciphers - -#endif // WEBCPP_CRYPTO_CIPHERS_SECRETBOX_HPP diff --git a/include/webcpp/crypto/equal.hpp b/include/webcpp/crypto/constant_time_equal.hpp similarity index 71% rename from include/webcpp/crypto/equal.hpp rename to include/webcpp/crypto/constant_time_equal.hpp index 75a689c0..233dec67 100644 --- a/include/webcpp/crypto/equal.hpp +++ b/include/webcpp/crypto/constant_time_equal.hpp @@ -5,10 +5,10 @@ // https://www.boost.org/LICENSE_1_0.txt) /** - `equal`, the constant-time comparison of tags and MACs, Boost.Hash2's included. + `constant_time_equal`, the constant-time comparison of tags and MACs, Boost.Hash2's included. */ -#ifndef WEBCPP_CRYPTO_EQUAL_HPP -#define WEBCPP_CRYPTO_EQUAL_HPP +#ifndef WEBCPP_CRYPTO_CONSTANT_TIME_EQUAL_HPP +#define WEBCPP_CRYPTO_CONSTANT_TIME_EQUAL_HPP #include @@ -35,9 +35,10 @@ namespace webcpp::crypto { * @param second_operand The second. * @return Whether they have the same size and the same bytes. */ -[[nodiscard]] inline bool equal(std::span first_operand, - std::span second_operand) noexcept { - detail::timing_guard const timing; +[[nodiscard]] inline bool constant_time_equal( + std::span first_operand, + std::span second_operand) noexcept { + detail::timing_guard const timing_scope; if (first_operand.size() != second_operand.size()) { return false; } @@ -64,13 +65,13 @@ namespace webcpp::crypto { * @return Whether every byte is equal. */ template -[[nodiscard]] bool equal(boost::hash2::digest const& first_operand, - boost::hash2::digest const& second_operand) noexcept { - detail::timing_guard const timing; - return equal(std::span(first_operand.data(), N), - std::span(second_operand.data(), N)); +[[nodiscard]] bool constant_time_equal(boost::hash2::digest const& first_operand, + boost::hash2::digest const& second_operand) noexcept { + detail::timing_guard const timing_scope; + return constant_time_equal(std::span(first_operand.data(), N), + std::span(second_operand.data(), N)); } } // namespace webcpp::crypto -#endif // WEBCPP_CRYPTO_EQUAL_HPP +#endif // WEBCPP_CRYPTO_CONSTANT_TIME_EQUAL_HPP diff --git a/include/webcpp/crypto/curves/ed25519.hpp b/include/webcpp/crypto/curves/ed25519.hpp index f0a017c6..b9cfd8e0 100644 --- a/include/webcpp/crypto/curves/ed25519.hpp +++ b/include/webcpp/crypto/curves/ed25519.hpp @@ -6,16 +6,21 @@ /** Ed25519 signatures (RFC 8032): a key pair made from a 32-byte seed, which `secret()` gives back, - and its public key, `curves::ed25519::public_key`; signatures of 64 bytes, - `key.sign(crypto::eddsa, message)`, and their verification, - `crypto::verify(crypto::eddsa, signature, message, public_key)`, strict on libsodium; the - conversion of a public key to X25519's; and Ed25519ph, the same signature over SHA-512 of a - message given in pieces. + and its public key, `curves::ed25519::public_key`; signatures, `curves::ed25519::signature` of 64 + bytes, `key.sign(crypto::eddsa, message)`, and their verification, + `crypto::verify(crypto::eddsa, signature, message, public_key)`, strict on libsodium; Ed25519ph, + the signature of a message's SHA-512, under the scheme `crypto::eddsa_prehashed` from the digest + and by `curves::ed25519::prehashed_signer` from the message given in pieces; and the conversion + of a key pair and of a public key to X25519's typed keys, `to_x25519()`, member and free. The family's default backend, libsodium on every target, is included when the program links it; a program that uses the family without linking it stops where it calls it, with the Jamfile line that links it. + 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 "Ed25519", in the guide. */ #ifndef WEBCPP_CRYPTO_CURVES_ED25519_HPP @@ -23,16 +28,19 @@ #include +#include // to_x25519()'s keys #include #include #include #include +#include #include #include #include #include // lint-world: random_device draws generate()'s seed #include #include +#include #include // webcpp::hash::sha2_512, Ed25519ph's hash (design D1) #include @@ -73,12 +81,18 @@ struct ed25519ph_engine; template struct ed25519_keypair_access; +/** The tag of `curves::ed25519::signature`. */ +struct ed25519_signature_tag { + /** No recovery id. */ + static constexpr bool recoverable = false; +}; + } // namespace webcpp::crypto::detail namespace webcpp::crypto::curves::ed25519 { template -class ph; +class prehashed_signer; /** * The type of the verification policy `strict`. @@ -96,6 +110,19 @@ struct strict_t { */ inline constexpr strict_t strict{}; +/** + * An Ed25519 signature (RFC 8032), 64 bytes, R then S: what `sign(crypto::eddsa, ...)`, + * `sign(crypto::eddsa_prehashed, ...)` and `prehashed_signer::sign` give, and `crypto::verify` of + * either scheme takes. + * + * One type for the two schemes, which are not interchangeable: RFC 8032 separates their domains, + * so a signature verifies under the scheme that made it alone, and a protocol says which it uses. + * + * `from_bytes` checks the size alone; whether S is below the group order and R canonical is the + * verification policy's judgment. + */ +using signature = detail::basic_signature; + } // namespace webcpp::crypto::curves::ed25519 namespace webcpp::crypto::detail { @@ -107,25 +134,49 @@ namespace webcpp::crypto::detail { * @tparam Backend The backend. * @tparam Policy `curves::ed25519::strict_t`; anything else stops the build. * @tparam Input A message; anything else stops the build. - * @param signature_bytes 64 bytes. + * @param signature_bytes The signature's 64 bytes. * @param message_input The signed bytes. * @param key_bytes The public key's 32 bytes. - * @return Nothing; `invalid_signature` for a signature of another size, and for one that does not - * verify. + * @return Nothing; `invalid_signature` for a signature that does not verify. */ template [[nodiscard]] boost::system::result ed25519_verify( - std::span signature_bytes, Input const& message_input, + std::span signature_bytes, Input const& message_input, std::span key_bytes) noexcept { static_assert(std::is_same_v, "webcpp::crypto: Ed25519's only verification policy is curves::ed25519::strict."); check_input(); if constexpr (input_valid_v) { - if (signature_bytes.size() != 64) { - return error::invalid_signature; - } return ed25519_engine::verify( - key_bytes, message_bytes(message_input), signature_bytes.first<64>()); + key_bytes, message_bytes(message_input), signature_bytes); + } else { + // Never compiled into a program: check_input stopped the build. + return error::invalid_signature; + } +} + +/** + * Verifies an Ed25519ph signature of a digest on `Backend` under `Policy`: the work of + * `public_key::verify` and of `crypto::verify` of `eddsa_prehashed`, which hold the guard. + * + * @tparam Backend The backend. + * @tparam Policy `curves::ed25519::strict_t`; anything else stops the build. + * @tparam Input `prehashed<64>`; anything else stops the build. + * @param signature_bytes The signature's 64 bytes. + * @param digest_input The marker of the message's SHA-512. + * @param key_bytes The public key's 32 bytes. + * @return Nothing; `invalid_signature` for a signature that does not verify. + */ +template +[[nodiscard]] boost::system::result ed25519ph_verify( + std::span signature_bytes, Input const& digest_input, + std::span key_bytes) noexcept { + static_assert(std::is_same_v, + "webcpp::crypto: Ed25519's only verification policy is curves::ed25519::strict."); + check_input(); + if constexpr (input_valid_v) { + return ed25519ph_engine::verify_digest( + key_bytes, digest_input.digest, signature_bytes); } else { // Never compiled into a program: check_input stopped the build. return error::invalid_signature; @@ -140,10 +191,10 @@ namespace webcpp::crypto::curves::ed25519 { * An Ed25519 public key (RFC 8032): the 32 bytes of the encoded point A, which * `crypto::verify(crypto::eddsa, ...)` takes. * - * `make` checks the size alone (design R16): whether the point is canonical and not of small + * `from_bytes` checks the size alone (design R16): whether the point is canonical and not of small * order is the verification policy's judgment (`strict` refuses both), so the type does not * prejudge it, and a key `crypto::verify` refuses may still be made. It holds nothing secret and - * is copied freely; it is made only by `make` and by a key pair's `public_key()`. + * is copied freely; it is made only by `from_bytes` and by a key pair's `public_key()`. */ class public_key { public: @@ -157,7 +208,7 @@ class public_key { * @param key_bytes 32 bytes. * @return The public key; `invalid_public_key` for another size. */ - [[nodiscard]] static boost::system::result make( + [[nodiscard]] static boost::system::result from_bytes( std::span key_bytes) noexcept { if (key_bytes.size() != size) { return error::invalid_public_key; @@ -176,49 +227,101 @@ class public_key { /** * Verifies an Ed25519 signature (RFC 8032's pure Ed25519) with this key, under a verification - * policy (design D31): `crypto::verify(crypto::eddsa, signature_bytes, message_input, key, - * verify_policy)`, of which it is the member form, with the same work, results and refusals. + * policy (design D31): + * `crypto::verify(crypto::eddsa, signature_value, message_input, key, verify_policy)`, of which + * it is the member form, with the same work, results and refusals. + * + * Ed25519ph's is the overload of `crypto::eddsa_prehashed`. * * @tparam Backend The backend; by default the family's. * @tparam Scheme `crypto::eddsa_t`; another scheme stops the build. + * @tparam Signature `curves::ed25519::signature`; another type, bytes included, stops the + * build. * @tparam Input A message, bytes that convert to `std::span`; a * `crypto::prehashed` marker, or anything else, stops the build. * @tparam Policy `curves::ed25519::strict_t` (libsodium's rules), the only policy declared; * anything else stops the build. * @param signing_scheme `crypto::eddsa`. - * @param signature_bytes 64 bytes. + * @param signature_value The signature; bytes from a peer are made into one by + * `curves::ed25519::signature::from_bytes`. * @param message_input The signed bytes. * @param verify_policy `curves::ed25519::strict`, the default. - * @return Nothing; `invalid_signature` for a signature of another size, and for one that does - * not verify, a key that is not canonical or of small order included. + * @return Nothing; `invalid_signature` for a signature that does not verify, a key that is not + * canonical or of small order included. */ - template , class Scheme, class Input, - class Policy = strict_t> + template , class Scheme, class Signature, + class Input, class Policy = strict_t> [[nodiscard]] boost::system::result verify( - [[maybe_unused]] Scheme signing_scheme, std::span signature_bytes, + [[maybe_unused]] Scheme signing_scheme, Signature const& signature_value, Input const& message_input, [[maybe_unused]] Policy verify_policy = Policy{}) const noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert(std::is_same_v, - "webcpp::crypto: an Ed25519 public key verifies crypto::eddsa."); + "webcpp::crypto: an Ed25519 public key verifies crypto::eddsa or " + "crypto::eddsa_prehashed."); static_assert(!detail::asynchronous_backend_v, "webcpp::crypto: verify on this backend completes asynchronously: call " "async_verify."); if constexpr (std::is_same_v && !detail::asynchronous_backend_v) { - return detail::ed25519_verify(signature_bytes, message_input, bytes_); + return detail::ed25519_verify( + detail::checked_signature_bytes(signature_value), message_input, + bytes_); } else { // Never compiled into a program: an assertion above stopped the build. return error::invalid_signature; } } + /** + * Verifies an Ed25519ph signature (RFC 8032's Ed25519 over a message's SHA-512) with this key, + * under a verification policy, strictly as `crypto::eddsa`'s: + * `crypto::verify(crypto::eddsa_prehashed, signature_value, digest_input, key, verify_policy)`, + * of which it is the member form, with the same work, results and refusals. + * + * It runs on a native backend: on one that completes by itself it stops the build (WebCrypto + * has no Ed25519ph). + * + * @tparam Backend The backend; by default the family's. + * @tparam Signature `curves::ed25519::signature`; another type, bytes included, stops the + * build. + * @tparam Input `crypto::prehashed<64>`, the message's SHA-512; a message, or a digest of + * another size, stops the build. + * @tparam Policy `curves::ed25519::strict_t` (libsodium's rules), the only policy declared; + * anything else stops the build. + * @param signing_scheme `crypto::eddsa_prehashed`. + * @param signature_value The signature; bytes from a peer are made into one by + * `curves::ed25519::signature::from_bytes`. + * @param digest_input `crypto::prehashed{digest}`, the 64 bytes of the message's SHA-512. + * @param verify_policy `curves::ed25519::strict`, the default. + * @return Nothing; `invalid_signature` for a signature that does not verify, an `eddsa` + * signature included, and a key that is not canonical or of small order. + */ + template , class Signature, class Input, + class Policy = strict_t> + [[nodiscard]] boost::system::result verify( + [[maybe_unused]] eddsa_prehashed_t signing_scheme, Signature const& signature_value, + Input const& digest_input, + [[maybe_unused]] Policy verify_policy = Policy{}) const noexcept { + detail::timing_guard const timing_scope; + if constexpr (detail::asynchronous_backend_v) { + detail::refuse_ed25519ph_on_asynchronous_backend(); + } + if constexpr (!detail::asynchronous_backend_v) { + return detail::ed25519ph_verify( + detail::checked_signature_bytes(signature_value), + digest_input, bytes_); + } else { + // Never compiled into a program: the assertion above stopped the build. + return error::invalid_signature; + } + } + /** * Verifies an Ed25519 signature with this key, asynchronously, strictly: `verify` run when the - * operation is initiated, its result posted to `completion_executor`; the member form of - * `crypto::async_verify(completion_executor, crypto::eddsa, signature_bytes, - * message_input, key, completion_token)`, which calls it. + * operation is initiated, its result posted to `completion_executor`; the member form of the + * free `crypto::async_verify`, with the same arguments and this key, which calls it. * - * The signature's and the message's bytes are the caller's until the completion; the key is + * The message's bytes are the caller's until the completion; the signature and the key are * copied. * * Declared here and defined in ``, which a program includes to call @@ -228,23 +331,27 @@ class public_key { * @tparam Backend The backend; by default the asynchronous family's * (`default_async_backend_t`), as the free form's. * @tparam Executor The executor's type, an Asio executor (an `io_context`'s or a strand's). - * @tparam Scheme `crypto::eddsa_t`; another scheme stops the build. - * @tparam Input A message, bytes that convert to `std::span`; a - * `crypto::prehashed` marker, or anything else, stops the build. + * @tparam Scheme `crypto::eddsa_t`, or `crypto::eddsa_prehashed_t` on a native backend; + * another scheme stops the build. + * @tparam Signature `curves::ed25519::signature`; another type, bytes included, stops the + * build. + * @tparam Input A message, bytes that convert to `std::span`, under + * `crypto::eddsa`; `crypto::prehashed<64>` under `crypto::eddsa_prehashed`; anything else stops + * the build. * @tparam CompletionToken Any completion token for the signature `completion_token` states. * @param completion_executor The executor the completion is posted to. - * @param signing_scheme `crypto::eddsa`. - * @param signature_bytes 64 bytes, the caller's until the completion. - * @param message_input The signed bytes, the caller's until the completion. + * @param signing_scheme `crypto::eddsa` or `crypto::eddsa_prehashed`. + * @param signature_value The signature. + * @param message_input The signed bytes, or the marker of their SHA-512, the caller's until the + * completion. * @param completion_token The completion token, of signature `void(boost::system::error_code)`: - * `invalid_signature` for a signature of another size, and for one that does not verify; - * `backend_failure`. + * `invalid_signature` for a signature that does not verify; `backend_failure`. * @return What the completion token's `async_result` gives. */ template , class Executor, - class Scheme, class Input, class CompletionToken> + class Scheme, class Signature, class Input, class CompletionToken> auto async_verify(Executor const& completion_executor, Scheme signing_scheme, - std::span signature_bytes, Input const& message_input, + Signature const& signature_value, Input const& message_input, CompletionToken&& completion_token) const; /** @@ -252,8 +359,8 @@ class public_key { * asynchronously: as the overload without it, with `verify`'s policy before the token. * * The policy is a policy tag, never deduced from another argument, so that a completion token - * is never read as one. The signature's and the message's bytes are the caller's until the - * completion; the key is copied. + * is never read as one. The message's bytes are the caller's until the completion; the + * signature and the key are copied. * * 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 @@ -262,24 +369,53 @@ class public_key { * @tparam Backend The backend; by default the asynchronous family's * (`default_async_backend_t`), as the free form's. * @tparam Executor The executor's type, an Asio executor (an `io_context`'s or a strand's). - * @tparam Scheme `crypto::eddsa_t`; another scheme stops the build. - * @tparam Input A message, bytes that convert to `std::span`. + * @tparam Scheme `crypto::eddsa_t`, or `crypto::eddsa_prehashed_t` on a native backend; + * another scheme stops the build. + * @tparam Signature `curves::ed25519::signature`; another type, bytes included, stops the + * build. + * @tparam Input A message, bytes that convert to `std::span`, under + * `crypto::eddsa`; `crypto::prehashed<64>` under `crypto::eddsa_prehashed`. * @tparam CompletionToken Any completion token for the signature `completion_token` states. * @param completion_executor The executor the completion is posted to. - * @param signing_scheme `crypto::eddsa`. - * @param signature_bytes 64 bytes. - * @param message_input The signed bytes. + * @param signing_scheme `crypto::eddsa` or `crypto::eddsa_prehashed`. + * @param signature_value The signature. + * @param message_input The signed bytes, or the marker of their SHA-512. * @param verify_policy `curves::ed25519::strict`, the only policy declared. * @param completion_token The completion token, of signature `void(boost::system::error_code)`, * as the overload without a policy completes. * @return What the completion token's `async_result` gives. */ template , class Executor, - class Scheme, class Input, class CompletionToken> + class Scheme, class Signature, class Input, class CompletionToken> auto async_verify(Executor const& completion_executor, Scheme signing_scheme, - std::span signature_bytes, Input const& message_input, + Signature const& signature_value, Input const& message_input, strict_t verify_policy, CompletionToken&& completion_token) const; + /** + * The X25519 public key of this key (the birational map from edwards25519 to Curve25519), so + * that a peer known by its Ed25519 key is agreed with by an X25519 key pair's `agree`; the + * key pair's own side is `basic_keypair::to_x25519`. + * + * It is synchronous on every backend (design R4): WebCrypto converts nothing between Ed25519 + * and X25519. + * + * @tparam Backend The backend; by default the family's. + * @return The X25519 public key; `invalid_public_key` for a key not canonical, not on the + * curve, of small order or outside the prime-order subgroup. + */ + template > + [[nodiscard]] boost::system::result to_x25519() const noexcept { + detail::timing_guard const timing_scope; + std::array converted_bytes{}; + auto const engine_done = + detail::ed25519_engine::to_x25519_public(bytes_, + converted_bytes); + if (!engine_done) { + return engine_done.error(); + } + return x25519::public_key::from_bytes(converted_bytes); + } + /** * Whether two keys are the same bytes. * @@ -306,7 +442,7 @@ class basic_keypair { using engine = detail::ed25519_engine; template - friend class ph; + friend class prehashed_signer; template friend struct detail::ed25519_keypair_access; // The asynchronous family's error completions make the empty object a move leaves. @@ -323,7 +459,7 @@ class basic_keypair { using public_key_type = ::webcpp::crypto::curves::ed25519::public_key; /** The seed's size. */ static constexpr std::size_t seed_size = 32; - /** The size of the secret bytes `make` takes and `secret()` gives, the seed's. */ + /** The size of the secret bytes `from_secret` takes and `secret()` gives, the seed's. */ static constexpr std::size_t secret_key_size = seed_size; /** The public key's size. */ static constexpr std::size_t public_key_size = 32; @@ -336,12 +472,12 @@ class basic_keypair { * @param seed_bytes 32 bytes. * @return The key pair; `invalid_key_size`; `backend_failure`. */ - [[nodiscard]] static boost::system::result make( + [[nodiscard]] static boost::system::result from_secret( std::span seed_bytes) noexcept { - detail::timing_guard const timing; - static_assert( - !detail::asynchronous_backend_v, - "webcpp::crypto: make on this backend completes asynchronously: call async_make."); + detail::timing_guard const timing_scope; + static_assert(!detail::asynchronous_backend_v, + "webcpp::crypto: from_secret on this backend completes asynchronously: call " + "async_from_secret."); if constexpr (detail::asynchronous_backend_v) { // Never compiled into a program: the assertion above stopped the build. return error::backend_failure; @@ -351,7 +487,7 @@ class basic_keypair { } basic_keypair made_pair; auto const engine_keyed = - engine::make(made_pair.state_, seed_bytes.template first()); + engine::seed_keypair(made_pair.state_, seed_bytes.template first()); if (!engine_keyed) { return engine_keyed.error(); } @@ -367,7 +503,7 @@ class basic_keypair { * none; `backend_failure`. */ [[nodiscard]] static boost::system::result generate() noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert(!detail::asynchronous_backend_v, "webcpp::crypto: generate on this backend completes asynchronously: call " "async_generate."); @@ -383,15 +519,14 @@ class basic_keypair { // for a key pair: one error to handle. return error::entropy_unavailable; } - return make(seed_secret.bytes()); + return from_secret(seed_secret.bytes()); } } /** - * Makes a key pair from a seed, asynchronously: `make` run when the operation is initiated, - * its result posted to `completion_executor`; the member form of - * `crypto::async_make(completion_executor, seed_bytes, completion_token)`, which - * calls it. + * Makes a key pair from a seed, asynchronously: `from_secret` run when the operation is + * initiated, its result posted to `completion_executor`; the member form of the free + * `crypto::async_from_secret`, with the same arguments, which calls it. * * 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 @@ -407,9 +542,9 @@ class basic_keypair { * @return What the completion token's `async_result` gives. */ template - static auto async_make(Executor const& completion_executor, - std::span seed_bytes, - CompletionToken&& completion_token); + static auto async_from_secret(Executor const& completion_executor, + std::span seed_bytes, + CompletionToken&& completion_token); /** * Makes a key pair from a fresh seed, asynchronously: `generate` run when the operation is @@ -474,23 +609,23 @@ class basic_keypair { * @return The public key; `invalid_state` moved from. */ [[nodiscard]] boost::system::result public_key() const noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; if (!keyed_) { return error::invalid_state; } std::array key_bytes{}; engine::public_key(state_, key_bytes); - return public_key_type::make(key_bytes); + return public_key_type::from_bytes(key_bytes); } /** * The seed, RFC 8032's secret key, for a program that keeps the key pair and makes it again - * with `make`, or exports it (PKCS#8 holds the seed alone). + * with `from_secret`, or exports it (PKCS#8 holds the seed alone). * * @return 32 secret bytes; `invalid_state` moved from. */ [[nodiscard]] boost::system::result> secret() const noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; if (!keyed_) { return error::invalid_state; } @@ -500,32 +635,53 @@ class basic_keypair { } /** - * Signs a message with Ed25519 (RFC 8032's pure Ed25519: the message itself, of any length, - * empty included, is signed; no digest is taken). + * Signs with Ed25519 (RFC 8032): under `crypto::eddsa`, the pure form, a message, the message + * itself, of any length, empty included, with no digest taken; under `crypto::eddsa_prehashed`, + * Ed25519ph, the 64 bytes of a message's SHA-512, `crypto::prehashed{digest}` (a message given + * in pieces is @ref prehashed_signer's). * - * @tparam Scheme `crypto::eddsa_t`; another scheme stops the build. - * @tparam Input A message, bytes that convert to `std::span`; a - * `crypto::prehashed` marker, or anything else, stops the build (Ed25519ph is @ref ph). - * @param signing_scheme `crypto::eddsa`. - * @param message_input Any bytes. - * @return The 64-byte signature; `invalid_state` moved from; `backend_failure`. + * The two signatures, of one type, are not interchangeable: each verifies under its own scheme. + * + * `crypto::eddsa_prehashed` runs on a native backend: on one that completes by itself it stops + * the build (WebCrypto has no Ed25519ph). + * + * @tparam Scheme `crypto::eddsa_t` or `crypto::eddsa_prehashed_t`; another scheme stops the + * build. + * @tparam Input Under `crypto::eddsa`, a message, bytes that convert to + * `std::span`, a marker stopping the build; under + * `crypto::eddsa_prehashed`, `crypto::prehashed<64>`, a message or a digest of another size + * stopping the build. + * @param signing_scheme `crypto::eddsa` or `crypto::eddsa_prehashed`. + * @param signing_input The message, or the marker of its SHA-512. + * @return The signature, `curves::ed25519::signature`; `invalid_state` moved from; + * `backend_failure`. */ template - [[nodiscard]] boost::system::result> sign( - [[maybe_unused]] Scheme signing_scheme, Input const& message_input) const noexcept { - detail::timing_guard const timing; - static_assert(std::is_same_v, - "webcpp::crypto: an Ed25519 key signs with crypto::eddsa."); - static_assert(!detail::asynchronous_backend_v, - "webcpp::crypto: sign on this backend completes asynchronously: call " - "async_sign."); - if constexpr (std::is_same_v && !detail::asynchronous_backend_v) { + [[nodiscard]] boost::system::result> sign( + [[maybe_unused]] Scheme signing_scheme, Input const& signing_input) const noexcept { + detail::timing_guard const timing_scope; + if constexpr (std::is_same_v && + detail::asynchronous_backend_v) { + detail::refuse_ed25519ph_on_asynchronous_backend(); + } + constexpr bool known_scheme = + std::is_same_v || std::is_same_v; + static_assert(known_scheme, + "webcpp::crypto: an Ed25519 key signs with crypto::eddsa or " + "crypto::eddsa_prehashed."); + static_assert( + !detail::asynchronous_backend_v || std::is_same_v, + "webcpp::crypto: sign on this backend completes asynchronously: call " + "async_sign."); + if constexpr (known_scheme && !detail::asynchronous_backend_v) { detail::check_input(); - if constexpr (detail::input_valid_v) { - return signed_message(detail::message_bytes(message_input)); - } else { + if constexpr (!detail::input_valid_v) { // Never compiled into a program: check_input stopped the build. return error::backend_failure; + } else if constexpr (std::is_same_v) { + return signed_digest(signing_input.digest); + } else { + return signed_message(detail::message_bytes(signing_input)); } } else { // Never compiled into a program: an assertion above stopped the build. @@ -534,10 +690,12 @@ class basic_keypair { } /** - * Signs a message with Ed25519, asynchronously: `sign` run when the operation is initiated, - * its result posted to `completion_executor`; the member form of - * `crypto::async_sign(completion_executor, key_pair, signing_scheme, message_input, - * completion_token)`, which calls it. + * Signs with Ed25519, asynchronously: `sign` run when the operation is initiated, its result + * posted to `completion_executor`; the member form of the free `crypto::async_sign`, with the + * same arguments and this key pair, which calls it. + * + * `crypto::eddsa_prehashed` runs on a native backend: on one that completes by itself it stops + * the build (WebCrypto has no Ed25519ph). * * The scheme and the input are checked as `crypto::can_sign` checks them, before anything * else. The key pair and the message's bytes are the caller's until the completion. @@ -547,16 +705,18 @@ class basic_keypair { * "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 Scheme `crypto::eddsa_t`; another scheme stops the build. - * @tparam Input A message, bytes that convert to `std::span`; a - * `crypto::prehashed` marker, or anything else, stops the build. + * @tparam Scheme `crypto::eddsa_t` or `crypto::eddsa_prehashed_t`; another scheme stops the + * build. + * @tparam Input Under `crypto::eddsa`, a message, bytes that convert to + * `std::span`; under `crypto::eddsa_prehashed`, `crypto::prehashed<64>`; + * anything else stops the build. * @tparam CompletionToken Any completion token for the signature `completion_token` states. * @param completion_executor The executor the completion is posted to. - * @param signing_scheme `crypto::eddsa`. - * @param message_input Any bytes. + * @param signing_scheme `crypto::eddsa` or `crypto::eddsa_prehashed`. + * @param message_input The message, or the marker of its SHA-512. * @param completion_token The completion token, of signature - * `void(boost::system::error_code, std::array)`; on an error 64 zeros - * (`invalid_state`, `backend_failure`). + * `void(boost::system::error_code, curves::ed25519::signature)`; on an error the signature of + * zeros (`invalid_state`, `backend_failure`). * @return What the completion token's `async_result` gives. */ template @@ -564,29 +724,41 @@ class basic_keypair { Input const& message_input, CompletionToken&& completion_token) const; /** - * The X25519 secret key of this key pair, RFC 7748's form of the clamped first half of the - * seed's SHA-512. + * The X25519 key pair of this key pair, on its backend: its secret key the clamped first half + * of the seed's SHA-512, its public key `public_key()->to_x25519()`, so that one seed serves + * for signatures and for agreement. + * + * It is synchronous on every backend (design R4): WebCrypto converts nothing between Ed25519 + * and X25519. A backend without X25519 stops the build. * - * @return 32 secret bytes; `invalid_state`; `backend_failure`. + * @return The X25519 key pair; `invalid_state` moved from; `backend_failure`. */ - [[nodiscard]] boost::system::result> x25519_secret() const noexcept { - detail::timing_guard const timing; - if (!keyed_) { - return error::invalid_state; - } - crypto::secret<32> converted_secret; - auto const engine_done = engine::x25519_secret(state_, converted_secret.writable()); - if (!engine_done) { - return engine_done.error(); + [[nodiscard]] boost::system::result> to_x25519() const noexcept { + detail::timing_guard const timing_scope; + using converted_type = x25519::basic_keypair; + static_assert(supports_v, + "webcpp::crypto: to_x25519: this backend has no X25519; libsodium has both."); + if constexpr (!supports_v) { + // Never compiled into a program: the assertion above stopped the build. + return error::backend_failure; + } else { + if (!keyed_) { + return error::invalid_state; + } + crypto::secret converted_secret; + auto const engine_done = engine::x25519_secret(state_, converted_secret.writable()); + if (!engine_done) { + return engine_done.error(); + } + return converted_type::from_secret(converted_secret.bytes()); } - return converted_secret; } private: basic_keypair() noexcept = default; // The work of sign, which holds the guard: the signature of the message's bytes. - [[nodiscard]] boost::system::result> signed_message( + [[nodiscard]] boost::system::result signed_message( std::span message_bytes) const noexcept { if (!keyed_) { return error::invalid_state; @@ -596,7 +768,23 @@ class basic_keypair { if (!signed_bytes) { return signed_bytes.error(); } - return signature_bytes; + return detail::signature_access::of(signature_bytes); + } + + // The work of sign under eddsa_prehashed, which holds the guard: Ed25519ph's signature of the + // digest. + [[nodiscard]] boost::system::result signed_digest( + std::span digest_bytes) const noexcept { + if (!keyed_) { + return error::invalid_state; + } + std::array signature_bytes{}; + auto const signed_bytes = detail::ed25519ph_engine::sign_digest( + state_, digest_bytes, signature_bytes); + if (!signed_bytes) { + return signed_bytes.error(); + } + return detail::signature_access::of(signature_bytes); } state_type state_{}; @@ -607,47 +795,24 @@ class basic_keypair { using keypair = basic_keypair<>; /** - * The X25519 public key of an Ed25519 public key (the birational map from edwards25519 to - * Curve25519), so that a peer known by its Ed25519 key can be agreed with by - * `curves::x25519::agree`; the key pair's own side is `basic_keypair::x25519_secret`. - * - * @tparam Backend The backend; by default the family's. - * @param ed25519_public_key The Ed25519 public key. - * @return 32 bytes; `invalid_public_key` for a key not canonical, not on the curve or of small - * order. - */ -template > -[[nodiscard]] boost::system::result> to_x25519_public( - public_key const& ed25519_public_key) noexcept { - detail::timing_guard const timing; - auto const key_bytes = ed25519_public_key.bytes(); - std::array converted_secret{}; - auto const engine_done = detail::ed25519_engine::to_x25519_public( - key_bytes, converted_secret); - if (!engine_done) { - return engine_done.error(); - } - return converted_secret; -} - -/** - * Ed25519ph (RFC 8032 section 5.1), the Ed25519 signature of a message's SHA-512, given in - * pieces. + * Ed25519ph (RFC 8032 section 5.1), the Ed25519 signature of a message's SHA-512, the message + * given in pieces: the streaming form of the scheme `crypto::eddsa_prehashed`, which signs a digest + * the program has, and gives the same signature. * * A large message need not be held whole: the signer is begun, updated with each piece, then * signs with a key pair or verifies with a public key, either of which ends the message. Its * state is wiped by every move, by the end of a message and by the destructor. * - * Its signature is not Ed25519's of the same message: a verifier is told which of the two a - * protocol uses. + * Its signature, a `curves::ed25519::signature`, is not `crypto::eddsa`'s of the same message: a + * verifier is told which of the two a protocol uses. * * @tparam Hash `webcpp::hash::sha2_512`, which RFC 8032 fixes; any other is refused. * @tparam Backend The backend; by default the family's (`default_backend_t`). */ template > -class ph { +class prehashed_signer { // clang-format off - static_assert(std::is_same_v, "webcpp::crypto: Ed25519ph is defined over SHA-512 (RFC 8032 section 5.1); name curves::ed25519::ph."); + static_assert(std::is_same_v, "webcpp::crypto: Ed25519ph is defined over SHA-512 (RFC 8032 section 5.1); name curves::ed25519::prehashed_signer."); // clang-format on using state_type = detail::ed25519ph_state; @@ -670,9 +835,9 @@ class ph { * * @return The signer, ready for the message's pieces; `backend_failure`. */ - [[nodiscard]] static boost::system::result begin() noexcept { - detail::timing_guard const timing; - ph begun_hash; + [[nodiscard]] static boost::system::result begin() noexcept { + detail::timing_guard const timing_scope; + prehashed_signer begun_hash; auto const begin_result = engine::begin(begun_hash.state_); if (!begin_result) { return begin_result.error(); @@ -686,7 +851,8 @@ class ph { * * @param moved_from The signer moved from. */ - ph(ph&& moved_from) noexcept : begun_(std::exchange(moved_from.begun_, false)) { + prehashed_signer(prehashed_signer&& moved_from) noexcept + : begun_(std::exchange(moved_from.begun_, false)) { state_ = moved_from.state_; engine::reset(moved_from.state_); } @@ -697,7 +863,7 @@ class ph { * @param moved_from The signer moved from, wiped and ended after. * @return This signer. */ - ph& operator=(ph&& moved_from) noexcept { + prehashed_signer& operator=(prehashed_signer&& moved_from) noexcept { if (this != &moved_from) { engine::reset(state_); begun_ = std::exchange(moved_from.begun_, false); @@ -708,12 +874,12 @@ class ph { } /** Not copyable: the state of a message has one owner. */ - ph(ph const&) = delete; + prehashed_signer(prehashed_signer const&) = delete; /** Not copyable: the state of a message has one owner. */ - ph& operator=(ph const&) = delete; + prehashed_signer& operator=(prehashed_signer const&) = delete; /** Wipes the state of the message. */ - ~ph() { engine::reset(state_); } + ~prehashed_signer() { engine::reset(state_); } /** * Adds a piece of the message. @@ -723,7 +889,7 @@ class ph { */ [[nodiscard]] boost::system::result update( std::span piece_bytes) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; if (!begun_) { return error::invalid_state; } @@ -735,12 +901,13 @@ class ph { * Signs the message given, which it ends. * * @param key_pair The key pair, of the same backend. - * @return The 64-byte signature; `invalid_state` once the message is ended, or moved from, - * or with a moved-from key pair; `backend_failure`. + * @return The signature, `curves::ed25519::signature` (an Ed25519ph signature, which only + * Ed25519ph verifies: this signer or `crypto::eddsa_prehashed`); `invalid_state` once the + * message is ended, or moved from, or with a moved-from key pair; `backend_failure`. */ - [[nodiscard]] boost::system::result> sign( + [[nodiscard]] boost::system::result<::webcpp::crypto::curves::ed25519::signature> sign( basic_keypair const& key_pair) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; if (!begun_ || !key_pair.keyed_) { return error::invalid_state; } @@ -750,36 +917,40 @@ class ph { if (!signed_message) { return signed_message.error(); } - return signature_bytes; + return detail::signature_access::of<::webcpp::crypto::curves::ed25519::signature>( + signature_bytes); } /** * Verifies a signature of the message given, which it ends, strictly (design D31). * - * @param signature_bytes 64 bytes. + * @tparam Signature `curves::ed25519::signature`; another type, bytes included, stops the + * build. + * @param signature_value The signature; bytes from a peer are made into one by + * `curves::ed25519::signature::from_bytes`. * @param verifying_key The signer's public key. * @return Nothing; `invalid_state` once the message is ended, or moved from; - * `invalid_signature` for a signature of another size, so that a key's 32 bytes given where - * the signature goes are refused as a signature, and for one that does not verify. + * `invalid_signature` for a signature that does not verify. */ + template [[nodiscard]] boost::system::result verify( - std::span signature_bytes, + Signature const& signature_value, ::webcpp::crypto::curves::ed25519::public_key const& verifying_key) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; + auto const& signature_bytes = + detail::checked_signature_bytes<::webcpp::crypto::curves::ed25519::signature, + detail::ed25519ph_verifier_t>(signature_value); if (!begun_) { return error::invalid_state; } - boost::system::result verify_result = error::invalid_signature; - if (signature_bytes.size() == 64) { - auto const key_bytes = verifying_key.bytes(); - verify_result = engine::verify(state_, key_bytes, signature_bytes.first<64>()); - } + auto const key_bytes = verifying_key.bytes(); + auto const verify_result = engine::verify(state_, key_bytes, signature_bytes); end(); return verify_result; } private: - ph() noexcept = default; + prehashed_signer() noexcept = default; // The message is ended: its state is wiped, and only begin makes another. void end() noexcept { @@ -799,43 +970,113 @@ namespace webcpp::crypto { * Verifies an Ed25519 signature (RFC 8032's pure Ed25519) under a verification policy (design * D31). * - * The signature comes first, as in every `verify`, and the key is typed (design R17): the - * arguments of the order before it do not compile, the signature's bytes being no key, and a - * key's 32 bytes where the signature goes are refused as a signature of another size. The key's - * own `verify` is its member form, with the same work. + * The signature comes first, as in every `verify`, and both the signature and the key are typed + * (design R1, R17): the arguments of the order before it do not compile, and neither do bytes + * where either goes. The key's own `verify` is its member form, with the same work. * * @tparam Backend The backend; by default the family's. + * @tparam Signature `curves::ed25519::signature`; another type, bytes included, stops the build. * @tparam Input A message, bytes that convert to `std::span`; a * `crypto::prehashed` marker, or anything else, stops the build. * @tparam Policy `curves::ed25519::strict_t` (libsodium's rules), the only policy declared; * anything else stops the build. * @param signing_scheme `crypto::eddsa`. - * @param signature_bytes 64 bytes. + * @param signature_value The signature; bytes from a peer are made into one by + * `curves::ed25519::signature::from_bytes`. * @param message_input The signed bytes. * @param public_key The signer's public key. * @param verify_policy `curves::ed25519::strict`, the default. - * @return Nothing; `invalid_signature` for a signature of another size, and for one that does not - * verify, a key that is not canonical or of small order included. + * @return Nothing; `invalid_signature` for a signature that does not verify, a key that is not + * canonical or of small order included. */ -template , class Input, +template , class Signature, class Input, class Policy = curves::ed25519::strict_t> [[nodiscard]] boost::system::result verify( - [[maybe_unused]] eddsa_t signing_scheme, std::span signature_bytes, + [[maybe_unused]] eddsa_t signing_scheme, Signature const& signature_value, Input const& message_input, curves::ed25519::public_key const& public_key, [[maybe_unused]] Policy verify_policy = Policy{}) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert(!detail::asynchronous_backend_v, "webcpp::crypto: verify on this backend completes asynchronously: call " "async_verify."); if constexpr (!detail::asynchronous_backend_v) { auto const key_bytes = public_key.bytes(); - return detail::ed25519_verify(signature_bytes, message_input, key_bytes); + return detail::ed25519_verify( + detail::checked_signature_bytes(signature_value), + message_input, key_bytes); } else { // Never compiled into a program: the assertion above stopped the build. return error::invalid_signature; } } +/** + * Verifies an Ed25519ph signature (RFC 8032's Ed25519 over a message's SHA-512, the digest given + * as `crypto::prehashed{digest}`) under a verification policy, strictly as `crypto::eddsa`'s. + * + * An `eddsa` signature, of the same type, does not verify here, nor this scheme's under `eddsa`: + * RFC 8032 separates the two. The key's own `verify` is its member form, with the same work. It + * runs on a native backend: on one that completes by itself it stops the build (WebCrypto has no + * Ed25519ph). + * + * @tparam Backend The backend; by default the family's. + * @tparam Signature `curves::ed25519::signature`; another type, bytes included, stops the build. + * @tparam Input `crypto::prehashed<64>`, the message's SHA-512; a message, or a digest of another + * size, stops the build. + * @tparam Policy `curves::ed25519::strict_t` (libsodium's rules), the only policy declared; + * anything else stops the build. + * @param signing_scheme `crypto::eddsa_prehashed`. + * @param signature_value The signature; bytes from a peer are made into one by + * `curves::ed25519::signature::from_bytes`. + * @param digest_input `crypto::prehashed{digest}`, the 64 bytes of the message's SHA-512. + * @param public_key The signer's public key. + * @param verify_policy `curves::ed25519::strict`, the default. + * @return Nothing; `invalid_signature` for a signature that does not verify, a key that is not + * canonical or of small order included. + */ +template , class Signature, class Input, + class Policy = curves::ed25519::strict_t> +[[nodiscard]] boost::system::result verify( + [[maybe_unused]] eddsa_prehashed_t signing_scheme, Signature const& signature_value, + Input const& digest_input, curves::ed25519::public_key const& public_key, + [[maybe_unused]] Policy verify_policy = Policy{}) noexcept { + detail::timing_guard const timing_scope; + if constexpr (detail::asynchronous_backend_v) { + detail::refuse_ed25519ph_on_asynchronous_backend(); + } + if constexpr (!detail::asynchronous_backend_v) { + auto const key_bytes = public_key.bytes(); + return detail::ed25519ph_verify( + detail::checked_signature_bytes( + signature_value), + digest_input, key_bytes); + } else { + // Never compiled into a program: the assertion above stopped the build. + return error::invalid_signature; + } +} + +/** + * Converts an Ed25519 key pair or public key to X25519's, `converted_value.to_x25519()`: the free + * form of the member, which it calls, with its results and its errors. + * + * It is synchronous on every backend (design R4): WebCrypto converts nothing between Ed25519 and + * X25519. + * + * @tparam Value `curves::ed25519::basic_keypair`, converted to an X25519 key pair of its + * backend, or `curves::ed25519::public_key`, converted on the family's default backend. + * @param converted_value The key pair or the public key. + * @return What `converted_value.to_x25519()` returns: the X25519 key pair, or the X25519 public + * key, or its error. + */ +template +[[nodiscard]] auto to_x25519(Value const& converted_value) noexcept + requires requires(Value const& candidate_value) { candidate_value.to_x25519(); } +{ + detail::timing_guard const timing_scope; + return converted_value.to_x25519(); +} + } // namespace webcpp::crypto namespace webcpp::crypto::detail { @@ -848,6 +1089,15 @@ namespace webcpp::crypto::detail { template inline constexpr bool signs_with_v, eddsa_t> = true; +/** + * An Ed25519 key pair signs with `eddsa_prehashed`, Ed25519ph. + * + * @tparam Backend The key pair's backend. + */ +template +inline constexpr bool signs_with_v, eddsa_prehashed_t> = + true; + /** * An Ed25519 key pair's backend. * @@ -866,6 +1116,47 @@ struct key_backend> { template <> inline constexpr bool verifies_with_v = true; +/** An Ed25519 public key verifies `eddsa_prehashed`, Ed25519ph. */ +template <> +inline constexpr bool verifies_with_v = true; + +/** + * An Ed25519 key pair's signature under `eddsa`, `curves::ed25519::signature`. + * + * @tparam Backend The key's backend. + */ +template +struct signature_of, eddsa_t> { + /** The signature type. */ + using type = curves::ed25519::signature; +}; + +/** + * An Ed25519 key pair's signature under `eddsa_prehashed`, `curves::ed25519::signature`, the type + * `eddsa`'s is. + * + * @tparam Backend The key's backend. + */ +template +struct signature_of, eddsa_prehashed_t> { + /** The signature type. */ + using type = curves::ed25519::signature; +}; + +/** An Ed25519 public key's signature under `eddsa`, `curves::ed25519::signature`. */ +template <> +struct signature_of { + /** The signature type. */ + using type = curves::ed25519::signature; +}; + +/** An Ed25519 public key's signature under `eddsa_prehashed`, `curves::ed25519::signature`. */ +template <> +struct signature_of { + /** The signature type. */ + using type = curves::ed25519::signature; +}; + /** * `crypto::verify` of `eddsa` against an Ed25519 public key is Ed25519's, so that the catch-all * steps aside. @@ -873,6 +1164,13 @@ inline constexpr bool verifies_with_v = tr template <> inline constexpr bool has_verifier_v = true; +/** + * `crypto::verify` of `eddsa_prehashed` against an Ed25519 public key is Ed25519ph's, so that the + * catch-all steps aside. + */ +template <> +inline constexpr bool has_verifier_v = true; + /** * Ed25519's engine on a backend whose header does not specialise it: the family's refusal, * which names what the program needs (`detail/capabilities.hpp`). Its functions are never @@ -886,7 +1184,8 @@ struct ed25519_engine { /** Never called; fails closed. */ template - [[nodiscard]] static boost::system::result make(Arguments&&... /*arguments*/) noexcept { + [[nodiscard]] static boost::system::result seed_keypair( + Arguments&&... /*arguments*/) noexcept { return error::backend_failure; } @@ -957,6 +1256,20 @@ struct ed25519ph_engine { return error::backend_failure; } + /** Never called; fails closed. */ + template + [[nodiscard]] static boost::system::result sign_digest( + Arguments&&... /*arguments*/) noexcept { + return error::backend_failure; + } + + /** Never called; fails closed. */ + template + [[nodiscard]] static boost::system::result verify_digest( + Arguments&&... /*arguments*/) noexcept { + return error::backend_failure; + } + /** Never called. */ template static void reset(Arguments&&... /*arguments*/) noexcept {} @@ -964,16 +1277,29 @@ struct ed25519ph_engine { } // namespace webcpp::crypto::detail +/** Defined once this header's declarations are, which libsodium's engines specialise. */ +// NOLINTNEXTLINE(modernize-macro-to-enum): read by backends/sodium.hpp's #if, not a value +#define WEBCPP_CRYPTO_DETAIL_ED25519_DECLARED 1 + // The default backend's engines, when the program links it (design D32): libsodium on every // target. Its header specialises them for this header, wherever it was first included. #if defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_ED25519_SODIUM) && defined(WEBCPP_CRYPTO_HAS_SODIUM) #include -// The key pair contract (design D8), on the family's default backend. +// The key pair concepts (design D4), on the family's default backend: it signs; it does not +// agree (to_x25519() converts it). static_assert( ::webcpp::crypto::keypair< ::webcpp::crypto::curves::ed25519::basic_keypair<::webcpp::crypto::backends::sodium>>, "webcpp::crypto: Ed25519's key pair meets crypto::keypair."); +static_assert( + ::webcpp::crypto::signing_keypair< + ::webcpp::crypto::curves::ed25519::basic_keypair<::webcpp::crypto::backends::sodium>>, + "webcpp::crypto: Ed25519's key pair meets crypto::signing_keypair."); +static_assert( + !::webcpp::crypto::agreement_keypair< + ::webcpp::crypto::curves::ed25519::basic_keypair<::webcpp::crypto::backends::sodium>>, + "webcpp::crypto: Ed25519's key pair is no crypto::agreement_keypair: it signs."); #endif #endif // WEBCPP_CRYPTO_CURVES_ED25519_HPP diff --git a/include/webcpp/crypto/curves/ed25519/formats.hpp b/include/webcpp/crypto/curves/ed25519/formats.hpp index f2a2142a..532cb388 100644 --- a/include/webcpp/crypto/curves/ed25519/formats.hpp +++ b/include/webcpp/crypto/curves/ed25519/formats.hpp @@ -123,8 +123,8 @@ template > * The public key of an SPKI, refused unless it is exactly RFC 8410's form: the 12 bytes of * Ed25519's prefix, then the key, and nothing after. * - * The key's point is not checked here, as `public_key::make` does not check it: `crypto::verify` - * refuses a key that is not one. + * The key's point is not checked here, as `public_key::from_bytes` does not check it: + * `crypto::verify` refuses a key that is not one. * * @tparam Backend The backend; by default the family's. * @param spki_bytes The DER. @@ -133,7 +133,7 @@ template > template > [[nodiscard]] boost::system::result decode_spki( std::span spki_bytes) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; if (spki_bytes.size() != max_spki_size) { return error::invalid_encoding; } @@ -144,7 +144,7 @@ template > if (!decoded_key) { return decoded_key.error(); } - return public_key::make(key_bytes); + return public_key::from_bytes(key_bytes); } /** @@ -186,7 +186,7 @@ template > template > [[nodiscard]] boost::system::result> decode_pkcs8( std::span pkcs8_bytes) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; if (pkcs8_bytes.size() != max_pkcs8_size) { return error::invalid_encoding; } @@ -197,7 +197,7 @@ template > if (!decoded_key) { return decoded_key.error(); } - return basic_keypair::make(seed_secret.bytes()); + return basic_keypair::from_secret(seed_secret.bytes()); } } // namespace webcpp::crypto::curves::ed25519 diff --git a/include/webcpp/crypto/curves/p256.hpp b/include/webcpp/crypto/curves/p256.hpp index 5e759b71..859838e4 100644 --- a/include/webcpp/crypto/curves/p256.hpp +++ b/include/webcpp/crypto/curves/p256.hpp @@ -10,8 +10,9 @@ SEC 1's uncompressed point; ECDSA over SHA-256 with RFC 6979's nonce, `key.sign(crypto::ecdsa_sha256, input)` and `crypto::verify(crypto::ecdsa_sha256, signature, input, public_key)`, the input a message, hashed - inside, or `crypto::prehashed{digest}`: signing gives low S, verification accepts high and low S; - the signature's raw and DER forms, and low S as two functions, `normalize_low_s` and `is_low_s`; + inside, or `crypto::prehashed{digest}`, the signature a `curves::p256::ecdsa_signature`: signing + gives low S, verification accepts high and low S; the signature's DER form, and low S as two + functions, `normalize_low_s` and `is_low_s`; ECDH's `agree`, the shared point's raw x coordinate, as WebCrypto's `deriveBits` gives it. The family's default backend, BearSSL on every target, is included when the program links it; @@ -29,6 +30,7 @@ #include #include #include +#include #include #include #include @@ -65,39 +67,41 @@ inline constexpr std::size_t max_der_size = 72; namespace webcpp::crypto::detail { +/** The tag of `curves::p256::ecdsa_signature`. */ +struct p256_ecdsa_signature_tag { + /** No recovery id. */ + static constexpr bool recoverable = false; +}; + /** * Verifies an ECDSA signature over SHA-256 with a P-256 point on `Backend`: the work of * `basic_public_key::verify` and of `crypto::verify` of `ecdsa_sha256`, which hold the guard. * * @tparam Backend The key's backend. * @tparam Input A message or `crypto::prehashed<32>`; anything else stops the build. - * @param signature_bytes 64 bytes, r then s; its size is checked first. + * @param signature_bytes The signature's 64 bytes, r then s. * @param signing_input The signed message, hashed with SHA-256 here, or the marker of its digest. * @param point_bytes The public key's point, validated when the key was made. - * @return Nothing; `invalid_signature` for a signature of another size, and for one out of range - * or that does not verify. + * @return Nothing; `invalid_signature` for a signature out of range or that does not verify. */ template [[nodiscard]] boost::system::result p256_verify( - std::span signature_bytes, Input const& signing_input, + std::span signature_bytes, + Input const& signing_input, std::span point_bytes) noexcept { check_input(); if constexpr (input_valid_v) { using engine = p_curve_engine; - if (signature_bytes.size() != curves::p256::signature_size) { - return error::invalid_signature; - } - auto const fixed_signature = signature_bytes.first(); std::array digest_bytes{}; if constexpr (is_prehashed_v) { std::ranges::copy(signing_input.digest, digest_bytes.begin()); } else { digest_bytes = sha256_of(message_bytes(signing_input)); } - if (!p_curve_signature_in_range(fixed_signature)) { + if (!p_curve_signature_in_range(signature_bytes)) { return error::invalid_signature; } - if (!engine::verify(point_bytes, digest_bytes, fixed_signature)) { + if (!engine::verify(point_bytes, digest_bytes, signature_bytes)) { return error::invalid_signature; } return {}; @@ -111,6 +115,16 @@ template namespace webcpp::crypto::curves::p256 { +/** + * A P-256 ECDSA signature, 64 bytes, r then s: what `sign(crypto::ecdsa_sha256, ...)` gives and + * `crypto::verify(crypto::ecdsa_sha256, ...)` takes. + * + * Each of r and s is 32 bytes big-endian (IEEE P1363, WebCrypto's form). `from_bytes` checks the + * size alone; whether r and s are in range, and s low, is verification's and `normalize_low_s`'s + * judgment. + */ +using ecdsa_signature = detail::basic_signature; + /** * A P-256 public key, validated: a point on the curve, its coordinates below p, never the * identity, kept as SEC 1's uncompressed point. @@ -147,9 +161,9 @@ class basic_public_key { * @return The public key; `invalid_public_key` for another size, another first byte (the * compressed form included), a coordinate not below p or a point off the curve. */ - [[nodiscard]] static boost::system::result make( + [[nodiscard]] static boost::system::result from_bytes( std::span uncompressed_point) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; if (uncompressed_point.size() != public_key_size || uncompressed_point[0] != 0x04) { return error::invalid_public_key; } @@ -164,10 +178,10 @@ class basic_public_key { * @return The public key; `invalid_public_key` for a coordinate not below p or a point off * the curve. */ - [[nodiscard]] static boost::system::result make( + [[nodiscard]] static boost::system::result from_coordinates( std::span x_coordinate, std::span y_coordinate) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; std::array point_bytes{0x04}; std::ranges::copy(x_coordinate, point_bytes.begin() + 1); std::ranges::copy(y_coordinate, point_bytes.begin() + 1 + coordinate_size); @@ -185,28 +199,30 @@ class basic_public_key { /** * Verifies an ECDSA signature over SHA-256 with this key: - * `crypto::verify(crypto::ecdsa_sha256, signature_bytes, signing_input, key)`, of which it is + * `crypto::verify(crypto::ecdsa_sha256, signature_value, signing_input, key)`, of which it is * the member form, with the same work, results and refusals. * * A high S and a low S are both accepted, as FIPS 186-5 and WebCrypto accept them; a protocol * that requires low S checks `curves::p256::is_low_s` too. * * @tparam Scheme `crypto::ecdsa_sha256_t`; another scheme stops the build. + * @tparam Signature `curves::p256::ecdsa_signature`; another type, bytes included, stops the + * build. * @tparam Input A message, bytes that convert to `std::span`, of any size, * empty included, or `crypto::prehashed<32>`; anything else stops the build. * @param signing_scheme `crypto::ecdsa_sha256`. - * @param signature_bytes 64 bytes, r then s (IEEE P1363, WebCrypto's form), as any bytes: a - * span, a `std::array`, a `std::vector`. + * @param signature_value The signature, r then s (IEEE P1363, WebCrypto's form); bytes from a + * peer are made into one by `curves::p256::ecdsa_signature::from_bytes`. * @param signing_input The signed message, hashed with SHA-256 inside the call; or * `crypto::prehashed{digest}`, its 32-byte SHA-256 digest. - * @return Nothing; `invalid_signature` for a signature of another size, an r or an s that is 0 - * or not below n, and a signature that does not verify. + * @return Nothing; `invalid_signature` for an r or an s that is 0 or not below n, and a + * signature that does not verify. */ - template + template [[nodiscard]] boost::system::result verify([[maybe_unused]] Scheme signing_scheme, - std::span signature_bytes, + Signature const& signature_value, Input const& signing_input) const noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert(std::is_same_v, "webcpp::crypto: a P-256 public key verifies crypto::ecdsa_sha256."); static_assert(!detail::asynchronous_backend_v, @@ -214,7 +230,9 @@ class basic_public_key { "async_verify."); if constexpr (std::is_same_v && !detail::asynchronous_backend_v) { - return detail::p256_verify(signature_bytes, signing_input, point_); + return detail::p256_verify( + detail::checked_signature_bytes(signature_value), + signing_input, point_); } else { // Never compiled into a program: an assertion above stopped the build. return error::invalid_signature; @@ -223,12 +241,11 @@ class basic_public_key { /** * Verifies an ECDSA signature over SHA-256 with this key, asynchronously: `verify` run when the - * operation is initiated, its result posted to `completion_executor`; the member form of - * `crypto::async_verify(completion_executor, crypto::ecdsa_sha256, signature_bytes, - * signing_input, key, completion_token)`, which calls it. + * operation is initiated, its result posted to `completion_executor`; the member form of the + * free `crypto::async_verify`, with the same arguments and this key, which calls it. * - * The key and the bytes the signature and the input view are the caller's until the - * completion. + * The key and the bytes the input views are the caller's until the completion; the signature + * is copied. * * 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 @@ -236,22 +253,23 @@ class basic_public_key { * * @tparam Executor The executor's type, an Asio executor (an `io_context`'s or a strand's). * @tparam Scheme `crypto::ecdsa_sha256_t`; another scheme stops the build. + * @tparam Signature `curves::p256::ecdsa_signature`; another type, bytes included, stops the + * build. * @tparam Input A message, bytes that convert to `std::span`, of any size, * empty included, or `crypto::prehashed<32>`; anything else stops the build. * @tparam CompletionToken Any completion token for the signature `completion_token` states. * @param completion_executor The executor the completion is posted to. * @param signing_scheme `crypto::ecdsa_sha256`. - * @param signature_bytes 64 bytes, r then s (IEEE P1363, WebCrypto's form). + * @param signature_value The signature, r then s (IEEE P1363, WebCrypto's form). * @param signing_input The signed message, or `crypto::prehashed{digest}`, its 32-byte SHA-256 * digest. * @param completion_token The completion token, of signature `void(boost::system::error_code)`: - * `invalid_signature` for a signature of another size, an r or an s that is 0 or not below n, - * and one that does not verify. + * `invalid_signature` for an r or an s that is 0 or not below n, and one that does not verify. * @return What the completion token's `async_result` gives. */ - template + template auto async_verify(Executor const& completion_executor, Scheme signing_scheme, - std::span signature_bytes, Input const& signing_input, + Signature const& signature_value, Input const& signing_input, CompletionToken&& completion_token) const; /** @@ -266,7 +284,7 @@ class basic_public_key { basic_public_key() noexcept = default; // The backend's check of a point whose size and first byte are checked, and the key made of - // it: the work of both make, which hold their own guards. + // it: the work of `from_bytes` and `from_coordinates`, which hold their own guards. [[nodiscard]] static boost::system::result checked( std::span point_bytes) noexcept { if (!engine::valid_point(point_bytes)) { @@ -307,7 +325,7 @@ class basic_keypair { using backend_type = Backend; /** The public key's type, which `crypto::verify` and `agree` take. */ using public_key_type = basic_public_key; - /** The size of the secret scalar, which `make` takes and `secret()` gives. */ + /** The size of the secret scalar, which `from_secret` takes and `secret()` gives. */ static constexpr std::size_t secret_key_size = p256::secret_key_size; /** The size of the public key, SEC 1's uncompressed point. */ static constexpr std::size_t public_key_size = p256::public_key_size; @@ -319,12 +337,12 @@ class basic_keypair { * @return The key pair; `invalid_key_size`; `invalid_secret_key` for a scalar 0 or not below * n, refused before the backend; `backend_failure`. */ - [[nodiscard]] static boost::system::result make( + [[nodiscard]] static boost::system::result from_secret( std::span secret_scalar) noexcept { - detail::timing_guard const timing; - static_assert( - !detail::asynchronous_backend_v, - "webcpp::crypto: make on this backend completes asynchronously: call async_make."); + detail::timing_guard const timing_scope; + static_assert(!detail::asynchronous_backend_v, + "webcpp::crypto: from_secret on this backend completes asynchronously: call " + "async_from_secret."); if constexpr (detail::asynchronous_backend_v) { // Never compiled into a program: the assertion above stopped the build. return error::backend_failure; @@ -337,7 +355,7 @@ class basic_keypair { return error::invalid_secret_key; } basic_keypair made_pair; - auto const engine_keyed = engine::make(made_pair.state_, scalar_bytes); + auto const engine_keyed = engine::import_secret(made_pair.state_, scalar_bytes); if (!engine_keyed) { return engine_keyed.error(); } @@ -354,7 +372,7 @@ class basic_keypair { * none; `backend_failure`. */ [[nodiscard]] static boost::system::result generate() noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert(!detail::asynchronous_backend_v, "webcpp::crypto: generate on this backend completes asynchronously: call " "async_generate."); @@ -371,15 +389,14 @@ class basic_keypair { return error::entropy_unavailable; } } while (!detail::p_curve_scalar_valid(scalar_bytes.bytes(), traits::order)); - return make(scalar_bytes.bytes()); + return from_secret(scalar_bytes.bytes()); } } /** - * Makes a key pair from its secret scalar, asynchronously: `make` run when the operation is - * initiated, its result posted to `completion_executor`; the member form of - * `crypto::async_make(completion_executor, secret_scalar, completion_token)`, - * which calls it. + * Makes a key pair from its secret scalar, asynchronously: `from_secret` run when the operation + * is initiated, its result posted to `completion_executor`; the member form of the free + * `crypto::async_from_secret`, with the same arguments, which calls it. * * 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 @@ -396,9 +413,9 @@ class basic_keypair { * @return What the completion token's `async_result` gives. */ template - static auto async_make(Executor const& completion_executor, - std::span secret_scalar, - CompletionToken&& completion_token); + static auto async_from_secret(Executor const& completion_executor, + std::span secret_scalar, + CompletionToken&& completion_token); /** * Makes a key pair from a fresh scalar, asynchronously: `generate` run when the operation is @@ -472,7 +489,8 @@ class basic_keypair { } /** - * The secret scalar, for a program that keeps the key pair and makes it again with `make`. + * The secret scalar, for a program that keeps the key pair and makes it again with + * `from_secret`. * * @return 32 secret bytes, big-endian; `invalid_state` moved from. */ @@ -497,13 +515,13 @@ class basic_keypair { * @param signing_input The message, hashed with SHA-256 inside the call, as WebCrypto's ECDSA * with SHA-256 hashes it; or `crypto::prehashed{digest}`, its 32-byte SHA-256 digest, signed as * given. - * @return 64 bytes, r then s (IEEE P1363, WebCrypto's form); `invalid_state` moved from; - * `backend_failure`, which a valid key pair cannot cause. + * @return The signature, `curves::p256::ecdsa_signature`, r then s (IEEE P1363, WebCrypto's + * form); `invalid_state` moved from; `backend_failure`, which a valid key pair cannot cause. */ template - [[nodiscard]] boost::system::result> sign( + [[nodiscard]] boost::system::result> sign( [[maybe_unused]] Scheme signing_scheme, Input const& signing_input) const noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert(std::is_same_v, "webcpp::crypto: a P-256 key signs with crypto::ecdsa_sha256."); static_assert(!detail::asynchronous_backend_v, @@ -530,9 +548,8 @@ class basic_keypair { /** * Signs with ECDSA over SHA-256, asynchronously: `sign` run when the operation is initiated, - * its result posted to `completion_executor`; the member form of - * `crypto::async_sign(completion_executor, key_pair, signing_scheme, signing_input, - * completion_token)`, which calls it. + * its result posted to `completion_executor`; the member form of the free `crypto::async_sign`, + * with the same arguments and this key pair, which calls it. * * The scheme and the input are checked as `crypto::can_sign` checks them, before anything * else. The key pair and the bytes the input views are the caller's until the completion. @@ -550,8 +567,8 @@ class basic_keypair { * @param signing_scheme `crypto::ecdsa_sha256`. * @param signing_input The message, hashed with SHA-256, or `crypto::prehashed{digest}`. * @param completion_token The completion token, of signature - * `void(boost::system::error_code, std::array)`: r then s, S low; on an error - * 64 zeros (`invalid_state`, `backend_failure`). + * `void(boost::system::error_code, curves::p256::ecdsa_signature)`: r then s, S low; on an + * error the signature of zeros (`invalid_state`, `backend_failure`). * @return What the completion token's `async_result` gives. */ template @@ -571,7 +588,7 @@ class basic_keypair { */ [[nodiscard]] boost::system::result> agree( basic_public_key const& peer_key) const noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert( !detail::asynchronous_backend_v, "webcpp::crypto: agree on this backend completes asynchronously: call async_agree."); @@ -624,7 +641,7 @@ class basic_keypair { // constant time: n - s is computed always and selected with a mask, with no branch on s and // nothing declassified, so that the signature stays as secret to a constant-time checker as // the engine made it. - [[nodiscard]] boost::system::result> signed_digest( + [[nodiscard]] boost::system::result signed_digest( std::span digest_bytes) const noexcept { if (!keyed_) { return error::invalid_state; @@ -645,7 +662,7 @@ class basic_keypair { s_byte = static_cast( kept_byte ^ (high_mask & (kept_byte ^ unsigned{negated_s[byte_index]}))); } - return signature_bytes; + return detail::signature_access::of(signature_bytes); } state_type state_{}; @@ -660,29 +677,29 @@ using keypair = basic_keypair<>; * and OpenSSL carry. * * @tparam Backend The backend that encodes; by default the family's. - * @param signature_bytes 64 bytes, r then s. - * @param output_bytes At least `max_der_size` bytes, whatever this signature's length; nothing is + * @param signature_value The signature. + * @param der_output At least `max_der_size` bytes, whatever this signature's length; nothing is * written on an error. * @return The number of bytes written, 8 to `max_der_size`; `invalid_input_size` when - * `output_bytes` is shorter than `max_der_size`; `invalid_signature` when r or s is 0 or not below + * `der_output` is shorter than `max_der_size`; `invalid_signature` when r or s is 0 or not below * n. */ template > [[nodiscard]] boost::system::result to_der( - std::span signature_bytes, - std::span output_bytes) noexcept { - detail::timing_guard const timing; + ecdsa_signature const& signature_value, std::span der_output) noexcept { + detail::timing_guard const timing_scope; using engine = detail::p_curve_engine; - if (output_bytes.size() < max_der_size) { + if (der_output.size() < max_der_size) { return error::invalid_input_size; } + std::span const signature_bytes(signature_value.bytes()); if (!detail::p_curve_signature_in_range(signature_bytes)) { return error::invalid_signature; } std::array der_bytes{}; std::size_t const der_length = engine::to_der(signature_bytes, der_bytes); std::ranges::copy(std::span(der_bytes).first(der_length), - output_bytes.begin()); + der_output.begin()); return der_length; } @@ -691,14 +708,14 @@ template > * * @tparam Backend The backend that decodes; by default the family's. * @param der_signature The encoding, exactly: nothing may follow it. - * @return 64 bytes, r then s; `invalid_signature` for anything that is not strict DER (a needless - * zero byte, a long length where a short one holds it, a negative integer, bytes after it, - * nothing), and for an r or an s that is 0 or not below n. + * @return The signature, r then s; `invalid_signature` for anything that is not strict DER (a + * needless zero byte, a long length where a short one holds it, a negative integer, bytes after + * it, nothing), and for an r or an s that is 0 or not below n. */ template > -[[nodiscard]] boost::system::result> from_der( +[[nodiscard]] boost::system::result from_der( std::span der_signature) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; using engine = detail::p_curve_engine; if (der_signature.empty()) { return error::invalid_signature; @@ -708,7 +725,7 @@ template > !detail::p_curve_signature_in_range(signature_bytes)) { return error::invalid_signature; } - return signature_bytes; + return detail::signature_access::of(signature_bytes); } /** @@ -719,23 +736,23 @@ template > * signature made elsewhere, such as WebCrypto's, whose S may be high. Arithmetic on public bytes, * with no backend. * - * @param signature_bytes 64 bytes, r then s. - * @return 64 bytes, r then s, with s at most (n - 1) / 2; `invalid_signature` when r or s is 0 or - * not below n. + * @param signature_value The signature. + * @return The signature with s at most (n - 1) / 2; `invalid_signature` when r or s is 0 or not + * below n. */ -[[nodiscard]] inline boost::system::result> -normalize_low_s(std::span signature_bytes) noexcept { +[[nodiscard]] inline boost::system::result normalize_low_s( + ecdsa_signature const& signature_value) noexcept { + std::span const signature_bytes(signature_value.bytes()); if (!detail::p_curve_signature_in_range(signature_bytes)) { return error::invalid_signature; } - std::array normalized_signature{}; - std::ranges::copy(signature_bytes, normalized_signature.begin()); + std::array normalized_signature = signature_value.bytes(); auto const s_value = signature_bytes.last(); if (!detail::p_curve_low_s(s_value)) { detail::p_curve_negate_scalar( s_value, std::span(normalized_signature).last()); } - return normalized_signature; + return detail::signature_access::of(normalized_signature); } /** @@ -744,11 +761,11 @@ normalize_low_s(std::span signature_bytes) n * * Arithmetic on public bytes, with no backend; it does not verify the signature. * - * @param signature_bytes 64 bytes, r then s. + * @param signature_value The signature. * @return True exactly when 0 < r < n and 0 < s <= (n - 1) / 2. */ -[[nodiscard]] inline bool is_low_s( - std::span signature_bytes) noexcept { +[[nodiscard]] inline bool is_low_s(ecdsa_signature const& signature_value) noexcept { + std::span const signature_bytes(signature_value.bytes()); return detail::p_curve_signature_in_range(signature_bytes) && detail::p_curve_low_s(signature_bytes.last()); } @@ -766,31 +783,36 @@ namespace webcpp::crypto { * * @tparam Backend The key's backend, which verifies: deduced from the key, or named first, as on * every curve, when it is the key's (another backend matches no overload). + * @tparam Signature `curves::p256::ecdsa_signature`; another type, a signature of another curve + * or bytes, stops the build. * @tparam Input A message, bytes that convert to `std::span`, of any size, * empty included, or `crypto::prehashed<32>`; anything else stops the build. * @param signing_scheme `crypto::ecdsa_sha256`. - * @param signature_bytes 64 bytes, r then s (IEEE P1363, WebCrypto's form), as any bytes; - * `curves::p256::from_der` reads DER. + * @param signature_value The signature, r then s (IEEE P1363, WebCrypto's form); bytes from a + * peer are made into one by `curves::p256::ecdsa_signature::from_bytes`, and DER by + * `curves::p256::from_der`. * @param signing_input The signed message, hashed with SHA-256 inside the call; or * `crypto::prehashed{digest}`, its 32-byte SHA-256 digest. * @param public_key The signer's public key. - * @return Nothing; `invalid_signature` for a signature of another size, an r or an s that is 0 or - * not below n, refused before the backend, and a signature that does not verify. A digest whose - * value modulo n is 0 (32 zero bytes, or n itself), which no SHA-256 of a message gives in - * practice, is refused too: BearSSL's verification refuses a zero multiplier. + * @return Nothing; `invalid_signature` for an r or an s that is 0 or not below n, refused before + * the backend, and a signature that does not verify. A digest whose value modulo n is 0 (32 zero + * bytes, or n itself), which no SHA-256 of a message gives in practice, is refused too: BearSSL's + * verification refuses a zero multiplier. */ -template +template [[nodiscard]] boost::system::result verify( - [[maybe_unused]] ecdsa_sha256_t signing_scheme, std::span signature_bytes, + [[maybe_unused]] ecdsa_sha256_t signing_scheme, Signature const& signature_value, Input const& signing_input, curves::p256::basic_public_key const& public_key) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert(!detail::asynchronous_backend_v, "webcpp::crypto: verify on this backend completes asynchronously: call " "async_verify."); if constexpr (!detail::asynchronous_backend_v) { - return detail::p256_verify(signature_bytes, signing_input, - detail::p_curve_access::point(public_key)); + return detail::p256_verify( + detail::checked_signature_bytes( + signature_value), + signing_input, detail::p_curve_access::point(public_key)); } else { // Never compiled into a program: the assertion above stopped the build. return error::invalid_signature; @@ -818,6 +840,28 @@ template inline constexpr bool verifies_with_v, ecdsa_sha256_t> = true; +/** + * A P-256 key pair's signature under ECDSA over SHA-256, `curves::p256::ecdsa_signature`. + * + * @tparam Backend The key's backend. + */ +template +struct signature_of, ecdsa_sha256_t> { + /** The signature type. */ + using type = curves::p256::ecdsa_signature; +}; + +/** + * A P-256 public key's signature under ECDSA over SHA-256, `curves::p256::ecdsa_signature`. + * + * @tparam Backend The key's backend. + */ +template +struct signature_of, ecdsa_sha256_t> { + /** The signature type. */ + using type = curves::p256::ecdsa_signature; +}; + /** * A P-256 key pair's backend. * @@ -862,7 +906,8 @@ struct p_curve_engine { /** Never called; fails closed. */ template - [[nodiscard]] static boost::system::result make(Arguments&&... /*arguments*/) noexcept { + [[nodiscard]] static boost::system::result import_secret( + Arguments&&... /*arguments*/) noexcept { return error::backend_failure; } @@ -922,11 +967,19 @@ struct p_curve_engine { #if defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_P256_BEARSSL) && defined(WEBCPP_CRYPTO_HAS_BEARSSL) #include -// The key pair contract (design D8), on the family's default backend. +// The key pair concepts (design D4), on the family's default backend: it signs and agrees. static_assert( ::webcpp::crypto::keypair< ::webcpp::crypto::curves::p256::basic_keypair<::webcpp::crypto::backends::bearssl>>, "webcpp::crypto: P-256's key pair meets crypto::keypair."); +static_assert( + ::webcpp::crypto::signing_keypair< + ::webcpp::crypto::curves::p256::basic_keypair<::webcpp::crypto::backends::bearssl>>, + "webcpp::crypto: P-256's key pair meets crypto::signing_keypair."); +static_assert( + ::webcpp::crypto::agreement_keypair< + ::webcpp::crypto::curves::p256::basic_keypair<::webcpp::crypto::backends::bearssl>>, + "webcpp::crypto: P-256's key pair meets crypto::agreement_keypair."); #endif #endif // WEBCPP_CRYPTO_CURVES_P256_HPP diff --git a/include/webcpp/crypto/curves/p256/formats.hpp b/include/webcpp/crypto/curves/p256/formats.hpp index d615c175..a0c562f8 100644 --- a/include/webcpp/crypto/curves/p256/formats.hpp +++ b/include/webcpp/crypto/curves/p256/formats.hpp @@ -18,12 +18,12 @@ #include +#include #include #include #include #include #include -#include #include #include @@ -101,7 +101,7 @@ template /** * The public key of an SPKI that is exactly what `encode_spki` writes, its point checked as - * `basic_public_key::make` checks it. + * `basic_public_key::from_bytes` checks it. * * @tparam Backend The backend that checks the point; by default the family's. * @param spki_bytes The SPKI, exactly: nothing may follow it. @@ -112,13 +112,13 @@ template template > [[nodiscard]] boost::system::result> decode_spki( std::span spki_bytes) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; constexpr std::size_t prefix_size = detail::p256_spki_prefix.size(); if (spki_bytes.size() != max_spki_size || - !equal(spki_bytes.first(prefix_size), detail::p256_spki_prefix)) { + !constant_time_equal(spki_bytes.first(prefix_size), detail::p256_spki_prefix)) { return error::invalid_encoding; } - auto decoded_key = basic_public_key::make(spki_bytes.subspan(prefix_size)); + auto decoded_key = basic_public_key::from_bytes(spki_bytes.subspan(prefix_size)); if (!decoded_key) { if (decoded_key.error() == error::invalid_public_key) { return error::invalid_encoding; @@ -165,32 +165,32 @@ template /** * The key pair of a PKCS#8 that is exactly what `encode_pkcs8` writes for its scalar, made as - * `basic_keypair::make` makes it. + * `basic_keypair::from_secret` makes it. * * @tparam Backend The backend; by default the family's. * @param pkcs8_bytes The PKCS#8, exactly: nothing may follow it. * @return The key pair; `invalid_encoding` for any other bytes: another version, another curve, * no public key, [0] parameters inside the ECPrivateKey, a scalar 0 or not below n, a public key - * that is not the scalar's; `backend_failure` as `make` reports it. + * that is not the scalar's; `backend_failure` as `from_secret` reports it. */ template > [[nodiscard]] boost::system::result> decode_pkcs8( std::span pkcs8_bytes) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; constexpr std::size_t prefix_size = detail::p256_pkcs8_prefix.size(); constexpr std::size_t infix_at = prefix_size + secret_key_size; constexpr std::size_t point_at = infix_at + detail::p256_pkcs8_infix.size(); if (pkcs8_bytes.size() != max_pkcs8_size || - !equal(pkcs8_bytes.first(prefix_size), detail::p256_pkcs8_prefix) || - !equal(pkcs8_bytes.subspan(infix_at, detail::p256_pkcs8_infix.size()), - detail::p256_pkcs8_infix)) { + !constant_time_equal(pkcs8_bytes.first(prefix_size), detail::p256_pkcs8_prefix) || + !constant_time_equal(pkcs8_bytes.subspan(infix_at, detail::p256_pkcs8_infix.size()), + detail::p256_pkcs8_infix)) { return error::invalid_encoding; } // The scalar's copy is a secret, wiped when it goes, on every path. secret scalar_bytes; std::ranges::copy(pkcs8_bytes.subspan(prefix_size, secret_key_size), scalar_bytes.writable().begin()); - auto made_pair = basic_keypair::make(scalar_bytes.bytes()); + auto made_pair = basic_keypair::from_secret(scalar_bytes.bytes()); if (!made_pair) { if (made_pair.error() == error::invalid_secret_key) { return error::invalid_encoding; @@ -204,7 +204,8 @@ template > // The point is d * G, computed from the secret; whether the input's is the same is public. // Not const: the branch reads it again after the mark (detail/declassify.hpp's tip). // NOLINTNEXTLINE(misc-const-correctness): see above - bool is_same = equal(public_point.unsafe_value().uncompressed(), pkcs8_bytes.subspan(point_at)); + bool is_same = constant_time_equal(public_point.unsafe_value().uncompressed(), + pkcs8_bytes.subspan(point_at)); WEBCPP_CRYPTO_DETAIL_DECLASSIFY(&is_same, sizeof is_same); if (!is_same) { return error::invalid_encoding; diff --git a/include/webcpp/crypto/curves/secp256k1.hpp b/include/webcpp/crypto/curves/secp256k1.hpp index 318fe2d2..4ea4addf 100644 --- a/include/webcpp/crypto/curves/secp256k1.hpp +++ b/include/webcpp/crypto/curves/secp256k1.hpp @@ -7,13 +7,16 @@ /** secp256k1 on libsecp256k1: a key pair made from its 32-byte secret key, which `secret()` gives back, and its typed public key, `curves::secp256k1::public_key`, made from SEC1 bytes by - `public_key::make` and giving its compressed, uncompressed and x-only forms; + `public_key::from_bytes` and giving its compressed, uncompressed and x-only forms; `key.sign(scheme, input)` with `crypto::ecdsa_sha256` (hedged too), - `crypto::ecdsa_sha256_recoverable` and `crypto::schnorr` (BIP340), the input a message or, for - ECDSA, `crypto::prehashed{digest}`; `crypto::verify` of ECDSA against the public key and of - Schnorr against the public key or its 32-byte x-only form; `recover`, the signer's key; ECDH in - three forms, `agree` (the shared x, as P-256's), `agree_hashed` and `agree_point`, each a secret; - ECDSA's DER form, `normalize_low_s` and `is_low_s`, the tweak of an x-only key, and the + `crypto::ecdsa_sha256_recoverable`, `crypto::ecdsa_keccak256_recoverable` (Ethereum's, over + Keccak-256: a message needs `/third_party//xkcp`) and `crypto::schnorr` (BIP340), the input a + message or, for ECDSA, `crypto::prehashed{digest}`, each giving its own signature type, + `ecdsa_signature`, `recoverable_signature` (both recoverable schemes) and `schnorr_signature`; + `crypto::verify` of ECDSA against the public key and of Schnorr against the public key or its + 32-byte x-only form; `recover`, the signer's key, under either recoverable scheme; ECDH + in three forms, `agree` (the shared x, as P-256's), `agree_hashed` and `agree_point`, each a + secret; ECDSA's DER form, `normalize_low_s` and `is_low_s`, the tweak of an x-only key, and the workspace a function over many keys borrows. @see "secp256k1", in the guide. @@ -27,6 +30,7 @@ #include #include #include +#include #include #include #include @@ -35,6 +39,12 @@ #include #include +#ifdef WEBCPP_HASH_HAS_XKCP +#include // crypto::ecdsa_keccak256_recoverable's hash of a message + +#include +#endif + #include #include @@ -60,6 +70,24 @@ class public_key; namespace webcpp::crypto::detail { +/** The tag of `curves::secp256k1::ecdsa_signature`. */ +struct secp256k1_ecdsa_signature_tag { + /** No recovery id. */ + static constexpr bool recoverable = false; +}; + +/** The tag of `curves::secp256k1::recoverable_signature`. */ +struct secp256k1_recoverable_signature_tag { + /** The last byte is the recovery id. */ + static constexpr bool recoverable = true; +}; + +/** The tag of `curves::secp256k1::schnorr_signature`. */ +struct secp256k1_schnorr_signature_tag { + /** No recovery id. */ + static constexpr bool recoverable = false; +}; + /** * The one door of the module headers (those under `curves/secp256k1/`) into a key pair and a public * key: the key pair's context and `secp256k1_keypair`, whether it is keyed, and a public key's @@ -389,20 +417,38 @@ template } /** - * The size of a signature of `Scheme` that a secp256k1 key pair's `sign` returns: the scheme's - * (65 for `ecdsa_sha256_recoverable`), and 64 for any type that is no scheme of the curve's, so - * that such a call reaches `sign`'s assertion of the schemes it has rather than failing to name - * a return type. + * The 32-byte digest Ethereum's recoverable ECDSA signs and recovers from: a marker's digest, + * copied, or the Keccak-256 of a message (webcpp::hash's `keccak_256`, the original padding, + * never SHA3-256), which needs XKCP: without `/third_party//xkcp`, a message stops the build. * - * @tparam Scheme Any type. + * @tparam Input A message or `prehashed<32>`, which `check_input` has accepted. + * @param signing_input The message or the marker. + * @return The digest. */ -template -inline constexpr std::size_t secp256k1_signature_size = 64; - -/** The size of a recoverable signature: r, s and the recovery id. */ -template <> -inline constexpr std::size_t secp256k1_signature_size = - scheme_traits::signature_size; +template +[[nodiscard]] std::array secp256k1_keccak_digest( + Input const& signing_input) noexcept { + std::array digest_bytes{}; + if constexpr (is_prehashed_v) { + std::ranges::copy(signing_input.digest, digest_bytes.begin()); + } else { +#ifdef WEBCPP_HASH_HAS_XKCP + auto const bytes_of_message = message_bytes(signing_input); + ::webcpp::hash::keccak_256 keccak_hasher; + keccak_hasher.update(bytes_of_message.data(), bytes_of_message.size()); + static_assert( + std::is_same_v<::webcpp::hash::keccak_256::result_type, boost::hash2::digest<32>>); + auto const hash_result = keccak_hasher.result(); + std::copy_n(hash_result.data(), digest_bytes.size(), digest_bytes.begin()); +#else + static_assert(refused_v, + "webcpp::crypto: crypto::ecdsa_keccak256_recoverable hashes a message with " + "webcpp::hash's keccak_256, which needs XKCP: add /third_party//xkcp to the " + "program's Jamfile, or sign crypto::prehashed{digest}."); +#endif + } + return digest_bytes; +} extern "C" { @@ -511,26 +557,22 @@ inline constexpr bool secp256k1_refuses_others = sizeof(secp256k1_refusal [[nodiscard]] boost::system::result secp256k1_verify_schnorr_key( - std::span signature_bytes, Input const& message_input, + std::span signature_bytes, Input const& message_input, secp256k1_pubkey const& point_value) noexcept { check_input(); if constexpr (input_valid_v) { - if (signature_bytes.size() != 64) { - return error::invalid_signature; - } auto const bytes_of_message = message_bytes(message_input); read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); secp256k1_selftest(); auto const xonly_key = secp256k1_xonly_of(point_value); - return secp256k1_verify_schnorr(signature_bytes.first<64>(), bytes_of_message, xonly_key); + return secp256k1_verify_schnorr(signature_bytes, bytes_of_message, xonly_key); } else { // Never compiled into a program: check_input stopped the build. return error::invalid_signature; @@ -544,21 +586,18 @@ template * * @tparam Backend The backend, libsecp256k1. * @tparam Input A message or `crypto::prehashed<32>`; anything else stops the build. - * @param signature_bytes 64 bytes, r then s; its size is checked first. + * @param signature_bytes The signature's 64 bytes, r then s. * @param signing_input The signed message, hashed with SHA-256 here, or the marker of its digest. * @param point_value The signer's point. - * @return Nothing; `invalid_signature` for a signature of another size, an r or an s not below the - * group order, a high S, or a signature that does not verify. + * @return Nothing; `invalid_signature` for an r or an s not below the group order, a high S, or a + * signature that does not verify. */ template [[nodiscard]] boost::system::result secp256k1_verify_ecdsa( - std::span signature_bytes, Input const& signing_input, + std::span signature_bytes, Input const& signing_input, secp256k1_pubkey const& point_value) noexcept { check_input(); if constexpr (input_valid_v) { - if (signature_bytes.size() != 64) { - return error::invalid_signature; - } auto const digest_bytes = secp256k1_digest(signing_input); read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); secp256k1_selftest(); @@ -580,6 +619,35 @@ template namespace webcpp::crypto::curves::secp256k1 { +/** + * A secp256k1 ECDSA signature, 64 bytes, r then s: what `sign(crypto::ecdsa_sha256, ...)` gives + * and `crypto::verify(crypto::ecdsa_sha256, ...)` takes. + * + * Each of r and s is 32 bytes big-endian (libsecp256k1's compact form). `from_bytes` checks the + * size alone; whether r and s are in range, and s low, is verification's and `normalize_low_s`'s + * judgment. + */ +using ecdsa_signature = detail::basic_signature; + +/** + * A secp256k1 recoverable ECDSA signature, 65 bytes, r, s and the recovery id: what `sign` gives + * with `crypto::ecdsa_sha256_recoverable` and with `crypto::ecdsa_keccak256_recoverable`, and + * what `recover` takes, under the scheme that signed it (design R20). + * + * `recovery_id()` reads its last byte. `from_bytes` checks the size alone; `recover` refuses an id + * above 3. + */ +using recoverable_signature = + detail::basic_signature; + +/** + * A BIP340 Schnorr signature, 64 bytes, R's x then s: what `sign(crypto::schnorr, ...)` gives and + * `crypto::verify(crypto::schnorr, ...)` takes. + * + * `from_bytes` checks the size alone. + */ +using schnorr_signature = detail::basic_signature; + /** The longest strict DER encoding of a secp256k1 ECDSA signature, in bytes. */ inline constexpr std::size_t max_der_size = 72; @@ -623,10 +691,10 @@ inline constexpr std::size_t recoverable_signature_size = 65; * `secp256k1_pubkey`), which `crypto::verify` takes, of ECDSA and of Schnorr, and a key pair's * `agree` takes as its peer. * - * It holds nothing secret and is copied freely; it is made only by `make` and by the functions - * that return one (a key pair's `public_key()`, `recover`, the tweaks), so that it is always - * valid. It gives its bytes in each of its forms: `compressed()` (33, Bitcoin's), `uncompressed()` - * (65, Ethereum's) and `xonly()` (32, BIP340's). + * It holds nothing secret and is copied freely; it is made only by `from_bytes` and by the + * functions that return one (a key pair's `public_key()`, `recover`, the tweaks), so that it is + * always valid. It gives its bytes in each of its forms: `compressed()` (33, Bitcoin's), + * `uncompressed()` (65, Ethereum's) and `xonly()` (32, BIP340's). */ class public_key { public: @@ -642,9 +710,9 @@ class public_key { * curve. */ template > - [[nodiscard]] static boost::system::result make( + [[nodiscard]] static boost::system::result from_bytes( std::span encoded_key) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); @@ -664,7 +732,7 @@ class public_key { */ [[nodiscard]] std::array> compressed() const noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; return encoded>( webcpp::crypto::detail::secp256k1_compressed); } @@ -676,7 +744,7 @@ class public_key { */ [[nodiscard]] std::array> uncompressed() const noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; return encoded>( webcpp::crypto::detail::secp256k1_uncompressed); } @@ -688,7 +756,7 @@ class public_key { * @return 32 bytes. */ [[nodiscard]] std::array xonly() const noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); secp256k1_selftest(); auto const xonly_key = webcpp::crypto::detail::secp256k1_xonly_of(point_value_); @@ -699,7 +767,7 @@ class public_key { /** * Verifies a signature with this key, of ECDSA over SHA-256 or of BIP340's Schnorr (design - * R22): `crypto::verify(signing_scheme, signature_bytes, signing_input, key)`, of which it is + * R22): `crypto::verify(signing_scheme, signature_value, signing_input, key)`, of which it is * the member form, with the same work, results and refusals. * * ECDSA's high S is refused, as libsecp256k1 refuses it; Schnorr reads the key's x-only form. @@ -707,35 +775,43 @@ class public_key { * @tparam Backend The backend, `backends::secp256k1`, the only one; another stops the build. * @tparam Scheme `crypto::ecdsa_sha256_t` or `crypto::schnorr_t`; another scheme stops the * build. + * @tparam Signature The scheme's signature type, `curves::secp256k1::ecdsa_signature` or + * `curves::secp256k1::schnorr_signature`; another type, bytes included, stops the build. * @tparam Input A message, bytes that convert to `std::span`, of any size, * empty included; or, for ECDSA, `crypto::prehashed<32>`; anything else stops the build. * @param signing_scheme `crypto::ecdsa_sha256` or `crypto::schnorr`. - * @param signature_bytes 64 bytes, as any bytes: r then s for ECDSA, BIP340's signature for - * Schnorr. + * @param signature_value The signature: r then s for ECDSA, BIP340's signature for Schnorr; + * bytes from a peer are made into one by its type's `from_bytes`. * @param signing_input For ECDSA, the message, hashed with SHA-256 inside the call, or * `crypto::prehashed{digest}`; for Schnorr, the message itself. - * @return Nothing; `invalid_signature` for a signature of another size, an r or an s not below - * the group order, a high S, or a signature that does not verify. + * @return Nothing; `invalid_signature` for an r or an s not below the group order, a high S, + * or a signature that does not verify. */ - template , class Scheme, class Input> + template , class Scheme, class Signature, + class Input> [[nodiscard]] boost::system::result verify([[maybe_unused]] Scheme signing_scheme, - std::span signature_bytes, + Signature const& signature_value, Input const& signing_input) const noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); constexpr bool is_ecdsa = std::is_same_v; constexpr bool is_schnorr = std::is_same_v; static_assert(is_ecdsa || is_schnorr, "webcpp::crypto: a secp256k1 public key verifies crypto::ecdsa_sha256 or " - "crypto::schnorr; a crypto::ecdsa_sha256_recoverable signature gives its " - "key to curves::secp256k1::recover."); + "crypto::schnorr; a crypto::ecdsa_sha256_recoverable or a " + "crypto::ecdsa_keccak256_recoverable signature gives its key to " + "curves::secp256k1::recover."); if constexpr (is_ecdsa) { return webcpp::crypto::detail::secp256k1_verify_ecdsa( - signature_bytes, signing_input, point_value_); + webcpp::crypto::detail::checked_signature_bytes( + signature_value), + signing_input, point_value_); } else if constexpr (is_schnorr) { return webcpp::crypto::detail::secp256k1_verify_schnorr_key( - signature_bytes, signing_input, point_value_); + webcpp::crypto::detail::checked_signature_bytes( + signature_value), + signing_input, point_value_); } else { // Never compiled into a program: an assertion above stopped the build. return error::invalid_signature; @@ -751,7 +827,7 @@ class public_key { */ [[nodiscard]] friend bool operator==(public_key const& left_key, public_key const& right_key) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; return compare(left_key, right_key) == 0; } @@ -764,7 +840,7 @@ class public_key { */ [[nodiscard]] friend std::strong_ordering operator<=>(public_key const& left_key, public_key const& right_key) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; return compare(left_key, right_key) <=> 0; } @@ -835,7 +911,7 @@ class basic_keypair { using name_type = families::secp256k1; /** The public key's type, which `crypto::verify` and `agree` take. */ using public_key_type = ::webcpp::crypto::curves::secp256k1::public_key; - /** The size of the secret key, which `make` takes and `secret()` gives. */ + /** The size of the secret key, which `from_secret` takes and `secret()` gives. */ static constexpr std::size_t secret_key_size = 32; /** The most draws `generate` makes: 32 bytes that are not a secret key are drawn again. */ static constexpr int max_draws = 4; @@ -854,10 +930,10 @@ class basic_keypair { * `secp256k1_keypair_create` only on a secret `secp256k1_ec_seckey_verify` refuses). A * failed allocation is the resource's to report; the seed is wiped then too. */ - [[nodiscard]] static boost::system::result make( + [[nodiscard]] static boost::system::result from_secret( std::span secret_bytes, std::pmr::memory_resource* memory_resource = std::pmr::get_default_resource()) { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; if (secret_bytes.size() != secret_key_size) { return error::invalid_key_size; } @@ -898,11 +974,11 @@ class basic_keypair { * @param memory_resource The resource of the signing context, the one allocation; it must * outlive the key pair. * @return The key pair; `entropy_unavailable` when the system's generator fails, there is - * none, or four draws were not a secret key; `backend_failure` as `make` returns it. + * none, or four draws were not a secret key; `backend_failure` as `from_secret` returns it. */ [[nodiscard]] static boost::system::result generate( std::pmr::memory_resource* memory_resource = std::pmr::get_default_resource()) { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; for (int draw_count = 0; draw_count < max_draws; ++draw_count) { crypto::secret secret_key; auto const entropy_drawn = @@ -912,7 +988,7 @@ class basic_keypair { // failure for a key pair: one error to handle. return error::entropy_unavailable; } - auto made_pair = make(secret_key.bytes(), memory_resource); + auto made_pair = from_secret(secret_key.bytes(), memory_resource); if (made_pair || made_pair.error() != error::invalid_secret_key) { return made_pair; } @@ -966,7 +1042,7 @@ class basic_keypair { * @return The public key; `invalid_state` moved from. */ [[nodiscard]] boost::system::result public_key() const noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; if (!keyed_) { return error::invalid_state; } @@ -980,12 +1056,12 @@ class basic_keypair { /** * The secret key (`secp256k1_keypair_sec`), for a program that keeps the key pair and makes it - * again with `make`, or exports it. + * again with `from_secret`, or exports it. * * @return 32 secret bytes, big-endian; `invalid_state` moved from. */ [[nodiscard]] boost::system::result> secret() const noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; if (!keyed_) { return error::invalid_state; } @@ -997,36 +1073,44 @@ class basic_keypair { } /** - * Signs with one of secp256k1's three schemes: ECDSA over SHA-256 with RFC 6979's nonce, low - * S, as libsecp256k1 signs; the same with the recovery id; or BIP340's Schnorr, with 32 bytes - * of auxiliary randomness drawn from the system's generator, as BIP340 recommends. + * Signs with one of secp256k1's four schemes: ECDSA over SHA-256 with RFC 6979's nonce, low + * S, as libsecp256k1 signs; the same with the recovery id; Ethereum's recoverable ECDSA, the + * same over Keccak-256 (EIP-2's low S); or BIP340's Schnorr, with 32 bytes of auxiliary + * randomness drawn from the system's generator, as BIP340 recommends. * - * @tparam Scheme `crypto::ecdsa_sha256_t`, `crypto::ecdsa_sha256_recoverable_t` or - * `crypto::schnorr_t`; another scheme stops the build. + * @tparam Scheme `crypto::ecdsa_sha256_t`, `crypto::ecdsa_sha256_recoverable_t`, + * `crypto::ecdsa_keccak256_recoverable_t` or `crypto::schnorr_t`; another scheme stops the + * build. * @tparam Input A message, bytes that convert to `std::span`, of any size, - * empty included; or, for the two ECDSA schemes, `crypto::prehashed<32>`; anything else stops - * the build. - * @param signing_scheme `crypto::ecdsa_sha256`, `crypto::ecdsa_sha256_recoverable` or - * `crypto::schnorr`. - * @param signing_input For ECDSA, the message, hashed with SHA-256 inside the call, or - * `crypto::prehashed{digest}`, a 32-byte digest signed as given (a Bitcoin sighash); for - * Schnorr, the message itself, signed as given. - * @return 64 bytes, r then s, for `ecdsa_sha256`; 65, r, s and the recovery id 0 to 3, for - * `ecdsa_sha256_recoverable`; 64, BIP340's signature, for `schnorr`; `invalid_state` moved - * from; `entropy_unavailable` when Schnorr's auxiliary randomness cannot be drawn; + * empty included; or, for the three ECDSA schemes, `crypto::prehashed<32>`; anything else + * stops the build, and so does a message for `ecdsa_keccak256_recoverable` in a program that + * does not link `/third_party//xkcp`. + * @param signing_scheme `crypto::ecdsa_sha256`, `crypto::ecdsa_sha256_recoverable`, + * `crypto::ecdsa_keccak256_recoverable` or `crypto::schnorr`. + * @param signing_input For ECDSA, the message, hashed inside the call with SHA-256, or with + * Keccak-256 for `ecdsa_keccak256_recoverable`, or `crypto::prehashed{digest}`, a 32-byte + * digest signed as given (a Bitcoin sighash, an EIP-191 or EIP-712 digest, a transaction's + * hash); for Schnorr, the message itself, signed as given. + * @return The scheme's signature: an `ecdsa_signature`, r then s, for `ecdsa_sha256`; a + * `recoverable_signature`, r, s and the recovery id 0 to 3, for `ecdsa_sha256_recoverable` and + * `ecdsa_keccak256_recoverable`; a `schnorr_signature`, BIP340's, for `schnorr`; + * `invalid_state` moved from; + * `entropy_unavailable` when Schnorr's auxiliary randomness cannot be drawn; * `backend_failure`. */ template [[nodiscard]] boost::system::result< - std::array>> + webcpp::crypto::detail::signature_of_t> sign([[maybe_unused]] Scheme signing_scheme, Input const& signing_input) const noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; constexpr bool has_scheme = std::is_same_v || std::is_same_v || + std::is_same_v || std::is_same_v; static_assert(has_scheme, "webcpp::crypto: a secp256k1 key signs with crypto::ecdsa_sha256, " - "crypto::ecdsa_sha256_recoverable or crypto::schnorr."); + "crypto::ecdsa_sha256_recoverable, crypto::ecdsa_keccak256_recoverable or " + "crypto::schnorr."); if constexpr (has_scheme) { detail::check_input(); if constexpr (!detail::input_valid_v) { @@ -1037,8 +1121,11 @@ class basic_keypair { } else if constexpr (std::is_same_v) { return signed_ecdsa(webcpp::crypto::detail::secp256k1_digest(signing_input), nullptr); - } else { + } else if constexpr (std::is_same_v) { return signed_recoverable(webcpp::crypto::detail::secp256k1_digest(signing_input)); + } else { + return signed_recoverable( + webcpp::crypto::detail::secp256k1_keccak_digest(signing_input)); } } else { // Never compiled into a program: the assertion above stopped the build. @@ -1057,13 +1144,13 @@ class basic_keypair { * @param signing_input The message, hashed with SHA-256 inside the call, or * `crypto::prehashed{digest}`, a 32-byte digest signed as given. * @param extra_entropy 32 bytes from crypto's random device, new for each signature. - * @return 64 bytes, r then s; `invalid_state` moved from; `backend_failure`. + * @return The signature, r then s; `invalid_state` moved from; `backend_failure`. */ template - [[nodiscard]] boost::system::result> sign( + [[nodiscard]] boost::system::result sign( [[maybe_unused]] ecdsa_sha256_t signing_scheme, Input const& signing_input, std::span extra_entropy) const noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; detail::check_input(); if constexpr (detail::input_valid_v) { webcpp::crypto::detail::secp256k1_secret nonce_data; @@ -1084,17 +1171,17 @@ class basic_keypair { * `crypto::prehashed` marker, or anything else, stops the build. * @param signing_scheme `crypto::schnorr`. * @param message_input The message, of any length, signed as given. - * @param aux_random 32 bytes of fresh randomness, the caller's. - * @return 64 bytes; `invalid_state` moved from; `backend_failure`. + * @param auxiliary_random_bytes 32 bytes of fresh randomness, the caller's. + * @return The signature; `invalid_state` moved from; `backend_failure`. */ template - [[nodiscard]] boost::system::result> sign( + [[nodiscard]] boost::system::result sign( [[maybe_unused]] schnorr_t signing_scheme, Input const& message_input, - std::span aux_random) const noexcept { - detail::timing_guard const timing; + std::span auxiliary_random_bytes) const noexcept { + detail::timing_guard const timing_scope; detail::check_input(); if constexpr (detail::input_valid_v) { - return signed_schnorr(detail::message_bytes(message_input), aux_random); + return signed_schnorr(detail::message_bytes(message_input), auxiliary_random_bytes); } else { // Never compiled into a program: check_input stopped the build. return error::backend_failure; @@ -1115,7 +1202,7 @@ class basic_keypair { */ [[nodiscard]] boost::system::result> agree( public_key_type const& peer_key) const noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; return ecdh_secret<32>(peer_key, webcpp::crypto::detail::webcpp_crypto_detail_secp256k1_copy_x); } @@ -1130,7 +1217,7 @@ class basic_keypair { */ [[nodiscard]] boost::system::result> agree_hashed( public_key_type const& peer_key) const noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; return ecdh_secret<32>(peer_key, nullptr); } @@ -1143,7 +1230,7 @@ class basic_keypair { */ [[nodiscard]] boost::system::result> agree_point( public_key_type const& peer_key) const noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; return ecdh_secret<65>(peer_key, webcpp::crypto::detail::webcpp_crypto_detail_secp256k1_copy_point); } @@ -1164,7 +1251,7 @@ class basic_keypair { */ [[nodiscard]] boost::system::result tweak_xonly( std::span tweak_bytes) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; if (!keyed_) { return error::invalid_state; } @@ -1187,9 +1274,9 @@ class basic_keypair { * * @param message_hash The 32-byte hash signed. * @param nonce_data 32 bytes of extra entropy, libsecp256k1's `ndata`, or null. - * @return 64 bytes, r then s, low-S; `invalid_state`; `backend_failure`. + * @return The signature, r then s, low-S; `invalid_state`; `backend_failure`. */ - [[nodiscard]] boost::system::result> signed_ecdsa( + [[nodiscard]] boost::system::result signed_ecdsa( std::span message_hash, unsigned char const* nonce_data) const noexcept { if (!keyed_) { @@ -1207,7 +1294,7 @@ class basic_keypair { } secp256k1_ecdsa_signature_serialize_compact(context_, output_bytes.data(), &signature_bytes); - return output_bytes; + return webcpp::crypto::detail::signature_access::of(output_bytes); } /** @@ -1215,10 +1302,10 @@ class basic_keypair { * `signed_ecdsa` with no extra entropy. * * @param message_hash The 32-byte hash signed. - * @return 65 bytes, r, s and the id 0 to 3; `invalid_state`; `backend_failure`. + * @return The signature, r, s and the id 0 to 3; `invalid_state`; `backend_failure`. */ - [[nodiscard]] boost::system::result> - signed_recoverable(std::span message_hash) const noexcept { + [[nodiscard]] boost::system::result signed_recoverable( + std::span message_hash) const noexcept { if (!keyed_) { return error::invalid_state; } @@ -1236,7 +1323,7 @@ class basic_keypair { secp256k1_ecdsa_recoverable_signature_serialize_compact(context_, output_bytes.data(), &recovery_id, &signature_value); output_bytes[64] = static_cast(recovery_id); - return output_bytes; + return webcpp::crypto::detail::signature_access::of(output_bytes); } /** @@ -1244,15 +1331,15 @@ class basic_keypair { * the call ends, the one copy crypto makes of it. * * @param message_bytes The message, of any length. - * @param aux_random_bytes 32 bytes of auxiliary randomness. - * @return 64 bytes; `invalid_state`; `backend_failure`. + * @param auxiliary_random_bytes 32 bytes of auxiliary randomness. + * @return The signature; `invalid_state`; `backend_failure`. */ - [[nodiscard]] boost::system::result> signed_schnorr( + [[nodiscard]] boost::system::result signed_schnorr( std::span message_bytes, - std::span aux_random_bytes) const noexcept { - webcpp::crypto::detail::secp256k1_secret aux_randomness; - std::ranges::copy(aux_random_bytes, aux_randomness.bytes.begin()); - return signed_schnorr(message_bytes, aux_randomness); + std::span auxiliary_random_bytes) const noexcept { + webcpp::crypto::detail::secp256k1_secret auxiliary_randomness; + std::ranges::copy(auxiliary_random_bytes, auxiliary_randomness.bytes.begin()); + return signed_schnorr(message_bytes, auxiliary_randomness); } /** @@ -1260,25 +1347,25 @@ class basic_keypair { * read in place: no second copy is made. * * @param message_bytes The message, of any length. - * @param aux_randomness The 32 bytes of auxiliary randomness. - * @return 64 bytes; `invalid_state`; `backend_failure`. + * @param auxiliary_randomness The 32 bytes of auxiliary randomness. + * @return The signature; `invalid_state`; `backend_failure`. */ - [[nodiscard]] boost::system::result> signed_schnorr( + [[nodiscard]] boost::system::result signed_schnorr( std::span message_bytes, - webcpp::crypto::detail::secp256k1_secret& aux_randomness) const noexcept { + webcpp::crypto::detail::secp256k1_secret& auxiliary_randomness) const noexcept { if (!keyed_) { return error::invalid_state; } webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); secp256k1_schnorrsig_extraparams extra_parameters = SECP256K1_SCHNORRSIG_EXTRAPARAMS_INIT; - extra_parameters.ndata = aux_randomness.bytes.data(); + extra_parameters.ndata = auxiliary_randomness.bytes.data(); std::array output_bytes{}; if (!webcpp::crypto::detail::secp256k1_accepted(secp256k1_schnorrsig_sign_custom( context_, output_bytes.data(), message_bytes.data(), message_bytes.size(), &keypair_, &extra_parameters))) { return error::backend_failure; } - return output_bytes; + return webcpp::crypto::detail::signature_access::of(output_bytes); } /** @@ -1286,21 +1373,21 @@ class basic_keypair { * into a buffer wiped when the call ends, their one home: the signing reads them there. * * @param message_bytes The message, of any length. - * @return 64 bytes; `invalid_state` moved from, before any draw; `entropy_unavailable` when - * the generator fails, or there is none (an Emscripten audio worklet); `backend_failure`. + * @return The signature; `invalid_state` moved from, before any draw; `entropy_unavailable` + * when the generator fails, or there is none (an Emscripten audio worklet); `backend_failure`. */ - [[nodiscard]] boost::system::result> signed_schnorr_drawn( + [[nodiscard]] boost::system::result signed_schnorr_drawn( std::span message_bytes) const noexcept { if (!keyed_) { return error::invalid_state; } - webcpp::crypto::detail::secp256k1_secret aux_randomness; + webcpp::crypto::detail::secp256k1_secret auxiliary_randomness; auto const entropy_drawn = - random_device().fill(aux_randomness.bytes); // lint-world: BIP340's aux randomness + random_device().fill(auxiliary_randomness.bytes); // lint-world: BIP340's aux_rand if (!entropy_drawn) { return error::entropy_unavailable; } - return signed_schnorr(message_bytes, aux_randomness); + return signed_schnorr(message_bytes, auxiliary_randomness); } /** @@ -1392,58 +1479,125 @@ inline curves::secp256k1::public_key secp256k1_access::make_public_key() noexcep return {}; } +/** + * The public key that made a recoverable signature of a 32-byte digest + * (`secp256k1_ecdsa_recover`), the work of `recover` under both recoverable schemes, unguarded: + * each `recover` holds the guard. + * + * A high S is accepted, as libsecp256k1's recovery and Ethereum's `ecrecover` accept it. + * + * @param signature_bytes The signature: r, s, then the recovery id. + * @param message_hash The 32-byte digest signed. + * @return The key; `invalid_signature` for a recovery id above 3, an r or an s not below the + * group order, or a signature from which no key is recovered. + */ +[[nodiscard]] inline boost::system::result secp256k1_recovered( + std::array const& signature_bytes, + std::span message_hash) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + // libsecp256k1 checks the id with ARG_CHECK, whose callback aborts: refused first here. + int const recovery_id = signature_bytes[curves::secp256k1::recoverable_signature_size - 1]; + if (recovery_id > 3) { + return error::invalid_signature; + } + secp256k1_selftest(); + secp256k1_ecdsa_recoverable_signature parsed_value{}; + curves::secp256k1::public_key recovered_key = secp256k1_access::make_public_key(); + if (secp256k1_ecdsa_recoverable_signature_parse_compact( + secp256k1_context_static, &parsed_value, signature_bytes.data(), recovery_id) == 0 || + secp256k1_ecdsa_recover(secp256k1_context_static, &secp256k1_access::point(recovered_key), + &parsed_value, message_hash.data()) == 0) { + return error::invalid_signature; + } + return recovered_key; +} + } // namespace webcpp::crypto::detail namespace webcpp::crypto::curves::secp256k1 { /** - * The public key that made a recoverable signature (`secp256k1_ecdsa_recover`), as Ethereum - * identifies a transaction's signer: the same inputs as - * `sign(crypto::ecdsa_sha256_recoverable, signing_input)`. + * The public key that made a recoverable signature (`secp256k1_ecdsa_recover`) of ECDSA over + * SHA-256: the same inputs as `sign(crypto::ecdsa_sha256_recoverable, signing_input)`. * * Tip: recovery finds some key for almost any signature; the signature is the expected * signer's only when the key recovered is the one expected. * * @tparam Backend The backend, `backends::secp256k1`. + * @tparam Signature `curves::secp256k1::recoverable_signature`; another type, bytes included, + * stops the build. * @tparam Input A message, bytes that convert to `std::span`, or * `crypto::prehashed<32>`; anything else stops the build. * @param signing_scheme `crypto::ecdsa_sha256_recoverable`. - * @param recoverable_signature 65 bytes, as any bytes: r, s, then the recovery id, 0 to 3. + * @param signature_value The signature: r, s, then the recovery id, 0 to 3; 65 bytes from a peer + * are made into one by `recoverable_signature::from_bytes`. * @param signing_input The signed message, hashed with SHA-256 inside the call, or * `crypto::prehashed{digest}`, the 32-byte digest signed. - * @return The key; `invalid_signature` for a signature of another size, a recovery id above 3, an - * r or an s not below the group order, or a signature from which no key is recovered. + * @return The key; `invalid_signature` for a recovery id above 3, an r or an s not below the + * group order, or a signature from which no key is recovered. */ -template , class Input> +template , class Signature, class Input> [[nodiscard]] boost::system::result recover( - [[maybe_unused]] ecdsa_sha256_recoverable_t signing_scheme, - std::span recoverable_signature, Input const& signing_input) noexcept { - detail::timing_guard const timing; + [[maybe_unused]] ecdsa_sha256_recoverable_t signing_scheme, Signature const& signature_value, + Input const& signing_input) noexcept { + detail::timing_guard const timing_scope; static_assert(webcpp::crypto::detail::secp256k1_refuses_others); + auto const& signature_bytes = + detail::checked_signature_bytes( + signature_value); detail::check_input(); if constexpr (detail::input_valid_v) { - if (recoverable_signature.size() != recoverable_signature_size) { - return error::invalid_signature; - } - auto const message_hash = webcpp::crypto::detail::secp256k1_digest(signing_input); - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); - // libsecp256k1 checks the id with ARG_CHECK, whose callback aborts: refused first here. - int const recovery_id = recoverable_signature[64]; - if (recovery_id > 3) { - return error::invalid_signature; - } - secp256k1_selftest(); - using access = webcpp::crypto::detail::secp256k1_access; - secp256k1_ecdsa_recoverable_signature parsed_value{}; - public_key recovered_key = access::make_public_key(); - if (secp256k1_ecdsa_recoverable_signature_parse_compact( - secp256k1_context_static, &parsed_value, recoverable_signature.data(), - recovery_id) == 0 || - secp256k1_ecdsa_recover(secp256k1_context_static, &access::point(recovered_key), - &parsed_value, message_hash.data()) == 0) { - return error::invalid_signature; - } - return recovered_key; + return webcpp::crypto::detail::secp256k1_recovered( + signature_bytes, webcpp::crypto::detail::secp256k1_digest(signing_input)); + } else { + // Never compiled into a program: check_input stopped the build. + return error::invalid_signature; + } +} + +/** + * The public key that made a signature of Ethereum's recoverable ECDSA over Keccak-256 + * (`secp256k1_ecdsa_recover`), as Ethereum identifies a transaction's or a message's signer: the + * same inputs as `sign(crypto::ecdsa_keccak256_recoverable, signing_input)`. + * + * Ethereum's `v` is the program's to turn into the recovery id (27 + id for `personal_sign`, + * 35 + 2 x chain id + id for EIP-155, the id itself, `yParity`, for a typed transaction), and the + * address the program's to compute from the key: crypto computes neither. + * + * A high S is accepted, as libsecp256k1's recovery and Ethereum's `ecrecover` accept it; EIP-2 + * refuses one in a transaction, which a program checks with `is_low_s` where it applies. + * + * Tip: recovery finds some key for almost any signature; the signature is the expected + * signer's only when the key, or its address, is the one expected. + * + * @tparam Backend The backend, `backends::secp256k1`. + * @tparam Signature `curves::secp256k1::recoverable_signature`; another type, bytes included, + * stops the build. + * @tparam Input A message, bytes that convert to `std::span`, or + * `crypto::prehashed<32>`; anything else stops the build, and so does a message in a program + * that does not link `/third_party//xkcp`. + * @param signing_scheme `crypto::ecdsa_keccak256_recoverable`. + * @param signature_value The signature: r, s, then the recovery id, 0 to 3; 65 bytes from a peer + * are made into one by `recoverable_signature::from_bytes`. + * @param signing_input The signed message, hashed with Keccak-256 inside the call, or + * `crypto::prehashed{digest}`, the 32-byte digest signed (an EIP-191 or EIP-712 digest, a + * transaction's hash). + * @return The key; `invalid_signature` for a recovery id above 3, an r or an s not below the + * group order, or a signature from which no key is recovered. + */ +template , class Signature, class Input> +[[nodiscard]] boost::system::result recover( + [[maybe_unused]] ecdsa_keccak256_recoverable_t signing_scheme, Signature const& signature_value, + Input const& signing_input) noexcept { + detail::timing_guard const timing_scope; + static_assert(webcpp::crypto::detail::secp256k1_refuses_others); + auto const& signature_bytes = + detail::checked_signature_bytes( + signature_value); + detail::check_input(); + if constexpr (detail::input_valid_v) { + return webcpp::crypto::detail::secp256k1_recovered( + signature_bytes, webcpp::crypto::detail::secp256k1_keccak_digest(signing_input)); } else { // Never compiled into a program: check_input stopped the build. return error::invalid_signature; @@ -1454,26 +1608,25 @@ template , class Input> * Encodes a compact ECDSA signature as strict DER (BIP66), with libsecp256k1's own encoder. * * @tparam Backend The backend, `backends::secp256k1`. - * @param compact_signature 64 bytes, r then s. - * @param output_bytes At least `max_der_size` bytes, whatever this signature's length; nothing is + * @param signature_value The signature. + * @param der_output At least `max_der_size` bytes, whatever this signature's length; nothing is * written on an error. * @return The number of bytes written, at most `max_der_size`; `invalid_input_size` when - * `output_bytes` is shorter than `max_der_size`; `invalid_signature` when r or s is zero or not + * `der_output` is shorter than `max_der_size`; `invalid_signature` when r or s is zero or not * below the group order. */ template > [[nodiscard]] boost::system::result to_der( - std::span compact_signature, - std::span output_bytes) noexcept { - detail::timing_guard const timing; + ecdsa_signature const& signature_value, std::span der_output) noexcept { + detail::timing_guard const timing_scope; static_assert(webcpp::crypto::detail::secp256k1_refuses_others); - if (output_bytes.size() < max_der_size) { + if (der_output.size() < max_der_size) { return error::invalid_input_size; } webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); secp256k1_selftest(); secp256k1_ecdsa_signature parsed_value{}; - if (!webcpp::crypto::detail::secp256k1_parse_compact(compact_signature, parsed_value)) { + if (!webcpp::crypto::detail::secp256k1_parse_compact(signature_value.bytes(), parsed_value)) { return error::invalid_signature; } std::array der_signature{}; @@ -1481,7 +1634,7 @@ template > secp256k1_ecdsa_signature_serialize_der(secp256k1_context_static, der_signature.data(), &der_size, &parsed_value); std::ranges::copy(std::span(der_signature).first(der_size), - output_bytes.begin()); + der_output.begin()); return der_size; } @@ -1491,13 +1644,13 @@ template > * * @tparam Backend The backend, `backends::secp256k1`. * @param der_signature The encoding, exactly: nothing may follow it. - * @return 64 bytes, r then s; `invalid_signature` for anything that is not strict DER, and for - * an r or an s that is zero or not below the group order. + * @return The signature, r then s; `invalid_signature` for anything that is not strict DER, and + * for an r or an s that is zero or not below the group order. */ template > -[[nodiscard]] boost::system::result> from_der( +[[nodiscard]] boost::system::result from_der( std::span der_signature) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert(webcpp::crypto::detail::secp256k1_refuses_others); if (der_signature.empty()) { return error::invalid_signature; @@ -1511,7 +1664,7 @@ template > !webcpp::crypto::detail::secp256k1_compact_of(parsed_value, output_bytes)) { return error::invalid_signature; } - return output_bytes; + return webcpp::crypto::detail::signature_access::of(output_bytes); } /** @@ -1522,26 +1675,26 @@ template > * only for signatures from a signer that does not enforce low S. * * @tparam Backend The backend, `backends::secp256k1`. - * @param compact_signature 64 bytes, r then s. - * @return 64 bytes, r then n - s when s was above half the group order; + * @param signature_value The signature. + * @return The signature, r then n - s when s was above half the group order; * `invalid_signature` when r or s is zero or not below the group order. */ template > -[[nodiscard]] boost::system::result> normalize_low_s( - std::span compact_signature) noexcept { - detail::timing_guard const timing; +[[nodiscard]] boost::system::result normalize_low_s( + ecdsa_signature const& signature_value) noexcept { + detail::timing_guard const timing_scope; static_assert(webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); secp256k1_selftest(); secp256k1_ecdsa_signature parsed_value{}; - if (!webcpp::crypto::detail::secp256k1_parse_compact(compact_signature, parsed_value)) { + if (!webcpp::crypto::detail::secp256k1_parse_compact(signature_value.bytes(), parsed_value)) { return error::invalid_signature; } secp256k1_ecdsa_signature_normalize(secp256k1_context_static, &parsed_value, &parsed_value); std::array output_bytes{}; secp256k1_ecdsa_signature_serialize_compact(secp256k1_context_static, output_bytes.data(), &parsed_value); - return output_bytes; + return webcpp::crypto::detail::signature_access::of(output_bytes); } /** @@ -1552,17 +1705,17 @@ template > * It does not verify the signature. * * @tparam Backend The backend, `backends::secp256k1`. - * @param compact_signature 64 bytes, r then s. + * @param signature_value The signature. * @return True exactly when 0 < r < n and 0 < s <= (n - 1) / 2, n the group order. */ template > -[[nodiscard]] bool is_low_s(std::span compact_signature) noexcept { - detail::timing_guard const timing; +[[nodiscard]] bool is_low_s(ecdsa_signature const& signature_value) noexcept { + detail::timing_guard const timing_scope; static_assert(webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); secp256k1_selftest(); secp256k1_ecdsa_signature parsed_value{}; - if (!webcpp::crypto::detail::secp256k1_parse_compact(compact_signature, parsed_value)) { + if (!webcpp::crypto::detail::secp256k1_parse_compact(signature_value.bytes(), parsed_value)) { return false; } // libsecp256k1 returns 1 when s was high, and writes nothing when the output is null. @@ -1587,7 +1740,7 @@ template > [[nodiscard]] boost::system::result tweak_xonly( std::span xonly_key_bytes, std::span tweak_bytes) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert(webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); secp256k1_selftest(); @@ -1622,25 +1775,30 @@ namespace webcpp::crypto { * `curves::secp256k1::normalize_low_s` makes a high one low. * * @tparam Backend The backend, `backends::secp256k1`, the only one; another stops the build. + * @tparam Signature `curves::secp256k1::ecdsa_signature`; another type, a signature of another + * curve or scheme or bytes, stops the build. * @tparam Input A message, bytes that convert to `std::span`, of any size, * empty included, or `crypto::prehashed<32>`; anything else stops the build. * @param signing_scheme `crypto::ecdsa_sha256`. - * @param signature_bytes 64 bytes, r then s, as any bytes; `curves::secp256k1::from_der` reads DER. + * @param signature_value The signature, r then s; bytes from a peer are made into one by + * `curves::secp256k1::ecdsa_signature::from_bytes`, and DER by `curves::secp256k1::from_der`. * @param signing_input The signed message, hashed with SHA-256 inside the call; or * `crypto::prehashed{digest}`, the 32-byte digest signed (a Bitcoin sighash). * @param public_key The signer's public key: a key pair's `public_key()`, or - * `curves::secp256k1::public_key::make` of its SEC1 bytes. - * @return Nothing; `invalid_signature` for a signature of another size, an r or an s not below the - * group order, a high S, or a signature that does not verify. + * `curves::secp256k1::public_key::from_bytes` of its SEC1 bytes. + * @return Nothing; `invalid_signature` for an r or an s not below the group order, a high S, or a + * signature that does not verify. */ -template , class Input> +template , class Signature, class Input> [[nodiscard]] boost::system::result verify( - [[maybe_unused]] ecdsa_sha256_t signing_scheme, std::span signature_bytes, + [[maybe_unused]] ecdsa_sha256_t signing_scheme, Signature const& signature_value, Input const& signing_input, curves::secp256k1::public_key const& public_key) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert(detail::secp256k1_refuses_others); - return detail::secp256k1_verify_ecdsa(signature_bytes, signing_input, - detail::secp256k1_access::point(public_key)); + return detail::secp256k1_verify_ecdsa( + detail::checked_signature_bytes( + signature_value), + signing_input, detail::secp256k1_access::point(public_key)); } /** @@ -1648,28 +1806,30 @@ template , class Input> * its self-test (`include/secp256k1.h:235-247`). * * @tparam Backend The backend, `backends::secp256k1`, the only one; another stops the build. + * @tparam Signature `curves::secp256k1::schnorr_signature`; another type, bytes included, stops + * the build. * @tparam Input A message, bytes that convert to `std::span`, of any size, * empty included; a `crypto::prehashed` marker, or anything else, stops the build. * @param signing_scheme `crypto::schnorr`. - * @param signature_bytes 64 bytes, as any bytes. + * @param signature_value The signature; 64 bytes from a peer are made into one by + * `curves::secp256k1::schnorr_signature::from_bytes`. * @param message_input The signed message, as given. * @param xonly_public_key The signer's 32-byte x-only key (a public key's `xonly()`, a taproot * output key, MuSig2's aggregate key). - * @return Nothing; `invalid_signature` for a signature of another size, checked before the key; - * `invalid_public_key` for 32 bytes that are no point's x; `invalid_signature` for a signature - * that does not verify. + * @return Nothing; `invalid_public_key` for 32 bytes that are no point's x; `invalid_signature` + * for a signature that does not verify. */ -template , class Input> +template , class Signature, class Input> [[nodiscard]] boost::system::result verify( - [[maybe_unused]] schnorr_t signing_scheme, std::span signature_bytes, + [[maybe_unused]] schnorr_t signing_scheme, Signature const& signature_value, Input const& message_input, std::span xonly_public_key) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert(detail::secp256k1_refuses_others); + auto const& signature_bytes = + detail::checked_signature_bytes( + signature_value); detail::check_input(); if constexpr (detail::input_valid_v) { - if (signature_bytes.size() != 64) { - return error::invalid_signature; - } auto const message_bytes = detail::message_bytes(message_input); detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); secp256k1_selftest(); @@ -1678,8 +1838,7 @@ template , class Input> xonly_public_key.data()) == 0) { return error::invalid_public_key; } - return detail::secp256k1_verify_schnorr(signature_bytes.first<64>(), message_bytes, - parsed_key); + return detail::secp256k1_verify_schnorr(signature_bytes, message_bytes, parsed_key); } else { // Never compiled into a program: check_input stopped the build. return error::invalid_signature; @@ -1692,23 +1851,27 @@ template , class Input> * after its self-test. * * @tparam Backend The backend, `backends::secp256k1`, the only one; another stops the build. + * @tparam Signature `curves::secp256k1::schnorr_signature`; another type, bytes included, stops + * the build. * @tparam Input A message, bytes that convert to `std::span`, of any size, * empty included; a `crypto::prehashed` marker, or anything else, stops the build. * @param signing_scheme `crypto::schnorr`. - * @param signature_bytes 64 bytes, as any bytes. + * @param signature_value The signature; 64 bytes from a peer are made into one by + * `curves::secp256k1::schnorr_signature::from_bytes`. * @param message_input The signed message, as given. * @param public_key The signer's public key: a key pair's `public_key()`. - * @return Nothing; `invalid_signature` for a signature of another size, and for one that does not - * verify. + * @return Nothing; `invalid_signature` for a signature that does not verify. */ -template , class Input> +template , class Signature, class Input> [[nodiscard]] boost::system::result verify( - [[maybe_unused]] schnorr_t signing_scheme, std::span signature_bytes, + [[maybe_unused]] schnorr_t signing_scheme, Signature const& signature_value, Input const& message_input, curves::secp256k1::public_key const& public_key) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert(detail::secp256k1_refuses_others); return detail::secp256k1_verify_schnorr_key( - signature_bytes, message_input, detail::secp256k1_access::point(public_key)); + detail::checked_signature_bytes( + signature_value), + message_input, detail::secp256k1_access::point(public_key)); } } // namespace webcpp::crypto @@ -1733,6 +1896,15 @@ template inline constexpr bool signs_with_v, ecdsa_sha256_recoverable_t> = true; +/** + * A secp256k1 key pair signs with Ethereum's recoverable ECDSA over Keccak-256. + * + * @tparam Backend The key pair's backend. + */ +template +inline constexpr bool + signs_with_v, ecdsa_keccak256_recoverable_t> = true; + /** * A secp256k1 key pair signs with BIP340's Schnorr. * @@ -1760,6 +1932,86 @@ template requires std::is_convertible_v> inline constexpr bool verifies_with_v = true; +/** + * A secp256k1 key pair's signature under ECDSA over SHA-256, `curves::secp256k1::ecdsa_signature`. + * + * @tparam Backend The key's backend. + */ +template +struct signature_of, ecdsa_sha256_t> { + /** The signature type. */ + using type = curves::secp256k1::ecdsa_signature; +}; + +/** + * A secp256k1 key pair's signature under ECDSA over SHA-256 with the recovery id, + * `curves::secp256k1::recoverable_signature`. + * + * @tparam Backend The key's backend. + */ +template +struct signature_of, ecdsa_sha256_recoverable_t> { + /** The signature type. */ + using type = curves::secp256k1::recoverable_signature; +}; + +/** + * A secp256k1 key pair's signature under Ethereum's recoverable ECDSA over Keccak-256, + * `curves::secp256k1::recoverable_signature`, the type `ecdsa_sha256_recoverable` gives (design + * R20): the bytes are the same, and the scheme is the input's hash. + * + * @tparam Backend The key's backend. + */ +template +struct signature_of, ecdsa_keccak256_recoverable_t> { + /** The signature type. */ + using type = curves::secp256k1::recoverable_signature; +}; + +/** + * A secp256k1 key pair's signature under BIP340's Schnorr, `curves::secp256k1::schnorr_signature`. + * + * @tparam Backend The key's backend. + */ +template +struct signature_of, schnorr_t> { + /** The signature type. */ + using type = curves::secp256k1::schnorr_signature; +}; + +/** + * A secp256k1 public key's signature under ECDSA over SHA-256, + * `curves::secp256k1::ecdsa_signature`. + */ +template <> +struct signature_of { + /** The signature type. */ + using type = curves::secp256k1::ecdsa_signature; +}; + +/** + * A secp256k1 public key's signature under BIP340's Schnorr, + * `curves::secp256k1::schnorr_signature`. + */ +template <> +struct signature_of { + /** The signature type. */ + using type = curves::secp256k1::schnorr_signature; +}; + +/** + * The signature of a BIP340 x-only key, its 32 bytes, under `schnorr`, + * `curves::secp256k1::schnorr_signature`. + * + * @tparam Key The public key's type. + */ +template + requires std::is_convertible_v> +struct signature_of { + /** The signature type. */ + using type = curves::secp256k1::schnorr_signature; +}; + /** * A secp256k1 key pair's backend. * @@ -1804,10 +2056,19 @@ inline constexpr bool has_verifier_v = true; } // namespace webcpp::crypto::detail -// The key pair contract (design D8), on the family's one backend, which this header includes. +// The key pair concepts (design D4), on the family's one backend, which this header includes: it +// signs and agrees. static_assert( ::webcpp::crypto::keypair< ::webcpp::crypto::curves::secp256k1::basic_keypair<::webcpp::crypto::backends::secp256k1>>, "webcpp::crypto: secp256k1's key pair meets crypto::keypair."); +static_assert( + ::webcpp::crypto::signing_keypair< + ::webcpp::crypto::curves::secp256k1::basic_keypair<::webcpp::crypto::backends::secp256k1>>, + "webcpp::crypto: secp256k1's key pair meets crypto::signing_keypair."); +static_assert( + ::webcpp::crypto::agreement_keypair< + ::webcpp::crypto::curves::secp256k1::basic_keypair<::webcpp::crypto::backends::secp256k1>>, + "webcpp::crypto: secp256k1's key pair meets crypto::agreement_keypair."); #endif // WEBCPP_CRYPTO_CURVES_SECP256K1_HPP diff --git a/include/webcpp/crypto/curves/secp256k1/ellswift.hpp b/include/webcpp/crypto/curves/secp256k1/ellswift.hpp index d4b67e58..097d4294 100644 --- a/include/webcpp/crypto/curves/secp256k1/ellswift.hpp +++ b/include/webcpp/crypto/curves/secp256k1/ellswift.hpp @@ -74,7 +74,7 @@ enum class ellswift_party { template > [[nodiscard]] std::array ellswift_encode( public_key const& parsed_key, std::span randomness_bytes) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); @@ -97,7 +97,7 @@ template > template > [[nodiscard]] public_key ellswift_decode( std::span encoded_key) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); @@ -124,7 +124,7 @@ template [[nodiscard]] boost::system::result> ellswift_create( basic_keypair const& key_pair, std::span randomness_bytes) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); @@ -166,7 +166,7 @@ template std::span initiator_encoding, std::span responder_encoding, ellswift_party our_party) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); diff --git a/include/webcpp/crypto/curves/secp256k1/formats.hpp b/include/webcpp/crypto/curves/secp256k1/formats.hpp index 747f66fd..0ea3f7e1 100644 --- a/include/webcpp/crypto/curves/secp256k1/formats.hpp +++ b/include/webcpp/crypto/curves/secp256k1/formats.hpp @@ -18,13 +18,13 @@ #include #include +#include #include #include #include #include #include #include -#include #include #include @@ -98,7 +98,7 @@ template > [[nodiscard]] boost::system::result encode_spki( public_key const& parsed_key, std::span output_bytes, point_form encoded_form = point_form::compressed) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert(webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); if (output_bytes.size() < max_spki_size) { @@ -133,7 +133,7 @@ template > template > [[nodiscard]] boost::system::result decode_spki( std::span spki_bytes) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert(webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); secp256k1_selftest(); @@ -145,7 +145,7 @@ template > webcpp::crypto::detail::secp256k1_spki_uncompressed_prefix); if ((spki_bytes.size() != spki_compressed_size && spki_bytes.size() != spki_uncompressed_size) || - !equal(spki_bytes.first(expected_prefix.size()), expected_prefix)) { + !constant_time_equal(spki_bytes.first(expected_prefix.size()), expected_prefix)) { return error::invalid_encoding; } using access = webcpp::crypto::detail::secp256k1_access; @@ -171,7 +171,7 @@ template > template > [[nodiscard]] boost::system::result encode_pkcs8( basic_keypair const& key_pair, std::span output_bytes) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert(webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); using access = webcpp::crypto::detail::secp256k1_access; @@ -202,32 +202,33 @@ template > /** * The key pair of a PKCS#8 that is exactly what `encode_pkcs8` writes for its secret, made as - * `basic_keypair::make` makes it. + * `basic_keypair::from_secret` makes it. * * @tparam Backend The backend, `backends::secp256k1`. * @param pkcs8_bytes The PKCS#8, exactly: nothing may follow it. - * @param memory_resource The resource of the key pair's signing context, as `make` takes it. + * @param memory_resource The resource of the key pair's signing context, as `from_secret` takes it. * @return The key pair; `invalid_encoding` for any other bytes, a secret zero or not below the * group order and a public key not the secret's included; `entropy_unavailable` and - * `backend_failure` as `make` reports them. + * `backend_failure` as `from_secret` reports them. */ template > [[nodiscard]] boost::system::result> decode_pkcs8( std::span pkcs8_bytes, std::pmr::memory_resource* memory_resource = std::pmr::get_default_resource()) { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert(webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); secp256k1_selftest(); constexpr std::size_t prefix_size = webcpp::crypto::detail::secp256k1_pkcs8_prefix.size(); if (pkcs8_bytes.size() != max_pkcs8_size || - !equal(pkcs8_bytes.first(prefix_size), webcpp::crypto::detail::secp256k1_pkcs8_prefix)) { + !constant_time_equal(pkcs8_bytes.first(prefix_size), + webcpp::crypto::detail::secp256k1_pkcs8_prefix)) { return error::invalid_encoding; } webcpp::crypto::detail::secp256k1_secret secret_bytes; std::ranges::copy(pkcs8_bytes.subspan(prefix_size, secret_bytes.bytes.size()), secret_bytes.bytes.begin()); - auto made_pair = basic_keypair::make(secret_bytes.bytes, memory_resource); + auto made_pair = basic_keypair::from_secret(secret_bytes.bytes, memory_resource); if (!made_pair) { if (made_pair.error() == error::invalid_secret_key) { return error::invalid_encoding; @@ -240,8 +241,8 @@ template > // Not const: the branch reads it again after the mark (detail/declassify.hpp's tip); the // comparison runs on the secret's bytes, and its verdict is public. // NOLINTNEXTLINE(misc-const-correctness): see above - bool is_same = - encode_pkcs8(*made_pair, encoded_again).has_value() && equal(encoded_again, pkcs8_bytes); + bool is_same = encode_pkcs8(*made_pair, encoded_again).has_value() && + constant_time_equal(encoded_again, pkcs8_bytes); WEBCPP_CRYPTO_DETAIL_DECLASSIFY(&is_same, sizeof is_same); webcpp::crypto::detail::wipe(encoded_again.data(), encoded_again.size()); if (!is_same) { diff --git a/include/webcpp/crypto/curves/secp256k1/musig.hpp b/include/webcpp/crypto/curves/secp256k1/musig.hpp index 5e1d9d1e..c7224ea2 100644 --- a/include/webcpp/crypto/curves/secp256k1/musig.hpp +++ b/include/webcpp/crypto/curves/secp256k1/musig.hpp @@ -20,6 +20,7 @@ #include #include #include +#include #include #include #include @@ -45,7 +46,7 @@ struct secp256k1_nonce_state { secp256k1_musig_secnonce nonce_value{}; /** The signer's public key, SEC1 compressed, public. */ std::array signer_key{}; - /** True from `nonce_gen` until a partial signature, a move or the destructor uses it. */ + /** True from `generate_nonce` until a partial signature, a move or the destructor uses it. */ bool fresh = false; }; @@ -86,7 +87,7 @@ class aggregate_key { * @return 32 bytes, the tweaks included. */ [[nodiscard]] std::array xonly_public_key() const noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); secp256k1_selftest(); public_key full_key = full_public_key(); @@ -107,7 +108,7 @@ class aggregate_key { * @return The key, the tweaks included. */ [[nodiscard]] public_key full_public_key() const noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); secp256k1_selftest(); using access = webcpp::crypto::detail::secp256k1_access; @@ -130,7 +131,7 @@ class aggregate_key { */ [[nodiscard]] boost::system::result tweak_add( std::span tweak_bytes) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; return tweaked(tweak_bytes, secp256k1_musig_pubkey_ec_tweak_add); } @@ -144,7 +145,7 @@ class aggregate_key { */ [[nodiscard]] boost::system::result tweak_xonly_add( std::span tweak_bytes) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; return tweaked(tweak_bytes, secp256k1_musig_pubkey_xonly_tweak_add); } @@ -178,7 +179,7 @@ class aggregate_key { /** * A signer's public nonce, parsed (libsecp256k1's pubnonce): public, copied freely, made only - * by `nonce_gen` and `parse_public_nonce`. + * by `generate_nonce` and `parse_public_nonce`. */ class public_nonce { private: @@ -229,7 +230,7 @@ class partial_signature { }; /** - * A signer's secret nonce: move-only, wiped on move and destruction, made only by `nonce_gen`. + * A signer's secret nonce: move-only, wiped on move and destruction, made only by `generate_nonce`. * * It is consumed by `partial_sign`, which takes it by value, so that a nonce cannot be passed to a * second signature without an explicit `std::move` of an object already moved from (which @@ -280,7 +281,7 @@ class secret_nonce { webcpp::crypto::detail::secp256k1_nonce_state native_value_{}; }; -/** What `nonce_gen` returns: the secret nonce to keep, the public nonce to send. */ +/** What `generate_nonce` returns: the secret nonce to keep, the public nonce to send. */ struct nonce_pair { /** The secret nonce, which this signer's `partial_sign` consumes. */ secret_nonce secret_part; @@ -315,7 +316,7 @@ struct nonce_pair { template > [[nodiscard]] boost::system::result key_aggregate( std::span signer_keys, workspace pointer_space) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); @@ -360,11 +361,11 @@ template > * extra input that is neither empty nor 32 bytes; `entropy_unavailable`; `backend_failure`. */ template -[[nodiscard]] boost::system::result nonce_gen( +[[nodiscard]] boost::system::result generate_nonce( basic_keypair const& signer_pair, aggregate_key const& signers_key, std::span message_hash = {}, std::span extra_input = {}) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); @@ -420,7 +421,7 @@ template template > [[nodiscard]] boost::system::result nonce_aggregate( std::span signer_nonces, workspace pointer_space) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); @@ -462,7 +463,7 @@ template > [[nodiscard]] boost::system::result nonce_process( aggregate_nonce const& nonce_sum, std::span message_bytes, aggregate_key const& signers_key) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); @@ -483,7 +484,7 @@ template > * * @tparam Backend The key pair's backend, `backends::secp256k1`. * @param signer_pair The signer's key pair. - * @param signer_nonce The nonce `nonce_gen` made for this key pair, moved in. + * @param signer_nonce The nonce `generate_nonce` made for this key pair, moved in. * @param signers_key The aggregate key, with its tweaks. * @param signing_session The session of the message. * @return The partial signature; `invalid_state` for a moved-from key pair or nonce, a nonce @@ -493,7 +494,7 @@ template [[nodiscard]] boost::system::result partial_sign( basic_keypair const& signer_pair, secret_nonce signer_nonce, aggregate_key const& signers_key, session const& signing_session) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); @@ -541,7 +542,7 @@ template > partial_signature const& signature_part, public_nonce const& signer_nonce, public_key const& signer_key, aggregate_key const& signers_key, session const& signing_session) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); @@ -566,14 +567,14 @@ template > * @param signature_parts Every signer's partial signature, at least one. * @param pointer_space At least `workspace_size(signature_parts.size())` bytes; zero when the * function returns, whatever it returns. - * @return 64 bytes; `invalid_input_size` for no partial signatures or a short workspace; - * `backend_failure`. + * @return The BIP 340 signature, a `curves::secp256k1::schnorr_signature`; `invalid_input_size` + * for no partial signatures or a short workspace; `backend_failure`. */ template > -[[nodiscard]] boost::system::result> partial_signature_aggregate( +[[nodiscard]] boost::system::result partial_signature_aggregate( session const& signing_session, std::span signature_parts, workspace pointer_space) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); @@ -599,7 +600,7 @@ template > signature_parts.size()) == 0) { return error::backend_failure; } - return output_bytes; + return webcpp::crypto::detail::signature_access::of(output_bytes); } /** @@ -613,7 +614,7 @@ template > template > [[nodiscard]] boost::system::result parse_public_nonce( std::span encoded_nonce) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); @@ -640,7 +641,7 @@ template > template > [[nodiscard]] std::array serialize_public_nonce( public_nonce const& parsed_nonce) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); @@ -665,7 +666,7 @@ template > template > [[nodiscard]] boost::system::result parse_aggregate_nonce( std::span encoded_nonce) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); @@ -692,7 +693,7 @@ template > template > [[nodiscard]] std::array serialize_aggregate_nonce( aggregate_nonce const& parsed_nonce) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); @@ -716,7 +717,7 @@ template > template > [[nodiscard]] boost::system::result parse_partial_signature( std::span encoded_signature) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); @@ -744,7 +745,7 @@ template > template > [[nodiscard]] std::array serialize_partial_signature( partial_signature const& parsed_signature) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); diff --git a/include/webcpp/crypto/curves/secp256k1/silent_payments.hpp b/include/webcpp/crypto/curves/secp256k1/silent_payments.hpp index 2204cc48..6cf5b510 100644 --- a/include/webcpp/crypto/curves/secp256k1/silent_payments.hpp +++ b/include/webcpp/crypto/curves/secp256k1/silent_payments.hpp @@ -128,7 +128,7 @@ struct label { /** * An output the recipient found: its x-only key, the tweak that spends it (added to the - * spend secret key with `seckey_tweak_add`), and the label it was sent to, if any. + * spend secret key with `secret_key_tweak_add`), and the label it was sent to, if any. */ struct found_output { /** The output's x-only key. */ @@ -140,15 +140,15 @@ struct found_output { }; /** - * The prevouts' summary a recipient scans with: the sum of the eligible inputs' public keys and - * the input hash (libsecp256k1's prevouts_summary, 101 bytes), public, copied freely, made only by - * `make_prevouts_summary`. + * The previous outputs' summary a recipient scans with: the sum of the eligible inputs' public + * keys and the input hash (libsecp256k1's `secp256k1_silentpayments_prevouts_summary`, 101 + * bytes), public, copied freely, made only by `make_previous_outputs_summary`. */ -class prevouts_summary { +class previous_outputs_summary { private: friend struct webcpp::crypto::detail::secp256k1_access; - prevouts_summary() noexcept = default; + previous_outputs_summary() noexcept = default; secp256k1_silentpayments_prevouts_summary native_value_{}; }; @@ -205,7 +205,7 @@ struct no_labels { } /** - * The workspace `make_prevouts_summary` needs, in bytes. + * The workspace `make_previous_outputs_summary` needs, in bytes. * * @param taproot_input_count The number of Taproot inputs' x-only keys. * @param plain_input_count The number of other eligible inputs' keys. @@ -302,7 +302,7 @@ template std::span> const* const> taproot_inputs, std::span> const* const> plain_inputs, std::span> output_keys, workspace pointer_space) noexcept { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); @@ -396,7 +396,7 @@ template template [[nodiscard]] boost::system::result(bytes)` and - `crypto::generate()`. + Beside them, the free synchronous forms of the key pairs' `sign` and `agree` (design D9), + `crypto::sign(key_pair, scheme, input)`, constrained by `signing_keypair`, and + `crypto::agree(key_pair, peer)`, constrained by `agreement_keypair`; and, through `factories.hpp`, + which it includes, `crypto::from_secret(bytes)`, `crypto::from_bytes(bytes)`, + `crypto::from_key(key)` and `crypto::generate()`. @see "Signatures: the scheme and the input", in the guide. */ @@ -25,34 +30,91 @@ #include +#include #include -#include +#include #include #include #include #include +#include #include #include #include namespace webcpp::crypto { +/** + * Whether `Keypair` is a key pair (design D4), what every curve's key pair is, whatever it does: + * - `Keypair::from_secret(secret_bytes)` and `Keypair::generate()` give `result`; + * - `key.public_key()` gives `result`, the curve's typed public + * key; + * - `key.secret()` gives `result>`, the bytes `from_secret` + * takes back. + * + * What it does is the refinements': `signing_keypair` signs, `agreement_keypair` agrees. + * + * @tparam Keypair A type, without its reference and qualifiers. + */ +template +concept keypair = requires { + typename Keypair::public_key_type; + { + Keypair::from_secret(std::declval&>()) + } -> std::same_as>; + { Keypair::generate() } -> std::same_as>; + { + std::declval().public_key() + } -> std::same_as>; + { + std::declval().secret() + } -> std::same_as>>; +}; + namespace detail { +/** + * The input `signing_keypair` signs under `Scheme`: a message, as + * `std::span`, for a scheme that takes one. + * + * @tparam Scheme A scheme tag. + */ +template > +struct contract_input { + /** A message. */ + using type = std::span; +}; + +/** + * The input `signing_keypair` signs under a scheme that takes its digest alone, + * `eddsa_prehashed`: the marker of the scheme's digest size. + * + * @tparam Scheme A scheme tag. + */ +template +struct contract_input { + /** The marker of a digest of the scheme's size. */ + using type = prehashed::digest_size>; +}; + /** * Whether the key pair `Keypair` keeps its curve's word about `Scheme`: a scheme the curve does * not declare for it asks nothing; one it declares (`signs_with_v`) asks that - * `key.sign(scheme, message)` be a valid call. + * `key.sign(scheme, input)` be a valid call giving `result>`, the + * scheme's signature type for the key pair's curve, the input a message, or for a scheme that + * takes its digest alone (`eddsa_prehashed`) the marker of one (`contract_input`). * * @tparam Keypair A key pair's type. * @tparam Scheme A scheme tag. */ template concept signs_as_declared = !signs_with_v || requires { - std::declval().sign(std::declval(), - std::declval&>()); + { + std::declval().sign(std::declval(), + std::declval::type&>()) + } -> std::same_as>>; }; /** @@ -96,69 +158,190 @@ inline constexpr bool signs_every_declared_v> = (signs_as_declared && ...); /** - * The key pair contract over the schemes of `List`: `crypto::keypair` is this concept over + * A signing key pair over the schemes of `List`: `crypto::signing_keypair` is this concept over * `all_schemes`, and a test passes a list with a scheme of its own. * * @tparam Keypair A type, without its reference and qualifiers. * @tparam List A `scheme_list`. */ template -concept keypair_over = signs_some_scheme_v && requires { - typename Keypair::public_key_type; - { - Keypair::make(std::declval&>()) - } -> std::same_as>; - { Keypair::generate() } -> std::same_as>; - { - std::declval().public_key() - } -> std::same_as>; - { - std::declval().secret() - } -> std::same_as>>; -} && signs_every_declared_v; +concept signing_keypair_over = + keypair && signs_some_scheme_v && signs_every_declared_v; + +/** + * Whether `Type` is the result of an agreement, `result>`: false for any other type. + * + * @tparam Type Any type. + */ +template +inline constexpr bool is_secret_result_v = false; + +/** + * Whether `result>` is the result of an agreement: it is. + * + * @tparam N The shared secret's size in bytes. + */ +template +inline constexpr bool is_secret_result_v>> = true; + +/** + * Whether `key.sign(scheme, input, extra...)` names a member `sign` of `Keypair` that takes these + * arguments: the key pair's own signing function, which `crypto::sign` calls. + * + * @tparam Keypair A key pair's type, or any type. + * @tparam Scheme A scheme tag, or any type. + * @tparam Input The input's type. + * @tparam Extra The types of the arguments after the input, secp256k1's 32 bytes. + */ +template +concept has_sign_member = requires { + std::declval().sign(std::declval(), std::declval(), + std::declval()...); +}; + +/** + * Whether `key.agree(peer)` names a member `agree` of `Keypair` that takes this peer: the key + * pair's own agreement, which `crypto::agree` calls. + * + * @tparam Keypair A key pair's type, or any type. + * @tparam PublicKey The peer's type. + */ +template +concept has_agree_member = + requires { std::declval().agree(std::declval()); }; } // namespace detail /** - * Whether `Keypair` is a key pair of the library's contract (design D8): - * - `Keypair::make(secret_bytes)` and `Keypair::generate()` give `result`; - * - `key.public_key()` gives `result`, the curve's typed - * public key, which `crypto::verify` takes; - * - `key.secret()` gives `result>`, the bytes `make` takes back; - * - `key.sign(scheme, message)` is valid for every scheme its curve declares for it - * (`detail::signs_with_v`), and it declares at least one; the schemes asked are the library's - * one list of them, `detail::all_schemes`, which the concept folds over - * (`detail::keypair_over`). + * Whether `Keypair` is a key pair that signs (design D4): a `keypair` whose + * `key.sign(scheme, input)` is valid for every scheme its curve declares for it + * (`detail::signs_with_v`), and it declares at least one, each giving `result` of the scheme's + * signature type for its curve (`detail::signature_of_t`); the input a message, or the marker of + * a digest for a scheme that takes its digest alone (`crypto::eddsa_prehashed`). + * + * The schemes asked are the library's one list of them, `detail::all_schemes`, which the concept + * folds over (`detail::signing_keypair_over`). + * + * Ed25519's, P-256's and secp256k1's key pairs are; X25519's is not: it agrees. * * @tparam Keypair A type, without its reference and qualifiers. */ template -concept keypair = detail::keypair_over; +concept signing_keypair = detail::signing_keypair_over; + +/** + * Whether `Keypair` is a key pair that agrees (design D4): a `keypair` whose `key.agree(peer)`, + * `peer` its own `typename Keypair::public_key_type`, gives `result>`, the shared secret. + * + * X25519's, P-256's and secp256k1's key pairs are; Ed25519's is not: it signs, and `to_x25519()` + * converts it to an X25519 key pair, which agrees. + * + * @tparam Keypair A type, without its reference and qualifiers. + */ +template +concept agreement_keypair = keypair && requires { + requires detail::is_secret_result_v().agree( + std::declval()))>; +}; + +/** + * Signs with a key pair, `key_pair.sign(signing_scheme, signing_input, extra_arguments...)`: the + * free form of the key pair's own `sign`, which it calls, with its results, its errors and its + * refusals. + * + * A scheme the key pair does not have, or an input the scheme does not take, stops the build with + * the key pair's own message. + * + * @tparam Keypair A `signing_keypair` whose `sign` takes these arguments: Ed25519's, P-256's or + * secp256k1's. + * @tparam Scheme A scheme tag. + * @tparam Input A message, bytes that convert to `std::span`, or + * `crypto::prehashed`. + * @tparam Extra Nothing, or secp256k1's 32 bytes: the hedged ECDSA's extra entropy or BIP340's + * auxiliary randomness. + * @param key_pair The key pair. + * @param signing_scheme The scheme. + * @param signing_input The message or the marker. + * @param extra_arguments Nothing, or secp256k1's 32 bytes. + * @return What `key_pair.sign(signing_scheme, signing_input, extra_arguments...)` returns: the + * signature, or its error. + */ +template + requires(signing_keypair && detail::has_sign_member) +[[nodiscard]] auto sign( + Keypair const& key_pair, Scheme signing_scheme, Input const& signing_input, + Extra const&... extra_arguments) noexcept(noexcept(key_pair.sign(signing_scheme, signing_input, + extra_arguments...))) + -> decltype(key_pair.sign(signing_scheme, signing_input, extra_arguments...)) { + detail::timing_guard const timing_scope; + return key_pair.sign(signing_scheme, signing_input, extra_arguments...); +} + +/** + * Stops the build: the first argument is not a signing key pair whose `sign` takes these + * arguments: an X25519 key pair, which agrees and does not sign, a public key, or a key pair given + * arguments its `sign` does not take. + * + * @tparam Keypair The first argument's type. + * @tparam Scheme A scheme tag. + * @tparam Input The input's type. + * @tparam Extra The types of the arguments after the input. + * @param key_pair The first argument. + * @param signing_scheme The scheme. + * @param signing_input The input. + * @param extra_arguments The arguments after the input. + * @return Never: the call does not compile. + */ +template + requires(detail::is_scheme_v && + !(signing_keypair && + detail::has_sign_member)) +[[nodiscard]] boost::system::result sign( + [[maybe_unused]] Keypair const& key_pair, [[maybe_unused]] Scheme signing_scheme, + [[maybe_unused]] Input const& signing_input, + [[maybe_unused]] Extra const&... extra_arguments) noexcept { + if constexpr (agreement_keypair && !signing_keypair) { + static_assert(detail::refused_v, + "webcpp::crypto: sign: X25519 key pairs agree; they do not sign: sign with " + "an Ed25519 key pair, which to_x25519() converts for agreement."); + } else { + static_assert( + detail::refused_v, + "webcpp::crypto: sign: the first argument is a key pair, and the others are " + "its sign's: crypto::sign(key_pair, scheme, input), and on secp256k1 its 32 " + "bytes of extra entropy or auxiliary randomness after the input; a public key " + "verifies, with crypto::verify."); + } + return {}; +} /** * Agrees a secret with a peer's public key, `key_pair.agree(peer_key)`: the free form of the key * pair's own `agree`, which it calls, with its results and its errors. * - * @tparam Keypair A key pair's type whose `agree` takes `peer_key`: P-256's or secp256k1's. + * @tparam Keypair An `agreement_keypair` whose `agree` takes `peer_key`: X25519's, P-256's or + * secp256k1's. * @tparam PublicKey The peer's public key's type, the key pair's own `public_key_type`. * @param key_pair The key pair. * @param peer_key The peer's public key. - * @return What `key_pair.agree(peer_key)` returns: the shared point's x coordinate, or its error. + * @return What `key_pair.agree(peer_key)` returns: the shared secret (X25519's, or the shared + * point's x coordinate), or its error. */ template - requires requires { std::declval().agree(std::declval()); } + requires(agreement_keypair && detail::has_agree_member) [[nodiscard]] auto agree(Keypair const& key_pair, PublicKey const& peer_key) noexcept(noexcept(key_pair.agree(peer_key))) -> decltype(key_pair.agree(peer_key)) { - detail::timing_guard const timing; + detail::timing_guard const timing_scope; return key_pair.agree(peer_key); } /** - * Stops the build: the key pair has no `agree` that takes this peer, a key pair of a curve without - * an agreement, or a peer of another curve, another backend, or bytes. + * Stops the build: the key pair is not an agreement key pair whose `agree` takes this peer: an + * Ed25519 key pair, which signs and does not agree, or a peer of another curve, another backend, + * or bytes, each with its own message. * - * @tparam Keypair The key pair's type, a key pair of the contract. + * @tparam Keypair The key pair's type, a `keypair`. * @tparam PublicKey The peer's type. * @param key_pair The key pair. * @param peer_key The peer. @@ -166,14 +349,20 @@ template */ template requires(keypair && - !requires { std::declval().agree(std::declval()); }) + !(agreement_keypair && detail::has_agree_member)) [[nodiscard]] boost::system::result agree( [[maybe_unused]] Keypair const& key_pair, [[maybe_unused]] PublicKey const& peer_key) noexcept { - static_assert(detail::refused_v, - "webcpp::crypto: agree: this key pair does not agree with this peer: a P-256 " - "key pair agrees with a curves::p256::basic_public_key of its backend, a " - "secp256k1 key pair with a curves::secp256k1::public_key; an Ed25519 key pair " - "agrees through X25519, its x25519_secret() and curves::x25519::agree."); + if constexpr (signing_keypair && !agreement_keypair) { + static_assert(detail::refused_v, + "webcpp::crypto: agree: Ed25519 key pairs sign; they do not agree: convert " + "one with to_x25519() and agree with the X25519 key pair."); + } else { + static_assert(detail::refused_v, + "webcpp::crypto: agree: this key pair does not agree with this peer: an " + "X25519 key pair agrees with a curves::x25519::public_key, a P-256 key pair " + "with a curves::p256::basic_public_key of its backend, a secp256k1 key pair " + "with a curves::secp256k1::public_key."); + } return {}; } diff --git a/include/webcpp/crypto/make.hpp b/include/webcpp/crypto/make.hpp deleted file mode 100644 index a6ec0ece..00000000 --- a/include/webcpp/crypto/make.hpp +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright (c) 2026 WebCpp.org -// -// Distributed under the Boost Software License, Version 1.0. (See -// accompanying file LICENSE_1_0.txt or copy at -// https://www.boost.org/LICENSE_1_0.txt) - -/** - The free synchronous forms of the static members that make an object (design D9, R23): - `crypto::make(bytes)`, which serves key pairs, public keys, AES-GCM and every AEAD, and - `crypto::generate()`, each calling the member it is named after. - - It depends on nothing but the configuration and the timing guard, so that `keypair.hpp` and the - AEAD headers include it without bringing in what the other needs. - - @see "Signatures: the scheme and the input", in the guide. -*/ -#ifndef WEBCPP_CRYPTO_MAKE_HPP -#define WEBCPP_CRYPTO_MAKE_HPP - -#include - -#include - -#include - -namespace webcpp::crypto { - -/** - * Makes an object from its key bytes, `Algorithm::make(forwarded_arguments...)`: the free form of - * the algorithm's own `make`, which it calls, with its results and its errors. - * - * @tparam Algorithm A type whose static `make` takes these arguments: a key pair, a public key, - * AES-GCM or another AEAD. - * @tparam Arguments The types of `make`'s arguments. - * @param forwarded_arguments `make`'s arguments: the key bytes, and secp256k1's memory resource. - * @return What `Algorithm::make(forwarded_arguments...)` returns: the object, or its error. - */ -template - requires requires { Algorithm::make(std::declval()...); } -[[nodiscard]] auto make(Arguments&&... forwarded_arguments) noexcept( - noexcept(Algorithm::make(std::forward(forwarded_arguments)...))) - -> decltype(Algorithm::make(std::forward(forwarded_arguments)...)) { - detail::timing_guard const timing; - return Algorithm::make(std::forward(forwarded_arguments)...); -} - -/** - * Makes a key pair from a fresh secret drawn from the system's generator, - * `Keypair::generate(forwarded_arguments...)`: the free form of the key pair's own `generate`, - * which it calls, with its results and its errors. - * - * @tparam Keypair A type whose static `generate` takes these arguments: a key pair. - * @tparam Arguments The types of `generate`'s arguments: none, or secp256k1's memory resource. - * @param forwarded_arguments `generate`'s arguments. - * @return What `Keypair::generate(forwarded_arguments...)` returns: the key pair, or its error. - */ -template - requires requires { Keypair::generate(std::declval()...); } -[[nodiscard]] auto generate(Arguments&&... forwarded_arguments) noexcept( - noexcept(Keypair::generate(std::forward(forwarded_arguments)...))) - -> decltype(Keypair::generate(std::forward(forwarded_arguments)...)) { - detail::timing_guard const timing; - return Keypair::generate(std::forward(forwarded_arguments)...); -} - -} // namespace webcpp::crypto - -#endif // WEBCPP_CRYPTO_MAKE_HPP diff --git a/include/webcpp/crypto/pem.hpp b/include/webcpp/crypto/pem.hpp index 1f529283..8f2ea39e 100644 --- a/include/webcpp/crypto/pem.hpp +++ b/include/webcpp/crypto/pem.hpp @@ -13,6 +13,10 @@ is included when the program links it; a program that uses the family without linking it stops where it calls it, with the Jamfile line that links it. + 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 "Key formats: SPKI, PKCS#8 and PEM", in the guide. */ #ifndef WEBCPP_CRYPTO_PEM_HPP @@ -20,12 +24,12 @@ #include +#include #include #include #include #include #include -#include #include #include @@ -63,19 +67,24 @@ inline constexpr std::size_t pem_line_characters = 64; * Whether a label is one RFC 7468 allows and that is not empty: printable ASCII characters, with * single spaces or hyphens between them, as in `PUBLIC KEY`. */ -[[nodiscard]] constexpr bool pem_label_allowed(std::string_view label) noexcept { - auto const separator = [](char c) { return c == ' ' || c == '-'; }; - auto const printable = [](char c) { return c >= '!' && c <= '~'; }; - if (label.empty() || separator(label.front()) || separator(label.back())) { +[[nodiscard]] constexpr bool pem_label_allowed(std::string_view pem_label) noexcept { + auto const separator_test = [](char pem_character) { + return pem_character == ' ' || pem_character == '-'; + }; + auto const printable_test = [](char pem_character) { + return pem_character >= '!' && pem_character <= '~'; + }; + if (pem_label.empty() || separator_test(pem_label.front()) || + separator_test(pem_label.back())) { return false; } - for (std::size_t at = 0; at < label.size(); ++at) { - char const c = label[at]; - if (separator(c)) { - if (separator(label[at - 1])) { + for (std::size_t character_index = 0; character_index < pem_label.size(); ++character_index) { + char const pem_character = pem_label[character_index]; + if (separator_test(pem_character)) { + if (separator_test(pem_label[character_index - 1])) { return false; } - } else if (!printable(c)) { + } else if (!printable_test(pem_character)) { return false; } } @@ -83,20 +92,22 @@ inline constexpr std::size_t pem_line_characters = 64; } /** - * The characters of text from `at`, at most `count` of them, none past its end: a - * `std::string_view::substr` that never throws. + * The characters of `pem_text` from `character_index`, at most `character_count` of them, none past + * its end: a `std::string_view::substr` that never throws. */ -[[nodiscard]] constexpr std::string_view pem_part(std::string_view text, std::size_t at, - std::size_t count) noexcept { - if (at > text.size()) { +[[nodiscard]] constexpr std::string_view pem_part(std::string_view pem_text, + std::size_t character_index, + std::size_t character_count) noexcept { + if (character_index > pem_text.size()) { return {}; } - return {text.data() + at, (std::min)(count, text.size() - at)}; + return {pem_text.data() + character_index, + (std::min)(character_count, pem_text.size() - character_index)}; } /** * Whether two lines of base64 are the same, in a time that does not depend on their characters, - * which encode a private key's bytes in PEM of a PKCS#8: through `equal`. + * which encode a private key's bytes in PEM of a PKCS#8: through `constant_time_equal`. */ [[nodiscard]] inline bool pem_same_line(std::span first_line, std::span second_line) noexcept { @@ -105,14 +116,16 @@ inline constexpr std::size_t pem_line_characters = 64; } std::array first_bytes{}; std::array second_bytes{}; - std::ranges::transform(first_line, first_bytes.begin(), - [](char c) { return static_cast(c); }); - std::ranges::transform(second_line, second_bytes.begin(), - [](char c) { return static_cast(c); }); - bool const same = equal(first_bytes, second_bytes); + std::ranges::transform(first_line, first_bytes.begin(), [](char pem_character) { + return static_cast(pem_character); + }); + std::ranges::transform(second_line, second_bytes.begin(), [](char pem_character) { + return static_cast(pem_character); + }); + bool const bytes_equal = constant_time_equal(first_bytes, second_bytes); wipe_object(first_bytes); wipe_object(second_bytes); - return same; + return bytes_equal; } } // namespace webcpp::crypto::detail @@ -134,11 +147,11 @@ inline constexpr std::string_view private_key_label = "PRIVATE KEY"; */ [[nodiscard]] constexpr std::size_t armoured_size(std::size_t label_size, std::size_t der_size) noexcept { - std::size_t const characters = ((der_size + 2) / 3) * 4; - std::size_t const lines = - (characters + detail::pem_line_characters - 1) / detail::pem_line_characters; - return detail::pem_begin.size() + label_size + detail::pem_close.size() + characters + lines + - detail::pem_end.size() + label_size + detail::pem_close.size(); + std::size_t const character_count = ((der_size + 2) / 3) * 4; + std::size_t const line_count = + (character_count + detail::pem_line_characters - 1) / detail::pem_line_characters; + return detail::pem_begin.size() + label_size + detail::pem_close.size() + character_count + + line_count + detail::pem_end.size() + label_size + detail::pem_close.size(); } /** @@ -159,49 +172,53 @@ struct algorithm { * Writes DER as PEM under a label: `-----BEGIN ::make(key); - auto b = ciphers::chacha20_poly1305::make(key); + auto a = ciphers::chacha20_poly1305::from_key(key); + auto b = ciphers::chacha20_poly1305::from_key(key); if (!BOOST_TEST(a.has_value()) || !BOOST_TEST(b.has_value())) { return false; } auto data_a = message; auto data_b = message; - auto const tag_a = a->seal(iv, additional_data, data_a); - auto const tag_b = b->seal(iv, additional_data, data_b); + auto const tag_a = a->seal(nonce, associated_data, data_a); + auto const tag_b = b->seal(nonce, associated_data, data_b); bool const same = tag_a && tag_b && data_a == data_b && *tag_a == *tag_b; if (!BOOST_TEST(same)) { print_disagreement(seed, "ChaCha20-Poly1305", 32, message_size); return false; } - bool const opened = BOOST_TEST(b->open(iv, additional_data, data_a, *tag_a).has_value()) && - BOOST_TEST(a->open(iv, additional_data, data_b, *tag_b).has_value()) && + bool const opened = BOOST_TEST(b->open(nonce, associated_data, data_a, *tag_a).has_value()) && + BOOST_TEST(a->open(nonce, associated_data, data_b, *tag_b).has_value()) && BOOST_TEST(data_a == message && data_b == message); if (!opened) { print_disagreement(seed, "ChaCha20-Poly1305", 32, message_size); diff --git a/test/support/capabilities.hpp b/test/support/capabilities.hpp index 61301c0f..115226b7 100644 --- a/test/support/capabilities.hpp +++ b/test/support/capabilities.hpp @@ -12,12 +12,13 @@ #include #include #include -#include #include namespace webcpp::test { -/** The size of the key an algorithm's `make` takes: its `key_size`, else a secret key's 32. */ +/** + * The size of the key an algorithm's factory takes: its `key_size`, else a secret key's 32. + */ template constexpr std::size_t key_size_of() { if constexpr (requires { Algorithm::key_size; }) { @@ -28,20 +29,20 @@ constexpr std::size_t key_size_of() { } /** - * Makes an algorithm, through the type a program names, from a key whose bytes are all 1, or, - * for one made of a secret key and a peer's public key (a box), from that key twice, or, for - * one keyed by no key of its own (Ed25519ph's signer), begins it, or, for sealed boxes, seals - * an empty message to that key as a public key, or, for PEM, armours that key as a public key's - * DER, or, for one of free functions alone (X25519), gives that key's public key: a cell the - * capability - * table marks present whose engine is missing fails to compile here. The type names its family - * and its algorithm as the table does, and `supports_v` says that the backend has it. + * Makes an algorithm, through the type a program names, from a key whose bytes are all 1 (its + * `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, + * or, for PEM, armours that key as a public key's DER: a cell the capability table marks present + * whose engine is missing fails to compile here. The type names its family and its algorithm as the + * table does, and `supports_v` says that the backend has it. * * @tparam Algorithm The type a program names, on `Backend`. * @tparam Family Its family's tag. * @tparam Name Its algorithm's tag. * @tparam Backend Its backend. - * @return Whether `make`, `begin`, `seal`, `armour` or `public_key` succeeded. + * @return Whether the factory, `begin`, `seal` or `armour` succeeded. */ template [[nodiscard]] bool made() { @@ -52,18 +53,32 @@ template key_bytes.fill(1); if constexpr (requires { Algorithm::begin(); }) { return Algorithm::begin().has_value(); - } else if constexpr (requires { Algorithm::make(key_bytes); }) { - return Algorithm::make(key_bytes).has_value(); - } else if constexpr (requires { Algorithm::make(key_bytes, key_bytes); }) { - return Algorithm::make(key_bytes, key_bytes).has_value(); - } else if constexpr (requires { Algorithm::overhead; }) { - std::array sealed{}; - return Algorithm::seal(key_bytes, {}, sealed).has_value(); - } else if constexpr (requires { Algorithm::armour("", key_bytes, std::span{}); }) { + } else if constexpr (requires { Algorithm::from_key(key_bytes); }) { + return Algorithm::from_key(key_bytes).has_value(); + } else if constexpr (requires { Algorithm::from_secret(key_bytes); }) { + 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 { + typename Algorithm::keypair_type; + Algorithm::key_size; + }) { + // A box, made of an X25519 key pair and a peer's public key, or a sealed box, sealing to + // a public key: both of that key, the key pair's secret and the peer's public key. + auto const peer_key = Algorithm::public_key_type::from_bytes(key_bytes); + if (!peer_key) { + return false; + } + if constexpr (requires { Algorithm::overhead; }) { + std::array sealed{}; + return Algorithm::seal(*peer_key, {}, sealed).has_value(); + } else { + auto const own_keypair = Algorithm::keypair_type::from_secret(key_bytes); + return own_keypair && Algorithm::from_keys(*own_keypair, *peer_key).has_value(); + } + } else { std::array text{}; return Algorithm::armour("PUBLIC KEY", key_bytes, text).has_value(); - } else { - return Algorithm::public_key(key_bytes).has_value(); } } diff --git a/test/support/gcm_checks.hpp b/test/support/gcm_checks.hpp index 12497ae1..34a533b2 100644 --- a/test/support/gcm_checks.hpp +++ b/test/support/gcm_checks.hpp @@ -26,7 +26,7 @@ #include #include -#include +#include #include #include @@ -57,9 +57,9 @@ inline bool all_zero(std::span bytes) { template void with_gcm(std::span key, F&& f) { switch (key.size()) { - case 16: f(crypto::ciphers::gcm>::make(key)); break; - case 24: f(crypto::ciphers::gcm>::make(key)); break; - default: f(crypto::ciphers::gcm>::make(key)); break; + case 16: f(crypto::ciphers::gcm>::from_key(key)); break; + case 24: f(crypto::ciphers::gcm>::from_key(key)); break; + default: f(crypto::ciphers::gcm>::from_key(key)); break; } } @@ -69,8 +69,8 @@ void check_spec_cases(gcm_cases cases = gcm_spec_cases) { BOOST_TEST_EQ(cases.size(), gcm_spec_cases.size()); for (auto const& c : cases) { auto const key = from_hex(c.key); - auto const iv = from_hex(c.iv); - auto const additional_data = from_hex(c.additional_data); + auto const nonce = from_hex(c.nonce); + auto const associated_data = from_hex(c.associated_data); auto const plaintext = from_hex(c.plaintext); auto const tag = from_hex(c.tag); with_gcm(key, [&](auto made) { @@ -78,11 +78,12 @@ void check_spec_cases(gcm_cases cases = gcm_spec_cases) { return; } auto data = plaintext; - auto const sealed = made->seal(iv, additional_data, data); + auto const sealed = made->seal(nonce, associated_data, data); BOOST_TEST(sealed.has_value()); BOOST_TEST_EQ(to_hex(data), c.ciphertext); - BOOST_TEST(sealed && crypto::equal(*sealed, std::span(tag))); - BOOST_TEST(made->open(iv, additional_data, data, tag).has_value()); + BOOST_TEST(sealed && + crypto::constant_time_equal(*sealed, std::span(tag))); + BOOST_TEST(made->open(nonce, associated_data, data, tag).has_value()); BOOST_TEST_EQ(to_hex(data), c.plaintext); }); } @@ -93,13 +94,13 @@ template void check_guards() { using checked_aead = crypto::ciphers::gcm>; std::array const short_key{}; - BOOST_TEST(checked_aead::make(short_key).error() == crypto::error::invalid_key_size); + BOOST_TEST(checked_aead::from_key(short_key).error() == crypto::error::invalid_key_size); std::array const key16{}; - BOOST_TEST(checked_aead::make(key16).error() == crypto::error::invalid_key_size); - BOOST_TEST(checked_aead::make({}).error() == crypto::error::invalid_key_size); + BOOST_TEST(checked_aead::from_key(key16).error() == crypto::error::invalid_key_size); + BOOST_TEST(checked_aead::from_key({}).error() == crypto::error::invalid_key_size); std::array const key{}; - auto made = checked_aead::make(key); + auto made = checked_aead::from_key(key); if (!BOOST_TEST(made.has_value())) { return; } @@ -110,10 +111,10 @@ void check_guards() { std::array const tag{}; std::array const long_tag{}; - BOOST_TEST(made->seal({}, {}, data).error() == crypto::error::invalid_iv_size); - BOOST_TEST(made->seal(long_iv, {}, data).error() == crypto::error::invalid_iv_size); - BOOST_TEST(made->open({}, {}, data, tag).error() == crypto::error::invalid_iv_size); - BOOST_TEST(made->open(long_iv, {}, data, tag).error() == crypto::error::invalid_iv_size); + BOOST_TEST(made->seal({}, {}, data).error() == crypto::error::invalid_nonce_size); + BOOST_TEST(made->seal(long_iv, {}, data).error() == crypto::error::invalid_nonce_size); + BOOST_TEST(made->open({}, {}, data, tag).error() == crypto::error::invalid_nonce_size); + BOOST_TEST(made->open(long_iv, {}, data, tag).error() == crypto::error::invalid_nonce_size); BOOST_TEST( made->open(std::span(long_iv).first(12), {}, data, std::span(tag).first(15)).error() == crypto::error::invalid_tag_size); @@ -123,24 +124,24 @@ void check_guards() { crypto::error::invalid_tag_size); // The IV is checked before the tag: both wrong gives the IV's error. BOOST_TEST(made->open(long_iv, {}, data, std::span(tag).first(15)).error() == - crypto::error::invalid_iv_size); + crypto::error::invalid_nonce_size); BOOST_TEST(data == untouched); // IVs of 1 and of 128 bytes are accepted (spec section 2.4, LEDGER:22), and open. for (std::size_t const size : {std::size_t{1}, std::size_t{128}}) { - auto const iv = std::span(long_iv).first(size); - auto const sealed = made->seal(iv, {}, data); + auto const nonce = std::span(long_iv).first(size); + auto const sealed = made->seal(nonce, {}, data); BOOST_TEST(sealed.has_value()); - BOOST_TEST(sealed && made->open(iv, {}, data, *sealed).has_value()); + BOOST_TEST(sealed && made->open(nonce, {}, data, *sealed).has_value()); BOOST_TEST(data == untouched); } } /** An open of a changed message fails with authentication_failed and zeroes data. */ template -void expect_tampered(Aead& made, std::span iv, - std::span additional_data, std::span data, +void expect_tampered(Aead& made, std::span nonce, + std::span associated_data, std::span data, std::span tag) { - BOOST_TEST(made.open(iv, additional_data, data, tag).error() == + BOOST_TEST(made.open(nonce, associated_data, data, tag).error() == crypto::error::authentication_failed); BOOST_TEST(all_zero(data)); } @@ -154,64 +155,64 @@ void check_tampering(gcm_cases cases = gcm_spec_cases) { } auto const& c = cases[3]; // case 4: plaintext and additional data auto const key = from_hex(c.key); - auto const iv = from_hex(c.iv); - auto const additional_data = from_hex(c.additional_data); + auto const nonce = from_hex(c.nonce); + auto const associated_data = from_hex(c.associated_data); auto const ciphertext = from_hex(c.ciphertext); auto const tag = from_hex(c.tag); - auto made = checked_aead::make(key); + auto made = checked_aead::from_key(key); if (!BOOST_TEST(made.has_value())) { return; } for (std::size_t i = 0; i < ciphertext.size(); ++i) { auto data = ciphertext; data[i] ^= 1U; - expect_tampered(*made, iv, additional_data, data, tag); + expect_tampered(*made, nonce, associated_data, data, tag); } for (std::size_t i = 0; i < tag.size(); ++i) { auto data = ciphertext; auto bad = tag; bad[i] ^= 0x80U; - expect_tampered(*made, iv, additional_data, data, bad); + expect_tampered(*made, nonce, associated_data, data, bad); } - for (std::size_t i = 0; i < additional_data.size(); ++i) { + for (std::size_t i = 0; i < associated_data.size(); ++i) { auto data = ciphertext; - auto bad = additional_data; + auto bad = associated_data; bad[i] ^= 2U; - expect_tampered(*made, iv, bad, data, tag); + expect_tampered(*made, nonce, bad, data, tag); } - for (std::size_t i = 0; i < iv.size(); ++i) { + for (std::size_t i = 0; i < nonce.size(); ++i) { auto data = ciphertext; - auto bad = iv; + auto bad = nonce; bad[i] ^= 4U; - expect_tampered(*made, bad, additional_data, data, tag); + expect_tampered(*made, bad, associated_data, data, tag); } // A ciphertext one byte shorter, its tag unchanged, fails too. { auto data = ciphertext; - expect_tampered(*made, iv, additional_data, std::span(data).first(data.size() - 1), tag); + expect_tampered(*made, nonce, associated_data, std::span(data).first(data.size() - 1), tag); } // The object works after failures. auto data = ciphertext; - BOOST_TEST(made->open(iv, additional_data, data, tag).has_value()); + BOOST_TEST(made->open(nonce, associated_data, data, tag).has_value()); BOOST_TEST_EQ(to_hex(data), c.plaintext); } /** Every call of an empty gcm is refused with invalid_state, and leaves data untouched. */ template -void expect_all_refused(Aead& empty, std::span iv, std::span data, - std::span tag, +void expect_all_refused(Aead& empty, std::span nonce, + std::span data, std::span tag, std::span untouched) { - BOOST_TEST(empty.seal(iv, {}, data).error() == crypto::error::invalid_state); - BOOST_TEST(empty.open(iv, {}, data, tag).error() == crypto::error::invalid_state); + BOOST_TEST(empty.seal(nonce, {}, data).error() == crypto::error::invalid_state); + BOOST_TEST(empty.open(nonce, {}, data, tag).error() == crypto::error::invalid_state); // The state is checked before the IV and the tag. BOOST_TEST(empty.seal({}, {}, data).error() == crypto::error::invalid_state); BOOST_TEST(empty.open({}, {}, data, {}).error() == crypto::error::invalid_state); - BOOST_TEST(empty.begin_seal(iv, {}).error() == crypto::error::invalid_state); + BOOST_TEST(empty.begin_seal(nonce, {}).error() == crypto::error::invalid_state); BOOST_TEST(empty.begin_seal({}, {}).error() == crypto::error::invalid_state); BOOST_TEST(empty.update(data).error() == crypto::error::invalid_state); BOOST_TEST(empty.update({}).error() == crypto::error::invalid_state); BOOST_TEST(empty.result().error() == crypto::error::invalid_state); - BOOST_TEST(empty.begin_open(iv, {}).error() == crypto::error::invalid_state); + BOOST_TEST(empty.begin_open(nonce, {}).error() == crypto::error::invalid_state); BOOST_TEST(empty.begin_open({}, {}).error() == crypto::error::invalid_state); BOOST_TEST(empty.authenticate(data).error() == crypto::error::invalid_state); BOOST_TEST(empty.verify(tag).error() == crypto::error::invalid_state); @@ -229,18 +230,18 @@ void check_moved_from(gcm_cases cases = gcm_spec_cases) { } auto const& one_block = cases[13]; // case 14: AES-256, one zero block std::array const key{}; - auto made = checked_aead::make(key); + auto made = checked_aead::from_key(key); if (!BOOST_TEST(made.has_value())) { return; } checked_aead moved = std::move(*made); - std::array const iv{}; + 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; std::array const tag{}; auto const all_refused = [&](checked_aead& empty) { - expect_all_refused(empty, iv, data, tag, untouched); + expect_all_refused(empty, nonce, data, tag, untouched); }; all_refused(*made); // Moving an object that was moved from gives an empty object, and crashes nothing (I1). @@ -251,53 +252,54 @@ void check_moved_from(gcm_cases cases = gcm_spec_cases) { all_refused(again); // The destination works: case 14. data.fill(0); - auto const sealed = moved.seal(iv, {}, data); + auto const sealed = moved.seal(nonce, {}, data); BOOST_TEST_EQ(to_hex(data), one_block.ciphertext); BOOST_TEST(sealed && to_hex(*sealed) == one_block.tag); // A swap of an empty object and a live one moves the key, both ways. std::swap(again, moved); - BOOST_TEST(sealed && again.open(iv, {}, data, *sealed).has_value()); + BOOST_TEST(sealed && again.open(nonce, {}, data, *sealed).has_value()); data.fill(0x6c); all_refused(moved); // Assignment back makes the source whole again. std::array block{}; *made = std::move(again); - auto const resealed = made->seal(iv, {}, block); + auto const resealed = made->seal(nonce, {}, block); BOOST_TEST(resealed && to_hex(*resealed) == one_block.tag); all_refused(again); // Self-move-assignment leaves the key in place. auto& self = *made; *made = std::move(self); block.fill(0); - auto const self_sealed = made->seal(iv, {}, block); + auto const self_sealed = made->seal(nonce, {}, block); BOOST_TEST(self_sealed && to_hex(*self_sealed) == one_block.tag); } /** Case 13: an empty message, through spans whose data() is null. */ template -void check_edge_empty(Aead& made, std::span iv, std::string_view tag_hex) { +void check_edge_empty(Aead& made, std::span nonce, std::string_view tag_hex) { // Case 13: empty plaintext and additional data, through spans whose data() is null. - auto const empty = made.seal(iv, std::span(), std::span()); + auto const empty = made.seal(nonce, std::span(), std::span()); BOOST_TEST(empty && to_hex(*empty) == tag_hex); - BOOST_TEST(empty && made.open(iv, {}, std::span(), *empty).has_value()); + BOOST_TEST(empty && made.open(nonce, {}, std::span(), *empty).has_value()); std::array const zero_tag{}; - BOOST_TEST(made.open(iv, {}, std::span(), zero_tag).error() == + BOOST_TEST(made.open(nonce, {}, std::span(), zero_tag).error() == crypto::error::authentication_failed); } /** A tag right after the data in one buffer. */ template -void check_edge_wire_tag(Aead& made, std::span iv) { +void check_edge_wire_tag(Aead& made, std::span nonce) { // A wire buffer: ciphertext then tag, the tag a subspan right after the data; the open // gives the plaintext back and leaves the tag's bytes as they were. std::array wire{}; std::fill(wire.begin(), wire.begin() + 16, 0x33); - auto const sealed = made.seal(iv, {}, std::span(wire).first(16)); + auto const sealed = made.seal(nonce, {}, std::span(wire).first(16)); if (!BOOST_TEST(sealed.has_value())) { return; } std::copy(sealed->begin(), sealed->end(), wire.begin() + 16); - BOOST_TEST(made.open(iv, {}, std::span(wire).first(16), std::span(wire).last(16)).has_value()); + BOOST_TEST( + made.open(nonce, {}, std::span(wire).first(16), std::span(wire).last(16)).has_value()); BOOST_TEST( std::all_of(wire.begin(), wire.begin() + 16, [](std::uint8_t b) { return b == 0x33; })); BOOST_TEST(std::equal(sealed->begin(), sealed->end(), wire.begin() + 16)); @@ -305,13 +307,13 @@ void check_edge_wire_tag(Aead& made, std::span iv) { /** A tag that overlaps the data's end. */ template -void check_edge_overlap(Aead& made, std::span iv) { +void check_edge_overlap(Aead& made, std::span nonce) { // A tag that overlaps the data's end fails cleanly: the data is zeroed, and the bytes // after the data, which only the tag covers, are as they were. std::array overlap{}; overlap.fill(0x5a); BOOST_TEST( - made.open(iv, {}, std::span(overlap).first(20), std::span(overlap).last(16)).error() == + made.open(nonce, {}, std::span(overlap).first(20), std::span(overlap).last(16)).error() == crypto::error::authentication_failed); BOOST_TEST(all_zero(std::span(overlap).first(20))); BOOST_TEST( @@ -381,14 +383,14 @@ void check_edges(gcm_cases cases = gcm_spec_cases) { return; } std::array const key{}; - auto made = checked_aead::make(key); + auto made = checked_aead::from_key(key); if (!BOOST_TEST(made.has_value())) { return; } - std::array const iv{}; - check_edge_empty(*made, iv, cases[12].tag); - check_edge_wire_tag(*made, iv); - check_edge_overlap(*made, iv); + std::array const nonce{}; + check_edge_empty(*made, nonce, cases[12].tag); + check_edge_wire_tag(*made, nonce); + check_edge_overlap(*made, nonce); check_edge_in_place(*made); check_edge_wire_open(*made); } @@ -399,12 +401,12 @@ void check_edges(gcm_cases cases = gcm_spec_cases) { * one shot (spec 8.1: every case sealed incrementally as well). */ template -void check_in_pieces(Aead& made, std::span iv, - std::span additional_data, +void check_in_pieces(Aead& made, std::span nonce, + std::span associated_data, std::vector const& plaintext, std::string_view ciphertext, std::string_view tag_hex, std::size_t piece) { auto data = plaintext; - BOOST_TEST(made.begin_seal(iv, additional_data).has_value()); + BOOST_TEST(made.begin_seal(nonce, associated_data).has_value()); for (std::size_t at = 0; at < data.size(); at += piece) { auto const size = (std::min)(piece, data.size() - at); BOOST_TEST(made.update(std::span(data).subspan(at, size)).has_value()); @@ -413,18 +415,18 @@ void check_in_pieces(Aead& made, std::span iv, auto const tag = made.result(); BOOST_TEST_EQ(to_hex(data), ciphertext); BOOST_TEST(tag && to_hex(*tag) == tag_hex); - BOOST_TEST(tag && made.open(iv, additional_data, data, *tag).has_value()); + BOOST_TEST(tag && made.open(nonce, associated_data, data, *tag).has_value()); BOOST_TEST(data == plaintext); } /** Every piece size from 1 to the whole message, the whole included (at least 1). */ template -void check_every_piece(Aead& made, std::span iv, - std::span additional_data, +void check_every_piece(Aead& made, std::span nonce, + std::span associated_data, std::vector const& plaintext, std::string_view ciphertext, std::string_view tag_hex) { for (std::size_t piece = 1; piece <= (std::max)(plaintext.size(), std::size_t{1}); ++piece) { - check_in_pieces(made, iv, additional_data, plaintext, ciphertext, tag_hex, piece); + check_in_pieces(made, nonce, associated_data, plaintext, ciphertext, tag_hex, piece); } } @@ -433,12 +435,12 @@ template void check_incremental(gcm_cases cases = gcm_spec_cases) { BOOST_TEST_EQ(cases.size(), gcm_spec_cases.size()); for (auto const& c : cases) { - auto const iv = from_hex(c.iv); - auto const additional_data = from_hex(c.additional_data); + auto const nonce = from_hex(c.nonce); + auto const associated_data = from_hex(c.associated_data); auto const plaintext = from_hex(c.plaintext); with_gcm(from_hex(c.key), [&](auto made) { if (BOOST_TEST(made.has_value())) { - check_every_piece(*made, iv, additional_data, plaintext, c.ciphertext, c.tag); + check_every_piece(*made, nonce, associated_data, plaintext, c.ciphertext, c.tag); } }); } @@ -446,9 +448,10 @@ void check_incremental(gcm_cases cases = gcm_spec_cases) { /** A fresh message of case 14 (AES-256, one zero block) seals as the specification says. */ template -void expect_fresh_message(Aead& made, std::span iv, gcm_case const& one_block) { +void expect_fresh_message(Aead& made, std::span nonce, + gcm_case const& one_block) { std::array data{}; - BOOST_TEST(made.begin_seal(iv, {}).has_value()); + BOOST_TEST(made.begin_seal(nonce, {}).has_value()); BOOST_TEST(made.update(data).has_value()); auto const tag = made.result(); BOOST_TEST_EQ(to_hex(data), one_block.ciphertext); @@ -460,13 +463,13 @@ void expect_fresh_message(Aead& made, std::span iv, gcm_case * refused, and none reaches the engine with the source's wiped state. */ template -void expect_source_refuses(Aead& source, std::span iv) { +void expect_source_refuses(Aead& source, std::span nonce) { std::array data{}; - BOOST_TEST(source.begin_seal(iv, {}).error() == crypto::error::invalid_state); + BOOST_TEST(source.begin_seal(nonce, {}).error() == crypto::error::invalid_state); BOOST_TEST(source.update(data).error() == crypto::error::invalid_state); BOOST_TEST(source.result().error() == crypto::error::invalid_state); - BOOST_TEST(source.begin_seal(iv, {}).error() == crypto::error::invalid_state); - BOOST_TEST(source.begin_open(iv, {}).error() == crypto::error::invalid_state); + BOOST_TEST(source.begin_seal(nonce, {}).error() == crypto::error::invalid_state); + BOOST_TEST(source.begin_open(nonce, {}).error() == crypto::error::invalid_state); BOOST_TEST(source.authenticate(data).error() == crypto::error::invalid_state); BOOST_TEST(source.verify(data).error() == crypto::error::invalid_state); BOOST_TEST(source.decrypt(data).error() == crypto::error::invalid_state); @@ -475,41 +478,42 @@ void expect_source_refuses(Aead& source, std::span iv) { /** The machine's wrong calls, each followed by a fresh message. */ template -void check_machine_calls(Aead& made, std::span iv, gcm_case const& one_block) { +void check_machine_calls(Aead& made, std::span nonce, + gcm_case const& one_block) { std::array data{}; BOOST_TEST(made.update(data).error() == crypto::error::invalid_state); BOOST_TEST(made.result().error() == crypto::error::invalid_state); - expect_fresh_message(made, iv, one_block); + expect_fresh_message(made, nonce, one_block); BOOST_TEST(made.result().error() == crypto::error::invalid_state); // a second result BOOST_TEST(made.update(data).error() == crypto::error::invalid_state); // after result - BOOST_TEST(made.begin_seal(iv, {}).has_value()); - BOOST_TEST(made.begin_seal(iv, {}).error() == crypto::error::invalid_state); + BOOST_TEST(made.begin_seal(nonce, {}).has_value()); + BOOST_TEST(made.begin_seal(nonce, {}).error() == crypto::error::invalid_state); BOOST_TEST(made.result().error() == crypto::error::invalid_state); // the error ended it - expect_fresh_message(made, iv, one_block); + expect_fresh_message(made, nonce, one_block); - BOOST_TEST(made.begin_seal(iv, {}).has_value()); + BOOST_TEST(made.begin_seal(nonce, {}).has_value()); std::array const long_iv{}; BOOST_TEST(made.begin_seal(long_iv, {}).error() == crypto::error::invalid_state); - expect_fresh_message(made, iv, one_block); - BOOST_TEST(made.begin_seal(long_iv, {}).error() == crypto::error::invalid_iv_size); - BOOST_TEST(made.begin_seal({}, {}).error() == crypto::error::invalid_iv_size); + expect_fresh_message(made, nonce, one_block); + BOOST_TEST(made.begin_seal(long_iv, {}).error() == crypto::error::invalid_nonce_size); + BOOST_TEST(made.begin_seal({}, {}).error() == crypto::error::invalid_nonce_size); BOOST_TEST(made.update(data).error() == crypto::error::invalid_state); // none began - expect_fresh_message(made, iv, one_block); + expect_fresh_message(made, nonce, one_block); // A message abandoned halfway leaves nothing behind: the next one is whole. - BOOST_TEST(made.begin_seal(iv, {}).has_value()); + BOOST_TEST(made.begin_seal(nonce, {}).has_value()); BOOST_TEST(made.update(std::span(data).first(7)).has_value()); - BOOST_TEST(made.begin_seal(iv, {}).error() == crypto::error::invalid_state); - expect_fresh_message(made, iv, one_block); + BOOST_TEST(made.begin_seal(nonce, {}).error() == crypto::error::invalid_state); + expect_fresh_message(made, nonce, one_block); } /** A fresh incremental open of case 14 (AES-256, one zero block) gives its zero block. */ template -void expect_fresh_open(Aead& made, std::span iv, gcm_case const& one_block) { +void expect_fresh_open(Aead& made, std::span nonce, gcm_case const& one_block) { auto data = from_hex(one_block.ciphertext); auto const tag = from_hex(one_block.tag); - BOOST_TEST(made.begin_open(iv, {}).has_value()); + BOOST_TEST(made.begin_open(nonce, {}).has_value()); BOOST_TEST(made.authenticate(data).has_value()); BOOST_TEST(made.verify(tag).has_value()); BOOST_TEST(made.decrypt(data).has_value()); @@ -519,17 +523,17 @@ void expect_fresh_open(Aead& made, std::span iv, gcm_case co /** Begins an open and authenticates the data: the first pass, before its tag is verified. */ template -void begin_authenticated(Aead& made, std::span iv, +void begin_authenticated(Aead& made, std::span nonce, std::span data) { - BOOST_TEST(made.begin_open(iv, {}).has_value()); + BOOST_TEST(made.begin_open(nonce, {}).has_value()); BOOST_TEST(made.authenticate(data).has_value()); } /** Begins an open, authenticates the data and verifies its tag: the second pass is next. */ template -void begin_verified(Aead& made, std::span iv, +void begin_verified(Aead& made, std::span nonce, std::span data, std::span tag) { - begin_authenticated(made, iv, data); + begin_authenticated(made, nonce, data); BOOST_TEST(made.verify(tag).has_value()); } @@ -539,7 +543,7 @@ void begin_verified(Aead& made, std::span iv, * pass; each is followed by a fresh open. */ template -void check_machine_first_pass_calls(Aead& made, std::span iv, +void check_machine_first_pass_calls(Aead& made, std::span nonce, gcm_case const& one_block) { auto data = from_hex(one_block.ciphertext); auto const tag = from_hex(one_block.tag); @@ -548,21 +552,21 @@ void check_machine_first_pass_calls(Aead& made, std::span iv BOOST_TEST(made.verify(tag).error() == crypto::error::invalid_state); BOOST_TEST(made.decrypt(data).error() == crypto::error::invalid_state); BOOST_TEST(made.end_open().error() == crypto::error::invalid_state); - expect_fresh_open(made, iv, one_block); + expect_fresh_open(made, nonce, one_block); // A second begin_open, and end_open before verify, end the first pass. - begin_authenticated(made, iv, data); - BOOST_TEST(made.begin_open(iv, {}).error() == crypto::error::invalid_state); + begin_authenticated(made, nonce, data); + BOOST_TEST(made.begin_open(nonce, {}).error() == crypto::error::invalid_state); BOOST_TEST(made.verify(tag).error() == crypto::error::invalid_state); - expect_fresh_open(made, iv, one_block); - begin_authenticated(made, iv, data); + expect_fresh_open(made, nonce, one_block); + begin_authenticated(made, nonce, data); BOOST_TEST(made.end_open().error() == crypto::error::invalid_state); BOOST_TEST(made.verify(tag).error() == crypto::error::invalid_state); - expect_fresh_open(made, iv, one_block); + expect_fresh_open(made, nonce, one_block); // The seal's calls in the first pass end it as well. - begin_authenticated(made, iv, data); + begin_authenticated(made, nonce, data); BOOST_TEST(made.result().error() == crypto::error::invalid_state); BOOST_TEST(made.verify(tag).error() == crypto::error::invalid_state); - expect_fresh_message(made, iv, one_block); + expect_fresh_message(made, nonce, one_block); } /** @@ -570,31 +574,31 @@ void check_machine_first_pass_calls(Aead& made, std::span iv * begin_seal, update and result end it, and each is followed by a fresh open. */ template -void check_machine_second_pass_calls(Aead& made, std::span iv, +void check_machine_second_pass_calls(Aead& made, std::span nonce, gcm_case const& one_block) { auto data = from_hex(one_block.ciphertext); auto const tag = from_hex(one_block.tag); - begin_verified(made, iv, data, tag); + begin_verified(made, nonce, data, tag); BOOST_TEST(made.authenticate(data).error() == crypto::error::invalid_state); BOOST_TEST(made.decrypt(data).error() == crypto::error::invalid_state); - expect_fresh_open(made, iv, one_block); - begin_verified(made, iv, data, tag); + expect_fresh_open(made, nonce, one_block); + begin_verified(made, nonce, data, tag); BOOST_TEST(made.verify(tag).error() == crypto::error::invalid_state); BOOST_TEST(made.end_open().error() == crypto::error::invalid_state); - expect_fresh_open(made, iv, one_block); - begin_verified(made, iv, data, tag); - BOOST_TEST(made.begin_open(iv, {}).error() == crypto::error::invalid_state); + expect_fresh_open(made, nonce, one_block); + begin_verified(made, nonce, data, tag); + BOOST_TEST(made.begin_open(nonce, {}).error() == crypto::error::invalid_state); BOOST_TEST(made.decrypt(data).error() == crypto::error::invalid_state); - expect_fresh_open(made, iv, one_block); - begin_verified(made, iv, data, tag); - BOOST_TEST(made.begin_seal(iv, {}).error() == crypto::error::invalid_state); + expect_fresh_open(made, nonce, one_block); + begin_verified(made, nonce, data, tag); + BOOST_TEST(made.begin_seal(nonce, {}).error() == crypto::error::invalid_state); BOOST_TEST(made.result().error() == crypto::error::invalid_state); BOOST_TEST(made.decrypt(data).error() == crypto::error::invalid_state); - expect_fresh_open(made, iv, one_block); - begin_verified(made, iv, data, tag); + expect_fresh_open(made, nonce, one_block); + begin_verified(made, nonce, data, tag); BOOST_TEST(made.update(data).error() == crypto::error::invalid_state); BOOST_TEST(made.decrypt(data).error() == crypto::error::invalid_state); - expect_fresh_open(made, iv, one_block); + expect_fresh_open(made, nonce, one_block); } /** @@ -602,44 +606,44 @@ void check_machine_second_pass_calls(Aead& made, std::span i * progress, and is followed by a fresh open. */ template -void check_machine_open_calls(Aead& made, std::span iv, +void check_machine_open_calls(Aead& made, std::span nonce, gcm_case const& one_block) { - check_machine_first_pass_calls(made, iv, one_block); - check_machine_second_pass_calls(made, iv, one_block); + check_machine_first_pass_calls(made, nonce, one_block); + check_machine_second_pass_calls(made, nonce, one_block); } /** A move abandons the message on both sides, and leaves the source refusing every call. */ template void check_machine_moves(Aead& made, std::span key, - std::span iv, gcm_case const& one_block) { - BOOST_TEST(made.begin_seal(iv, {}).has_value()); + std::span nonce, gcm_case const& one_block) { + BOOST_TEST(made.begin_seal(nonce, {}).has_value()); Aead moved = std::move(made); // a move abandons the message on both sides BOOST_TEST(moved.result().error() == crypto::error::invalid_state); - expect_source_refuses(made, iv); + expect_source_refuses(made, nonce); made = std::move(moved); - expect_fresh_message(made, iv, one_block); + expect_fresh_message(made, nonce, one_block); // A move assignment from an object in a message: the same for its source. - auto other = Aead::make(key); + auto other = Aead::from_key(key); if (!BOOST_TEST(other.has_value())) { return; } - BOOST_TEST(other->begin_seal(iv, {}).has_value()); + BOOST_TEST(other->begin_seal(nonce, {}).has_value()); made = std::move(*other); BOOST_TEST(made.result().error() == crypto::error::invalid_state); - expect_source_refuses(*other, iv); - expect_fresh_message(made, iv, one_block); + expect_source_refuses(*other, nonce); + expect_fresh_message(made, nonce, one_block); // A move assignment over an object in a message abandons that message too. - BOOST_TEST(made.begin_seal(iv, {}).has_value()); - auto third = Aead::make(key); + BOOST_TEST(made.begin_seal(nonce, {}).has_value()); + auto third = Aead::from_key(key); if (!BOOST_TEST(third.has_value())) { return; } made = std::move(*third); BOOST_TEST(made.result().error() == crypto::error::invalid_state); - expect_source_refuses(*third, iv); - expect_fresh_message(made, iv, one_block); + expect_source_refuses(*third, nonce); + expect_fresh_message(made, nonce, one_block); } /** @@ -654,14 +658,14 @@ void check_machine(gcm_cases cases = gcm_spec_cases) { } auto const& one_block = cases[13]; // case 14: AES-256, one zero block std::array const key{}; - std::array const iv{}; - auto made = checked_aead::make(key); + std::array const nonce{}; + auto made = checked_aead::from_key(key); if (!BOOST_TEST(made.has_value())) { return; } - check_machine_calls(*made, iv, one_block); - check_machine_open_calls(*made, iv, one_block); - check_machine_moves(*made, key, iv, one_block); + check_machine_calls(*made, nonce, one_block); + check_machine_open_calls(*made, nonce, one_block); + check_machine_moves(*made, key, nonce, one_block); } /** A one-shot seal or open during an incremental message is refused (Review Focus 1). */ @@ -673,23 +677,23 @@ void check_one_shot_during_message(gcm_cases cases = gcm_spec_cases) { } auto const& one_block = cases[13]; // case 14: AES-256, one zero block std::array const key{}; - std::array const iv{}; - auto made = checked_aead::make(key); + std::array const nonce{}; + auto made = checked_aead::from_key(key); if (!BOOST_TEST(made.has_value())) { return; } std::array message{}; - BOOST_TEST(made->begin_seal(iv, {}).has_value()); + BOOST_TEST(made->begin_seal(nonce, {}).has_value()); BOOST_TEST(made->update(std::span(message).first(5)).has_value()); std::array other{}; other.fill(9); auto const untouched = other; std::array const tag{}; - BOOST_TEST(made->seal(iv, {}, other).error() == crypto::error::invalid_state); - BOOST_TEST(made->open(iv, {}, other, tag).error() == crypto::error::invalid_state); + BOOST_TEST(made->seal(nonce, {}, other).error() == crypto::error::invalid_state); + BOOST_TEST(made->open(nonce, {}, other, tag).error() == crypto::error::invalid_state); // The message is checked before the IV and the tag. BOOST_TEST(made->seal({}, {}, other).error() == crypto::error::invalid_state); - BOOST_TEST(made->open(iv, {}, other, {}).error() == crypto::error::invalid_state); + BOOST_TEST(made->open(nonce, {}, other, {}).error() == crypto::error::invalid_state); BOOST_TEST(made->open({}, {}, other, {}).error() == crypto::error::invalid_state); BOOST_TEST(other == untouched); BOOST_TEST(made->update(std::span(message).subspan(5)).has_value()); @@ -704,11 +708,11 @@ void check_one_shot_during_message(gcm_cases cases = gcm_spec_cases) { * one the rest, and `end_open`. Every call must have a value; the plaintext is returned. */ template -std::vector open_in_two_passes(Aead& made, std::span iv, - std::span additional_data, +std::vector open_in_two_passes(Aead& made, std::span nonce, + std::span associated_data, std::vector data, std::span tag, std::size_t piece) { - BOOST_TEST(made.begin_open(iv, additional_data).has_value()); + BOOST_TEST(made.begin_open(nonce, associated_data).has_value()); for (std::size_t at = 0; at < data.size(); at += piece) { auto const size = (std::min)(piece, data.size() - at); BOOST_TEST(made.authenticate(std::span(data).subspan(at, size)).has_value()); @@ -731,15 +735,15 @@ template void incremental_open_pieces(gcm_cases cases = gcm_spec_cases) { BOOST_TEST_EQ(cases.size(), gcm_spec_cases.size()); for (auto const& c : cases) { - auto const iv = from_hex(c.iv); - auto const additional_data = from_hex(c.additional_data); + auto const nonce = from_hex(c.nonce); + auto const associated_data = from_hex(c.associated_data); auto const plaintext = from_hex(c.plaintext); with_gcm(from_hex(c.key), [&](auto made) { if (!BOOST_TEST(made.has_value())) { return; } auto ciphertext = plaintext; - auto const tag = made->seal(iv, additional_data, ciphertext); + auto const tag = made->seal(nonce, associated_data, ciphertext); if (!BOOST_TEST(tag.has_value())) { return; } @@ -751,7 +755,7 @@ void incremental_open_pieces(gcm_cases cases = gcm_spec_cases) { (std::max)(plaintext.size(), std::size_t{1}), }) { auto const opened = - open_in_two_passes(*made, iv, additional_data, ciphertext, *tag, piece); + open_in_two_passes(*made, nonce, associated_data, ciphertext, *tag, piece); BOOST_TEST(opened == plaintext); } }); @@ -766,19 +770,19 @@ void incremental_open_wrong_tag(gcm_cases cases = gcm_spec_cases) { if (!BOOST_TEST(made.has_value())) { return; } - auto const iv = from_hex(c.iv); + auto const nonce = from_hex(c.nonce); auto ciphertext = from_hex(c.ciphertext); auto const kept = ciphertext; auto tag = from_hex(c.tag); tag[0] ^= 1U; - BOOST_TEST(made->begin_open(iv, {}).has_value()); + BOOST_TEST(made->begin_open(nonce, {}).has_value()); BOOST_TEST(made->authenticate(ciphertext).has_value()); BOOST_TEST(made->verify(tag).error() == crypto::error::authentication_failed); BOOST_TEST(ciphertext == kept); BOOST_TEST(made->decrypt(ciphertext).error() == crypto::error::invalid_state); BOOST_TEST(ciphertext == kept); BOOST_TEST(made->end_open().error() == crypto::error::invalid_state); - BOOST_TEST(made->begin_open(iv, {}).has_value()); + BOOST_TEST(made->begin_open(nonce, {}).has_value()); }); } @@ -790,11 +794,11 @@ void incremental_open_decrypt_before_verify(gcm_cases cases = gcm_spec_cases) { if (!BOOST_TEST(made.has_value())) { return; } - auto const iv = from_hex(c.iv); + auto const nonce = from_hex(c.nonce); auto ciphertext = from_hex(c.ciphertext); auto const kept = ciphertext; auto const tag = from_hex(c.tag); - BOOST_TEST(made->begin_open(iv, {}).has_value()); + BOOST_TEST(made->begin_open(nonce, {}).has_value()); BOOST_TEST(made->authenticate(ciphertext).has_value()); BOOST_TEST(made->decrypt(ciphertext).error() == crypto::error::invalid_state); BOOST_TEST(ciphertext == kept); @@ -805,12 +809,12 @@ void incremental_open_decrypt_before_verify(gcm_cases cases = gcm_spec_cases) { /** Seals 32 bytes of case 14's key and IV one shot: the ciphertext, then its tag. */ template std::pair, std::vector> sealed_32( - Aead& made, std::span iv) { + Aead& made, std::span nonce) { std::vector data(32); for (std::size_t i = 0; i < data.size(); ++i) { data[i] = static_cast((i * 13) + 5); } - auto const tag = made.seal(iv, {}, data); + auto const tag = made.seal(nonce, {}, data); BOOST_TEST(tag.has_value()); std::vector tag_bytes(16); if (tag) { @@ -827,11 +831,11 @@ void incremental_open_longer_second_pass(gcm_cases cases = gcm_spec_cases) { if (!BOOST_TEST(made.has_value())) { return; } - auto const iv = from_hex(c.iv); - auto [ciphertext, tag] = sealed_32(*made, iv); + auto const nonce = from_hex(c.nonce); + auto [ciphertext, tag] = sealed_32(*made, nonce); ciphertext.push_back(0x77); auto const kept = ciphertext; - BOOST_TEST(made->begin_open(iv, {}).has_value()); + BOOST_TEST(made->begin_open(nonce, {}).has_value()); BOOST_TEST(made->authenticate(std::span(ciphertext).first(32)).has_value()); BOOST_TEST(made->verify(tag).has_value()); BOOST_TEST(made->decrypt(ciphertext).error() == crypto::error::invalid_input_size); @@ -848,15 +852,15 @@ void incremental_open_shorter_second_pass(gcm_cases cases = gcm_spec_cases) { if (!BOOST_TEST(made.has_value())) { return; } - auto const iv = from_hex(c.iv); - auto [ciphertext, tag] = sealed_32(*made, iv); - BOOST_TEST(made->begin_open(iv, {}).has_value()); + auto const nonce = from_hex(c.nonce); + auto [ciphertext, tag] = sealed_32(*made, nonce); + BOOST_TEST(made->begin_open(nonce, {}).has_value()); BOOST_TEST(made->authenticate(ciphertext).has_value()); BOOST_TEST(made->verify(tag).has_value()); BOOST_TEST(made->decrypt(std::span(ciphertext).first(31)).has_value()); BOOST_TEST(made->end_open().error() == crypto::error::invalid_input_size); BOOST_TEST(made->end_open().error() == crypto::error::invalid_state); // it ended - BOOST_TEST(made->begin_open(iv, {}).has_value()); + BOOST_TEST(made->begin_open(nonce, {}).has_value()); }); } @@ -866,13 +870,13 @@ void incremental_open_shorter_second_pass(gcm_cases cases = gcm_spec_cases) { */ template void incremental_open_too_long([[maybe_unused]] Aead& made, - [[maybe_unused]] std::span iv, + [[maybe_unused]] std::span nonce, [[maybe_unused]] std::span tag) { #if !defined(__wasi__) && !defined(__EMSCRIPTEN__) if constexpr (sizeof(std::size_t) == 8) { // Faults on any access: refused by its size before a byte is read. auto const huge = reserved(static_cast(Aead::max_message_size) + 1); - if (BOOST_TEST(!huge.empty()) && BOOST_TEST(made.begin_open(iv, {}).has_value())) { + if (BOOST_TEST(!huge.empty()) && BOOST_TEST(made.begin_open(nonce, {}).has_value())) { BOOST_TEST(made.authenticate(huge).error() == crypto::error::message_too_long); BOOST_TEST(made.verify(tag).error() == crypto::error::invalid_state); } @@ -883,19 +887,19 @@ void incremental_open_too_long([[maybe_unused]] Aead& made, /** The guards of the incremental open on a made gcm: the IV, the tag, the state and the length. */ template void incremental_open_guards_of(Aead& made, gcm_case const& c) { - auto const iv = from_hex(c.iv); + auto const nonce = from_hex(c.nonce); auto const ciphertext = from_hex(c.ciphertext); auto const tag = from_hex(c.tag); std::array const long_iv{}; - BOOST_TEST(made.begin_open({}, {}).error() == crypto::error::invalid_iv_size); - BOOST_TEST(made.begin_open(long_iv, {}).error() == crypto::error::invalid_iv_size); + BOOST_TEST(made.begin_open({}, {}).error() == crypto::error::invalid_nonce_size); + BOOST_TEST(made.begin_open(long_iv, {}).error() == crypto::error::invalid_nonce_size); BOOST_TEST(made.authenticate(ciphertext).error() == crypto::error::invalid_state); - BOOST_TEST(made.begin_open(iv, {}).has_value()); + BOOST_TEST(made.begin_open(nonce, {}).has_value()); BOOST_TEST(made.authenticate(ciphertext).has_value()); BOOST_TEST(made.verify(std::span(tag).first(15)).error() == crypto::error::invalid_tag_size); BOOST_TEST(made.verify(tag).error() == crypto::error::invalid_state); // it ended - incremental_open_too_long(made, iv, tag); - auto const opened = open_in_two_passes(made, iv, {}, ciphertext, tag, 16); + incremental_open_too_long(made, nonce, tag); + auto const opened = open_in_two_passes(made, nonce, {}, ciphertext, tag, 16); BOOST_TEST_EQ(to_hex(opened), c.plaintext); } @@ -913,19 +917,19 @@ void incremental_open_guards(gcm_cases cases = gcm_spec_cases) { /** A one-shot seal or open during an incremental open is refused, and leaves the open going. */ template void incremental_open_beside_one_shot(Aead& made, gcm_case const& c) { - auto const iv = from_hex(c.iv); + auto const nonce = from_hex(c.nonce); auto const tag = from_hex(c.tag); std::array other{}; other.fill(9); auto const untouched = other; auto data = from_hex(c.ciphertext); - BOOST_TEST(made.begin_open(iv, {}).has_value()); + BOOST_TEST(made.begin_open(nonce, {}).has_value()); BOOST_TEST(made.authenticate(data).has_value()); - BOOST_TEST(made.seal(iv, {}, other).error() == crypto::error::invalid_state); - BOOST_TEST(made.open(iv, {}, other, tag).error() == crypto::error::invalid_state); + BOOST_TEST(made.seal(nonce, {}, other).error() == crypto::error::invalid_state); + BOOST_TEST(made.open(nonce, {}, other, tag).error() == crypto::error::invalid_state); BOOST_TEST(made.verify(tag).has_value()); - BOOST_TEST(made.seal(iv, {}, other).error() == crypto::error::invalid_state); - BOOST_TEST(made.open(iv, {}, other, tag).error() == crypto::error::invalid_state); + BOOST_TEST(made.seal(nonce, {}, other).error() == crypto::error::invalid_state); + BOOST_TEST(made.open(nonce, {}, other, tag).error() == crypto::error::invalid_state); BOOST_TEST(other == untouched); BOOST_TEST(made.decrypt(data).has_value()); BOOST_TEST(made.end_open().has_value()); @@ -938,7 +942,7 @@ void incremental_open_beside_one_shot(Aead& made, gcm_case const& c) { */ template void incremental_open_beside_seal(Aead& made, gcm_case const& c) { - auto const iv = from_hex(c.iv); + auto const nonce = from_hex(c.nonce); auto const ciphertext = from_hex(c.ciphertext); auto const tag = from_hex(c.tag); std::array other{}; @@ -946,25 +950,25 @@ void incremental_open_beside_seal(Aead& made, gcm_case const& c) { auto const untouched = other; // begin_seal ends it. - BOOST_TEST(made.begin_open(iv, {}).has_value()); - BOOST_TEST(made.begin_seal(iv, {}).error() == crypto::error::invalid_state); + BOOST_TEST(made.begin_open(nonce, {}).has_value()); + BOOST_TEST(made.begin_seal(nonce, {}).error() == crypto::error::invalid_state); BOOST_TEST(made.authenticate(ciphertext).error() == crypto::error::invalid_state); // update and result are refused, and end it. - BOOST_TEST(made.begin_open(iv, {}).has_value()); + BOOST_TEST(made.begin_open(nonce, {}).has_value()); BOOST_TEST(made.update(other).error() == crypto::error::invalid_state); BOOST_TEST(other == untouched); BOOST_TEST(made.authenticate(ciphertext).error() == crypto::error::invalid_state); - BOOST_TEST(made.begin_open(iv, {}).has_value()); + BOOST_TEST(made.begin_open(nonce, {}).has_value()); BOOST_TEST(made.result().error() == crypto::error::invalid_state); BOOST_TEST(made.authenticate(ciphertext).error() == crypto::error::invalid_state); // begin_open during a seal ends the seal. - BOOST_TEST(made.begin_seal(iv, {}).has_value()); - BOOST_TEST(made.begin_open(iv, {}).error() == crypto::error::invalid_state); + BOOST_TEST(made.begin_seal(nonce, {}).has_value()); + BOOST_TEST(made.begin_open(nonce, {}).error() == crypto::error::invalid_state); BOOST_TEST(made.result().error() == crypto::error::invalid_state); - auto const opened = open_in_two_passes(made, iv, {}, ciphertext, tag, 7); + auto const opened = open_in_two_passes(made, nonce, {}, ciphertext, tag, 7); BOOST_TEST_EQ(to_hex(opened), c.plaintext); } @@ -988,16 +992,16 @@ void incremental_open_moved(gcm_cases cases = gcm_spec_cases) { if (!BOOST_TEST(made.has_value())) { return; } - auto const iv = from_hex(c.iv); + auto const nonce = from_hex(c.nonce); auto const ciphertext = from_hex(c.ciphertext); auto const tag = from_hex(c.tag); - BOOST_TEST(made->begin_open(iv, {}).has_value()); + BOOST_TEST(made->begin_open(nonce, {}).has_value()); BOOST_TEST(made->authenticate(std::span(ciphertext).first(5)).has_value()); auto moved = std::move(*made); BOOST_TEST(moved.verify(tag).error() == crypto::error::invalid_state); BOOST_TEST(made->verify(tag).error() == crypto::error::invalid_state); - BOOST_TEST(made->begin_open(iv, {}).error() == crypto::error::invalid_state); - auto const opened = open_in_two_passes(moved, iv, {}, ciphertext, tag, 16); + BOOST_TEST(made->begin_open(nonce, {}).error() == crypto::error::invalid_state); + auto const opened = open_in_two_passes(moved, nonce, {}, ciphertext, tag, 16); BOOST_TEST_EQ(to_hex(opened), c.plaintext); }); } @@ -1030,17 +1034,17 @@ void check_limits() { using checked_aead = crypto::ciphers::gcm>; static_assert(sizeof(std::size_t) == 8, "the limits are reachable only with 64-bit sizes"); std::array const key{}; - std::array const iv{}; - auto made = checked_aead::make(key); + std::array const nonce{}; + auto made = checked_aead::from_key(key); auto const huge = reserved(static_cast(checked_aead::max_message_size) + 1); if (!BOOST_TEST(made.has_value()) || !BOOST_TEST(!huge.empty())) { return; } - BOOST_TEST(made->seal(iv, {}, huge).error() == crypto::error::message_too_long); + BOOST_TEST(made->seal(nonce, {}, huge).error() == crypto::error::message_too_long); std::array const tag{}; - BOOST_TEST(made->open(iv, {}, huge, tag).error() == crypto::error::message_too_long); + BOOST_TEST(made->open(nonce, {}, huge, tag).error() == crypto::error::message_too_long); std::array first{}; - BOOST_TEST(made->begin_seal(iv, {}).has_value()); + BOOST_TEST(made->begin_seal(nonce, {}).has_value()); BOOST_TEST(made->update(first).has_value()); BOOST_TEST( made->update(huge.first(static_cast(checked_aead::max_message_size) - 15)) @@ -1049,7 +1053,7 @@ void check_limits() { // The error ends the message, not the object: a fresh message seals as the specification // says (case 14: AES-256, the zero key and IV, one zero block). The mock answers its own. if constexpr (Specified) { - expect_fresh_message(*made, iv, gcm_spec_cases[13]); + expect_fresh_message(*made, nonce, gcm_spec_cases[13]); } } #endif diff --git a/test/support/gcm_spec_vectors.hpp b/test/support/gcm_spec_vectors.hpp index 29223464..c96b491e 100644 --- a/test/support/gcm_spec_vectors.hpp +++ b/test/support/gcm_spec_vectors.hpp @@ -14,7 +14,7 @@ namespace webcpp::test { /** One case of the GCM specification, in hex. */ struct gcm_case { - std::string_view key, plaintext, additional_data, iv, ciphertext, tag; + std::string_view key, plaintext, associated_data, nonce, ciphertext, tag; }; /** The 18 cases of the GCM specification (McGrew and Viega, appendix B), 1 to 18 in order. */ @@ -23,16 +23,16 @@ inline constexpr std::array gcm_spec_cases{ { .key = "00000000000000000000000000000000", .plaintext = "", - .additional_data = "", - .iv = "000000000000000000000000", + .associated_data = "", + .nonce = "000000000000000000000000", .ciphertext = "", .tag = "58e2fccefa7e3061367f1d57a4e7455a", }, { .key = "00000000000000000000000000000000", .plaintext = "00000000000000000000000000000000", - .additional_data = "", - .iv = "000000000000000000000000", + .associated_data = "", + .nonce = "000000000000000000000000", .ciphertext = "0388dace60b6a392f328c2b971b2fe78", .tag = "ab6e47d42cec13bdf53a67b21257bddf", }, @@ -41,8 +41,8 @@ inline constexpr std::array gcm_spec_cases{ .plaintext = "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c959" "56809532fcf0e2449a6b" "525b16aedf5aa0de657ba637b391aafd255", - .additional_data = "", - .iv = "cafebabefacedbaddecaf888", + .associated_data = "", + .nonce = "cafebabefacedbaddecaf888", .ciphertext = "42831ec2217774244b7221b784d0d49ce3aa212f2c02a4e035c17e2329aca12e21d514b2" "5466931c7d8f6a5aac84a" "a051ba30b396a0aac973d58e091473f5985", @@ -53,8 +53,8 @@ inline constexpr std::array gcm_spec_cases{ .plaintext = "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c959" "56809532fcf0e2449a6b" "525b16aedf5aa0de657ba637b39", - .additional_data = "feedfacedeadbeeffeedfacedeadbeefabaddad2", - .iv = "cafebabefacedbaddecaf888", + .associated_data = "feedfacedeadbeeffeedfacedeadbeefabaddad2", + .nonce = "cafebabefacedbaddecaf888", .ciphertext = "42831ec2217774244b7221b784d0d49ce3aa212f2c02a4e035c17e2329aca12e21d514b2" "5466931c7d8f6a5aac84a" "a051ba30b396a0aac973d58e091", @@ -65,8 +65,8 @@ inline constexpr std::array gcm_spec_cases{ .plaintext = "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c959" "56809532fcf0e2449a6b" "525b16aedf5aa0de657ba637b39", - .additional_data = "feedfacedeadbeeffeedfacedeadbeefabaddad2", - .iv = "cafebabefacedbad", + .associated_data = "feedfacedeadbeeffeedfacedeadbeefabaddad2", + .nonce = "cafebabefacedbad", .ciphertext = "61353b4c2806934a777ff51fa22a4755699b2a714fcdc6f83766e5f97b6c742373806900" "e49f24b22b097544d4896" "b424989b5e1ebac0f07c23f4598", @@ -77,10 +77,11 @@ inline constexpr std::array gcm_spec_cases{ .plaintext = "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c959" "56809532fcf0e2449a6b" "525b16aedf5aa0de657ba637b39", - .additional_data = "feedfacedeadbeeffeedfacedeadbeefabaddad2", - .iv = "9313225df88406e555909c5aff5269aa6a7a9538534f7da1e4c303d2a318a728c3c0c95156809539" - "fcf0e2429a6b5" - "25416aedbf5a0de6a57a637b39b", + .associated_data = "feedfacedeadbeeffeedfacedeadbeefabaddad2", + .nonce = + "9313225df88406e555909c5aff5269aa6a7a9538534f7da1e4c303d2a318a728c3c0c95156809539" + "fcf0e2429a6b5" + "25416aedbf5a0de6a57a637b39b", .ciphertext = "8ce24998625615b603a033aca13fb894be9112a5c3a211a8ba262a3cca7e2ca701e4a9a4" "fba43c90ccdcb281d48c7" "c6fd62875d2aca417034c34aee5", @@ -89,16 +90,16 @@ inline constexpr std::array gcm_spec_cases{ { .key = "000000000000000000000000000000000000000000000000", .plaintext = "", - .additional_data = "", - .iv = "000000000000000000000000", + .associated_data = "", + .nonce = "000000000000000000000000", .ciphertext = "", .tag = "cd33b28ac773f74ba00ed1f312572435", }, { .key = "000000000000000000000000000000000000000000000000", .plaintext = "00000000000000000000000000000000", - .additional_data = "", - .iv = "000000000000000000000000", + .associated_data = "", + .nonce = "000000000000000000000000", .ciphertext = "98e7247c07f0fe411c267e4384b0f600", .tag = "2ff58d80033927ab8ef4d4587514f0fb", }, @@ -107,8 +108,8 @@ inline constexpr std::array gcm_spec_cases{ .plaintext = "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c959" "56809532fcf0e2449a6b" "525b16aedf5aa0de657ba637b391aafd255", - .additional_data = "", - .iv = "cafebabefacedbaddecaf888", + .associated_data = "", + .nonce = "cafebabefacedbaddecaf888", .ciphertext = "3980ca0b3c00e841eb06fac4872a2757859e1ceaa6efd984628593b40ca1e19c7d773d00" "c144c525ac619d18c84a3" "f4718e2448b2fe324d9ccda2710acade256", @@ -119,8 +120,8 @@ inline constexpr std::array gcm_spec_cases{ .plaintext = "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c959" "56809532fcf0e2449a6b" "525b16aedf5aa0de657ba637b39", - .additional_data = "feedfacedeadbeeffeedfacedeadbeefabaddad2", - .iv = "cafebabefacedbaddecaf888", + .associated_data = "feedfacedeadbeeffeedfacedeadbeefabaddad2", + .nonce = "cafebabefacedbaddecaf888", .ciphertext = "3980ca0b3c00e841eb06fac4872a2757859e1ceaa6efd984628593b40ca1e19c7d773d00" "c144c525ac619d18c84a3" "f4718e2448b2fe324d9ccda2710", @@ -131,8 +132,8 @@ inline constexpr std::array gcm_spec_cases{ .plaintext = "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c959" "56809532fcf0e2449a6b" "525b16aedf5aa0de657ba637b39", - .additional_data = "feedfacedeadbeeffeedfacedeadbeefabaddad2", - .iv = "cafebabefacedbad", + .associated_data = "feedfacedeadbeeffeedfacedeadbeefabaddad2", + .nonce = "cafebabefacedbad", .ciphertext = "0f10f599ae14a154ed24b36e25324db8c566632ef2bbb34f8347280fc4507057fddc29df" "9a471f75c66541d4d4dad" "1c9e93a19a58e8b473fa0f062f7", @@ -143,10 +144,11 @@ inline constexpr std::array gcm_spec_cases{ .plaintext = "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c959" "56809532fcf0e2449a6b" "525b16aedf5aa0de657ba637b39", - .additional_data = "feedfacedeadbeeffeedfacedeadbeefabaddad2", - .iv = "9313225df88406e555909c5aff5269aa6a7a9538534f7da1e4c303d2a318a728c3c0c95156809539" - "fcf0e2429a6b5" - "25416aedbf5a0de6a57a637b39b", + .associated_data = "feedfacedeadbeeffeedfacedeadbeefabaddad2", + .nonce = + "9313225df88406e555909c5aff5269aa6a7a9538534f7da1e4c303d2a318a728c3c0c95156809539" + "fcf0e2429a6b5" + "25416aedbf5a0de6a57a637b39b", .ciphertext = "d27e88681ce3243c4830165a8fdcf9ff1de9a1d8e6b447ef6ef7b79828666e4581e79012" "af34ddd9e2f037589b292" "db3e67c036745fa22e7e9b7373b", @@ -155,16 +157,16 @@ inline constexpr std::array gcm_spec_cases{ { .key = "0000000000000000000000000000000000000000000000000000000000000000", .plaintext = "", - .additional_data = "", - .iv = "000000000000000000000000", + .associated_data = "", + .nonce = "000000000000000000000000", .ciphertext = "", .tag = "530f8afbc74536b9a963b4f1c4cb738b", }, { .key = "0000000000000000000000000000000000000000000000000000000000000000", .plaintext = "00000000000000000000000000000000", - .additional_data = "", - .iv = "000000000000000000000000", + .associated_data = "", + .nonce = "000000000000000000000000", .ciphertext = "cea7403d4d606b6e074ec5d3baf39d18", .tag = "d0d1c8a799996bf0265b98b5d48ab919", }, @@ -173,8 +175,8 @@ inline constexpr std::array gcm_spec_cases{ .plaintext = "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c959" "56809532fcf0e2449a6b" "525b16aedf5aa0de657ba637b391aafd255", - .additional_data = "", - .iv = "cafebabefacedbaddecaf888", + .associated_data = "", + .nonce = "cafebabefacedbaddecaf888", .ciphertext = "522dc1f099567d07f47f37a32a84427d643a8cdcbfe5c0c97598a2bd2555d1aa8cb08e48" "590dbb3da7b08b1056828" "838c5f61e6393ba7a0abcc9f662898015ad", @@ -185,8 +187,8 @@ inline constexpr std::array gcm_spec_cases{ .plaintext = "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c959" "56809532fcf0e2449a6b" "525b16aedf5aa0de657ba637b39", - .additional_data = "feedfacedeadbeeffeedfacedeadbeefabaddad2", - .iv = "cafebabefacedbaddecaf888", + .associated_data = "feedfacedeadbeeffeedfacedeadbeefabaddad2", + .nonce = "cafebabefacedbaddecaf888", .ciphertext = "522dc1f099567d07f47f37a32a84427d643a8cdcbfe5c0c97598a2bd2555d1aa8cb08e48" "590dbb3da7b08b1056828" "838c5f61e6393ba7a0abcc9f662", @@ -197,8 +199,8 @@ inline constexpr std::array gcm_spec_cases{ .plaintext = "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c959" "56809532fcf0e2449a6b" "525b16aedf5aa0de657ba637b39", - .additional_data = "feedfacedeadbeeffeedfacedeadbeefabaddad2", - .iv = "cafebabefacedbad", + .associated_data = "feedfacedeadbeeffeedfacedeadbeefabaddad2", + .nonce = "cafebabefacedbad", .ciphertext = "c3762df1ca787d32ae47c13bf19844cbaf1ae14d0b976afac52ff7d79bba9de0feb582d3" "3934a4f0954cc2363bc73" "f7862ac430e64abe499f47c9b1f", @@ -209,10 +211,11 @@ inline constexpr std::array gcm_spec_cases{ .plaintext = "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c959" "56809532fcf0e2449a6b" "525b16aedf5aa0de657ba637b39", - .additional_data = "feedfacedeadbeeffeedfacedeadbeefabaddad2", - .iv = "9313225df88406e555909c5aff5269aa6a7a9538534f7da1e4c303d2a318a728c3c0c95156809539" - "fcf0e2429a6b5" - "25416aedbf5a0de6a57a637b39b", + .associated_data = "feedfacedeadbeeffeedfacedeadbeefabaddad2", + .nonce = + "9313225df88406e555909c5aff5269aa6a7a9538534f7da1e4c303d2a318a728c3c0c95156809539" + "fcf0e2429a6b5" + "25416aedbf5a0de6a57a637b39b", .ciphertext = "5a8def2f0c9e53f1f75d7853659e2a20eeb2b22aafde6419a058ab4f6f746bf40fc0c3b7" "80f244452da3ebf1c5d82" "cdea2418997200ef82e44ae7e3f", diff --git a/test/support/mock_backend.hpp b/test/support/mock_backend.hpp index 3dfaefd2..4f2582db 100644 --- a/test/support/mock_backend.hpp +++ b/test/support/mock_backend.hpp @@ -111,14 +111,14 @@ constexpr std::uint8_t stream_byte(std::uint64_t seed, std::uint64_t index) noex } /** The first value of a message's tag, from the key, the IV and the additional data. */ -inline std::uint64_t mac_start(std::uint64_t key, std::span iv, - std::span additional_data) noexcept { - return absorb(absorb(mix(key ^ 0x6d6163U), iv), additional_data); +inline std::uint64_t mac_start(std::uint64_t key, std::span nonce, + std::span associated_data) noexcept { + return absorb(absorb(mix(key ^ 0x6d6163U), nonce), associated_data); } /** The seed of a message's stream, from the key and the IV. */ -inline std::uint64_t stream_start(std::uint64_t key, std::span iv) noexcept { - return absorb(mix(key ^ 0x737472U), iv); +inline std::uint64_t stream_start(std::uint64_t key, std::span nonce) noexcept { + return absorb(mix(key ^ 0x737472U), nonce); } /** The tag of a message whose ciphertext's `size` bytes were absorbed into `mac`. */ @@ -134,12 +134,12 @@ inline void finish(std::uint64_t mac, std::uint64_t size, /** The mock's whole seal in one pass, the reference the generic layer's results must match. */ inline std::array reference_seal(std::span key, - std::span iv, - std::span additional_data, + std::span nonce, + std::span associated_data, std::span data) noexcept { auto const k = key_hash(key); - auto const seed = stream_start(k, iv); - auto mac = mac_start(k, iv, additional_data); + auto const seed = stream_start(k, nonce); + auto mac = mac_start(k, nonce, associated_data); for (std::size_t i = 0; i < data.size(); ++i) { data[i] = static_cast(data[i] ^ stream_byte(seed, i)); mac = mix(mac ^ data[i]); @@ -162,15 +162,15 @@ class mock_cases { for (std::size_t i = 0; i < gcm_spec_cases.size(); ++i) { auto const& spec = gcm_spec_cases[i]; auto data = from_hex(spec.plaintext); - auto const tag = mock_detail::reference_seal(from_hex(spec.key), from_hex(spec.iv), - from_hex(spec.additional_data), data); + auto const tag = mock_detail::reference_seal(from_hex(spec.key), from_hex(spec.nonce), + from_hex(spec.associated_data), data); ciphertexts_[i] = to_hex(data); tags_[i] = to_hex(tag); cases_[i] = { .key = spec.key, .plaintext = spec.plaintext, - .additional_data = spec.additional_data, - .iv = spec.iv, + .associated_data = spec.associated_data, + .nonce = spec.nonce, .ciphertext = ciphertexts_[i], .tag = tags_[i], }; @@ -291,14 +291,14 @@ struct gcm_engine { // The IV and the additional data are consumed here, whole: nothing of them is kept. static boost::system::result start( - state& s, bool sealing, std::span iv, - std::span additional_data) noexcept { - breach(!s.live || iv.empty() || iv.size() > 128); + state& s, bool sealing, std::span nonce, + std::span associated_data) noexcept { + breach(!s.live || nonce.empty() || nonce.size() > 128); if (test::mock_control.start) { return test::mock_control.start; } - s.stream = test::mock_detail::stream_start(s.key, iv); - s.mac = test::mock_detail::mac_start(s.key, iv, additional_data); + s.stream = test::mock_detail::stream_start(s.key, nonce); + s.mac = test::mock_detail::mac_start(s.key, nonce, associated_data); s.position = 0; s.sealing = sealing; s.started = true; diff --git a/test/support/random_device_second_unit.cpp b/test/support/random_device_second_unit.cpp new file mode 100644 index 00000000..a1c29e77 --- /dev/null +++ b/test/support/random_device_second_unit.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) + +#include "random_device_second_unit.hpp" + +#include + +#include + +#include +#include + +namespace webcpp::test { + +boost::system::result fill_in_second_unit(std::span output_bytes) noexcept { + return crypto::random_device{}.fill(output_bytes); +} + +} // namespace webcpp::test diff --git a/test/support/random_device_second_unit.hpp b/test/support/random_device_second_unit.hpp new file mode 100644 index 00000000..ad77d0ae --- /dev/null +++ b/test/support/random_device_second_unit.hpp @@ -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 second translation unit that draws from random_device, linked into random_device_browser: +// whatever the Emscripten draw defines in a header must link from two units of one program. + +#ifndef WEBCPP_TEST_CRYPTO_SUPPORT_RANDOM_DEVICE_SECOND_UNIT_HPP +#define WEBCPP_TEST_CRYPTO_SUPPORT_RANDOM_DEVICE_SECOND_UNIT_HPP + +#include + +#include +#include + +namespace webcpp::test { + +/** Fills `output_bytes` through a `random_device` made in another translation unit. */ +[[nodiscard]] boost::system::result fill_in_second_unit( + std::span output_bytes) noexcept; + +} // namespace webcpp::test + +#endif // WEBCPP_TEST_CRYPTO_SUPPORT_RANDOM_DEVICE_SECOND_UNIT_HPP diff --git a/test/support/secp256k1_checks.hpp b/test/support/secp256k1_checks.hpp index 30db4b0c..c80050bf 100644 --- a/test/support/secp256k1_checks.hpp +++ b/test/support/secp256k1_checks.hpp @@ -49,9 +49,9 @@ inline void expect_empty_musig_signer(webcpp::crypto::curves::secp256k1::keypair if (!BOOST_TEST(signers_key.has_value())) { return; } - BOOST_TEST(secp::musig::nonce_gen(key, *signers_key).error() == + BOOST_TEST(secp::musig::generate_nonce(key, *signers_key).error() == webcpp::crypto::error::invalid_state); - auto made = secp::musig::nonce_gen(live, *signers_key); + auto made = secp::musig::generate_nonce(live, *signers_key); if (!BOOST_TEST(made.has_value())) { return; } @@ -99,7 +99,7 @@ inline void expect_empty_silent_payments(webcpp::crypto::curves::secp256k1::keyp BOOST_TEST(sp::create_label(key, 0).error() == webcpp::crypto::error::invalid_state); std::array const input_keys{*live_key}; std::array summary_space{}; - auto const summary = sp::make_prevouts_summary(outpoint, {}, input_keys, summary_space); + auto const summary = sp::make_previous_outputs_summary(outpoint, {}, input_keys, summary_space); if (!BOOST_TEST(summary.has_value())) { return; } @@ -116,10 +116,11 @@ inline void expect_empty_silent_payments(webcpp::crypto::curves::secp256k1::keyp * @param key The pair, which the tweak is asked of (it stays empty). */ inline void expect_empty_keypair(webcpp::crypto::curves::secp256k1::keypair& key) { - auto const live = webcpp::crypto::curves::secp256k1::keypair::make(std::array{ - 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, - 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, - }); + auto const live = + webcpp::crypto::curves::secp256k1::keypair::from_secret(std::array{ + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, + 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, + }); std::array const message{}; std::array const aux{}; std::array const tweak{}; @@ -135,6 +136,9 @@ inline void expect_empty_keypair(webcpp::crypto::curves::secp256k1::keypair& key webcpp::crypto::error::invalid_state); BOOST_TEST(key.sign(webcpp::crypto::ecdsa_sha256_recoverable, message).error() == webcpp::crypto::error::invalid_state); + BOOST_TEST( + key.sign(webcpp::crypto::ecdsa_keccak256_recoverable, webcpp::crypto::prehashed{message}) + .error() == webcpp::crypto::error::invalid_state); BOOST_TEST(key.tweak_xonly(tweak).error() == webcpp::crypto::error::invalid_state); BOOST_TEST(webcpp::crypto::curves::secp256k1::ellswift_create(key, aux).error() == webcpp::crypto::error::invalid_state); diff --git a/test/support/timing_coverage.hpp b/test/support/timing_coverage.hpp index b4d6ae66..4522a5c9 100644 --- a/test/support/timing_coverage.hpp +++ b/test/support/timing_coverage.hpp @@ -5,11 +5,12 @@ // https://www.boost.org/LICENSE_1_0.txt) // The coverage of detail::timing_guard by the families every backend shares: each public function -// of the AES block cipher, gcm and ciphers::aead, and the free crypto::make, crypto::seal and -// crypto::open that call gcm's and aead's, 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 crypto header, then this one. +// 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 crypto header, then this one. #ifndef WEBCPP_TEST_CRYPTO_SUPPORT_TIMING_COVERAGE_HPP #define WEBCPP_TEST_CRYPTO_SUPPORT_TIMING_COVERAGE_HPP @@ -24,6 +25,7 @@ #include #include #include +#include #include #include @@ -84,7 +86,45 @@ std::array coverage_key() { } /** - * The AES block cipher's guarded functions: `make`, a key of the wrong size included, `encrypt` + * A signature type's functions, which call no backend and enter no guard: `from_bytes`, member + * and free (`crypto::from_bytes`), of its size and of one byte fewer, `bytes()`, and + * `recovery_id()` where the type has it. + * + * @tparam Signature A curve's signature type, `curves::p256::ecdsa_signature` and the others. + * @param type The type's name, `::`. + * @param backend The backend's name, which the test that calls this one covers. + */ +template +void cover_signature(std::string const& type, std::string const& backend) { + auto const wire_bytes = coverage_key(); + std::string const on = " on " + backend; + uncovered(type + "::from_bytes" + on, + [&] { BOOST_TEST(Signature::from_bytes(wire_bytes).has_value()); }); + uncovered(type + "::from_bytes of one byte fewer" + on, [&] { + BOOST_TEST( + Signature::from_bytes(std::span(wire_bytes).first(Signature::size - 1)).error() == + webcpp::crypto::error::invalid_signature); + }); + uncovered("crypto::from_bytes of a " + type + on, + [&] { BOOST_TEST(webcpp::crypto::from_bytes(wire_bytes).has_value()); }); + uncovered("crypto::from_bytes of a short " + type + on, [&] { + BOOST_TEST( + webcpp::crypto::from_bytes(std::span(wire_bytes).first(Signature::size - 1)) + .error() == webcpp::crypto::error::invalid_signature); + }); + auto const made = Signature::from_bytes(wire_bytes); + if (!BOOST_TEST(made.has_value())) { + return; + } + uncovered(type + "::bytes" + on, [&] { BOOST_TEST(made->bytes() == wire_bytes); }); + if constexpr (requires { made->recovery_id(); }) { + uncovered(type + "::recovery_id" + on, + [&] { BOOST_TEST_EQ(made->recovery_id(), wire_bytes.back()); }); + } +} + +/** + * The AES block cipher's guarded functions: `from_key`, a key of the wrong size included, `encrypt` * and `decrypt`, a partial block included. * * @tparam Cipher `aes128`, `aes192` or `aes256`. @@ -95,12 +135,12 @@ template void cover_aes(std::string const& family, std::string const& backend) { std::string const on = " on " + backend; auto const key = coverage_key(); - covered(family + "::make" + on, [&key] { BOOST_TEST(Cipher::make(key).has_value()); }); - covered(family + "::make with a short key" + on, [&key] { - BOOST_TEST(Cipher::make(std::span(key).first(Cipher::key_size - 1)).error() == + covered(family + "::from_key" + on, [&key] { BOOST_TEST(Cipher::from_key(key).has_value()); }); + covered(family + "::from_key with a short key" + on, [&key] { + BOOST_TEST(Cipher::from_key(std::span(key).first(Cipher::key_size - 1)).error() == webcpp::crypto::error::invalid_key_size); }); - auto made = Cipher::make(key); + auto made = Cipher::from_key(key); if (!BOOST_TEST(made.has_value())) { return; } @@ -128,9 +168,9 @@ void cover_aes(std::string const& family, std::string const& backend) { template struct gcm_coverage_message { /** An IV of the size gcm takes. */ - std::array iv{}; + std::array nonce{}; /** Four bytes of additional data. */ - std::array additional_data{1, 2, 3, 4}; + std::array associated_data{1, 2, 3, 4}; /** The data, sealed and opened in place. */ std::array data{}; /** The tag of the last seal. */ @@ -138,8 +178,8 @@ struct gcm_coverage_message { }; /** - * gcm's one-shot `seal` and `open`, and the free `crypto::seal` and `crypto::open` that call - * them, an IV of no byte included. + * gcm's one-shot `seal` and `open`, and the free `secret_key_encryption::aead::seal` and + * `secret_key_encryption::aead::open` that call them, a nonce of no byte included. * * @tparam Gcm `gcm>`, `gcm>` or `gcm>`. * @param made A keyed object, with no message in progress, as it is left. @@ -150,46 +190,53 @@ struct gcm_coverage_message { template void cover_gcm_one_shot(Gcm& made, gcm_coverage_message& message, std::string const& family, std::string const& on) { - covered(family + " crypto::seal" + on, "crypto::seal", [&] { - auto const sealed = - webcpp::crypto::seal(made, message.iv, message.additional_data, message.data); - if (BOOST_TEST(sealed.has_value())) { - message.tag = *sealed; - } - }); - covered(family + " crypto::open" + on, "crypto::open", [&] { - BOOST_TEST(webcpp::crypto::open(made, message.iv, message.additional_data, message.data, - std::span(message.tag.data(), message.tag.size())) - .has_value()); - }); - covered(family + " crypto::seal with an empty IV" + on, "crypto::seal", [&] { - BOOST_TEST(webcpp::crypto::seal(made, {}, message.additional_data, message.data).error() == - webcpp::crypto::error::invalid_iv_size); - }); - covered(family + " crypto::open with an empty IV" + on, "crypto::open", [&] { - BOOST_TEST(webcpp::crypto::open(made, {}, message.additional_data, message.data, - std::span(message.tag.data(), message.tag.size())) - .error() == webcpp::crypto::error::invalid_iv_size); - }); + covered(family + " secret_key_encryption::aead::seal" + on, "secret_key_encryption::aead::seal", + [&] { + auto const sealed = webcpp::crypto::secret_key_encryption::aead::seal( + made, message.nonce, message.associated_data, message.data); + if (BOOST_TEST(sealed.has_value())) { + message.tag = *sealed; + } + }); + covered(family + " secret_key_encryption::aead::open" + on, "secret_key_encryption::aead::open", + [&] { + BOOST_TEST(webcpp::crypto::secret_key_encryption::aead::open( + made, message.nonce, message.associated_data, message.data, + std::span(message.tag.data(), message.tag.size())) + .has_value()); + }); + covered(family + " secret_key_encryption::aead::seal with an empty nonce" + on, + "secret_key_encryption::aead::seal", [&] { + BOOST_TEST(webcpp::crypto::secret_key_encryption::aead::seal( + made, {}, message.associated_data, message.data) + .error() == webcpp::crypto::error::invalid_nonce_size); + }); + covered(family + " secret_key_encryption::aead::open with an empty nonce" + on, + "secret_key_encryption::aead::open", [&] { + BOOST_TEST(webcpp::crypto::secret_key_encryption::aead::open( + made, {}, message.associated_data, message.data, + std::span(message.tag.data(), message.tag.size())) + .error() == webcpp::crypto::error::invalid_nonce_size); + }); covered(family + "::seal" + on, "gcm::seal", [&] { - auto const sealed = made.seal(message.iv, message.additional_data, message.data); + auto const sealed = made.seal(message.nonce, message.associated_data, message.data); if (BOOST_TEST(sealed.has_value())) { message.tag = *sealed; } }); covered(family + "::open" + on, "gcm::open", [&] { - BOOST_TEST(made.open(message.iv, message.additional_data, message.data, + BOOST_TEST(made.open(message.nonce, message.associated_data, message.data, std::span(message.tag.data(), message.tag.size())) .has_value()); }); - covered(family + "::seal with an empty IV" + on, "gcm::seal", [&] { - BOOST_TEST(made.seal({}, message.additional_data, message.data).error() == - webcpp::crypto::error::invalid_iv_size); + covered(family + "::seal with an empty nonce" + on, "gcm::seal", [&] { + BOOST_TEST(made.seal({}, message.associated_data, message.data).error() == + webcpp::crypto::error::invalid_nonce_size); }); - covered(family + "::open with an empty IV" + on, "gcm::open", [&] { - BOOST_TEST(made.open({}, message.additional_data, message.data, + covered(family + "::open with an empty nonce" + on, "gcm::open", [&] { + BOOST_TEST(made.open({}, message.associated_data, message.data, std::span(message.tag.data(), message.tag.size())) - .error() == webcpp::crypto::error::invalid_iv_size); + .error() == webcpp::crypto::error::invalid_nonce_size); }); } @@ -205,15 +252,16 @@ void cover_gcm_one_shot(Gcm& made, gcm_coverage_message& message, std::stri template void cover_gcm_incremental_seal(Gcm& made, gcm_coverage_message& message, std::string const& family, std::string const& on) { - covered(family + "::begin_seal" + on, "gcm::begin_seal", - [&] { BOOST_TEST(made.begin_seal(message.iv, message.additional_data).has_value()); }); + covered(family + "::begin_seal" + on, "gcm::begin_seal", [&] { + BOOST_TEST(made.begin_seal(message.nonce, message.associated_data).has_value()); + }); covered(family + "::update" + on, "gcm::update", [&] { BOOST_TEST(made.update(message.data).has_value()); }); covered(family + "::result" + on, "gcm::result", [&] { BOOST_TEST(made.result().has_value()); }); - covered(family + "::begin_seal with an empty IV" + on, "gcm::begin_seal", [&] { - BOOST_TEST(made.begin_seal({}, message.additional_data).error() == - webcpp::crypto::error::invalid_iv_size); + covered(family + "::begin_seal with an empty nonce" + on, "gcm::begin_seal", [&] { + BOOST_TEST(made.begin_seal({}, message.associated_data).error() == + webcpp::crypto::error::invalid_nonce_size); }); covered(family + "::update without a message" + on, "gcm::update", [&] { BOOST_TEST(made.update(message.data).error() == webcpp::crypto::error::invalid_state); @@ -235,8 +283,9 @@ void cover_gcm_incremental_seal(Gcm& made, gcm_coverage_message& message, template void cover_gcm_incremental_open(Gcm& made, gcm_coverage_message& message, std::string const& family, std::string const& on) { - covered(family + "::begin_open" + on, "gcm::begin_open", - [&] { BOOST_TEST(made.begin_open(message.iv, message.additional_data).has_value()); }); + covered(family + "::begin_open" + on, "gcm::begin_open", [&] { + BOOST_TEST(made.begin_open(message.nonce, message.associated_data).has_value()); + }); covered(family + "::authenticate" + on, "gcm::authenticate", [&] { BOOST_TEST(made.authenticate(message.data).has_value()); }); covered(family + "::verify" + on, "gcm::verify", [&] { @@ -246,9 +295,9 @@ void cover_gcm_incremental_open(Gcm& made, gcm_coverage_message& message, [&] { BOOST_TEST(made.decrypt(message.data).has_value()); }); covered(family + "::end_open" + on, "gcm::end_open", [&] { BOOST_TEST(made.end_open().has_value()); }); - covered(family + "::begin_open with an empty IV" + on, "gcm::begin_open", [&] { - BOOST_TEST(made.begin_open({}, message.additional_data).error() == - webcpp::crypto::error::invalid_iv_size); + covered(family + "::begin_open with an empty nonce" + on, "gcm::begin_open", [&] { + BOOST_TEST(made.begin_open({}, message.associated_data).error() == + webcpp::crypto::error::invalid_nonce_size); }); covered(family + "::authenticate without a message" + on, "gcm::authenticate", [&] { BOOST_TEST(made.authenticate(message.data).error() == webcpp::crypto::error::invalid_state); @@ -296,19 +345,19 @@ void cover_gcm_messages(Gcm& made, std::string const& family, std::string const& template void cover_gcm_moves(std::string const& family, std::string const& on) { auto const key = coverage_key(); - std::array const iv{}; - auto keyed = Gcm::make(key); - auto other_keyed = Gcm::make(key); - auto target = Gcm::make(key); - auto in_message = Gcm::make(key); - auto in_other_message = Gcm::make(key); - auto in_open = Gcm::make(key); + std::array const nonce{}; + auto keyed = Gcm::from_key(key); + auto other_keyed = Gcm::from_key(key); + auto target = Gcm::from_key(key); + auto in_message = Gcm::from_key(key); + auto in_other_message = Gcm::from_key(key); + auto in_open = Gcm::from_key(key); if (!BOOST_TEST(keyed.has_value()) || !BOOST_TEST(other_keyed.has_value()) || !BOOST_TEST(target.has_value()) || !BOOST_TEST(in_message.has_value()) || !BOOST_TEST(in_other_message.has_value()) || !BOOST_TEST(in_open.has_value()) || - !BOOST_TEST(in_message->begin_seal(iv, {}).has_value()) || - !BOOST_TEST(in_other_message->begin_seal(iv, {}).has_value()) || - !BOOST_TEST(in_open->begin_open(iv, {}).has_value())) { + !BOOST_TEST(in_message->begin_seal(nonce, {}).has_value()) || + !BOOST_TEST(in_other_message->begin_seal(nonce, {}).has_value()) || + !BOOST_TEST(in_open->begin_open(nonce, {}).has_value())) { return; } covered(family + "::gcm(gcm&&) of a keyed object" + on, "gcm::gcm", @@ -324,8 +373,8 @@ void cover_gcm_moves(std::string const& family, std::string const& on) { } /** - * gcm's guarded functions: `make` and the free `crypto::make`, a key of the wrong size included; - * those on a message (`cover_gcm_messages`); and the moves (`cover_gcm_moves`). + * gcm's guarded functions: `from_key` and the free `crypto::from_key`, a key of the wrong size + * included; those on a message (`cover_gcm_messages`); and the moves (`cover_gcm_moves`). * * @tparam Gcm `gcm>`, `gcm>` or `gcm>`. * @param family The algorithm's name, `aes128_gcm` or `aes256_gcm`. @@ -335,19 +384,19 @@ template void cover_gcm(std::string const& family, std::string const& backend) { std::string const on = " on " + backend; auto const key = coverage_key(); - covered(family + "::make" + on, "gcm::make", - [&key] { BOOST_TEST(Gcm::make(key).has_value()); }); - covered(family + "::make with a short key" + on, "gcm::make", [&key] { - BOOST_TEST(Gcm::make(std::span(key).first(Gcm::key_size - 1)).error() == + covered(family + "::from_key" + on, "gcm::from_key", + [&key] { BOOST_TEST(Gcm::from_key(key).has_value()); }); + covered(family + "::from_key with a short key" + on, "gcm::from_key", [&key] { + BOOST_TEST(Gcm::from_key(std::span(key).first(Gcm::key_size - 1)).error() == webcpp::crypto::error::invalid_key_size); }); - covered(family + " crypto::make" + on, "crypto::make", - [&key] { BOOST_TEST(webcpp::crypto::make(key).has_value()); }); - covered(family + " crypto::make with a short key" + on, "crypto::make", [&key] { - BOOST_TEST(webcpp::crypto::make(std::span(key).first(Gcm::key_size - 1)).error() == + 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(Gcm::key_size - 1)).error() == webcpp::crypto::error::invalid_key_size); }); - auto made = Gcm::make(key); + auto made = Gcm::from_key(key); if (BOOST_TEST(made.has_value())) { cover_gcm_messages(*made, family, on); } @@ -382,8 +431,8 @@ struct async_completion_counter { }; /** - * gcm's asynchronous functions, `async_make`, `async_seal` and `async_open`, free and member, each - * called with valid input and with input refused before the backend, an `io_context` run after + * gcm's asynchronous functions, `async_from_key`, `async_seal` and `async_open`, free and member, + * each called with valid input and with input refused before the backend, an `io_context` run after * each call so that its completion is delivered. The first guard each enters is its own (the * member a free one calls, and the synchronous call the member makes, hold others, which run * after). @@ -411,61 +460,69 @@ void cover_async_gcm(std::string const& family, std::string const& backend) { context.restart(); context.run(); // lint-run: the test's event loop }; - covered(family + "::async_make" + on, "crypto::async_make", [&] { - crypto::async_make(executor, key, counted); + covered(family + " crypto::async_from_key" + on, "crypto::async_from_key", [&] { + crypto::async_from_key(executor, key, counted); deliver(); }); - covered(family + "::async_make with a short key" + on, "crypto::async_make", [&] { - crypto::async_make(executor, std::span(key).first(Gcm::key_size - 1), counted); + covered( + family + " crypto::async_from_key with a short key" + on, "crypto::async_from_key", [&] { + crypto::async_from_key(executor, std::span(key).first(Gcm::key_size - 1), counted); + deliver(); + }); + covered(family + "::async_from_key" + on, "gcm::async_from_key", [&] { + Gcm::async_from_key(executor, key, counted); deliver(); }); - covered(family + "::async_make, the member," + on, "gcm::async_make", [&] { - Gcm::async_make(executor, key, counted); + covered(family + "::async_from_key with a short key" + on, "gcm::async_from_key", [&] { + Gcm::async_from_key(executor, std::span(key).first(Gcm::key_size - 1), counted); deliver(); }); - covered(family + "::async_make, the member, with a short key" + on, "gcm::async_make", [&] { - Gcm::async_make(executor, std::span(key).first(Gcm::key_size - 1), counted); - deliver(); - }); - auto made = Gcm::make(key); + auto made = Gcm::from_key(key); if (!BOOST_TEST(made.has_value())) { return; } gcm_coverage_message message; - covered(family + "::async_seal" + on, "crypto::async_seal", [&] { - crypto::async_seal(executor, *made, message.iv, message.additional_data, message.data, - keeping); - deliver(); - }); - covered(family + "::async_open" + on, "crypto::async_open", [&] { - crypto::async_open(executor, *made, message.iv, message.additional_data, message.data, - std::span(kept.data(), kept.size()), counted); - deliver(); - }); - covered(family + "::async_seal with an empty IV" + on, "crypto::async_seal", [&] { - crypto::async_seal(executor, *made, {}, message.additional_data, message.data, counted); - deliver(); - }); - covered(family + "::async_open with an empty IV" + on, "crypto::async_open", [&] { - crypto::async_open(executor, *made, {}, message.additional_data, message.data, - std::span(kept.data(), kept.size()), counted); - deliver(); - }); + covered(family + " secret_key_encryption::aead::async_seal" + on, + "secret_key_encryption::aead::async_seal", [&] { + crypto::secret_key_encryption::aead::async_seal( + executor, *made, message.nonce, message.associated_data, message.data, keeping); + deliver(); + }); + covered(family + " secret_key_encryption::aead::async_open" + on, + "secret_key_encryption::aead::async_open", [&] { + crypto::secret_key_encryption::aead::async_open( + executor, *made, message.nonce, message.associated_data, message.data, + std::span(kept.data(), kept.size()), counted); + deliver(); + }); + covered(family + "::async_seal with an empty nonce" + on, + "secret_key_encryption::aead::async_seal", [&] { + crypto::secret_key_encryption::aead::async_seal( + executor, *made, {}, message.associated_data, message.data, counted); + deliver(); + }); + covered(family + "::async_open with an empty nonce" + on, + "secret_key_encryption::aead::async_open", [&] { + crypto::secret_key_encryption::aead::async_open( + executor, *made, {}, message.associated_data, message.data, + std::span(kept.data(), kept.size()), counted); + deliver(); + }); covered(family + "::async_seal, the member," + on, "gcm::async_seal", [&] { - made->async_seal(executor, message.iv, message.additional_data, message.data, keeping); + made->async_seal(executor, message.nonce, message.associated_data, message.data, keeping); deliver(); }); covered(family + "::async_open, the member," + on, "gcm::async_open", [&] { - made->async_open(executor, message.iv, message.additional_data, message.data, + made->async_open(executor, message.nonce, message.associated_data, message.data, std::span(kept.data(), kept.size()), counted); deliver(); }); - covered(family + "::async_seal, the member, with an empty IV" + on, "gcm::async_seal", [&] { - made->async_seal(executor, {}, message.additional_data, message.data, counted); + covered(family + "::async_seal, the member, with an empty nonce" + on, "gcm::async_seal", [&] { + made->async_seal(executor, {}, message.associated_data, message.data, counted); deliver(); }); - covered(family + "::async_open, the member, with an empty IV" + on, "gcm::async_open", [&] { - made->async_open(executor, {}, message.additional_data, message.data, + covered(family + "::async_open, the member, with an empty nonce" + on, "gcm::async_open", [&] { + made->async_open(executor, {}, message.associated_data, message.data, std::span(kept.data(), kept.size()), counted); deliver(); }); @@ -473,10 +530,11 @@ void cover_async_gcm(std::string const& family, std::string const& backend) { } /** - * Ed25519's asynchronous functions, `async_make`, `async_generate`, `async_sign` and + * Ed25519's asynchronous functions, `async_from_secret`, `async_generate`, `async_sign` and * `async_verify` (both overloads, without and with the policy), free and member, each called with - * valid input and with input refused before the backend (a seed of 31 bytes, a signature of 63, a - * moved-from key pair), an `io_context` run after each call so that its completion is delivered. + * valid input, with input refused before the backend (a seed of 31 bytes, a moved-from key pair) + * and with a signature of zeros, which the backend refuses, an `io_context` run after each call so + * that its completion is delivered. * The first guard each enters is its own (the member a free one calls, and the synchronous call * the member makes, hold others, which run after). * @@ -486,7 +544,7 @@ void cover_async_gcm(std::string const& family, std::string const& backend) { template void cover_async_ed25519(std::string const& backend) { namespace crypto = webcpp::crypto; - using signature_type = std::array; + using signature_type = crypto::curves::ed25519::signature; using backend_type = Keypair::backend_type; std::string const on = " on " + backend; webcpp::asio::io_context context; @@ -495,6 +553,7 @@ void cover_async_ed25519(std::string const& backend) { std::array const message{1, 2, 3}; int completions = 0; signature_type kept{}; + signature_type const zero_signature{}; async_completion_counter const counted{.completions = &completions}; async_completion_counter const keeping{ .completions = &completions, @@ -505,32 +564,34 @@ void cover_async_ed25519(std::string const& backend) { context.restart(); context.run(); // lint-run: the test's event loop }; - covered("ed25519::async_make" + on, "crypto::async_make", [&] { - crypto::async_make(executor, seed, counted); - deliver(); - }); - covered("ed25519::async_make with a short seed" + on, "crypto::async_make", [&] { - crypto::async_make(executor, std::span(seed).first(Keypair::seed_size - 1), - counted); + covered("ed25519 crypto::async_from_secret" + on, "crypto::async_from_secret", [&] { + crypto::async_from_secret(executor, seed, counted); deliver(); }); + covered("ed25519 crypto::async_from_secret with a short seed" + on, "crypto::async_from_secret", + [&] { + crypto::async_from_secret( + executor, std::span(seed).first(Keypair::seed_size - 1), counted); + deliver(); + }); covered("ed25519::async_generate" + on, "crypto::async_generate", [&] { crypto::async_generate(executor, counted); deliver(); }); - covered("ed25519::basic_keypair::async_make" + on, [&] { - Keypair::async_make(executor, seed, counted); + covered("ed25519::basic_keypair::async_from_secret" + on, [&] { + Keypair::async_from_secret(executor, seed, counted); deliver(); }); - covered("ed25519::basic_keypair::async_make with a short seed" + on, [&] { - Keypair::async_make(executor, std::span(seed).first(Keypair::seed_size - 1), counted); + covered("ed25519::basic_keypair::async_from_secret with a short seed" + on, [&] { + Keypair::async_from_secret(executor, std::span(seed).first(Keypair::seed_size - 1), + counted); deliver(); }); covered("ed25519::basic_keypair::async_generate" + on, [&] { Keypair::async_generate(executor, counted); deliver(); }); - auto made = Keypair::make(seed); + auto made = Keypair::from_secret(seed); if (!BOOST_TEST(made.has_value())) { return; } @@ -552,9 +613,9 @@ void cover_async_ed25519(std::string const& backend) { crypto::curves::ed25519::strict, counted); deliver(); }); - covered("ed25519::async_verify with a short signature" + on, "crypto::async_verify", [&] { - crypto::async_verify(executor, crypto::eddsa, std::span(kept).first(63), - message, *public_key, counted); + covered("ed25519::async_verify with a zero signature" + on, "crypto::async_verify", [&] { + crypto::async_verify(executor, crypto::eddsa, zero_signature, message, + *public_key, counted); deliver(); }); covered("ed25519::basic_keypair::async_sign" + on, [&] { @@ -571,9 +632,9 @@ void cover_async_ed25519(std::string const& backend) { crypto::curves::ed25519::strict, counted); deliver(); }); - covered("ed25519::public_key::async_verify with a short signature" + on, [&] { - public_key->template async_verify( - executor, crypto::eddsa, std::span(kept).first(63), message, counted); + covered("ed25519::public_key::async_verify with a zero signature" + on, [&] { + public_key->template async_verify(executor, crypto::eddsa, zero_signature, + message, counted); deliver(); }); [[maybe_unused]] Keypair const taken(std::move(*made)); @@ -591,93 +652,246 @@ void cover_async_ed25519(std::string const& backend) { } /** - * X25519's asynchronous `async_agree`, called with valid input and with a key of 31 bytes, an - * `io_context` run after each call so that its completion is delivered. Its first guard is its - * own (the synchronous call it makes holds others, which run after). + * X25519's asynchronous functions, `async_from_secret`, `async_generate` and `async_agree`, free + * and member, each called with valid input and with input refused before the backend (a secret + * key of 31 bytes, a moved-from key pair), an `io_context` run after each call so that its + * completion is delivered. The first guard each enters is its own (the member a free one calls, + * and the synchronous call the member makes, hold others, which run after). * - * @tparam Backend The backend of X25519. + * @tparam Keypair `curves::x25519::basic_keypair`. * @param backend The backend's name. */ -template +template void cover_async_x25519(std::string const& backend) { namespace crypto = webcpp::crypto; std::string const on = " on " + backend; webcpp::asio::io_context context; auto const executor = context.get_executor(); - auto const alice = coverage_key<32>(); - auto bob_secret = coverage_key<32>(); + auto const alice = coverage_key(); + auto bob_secret = coverage_key(); bob_secret[0] ^= 0x42U; - auto const bob = crypto::curves::x25519::public_key(bob_secret); - if (!BOOST_TEST(bob.has_value())) { - return; - } + auto const short_key = std::span(alice).first(Keypair::secret_key_size - 1); int completions = 0; async_completion_counter<> const counted{.completions = &completions}; - covered("x25519::async_agree" + on, "crypto::async_agree", [&] { - crypto::async_agree(executor, alice, *bob, counted); + // Each call's completion is delivered before the next call. + auto const deliver = [&context] { context.restart(); context.run(); // lint-run: the test's event loop + }; + covered("x25519 crypto::async_from_secret" + on, "crypto::async_from_secret", [&] { + crypto::async_from_secret(executor, alice, counted); + deliver(); }); - covered("x25519::async_agree with a short key" + on, "crypto::async_agree", [&] { - crypto::async_agree(executor, std::span(alice).first(31), *bob, counted); - context.restart(); - context.run(); // lint-run: the test's event loop + covered("x25519 crypto::async_from_secret with a short key" + on, "crypto::async_from_secret", + [&] { + crypto::async_from_secret(executor, short_key, counted); + deliver(); + }); + covered("x25519 crypto::async_generate" + on, "crypto::async_generate", [&] { + crypto::async_generate(executor, counted); + deliver(); + }); + covered("x25519::basic_keypair::async_from_secret" + on, [&] { + Keypair::async_from_secret(executor, alice, counted); + deliver(); }); - BOOST_TEST_EQ(completions, 2); + covered("x25519::basic_keypair::async_from_secret with a short key" + on, [&] { + Keypair::async_from_secret(executor, short_key, counted); + deliver(); + }); + covered("x25519::basic_keypair::async_generate" + on, [&] { + Keypair::async_generate(executor, counted); + deliver(); + }); + auto made = Keypair::from_secret(alice); + auto const bob = Keypair::from_secret(bob_secret); + if (!BOOST_TEST(made.has_value()) || !BOOST_TEST(bob.has_value())) { + return; + } + auto const peer = bob->public_key(); + if (!BOOST_TEST(peer.has_value())) { + return; + } + covered("x25519 crypto::async_agree" + on, "crypto::async_agree", [&] { + crypto::async_agree(executor, *made, *peer, counted); + deliver(); + }); + covered("x25519::basic_keypair::async_agree" + on, [&] { + made->async_agree(executor, *peer, counted); + deliver(); + }); + [[maybe_unused]] Keypair const taken(std::move(*made)); + covered("x25519 crypto::async_agree moved from" + on, "crypto::async_agree", [&] { + // NOLINTNEXTLINE(bugprone-use-after-move): the moved-from key pair's refusal + crypto::async_agree(executor, *made, *peer, counted); + deliver(); + }); + covered("x25519::basic_keypair::async_agree moved from" + on, [&] { + // NOLINTNEXTLINE(bugprone-use-after-move): the moved-from key pair's refusal + made->async_agree(executor, *peer, counted); + deliver(); + }); + BOOST_TEST_EQ(completions, 10); } /** - * The free `crypto::make`, `crypto::seal` and `crypto::open` over a `ciphers::aead`, each - * entering its own guard before the member's, a key and a nonce of the wrong size included. + * The free `crypto::from_key`, `secret_key_encryption::aead::seal` and + * `secret_key_encryption::aead::open` over a `ciphers::basic_chacha20_poly1305`, each entering its + * own guard before the member's, a key and a nonce of the wrong size included. * - * @tparam Aead `aead`: ChaCha20-Poly1305 and its forms, or a secret box. + * @tparam Aead `basic_chacha20_poly1305`: ChaCha20-Poly1305 and its forms. * @param family The family's name, as the public alias spells it. * @param on ` on `, which ends each name. */ template void cover_aead_free_forms(std::string const& family, std::string const& on) { auto const key = coverage_key(); - covered(family + " crypto::make" + on, "crypto::make", - [&key] { BOOST_TEST(webcpp::crypto::make(key).has_value()); }); - covered(family + " crypto::make with a short key" + on, "crypto::make", [&key] { - BOOST_TEST(webcpp::crypto::make(std::span(key).first(Aead::key_size - 1)).error() == - webcpp::crypto::error::invalid_key_size); + 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(Aead::key_size - 1)).error() == + webcpp::crypto::error::invalid_key_size); }); - auto made = Aead::make(key); + auto made = Aead::from_key(key); if (!BOOST_TEST(made.has_value())) { return; } - std::array const iv{}; + std::array const nonce{}; std::array data{}; typename Aead::result_type tag{}; - covered(family + " crypto::seal" + on, "crypto::seal", [&] { - auto const sealed = webcpp::crypto::seal(*made, iv, {}, data); - if (BOOST_TEST(sealed.has_value())) { - tag = *sealed; - } - }); - covered(family + " crypto::open" + on, "crypto::open", [&] { - BOOST_TEST(webcpp::crypto::open(*made, iv, {}, data, std::span(tag.data(), tag.size())) - .has_value()); + covered(family + " secret_key_encryption::aead::seal" + on, "secret_key_encryption::aead::seal", + [&] { + auto const sealed = + webcpp::crypto::secret_key_encryption::aead::seal(*made, nonce, {}, data); + if (BOOST_TEST(sealed.has_value())) { + tag = *sealed; + } + }); + covered(family + " secret_key_encryption::aead::open" + on, "secret_key_encryption::aead::open", + [&] { + BOOST_TEST(webcpp::crypto::secret_key_encryption::aead::open( + *made, nonce, {}, data, std::span(tag.data(), tag.size())) + .has_value()); + }); + covered(family + " secret_key_encryption::aead::seal with a short nonce" + on, + "secret_key_encryption::aead::seal", [&] { + BOOST_TEST(webcpp::crypto::secret_key_encryption::aead::seal( + *made, std::span(nonce).first(Aead::nonce_size - 1), {}, data) + .error() == webcpp::crypto::error::invalid_nonce_size); + }); + covered(family + " secret_key_encryption::aead::open with a short nonce" + on, + "secret_key_encryption::aead::open", [&] { + BOOST_TEST(webcpp::crypto::secret_key_encryption::aead::open( + *made, std::span(nonce).first(Aead::nonce_size - 1), {}, data, + std::span(tag.data(), tag.size())) + .error() == webcpp::crypto::error::invalid_nonce_size); + }); +} + +/** + * ciphers::basic_chacha20_poly1305's asynchronous functions (design D6): `crypto::async_from_key` + * and the static `async_from_key`, a key of the wrong size included, and `async_seal` and + * `async_open`, free (`secret_key_encryption::aead`) and member, a nonce of the wrong size + * included, an `io_context` run after each call so that its completion is delivered. The first + * guard each enters is its own. + * + * @tparam Aead `basic_chacha20_poly1305`: ChaCha20-Poly1305 and its forms. + * @param family The family's name, as the public alias spells it. + * @param on ` on `, which ends each name. + */ +template +void cover_async_aead(std::string const& family, std::string const& on) { + namespace aead = webcpp::crypto::secret_key_encryption::aead; + webcpp::asio::io_context context; + auto const executor = context.get_executor(); + auto const key = coverage_key(); + auto const short_key = std::span(key).first(Aead::key_size - 1); + int completions = 0; + typename Aead::result_type kept{}; + async_completion_counter const counted{.completions = &completions}; + async_completion_counter const keeping{ + .completions = &completions, + .tag = &kept, + }; + 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::seal with a short nonce" + on, "crypto::seal", [&] { - BOOST_TEST( - webcpp::crypto::seal(*made, std::span(iv).first(Aead::iv_size - 1), {}, data).error() == - webcpp::crypto::error::invalid_iv_size); + 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_poly1305::async_from_key", + [&] { + Aead::async_from_key(executor, key, counted); + deliver(); + }); + covered(family + "::async_from_key with a short key" + on, + "ciphers::basic_chacha20_poly1305::async_from_key", [&] { + Aead::async_from_key(executor, short_key, counted); + deliver(); + }); + auto made = Aead::from_key(key); + if (!BOOST_TEST(made.has_value())) { + return; + } + std::array const nonce{}; + auto const short_nonce = std::span(nonce).first(Aead::nonce_size - 1); + std::array data{}; + auto const tag = [&kept] { return std::span(kept.data(), kept.size()); }; + covered(family + " secret_key_encryption::aead::async_seal" + on, + "secret_key_encryption::aead::async_seal", [&] { + aead::async_seal(executor, *made, nonce, {}, data, keeping); + deliver(); + }); + covered(family + " secret_key_encryption::aead::async_open" + on, + "secret_key_encryption::aead::async_open", [&] { + aead::async_open(executor, *made, nonce, {}, data, tag(), counted); + deliver(); + }); + covered(family + " secret_key_encryption::aead::async_seal with a short nonce" + on, + "secret_key_encryption::aead::async_seal", [&] { + aead::async_seal(executor, *made, short_nonce, {}, data, counted); + deliver(); + }); + covered(family + " secret_key_encryption::aead::async_open with a short nonce" + on, + "secret_key_encryption::aead::async_open", [&] { + aead::async_open(executor, *made, short_nonce, {}, data, tag(), counted); + deliver(); + }); + covered(family + "::async_seal" + on, "ciphers::basic_chacha20_poly1305::async_seal", [&] { + made->async_seal(executor, nonce, {}, data, keeping); + deliver(); }); - covered(family + " crypto::open with a short nonce" + on, "crypto::open", [&] { - BOOST_TEST(webcpp::crypto::open(*made, std::span(iv).first(Aead::iv_size - 1), {}, data, - std::span(tag.data(), tag.size())) - .error() == webcpp::crypto::error::invalid_iv_size); + covered(family + "::async_open" + on, "ciphers::basic_chacha20_poly1305::async_open", [&] { + made->async_open(executor, nonce, {}, data, tag(), counted); + deliver(); }); + covered(family + "::async_seal with a short nonce" + on, + "ciphers::basic_chacha20_poly1305::async_seal", [&] { + made->async_seal(executor, short_nonce, {}, data, counted); + deliver(); + }); + covered(family + "::async_open with a short nonce" + on, + "ciphers::basic_chacha20_poly1305::async_open", [&] { + made->async_open(executor, short_nonce, {}, data, tag(), counted); + deliver(); + }); + BOOST_TEST_EQ(completions, 12); } /** - * ciphers::aead's guarded functions: `make`, a key of the wrong size included, `seal` and - * `open`, a nonce of the wrong size included, and the free forms that call them - * (`cover_aead_free_forms`). + * ciphers::basic_chacha20_poly1305's guarded functions: `from_key`, a key of the wrong size + * included, `seal` and `open`, a nonce of the wrong size included, and the free forms that call + * them (`cover_aead_free_forms`), and their asynchronous forms (`cover_async_aead`). * - * @tparam Aead `aead`: ChaCha20-Poly1305 and its forms, or a secret box. + * @tparam Aead `basic_chacha20_poly1305`: ChaCha20-Poly1305 and its forms. * @param family The family's name, as the public alias spells it. * @param backend The backend's name. */ @@ -685,38 +899,42 @@ template void cover_aead(std::string const& family, std::string const& backend) { std::string const on = " on " + backend; auto const key = coverage_key(); - covered(family + "::make" + on, "aead::make", - [&key] { BOOST_TEST(Aead::make(key).has_value()); }); - covered(family + "::make with a short key" + on, "aead::make", [&key] { - BOOST_TEST(Aead::make(std::span(key).first(Aead::key_size - 1)).error() == - webcpp::crypto::error::invalid_key_size); - }); - auto made = Aead::make(key); + covered(family + "::from_key" + on, "ciphers::basic_chacha20_poly1305::from_key", + [&key] { BOOST_TEST(Aead::from_key(key).has_value()); }); + covered(family + "::from_key with a short key" + on, + "ciphers::basic_chacha20_poly1305::from_key", [&key] { + BOOST_TEST(Aead::from_key(std::span(key).first(Aead::key_size - 1)).error() == + webcpp::crypto::error::invalid_key_size); + }); + auto made = Aead::from_key(key); if (!BOOST_TEST(made.has_value())) { return; } - std::array const iv{}; + std::array const nonce{}; std::array data{}; typename Aead::result_type tag{}; - covered(family + "::seal" + on, "aead::seal", [&] { - auto const sealed = made->seal(iv, {}, data); + covered(family + "::seal" + on, "ciphers::basic_chacha20_poly1305::seal", [&] { + auto const sealed = made->seal(nonce, {}, data); if (BOOST_TEST(sealed.has_value())) { tag = *sealed; } }); - covered(family + "::open" + on, "aead::open", [&] { - BOOST_TEST(made->open(iv, {}, data, std::span(tag.data(), tag.size())).has_value()); - }); - covered(family + "::seal with a short nonce" + on, "aead::seal", [&] { - BOOST_TEST(made->seal(std::span(iv).first(Aead::iv_size - 1), {}, data).error() == - webcpp::crypto::error::invalid_iv_size); - }); - covered(family + "::open with a short nonce" + on, "aead::open", [&] { - BOOST_TEST(made->open(std::span(iv).first(Aead::iv_size - 1), {}, data, - std::span(tag.data(), tag.size())) - .error() == webcpp::crypto::error::invalid_iv_size); - }); + covered(family + "::open" + on, "ciphers::basic_chacha20_poly1305::open", [&] { + BOOST_TEST(made->open(nonce, {}, data, std::span(tag.data(), tag.size())).has_value()); + }); + covered( + family + "::seal with a short nonce" + on, "ciphers::basic_chacha20_poly1305::seal", [&] { + BOOST_TEST(made->seal(std::span(nonce).first(Aead::nonce_size - 1), {}, data).error() == + webcpp::crypto::error::invalid_nonce_size); + }); + covered(family + "::open with a short nonce" + on, "ciphers::basic_chacha20_poly1305::open", + [&] { + BOOST_TEST(made->open(std::span(nonce).first(Aead::nonce_size - 1), {}, data, + std::span(tag.data(), tag.size())) + .error() == webcpp::crypto::error::invalid_nonce_size); + }); cover_aead_free_forms(family, on); + cover_async_aead(family, on); } } // namespace webcpp::test diff --git a/test/support/timing_seam.hpp b/test/support/timing_seam.hpp index e1e1c572..bffe5341 100644 --- a/test/support/timing_seam.hpp +++ b/test/support/timing_seam.hpp @@ -22,10 +22,12 @@ #include #include +#include #include #include #include #include +#include namespace webcpp::test { @@ -61,12 +63,18 @@ inline void timing_entered(std::source_location const& where) noexcept { namespace webcpp::test { /** - * A function as a check names it: its identifier, the scope that qualifies it, and optionally a - * word its parameter list holds, for overloads of one scope and name. + * A function as a check names it: its identifier, the scope that qualifies it and the qualifiers + * the check writes before that scope, and optionally a word its parameter list holds, for + * overloads of one scope and name. */ struct named_function { /** The class or namespace that qualifies it, unqualified and without template arguments. */ std::string scope; + /** + * Every component the check writes before the identifier, the outermost first, `scope` last: + * `secret_key_encryption`, `aead` for `secret_key_encryption::aead::seal`. + */ + std::vector qualifiers; /** Its name: an identifier, or `operator` and its symbol (`operator==`). */ std::string identifier; /** A word its parameter list holds, or empty for any. */ @@ -77,8 +85,9 @@ struct named_function { * Reads a function, spelled `::::`, optionally followed by * `(`, or by a space and words that say how it is called. * - * The scope is the component before the identifier, empty when there is none. A check named - * `pem::algorithm::unarmour of a text without lines on sodium` names `algorithm::unarmour`; + * The scope is the component before the identifier, empty when there is none; every component + * before it is kept too, and each must match (`names_function`). A check named + * `pem::algorithm::unarmour of a text without lines on sodium` names `pem::algorithm::unarmour`; * `secp256k1::equal(digest` names `secp256k1::equal` with a parameter list that holds `digest`. * * @param spelled The function as a check spells it. @@ -98,11 +107,18 @@ inline named_function function_named(std::string_view spelled) { return named; } named.identifier = std::string(qualified.substr(separator + 2)); - std::string_view const qualifiers = qualified.substr(0, separator); - std::size_t const scope_separator = qualifiers.rfind("::"); - named.scope = std::string(scope_separator == std::string_view::npos - ? qualifiers - : qualifiers.substr(scope_separator + 2)); + std::string_view qualifiers = qualified.substr(0, separator); + while (!qualifiers.empty()) { + std::size_t const component_separator = qualifiers.find("::"); + named.qualifiers.emplace_back(qualifiers.substr(0, component_separator)); + qualifiers = component_separator == std::string_view::npos + ? std::string_view{} + : qualifiers.substr(component_separator + 2); + } + if (!named.qualifiers.empty()) { + // A label that starts with `::` (`::seal`) writes no component: its scope stays empty. + named.scope = named.qualifiers.back(); + } return named; } @@ -145,15 +161,18 @@ inline std::size_t exception_specification_of(std::string_view text) { /** * A `function_name()` in one spelling for clang, GCC and MSVC: the template arguments clang and - * GCC append (` [B = ...]`, ` [with B = ...]`) cut, the exception specification MSVC appends to a - * function that may throw or whose `noexcept` depends on its arguments (` noexcept(false)`) cut, - * and the space MSVC puts between `operator` and its symbol (`operator ==`) removed. + * GCC append (` [B = ...]`, ` [with B = ...]`) cut, the trailing requires-clause GCC writes after + * the parameter list (` requires requires(...) {...}`) cut, the exception specification MSVC + * appends to a function that may throw or whose `noexcept` depends on its arguments + * (` noexcept(false)`) cut, and the space MSVC puts between `operator` and its symbol + * (`operator ==`) removed. * * @param entered A `function_name()`. * @return The same function, spelled for the search of `names_function`. */ inline std::string normalized_function_name(std::string_view entered) { - std::string_view const cut = entered.substr(0, entered.find(" [")); + std::string_view cut = entered.substr(0, entered.find(" [")); + cut = cut.substr(0, cut.find(" requires ")); std::string normal(cut.substr(0, exception_specification_of(cut))); constexpr std::string_view operator_word = "operator "; for (std::size_t found = normal.find(operator_word); found != std::string::npos; @@ -224,11 +243,12 @@ inline std::size_t parameter_list_of(std::string_view text) { /** * Whether a `function_name()` is the named function: its own name, the qualified name before its * outermost parameter list (and before the template arguments MSVC writes there), ends with - * `::::`, its scope read without template arguments, and its parameter list - * holds the named word. A name in the return type or a parameter type never counts, a named - * function without a scope never matches, and a lambda's (`(lambda)`, `(anonymous class)`, - * ``, ``) never is: a guard belongs at the top of the public function, not in - * a lambda in it. + * `::::::`, each component read without its template arguments, so + * that `secret_key_encryption::aead::seal` is not `ciphers::basic_chacha20_poly1305::seal`, + * and its parameter list holds the named word. A name in the return type or a parameter type never + * counts, a named function without a scope never matches, and a lambda's (`(lambda)`, + * `(anonymous class)`, ``, ``) never is: a guard belongs at the top of the + * public function, not in a lambda in it. * * @param entered A `function_name()`, as clang, GCC or MSVC spells it. * @param named The function a check names. @@ -261,10 +281,25 @@ inline bool names_function(std::string_view entered, named_function const& named } name = name.substr(0, end); } - if (!name.ends_with(needle) || - qualifier_before(text, name.size() - needle.size()) != named.scope) { + if (!name.ends_with(needle)) { return false; } + // Each component the check names, from the scope outwards, its template arguments skipped. + std::size_t separator = name.size() - needle.size(); + for (auto component = named.qualifiers.rbegin(); component != named.qualifiers.rend(); + ++component) { + std::string_view const found = qualifier_before(text, separator); + if (found != *component) { + return false; + } + separator = static_cast(found.data() - text.data()); + if (std::next(component) != named.qualifiers.rend()) { + if (separator < 2 || text.substr(separator - 2, 2) != "::") { + return false; + } + separator -= 2; + } + } std::string_view const parameters = text.substr(open, text.rfind(')') - open); return named.parameter.empty() || parameters.find(named.parameter) != std::string_view::npos; } diff --git a/test/support/valgrind_stub/valgrind/memcheck.h b/test/support/valgrind_stub/valgrind/memcheck.h new file mode 100644 index 00000000..a33ca71d --- /dev/null +++ b/test/support/valgrind_stub/valgrind/memcheck.h @@ -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 stand-in for Valgrind's , for declassify_compile_test.cpp alone: the one +// client request crypto's headers name under WEBCPP_CRYPTO_DETAIL_CT_VALGRIND, which reads both +// its arguments, so that every lane compiles the marks the constant-time lane alone runs. + +#ifndef WEBCPP_TEST_CRYPTO_SUPPORT_VALGRIND_STUB_MEMCHECK_H +#define WEBCPP_TEST_CRYPTO_SUPPORT_VALGRIND_STUB_MEMCHECK_H + +/** Reads the address and the size, as Valgrind's request does, and marks nothing. */ +#define VALGRIND_MAKE_MEM_DEFINED(address, size) \ + (static_cast(address), static_cast(size), 0) + +#endif // WEBCPP_TEST_CRYPTO_SUPPORT_VALGRIND_STUB_MEMCHECK_H diff --git a/test/support/wycheproof_aead.hpp b/test/support/wycheproof_aead.hpp index c7471358..1096596b 100644 --- a/test/support/wycheproof_aead.hpp +++ b/test/support/wycheproof_aead.hpp @@ -4,10 +4,10 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// Wycheproof's tests of an AEAD of ciphers::aead, read at run time from +// Wycheproof's tests of an AEAD of ciphers::basic_chacha20_poly1305, read at run time from // third_party/libs/wycheproof: those with the family's IV size seal and open, the valid // matching and the invalid failing with authentication_failed and the data zeroed; those with -// another IV size give invalid_iv_size on seal and open, the data untouched. +// another IV size give invalid_nonce_size on seal and open, the data untouched. #ifndef WEBCPP_TEST_CRYPTO_SUPPORT_WYCHEPROOF_AEAD_HPP #define WEBCPP_TEST_CRYPTO_SUPPORT_WYCHEPROOF_AEAD_HPP @@ -34,30 +34,30 @@ struct wycheproof_aead_counts { std::size_t valid = 0; /** Invalid, refused with authentication_failed and the data zeroed. */ std::size_t invalid = 0; - /** An IV of another size than the family's, refused with invalid_iv_size. */ + /** An IV of another size than the family's, refused with invalid_nonce_size. */ std::size_t other_iv = 0; }; /** Runs one Wycheproof test through `Aead` and counts how it ended. */ template void check_wycheproof_aead_test(boost::json::value const& test, wycheproof_aead_counts& counts) { - auto made = Aead::make(wycheproof_bytes(test, "key")); + auto made = Aead::from_key(wycheproof_bytes(test, "key")); if (!BOOST_TEST(made.has_value())) { return; } - auto const iv = wycheproof_bytes(test, "iv"); - auto const additional_data = wycheproof_bytes(test, "aad"); + auto const nonce = wycheproof_bytes(test, "iv"); + auto const associated_data = wycheproof_bytes(test, "aad"); auto const message = wycheproof_bytes(test, "msg"); auto const ciphertext = wycheproof_bytes(test, "ct"); auto const tag = wycheproof_bytes(test, "tag"); auto data = ciphertext; - auto const opened = made->open(iv, additional_data, data, tag); - if (iv.size() != Aead::iv_size) { - BOOST_TEST(opened.error() == crypto::error::invalid_iv_size); + auto const opened = made->open(nonce, associated_data, data, tag); + if (nonce.size() != Aead::nonce_size) { + BOOST_TEST(opened.error() == crypto::error::invalid_nonce_size); BOOST_TEST(data == ciphertext); auto plaintext = message; - BOOST_TEST(made->seal(iv, additional_data, plaintext).error() == - crypto::error::invalid_iv_size); + BOOST_TEST(made->seal(nonce, associated_data, plaintext).error() == + crypto::error::invalid_nonce_size); BOOST_TEST(plaintext == message); ++counts.other_iv; return; @@ -71,7 +71,7 @@ void check_wycheproof_aead_test(boost::json::value const& test, wycheproof_aead_ BOOST_TEST(opened.has_value()); BOOST_TEST(data == message); auto sealed_data = message; - auto const sealed = made->seal(iv, additional_data, sealed_data); + auto const sealed = made->seal(nonce, associated_data, sealed_data); BOOST_TEST(sealed_data == ciphertext); BOOST_TEST(sealed && to_hex(*sealed) == to_hex(tag)); ++counts.valid; diff --git a/test/support/wycheproof_gcm.hpp b/test/support/wycheproof_gcm.hpp index 4cb5eacd..ee49de53 100644 --- a/test/support/wycheproof_gcm.hpp +++ b/test/support/wycheproof_gcm.hpp @@ -6,8 +6,8 @@ // Wycheproof's 316 AES-GCM tests at 12fd3aaf (spec section 8.1): the 307 with an IV of 1 // to 128 bytes seal and open, the 226 valid matching and the 81 invalid failing with -// authentication_failed and data zeroed; the 6 with an empty IV give invalid_iv_size; the -// 3 with a 257-byte IV (tcId 268, 272, 276), valid in Wycheproof, give invalid_iv_size +// authentication_failed and data zeroed; the 6 with an empty IV give invalid_nonce_size; the +// 3 with a 257-byte IV (tcId 268, 272, 276), valid in Wycheproof, give invalid_nonce_size // with data untouched, by the cap of section 2.4. #ifndef WEBCPP_TEST_CRYPTO_SUPPORT_WYCHEPROOF_GCM_HPP @@ -41,9 +41,9 @@ struct wycheproof_gcm_counts { std::size_t valid = 0; /** Invalid, refused with authentication_failed and data zeroed. */ std::size_t invalid = 0; - /** An empty IV, refused with invalid_iv_size. */ + /** An empty IV, refused with invalid_nonce_size. */ std::size_t empty_iv = 0; - /** An IV over max_iv_size, refused with invalid_iv_size. */ + /** An IV over max_nonce_size, refused with invalid_nonce_size. */ std::size_t over_cap = 0; }; @@ -52,9 +52,9 @@ struct wycheproof_gcm_test { /** The key, 16, 24 or 32 bytes. */ std::vector key; /** The IV. */ - std::vector iv; + std::vector nonce; /** The additional data. */ - std::vector additional_data; + std::vector associated_data; /** The plaintext. */ std::vector message; /** The ciphertext. */ @@ -70,17 +70,17 @@ template void check_wycheproof_gcm_test(Aead& made, wycheproof_gcm_test const& t, wycheproof_gcm_counts& counts) { auto data = t.ciphertext; - auto const opened = made.open(t.iv, t.additional_data, data, t.tag); - if (t.iv.empty() || t.iv.size() > Aead::max_iv_size) { - BOOST_TEST(opened.error() == crypto::error::invalid_iv_size); + auto const opened = made.open(t.nonce, t.associated_data, data, t.tag); + if (t.nonce.empty() || t.nonce.size() > Aead::max_nonce_size) { + BOOST_TEST(opened.error() == crypto::error::invalid_nonce_size); BOOST_TEST(data == t.ciphertext); // Sealed as well (spec section 2.4: the 257-byte IV is refused by seal too), and the // data is left as it was. auto plaintext = t.message; - BOOST_TEST(made.seal(t.iv, t.additional_data, plaintext).error() == - crypto::error::invalid_iv_size); + BOOST_TEST(made.seal(t.nonce, t.associated_data, plaintext).error() == + crypto::error::invalid_nonce_size); BOOST_TEST(plaintext == t.message); - ++(t.iv.empty() ? counts.empty_iv : counts.over_cap); + ++(t.nonce.empty() ? counts.empty_iv : counts.over_cap); return; } if (!t.valid) { @@ -92,11 +92,11 @@ void check_wycheproof_gcm_test(Aead& made, wycheproof_gcm_test const& t, BOOST_TEST(opened.has_value()); BOOST_TEST(data == t.message); auto sealed_data = t.message; - auto const sealed = made.seal(t.iv, t.additional_data, sealed_data); + auto const sealed = made.seal(t.nonce, t.associated_data, sealed_data); BOOST_TEST(sealed_data == t.ciphertext); BOOST_TEST(sealed && to_hex(*sealed) == to_hex(t.tag)); // Sealed incrementally as well, in pieces of every size (I4). - check_every_piece(made, t.iv, t.additional_data, t.message, to_hex(t.ciphertext), + check_every_piece(made, t.nonce, t.associated_data, t.message, to_hex(t.ciphertext), to_hex(t.tag)); ++counts.valid; } @@ -111,8 +111,8 @@ void check_wycheproof_gcm() { for (auto const& test : group.at("tests").as_array()) { wycheproof_gcm_test const t{ .key = wycheproof_bytes(test, "key"), - .iv = wycheproof_bytes(test, "iv"), - .additional_data = wycheproof_bytes(test, "aad"), + .nonce = wycheproof_bytes(test, "iv"), + .associated_data = wycheproof_bytes(test, "aad"), .message = wycheproof_bytes(test, "msg"), .ciphertext = wycheproof_bytes(test, "ct"), .tag = wycheproof_bytes(test, "tag"), diff --git a/test/synchronous_forms_test.cpp b/test/synchronous_forms_test.cpp index ae4927a3..6944c50a 100644 --- a/test/synchronous_forms_test.cpp +++ b/test/synchronous_forms_test.cpp @@ -5,37 +5,47 @@ // https://www.boost.org/LICENSE_1_0.txt) // Each operation's member and free synchronous forms (design D9, R21 to R23) give the same results -// on every curve and on AES-GCM and ChaCha20-Poly1305, since the free form calls the member, or -// both call one worker: -// - make: K::make(bytes) and crypto::make(bytes) give the same key (its secret, or its seal), -// of the same type, on every key pair, AEAD and public key (P-256's of its coordinates too), -// secp256k1's with a memory resource; generate: crypto::generate() gives a key pair whose -// signature verifies. +// on every curve and on AES-GCM, ChaCha20-Poly1305 and XChaCha20-Poly1305, since the free form +// calls the member, or both call one worker: +// - the factories, named by their input (design D3c): K::from_secret(bytes) and +// crypto::from_secret(bytes) give the same key pair (its secret and its public key back), of +// the same type, on every curve, secp256k1's with a memory resource; T::from_bytes(bytes) and +// crypto::from_bytes(bytes) the same public key, on every curve, and P-256's +// from_coordinates(x, y) the key from_bytes makes of 04 || x || y; C::from_key(key) and +// crypto::from_key(key) the same AEAD, its seal; generate: crypto::generate() gives a key +// pair whose signature verifies. // - sign: key.sign(scheme, input[, extra]) and crypto::sign(key, scheme, input[, extra]) give the // same signature, on every scheme of every curve, secp256k1's hedged ECDSA and BIP340 with // auxiliary randomness included, each the same type. // - verify: pub.verify(scheme, signature, input) and crypto::verify(scheme, signature, input, pub) // accept a valid signature and refuse a changed one with invalid_signature, a message and a // marker of its digest alike; Ed25519's policy and backend named, on both. Both take the -// signature as bytes of any size, so the same arguments go to every form and every curve: a -// std::vector of the signature verifies, and 63 or 65 bytes are invalid_signature, on every -// scheme, secp256k1's x-only key and recover (64 or 66 bytes, and a std::vector) included. +// signature as its curve's and scheme's type (design R1), so the same arguments go to every +// form: a std::vector of the signature, made into the type with from_bytes, verifies, and 63 or +// 65 bytes are refused by from_bytes with invalid_signature, on every scheme, secp256k1's +// x-only key and recover (64 or 66 bytes, and a std::vector) included. // - agree: key.agree(peer) and crypto::agree(key, peer) give the same secret, on P-256 and // secp256k1. -// - seal and open: aead.seal and crypto::seal give the same ciphertext and tag; aead.open and -// crypto::open open it, and refuse a changed tag with authentication_failed, zeroing the data. +// - seal and open: cipher.seal and crypto::secret_key_encryption::aead::seal give the same +// ciphertext and tag; cipher.open and secret_key_encryption::aead::open open it, and refuse a +// changed tag with authentication_failed, zeroing the data (design D11). +// - the size constants are named nonce_size, max_nonce_size and max_associated_data_size (design +// D11, R22), on the AEADs, the secret box and the public-key box. #include #include -#include #include +#include #include #include #include #include #include #include +#include #include +#include +#include #include #include #include @@ -64,6 +74,15 @@ using p256_keypair = p256::basic_keypair; using secp_keypair = secp256k1::basic_keypair; using gcm = crypto::ciphers::gcm>; using chacha = crypto::ciphers::chacha20_poly1305; +using xchacha = crypto::ciphers::xchacha20_poly1305; + +// The size constants spell the nonce and the associated data out (design D11, R22). +static_assert(crypto::ciphers::xchacha20_poly1305<>::nonce_size == 24); +static_assert(crypto::ciphers::aes256_gcm::nonce_size == 12); +static_assert(crypto::ciphers::aes256_gcm::max_nonce_size == 128); +static_assert(crypto::secret_key_encryption::secretbox<>::nonce_size == 24); +static_assert(crypto::public_key_encryption::box::nonce_size == 24); +static_assert(crypto::ciphers::xchacha20_poly1305<>::max_associated_data_size == ~std::uint64_t{0}); /** The message every check signs: "abc". */ constexpr std::array message{'a', 'b', 'c'}; @@ -98,31 +117,71 @@ bool same_secret(crypto::secret const& left, crypto::secret const& right) return std::ranges::equal(left.bytes(), right.bytes()); } +/** + * Whether two results both hold a value, each checked before it is read, and equal values: two + * public keys, or two secrets (of their bytes). + * + * @param left A result. + * @param right Another result of the same value type. + * @return True when both hold a value and the values are equal. + */ +template +bool same_values(Result const& left, Result const& right) { + if (!BOOST_TEST(left.has_value()) || !BOOST_TEST(right.has_value())) { + return false; + } + if constexpr (requires { same_secret(*left, *right); }) { + return same_secret(*left, *right); + } else { + return *left == *right; + } +} + +/** + * A member's result and the free form's: the same type, both values, and equal values. + * + * @tparam Member The member's result type. + * @tparam Free The free form's result type. + * @param member The member's result. + * @param free The free form's result. + */ +template +void same_result(Member const& member, Free const& free) { + static_assert(std::is_same_v); + if (BOOST_TEST(member.has_value()) && BOOST_TEST(free.has_value())) { + BOOST_TEST(*free == *member); + } +} + /** * A changed copy of a signature: its last byte flipped. * + * @tparam Signature A signature type. * @param signature A signature. - * @return The changed copy. + * @return The changed copy, of the same type. */ -template -std::array changed(std::array signature) { - signature.back() ^= 0x01U; - return signature; +template +Signature changed(Signature const& signature) { + auto changed_bytes = signature.bytes(); + changed_bytes.back() ^= 0x01U; + return Signature::from_bytes(changed_bytes).value(); } /** - * A key pair's make, member and free: the same type, and the same key (its secret back). + * A key pair's from_secret, member and free: the same type, and the same key pair (its secret + * back, and the member's public key). * * @tparam Keypair A key pair's type. */ template -void make_forms() { +void from_secret_forms() { auto const secret_key = secret_bytes(1); - auto const member_made = Keypair::make(secret_key); - auto const free_made = crypto::make(secret_key); + auto const member_made = Keypair::from_secret(secret_key); + auto const free_made = crypto::from_secret(secret_key); static_assert(std::is_same_v); if (BOOST_TEST(member_made.has_value()) && BOOST_TEST(free_made.has_value())) { - BOOST_TEST(same_secret(*free_made->secret(), *member_made->secret())); + BOOST_TEST(same_values(free_made->secret(), member_made->secret())); + BOOST_TEST(same_values(free_made->public_key(), member_made->public_key())); } } @@ -155,8 +214,8 @@ void generate_forms(Scheme scheme) { */ template void agree_forms() { - auto const made = Keypair::make(secret_bytes(1)); - auto const peer = Keypair::make(secret_bytes(2)); + auto const made = Keypair::from_secret(secret_bytes(1)); + auto const peer = Keypair::from_secret(secret_bytes(2)); if (!BOOST_TEST(made.has_value()) || !BOOST_TEST(peer.has_value())) { return; } @@ -176,6 +235,7 @@ void agree_forms() { * crypto::verify: both accept the first and refuse the second with invalid_signature. * * @tparam Scheme The scheme. + * @tparam Signature The signature's type, the curve's and the scheme's. * @tparam PublicKey The public key's type. * @tparam Input A message or a marker. * @param scheme The scheme. @@ -183,8 +243,8 @@ void agree_forms() { * @param input The message or the marker. * @param public_key The signer's public key. */ -template -void verify_forms(Scheme scheme, std::array const& signature, Input const& input, +template +void verify_forms(Scheme scheme, Signature const& signature, Input const& input, PublicKey const& public_key) { BOOST_TEST(public_key.verify(scheme, signature, input).has_value()); BOOST_TEST(crypto::verify(scheme, signature, input, public_key).has_value()); @@ -192,27 +252,27 @@ void verify_forms(Scheme scheme, std::array const& signature, BOOST_TEST(public_key.verify(scheme, wrong, input).error() == crypto::error::invalid_signature); BOOST_TEST(crypto::verify(scheme, wrong, input, public_key).error() == crypto::error::invalid_signature); - // The signature as bytes off the wire: a std::vector, and a dynamic span of it. - std::vector const received(signature.begin(), signature.end()); - BOOST_TEST(public_key.verify(scheme, received, input).has_value()); - BOOST_TEST(crypto::verify(scheme, received, input, public_key).has_value()); - BOOST_TEST(crypto::verify(scheme, std::span(received), input, public_key) - .has_value()); - // One byte short (the signature's first 63) and one byte more (a 65th of 0). + // The signature as bytes off the wire, a std::vector, made into the type, by its own + // from_bytes and by crypto::from_bytes. + std::vector const received(signature.bytes().begin(), signature.bytes().end()); + auto const made = Signature::from_bytes(received); + same_result(made, crypto::from_bytes(received)); + if (BOOST_TEST(made.has_value())) { + BOOST_TEST(public_key.verify(scheme, *made, input).has_value()); + BOOST_TEST(crypto::verify(scheme, *made, input, public_key).has_value()); + } + // One byte short (the signature's first 63) and one byte more (a 65th of 0): no signature. auto const short_one = std::span(received).first(63); std::vector long_one = received; long_one.push_back(0); for (auto const sized : {short_one, std::span(long_one)}) { - BOOST_TEST(public_key.verify(scheme, sized, input).error() == - crypto::error::invalid_signature); - BOOST_TEST(crypto::verify(scheme, sized, input, public_key).error() == - crypto::error::invalid_signature); + BOOST_TEST(Signature::from_bytes(sized).error() == crypto::error::invalid_signature); } } /** Ed25519: sign and verify, member and free; Ed25519's policy and backend named on both. */ void ed25519_forms() { - auto const made = ed25519_keypair::make(secret_bytes(1)); + auto const made = ed25519_keypair::from_secret(secret_bytes(1)); if (!BOOST_TEST(made.has_value())) { return; } @@ -233,14 +293,14 @@ void ed25519_forms() { BOOST_TEST(crypto::verify(crypto::eddsa, *member_signed, message, *public_key, ed25519::strict) .has_value()); - // A signature of another size, a key's 32 bytes given where the signature goes. - BOOST_TEST(public_key->verify(crypto::eddsa, public_key->bytes(), message).error() == + // A key's 32 bytes, where the signature goes, are no signature. + BOOST_TEST(ed25519::signature::from_bytes(public_key->bytes()).error() == crypto::error::invalid_signature); } /** P-256: sign and verify, member and free, of a message and of a marker of its digest. */ void p256_forms() { - auto const made = p256_keypair::make(secret_bytes(1)); + auto const made = p256_keypair::from_secret(secret_bytes(1)); if (!BOOST_TEST(made.has_value())) { return; } @@ -262,25 +322,9 @@ void p256_forms() { verify_forms(crypto::ecdsa_sha256, *member_signed, crypto::prehashed{digest}, *public_key); } -/** - * A member's result and the free form's: the same type, both values, and equal values. - * - * @tparam Member The member's result type. - * @tparam Free The free form's result type. - * @param member The member's result. - * @param free The free form's result. - */ -template -void same_result(Member const& member, Free const& free) { - static_assert(std::is_same_v); - if (BOOST_TEST(member.has_value()) && BOOST_TEST(free.has_value())) { - BOOST_TEST(*free == *member); - } -} - /** secp256k1: every sign, member and free, the same signatures and types. */ void secp256k1_sign_forms() { - auto const made = secp_keypair::make(secret_bytes(1)); + auto const made = secp_keypair::from_secret(secret_bytes(1)); if (!BOOST_TEST(made.has_value())) { return; } @@ -298,45 +342,46 @@ void secp256k1_sign_forms() { } /** - * The public keys' make, member and free, on every curve (P-256's of a point and of its - * coordinates), and secp256k1's key pair make and generate with a memory resource. + * The public keys' from_bytes, member and free, on every curve, P-256's from_coordinates the key + * from_bytes makes of 04 || x || y, and secp256k1's key pair from_secret and generate with a + * memory resource. */ void public_key_and_resource_forms() { - auto const ed25519_made = ed25519_keypair::make(secret_bytes(1)); - auto const p256_made = p256_keypair::make(secret_bytes(1)); - auto const secp_made = secp_keypair::make(secret_bytes(1)); + auto const ed25519_made = ed25519_keypair::from_secret(secret_bytes(1)); + auto const p256_made = p256_keypair::from_secret(secret_bytes(1)); + auto const secp_made = secp_keypair::from_secret(secret_bytes(1)); if (!BOOST_TEST(ed25519_made.has_value()) || !BOOST_TEST(p256_made.has_value()) || !BOOST_TEST(secp_made.has_value())) { return; } auto const ed25519_bytes = ed25519_made->public_key()->bytes(); - same_result(ed25519::public_key::make(ed25519_bytes), - crypto::make(ed25519_bytes)); + same_result(ed25519::public_key::from_bytes(ed25519_bytes), + crypto::from_bytes(ed25519_bytes)); using p256_public_key = p256::basic_public_key; auto const point = p256_made->public_key()->uncompressed(); - auto const member_point = p256_public_key::make(point); - auto const free_point = crypto::make(point); - static_assert(std::is_same_v); - std::span const x(point.data() + 1, 32); - std::span const y(point.data() + 33, 32); - auto const free_coordinates = crypto::make(x, y); - if (BOOST_TEST(member_point.has_value()) && BOOST_TEST(free_point.has_value()) && - BOOST_TEST(free_coordinates.has_value())) { - BOOST_TEST(free_point->uncompressed() == member_point->uncompressed()); - BOOST_TEST(free_coordinates->uncompressed() == point); - } + same_result(p256_public_key::from_bytes(point), crypto::from_bytes(point)); + std::span const x_bytes(point.data() + 1, 32); + std::span const y_bytes(point.data() + 33, 32); + std::array joined{0x04}; + std::ranges::copy(x_bytes, joined.begin() + 1); + std::ranges::copy(y_bytes, joined.begin() + 33); + same_result(p256_public_key::from_bytes(joined), + p256_public_key::from_coordinates(x_bytes, y_bytes)); + BOOST_TEST( + same_values(p256_public_key::from_coordinates(x_bytes, y_bytes), p256_made->public_key())); auto const compressed = secp_made->public_key()->compressed(); - same_result(secp256k1::public_key::make(compressed), - crypto::make(compressed)); + same_result(secp256k1::public_key::from_bytes(compressed), + crypto::from_bytes(compressed)); std::pmr::memory_resource* const resource = std::pmr::new_delete_resource(); - auto const member_made = secp_keypair::make(secret_bytes(1), resource); - auto const free_made = crypto::make(secret_bytes(1), resource); + auto const member_made = secp_keypair::from_secret(secret_bytes(1), resource); + auto const free_made = crypto::from_secret(secret_bytes(1), resource); static_assert(std::is_same_v); if (BOOST_TEST(member_made.has_value()) && BOOST_TEST(free_made.has_value())) { - BOOST_TEST(same_secret(*free_made->secret(), *member_made->secret())); + BOOST_TEST(same_values(free_made->secret(), member_made->secret())); + BOOST_TEST(same_values(free_made->public_key(), secp_made->public_key())); } auto const generated = crypto::generate(resource); static_assert( @@ -346,7 +391,7 @@ void public_key_and_resource_forms() { /** secp256k1: both verify schemes, member and free, ECDSA of a marker and Schnorr drawn too. */ void secp256k1_verify_forms() { - auto const made = secp_keypair::make(secret_bytes(1)); + auto const made = secp_keypair::from_secret(secret_bytes(1)); if (!BOOST_TEST(made.has_value())) { return; } @@ -370,31 +415,41 @@ void secp256k1_verify_forms() { BOOST_TEST(crypto::verify(crypto::schnorr, *schnorr, message, public_key->xonly()).has_value()); BOOST_TEST(public_key->verify(crypto::schnorr, *schnorr, message) .has_value()); - // BIP340's x-only key takes the signature as bytes too, its size checked before the key: 63 - // bytes are invalid_signature even with 32 bytes that are no point's x. - std::vector const received(schnorr->begin(), schnorr->end()); - BOOST_TEST(crypto::verify(crypto::schnorr, received, message, public_key->xonly()).has_value()); + // BIP340's x-only key takes the typed signature too, made from bytes received; 63 bytes are + // no signature, whatever the key; a signature with 32 bytes that are no point's x is refused + // for its key. + std::vector const received(schnorr->bytes().begin(), schnorr->bytes().end()); + auto const received_signature = secp256k1::schnorr_signature::from_bytes(received); + if (!BOOST_TEST(received_signature.has_value())) { + return; + } + BOOST_TEST(crypto::verify(crypto::schnorr, *received_signature, message, public_key->xonly()) + .has_value()); auto const short_one = std::span(received).first(63); - BOOST_TEST(crypto::verify(crypto::schnorr, short_one, message, public_key->xonly()).error() == + BOOST_TEST(secp256k1::schnorr_signature::from_bytes(short_one).error() == crypto::error::invalid_signature); std::array const no_point{}; - BOOST_TEST(crypto::verify(crypto::schnorr, short_one, message, no_point).error() == - crypto::error::invalid_signature); - BOOST_TEST(crypto::verify(crypto::schnorr, received, message, no_point).error() == + BOOST_TEST(crypto::verify(crypto::schnorr, *received_signature, message, no_point).error() == crypto::error::invalid_public_key); - // Each scheme refuses the other's signature. - BOOST_TEST(public_key->verify(crypto::schnorr, *ecdsa, message).error() == - crypto::error::invalid_signature); - BOOST_TEST(public_key->verify(crypto::ecdsa_sha256, *schnorr, message).error() == - crypto::error::invalid_signature); + // Each scheme refuses the other's signature: its type does not compile there (design R1), + // and its bytes made into the other's type do not verify. + auto const ecdsa_as_schnorr = secp256k1::schnorr_signature::from_bytes(ecdsa->bytes()); + auto const schnorr_as_ecdsa = secp256k1::ecdsa_signature::from_bytes(schnorr->bytes()); + if (BOOST_TEST(ecdsa_as_schnorr.has_value()) && BOOST_TEST(schnorr_as_ecdsa.has_value())) { + BOOST_TEST(public_key->verify(crypto::schnorr, *ecdsa_as_schnorr, message).error() == + crypto::error::invalid_signature); + BOOST_TEST(public_key->verify(crypto::ecdsa_sha256, *schnorr_as_ecdsa, message).error() == + crypto::error::invalid_signature); + } } /** - * secp256k1's recover takes the recoverable signature as bytes of any size: a std::vector of the - * 65 bytes gives the signer's key, and 64 or 66 bytes are invalid_signature. + * secp256k1's recover takes the recoverable signature as its type: a std::vector of the 65 bytes, + * made into it, gives the signer's key, and 64 or 66 bytes are refused by from_bytes with + * invalid_signature. */ void secp256k1_recover_sizes() { - auto const made = secp_keypair::make(secret_bytes(1)); + auto const made = secp_keypair::from_secret(secret_bytes(1)); if (!BOOST_TEST(made.has_value())) { return; } @@ -403,42 +458,49 @@ void secp256k1_recover_sizes() { if (!BOOST_TEST(public_key.has_value()) || !BOOST_TEST(recoverable.has_value())) { return; } - std::vector const received(recoverable->begin(), recoverable->end()); - auto const recovered = secp256k1::recover(crypto::ecdsa_sha256_recoverable, received, message); + std::vector const received(recoverable->bytes().begin(), + recoverable->bytes().end()); + auto const received_signature = secp256k1::recoverable_signature::from_bytes(received); + if (!BOOST_TEST(received_signature.has_value())) { + return; + } + auto const recovered = + secp256k1::recover(crypto::ecdsa_sha256_recoverable, *received_signature, message); if (BOOST_TEST(recovered.has_value())) { BOOST_TEST(*recovered == *public_key); } auto const short_one = std::span(received).first(64); std::vector long_one = received; long_one.push_back(0); - BOOST_TEST(secp256k1::recover(crypto::ecdsa_sha256_recoverable, short_one, message).error() == + BOOST_TEST(secp256k1::recoverable_signature::from_bytes(short_one).error() == crypto::error::invalid_signature); - BOOST_TEST(secp256k1::recover(crypto::ecdsa_sha256_recoverable, long_one, message).error() == + BOOST_TEST(secp256k1::recoverable_signature::from_bytes(long_one).error() == crypto::error::invalid_signature); } /** - * An AEAD's make, seal and open, member and free: the same ciphertext and tag, and the same + * An AEAD's from_key, seal and open, member and free: the same ciphertext and tag, and the same * refusal of a changed tag. * - * @tparam Aead `gcm` or `chacha`. + * @tparam Aead `gcm`, `chacha` or `xchacha`. */ template void aead_forms() { std::array key{}; std::ranges::copy(secret_bytes(3), key.begin()); - std::array const iv{9}; - std::array const additional_data{'h', 'e', 'a', 'd'}; - auto member_made = Aead::make(key); - auto free_made = crypto::make(key); + std::array const nonce{9}; + std::array const associated_data{'h', 'e', 'a', 'd'}; + auto member_made = Aead::from_key(key); + auto free_made = crypto::from_key(key); static_assert(std::is_same_v); if (!BOOST_TEST(member_made.has_value()) || !BOOST_TEST(free_made.has_value())) { return; } std::array member_data{1, 2, 3}; std::array free_data = member_data; - auto const member_tag = member_made->seal(iv, additional_data, member_data); - auto const free_tag = crypto::seal(*free_made, iv, additional_data, free_data); + auto const member_tag = member_made->seal(nonce, associated_data, member_data); + auto const free_tag = + crypto::secret_key_encryption::aead::seal(*free_made, nonce, associated_data, free_data); static_assert(std::is_same_v); if (!BOOST_TEST(member_tag.has_value()) || !BOOST_TEST(free_tag.has_value())) { return; @@ -448,8 +510,10 @@ void aead_forms() { auto const tag = std::span(member_tag->data(), member_tag->size()); auto opened_by_member = member_data; - BOOST_TEST(member_made->open(iv, additional_data, opened_by_member, tag).has_value()); - BOOST_TEST(crypto::open(*free_made, iv, additional_data, free_data, tag).has_value()); + BOOST_TEST(member_made->open(nonce, associated_data, opened_by_member, tag).has_value()); + BOOST_TEST(crypto::secret_key_encryption::aead::open(*free_made, nonce, associated_data, + free_data, tag) + .has_value()); BOOST_TEST(free_data == opened_by_member); BOOST_TEST(free_data[0] == 1 && free_data[1] == 2 && free_data[2] == 3); @@ -458,12 +522,13 @@ void aead_forms() { auto const wrong = std::span(wrong_tag.data(), wrong_tag.size()); std::array sealed{1, 2, 3}; std::array const zeros{}; - BOOST_TEST(member_made->seal(iv, additional_data, sealed).has_value()); + BOOST_TEST(member_made->seal(nonce, associated_data, sealed).has_value()); auto refused_by_member = sealed; - BOOST_TEST(member_made->open(iv, additional_data, refused_by_member, wrong).error() == - crypto::error::authentication_failed); - BOOST_TEST(crypto::open(*free_made, iv, additional_data, sealed, wrong).error() == + BOOST_TEST(member_made->open(nonce, associated_data, refused_by_member, wrong).error() == crypto::error::authentication_failed); + BOOST_TEST( + crypto::secret_key_encryption::aead::open(*free_made, nonce, associated_data, sealed, wrong) + .error() == crypto::error::authentication_failed); BOOST_TEST(sealed == zeros); BOOST_TEST(refused_by_member == zeros); } @@ -471,9 +536,9 @@ void aead_forms() { } // namespace int main() { - make_forms(); - make_forms(); - make_forms(); + from_secret_forms(); + from_secret_forms(); + from_secret_forms(); generate_forms(crypto::eddsa); generate_forms(crypto::ecdsa_sha256); generate_forms(crypto::schnorr); @@ -488,5 +553,6 @@ int main() { public_key_and_resource_forms(); aead_forms(); aead_forms(); + aead_forms(); return webcpp::test::exit_status(boost::report_errors()); } diff --git a/test/timing_coverage_bearssl_test.cpp b/test/timing_coverage_bearssl_test.cpp index b871d5bb..2f7eb453 100644 --- a/test/timing_coverage_bearssl_test.cpp +++ b/test/timing_coverage_bearssl_test.cpp @@ -12,25 +12,28 @@ // its own guard fails although it calls another guarded function. // // What it covers, by family; a family BearSSL gains adds its line and its checks: -// - AES-GCM, gcm, gcm and gcm: make, the move constructor and move +// - AES-GCM, gcm, gcm and gcm: from_key, the move constructor and move // assignment (ruling R3), seal, open, begin_seal, update, result, and the asynchronous -// async_make, async_seal and async_open, free and member; the free crypto::make, crypto::seal -// and crypto::open. -// - ChaCha20-Poly1305, aead: make, seal, open; the free crypto::make, crypto::seal and -// crypto::open. -// - P-256, curves::p256: basic_keypair::make, generate, sign (ecdsa_sha256, of a message and of -// a digest), agree; basic_public_key::make (both), verify (ecdsa_sha256, of a message and of -// a digest); crypto::verify (ecdsa_sha256, of a message and of a digest), to_der, from_der; -// decode_spki, decode_pkcs8; the free synchronous forms of the members, crypto::make (of a -// key pair and of a public key, both forms), crypto::generate, crypto::sign and crypto::agree, -// which enter their own guard before the member's; not guarded (no BearSSL call): public_key, -// secret, uncompressed, encode_spki, encode_pkcs8, basic_keypair's move constructor and move -// assignment, and normalize_low_s and is_low_s, which test/timing_test.cpp calls without a -// backend; and the asynchronous async_make, async_generate, async_sign and async_verify -// (ecdsa_sha256, of a message and of a digest) and async_agree, all but async_generate (which -// takes no input) also refused once before BearSSL, both free and as the members -// basic_keypair::async_make, async_generate, async_sign, async_agree and -// basic_public_key::async_verify, which the free ones call. +// async_from_key, async_seal and async_open, free (secret_key_encryption::aead's) and member; +// the free crypto::from_key, secret_key_encryption::aead::seal and +// secret_key_encryption::aead::open. +// - 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. +// - P-256, curves::p256: basic_keypair::from_secret, generate, sign (ecdsa_sha256, of a message and +// of a digest), agree; basic_public_key::from_bytes, from_coordinates, verify (ecdsa_sha256, of a +// message and of a digest); crypto::verify (ecdsa_sha256, of a message and of a digest), to_der, +// from_der; decode_spki, decode_pkcs8; the free synchronous forms of the members, +// crypto::from_secret, crypto::generate, crypto::sign and crypto::agree, which enter their own +// guard before the member's, and crypto::from_bytes, which holds none (the member's is its +// first); not guarded (no BearSSL call): public_key, secret, uncompressed, encode_spki, +// encode_pkcs8, basic_keypair's move constructor and move assignment, and normalize_low_s and +// is_low_s, which test/timing_test.cpp calls without a backend, and ecdsa_signature's +// from_bytes, member and free, and bytes; and the asynchronous +// async_from_secret, async_generate, async_sign and async_verify (ecdsa_sha256, of a message and +// of a digest) and async_agree, all but async_generate (which takes no input) also refused once +// before BearSSL, both free and as the members basic_keypair::async_from_secret, async_generate, +// async_sign, async_agree and basic_public_key::async_verify, which the free ones call. #include "support/timing_seam.hpp" @@ -82,36 +85,38 @@ void cover_ciphers() { "bearssl"); } -// P-256: the key pair's make and generate, the public key's two make, each refused once before +// P-256: the key pair's from_secret and generate, the public key's from_bytes and +// from_coordinates, each refused once before // BearSSL; the functions that copy what the key pair holds enter no guard. void cover_p256_keys() { namespace p256 = crypto::curves::p256; namespace data = webcpp::test::p256; using keypair = p256::basic_keypair; using public_key = p256::basic_public_key; - webcpp::test::covered("p256::basic_keypair::make on bearssl", - [] { BOOST_TEST(keypair::make(data::rfc6979_scalar).has_value()); }); - webcpp::test::covered("p256::basic_keypair::make of the order on bearssl", [] { - BOOST_TEST(keypair::make(data::order).error() == crypto::error::invalid_secret_key); + webcpp::test::covered("p256::basic_keypair::from_secret on bearssl", [] { + BOOST_TEST(keypair::from_secret(data::rfc6979_scalar).has_value()); + }); + webcpp::test::covered("p256::basic_keypair::from_secret of the order on bearssl", [] { + BOOST_TEST(keypair::from_secret(data::order).error() == crypto::error::invalid_secret_key); }); webcpp::test::covered("p256::basic_keypair::generate on bearssl", [] { BOOST_TEST(keypair::generate().has_value()); }); std::span const point(data::rfc6979_public); - webcpp::test::covered("p256::basic_public_key::make of a point on bearssl", - "basic_public_key::make", - [point] { BOOST_TEST(public_key::make(point).has_value()); }); + webcpp::test::covered("p256::basic_public_key::from_bytes of a point on bearssl", + "basic_public_key::from_bytes", + [point] { BOOST_TEST(public_key::from_bytes(point).has_value()); }); webcpp::test::covered( - "p256::basic_public_key::make of coordinates on bearssl", "basic_public_key::make", + "p256::basic_public_key::from_coordinates on bearssl", "basic_public_key::from_coordinates", [point] { - BOOST_TEST( - public_key::make(point.subspan<1, 32>(), point.subspan<33, 32>()).has_value()); + BOOST_TEST(public_key::from_coordinates(point.subspan<1, 32>(), point.subspan<33, 32>()) + .has_value()); }); - webcpp::test::covered("p256::basic_public_key::make of 64 bytes on bearssl", - "basic_public_key::make", [point] { - BOOST_TEST(public_key::make(point.first(64)).error() == + webcpp::test::covered("p256::basic_public_key::from_bytes of 64 bytes on bearssl", + "basic_public_key::from_bytes", [point] { + BOOST_TEST(public_key::from_bytes(point.first(64)).error() == crypto::error::invalid_public_key); }); - auto const made = keypair::make(data::rfc6979_scalar); + auto const made = keypair::from_secret(data::rfc6979_scalar); if (!BOOST_TEST(made.has_value())) { return; } @@ -133,15 +138,15 @@ void cover_p256_keypair_moves() { namespace p256 = crypto::curves::p256; namespace data = webcpp::test::p256; using keypair = p256::basic_keypair; - auto mover = keypair::make(data::rfc6979_scalar); + auto mover = keypair::from_secret(data::rfc6979_scalar); if (BOOST_TEST(mover.has_value())) { webcpp::test::uncovered("p256::basic_keypair move constructor on bearssl", [&mover] { keypair const taken = std::move(*mover); BOOST_TEST(taken.public_key().has_value()); }); } - auto target = keypair::make(data::rfc6979_scalar); - auto source = keypair::make(data::rfc6979_scalar); + auto target = keypair::from_secret(data::rfc6979_scalar); + auto source = keypair::from_secret(data::rfc6979_scalar); if (BOOST_TEST(target.has_value()) && BOOST_TEST(source.has_value())) { webcpp::test::uncovered("p256::basic_keypair move assignment on bearssl", [&target, &source] { @@ -157,7 +162,7 @@ void cover_p256_sign_moved_from(std::array const& digest) { namespace p256 = crypto::curves::p256; namespace data = webcpp::test::p256; using keypair = p256::basic_keypair; - auto source = keypair::make(data::rfc6979_scalar); + auto source = keypair::from_secret(data::rfc6979_scalar); if (BOOST_TEST(source.has_value())) { keypair const taken = std::move(*source); webcpp::test::covered( @@ -182,24 +187,29 @@ constexpr std::array p256_test_message{'t', 'e', 's', 't'}; void cover_p256_verify() { namespace p256 = crypto::curves::p256; namespace data = webcpp::test::p256; - auto const key = p256::basic_public_key::make(data::rfc6979_public); - if (!BOOST_TEST(key.has_value())) { + auto const key = p256::basic_public_key::from_bytes(data::rfc6979_public); + auto const test = p256::ecdsa_signature::from_bytes(data::rfc6979_test); + auto zero_r_bytes = data::rfc6979_test; + std::fill_n(zero_r_bytes.begin(), 32, std::uint8_t{0}); + auto const zero_r = p256::ecdsa_signature::from_bytes(zero_r_bytes); + if (!BOOST_TEST(key.has_value()) || !BOOST_TEST(test.has_value()) || + !BOOST_TEST(zero_r.has_value())) { return; } - webcpp::test::covered("p256 crypto::verify of a message on bearssl", "crypto::verify", [&key] { - BOOST_TEST(crypto::verify(crypto::ecdsa_sha256, data::rfc6979_test, p256_test_message, *key) - .has_value()); - }); - webcpp::test::covered("p256 crypto::verify of a digest on bearssl", "crypto::verify", [&key] { - BOOST_TEST(crypto::verify(crypto::ecdsa_sha256, data::rfc6979_test, - crypto::prehashed{p256_test_digest}, *key) - .has_value()); - }); - auto zero_r = data::rfc6979_test; - std::fill_n(zero_r.begin(), 32, std::uint8_t{0}); + webcpp::test::covered( + "p256 crypto::verify of a message on bearssl", "crypto::verify", [&key, &test] { + BOOST_TEST( + crypto::verify(crypto::ecdsa_sha256, *test, p256_test_message, *key).has_value()); + }); + webcpp::test::covered("p256 crypto::verify of a digest on bearssl", "crypto::verify", + [&key, &test] { + BOOST_TEST(crypto::verify(crypto::ecdsa_sha256, *test, + crypto::prehashed{p256_test_digest}, *key) + .has_value()); + }); webcpp::test::covered("p256 crypto::verify of r = 0 on bearssl", "crypto::verify", [&key, &zero_r] { - BOOST_TEST(crypto::verify(crypto::ecdsa_sha256, zero_r, + BOOST_TEST(crypto::verify(crypto::ecdsa_sha256, *zero_r, crypto::prehashed{p256_test_digest}, *key) .error() == crypto::error::invalid_signature); }); @@ -210,64 +220,64 @@ void cover_p256_verify() { void cover_p256_public_key_verify() { namespace p256 = crypto::curves::p256; namespace data = webcpp::test::p256; - auto const key = p256::basic_public_key::make(data::rfc6979_public); - if (!BOOST_TEST(key.has_value())) { + auto const key = p256::basic_public_key::from_bytes(data::rfc6979_public); + auto const test = p256::ecdsa_signature::from_bytes(data::rfc6979_test); + auto zero_r_bytes = data::rfc6979_test; + std::fill_n(zero_r_bytes.begin(), 32, std::uint8_t{0}); + auto const zero_r = p256::ecdsa_signature::from_bytes(zero_r_bytes); + if (!BOOST_TEST(key.has_value()) || !BOOST_TEST(test.has_value()) || + !BOOST_TEST(zero_r.has_value())) { return; } - webcpp::test::covered("p256::basic_public_key::verify of a message on bearssl", [&key] { - BOOST_TEST( - key->verify(crypto::ecdsa_sha256, data::rfc6979_test, p256_test_message).has_value()); + webcpp::test::covered("p256::basic_public_key::verify of a message on bearssl", [&key, &test] { + BOOST_TEST(key->verify(crypto::ecdsa_sha256, *test, p256_test_message).has_value()); }); - webcpp::test::covered("p256::basic_public_key::verify of a digest on bearssl", [&key] { - BOOST_TEST(key->verify(crypto::ecdsa_sha256, data::rfc6979_test, - crypto::prehashed{p256_test_digest}) + webcpp::test::covered("p256::basic_public_key::verify of a digest on bearssl", [&key, &test] { + BOOST_TEST(key->verify(crypto::ecdsa_sha256, *test, crypto::prehashed{p256_test_digest}) .has_value()); }); - auto zero_r = data::rfc6979_test; - std::fill_n(zero_r.begin(), 32, std::uint8_t{0}); webcpp::test::covered("p256::basic_public_key::verify of r = 0 on bearssl", [&key, &zero_r] { - BOOST_TEST(key->verify(crypto::ecdsa_sha256, zero_r, crypto::prehashed{p256_test_digest}) + BOOST_TEST(key->verify(crypto::ecdsa_sha256, *zero_r, crypto::prehashed{p256_test_digest}) .error() == crypto::error::invalid_signature); }); } -// P-256's free synchronous forms, crypto::make, crypto::generate, crypto::sign and +// P-256's free synchronous forms, crypto::from_secret, crypto::generate, crypto::sign and // crypto::agree, each entering its own guard before the member's, and refused once before -// BearSSL (the group order, a moved-from key pair). +// BearSSL (the group order, a moved-from key pair); crypto::from_bytes holds none, so the first +// guard it enters is the member's. void cover_p256_free_forms() { namespace p256 = crypto::curves::p256; namespace data = webcpp::test::p256; using keypair = p256::basic_keypair; - webcpp::test::covered("p256 crypto::make on bearssl", "crypto::make", [] { - BOOST_TEST(crypto::make(data::rfc6979_scalar).has_value()); - }); - webcpp::test::covered("p256 crypto::make of the order on bearssl", "crypto::make", [] { - BOOST_TEST(crypto::make(data::order).error() == crypto::error::invalid_secret_key); + webcpp::test::covered("p256 crypto::from_secret on bearssl", "crypto::from_secret", [] { + BOOST_TEST(crypto::from_secret(data::rfc6979_scalar).has_value()); }); + webcpp::test::covered("p256 crypto::from_secret of the order on bearssl", "crypto::from_secret", + [] { + BOOST_TEST(crypto::from_secret(data::order).error() == + crypto::error::invalid_secret_key); + }); using public_key = p256::basic_public_key; std::span const point(data::rfc6979_public); - webcpp::test::covered("p256 crypto::make of a public key on bearssl", "crypto::make", - [point] { BOOST_TEST(crypto::make(point).has_value()); }); webcpp::test::covered( - "p256 crypto::make of a public key's coordinates on bearssl", "crypto::make", [point] { - BOOST_TEST(crypto::make(point.subspan<1, 32>(), point.subspan<33, 32>()) - .has_value()); - }); - webcpp::test::covered("p256 crypto::make of a public key of 64 bytes on bearssl", - "crypto::make", [point] { - BOOST_TEST(crypto::make(point.first(64)).error() == + "p256 crypto::from_bytes of a public key on bearssl", "basic_public_key::from_bytes", + [point] { BOOST_TEST(crypto::from_bytes(point).has_value()); }); + webcpp::test::covered("p256 crypto::from_bytes of a public key of 64 bytes on bearssl", + "basic_public_key::from_bytes", [point] { + BOOST_TEST(crypto::from_bytes(point.first(64)).error() == crypto::error::invalid_public_key); }); webcpp::test::covered("p256 crypto::generate on bearssl", "crypto::generate", [] { BOOST_TEST(crypto::generate().has_value()); }); - auto made = keypair::make(data::rfc6979_scalar); - auto const peer = public_key::make(data::rfc6979_public); + auto made = keypair::from_secret(data::rfc6979_scalar); + auto const peer = public_key::from_bytes(data::rfc6979_public); if (!BOOST_TEST(made.has_value()) || !BOOST_TEST(peer.has_value())) { return; } webcpp::test::covered("p256 crypto::sign on bearssl", "crypto::sign", [&made] { auto const signature = crypto::sign(*made, crypto::ecdsa_sha256, p256_test_message); - BOOST_TEST(signature.has_value() && *signature == data::rfc6979_test); + BOOST_TEST(signature.has_value() && signature->bytes() == data::rfc6979_test); }); webcpp::test::covered("p256 crypto::agree on bearssl", "crypto::agree", [&made, &peer] { BOOST_TEST(crypto::agree(*made, *peer).has_value()); }); @@ -289,20 +299,24 @@ void cover_p256_der() { namespace p256 = crypto::curves::p256; namespace data = webcpp::test::p256; std::array der{}; - webcpp::test::covered("p256::to_der on bearssl", [&der] { - BOOST_TEST(p256::to_der(data::rfc6979_test, der).has_value()); + auto const test = p256::ecdsa_signature::from_bytes(data::rfc6979_test); + if (!BOOST_TEST(test.has_value())) { + return; + } + webcpp::test::covered("p256::to_der on bearssl", [&der, &test] { + BOOST_TEST(p256::to_der(*test, der).has_value()); }); - webcpp::test::covered("p256::to_der into 71 bytes on bearssl", [&der] { - BOOST_TEST(p256::to_der(data::rfc6979_test, std::span(der).first(71)).error() == + webcpp::test::covered("p256::to_der into 71 bytes on bearssl", [&der, &test] { + BOOST_TEST(p256::to_der(*test, std::span(der).first(71)).error() == crypto::error::invalid_input_size); }); - auto const encoded = p256::to_der(data::rfc6979_test, der); + auto const encoded = p256::to_der(*test, der); if (!BOOST_TEST(encoded.has_value())) { return; } - webcpp::test::covered("p256::from_der on bearssl", [&der, &encoded] { + webcpp::test::covered("p256::from_der on bearssl", [&der, &encoded, &test] { auto const decoded = p256::from_der(std::span(der).first(*encoded)); - BOOST_TEST(decoded.has_value() && *decoded == data::rfc6979_test); + BOOST_TEST(decoded.has_value() && *decoded == *test); }); webcpp::test::covered("p256::from_der of nothing on bearssl", [] { BOOST_TEST(p256::from_der({}).error() == crypto::error::invalid_signature); @@ -314,26 +328,27 @@ void cover_p256_der() { void cover_p256_ecdsa() { namespace p256 = crypto::curves::p256; namespace data = webcpp::test::p256; - auto const made = p256::basic_keypair::make(data::rfc6979_scalar); + auto const made = p256::basic_keypair::from_secret(data::rfc6979_scalar); if (!BOOST_TEST(made.has_value())) { return; } webcpp::test::covered( "p256::basic_keypair::sign of a message on bearssl", "p256::basic_keypair::sign", [&made] { auto const signature = made->sign(crypto::ecdsa_sha256, p256_test_message); - BOOST_TEST(signature.has_value() && *signature == data::rfc6979_test); + BOOST_TEST(signature.has_value() && signature->bytes() == data::rfc6979_test); }); webcpp::test::covered( "p256::basic_keypair::sign of a digest on bearssl", "p256::basic_keypair::sign", [&made] { auto const signature = made->sign(crypto::ecdsa_sha256, crypto::prehashed{p256_test_digest}); - BOOST_TEST(signature.has_value() && *signature == data::rfc6979_test); + BOOST_TEST(signature.has_value() && signature->bytes() == data::rfc6979_test); }); cover_p256_sign_moved_from(p256_test_digest); cover_p256_verify(); cover_p256_public_key_verify(); cover_p256_free_forms(); cover_p256_der(); + webcpp::test::cover_signature("p256::ecdsa_signature", "bearssl"); } // P-256's ECDH: the shared x of RFC 6979's key with its own public key, and the same call on a @@ -343,8 +358,8 @@ void cover_p256_ecdh() { namespace data = webcpp::test::p256; using keypair = p256::basic_keypair; using public_key = p256::basic_public_key; - auto made = keypair::make(data::rfc6979_scalar); - auto const peer = public_key::make(data::rfc6979_public); + auto made = keypair::from_secret(data::rfc6979_scalar); + auto const peer = public_key::from_bytes(data::rfc6979_public); if (!BOOST_TEST(made.has_value()) || !BOOST_TEST(peer.has_value())) { return; } @@ -358,13 +373,13 @@ void cover_p256_ecdh() { } // P-256's formats: the decoders, with an encoding each and one refused before BearSSL, inside -// their own guards (make's, which they call, is entered after theirs); the encoders copy what the -// key and the key pair hold and enter no guard. +// their own guards (from_secret's and from_bytes', which they call, are entered after theirs); the +// encoders copy what the key and the key pair hold and enter no guard. void cover_p256_formats() { namespace p256 = crypto::curves::p256; namespace data = webcpp::test::p256; using keypair = p256::basic_keypair; - auto const made = keypair::make(data::rfc6979_scalar); + auto const made = keypair::from_secret(data::rfc6979_scalar); if (!BOOST_TEST(made.has_value())) { return; } @@ -393,7 +408,7 @@ void cover_p256_formats() { } // P-256's asynchronous functions, each with valid input and with input refused before BearSSL (a -// scalar of 31 bytes, a signature of 63 bytes, a moved-from key pair), an io_context run after +// scalar of 31 bytes, a signature whose r is 0, a moved-from key pair), an io_context run after // each call so that its completion is delivered. The first guard each enters is its own (the // synchronous call it makes holds others, which run after). void cover_async_p256() { @@ -401,7 +416,7 @@ void cover_async_p256() { namespace data = webcpp::test::p256; using keypair = p256::basic_keypair; using public_key = p256::basic_public_key; - using signature_type = std::array; + using signature_type = p256::ecdsa_signature; webcpp::asio::io_context context; auto const executor = context.get_executor(); std::array const message{1, 2, 3}; @@ -419,13 +434,14 @@ void cover_async_p256() { context.restart(); context.run(); // lint-run: the test's event loop }; - webcpp::test::covered("p256::async_make on bearssl", "crypto::async_make", [&] { - crypto::async_make(executor, data::rfc6979_scalar, counted); - deliver(); - }); - webcpp::test::covered("p256::async_make with a short scalar on bearssl", "crypto::async_make", - [&] { - crypto::async_make( + webcpp::test::covered( + "p256 crypto::async_from_secret on bearssl", "crypto::async_from_secret", [&] { + crypto::async_from_secret(executor, data::rfc6979_scalar, counted); + deliver(); + }); + webcpp::test::covered("p256 crypto::async_from_secret with a short scalar on bearssl", + "crypto::async_from_secret", [&] { + crypto::async_from_secret( executor, std::span(data::rfc6979_scalar).first(31), counted); deliver(); }); @@ -433,21 +449,28 @@ void cover_async_p256() { crypto::async_generate(executor, counted); deliver(); }); - webcpp::test::covered("p256::basic_keypair::async_make on bearssl", [&] { - keypair::async_make(executor, data::rfc6979_scalar, counted); - deliver(); - }); - webcpp::test::covered("p256::basic_keypair::async_make with a short scalar on bearssl", [&] { - keypair::async_make(executor, std::span(data::rfc6979_scalar).first(31), counted); + webcpp::test::covered("p256::basic_keypair::async_from_secret on bearssl", [&] { + keypair::async_from_secret(executor, data::rfc6979_scalar, counted); deliver(); }); + webcpp::test::covered("p256::basic_keypair::async_from_secret with a short scalar on bearssl", + [&] { + keypair::async_from_secret( + executor, std::span(data::rfc6979_scalar).first(31), counted); + deliver(); + }); webcpp::test::covered("p256::basic_keypair::async_generate on bearssl", [&] { keypair::async_generate(executor, counted); deliver(); }); - auto made = keypair::make(data::rfc6979_scalar); - auto const key = public_key::make(data::rfc6979_public); - if (!BOOST_TEST(made.has_value()) || !BOOST_TEST(key.has_value())) { + auto made = keypair::from_secret(data::rfc6979_scalar); + auto const key = public_key::from_bytes(data::rfc6979_public); + auto const rfc_test = signature_type::from_bytes(data::rfc6979_test); + auto zero_r_bytes = data::rfc6979_test; + std::fill_n(zero_r_bytes.begin(), 32, std::uint8_t{0}); + auto const zero_r = signature_type::from_bytes(zero_r_bytes); + if (!BOOST_TEST(made.has_value()) || !BOOST_TEST(key.has_value()) || + !BOOST_TEST(rfc_test.has_value()) || !BOOST_TEST(zero_r.has_value())) { return; } webcpp::test::covered("p256::async_sign on bearssl", "crypto::async_sign", [&] { @@ -464,13 +487,12 @@ void cover_async_p256() { deliver(); }); webcpp::test::covered("p256::async_verify of a digest on bearssl", "crypto::async_verify", [&] { - crypto::async_verify(executor, crypto::ecdsa_sha256, data::rfc6979_test, + crypto::async_verify(executor, crypto::ecdsa_sha256, *rfc_test, crypto::prehashed{p256_test_digest}, *key, counted); deliver(); }); - webcpp::test::covered("p256::async_verify of 63 bytes on bearssl", "crypto::async_verify", [&] { - crypto::async_verify(executor, crypto::ecdsa_sha256, std::span(kept).first(63), message, - *key, counted); + webcpp::test::covered("p256::async_verify of r = 0 on bearssl", "crypto::async_verify", [&] { + crypto::async_verify(executor, crypto::ecdsa_sha256, *zero_r, message, *key, counted); deliver(); }); webcpp::test::covered("p256::async_agree on bearssl", "crypto::async_agree", [&] { @@ -491,13 +513,12 @@ void cover_async_p256() { deliver(); }); webcpp::test::covered("p256::basic_public_key::async_verify of a digest on bearssl", [&] { - key->async_verify(executor, crypto::ecdsa_sha256, data::rfc6979_test, + key->async_verify(executor, crypto::ecdsa_sha256, *rfc_test, crypto::prehashed{p256_test_digest}, counted); deliver(); }); - webcpp::test::covered("p256::basic_public_key::async_verify of 63 bytes on bearssl", [&] { - key->async_verify(executor, crypto::ecdsa_sha256, std::span(kept).first(63), message, - counted); + webcpp::test::covered("p256::basic_public_key::async_verify of r = 0 on bearssl", [&] { + key->async_verify(executor, crypto::ecdsa_sha256, *zero_r, message, counted); deliver(); }); webcpp::test::covered("p256::basic_keypair::async_agree on bearssl", [&] { diff --git a/test/timing_coverage_ctaes_test.cpp b/test/timing_coverage_ctaes_test.cpp index 537d5fb1..9cad2554 100644 --- a/test/timing_coverage_ctaes_test.cpp +++ b/test/timing_coverage_ctaes_test.cpp @@ -12,7 +12,7 @@ // its own guard fails although it calls another guarded function. // // What it covers, by family; a family ctaes gains adds its line and its checks: -// - The AES block cipher, aes128, aes192 and aes256: make; basic_aes: encrypt, decrypt. +// - The AES block cipher, aes128, aes192 and aes256: from_key; basic_aes: encrypt, decrypt. #include "support/timing_seam.hpp" diff --git a/test/timing_coverage_openssl_test.cpp b/test/timing_coverage_openssl_test.cpp index 498da6db..ebb39f4a 100644 --- a/test/timing_coverage_openssl_test.cpp +++ b/test/timing_coverage_openssl_test.cpp @@ -12,13 +12,15 @@ // its own guard fails although it calls another guarded function. // // What it covers, by family; a family OpenSSL gains adds its line and its checks: -// - The AES block cipher, aes128, aes192 and aes256: make; basic_aes: encrypt, decrypt. -// - AES-GCM, gcm, gcm and gcm: make, the move constructor and move +// - The AES block cipher, aes128, aes192 and aes256: from_key; basic_aes: encrypt, decrypt. +// - AES-GCM, gcm, gcm and gcm: from_key, the move constructor and move // assignment (ruling R3), seal, open, begin_seal, update, result, and the asynchronous -// async_make, async_seal and async_open, free and member; the free crypto::make, crypto::seal -// and crypto::open. -// - ChaCha20-Poly1305, aead: make, seal, open; the free crypto::make, crypto::seal and -// crypto::open. +// async_from_key, async_seal and async_open, free (secret_key_encryption::aead's) and member; +// the free crypto::from_key, secret_key_encryption::aead::seal and +// secret_key_encryption::aead::open. +// - 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. #include "support/timing_seam.hpp" diff --git a/test/timing_coverage_secp256k1_test.cpp b/test/timing_coverage_secp256k1_test.cpp index a28deb1a..dbc9afd7 100644 --- a/test/timing_coverage_secp256k1_test.cpp +++ b/test/timing_coverage_secp256k1_test.cpp @@ -8,11 +8,10 @@ // leaves the thread's DIT as it found it, on every target, also where DIT does not apply, each // with valid input and, where it has one, with input refused before the backend // (support/timing_coverage.hpp). One section per header. With exceptions, a memory resource that -// throws in basic_keypair::make and decode_pkcs8 unwinds through the guard, which leaves DIT clear -// from clear and set from set. -// A check fails, naming itself, when its call enters no guard or when the first guard it enters is -// not the one of the function it names (support/timing_seam.hpp), so that a function that forgot -// its own guard fails although it calls another guarded function. +// throws in basic_keypair::from_secret and decode_pkcs8 unwinds through the guard, which leaves DIT +// clear from clear and set from set. A check fails, naming itself, when its call enters no guard or +// when the first guard it enters is not the one of the function it names (support/timing_seam.hpp), +// so that a function that forgot its own guard fails although it calls another guarded function. // The key pair's sign overloads share one name: the hedged one and the one with Schnorr's // randomness given are named with a parameter word, sign(ecdsa_sha256_t and sign(schnorr_t, which // clang and GCC print only for those overloads (the generic one prints its parameter as Scheme); @@ -20,26 +19,30 @@ // generic one too, and the check only proves that a guard of some sign was entered first. // // What it covers, by family; a family libsecp256k1 gains adds its line and its checks: -// - secp256k1, curves/secp256k1.hpp: public_key's make, compressed, uncompressed, xonly, -// operator== and operator<=>; basic_keypair: make, public_key, secret, sign with each scheme -// (ecdsa_sha256 of a message and of a digest, ecdsa_sha256_recoverable, schnorr with its -// auxiliary randomness drawn), sign hedged, sign with Schnorr's auxiliary randomness given, -// agree, agree_hashed, agree_point, tweak_xonly; public_key::verify of ecdsa_sha256 and of -// schnorr; the free recover, crypto::verify of ecdsa_sha256 and of schnorr (against the typed -// key and against x-only bytes), to_der, from_der, normalize_low_s, is_low_s, tweak_xonly; the -// free synchronous forms of the members, crypto::make (of a key pair and of a public key), -// crypto::generate, crypto::sign (with each scheme, Schnorr's randomness drawn and given, and -// hedged) and crypto::agree, which enter their own guard before the member's. Its -// formats: encode_spki, decode_spki, encode_pkcs8, decode_pkcs8. Its tweaks: seckey_tweak_add, -// seckey_tweak_mul, seckey_negate, pubkey_tweak_add, pubkey_tweak_mul, pubkey_negate, -// pubkey_combine. +// - secp256k1, curves/secp256k1.hpp: public_key's from_bytes, compressed, uncompressed, xonly, +// operator== and operator<=>; basic_keypair: from_secret, public_key, secret, sign with each scheme +// (ecdsa_sha256 of a message and of a digest, ecdsa_sha256_recoverable, ecdsa_keccak256_recoverable +// of a message and of a digest, schnorr with its auxiliary randomness drawn), sign hedged, sign +// with Schnorr's auxiliary randomness given, agree, agree_hashed, agree_point, tweak_xonly; +// public_key::verify of ecdsa_sha256 and of schnorr; the free recover of each recoverable scheme, +// of a message and of a digest, crypto::verify of ecdsa_sha256 and of schnorr (against the typed +// key and against x-only bytes), to_der, from_der, normalize_low_s, is_low_s, tweak_xonly; the free +// synchronous forms of the members, crypto::from_secret, crypto::generate, crypto::sign (with each +// scheme, Keccak-256's of a message and of a digest, Schnorr's randomness drawn and given, and +// hedged) and crypto::agree, which enter their own guard before the member's, and +// crypto::from_bytes of a public key, which holds none (the member's is its first). Not guarded (no +// libsecp256k1 call): ecdsa_signature's, recoverable_signature's and schnorr_signature's +// from_bytes, member and free, and bytes, and recoverable_signature's recovery_id. Its formats: +// encode_spki, decode_spki, encode_pkcs8, decode_pkcs8. Its tweaks: secret_key_tweak_add, +// secret_key_tweak_mul, secret_key_negate, public_key_tweak_add, public_key_tweak_mul, +// public_key_negate, public_key_combine. // - ElligatorSwift: ellswift_encode, ellswift_decode, ellswift_create, ellswift_xdh. // - MuSig2, a whole round of two signers: aggregate_key's xonly_public_key, full_public_key, -// tweak_add, tweak_xonly_add; the free key_aggregate, nonce_gen, nonce_aggregate, +// tweak_add, tweak_xonly_add; the free key_aggregate, generate_nonce, nonce_aggregate, // nonce_process, partial_sign, partial_signature_verify, partial_signature_aggregate, and the // parse and serialize of the public nonce, the aggregate nonce and the partial signature. // - BIP 352 silent payments, a payment created and scanned: create_label, -// create_labeled_spend_key, create_outputs, make_prevouts_summary, scan_outputs. +// create_labeled_spend_key, create_outputs, make_previous_outputs_summary, scan_outputs. #include "support/timing_seam.hpp" @@ -96,7 +99,7 @@ bytes32 secret_bytes(std::uint8_t fill) { /** The key pair of the secret key of 32 bytes `fill`, made outside a check. */ secp::keypair keypair_of(std::uint8_t fill) { - auto made = secp::keypair::make(secret_bytes(fill)); + auto made = secp::keypair::from_secret(secret_bytes(fill)); if (!BOOST_TEST(made.has_value())) { std::exit(boost::report_errors()); } @@ -135,15 +138,15 @@ std::vector lent(std::size_t size) { // --------------------------------------------------------------------------------------------- /** - * basic_keypair::make, a secret of the wrong size included, generate, and public_key's two + * basic_keypair::from_secret, a secret of the wrong size included, generate, and public_key's two * operators. */ void cover_make_and_compare() { auto const secret_key = secret_bytes(0x11); - covered("secp256k1::basic_keypair::make on secp256k1", - [&] { BOOST_TEST(secp::keypair::make(secret_key).has_value()); }); - covered("secp256k1::basic_keypair::make with a short secret on secp256k1", [&] { - BOOST_TEST(secp::keypair::make(std::span(secret_key).first(31)).error() == + covered("secp256k1::basic_keypair::from_secret on secp256k1", + [&] { BOOST_TEST(secp::keypair::from_secret(secret_key).has_value()); }); + covered("secp256k1::basic_keypair::from_secret with a short secret on secp256k1", [&] { + BOOST_TEST(secp::keypair::from_secret(std::span(secret_key).first(31)).error() == crypto::error::invalid_key_size); }); // The system's source answers here; the refused draws are secp256k1_generate's, the program @@ -174,6 +177,14 @@ void cover_keypair_signing() { [&] { BOOST_TEST(made.sign(crypto::ecdsa_sha256, digest).has_value()); }); covered("secp256k1::basic_keypair::sign with ecdsa_sha256_recoverable on secp256k1", [&] { BOOST_TEST(made.sign(crypto::ecdsa_sha256_recoverable, digest).has_value()); }); + covered( + "secp256k1::basic_keypair::sign with ecdsa_keccak256_recoverable of a message on secp256k1", + "secp256k1::basic_keypair::sign", + [&] { BOOST_TEST(made.sign(crypto::ecdsa_keccak256_recoverable, hash).has_value()); }); + covered( + "secp256k1::basic_keypair::sign with ecdsa_keccak256_recoverable of a digest on secp256k1", + "secp256k1::basic_keypair::sign", + [&] { BOOST_TEST(made.sign(crypto::ecdsa_keccak256_recoverable, digest).has_value()); }); covered("secp256k1::basic_keypair::sign with schnorr, its randomness drawn, on secp256k1", [&] { BOOST_TEST(made.sign(crypto::schnorr, hash).has_value()); }); covered("secp256k1::basic_keypair::sign hedged on secp256k1", @@ -207,6 +218,13 @@ void cover_keypair_signing_moved_from() { BOOST_TEST(empty.sign(crypto::ecdsa_sha256_recoverable, digest).error() == crypto::error::invalid_state); }); + covered( + "secp256k1::basic_keypair::sign with ecdsa_keccak256_recoverable moved from on " + "secp256k1", + "secp256k1::basic_keypair::sign", [&] { + BOOST_TEST(empty.sign(crypto::ecdsa_keccak256_recoverable, hash).error() == + crypto::error::invalid_state); + }); covered("secp256k1::basic_keypair::sign with schnorr moved from on secp256k1", [&] { BOOST_TEST(empty.sign(crypto::schnorr, hash).error() == crypto::error::invalid_state); }); @@ -249,14 +267,14 @@ void cover_keypair_agreement() { [&] { BOOST_TEST(empty.tweak_xonly(tweak).error() == crypto::error::invalid_state); }); } -/** public_key::make, a key of the wrong size included, and the key's three byte forms. */ +/** public_key::from_bytes, a key of the wrong size included, and the key's three byte forms. */ void cover_public_keys() { auto const parsed = public_of(keypair_of(0x41)); auto const encoded = parsed.compressed(); - covered("secp256k1::public_key::make on secp256k1", - [&] { BOOST_TEST(secp::public_key::make(encoded).has_value()); }); - covered("secp256k1::public_key::make of a short key on secp256k1", [&] { - BOOST_TEST(secp::public_key::make(std::span(encoded).first(32)).error() == + covered("secp256k1::public_key::from_bytes on secp256k1", + [&] { BOOST_TEST(secp::public_key::from_bytes(encoded).has_value()); }); + covered("secp256k1::public_key::from_bytes of a short key on secp256k1", [&] { + BOOST_TEST(secp::public_key::from_bytes(std::span(encoded).first(32)).error() == crypto::error::invalid_public_key); }); covered("secp256k1::public_key::compressed on secp256k1", @@ -314,13 +332,53 @@ void cover_verification() { BOOST_TEST(crypto::verify(crypto::schnorr, *schnorr, hash, not_a_key).error() == crypto::error::invalid_public_key); }); - (*recoverable)[64] = 4; + auto id_of_four = recoverable->bytes(); + id_of_four[64] = 4; + auto const bad_id = secp::recoverable_signature::from_bytes(id_of_four); + if (!BOOST_TEST(bad_id.has_value())) { + return; + } covered("secp256k1::recover with a recovery id of 4 on secp256k1", [&] { - BOOST_TEST(secp::recover(crypto::ecdsa_sha256_recoverable, *recoverable, hash).error() == + BOOST_TEST(secp::recover(crypto::ecdsa_sha256_recoverable, *bad_id, hash).error() == crypto::error::invalid_signature); }); } +/** recover of Ethereum's scheme, of a message and of a digest, and with a recovery id of 4. */ +void cover_ethereum_recovery() { + auto const signer = keypair_of(0x53); + bytes32 const hash = secret_bytes(0x5c); + crypto::prehashed const digest{hash}; + auto const keccak = signer.sign(crypto::ecdsa_keccak256_recoverable, hash); + if (!BOOST_TEST(keccak.has_value())) { + return; + } + auto id_of_four = keccak->bytes(); + id_of_four[64] = 4; + auto const bad_id = secp::recoverable_signature::from_bytes(id_of_four); + if (!BOOST_TEST(bad_id.has_value())) { + return; + } + covered("secp256k1::recover with ecdsa_keccak256_recoverable of a message on secp256k1", + "secp256k1::recover(ecdsa_keccak256_recoverable_t", [&] { + BOOST_TEST( + secp::recover(crypto::ecdsa_keccak256_recoverable, *keccak, hash).has_value()); + }); + covered( + "secp256k1::recover with ecdsa_keccak256_recoverable of a digest on secp256k1", + "secp256k1::recover(ecdsa_keccak256_recoverable_t", [&] { + BOOST_TEST( + secp::recover(crypto::ecdsa_keccak256_recoverable, *keccak, digest).has_value()); + }); + covered( + "secp256k1::recover with ecdsa_keccak256_recoverable and a recovery id of 4 on " + "secp256k1", + "secp256k1::recover(ecdsa_keccak256_recoverable_t", [&] { + BOOST_TEST(secp::recover(crypto::ecdsa_keccak256_recoverable, *bad_id, hash).error() == + crypto::error::invalid_signature); + }); +} + /** public_key::verify of both its schemes, each of a signature that does not verify too. */ void cover_public_key_verify() { auto const signer = keypair_of(0x52); @@ -332,43 +390,53 @@ void cover_public_key_verify() { !BOOST_TEST(ecdsa.has_value())) { return; } + // The other scheme's signature, its bytes made into this scheme's type: it does not verify. + auto const schnorr_as_ecdsa = secp::ecdsa_signature::from_bytes(schnorr->bytes()); + auto const ecdsa_as_schnorr = secp::schnorr_signature::from_bytes(ecdsa->bytes()); + if (!BOOST_TEST(schnorr_as_ecdsa.has_value()) || !BOOST_TEST(ecdsa_as_schnorr.has_value())) { + return; + } covered("secp256k1::public_key::verify of ecdsa_sha256 on secp256k1", [&] { BOOST_TEST(public_key->verify(crypto::ecdsa_sha256, *ecdsa, hash).has_value()); }); covered("secp256k1::public_key::verify of schnorr on secp256k1", [&] { BOOST_TEST(public_key->verify(crypto::schnorr, *schnorr, hash).has_value()); }); covered("secp256k1::public_key::verify of ecdsa_sha256 of another signature on secp256k1", [&] { - BOOST_TEST(public_key->verify(crypto::ecdsa_sha256, *schnorr, hash).error() == + BOOST_TEST(public_key->verify(crypto::ecdsa_sha256, *schnorr_as_ecdsa, hash).error() == crypto::error::invalid_signature); }); covered("secp256k1::public_key::verify of schnorr of another signature on secp256k1", [&] { - BOOST_TEST(public_key->verify(crypto::schnorr, *ecdsa, hash).error() == + BOOST_TEST(public_key->verify(crypto::schnorr, *ecdsa_as_schnorr, hash).error() == crypto::error::invalid_signature); }); } /** - * The free crypto::make, of a key pair and of a public key, and crypto::generate, each entering - * its own guard before the member's, and refused once before the backend (a short secret, a short - * key). + * The free crypto::from_secret and crypto::generate, each entering its own guard before the + * member's, and crypto::from_bytes of a public key, which holds none, so that the member's is the + * first it enters; each refused once before the backend (a short secret, a short key). */ -void cover_free_make_forms() { +void cover_free_factories() { auto const secret_key = secret_bytes(0x61); - covered("secp256k1 crypto::make on secp256k1", "crypto::make", - [&] { BOOST_TEST(crypto::make(secret_key).has_value()); }); - covered("secp256k1 crypto::make with a short secret on secp256k1", "crypto::make", [&] { - BOOST_TEST(crypto::make(std::span(secret_key).first(31)).error() == - crypto::error::invalid_key_size); - }); + covered("secp256k1 crypto::from_secret on secp256k1", "crypto::from_secret", + [&] { BOOST_TEST(crypto::from_secret(secret_key).has_value()); }); + covered("secp256k1 crypto::from_secret with a short secret on secp256k1", "crypto::from_secret", + [&] { + BOOST_TEST( + crypto::from_secret(std::span(secret_key).first(31)).error() == + crypto::error::invalid_key_size); + }); covered("secp256k1 crypto::generate on secp256k1", "crypto::generate", [&] { BOOST_TEST(crypto::generate().has_value()); }); auto const encoded = public_of(keypair_of(0x64)).compressed(); - covered("secp256k1 crypto::make of a public key on secp256k1", "crypto::make", - [&] { BOOST_TEST(crypto::make(encoded).has_value()); }); - covered("secp256k1 crypto::make of a short public key on secp256k1", "crypto::make", [&] { - BOOST_TEST(crypto::make(std::span(encoded).first(32)).error() == - crypto::error::invalid_public_key); - }); + covered("secp256k1 crypto::from_bytes of a public key on secp256k1", "public_key::from_bytes", + [&] { BOOST_TEST(crypto::from_bytes(encoded).has_value()); }); + covered( + "secp256k1 crypto::from_bytes of a short public key on secp256k1", "public_key::from_bytes", + [&] { + BOOST_TEST(crypto::from_bytes(std::span(encoded).first(32)).error() == + crypto::error::invalid_public_key); + }); } /** @@ -392,6 +460,17 @@ void cover_free_forms() { [&] { BOOST_TEST(crypto::sign(made, crypto::ecdsa_sha256_recoverable, hash).has_value()); }); + covered( + "secp256k1 crypto::sign with ecdsa_keccak256_recoverable of a message on secp256k1", + "crypto::sign", [&] { + BOOST_TEST(crypto::sign(made, crypto::ecdsa_keccak256_recoverable, hash).has_value()); + }); + covered("secp256k1 crypto::sign with ecdsa_keccak256_recoverable of a digest on secp256k1", + "crypto::sign", [&] { + BOOST_TEST( + crypto::sign(made, crypto::ecdsa_keccak256_recoverable, crypto::prehashed{hash}) + .has_value()); + }); covered("secp256k1 crypto::sign with schnorr, its randomness drawn, on secp256k1", "crypto::sign", [&] { BOOST_TEST(crypto::sign(made, crypto::schnorr, hash).has_value()); }); @@ -449,7 +528,7 @@ void cover_low_s() { if (!BOOST_TEST(ecdsa.has_value())) { return; } - std::array const zero_signature{}; + secp::ecdsa_signature const zero_signature{}; covered("secp256k1::normalize_low_s on secp256k1", [&] { BOOST_TEST(secp::normalize_low_s(*ecdsa).has_value()); }); covered("secp256k1::is_low_s on secp256k1", [&] { BOOST_TEST(secp::is_low_s(*ecdsa)); }); @@ -511,7 +590,7 @@ void cover_ellswift() { /** * SPKI and PKCS#8, each refused once before the backend too: the decoders call equal, and - * decode_pkcs8 also make and encode_pkcs8, so only their refusals show their own guards. + * decode_pkcs8 also from_secret and encode_pkcs8, so only their refusals show their own guards. */ void cover_formats() { auto const made = keypair_of(0x81); @@ -660,7 +739,7 @@ struct musig_round { }; /** - * MuSig2's first round, as secp256k1_musig_test.cpp builds it: nonce_gen, of a moved-from key + * MuSig2's first round, as secp256k1_musig_test.cpp builds it: generate_nonce, of a moved-from key * pair too, and nonce_aggregate, of no nonce too. * * @param round The round, whose aggregate key is made. @@ -668,18 +747,18 @@ struct musig_round { */ bool cover_musig_nonces(musig_round& round) { auto const empty = moved_from(); - covered("musig::nonce_gen on secp256k1", [&] { - auto made = musig::nonce_gen(round.alice, *round.aggregate, round.message); + covered("musig::generate_nonce on secp256k1", [&] { + auto made = musig::generate_nonce(round.alice, *round.aggregate, round.message); if (BOOST_TEST(made.has_value())) { round.alice_nonce.emplace(std::move(*made)); } }); - covered("musig::nonce_gen moved from on secp256k1", [&] { - BOOST_TEST(musig::nonce_gen(empty, *round.aggregate, round.message).error() == + covered("musig::generate_nonce moved from on secp256k1", [&] { + BOOST_TEST(musig::generate_nonce(empty, *round.aggregate, round.message).error() == crypto::error::invalid_state); }); - auto bob_nonce = musig::nonce_gen(round.bob, *round.aggregate, round.message); - auto spare_nonce = musig::nonce_gen(round.bob, *round.aggregate, round.message); + auto bob_nonce = musig::generate_nonce(round.bob, *round.aggregate, round.message); + auto spare_nonce = musig::generate_nonce(round.bob, *round.aggregate, round.message); if (!round.alice_nonce || !BOOST_TEST(bob_nonce.has_value()) || !BOOST_TEST(spare_nonce.has_value())) { return false; @@ -822,7 +901,7 @@ struct silent_payment { /** The output the sender made. */ std::array outputs{}; /** The summary of the sender's inputs, which the recipient scans with. */ - std::optional summary; + std::optional summary; }; /** @@ -856,7 +935,7 @@ bool cover_silent_payment_labels(silent_payment& payment) { /** * Sending: create_outputs to the labelled address, to no recipient too, and - * make_prevouts_summary of the sender's key, of no input too. + * make_previous_outputs_summary of the sender's key, of no input too. * * @param payment The payment, whose labelled spend key is made. * @return Whether the output and the summary are made. @@ -879,16 +958,16 @@ bool cover_silent_payment_sending(silent_payment& payment) { }); std::array const sender_keys{public_of(payment.sender)}; auto summary_space = lent(sp::summary_workspace_size(0, 1)); - covered("silent_payments::make_prevouts_summary on secp256k1", [&] { + covered("silent_payments::make_previous_outputs_summary on secp256k1", [&] { auto const made = - sp::make_prevouts_summary(payment.outpoint, {}, sender_keys, summary_space); + sp::make_previous_outputs_summary(payment.outpoint, {}, sender_keys, summary_space); if (BOOST_TEST(made.has_value())) { payment.summary = *made; } }); - covered("silent_payments::make_prevouts_summary of no input on secp256k1", [&] { - BOOST_TEST(sp::make_prevouts_summary(payment.outpoint, {}, std::span(sender_keys).first(0), - summary_space) + covered("silent_payments::make_previous_outputs_summary of no input on secp256k1", [&] { + BOOST_TEST(sp::make_previous_outputs_summary(payment.outpoint, {}, + std::span(sender_keys).first(0), summary_space) .error() == crypto::error::invalid_input_size); }); return payment.summary.has_value(); @@ -939,7 +1018,7 @@ void cover_silent_payments() { // curves/secp256k1/tweak.hpp. // --------------------------------------------------------------------------------------------- -/** The tweaks, negations and combination of keys, and pubkey_combine refused. */ +/** The tweaks, negations and combination of keys, and public_key_combine refused. */ void cover_tweaks() { bytes32 const secret_key = secret_bytes(0xb1); bytes32 const tweak = secret_bytes(0x0b); @@ -947,25 +1026,25 @@ void cover_tweaks() { public_of(keypair_of(0xb2)), public_of(keypair_of(0xb3)), }; - covered("secp256k1::seckey_tweak_add on secp256k1", - [&] { BOOST_TEST(secp::seckey_tweak_add(secret_key, tweak).has_value()); }); - covered("secp256k1::seckey_tweak_mul on secp256k1", - [&] { BOOST_TEST(secp::seckey_tweak_mul(secret_key, tweak).has_value()); }); - covered("secp256k1::seckey_negate on secp256k1", - [&] { BOOST_TEST(secp::seckey_negate(secret_key).has_value()); }); - covered("secp256k1::pubkey_tweak_add on secp256k1", - [&] { BOOST_TEST(secp::pubkey_tweak_add(keys[0], tweak).has_value()); }); - covered("secp256k1::pubkey_tweak_mul on secp256k1", - [&] { BOOST_TEST(secp::pubkey_tweak_mul(keys[0], tweak).has_value()); }); + covered("secp256k1::secret_key_tweak_add on secp256k1", + [&] { BOOST_TEST(secp::secret_key_tweak_add(secret_key, tweak).has_value()); }); + covered("secp256k1::secret_key_tweak_mul on secp256k1", + [&] { BOOST_TEST(secp::secret_key_tweak_mul(secret_key, tweak).has_value()); }); + covered("secp256k1::secret_key_negate on secp256k1", + [&] { BOOST_TEST(secp::secret_key_negate(secret_key).has_value()); }); + covered("secp256k1::public_key_tweak_add on secp256k1", + [&] { BOOST_TEST(secp::public_key_tweak_add(keys[0], tweak).has_value()); }); + covered("secp256k1::public_key_tweak_mul on secp256k1", + [&] { BOOST_TEST(secp::public_key_tweak_mul(keys[0], tweak).has_value()); }); boost::system::result negated = crypto::error::backend_failure; - covered("secp256k1::pubkey_negate on secp256k1", - [&] { negated = secp::pubkey_negate(keys[0]); }); + covered("secp256k1::public_key_negate on secp256k1", + [&] { negated = secp::public_key_negate(keys[0]); }); BOOST_TEST((negated && !(*negated == keys[0]))); auto space = lent(secp::combine_workspace_size(keys.size())); - covered("secp256k1::pubkey_combine on secp256k1", - [&] { BOOST_TEST(secp::pubkey_combine(keys, space).has_value()); }); - covered("secp256k1::pubkey_combine of no key on secp256k1", [&] { - BOOST_TEST(secp::pubkey_combine(std::span(keys).first(0), space).error() == + covered("secp256k1::public_key_combine on secp256k1", + [&] { BOOST_TEST(secp::public_key_combine(keys, space).has_value()); }); + covered("secp256k1::public_key_combine of no key on secp256k1", [&] { + BOOST_TEST(secp::public_key_combine(std::span(keys).first(0), space).error() == crypto::error::invalid_input_size); }); } @@ -1022,8 +1101,8 @@ bool throws_bad_alloc(Call const& call) { } /** - * An exception from the memory resource unwinds through basic_keypair::make's guard and through - * decode_pkcs8's: DIT is clear after it from clear, and still set from set (ruling R6). + * An exception from the memory resource unwinds through basic_keypair::from_secret's guard and + * through decode_pkcs8's: DIT is clear after it from clear, and still set from set (ruling R6). */ void throwing_resource_restores_state() { throwing_resource resource; @@ -1032,17 +1111,20 @@ void throwing_resource_restores_state() { if (!BOOST_TEST(secp::encode_pkcs8(keypair_of(0xc1), pkcs8).has_value())) { return; } - auto const make = [&] { static_cast(secp::keypair::make(secret_key, &resource)); }; - // decode_pkcs8 reaches the resource through make, guarded too: its own entry is checked by - // cover_formats' refusal; here the subject is the state the unwinding leaves. + auto const from_secret = [&] { + static_cast(secp::keypair::from_secret(secret_key, &resource)); + }; + // decode_pkcs8 reaches the resource through from_secret, guarded too: its own entry is checked + // by cover_formats' refusal; here the subject is the state the unwinding leaves. auto const decode = [&] { static_cast(secp::decode_pkcs8(std::span(pkcs8), &resource)); }; for (bool const set : {false, true}) { std::string const from = set ? " from set" : " from clear"; force_dit(set); - covered("secp256k1::basic_keypair::make with a throwing resource" + from + " on secp256k1", - [&] { BOOST_TEST(throws_bad_alloc(make)); }); + covered("secp256k1::basic_keypair::from_secret with a throwing resource" + from + + " on secp256k1", + [&] { BOOST_TEST(throws_bad_alloc(from_secret)); }); BOOST_TEST_EQ(crypto::detail::dit_is_set(), set && crypto::detail::cpu_has_dit()); covered("secp256k1::decode_pkcs8 with a throwing resource" + from + " on secp256k1", [&] { BOOST_TEST(throws_bad_alloc(decode)); }); @@ -1062,11 +1144,17 @@ int main() { cover_keypair_agreement(); cover_public_keys(); cover_verification(); + cover_ethereum_recovery(); cover_public_key_verify(); - cover_free_make_forms(); + cover_free_factories(); cover_free_forms(); cover_signature_forms(); cover_low_s(); + webcpp::test::cover_signature("secp256k1::ecdsa_signature", "secp256k1"); + webcpp::test::cover_signature("secp256k1::recoverable_signature", + "secp256k1"); + webcpp::test::cover_signature("secp256k1::schnorr_signature", + "secp256k1"); cover_ellswift(); cover_formats(); cover_musig_key(); diff --git a/test/timing_coverage_sodium_test.cpp b/test/timing_coverage_sodium_test.cpp index f8ac0ebd..813a6a1e 100644 --- a/test/timing_coverage_sodium_test.cpp +++ b/test/timing_coverage_sodium_test.cpp @@ -13,44 +13,65 @@ // its own guard fails although it calls another guarded function. // // What it covers, by family; a family libsodium gains adds its line and its checks: -// - ChaCha20-Poly1305, its original form, XChaCha20-Poly1305 and both secret boxes, aead: make, -// seal, open; the free crypto::make, crypto::seal and crypto::open. -// - Both boxes, basic_box: make, seal, open. The sealed box, basic_sealed_box: seal, open. +// - 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. +// - 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. +// - Both boxes, basic_box: from_keys, of a moved-from key pair too, seal, open; the box forms +// secret_key_encryption::seal and secret_key_encryption::open; the asynchronous async_seal and +// async_open, member and free. The sealed box, basic_sealed_box: +// seal, open, of a moved-from key pair too. // - PEM: algorithm::armour, algorithm::unarmour, and the free armour and unarmour, which forward. -// - Ed25519, basic_keypair: make, generate, public_key, secret, sign, x25519_secret; public_key: -// verify; the free crypto::verify and to_x25519_public, and the free synchronous forms of the -// members, crypto::make (of a key pair, and of a public key, whose own make holds no guard), -// crypto::generate and crypto::sign, which enter their own guard before the member's. Ed25519ph, -// ph: begin, update, sign, verify. Its formats: decode_spki, decode_pkcs8 (the encoders call no -// backend and hold no guard, ruling R4; nor do public_key::make and bytes). -// - Ed25519's asynchronous functions: async_make, async_generate, async_sign, async_verify, free -// and as the members basic_keypair::async_make, async_generate, async_sign and +// - Ed25519, basic_keypair: from_secret, generate, public_key, secret, sign, to_x25519; +// public_key: verify, to_x25519; the free crypto::verify, and the free synchronous forms of the +// members, crypto::from_secret, crypto::generate, crypto::sign and crypto::to_x25519 (of a key +// pair and of a public key), which enter their own guard before the member's, and +// crypto::from_bytes of a public key, which enters none, as its member does not. Ed25519ph, the +// scheme eddsa_prehashed: basic_keypair::sign, the free crypto::sign, public_key::verify, +// crypto::verify, and their asynchronous forms, async_sign and async_verify, member and free; +// prehashed_signer: begin, update, sign, verify. Its formats: decode_spki, decode_pkcs8 (the +// encoders call no backend and hold no guard, ruling R4; nor do public_key::from_bytes and +// bytes). Its signature, signature: from_bytes, member and free, and bytes, which call no backend +// and enter no guard. +// - Ed25519's asynchronous functions: async_from_secret, async_generate, async_sign, async_verify, +// free and as the members basic_keypair::async_from_secret, async_generate, async_sign and // public_key::async_verify, which the free ones call. -// - X25519, algorithm: public_key, agree; the free public_key and agree, which forward, and -// the asynchronous async_agree. Its formats: decode_spki, decode_pkcs8. -// - crypto_kx, kx_keypair: make, generate, client_session_keys, server_session_keys. +// - X25519, basic_keypair: from_secret, generate, agree, each of a moved-from key pair too where +// it applies; public_key and secret, which copy, and public_key's from_bytes and bytes, which +// enter none; the free crypto::from_secret, crypto::generate and crypto::agree, and crypto:: +// from_bytes, which enters none; the asynchronous async_from_secret, async_generate and +// async_agree, member and free. Its formats: decode_spki, decode_pkcs8. +// - crypto_kx, kx_keypair: from_keypair, derive_from_seed, generate, client_session_keys, +// server_session_keys, each of a moved-from key pair too where it applies; keypair and +// public_key, which call no backend and enter none. #include "support/timing_seam.hpp" +#include #include #include -#include #include #include #include #include -#include #include -#include -#include +#include #include #include +#include +#include +#include +#include #include #include #include #include "support/timing_coverage.hpp" +#include + #include #include @@ -71,6 +92,211 @@ using webcpp::test::covered; // The ciphers. // --------------------------------------------------------------------------------------------- +/** + * The box forms, `secret_key_encryption::seal` and `open`, over a keyed box, each entering its own + * guard before the member's, a nonce of the wrong size included. + * + * @tparam Box An `authenticated_box`: a secret box or a crypto_box. + * @param made A keyed box. + * @param family The family's name, as the public alias spells it. + * @param on ` on `, which ends each name. + */ +template +void cover_box_forms(Box& made, std::string const& family, std::string const& on) { + std::array const nonce{}; + std::array data{}; + typename Box::result_type tag{}; + covered(family + " secret_key_encryption::seal" + on, "secret_key_encryption::seal", [&] { + auto const sealed = crypto::secret_key_encryption::seal(made, nonce, data); + if (BOOST_TEST(sealed.has_value())) { + tag = *sealed; + } + }); + covered(family + " secret_key_encryption::open" + on, "secret_key_encryption::open", [&] { + BOOST_TEST(crypto::secret_key_encryption::open(made, nonce, data, + std::span(tag.data(), tag.size())) + .has_value()); + }); + covered(family + " secret_key_encryption::seal with a short nonce" + on, + "secret_key_encryption::seal", [&] { + BOOST_TEST(crypto::secret_key_encryption::seal( + made, std::span(nonce).first(Box::nonce_size - 1), data) + .error() == crypto::error::invalid_nonce_size); + }); + covered(family + " secret_key_encryption::open with a short nonce" + on, + "secret_key_encryption::open", [&] { + BOOST_TEST(crypto::secret_key_encryption::open( + made, std::span(nonce).first(Box::nonce_size - 1), data, + std::span(tag.data(), tag.size())) + .error() == crypto::error::invalid_nonce_size); + }); +} + +/** + * A box's asynchronous `async_seal` and `async_open` (design D6), the box forms + * (`secret_key_encryption::async_seal` and `async_open`) and the members, each a nonce of the + * wrong size included, an `io_context` run after each call so that its completion is delivered. + * + * @tparam Box An `authenticated_box`: a secret box or a crypto_box. + * @param made A keyed box. + * @param family The family's name, as the public alias spells it. + * @param on ` on `, which ends each name. + * @param members The class that declares the members, `basic_secretbox` or `basic_box`. + */ +template +void cover_async_box_forms(Box& made, std::string const& family, std::string const& on, + std::string const& members) { + webcpp::asio::io_context context; + auto const executor = context.get_executor(); + std::array const nonce{}; + auto const short_nonce = std::span(nonce).first(Box::nonce_size - 1); + std::array data{}; + int completions = 0; + typename Box::result_type kept{}; + webcpp::test::async_completion_counter const counted{ + .completions = &completions, + }; + webcpp::test::async_completion_counter const keeping{ + .completions = &completions, + .tag = &kept, + }; + auto const deliver = [&context] { + context.restart(); + context.run(); // lint-run: the test's event loop + }; + auto const tag = [&kept] { return std::span(kept.data(), kept.size()); }; + covered(family + " secret_key_encryption::async_seal" + on, "secret_key_encryption::async_seal", + [&] { + crypto::secret_key_encryption::async_seal(executor, made, nonce, data, keeping); + deliver(); + }); + covered(family + " secret_key_encryption::async_open" + on, "secret_key_encryption::async_open", + [&] { + crypto::secret_key_encryption::async_open(executor, made, nonce, data, tag(), + counted); + deliver(); + }); + covered(family + " secret_key_encryption::async_seal with a short nonce" + on, + "secret_key_encryption::async_seal", [&] { + crypto::secret_key_encryption::async_seal(executor, made, short_nonce, data, + counted); + deliver(); + }); + covered(family + " secret_key_encryption::async_open with a short nonce" + on, + "secret_key_encryption::async_open", [&] { + crypto::secret_key_encryption::async_open(executor, made, short_nonce, data, tag(), + counted); + deliver(); + }); + covered(family + "::async_seal" + on, members + "::async_seal", [&] { + made.async_seal(executor, nonce, data, keeping); + deliver(); + }); + covered(family + "::async_open" + on, members + "::async_open", [&] { + made.async_open(executor, nonce, data, tag(), counted); + deliver(); + }); + covered(family + "::async_seal with a short nonce" + on, members + "::async_seal", [&] { + made.async_seal(executor, short_nonce, data, counted); + deliver(); + }); + covered(family + "::async_open with a short nonce" + on, members + "::async_open", [&] { + made.async_open(executor, short_nonce, data, tag(), counted); + deliver(); + }); + BOOST_TEST_EQ(completions, 8); +} + +/** + * A secret box's `async_from_key`, free and member, a key of the wrong size included. + * + * @tparam Secretbox `basic_secretbox`. + * @param family The family's name, as the public alias spells it. + * @param on ` on `, which ends each name. + */ +template +void cover_async_secretbox_from_key(std::string const& family, std::string const& on) { + webcpp::asio::io_context context; + auto const executor = context.get_executor(); + auto const key = webcpp::test::coverage_key(); + auto const short_key = std::span(key).first(Secretbox::key_size - 1); + int completions = 0; + webcpp::test::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", [&] { + crypto::async_from_key(executor, key, counted); + deliver(); + }); + covered(family + " crypto::async_from_key with a short key" + on, "crypto::async_from_key", + [&] { + crypto::async_from_key(executor, short_key, counted); + deliver(); + }); + covered(family + "::async_from_key" + on, "basic_secretbox::async_from_key", [&] { + Secretbox::async_from_key(executor, key, counted); + deliver(); + }); + covered(family + "::async_from_key with a short key" + on, "basic_secretbox::async_from_key", + [&] { + Secretbox::async_from_key(executor, short_key, counted); + deliver(); + }); + BOOST_TEST_EQ(completions, 4); +} + +/** + * A secret box's guarded functions: `from_key`, a key of the wrong size included, member and + * free; `seal` and `open`, a nonce of the wrong size included; and the box forms + * (`cover_box_forms`). + * + * @tparam Secretbox `basic_secretbox`. + * @param family The family's name, as the public alias spells it. + */ +template +void cover_secretbox(std::string const& family) { + std::string const on = " on sodium"; + auto const key = webcpp::test::coverage_key(); + covered(family + "::from_key" + on, "basic_secretbox::from_key", + [&key] { BOOST_TEST(Secretbox::from_key(key).has_value()); }); + covered(family + "::from_key with a short key" + on, "basic_secretbox::from_key", [&key] { + BOOST_TEST(Secretbox::from_key(std::span(key).first(Secretbox::key_size - 1)).error() == + crypto::error::invalid_key_size); + }); + covered(family + " crypto::from_key" + on, "crypto::from_key", + [&key] { BOOST_TEST(crypto::from_key(key).has_value()); }); + auto made = Secretbox::from_key(key); + if (!BOOST_TEST(made.has_value())) { + return; + } + std::array const nonce{}; + std::array data{}; + typename Secretbox::result_type tag{}; + covered(family + "::seal" + on, "basic_secretbox::seal", [&] { + auto const sealed = made->seal(nonce, data); + if (BOOST_TEST(sealed.has_value())) { + tag = *sealed; + } + }); + covered(family + "::open" + on, "basic_secretbox::open", [&] { + BOOST_TEST(made->open(nonce, data, std::span(tag.data(), tag.size())).has_value()); + }); + covered(family + "::seal with a short nonce" + on, "basic_secretbox::seal", [&] { + BOOST_TEST(made->seal(std::span(nonce).first(Secretbox::nonce_size - 1), data).error() == + crypto::error::invalid_nonce_size); + }); + covered(family + "::open with a short nonce" + on, "basic_secretbox::open", [&] { + BOOST_TEST(made->open(std::span(nonce).first(Secretbox::nonce_size - 1), data, + std::span(tag.data(), tag.size())) + .error() == crypto::error::invalid_nonce_size); + }); + cover_box_forms(*made, family, on); + cover_async_box_forms(*made, family, on, "basic_secretbox"); + cover_async_secretbox_from_key(family, on); +} + /** ChaCha20-Poly1305, its original form, XChaCha20-Poly1305 and both secret boxes. */ void cover_ciphers() { webcpp::test::cover_aead>("chacha20_poly1305", @@ -79,16 +305,16 @@ void cover_ciphers() { "chacha20_poly1305_original", "sodium"); webcpp::test::cover_aead>("xchacha20_poly1305", "sodium"); - webcpp::test::cover_aead>("secretbox", "sodium"); - webcpp::test::cover_aead>( - "secretbox_xchacha20poly1305", "sodium"); + cover_secretbox>("secretbox"); + cover_secretbox>( + "secretbox_xchacha20poly1305"); } // --------------------------------------------------------------------------------------------- // The boxes. // --------------------------------------------------------------------------------------------- -/** An X25519 key pair whose secret key is `fill` repeated, for the boxes. */ +/** An X25519 key pair's bytes, its secret key `fill` repeated, for X25519's own checks. */ struct coverage_keypair { /** The secret key. */ std::array secret_key{}; @@ -100,16 +326,27 @@ struct coverage_keypair { coverage_keypair make_keypair(std::uint8_t fill) { coverage_keypair made; made.secret_key.fill(fill); - auto const derived = crypto::curves::x25519::public_key(made.secret_key); + auto const derived = + crypto::curves::x25519::basic_keypair::from_secret(made.secret_key); if (BOOST_TEST(derived.has_value())) { - made.public_key = *derived; + made.public_key = derived->public_key().value().bytes(); } return made; } /** - * A box's guarded functions: `make`, a secret key of the wrong size included, `seal` and `open`, - * a nonce of the wrong size included. + * The typed X25519 key pair whose secret key is 32 bytes `fill`, made outside a check, for the + * boxes and crypto_kx. + */ +crypto::curves::x25519::basic_keypair typed_keypair(std::uint8_t fill) { + std::array secret_key{}; + secret_key.fill(fill); + return crypto::curves::x25519::basic_keypair::from_secret(secret_key).value(); +} + +/** + * A box's guarded functions: `from_keys`, a moved-from key pair included, `seal` and `open`, a + * nonce of the wrong size included. * * @tparam Box `basic_box`. * @param family The family's name, as the public alias spells it. @@ -117,68 +354,83 @@ coverage_keypair make_keypair(std::uint8_t fill) { template void cover_box(std::string const& family) { std::string const on = " on sodium"; - auto const alice = make_keypair(0x41); - auto const bob = make_keypair(0x42); - covered(family + "::make" + on, "basic_box::make", - [&] { BOOST_TEST(Box::make(alice.secret_key, bob.public_key).has_value()); }); - covered(family + "::make with a short secret key" + on, "basic_box::make", [&] { - BOOST_TEST(Box::make(std::span(alice.secret_key).first(31), bob.public_key).error() == - crypto::error::invalid_key_size); - }); - auto made = Box::make(alice.secret_key, bob.public_key); + auto alice = typed_keypair(0x41); + auto const bob_public = typed_keypair(0x42).public_key().value(); + covered(family + "::from_keys" + on, "basic_box::from_keys", + [&] { BOOST_TEST(Box::from_keys(alice, bob_public).has_value()); }); + auto made = Box::from_keys(alice, bob_public); if (!BOOST_TEST(made.has_value())) { return; } - std::array const iv{}; + auto const kept = std::move(alice); + // NOLINTBEGIN(bugprone-use-after-move,clang-analyzer-cplusplus.Move): the refusal + covered(family + "::from_keys of a moved-from key pair" + on, "basic_box::from_keys", [&] { + BOOST_TEST(Box::from_keys(alice, bob_public).error() == crypto::error::invalid_state); + }); + // NOLINTEND(bugprone-use-after-move,clang-analyzer-cplusplus.Move) + std::array const nonce{}; std::array data{}; typename Box::result_type tag{}; covered(family + "::seal" + on, "basic_box::seal", [&] { - auto const sealed = made->seal(iv, data); + auto const sealed = made->seal(nonce, data); if (BOOST_TEST(sealed.has_value())) { tag = *sealed; } }); covered(family + "::open" + on, "basic_box::open", [&] { - BOOST_TEST(made->open(iv, data, std::span(tag.data(), tag.size())).has_value()); + BOOST_TEST(made->open(nonce, data, std::span(tag.data(), tag.size())).has_value()); }); covered(family + "::seal with a short nonce" + on, "basic_box::seal", [&] { - BOOST_TEST(made->seal(std::span(iv).first(Box::iv_size - 1), data).error() == - crypto::error::invalid_iv_size); + BOOST_TEST(made->seal(std::span(nonce).first(Box::nonce_size - 1), data).error() == + crypto::error::invalid_nonce_size); }); covered(family + "::open with a short nonce" + on, "basic_box::open", [&] { - BOOST_TEST(made->open(std::span(iv).first(Box::iv_size - 1), data, + BOOST_TEST(made->open(std::span(nonce).first(Box::nonce_size - 1), data, std::span(tag.data(), tag.size())) - .error() == crypto::error::invalid_iv_size); + .error() == crypto::error::invalid_nonce_size); }); + cover_box_forms(*made, family, on); + cover_async_box_forms(*made, family, on, "basic_box"); } -/** The sealed box's `seal` and `open`, an output of the wrong size included. */ +/** + * The sealed box's `seal` and `open`, an output of the wrong size and a moved-from key pair + * included. + */ void cover_sealed_box() { - using sealed_box = crypto::hybrid::basic_sealed_box; - auto const bob = make_keypair(0x42); + using sealed_box = crypto::public_key_encryption::basic_sealed_box; + auto bob = typed_keypair(0x42); + auto const bob_public = bob.public_key().value(); std::array const message{1, 2, 3, 4, 5, 6, 7, 8}; std::array sealed{}; std::array opened{}; covered("sealed_box::seal on sodium", "basic_sealed_box::seal", - [&] { BOOST_TEST(sealed_box::seal(bob.public_key, message, sealed).has_value()); }); - covered("sealed_box::open on sodium", "basic_sealed_box::open", [&] { - BOOST_TEST(sealed_box::open(bob.public_key, bob.secret_key, sealed, opened).has_value()); - }); + [&] { BOOST_TEST(sealed_box::seal(bob_public, message, sealed).has_value()); }); + covered("sealed_box::open on sodium", "basic_sealed_box::open", + [&] { BOOST_TEST(sealed_box::open(bob, sealed, opened).has_value()); }); covered("sealed_box::seal into a short output on sodium", "basic_sealed_box::seal", [&] { - BOOST_TEST(sealed_box::seal(bob.public_key, message, std::span(sealed).first(1)).error() == + BOOST_TEST(sealed_box::seal(bob_public, message, std::span(sealed).first(1)).error() == crypto::error::invalid_input_size); }); covered("sealed_box::open into a short output on sodium", "basic_sealed_box::open", [&] { - BOOST_TEST( - sealed_box::open(bob.public_key, bob.secret_key, sealed, std::span(opened).first(1)) - .error() == crypto::error::invalid_input_size); + BOOST_TEST(sealed_box::open(bob, sealed, std::span(opened).first(1)).error() == + crypto::error::invalid_input_size); + }); + auto const kept = std::move(bob); + // NOLINTBEGIN(bugprone-use-after-move,clang-analyzer-cplusplus.Move): the refusal + covered("sealed_box::open of a moved-from key pair on sodium", "basic_sealed_box::open", [&] { + BOOST_TEST(sealed_box::open(bob, sealed, opened).error() == crypto::error::invalid_state); }); + // NOLINTEND(bugprone-use-after-move,clang-analyzer-cplusplus.Move) } /** Both boxes and the sealed box. */ void cover_boxes() { - cover_box>("box"); - cover_box>( + cover_box< + crypto::public_key_encryption::basic_box>( + "box"); + cover_box< + crypto::public_key_encryption::basic_box>( "box_xchacha20poly1305"); cover_sealed_box(); } @@ -225,23 +477,23 @@ void cover_pem() { // --------------------------------------------------------------------------------------------- /** - * Ed25519's key pair: `make`, a seed of the wrong size included, `generate` (the system's - * entropy), and `public_key`, `secret`, `sign` and `x25519_secret`, each of a moved-from key pair + * Ed25519's key pair: `from_secret`, a seed of the wrong size included, `generate` (the system's + * entropy), and `public_key`, `secret`, `sign` and `to_x25519`, each of a moved-from key pair * too. */ void cover_ed25519_keypair() { using keypair = crypto::curves::ed25519::basic_keypair; auto const seed = webcpp::test::coverage_key(); std::array const message{1, 2, 3}; - covered("ed25519::basic_keypair::make on sodium", - [&] { BOOST_TEST(keypair::make(seed).has_value()); }); - covered("ed25519::basic_keypair::make with a short seed on sodium", [&] { - BOOST_TEST(keypair::make(std::span(seed).first(31)).error() == + covered("ed25519::basic_keypair::from_secret on sodium", + [&] { BOOST_TEST(keypair::from_secret(seed).has_value()); }); + covered("ed25519::basic_keypair::from_secret with a short seed on sodium", [&] { + BOOST_TEST(keypair::from_secret(std::span(seed).first(31)).error() == crypto::error::invalid_key_size); }); covered("ed25519::basic_keypair::generate on sodium", [] { BOOST_TEST(keypair::generate().has_value()); }); - auto made = keypair::make(seed); + auto made = keypair::from_secret(seed); if (!BOOST_TEST(made.has_value())) { return; } @@ -251,8 +503,8 @@ void cover_ed25519_keypair() { [&] { BOOST_TEST(made->secret().has_value()); }); covered("ed25519::basic_keypair::sign on sodium", [&] { BOOST_TEST(made->sign(crypto::eddsa, message).has_value()); }); - covered("ed25519::basic_keypair::x25519_secret on sodium", - [&] { BOOST_TEST(made->x25519_secret().has_value()); }); + covered("ed25519::basic_keypair::to_x25519 on sodium", + [&] { BOOST_TEST(made->to_x25519().has_value()); }); [[maybe_unused]] keypair const taken(std::move(*made)); covered("ed25519::basic_keypair::public_key moved from on sodium", [&] { // NOLINTNEXTLINE(bugprone-use-after-move): the moved-from key pair's refusal @@ -266,58 +518,68 @@ void cover_ed25519_keypair() { // NOLINTNEXTLINE(bugprone-use-after-move): the moved-from key pair's refusal BOOST_TEST(made->sign(crypto::eddsa, message).error() == crypto::error::invalid_state); }); - covered("ed25519::basic_keypair::x25519_secret moved from on sodium", [&] { + covered("ed25519::basic_keypair::to_x25519 moved from on sodium", [&] { // NOLINTNEXTLINE(bugprone-use-after-move): the moved-from key pair's refusal - BOOST_TEST(made->x25519_secret().error() == crypto::error::invalid_state); + BOOST_TEST(made->to_x25519().error() == crypto::error::invalid_state); }); } /** - * Ed25519's free synchronous forms, crypto::make, crypto::generate and crypto::sign, each entering - * its own guard before the member's, and refused once before libsodium (a short seed, a moved-from - * key pair). + * Ed25519's free synchronous forms, crypto::from_secret, crypto::generate, crypto::sign and + * crypto::to_x25519 of a key pair, each entering its own guard before the member's, and refused + * once before libsodium (a short seed, a moved-from key pair); crypto::from_bytes of a public key + * enters none, as its member does not. */ void cover_ed25519_free_forms() { using keypair = crypto::curves::ed25519::basic_keypair; auto const seed = webcpp::test::coverage_key(); std::array const message{1, 2, 3}; - covered("ed25519 crypto::make on sodium", "crypto::make", - [&] { BOOST_TEST(crypto::make(seed).has_value()); }); - covered("ed25519 crypto::make with a short seed on sodium", "crypto::make", [&] { - BOOST_TEST(crypto::make(std::span(seed).first(31)).error() == + covered("ed25519 crypto::from_secret on sodium", "crypto::from_secret", + [&] { BOOST_TEST(crypto::from_secret(seed).has_value()); }); + covered("ed25519 crypto::from_secret with a short seed on sodium", "crypto::from_secret", [&] { + BOOST_TEST(crypto::from_secret(std::span(seed).first(31)).error() == crypto::error::invalid_key_size); }); std::array const key_bytes = seed; - covered("ed25519 crypto::make of a public key on sodium", "crypto::make", [&] { - BOOST_TEST(crypto::make(key_bytes).has_value()); + webcpp::test::uncovered("ed25519 crypto::from_bytes of a public key on sodium", [&] { + BOOST_TEST(crypto::from_bytes(key_bytes).has_value()); }); - covered("ed25519 crypto::make of a short public key on sodium", "crypto::make", [&] { - BOOST_TEST(crypto::make(std::span(key_bytes).first(31)) - .error() == crypto::error::invalid_public_key); + webcpp::test::uncovered("ed25519 crypto::from_bytes of a short public key on sodium", [&] { + BOOST_TEST( + crypto::from_bytes(std::span(key_bytes).first(31)) + .error() == crypto::error::invalid_public_key); }); covered("ed25519 crypto::generate on sodium", "crypto::generate", [] { BOOST_TEST(crypto::generate().has_value()); }); - auto made = keypair::make(seed); + auto made = keypair::from_secret(seed); if (!BOOST_TEST(made.has_value())) { return; } covered("ed25519 crypto::sign on sodium", "crypto::sign", [&] { BOOST_TEST(crypto::sign(*made, crypto::eddsa, message).has_value()); }); + covered("ed25519 crypto::to_x25519 of a key pair on sodium", "crypto::to_x25519", + [&] { BOOST_TEST(crypto::to_x25519(*made).has_value()); }); [[maybe_unused]] keypair const taken(std::move(*made)); covered("ed25519 crypto::sign moved from on sodium", "crypto::sign", [&] { // NOLINTNEXTLINE(bugprone-use-after-move): the moved-from key pair's refusal BOOST_TEST(crypto::sign(*made, crypto::eddsa, message).error() == crypto::error::invalid_state); }); + covered("ed25519 crypto::to_x25519 of a key pair moved from on sodium", "crypto::to_x25519", + [&] { + // NOLINTNEXTLINE(bugprone-use-after-move): the moved-from key pair's refusal + BOOST_TEST(crypto::to_x25519(*made).error() == crypto::error::invalid_state); + }); } /** * Ed25519's `crypto::verify` and `public_key::verify`, a signature of the wrong size included, - * and `to_x25519_public`, a key of small order included. + * and `public_key::to_x25519` and the free `crypto::to_x25519` of a public key, a key of small + * order included. */ void cover_ed25519_free() { namespace ed25519 = crypto::curves::ed25519; - auto const made = ed25519::basic_keypair::make(webcpp::test::coverage_key<32>()); + auto const made = ed25519::basic_keypair::from_secret(webcpp::test::coverage_key<32>()); std::array const message{1, 2, 3}; if (!BOOST_TEST(made.has_value())) { return; @@ -332,43 +594,154 @@ void cover_ed25519_free() { crypto::verify(crypto::eddsa, *signature, message, *public_key, ed25519::strict) .has_value())); }); - covered("ed25519 crypto::verify with a short signature on sodium", "crypto::verify", [&] { - BOOST_TEST((crypto::verify(crypto::eddsa, std::span(*signature).first(63), message, - *public_key, ed25519::strict) + // A signature of another size is refused by from_bytes, which calls no backend; one that does + // not verify is the backend's refusal. + ed25519::signature const zero_signature{}; + covered("ed25519 crypto::verify with a zero signature on sodium", "crypto::verify", [&] { + BOOST_TEST((crypto::verify(crypto::eddsa, zero_signature, message, *public_key, + ed25519::strict) .error() == crypto::error::invalid_signature)); }); covered("ed25519::public_key::verify on sodium", [&] { BOOST_TEST(public_key->verify(crypto::eddsa, *signature, message).has_value()); }); - covered("ed25519::public_key::verify with a short signature on sodium", [&] { - BOOST_TEST( - public_key->verify(crypto::eddsa, std::span(*signature).first(63), message).error() == - crypto::error::invalid_signature); + covered("ed25519::public_key::verify with a zero signature on sodium", [&] { + BOOST_TEST(public_key->verify(crypto::eddsa, zero_signature, message).error() == + crypto::error::invalid_signature); }); - covered("ed25519::to_x25519_public on sodium", - [&] { BOOST_TEST(ed25519::to_x25519_public(*public_key).has_value()); }); + covered("ed25519::public_key::to_x25519 on sodium", + [&] { BOOST_TEST(public_key->to_x25519().has_value()); }); + covered("ed25519 crypto::to_x25519 of a public key on sodium", "crypto::to_x25519", + [&] { BOOST_TEST(crypto::to_x25519(*public_key).has_value()); }); // The identity's encoding, 01 then zeros, a point of small order. std::array identity{}; identity[0] = 0x01; - auto const small_order = ed25519::public_key::make(identity); + auto const small_order = ed25519::public_key::from_bytes(identity); if (!BOOST_TEST(small_order.has_value())) { return; } - covered("ed25519::to_x25519_public with a key of small order on sodium", [&] { - BOOST_TEST(ed25519::to_x25519_public(*small_order).error() == - crypto::error::invalid_public_key); + covered("ed25519::public_key::to_x25519 with a key of small order on sodium", [&] { + BOOST_TEST(small_order->to_x25519().error() == crypto::error::invalid_public_key); + }); + covered("ed25519 crypto::to_x25519 of a public key of small order on sodium", + "crypto::to_x25519", [&] { + BOOST_TEST(crypto::to_x25519(*small_order).error() == + crypto::error::invalid_public_key); + }); +} + +/** + * Ed25519ph under the scheme `eddsa_prehashed`: the key pair's `sign` and the free `crypto::sign`, + * the key's `verify` and the free `crypto::verify` (each entering its own overload's guard first), + * a moved-from key pair and a zero signature refused, and their asynchronous forms, member and + * free. + */ +void cover_ed25519_prehashed() { + namespace ed25519 = crypto::curves::ed25519; + using keypair = ed25519::basic_keypair; + auto made = keypair::from_secret(webcpp::test::coverage_key<32>()); + std::array digest{}; + digest.fill(0x5a); + crypto::prehashed const marker{digest}; + if (!BOOST_TEST(made.has_value())) { + return; + } + auto const public_key = made->public_key(); + auto const signature = made->sign(crypto::eddsa_prehashed, marker); + if (!BOOST_TEST(public_key.has_value()) || !BOOST_TEST(signature.has_value())) { + return; + } + ed25519::signature const zero_signature{}; + covered("ed25519::basic_keypair::sign under eddsa_prehashed on sodium", + [&] { BOOST_TEST(made->sign(crypto::eddsa_prehashed, marker).has_value()); }); + covered("ed25519 crypto::sign under eddsa_prehashed on sodium", "crypto::sign", + [&] { BOOST_TEST(crypto::sign(*made, crypto::eddsa_prehashed, marker).has_value()); }); + covered("ed25519 crypto::verify under eddsa_prehashed on sodium", + "crypto::verify(eddsa_prehashed_t", [&] { + BOOST_TEST(crypto::verify(crypto::eddsa_prehashed, *signature, marker, + *public_key, ed25519::strict) + .has_value()); + }); + covered( + "ed25519 crypto::verify under eddsa_prehashed with a zero signature on sodium", + "crypto::verify(eddsa_prehashed_t", [&] { + BOOST_TEST(crypto::verify(crypto::eddsa_prehashed, zero_signature, marker, *public_key) + .error() == crypto::error::invalid_signature); + }); + covered( + "ed25519::public_key::verify under eddsa_prehashed on sodium", + "ed25519::public_key::verify(eddsa_prehashed_t", [&] { + BOOST_TEST(public_key->verify(crypto::eddsa_prehashed, *signature, marker).has_value()); + }); + covered("ed25519::public_key::verify under eddsa_prehashed with a zero signature on sodium", + "ed25519::public_key::verify(eddsa_prehashed_t", [&] { + BOOST_TEST( + public_key->verify(crypto::eddsa_prehashed, zero_signature, marker).error() == + crypto::error::invalid_signature); + }); + + webcpp::asio::io_context context; + auto const executor = context.get_executor(); + int completions = 0; + webcpp::test::async_completion_counter const counted{ + .completions = &completions, + }; + auto const deliver = [&context] { + context.restart(); + context.run(); // lint-run: the test's event loop + }; + covered("ed25519::basic_keypair::async_sign under eddsa_prehashed on sodium", [&] { + made->async_sign(executor, crypto::eddsa_prehashed, marker, counted); + deliver(); + }); + covered("ed25519 crypto::async_sign under eddsa_prehashed on sodium", "crypto::async_sign", + [&] { + crypto::async_sign(executor, *made, crypto::eddsa_prehashed, marker, counted); + deliver(); + }); + covered("ed25519::public_key::async_verify under eddsa_prehashed on sodium", [&] { + public_key->async_verify(executor, crypto::eddsa_prehashed, *signature, marker, + counted); + deliver(); + }); + covered("ed25519::public_key::async_verify under eddsa_prehashed with its policy on sodium", + [&] { + public_key->async_verify(executor, crypto::eddsa_prehashed, *signature, + marker, ed25519::strict, counted); + deliver(); + }); + covered("ed25519 crypto::async_verify under eddsa_prehashed on sodium", + "crypto::async_verify(eddsa_prehashed_t", [&] { + crypto::async_verify(executor, crypto::eddsa_prehashed, *signature, marker, + *public_key, counted); + deliver(); + }); + covered("ed25519 crypto::async_verify under eddsa_prehashed with its policy on sodium", + "crypto::async_verify(eddsa_prehashed_t", [&] { + crypto::async_verify(executor, crypto::eddsa_prehashed, zero_signature, + marker, *public_key, ed25519::strict, counted); + deliver(); + }); + BOOST_TEST_EQ(completions, 6); + + [[maybe_unused]] keypair const taken(std::move(*made)); + covered("ed25519::basic_keypair::sign under eddsa_prehashed moved from on sodium", [&] { + // NOLINTNEXTLINE(bugprone-use-after-move): the moved-from key pair's refusal + BOOST_TEST(made->sign(crypto::eddsa_prehashed, marker).error() == + crypto::error::invalid_state); }); } /** Ed25519ph's `begin`, `update`, `sign` and `verify` of a message, a valid one. */ void cover_ed25519ph() { namespace ed25519 = crypto::curves::ed25519; - using ph = ed25519::ph; - auto const key = ed25519::basic_keypair::make(webcpp::test::coverage_key<32>()); + using signer_type = ed25519::prehashed_signer; + auto const key = ed25519::basic_keypair::from_secret(webcpp::test::coverage_key<32>()); std::array const piece{1, 2, 3}; - covered("ed25519::ph::begin on sodium", [] { BOOST_TEST(ph::begin().has_value()); }); - auto signer = ph::begin(); - auto verifier = ph::begin(); + covered("ed25519::prehashed_signer::begin on sodium", + [] { BOOST_TEST(signer_type::begin().has_value()); }); + auto signer = signer_type::begin(); + auto verifier = signer_type::begin(); if (!BOOST_TEST(key.has_value()) || !BOOST_TEST(signer.has_value()) || !BOOST_TEST(verifier.has_value()) || !BOOST_TEST(verifier->update(piece).has_value())) { return; @@ -377,48 +750,48 @@ void cover_ed25519ph() { if (!BOOST_TEST(public_key.has_value())) { return; } - covered("ed25519::ph::update on sodium", + covered("ed25519::prehashed_signer::update on sodium", [&] { BOOST_TEST(signer->update(piece).has_value()); }); - std::array signature{}; - covered("ed25519::ph::sign on sodium", [&] { + ed25519::signature signature{}; + covered("ed25519::prehashed_signer::sign on sodium", [&] { auto const signed_message = signer->sign(*key); if (BOOST_TEST(signed_message.has_value())) { signature = *signed_message; } }); - covered("ed25519::ph::verify on sodium", + covered("ed25519::prehashed_signer::verify on sodium", [&] { BOOST_TEST(verifier->verify(signature, *public_key).has_value()); }); } /** * Ed25519ph's `update`, `sign` and `verify` of an ended message, refused before the backend, and - * `verify` with a signature of the wrong size. + * `verify` of a signature that does not verify, refused by the backend. */ void cover_ed25519ph_refusals() { namespace ed25519 = crypto::curves::ed25519; - using ph = ed25519::ph; - auto const key = ed25519::basic_keypair::make(webcpp::test::coverage_key<32>()); - std::array const signature{}; + using signer_type = ed25519::prehashed_signer; + auto const key = ed25519::basic_keypair::from_secret(webcpp::test::coverage_key<32>()); + ed25519::signature const signature{}; std::array const piece{1, 2, 3}; - auto ended = ph::begin(); - auto short_signature = ph::begin(); + auto ended = signer_type::begin(); + auto refused = signer_type::begin(); if (!BOOST_TEST(key.has_value()) || !BOOST_TEST(ended.has_value()) || - !BOOST_TEST(short_signature.has_value()) || !BOOST_TEST(ended->sign(*key).has_value())) { + !BOOST_TEST(refused.has_value()) || !BOOST_TEST(ended->sign(*key).has_value())) { return; } auto const public_key = key->public_key(); if (!BOOST_TEST(public_key.has_value())) { return; } - covered("ed25519::ph::update of an ended message on sodium", + covered("ed25519::prehashed_signer::update of an ended message on sodium", [&] { BOOST_TEST(ended->update(piece).error() == crypto::error::invalid_state); }); - covered("ed25519::ph::sign of an ended message on sodium", + covered("ed25519::prehashed_signer::sign of an ended message on sodium", [&] { BOOST_TEST(ended->sign(*key).error() == crypto::error::invalid_state); }); - covered("ed25519::ph::verify of an ended message on sodium", [&] { + covered("ed25519::prehashed_signer::verify of an ended message on sodium", [&] { BOOST_TEST(ended->verify(signature, *public_key).error() == crypto::error::invalid_state); }); - covered("ed25519::ph::verify with a short signature on sodium", [&] { - BOOST_TEST(short_signature->verify(std::span(signature).first(63), *public_key).error() == + covered("ed25519::prehashed_signer::verify with a zero signature on sodium", [&] { + BOOST_TEST(refused->verify(signature, *public_key).error() == crypto::error::invalid_signature); }); } @@ -426,7 +799,7 @@ void cover_ed25519ph_refusals() { /** Ed25519's `decode_spki` and `decode_pkcs8`, an encoding of the wrong size of each included. */ void cover_ed25519_formats() { namespace ed25519 = crypto::curves::ed25519; - auto const key = ed25519::basic_keypair::make(webcpp::test::coverage_key<32>()); + auto const key = ed25519::basic_keypair::from_secret(webcpp::test::coverage_key<32>()); if (!BOOST_TEST(key.has_value())) { return; } @@ -453,39 +826,102 @@ void cover_ed25519_formats() { } /** - * X25519's `algorithm::public_key` and `agree`, and the free functions, a key of the - * wrong size of each included. + * X25519's key pair: `from_secret`, a secret key of the wrong size included, `generate` (the + * system's entropy) and `agree`, each entering its own guard; and `public_key` and `secret`, which + * copy, and the public key's `from_bytes` and `bytes`, which enter none. */ void cover_x25519() { namespace x25519 = crypto::curves::x25519; - using algorithm = x25519::algorithm; + using keypair = x25519::basic_keypair; auto const alice = make_keypair(0x41); auto const bob = make_keypair(0x42); auto const short_key = std::span(alice.secret_key).first(31); - covered("x25519::algorithm::public_key on sodium", - [&] { BOOST_TEST(algorithm::public_key(alice.secret_key).has_value()); }); - covered("x25519::algorithm::agree on sodium", - [&] { BOOST_TEST(algorithm::agree(alice.secret_key, bob.public_key).has_value()); }); - covered("x25519::public_key on sodium", - [&] { BOOST_TEST(x25519::public_key(alice.secret_key).has_value()); }); - covered("x25519::agree on sodium", [&] { - BOOST_TEST(x25519::agree(alice.secret_key, bob.public_key).has_value()); - }); - covered("x25519::algorithm::public_key with a short key on sodium", [&] { - BOOST_TEST(algorithm::public_key(short_key).error() == crypto::error::invalid_key_size); - }); - covered("x25519::algorithm::agree with a short key on sodium", [&] { - BOOST_TEST(algorithm::agree(short_key, bob.public_key).error() == - crypto::error::invalid_key_size); + covered("x25519::basic_keypair::from_secret on sodium", + [&] { BOOST_TEST(keypair::from_secret(alice.secret_key).has_value()); }); + covered("x25519::basic_keypair::from_secret with a short key on sodium", [&] { + BOOST_TEST(keypair::from_secret(short_key).error() == crypto::error::invalid_key_size); }); - covered("x25519::public_key with a short key on sodium", [&] { - BOOST_TEST(x25519::public_key(short_key).error() == - crypto::error::invalid_key_size); + covered("x25519::basic_keypair::generate on sodium", + [] { BOOST_TEST(keypair::generate().has_value()); }); + auto made = keypair::from_secret(alice.secret_key); + auto const peer = x25519::public_key::from_bytes(bob.public_key); + if (!BOOST_TEST(made.has_value()) || !BOOST_TEST(peer.has_value())) { + return; + } + covered("x25519::basic_keypair::agree on sodium", + [&] { BOOST_TEST(made->agree(*peer).has_value()); }); + webcpp::test::uncovered("x25519::basic_keypair::public_key on sodium", + [&] { BOOST_TEST(made->public_key().has_value()); }); + webcpp::test::uncovered("x25519::basic_keypair::secret on sodium", + [&] { BOOST_TEST(made->secret().has_value()); }); + webcpp::test::uncovered("x25519::public_key::from_bytes on sodium", [&] { + BOOST_TEST(x25519::public_key::from_bytes(bob.public_key).has_value()); + }); + webcpp::test::uncovered("x25519::public_key::from_bytes of a short key on sodium", [&] { + BOOST_TEST(x25519::public_key::from_bytes(short_key).error() == + crypto::error::invalid_public_key); + }); + webcpp::test::uncovered("x25519::public_key::bytes on sodium", + [&] { BOOST_TEST(peer->bytes() == bob.public_key); }); +} + +/** + * X25519's moved-from key pair: `agree` enters its guard and refuses; `public_key` and `secret` + * refuse with none. + */ +void cover_x25519_moved_from() { + namespace x25519 = crypto::curves::x25519; + using keypair = x25519::basic_keypair; + auto const alice = make_keypair(0x41); + auto const bob = make_keypair(0x42); + auto made = keypair::from_secret(alice.secret_key); + auto const peer = x25519::public_key::from_bytes(bob.public_key); + if (!BOOST_TEST(made.has_value()) || !BOOST_TEST(peer.has_value())) { + return; + } + [[maybe_unused]] keypair const taken(std::move(*made)); + covered("x25519::basic_keypair::agree moved from on sodium", [&] { + // NOLINTNEXTLINE(bugprone-use-after-move): the moved-from key pair's refusal + BOOST_TEST(made->agree(*peer).error() == crypto::error::invalid_state); + }); + webcpp::test::uncovered("x25519::basic_keypair::public_key moved from on sodium", [&] { + // NOLINTNEXTLINE(bugprone-use-after-move): the moved-from key pair's refusal + BOOST_TEST(made->public_key().error() == crypto::error::invalid_state); + }); + webcpp::test::uncovered("x25519::basic_keypair::secret moved from on sodium", [&] { + // NOLINTNEXTLINE(bugprone-use-after-move): the moved-from key pair's refusal + BOOST_TEST(made->secret().error() == crypto::error::invalid_state); }); - covered("x25519::agree with a short key on sodium", [&] { - BOOST_TEST(x25519::agree(short_key, bob.public_key).error() == +} + +/** + * X25519's free synchronous forms, crypto::from_secret, crypto::generate and crypto::agree, each + * entering its own guard before the member's, a short secret key included; crypto::from_bytes of a + * public key enters none, as its member does not. + */ +void cover_x25519_free_forms() { + namespace x25519 = crypto::curves::x25519; + using keypair = x25519::basic_keypair; + auto const alice = make_keypair(0x41); + auto const bob = make_keypair(0x42); + covered("x25519 crypto::from_secret on sodium", "crypto::from_secret", + [&] { BOOST_TEST(crypto::from_secret(alice.secret_key).has_value()); }); + covered("x25519 crypto::from_secret with a short key on sodium", "crypto::from_secret", [&] { + BOOST_TEST(crypto::from_secret(std::span(alice.secret_key).first(31)).error() == crypto::error::invalid_key_size); }); + covered("x25519 crypto::generate on sodium", "crypto::generate", + [] { BOOST_TEST(crypto::generate().has_value()); }); + webcpp::test::uncovered("x25519 crypto::from_bytes of a public key on sodium", [&] { + BOOST_TEST(crypto::from_bytes(bob.public_key).has_value()); + }); + auto const made = keypair::from_secret(alice.secret_key); + auto const peer = x25519::public_key::from_bytes(bob.public_key); + if (!BOOST_TEST(made.has_value()) || !BOOST_TEST(peer.has_value())) { + return; + } + covered("x25519 crypto::agree on sodium", "crypto::agree", + [&] { BOOST_TEST(crypto::agree(*made, *peer).has_value()); }); } /** X25519's `decode_spki` and `decode_pkcs8`, an encoding of the wrong size of each included. */ @@ -513,56 +949,90 @@ void cover_x25519_formats() { } /** - * crypto_kx's key pair: `make`, a seed of the wrong size included, `generate` (the system's - * entropy), and `client_session_keys` and `server_session_keys`, a peer key of the wrong size - * included. `public_key` copies bytes and holds no guard (ruling R4). + * crypto_kx's session keys: `client_session_keys` and `server_session_keys`, of a moved-from key + * pair too. `keypair` and `public_key` call no backend and enter none. */ -void cover_kx() { - using kx_keypair = crypto::curves::x25519::kx_keypair; - auto const seed = webcpp::test::coverage_key(); - covered("x25519::kx_keypair::make on sodium", - [&] { BOOST_TEST(kx_keypair::make(seed).has_value()); }); - covered("x25519::kx_keypair::make with a short seed on sodium", [&] { - BOOST_TEST(kx_keypair::make(std::span(seed).first(31)).error() == - crypto::error::invalid_key_size); - }); - covered("x25519::kx_keypair::generate on sodium", - [] { BOOST_TEST(kx_keypair::generate().has_value()); }); - auto const client = kx_keypair::make(seed); +void cover_kx_sessions() { + using kx_keypair = crypto::key_exchange::kx_keypair; + auto client = kx_keypair::derive_from_seed(webcpp::test::coverage_key()); auto const server = kx_keypair::generate(); if (!BOOST_TEST(client.has_value()) || !BOOST_TEST(server.has_value())) { return; } + webcpp::test::uncovered("key_exchange::kx_keypair::keypair on sodium", + [&] { BOOST_TEST(client->keypair().public_key().has_value()); }); + webcpp::test::uncovered("key_exchange::kx_keypair::public_key on sodium", + [&] { BOOST_TEST(client->public_key().has_value()); }); auto const client_public = client->public_key(); auto const server_public = server->public_key(); if (!BOOST_TEST(client_public.has_value()) || !BOOST_TEST(server_public.has_value())) { return; } - covered("x25519::kx_keypair::client_session_keys on sodium", + covered("key_exchange::kx_keypair::client_session_keys on sodium", [&] { BOOST_TEST(client->client_session_keys(*server_public).has_value()); }); - covered("x25519::kx_keypair::server_session_keys on sodium", + covered("key_exchange::kx_keypair::server_session_keys on sodium", [&] { BOOST_TEST(server->server_session_keys(*client_public).has_value()); }); - covered("x25519::kx_keypair::client_session_keys with a short key on sodium", [&] { - BOOST_TEST(client->client_session_keys(std::span(*server_public).first(31)).error() == - crypto::error::invalid_public_key); + auto const moved = std::move(*client); + // NOLINTBEGIN(bugprone-use-after-move,clang-analyzer-cplusplus.Move): the refusals + covered("key_exchange::kx_keypair::client_session_keys of a moved-from key pair on sodium", + [&] { + BOOST_TEST(client->client_session_keys(*server_public).error() == + crypto::error::invalid_state); + }); + covered("key_exchange::kx_keypair::server_session_keys of a moved-from key pair on sodium", + [&] { + BOOST_TEST(client->server_session_keys(*server_public).error() == + crypto::error::invalid_state); + }); + // NOLINTEND(bugprone-use-after-move,clang-analyzer-cplusplus.Move) +} + +/** + * crypto_kx's key pair: `from_keypair`, a moved-from X25519 key pair included, + * `derive_from_seed`, a seed of the wrong size included, and `generate` (the system's entropy); + * then its session keys. + */ +void cover_kx() { + using kx_keypair = crypto::key_exchange::kx_keypair; + auto const seed = webcpp::test::coverage_key(); + auto fresh = typed_keypair(0x43); + covered("key_exchange::kx_keypair::from_keypair on sodium", + [&] { BOOST_TEST(kx_keypair::from_keypair(std::move(fresh)).has_value()); }); + auto inner = typed_keypair(0x44); + auto const kept = std::move(inner); + // NOLINTBEGIN(bugprone-use-after-move,clang-analyzer-cplusplus.Move): the refusal + covered("key_exchange::kx_keypair::from_keypair of a moved-from key pair on sodium", [&] { + BOOST_TEST(kx_keypair::from_keypair(std::move(inner)).error() == + crypto::error::invalid_state); }); - covered("x25519::kx_keypair::server_session_keys with a short key on sodium", [&] { - BOOST_TEST(server->server_session_keys(std::span(*client_public).first(31)).error() == - crypto::error::invalid_public_key); + // NOLINTEND(bugprone-use-after-move,clang-analyzer-cplusplus.Move) + covered("key_exchange::kx_keypair::derive_from_seed on sodium", + [&] { BOOST_TEST(kx_keypair::derive_from_seed(seed).has_value()); }); + covered("key_exchange::kx_keypair::derive_from_seed with a short seed on sodium", [&] { + BOOST_TEST(kx_keypair::derive_from_seed(std::span(seed).first(31)).error() == + crypto::error::invalid_key_size); }); + covered("key_exchange::kx_keypair::generate on sodium", + [] { BOOST_TEST(kx_keypair::generate().has_value()); }); + cover_kx_sessions(); } /** Ed25519, Ed25519ph, X25519, crypto_kx, and the decoders of the key formats. */ void cover_curves() { cover_ed25519_keypair(); webcpp::test::cover_async_ed25519>("sodium"); - webcpp::test::cover_async_x25519("sodium"); + webcpp::test::cover_async_x25519>("sodium"); cover_ed25519_free(); cover_ed25519_free_forms(); + webcpp::test::cover_signature("ed25519::signature", + "sodium"); + cover_ed25519_prehashed(); cover_ed25519ph(); cover_ed25519ph_refusals(); cover_ed25519_formats(); cover_x25519(); + cover_x25519_moved_from(); + cover_x25519_free_forms(); cover_x25519_formats(); cover_kx(); } diff --git a/test/timing_hash_interop_test.cpp b/test/timing_hash_interop_test.cpp index 8f8f8770..19ee1630 100644 --- a/test/timing_hash_interop_test.cpp +++ b/test/timing_hash_interop_test.cpp @@ -158,18 +158,18 @@ void crypto_inside_hash() { // Ed25519ph signs with hash's SHA-512 as its prehash, which is unkeyed (D2): crypto's counter // rises, hash's does not. void ed25519ph_uses_hash_unkeyed() { - using ph = ed25519::ph; + using prehashed_signer = ed25519::prehashed_signer; // RFC 8032 section 7.1, TEST 1: the secret key (the seed). A local, since a global of this // name would be hidden by ed25519.hpp's parameter `seed` (MSVC's C4459, an error at /WX). constexpr std::string_view seed = "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60"; - auto const key = ed25519::basic_keypair::make( + auto const key = ed25519::basic_keypair::from_secret( webcpp::test::from_hex(seed)); if (!BOOST_TEST(key.has_value())) { return; } std::array const piece{1, 2, 3}; - auto signer = ph::begin(); + auto signer = prehashed_signer::begin(); if (!BOOST_TEST(signer.has_value()) || !BOOST_TEST(signer->update(piece).has_value())) { return; } @@ -203,7 +203,7 @@ void hkdf_beside_crypto() { BOOST_TEST(first_is(webcpp::test::hash_timing_first_entry, "webcpp::hash::hkdf")); BOOST_TEST_EQ(dit_set(), before); - auto const key = ed25519::basic_keypair::make(okm); + auto const key = ed25519::basic_keypair::from_secret(okm); if (!BOOST_TEST(key.has_value())) { continue; } diff --git a/test/timing_mock_test.cpp b/test/timing_mock_test.cpp index 59367d02..0f6b9283 100644 --- a/test/timing_mock_test.cpp +++ b/test/timing_mock_test.cpp @@ -52,8 +52,8 @@ struct aead_engine { /** Records whether DIT is set, then succeeds. */ [[nodiscard]] static boost::system::result seal( aead_state& /*state*/, - std::span /*iv_bytes*/, - std::span /*additional_data_bytes*/, std::span /*data*/, + std::span /*nonce_bytes*/, + std::span /*associated_data_bytes*/, std::span /*data*/, boost::hash2::digest<16>& /*tag*/) noexcept { test::dit_during_seal = dit_is_set(); return {}; @@ -62,8 +62,8 @@ struct aead_engine { /** Succeeds. */ [[nodiscard]] static boost::system::result open( aead_state& /*state*/, - std::span /*iv_bytes*/, - std::span /*additional_data_bytes*/, std::span /*data*/, + std::span /*nonce_bytes*/, + std::span /*associated_data_bytes*/, std::span /*data*/, std::array const& /*tag*/) noexcept { return {}; } @@ -83,23 +83,24 @@ struct aead_engine { namespace { namespace crypto = webcpp::crypto; -using aead = - crypto::ciphers::aead; +using cipher = crypto::ciphers::basic_chacha20_poly1305; // From clear: the backend's seal runs with DIT set where the CPU has it, and DIT is clear after. void backend_runs_with_dit() { BOOST_TEST(!crypto::detail::dit_is_set()); - std::array const key{}; - auto made = aead::make(key); + std::array const key{}; + auto made = cipher::from_key(key); if (!BOOST_TEST(made.has_value())) { return; } BOOST_TEST(!crypto::detail::dit_is_set()); - std::array const iv{}; + std::array const nonce{}; std::array data{}; webcpp::test::dit_during_seal = !crypto::detail::cpu_has_dit(); - webcpp::test::require_enters( - "aead::seal", [&made, &iv, &data] { BOOST_TEST(made->seal(iv, {}, data).has_value()); }); + webcpp::test::require_enters("basic_chacha20_poly1305::seal", [&made, &nonce, &data] { + BOOST_TEST(made->seal(nonce, {}, data).has_value()); + }); BOOST_TEST_EQ(webcpp::test::dit_during_seal, crypto::detail::cpu_has_dit()); BOOST_TEST(!crypto::detail::dit_is_set()); } @@ -108,10 +109,11 @@ void backend_runs_with_dit() { // and DIT is clear after. void early_error_restores_state() { BOOST_TEST(!crypto::detail::dit_is_set()); - std::array const short_key{}; - webcpp::test::require_enters("aead::make with a 31-byte key", [&short_key] { - BOOST_TEST(aead::make(short_key).error() == crypto::error::invalid_key_size); - }); + std::array const short_key{}; + webcpp::test::require_enters( + "basic_chacha20_poly1305::from_key with a 31-byte key", [&short_key] { + BOOST_TEST(cipher::from_key(short_key).error() == crypto::error::invalid_key_size); + }); BOOST_TEST(!crypto::detail::dit_is_set()); } diff --git a/test/timing_sodium_test.cpp b/test/timing_sodium_test.cpp index 82f38a19..a080ada0 100644 --- a/test/timing_sodium_test.cpp +++ b/test/timing_sodium_test.cpp @@ -54,13 +54,13 @@ void force_dit([[maybe_unused]] bool set) { void sign_test_1() { auto const seed = webcpp::test::from_hex(rfc8032_seed); auto const expected = webcpp::test::from_hex(rfc8032_signature); - auto const made = keypair::make(seed); + auto const made = keypair::from_secret(seed); if (!BOOST_TEST(made.has_value())) { return; } auto const signature = made->sign(webcpp::crypto::eddsa, std::span()); if (BOOST_TEST(signature.has_value())) { - BOOST_TEST(std::ranges::equal(*signature, expected)); + BOOST_TEST(std::ranges::equal(signature->bytes(), expected)); } } diff --git a/test/timing_test.cpp b/test/timing_test.cpp index 12f4f6ef..e0c1a4e9 100644 --- a/test/timing_test.cpp +++ b/test/timing_test.cpp @@ -7,16 +7,18 @@ // detail::timing_guard, with no backend: its seam fires once per guard on every target and names // the function that holds the guard, which require_enters reads in the spellings of clang, GCC // and MSVC; where the CPU has DIT, a guard sets it for its scope and clears it after when it was -// clear, leaves it set when it was set, and nests; equal enters its own guard. Built with -// WEBCPP_TEST_TIMING_THREADS (timing_threads, native, with threads), a guard on one thread leaves -// another's DIT clear. P-256's normalize_low_s and is_low_s, which call no backend, enter no -// guard: this program links none, and curves/p256.hpp needs none to declare them. +// clear, leaves it set when it was set, and nests; constant_time_equal enters its own guard. Built +// with WEBCPP_TEST_TIMING_THREADS (timing_threads, native, with threads), a guard on one thread +// leaves another's DIT clear. P-256's normalize_low_s and is_low_s, which call no backend, enter no +// guard: this program links none, and curves/p256.hpp needs none to declare them; nor does +// erase_secret, which only stores zeroes. #include "support/timing_seam.hpp" +#include #include #include -#include +#include #include #include "support/p256_data.hpp" @@ -129,8 +131,8 @@ void names_function_spellings() { // A name in the return type or a parameter type is not the function's own. BOOST_TEST(!names("int ns::other(ns::pem::armour, int) [with B = int]", "pem::armour")); BOOST_TEST(!names("int ns::other(ns::pem::armour(int)) [with B = int]", "pem::armour")); - BOOST_TEST(!names("ns::pem::armour ns::make(int) [B = int]", "pem::armour")); - BOOST_TEST(!names("struct ns::pem::armour __cdecl ns::make(int)", "pem::armour")); + BOOST_TEST(!names("ns::pem::armour ns::from_key(int) [B = int]", "pem::armour")); + BOOST_TEST(!names("struct ns::pem::armour __cdecl ns::from_key(int)", "pem::armour")); BOOST_TEST(!names("ns::algorithm>::seal(int)", "pem::armour")); BOOST_TEST(names("ns::pem::armour ns::pem::armour(ns::pem::armour)", "pem::armour")); // A function named without a scope never matches. @@ -144,18 +146,76 @@ void names_function_spellings() { BOOST_TEST(!names("auto __cdecl ns::f::::operator ()(void) const", "ns::f")); } +// GCC writes a trailing requires-clause after the parameter list, before the template arguments: +// its parentheses are not the function's own. +void names_function_requires_clause() { + constexpr std::string_view entered = + "auto ns::to_x25519(const Value&) requires requires(const Value& v) {v->to_x25519();} " + "[with Value = ns::pk]"; + BOOST_TEST( + webcpp::test::names_function(entered, webcpp::test::function_named("ns::to_x25519"))); + BOOST_TEST( + !webcpp::test::names_function(entered, webcpp::test::function_named("pk::to_x25519"))); +} + +// A check names every component it writes, each compared: the free AEAD form, +// secret_key_encryption::aead::seal, is not the member of the class template +// ciphers::basic_chacha20_poly1305, and a label names the class by its own name. +void names_function_qualifiers() { + auto const names = [](std::string_view entered, std::string_view spelled) { + return webcpp::test::names_function(entered, webcpp::test::function_named(spelled)); + }; + constexpr std::string_view member = + "boost::system::result> webcpp::crypto::ciphers::basic_chacha20_poly1305::seal(std::span, std::span, std::span) [F = f, B = b]"; + constexpr std::string_view free_form = + "boost::system::result " + "webcpp::crypto::secret_key_encryption::aead::seal(Cipher &, std::span, std::span, std::span) [Cipher = c]"; + BOOST_TEST(!names(member, "secret_key_encryption::aead::seal")); + BOOST_TEST(names(member, "ciphers::basic_chacha20_poly1305::seal")); + BOOST_TEST(names(member, "basic_chacha20_poly1305::seal")); + BOOST_TEST(!names(member, "aead::seal")); + BOOST_TEST(names(free_form, "secret_key_encryption::aead::seal")); + BOOST_TEST(!names(free_form, "ciphers::basic_chacha20_poly1305::seal")); + BOOST_TEST(names(free_form, "crypto::secret_key_encryption::aead::seal")); + BOOST_TEST(!names(free_form, "other::secret_key_encryption::aead::seal")); + // MSVC writes the class template's arguments, which each component skips. + BOOST_TEST( + !names("class boost::system::result __cdecl " + "webcpp::crypto::ciphers::basic_chacha20_poly1305::open(class std::span)", + "secret_key_encryption::aead::open")); + BOOST_TEST( + names("class boost::system::result __cdecl " + "webcpp::crypto::ciphers::basic_chacha20_poly1305::open(class std::span)", + "ciphers::basic_chacha20_poly1305::open")); +} + +// A label that starts with `::` writes no component before the identifier: its scope is empty, as +// a label without `::`, and it names no function. +void names_function_leading_separator() { + webcpp::test::named_function const named = webcpp::test::function_named("::seal"); + BOOST_TEST(named.identifier == "seal"); + BOOST_TEST(named.scope.empty()); + BOOST_TEST(named.qualifiers.empty()); + BOOST_TEST(!webcpp::test::names_function("void webcpp::crypto::seal(int)", named)); +} + // MSVC writes the exception specification of a function that may throw after its parameters, -// clang and GCC none: crypto::make and crypto::generate of secp256k1's key pair, whose memory -// resource may throw, are read as their own in either spelling. +// clang and GCC none: crypto::from_secret and crypto::generate of secp256k1's key pair, whose +// memory resource may throw, are read as their own in either spelling. void names_function_exception_specifications() { auto const names = [](std::string_view entered, std::string_view spelled) { return webcpp::test::names_function(entered, webcpp::test::function_named(spelled)); }; BOOST_TEST( names("class ns::result> __cdecl " - "ns::crypto::make,const class std::array,const class std::array&>(const class std::array &) noexcept(false)", - "crypto::make")); + "crypto::from_secret")); BOOST_TEST( names("class ns::result> __cdecl " "ns::crypto::generate,>(void) noexcept(false)", @@ -163,8 +223,8 @@ void names_function_exception_specifications() { BOOST_TEST(names("int __cdecl ns::pem::armour(int) noexcept", "pem::armour")); BOOST_TEST(names("int __cdecl ns::pk::compare(int) const noexcept(true)", "pk::compare(int")); // The specification is not a parameter list: its words never name the function. - BOOST_TEST( - !names("int __cdecl ns::crypto::make(int) noexcept(false)", "crypto::make(false")); + BOOST_TEST(!names("int __cdecl ns::crypto::from_secret(int) noexcept(false)", + "crypto::from_secret(false")); BOOST_TEST(!names("int __cdecl ns::other(int) noexcept(ns::pem::armour(int))", "pem::armour")); } @@ -206,21 +266,23 @@ void nested_guards() { BOOST_TEST(!detail::dit_is_set()); } -// Both overloads of equal enter a guard, and leave DIT as they found it. -void equal_enters() { +// Both overloads of constant_time_equal enter a guard, and leave DIT as they found it. +void constant_time_equal_enters() { force_dit(false); std::array const first{}; std::array const second{}; - webcpp::test::require_enters("equal(span, span)", "crypto::equal(span", [&first, &second] { - BOOST_TEST(webcpp::crypto::equal(std::span(first), - std::span(second))); - }); + webcpp::test::require_enters( + "constant_time_equal(span, span)", "crypto::constant_time_equal(span", [&first, &second] { + BOOST_TEST(webcpp::crypto::constant_time_equal(std::span(first), + std::span(second))); + }); boost::hash2::digest<16> const first_digest{}; boost::hash2::digest<16> const second_digest{}; - webcpp::test::require_enters("equal(digest, digest)", "crypto::equal(digest", - [&first_digest, &second_digest] { - BOOST_TEST(webcpp::crypto::equal(first_digest, second_digest)); - }); + webcpp::test::require_enters( + "constant_time_equal(digest, digest)", "crypto::constant_time_equal(digest", + [&first_digest, &second_digest] { + BOOST_TEST(webcpp::crypto::constant_time_equal(first_digest, second_digest)); + }); BOOST_TEST(!detail::dit_is_set()); } @@ -228,12 +290,27 @@ void equal_enters() { void p256_low_s_unguarded() { namespace p256 = webcpp::crypto::curves::p256; namespace data = webcpp::test::p256; - webcpp::test::uncovered("p256::normalize_low_s", [] { - auto const normalized = p256::normalize_low_s(data::rfc6979_sample); - BOOST_TEST(normalized.has_value() && *normalized == data::rfc6979_sample_low_s); + auto const sample = p256::ecdsa_signature::from_bytes(data::rfc6979_sample); + auto const test = p256::ecdsa_signature::from_bytes(data::rfc6979_test); + if (!BOOST_TEST(sample.has_value()) || !BOOST_TEST(test.has_value())) { + return; + } + webcpp::test::uncovered("p256::normalize_low_s", [&sample] { + auto const normalized = p256::normalize_low_s(*sample); + BOOST_TEST(normalized.has_value() && normalized->bytes() == data::rfc6979_sample_low_s); + }); + webcpp::test::uncovered("p256::is_low_s", [&test] { BOOST_TEST(p256::is_low_s(*test)); }); +} + +// erase_secret calls no backend: it stores zeroes through detail::wipe, and holds no guard. +void erase_secret_unguarded() { + webcpp::test::uncovered("erase_secret", [] { + std::array const zero{}; + std::array password{}; + password.fill(0x5a); + webcpp::crypto::erase_secret(password); + BOOST_TEST(password == zero); }); - webcpp::test::uncovered("p256::is_low_s", - [] { BOOST_TEST(p256::is_low_s(data::rfc6979_test)); }); } #ifdef WEBCPP_TEST_TIMING_THREADS @@ -265,12 +342,16 @@ int main() { seam_fires(); seam_names_function(); names_function_spellings(); + names_function_requires_clause(); + names_function_qualifiers(); + names_function_leading_separator(); names_function_exception_specifications(); guard_sets_and_clears(); guard_leaves_set_bit(); nested_guards(); - equal_enters(); + constant_time_equal_enters(); p256_low_s_unguarded(); + erase_secret_unguarded(); #ifdef WEBCPP_TEST_TIMING_THREADS other_thread_untouched(); #endif diff --git a/test/timing_unseamed_test.cpp b/test/timing_unseamed_test.cpp index 318ee0d0..dc73fcb1 100644 --- a/test/timing_unseamed_test.cpp +++ b/test/timing_unseamed_test.cpp @@ -7,11 +7,11 @@ // detail::timing_guard in a program's build, without the seam: its constructor takes no argument, // a std::source_location least of all, on every target, so that no guarded function's name or // header's path can reach a program. Built with WEBCPP_TEST_TIMING_READ_SELF (natively, at -// release), the program reads its own executable and finds neither the name of equal, which it -// calls, nor the path of equal.hpp, where its guards are declared. +// release), the program reads its own executable and finds neither the name of constant_time_equal, +// which it calls, nor the path of constant_time_equal.hpp, where its guards are declared. +#include #include -#include #include #include @@ -41,18 +41,19 @@ static_assert(!std::is_constructible_v, "without the seam, timing_guard is constructed from nothing, and never throws"); -// equal, both overloads, runs and answers as it does with the seam. Each call is outside -// BOOST_TEST, whose message would put the call's text, equal's name among it, in the program. -void equal_runs() { +// constant_time_equal, both overloads, runs and answers as it does with the seam. Each call is +// outside BOOST_TEST, whose message would put the call's text, constant_time_equal's name among +// it, in the program. +void constant_time_equal_runs() { std::array const first{1, 2, 3, 4}; std::array const second{1, 2, 3, 5}; - bool const same = webcpp::crypto::equal(std::span(first), - std::span(first)); - bool const different = webcpp::crypto::equal(std::span(first), - std::span(second)); + bool const same = webcpp::crypto::constant_time_equal(std::span(first), + std::span(first)); + bool const different = webcpp::crypto::constant_time_equal( + std::span(first), std::span(second)); boost::hash2::digest<4> digest; std::ranges::copy(first, digest.begin()); - bool const same_digest = webcpp::crypto::equal(digest, digest); + bool const same_digest = webcpp::crypto::constant_time_equal(digest, digest); BOOST_TEST(same); BOOST_TEST(!different); BOOST_TEST(same_digest); @@ -65,8 +66,8 @@ void equal_runs() { * pointer, which keeps it in the program whole: a search for a constant could otherwise compile * to comparisons with no copy of the text. */ -constexpr std::string_view masked_name_text = "webcpp::crypto::equal#"; -constexpr std::string_view masked_path_text = "equal.hp#"; +constexpr std::string_view masked_name_text = "webcpp::crypto::constant_time_equal#"; +constexpr std::string_view masked_path_text = "constant_time_equal.hp#"; /** * A text of the program's, read where the compiler cannot see it. @@ -106,7 +107,7 @@ bool holds(std::vector const& bytes, std::string_view text) { } // The executable holds the masked texts, which shows the search reads it whole, and neither -// equal's name, as clang, GCC and MSVC begin function_name(), nor its header's path. +// constant_time_equal's name, as clang, GCC and MSVC begin function_name(), nor its header's path. void executable_holds_no_location(char const* executable) { std::ifstream file(executable, std::ios::binary); if (!BOOST_TEST(file.is_open())) { @@ -127,7 +128,7 @@ void executable_holds_no_location(char const* executable) { // NOLINTNEXTLINE(misc-const-correctness): main's arguments have the type the standard gives them int main([[maybe_unused]] int argc, [[maybe_unused]] char** argv) { - equal_runs(); + constant_time_equal_runs(); #ifdef WEBCPP_TEST_TIMING_READ_SELF if (BOOST_TEST(argc > 0)) { executable_holds_no_location(argv[0]); diff --git a/test/user_globals_test.cpp b/test/user_globals_test.cpp new file mode 100644 index 00000000..1512d254 --- /dev/null +++ b/test/user_globals_test.cpp @@ -0,0 +1,145 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// No local name in a crypto header hides a program's global. MSVC warns, C4459, at a parameter +// or a local of a header's non-template function (inline code) that has the name of a global of +// the program ("declaration of 'timing' hides global declaration"), an error at /W4 /WX; it does +// not warn in function templates, generic lambdas or members of class templates, even +// instantiated, so the names that live only in templates are listed defensively, for a function +// that stops being a template. Clang and GCC never warn across namespaces, so the test is +// MSVC's, and natively it only compiles. A local takes two words, the role then the kind +// (`timing_scope`, `completion_token`, `signature_bytes`), which no program names a global. +// +// Every header of another library that a crypto header includes comes first, so that their own +// names are parsed before the globals exist; then a global of every one-word name a crypto +// header gave a local or a parameter until each took two words; then every public header. +// +// How the list was made: an aggregate translation unit of every header of include/, every +// backend and XKCP linked (secp256k1's Keccak-256 path), its AST dumped (clang -Xclang +// -ast-dump), each ParmVarDecl, VarDecl and BindingDecl inside a function of include/ whose name +// matches ^[a-z][a-z0-9]*$; again with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE, +// WEBCPP_CRYPTO_DETAIL_TIMING_COVERED and WEBCPP_CRYPTO_DETAIL_TIMING_ENTERED, and without +// threads, for the code only they compile. The namespace-scope constants (`eddsa`, `schnorr`, +// `strict`, the generated tables' `supported` and `linked`) and the static data members (each +// backend's `name`, `overhead`) are not locals, and are left out: C4459 applies to neither; +// `size` (ed25519's `public_key::size`) and `order` (`p_curve_traits`) are static data members +// too, listed only because they were also locals. +// +// A name that the platform's C library already declares as a global (`encrypt`, 's) +// cannot be a program's global there anyway: it is declared on MSVC alone. + +#include +#include // and on Windows, alone + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef _WIN32 +#include // lint-world: getentropy's header, which detail/entropy.hpp includes +#endif +#if defined(__aarch64__) && defined(__APPLE__) +#include // lint-world: sysctlbyname's header, which detail/timing.hpp includes +#elif defined(__aarch64__) && defined(__linux__) +#include // lint-world: getauxval's header, which detail/timing.hpp includes +#endif + +// NOLINTBEGIN(readability-redundant-declaration): clang-tidy takes Boost.Variant2's dependent +// `mp_all<...>::value` for a declaration of `value` +extern int const accepted, address, aead, again, agreed, allocator, at, beforenm, begun, block, + body, borrow, bound, bytes, c, characters, code, copy, count, data, decoded, decrypt, der, + difference, digest, done, end, executor, expected, f, feature, file, first, from, guard, + guarded, guards, half, handler, head, header, held, high, i, input, invoke, iv, job, key, keyed, + label, last, length, line, lines, location, longest, m, made, message, moved, multiplied, nonce, + nonzero, old, one, opened, opening, operation, order, other, out, output, peer, piece, pkcs8, + point, policy, prefix, printable, put, r, ran, raw, ready, receive, returned, run, s, same, + scalar, scheme, scratch, sealed, seed, separator, shared, signature, size, slot, spki, start, + started, state, storage, tag, tail, taken, text, timing, to, token, transmit, type, value, + verdict, view, visit, where, whole, wide, work, written; +#ifdef _MSC_VER +extern int const encrypt; +#endif +// NOLINTEND(readability-redundant-declaration) + +#include +#include +#include +#include + +int main() { + return 0; +} diff --git a/test/windows_h_after_test.cpp b/test/windows_h_after_test.cpp index 11a87c98..ffea206f 100644 --- a/test/windows_h_after_test.cpp +++ b/test/windows_h_after_test.cpp @@ -22,8 +22,8 @@ #include #include #include -#include #include +#include #include #include #include @@ -32,11 +32,13 @@ #include #include #include -#include #include -#include -#include +#include +#include #include +#include +#include +#include #include // webcpp undefined again the macros it defined for its own include. diff --git a/test/windows_h_before_test.cpp b/test/windows_h_before_test.cpp index cc3e915c..dfc4cb9f 100644 --- a/test/windows_h_before_test.cpp +++ b/test/windows_h_before_test.cpp @@ -37,8 +37,8 @@ #include #include #include -#include #include +#include #include #include #include @@ -47,11 +47,13 @@ #include #include #include -#include #include -#include -#include +#include +#include #include +#include +#include +#include #include #include diff --git a/test/wipe_objects_test.cpp b/test/wipe_objects_test.cpp index 684482ce..24305ee0 100644 --- a/test/wipe_objects_test.cpp +++ b/test/wipe_objects_test.cpp @@ -36,8 +36,8 @@ #elif defined(WEBCPP_TEST_WIPE_SODIUM) #include #include -#include -#include +#include +#include #else #error "name a backend: WEBCPP_TEST_WIPE_BEARSSL, _CTAES, _SECP256K1, _OPENSSL or _SODIUM" #endif @@ -117,32 +117,39 @@ constexpr std::array rfc7748_peer_key{ 0x3f, 0x83, 0x43, 0xc8, 0x5b, 0x78, 0x67, 0x4d, 0xad, 0xfc, 0x7e, 0x14, 0x6f, 0x88, 0x2b, 0x4f, }; -// A keyed object of the type under test, from a key of non-zero bytes; a box's from that secret -// key and a peer's public key. +// A keyed object of the type under test, from a key of non-zero bytes (a cipher's key, or a key +// pair's secret); a box's from the X25519 key pair of that secret key and a peer's public key. template T keyed(std::uint8_t first) { std::array key{}; for (std::size_t i = 0; i < key.size(); ++i) { key[i] = static_cast(first + i); } - if constexpr (requires { T::make(key, rfc7748_peer_key); }) { - auto made = T::make(key, rfc7748_peer_key); + if constexpr (requires { typename T::keypair_type; }) { + auto const own = T::keypair_type::from_secret(key); + auto const peer = T::public_key_type::from_bytes(rfc7748_peer_key); + webcpp::test::require(own.has_value() && peer.has_value()); + auto made = T::from_keys(*own, *peer); + webcpp::test::require(made.has_value()); + return std::move(*made); + } else if constexpr (requires { T::from_key(key); }) { + auto made = T::from_key(key); webcpp::test::require(made.has_value()); return std::move(*made); } else { - auto made = T::make(key); + auto made = T::from_secret(key); webcpp::test::require(made.has_value()); return std::move(*made); } } -// The three ways a keyed object stops holding its key; `make` makes one from a first byte. +// The three ways a keyed object stops holding its key; `make_keyed` makes one from a first byte. template -void check_wiped(region where, T (*make)(std::uint8_t) = &keyed) { +void check_wiped(region where, T (*make_keyed)(std::uint8_t) = &keyed) { { // The destructor. slot storage; - placed object(storage, make(1)); + placed object(storage, make_keyed(1)); BOOST_TEST(any_set(storage, where)); object.destroy(); BOOST_TEST(!any_set(storage, where)); @@ -152,7 +159,7 @@ void check_wiped(region where, T (*make)(std::uint8_t) = &keyed) { // none. slot from_storage; slot to_storage; - placed from(from_storage, make(1)); + placed from(from_storage, make_keyed(1)); BOOST_TEST(any_set(from_storage, where)); placed to(to_storage, std::move(*from)); BOOST_TEST(!any_set(from_storage, where)); @@ -167,8 +174,8 @@ void check_wiped(region where, T (*make)(std::uint8_t) = &keyed) { // gives up first. slot from_storage; slot to_storage; - placed from(from_storage, make(1)); - placed to(to_storage, make(100)); + placed from(from_storage, make_keyed(1)); + placed to(to_storage, make_keyed(100)); BOOST_TEST(any_set(from_storage, where)); BOOST_TEST(any_set(to_storage, where)); *to = std::move(*from); @@ -182,13 +189,20 @@ void check_wiped(region where, T (*make)(std::uint8_t) = &keyed) { } #ifdef WEBCPP_TEST_WIPE_SODIUM -// The key libsodium's AEAD or secret box of the family Family keeps in the object, first. +// The key libsodium's AEAD of the family Family keeps in the object, first. template constexpr region aead_key{ .offset = 0, .size = sizeof(crypto::detail::aead_state), }; +// The key libsodium's secret box of the family Family keeps in the object, first. +template +constexpr region secretbox_key{ + .offset = 0, + .size = sizeof(crypto::detail::secretbox_state), +}; + // The key libsodium's box of the family Family agreed and keeps in the object, first. template constexpr region box_key{ @@ -208,7 +222,7 @@ crypto::curves::secp256k1::musig::secret_nonce nonce_of(std::uint8_t first) { std::array space{}; auto const key = secp::musig::key_aggregate(keys, space); webcpp::test::require(key.has_value()); - auto made = secp::musig::nonce_gen(signer, *key); + auto made = secp::musig::generate_nonce(signer, *key); webcpp::test::require(made.has_value()); return std::move(made->secret_part); } @@ -270,12 +284,13 @@ int main() { aead_key); check_wiped>( aead_key); - check_wiped>(aead_key); - check_wiped>( - aead_key); - check_wiped>( + check_wiped>( + secretbox_key); + check_wiped>( + secretbox_key); + check_wiped>( box_key); - check_wiped>( + check_wiped>( box_key); #endif return webcpp::test::exit_status(boost::report_errors()); diff --git a/test/x25519_mock_test.cpp b/test/x25519_mock_test.cpp index f0c2744d..a6a15151 100644 --- a/test/x25519_mock_test.cpp +++ b/test/x25519_mock_test.cpp @@ -5,12 +5,13 @@ // https://www.boost.org/LICENSE_1_0.txt) // X25519's generic layer on a stand-in backend whose engine reports success for every shared -// secret: curves::x25519::agree refuses an all-zero result itself (design D8), as libsodium -// does, so that a backend that does not refuse it gives the same answer; any other result is -// the shared secret, and an engine's error is passed on. +// secret: a key pair's agree, member and free, refuses an all-zero result itself (design D8), as +// libsodium does, so that a backend that does not refuse it gives the same answer; any other +// result is the shared secret, and an engine's error is passed on, by agree and by from_secret. #include #include +#include #include #include @@ -31,7 +32,7 @@ struct x25519_stand_in {}; struct x25519_stand_in_knobs { /** The byte every byte of the shared secret is set to. */ std::uint8_t fill = 0; - /** The error agree returns, when set. */ + /** The error base and agree return, when set. */ boost::system::error_code error; }; @@ -47,10 +48,13 @@ namespace webcpp::crypto::detail { * not refuse an all-zero shared secret would. */ template <> struct x25519_engine { - /** Writes the knob's byte. */ + /** Writes the knob's byte, or returns the knob's error. */ [[nodiscard]] static boost::system::result base( std::span /*secret_key*/, std::span out) noexcept { + if (test::x25519_stand_in_control.error) { + return test::x25519_stand_in_control.error; + } std::ranges::fill(out, test::x25519_stand_in_control.fill); return {}; } @@ -74,27 +78,40 @@ namespace { namespace crypto = webcpp::crypto; namespace test = webcpp::test; -using stand_in = crypto::curves::x25519::algorithm; +using stand_in = crypto::curves::x25519::basic_keypair; -void all_zero_refused() { +/** The stand-in's key pair of the secret key {9}, made while the knobs are clear. */ +stand_in made_keypair() { test::x25519_stand_in_control = {}; std::array const key{9}; - auto const shared = stand_in::agree(key, key); + return stand_in::from_secret(key).value(); +} + +/** The peer key {9}. */ +crypto::curves::x25519::public_key peer_key() { + std::array const key{9}; + return crypto::curves::x25519::public_key::from_bytes(key).value(); +} + +void all_zero_refused() { + auto const key = made_keypair(); + test::x25519_stand_in_control = {}; + auto const shared = key.agree(peer_key()); BOOST_TEST(!shared.has_value()); if (!shared) { BOOST_TEST(shared.error() == crypto::error::weak_public_key); } - auto const named = crypto::curves::x25519::agree(key, key); - BOOST_TEST(!named.has_value()); - if (!named) { - BOOST_TEST(named.error() == crypto::error::weak_public_key); + auto const free_shared = crypto::agree(key, peer_key()); + BOOST_TEST(!free_shared.has_value()); + if (!free_shared) { + BOOST_TEST(free_shared.error() == crypto::error::weak_public_key); } } void other_result_kept() { + auto const key = made_keypair(); test::x25519_stand_in_control = {.fill = 0x5a, .error = {}}; - std::array const key{9}; - auto const shared = stand_in::agree(key, key); + auto const shared = key.agree(peer_key()); BOOST_TEST(shared.has_value()); if (shared) { auto const bytes = shared->bytes(); @@ -103,13 +120,19 @@ void other_result_kept() { } void engine_error_passed_on() { + auto const key = made_keypair(); test::x25519_stand_in_control = {.fill = 0, .error = crypto::error::backend_failure}; - std::array const key{9}; - auto const shared = stand_in::agree(key, key); + auto const shared = key.agree(peer_key()); BOOST_TEST(!shared.has_value()); if (!shared) { BOOST_TEST(shared.error() == crypto::error::backend_failure); } + std::array const secret_key{9}; + auto const refused = stand_in::from_secret(secret_key); + BOOST_TEST(!refused.has_value()); + if (!refused) { + BOOST_TEST(refused.error() == crypto::error::backend_failure); + } } } // namespace diff --git a/test/x25519_sodium_test.cpp b/test/x25519_sodium_test.cpp index ad8198af..a5e63335 100644 --- a/test/x25519_sodium_test.cpp +++ b/test/x25519_sodium_test.cpp @@ -4,18 +4,34 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// X25519 on libsodium: RFC 7748 section 5.2's two scalar multiplications and section 6.1's -// Alice and Bob; a peer key of order 8 (Wycheproof's tcId 63) refused with weak_public_key; the -// guards (keys of other sizes); detail::is_all_zero; and the conversion from Ed25519: the X25519 -// public key of a key pair's x25519_secret() equals curves::ed25519::to_x25519_public of its -// Ed25519 public key, and an Ed25519 key of small order, of mixed order, not canonical or off the -// curve is invalid_public_key. +// X25519 on libsodium, on typed keys: +// - rfc7748_section_5_2: section 5.2's two scalar multiplications, the scalar a key pair's secret +// key and the u-coordinate a public key made by from_bytes. +// - rfc7748: section 6.1's Alice and Bob, made with from_secret, give the RFC's public keys and +// agree in both directions on the RFC's shared secret, through the member, the free +// crypto::agree, the free crypto::from_secret and the backend named; detail::x25519_access views +// the key pair's own bytes. +// - secret_round_trip: from_secret of a key pair's secret() has its public key. +// - sizes: from_bytes of 31 and 33 bytes is invalid_public_key, from_secret of 31 and 33 bytes +// invalid_key_size. +// - weak_peer: a peer key of order 8 (Wycheproof's tcId 63) and one of 32 zero bytes are refused +// by agree with weak_public_key. +// - moved_from: a key pair moved from, by construction and by assignment, refuses public_key, +// secret and agree with invalid_state, and detail::x25519_access::keyed says it holds no key; +// the one moved to agrees as the source did. +// - generated: two generated key pairs differ and agree with each other. +// - all_zero: detail::is_all_zero. +// - conversion: the public key of an Ed25519 key pair's to_x25519() equals its Ed25519 public +// key's to_x25519(), and an Ed25519 key of small order, of mixed order, not canonical or off the +// curve is invalid_public_key. #include #include #include #include #include +#include +#include #include #include @@ -23,11 +39,13 @@ #include +#include #include #include #include #include #include +#include #include namespace crypto = webcpp::crypto; @@ -48,9 +66,30 @@ std::vector bytes_of(std::array const& key) { return {key.begin(), key.end()}; } +/** The bytes of a typed public key, as a vector a test compares. */ +std::vector bytes_of(x25519::public_key const& key) { + return bytes_of(key.bytes()); +} + +constexpr std::string_view alice_secret_hex = + "77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a"; +constexpr std::string_view alice_public_hex = + "8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a"; +constexpr std::string_view bob_secret_hex = + "5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb"; +constexpr std::string_view bob_public_hex = + "de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f"; +constexpr std::string_view shared_hex = + "4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742"; + /** RFC 7748 section 5.2: an input scalar and u-coordinate, and the output u-coordinate. */ void scalar_multiplication(std::string_view scalar, std::string_view u, std::string_view out) { - auto const shared = x25519::agree(test::from_hex(scalar), test::from_hex(u)); + auto const key = x25519::keypair::from_secret(test::from_hex(scalar)); + auto const peer = x25519::public_key::from_bytes(test::from_hex(u)); + if (!BOOST_TEST(key.has_value()) || !BOOST_TEST(peer.has_value())) { + return; + } + auto const shared = key->agree(*peer); BOOST_TEST(shared.has_value()); if (shared) { BOOST_TEST(bytes_of(*shared) == test::from_hex(out)); @@ -66,59 +105,150 @@ void rfc7748_section_5_2() { "95cbde9476e8907d7aade45cb4b873f88b595a68799fa152e6f8f7647aac7957"); } -void rfc7748_section_6_1() { - auto const alice_secret = - test::from_hex("77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a"); - auto const bob_secret = - test::from_hex("5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb"); - auto const alice_public = x25519::public_key(alice_secret); - auto const bob_public = x25519::public_key(bob_secret); - BOOST_TEST(alice_public.has_value()); - BOOST_TEST(bob_public.has_value()); - if (!alice_public || !bob_public) { +void rfc7748() { + auto const alice = x25519::keypair::from_secret(test::from_hex(alice_secret_hex)); + auto const bob = x25519::basic_keypair::from_secret( + test::from_hex(bob_secret_hex)); + if (!BOOST_TEST(alice.has_value()) || !BOOST_TEST(bob.has_value())) { return; } - BOOST_TEST(bytes_of(*alice_public) == - test::from_hex("8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a")); - BOOST_TEST(bytes_of(*bob_public) == - test::from_hex("de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f")); - auto const shared = - test::from_hex("4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742"); - auto const alice_shared = x25519::agree(alice_secret, *bob_public); - auto const bob_shared = - x25519::algorithm::agree(bob_secret, *alice_public); - BOOST_TEST(alice_shared.has_value()); - BOOST_TEST(bob_shared.has_value()); - if (alice_shared && bob_shared) { - BOOST_TEST(bytes_of(*alice_shared) == shared); - BOOST_TEST(bytes_of(*bob_shared) == shared); + auto const alice_public = alice->public_key(); + auto const bob_public = bob->public_key(); + if (!BOOST_TEST(alice_public.has_value()) || !BOOST_TEST(bob_public.has_value())) { + return; } + BOOST_TEST(bytes_of(*alice_public) == test::from_hex(alice_public_hex)); + BOOST_TEST(bytes_of(*bob_public) == test::from_hex(bob_public_hex)); + auto const shared = test::from_hex(shared_hex); + auto const alice_shared = alice->agree(*bob_public); + auto const bob_shared = bob->agree(*alice_public); + BOOST_TEST(alice_shared.has_value() && bytes_of(*alice_shared) == shared); + BOOST_TEST(bob_shared.has_value() && bytes_of(*bob_shared) == shared); + + // The free forms equal the members. + auto const free_shared = crypto::agree(*alice, *bob_public); + BOOST_TEST(free_shared.has_value() && bytes_of(*free_shared) == shared); + auto const free_made = crypto::from_secret(test::from_hex(alice_secret_hex)); + BOOST_TEST(free_made.has_value() && free_made->public_key() == alice_public); + + // The access the boxes and crypto_kx use views the key pair's own bytes. + auto const secret_key = alice->secret(); + BOOST_TEST(secret_key.has_value() && + std::ranges::equal(crypto::detail::x25519_access::secret_bytes(*alice), + secret_key->bytes())); + BOOST_TEST(std::ranges::equal(crypto::detail::x25519_access::public_bytes(*alice), + alice_public->bytes())); } -void weak_peer() { - // Wycheproof x25519_test.json, tcId 63: a public key of order 8, whose shared secret is 0. - auto const shared = x25519::agree( - test::from_hex("e0f978dfcd3a8f1a5093418de54136a584c20b7b349afdf6c0520886f95b1272"), - test::from_hex("e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b800")); - BOOST_TEST(!shared.has_value()); - BOOST_TEST(shared.error() == crypto::error::weak_public_key); +void secret_round_trip() { + auto const key = x25519::keypair::from_secret(test::from_hex(alice_secret_hex)); + if (!BOOST_TEST(key.has_value())) { + return; + } + auto const secret_key = key->secret(); + if (!BOOST_TEST(secret_key.has_value())) { + return; + } + BOOST_TEST(bytes_of(*secret_key) == test::from_hex(alice_secret_hex)); + auto const again = x25519::keypair::from_secret(secret_key->bytes()); + BOOST_TEST(again.has_value() && again->public_key() == key->public_key()); } -void guards() { - std::array const long_key{}; - std::array const key{9}; - BOOST_TEST(x25519::public_key(std::span(long_key).first(31)).error() == - crypto::error::invalid_key_size); - BOOST_TEST(x25519::public_key(long_key).error() == crypto::error::invalid_key_size); - BOOST_TEST(x25519::agree(std::span(long_key).first(31), key).error() == +void sizes() { + std::array const long_key{9}; + BOOST_TEST(x25519::public_key::from_bytes(std::span(long_key).first(31)).error() == + crypto::error::invalid_public_key); + BOOST_TEST(x25519::public_key::from_bytes(long_key).error() == + crypto::error::invalid_public_key); + BOOST_TEST(crypto::from_bytes(long_key).error() == + crypto::error::invalid_public_key); + BOOST_TEST(x25519::public_key::from_bytes(std::span(long_key).first(32)).has_value()); + BOOST_TEST(x25519::keypair::from_secret(std::span(long_key).first(31)).error() == crypto::error::invalid_key_size); - BOOST_TEST(x25519::agree(key, std::span(long_key).first(31)).error() == + BOOST_TEST(x25519::keypair::from_secret(long_key).error() == crypto::error::invalid_key_size); + // An Ed25519 key of another size is never made, so its to_x25519() never sees one. + BOOST_TEST(ed25519::public_key::from_bytes(std::span(long_key).first(31)).error() == crypto::error::invalid_public_key); - BOOST_TEST(x25519::agree(key, long_key).error() == crypto::error::invalid_public_key); - // An Ed25519 key of another size is never made, so to_x25519_public never sees one. - BOOST_TEST(ed25519::public_key::make(std::span(long_key).first(31)).error() == + BOOST_TEST(ed25519::public_key::from_bytes(long_key).error() == crypto::error::invalid_public_key); - BOOST_TEST(ed25519::public_key::make(long_key).error() == crypto::error::invalid_public_key); +} + +/** A key pair's agreement with a peer key's bytes, refused with weak_public_key. */ +void refused_as_weak(x25519::keypair const& key, std::span peer_bytes) { + auto const peer = x25519::public_key::from_bytes(peer_bytes); + if (!BOOST_TEST(peer.has_value())) { + return; + } + auto const shared = key.agree(*peer); + BOOST_TEST(!shared.has_value()); + if (!shared) { + BOOST_TEST(shared.error() == crypto::error::weak_public_key); + } +} + +void weak_peer() { + // Wycheproof x25519_test.json, tcId 63: a public key of order 8, whose shared secret is 0. + auto const key = x25519::keypair::from_secret( + test::from_hex("e0f978dfcd3a8f1a5093418de54136a584c20b7b349afdf6c0520886f95b1272")); + if (!BOOST_TEST(key.has_value())) { + return; + } + refused_as_weak( + *key, test::from_hex("e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b800")); + std::array const zero_point{}; + refused_as_weak(*key, zero_point); +} + +/** Whether a key pair refuses its three members with invalid_state. */ +void refuses_every_member(x25519::keypair const& key, x25519::public_key const& peer) { + BOOST_TEST(key.public_key().error() == crypto::error::invalid_state); + BOOST_TEST(key.secret().error() == crypto::error::invalid_state); + BOOST_TEST(key.agree(peer).error() == crypto::error::invalid_state); +} + +void moved_from() { + auto made = x25519::keypair::from_secret(test::from_hex(alice_secret_hex)); + auto other = x25519::keypair::from_secret(test::from_hex(bob_secret_hex)); + auto const peer = x25519::public_key::from_bytes(test::from_hex(bob_public_hex)); + if (!BOOST_TEST(made.has_value()) || !BOOST_TEST(other.has_value()) || + !BOOST_TEST(peer.has_value())) { + return; + } + BOOST_TEST(crypto::detail::x25519_access::keyed(*made)); + x25519::keypair taken(std::move(*made)); + // NOLINTNEXTLINE(bugprone-use-after-move): the moved-from key pair holds no key + BOOST_TEST(!crypto::detail::x25519_access::keyed(*made)); + BOOST_TEST(crypto::detail::x25519_access::keyed(taken)); + // NOLINTNEXTLINE(bugprone-use-after-move): the moved-from key pair's refusal + refuses_every_member(*made, *peer); + auto const shared = taken.agree(*peer); + BOOST_TEST(shared.has_value() && bytes_of(*shared) == test::from_hex(shared_hex)); + taken = std::move(*other); + // NOLINTNEXTLINE(bugprone-use-after-move): the moved-from key pair holds no key + BOOST_TEST(!crypto::detail::x25519_access::keyed(*other)); + BOOST_TEST(crypto::detail::x25519_access::keyed(taken)); + // NOLINTNEXTLINE(bugprone-use-after-move): the moved-from key pair's refusal + refuses_every_member(*other, *peer); + auto const own = taken.public_key(); + BOOST_TEST(own.has_value() && bytes_of(*own) == test::from_hex(bob_public_hex)); +} + +void generated() { + auto const first = x25519::keypair::generate(); + auto const second = crypto::generate(); + if (!BOOST_TEST(first.has_value()) || !BOOST_TEST(second.has_value())) { + return; + } + auto const first_public = first->public_key(); + auto const second_public = second->public_key(); + if (!BOOST_TEST(first_public.has_value()) || !BOOST_TEST(second_public.has_value())) { + return; + } + BOOST_TEST(!(*first_public == *second_public)); + auto const first_shared = first->agree(*second_public); + auto const second_shared = second->agree(*first_public); + BOOST_TEST(first_shared.has_value() && second_shared.has_value() && + bytes_of(*first_shared) == bytes_of(*second_shared)); } void all_zero() { @@ -132,23 +262,23 @@ void all_zero() { BOOST_TEST(!crypto::detail::is_all_zero(bytes)); } -/** One Ed25519 key pair's X25519 public key, derived from its secret and converted. */ +/** One Ed25519 key pair's X25519 public key, of its converted key pair and converted itself. */ void converted(std::string_view seed) { - auto const key = ed25519::keypair::make(test::from_hex(seed)); + auto const key = ed25519::keypair::from_secret(test::from_hex(seed)); BOOST_TEST(key.has_value()); if (!key) { return; } - auto const secret_key = key->x25519_secret(); + auto const x25519_key = key->to_x25519(); auto const ed25519_public = key->public_key(); - BOOST_TEST(secret_key.has_value()); + BOOST_TEST(x25519_key.has_value()); BOOST_TEST(ed25519_public.has_value()); - if (!secret_key || !ed25519_public) { + if (!x25519_key || !ed25519_public) { return; } - auto const derived = x25519::public_key(secret_key->bytes()); - auto const converted_key = ed25519::to_x25519_public(*ed25519_public); - auto const named = ed25519::to_x25519_public(*ed25519_public); + auto const derived = x25519_key->public_key(); + auto const converted_key = ed25519_public->to_x25519(); + auto const named = ed25519_public->to_x25519(); BOOST_TEST(derived.has_value()); BOOST_TEST(converted_key.has_value()); BOOST_TEST(named.has_value()); @@ -193,11 +323,11 @@ void conversion_refuses() { }); for (auto const key : refused) { // Made, since the size is right: the conversion judges the point. - auto const made = ed25519::public_key::make(test::from_hex(key)); + auto const made = ed25519::public_key::from_bytes(test::from_hex(key)); if (!BOOST_TEST(made.has_value())) { continue; } - auto const converted = ed25519::to_x25519_public(*made); + auto const converted = made->to_x25519(); BOOST_TEST(!converted.has_value()); if (!converted) { BOOST_TEST(converted.error() == crypto::error::invalid_public_key); @@ -205,20 +335,31 @@ void conversion_refuses() { } } -// The algorithm names its family, its name and its backend, as the capability table does. -static_assert(std::is_same_v::family_type, crypto::families::x25519>); -static_assert(std::is_same_v::name_type, crypto::families::x25519>); -static_assert(std::is_same_v::backend_type, crypto::backends::sodium>); -static_assert(x25519::algorithm<>::key_size == 32); -static_assert(crypto::supports_v, crypto::backends::sodium>); +// The key pair names its family, its name and its backend, as the capability table does. +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(x25519::keypair::secret_key_size == 32); +static_assert(x25519::public_key::public_key_size == 32); +static_assert(crypto::supports_v); +// The public key is made by from_bytes and a key pair alone; the key pair is not copied. +static_assert(!std::is_default_constructible_v); +static_assert(!std::is_default_constructible_v); +static_assert(!std::is_copy_constructible_v); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_move_assignable_v); } // namespace int main() { rfc7748_section_5_2(); - rfc7748_section_6_1(); + rfc7748(); + secret_round_trip(); + sizes(); weak_peer(); - guards(); + moved_from(); + generated(); all_zero(); conversion(); conversion_refuses(); diff --git a/test/x25519_wycheproof_sodium_test.cpp b/test/x25519_wycheproof_sodium_test.cpp index c7d6ed5a..752176c9 100644 --- a/test/x25519_wycheproof_sodium_test.cpp +++ b/test/x25519_wycheproof_sodium_test.cpp @@ -4,10 +4,11 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// X25519 against Wycheproof's file (testvectors_v1/x25519_test.json) through curves::x25519::agree -// on libsodium, every case: each shared secret Wycheproof gives, except the all-zero ones (keys of -// low order), which libsodium refuses and agree reports as weak_public_key (design D8). A -// disagreement is reported, never listed away. +// X25519 against Wycheproof's file (testvectors_v1/x25519_test.json) on typed keys, a key pair +// made by from_secret agreeing with a public key made by from_bytes, on libsodium, every case: +// each shared secret Wycheproof gives, except the all-zero ones (keys of low order), which +// libsodium refuses and agree reports as weak_public_key (design D8). A disagreement is reported, +// never listed away. #include #include @@ -51,7 +52,13 @@ outcome run_case(json::value const& tested) { BOOST_ERROR(((label += ": the verdict ") += verdict).c_str()); return outcome::unknown; } - auto const shared = x25519::agree(secret_key, peer_key); + auto const key = x25519::keypair::from_secret(secret_key); + auto const peer = x25519::public_key::from_bytes(peer_key); + if (!key || !peer) { + BOOST_ERROR((label += ": a key of Wycheproof's not made").c_str()); + return outcome::unknown; + } + auto const shared = key->agree(*peer); if (std::ranges::all_of(expected, [](std::uint8_t byte) { return byte == 0; })) { if (shared || shared.error() != crypto::error::weak_public_key) { BOOST_ERROR((label += ": an all-zero secret not refused as weak_public_key").c_str()); diff --git a/test/xchacha_sodium_test.cpp b/test/xchacha_sodium_test.cpp index c55038ab..57f6c28b 100644 --- a/test/xchacha_sodium_test.cpp +++ b/test/xchacha_sodium_test.cpp @@ -26,12 +26,13 @@ using xchacha = crypto::ciphers::xchacha20_poly1305<>; static_assert(std::is_same_v, crypto::backends::sodium>); -static_assert(std::is_same_v>); +static_assert( + std::is_same_v>); static_assert(std::is_same_v); static_assert(std::is_same_v); static_assert(crypto::supports_v); -static_assert(xchacha::key_size == 32 && xchacha::iv_size == 24 && xchacha::tag_size == 16); +static_assert(xchacha::key_size == 32 && xchacha::nonce_size == 24 && xchacha::tag_size == 16); static_assert(xchacha::max_message_size == ~std::uint64_t{0} - 16); int main() {