From e91af7e3f258341bc5aef09cda3180a4677145bc Mon Sep 17 00:00:00 2001 From: R Date: Mon, 30 Nov 2026 17:02:03 -0300 Subject: [PATCH 01/81] crypto: the scheme tags and prehashed move to crypto::signing_schemes; the namespaces formats, signing_schemes and verification_policies are declared --- bench/operations.hpp | 63 ++-- doc/async.adoc | 6 +- doc/backends.adoc | 2 +- doc/curves.adoc | 94 ++--- doc/ed25519.adoc | 58 ++-- doc/everyday.adoc | 2 +- doc/formats.adoc | 2 +- doc/generated/constant-time.adoc | 2 +- doc/generated/messages.adoc | 158 ++++----- doc/generated/namespace-curves.adoc | 4 +- doc/generated/use-cases.adoc | 14 +- doc/llms.txt | 66 ++-- doc/overview.adoc | 2 +- doc/p256.adoc | 32 +- doc/p2p.adoc | 2 +- doc/secp256k1.adoc | 56 +-- doc/tables/crypto.json | 115 +++---- doc/wallets.adoc | 10 +- example/Jamfile | 4 +- example/arena_signer.cpp | 4 +- example/async_sign.cpp | 15 +- example/bitcoin_sighash.cpp | 11 +- example/ecdsa_der.cpp | 15 +- example/ed25519_sign.cpp | 35 +- example/ethereum_personal_sign.cpp | 25 +- example/four_forms.cpp | 28 +- example/key_formats.cpp | 5 +- example/key_tweak.cpp | 5 +- example/musig_network.cpp | 4 +- example/musig_taproot.cpp | 6 +- example/musig_wallet.cpp | 4 +- example/p256_handshake.cpp | 10 +- example/p256_sign.cpp | 17 +- example/recover_signer.cpp | 17 +- example/schnorr_sign.cpp | 8 +- example/signed_message.cpp | 9 +- example/signed_update.cpp | 10 +- example/taproot_tweak.cpp | 5 +- include/webcpp/crypto/async.hpp | 195 ++++++----- include/webcpp/crypto/backends/secp256k1.hpp | 11 +- include/webcpp/crypto/config.hpp | 25 ++ include/webcpp/crypto/curves/ed25519.hpp | 231 +++++++------ include/webcpp/crypto/curves/p256.hpp | 111 +++--- include/webcpp/crypto/curves/secp256k1.hpp | 288 +++++++++------- .../webcpp/crypto/curves/secp256k1/musig.hpp | 2 +- include/webcpp/crypto/keypair.hpp | 6 +- include/webcpp/crypto/signing.hpp | 142 +++++--- test/Jamfile | 8 +- test/allocation_bearssl_test.cpp | 11 +- test/allocation_sodium_test.cpp | 16 +- test/async_25519_test.cpp | 144 ++++---- test/async_p256_test.cpp | 130 +++---- test/async_post_test.cpp | 8 +- test/constant_time/bearssl_verdicts.supp | 2 +- test/constant_time/dudect_sodium_test.cpp | 2 +- test/constant_time/dudect_test.cpp | 4 +- test/constant_time/paths.hpp | 22 +- test/convenience_header_test.cpp | 4 +- test/crypto_secp256k1_test.cpp | 9 +- test/ed25519_sodium_test.cpp | 144 ++++---- test/ed25519_speccheck_test.cpp | 19 +- test/ed25519_wycheproof_sodium_test.cpp | 8 +- test/ed25519ph_sodium_test.cpp | 146 ++++---- test/formats_25519_sodium_test.cpp | 4 +- test/formats_25519_webcrypto_oracle_test.cpp | 4 +- test/keypair_test.cpp | 108 +++--- test/messages/Jamfile | 1 + .../async_member_without_async_hpp.cpp | 4 +- .../async_sign_ed25519_prehashed.cpp | 12 +- ...n_eddsa_prehashed_asynchronous_backend.cpp | 16 +- .../async_sign_p256_eddsa.cpp | 9 +- .../async_sign_secp256k1.cpp | 8 +- .../async_sign_x25519/async_sign_x25519.cpp | 2 +- .../async_verify_eddsa_bytes_key.cpp | 8 +- ...y_eddsa_prehashed_asynchronous_backend.cpp | 26 +- .../async_verify_named_backend.cpp | 14 +- .../async_verify_p256_bytes_signature.cpp | 4 +- .../async_verify_wrong_key.cpp | 18 +- .../ed25519_unknown_policy.cpp | 2 +- .../prehashed_dynamic/prehashed_dynamic.cpp | 6 +- .../recover_ecdsa_signature.cpp | 6 +- .../scheme_in_crypto_namespace/Jamfile | 14 + .../scheme_in_crypto_namespace.cpp | 25 ++ .../sign_asynchronous_backend.cpp | 2 +- .../sign_ed25519_ecdsa/sign_ed25519_ecdsa.cpp | 8 +- .../sign_ed25519_keccak.cpp | 8 +- .../sign_ed25519_prehashed.cpp | 14 +- ...n_eddsa_prehashed_asynchronous_backend.cpp | 18 +- .../sign_eddsa_prehashed_digest_32.cpp | 11 +- .../sign_eddsa_prehashed_message.cpp | 15 +- .../sign_free_ed25519_ecdsa.cpp | 4 +- .../sign_free_public_key.cpp | 2 +- .../sign_keccak_digest_20.cpp | 6 +- .../sign_keccak_without_xkcp.cpp | 4 +- .../sign_p256_digest_48.cpp | 5 +- .../sign_p256_keccak/sign_p256_keccak.cpp | 4 +- .../sign_p256_schnorr/sign_p256_schnorr.cpp | 4 +- .../sign_schnorr_prehashed.cpp | 14 +- .../sign_secp256k1_eddsa.cpp | 8 +- .../sign_secp256k1_not_a_scheme.cpp | 2 +- .../sign_secp256k1_recoverable_digest_48.cpp | 6 +- test/messages/sign_x25519/sign_x25519.cpp | 2 +- .../verify_asynchronous_backend.cpp | 3 +- .../verify_ecdsa_bytes_key.cpp | 7 +- .../verify_ed25519_bytes_signature.cpp | 7 +- .../verify_eddsa_bytes_key.cpp | 8 +- ...y_eddsa_prehashed_asynchronous_backend.cpp | 21 +- .../verify_eddsa_prehashed_message.cpp | 11 +- .../verify_free_asynchronous_backend.cpp | 3 +- .../verify_free_secp256k1_recoverable.cpp | 6 +- .../verify_keccak_recoverable.cpp | 10 +- .../verify_member_ed25519_ecdsa.cpp | 7 +- .../verify_member_eddsa_prehashed.cpp | 13 +- .../verify_member_p256_eddsa.cpp | 5 +- .../verify_member_secp256k1_recoverable.cpp | 5 +- .../verify_p256_secp256k1_signature.cpp | 6 +- .../verify_schnorr_as_ecdsa.cpp | 7 +- test/msvc/async_sign_secp256k1/app.cpp | 4 +- test/msvc/canary_secp256k1_missing/app.cpp | 2 +- test/msvc/canary_secp256k1_small/app.cpp | 2 +- test/msvc/canary_secp256k1_two_files/app.cpp | 4 +- .../msvc/canary_secp256k1_two_files/other.cpp | 2 +- test/msvc/ed25519_unknown_policy/app.cpp | 2 +- .../msvc/sign_eddsa_prehashed_message/app.cpp | 11 +- test/msvc/sign_keccak_without_xkcp/app.cpp | 2 +- test/oracle_25519_test.cpp | 5 +- test/p256_ecdsa_bearssl_test.cpp | 137 ++++---- test/p256_keys_bearssl_test.cpp | 14 +- test/p256_openssl_oracle_test.cpp | 11 +- test/p256_webcrypto_oracle_test.cpp | 11 +- test/p256_wycheproof_bearssl_test.cpp | 6 +- test/secp256k1_allocation_test.cpp | 33 +- test/secp256k1_bip340_test.cpp | 16 +- test/secp256k1_c_api_test.cpp | 6 +- test/secp256k1_der_test.cpp | 29 +- test/secp256k1_ethereum_test.cpp | 109 +++--- test/secp256k1_formats_test.cpp | 8 +- test/secp256k1_generate_test.cpp | 15 +- test/secp256k1_keccak_alone_test.cpp | 14 +- test/secp256k1_musig_test.cpp | 36 +- test/secp256k1_recovery_test.cpp | 118 ++++--- test/secp256k1_silent_payments_test.cpp | 2 +- test/secp256k1_test.cpp | 322 ++++++++++-------- test/secp256k1_wycheproof_test.cpp | 12 +- test/secp256k1_xonly_tweak_test.cpp | 5 +- test/signature_types_test.cpp | 79 +++-- test/signing_curves_test.cpp | 168 ++++----- test/signing_namespaces_test.cpp | 100 ++++++ test/signing_test.cpp | 263 ++++++++------ test/support/secp256k1_checks.hpp | 17 +- test/support/timing_coverage.hpp | 31 +- test/synchronous_forms_test.cpp | 103 +++--- test/timing_coverage_bearssl_test.cpp | 105 +++--- test/timing_coverage_secp256k1_test.cpp | 221 +++++++----- test/timing_coverage_sodium_test.cpp | 105 +++--- test/timing_sodium_test.cpp | 3 +- 156 files changed, 3014 insertions(+), 2279 deletions(-) create mode 100644 test/messages/scheme_in_crypto_namespace/Jamfile create mode 100644 test/messages/scheme_in_crypto_namespace/scheme_in_crypto_namespace.cpp create mode 100644 test/signing_namespaces_test.cpp diff --git a/bench/operations.hpp b/bench/operations.hpp index 16e62201..23be8def 100644 --- a/bench/operations.hpp +++ b/bench/operations.hpp @@ -187,12 +187,15 @@ class secp256k1 { filled<32>(static_cast(seed | 1U))), "from_secret")) {} - std::uint8_t run() { return take(key_.sign(schnorr, message_, aux_), "sign").bytes()[0]; } + std::uint8_t run() { + return take(key_.sign(signing_schemes::schnorr, message_, aux_), "sign").bytes()[0]; + } bool check() { - auto const signature = take(key_.sign(schnorr, message_, aux_), "sign"); + auto const signature = take(key_.sign(signing_schemes::schnorr, message_, aux_), "sign"); auto const public_key = take(key_.public_key(), "public_key"); - return crypto::verify(schnorr, signature, message_, public_key).has_value(); + return crypto::verify(signing_schemes::schnorr, signature, message_, public_key) + .has_value(); } private: @@ -249,19 +252,23 @@ class secp256k1_recover { key_(take(curves::secp256k1::basic_keypair::from_secret( filled<32>(static_cast(seed | 1U))), "from_secret")), - signature_(take(key_.sign(ecdsa_sha256_recoverable, prehashed{hash_}), "sign")) {} + signature_(take(key_.sign(signing_schemes::ecdsa_sha256_recoverable, + signing_schemes::prehashed{hash_}), + "sign")) {} std::uint8_t run() { - auto const recovered = take(curves::secp256k1::recover( - ecdsa_sha256_recoverable, signature_, prehashed{hash_}), - "recover"); + auto const recovered = + take(curves::secp256k1::recover(signing_schemes::ecdsa_sha256_recoverable, + signature_, signing_schemes::prehashed{hash_}), + "recover"); return recovered.compressed()[1]; } bool check() { - auto const recovered = take(curves::secp256k1::recover( - ecdsa_sha256_recoverable, signature_, prehashed{hash_}), - "recover"); + auto const recovered = + take(curves::secp256k1::recover(signing_schemes::ecdsa_sha256_recoverable, + signature_, signing_schemes::prehashed{hash_}), + "recover"); return recovered == take(key_.public_key(), "public_key"); } @@ -339,7 +346,8 @@ class secp256k1_musig { std::uint8_t run() { return sign().bytes()[0]; } bool check() { - return crypto::verify(schnorr, sign(), message_, signers_key_.xonly_public_key()) + return crypto::verify(signing_schemes::schnorr, sign(), message_, + signers_key_.xonly_public_key()) .has_value(); } @@ -466,13 +474,17 @@ class p256 { "from_secret")) {} std::uint8_t run() { - return take(key_.sign(ecdsa_sha256, prehashed{digest_}), "sign").bytes()[0]; + return take(key_.sign(signing_schemes::ecdsa_sha256, signing_schemes::prehashed{digest_}), + "sign") + .bytes()[0]; } bool check() { - auto const signature = take(key_.sign(ecdsa_sha256, prehashed{digest_}), "sign"); + auto const signature = take( + key_.sign(signing_schemes::ecdsa_sha256, signing_schemes::prehashed{digest_}), "sign"); auto const public_key = take(key_.public_key(), "public_key"); - return crypto::verify(ecdsa_sha256, signature, prehashed{digest_}, public_key) + return crypto::verify(signing_schemes::ecdsa_sha256, signature, + signing_schemes::prehashed{digest_}, public_key) .has_value() && curves::p256::is_low_s(signature); } @@ -496,10 +508,14 @@ class p256_verify_ecdsa { filled<32>(static_cast(seed | 1U))), "from_secret")), public_key_(take(key_.public_key(), "public_key")), - signature_(take(key_.sign(ecdsa_sha256, prehashed{digest_}), "sign")) {} + signature_( + take(key_.sign(signing_schemes::ecdsa_sha256, signing_schemes::prehashed{digest_}), + "sign")) {} std::uint8_t run() { - take(crypto::verify(ecdsa_sha256, signature_, prehashed{digest_}, public_key_), "verify"); + take(crypto::verify(signing_schemes::ecdsa_sha256, signature_, + signing_schemes::prehashed{digest_}, public_key_), + "verify"); return signature_.bytes()[0]; } @@ -508,9 +524,12 @@ class p256_verify_ecdsa { 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_) + return crypto::verify(signing_schemes::ecdsa_sha256, signature_, + signing_schemes::prehashed{digest_}, public_key_) .has_value() && - !crypto::verify(ecdsa_sha256, other, prehashed{digest_}, public_key_).has_value(); + !crypto::verify(signing_schemes::ecdsa_sha256, other, + signing_schemes::prehashed{digest_}, public_key_) + .has_value(); } private: @@ -565,12 +584,14 @@ class ed25519 { key_(take(curves::ed25519::basic_keypair::from_secret(filled<32>(seed)), "from_secret")) {} - std::uint8_t run() { return take(key_.sign(eddsa, message_), "sign").bytes()[0]; } + std::uint8_t run() { + return take(key_.sign(signing_schemes::eddsa, message_), "sign").bytes()[0]; + } bool check() { - auto const signature = take(key_.sign(eddsa, message_), "sign"); + auto const signature = take(key_.sign(signing_schemes::eddsa, message_), "sign"); auto const public_key = take(key_.public_key(), "public_key"); - return crypto::verify(eddsa, signature, message_, public_key, + return crypto::verify(signing_schemes::eddsa, signature, message_, public_key, curves::ed25519::strict) .has_value(); } diff --git a/doc/async.adoc b/doc/async.adoc index 0cbbc843..c57c5c2b 100644 --- a/doc/async.adoc +++ b/doc/async.adoc @@ -52,7 +52,7 @@ its own, and the handler would run off the program's loop. | `void(error_code, Secretbox)` for `async_from_key`, `void(error_code, tag)` for `async_seal`, `void(error_code)` for `async_open` | Ed25519 (<>) -| `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 +| `async_from_secret(executor, seed, token)`, `async_generate(executor, token)`, `async_sign(executor, key_pair, crypto::signing_schemes::eddsa, message, token)`, `async_verify(executor, crypto::signing_schemes::eddsa, signature, message, public_key, token)`, the policy optional before the token; on a native backend the same under `crypto::signing_schemes::eddsa_prehashed` with `+crypto::signing_schemes::prehashed{digest}+`, the message's SHA-512 (<>), which the browser's backend refuses at compile time | `void(error_code, Keypair)` for `async_from_secret` and `async_generate`, `void(error_code, signature)` for `async_sign`, `void(error_code)` for `async_verify` | X25519 (<>) @@ -60,7 +60,7 @@ its own, and the handler would run off the program's loop. | `void(error_code, Keypair)` for `async_from_secret` and `async_generate`, `void(error_code, secure::secret<32>)` for `async_agree` | P-256 (<>) -| `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)` +| `async_from_secret(executor, scalar, token)`, `async_generate(executor, token)`, `async_sign(executor, key_pair, crypto::signing_schemes::ecdsa_sha256, input, token)`, `async_verify(executor, crypto::signing_schemes::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, secure::secret<32>)` for `async_agree` |=== @@ -89,7 +89,7 @@ synchronous call refuses stops the build here too with SHA-256, as WebCrypto's `+sign({name: "ECDSA", hash: "SHA-256"}, ...)+` hashes and signs in one call (link:https://www.w3.org/TR/WebCryptoAPI/#ecdsa-operations[W3C, ECDSA's -operations]), or `+crypto::prehashed{digest}+`, signed as given. WebCrypto has no +operations]), or `+crypto::signing_schemes::prehashed{digest}+`, signed as given. WebCrypto has no prehash mode, so a backend that completes by itself, as the browser's will (<>), refuses the marker at compile time. The signature is r then s, 64 bytes, WebCrypto's form, low S as `sign` gives it; one of diff --git a/doc/backends.adoc b/doc/backends.adoc index 83d7f5f4..e77ecdd3 100644 --- a/doc/backends.adoc +++ b/doc/backends.adoc @@ -137,7 +137,7 @@ 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 +pair's making, `sign` of a digest (`crypto::signing_schemes::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 diff --git a/doc/curves.adoc b/doc/curves.adoc index 6f071dd6..b8753084 100644 --- a/doc/curves.adoc +++ b/doc/curves.adoc @@ -29,11 +29,11 @@ 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`, +`sign` with `crypto::signing_schemes::schnorr`, `crypto::signing_schemes::ecdsa_sha256`, +`crypto::signing_schemes::ecdsa_sha256_recoverable` and `crypto::signing_schemes::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`, +with `crypto::signing_schemes::schnorr` and `crypto::signing_schemes::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: `secret_key_tweak_add`, @@ -96,9 +96,9 @@ 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::eddsa_prehashed`, -`crypto::ecdsa_sha256`, `crypto::ecdsa_sha256_recoverable`, -`crypto::ecdsa_keccak256_recoverable` and `crypto::schnorr`. It is named at +operations]): `crypto::signing_schemes::eddsa`, `crypto::signing_schemes::eddsa_prehashed`, +`crypto::signing_schemes::ecdsa_sha256`, `crypto::signing_schemes::ecdsa_sha256_recoverable`, +`crypto::signing_schemes::ecdsa_keccak256_recoverable` and `crypto::signing_schemes::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. @@ -107,12 +107,12 @@ 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, 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 +`crypto::signing_schemes::ecdsa_keccak256_recoverable` with Keccak-256; EdDSA and Schnorr sign it +as given; Ed25519ph, `crypto::signing_schemes::eddsa_prehashed`, takes none. +* A *digest* is `+crypto::signing_schemes::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, and so does Ed25519ph, `crypto::eddsa_prehashed`, a message's SHA-512. +given, and so does Ed25519ph, `crypto::signing_schemes::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, @@ -121,55 +121,55 @@ takes a digest as a span of bytes, a 32-byte message passed to it compiles, signs the message unhashed, and verifies under the same mistake, and a program that moves from one function or one curve to another changes the meaning of its argument without a diagnostic. Here a span is a message whatever its size, -and no conversion turns a span into a `crypto::prehashed` or a -`crypto::prehashed` into a span: a digest is a digest because the program says +and no conversion turns a span into a `crypto::signing_schemes::prehashed` or a +`crypto::signing_schemes::prehashed` into a span: a digest is a digest because the program says 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 +| `+crypto::signing_schemes::prehashed{digest}+` | Signature -| `crypto::eddsa` +| `crypto::signing_schemes::eddsa` | Ed25519: `curves::ed25519::keypair`; `curves::ed25519::public_key` | signed as given (RFC 8032's PureEdDSA) | does not compile | `curves::ed25519::signature`, 64 bytes -| `crypto::eddsa_prehashed` +| `crypto::signing_schemes::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` +of `crypto::signing_schemes::eddsa` -| `crypto::ecdsa_sha256` +| `crypto::signing_schemes::ecdsa_sha256` | P-256: `curves::p256::keypair`; `curves::p256::public_key` | hashed with SHA-256 inside the call | 32 bytes, signed as given | `curves::p256::ecdsa_signature`, 64 bytes, r then s, low S -| `crypto::ecdsa_sha256` +| `crypto::signing_schemes::ecdsa_sha256` | secp256k1: `curves::secp256k1::keypair`; `curves::secp256k1::public_key` | hashed with SHA-256 inside the call | 32 bytes, signed as given | `curves::secp256k1::ecdsa_signature`, 64 bytes, r then s, low S -| `crypto::ecdsa_sha256_recoverable` +| `crypto::signing_schemes::ecdsa_sha256_recoverable` | secp256k1: `curves::secp256k1::keypair`; none: `recover` gives the key | hashed with SHA-256 inside the call | 32 bytes, signed as given | `curves::secp256k1::recoverable_signature`, 65 bytes, r, s and the recovery id -| `crypto::ecdsa_keccak256_recoverable` +| `crypto::signing_schemes::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` +| `crypto::signing_schemes::schnorr` | secp256k1: `curves::secp256k1::keypair`; `curves::secp256k1::public_key`, or its 32-byte x-only form | signed as given (BIP 340) @@ -178,17 +178,17 @@ its 32-byte x-only form |=== 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 +scheme the key's curve does not have, `crypto::signing_schemes::eddsa` or `crypto::signing_schemes::schnorr` with +a marker, `crypto::signing_schemes::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 -validated object on both curves, never bytes, so that `crypto::ecdsa_sha256` +validated object on both curves, never bytes, so that `crypto::signing_schemes::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. +wire, so `crypto::signing_schemes::schnorr` also takes the 32-byte x-only key. The signature is a type of its curve and scheme, the table's last column, and nothing else is taken where one is expected (<>). @@ -204,14 +204,14 @@ signatures may be high. A protocol that requires low S from a P-256 peer checks `is_low_s` before `crypto::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, +`sign(crypto::signing_schemes::ecdsa_sha256, input, extra_entropy)`, mixes 32 fresh bytes of the +caller's into the nonce, and `sign(crypto::signing_schemes::schnorr, message, auxiliary_random_bytes)` takes BIP 340's auxiliary randomness from the caller, -for test vectors; `sign(crypto::schnorr, message)` draws it from +for test vectors; `sign(crypto::signing_schemes::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)` +`recover(crypto::signing_schemes::ecdsa_sha256_recoverable, signature, input)` or +`recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, signature, input)` (<>). Every `crypto::verify` takes its backend as its first template parameter, @@ -242,31 +242,31 @@ namespace: | `curves::ed25519::signature` | 64 -| `crypto::eddsa` and `crypto::eddsa_prehashed`; Ed25519ph's streaming +| `crypto::signing_schemes::eddsa` and `crypto::signing_schemes::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 +| `verify` under the scheme that made it, `crypto::signing_schemes::eddsa` or +`crypto::signing_schemes::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 +| `crypto::signing_schemes::ecdsa_sha256` +| `verify` under `crypto::signing_schemes::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 +| `crypto::signing_schemes::ecdsa_sha256` +| `verify` under `crypto::signing_schemes::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` +| `crypto::signing_schemes::ecdsa_sha256_recoverable` and +`crypto::signing_schemes::ecdsa_keccak256_recoverable` | `recover` under the scheme that made it | `curves::secp256k1::schnorr_signature` | 64 -| `crypto::schnorr` -| `verify` under `crypto::schnorr` +| `crypto::signing_schemes::schnorr` +| `verify` under `crypto::signing_schemes::schnorr` |=== `sign` returns its scheme's type, and every `verify`, member and free, @@ -544,7 +544,7 @@ 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, +tag being of the namespace `webcpp::crypto`: `verify(crypto::signing_schemes::eddsa, signature, message, public_key)` is `crypto::verify`. The catch-alls that stop the build with a message, those of `crypto::sign`, `crypto::verify` and `crypto::async_verify`, take only a scheme tag in the place of the scheme, and @@ -602,7 +602,7 @@ SHA-256 of the transaction's serialization (link:https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki[BIP 143]): a protocol's digest. crypto holds primitives only, so the program, or a domain library, computes the sighash with webcpp::hash and signs -`+crypto::prehashed{sighash}+` under `crypto::ecdsa_sha256`. That is honest: the +`+crypto::signing_schemes::prehashed{sighash}+` under `crypto::signing_schemes::ecdsa_sha256`. That is honest: the sighash is the SHA-256 of a SHA-256, the second hash being the scheme's own, and no scheme of its own is needed: @@ -613,7 +613,7 @@ include::{examples}/bitcoin_sighash.cpp[tag=sign,indent=0] The sighash's computation, and the signature written as DER, are in <>. A taproot sighash, BIP 341's tagged hash, is the -message of `crypto::schnorr` instead, signed as given +message of `crypto::signing_schemes::schnorr` instead, signed as given (<>, <>). [#crypto-curves-signatures-ethereum] @@ -621,12 +621,12 @@ message of `crypto::schnorr` instead, signed as given Ethereum signs Keccak-256 digests with recoverable ECDSA (link:https://ethereum.github.io/yellowpaper/paper.pdf[Ethereum's yellow paper, -appendix F]), and its scheme says so: `crypto::ecdsa_keccak256_recoverable` +appendix F]), and its scheme says so: `crypto::signing_schemes::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 +transaction's, given as `+crypto::signing_schemes::prehashed{digest}+`. Its signature is the `curves::secp256k1::recoverable_signature` of -`crypto::ecdsa_sha256_recoverable`, and a message recovered under the other +`crypto::signing_schemes::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 8a734e86..0c4afaf7 100644 --- a/doc/ed25519.adoc +++ b/doc/ed25519.adoc @@ -25,12 +25,12 @@ Ethereum and Nostr sign on secp256k1 instead (<>). 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 `secure::secret<32>`), signs -(`sign(crypto::eddsa, message)`), and converts itself to an X25519 key pair +(`sign(crypto::signing_schemes::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 +destroyed. `crypto::verify(crypto::signing_schemes::eddsa, signature, message, public_key)` +checks a signature with the public key alone. The scheme `crypto::signing_schemes::eddsa` signs +the message itself, of any length: a `crypto::signing_schemes::prehashed` digest does not compile, and the key pair is a `crypto::signing_keypair` and no `crypto::agreement_keypair` (<>). @@ -65,26 +65,26 @@ in the asynchronous forms. An asynchronous form needs `crypto::async_generate(executor, token)` | Sign -| `key_pair.sign(crypto::eddsa, message)` + -`crypto::sign(key_pair, crypto::eddsa, message)` -| `key_pair.async_sign(executor, crypto::eddsa, message, token)` + -`crypto::async_sign(executor, key_pair, crypto::eddsa, message, token)` +| `key_pair.sign(crypto::signing_schemes::eddsa, message)` + +`crypto::sign(key_pair, crypto::signing_schemes::eddsa, message)` +| `key_pair.async_sign(executor, crypto::signing_schemes::eddsa, message, token)` + +`crypto::async_sign(executor, key_pair, crypto::signing_schemes::eddsa, message, token)` | Verify -| `public_key.verify(crypto::eddsa, signature, message)` + -`crypto::verify(crypto::eddsa, signature, message, public_key)` -| `public_key.async_verify(executor, crypto::eddsa, signature, message, token)` + -`crypto::async_verify(executor, crypto::eddsa, signature, message, public_key, token)` +| `public_key.verify(crypto::signing_schemes::eddsa, signature, message)` + +`crypto::verify(crypto::signing_schemes::eddsa, signature, message, public_key)` +| `public_key.async_verify(executor, crypto::signing_schemes::eddsa, signature, message, token)` + +`crypto::async_verify(executor, crypto::signing_schemes::eddsa, signature, message, public_key, token)` |=== *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` +scheme `crypto::signing_schemes::eddsa_prehashed`, marked as one: +`+key_pair.sign(crypto::signing_schemes::eddsa_prehashed, crypto::signing_schemes::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 +and `+crypto::verify(crypto::signing_schemes::eddsa_prehashed, signature, crypto::signing_schemes::prehashed{digest}, +public_key)+` or `+public_key.verify(crypto::signing_schemes::eddsa_prehashed, signature, +crypto::signing_schemes::prehashed{digest})+` checks it, strictly, as `crypto::signing_schemes::eddsa` does. The scheme takes the digest alone: a message, even one of 64 bytes, and a digest of another size do not compile. @@ -97,16 +97,16 @@ 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 +Both give a `curves::ed25519::signature`, the type `crypto::signing_schemes::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`, +browser's backend every function under `crypto::signing_schemes::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 +the message with `crypto::signing_schemes::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. @@ -117,16 +117,16 @@ its sources, and RFC 8032's Ed25519ph vectors check the result on every target. | 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)+` +| `+key_pair.sign(crypto::signing_schemes::eddsa_prehashed, crypto::signing_schemes::prehashed{digest})+` + +`+crypto::sign(key_pair, crypto::signing_schemes::eddsa_prehashed, crypto::signing_schemes::prehashed{digest})+` +| `+key_pair.async_sign(executor, crypto::signing_schemes::eddsa_prehashed, crypto::signing_schemes::prehashed{digest}, token)+` + +`+crypto::async_sign(executor, key_pair, crypto::signing_schemes::eddsa_prehashed, crypto::signing_schemes::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)+` +| `+public_key.verify(crypto::signing_schemes::eddsa_prehashed, signature, crypto::signing_schemes::prehashed{digest})+` + +`+crypto::verify(crypto::signing_schemes::eddsa_prehashed, signature, crypto::signing_schemes::prehashed{digest}, public_key)+` +| `+public_key.async_verify(executor, crypto::signing_schemes::eddsa_prehashed, signature, crypto::signing_schemes::prehashed{digest}, token)+` + +`+crypto::async_verify(executor, crypto::signing_schemes::eddsa_prehashed, signature, crypto::signing_schemes::prehashed{digest}, public_key, token)+` | A message in pieces | `prehashed_signer::begin()`, `update(piece)`, then @@ -144,7 +144,7 @@ include::generated/backends-ed25519ph.adoc[] *Example.* RFC 8032's second test signed and verified, then its Ed25519ph test, the message given in two pieces to the streaming signer, and its SHA-512 signed -under `crypto::eddsa_prehashed` into the same signature: +under `crypto::signing_schemes::eddsa_prehashed` into the same signature: [source,cpp] ---- diff --git a/doc/everyday.adoc b/doc/everyday.adoc index 7e5bac94..09200200 100644 --- a/doc/everyday.adoc +++ b/doc/everyday.adoc @@ -115,7 +115,7 @@ who can change the download, a compromised mirror, a network in the middle, could ship code that the program then runs. *The idea.* The publisher signs each update with ECDSA over SHA-256, -`crypto::ecdsa_sha256`, which hashes the update inside the call; the program +`crypto::signing_schemes::ecdsa_sha256`, which hashes the update inside the call; the program ships with the publisher's public key and accepts an update only when its signature verifies. Only the publisher's secret key can produce a signature the program accepts. diff --git a/doc/formats.adoc b/doc/formats.adoc index 36282f69..69e828d3 100644 --- a/doc/formats.adoc +++ b/doc/formats.adoc @@ -108,7 +108,7 @@ include::{examples}/key_formats.expected[] example does, it is wiped when it goes; written to a file or a database, it is sealed first, as any secret at rest (<>). * `decode_spki` checks the form, not the key: `crypto::verify` with -`crypto::eddsa` refuses a public key that is not a point of the curve, and +`crypto::signing_schemes::eddsa` refuses a public key that is not a point of the curve, and X25519's `agree` one of low order (`weak_public_key`). A key read from outside is used through those, which check it. * SPKI names the algorithm, the raw 32 bytes do not: an Ed25519 key and an diff --git a/doc/generated/constant-time.adoc b/doc/generated/constant-time.adoc index 7725ce01..f58e2ce9 100644 --- a/doc/generated/constant-time.adoc +++ b/doc/generated/constant-time.adoc @@ -13,7 +13,7 @@ |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)) +|Valgrind's memcheck (Linux): AES-GCM, ChaCha20-Poly1305, P-256 (the key pair's making, `+sign+` of a digest (`+crypto::signing_schemes::prehashed+`), which makes its signature low S without a branch, then `+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 diff --git a/doc/generated/messages.adoc b/doc/generated/messages.adoc index 16a097ff..b90657b7 100644 --- a/doc/generated/messages.adoc +++ b/doc/generated/messages.adoc @@ -163,21 +163,21 @@ The fix: Name a native backend, such as `+backends::sodium+`, for `+async_seal+` |`+async_sign_ed25519_prehashed+` |native, wasip2, wasip3 -|`+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).+` +|`+webcpp::crypto: crypto::signing_schemes::eddsa signs the message itself (RFC 8032's pure Ed25519) and takes no digest; a message's SHA-512 is signed with crypto::signing_schemes::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; a message's SHA-512 is signed with `+crypto::eddsa_prehashed+` (Ed25519ph), on a native backend. +The fix: Give `+async_sign+` the message itself with `+crypto::signing_schemes::eddsa+`, RFC 8032's pure Ed25519, which takes no digest, as the synchronous `+sign+` does; a message's SHA-512 is signed with `+crypto::signing_schemes::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.+` +|`+webcpp::crypto: WebCrypto has no Ed25519ph: crypto::signing_schemes::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. +The fix: As `+sign_eddsa_prehashed_asynchronous_backend+`: `+async_sign+` under `+crypto::signing_schemes::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 or crypto::eddsa_prehashed, 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::signing_schemes::eddsa or crypto::signing_schemes::eddsa_prehashed, a P-256 key pair with crypto::signing_schemes::ecdsa_sha256.+` -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. +The fix: Give `+async_sign+` the key pair's own scheme: `+crypto::signing_schemes::ecdsa_sha256+` for a P-256 key pair, `+crypto::signing_schemes::eddsa+` or `+crypto::signing_schemes::eddsa_prehashed+` for an Ed25519 key pair. |`+async_sign_secp256k1+` |native, wasip2, wasip3 @@ -193,21 +193,21 @@ The fix: As `+sign_x25519+`: give `+async_sign+` an Ed25519 key pair, which sign |`+async_verify_eddsa_bytes_key+` |native, wasip2, wasip3 -|`+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.+` +|`+webcpp::crypto: async_verify takes crypto::signing_schemes::eddsa or crypto::signing_schemes::eddsa_prehashed with a curves::ed25519::public_key or crypto::signing_schemes::ecdsa_sha256 with a curves::p256::basic_public_key, the algorithms WebCrypto has: call crypto::verify for the others.+` -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)+`. +The fix: Give `+async_verify+` with `+crypto::signing_schemes::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.+` +|`+webcpp::crypto: WebCrypto has no Ed25519ph: crypto::signing_schemes::eddsa_prehashed's sign, verify, async_sign and async_verify run on a native backend.+` -The fix: As `+verify_eddsa_prehashed_asynchronous_backend+`: `+async_verify+` under `+crypto::eddsa_prehashed+`, free and member, runs on a native backend. +The fix: As `+verify_eddsa_prehashed_asynchronous_backend+`: `+async_verify+` under `+crypto::signing_schemes::eddsa_prehashed+`, free and member, runs on a native backend. |`+async_verify_named_backend+` |native, wasip2, wasip3 -|`+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.+` +|`+webcpp::crypto: async_verify takes crypto::signing_schemes::eddsa or crypto::signing_schemes::eddsa_prehashed with a curves::ed25519::public_key or crypto::signing_schemes::ecdsa_sha256 with a curves::p256::basic_public_key, the algorithms WebCrypto has: call crypto::verify for the others.+` -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. +The fix: As `+async_verify_wrong_key+`: naming the backend does not add a scheme; call `+crypto::verify+` for `+crypto::signing_schemes::schnorr+` and secp256k1's keys. |`+async_verify_p256_bytes_signature+` |native, wasip2, wasip3 @@ -217,9 +217,9 @@ The fix: As `+verify_p256_secp256k1_signature+`: make the 64 bytes received into |`+async_verify_wrong_key+` |native, wasip2, wasip3 -|`+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.+` +|`+webcpp::crypto: async_verify takes crypto::signing_schemes::eddsa or crypto::signing_schemes::eddsa_prehashed with a curves::ed25519::public_key or crypto::signing_schemes::ecdsa_sha256 with a curves::p256::basic_public_key, the algorithms WebCrypto has: call crypto::verify for the others.+` -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+`. +The fix: Call `+crypto::verify+` for a key the asynchronous family lacks (secp256k1's, Schnorr's x-only key): `+async_verify+` has a `+curves::ed25519::public_key+` with `+crypto::signing_schemes::eddsa+` or `+crypto::signing_schemes::eddsa_prehashed+` and a `+curves::p256::basic_public_key+` with `+crypto::signing_schemes::ecdsa_sha256+`. |`+bearssl_not_linked+` |native, wasip2 @@ -315,7 +315,7 @@ The fix: Leave the backend out, as in `+curves::ed25519::keypair+`, or name `+ba |native, wasip2, wasip3 |`+webcpp::crypto: Ed25519's only verification policy is curves::ed25519::strict.+` -The fix: Leave the policy out, as in `+crypto::verify(crypto::eddsa, signature, message, public_key)+`, or name `+curves::ed25519::strict+`. +The fix: Leave the policy out, as in `+crypto::verify(crypto::signing_schemes::eddsa, signature, message, public_key)+`, or name `+curves::ed25519::strict+`. |`+ed25519ph_sha256+` |native, wasip2, wasip3 @@ -503,9 +503,9 @@ The fix: Name Ed25519ph's streaming signer `+curves::ed25519::prehashed_signer or a std::span.+` +|`+webcpp::crypto: crypto::signing_schemes::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>+`. +The fix: Give `+crypto::signing_schemes::prehashed+` a digest of a fixed size: a `+std::array+`, a `+std::span+` or a `+boost::hash2::digest<32>+`. |`+prevouts_summary_removed+` |native, wasip2 @@ -525,7 +525,13 @@ The fix: As `+prevouts_summary_removed+`. |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. +The fix: Give `+recover+` a `+curves::secp256k1::recoverable_signature+`, which `+sign(crypto::signing_schemes::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. + +|`+scheme_in_crypto_namespace+` +|native, wasip2, wasip3 +|`+no member named 'ecdsa_sha256' in namespace 'webcpp::crypto'+` + +The fix: Name the scheme in `+crypto::signing_schemes+`: `+crypto::signing_schemes::ecdsa_sha256+`; the tags are no longer in `+crypto+`, with no alias. |`+seal_asynchronous_backend+` |native, wasip2, wasip3 @@ -665,45 +671,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 or crypto::eddsa_prehashed.+` +|`+webcpp::crypto: an Ed25519 key signs with crypto::signing_schemes::eddsa or crypto::signing_schemes::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. +The fix: Sign with `+crypto::signing_schemes::eddsa+` or `+crypto::signing_schemes::eddsa_prehashed+`, Ed25519's schemes; `+crypto::signing_schemes::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.+` +|`+webcpp::crypto: an Ed25519 key signs with crypto::signing_schemes::eddsa or crypto::signing_schemes::eddsa_prehashed.+` -The fix: Sign with `+crypto::eddsa+` or `+crypto::eddsa_prehashed+`, Ed25519's schemes; Ethereum's `+crypto::ecdsa_keccak256_recoverable+` is secp256k1's. +The fix: Sign with `+crypto::signing_schemes::eddsa+` or `+crypto::signing_schemes::eddsa_prehashed+`, Ed25519's schemes; Ethereum's `+crypto::signing_schemes::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; a message's SHA-512 is signed with crypto::eddsa_prehashed (Ed25519ph).+` +|`+webcpp::crypto: crypto::signing_schemes::eddsa signs the message itself (RFC 8032's pure Ed25519) and takes no digest; a message's SHA-512 is signed with crypto::signing_schemes::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+`. +The fix: Sign the message itself with `+crypto::signing_schemes::eddsa+`, RFC 8032's pure Ed25519, which takes no digest; to sign a message's SHA-512, use Ed25519ph, `+crypto::signing_schemes::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.+` +|`+webcpp::crypto: WebCrypto has no Ed25519ph: crypto::signing_schemes::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+`. +The fix: Sign under `+crypto::signing_schemes::eddsa_prehashed+` with a key pair of a native backend: WebCrypto has no Ed25519ph; on the browser's backend, sign the message with `+crypto::signing_schemes::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.+` +|`+webcpp::crypto: crypto::signing_schemes::eddsa_prehashed takes a 64-byte digest, SHA-512's: crypto::signing_schemes::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. +The fix: Give `+crypto::signing_schemes::eddsa_prehashed+` SHA-512's 64-byte digest, `+crypto::signing_schemes::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.+` +|`+webcpp::crypto: crypto::signing_schemes::eddsa_prehashed (RFC 8032's Ed25519ph) signs a digest, the message's SHA-512: crypto::signing_schemes::prehashed{digest} of a std::array; sign the message itself with crypto::signing_schemes::eddsa, or give it in pieces to curves::ed25519::prehashed_signer.+` -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+`. +The fix: Give `+crypto::signing_schemes::eddsa_prehashed+` the message's SHA-512 marked as a digest, `+crypto::signing_schemes::prehashed{digest}+` of a `+std::array+`; sign the message itself with `+crypto::signing_schemes::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 or crypto::eddsa_prehashed.+` +|`+webcpp::crypto: an Ed25519 key signs with crypto::signing_schemes::eddsa or crypto::signing_schemes::eddsa_prehashed.+` -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. +The fix: As `+sign_ed25519_ecdsa+`: `+crypto::sign+` calls the key pair's own `+sign+`, so sign with `+crypto::signing_schemes::eddsa+` or `+crypto::signing_schemes::eddsa_prehashed+`, Ed25519's schemes. |`+sign_free_public_key+` |native, wasip2, wasip3 @@ -713,57 +719,57 @@ The fix: Give `+crypto::sign+` the key pair, whose public key verifies: `+crypto |`+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.+` +|`+webcpp::crypto: crypto::signing_schemes::ecdsa_keccak256_recoverable takes a 32-byte digest, Keccak-256's: crypto::signing_schemes::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. +The fix: As `+sign_p256_digest_48+`: give `+crypto::signing_schemes::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}.+` +|`+webcpp::crypto: crypto::signing_schemes::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::signing_schemes::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. +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::signing_schemes::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.+` +|`+webcpp::crypto: crypto::signing_schemes::ecdsa_sha256 takes a 32-byte digest, SHA-256's: crypto::signing_schemes::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. +The fix: Give `+crypto::signing_schemes::ecdsa_sha256+` SHA-256's 32-byte digest, `+crypto::signing_schemes::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.+` +|`+webcpp::crypto: a P-256 key signs with crypto::signing_schemes::ecdsa_sha256.+` -The fix: Sign with `+crypto::ecdsa_sha256+`, P-256's scheme; Ethereum's `+crypto::ecdsa_keccak256_recoverable+` is secp256k1's. +The fix: Sign with `+crypto::signing_schemes::ecdsa_sha256+`, P-256's scheme; Ethereum's `+crypto::signing_schemes::ecdsa_keccak256_recoverable+` is secp256k1's. |`+sign_p256_schnorr+` |native, wasip2, wasip3 -|`+webcpp::crypto: a P-256 key signs with crypto::ecdsa_sha256.+` +|`+webcpp::crypto: a P-256 key signs with crypto::signing_schemes::ecdsa_sha256.+` -The fix: Sign with `+crypto::ecdsa_sha256+`, P-256's scheme; BIP340's `+crypto::schnorr+` is secp256k1's. +The fix: Sign with `+crypto::signing_schemes::ecdsa_sha256+`, P-256's scheme; BIP340's `+crypto::signing_schemes::schnorr+` is secp256k1's. |`+sign_schnorr_prehashed+` |native, wasip2, wasip3 -|`+webcpp::crypto: crypto::schnorr (BIP340) signs a message of any length and has no prehash mode: pass the message.+` +|`+webcpp::crypto: crypto::signing_schemes::schnorr (BIP340) signs a message of any length and has no prehash mode: pass the message.+` -The fix: Sign the message itself with `+crypto::schnorr+`, BIP340's, which has no prehash mode; a taproot sighash, BIP341's tagged hash, is that message. +The fix: Sign the message itself with `+crypto::signing_schemes::schnorr+`, BIP340's, which has no prehash mode; a taproot sighash, BIP341's tagged hash, is that message. |`+sign_secp256k1_eddsa+` |native, wasip2, wasip3 -|`+webcpp::crypto: a secp256k1 key signs with crypto::ecdsa_sha256, crypto::ecdsa_sha256_recoverable, crypto::ecdsa_keccak256_recoverable or crypto::schnorr.+` +|`+webcpp::crypto: a secp256k1 key signs with crypto::signing_schemes::ecdsa_sha256, crypto::signing_schemes::ecdsa_sha256_recoverable, crypto::signing_schemes::ecdsa_keccak256_recoverable or crypto::signing_schemes::schnorr.+` -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. +The fix: Sign with `+crypto::signing_schemes::ecdsa_sha256+`, `+crypto::signing_schemes::ecdsa_sha256_recoverable+`, `+crypto::signing_schemes::ecdsa_keccak256_recoverable+` or `+crypto::signing_schemes::schnorr+`, secp256k1's schemes; `+crypto::signing_schemes::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, crypto::ecdsa_keccak256_recoverable or crypto::schnorr.+` +|`+webcpp::crypto: a secp256k1 key signs with crypto::signing_schemes::ecdsa_sha256, crypto::signing_schemes::ecdsa_sha256_recoverable, crypto::signing_schemes::ecdsa_keccak256_recoverable or crypto::signing_schemes::schnorr.+` -The fix: Name the scheme with its tag: `+crypto::ecdsa_sha256+`, `+crypto::ecdsa_sha256_recoverable+`, `+crypto::ecdsa_keccak256_recoverable+` or `+crypto::schnorr+`. +The fix: Name the scheme with its tag: `+crypto::signing_schemes::ecdsa_sha256+`, `+crypto::signing_schemes::ecdsa_sha256_recoverable+`, `+crypto::signing_schemes::ecdsa_keccak256_recoverable+` or `+crypto::signing_schemes::schnorr+`. |`+sign_secp256k1_recoverable_digest_48+` |native, wasip2, wasip3 -|`+webcpp::crypto: crypto::ecdsa_sha256_recoverable takes a 32-byte digest, SHA-256's: crypto::prehashed{digest} of a std::array.+` +|`+webcpp::crypto: crypto::signing_schemes::ecdsa_sha256_recoverable takes a 32-byte digest, SHA-256's: crypto::signing_schemes::prehashed{digest} of a std::array.+` -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. +The fix: As `+sign_p256_digest_48+`: give `+crypto::signing_schemes::ecdsa_sha256_recoverable+` SHA-256's 32-byte digest, or the message itself, which it hashes. |`+sign_x25519+` |native, wasip2, wasip3 @@ -791,33 +797,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 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.+` +|`+webcpp::crypto: verify: this public key does not go with this scheme: crypto::signing_schemes::eddsa and crypto::signing_schemes::eddsa_prehashed take a curves::ed25519::public_key, crypto::signing_schemes::ecdsa_sha256 a curves::p256::basic_public_key or a curves::secp256k1::public_key, crypto::signing_schemes::schnorr a curves::secp256k1::public_key or a 32-byte x-only key; a crypto::signing_schemes::ecdsa_sha256_recoverable or a crypto::signing_schemes::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::from_bytes(bytes)+` or `+curves::p256::public_key::from_bytes(bytes)+`: bytes never choose the curve. +The fix: Give `+crypto::signing_schemes::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.+` +|`+webcpp::crypto: verify: an Ed25519 key verifies a curves::ed25519::signature under crypto::signing_schemes::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 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.+` +|`+webcpp::crypto: verify: this public key does not go with this scheme: crypto::signing_schemes::eddsa and crypto::signing_schemes::eddsa_prehashed take a curves::ed25519::public_key, crypto::signing_schemes::ecdsa_sha256 a curves::p256::basic_public_key or a curves::secp256k1::public_key, crypto::signing_schemes::schnorr a curves::secp256k1::public_key or a 32-byte x-only key; a crypto::signing_schemes::ecdsa_sha256_recoverable or a crypto::signing_schemes::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::signing_schemes::eddsa+` (or `+crypto::signing_schemes::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. |`+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.+` +|`+webcpp::crypto: WebCrypto has no Ed25519ph: crypto::signing_schemes::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+`. +The fix: Verify under `+crypto::signing_schemes::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::signing_schemes::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.+` +|`+webcpp::crypto: crypto::signing_schemes::eddsa_prehashed (RFC 8032's Ed25519ph) signs a digest, the message's SHA-512: crypto::signing_schemes::prehashed{digest} of a std::array; sign the message itself with crypto::signing_schemes::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+`. +The fix: As `+sign_eddsa_prehashed_message+`: verify under `+crypto::signing_schemes::eddsa_prehashed+` the marker of the message's SHA-512, or the message itself under `+crypto::signing_schemes::eddsa+`. |`+verify_free_asynchronous_backend+` |native, wasip2, wasip3 @@ -827,39 +833,39 @@ 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 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.+` +|`+webcpp::crypto: verify: this public key does not go with this scheme: crypto::signing_schemes::eddsa and crypto::signing_schemes::eddsa_prehashed take a curves::ed25519::public_key, crypto::signing_schemes::ecdsa_sha256 a curves::p256::basic_public_key or a curves::secp256k1::public_key, crypto::signing_schemes::schnorr a curves::secp256k1::public_key or a 32-byte x-only key; a crypto::signing_schemes::ecdsa_sha256_recoverable or a crypto::signing_schemes::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. +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::signing_schemes::ecdsa_sha256+` and `+crypto::signing_schemes::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.+` +|`+webcpp::crypto: verify: this public key does not go with this scheme: crypto::signing_schemes::eddsa and crypto::signing_schemes::eddsa_prehashed take a curves::ed25519::public_key, crypto::signing_schemes::ecdsa_sha256 a curves::p256::basic_public_key or a curves::secp256k1::public_key, crypto::signing_schemes::schnorr a curves::secp256k1::public_key or a 32-byte x-only key; a crypto::signing_schemes::ecdsa_sha256_recoverable or a crypto::signing_schemes::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+`. +The fix: Give the signature to `+curves::secp256k1::recover(crypto::signing_schemes::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 or crypto::eddsa_prehashed.+` +|`+webcpp::crypto: an Ed25519 public key verifies crypto::signing_schemes::eddsa or crypto::signing_schemes::eddsa_prehashed.+` -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+`. +The fix: Verify with `+crypto::signing_schemes::eddsa+` or `+crypto::signing_schemes::eddsa_prehashed+`, Ed25519's schemes; `+crypto::signing_schemes::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; a message's SHA-512 is signed with crypto::eddsa_prehashed (Ed25519ph).+` +|`+webcpp::crypto: crypto::signing_schemes::eddsa signs the message itself (RFC 8032's pure Ed25519) and takes no digest; a message's SHA-512 is signed with crypto::signing_schemes::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 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+`. +The fix: Verify the message itself with `+crypto::signing_schemes::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::signing_schemes::eddsa_prehashed+`, or for a message given in pieces with `+curves::ed25519::prehashed_signer+`. |`+verify_member_p256_eddsa+` |native, wasip2, wasip3 -|`+webcpp::crypto: a P-256 public key verifies crypto::ecdsa_sha256.+` +|`+webcpp::crypto: a P-256 public key verifies crypto::signing_schemes::ecdsa_sha256.+` -The fix: Verify with `+crypto::ecdsa_sha256+`, P-256's scheme; `+crypto::eddsa+` is Ed25519's, whose key is a `+curves::ed25519::public_key+`. +The fix: Verify with `+crypto::signing_schemes::ecdsa_sha256+`, P-256's scheme; `+crypto::signing_schemes::eddsa+` is Ed25519's, whose key is a `+curves::ed25519::public_key+`. |`+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 or a crypto::ecdsa_keccak256_recoverable signature gives its key to curves::secp256k1::recover.+` +|`+webcpp::crypto: a secp256k1 public key verifies crypto::signing_schemes::ecdsa_sha256 or crypto::signing_schemes::schnorr; a crypto::signing_schemes::ecdsa_sha256_recoverable or a crypto::signing_schemes::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+`. +The fix: Give a recoverable signature to `+curves::secp256k1::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, signature, input)+`, which gives the signer's key; a public key verifies `+crypto::signing_schemes::ecdsa_sha256+` and `+crypto::signing_schemes::schnorr+`. |`+verify_p256_secp256k1_signature+` |native, wasip2, wasip3 @@ -869,9 +875,9 @@ The fix: Give a P-256 key a `+curves::p256::ecdsa_signature+`, made from the 64 |`+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.+` +|`+webcpp::crypto: verify: a secp256k1 key verifies a curves::secp256k1::ecdsa_signature under crypto::signing_schemes::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. +The fix: Verify a BIP340 signature with `+crypto::signing_schemes::schnorr+`, its scheme; `+crypto::signing_schemes::ecdsa_sha256+` takes a `+curves::secp256k1::ecdsa_signature+`, which `+sign(crypto::signing_schemes::ecdsa_sha256, input)+` gives. |`+wipe_removed+` |native, wasip2, wasip3 @@ -1668,7 +1674,7 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |`+ed25519_unknown_policy+` |the compile -|Leave the policy out, as in `+crypto::verify(crypto::eddsa, signature, message, public_key)+`, or name `+curves::ed25519::strict+`. +|Leave the policy out, as in `+crypto::verify(crypto::signing_schemes::eddsa, signature, message, public_key)+`, or name `+curves::ed25519::strict+`. |`+ed25519ph_sha256+` |the compile @@ -1752,11 +1758,11 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |`+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+`. +|Give `+crypto::signing_schemes::eddsa_prehashed+` the message's SHA-512 marked as a digest, `+crypto::signing_schemes::prehashed{digest}+` of a `+std::array+`; sign the message itself with `+crypto::signing_schemes::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. +|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::signing_schemes::prehashed{digest}+`, which needs no XKCP. |`+silent_payments_other_backend+` |the compile diff --git a/doc/generated/namespace-curves.adoc b/doc/generated/namespace-curves.adoc index 30fc16e0..a24a3b36 100644 --- a/doc/generated/namespace-curves.adoc +++ b/doc/generated/namespace-curves.adoc @@ -13,7 +13,7 @@ |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, 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 +|Ed25519 signatures, and Ed25519ph over SHA-512, of a digest (`crypto::signing_schemes::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 @@ -45,7 +45,7 @@ |libsecp256k1: native, Valgrind's memcheck (Linux; 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), MemorySanitizer (Linux, clang; the same paths as memcheck's) and dudect (judged; on a runner GitHub hosts, by two of three runs; `+agree+`), nothing found; wasip2, dudect (judged; on a runner GitHub hosts, by two of three runs; `+agree+`), nothing found; not measured yet on wasip3, emscripten (<>) |libsodium: native, Valgrind's memcheck (Linux), MemorySanitizer (Linux, clang) and dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; wasip2, dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; not measured yet on wasip3, emscripten (<>) |libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found, and dudect (judged; on a runner GitHub hosts, by two of three runs): nothing found with arm64's DIT (data-independent timing) bit set, which webcpp sets around every call on 64-bit ARM under macOS, iOS, Linux, Android and Windows where the CPU has it, as Apple requires 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, Writing ARM64 code for Apple platforms: enable DIT for constant-time cryptographic operations]); the lane's dudect sets nothing itself and measures what a program gets: \|t\| 1.8 to 2.8 against the threshold 10 (2026-11-21, five runs), while its `dudect_planted`, an early-exit scan of the secret key run inside the same guard, reads \|t\| 66.72 and 65.53 (2026-11-21): DIT does not hide a leak. Without DIT, dudect times `agree` with an all-zero secret key against random ones at \|t\| 6.7 to 14.5 (2026-11-19) and 4.3 to 7.8 (2026-11-21, three runs): about one nanosecond in 15 µs. Each on an Apple M5 Max, from a release build. libsodium does not set DIT, and webcpp sets nothing on x86 or WebAssembly; wasip2, dudect (judged; on a runner GitHub hosts, by two of three runs): an open finding, its cause measured: dudect times `agree` with an all-zero secret key against random ones at \|t\| 13 to 32 (2026-11-18; a fixed key against another fixed key: 22.9) and 107 to 260 (2026-11-19), and 25.25 in the lane on 2026-11-21, against the threshold 10, under wasmtime 47 on an Apple M5 Max, from a release build. The cause is Apple silicon's DIT (data-independent timing), which wasmtime does not set (link:https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Enable-DIT-for-constant-time-cryptographic-operations[Apple, Writing ARM64 code for Apple platforms: enable DIT for constant-time cryptographic operations]): with DIT set in wasmtime's main thread, an experiment and not the lane, the same case reads \|t\| 1.5 to 2.1; no branch on a secret was found in the WebAssembly or in wasmtime's compiled code. The lane cannot set DIT from inside the WebAssembly, so it prints this value on wasip2 without judging it; the CI's x86-64 run measures it next; not measured yet on wasip3, emscripten (<>) -|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 (<>) +|BearSSL: native, Valgrind's memcheck (Linux; the key pair's making, `+sign+` of a digest (`+crypto::signing_schemes::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 (<>) |Standards |link:https://www.secg.org/sec2-v2.pdf[SEC 2, Recommended Elliptic Curve Domain Parameters], link:https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki[BIP 340, Schnorr signatures for secp256k1], link:https://www.rfc-editor.org/rfc/rfc6979[RFC 6979, deterministic ECDSA nonces], link:https://github.com/bitcoin/bips/blob/master/bip-0324.mediawiki[BIP 324, version 2 P2P encrypted transport protocol], link:https://github.com/bitcoin/bips/blob/master/bip-0327.mediawiki[BIP 327, MuSig2 for BIP340-compatible multi-signatures], link:https://github.com/bitcoin/bips/blob/master/bip-0352.mediawiki[BIP 352, Silent Payments] diff --git a/doc/generated/use-cases.adoc b/doc/generated/use-cases.adoc index 58617e49..9db7cb62 100644 --- a/doc/generated/use-cases.adoc +++ b/doc/generated/use-cases.adoc @@ -73,14 +73,14 @@ |<> |Prove who wrote a message posted to a relay -|In `+curves::secp256k1+`: `+keypair::sign(crypto::schnorr, message)+`, `+crypto::verify+` +|In `+curves::secp256k1+`: `+keypair::sign(crypto::signing_schemes::schnorr, message)+`, `+crypto::verify+` |libsecp256k1 |`+/webcpp/crypto//crypto+` + `+/third_party//secp256k1+` |<> |Check a software update or a licence file -|In `+curves::secp256k1+`: `+keypair::sign(crypto::ecdsa_sha256, message)+`, `+public_key::from_bytes+`, `+crypto::verify+` +|In `+curves::secp256k1+`: `+keypair::sign(crypto::signing_schemes::ecdsa_sha256, message)+`, `+public_key::from_bytes+`, `+crypto::verify+` |libsecp256k1 |`+/webcpp/crypto//crypto+` + `+/third_party//secp256k1+` @@ -102,7 +102,7 @@ |<> |Find who signed a message or a transaction without being sent their key (Ethereum's signatures) -|In `+curves::secp256k1+`: `+keypair::sign(crypto::ecdsa_keccak256_recoverable, message)+`, `+recover+` +|In `+curves::secp256k1+`: `+keypair::sign(crypto::signing_schemes::ecdsa_keccak256_recoverable, message)+`, `+recover+` |libsecp256k1 |`+/webcpp/crypto//crypto+` + `+/third_party//secp256k1+` + @@ -154,7 +154,7 @@ |<> |Sign a Bitcoin SegWit v0 input (a domain library's job) -|In `+curves::secp256k1+`: `+keypair::sign(crypto::ecdsa_sha256, crypto::prehashed{sighash})+`, `+to_der+`, `+is_low_s+`, `+normalize_low_s+` +|In `+curves::secp256k1+`: `+keypair::sign(crypto::signing_schemes::ecdsa_sha256, crypto::signing_schemes::prehashed{sighash})+`, `+to_der+`, `+is_low_s+`, `+normalize_low_s+` |libsecp256k1 |`+/webcpp/crypto//crypto+` + `+/third_party//secp256k1+` @@ -194,7 +194,7 @@ |<> |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+` +|In `+curves::ed25519+`: `+keypair::from_secret+`, `+keypair::generate+`, `+keypair::sign(crypto::signing_schemes::eddsa, message)+`, `+keypair::sign(crypto::signing_schemes::eddsa_prehashed, crypto::signing_schemes::prehashed{digest})+`, `+crypto::verify+`; `+prehashed_signer+` |libsodium |`+/webcpp/crypto//crypto+` + `+/webcpp/crypto//ed25519-default+` @@ -268,7 +268,7 @@ |<> |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 -|In `+curves::p256+`: `+keypair::sign(crypto::ecdsa_sha256, message)+`, `+crypto::verify+`, `+is_low_s+`, `+normalize_low_s+`; `+to_der+`, `+from_der+` for X.509 +|In `+curves::p256+`: `+keypair::sign(crypto::signing_schemes::ecdsa_sha256, message)+`, `+crypto::verify+`, `+is_low_s+`, `+normalize_low_s+`; `+to_der+`, `+from_der+` for X.509 |BearSSL |`+/webcpp/crypto//crypto+` + `+/webcpp/crypto//p256-default+` @@ -290,7 +290,7 @@ |<> |Sign a peer-to-peer handshake a browser's WebCrypto verifies, low S, check the peer's, and derive the session key from ECDH (Trystero's protocol is webcpp::trystero's) -|In `+curves::p256+`: `+keypair::sign(crypto::ecdsa_sha256, crypto::prehashed{digest})+`, `+is_low_s+`, `+crypto::verify+`, `+keypair::agree+`; `+webcpp::hash::hkdf+` for the key +|In `+curves::p256+`: `+keypair::sign(crypto::signing_schemes::ecdsa_sha256, crypto::signing_schemes::prehashed{digest})+`, `+is_low_s+`, `+crypto::verify+`, `+keypair::agree+`; `+webcpp::hash::hkdf+` for the key |BearSSL |`+/webcpp/crypto//crypto+` + `+/webcpp/crypto//p256-default+` diff --git a/doc/llms.txt b/doc/llms.txt index 41f947a2..831fd92c 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -16,20 +16,20 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - 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, async_generate, async_sign, async_verify](https://webcpporg.github.io/libs/crypto/#crypto-async): Ed25519's asynchronous from_secret, generate, sign and verify with `crypto::signing_schemes::eddsa`, and on a native backend with `crypto::signing_schemes::eddsa_prehashed` (Ed25519ph, which WebCrypto lacks), each completing through a post to the executor the call gives, with any Asio completion token. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Use it to: sign and verify with Ed25519 in a coroutine. - 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_verify: Verifies an Ed25519 signature (RFC 8032's pure Ed25519), asynchronously, strictly: `crypto::verify(signing_schemes::eddsa, ...)` 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, 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::signing_schemes::ecdsa_sha256`, of a message hashed with SHA-256 or `crypto::signing_schemes::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_verify: Verifies a P-256 ECDSA signature over SHA-256, asynchronously: `crypto::verify(signing_schemes::ecdsa_sha256, ...)` 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::signing_schemes::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. - [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. @@ -105,7 +105,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp ## 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), `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. +- [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::signing_schemes::schnorr, message)` (BIP 340, its auxiliary randomness drawn or given), `sign(crypto::signing_schemes::ecdsa_sha256, input)` (hedged too), `sign(crypto::signing_schemes::ecdsa_sha256_recoverable, input)` and Ethereum's `sign(crypto::signing_schemes::ecdsa_keccak256_recoverable, input)`, the input a message hashed inside (with Keccak-256 for Ethereum's, which needs `/third_party//xkcp`) or `crypto::signing_schemes::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. @@ -115,9 +115,9 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - 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)` 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. +- [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::signing_schemes::schnorr, signature, message, key)`, or an ECDSA one against a `curves::secp256k1::public_key`, `crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, input, public_key)`, refusing a high S; `recover(crypto::signing_schemes::ecdsa_sha256_recoverable, signature, input)` and `recover(crypto::signing_schemes::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`) of ECDSA over SHA-256: 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(signing_schemes::ecdsa_sha256_recoverable, ...)`. - [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. @@ -125,25 +125,25 @@ 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 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. +- [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::signing_schemes::eddsa, message)`, and of a message's SHA-512 with `sign(crypto::signing_schemes::eddsa_prehashed, crypto::signing_schemes::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_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 `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). + - sign: Signs with Ed25519 (RFC 8032): under `crypto::signing_schemes::eddsa`, the pure form, a message, the message itself, of any length, empty included, with no digest taken; under `crypto::signing_schemes::eddsa_prehashed`, Ed25519ph, the 64 bytes of a message's SHA-512, `crypto::signing_schemes::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. +- [curves::ed25519::public_key](https://webcpporg.github.io/libs/crypto/#crypto-ed25519): An Ed25519 public key, its 32 bytes, which `crypto::verify(crypto::signing_schemes::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_value, message_input, key, verify_policy)`, of which it is the member form, with the same work, results and refusals. + - verify: Verifies an Ed25519 signature (RFC 8032's pure Ed25519) with this key, under a verification policy (design D31): `crypto::verify(signing_schemes::eddsa, ...)`, 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. +- [crypto::verify](https://webcpporg.github.io/libs/crypto/#crypto-ed25519): Verifies an Ed25519 signature with a public key alone, `crypto::verify(crypto::signing_schemes::eddsa, signature, message, public_key)`, or an Ed25519ph one, `crypto::verify(crypto::signing_schemes::eddsa_prehashed, signature, crypto::signing_schemes::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::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. +- [curves::ed25519::prehashed_signer](https://webcpporg.github.io/libs/crypto/#crypto-ed25519): Ed25519ph (RFC 8032), the streaming form of the scheme `crypto::signing_schemes::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::signing_schemes::eddsa_prehashed, crypto::signing_schemes::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. @@ -172,13 +172,13 @@ 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::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::recover](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-recovery): The public key that made a recoverable ECDSA signature, `recover(crypto::signing_schemes::ecdsa_sha256_recoverable, signature, input)` or Ethereum's `recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, signature, input)`, the input as signing took it: a message hashed inside (with SHA-256, or Keccak-256) or `crypto::signing_schemes::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(signing_schemes::ecdsa_sha256_recoverable, ...)`. - [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. - 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. + - xonly: The key's BIP340 x-only form, its x coordinate, which `crypto::verify(crypto::signing_schemes::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_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`). @@ -210,7 +210,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - 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. - partial_signature_verify: Verifies one signer's partial signature (`secp256k1_musig_partial_sig_verify`), which tells a dishonest or faulty signer apart before the signature is aggregated. - - partial_signature_aggregate: The BIP 340 signature of the partial signatures (`secp256k1_musig_partial_sig_agg`), which `crypto::verify(crypto::schnorr, signature, message, key)` checks under `aggregate_key::xonly_public_key()`. + - partial_signature_aggregate: The BIP 340 signature of the partial signatures (`secp256k1_musig_partial_sig_agg`), which `crypto::verify(crypto::signing_schemes::schnorr, signature, message, key)` checks under `aggregate_key::xonly_public_key()`. - parse_public_nonce: Parses a signer's public nonce (`secp256k1_musig_pubnonce_parse`): two compressed points. - serialize_public_nonce: Serialises a signer's public nonce (`secp256k1_musig_pubnonce_serialize`). - parse_aggregate_nonce: Parses an aggregate nonce (`secp256k1_musig_aggnonce_parse`): two compressed points, either of which may be the point at infinity, written as 33 zero bytes. @@ -237,9 +237,9 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - 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_value, signing_input, key)`, of which it is the member form, with the same work, results and refusals. + - verify: Verifies an ECDSA signature over SHA-256 with this key: `crypto::verify(crypto::signing_schemes::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. +- [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::signing_schemes::ecdsa_sha256, input)` and `crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, input, public_key)`, the input a message hashed inside or `crypto::signing_schemes::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 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. @@ -332,7 +332,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - 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 `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. +- P-256: BearSSL: native, Valgrind's memcheck (Linux; the key pair's making, `sign` of a digest (`crypto::signing_schemes::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 @@ -342,7 +342,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [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 `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. +- [Ethereum](https://webcpporg.github.io/libs/crypto/#crypto-curves): this version signs Ethereum's recoverable ECDSA over Keccak-256 (`keypair::sign(crypto::signing_schemes::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 `secure::constant_time_equal`, never `==` or `memcmp` ([CWE-208, observable timing discrepancy](https://cwe.mitre.org/data/definitions/208.html)). - [Secrets come from random_device](https://webcpporg.github.io/libs/crypto/#crypto-entropy): keys, nonces and tokens are drawn from `random_device`, never `std::mt19937` or `rand` ([CWE-338, a weak generator used for security](https://cwe.mitre.org/data/definitions/338.html)). - [Never reuse a nonce under one ChaCha20-Poly1305 key](https://webcpporg.github.io/libs/crypto/#crypto-chacha): two messages under one key and one nonce reveal the XOR of their plaintexts and let an attacker forge tags ([RFC 8439, section 4: a nonce is never repeated under one key](https://www.rfc-editor.org/rfc/rfc8439#section-4)). `xchacha20_poly1305` and the secret boxes: draw 24 bytes at random per message. `chacha20_poly1305`: number the 12-byte nonces with a counter that never repeats, a restart included, or draw them at random for at most 2^32 messages per key, AES-GCM's bound for random 12-byte nonces ([NIST SP 800-38D, GCM and GMAC](https://csrc.nist.gov/pubs/sp/800/38/d/final)). `chacha20_poly1305_original`: a counter only, its 8 bytes are too short to draw. @@ -360,24 +360,24 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [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::from_bytes`, `crypto::verify` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/signed_update.cpp. +- [Prove who wrote a message posted to a relay](https://webcpporg.github.io/libs/crypto/#crypto-p2p-signed): `keypair::sign(crypto::signing_schemes::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::signing_schemes::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_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. +- [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::signing_schemes::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_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. +- [Sign a Bitcoin SegWit v0 input (a domain library's job)](https://webcpporg.github.io/libs/crypto/#crypto-wallets-der): `keypair::sign(crypto::signing_schemes::ecdsa_sha256, crypto::signing_schemes::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::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/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. +- [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::signing_schemes::eddsa, message)`, `keypair::sign(crypto::signing_schemes::eddsa_prehashed, crypto::signing_schemes::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. @@ -387,30 +387,30 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [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. +- [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::signing_schemes::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. -- [Sign a peer-to-peer handshake a browser's WebCrypto verifies, low S, check the peer's, and derive the session key from ECDH (Trystero's protocol is webcpp::trystero's)](https://webcpporg.github.io/libs/crypto/#crypto-p2p-handshake): `keypair::sign(crypto::ecdsa_sha256, crypto::prehashed{digest})`, `is_low_s`, `crypto::verify`, `keypair::agree`; `webcpp::hash::hkdf` for the key (webcpp::crypto::curves::p256); backend BearSSL; Jamfile /webcpp/crypto//crypto /webcpp/crypto//p256-default. Example: example/p256_handshake.cpp. +- [Sign a peer-to-peer handshake a browser's WebCrypto verifies, low S, check the peer's, and derive the session key from ECDH (Trystero's protocol is webcpp::trystero's)](https://webcpporg.github.io/libs/crypto/#crypto-p2p-handshake): `keypair::sign(crypto::signing_schemes::ecdsa_sha256, crypto::signing_schemes::prehashed{digest})`, `is_low_s`, `crypto::verify`, `keypair::agree`; `webcpp::hash::hkdf` for the key (webcpp::crypto::curves::p256); backend BearSSL; Jamfile /webcpp/crypto//crypto /webcpp/crypto//p256-default. Example: example/p256_handshake.cpp. ## Examples - 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 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/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::signing_schemes::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. tag::program[] - 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/bitcoin_sighash.cpp: Signs a Bitcoin legacy or segwit v0 input's sighash: SHA-256d of the transaction's serialization, computed by the program with webcpp::hash, signed as a digest with ECDSA over SHA-256, verified, and written as strict DER for the witness. Crypto computes no sighash: the serialization and its hash are the protocol's, a domain library's work; the sighash is the SHA-256 of a SHA-256, so the second hash is the scheme's own and the digest is honest under crypto::signing_schemes::ecdsa_sha256. A taproot sighash, BIP341's tagged hash, is the message of crypto::signing_schemes::schnorr instead (musig_taproot.cpp, taproot_tweak.cpp). - example/box_messages.cpp: Two people who know each other's X25519 public keys exchange messages in libsodium's box: each makes a box from the own key pair and the other's public key, agreeing one key for the pair, then seals each message with a nonce drawn at random. What one seals the other opens; a stranger's box, from another key pair, does not. Prints what each reads. - example/constant_time_equal_hmac.cpp: Checks an HMAC-SHA-256 tag from Boost.Hash2 with webcpp::secure::constant_time_equal, the constant-time comparison. Comparing tags with == or memcmp stops at the first difference, and that timing lets an attacker guess a valid tag one byte at a time. - example/ecdh_session.cpp: Two peers agree on a shared secret with ECDH, derive a session key from it with HKDF-SHA-256 and talk over AES-256-GCM. The raw ECDH output is not a key: HKDF turns it into one and ties it to this application with a context string. - example/ecdh_x_coordinate.cpp: Two key pairs agree on the shared point's raw x coordinate with agree, the form Nostr's encrypted messages (NIP-44) take, then derive from it what a NIP-44 library would: the conversation key, HKDF-extract with the salt "nip44-v2". The x coordinate is not a key; the derivation that makes one is the protocol's, and belongs to a domain library. - 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'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/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::signing_schemes::eddsa, message)` and `crypto::verify(crypto::signing_schemes::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::signing_schemes::eddsa_prehashed`, which gives the same signature, and verifies it with `crypto::verify(crypto::signing_schemes::eddsa_prehashed, signature, crypto::signing_schemes::prehashed{digest}, public_key)`. Prints each key and signature in hex, and whether the two Ed25519ph signatures are equal. tag::program[] - 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/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/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::signing_schemes::prehashed with crypto::signing_schemes::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[] - 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/four_forms.cpp: Makes RFC 6979's P-256 key pair (a published scalar, never a real key), signs "sample" with crypto::signing_schemes::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. tag::program[] - 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. diff --git a/doc/overview.adoc b/doc/overview.adoc index 98bf8189..d6d052ed 100644 --- a/doc/overview.adoc +++ b/doc/overview.adoc @@ -29,7 +29,7 @@ and SPKI and PKCS#8 keys, through BearSSL. * *One way to sign.* Every key pair signs with `sign(scheme, input)`, and `crypto::verify(scheme, signature, input, public_key)` checks the signature, the scheme named at every call and a digest given only as -`+crypto::prehashed{digest}+` (<>). Each operation +`+crypto::signing_schemes::prehashed{digest}+` (<>). Each operation has the member and its free form, and, where WebCrypto has the algorithm, their asynchronous forms, with one implementation (<>). diff --git a/doc/p256.adoc b/doc/p256.adoc index 1c5461fe..29490767 100644 --- a/doc/p256.adoc +++ b/doc/p256.adoc @@ -109,16 +109,16 @@ asynchronous form needs `` and `crypto::async_generate(executor, token)` | Sign -| `key_pair.sign(crypto::ecdsa_sha256, input)` + -`crypto::sign(key_pair, crypto::ecdsa_sha256, input)` -| `key_pair.async_sign(executor, crypto::ecdsa_sha256, input, token)` + -`crypto::async_sign(executor, key_pair, crypto::ecdsa_sha256, input, token)` +| `key_pair.sign(crypto::signing_schemes::ecdsa_sha256, input)` + +`crypto::sign(key_pair, crypto::signing_schemes::ecdsa_sha256, input)` +| `key_pair.async_sign(executor, crypto::signing_schemes::ecdsa_sha256, input, token)` + +`crypto::async_sign(executor, key_pair, crypto::signing_schemes::ecdsa_sha256, input, token)` | Verify -| `public_key.verify(crypto::ecdsa_sha256, signature, input)` + -`crypto::verify(crypto::ecdsa_sha256, signature, input, public_key)` -| `public_key.async_verify(executor, crypto::ecdsa_sha256, signature, input, token)` + -`crypto::async_verify(executor, crypto::ecdsa_sha256, signature, input, public_key, token)` +| `public_key.verify(crypto::signing_schemes::ecdsa_sha256, signature, input)` + +`crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, input, public_key)` +| `public_key.async_verify(executor, crypto::signing_schemes::ecdsa_sha256, signature, input, token)` + +`crypto::async_verify(executor, crypto::signing_schemes::ecdsa_sha256, signature, input, public_key, token)` | Agree | `key_pair.agree(peer)` + @@ -176,13 +176,13 @@ first. ECDSA signs bytes so that anyone who holds the public key, a browser's WebCrypto included, can check who signed them and that nothing changed: a handshake, a token, a record a peer sends on. It signs the SHA-256 of a -message: `keypair::sign(crypto::ecdsa_sha256, message)` hashes the message +message: `keypair::sign(crypto::signing_schemes::ecdsa_sha256, message)` hashes the message inside the call and signs those 32 bytes, as WebCrypto's `+sign({name: "ECDSA", hash: "SHA-256"}, ...)+` hashes and signs in one call (link:https://www.w3.org/TR/WebCryptoAPI/[W3C]) and passkeys' ES256 does (link:https://www.w3.org/TR/webauthn-2/#sctn-alg-identifier[W3C Web Authentication]). A digest computed elsewhere is given as -`+crypto::prehashed{digest}+`, 32 bytes, and signed as given; a message is never +`+crypto::signing_schemes::prehashed{digest}+`, 32 bytes, and signed as given; a message is never read as a digest, whatever its size (<>): [source,cpp] @@ -196,13 +196,13 @@ number, a weak generator cannot leak the key, and the same key and digest give the same signature. Every verifier accepts it, WebCrypto's and OpenSSL's included: a verifier cannot tell how a nonce was made, and the signature is an ordinary ECDSA signature (link:https://csrc.nist.gov/pubs/fips/186-5/final[FIPS -186-5]). `crypto::verify(crypto::ecdsa_sha256, signature, input, public_key)`, +186-5]). `crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, input, public_key)`, the input the message or the marked digest, succeeds or returns `invalid_signature`, also for an r or an s that is 0 or not below the group order n, refused before BearSSL sees it. -In an event loop, `async_sign(executor, key_pair, crypto::ecdsa_sha256, input, -token)` and `async_verify(executor, crypto::ecdsa_sha256, signature, input, +In an event loop, `async_sign(executor, key_pair, crypto::signing_schemes::ecdsa_sha256, input, +token)` and `async_verify(executor, crypto::signing_schemes::ecdsa_sha256, signature, input, public_key, token)` do the same through a completion, with the same inputs (<>). @@ -269,8 +269,8 @@ peer's is about one signature in two. Check every signature such a protocol receives. * `is_low_s` does not verify: a forged signature can have a low S. Check low S, then verify, and accept the signature only when both succeed. -* A 32-byte message is a message: `sign(crypto::ecdsa_sha256, message)` -hashes it, and only `+crypto::prehashed{digest}+` is signed as given. A digest +* A 32-byte message is a message: `sign(crypto::signing_schemes::ecdsa_sha256, message)` +hashes it, and only `+crypto::signing_schemes::prehashed{digest}+` is signed as given. A digest of another hash than SHA-256, marked as one, signs, and no WebCrypto peer verifies it, since WebCrypto's ECDSA with SHA-256 hashes what it verifies with SHA-256 itself; a marked digest of another size than 32 bytes does not @@ -279,7 +279,7 @@ compile. signature arrives in DER (link:https://www.w3.org/TR/webauthn-2/#sctn-signature-attestation-types[W3C Web Authentication, section 6.5.5]): `from_der`, then -`+crypto::verify(crypto::ecdsa_sha256, ...)+` of what the authenticator signed, +`+crypto::verify(crypto::signing_schemes::ecdsa_sha256, ...)+` of what the authenticator signed, which it hashes with SHA-256. Reading the COSE key and building those signed bytes are WebAuthn's, and stay outside crypto. diff --git a/doc/p2p.adoc b/doc/p2p.adoc index df34a9de..e5a4e7a9 100644 --- a/doc/p2p.adoc +++ b/doc/p2p.adoc @@ -261,7 +261,7 @@ its 32-byte scalar and made again from it (<>), and draws a fresh key pair for each session. It sends both public keys raw, the 65 bytes of WebCrypto's `exportKey("raw")`, and the receiver makes each a `public_key`, which checks the point once. Both sides hash the handshake's bytes with SHA-256 -and each signs the digest, marked `+crypto::prehashed{digest}+`, with its +and each signs the digest, marked `+crypto::signing_schemes::prehashed{digest}+`, with its identity, as WebCrypto's ECDSA with SHA-256 signs (<>). A signature has two forms, s and n - s, and both verify; a protocol that requires one form, low S, gets it from `sign`, which signs no other, and its receiver diff --git a/doc/secp256k1.adoc b/doc/secp256k1.adoc index 0ebcb12c..e8c3bdeb 100644 --- a/doc/secp256k1.adoc +++ b/doc/secp256k1.adoc @@ -12,14 +12,14 @@ `webcpp::crypto::curves::secp256k1`. It offers two signature schemes and one key agreement: -* *BIP 340 Schnorr signatures*, `crypto::schnorr`, 64 bytes over a message of +* *BIP 340 Schnorr signatures*, `crypto::signing_schemes::schnorr`, 64 bytes over a message of any length, with a 32-byte x-only public key: Bitcoin's Taproot and Nostr's events (link:https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki[BIP 340]; link:https://github.com/nostr-protocol/nips/blob/master/01.md[NIP-01]; link:https://en.wikipedia.org/wiki/Schnorr_signature[Wikipedia]); -* *ECDSA signatures*, `crypto::ecdsa_sha256`, 64 bytes over the SHA-256 of a -message, or over a 32-byte digest given as `+crypto::prehashed{digest}+`, with a +* *ECDSA signatures*, `crypto::signing_schemes::ecdsa_sha256`, 64 bytes over the SHA-256 of a +message, or over a 32-byte digest given as `+crypto::signing_schemes::prehashed{digest}+`, with a 33-byte compressed public key: Bitcoin before Taproot and Ethereum (link:https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm[Wikipedia]; link:https://ethereum.github.io/yellowpaper/paper.pdf[Ethereum's yellow paper]). @@ -45,8 +45,8 @@ and refusals (<>). It has no asynchronous form: secp256k1 is not in WebCrypto, whose algorithms the asynchronous family follows. `sign` and `crypto::sign` take the 32 bytes of hedged ECDSA's extra entropy or BIP 340's auxiliary randomness after the input; `public_key.verify` -takes `crypto::ecdsa_sha256` and `crypto::schnorr`, and `crypto::verify` with -`crypto::schnorr` also takes the 32-byte x-only key: +takes `crypto::signing_schemes::ecdsa_sha256` and `crypto::signing_schemes::schnorr`, and `crypto::verify` with +`crypto::signing_schemes::schnorr` also takes the 32-byte x-only key: .secp256k1's operations in their two forms [cols="1,3,3",options="header"] @@ -83,12 +83,12 @@ nothing else (<>). The namespace's functions, by header: * ``: 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, with -`crypto::ecdsa_sha256_recoverable`, and with Ethereum's -`crypto::ecdsa_keccak256_recoverable`), its ECDH (`agree`, `agree_hashed`, +`crypto::signing_schemes::schnorr`, its auxiliary randomness drawn or given, with +`crypto::signing_schemes::ecdsa_sha256`, hedged or not, with +`crypto::signing_schemes::ecdsa_sha256_recoverable`, and with Ethereum's +`crypto::signing_schemes::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 +`crypto::signing_schemes::schnorr` and `crypto::signing_schemes::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 @@ -159,12 +159,12 @@ overwhelming probability, but not always: `from_secret` returns * Keep the secret key out of logs, crash reports and source control: the key 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, +`sign(crypto::signing_schemes::schnorr, message)` draws it from `random_device`, and returns +`entropy_unavailable` when it cannot. `sign(crypto::signing_schemes::schnorr, message, 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 +* `+crypto::verify(crypto::signing_schemes::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 accepts both forms of a signature, so it must not rely on the signature's bytes @@ -270,7 +270,7 @@ the uncompressed form without its prefix `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 +coordinate alone, 32 bytes, which `+crypto::verify(crypto::signing_schemes::schnorr, ...)+` takes as it takes the `public_key` itself. Two `public_key` values compare with `==`, and order with `+<=>+` as their compressed encodings do, the order MuSig2's key sorting uses @@ -304,16 +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)` gives a +`sign(crypto::signing_schemes::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 +`sign(crypto::signing_schemes::ecdsa_sha256, input)`, and +`recover(crypto::signing_schemes::ecdsa_sha256_recoverable, signature, input)` returns the `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 +a digest marked `crypto::signing_schemes::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: its scheme -is `crypto::ecdsa_keccak256_recoverable` (<>). +is `crypto::signing_schemes::ecdsa_keccak256_recoverable` (<>). include::generated/backends-recovery.adoc[] @@ -331,7 +331,7 @@ include::{examples}/recover_signer.cpp[tag=program] include::{examples}/recover_signer.expected[] ---- -`sign(crypto::ecdsa_sha256, input, extra_entropy)` is ECDSA's hedged form, +`sign(crypto::signing_schemes::ecdsa_sha256, input, extra_entropy)` is ECDSA's hedged form, which takes 32 more bytes, drawn from `random_device` and new for each signature, and mixes them into RFC 6979's nonce, as the RFC's variant with additional data allows @@ -363,16 +363,16 @@ extra data leaves the signature deterministic, as plain RFC 6979. 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 +paper, appendix F]), the scheme `crypto::signing_schemes::ecdsa_keccak256_recoverable`. +`sign(crypto::signing_schemes::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, +recovery id, and `recover(crypto::signing_schemes::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 +`+crypto::signing_schemes::prehashed{digest}+`. The scheme has no `crypto::verify`, as +`crypto::signing_schemes::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. @@ -442,8 +442,8 @@ 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 +* A message signed with `crypto::signing_schemes::ecdsa_keccak256_recoverable` and recovered +under `crypto::signing_schemes::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 @@ -721,7 +721,7 @@ send; * `partial_sign` signs this signer's part, consuming its secret nonce; `partial_signature_verify` checks one signer's part, and `partial_signature_aggregate` adds the parts into 64 bytes that -`+crypto::verify(crypto::schnorr, ...)+` checks; +`+crypto::verify(crypto::signing_schemes::schnorr, ...)+` checks; * `parse_public_nonce`, `parse_aggregate_nonce` and `parse_partial_signature` read what the other signers send, and the `serialize_` functions write it. diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 27c12293..d41b9747 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -270,7 +270,7 @@ "namespace": "root", "api": "async_from_secret, async_generate, async_sign, async_verify", "header": "", - "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.", + "what": "Ed25519's asynchronous from_secret, generate, sign and verify with `crypto::signing_schemes::eddsa`, and on a native backend with `crypto::signing_schemes::eddsa_prehashed` (Ed25519ph, which WebCrypto lacks), each completing through a post to the executor the call gives, with any Asio completion token.", "section": "crypto-async", "backends": { "sodium": {"tests": ["async_25519", "async_post"]} @@ -298,7 +298,7 @@ "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 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.", + "what": "P-256's asynchronous from_secret, generate, ECDSA sign and verify with `crypto::signing_schemes::ecdsa_sha256`, of a message hashed with SHA-256 or `crypto::signing_schemes::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"]} @@ -357,7 +357,7 @@ "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), `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.", + "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::signing_schemes::schnorr, message)` (BIP 340, its auxiliary randomness drawn or given), `sign(crypto::signing_schemes::ecdsa_sha256, input)` (hedged too), `sign(crypto::signing_schemes::ecdsa_sha256_recoverable, input)` and Ethereum's `sign(crypto::signing_schemes::ecdsa_keccak256_recoverable, input)`, the input a message hashed inside (with Keccak-256 for Ethereum's, which needs `/third_party//xkcp`) or `crypto::signing_schemes::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"]}} }, @@ -369,7 +369,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)` and `recover(crypto::ecdsa_keccak256_recoverable, signature, input)` give 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::signing_schemes::schnorr, signature, message, key)`, or an ECDSA one against a `curves::secp256k1::public_key`, `crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, input, public_key)`, refusing a high S; `recover(crypto::signing_schemes::ecdsa_sha256_recoverable, signature, input)` and `recover(crypto::signing_schemes::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,7 +415,7 @@ "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 of a message's SHA-512 with `sign(crypto::eddsa_prehashed, crypto::prehashed{digest})` (Ed25519ph, native backends); and its X25519 key pair, `to_x25519()`.", + "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::signing_schemes::eddsa, message)`, and of a message's SHA-512 with `sign(crypto::signing_schemes::eddsa_prehashed, crypto::signing_schemes::prehashed{digest})` (Ed25519ph, native backends); and its X25519 key pair, `to_x25519()`.", "section": "crypto-ed25519", "backends": { "sodium": {"tests": ["ed25519_sodium", "oracle_25519"]}, @@ -430,7 +430,7 @@ "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; and its X25519 public key, `to_x25519()`.", + "what": "An Ed25519 public key, its 32 bytes, which `crypto::verify(crypto::signing_schemes::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"]}, @@ -445,7 +445,7 @@ "namespace": "curves", "api": "crypto::verify", "header": "", - "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.", + "what": "Verifies an Ed25519 signature with a public key alone, `crypto::verify(crypto::signing_schemes::eddsa, signature, message, public_key)`, or an Ed25519ph one, `crypto::verify(crypto::signing_schemes::eddsa_prehashed, signature, crypto::signing_schemes::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"]}} }, @@ -456,7 +456,7 @@ "namespace": "curves", "api": "curves::ed25519::prehashed_signer", "header": "", - "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.", + "what": "Ed25519ph (RFC 8032), the streaming form of the scheme `crypto::signing_schemes::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::signing_schemes::eddsa_prehashed, crypto::signing_schemes::prehashed{digest})` gives of its SHA-512.", "section": "crypto-ed25519", "backends": {"sodium": {"tests": ["ed25519ph_sodium"]}} }, @@ -665,7 +665,7 @@ "namespace": "curves", "api": "curves::secp256k1::recover", "header": "", - "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}`.", + "what": "The public key that made a recoverable ECDSA signature, `recover(crypto::signing_schemes::ecdsa_sha256_recoverable, signature, input)` or Ethereum's `recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, signature, input)`, the input as signing took it: a message hashed inside (with SHA-256, or Keccak-256) or `crypto::signing_schemes::prehashed{digest}`.", "section": "crypto-secp256k1-recovery", "backends": {"secp256k1": {"tests": ["secp256k1_recovery"]}} }, @@ -779,7 +779,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}`; 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.", + "what": "ECDSA over SHA-256 with RFC 6979's nonce, `sign(crypto::signing_schemes::ecdsa_sha256, input)` and `crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, input, public_key)`, the input a message hashed inside or `crypto::signing_schemes::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"]}, @@ -1158,7 +1158,7 @@ {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "bearssl", "tests": ["p256_keys_bearssl", "p256_ecdsa_bearssl", "p256_ecdh_bearssl", "default_backend_none_linked"], "why": "the one backend of the P-curves on all four targets, constant time by design and allocating nothing ({bearssl}); OpenSSL and Botan join in increments 8 and 7"} ], "backends": { - "bearssl": {"targets": "all", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect"]}, "lane_note": {"memcheck": "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)", "msan": "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": "`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)"}} + "bearssl": {"targets": "all", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect"]}, "lane_note": {"memcheck": "the key pair's making, `sign` of a digest (`crypto::signing_schemes::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)", "msan": "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": "`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)"}} } } ], @@ -1169,7 +1169,7 @@ {"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 `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": "Ethereum", "section": "crypto-curves", "text": "this version signs Ethereum's recoverable ECDSA over Keccak-256 (`keypair::sign(crypto::signing_schemes::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 `secure::constant_time_equal`, never `==` or `memcmp` ({cwe208})."}, {"title": "Secrets come from random_device", "section": "crypto-entropy", "text": "keys, nonces and tokens are drawn from `random_device`, never `std::mt19937` or `rand` ({cwe338})."}, {"title": "Never reuse a nonce under one ChaCha20-Poly1305 key", "section": "crypto-chacha", "text": "two messages under one key and one nonce reveal the XOR of their plaintexts and let an attacker forge tags ({rfc8439-nonce}). `xchacha20_poly1305` and the secret boxes: draw 24 bytes at random per message. `chacha20_poly1305`: number the 12-byte nonces with a counter that never repeats, a restart included, or draw them at random for at most 2^32 messages per key, AES-GCM's bound for random 12-byte nonces ({sp800-38d}). `chacha20_poly1305_original`: a counter only, its 8 bytes are too short to draw."}, @@ -1243,7 +1243,7 @@ "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, 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"], + ["`ed25519`", "Ed25519 signatures, and Ed25519ph over SHA-512, of a digest (`crypto::signing_schemes::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"] ] @@ -1277,24 +1277,24 @@ {"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::from_bytes`, `crypto::verify`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "signed_update", "section": "crypto-everyday-update"}, + {"need": "Prove who wrote a message posted to a relay", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::sign(crypto::signing_schemes::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::signing_schemes::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_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": "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::signing_schemes::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_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": "Sign a Bitcoin SegWit v0 input (a domain library's job)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::sign(crypto::signing_schemes::ecdsa_sha256, crypto::signing_schemes::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::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": "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": "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::signing_schemes::eddsa, message)`, `keypair::sign(crypto::signing_schemes::eddsa_prehashed, crypto::signing_schemes::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"}, @@ -1304,10 +1304,10 @@ {"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": "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::signing_schemes::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"}, - {"need": "Sign a peer-to-peer handshake a browser's WebCrypto verifies, low S, check the peer's, and derive the session key from ECDH (Trystero's protocol is webcpp::trystero's)", "namespace": "webcpp::crypto::curves::p256", "api": "`keypair::sign(crypto::ecdsa_sha256, crypto::prehashed{digest})`, `is_low_s`, `crypto::verify`, `keypair::agree`; `webcpp::hash::hkdf` for the key", "backend": "BearSSL", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//p256-default", "example": "p256_handshake", "section": "crypto-p2p-handshake"} + {"need": "Sign a peer-to-peer handshake a browser's WebCrypto verifies, low S, check the peer's, and derive the session key from ECDH (Trystero's protocol is webcpp::trystero's)", "namespace": "webcpp::crypto::curves::p256", "api": "`keypair::sign(crypto::signing_schemes::ecdsa_sha256, crypto::signing_schemes::prehashed{digest})`, `is_low_s`, `crypto::verify`, `keypair::agree`; `webcpp::hash::hkdf` for the key", "backend": "BearSSL", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//p256-default", "example": "p256_handshake", "section": "crypto-p2p-handshake"} ], "fixtures": { "web": "A web application: AES-256-GCM on BearSSL, the default on WebAssembly.", @@ -1447,31 +1447,32 @@ "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; 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` 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` 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`, `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.", + "async_sign_ed25519_prehashed": "Give `async_sign` the message itself with `crypto::signing_schemes::eddsa`, RFC 8032's pure Ed25519, which takes no digest, as the synchronous `sign` does; a message's SHA-512 is signed with `crypto::signing_schemes::eddsa_prehashed` (Ed25519ph), on a native backend.", + "async_sign_p256_eddsa": "Give `async_sign` the key pair's own scheme: `crypto::signing_schemes::ecdsa_sha256` for a P-256 key pair, `crypto::signing_schemes::eddsa` or `crypto::signing_schemes::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::signing_schemes::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::signing_schemes::eddsa` or `crypto::signing_schemes::eddsa_prehashed` and a `curves::p256::basic_public_key` with `crypto::signing_schemes::ecdsa_sha256`.", + "scheme_in_crypto_namespace": "Name the scheme in `crypto::signing_schemes`: `crypto::signing_schemes::ecdsa_sha256`; the tags are no longer in `crypto`, with no alias.", + "prehashed_dynamic": "Give `crypto::signing_schemes::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::signing_schemes::ecdsa_sha256`, P-256's scheme; BIP340's `crypto::signing_schemes::schnorr` is secp256k1's.", + "sign_ed25519_ecdsa": "Sign with `crypto::signing_schemes::eddsa` or `crypto::signing_schemes::eddsa_prehashed`, Ed25519's schemes; `crypto::signing_schemes::ecdsa_sha256` is P-256's and secp256k1's.", + "sign_ed25519_prehashed": "Sign the message itself with `crypto::signing_schemes::eddsa`, RFC 8032's pure Ed25519, which takes no digest; to sign a message's SHA-512, use Ed25519ph, `crypto::signing_schemes::eddsa_prehashed`, or for a message given in pieces `curves::ed25519::prehashed_signer`.", + "sign_schnorr_prehashed": "Sign the message itself with `crypto::signing_schemes::schnorr`, BIP340's, which has no prehash mode; a taproot sighash, BIP341's tagged hash, is that message.", + "sign_secp256k1_eddsa": "Sign with `crypto::signing_schemes::ecdsa_sha256`, `crypto::signing_schemes::ecdsa_sha256_recoverable`, `crypto::signing_schemes::ecdsa_keccak256_recoverable` or `crypto::signing_schemes::schnorr`, secp256k1's schemes; `crypto::signing_schemes::eddsa` is Ed25519's.", + "sign_secp256k1_not_a_scheme": "Name the scheme with its tag: `crypto::signing_schemes::ecdsa_sha256`, `crypto::signing_schemes::ecdsa_sha256_recoverable`, `crypto::signing_schemes::ecdsa_keccak256_recoverable` or `crypto::signing_schemes::schnorr`.", + "verify_ecdsa_bytes_key": "Give `crypto::signing_schemes::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::signing_schemes::eddsa` (or `crypto::signing_schemes::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::signing_schemes::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::signing_schemes::eddsa` or `crypto::signing_schemes::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 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`.", + "verify_member_eddsa_prehashed": "Verify the message itself with `crypto::signing_schemes::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::signing_schemes::eddsa_prehashed`, or for a message given in pieces with `curves::ed25519::prehashed_signer`.", + "verify_member_ed25519_ecdsa": "Verify with `crypto::signing_schemes::eddsa` or `crypto::signing_schemes::eddsa_prehashed`, Ed25519's schemes; `crypto::signing_schemes::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::signing_schemes::ecdsa_sha256_recoverable, signature, input)`, which gives the signer's key; a public key verifies `crypto::signing_schemes::ecdsa_sha256` and `crypto::signing_schemes::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::signing_schemes::ecdsa_sha256` and `crypto::signing_schemes::schnorr` with a secp256k1 key.", + "verify_member_p256_eddsa": "Verify with `crypto::signing_schemes::ecdsa_sha256`, P-256's scheme; `crypto::signing_schemes::eddsa` is Ed25519's, whose key is a `curves::ed25519::public_key`.", "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_schnorr_as_ecdsa": "Verify a BIP340 signature with `crypto::signing_schemes::schnorr`, its scheme; `crypto::signing_schemes::ecdsa_sha256` takes a `curves::secp256k1::ecdsa_signature`, which `sign(crypto::signing_schemes::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.", + "recover_ecdsa_signature": "Give `recover` a `curves::secp256k1::recoverable_signature`, which `sign(crypto::signing_schemes::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.", @@ -1488,20 +1489,20 @@ "seal_asynchronous_backend": "Call `async_seal` 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.", + "sign_p256_digest_48": "Give `crypto::signing_schemes::ecdsa_sha256` SHA-256's 32-byte digest, `crypto::signing_schemes::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::signing_schemes::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::signing_schemes::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::signing_schemes::ecdsa_sha256`, P-256's scheme; Ethereum's `crypto::signing_schemes::ecdsa_keccak256_recoverable` is secp256k1's.", + "sign_ed25519_keccak": "Sign with `crypto::signing_schemes::eddsa` or `crypto::signing_schemes::eddsa_prehashed`, Ed25519's schemes; Ethereum's `crypto::signing_schemes::ecdsa_keccak256_recoverable` is secp256k1's.", + "verify_keccak_recoverable": "Give the signature to `curves::secp256k1::recover(crypto::signing_schemes::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::signing_schemes::prehashed{digest}`, which needs no XKCP.", + "sign_eddsa_prehashed_message": "Give `crypto::signing_schemes::eddsa_prehashed` the message's SHA-512 marked as a digest, `crypto::signing_schemes::prehashed{digest}` of a `std::array`; sign the message itself with `crypto::signing_schemes::eddsa`, or give it in pieces to `curves::ed25519::prehashed_signer`.", + "sign_eddsa_prehashed_digest_32": "Give `crypto::signing_schemes::eddsa_prehashed` SHA-512's 64-byte digest, `crypto::signing_schemes::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::signing_schemes::eddsa_prehashed` the marker of the message's SHA-512, or the message itself under `crypto::signing_schemes::eddsa`.", + "sign_eddsa_prehashed_asynchronous_backend": "Sign under `crypto::signing_schemes::eddsa_prehashed` with a key pair of a native backend: WebCrypto has no Ed25519ph; on the browser's backend, sign the message with `crypto::signing_schemes::eddsa`.", + "async_sign_eddsa_prehashed_asynchronous_backend": "As `sign_eddsa_prehashed_asynchronous_backend`: `async_sign` under `crypto::signing_schemes::eddsa_prehashed` runs on a native backend.", + "verify_eddsa_prehashed_asynchronous_backend": "Verify under `crypto::signing_schemes::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::signing_schemes::eddsa`.", + "async_verify_eddsa_prehashed_asynchronous_backend": "As `verify_eddsa_prehashed_asynchronous_backend`: `async_verify` under `crypto::signing_schemes::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`.", @@ -1514,7 +1515,7 @@ "pem_default_not_linked": "Add `/webcpp/crypto//pem-default`, which links `/third_party//sodium` on every target.", "chacha_header_not_included": "Include the backend's header the message names, as ``, and add its library, as `/third_party//bearssl`.", "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`.", + "ed25519_unknown_policy": "Leave the policy out, as in `crypto::verify(crypto::signing_schemes::eddsa, signature, message, public_key)`, or name `curves::ed25519::strict`.", "equal_header_removed": "Include ``, the header of `secure::constant_time_equal`; `equal.hpp` is gone, with no header left at its path.", "equal_removed": "Call `webcpp::secure::constant_time_equal`, the same comparison of two byte sequences in constant time; `crypto::equal` is gone, with no alias.", "wipe_removed": "Call `webcpp::secure::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.", diff --git a/doc/wallets.adoc b/doc/wallets.adoc index b07a44b0..0c554466 100644 --- a/doc/wallets.adoc +++ b/doc/wallets.adoc @@ -66,7 +66,7 @@ proposed it as a consensus rule). *The idea.* The domain library computes the signature hash, the sighash (SHA-256 twice over the preimage it serialized); crypto signs it as -`+crypto::prehashed{sighash}+` under `crypto::ecdsa_sha256`, which is honest, the +`+crypto::signing_schemes::prehashed{sighash}+` under `crypto::signing_schemes::ecdsa_sha256`, which is honest, the sighash being the SHA-256 of a SHA-256 (<>). It signs deterministically and in low-S form, and `to_der` encodes the signature as strict DER: @@ -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 +appendix F]). `sign(crypto::signing_schemes::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 +`recover(crypto::signing_schemes::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,8 +185,8 @@ 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: Ethereum's scheme is `crypto::ecdsa_keccak256_recoverable`, which -signs and recovers that digest given as `+crypto::prehashed{digest}+` +Keccak-256's: Ethereum's scheme is `crypto::signing_schemes::ecdsa_keccak256_recoverable`, which +signs and recovers that digest given as `+crypto::signing_schemes::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 diff --git a/example/Jamfile b/example/Jamfile index 16d7c7e5..8d0ba3ea 100644 --- a/example/Jamfile +++ b/example/Jamfile @@ -63,7 +63,7 @@ webcpp.example ecdh_x_coordinate.cpp : /third_party//secp256k1 ; 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 +# Keccak-256, signed with crypto::signing_schemes::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 ; @@ -107,7 +107,7 @@ webcpp.example wallet_key.cpp : /third_party//secp256k1 /webcp webcpp.example ecdsa_der.cpp : /third_party//secp256k1 ; # A Bitcoin legacy or segwit v0 sighash: SHA-256d computed with webcpp::hash, -# signed as crypto::prehashed under crypto::ecdsa_sha256, verified, as DER. +# signed as crypto::signing_schemes::prehashed under crypto::signing_schemes::ecdsa_sha256, verified, as DER. webcpp.example bitcoin_sighash.cpp : /third_party//secp256k1 ; # BIP341 key-path tweak of an internal key and a signature under the output key. diff --git a/example/arena_signer.cpp b/example/arena_signer.cpp index acb968d3..81ebec36 100644 --- a/example/arena_signer.cpp +++ b/example/arena_signer.cpp @@ -75,9 +75,9 @@ int main() { message.fill(0x17); std::array const aux{}; auto const public_key = key->public_key(); - auto const signature = key->sign(crypto::schnorr, message, aux); + auto const signature = key->sign(crypto::signing_schemes::schnorr, message, aux); if (!public_key || !signature || - !crypto::verify(crypto::schnorr, *signature, message, *public_key)) { + !crypto::verify(crypto::signing_schemes::schnorr, *signature, message, *public_key)) { return 1; } std::printf("allocations in the arena: %zu\n", counting.allocations()); diff --git a/example/async_sign.cpp b/example/async_sign.cpp index 10d185f0..c75c7ff7 100644 --- a/example/async_sign.cpp +++ b/example/async_sign.cpp @@ -5,11 +5,10 @@ // https://www.boost.org/LICENSE_1_0.txt) // 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. -// tag::program[] +// published seed, never a real key), signs the test's message with crypto::signing_schemes::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. tag::program[] #include #include @@ -73,7 +72,7 @@ asio::awaitable sign_and_verify() { co_return false; } auto [signed_code, signature] = - co_await crypto::async_sign(executor, key, crypto::eddsa, message, use); + co_await crypto::async_sign(executor, key, crypto::signing_schemes::eddsa, message, use); if (signed_code) { std::printf("sign: %s\n", signed_code.message().c_str()); co_return false; @@ -81,8 +80,8 @@ asio::awaitable sign_and_verify() { print("public key", public_key->bytes()); 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); + auto [verified] = co_await crypto::async_verify(executor, crypto::signing_schemes::eddsa, + signature, message, *public_key, use); if (verified) { std::printf("verify: %s\n", verified.message().c_str()); co_return false; diff --git a/example/bitcoin_sighash.cpp b/example/bitcoin_sighash.cpp index 807cfc9c..cec5f8a6 100644 --- a/example/bitcoin_sighash.cpp +++ b/example/bitcoin_sighash.cpp @@ -9,8 +9,8 @@ // 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). +// crypto::signing_schemes::ecdsa_sha256. A taproot sighash, BIP341's tagged hash, is the message of +// crypto::signing_schemes::schnorr instead (musig_taproot.cpp, taproot_tweak.cpp). // tag::program[] #include #include @@ -74,9 +74,10 @@ int main() { // tag::sign[] // The sighash is a SHA-256 digest: marked as one, ECDSA over SHA-256 signs it as given. - auto const signature = key->sign(crypto::ecdsa_sha256, crypto::prehashed{sighash}); - if (!signature || !crypto::verify(crypto::ecdsa_sha256, *signature, crypto::prehashed{sighash}, - *public_key)) { + auto const signature = key->sign(crypto::signing_schemes::ecdsa_sha256, + crypto::signing_schemes::prehashed{sighash}); + if (!signature || !crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signature, + crypto::signing_schemes::prehashed{sighash}, *public_key)) { return 1; } // end::sign[] diff --git a/example/ecdsa_der.cpp b/example/ecdsa_der.cpp index 0ac6fc44..0da1b4f7 100644 --- a/example/ecdsa_der.cpp +++ b/example/ecdsa_der.cpp @@ -95,7 +95,8 @@ int main() { reinterpret_cast(preimage.data()), preimage.size())); auto const sighash = sha256(first); // A digest the library computed is marked as one; ECDSA over SHA-256 signs it as given. - auto const signature = key->sign(crypto::ecdsa_sha256, crypto::prehashed{sighash}); + auto const signature = key->sign(crypto::signing_schemes::ecdsa_sha256, + crypto::signing_schemes::prehashed{sighash}); if (!signature) { return 1; } @@ -113,8 +114,8 @@ int main() { } std::printf("strict der round trip ok\n"); if (!secp256k1::is_low_s(*signature) || - !crypto::verify(crypto::ecdsa_sha256, *signature, crypto::prehashed{sighash}, - *public_key)) { + !crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signature, + crypto::signing_schemes::prehashed{sighash}, *public_key)) { return 1; } std::printf("verified\n"); @@ -129,8 +130,8 @@ int main() { return 1; } auto const& high = *received; - auto const refused = - crypto::verify(crypto::ecdsa_sha256, high, crypto::prehashed{sighash}, *public_key); + auto const refused = crypto::verify(crypto::signing_schemes::ecdsa_sha256, high, + crypto::signing_schemes::prehashed{sighash}, *public_key); if (refused || refused.error() != crypto::error::invalid_signature) { return 1; } @@ -138,8 +139,8 @@ int main() { // A signature from elsewhere can be brought to the low-S form before it is checked. auto const normalized = secp256k1::normalize_low_s(high); if (secp256k1::is_low_s(high) || !normalized || *normalized != *signature || - !crypto::verify(crypto::ecdsa_sha256, *normalized, crypto::prehashed{sighash}, - *public_key)) { + !crypto::verify(crypto::signing_schemes::ecdsa_sha256, *normalized, + crypto::signing_schemes::prehashed{sighash}, *public_key)) { return 1; } std::printf("normalized to low-S: verified\n"); diff --git a/example/ed25519_sign.cpp b/example/ed25519_sign.cpp index 45a92e5a..8540c061 100644 --- a/example/ed25519_sign.cpp +++ b/example/ed25519_sign.cpp @@ -5,15 +5,15 @@ // https://www.boost.org/LICENSE_1_0.txt) // Signs RFC 8032's second Ed25519 test with a key pair made from its seed and verifies the -// signature with the public key alone, `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. -// tag::program[] +// signature with the public key alone, `key.sign(crypto::signing_schemes::eddsa, message)` and +// `crypto::verify(crypto::signing_schemes::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::signing_schemes::eddsa_prehashed`, which gives the same signature, and +// verifies it with `crypto::verify(crypto::signing_schemes::eddsa_prehashed, signature, +// crypto::signing_schemes::prehashed{digest}, public_key)`. Prints each key and signature in hex, +// and whether the two Ed25519ph signatures are equal. tag::program[] #include #include @@ -58,19 +58,20 @@ bool sign_whole() { return false; } auto const public_key = key->public_key(); - auto const signature = key->sign(crypto::eddsa, message); + auto const signature = key->sign(crypto::signing_schemes::eddsa, message); if (!public_key || !signature) { return false; } print("public key", public_key->bytes()); 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(); + return crypto::verify(crypto::signing_schemes::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; then the same message's SHA-512 signed under the scheme -// crypto::eddsa_prehashed, as a program that has the digest already signs it. +// crypto::signing_schemes::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, @@ -104,15 +105,17 @@ bool sign_in_pieces() { 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}); + auto const from_digest = key->sign(crypto::signing_schemes::eddsa_prehashed, + crypto::signing_schemes::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(); + return *from_digest == *signature && + crypto::verify(crypto::signing_schemes::eddsa_prehashed, *from_digest, + crypto::signing_schemes::prehashed{digest}, *public_key) + .has_value(); } } // namespace diff --git a/example/ethereum_personal_sign.cpp b/example/ethereum_personal_sign.cpp index 8b8d41b5..bf24fde8 100644 --- a/example/ethereum_personal_sign.cpp +++ b/example/ethereum_personal_sign.cpp @@ -6,13 +6,13 @@ // 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[] +// Keccak-256, signs it as crypto::signing_schemes::prehashed with +// crypto::signing_schemes::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 @@ -79,10 +79,11 @@ int main() { } // tag::sign[] - // The wallet signs EIP-191's digest as given: crypto::prehashed, never hashed again. + // The wallet signs EIP-191's digest as given: crypto::signing_schemes::prehashed, never hashed + // again. auto const digest = personal_sign_digest("Some data"); - auto const signature = - wallet->sign(crypto::ecdsa_keccak256_recoverable, crypto::prehashed{digest}); + auto const signature = wallet->sign(crypto::signing_schemes::ecdsa_keccak256_recoverable, + crypto::signing_schemes::prehashed{digest}); if (!signature) { return 1; } @@ -96,8 +97,8 @@ int main() { // 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}); + auto const signer = secp256k1::recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, + *signature, crypto::signing_schemes::prehashed{digest}); if (!signer) { return 1; } diff --git a/example/four_forms.cpp b/example/four_forms.cpp index 2b0568bd..85f4990a 100644 --- a/example/four_forms.cpp +++ b/example/four_forms.cpp @@ -5,11 +5,10 @@ // https://www.boost.org/LICENSE_1_0.txt) // 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. -// tag::program[] +// crypto::signing_schemes::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. tag::program[] #include #include #include @@ -82,8 +81,8 @@ int main() { // tag::sign[] // Synchronous: the member, and its free form, which calls it. - auto const signature = key->sign(crypto::ecdsa_sha256, message); - auto const free_signature = crypto::sign(*key, crypto::ecdsa_sha256, message); + auto const signature = key->sign(crypto::signing_schemes::ecdsa_sha256, message); + auto const free_signature = crypto::sign(*key, crypto::signing_schemes::ecdsa_sha256, message); // Asynchronous: the member, and its free form, which calls it. Each runs the synchronous // member when it is initiated and completes through the loop, never inside the call. @@ -91,13 +90,13 @@ int main() { auto const executor = loop.get_executor(); p256::ecdsa_signature async_signature; p256::ecdsa_signature free_async_signature; - key->async_sign(executor, crypto::ecdsa_sha256, message, + key->async_sign(executor, crypto::signing_schemes::ecdsa_sha256, message, [&](boost::system::error_code code, p256::ecdsa_signature made) { if (!code) { async_signature = made; } }); - crypto::async_sign(executor, *key, crypto::ecdsa_sha256, message, + crypto::async_sign(executor, *key, crypto::signing_schemes::ecdsa_sha256, message, [&](boost::system::error_code code, p256::ecdsa_signature made) { if (!code) { free_async_signature = made; @@ -116,16 +115,19 @@ int main() { // tag::verify[] // Synchronous: the public key's member, and its free form, crypto::verify. - bool const verified = public_key->verify(crypto::ecdsa_sha256, *signature, message).has_value(); + bool const verified = + public_key->verify(crypto::signing_schemes::ecdsa_sha256, *signature, message).has_value(); bool const free_verified = - crypto::verify(crypto::ecdsa_sha256, *signature, message, *public_key).has_value(); + crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signature, message, *public_key) + .has_value(); // Asynchronous: the member and its free form complete with the error code alone. bool async_verified = false; bool free_async_verified = false; - public_key->async_verify(executor, crypto::ecdsa_sha256, *signature, message, + public_key->async_verify(executor, crypto::signing_schemes::ecdsa_sha256, *signature, message, [&](boost::system::error_code code) { async_verified = !code; }); - crypto::async_verify(executor, crypto::ecdsa_sha256, *signature, message, *public_key, + crypto::async_verify(executor, crypto::signing_schemes::ecdsa_sha256, *signature, message, + *public_key, [&](boost::system::error_code code) { free_async_verified = !code; }); loop.restart(); loop.run(); // lint-run: the program's event loop diff --git a/example/key_formats.cpp b/example/key_formats.cpp index d4f92865..7975d4e1 100644 --- a/example/key_formats.cpp +++ b/example/key_formats.cpp @@ -75,8 +75,9 @@ bool ed25519_from_pem() { return false; } std::array const message{'h', 'e', 'l', 'l', 'o'}; - auto const signature = pair->sign(crypto::eddsa, message); - return signature && crypto::verify(crypto::eddsa, *signature, message, *public_key); + auto const signature = pair->sign(crypto::signing_schemes::eddsa, message); + return signature && + crypto::verify(crypto::signing_schemes::eddsa, *signature, message, *public_key); } // An X25519 public key of RFC 7748's Alice, as SPKI in PEM. diff --git a/example/key_tweak.cpp b/example/key_tweak.cpp index 76299c49..c63ab724 100644 --- a/example/key_tweak.cpp +++ b/example/key_tweak.cpp @@ -117,9 +117,10 @@ int main() { if (!device.fill(aux)) { return 1; } - auto const signature = payment_key->sign(crypto::schnorr, message, aux); + auto const signature = payment_key->sign(crypto::signing_schemes::schnorr, message, aux); auto const xonly = watched->xonly(); - if (!signature || !crypto::verify(crypto::schnorr, *signature, message, xonly)) { + if (!signature || + !crypto::verify(crypto::signing_schemes::schnorr, *signature, message, xonly)) { return 1; } std::printf("signature verifies under the tweaked public key\n"); diff --git a/example/musig_network.cpp b/example/musig_network.cpp index 2857abef..d1bc3ddf 100644 --- a/example/musig_network.cpp +++ b/example/musig_network.cpp @@ -177,8 +177,8 @@ int main() { // The parts add up to one BIP 340 signature under the wallet's one x-only key. std::array const parts{*phone_part_in, *laptop_part_in}; auto const signature = musig::partial_signature_aggregate(*signing_session, parts, space); - if (!signature || - !crypto::verify(crypto::schnorr, *signature, message, wallet_key->xonly_public_key())) { + if (!signature || !crypto::verify(crypto::signing_schemes::schnorr, *signature, message, + wallet_key->xonly_public_key())) { return 1; } std::printf("the aggregate signature verifies as one BIP 340 signature: %zu bytes\n", diff --git a/example/musig_taproot.cpp b/example/musig_taproot.cpp index f88e606c..d1c58cbf 100644 --- a/example/musig_taproot.cpp +++ b/example/musig_taproot.cpp @@ -137,11 +137,13 @@ int main() { // path, and not under the internal key. std::array const parts{*phone_part, *laptop_part}; auto const signature = musig::partial_signature_aggregate(*signing_session, parts, space); - if (!signature || !crypto::verify(crypto::schnorr, *signature, message, output_key)) { + if (!signature || + !crypto::verify(crypto::signing_schemes::schnorr, *signature, message, output_key)) { return 1; } std::printf("the signature verifies under the output key\n"); - auto const under_internal = crypto::verify(crypto::schnorr, *signature, message, internal_key); + auto const under_internal = + crypto::verify(crypto::signing_schemes::schnorr, *signature, message, internal_key); if (under_internal) { return 1; } diff --git a/example/musig_wallet.cpp b/example/musig_wallet.cpp index f08abed4..614842a4 100644 --- a/example/musig_wallet.cpp +++ b/example/musig_wallet.cpp @@ -103,8 +103,8 @@ int main() { // The parts add up to one BIP 340 signature under the wallet's one x-only key. std::array const parts{*phone_part, *laptop_part}; auto const signature = musig::partial_signature_aggregate(*signing_session, parts, space); - if (!signature || - !crypto::verify(crypto::schnorr, *signature, message, wallet_key->xonly_public_key())) { + if (!signature || !crypto::verify(crypto::signing_schemes::schnorr, *signature, message, + wallet_key->xonly_public_key())) { return 1; } std::printf("the aggregate signature verifies as one BIP 340 signature\n"); diff --git a/example/p256_handshake.cpp b/example/p256_handshake.cpp index 2dffab2d..40c1128e 100644 --- a/example/p256_handshake.cpp +++ b/example/p256_handshake.cpp @@ -155,7 +155,8 @@ struct peer { // requires. [[nodiscard]] boost::system::result sign( std::span digest) const { - return identity.sign(crypto::ecdsa_sha256, crypto::prehashed{digest}); + return identity.sign(crypto::signing_schemes::ecdsa_sha256, + crypto::signing_schemes::prehashed{digest}); } // end::sign[] @@ -180,8 +181,8 @@ struct peer { if (!p256::is_low_s(*signature)) { return verdict::high_s; } - if (!crypto::verify(crypto::ecdsa_sha256, *signature, crypto::prehashed{digest}, - *identity_key)) { + if (!crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signature, + crypto::signing_schemes::prehashed{digest}, *identity_key)) { return verdict::bad_signature; } return verdict::ok; @@ -276,7 +277,8 @@ int main() { return 1; } bool const verifies_alone = - crypto::verify(crypto::ecdsa_sha256, *high, crypto::prehashed{*digest}, *alice_identity) + crypto::verify(crypto::signing_schemes::ecdsa_sha256, *high, + crypto::signing_schemes::prehashed{*digest}, *alice_identity) .has_value(); std::printf("high S: %s; crypto::verify alone: %s\n", text_of(peer::check(*alice_hello, *digest, high->bytes())), diff --git a/example/p256_sign.cpp b/example/p256_sign.cpp index 96f57425..24e0ae71 100644 --- a/example/p256_sign.cpp +++ b/example/p256_sign.cpp @@ -64,7 +64,7 @@ int main() { // tag::sign[] // The message itself: ECDSA over SHA-256 hashes it inside, as WebCrypto's ECDSA with SHA-256 // signs. RFC 6979's nonce: no random number, the same signature for the same key and message. - auto const signature = key->sign(crypto::ecdsa_sha256, bytes_of("sample")); + auto const signature = key->sign(crypto::signing_schemes::ecdsa_sha256, bytes_of("sample")); // end::sign[] if (!signature) { std::printf("failed\n"); @@ -84,18 +84,19 @@ int main() { print("DER ", std::span(der).first(*length)); // The verifier holds the public key, the message and the signature; nothing secret. A digest - // computed elsewhere is marked as one, crypto::prehashed{digest}. + // computed elsewhere is marked as one, crypto::signing_schemes::prehashed{digest}. auto const decoded = p256::from_der(std::span(der).first(*length)); std::array digest{}; auto const hashed = webcpp::hash::digest_of(digest, bytes_of("sample")); - bool const both = - decoded && hashed && - crypto::verify(crypto::ecdsa_sha256, *decoded, bytes_of("sample"), *public_key) && - crypto::verify(crypto::ecdsa_sha256, *decoded, crypto::prehashed{digest}, *public_key); + bool const both = decoded && hashed && + crypto::verify(crypto::signing_schemes::ecdsa_sha256, *decoded, + bytes_of("sample"), *public_key) && + crypto::verify(crypto::signing_schemes::ecdsa_sha256, *decoded, + crypto::signing_schemes::prehashed{digest}, *public_key); std::printf("verified %s\n", both ? "message and digest" : "FAILED"); - auto const other = - crypto::verify(crypto::ecdsa_sha256, *signature, bytes_of("test"), *public_key); + auto const other = crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signature, + bytes_of("test"), *public_key); std::string const outcome = other ? std::string("verified") : other.error().message(); std::printf("other text %s\n", outcome.c_str()); return 0; diff --git a/example/recover_signer.cpp b/example/recover_signer.cpp index 8470f4c3..c5251f07 100644 --- a/example/recover_signer.cpp +++ b/example/recover_signer.cpp @@ -31,9 +31,9 @@ namespace secp256k1 = webcpp::crypto::curves::secp256k1; namespace { -// A text's bytes, the message. crypto::ecdsa_sha256_recoverable hashes it with SHA-256 inside; -// Ethereum's own message hash is EIP-191's (a prefix, then Keccak-256), which a domain library -// computes and gives as crypto::prehashed{digest}. +// A text's bytes, the message. crypto::signing_schemes::ecdsa_sha256_recoverable hashes it with +// SHA-256 inside; Ethereum's own message hash is EIP-191's (a prefix, then Keccak-256), which a +// domain library computes and gives as crypto::signing_schemes::prehashed{digest}. std::span bytes_of(std::string_view text) { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): a text's bytes return {reinterpret_cast(text.data()), text.size()}; @@ -66,7 +66,8 @@ int main() { } auto const wallet_key = wallet->public_key(); std::string message = "pay 10 to bob"; - auto const signature = wallet->sign(crypto::ecdsa_sha256_recoverable, bytes_of(message)); + auto const signature = + wallet->sign(crypto::signing_schemes::ecdsa_sha256_recoverable, bytes_of(message)); if (!wallet_key || !signature) { return 1; } @@ -76,8 +77,8 @@ int main() { // 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::from_bytes(published); - auto const signer = - secp256k1::recover(crypto::ecdsa_sha256_recoverable, *signature, bytes_of(message)); + auto const signer = secp256k1::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, + *signature, bytes_of(message)); if (!expected || !signer || *signer != *expected) { return 1; } @@ -85,8 +86,8 @@ int main() { // A changed message still recovers a key, but not the wallet's. message = "pay 99 to bob"; - auto const other = - secp256k1::recover(crypto::ecdsa_sha256_recoverable, *signature, bytes_of(message)); + auto const other = secp256k1::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, + *signature, bytes_of(message)); if (other && *other == *expected) { return 1; } diff --git a/example/schnorr_sign.cpp b/example/schnorr_sign.cpp index 9b7d1c8a..906d4f05 100644 --- a/example/schnorr_sign.cpp +++ b/example/schnorr_sign.cpp @@ -39,17 +39,19 @@ void print(char const* name, std::span bytes) { // Signs message with key and checks the signature under the key's x-only public key. The // auxiliary randomness is BIP340's first vector's, 32 zero bytes, so that the output is the same -// on every run; sign(crypto::schnorr, message) alone draws fresh bytes, as BIP340 recommends. +// on every run; sign(crypto::signing_schemes::schnorr, message) alone draws fresh bytes, as BIP340 +// recommends. bool sign_and_verify(secp256k1::keypair const& key, std::span message) { std::array const aux{}; auto const public_key = key.public_key(); - auto const signature = key.sign(crypto::schnorr, message, aux); + auto const signature = key.sign(crypto::signing_schemes::schnorr, message, aux); if (!public_key || !signature) { return false; } print("public key", public_key->xonly()); print("signature ", signature->bytes()); - return crypto::verify(crypto::schnorr, *signature, message, *public_key).has_value(); + return crypto::verify(crypto::signing_schemes::schnorr, *signature, message, *public_key) + .has_value(); } } // namespace diff --git a/example/signed_message.cpp b/example/signed_message.cpp index 434e1d71..28d35f4a 100644 --- a/example/signed_message.cpp +++ b/example/signed_message.cpp @@ -76,7 +76,7 @@ int main() { auto const id = id_of("meet at noon"); // sign draws 32 fresh auxiliary bytes, which make the signature unpredictable and guard // against fault attacks (BIP340). - auto const signature = author->sign(crypto::schnorr, id); + auto const signature = author->sign(crypto::signing_schemes::schnorr, id); if (!signature) { return 1; } @@ -84,12 +84,13 @@ int main() { // tag::verify[] // The reader needs only the message, the signature and the public key. - if (!crypto::verify(crypto::schnorr, *signature, id_of("meet at noon"), *public_key)) { + if (!crypto::verify(crypto::signing_schemes::schnorr, *signature, id_of("meet at noon"), + *public_key)) { return 1; } std::printf("verified\n"); - auto const altered = - crypto::verify(crypto::schnorr, *signature, id_of("meet at nine"), *public_key); + auto const altered = crypto::verify(crypto::signing_schemes::schnorr, *signature, + id_of("meet at nine"), *public_key); if (altered || altered.error() != crypto::error::invalid_signature) { return 1; } diff --git a/example/signed_update.cpp b/example/signed_update.cpp index 48f6b41b..f7180a9e 100644 --- a/example/signed_update.cpp +++ b/example/signed_update.cpp @@ -63,7 +63,7 @@ int main() { // The compressed public key (33 bytes) is what the program ships with. auto const publisher_public = publisher->public_key(); std::string update = "update v2.1 payload"; - auto const signature = publisher->sign(crypto::ecdsa_sha256, bytes_of(update)); + auto const signature = publisher->sign(crypto::signing_schemes::ecdsa_sha256, bytes_of(update)); if (!publisher_public || !signature) { return 1; } @@ -73,15 +73,15 @@ int main() { // 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::from_bytes(shipped_key); - if (!publisher_key || - !crypto::verify(crypto::ecdsa_sha256, *signature, bytes_of(update), *publisher_key)) { + if (!publisher_key || !crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signature, + bytes_of(update), *publisher_key)) { return 1; } std::printf("update accepted\n"); update[7] = update[7] == '2' ? '3' : '2'; - auto const tampered = - crypto::verify(crypto::ecdsa_sha256, *signature, bytes_of(update), *publisher_key); + auto const tampered = crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signature, + bytes_of(update), *publisher_key); if (tampered || tampered.error() != crypto::error::invalid_signature) { return 1; } diff --git a/example/taproot_tweak.cpp b/example/taproot_tweak.cpp index 4727e794..7f7df292 100644 --- a/example/taproot_tweak.cpp +++ b/example/taproot_tweak.cpp @@ -95,8 +95,9 @@ int main() { std::array const message{}; std::array const aux{}; - auto const signature = key->sign(crypto::schnorr, message, aux); - if (!signature || !crypto::verify(crypto::schnorr, *signature, message, output->key)) { + auto const signature = key->sign(crypto::signing_schemes::schnorr, message, aux); + if (!signature || + !crypto::verify(crypto::signing_schemes::schnorr, *signature, message, output->key)) { return 1; } std::printf("key-path signature verified\n"); diff --git a/include/webcpp/crypto/async.hpp b/include/webcpp/crypto/async.hpp index fc87f601..440017ec 100644 --- a/include/webcpp/crypto/async.hpp +++ b/include/webcpp/crypto/async.hpp @@ -31,26 +31,25 @@ 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, 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`. + `async_sign(executor, key_pair, crypto::signing_schemes::eddsa, message, token)` and + `async_verify(executor, crypto::signing_schemes::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, the typed `curves::ed25519::signature` and the typed + `curves::ed25519::public_key`. Under `crypto::signing_schemes::eddsa_prehashed` (Ed25519ph), + the same functions take `crypto::signing_schemes::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_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 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`. + `async_sign(executor, key_pair, crypto::signing_schemes::ecdsa_sha256, input, token)` and + `async_verify(executor, crypto::signing_schemes::ecdsa_sha256, signature, input, public_key, + token)`, ECDSA 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::signing_schemes::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`. - The heavy functions (design D32's list) take the work executor first (a `webcpp::asio::thread_pool`'s): they check their guards on the caller's thread, run the work on the work executor and complete on the handler's associated executor, with webcpp::hash's @@ -334,9 +333,10 @@ inline constexpr bool is_p256_public_key_v 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); + (std::is_same_v && is_p256_public_key_v); /** * Stops the build with the one reason the key pair `Keypair` does not sign `Input` with `Scheme`: @@ -352,8 +352,9 @@ 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 or crypto::eddsa_prehashed, a " - "P-256 key pair with crypto::ecdsa_sha256."); + "an Ed25519 key pair signs with crypto::signing_schemes::eddsa or " + "crypto::signing_schemes::eddsa_prehashed, a " + "P-256 key pair with crypto::signing_schemes::ecdsa_sha256."); } else { check_input::type>(); } @@ -414,7 +415,7 @@ constexpr void refuse_async_agree_keypair() noexcept { */ template inline constexpr bool ed25519ph_on_browser_v = - is_ed25519_keypair_v && std::is_same_v && + is_ed25519_keypair_v && std::is_same_v && asynchronous_backend_v::type>; /** @@ -569,18 +570,20 @@ auto initiate_verify_ed25519(Executor const& completion_executor, Signature cons 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 or " - "crypto::eddsa_prehashed."); + if constexpr (!std::is_same_v && + !std::is_same_v) { + static_assert( + refused_v, + "webcpp::crypto: an Ed25519 public key verifies crypto::signing_schemes::eddsa or " + "crypto::signing_schemes::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( - completion_executor, eddsa, signature_value, kept_input(signing_input), public_key, - verification_policy, std::forward(completion_token)); + completion_executor, signing_schemes::eddsa, signature_value, kept_input(signing_input), + public_key, verification_policy, std::forward(completion_token)); } else { return complete_by_post( completion_executor, completion_token, @@ -927,12 +930,13 @@ auto async_open(Executor const& completion_executor, Box& keyed_box, * 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). + * Ed25519 signs the message with `crypto::signing_schemes::eddsa`, or with + * `crypto::signing_schemes::eddsa_prehashed` (Ed25519ph) + * `crypto::signing_schemes::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::signing_schemes::ecdsa_sha256` the message, which it hashes with SHA-256, as WebCrypto's + * ECDSA with SHA-256 signs, or `crypto::signing_schemes::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 @@ -943,18 +947,19 @@ auto async_open(Executor const& completion_executor, Box& keyed_box, * `curves::p256::basic_keypair`; 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` or `crypto::eddsa_prehashed_t` for Ed25519, - * `crypto::ecdsa_sha256_t` for P-256. + * @tparam Scheme `crypto::signing_schemes::eddsa_t` or `crypto::signing_schemes::eddsa_prehashed_t` + * for Ed25519, `crypto::signing_schemes::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>`; under `crypto::eddsa_prehashed`, - * `crypto::prehashed<64>` alone. + * empty included, or for P-256 `crypto::signing_schemes::prehashed<32>`; under + * `crypto::signing_schemes::eddsa_prehashed`, `crypto::signing_schemes::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 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 signing_scheme `crypto::signing_schemes::eddsa`, + * `crypto::signing_schemes::eddsa_prehashed` or `crypto::signing_schemes::ecdsa_sha256`. + * @param signing_input The message, or for P-256 `crypto::signing_schemes::prehashed{digest}`, its + * 32-byte SHA-256 digest, or under `crypto::signing_schemes::eddsa_prehashed` + * `crypto::signing_schemes::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 @@ -1005,12 +1010,12 @@ void async_sign([[maybe_unused]] Executor const& completion_executor, /** * 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`. + * `crypto::verify(signing_schemes::eddsa, ...)` 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` among them, and which runs the - * key's `verify`, with the same work. + * arguments other than `public_key`, the scheme `crypto::signing_schemes::eddsa` among them, and + * which runs the key's `verify`, with the same work. * * 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 @@ -1023,7 +1028,7 @@ void async_sign([[maybe_unused]] Executor const& completion_executor, * @tparam Input A message, bytes that convert to `std::span`. * @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 signing_scheme `crypto::signing_schemes::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. @@ -1034,7 +1039,7 @@ void async_sign([[maybe_unused]] Executor const& completion_executor, */ template , class Executor, class Signature, class Input, class CompletionToken> -auto async_verify(Executor const& completion_executor, eddsa_t signing_scheme, +auto async_verify(Executor const& completion_executor, signing_schemes::eddsa_t signing_scheme, Signature const& signature_value, Input const& message_bytes, curves::ed25519::public_key const& public_key, CompletionToken&& completion_token) { @@ -1057,7 +1062,7 @@ auto async_verify(Executor const& completion_executor, eddsa_t signing_scheme, * @tparam Input A message, bytes that convert to `std::span`. * @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 signing_scheme `crypto::signing_schemes::eddsa`. * @param signature_value The signature. * @param message_bytes The signed bytes. * @param public_key The signer's public key. @@ -1069,7 +1074,7 @@ auto async_verify(Executor const& completion_executor, eddsa_t signing_scheme, */ template , class Executor, class Signature, class Input, class CompletionToken> -auto async_verify(Executor const& completion_executor, eddsa_t signing_scheme, +auto async_verify(Executor const& completion_executor, signing_schemes::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, @@ -1082,13 +1087,13 @@ auto async_verify(Executor const& completion_executor, eddsa_t signing_scheme, /** * 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`. + * strictly: `crypto::verify` of `crypto::signing_schemes::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). + * arguments other than `public_key`, the scheme `crypto::signing_schemes::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 @@ -1098,13 +1103,14 @@ auto async_verify(Executor const& completion_executor, eddsa_t signing_scheme, * @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 Input `crypto::signing_schemes::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 signing_scheme `crypto::signing_schemes::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 digest_input `crypto::signing_schemes::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; @@ -1113,7 +1119,8 @@ auto async_verify(Executor const& completion_executor, eddsa_t signing_scheme, */ template , class Executor, class Signature, class Input, class CompletionToken> -auto async_verify(Executor const& completion_executor, eddsa_prehashed_t signing_scheme, +auto async_verify(Executor const& completion_executor, + signing_schemes::eddsa_prehashed_t signing_scheme, Signature const& signature_value, Input const& digest_input, curves::ed25519::public_key const& public_key, CompletionToken&& completion_token) { @@ -1137,12 +1144,13 @@ auto async_verify(Executor const& completion_executor, eddsa_prehashed_t signing * @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 Input `crypto::signing_schemes::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 signing_scheme `crypto::signing_schemes::eddsa_prehashed`. * @param signature_value The signature. - * @param digest_input `crypto::prehashed{digest}`, the 64 bytes of the message's SHA-512. + * @param digest_input `crypto::signing_schemes::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. @@ -1152,7 +1160,8 @@ auto async_verify(Executor const& completion_executor, eddsa_prehashed_t signing */ template , class Executor, class Signature, class Input, class CompletionToken> -auto async_verify(Executor const& completion_executor, eddsa_prehashed_t signing_scheme, +auto async_verify(Executor const& completion_executor, + signing_schemes::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, @@ -1169,14 +1178,14 @@ auto async_verify(Executor const& completion_executor, eddsa_prehashed_t signing /** * 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. + * `crypto::verify(signing_schemes::ecdsa_sha256, ...)` 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::signing_schemes::prehashed{digest}` gives its digest. * * 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. + * other than `public_key`, the scheme `crypto::signing_schemes::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 * signature and the input are checked as `crypto::can_verify` checks them, before anything else: @@ -1189,23 +1198,24 @@ auto async_verify(Executor const& completion_executor, eddsa_prehashed_t signing * @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>`. + * empty included, or `crypto::signing_schemes::prehashed<32>`. * @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 signing_scheme `crypto::signing_schemes::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 signing_input The signed message, or `crypto::signing_schemes::prehashed{digest}`, its + * 32-byte SHA-256 digest. * @param public_key The signer's public key, validated when it was made. * @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& completion_executor, ecdsa_sha256_t signing_scheme, - Signature const& signature_value, Input const& signing_input, +auto async_verify(Executor const& completion_executor, + signing_schemes::ecdsa_sha256_t signing_scheme, Signature const& signature_value, + Input const& signing_input, curves::p256::basic_public_key const& public_key, CompletionToken&& completion_token) { secure::timing_guard const timing_scope; @@ -1244,11 +1254,13 @@ void async_verify([[maybe_unused]] Executor const& completion_executor, [[maybe_unused]] Input const& signing_input, [[maybe_unused]] PublicKey const& public_key, [[maybe_unused]] CompletionToken&& completion_token) { - static_assert(detail::refused_v, - "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."); + static_assert( + detail::refused_v, + "webcpp::crypto: async_verify takes crypto::signing_schemes::eddsa or " + "crypto::signing_schemes::eddsa_prehashed " + "with a curves::ed25519::public_key or crypto::signing_schemes::ecdsa_sha256 with a " + "curves::p256::basic_public_key, the algorithms WebCrypto has: call " + "crypto::verify for the others."); } /** @@ -1558,7 +1570,7 @@ auto curves::ed25519::public_key::async_verify(Executor const& completion_execut Input const& message_input, CompletionToken&& completion_token) const { secure::timing_guard const timing_scope; - if constexpr (std::is_same_v && + if constexpr (std::is_same_v && detail::asynchronous_backend_v) { detail::refuse_ed25519ph_on_asynchronous_backend(); } else { @@ -1576,7 +1588,7 @@ auto curves::ed25519::public_key::async_verify(Executor const& completion_execut Input const& message_input, strict_t verify_policy, CompletionToken&& completion_token) const { secure::timing_guard const timing_scope; - if constexpr (std::is_same_v && + if constexpr (std::is_same_v && detail::asynchronous_backend_v) { detail::refuse_ed25519ph_on_asynchronous_backend(); } else { @@ -1673,23 +1685,26 @@ auto curves::p256::basic_public_key::async_verify( Signature const& signature_value, Input const& signing_input, CompletionToken&& completion_token) const { secure::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 (!detail::check_signature()) { + if constexpr (!std::is_same_v) { + static_assert( + detail::refused_v, + "webcpp::crypto: a P-256 public key verifies crypto::signing_schemes::ecdsa_sha256."); + } 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::input_valid_v) { + detail::check_input(); } else if constexpr (detail::asynchronous_backend_v) { return detail::async_engine::verify( - completion_executor, ecdsa_sha256, signature_value, detail::kept_input(signing_input), - *this, std::forward(completion_token)); + completion_executor, signing_schemes::ecdsa_sha256, signature_value, + detail::kept_input(signing_input), *this, + std::forward(completion_token)); } else { return detail::complete_by_post( completion_executor, completion_token, [this, signature_value, kept = detail::kept_input(signing_input)]() noexcept -> boost::system::result { - return verify(ecdsa_sha256, signature_value, kept); + return verify(signing_schemes::ecdsa_sha256, signature_value, kept); }); } } diff --git a/include/webcpp/crypto/backends/secp256k1.hpp b/include/webcpp/crypto/backends/secp256k1.hpp index 0949dc8a..2a91a0ea 100644 --- a/include/webcpp/crypto/backends/secp256k1.hpp +++ b/include/webcpp/crypto/backends/secp256k1.hpp @@ -7,11 +7,12 @@ /** The backend libsecp256k1: its v0.8.0, built from its sources by `/third_party//secp256k1`, every module on. It serves `curves::secp256k1::keypair` and its `sign`, `crypto::verify` of - `crypto::ecdsa_sha256` and `crypto::schnorr`, `recover`, the parsed `public_key`, the DER and - low-S functions, the x-only tweak, the tweaks and combination of `curves/secp256k1/tweak.hpp`, - the SPKI and PKCS#8 of `curves/secp256k1/formats.hpp`, the ElligatorSwift of - `curves/secp256k1/ellswift.hpp`, the MuSig2 of `curves/secp256k1/musig.hpp` and the silent - payments of `curves/secp256k1/silent_payments.hpp`, and its whole C API stays reachable through + `crypto::signing_schemes::ecdsa_sha256` and `crypto::signing_schemes::schnorr`, `recover`, the + parsed `public_key`, the DER and low-S functions, the x-only tweak, the tweaks and combination of + `curves/secp256k1/tweak.hpp`, the SPKI and PKCS#8 of `curves/secp256k1/formats.hpp`, the + ElligatorSwift of `curves/secp256k1/ellswift.hpp`, the MuSig2 of `curves/secp256k1/musig.hpp` and + the silent payments of `curves/secp256k1/silent_payments.hpp`, and its whole C API stays reachable + through ``. @see "secp256k1", in the guide. diff --git a/include/webcpp/crypto/config.hpp b/include/webcpp/crypto/config.hpp index 93842d5b..0004ffe5 100644 --- a/include/webcpp/crypto/config.hpp +++ b/include/webcpp/crypto/config.hpp @@ -190,6 +190,31 @@ #endif // clang-format on +namespace webcpp::crypto { + +/** + The formats of keys and signatures: the tags that name one, `formats::raw`, `formats::spki` and + the others, and the lists that say which a type has. Each curve's header and + `` fill it; a format is named in it and nowhere else. +*/ +namespace formats {} + +/** + The signature schemes: the tags that name one, `signing_schemes::eddsa`, `eddsa_prehashed`, + `ecdsa_sha256`, `ecdsa_sha256_recoverable`, `ecdsa_keccak256_recoverable` and `schnorr`, and + the marker of a digest, `signing_schemes::prehashed`. They are in this namespace and in `crypto` + itself under no name. +*/ +namespace signing_schemes {} + +/** + The verification policies, which `verify` takes to say what a signature must be besides valid: + the names of the policies are declared in it. +*/ +namespace verification_policies {} + +} // namespace webcpp::crypto + // The backends' tags. webcpp::hash has tags of the same names in webcpp::hash::backends, and a // program that uses both libraries (signing.hpp's SHA-256 is webcpp::hash's) sees both: // clang-tidy's bugprone-forward-declaration-namespace then takes a tag this translation unit does diff --git a/include/webcpp/crypto/curves/ed25519.hpp b/include/webcpp/crypto/curves/ed25519.hpp index a2506793..62593405 100644 --- a/include/webcpp/crypto/curves/ed25519.hpp +++ b/include/webcpp/crypto/curves/ed25519.hpp @@ -7,11 +7,12 @@ /** 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, `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. + bytes, `key.sign(crypto::signing_schemes::eddsa, message)`, and their verification, + `crypto::verify(crypto::signing_schemes::eddsa, signature, message, public_key)`, strict on + libsodium; Ed25519ph, the signature of a message's SHA-512, under the scheme + `crypto::signing_schemes::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 @@ -111,9 +112,9 @@ 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. + * An Ed25519 signature (RFC 8032), 64 bytes, R then S: what `sign(signing_schemes::eddsa, ...)`, + * `sign(signing_schemes::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. @@ -145,8 +146,8 @@ template 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) { + check_input(); + if constexpr (input_valid_v) { return ed25519_engine::verify( key_bytes, message_bytes(message_input), signature_bytes); } else { @@ -173,8 +174,8 @@ template 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) { + check_input(); + if constexpr (input_valid_v) { return ed25519ph_engine::verify_digest( key_bytes, digest_input.digest, signature_bytes); } else { @@ -189,7 +190,7 @@ 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. + * `crypto::verify(crypto::signing_schemes::eddsa, ...)` takes. * * `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 @@ -228,20 +229,20 @@ 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_value, message_input, key, verify_policy)`, of which - * it is the member form, with the same work, results and refusals. + * `crypto::verify(signing_schemes::eddsa, ...)`, of which it is the member form, with the same + * work, results and refusals. * - * Ed25519ph's is the overload of `crypto::eddsa_prehashed`. + * Ed25519ph's is the overload of `crypto::signing_schemes::eddsa_prehashed`. * * @tparam Backend The backend; by default the family's. - * @tparam Scheme `crypto::eddsa_t`; another scheme stops the build. + * @tparam Scheme `crypto::signing_schemes::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. + * `crypto::signing_schemes::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 signing_scheme `crypto::signing_schemes::eddsa`. * @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. @@ -256,16 +257,19 @@ class public_key { Input const& message_input, [[maybe_unused]] Policy verify_policy = Policy{}) const noexcept { secure::timing_guard const timing_scope; - static_assert(std::is_same_v, - "webcpp::crypto: an Ed25519 public key verifies crypto::eddsa or " - "crypto::eddsa_prehashed."); + static_assert( + std::is_same_v, + "webcpp::crypto: an Ed25519 public key verifies crypto::signing_schemes::eddsa or " + "crypto::signing_schemes::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) { + if constexpr (std::is_same_v && + !detail::asynchronous_backend_v) { return detail::ed25519_verify( - detail::checked_signature_bytes(signature_value), message_input, - bytes_); + 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; @@ -274,9 +278,9 @@ class public_key { /** * 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. + * under a verification policy, strictly as `crypto::signing_schemes::eddsa`'s: + * `crypto::verify(signing_schemes::eddsa_prehashed, ...)`, 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). @@ -284,14 +288,15 @@ class public_key { * @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 Input `crypto::signing_schemes::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 signing_scheme `crypto::signing_schemes::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 digest_input `crypto::signing_schemes::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. @@ -299,8 +304,8 @@ class public_key { 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]] signing_schemes::eddsa_prehashed_t signing_scheme, + Signature const& signature_value, Input const& digest_input, [[maybe_unused]] Policy verify_policy = Policy{}) const noexcept { secure::timing_guard const timing_scope; if constexpr (detail::asynchronous_backend_v) { @@ -308,7 +313,8 @@ class public_key { } if constexpr (!detail::asynchronous_backend_v) { return detail::ed25519ph_verify( - detail::checked_signature_bytes(signature_value), + detail::checked_signature_bytes( + signature_value), digest_input, bytes_); } else { // Never compiled into a program: the assertion above stopped the build. @@ -331,16 +337,18 @@ 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`, or `crypto::eddsa_prehashed_t` on a native backend; - * another scheme stops the build. + * @tparam Scheme `crypto::signing_schemes::eddsa_t`, or + * `crypto::signing_schemes::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. + * `crypto::signing_schemes::eddsa`; `crypto::signing_schemes::prehashed<64>` under + * `crypto::signing_schemes::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` or `crypto::eddsa_prehashed`. + * @param signing_scheme `crypto::signing_schemes::eddsa` or + * `crypto::signing_schemes::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. @@ -369,15 +377,18 @@ 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`, or `crypto::eddsa_prehashed_t` on a native backend; - * another scheme stops the build. + * @tparam Scheme `crypto::signing_schemes::eddsa_t`, or + * `crypto::signing_schemes::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`. + * `crypto::signing_schemes::eddsa`; `crypto::signing_schemes::prehashed<64>` under + * `crypto::signing_schemes::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` or `crypto::eddsa_prehashed`. + * @param signing_scheme `crypto::signing_schemes::eddsa` or + * `crypto::signing_schemes::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. @@ -635,23 +646,25 @@ class basic_keypair { } /** - * 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). + * Signs with Ed25519 (RFC 8032): under `crypto::signing_schemes::eddsa`, the pure form, a + * message, the message itself, of any length, empty included, with no digest taken; under + * `crypto::signing_schemes::eddsa_prehashed`, Ed25519ph, the 64 bytes of a message's SHA-512, + * `crypto::signing_schemes::prehashed{digest}` (a message given in pieces is @ref + * prehashed_signer's). * * 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). + * `crypto::signing_schemes::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 + * @tparam Scheme `crypto::signing_schemes::eddsa_t` or + * `crypto::signing_schemes::eddsa_prehashed_t`; another scheme stops the build. + * @tparam Input Under `crypto::signing_schemes::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`. + * `crypto::signing_schemes::eddsa_prehashed`, `crypto::signing_schemes::prehashed<64>`, a + * message or a digest of another size stopping the build. + * @param signing_scheme `crypto::signing_schemes::eddsa` or + * `crypto::signing_schemes::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`. @@ -660,25 +673,25 @@ class basic_keypair { [[nodiscard]] boost::system::result> sign( [[maybe_unused]] Scheme signing_scheme, Input const& signing_input) const noexcept { secure::timing_guard const timing_scope; - if constexpr (std::is_same_v && + 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; + 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."); + "webcpp::crypto: an Ed25519 key signs with crypto::signing_schemes::eddsa or " + "crypto::signing_schemes::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) { // Never compiled into a program: check_input stopped the build. return error::backend_failure; - } else if constexpr (std::is_same_v) { + } else if constexpr (std::is_same_v) { return signed_digest(signing_input.digest); } else { return signed_message(detail::message_bytes(signing_input)); @@ -694,8 +707,8 @@ class basic_keypair { * 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). + * `crypto::signing_schemes::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. @@ -705,14 +718,15 @@ 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` 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 Scheme `crypto::signing_schemes::eddsa_t` or + * `crypto::signing_schemes::eddsa_prehashed_t`; another scheme stops the build. + * @tparam Input Under `crypto::signing_schemes::eddsa`, a message, bytes that convert to + * `std::span`; under `crypto::signing_schemes::eddsa_prehashed`, + * `crypto::signing_schemes::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` or `crypto::eddsa_prehashed`. + * @param signing_scheme `crypto::signing_schemes::eddsa` or + * `crypto::signing_schemes::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, curves::ed25519::signature)`; on an error the signature of @@ -796,15 +810,15 @@ using keypair = basic_keypair<>; /** * 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. + * given in pieces: the streaming form of the scheme `crypto::signing_schemes::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, a `curves::ed25519::signature`, is not `crypto::eddsa`'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::signing_schemes::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`). @@ -902,8 +916,9 @@ class prehashed_signer { * * @param key_pair The key pair, of the same backend. * @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`. + * Ed25519ph verifies: this signer or `crypto::signing_schemes::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<::webcpp::crypto::curves::ed25519::signature> sign( basic_keypair const& key_pair) noexcept { @@ -977,10 +992,10 @@ namespace webcpp::crypto { * @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. + * `crypto::signing_schemes::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 signing_scheme `crypto::signing_schemes::eddsa`. * @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. @@ -992,7 +1007,7 @@ namespace webcpp::crypto { template , class Signature, class Input, class Policy = curves::ed25519::strict_t> [[nodiscard]] boost::system::result verify( - [[maybe_unused]] eddsa_t signing_scheme, Signature const& signature_value, + [[maybe_unused]] signing_schemes::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 { secure::timing_guard const timing_scope; @@ -1002,7 +1017,8 @@ template , class Signature, if constexpr (!detail::asynchronous_backend_v) { auto const key_bytes = public_key.bytes(); return detail::ed25519_verify( - detail::checked_signature_bytes(signature_value), + detail::checked_signature_bytes( + signature_value), message_input, key_bytes); } else { // Never compiled into a program: the assertion above stopped the build. @@ -1012,7 +1028,8 @@ template , class 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. + * as `crypto::signing_schemes::prehashed{digest}`) under a verification policy, strictly as + * `crypto::signing_schemes::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 @@ -1021,14 +1038,15 @@ template , class Signature, * * @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 Input `crypto::signing_schemes::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 signing_scheme `crypto::signing_schemes::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 digest_input `crypto::signing_schemes::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 @@ -1037,8 +1055,9 @@ template , class Signature, 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]] signing_schemes::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 { secure::timing_guard const timing_scope; if constexpr (detail::asynchronous_backend_v) { @@ -1047,8 +1066,8 @@ template , class Signature, if constexpr (!detail::asynchronous_backend_v) { auto const key_bytes = public_key.bytes(); return detail::ed25519ph_verify( - detail::checked_signature_bytes( - signature_value), + detail::checked_signature_bytes(signature_value), digest_input, key_bytes); } else { // Never compiled into a program: the assertion above stopped the build. @@ -1087,7 +1106,8 @@ namespace webcpp::crypto::detail { * @tparam Backend The key pair's backend. */ template -inline constexpr bool signs_with_v, eddsa_t> = true; +inline constexpr bool + signs_with_v, signing_schemes::eddsa_t> = true; /** * An Ed25519 key pair signs with `eddsa_prehashed`, Ed25519ph. @@ -1095,8 +1115,9 @@ inline constexpr bool signs_with_v, edds * @tparam Backend The key pair's backend. */ template -inline constexpr bool signs_with_v, eddsa_prehashed_t> = - true; +inline constexpr bool + signs_with_v, signing_schemes::eddsa_prehashed_t> = + true; /** * An Ed25519 key pair's backend. @@ -1114,11 +1135,12 @@ struct key_backend> { * primary `key_backend`'s: the key holds no backend, `crypto::verify` names one. */ template <> -inline constexpr bool verifies_with_v = true; +inline constexpr bool verifies_with_v = true; /** An Ed25519 public key verifies `eddsa_prehashed`, Ed25519ph. */ template <> -inline constexpr bool verifies_with_v = true; +inline constexpr bool + verifies_with_v = true; /** * An Ed25519 key pair's signature under `eddsa`, `curves::ed25519::signature`. @@ -1126,7 +1148,7 @@ inline constexpr bool verifies_with_v -struct signature_of, eddsa_t> { +struct signature_of, signing_schemes::eddsa_t> { /** The signature type. */ using type = curves::ed25519::signature; }; @@ -1138,21 +1160,21 @@ struct signature_of, eddsa_t> { * @tparam Backend The key's backend. */ template -struct signature_of, eddsa_prehashed_t> { +struct signature_of, signing_schemes::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 { +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 { +struct signature_of { /** The signature type. */ using type = curves::ed25519::signature; }; @@ -1162,14 +1184,15 @@ struct signature_of { * steps aside. */ template <> -inline constexpr bool has_verifier_v = true; +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; +inline constexpr bool + has_verifier_v = true; /** * Ed25519's engine on a backend whose header does not specialise it: the family's refusal, diff --git a/include/webcpp/crypto/curves/p256.hpp b/include/webcpp/crypto/curves/p256.hpp index 3da1b771..181cad9f 100644 --- a/include/webcpp/crypto/curves/p256.hpp +++ b/include/webcpp/crypto/curves/p256.hpp @@ -8,12 +8,12 @@ P-256, NIST's curve of FIPS 186-5 (secp256r1): a key pair made from its 32-byte scalar, which `secret()` gives back, or drawn from the system's generator, and a public key validated once, as 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}`, 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. + ECDSA over SHA-256 with RFC 6979's nonce, `key.sign(crypto::signing_schemes::ecdsa_sha256, input)` + and `crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, input, public_key)`, the + input a message, hashed inside, or `crypto::signing_schemes::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; a program that uses the family without linking it stops where it calls it, with the Jamfile @@ -78,7 +78,8 @@ struct p256_ecdsa_signature_tag { * `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. + * @tparam Input A message or `crypto::signing_schemes::prehashed<32>`; anything else stops the + * build. * @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. @@ -89,8 +90,8 @@ template std::span signature_bytes, Input const& signing_input, std::span point_bytes) noexcept { - check_input(); - if constexpr (input_valid_v) { + check_input(); + if constexpr (input_valid_v) { using engine = p_curve_engine; std::array digest_bytes{}; if constexpr (is_prehashed_v) { @@ -116,8 +117,8 @@ 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. + * A P-256 ECDSA signature, 64 bytes, r then s: what `sign(signing_schemes::ecdsa_sha256, ...)` + * gives and `crypto::verify(signing_schemes::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 @@ -199,22 +200,22 @@ class basic_public_key { /** * 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. + * `crypto::verify(crypto::signing_schemes::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 Scheme `crypto::signing_schemes::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`. + * empty included, or `crypto::signing_schemes::prehashed<32>`; anything else stops the build. + * @param signing_scheme `crypto::signing_schemes::ecdsa_sha256`. * @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. + * `crypto::signing_schemes::prehashed{digest}`, its 32-byte SHA-256 digest. * @return Nothing; `invalid_signature` for an r or an s that is 0 or not below n, and a * signature that does not verify. */ @@ -223,15 +224,17 @@ class basic_public_key { Signature const& signature_value, Input const& signing_input) const noexcept { secure::timing_guard const timing_scope; - static_assert(std::is_same_v, - "webcpp::crypto: a P-256 public key verifies crypto::ecdsa_sha256."); + static_assert( + std::is_same_v, + "webcpp::crypto: a P-256 public key verifies crypto::signing_schemes::ecdsa_sha256."); static_assert(!detail::asynchronous_backend_v, "webcpp::crypto: verify on this backend completes asynchronously: call " "async_verify."); - if constexpr (std::is_same_v && + if constexpr (std::is_same_v && !detail::asynchronous_backend_v) { return detail::p256_verify( - detail::checked_signature_bytes(signature_value), + detail::checked_signature_bytes( + signature_value), signing_input, point_); } else { // Never compiled into a program: an assertion above stopped the build. @@ -252,17 +255,17 @@ class basic_public_key { * "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::ecdsa_sha256_t`; another scheme stops the build. + * @tparam Scheme `crypto::signing_schemes::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. + * empty included, or `crypto::signing_schemes::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 signing_scheme `crypto::signing_schemes::ecdsa_sha256`. * @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 signing_input The signed message, or `crypto::signing_schemes::prehashed{digest}`, its + * 32-byte SHA-256 digest. * @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. @@ -508,13 +511,13 @@ class basic_keypair { * 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. * - * @tparam Scheme `crypto::ecdsa_sha256_t`; another scheme stops the build. + * @tparam Scheme `crypto::signing_schemes::ecdsa_sha256_t`; another scheme 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`. + * empty included, or `crypto::signing_schemes::prehashed<32>`; anything else stops the build. + * @param signing_scheme `crypto::signing_schemes::ecdsa_sha256`. * @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. + * with SHA-256 hashes it; or `crypto::signing_schemes::prehashed{digest}`, its 32-byte SHA-256 + * digest, signed as given. * @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. */ @@ -522,12 +525,13 @@ class basic_keypair { [[nodiscard]] boost::system::result> sign( [[maybe_unused]] Scheme signing_scheme, Input const& signing_input) const noexcept { secure::timing_guard const timing_scope; - static_assert(std::is_same_v, - "webcpp::crypto: a P-256 key signs with crypto::ecdsa_sha256."); + static_assert( + std::is_same_v, + "webcpp::crypto: a P-256 key signs with crypto::signing_schemes::ecdsa_sha256."); static_assert(!detail::asynchronous_backend_v, "webcpp::crypto: sign on this backend completes asynchronously: call " "async_sign."); - if constexpr (std::is_same_v && + if constexpr (std::is_same_v && !detail::asynchronous_backend_v) { detail::check_input(); if constexpr (detail::input_valid_v) { @@ -559,13 +563,14 @@ 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::ecdsa_sha256_t`; another scheme stops the build. + * @tparam Scheme `crypto::signing_schemes::ecdsa_sha256_t`; another scheme 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. + * empty included, or `crypto::signing_schemes::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 signing_input The message, hashed with SHA-256, or `crypto::prehashed{digest}`. + * @param signing_scheme `crypto::signing_schemes::ecdsa_sha256`. + * @param signing_input The message, hashed with SHA-256, or + * `crypto::signing_schemes::prehashed{digest}`. * @param completion_token The completion token, of signature * `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`). @@ -786,13 +791,13 @@ namespace webcpp::crypto { * @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`. + * empty included, or `crypto::signing_schemes::prehashed<32>`; anything else stops the build. + * @param signing_scheme `crypto::signing_schemes::ecdsa_sha256`. * @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. + * `crypto::signing_schemes::prehashed{digest}`, its 32-byte SHA-256 digest. * @param public_key The signer's public key. * @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 @@ -801,8 +806,8 @@ namespace webcpp::crypto { */ template [[nodiscard]] boost::system::result verify( - [[maybe_unused]] ecdsa_sha256_t signing_scheme, Signature const& signature_value, - Input const& signing_input, + [[maybe_unused]] signing_schemes::ecdsa_sha256_t signing_scheme, + Signature const& signature_value, Input const& signing_input, curves::p256::basic_public_key const& public_key) noexcept { secure::timing_guard const timing_scope; static_assert(!detail::asynchronous_backend_v, @@ -810,8 +815,8 @@ template "async_verify."); if constexpr (!detail::asynchronous_backend_v) { return detail::p256_verify( - detail::checked_signature_bytes( - signature_value), + 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. @@ -829,7 +834,8 @@ namespace webcpp::crypto::detail { * @tparam Backend The key pair's backend. */ template -inline constexpr bool signs_with_v, ecdsa_sha256_t> = true; +inline constexpr bool + signs_with_v, signing_schemes::ecdsa_sha256_t> = true; /** * A P-256 public key verifies ECDSA over SHA-256. @@ -837,8 +843,9 @@ inline constexpr bool signs_with_v, ecdsa_s * @tparam Backend The public key's backend. */ template -inline constexpr bool verifies_with_v, ecdsa_sha256_t> = - true; +inline constexpr bool + verifies_with_v, signing_schemes::ecdsa_sha256_t> = + true; /** * A P-256 key pair's signature under ECDSA over SHA-256, `curves::p256::ecdsa_signature`. @@ -846,7 +853,7 @@ inline constexpr bool verifies_with_v, e * @tparam Backend The key's backend. */ template -struct signature_of, ecdsa_sha256_t> { +struct signature_of, signing_schemes::ecdsa_sha256_t> { /** The signature type. */ using type = curves::p256::ecdsa_signature; }; @@ -857,7 +864,7 @@ struct signature_of, ecdsa_sha256_t> { * @tparam Backend The key's backend. */ template -struct signature_of, ecdsa_sha256_t> { +struct signature_of, signing_schemes::ecdsa_sha256_t> { /** The signature type. */ using type = curves::p256::ecdsa_signature; }; @@ -891,8 +898,8 @@ struct key_backend> { * @tparam Backend The public key's backend. */ template -inline constexpr bool has_verifier_v> = - true; +inline constexpr bool + has_verifier_v> = true; /** * P-256's engine on a backend whose header does not specialise it: the family's refusal, which diff --git a/include/webcpp/crypto/curves/secp256k1.hpp b/include/webcpp/crypto/curves/secp256k1.hpp index b230a0b6..46924869 100644 --- a/include/webcpp/crypto/curves/secp256k1.hpp +++ b/include/webcpp/crypto/curves/secp256k1.hpp @@ -8,10 +8,11 @@ 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::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`, `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, + `key.sign(scheme, input)` with `crypto::signing_schemes::ecdsa_sha256` (hedged too), + `crypto::signing_schemes::ecdsa_sha256_recoverable`, + `crypto::signing_schemes::ecdsa_keccak256_recoverable` (Ethereum's, over Keccak-256: a message + needs `/third_party//xkcp`) and `crypto::signing_schemes::schnorr` (BIP340), the input a message + or, for ECDSA, `crypto::signing_schemes::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 @@ -40,7 +41,7 @@ #include #ifdef WEBCPP_HASH_HAS_XKCP -#include // crypto::ecdsa_keccak256_recoverable's hash of a message +#include // crypto::signing_schemes::ecdsa_keccak256_recoverable's hash of a message #include #endif @@ -443,9 +444,10 @@ template 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::crypto: crypto::signing_schemes::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}."); + "program's Jamfile, or sign crypto::signing_schemes::prehashed{digest}."); #endif } return digest_bytes; @@ -567,8 +569,8 @@ template [[nodiscard]] boost::system::result secp256k1_verify_schnorr_key( std::span signature_bytes, Input const& message_input, secp256k1_pubkey const& point_value) noexcept { - check_input(); - if constexpr (input_valid_v) { + check_input(); + if constexpr (input_valid_v) { auto const bytes_of_message = message_bytes(message_input); read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); secp256k1_selftest(); @@ -586,7 +588,8 @@ template * of `ecdsa_sha256`, which hold the guard. * * @tparam Backend The backend, libsecp256k1. - * @tparam Input A message or `crypto::prehashed<32>`; anything else stops the build. + * @tparam Input A message or `crypto::signing_schemes::prehashed<32>`; anything else stops the + * build. * @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. @@ -597,8 +600,8 @@ template [[nodiscard]] boost::system::result secp256k1_verify_ecdsa( std::span signature_bytes, Input const& signing_input, secp256k1_pubkey const& point_value) noexcept { - check_input(); - if constexpr (input_valid_v) { + check_input(); + if constexpr (input_valid_v) { auto const digest_bytes = secp256k1_digest(signing_input); read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); secp256k1_selftest(); @@ -621,8 +624,9 @@ 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. + * A secp256k1 ECDSA signature, 64 bytes, r then s: what + * `sign(signing_schemes::ecdsa_sha256, ...)` gives and + * `crypto::verify(signing_schemes::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 @@ -632,8 +636,9 @@ using ecdsa_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. + * A BIP340 Schnorr signature, 64 bytes, R's x then s: what `sign(signing_schemes::schnorr, ...)` + * gives and `crypto::verify(signing_schemes::schnorr, ...)` takes. * * `from_bytes` checks the size alone. */ @@ -751,8 +756,9 @@ class public_key { } /** - * 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. + * The key's BIP340 x-only form, its x coordinate, which + * `crypto::verify(crypto::signing_schemes::schnorr, ...)` takes as the key itself does; the + * parity of y is dropped. * * @return 32 bytes. */ @@ -774,17 +780,19 @@ class public_key { * ECDSA's high S is refused, as libsecp256k1 refuses it; Schnorr reads the key's x-only form. * * @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 Scheme `crypto::signing_schemes::ecdsa_sha256_t` or + * `crypto::signing_schemes::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`. + * empty included; or, for ECDSA, `crypto::signing_schemes::prehashed<32>`; anything else stops + * the build. + * @param signing_scheme `crypto::signing_schemes::ecdsa_sha256` or + * `crypto::signing_schemes::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. + * `crypto::signing_schemes::prehashed{digest}`; for Schnorr, the message itself. * @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. */ @@ -796,21 +804,26 @@ class public_key { secure::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 or a " - "crypto::ecdsa_keccak256_recoverable signature gives its key to " - "curves::secp256k1::recover."); + 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::signing_schemes::ecdsa_sha256 " + "or " + "crypto::signing_schemes::schnorr; a crypto::signing_schemes::ecdsa_sha256_recoverable " + "or a " + "crypto::signing_schemes::ecdsa_keccak256_recoverable signature gives its key to " + "curves::secp256k1::recover."); if constexpr (is_ecdsa) { return webcpp::crypto::detail::secp256k1_verify_ecdsa( - webcpp::crypto::detail::checked_signature_bytes( + 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( - webcpp::crypto::detail::checked_signature_bytes( + webcpp::crypto::detail::checked_signature_bytes( signature_value), signing_input, point_value_); } else { @@ -1079,19 +1092,22 @@ class basic_keypair { * 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`, - * `crypto::ecdsa_keccak256_recoverable_t` or `crypto::schnorr_t`; another scheme stops the - * build. + * @tparam Scheme `crypto::signing_schemes::ecdsa_sha256_t`, + * `crypto::signing_schemes::ecdsa_sha256_recoverable_t`, + * `crypto::signing_schemes::ecdsa_keccak256_recoverable_t` or + * `crypto::signing_schemes::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 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`. + * empty included; or, for the three ECDSA schemes, `crypto::signing_schemes::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::signing_schemes::ecdsa_sha256`, + * `crypto::signing_schemes::ecdsa_sha256_recoverable`, + * `crypto::signing_schemes::ecdsa_keccak256_recoverable` or `crypto::signing_schemes::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. + * Keccak-256 for `ecdsa_keccak256_recoverable`, or + * `crypto::signing_schemes::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`; @@ -1104,25 +1120,29 @@ class basic_keypair { webcpp::crypto::detail::signature_of_t> sign([[maybe_unused]] Scheme signing_scheme, Input const& signing_input) const noexcept { secure::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, crypto::ecdsa_keccak256_recoverable or " - "crypto::schnorr."); + 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::signing_schemes::ecdsa_sha256, " + "crypto::signing_schemes::ecdsa_sha256_recoverable, " + "crypto::signing_schemes::ecdsa_keccak256_recoverable or " + "crypto::signing_schemes::schnorr."); if constexpr (has_scheme) { detail::check_input(); 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) { + } else if constexpr (std::is_same_v) { return signed_schnorr_drawn(detail::message_bytes(signing_input)); - } else if constexpr (std::is_same_v) { + } else if constexpr (std::is_same_v) { return signed_ecdsa(webcpp::crypto::detail::secp256k1_digest(signing_input), nullptr); - } else if constexpr (std::is_same_v) { + } else if constexpr (std::is_same_v) { return signed_recoverable(webcpp::crypto::detail::secp256k1_digest(signing_input)); } else { return signed_recoverable( @@ -1140,20 +1160,20 @@ class basic_keypair { * signing does not repeat on the next; low S. * * @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`. + * `crypto::signing_schemes::prehashed<32>`; anything else stops the build. + * @param signing_scheme `crypto::signing_schemes::ecdsa_sha256`. * @param signing_input The message, hashed with SHA-256 inside the call, or - * `crypto::prehashed{digest}`, a 32-byte digest signed as given. + * `crypto::signing_schemes::prehashed{digest}`, a 32-byte digest signed as given. * @param extra_entropy 32 bytes from crypto's random device, new for each signature. * @return The signature, r then s; `invalid_state` moved from; `backend_failure`. */ template [[nodiscard]] boost::system::result sign( - [[maybe_unused]] ecdsa_sha256_t signing_scheme, Input const& signing_input, + [[maybe_unused]] signing_schemes::ecdsa_sha256_t signing_scheme, Input const& signing_input, std::span extra_entropy) const noexcept { secure::timing_guard const timing_scope; - detail::check_input(); - if constexpr (detail::input_valid_v) { + detail::check_input(); + if constexpr (detail::input_valid_v) { webcpp::crypto::detail::secp256k1_secret nonce_data; std::ranges::copy(extra_entropy, nonce_data.bytes.begin()); return signed_ecdsa(webcpp::crypto::detail::secp256k1_digest(signing_input), @@ -1169,19 +1189,19 @@ class basic_keypair { * vectors, and for a program that draws its own. * * @tparam Input A message, bytes that convert to `std::span`; a - * `crypto::prehashed` marker, or anything else, stops the build. - * @param signing_scheme `crypto::schnorr`. + * `crypto::signing_schemes::prehashed` marker, or anything else, stops the build. + * @param signing_scheme `crypto::signing_schemes::schnorr`. * @param message_input The message, of any length, signed as given. * @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( - [[maybe_unused]] schnorr_t signing_scheme, Input const& message_input, + [[maybe_unused]] signing_schemes::schnorr_t signing_scheme, Input const& message_input, std::span auxiliary_random_bytes) const noexcept { secure::timing_guard const timing_scope; - detail::check_input(); - if constexpr (detail::input_valid_v) { + detail::check_input(); + if constexpr (detail::input_valid_v) { return signed_schnorr(detail::message_bytes(message_input), auxiliary_random_bytes); } else { // Never compiled into a program: check_input stopped the build. @@ -1519,7 +1539,7 @@ namespace webcpp::crypto::curves::secp256k1 { /** * 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)`. + * SHA-256: the same inputs as `sign(signing_schemes::ecdsa_sha256_recoverable, ...)`. * * 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. @@ -1528,26 +1548,26 @@ namespace webcpp::crypto::curves::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`. + * `crypto::signing_schemes::prehashed<32>`; anything else stops the build. + * @param signing_scheme `crypto::signing_schemes::ecdsa_sha256_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 SHA-256 inside the call, or - * `crypto::prehashed{digest}`, the 32-byte digest signed. + * `crypto::signing_schemes::prehashed{digest}`, 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. */ template , class Signature, class Input> [[nodiscard]] boost::system::result recover( - [[maybe_unused]] ecdsa_sha256_recoverable_t signing_scheme, Signature const& signature_value, - Input const& signing_input) noexcept { + [[maybe_unused]] signing_schemes::ecdsa_sha256_recoverable_t signing_scheme, + Signature const& signature_value, Input const& signing_input) noexcept { secure::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) { + auto const& signature_bytes = detail::checked_signature_bytes< + recoverable_signature, signing_schemes::ecdsa_sha256_recoverable_t>(signature_value); + detail::check_input(); + if constexpr (detail::input_valid_v) { return webcpp::crypto::detail::secp256k1_recovered( signature_bytes, webcpp::crypto::detail::secp256k1_digest(signing_input)); } else { @@ -1559,7 +1579,7 @@ template , class Signatur /** * 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)`. + * same inputs as `sign(crypto::signing_schemes::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 @@ -1575,28 +1595,28 @@ template , class Signatur * @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`. + * `crypto::signing_schemes::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::signing_schemes::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). + * `crypto::signing_schemes::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 { + [[maybe_unused]] signing_schemes::ecdsa_keccak256_recoverable_t signing_scheme, + Signature const& signature_value, Input const& signing_input) noexcept { secure::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) { + auto const& signature_bytes = detail::checked_signature_bytes< + recoverable_signature, signing_schemes::ecdsa_keccak256_recoverable_t>(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 { @@ -1779,12 +1799,12 @@ namespace webcpp::crypto { * @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`. + * empty included, or `crypto::signing_schemes::prehashed<32>`; anything else stops the build. + * @param signing_scheme `crypto::signing_schemes::ecdsa_sha256`. * @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). + * `crypto::signing_schemes::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::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 @@ -1792,13 +1812,14 @@ namespace webcpp::crypto { */ template , class Signature, class Input> [[nodiscard]] boost::system::result verify( - [[maybe_unused]] ecdsa_sha256_t signing_scheme, Signature const& signature_value, - Input const& signing_input, curves::secp256k1::public_key const& public_key) noexcept { + [[maybe_unused]] signing_schemes::ecdsa_sha256_t signing_scheme, + Signature const& signature_value, Input const& signing_input, + curves::secp256k1::public_key const& public_key) noexcept { secure::timing_guard const timing_scope; static_assert(detail::secp256k1_refuses_others); return detail::secp256k1_verify_ecdsa( - detail::checked_signature_bytes( - signature_value), + detail::checked_signature_bytes(signature_value), signing_input, detail::secp256k1_access::point(public_key)); } @@ -1810,8 +1831,8 @@ template , class Signatur * @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`. + * empty included; a `crypto::signing_schemes::prehashed` marker, or anything else, stops the build. + * @param signing_scheme `crypto::signing_schemes::schnorr`. * @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. @@ -1822,15 +1843,15 @@ template , class Signatur */ template , class Signature, class Input> [[nodiscard]] boost::system::result verify( - [[maybe_unused]] schnorr_t signing_scheme, Signature const& signature_value, + [[maybe_unused]] signing_schemes::schnorr_t signing_scheme, Signature const& signature_value, Input const& message_input, std::span xonly_public_key) noexcept { secure::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) { + detail::checked_signature_bytes(signature_value); + detail::check_input(); + if constexpr (detail::input_valid_v) { auto const message_bytes = detail::message_bytes(message_input); detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); secp256k1_selftest(); @@ -1855,8 +1876,8 @@ template , class Signatur * @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`. + * empty included; a `crypto::signing_schemes::prehashed` marker, or anything else, stops the build. + * @param signing_scheme `crypto::signing_schemes::schnorr`. * @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. @@ -1865,13 +1886,13 @@ template , class Signatur */ template , class Signature, class Input> [[nodiscard]] boost::system::result verify( - [[maybe_unused]] schnorr_t signing_scheme, Signature const& signature_value, + [[maybe_unused]] signing_schemes::schnorr_t signing_scheme, Signature const& signature_value, Input const& message_input, curves::secp256k1::public_key const& public_key) noexcept { secure::timing_guard const timing_scope; static_assert(detail::secp256k1_refuses_others); return detail::secp256k1_verify_schnorr_key( - detail::checked_signature_bytes( - signature_value), + detail::checked_signature_bytes(signature_value), message_input, detail::secp256k1_access::point(public_key)); } @@ -1885,8 +1906,8 @@ namespace webcpp::crypto::detail { * @tparam Backend The key pair's backend. */ template -inline constexpr bool signs_with_v, ecdsa_sha256_t> = - true; +inline constexpr bool + signs_with_v, signing_schemes::ecdsa_sha256_t> = true; /** * A secp256k1 key pair signs with ECDSA over SHA-256 with the recovery id. @@ -1894,8 +1915,8 @@ inline constexpr bool signs_with_v, ec * @tparam Backend The key pair's backend. */ template -inline constexpr bool - signs_with_v, ecdsa_sha256_recoverable_t> = true; +inline constexpr bool signs_with_v, + signing_schemes::ecdsa_sha256_recoverable_t> = true; /** * A secp256k1 key pair signs with Ethereum's recoverable ECDSA over Keccak-256. @@ -1903,8 +1924,8 @@ inline constexpr bool * @tparam Backend The key pair's backend. */ template -inline constexpr bool - signs_with_v, ecdsa_keccak256_recoverable_t> = true; +inline constexpr bool signs_with_v, + signing_schemes::ecdsa_keccak256_recoverable_t> = true; /** * A secp256k1 key pair signs with BIP340's Schnorr. @@ -1912,15 +1933,18 @@ inline constexpr bool * @tparam Backend The key pair's backend. */ template -inline constexpr bool signs_with_v, schnorr_t> = true; +inline constexpr bool + signs_with_v, signing_schemes::schnorr_t> = true; /** A secp256k1 public key verifies ECDSA over SHA-256. */ template <> -inline constexpr bool verifies_with_v = true; +inline constexpr bool + verifies_with_v = true; /** A secp256k1 public key verifies BIP340's Schnorr, through its x-only form. */ template <> -inline constexpr bool verifies_with_v = true; +inline constexpr bool verifies_with_v = + true; /** * A BIP340 x-only key, its 32 bytes, verifies `schnorr`: any bytes that convert to @@ -1931,7 +1955,7 @@ inline constexpr bool verifies_with_v */ template requires std::is_convertible_v> -inline constexpr bool verifies_with_v = true; +inline constexpr bool verifies_with_v = true; /** * A secp256k1 key pair's signature under ECDSA over SHA-256, `curves::secp256k1::ecdsa_signature`. @@ -1939,7 +1963,7 @@ inline constexpr bool verifies_with_v = true; * @tparam Backend The key's backend. */ template -struct signature_of, ecdsa_sha256_t> { +struct signature_of, signing_schemes::ecdsa_sha256_t> { /** The signature type. */ using type = curves::secp256k1::ecdsa_signature; }; @@ -1951,7 +1975,8 @@ struct signature_of, ecdsa_sha256_t> { * @tparam Backend The key's backend. */ template -struct signature_of, ecdsa_sha256_recoverable_t> { +struct signature_of, + signing_schemes::ecdsa_sha256_recoverable_t> { /** The signature type. */ using type = curves::secp256k1::recoverable_signature; }; @@ -1964,7 +1989,8 @@ struct signature_of, ecdsa_sha256_reco * @tparam Backend The key's backend. */ template -struct signature_of, ecdsa_keccak256_recoverable_t> { +struct signature_of, + signing_schemes::ecdsa_keccak256_recoverable_t> { /** The signature type. */ using type = curves::secp256k1::recoverable_signature; }; @@ -1975,7 +2001,7 @@ struct signature_of, ecdsa_keccak256_r * @tparam Backend The key's backend. */ template -struct signature_of, schnorr_t> { +struct signature_of, signing_schemes::schnorr_t> { /** The signature type. */ using type = curves::secp256k1::schnorr_signature; }; @@ -1985,7 +2011,7 @@ struct signature_of, schnorr_t> { * `curves::secp256k1::ecdsa_signature`. */ template <> -struct signature_of { +struct signature_of { /** The signature type. */ using type = curves::secp256k1::ecdsa_signature; }; @@ -1995,7 +2021,7 @@ struct signature_of { * `curves::secp256k1::schnorr_signature`. */ template <> -struct signature_of { +struct signature_of { /** The signature type. */ using type = curves::secp256k1::schnorr_signature; }; @@ -2008,7 +2034,7 @@ struct signature_of { */ template requires std::is_convertible_v> -struct signature_of { +struct signature_of { /** The signature type. */ using type = curves::secp256k1::schnorr_signature; }; @@ -2036,14 +2062,16 @@ struct key_backend { * the catch-all steps aside. */ template <> -inline constexpr bool has_verifier_v = true; +inline constexpr bool + has_verifier_v = true; /** * `crypto::verify` of `schnorr` against a secp256k1 public key is secp256k1's, so that the * catch-all steps aside. */ template <> -inline constexpr bool has_verifier_v = true; +inline constexpr bool has_verifier_v = + true; /** * `crypto::verify` of `schnorr` against 32 bytes is secp256k1's, so that the catch-all steps @@ -2053,7 +2081,7 @@ inline constexpr bool has_verifier_v = */ template requires std::is_convertible_v> -inline constexpr bool has_verifier_v = true; +inline constexpr bool has_verifier_v = true; } // namespace webcpp::crypto::detail diff --git a/include/webcpp/crypto/curves/secp256k1/musig.hpp b/include/webcpp/crypto/curves/secp256k1/musig.hpp index 958946ef..f08f33f4 100644 --- a/include/webcpp/crypto/curves/secp256k1/musig.hpp +++ b/include/webcpp/crypto/curves/secp256k1/musig.hpp @@ -559,7 +559,7 @@ template > /** * The BIP 340 signature of the partial signatures (`secp256k1_musig_partial_sig_agg`), which - * `crypto::verify(crypto::schnorr, signature, message, key)` checks under + * `crypto::verify(crypto::signing_schemes::schnorr, signature, message, key)` checks under * `aggregate_key::xonly_public_key()`. * * @tparam Backend The backend, `backends::secp256k1`. diff --git a/include/webcpp/crypto/keypair.hpp b/include/webcpp/crypto/keypair.hpp index a8e1012c..016da774 100644 --- a/include/webcpp/crypto/keypair.hpp +++ b/include/webcpp/crypto/keypair.hpp @@ -96,7 +96,7 @@ struct contract_input { template struct contract_input { /** The marker of a digest of the scheme's size. */ - using type = prehashed::digest_size>; + using type = signing_schemes::prehashed::digest_size>; }; /** @@ -218,7 +218,7 @@ concept has_agree_member = * `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`). + * a digest for a scheme that takes its digest alone (`crypto::signing_schemes::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`). @@ -258,7 +258,7 @@ concept agreement_keypair = keypair && requires { * secp256k1's. * @tparam Scheme A scheme tag. * @tparam Input A message, bytes that convert to `std::span`, or - * `crypto::prehashed`. + * `crypto::signing_schemes::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. diff --git a/include/webcpp/crypto/signing.hpp b/include/webcpp/crypto/signing.hpp index 4f3c436c..79b45c35 100644 --- a/include/webcpp/crypto/signing.hpp +++ b/include/webcpp/crypto/signing.hpp @@ -42,6 +42,7 @@ #include namespace webcpp::crypto { +namespace signing_schemes { /** * The type of @ref eddsa, Ed25519's signature scheme (RFC 8032's pure Ed25519). @@ -105,6 +106,7 @@ struct schnorr_t { /** Makes the tag; explicit, so that only its name makes one. */ explicit schnorr_t() = default; }; +} // namespace signing_schemes namespace detail { @@ -122,8 +124,9 @@ struct scheme_list {}; * list. */ using all_schemes = - scheme_list; + scheme_list; /** * Whether `Type` is a member of the list `List`: false for a type that is not a `scheme_list`. @@ -154,6 +157,8 @@ inline constexpr bool is_scheme_v = in_scheme_list_v; } // namespace detail +namespace signing_schemes { + /** * Ed25519's signature scheme, RFC 8032's pure Ed25519: it signs the message itself, of any * length, and takes no digest; its signature is 64 bytes. @@ -201,7 +206,7 @@ inline constexpr schnorr_t schnorr{}; /** * A digest given to a scheme that signs one, in place of the message it hashes: - * `key.sign(crypto::ecdsa_sha256, crypto::prehashed{digest})`. + * `key.sign(crypto::signing_schemes::ecdsa_sha256, crypto::signing_schemes::prehashed{digest})`. * * It refers to the digest, which stays the caller's: the marker must not outlive it, so a marker * of a temporary, such as `prehashed{hasher.result()}`, is valid only within the full expression @@ -215,9 +220,10 @@ inline constexpr schnorr_t schnorr{}; */ template struct prehashed { - static_assert(N != std::dynamic_extent, - "webcpp::crypto: crypto::prehashed takes a digest of a fixed size: a " - "std::array or a std::span."); + static_assert( + N != std::dynamic_extent, + "webcpp::crypto: crypto::signing_schemes::prehashed takes a digest of a fixed size: a " + "std::array or a std::span."); /** The digest's bytes, the caller's. */ std::span digest; @@ -272,6 +278,7 @@ prehashed(std::span) -> prehashed; */ template prehashed(boost::hash2::digest const&) -> prehashed; +} // namespace signing_schemes namespace detail { @@ -289,7 +296,7 @@ struct scheme_traits; /** Ed25519's: a 64-byte signature, and no digest. */ template <> -struct scheme_traits { +struct scheme_traits { /** Whether it takes a message: it does. */ static constexpr bool takes_message = true; /** The signature's size in bytes. */ @@ -300,7 +307,7 @@ struct scheme_traits { /** Ed25519ph's: a 64-byte signature, and SHA-512's 64-byte digest. */ template <> -struct scheme_traits { +struct scheme_traits { /** Whether it takes a message: no, its digest alone. */ static constexpr bool takes_message = false; /** The signature's size in bytes. */ @@ -311,7 +318,7 @@ struct scheme_traits { /** ECDSA over SHA-256's: a 64-byte signature, and SHA-256's 32-byte digest. */ template <> -struct scheme_traits { +struct scheme_traits { /** Whether it takes a message: it does. */ static constexpr bool takes_message = true; /** The signature's size in bytes. */ @@ -322,7 +329,7 @@ struct scheme_traits { /** Recoverable ECDSA over SHA-256's: a 65-byte signature, and SHA-256's 32-byte digest. */ template <> -struct scheme_traits { +struct scheme_traits { /** Whether it takes a message: it does. */ static constexpr bool takes_message = true; /** The signature's size in bytes, with the recovery id. */ @@ -333,7 +340,7 @@ struct scheme_traits { /** Ethereum's recoverable ECDSA's: a 65-byte signature, and Keccak-256's 32-byte digest. */ template <> -struct scheme_traits { +struct scheme_traits { /** Whether it takes a message: it does. */ static constexpr bool takes_message = true; /** The signature's size in bytes, with the recovery id. */ @@ -344,7 +351,7 @@ struct scheme_traits { /** BIP340's: a 64-byte signature, and no digest. */ template <> -struct scheme_traits { +struct scheme_traits { /** Whether it takes a message: it does. */ static constexpr bool takes_message = true; /** The signature's size in bytes. */ @@ -367,7 +374,7 @@ inline constexpr bool is_prehashed_v = false; * @tparam N The digest's size in bytes. */ template -inline constexpr bool is_prehashed_v> = true; +inline constexpr bool is_prehashed_v> = true; /** * Whether `Type` is a message: bytes that convert to `std::span`, of any @@ -469,7 +476,7 @@ inline constexpr bool input_valid_v = is_message_v && takes_message_v -inline constexpr bool input_valid_v, Backend> = +inline constexpr bool input_valid_v, Backend> = scheme_traits::digest_size != 0 && N == scheme_traits::digest_size && signs_prehashed_v; @@ -484,43 +491,57 @@ inline constexpr bool input_valid_v, Backend> = template constexpr void check_input() noexcept { if constexpr (!is_prehashed_v && is_message_v && !takes_message_v) { - static_assert(refused_v, - "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."); + static_assert( + refused_v, + "webcpp::crypto: crypto::signing_schemes::eddsa_prehashed (RFC 8032's Ed25519ph) signs " + "a " + "digest, the message's SHA-512: crypto::signing_schemes::prehashed{digest} of a " + "std::array; sign the message itself with " + "crypto::signing_schemes::eddsa, " + "or give it in pieces to curves::ed25519::prehashed_signer."); } else if constexpr (!is_prehashed_v) { - static_assert(is_message_v, - "webcpp::crypto: a signature's input is a message (bytes, as " - "std::span) or crypto::prehashed{digest}."); - } else if constexpr (std::is_same_v) { + static_assert( + is_message_v, + "webcpp::crypto: a signature's input is a message (bytes, as " + "std::span) or crypto::signing_schemes::prehashed{digest}."); + } else if constexpr (std::is_same_v) { static_assert(refused_v, - "webcpp::crypto: crypto::eddsa signs the message itself (RFC 8032's pure " + "webcpp::crypto: crypto::signing_schemes::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)."); + "crypto::signing_schemes::eddsa_prehashed (Ed25519ph)."); } else if constexpr (decltype(Input::digest)::extent != scheme_traits::digest_size && - std::is_same_v) { + std::is_same_v) { + static_assert( + refused_v, + "webcpp::crypto: crypto::signing_schemes::eddsa_prehashed takes a 64-byte digest, " + "SHA-512's: " + "crypto::signing_schemes::prehashed{digest} of a std::array."); + } else if constexpr (std::is_same_v) { static_assert(refused_v, - "webcpp::crypto: crypto::eddsa_prehashed takes a 64-byte digest, SHA-512's: " - "crypto::prehashed{digest} of a std::array."); - } else if constexpr (std::is_same_v) { - static_assert(refused_v, - "webcpp::crypto: crypto::schnorr (BIP340) signs a message of any length and " + "webcpp::crypto: crypto::signing_schemes::schnorr (BIP340) signs a message " + "of any length and " "has no prehash mode: pass the message."); } else if constexpr (decltype(Input::digest)::extent != scheme_traits::digest_size && - std::is_same_v) { + std::is_same_v) { static_assert(refused_v, - "webcpp::crypto: crypto::ecdsa_sha256_recoverable takes a 32-byte digest, " - "SHA-256's: crypto::prehashed{digest} of a std::array."); + "webcpp::crypto: crypto::signing_schemes::ecdsa_sha256_recoverable takes a " + "32-byte digest, " + "SHA-256's: crypto::signing_schemes::prehashed{digest} of a " + "std::array."); } else if constexpr (decltype(Input::digest)::extent != scheme_traits::digest_size && - std::is_same_v) { + std::is_same_v) { static_assert(refused_v, - "webcpp::crypto: crypto::ecdsa_keccak256_recoverable takes a 32-byte digest, " - "Keccak-256's: crypto::prehashed{digest} of a std::array."); + "webcpp::crypto: crypto::signing_schemes::ecdsa_keccak256_recoverable takes " + "a 32-byte digest, " + "Keccak-256's: crypto::signing_schemes::prehashed{digest} of a " + "std::array."); } else if constexpr (decltype(Input::digest)::extent != scheme_traits::digest_size) { - static_assert(refused_v, - "webcpp::crypto: crypto::ecdsa_sha256 takes a 32-byte digest, SHA-256's: " - "crypto::prehashed{digest} of a std::array."); + static_assert( + refused_v, + "webcpp::crypto: crypto::signing_schemes::ecdsa_sha256 takes a 32-byte digest, " + "SHA-256's: " + "crypto::signing_schemes::prehashed{digest} of a std::array."); } else if constexpr (!signs_prehashed_v) { static_assert(refused_v, "webcpp::crypto: this backend cannot sign or verify a digest (WebCrypto has " @@ -541,7 +562,8 @@ constexpr void check_input() noexcept { template constexpr void refuse_ed25519ph_on_asynchronous_backend() noexcept { static_assert(refused_v, - "webcpp::crypto: WebCrypto has no Ed25519ph: crypto::eddsa_prehashed's sign, " + "webcpp::crypto: WebCrypto has no Ed25519ph: " + "crypto::signing_schemes::eddsa_prehashed's sign, " "verify, async_sign and async_verify run on a native backend."); } @@ -620,40 +642,45 @@ template static_assert(signature_matches, "webcpp::crypto: verify: Ed25519ph verifies a curves::ed25519::signature: " "make one from 64 bytes with curves::ed25519::signature::from_bytes."); - } else if constexpr (ed25519_expected && std::is_same_v) { + } else if constexpr (ed25519_expected && std::is_same_v) { static_assert(signature_matches, "webcpp::crypto: verify: an Ed25519 key verifies a " - "curves::ed25519::signature under crypto::eddsa: make one from 64 bytes " + "curves::ed25519::signature under crypto::signing_schemes::eddsa: make one " + "from 64 bytes " "with curves::ed25519::signature::from_bytes."); - } else if constexpr (ed25519_expected && std::is_same_v) { + } else if constexpr (ed25519_expected && + std::is_same_v) { static_assert(signature_matches, "webcpp::crypto: verify: an Ed25519 key verifies a " - "curves::ed25519::signature under crypto::eddsa_prehashed: make one from 64 " + "curves::ed25519::signature under crypto::signing_schemes::eddsa_prehashed: " + "make one from 64 " "bytes with curves::ed25519::signature::from_bytes."); } else if constexpr (is_signature_of_tag_v && - std::is_same_v) { + std::is_same_v) { static_assert(signature_matches, - "webcpp::crypto: verify: crypto::schnorr verifies a " + "webcpp::crypto: verify: crypto::signing_schemes::schnorr verifies a " "curves::secp256k1::schnorr_signature: make one from 64 bytes with " "curves::secp256k1::schnorr_signature::from_bytes."); } else if constexpr (is_signature_of_tag_v && - (std::is_same_v || - std::is_same_v)) { + (std::is_same_v || + std::is_same_v)) { static_assert(signature_matches, "webcpp::crypto: recover takes a curves::secp256k1::recoverable_signature: " "make one from 65 bytes with " "curves::secp256k1::recoverable_signature::from_bytes."); } else if constexpr (is_signature_of_tag_v && - std::is_same_v) { + std::is_same_v) { static_assert(signature_matches, "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."); } else if constexpr (is_signature_of_tag_v && - std::is_same_v) { + std::is_same_v) { static_assert(signature_matches, "webcpp::crypto: verify: a secp256k1 key verifies a " - "curves::secp256k1::ecdsa_signature under crypto::ecdsa_sha256: make one " + "curves::secp256k1::ecdsa_signature under " + "crypto::signing_schemes::ecdsa_sha256: make one " "from 64 bytes with curves::secp256k1::ecdsa_signature::from_bytes."); } else { static_assert(refused_v, @@ -765,11 +792,14 @@ template [[maybe_unused]] PublicKey const& public_key) noexcept { static_assert(detail::refused_v, "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 " + "crypto::signing_schemes::eddsa and crypto::signing_schemes::eddsa_prehashed " + "take a curves::ed25519::public_key, " + "crypto::signing_schemes::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 " + "crypto::signing_schemes::schnorr a curves::secp256k1::public_key or a 32-byte " + "x-only key; a " + "crypto::signing_schemes::ecdsa_sha256_recoverable or a " + "crypto::signing_schemes::ecdsa_keccak256_recoverable " "signature gives its key to curves::secp256k1::recover."); return {}; } diff --git a/test/Jamfile b/test/Jamfile index c7475b9b..58cf0db0 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -202,6 +202,10 @@ crypto-run error : error_test.cpp ; # signing.hpp's tags and their one list, prehashed, the input checks and the # concepts, over stand-in key types; the catch-all verify; sha256_of. crypto-run signing : signing_test.cpp ; +# The scheme tags and prehashed in crypto::signing_schemes: each of the six is a +# scheme, constructible by name and from no braces; prehashed signs what the message signs. +crypto-run signing_namespaces : signing_namespaces_test.cpp + : /third_party//bearssl ; # The three key pair concepts, keypair, signing_keypair and agreement_keypair: # stand-ins that sign, agree, do both, lack a member or sign or agree into # another type give each verdict; the four curves' key pairs give D4's table, @@ -400,7 +404,7 @@ crypto-run secp256k1_keys : secp256k1_keys_test.cpp : /third_party//sec # Recoverable ECDSA signatures, libsecp256k1's edge cases, and hedged ECDSA. crypto-run secp256k1_recovery : secp256k1_recovery_test.cpp : /third_party//secp256k1 ; # Ethereum's recoverable ECDSA over Keccak-256 -# (crypto::ecdsa_keccak256_recoverable): go-ethereum's recovery vector, +# (crypto::signing_schemes::ecdsa_keccak256_recoverable): go-ethereum's recovery vector, # web3.js's personal_sign, a message hashed with Keccak-256 (XKCP's) and never # SHA3-256, low S, and a signature recovered under the other recoverable scheme # giving another key. @@ -618,7 +622,7 @@ crypto-run ed25519_sodium : ed25519_sodium_test.cpp crypto-run ed25519_wycheproof_sodium : ed25519_wycheproof_sodium_test.cpp : /third_party//sodium /third_party//wycheproof /webcpp//boost_json ; -# Ed25519ph on libsodium, the scheme crypto::eddsa_prehashed and the streaming +# Ed25519ph on libsodium, the scheme crypto::signing_schemes::eddsa_prehashed and the streaming # signer: RFC 8032 section 7.3's case, the signer equal to the scheme, the two # Ed25519 schemes not interchangeable; P-256's and secp256k1's key pairs, which # do not sign under the scheme, are linked for can_sign's checks. diff --git a/test/allocation_bearssl_test.cpp b/test/allocation_bearssl_test.cpp index 58022d47..9eb12d2a 100644 --- a/test/allocation_bearssl_test.cpp +++ b/test/allocation_bearssl_test.cpp @@ -57,16 +57,19 @@ void p256_calls() { if (!BOOST_TEST(pair.has_value())) { return; } - auto const signature = pair->sign(crypto::ecdsa_sha256, crypto::prehashed{digest}); - auto const of_message = pair->sign(crypto::ecdsa_sha256, digest); + auto const signature = pair->sign(crypto::signing_schemes::ecdsa_sha256, + crypto::signing_schemes::prehashed{digest}); + auto const of_message = pair->sign(crypto::signing_schemes::ecdsa_sha256, digest); auto const key = public_key::from_bytes(point); if (!BOOST_TEST(signature.has_value()) || !BOOST_TEST(of_message.has_value()) || !BOOST_TEST(key.has_value())) { return; } - BOOST_TEST(crypto::verify(crypto::ecdsa_sha256, *signature, crypto::prehashed{digest}, *key) + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signature, + crypto::signing_schemes::prehashed{digest}, *key) + .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *of_message, digest, *key) .has_value()); - BOOST_TEST(crypto::verify(crypto::ecdsa_sha256, *of_message, digest, *key).has_value()); std::array der{}; auto const written = p256::to_der(*signature, der); if (BOOST_TEST(written.has_value())) { diff --git a/test/allocation_sodium_test.cpp b/test/allocation_sodium_test.cpp index 336d0b95..043b2631 100644 --- a/test/allocation_sodium_test.cpp +++ b/test/allocation_sodium_test.cpp @@ -103,8 +103,9 @@ void expect_no_allocation_ed25519() { // Strict verification on libsodium, named once: a call's commas would split a macro's // argument. auto const verify = [](auto const& signature, auto const& message, auto const& public_key) { - return crypto::verify( - crypto::eddsa, signature, message, public_key, crypto::curves::ed25519::strict); + return crypto::verify(crypto::signing_schemes::eddsa, signature, + message, public_key, + crypto::curves::ed25519::strict); }; std::array seed{}; seed.fill(5); @@ -117,7 +118,7 @@ void expect_no_allocation_ed25519() { BOOST_TEST(drawn.has_value()); auto const public_key = made->public_key(); BOOST_TEST(public_key.has_value()); - auto const signature = made->sign(crypto::eddsa, message); + auto const signature = made->sign(crypto::signing_schemes::eddsa, message); BOOST_TEST(signature.has_value()); auto const verified = verify(*signature, message, *public_key); BOOST_TEST(verified.has_value()); @@ -138,12 +139,13 @@ void expect_no_allocation_ed25519() { webcpp::hash::sha2_512 hasher; hasher.update(message.data(), message.size()); auto const digest = hasher.result(); - auto const scheme_signature = - made->sign(crypto::eddsa_prehashed, crypto::prehashed{digest}); + auto const scheme_signature = made->sign(crypto::signing_schemes::eddsa_prehashed, + crypto::signing_schemes::prehashed{digest}); BOOST_TEST(scheme_signature.has_value() && *scheme_signature == *streamed_signature); BOOST_TEST(crypto::verify( - crypto::eddsa_prehashed, *scheme_signature, crypto::prehashed{digest}, - *public_key, crypto::curves::ed25519::strict) + crypto::signing_schemes::eddsa_prehashed, *scheme_signature, + crypto::signing_schemes::prehashed{digest}, *public_key, + crypto::curves::ed25519::strict) .has_value()); auto const converted_pair = made->to_x25519(); BOOST_TEST(converted_pair.has_value()); diff --git a/test/async_25519_test.cpp b/test/async_25519_test.cpp index 67ab2f81..63bd50cd 100644 --- a/test/async_25519_test.cpp +++ b/test/async_25519_test.cpp @@ -5,8 +5,8 @@ // https://www.boost.org/LICENSE_1_0.txt) // Ed25519's and X25519's asynchronous functions on libsodium, on a callback and in a coroutine. -// async_sign and async_verify take the scheme, crypto::eddsa, and the synchronous calls' inputs, -// the message and, for async_verify, the policy before the token, strict by default: +// async_sign and async_verify take the scheme, crypto::signing_schemes::eddsa, and the synchronous +// calls' inputs, the message and, for async_verify, the policy before the token, strict by default: // - async_rfc8032: RFC 8032 section 7.1's tests 1, 2 and 3 through async_from_secret and async_sign // give the RFC's signatures and the synchronous ones, and async_verify accepts them, with the // backend named and its policy given, and with the defaults; each completion arrives after the @@ -39,7 +39,8 @@ // signature, received as a std::vector and made into the type with from_bytes, and refuses a // changed one with invalid_signature; from_bytes refuses 63 and 65 bytes with // invalid_signature); each asynchronous completion arrives after the initiating call returned. -// - eddsa_prehashed_async: under crypto::eddsa_prehashed, RFC 8032 section 7.3's key pair signs +// - eddsa_prehashed_async: under crypto::signing_schemes::eddsa_prehashed, RFC 8032 section 7.3's +// key pair signs // the marker of "abc"'s SHA-512 through key.async_sign and crypto::async_sign into the // synchronous signature, which async_verify, member and free, accepts, with the defaults and with // the backend and the policy named; each completion arrives after the initiating call returned. @@ -181,13 +182,16 @@ constexpr auto rfc8032_cases = std::to_array({ // async_verify of eddsa takes the typed key alone: bytes fall to the catch-all // (messages/async_verify_eddsa_bytes_key). -static_assert(crypto::detail::has_async_verifier_v); -static_assert(!crypto::detail::has_async_verifier_v>); static_assert( - !crypto::detail::has_async_verifier_v>); -static_assert(crypto::detail::has_async_verifier_v); -static_assert( - !crypto::detail::has_async_verifier_v>); + crypto::detail::has_async_verifier_v); +static_assert(!crypto::detail::has_async_verifier_v>); +static_assert(!crypto::detail::has_async_verifier_v>); +static_assert(crypto::detail::has_async_verifier_v); +static_assert(!crypto::detail::has_async_verifier_v>); /** * The public key of a case's hex, 32 bytes; a key not made throws (or, without exceptions, ends @@ -223,7 +227,7 @@ void async_rfc8032(asio::io_context& context) { auto& key = std::get<0>(*made.value); auto const signed_async = complete(context, [&](auto const& executor, auto&& token) { - return crypto::async_sign(executor, key, crypto::eddsa, message, + return crypto::async_sign(executor, key, crypto::signing_schemes::eddsa, message, std::forward(token)); }); BOOST_TEST(!signed_async.code); @@ -232,20 +236,20 @@ void async_rfc8032(asio::io_context& context) { } auto const& signature = std::get<0>(*signed_async.value); BOOST_TEST(std::ranges::equal(signature.bytes(), expected)); - auto const signed_sync = key.sign(crypto::eddsa, message); + auto const signed_sync = key.sign(crypto::signing_schemes::eddsa, message); BOOST_TEST(signed_sync.has_value() && *signed_sync == signature); auto const verified = complete_code(context, [&](auto const& executor, auto&& token) { return crypto::async_verify( - executor, crypto::eddsa, signature, message, public_key, ed25519::strict, - std::forward(token)); + executor, crypto::signing_schemes::eddsa, signature, message, public_key, + ed25519::strict, std::forward(token)); }); BOOST_TEST(!verified); // The defaults name the same backend. - auto const verified_default = - complete_code(context, [&](auto const& executor, auto&& token) { - return crypto::async_verify(executor, crypto::eddsa, signature, message, public_key, - std::forward(token)); - }); + auto const verified_default = complete_code(context, [&](auto const& executor, + auto&& token) { + return crypto::async_verify(executor, crypto::signing_schemes::eddsa, signature, + message, public_key, std::forward(token)); + }); BOOST_TEST(!verified_default); } } @@ -258,7 +262,8 @@ void async_verify_changed(asio::io_context& context) { auto const verify = [&](ed25519::public_key const& key, std::span signed_bytes) { return complete_code(context, [&](auto const& executor, auto&& token) { - return crypto::async_verify(executor, crypto::eddsa, typed(signed_bytes), message, key, + return crypto::async_verify(executor, crypto::signing_schemes::eddsa, + typed(signed_bytes), message, key, std::forward(token)); }); }; @@ -289,23 +294,23 @@ void generated(asio::io_context& context) { auto& key = std::get<0>(*made.value); std::array const message{1, 2, 3, 4, 5}; auto const public_key = key.public_key(); - auto const signature = key.sign(crypto::eddsa, message); + auto const signature = key.sign(crypto::signing_schemes::eddsa, message); if (!BOOST_TEST(public_key.has_value()) || !BOOST_TEST(signature.has_value())) { return; } auto const verified_sync = crypto::verify( - crypto::eddsa, *signature, message, *public_key, ed25519::strict); + crypto::signing_schemes::eddsa, *signature, message, *public_key, ed25519::strict); BOOST_TEST(verified_sync.has_value()); auto const signed_async = complete(context, [&](auto const& executor, auto&& token) { - return crypto::async_sign(executor, key, crypto::eddsa, message, + return crypto::async_sign(executor, key, crypto::signing_schemes::eddsa, message, std::forward(token)); }); BOOST_TEST(!signed_async.code); BOOST_TEST(signed_async.value.has_value() && std::get<0>(*signed_async.value) == *signature); auto const verified = complete_code(context, [&](auto const& executor, auto&& token) { - return crypto::async_verify(executor, crypto::eddsa, *signature, message, *public_key, - std::forward(token)); + return crypto::async_verify(executor, crypto::signing_schemes::eddsa, *signature, message, + *public_key, std::forward(token)); }); BOOST_TEST(!verified); } @@ -328,11 +333,12 @@ void async_from_secret_refused(asio::io_context& context) { auto const& empty = std::get<0>(*made.value); std::array const message{1, 2, 3}; BOOST_TEST(empty.public_key().error() == crypto::error::invalid_state); - BOOST_TEST(empty.sign(crypto::eddsa, message).error() == crypto::error::invalid_state); + BOOST_TEST(empty.sign(crypto::signing_schemes::eddsa, message).error() == + crypto::error::invalid_state); BOOST_TEST(empty.to_x25519().error() == crypto::error::invalid_state); auto const signed_empty = complete(context, [&](auto const& executor, auto&& token) { - return crypto::async_sign(executor, empty, crypto::eddsa, message, + return crypto::async_sign(executor, empty, crypto::signing_schemes::eddsa, message, std::forward(token)); }); BOOST_TEST(signed_empty.code == crypto::error::invalid_state); @@ -496,7 +502,7 @@ void async_destroyed(asio::io_context& context) { if (!BOOST_TEST(key.has_value()) || !BOOST_TEST(alice.has_value())) { return; } - crypto::async_sign(context.get_executor(), *key, crypto::eddsa, *message, + crypto::async_sign(context.get_executor(), *key, crypto::signing_schemes::eddsa, *message, [&](boost::system::error_code code, signature_type done) { sign_code = code; signature = done; @@ -530,13 +536,14 @@ void async_coroutine(asio::io_context& context) { executor, seed, asio::as_tuple(asio::use_awaitable)); auto& [made_code, key] = made_code_result; BOOST_TEST(!made_code); - auto [sign_code, signature] = co_await crypto::async_sign( - executor, key, crypto::eddsa, message, asio::as_tuple(asio::use_awaitable)); + auto [sign_code, signature] = + co_await crypto::async_sign(executor, key, crypto::signing_schemes::eddsa, message, + asio::as_tuple(asio::use_awaitable)); BOOST_TEST(!sign_code); BOOST_TEST(std::ranges::equal(signature.bytes(), test::from_hex(tested.signature))); - auto [verify_code] = - co_await crypto::async_verify(executor, crypto::eddsa, signature, message, - public_key, asio::as_tuple(asio::use_awaitable)); + auto [verify_code] = co_await crypto::async_verify( + executor, crypto::signing_schemes::eddsa, signature, message, public_key, + asio::as_tuple(asio::use_awaitable)); BOOST_TEST(!verify_code); auto generate_code_result = co_await crypto::async_generate(executor, asio::as_tuple(asio::use_awaitable)); @@ -597,10 +604,10 @@ void four_forms_from_secret(asio::io_context& context, std::span const message{1, 2, 3}; - auto const signature = key.sign(crypto::eddsa, message); + auto const signature = key.sign(crypto::signing_schemes::eddsa, message); auto const own = key.public_key(); return signature.has_value() && own.has_value() && - own->verify(crypto::eddsa, *signature, message).has_value(); + own->verify(crypto::signing_schemes::eddsa, *signature, message).has_value(); } // generate in its four forms: each a key pair whose signature verifies. @@ -627,16 +634,16 @@ void check_four_signatures(asio::io_context& context, keypair const& key, std::span message, std::span expected, boost::system::error_code expected_code) { - auto const member_sync = key.sign(crypto::eddsa, message); - auto const free_sync = crypto::sign(key, crypto::eddsa, message); + auto const member_sync = key.sign(crypto::signing_schemes::eddsa, message); + auto const free_sync = crypto::sign(key, crypto::signing_schemes::eddsa, message); auto const member_async = complete(context, [&](auto const& executor, auto&& token) { - return key.async_sign(executor, crypto::eddsa, message, + return key.async_sign(executor, crypto::signing_schemes::eddsa, message, std::forward(token)); }); auto const free_async = complete(context, [&](auto const& executor, auto&& token) { - return crypto::async_sign(executor, key, crypto::eddsa, message, + return crypto::async_sign(executor, key, crypto::signing_schemes::eddsa, message, std::forward(token)); }); BOOST_TEST(member_async.code == expected_code); @@ -670,28 +677,30 @@ void check_four_verifications(asio::io_context& context, ed25519::public_key con auto const code_of = [](boost::system::result const& done) { return done ? boost::system::error_code{} : done.error(); }; - BOOST_TEST(code_of(key.verify(crypto::eddsa, signature, message)) == expected_code); - BOOST_TEST(code_of(key.verify(crypto::eddsa, signature, message, ed25519::strict)) == + BOOST_TEST(code_of(key.verify(crypto::signing_schemes::eddsa, signature, message)) == expected_code); - BOOST_TEST(code_of(crypto::verify(crypto::eddsa, signature, message, key)) == expected_code); - BOOST_TEST(code_of(crypto::verify(crypto::eddsa, signature, message, key, - ed25519::strict)) == expected_code); + BOOST_TEST(code_of(key.verify(crypto::signing_schemes::eddsa, signature, message, + ed25519::strict)) == expected_code); + BOOST_TEST(code_of(crypto::verify(crypto::signing_schemes::eddsa, signature, message, key)) == + expected_code); + BOOST_TEST(code_of(crypto::verify(crypto::signing_schemes::eddsa, signature, message, + key, ed25519::strict)) == expected_code); BOOST_TEST(complete_code(context, [&](auto const& executor, auto&& token) { - return key.async_verify(executor, crypto::eddsa, signature, message, - std::forward(token)); + return key.async_verify(executor, crypto::signing_schemes::eddsa, signature, + message, std::forward(token)); }) == expected_code); BOOST_TEST(complete_code(context, [&](auto const& executor, auto&& token) { - return key.async_verify(executor, crypto::eddsa, signature, message, - ed25519::strict, + return key.async_verify(executor, crypto::signing_schemes::eddsa, + signature, message, ed25519::strict, std::forward(token)); }) == expected_code); BOOST_TEST(complete_code(context, [&](auto const& executor, auto&& token) { - return crypto::async_verify(executor, crypto::eddsa, signature, message, key, - std::forward(token)); + return crypto::async_verify(executor, crypto::signing_schemes::eddsa, signature, + message, key, std::forward(token)); }) == expected_code); BOOST_TEST(complete_code(context, [&](auto const& executor, auto&& token) { - return crypto::async_verify(executor, crypto::eddsa, signature, message, - key, ed25519::strict, + return crypto::async_verify(executor, crypto::signing_schemes::eddsa, + signature, message, key, ed25519::strict, std::forward(token)); }) == expected_code); } @@ -738,8 +747,8 @@ void eddsa_prehashed_async(asio::io_context& context) { webcpp::hash::sha2_512 hasher; hasher.update(abc.data(), abc.size()); boost::hash2::digest<64> const digest = hasher.result(); - crypto::prehashed const marker{digest}; - auto const expected = key.sign(crypto::eddsa_prehashed, marker); + crypto::signing_schemes::prehashed const marker{digest}; + auto const expected = key.sign(crypto::signing_schemes::eddsa_prehashed, marker); if (!BOOST_TEST(expected.has_value())) { return; } @@ -749,42 +758,43 @@ void eddsa_prehashed_async(asio::io_context& context) { auto const signed_member = complete(context, [&](auto const& executor, auto&& token) { - return key.async_sign(executor, crypto::eddsa_prehashed, marker, + return key.async_sign(executor, crypto::signing_schemes::eddsa_prehashed, marker, std::forward(token)); }); BOOST_TEST(!signed_member.code); BOOST_TEST(signed_member.value && std::get<0>(*signed_member.value) == *expected); auto const signed_free = complete(context, [&](auto const& executor, auto&& token) { - return crypto::async_sign(executor, key, crypto::eddsa_prehashed, marker, - std::forward(token)); + return crypto::async_sign(executor, key, crypto::signing_schemes::eddsa_prehashed, + marker, std::forward(token)); }); BOOST_TEST(!signed_free.code); BOOST_TEST(signed_free.value && std::get<0>(*signed_free.value) == *expected); BOOST_TEST(!complete_code(context, [&](auto const& executor, auto&& token) { - return public_key.async_verify(executor, crypto::eddsa_prehashed, *expected, marker, - std::forward(token)); + return public_key.async_verify(executor, crypto::signing_schemes::eddsa_prehashed, + *expected, marker, std::forward(token)); })); BOOST_TEST(!complete_code(context, [&](auto const& executor, auto&& token) { - return public_key.async_verify(executor, crypto::eddsa_prehashed, *expected, marker, - ed25519::strict, + return public_key.async_verify(executor, crypto::signing_schemes::eddsa_prehashed, + *expected, marker, ed25519::strict, std::forward(token)); })); BOOST_TEST(!complete_code(context, [&](auto const& executor, auto&& token) { - return crypto::async_verify(executor, crypto::eddsa_prehashed, *expected, marker, - public_key, std::forward(token)); + return crypto::async_verify(executor, crypto::signing_schemes::eddsa_prehashed, *expected, + marker, public_key, std::forward(token)); })); BOOST_TEST(!complete_code(context, [&](auto const& executor, auto&& token) { - return crypto::async_verify(executor, crypto::eddsa_prehashed, *expected, marker, - public_key, ed25519::strict, + return crypto::async_verify(executor, crypto::signing_schemes::eddsa_prehashed, + *expected, marker, public_key, ed25519::strict, std::forward(token)); })); // The pure scheme's signature of the same message is refused under eddsa_prehashed. BOOST_TEST(complete_code(context, [&](auto const& executor, auto&& token) { - return crypto::async_verify(executor, crypto::eddsa_prehashed, - key.sign(crypto::eddsa, abc).value(), marker, - public_key, std::forward(token)); + return crypto::async_verify( + executor, crypto::signing_schemes::eddsa_prehashed, + key.sign(crypto::signing_schemes::eddsa, abc).value(), marker, public_key, + std::forward(token)); }) == crypto::error::invalid_signature); } diff --git a/test/async_p256_test.cpp b/test/async_p256_test.cpp index 30b53b6e..0b8e432b 100644 --- a/test/async_p256_test.cpp +++ b/test/async_p256_test.cpp @@ -5,9 +5,9 @@ // https://www.boost.org/LICENSE_1_0.txt) // P-256's asynchronous functions on BearSSL, on a callback and in a coroutine. async_sign and -// async_verify take the scheme, crypto::ecdsa_sha256, and the synchronous calls' inputs: the -// message, which they hash with SHA-256, as WebCrypto's ECDSA with SHA-256 does, or -// crypto::prehashed{digest}; the synchronous answers they are checked against are +// async_verify take the scheme, crypto::signing_schemes::ecdsa_sha256, and the synchronous calls' +// inputs: the message, which they hash with SHA-256, as WebCrypto's ECDSA with SHA-256 does, or +// crypto::signing_schemes::prehashed{digest}; the synchronous answers they are checked against are // sign(ecdsa_sha256, prehashed{digest}) and crypto::verify(ecdsa_sha256, signature, // prehashed{digest}, key) of its digest, computed here. // - async_rfc6979: RFC 6979 section A.2.5's key through async_from_secret, its messages "sample" @@ -45,7 +45,8 @@ // same secret); and the refusals are the same, a short scalar's // invalid_key_size and an empty key pair's invalid_state, each asynchronous completion arriving // after the initiating call returned. -// - async_member_deferred: key.async_sign with asio::deferred, of a crypto::prehashed{digest} +// - async_member_deferred: key.async_sign with asio::deferred, of a +// crypto::signing_schemes::prehashed{digest} // made in the call's argument list, launched after the statement that made it ended, runs when // launched and gives RFC 6979's signature. @@ -112,16 +113,18 @@ inline constexpr bool asynchronous_backend_v = true; // Such a backend signs a message and no digest (WebCrypto has no prehash mode); the concept answers // from the traits' partial specializations, without instantiating the key pair's class. -static_assert(!crypto::can_sign, crypto::ecdsa_sha256_t, - crypto::prehashed<32>>); -static_assert(crypto::can_sign, crypto::ecdsa_sha256_t, - std::span>); +static_assert(!crypto::can_sign, + crypto::signing_schemes::ecdsa_sha256_t, + crypto::signing_schemes::prehashed<32>>); static_assert( - !crypto::can_verify, - p256::basic_public_key>); -static_assert( - crypto::can_verify, - p256::basic_public_key>); + crypto::can_sign, + crypto::signing_schemes::ecdsa_sha256_t, std::span>); +static_assert(!crypto::can_verify, + p256::basic_public_key>); +static_assert(crypto::can_verify, + p256::basic_public_key>); namespace { @@ -223,7 +226,7 @@ std::optional made_async(asio::io_context& context, std::span sign_async(asio::io_context& context, keypair const& key, std::span message) { return complete(context, [&](auto const& executor, auto&& token) { - return crypto::async_sign(executor, key, crypto::ecdsa_sha256, message, + return crypto::async_sign(executor, key, crypto::signing_schemes::ecdsa_sha256, message, std::forward(token)); }); } @@ -232,8 +235,8 @@ boost::system::error_code verify_async(asio::io_context& context, public_key con std::span message, signature_type const& signature) { return complete_code(context, [&](auto const& executor, auto&& token) { - return crypto::async_verify(executor, crypto::ecdsa_sha256, signature, message, key, - std::forward(token)); + return crypto::async_verify(executor, crypto::signing_schemes::ecdsa_sha256, signature, + message, key, std::forward(token)); }); } @@ -266,8 +269,8 @@ void async_rfc6979(asio::io_context& context) { } auto const& signature = std::get<0>(*signed_async.value); BOOST_TEST(signature.bytes() == expected); - auto const signed_sync = - key->sign(crypto::ecdsa_sha256, crypto::prehashed{sha256(message)}); + auto const signed_sync = key->sign(crypto::signing_schemes::ecdsa_sha256, + crypto::signing_schemes::prehashed{sha256(message)}); BOOST_TEST(signed_sync.has_value() && *signed_sync == signature); BOOST_TEST(!verify_async(context, *own, message, signature)); } @@ -298,15 +301,16 @@ void check_wycheproof_ecdsa_case(asio::io_context& context, public_key const& ke } auto const signature = typed(encoded); auto const verified_sync = - crypto::verify(crypto::ecdsa_sha256, signature, crypto::prehashed{sha256(message)}, key); + crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, + crypto::signing_schemes::prehashed{sha256(message)}, key); BOOST_TEST(verified_sync.has_value()); BOOST_TEST(!verify_async(context, key, message, signature)); // A changed byte of the message: both refuse it. message.push_back(0); message.front() ^= 1U; - BOOST_TEST( - crypto::verify(crypto::ecdsa_sha256, signature, crypto::prehashed{sha256(message)}, key) - .error() == crypto::error::invalid_signature); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, + crypto::signing_schemes::prehashed{sha256(message)}, key) + .error() == crypto::error::invalid_signature); BOOST_TEST(verify_async(context, key, message, signature) == crypto::error::invalid_signature); } @@ -409,13 +413,14 @@ void async_prehashed(asio::io_context& context) { } auto const message = bytes_of("sample"); auto digest = sha256(message); - auto const signed_sync = key->sign(crypto::ecdsa_sha256, message); + auto const signed_sync = key->sign(crypto::signing_schemes::ecdsa_sha256, message); auto const signed_message = sign_async(context, *key, message); - auto const signed_digest = complete(context, [&](auto const& executor, - auto&& token) { - return crypto::async_sign(executor, *key, crypto::ecdsa_sha256, crypto::prehashed{digest}, - std::forward(token)); - }); + auto const signed_digest = + complete(context, [&](auto const& executor, auto&& token) { + return crypto::async_sign(executor, *key, crypto::signing_schemes::ecdsa_sha256, + crypto::signing_schemes::prehashed{digest}, + std::forward(token)); + }); BOOST_TEST(!signed_message.code); BOOST_TEST(!signed_digest.code); if (!BOOST_TEST(signed_sync.has_value()) || !BOOST_TEST(signed_message.value.has_value()) || @@ -427,8 +432,8 @@ void async_prehashed(asio::io_context& context) { BOOST_TEST(std::get<0>(*signed_digest.value) == *signed_sync); auto const verify_digest = [&] { return complete_code(context, [&](auto const& executor, auto&& token) { - return crypto::async_verify(executor, crypto::ecdsa_sha256, signature, - crypto::prehashed{digest}, *own, + return crypto::async_verify(executor, crypto::signing_schemes::ecdsa_sha256, signature, + crypto::signing_schemes::prehashed{digest}, *own, std::forward(token)); }); }; @@ -473,7 +478,7 @@ void generated(asio::io_context& context) { } auto const signed_async = complete(context, [&](auto const& executor, auto&& token) { - return crypto::async_sign(executor, key, crypto::ecdsa_sha256, message, + return crypto::async_sign(executor, key, crypto::signing_schemes::ecdsa_sha256, message, std::forward(token)); }); BOOST_TEST(!signed_async.code); @@ -481,12 +486,12 @@ void generated(asio::io_context& context) { return; } auto const& signature = std::get<0>(*signed_async.value); - BOOST_TEST( - crypto::verify(crypto::ecdsa_sha256, signature, crypto::prehashed{sha256(message)}, *own) - .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, + crypto::signing_schemes::prehashed{sha256(message)}, *own) + .has_value()); auto const verified = complete_code(context, [&](auto const& executor, auto&& token) { - return crypto::async_verify(executor, crypto::ecdsa_sha256, signature, message, *own, - std::forward(token)); + return crypto::async_verify(executor, crypto::signing_schemes::ecdsa_sha256, signature, + message, *own, std::forward(token)); }); BOOST_TEST(!verified); } @@ -502,7 +507,8 @@ void check_empty_keypair(asio::io_context& context, keypair const& empty, public std::span message) { BOOST_TEST(empty.public_key().error() == crypto::error::invalid_state); BOOST_TEST(empty.secret().error() == crypto::error::invalid_state); - BOOST_TEST(empty.sign(crypto::ecdsa_sha256, message).error() == crypto::error::invalid_state); + BOOST_TEST(empty.sign(crypto::signing_schemes::ecdsa_sha256, message).error() == + crypto::error::invalid_state); BOOST_TEST(empty.agree(peer).error() == crypto::error::invalid_state); auto const signed_empty = sign_async(context, empty, message); BOOST_TEST(signed_empty.code == crypto::error::invalid_state); @@ -558,8 +564,8 @@ void async_destroyed(asio::io_context& context) { return; } std::ranges::copy(agreed_sync->bytes(), expected_shared.begin()); - crypto::async_sign(context.get_executor(), *key, crypto::ecdsa_sha256, *message, - [&](boost::system::error_code code, signature_type done) { + crypto::async_sign(context.get_executor(), *key, crypto::signing_schemes::ecdsa_sha256, + *message, [&](boost::system::error_code code, signature_type done) { sign_code = code; signature = done; }); @@ -606,8 +612,9 @@ asio::awaitable coroutine_body(bool& done) { executor, data::rfc6979_scalar, asio::as_tuple(asio::use_awaitable)); auto& [made_code, key] = made_result; BOOST_TEST(!made_code); - auto [sign_code, signature] = co_await crypto::async_sign( - executor, key, crypto::ecdsa_sha256, message, asio::as_tuple(asio::use_awaitable)); + auto [sign_code, signature] = + co_await crypto::async_sign(executor, key, crypto::signing_schemes::ecdsa_sha256, message, + asio::as_tuple(asio::use_awaitable)); BOOST_TEST(!sign_code); BOOST_TEST(signature.bytes() == data::rfc6979_test); auto const own = key.public_key(); @@ -615,8 +622,8 @@ asio::awaitable coroutine_body(bool& done) { co_return; } auto [verify_code] = - co_await crypto::async_verify(executor, crypto::ecdsa_sha256, signature, message, *own, - asio::as_tuple(asio::use_awaitable)); + co_await crypto::async_verify(executor, crypto::signing_schemes::ecdsa_sha256, signature, + message, *own, asio::as_tuple(asio::use_awaitable)); BOOST_TEST(!verify_code); co_await coroutine_agreement(executor, key, *own, done); } @@ -670,10 +677,10 @@ void four_forms_from_secret(asio::io_context& context) { // Whether a generated key pair signs a message its own public key verifies. bool signs_and_verifies(keypair const& key) { std::array const message{1, 2, 3}; - auto const signature = key.sign(crypto::ecdsa_sha256, message); + auto const signature = key.sign(crypto::signing_schemes::ecdsa_sha256, message); auto const own = key.public_key(); return signature.has_value() && own.has_value() && - own->verify(crypto::ecdsa_sha256, *signature, message).has_value(); + own->verify(crypto::signing_schemes::ecdsa_sha256, *signature, message).has_value(); } // generate in its four forms: each a key pair whose signature verifies. @@ -699,16 +706,16 @@ void four_forms_generate(asio::io_context& context) { template void check_four_signatures(asio::io_context& context, keypair const& key, Input const& input, boost::system::error_code expected_code) { - auto const member_sync = key.sign(crypto::ecdsa_sha256, input); - auto const free_sync = crypto::sign(key, crypto::ecdsa_sha256, input); + auto const member_sync = key.sign(crypto::signing_schemes::ecdsa_sha256, input); + auto const free_sync = crypto::sign(key, crypto::signing_schemes::ecdsa_sha256, input); auto const member_async = complete(context, [&](auto const& executor, auto&& token) { - return key.async_sign(executor, crypto::ecdsa_sha256, input, + return key.async_sign(executor, crypto::signing_schemes::ecdsa_sha256, input, std::forward(token)); }); auto const free_async = complete(context, [&](auto const& executor, auto&& token) { - return crypto::async_sign(executor, key, crypto::ecdsa_sha256, input, + return crypto::async_sign(executor, key, crypto::signing_schemes::ecdsa_sha256, input, std::forward(token)); }); BOOST_TEST(member_async.code == expected_code); @@ -740,16 +747,18 @@ void check_four_verifications(asio::io_context& context, public_key const& key, auto const code_of = [](boost::system::result const& done) { return done ? boost::system::error_code{} : done.error(); }; - BOOST_TEST(code_of(key.verify(crypto::ecdsa_sha256, signature, input)) == expected_code); - BOOST_TEST(code_of(crypto::verify(crypto::ecdsa_sha256, signature, input, key)) == + BOOST_TEST(code_of(key.verify(crypto::signing_schemes::ecdsa_sha256, signature, input)) == expected_code); + BOOST_TEST(code_of(crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, input, + key)) == expected_code); BOOST_TEST(complete_code(context, [&](auto const& executor, auto&& token) { - return key.async_verify(executor, crypto::ecdsa_sha256, signature, input, - std::forward(token)); + return key.async_verify(executor, crypto::signing_schemes::ecdsa_sha256, + signature, input, std::forward(token)); }) == expected_code); BOOST_TEST(complete_code(context, [&](auto const& executor, auto&& token) { - return crypto::async_verify(executor, crypto::ecdsa_sha256, signature, input, - key, std::forward(token)); + return crypto::async_verify(executor, crypto::signing_schemes::ecdsa_sha256, + signature, input, key, + std::forward(token)); }) == expected_code); } @@ -795,8 +804,8 @@ void async_member_deferred(asio::io_context& context) { } auto const digest = sha256(bytes_of("test")); // The marker is a temporary of this statement: the operation keeps its own copy. - auto operation = key->async_sign(context.get_executor(), crypto::ecdsa_sha256, - crypto::prehashed{digest}, asio::deferred); + auto operation = key->async_sign(context.get_executor(), crypto::signing_schemes::ecdsa_sha256, + crypto::signing_schemes::prehashed{digest}, asio::deferred); int calls = 0; signature_type signature{}; std::move(operation)([&](boost::system::error_code code, signature_type done) { @@ -828,10 +837,11 @@ void async_four_forms(asio::io_context& context) { auto const message = bytes_of("test"); auto digest = sha256(message); check_four_signatures(context, *key, message, {}); - check_four_signatures(context, *key, crypto::prehashed{digest}, {}); + check_four_signatures(context, *key, crypto::signing_schemes::prehashed{digest}, {}); auto const rfc_test = typed(data::rfc6979_test); check_four_verifications(context, *own, rfc_test, message, {}); - check_four_verifications(context, *own, rfc_test, crypto::prehashed{digest}, {}); + check_four_verifications(context, *own, rfc_test, crypto::signing_schemes::prehashed{digest}, + {}); // The signature received as a std::vector, made into the type; 63 and 65 bytes are refused // by from_bytes. std::vector const received(data::rfc6979_test.begin(), data::rfc6979_test.end()); @@ -847,7 +857,7 @@ void async_four_forms(asio::io_context& context) { check_four_verifications(context, *own, typed(changed), message, crypto::error::invalid_signature); digest[0] ^= 1U; - check_four_verifications(context, *own, rfc_test, crypto::prehashed{digest}, + check_four_verifications(context, *own, rfc_test, crypto::signing_schemes::prehashed{digest}, crypto::error::invalid_signature); check_four_agreements(context, *key, *peer, {}); [[maybe_unused]] keypair const taken(std::move(*key)); diff --git a/test/async_post_test.cpp b/test/async_post_test.cpp index eb307339..3f6474a7 100644 --- a/test/async_post_test.cpp +++ b/test/async_post_test.cpp @@ -832,8 +832,8 @@ struct verify_fixture { auto verify() { return [this](auto const& executor, auto&& token) { - return crypto::async_verify(executor, crypto::eddsa, typed_signature(), message, - public_key, std::forward(token)); + return crypto::async_verify(executor, crypto::signing_schemes::eddsa, typed_signature(), + message, public_key, std::forward(token)); }; } @@ -843,7 +843,7 @@ struct verify_fixture { auto changed = typed_signature().bytes(); ++changed[3]; return crypto::async_verify( - executor, crypto::eddsa, + executor, crypto::signing_schemes::eddsa, crypto::curves::ed25519::signature::from_bytes(changed).value(), message, public_key, std::forward(token)); }; @@ -851,7 +851,7 @@ struct verify_fixture { auto sign() { return [this](auto const& executor, auto&& token) { - return crypto::async_sign(executor, key_pair, crypto::eddsa, message, + return crypto::async_sign(executor, key_pair, crypto::signing_schemes::eddsa, message, std::forward(token)); }; } diff --git a/test/constant_time/bearssl_verdicts.supp b/test/constant_time/bearssl_verdicts.supp index a78da17d..26250c07 100644 --- a/test/constant_time/bearssl_verdicts.supp +++ b/test/constant_time/bearssl_verdicts.supp @@ -19,7 +19,7 @@ # builds BearSSL without link-time optimisation, which would inline a callee's jumps into it. # ec/ecdsa_i31_sign_raw.c, P-256's ECDSA (curves::p256::basic_keypair::sign with -# crypto::ecdsa_sha256, through its private signed_digest): whether the scalar decodes below n and +# crypto::signing_schemes::ecdsa_sha256, through its private signed_digest): whether the scalar decodes below n and # is not zero (lines 89 and 92), which webcpp has checked before, and RFC 6979's retry of a nonce # that is zero or not below n (lines 121 and 124), which libsecp256k1 marks public in its own # signing; br_i31_decode_mod, br_i31_iszero and br_i31_sub compute each verdict without a branch, diff --git a/test/constant_time/dudect_sodium_test.cpp b/test/constant_time/dudect_sodium_test.cpp index 0404bf0f..b6b922c3 100644 --- a/test/constant_time/dudect_sodium_test.cpp +++ b/test/constant_time/dudect_sodium_test.cpp @@ -155,7 +155,7 @@ int main(int argc, char** argv) { test::choose(which, generator, zero, secret_key); signer.emplace(*keypair::from_secret(secret_key)); }, - [&] { static_cast(signer->sign(crypto::eddsa, message)); }); + [&] { static_cast(signer->sign(crypto::signing_schemes::eddsa, message)); }); results.record( "ed25519_sign", "Ed25519 signing", sign_t, true, {{"secret_key", secret_key.data()}, {"message", message.data()}, {"object", &*signer}}); diff --git a/test/constant_time/dudect_test.cpp b/test/constant_time/dudect_test.cpp index 72ab1827..6ebe42ac 100644 --- a/test/constant_time/dudect_test.cpp +++ b/test/constant_time/dudect_test.cpp @@ -157,8 +157,8 @@ bool measure_p256(test::case_results& results, test::case_selection const& selec }; if (sign) { auto const sign_t = test::twice(p256_count, prepare, [&] { - static_cast( - pair->sign(webcpp::crypto::ecdsa_sha256, webcpp::crypto::prehashed{digest})); + static_cast(pair->sign(webcpp::crypto::signing_schemes::ecdsa_sha256, + webcpp::crypto::signing_schemes::prehashed{digest})); }); results.record("p256_sign", "p256 sign", sign_t, true, {{"digest", digest.data()}, {"scalar", scalar.data()}, {"object", &*pair}}); diff --git a/test/constant_time/paths.hpp b/test/constant_time/paths.hpp index 67239002..368cfa6a 100644 --- a/test/constant_time/paths.hpp +++ b/test/constant_time/paths.hpp @@ -242,9 +242,9 @@ int sodium_ed25519() { seed.fill(0x42); Checker::mark_secret(seed); auto const pair = crypto::curves::ed25519::basic_keypair::from_secret(seed); - auto const signature = pair->sign(crypto::eddsa, message); - auto const prehashed_signature = - pair->sign(crypto::eddsa_prehashed, crypto::prehashed{message}); + auto const signature = pair->sign(crypto::signing_schemes::eddsa, message); + auto const prehashed_signature = pair->sign(crypto::signing_schemes::eddsa_prehashed, + crypto::signing_schemes::prehashed{message}); auto const kept = pair->secret(); auto const converted = pair->to_x25519(); auto const converted_secret = @@ -533,12 +533,13 @@ int secp256k1_signing() { message_hash.fill(0x17); extra_entropy.fill(0x5a); Checker::mark_secret(extra_entropy); - crypto::prehashed const digest{message_hash}; - auto const schnorr = pair->sign(crypto::schnorr, message_hash, extra_entropy); - auto const drawn = pair->sign(crypto::schnorr, message_hash); - auto const recoverable = pair->sign(crypto::ecdsa_sha256_recoverable, digest); - auto const ethereum = pair->sign(crypto::ecdsa_keccak256_recoverable, message_hash); - auto const hedged = pair->sign(crypto::ecdsa_sha256, digest, extra_entropy); + crypto::signing_schemes::prehashed const digest{message_hash}; + auto const schnorr = pair->sign(crypto::signing_schemes::schnorr, message_hash, extra_entropy); + auto const drawn = pair->sign(crypto::signing_schemes::schnorr, message_hash); + auto const recoverable = pair->sign(crypto::signing_schemes::ecdsa_sha256_recoverable, digest); + auto const ethereum = + pair->sign(crypto::signing_schemes::ecdsa_keccak256_recoverable, message_hash); + auto const hedged = pair->sign(crypto::signing_schemes::ecdsa_sha256, digest, extra_entropy); std::array tweak_bytes{}; tweak_bytes.fill(0x24); auto const tweaked = pair->tweak_xonly(tweak_bytes); @@ -813,7 +814,8 @@ int bearssl_p256_sign() { } std::array digest{}; digest.fill(0x17); - auto const signature = pair->sign(crypto::ecdsa_sha256, crypto::prehashed{digest}); + auto const signature = pair->sign(crypto::signing_schemes::ecdsa_sha256, + crypto::signing_schemes::prehashed{digest}); if (!signature) { return check(false, "P-256's sign on BearSSL"); } diff --git a/test/convenience_header_test.cpp b/test/convenience_header_test.cpp index 73a9d740..913744fc 100644 --- a/test/convenience_header_test.cpp +++ b/test/convenience_header_test.cpp @@ -38,8 +38,8 @@ static_assert(webcpp::crypto::supports_v); +static_assert(std::is_same_v); int main() { std::array const zero{}; diff --git a/test/crypto_secp256k1_test.cpp b/test/crypto_secp256k1_test.cpp index 690ed680..4d60841f 100644 --- a/test/crypto_secp256k1_test.cpp +++ b/test/crypto_secp256k1_test.cpp @@ -24,13 +24,14 @@ namespace secp = webcpp::crypto::curves::secp256k1; static_assert(std::is_same_v); -static_assert(webcpp::crypto::can_sign>); static_assert( - webcpp::crypto::can_verify, std::array>); -static_assert(webcpp::crypto::can_verify, secp::public_key>); +static_assert(webcpp::crypto::can_verify, + secp::public_key>); static_assert(std::is_function_v)>); static_assert(std::is_function_v)>); static_assert(std::is_function_v)>); diff --git a/test/ed25519_sodium_test.cpp b/test/ed25519_sodium_test.cpp index dd7f47c2..010cde61 100644 --- a/test/ed25519_sodium_test.cpp +++ b/test/ed25519_sodium_test.cpp @@ -6,20 +6,21 @@ // Ed25519 on libsodium: RFC 8032 section 7.1's tests 1, 2, 3 and SHA(abc), each key pair made // from the RFC's secret key, its public key and signature the RFC's, signed with -// sign(crypto::eddsa, message) and accepted by crypto::verify(crypto::eddsa, signature, message, -// public_key), the key pair's typed public key or one made from the RFC's bytes, its policy and -// backend deduced and named; secret() gives the seed back, which makes the same key pair; -// public_key::from_bytes checks the size alone; the empty message; the arguments of the order -// before it (key, message, signature) refused as a signature; speccheck's small-order key refused -// under strict; the guards (a seed of 31 bytes, a moved-from key pair, a signature changed in one -// bit, keys of other sizes, and signatures of other sizes refused by -// ed25519::signature::from_bytes); a signature received as a std::vector, made into the type, -// verified by the key's verify and crypto::verify; generate() under the planted entropy source of -// the test seam WEBCPP_CRYPTO_DETAIL_TEST_ENTROPY, failing and answering; and the conversion to -// X25519, to_x25519() of the key pair and of its public key, member and free, equal to libsodium's -// crypto_sign_ed25519_sk_to_curve25519 and pk_to_curve25519, the converted key pair agreeing with -// an X25519 peer, and keys of small order or not canonical refused; the key pair's x25519_secret() -// and the free to_x25519_public, which to_x25519() replaced, are not public. +// sign(crypto::signing_schemes::eddsa, message) and accepted by +// crypto::verify(crypto::signing_schemes::eddsa, signature, message, public_key), the key pair's +// typed public key or one made from the RFC's bytes, its policy and backend deduced and named; +// secret() gives the seed back, which makes the same key pair; public_key::from_bytes checks the +// size alone; the empty message; the arguments of the order before it (key, message, signature) +// refused as a signature; speccheck's small-order key refused under strict; the guards (a seed of +// 31 bytes, a moved-from key pair, a signature changed in one bit, keys of other sizes, and +// signatures of other sizes refused by ed25519::signature::from_bytes); a signature received as a +// std::vector, made into the type, verified by the key's verify and crypto::verify; generate() +// under the planted entropy source of the test seam WEBCPP_CRYPTO_DETAIL_TEST_ENTROPY, failing and +// answering; and the conversion to X25519, to_x25519() of the key pair and of its public key, +// member and free, equal to libsodium's crypto_sign_ed25519_sk_to_curve25519 and pk_to_curve25519, +// the converted key pair agreeing with an X25519 peer, and keys of small order or not canonical +// refused; the key pair's x25519_secret() and the free to_x25519_public, which to_x25519() +// replaced, are not public. #include #include @@ -136,18 +137,21 @@ void rfc8032() { BOOST_TEST(public_key && std::ranges::equal(public_key->bytes(), expected_public_key)); auto const expected_key = ed25519::public_key::from_bytes(expected_public_key); BOOST_TEST(expected_key && public_key && *expected_key == *public_key); - auto const signature = key->sign(crypto::eddsa, message); + auto const signature = key->sign(crypto::signing_schemes::eddsa, message); BOOST_TEST(signature && std::ranges::equal(signature->bytes(), expected_signature)); if (!signature || !public_key || !expected_key) { continue; } // The default policy, and strict named, on the default backend and on libsodium named: // the explicit arguments pick Ed25519's verify, never P-256's or the catch-all. - BOOST_TEST(crypto::verify(crypto::eddsa, *signature, message, *public_key).has_value()); - BOOST_TEST((crypto::verify(crypto::eddsa, *signature, message, - *public_key, ed25519::strict) - .has_value())); - BOOST_TEST(crypto::verify(crypto::eddsa, typed(expected_signature), message, *expected_key) + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, *signature, message, *public_key) + .has_value()); + BOOST_TEST( + (crypto::verify(crypto::signing_schemes::eddsa, *signature, + message, *public_key, ed25519::strict) + .has_value())); + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, typed(expected_signature), + message, *expected_key) .has_value()); } } @@ -176,11 +180,12 @@ void guards() { // is what is tested BOOST_TEST(source.public_key().error() == crypto::error::invalid_state); BOOST_TEST(source.secret().error() == crypto::error::invalid_state); - BOOST_TEST(source.sign(crypto::eddsa, message).error() == crypto::error::invalid_state); + BOOST_TEST(source.sign(crypto::signing_schemes::eddsa, message).error() == + crypto::error::invalid_state); BOOST_TEST(source.to_x25519().error() == crypto::error::invalid_state); BOOST_TEST(crypto::to_x25519(source).error() == crypto::error::invalid_state); // NOLINTEND(bugprone-use-after-move,clang-analyzer-cplusplus.Move) - auto const signature = target.sign(crypto::eddsa, message); + auto const signature = target.sign(crypto::signing_schemes::eddsa, message); BOOST_TEST(signature && std::ranges::equal(signature->bytes(), test::from_hex(rfc8032_cases[1].signature))); @@ -212,13 +217,15 @@ void refusals() { {std::size_t{0}, std::size_t{31}, std::size_t{32}, std::size_t{63}}) { auto changed = good; changed[index] ^= 0x01U; - auto const refused = crypto::verify(crypto::eddsa, typed(changed), message, public_key); + auto const refused = + crypto::verify(crypto::signing_schemes::eddsa, typed(changed), message, public_key); BOOST_TEST(refused.has_error() && refused.error() == crypto::error::invalid_signature); } auto changed_message = message; changed_message[0] ^= 0x01U; - BOOST_TEST(crypto::verify(crypto::eddsa, typed(good), changed_message, public_key).error() == - crypto::error::invalid_signature); + BOOST_TEST( + crypto::verify(crypto::signing_schemes::eddsa, typed(good), changed_message, public_key) + .error() == crypto::error::invalid_signature); // A signature of another size is no signature: from_bytes refuses it, before any verify. BOOST_TEST(ed25519::signature::from_bytes(std::span(good).first(63)).error() == @@ -240,8 +247,9 @@ void signature_from_vector() { if (!BOOST_TEST(public_key.has_value()) || !BOOST_TEST(made.has_value())) { return; } - BOOST_TEST(public_key->verify(crypto::eddsa, *made, message).has_value()); - BOOST_TEST(crypto::verify(crypto::eddsa, *made, message, *public_key).has_value()); + BOOST_TEST(public_key->verify(crypto::signing_schemes::eddsa, *made, message).has_value()); + BOOST_TEST( + crypto::verify(crypto::signing_schemes::eddsa, *made, message, *public_key).has_value()); for (std::size_t const size : {std::size_t{63}, std::size_t{65}}) { auto resized = received; resized.resize(size); @@ -260,13 +268,16 @@ void old_order_fails_closed() { std::ranges::copy(test::from_hex(rfc8032_cases[1].public_key), key_bytes.begin()); std::array signature{}; std::ranges::copy(test::from_hex(rfc8032_cases[1].signature), signature.begin()); - static_assert(!crypto::detail::has_verifier_v>); + static_assert(!crypto::detail::has_verifier_v>); auto const public_key = ed25519::public_key::from_bytes(key_bytes); BOOST_TEST(public_key.has_value()); if (!public_key) { return; } - BOOST_TEST(crypto::verify(crypto::eddsa, typed(signature), message, *public_key).has_value()); + BOOST_TEST( + crypto::verify(crypto::signing_schemes::eddsa, typed(signature), message, *public_key) + .has_value()); auto const swapped = ed25519::signature::from_bytes(key_bytes); BOOST_TEST(swapped.has_error() && swapped.error() == crypto::error::invalid_signature); } @@ -309,8 +320,8 @@ void secret_round_trip() { auto const again = ed25519::keypair::from_secret(exported->bytes()); BOOST_TEST(again && *again->public_key() == *key->public_key()); auto const message = test::from_hex(tested.message); - BOOST_TEST(again && - *again->sign(crypto::eddsa, message) == *key->sign(crypto::eddsa, message)); + BOOST_TEST(again && *again->sign(crypto::signing_schemes::eddsa, message) == + *key->sign(crypto::signing_schemes::eddsa, message)); } } @@ -323,18 +334,20 @@ void empty_message() { return; } auto const public_key = key->public_key(); - auto const signature = key->sign(crypto::eddsa, std::span{}); + auto const signature = + key->sign(crypto::signing_schemes::eddsa, std::span{}); BOOST_TEST(public_key && signature && std::ranges::equal(signature->bytes(), test::from_hex(rfc8032_cases[0].signature))); if (!public_key || !signature) { return; } - BOOST_TEST( - crypto::verify(crypto::eddsa, *signature, std::span{}, *public_key) - .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, *signature, + std::span{}, *public_key) + .has_value()); std::array const one_byte{}; - BOOST_TEST(crypto::verify(crypto::eddsa, *signature, one_byte, *public_key).error() == - crypto::error::invalid_signature); + BOOST_TEST( + crypto::verify(crypto::signing_schemes::eddsa, *signature, one_byte, *public_key).error() == + crypto::error::invalid_signature); } // ed25519-speccheck's case 0 (Chalkias, Garillot and Nikolaenko; Wycheproof's EdDSA file has no @@ -354,8 +367,8 @@ void small_order_key() { if (!key) { return; } - auto const refused = crypto::verify(crypto::eddsa, typed(signature), - message, *key, ed25519::strict); + auto const refused = crypto::verify( + crypto::signing_schemes::eddsa, typed(signature), message, *key, ed25519::strict); BOOST_TEST(refused.has_error() && refused.error() == crypto::error::invalid_signature); } @@ -535,43 +548,50 @@ int main() { std::is_nothrow_move_assignable_v); // An Ed25519 key pair signs a message with eddsa, never a digest, nor with another scheme; // its typed public key verifies eddsa, and bytes do not (design R17). - static_assert(crypto::can_sign>); - static_assert(!crypto::can_sign>); - static_assert( - !crypto::can_sign>); - static_assert(crypto::can_verify, - ed25519::public_key>); - static_assert(!crypto::can_verify, - ed25519::public_key>); - static_assert(!crypto::can_verify>); + static_assert(!crypto::can_sign>); + static_assert(!crypto::can_sign>); + static_assert(crypto::can_verify, ed25519::public_key>); + static_assert(!crypto::can_verify, ed25519::public_key>); + static_assert(!crypto::can_verify, std::array>); // The signature is the type: bytes are none (design R1), nor another curve's signature. - static_assert(!crypto::can_verify, - std::vector, ed25519::public_key>); - static_assert(!crypto::can_verify, + static_assert( + !crypto::can_verify, + std::vector, ed25519::public_key>); + static_assert(!crypto::can_verify, std::vector, ed25519::public_key>); // Bytes never sign, whatever their size, and a key pair is no public key: it verifies // nothing, its public key does. - static_assert(!crypto::can_sign, crypto::eddsa_t, + static_assert(!crypto::can_sign, crypto::signing_schemes::eddsa_t, std::span>); - static_assert(!crypto::can_sign, crypto::eddsa_t, + static_assert(!crypto::can_sign, crypto::signing_schemes::eddsa_t, std::span>); - static_assert(!crypto::can_verify, ed25519::keypair>); - static_assert( - crypto::can_sign>); - static_assert(crypto::can_verify>); + static_assert(crypto::can_verify, ed25519::public_key const&>); static_assert(std::is_same_v().sign( - crypto::eddsa, std::declval>())), + crypto::signing_schemes::eddsa, + std::declval>())), boost::system::result>); // The typed key verifies eddsa through Ed25519's crypto::verify, so the catch-all steps aside; // bytes are no key under any scheme, and the catch-all refuses them. - static_assert(crypto::detail::has_verifier_v); - static_assert(!crypto::detail::has_verifier_v>); - static_assert(!crypto::detail::has_verifier_v>); static_assert( - !crypto::detail::has_verifier_v>); + crypto::detail::has_verifier_v); + static_assert(!crypto::detail::has_verifier_v>); + static_assert(!crypto::detail::has_verifier_v>); + static_assert(!crypto::detail::has_verifier_v>); static_assert(std::is_void_v>::type>); static_assert(std::is_void_v::type>); static_assert(std::is_same_v::type, diff --git a/test/ed25519_speccheck_test.cpp b/test/ed25519_speccheck_test.cpp index f51ab563..968ac0fe 100644 --- a/test/ed25519_speccheck_test.cpp +++ b/test/ed25519_speccheck_test.cpp @@ -7,12 +7,12 @@ // The twelve Ed25519 edge cases of Chalkias, Garillot and Nikolaenko, "Taming the many EdDSAs" // (2020), novifinancial/ed25519-speccheck's cases.json, against every Ed25519 backend linked // (design D31): each backend's raw verdict, its own library called directly, and the verdict of -// crypto::verify(crypto::eddsa, ..., strict), compared with the verdicts committed in -// meta/ed25519_cases.json. Under strict every backend gives libsodium's verdicts. On Emscripten, -// node's WebCrypto verify (Ed25519) gives the row webcrypto-node, an outside view that is compared -// with its committed row but never with strict's. A pin move that changes a verdict fails here -// until the data and the page are regenerated. Each row is printed, so that a first run gives -// the data to review. +// crypto::verify(crypto::signing_schemes::eddsa, ..., strict), compared with the verdicts +// committed in meta/ed25519_cases.json. Under strict every backend gives libsodium's verdicts. On +// Emscripten, node's WebCrypto verify (Ed25519) gives the row webcrypto-node, an outside view that +// is compared with its committed row but never with strict's. A pin move that changes a verdict +// fails here until the data and the page are regenerated. Each row is printed, so that a first run +// gives the data to review. #include #include @@ -169,7 +169,7 @@ void compare(std::string const& label, verdicts const& computed, verdicts const& } // libsodium's raw verdicts, crypto_sign_ed25519_verify_detached called directly, and strict's, -// crypto::verify(crypto::eddsa, ..., strict), whose refusal is +// crypto::verify(crypto::signing_schemes::eddsa, ..., strict), whose refusal is // invalid_signature. void sodium_rows(std::vector const& cases, verdicts& raw, verdicts& strict) { for (auto const& tested : cases) { @@ -190,8 +190,9 @@ void sodium_rows(std::vector const& cases, verdicts& raw, verdicts& s strict.emplace_back(verdict(false)); continue; } - auto const verified = crypto::verify( - crypto::eddsa, *signature, tested.message, *public_key, ed25519::strict); + auto const verified = + crypto::verify(crypto::signing_schemes::eddsa, *signature, + tested.message, *public_key, ed25519::strict); if (!verified) { BOOST_TEST(verified.error() == crypto::error::invalid_signature); } diff --git a/test/ed25519_wycheproof_sodium_test.cpp b/test/ed25519_wycheproof_sodium_test.cpp index a3d0698d..09b88d49 100644 --- a/test/ed25519_wycheproof_sodium_test.cpp +++ b/test/ed25519_wycheproof_sodium_test.cpp @@ -5,9 +5,9 @@ // https://www.boost.org/LICENSE_1_0.txt) // Ed25519 against Wycheproof's EdDSA file (testvectors_v1/ed25519_test.json) through -// crypto::verify(crypto::eddsa, ...) on libsodium, strict: every valid case accepted and every -// invalid case refused with invalid_signature, without exception (a disagreement is reported, never -// listed away). +// crypto::verify(crypto::signing_schemes::eddsa, ...) on libsodium, strict: every valid case +// accepted and every invalid case refused with invalid_signature, without exception (a disagreement +// is reported, never listed away). #include #include @@ -47,7 +47,7 @@ boost::system::result verified_case(std::span signatur if (!made) { return made.error(); } - return crypto::verify(crypto::eddsa, *made, message, public_key); + return crypto::verify(crypto::signing_schemes::eddsa, *made, message, public_key); } } // namespace diff --git a/test/ed25519ph_sodium_test.cpp b/test/ed25519ph_sodium_test.cpp index 7af07202..1ad4ce13 100644 --- a/test/ed25519ph_sodium_test.cpp +++ b/test/ed25519ph_sodium_test.cpp @@ -4,22 +4,24 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// Ed25519ph on libsodium, the scheme crypto::eddsa_prehashed and the streaming signer -// curves::ed25519::prehashed_signer: +// Ed25519ph on libsodium, the scheme crypto::signing_schemes::eddsa_prehashed and the streaming +// signer curves::ed25519::prehashed_signer: // - rfc8032_ph: RFC 8032 section 7.3's test, the message "abc" given to the signer in one piece and // in two, signed into the RFC's signature, a curves::ed25519::signature, and verified with // verify(signature, public_key), the signature first, of that type, and the key a // curves::ed25519::public_key; the key's bytes, and 63 bytes, refused as a signature by // from_bytes; a signature changed in one bit and a different message refused. -// - rfc8032_ph_scheme: the same key pair signs crypto::prehashed{sha512("abc")} with -// sign(crypto::eddsa_prehashed, ...) into the RFC's signature, which crypto::verify and the -// key's verify accept under the scheme; a flipped byte of the signature or of the digest is -// invalid_signature. +// - rfc8032_ph_scheme: the same key pair signs crypto::signing_schemes::prehashed{sha512("abc")} +// with +// sign(crypto::signing_schemes::eddsa_prehashed, ...) into the RFC's signature, which +// crypto::verify and the key's verify accept under the scheme; a flipped byte of the signature or +// of the digest is invalid_signature. // - streaming_equals_scheme: for messages of 0, 1, 64 and 1000 bytes, given whole and in pieces // of 1 and of 7 bytes, the signer's signature is the scheme's of the message's SHA-512, and each // verifies the other's. -// - not_interchangeable: an Ed25519ph signature does not verify under crypto::eddsa, nor an -// Ed25519 one under crypto::eddsa_prehashed. +// - not_interchangeable: an Ed25519ph signature does not verify under +// crypto::signing_schemes::eddsa, nor an +// Ed25519 one under crypto::signing_schemes::eddsa_prehashed. // - typed: the scheme's and the signer's results are curves::ed25519::signature; can_sign takes // a 64-byte marker alone, and only with an Ed25519 key pair. // - moved_from: a moved-from key pair signs nothing under the scheme (invalid_state). @@ -140,7 +142,7 @@ void rfc8032_ph() { BOOST_TEST(other.verify(expected, public_key).error() == crypto::error::invalid_signature); // Ed25519ph's signature is not Ed25519's of the same message. - BOOST_TEST(crypto::verify(crypto::eddsa, expected, abc, public_key).error() == + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, expected, abc, public_key).error() == crypto::error::invalid_signature); // The arguments in the other order, (public_key, signature): the key's 32 bytes are no @@ -204,38 +206,44 @@ void rfc8032_ph_scheme() { auto const expected = rfc_signature(); std::array const abc{0x61, 0x62, 0x63}; auto const digest = sha512(abc); - crypto::prehashed const marker{digest}; + crypto::signing_schemes::prehashed const marker{digest}; - auto const signature = key.sign(crypto::eddsa_prehashed, marker); + auto const signature = key.sign(crypto::signing_schemes::eddsa_prehashed, marker); BOOST_TEST(signature && *signature == expected); - auto const signed_free = crypto::sign(key, crypto::eddsa_prehashed, marker); + auto const signed_free = crypto::sign(key, crypto::signing_schemes::eddsa_prehashed, marker); BOOST_TEST(signed_free && *signed_free == expected); - BOOST_TEST(crypto::verify(crypto::eddsa_prehashed, expected, marker, public_key).has_value()); - BOOST_TEST(public_key.verify(crypto::eddsa_prehashed, expected, marker).has_value()); - BOOST_TEST(crypto::verify(crypto::eddsa_prehashed, expected, marker, - public_key, ed25519::strict) + BOOST_TEST( + crypto::verify(crypto::signing_schemes::eddsa_prehashed, expected, marker, public_key) + .has_value()); + BOOST_TEST( + public_key.verify(crypto::signing_schemes::eddsa_prehashed, expected, marker).has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa_prehashed, + expected, marker, public_key, + ed25519::strict) .has_value()); BOOST_TEST(public_key - .verify(crypto::eddsa_prehashed, expected, marker, - ed25519::strict) + .verify(crypto::signing_schemes::eddsa_prehashed, + expected, marker, ed25519::strict) .has_value()); // A flipped byte of the signature, and of the digest, are refused. auto changed_signature = test::from_hex(signature_hex); changed_signature[5] ^= 0x01U; auto const changed = ed25519::signature::from_bytes(changed_signature).value(); - BOOST_TEST(crypto::verify(crypto::eddsa_prehashed, changed, marker, public_key).error() == - crypto::error::invalid_signature); - BOOST_TEST(public_key.verify(crypto::eddsa_prehashed, changed, marker).error() == - crypto::error::invalid_signature); + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa_prehashed, changed, marker, public_key) + .error() == crypto::error::invalid_signature); + BOOST_TEST( + public_key.verify(crypto::signing_schemes::eddsa_prehashed, changed, marker).error() == + crypto::error::invalid_signature); auto changed_digest = digest; changed_digest[0] ^= 0x01U; - BOOST_TEST(crypto::verify(crypto::eddsa_prehashed, expected, crypto::prehashed{changed_digest}, - public_key) + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa_prehashed, expected, + crypto::signing_schemes::prehashed{changed_digest}, public_key) + .error() == crypto::error::invalid_signature); + BOOST_TEST(public_key + .verify(crypto::signing_schemes::eddsa_prehashed, expected, + crypto::signing_schemes::prehashed{changed_digest}) .error() == crypto::error::invalid_signature); - BOOST_TEST( - public_key.verify(crypto::eddsa_prehashed, expected, crypto::prehashed{changed_digest}) - .error() == crypto::error::invalid_signature); } /** The message in pieces of `piece_size` bytes, the last one shorter. */ @@ -260,7 +268,8 @@ void streaming_equals_scheme() { message[index] = static_cast((index * 31U) + 7U); } auto const digest = sha512(message); - auto const scheme_signature = key.sign(crypto::eddsa_prehashed, crypto::prehashed{digest}); + auto const scheme_signature = key.sign(crypto::signing_schemes::eddsa_prehashed, + crypto::signing_schemes::prehashed{digest}); if (!BOOST_TEST(scheme_signature.has_value())) { continue; } @@ -276,8 +285,8 @@ void streaming_equals_scheme() { auto verifying = begun(pieces); BOOST_TEST(verifying.verify(*scheme_signature, public_key).has_value()); if (streamed) { - BOOST_TEST(crypto::verify(crypto::eddsa_prehashed, *streamed, - crypto::prehashed{digest}, public_key) + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa_prehashed, *streamed, + crypto::signing_schemes::prehashed{digest}, public_key) .has_value()); } } @@ -288,48 +297,59 @@ void not_interchangeable() { auto const key = rfc_key(); auto const public_key = rfc_public_key(); std::array const abc{0x61, 0x62, 0x63}; - auto const prehashed_signature_value = - key.sign(crypto::eddsa_prehashed, crypto::prehashed{sha512(abc)}).value(); - BOOST_TEST(crypto::verify(crypto::eddsa, prehashed_signature_value, abc, public_key).error() == - crypto::error::invalid_signature); - BOOST_TEST(crypto::verify(crypto::eddsa_prehashed, key.sign(crypto::eddsa, abc).value(), - crypto::prehashed{sha512(abc)}, public_key) + auto const prehashed_signature_value = key.sign(crypto::signing_schemes::eddsa_prehashed, + crypto::signing_schemes::prehashed{sha512(abc)}) + .value(); + BOOST_TEST( + crypto::verify(crypto::signing_schemes::eddsa, prehashed_signature_value, abc, public_key) + .error() == crypto::error::invalid_signature); + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa_prehashed, + key.sign(crypto::signing_schemes::eddsa, abc).value(), + crypto::signing_schemes::prehashed{sha512(abc)}, public_key) .error() == crypto::error::invalid_signature); } void typed() { auto const key = rfc_key(); std::array const digest{}; - crypto::prehashed const marker{digest}; - static_assert(std::is_same_v>); + crypto::signing_schemes::prehashed const marker{digest}; + static_assert( + std::is_same_v>); static_assert(std::is_same_v().sign(key)), boost::system::result>); static_assert( - std::is_same_v, + std::is_same_v, ed25519::signature>); - static_assert(std::is_same_v< - crypto::detail::signature_of_t, - ed25519::signature>); static_assert( - crypto::can_sign>); - static_assert(!crypto::can_sign, + ed25519::signature>); + static_assert(crypto::can_sign>); + static_assert(!crypto::can_sign>); - static_assert(!crypto::can_sign); + static_assert(!crypto::can_sign); + static_assert(!crypto::can_sign>); static_assert( - !crypto::can_sign>); - static_assert(!crypto::can_sign>); - static_assert(!crypto::can_sign>); - static_assert(crypto::can_verify, ed25519::public_key>); - static_assert(!crypto::can_verify); - static_assert(crypto::detail::has_verifier_v); + !crypto::can_sign>); + static_assert(!crypto::can_sign>); + static_assert(crypto::can_verify, ed25519::public_key>); + static_assert(!crypto::can_verify); + static_assert(crypto::detail::has_verifier_v); // eddsa still takes no marker. - static_assert(!crypto::can_sign>); - BOOST_TEST(key.sign(crypto::eddsa_prehashed, marker).has_value()); + static_assert(!crypto::can_sign>); + BOOST_TEST(key.sign(crypto::signing_schemes::eddsa_prehashed, marker).has_value()); } void moved_from() { @@ -337,9 +357,13 @@ void moved_from() { ed25519::keypair const taken = std::move(key); std::array const digest{}; // NOLINTNEXTLINE(bugprone-use-after-move,clang-analyzer-cplusplus.Move): tested - BOOST_TEST(key.sign(crypto::eddsa_prehashed, crypto::prehashed{digest}).error() == - crypto::error::invalid_state); - BOOST_TEST(taken.sign(crypto::eddsa_prehashed, crypto::prehashed{digest}).has_value()); + BOOST_TEST(key.sign(crypto::signing_schemes::eddsa_prehashed, + crypto::signing_schemes::prehashed{digest}) + .error() == crypto::error::invalid_state); + BOOST_TEST(taken + .sign(crypto::signing_schemes::eddsa_prehashed, + crypto::signing_schemes::prehashed{digest}) + .has_value()); } } // namespace diff --git a/test/formats_25519_sodium_test.cpp b/test/formats_25519_sodium_test.cpp index 3f57f2c9..71eb9c5a 100644 --- a/test/formats_25519_sodium_test.cpp +++ b/test/formats_25519_sodium_test.cpp @@ -271,8 +271,8 @@ void ed25519_round_trip() { BOOST_TEST(decoded.has_value()); if (decoded) { BOOST_TEST(decoded->public_key().has_value() && *decoded->public_key() == *public_key); - auto const signed_again = decoded->sign(crypto::eddsa, message); - auto const signed_first = pair->sign(crypto::eddsa, message); + auto const signed_again = decoded->sign(crypto::signing_schemes::eddsa, message); + auto const signed_first = pair->sign(crypto::signing_schemes::eddsa, message); BOOST_TEST(signed_again.has_value() && signed_first.has_value() && *signed_again == *signed_first); } diff --git a/test/formats_25519_webcrypto_oracle_test.cpp b/test/formats_25519_webcrypto_oracle_test.cpp index 75092c4c..25c45ee3 100644 --- a/test/formats_25519_webcrypto_oracle_test.cpp +++ b/test/formats_25519_webcrypto_oracle_test.cpp @@ -155,7 +155,7 @@ void ed25519_through_webcrypto(std::mt19937_64& generator) { continue; } auto const public_key = pair->public_key(); - auto const signature = pair->sign(crypto::eddsa, message); + auto const signature = pair->sign(crypto::signing_schemes::eddsa, message); if (!BOOST_TEST(public_key.has_value() && signature.has_value())) { static_cast(std::fprintf(stderr, "Ed25519 key pair failed: seed %s\n", test::to_hex(seed_bytes).c_str())); @@ -194,7 +194,7 @@ void ed25519_from_webcrypto() { continue; } auto const its_public = pair->public_key(); - auto const signature = pair->sign(crypto::eddsa, message); + auto const signature = pair->sign(crypto::signing_schemes::eddsa, message); if (!BOOST_TEST(its_public.has_value() && signature.has_value())) { continue; } diff --git a/test/keypair_test.cpp b/test/keypair_test.cpp index b4f2f79d..066f185a 100644 --- a/test/keypair_test.cpp +++ b/test/keypair_test.cpp @@ -63,7 +63,7 @@ struct complete_keypair { [[nodiscard]] boost::system::result public_key() const noexcept; [[nodiscard]] boost::system::result> secret() const noexcept; [[nodiscard]] boost::system::result sign( - crypto::ecdsa_sha256_t, std::span) const noexcept; + crypto::signing_schemes::ecdsa_sha256_t, std::span) const noexcept; }; // Every member of keypair and an agree with its own public key type: it agrees alone. @@ -89,7 +89,7 @@ struct signing_and_agreeing_keypair { [[nodiscard]] boost::system::result public_key() const noexcept; [[nodiscard]] boost::system::result> secret() const noexcept; [[nodiscard]] boost::system::result sign( - crypto::ecdsa_sha256_t, std::span) const noexcept; + crypto::signing_schemes::ecdsa_sha256_t, std::span) const noexcept; [[nodiscard]] boost::system::result> agree( stand_in_public_key const&) const noexcept; }; @@ -104,7 +104,7 @@ struct byte_sign_keypair { [[nodiscard]] boost::system::result public_key() const noexcept; [[nodiscard]] boost::system::result> secret() const noexcept; [[nodiscard]] boost::system::result> sign( - crypto::ecdsa_sha256_t, std::span) const noexcept; + crypto::signing_schemes::ecdsa_sha256_t, std::span) const noexcept; }; // An agree that gives bytes, not a secret. @@ -142,7 +142,7 @@ struct no_secret_keypair { static boost::system::result generate() noexcept; [[nodiscard]] boost::system::result public_key() const noexcept; [[nodiscard]] boost::system::result sign( - crypto::ecdsa_sha256_t, std::span) const noexcept; + crypto::signing_schemes::ecdsa_sha256_t, std::span) const noexcept; }; // A secret() of a size other than secret_key_size. @@ -155,7 +155,7 @@ struct wrong_secret_keypair { [[nodiscard]] boost::system::result public_key() const noexcept; [[nodiscard]] boost::system::result> secret() const noexcept; [[nodiscard]] boost::system::result sign( - crypto::ecdsa_sha256_t, std::span) const noexcept; + crypto::signing_schemes::ecdsa_sha256_t, std::span) const noexcept; }; // A public_key() that gives bytes, not public_key_type. @@ -168,7 +168,7 @@ struct byte_public_keypair { [[nodiscard]] boost::system::result> public_key() const noexcept; [[nodiscard]] boost::system::result> secret() const noexcept; [[nodiscard]] boost::system::result sign( - crypto::ecdsa_sha256_t, std::span) const noexcept; + crypto::signing_schemes::ecdsa_sha256_t, std::span) const noexcept; }; // No generate(). @@ -180,7 +180,7 @@ struct no_generate_keypair { [[nodiscard]] boost::system::result public_key() const noexcept; [[nodiscard]] boost::system::result> secret() const noexcept; [[nodiscard]] boost::system::result sign( - crypto::ecdsa_sha256_t, std::span) const noexcept; + crypto::signing_schemes::ecdsa_sha256_t, std::span) const noexcept; }; // Every member, but its curve declares no scheme for it: a keypair that does nothing. @@ -193,7 +193,7 @@ struct no_scheme_keypair { [[nodiscard]] boost::system::result public_key() const noexcept; [[nodiscard]] boost::system::result> secret() const noexcept; [[nodiscard]] boost::system::result sign( - crypto::ecdsa_sha256_t, std::span) const noexcept; + crypto::signing_schemes::ecdsa_sha256_t, std::span) const noexcept; }; // Its curve declares schnorr too, which it does not sign. @@ -206,7 +206,7 @@ struct unsigned_scheme_keypair { [[nodiscard]] boost::system::result public_key() const noexcept; [[nodiscard]] boost::system::result> secret() const noexcept; [[nodiscard]] boost::system::result sign( - crypto::ecdsa_sha256_t, std::span) const noexcept; + crypto::signing_schemes::ecdsa_sha256_t, std::span) const noexcept; }; // No from_secret(), though it signs and agrees. @@ -217,7 +217,7 @@ struct no_from_secret_keypair { [[nodiscard]] boost::system::result public_key() const noexcept; [[nodiscard]] boost::system::result> secret() const noexcept; [[nodiscard]] boost::system::result sign( - crypto::ecdsa_sha256_t, std::span) const noexcept; + crypto::signing_schemes::ecdsa_sha256_t, std::span) const noexcept; [[nodiscard]] boost::system::result> agree( stand_in_public_key const&) const noexcept; }; @@ -231,7 +231,7 @@ struct no_public_key_type_keypair { [[nodiscard]] boost::system::result public_key() const noexcept; [[nodiscard]] boost::system::result> secret() const noexcept; [[nodiscard]] boost::system::result sign( - crypto::ecdsa_sha256_t, std::span) const noexcept; + crypto::signing_schemes::ecdsa_sha256_t, std::span) const noexcept; }; // A generate() that gives something other than result. @@ -244,7 +244,7 @@ struct wrong_generate_keypair { [[nodiscard]] boost::system::result public_key() const noexcept; [[nodiscard]] boost::system::result> secret() const noexcept; [[nodiscard]] boost::system::result sign( - crypto::ecdsa_sha256_t, std::span) const noexcept; + crypto::signing_schemes::ecdsa_sha256_t, std::span) const noexcept; }; // A from_secret() that gives the key pair itself, not result. @@ -256,7 +256,7 @@ struct wrong_from_secret_keypair { [[nodiscard]] boost::system::result public_key() const noexcept; [[nodiscard]] boost::system::result> secret() const noexcept; [[nodiscard]] boost::system::result sign( - crypto::ecdsa_sha256_t, std::span) const noexcept; + crypto::signing_schemes::ecdsa_sha256_t, std::span) const noexcept; }; // A scheme of this test alone, which no curve has. @@ -274,7 +274,7 @@ struct unsigned_test_scheme_keypair { [[nodiscard]] boost::system::result public_key() const noexcept; [[nodiscard]] boost::system::result> secret() const noexcept; [[nodiscard]] boost::system::result sign( - crypto::ecdsa_sha256_t, std::span) const noexcept; + crypto::signing_schemes::ecdsa_sha256_t, std::span) const noexcept; }; // Every member, and the test scheme declared with ecdsa_sha256 and signed. @@ -287,7 +287,7 @@ struct test_scheme_keypair { [[nodiscard]] boost::system::result public_key() const noexcept; [[nodiscard]] boost::system::result> secret() const noexcept; [[nodiscard]] boost::system::result sign( - crypto::ecdsa_sha256_t, std::span) const noexcept; + crypto::signing_schemes::ecdsa_sha256_t, std::span) const noexcept; [[nodiscard]] boost::system::result sign( test_scheme_t, std::span) const noexcept; }; @@ -327,37 +327,41 @@ constexpr bool is_stand_in_v = namespace webcpp::crypto::detail { template <> -inline constexpr bool signs_with_v = true; +inline constexpr bool signs_with_v = true; template <> -inline constexpr bool signs_with_v = true; +inline constexpr bool signs_with_v = + true; template <> -inline constexpr bool signs_with_v = true; +inline constexpr bool signs_with_v = true; template <> -inline constexpr bool signs_with_v = true; +inline constexpr bool signs_with_v = true; template <> -inline constexpr bool signs_with_v = true; +inline constexpr bool signs_with_v = true; template <> -inline constexpr bool signs_with_v = true; +inline constexpr bool signs_with_v = true; template <> -inline constexpr bool signs_with_v = true; +inline constexpr bool signs_with_v = true; template <> -inline constexpr bool signs_with_v = true; +inline constexpr bool signs_with_v = true; template <> -inline constexpr bool signs_with_v = true; +inline constexpr bool signs_with_v = true; template <> -inline constexpr bool signs_with_v = true; +inline constexpr bool signs_with_v = true; template <> -inline constexpr bool signs_with_v = true; +inline constexpr bool signs_with_v = + true; template <> -inline constexpr bool signs_with_v = true; +inline constexpr bool signs_with_v = true; template <> -inline constexpr bool signs_with_v = true; +inline constexpr bool signs_with_v = + true; template <> -inline constexpr bool signs_with_v = true; +inline constexpr bool signs_with_v = + true; template <> inline constexpr bool signs_with_v = true; template <> -inline constexpr bool signs_with_v = true; +inline constexpr bool signs_with_v = true; template <> inline constexpr bool signs_with_v = true; template <> @@ -478,20 +482,23 @@ static_assert( static_assert(crypto::detail::signing_keypair_over); // A type that is not a list of schemes asks for a scheme that none is. static_assert(!crypto::detail::signing_keypair_over); -static_assert( - !crypto::detail::signing_keypair_over>); +static_assert(!crypto::detail::signing_keypair_over< + complete_keypair, std::tuple>); // The curves' key pairs, on each backend this test links: D4's table. using ed25519_pair = crypto::curves::ed25519::basic_keypair; using x25519_pair = crypto::curves::x25519::basic_keypair; using p256_pair = crypto::curves::p256::basic_keypair; using secp256k1_pair = crypto::curves::secp256k1::basic_keypair; -static_assert(std::is_same_v, - crypto::curves::ed25519::signature>); -static_assert(std::is_same_v, - crypto::curves::p256::ecdsa_signature>); -static_assert(std::is_same_v, - crypto::curves::secp256k1::schnorr_signature>); +static_assert( + std::is_same_v, + crypto::curves::ed25519::signature>); +static_assert(std::is_same_v< + crypto::detail::signature_of_t, + crypto::curves::p256::ecdsa_signature>); +static_assert(std::is_same_v< + crypto::detail::signature_of_t, + crypto::curves::secp256k1::schnorr_signature>); static_assert(crypto::keypair); static_assert(crypto::signing_keypair); static_assert(!crypto::agreement_keypair); @@ -549,10 +556,11 @@ void prehashed_round_trip() { BOOST_TEST(again.has_value()); std::array digest{}; digest.fill(0x5a); - auto const signature = again->sign(crypto::eddsa_prehashed, crypto::prehashed{digest}); + auto const signature = again->sign(crypto::signing_schemes::eddsa_prehashed, + crypto::signing_schemes::prehashed{digest}); BOOST_TEST(signature.has_value()); - BOOST_TEST(crypto::verify(crypto::eddsa_prehashed, *signature, crypto::prehashed{digest}, - *key->public_key()) + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa_prehashed, *signature, + crypto::signing_schemes::prehashed{digest}, *key->public_key()) .has_value()); } @@ -584,10 +592,10 @@ void recovered_round_trip(Scheme scheme) { BOOST_TEST(again.has_value()); std::array digest{}; digest.fill(0x3c); - auto const signature = again->sign(scheme, crypto::prehashed{digest}); + auto const signature = again->sign(scheme, crypto::signing_schemes::prehashed{digest}); BOOST_TEST(signature.has_value()); - auto const recovered = - crypto::curves::secp256k1::recover(scheme, *signature, crypto::prehashed{digest}); + auto const recovered = crypto::curves::secp256k1::recover( + scheme, *signature, crypto::signing_schemes::prehashed{digest}); BOOST_TEST(recovered.has_value() && *recovered == *key->public_key()); } @@ -611,13 +619,13 @@ int main() { from_secret_round_trip(); from_secret_round_trip(); from_secret_round_trip(); - signing_round_trip(crypto::eddsa); + signing_round_trip(crypto::signing_schemes::eddsa); prehashed_round_trip(); - signing_round_trip(crypto::ecdsa_sha256); - signing_round_trip(crypto::ecdsa_sha256); - signing_round_trip(crypto::schnorr); - recovered_round_trip(crypto::ecdsa_sha256_recoverable); - recovered_round_trip(crypto::ecdsa_keccak256_recoverable); + signing_round_trip(crypto::signing_schemes::ecdsa_sha256); + signing_round_trip(crypto::signing_schemes::ecdsa_sha256); + signing_round_trip(crypto::signing_schemes::schnorr); + recovered_round_trip(crypto::signing_schemes::ecdsa_sha256_recoverable); + recovered_round_trip(crypto::signing_schemes::ecdsa_keccak256_recoverable); agreement_round_trip(); agreement_round_trip(); agreement_round_trip(); diff --git a/test/messages/Jamfile b/test/messages/Jamfile index abd348cb..ebd6feb4 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -80,6 +80,7 @@ build-project p256_on_sodium ; build-project aes_block_default_not_linked ; build-project aes_block_default_not_linked_wasm ; build-project prehashed_dynamic ; +build-project scheme_in_crypto_namespace ; build-project sign_p256_schnorr ; build-project sign_p256_digest_48 ; build-project sign_secp256k1_recoverable_digest_48 ; diff --git a/test/messages/async_member_without_async_hpp/async_member_without_async_hpp.cpp b/test/messages/async_member_without_async_hpp/async_member_without_async_hpp.cpp index 091dd48b..03911634 100644 --- a/test/messages/async_member_without_async_hpp/async_member_without_async_hpp.cpp +++ b/test/messages/async_member_without_async_hpp/async_member_without_async_hpp.cpp @@ -29,11 +29,11 @@ int main() { std::array const scalar{1}; std::array const message{'h', 'e', 'l', 'l', 'o'}; auto const made = crypto::curves::p256::keypair::from_secret(scalar); - if (!made || !made->sign(crypto::ecdsa_sha256, message)) { + if (!made || !made->sign(crypto::signing_schemes::ecdsa_sha256, message)) { return 1; } webcpp::asio::io_context context; - made->async_sign(context.get_executor(), crypto::ecdsa_sha256, message, + made->async_sign(context.get_executor(), crypto::signing_schemes::ecdsa_sha256, message, [](boost::system::error_code, std::array) {}); return 0; } diff --git a/test/messages/async_sign_ed25519_prehashed/async_sign_ed25519_prehashed.cpp b/test/messages/async_sign_ed25519_prehashed/async_sign_ed25519_prehashed.cpp index b471ee78..8933ec58 100644 --- a/test/messages/async_sign_ed25519_prehashed/async_sign_ed25519_prehashed.cpp +++ b/test/messages/async_sign_ed25519_prehashed/async_sign_ed25519_prehashed.cpp @@ -4,14 +4,15 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// async_sign of an Ed25519 key pair given a digest marked as one, crypto::prehashed{digest}, with -// crypto::eddsa stops at the input's check, as the synchronous sign does: pure Ed25519 signs the -// message itself, and the text names crypto::eddsa_prehashed (Ed25519ph); with that error alone. +// async_sign of an Ed25519 key pair given a digest marked as one, +// crypto::signing_schemes::prehashed{digest}, with crypto::signing_schemes::eddsa stops at the +// input's check, as the synchronous sign does: pure Ed25519 signs the message itself, and the text +// names crypto::signing_schemes::eddsa_prehashed (Ed25519ph); with that error alone. // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/signing.hpp:* {{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).}} +// expected-error@webcpp/crypto/signing.hpp:* {{webcpp::crypto: crypto::signing_schemes::eddsa signs the message itself (RFC 8032's pure Ed25519) and takes no digest; a message's SHA-512 is signed with crypto::signing_schemes::eddsa_prehashed (Ed25519ph).}} // clang-format on #include #include @@ -33,7 +34,8 @@ int main() { return 1; } webcpp::asio::io_context context; - crypto::async_sign(context.get_executor(), *made, crypto::eddsa, crypto::prehashed{digest}, + crypto::async_sign(context.get_executor(), *made, crypto::signing_schemes::eddsa, + crypto::signing_schemes::prehashed{digest}, [](boost::system::error_code, std::array) {}); return 0; } diff --git a/test/messages/async_sign_eddsa_prehashed_asynchronous_backend/async_sign_eddsa_prehashed_asynchronous_backend.cpp b/test/messages/async_sign_eddsa_prehashed_asynchronous_backend/async_sign_eddsa_prehashed_asynchronous_backend.cpp index f97b3969..9b518f7a 100644 --- a/test/messages/async_sign_eddsa_prehashed_asynchronous_backend/async_sign_eddsa_prehashed_asynchronous_backend.cpp +++ b/test/messages/async_sign_eddsa_prehashed_asynchronous_backend/async_sign_eddsa_prehashed_asynchronous_backend.cpp @@ -4,16 +4,16 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// The free crypto::async_sign under crypto::eddsa_prehashed with an Ed25519 key pair of a backend -// that completes by itself (a stand-in whose detail::asynchronous_backend_v is true) stops at its -// first statement after the guard, with the refusal that says WebCrypto has no Ed25519ph, and with -// that error alone: neither the key pair's async_sign nor any engine is reached. The key pair is a -// parameter, since making one would run the stand-in's engine. +// The free crypto::async_sign under crypto::signing_schemes::eddsa_prehashed with an Ed25519 key +// pair of a backend that completes by itself (a stand-in whose detail::asynchronous_backend_v is +// true) stops at its first statement after the guard, with the refusal that says WebCrypto has no +// Ed25519ph, and with that error alone: neither the key pair's async_sign nor any engine is +// reached. The key pair is a parameter, since making one would run the stand-in's engine. // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/signing.hpp:* {{webcpp::crypto: WebCrypto has no Ed25519ph: crypto::eddsa_prehashed's sign, verify, async_sign and async_verify run on a native backend.}} +// expected-error@webcpp/crypto/signing.hpp:* {{webcpp::crypto: WebCrypto has no Ed25519ph: crypto::signing_schemes::eddsa_prehashed's sign, verify, async_sign and async_verify run on a native backend.}} // clang-format on #include #include @@ -43,8 +43,8 @@ void signed_digest(webcpp::asio::io_context& context, webcpp::crypto::curves::ed25519::basic_keypair const& key) { namespace crypto = webcpp::crypto; std::array const digest{}; - crypto::async_sign(context.get_executor(), key, crypto::eddsa_prehashed, - crypto::prehashed{digest}, + crypto::async_sign(context.get_executor(), key, crypto::signing_schemes::eddsa_prehashed, + crypto::signing_schemes::prehashed{digest}, [](boost::system::error_code, crypto::curves::ed25519::signature) {}); } diff --git a/test/messages/async_sign_p256_eddsa/async_sign_p256_eddsa.cpp b/test/messages/async_sign_p256_eddsa/async_sign_p256_eddsa.cpp index dd925269..630bbe44 100644 --- a/test/messages/async_sign_p256_eddsa/async_sign_p256_eddsa.cpp +++ b/test/messages/async_sign_p256_eddsa/async_sign_p256_eddsa.cpp @@ -4,13 +4,14 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// async_sign of a P-256 key pair with crypto::eddsa, Ed25519's scheme, stops at async_sign's check -// of the key pair and the scheme, which names each key pair's scheme, and with that error alone. +// async_sign of a P-256 key pair with crypto::signing_schemes::eddsa, Ed25519's scheme, stops at +// async_sign's check of the key pair and the scheme, which names each key pair's scheme, and with +// that error alone. // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/async.hpp:* {{webcpp::crypto: async_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.}} +// expected-error@webcpp/crypto/async.hpp:* {{webcpp::crypto: async_sign: this key pair does not sign with this scheme: an Ed25519 key pair signs with crypto::signing_schemes::eddsa or crypto::signing_schemes::eddsa_prehashed, a P-256 key pair with crypto::signing_schemes::ecdsa_sha256.}} // clang-format on #include #include @@ -32,7 +33,7 @@ int main() { return 1; } webcpp::asio::io_context context; - crypto::async_sign(context.get_executor(), *made, crypto::eddsa, message, + crypto::async_sign(context.get_executor(), *made, crypto::signing_schemes::eddsa, message, [](boost::system::error_code, std::array) {}); return 0; } diff --git a/test/messages/async_sign_secp256k1/async_sign_secp256k1.cpp b/test/messages/async_sign_secp256k1/async_sign_secp256k1.cpp index 6cf71f74..c7cd5ec3 100644 --- a/test/messages/async_sign_secp256k1/async_sign_secp256k1.cpp +++ b/test/messages/async_sign_secp256k1/async_sign_secp256k1.cpp @@ -6,7 +6,7 @@ // async_sign on a key pair of an algorithm WebCrypto lacks, secp256k1's, stops with the key pair's // own signing to call instead, and with that error alone, while the key pair's -// sign(crypto::ecdsa_sha256, message) compiles. +// sign(crypto::signing_schemes::ecdsa_sha256, message) compiles. // clang-format off // expected-error@webcpp/crypto/async.hpp:* {{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.}} @@ -30,11 +30,11 @@ int main() { return 1; } // The synchronous signing compiles. - if (!made->sign(crypto::ecdsa_sha256, message)) { + if (!made->sign(crypto::signing_schemes::ecdsa_sha256, message)) { return 1; } webcpp::asio::io_context context; - crypto::async_sign(context.get_executor(), *made, crypto::ecdsa_sha256, message, - [](boost::system::error_code, std::array) {}); + crypto::async_sign(context.get_executor(), *made, crypto::signing_schemes::ecdsa_sha256, + message, [](boost::system::error_code, std::array) {}); return 0; } diff --git a/test/messages/async_sign_x25519/async_sign_x25519.cpp b/test/messages/async_sign_x25519/async_sign_x25519.cpp index 9c4272fc..f2b59db9 100644 --- a/test/messages/async_sign_x25519/async_sign_x25519.cpp +++ b/test/messages/async_sign_x25519/async_sign_x25519.cpp @@ -32,7 +32,7 @@ int main() { return 1; } webcpp::asio::io_context context; - crypto::async_sign(context.get_executor(), *key, crypto::eddsa, message, + crypto::async_sign(context.get_executor(), *key, crypto::signing_schemes::eddsa, message, [](boost::system::error_code, crypto::curves::ed25519::signature) {}); return 0; } diff --git a/test/messages/async_verify_eddsa_bytes_key/async_verify_eddsa_bytes_key.cpp b/test/messages/async_verify_eddsa_bytes_key/async_verify_eddsa_bytes_key.cpp index 67d9e246..7a2f121b 100644 --- a/test/messages/async_verify_eddsa_bytes_key/async_verify_eddsa_bytes_key.cpp +++ b/test/messages/async_verify_eddsa_bytes_key/async_verify_eddsa_bytes_key.cpp @@ -4,14 +4,14 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// async_verify of crypto::eddsa given the public key as its 32 bytes, not as a +// async_verify of crypto::signing_schemes::eddsa given the public key as its 32 bytes, not as a // curves::ed25519::public_key, stops at the catch-all async_verify, which names the keys the // asynchronous family takes, and with that error alone (design R17), as crypto::verify does. // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/async.hpp:* {{webcpp::crypto: async_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.}} +// expected-error@webcpp/crypto/async.hpp:* {{webcpp::crypto: async_verify takes crypto::signing_schemes::eddsa or crypto::signing_schemes::eddsa_prehashed with a curves::ed25519::public_key or crypto::signing_schemes::ecdsa_sha256 with a curves::p256::basic_public_key, the algorithms WebCrypto has: call crypto::verify for the others.}} // clang-format on #include #include @@ -30,7 +30,7 @@ int main() { std::array const message{'h', 'e', 'l', 'l', 'o'}; std::array const key_bytes{}; webcpp::asio::io_context context; - crypto::async_verify(context.get_executor(), crypto::eddsa, signature, message, key_bytes, - [](boost::system::error_code) {}); + crypto::async_verify(context.get_executor(), crypto::signing_schemes::eddsa, signature, message, + key_bytes, [](boost::system::error_code) {}); return 0; } diff --git a/test/messages/async_verify_eddsa_prehashed_asynchronous_backend/async_verify_eddsa_prehashed_asynchronous_backend.cpp b/test/messages/async_verify_eddsa_prehashed_asynchronous_backend/async_verify_eddsa_prehashed_asynchronous_backend.cpp index 47a635b8..ec8d5243 100644 --- a/test/messages/async_verify_eddsa_prehashed_asynchronous_backend/async_verify_eddsa_prehashed_asynchronous_backend.cpp +++ b/test/messages/async_verify_eddsa_prehashed_asynchronous_backend/async_verify_eddsa_prehashed_asynchronous_backend.cpp @@ -4,17 +4,17 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// crypto::async_verify and the public key's own async_verify under crypto::eddsa_prehashed, named -// with a backend that completes by itself (a stand-in whose detail::asynchronous_backend_v is -// true), each stop at their first statement after the guard with the refusal that says WebCrypto -// has no Ed25519ph, and with those two errors alone: neither the synchronous verify nor any engine -// is reached. Each form names a stand-in of its own, since one refusal of one backend is reported -// once however many calls reach it. +// crypto::async_verify and the public key's own async_verify under +// crypto::signing_schemes::eddsa_prehashed, named with a backend that completes by itself (a +// stand-in whose detail::asynchronous_backend_v is true), each stop at their first statement after +// the guard with the refusal that says WebCrypto has no Ed25519ph, and with those two errors alone: +// neither the synchronous verify nor any engine is reached. Each form names a stand-in of its own, +// since one refusal of one backend is reported once however many calls reach it. // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/signing.hpp:* 2 {{webcpp::crypto: WebCrypto has no Ed25519ph: crypto::eddsa_prehashed's sign, verify, async_sign and async_verify run on a native backend.}} +// expected-error@webcpp/crypto/signing.hpp:* 2 {{webcpp::crypto: WebCrypto has no Ed25519ph: crypto::signing_schemes::eddsa_prehashed's sign, verify, async_sign and async_verify run on a native backend.}} // clang-format on #include #include @@ -51,12 +51,12 @@ void verified(webcpp::asio::io_context& context, namespace crypto = webcpp::crypto; crypto::curves::ed25519::signature const signature{}; std::array const digest{}; - crypto::async_verify(context.get_executor(), crypto::eddsa_prehashed, - signature, crypto::prehashed{digest}, public_key, - [](boost::system::error_code) {}); - public_key.async_verify(context.get_executor(), crypto::eddsa_prehashed, - signature, crypto::prehashed{digest}, - [](boost::system::error_code) {}); + crypto::async_verify( + context.get_executor(), crypto::signing_schemes::eddsa_prehashed, signature, + crypto::signing_schemes::prehashed{digest}, public_key, [](boost::system::error_code) {}); + public_key.async_verify( + context.get_executor(), crypto::signing_schemes::eddsa_prehashed, signature, + crypto::signing_schemes::prehashed{digest}, [](boost::system::error_code) {}); } } // namespace diff --git a/test/messages/async_verify_named_backend/async_verify_named_backend.cpp b/test/messages/async_verify_named_backend/async_verify_named_backend.cpp index 807a02b6..7e6b8294 100644 --- a/test/messages/async_verify_named_backend/async_verify_named_backend.cpp +++ b/test/messages/async_verify_named_backend/async_verify_named_backend.cpp @@ -5,14 +5,14 @@ // https://www.boost.org/LICENSE_1_0.txt) // async_verify with its backend named first, as on every async_verify, and a scheme and key the -// asynchronous family lacks (crypto::schnorr and a 32-byte x-only key) still reaches the -// catch-all async_verify, which names the keys the family takes and crypto::verify for the -// others, and with that error alone. +// asynchronous family lacks (crypto::signing_schemes::schnorr and a 32-byte x-only key) still +// reaches the catch-all async_verify, which names the keys the family takes and crypto::verify for +// the others, and with that error alone. // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/async.hpp:* {{webcpp::crypto: async_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.}} +// expected-error@webcpp/crypto/async.hpp:* {{webcpp::crypto: async_verify takes crypto::signing_schemes::eddsa or crypto::signing_schemes::eddsa_prehashed with a curves::ed25519::public_key or crypto::signing_schemes::ecdsa_sha256 with a curves::p256::basic_public_key, the algorithms WebCrypto has: call crypto::verify for the others.}} // clang-format on #include #include @@ -32,8 +32,8 @@ int main() { std::array const message{'h', 'e', 'l', 'l', 'o'}; std::array const xonly_key{}; webcpp::asio::io_context context; - crypto::async_verify(context.get_executor(), crypto::schnorr, - signature, message, xonly_key, - [](boost::system::error_code) {}); + crypto::async_verify( + context.get_executor(), crypto::signing_schemes::schnorr, signature, message, xonly_key, + [](boost::system::error_code) {}); return 0; } diff --git a/test/messages/async_verify_p256_bytes_signature/async_verify_p256_bytes_signature.cpp b/test/messages/async_verify_p256_bytes_signature/async_verify_p256_bytes_signature.cpp index 3deee744..ee20f23a 100644 --- a/test/messages/async_verify_p256_bytes_signature/async_verify_p256_bytes_signature.cpp +++ b/test/messages/async_verify_p256_bytes_signature/async_verify_p256_bytes_signature.cpp @@ -42,7 +42,7 @@ int main() { std::array const signature{}; std::array const message{'h', 'e', 'l', 'l', 'o'}; webcpp::asio::io_context context; - crypto::async_verify(context.get_executor(), crypto::ecdsa_sha256, signature, message, - *public_key, [](boost::system::error_code) {}); + crypto::async_verify(context.get_executor(), crypto::signing_schemes::ecdsa_sha256, signature, + message, *public_key, [](boost::system::error_code) {}); return 0; } diff --git a/test/messages/async_verify_wrong_key/async_verify_wrong_key.cpp b/test/messages/async_verify_wrong_key/async_verify_wrong_key.cpp index bc81408a..09061032 100644 --- a/test/messages/async_verify_wrong_key/async_verify_wrong_key.cpp +++ b/test/messages/async_verify_wrong_key/async_verify_wrong_key.cpp @@ -4,15 +4,15 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// async_verify of crypto::ecdsa_sha256 against a secp256k1 public key, an algorithm WebCrypto -// lacks, stops at the catch-all async_verify, which names the keys the asynchronous family takes -// and crypto::verify for the others, and with that error alone, while crypto::verify of the same -// arguments compiles. +// async_verify of crypto::signing_schemes::ecdsa_sha256 against a secp256k1 public key, an +// algorithm WebCrypto lacks, stops at the catch-all async_verify, which names the keys the +// asynchronous family takes and crypto::verify for the others, and with that error alone, while +// crypto::verify of the same arguments compiles. // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/async.hpp:* {{webcpp::crypto: async_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.}} +// expected-error@webcpp/crypto/async.hpp:* {{webcpp::crypto: async_verify takes crypto::signing_schemes::eddsa or crypto::signing_schemes::eddsa_prehashed with a curves::ed25519::public_key or crypto::signing_schemes::ecdsa_sha256 with a curves::p256::basic_public_key, the algorithms WebCrypto has: call crypto::verify for the others.}} // clang-format on #include #include @@ -34,16 +34,16 @@ int main() { return 1; } auto const public_key = made->public_key(); - auto const signature = made->sign(crypto::ecdsa_sha256, message); + auto const signature = made->sign(crypto::signing_schemes::ecdsa_sha256, message); if (!public_key || !signature) { return 1; } // The synchronous verification compiles. - if (!crypto::verify(crypto::ecdsa_sha256, *signature, message, *public_key)) { + if (!crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signature, message, *public_key)) { return 1; } webcpp::asio::io_context context; - crypto::async_verify(context.get_executor(), crypto::ecdsa_sha256, *signature, message, - *public_key, [](boost::system::error_code) {}); + crypto::async_verify(context.get_executor(), crypto::signing_schemes::ecdsa_sha256, *signature, + message, *public_key, [](boost::system::error_code) {}); return 0; } diff --git a/test/messages/ed25519_unknown_policy/ed25519_unknown_policy.cpp b/test/messages/ed25519_unknown_policy/ed25519_unknown_policy.cpp index 901bae9d..b4579461 100644 --- a/test/messages/ed25519_unknown_policy/ed25519_unknown_policy.cpp +++ b/test/messages/ed25519_unknown_policy/ed25519_unknown_policy.cpp @@ -32,7 +32,7 @@ int main() { webcpp::crypto::curves::ed25519::public_key::from_bytes(std::array{}); webcpp::crypto::curves::ed25519::signature const signature{}; return public_key && - webcpp::crypto::verify(webcpp::crypto::eddsa, signature, + webcpp::crypto::verify(webcpp::crypto::signing_schemes::eddsa, signature, std::span{}, *public_key, lenient{}) ? 0 : 1; diff --git a/test/messages/prehashed_dynamic/prehashed_dynamic.cpp b/test/messages/prehashed_dynamic/prehashed_dynamic.cpp index c947e655..fa7f1ed0 100644 --- a/test/messages/prehashed_dynamic/prehashed_dynamic.cpp +++ b/test/messages/prehashed_dynamic/prehashed_dynamic.cpp @@ -11,7 +11,7 @@ // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/signing.hpp:* {{webcpp::crypto: crypto::prehashed takes a digest of a fixed size: a std::array or a std::span.}} +// expected-error@webcpp/crypto/signing.hpp:* {{webcpp::crypto: crypto::signing_schemes::prehashed takes a digest of a fixed size: a std::array or a std::span.}} // clang-format on #include @@ -23,7 +23,7 @@ int main() { namespace crypto = webcpp::crypto; std::array const bytes{}; // The marker of a fixed-size span compiles. - crypto::prehashed const fixed{std::span(bytes)}; - crypto::prehashed const dynamic{std::span(bytes)}; + crypto::signing_schemes::prehashed const fixed{std::span(bytes)}; + crypto::signing_schemes::prehashed const dynamic{std::span(bytes)}; return static_cast(fixed.digest.size() + dynamic.digest.size()); } diff --git a/test/messages/recover_ecdsa_signature/recover_ecdsa_signature.cpp b/test/messages/recover_ecdsa_signature/recover_ecdsa_signature.cpp index 1922af33..5f52f0e5 100644 --- a/test/messages/recover_ecdsa_signature/recover_ecdsa_signature.cpp +++ b/test/messages/recover_ecdsa_signature/recover_ecdsa_signature.cpp @@ -28,9 +28,9 @@ int main() { return 1; } std::array const message{'h', 'e', 'l', 'l', 'o'}; - auto const signature = key->sign(crypto::ecdsa_sha256, message); - return signature && crypto::curves::secp256k1::recover(crypto::ecdsa_sha256_recoverable, - *signature, message) + auto const signature = key->sign(crypto::signing_schemes::ecdsa_sha256, message); + return signature && crypto::curves::secp256k1::recover( + crypto::signing_schemes::ecdsa_sha256_recoverable, *signature, message) ? 0 : 1; } diff --git a/test/messages/scheme_in_crypto_namespace/Jamfile b/test/messages/scheme_in_crypto_namespace/Jamfile new file mode 100644 index 00000000..a945fd84 --- /dev/null +++ b/test/messages/scheme_in_crypto_namespace/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic scheme_in_crypto_namespace : scheme_in_crypto_namespace.cpp + : /third_party//bearssl : native wasip2 wasip3 : alone ; diff --git a/test/messages/scheme_in_crypto_namespace/scheme_in_crypto_namespace.cpp b/test/messages/scheme_in_crypto_namespace/scheme_in_crypto_namespace.cpp new file mode 100644 index 00000000..64ac1e65 --- /dev/null +++ b/test/messages/scheme_in_crypto_namespace/scheme_in_crypto_namespace.cpp @@ -0,0 +1,25 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The scheme tags live in crypto::signing_schemes, with no alias in crypto (design D1): a program +// that still names one in crypto stops at that name, with that error alone. + +#include +#include +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array scalar{}; + scalar.back() = 1; + auto const key = crypto::curves::p256::keypair::from_secret(scalar); + std::array const message{'h', 'e', 'l', 'l', 'o'}; + // expected-error@+1 {{no member named 'ecdsa_sha256' in namespace 'webcpp::crypto'}} + return key && key->sign(crypto::ecdsa_sha256, message) ? 0 : 1; +} diff --git a/test/messages/sign_asynchronous_backend/sign_asynchronous_backend.cpp b/test/messages/sign_asynchronous_backend/sign_asynchronous_backend.cpp index 41112ac0..e656e6c2 100644 --- a/test/messages/sign_asynchronous_backend/sign_asynchronous_backend.cpp +++ b/test/messages/sign_asynchronous_backend/sign_asynchronous_backend.cpp @@ -36,7 +36,7 @@ namespace { bool signed_message(webcpp::crypto::curves::p256::basic_keypair const& key) { namespace crypto = webcpp::crypto; std::array const message{'h', 'e', 'l', 'l', 'o'}; - return crypto::sign(key, crypto::ecdsa_sha256, message).has_value(); + return crypto::sign(key, crypto::signing_schemes::ecdsa_sha256, message).has_value(); } } // namespace diff --git a/test/messages/sign_ed25519_ecdsa/sign_ed25519_ecdsa.cpp b/test/messages/sign_ed25519_ecdsa/sign_ed25519_ecdsa.cpp index 46d4c986..980cca80 100644 --- a/test/messages/sign_ed25519_ecdsa/sign_ed25519_ecdsa.cpp +++ b/test/messages/sign_ed25519_ecdsa/sign_ed25519_ecdsa.cpp @@ -5,13 +5,13 @@ // https://www.boost.org/LICENSE_1_0.txt) // An Ed25519 key pair asked to sign with ECDSA over SHA-256, a scheme of P-256 and secp256k1, -// stops at the scheme's check with the two schemes it has, crypto::eddsa and -// crypto::eddsa_prehashed, and with that error alone. +// stops at the scheme's check with the two schemes it has, crypto::signing_schemes::eddsa and +// crypto::signing_schemes::eddsa_prehashed, and with that error alone. // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/curves/ed25519.hpp:* {{webcpp::crypto: an Ed25519 key signs with crypto::eddsa or crypto::eddsa_prehashed.}} +// expected-error@webcpp/crypto/curves/ed25519.hpp:* {{webcpp::crypto: an Ed25519 key signs with crypto::signing_schemes::eddsa or crypto::signing_schemes::eddsa_prehashed.}} // clang-format on #include #include @@ -24,5 +24,5 @@ int main() { std::array const seed{}; std::array const message{1, 2, 3}; auto const key = crypto::curves::ed25519::keypair::from_secret(seed); - return key && key->sign(crypto::ecdsa_sha256, message) ? 0 : 1; + return key && key->sign(crypto::signing_schemes::ecdsa_sha256, message) ? 0 : 1; } diff --git a/test/messages/sign_ed25519_keccak/sign_ed25519_keccak.cpp b/test/messages/sign_ed25519_keccak/sign_ed25519_keccak.cpp index 3893d94f..90b020b1 100644 --- a/test/messages/sign_ed25519_keccak/sign_ed25519_keccak.cpp +++ b/test/messages/sign_ed25519_keccak/sign_ed25519_keccak.cpp @@ -5,13 +5,13 @@ // https://www.boost.org/LICENSE_1_0.txt) // An Ed25519 key pair asked to sign with Ethereum's recoverable ECDSA, a scheme of secp256k1, -// stops at the scheme's check with the two schemes it has, crypto::eddsa and -// crypto::eddsa_prehashed, and with that error alone. +// stops at the scheme's check with the two schemes it has, crypto::signing_schemes::eddsa and +// crypto::signing_schemes::eddsa_prehashed, and with that error alone. // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/curves/ed25519.hpp:* {{webcpp::crypto: an Ed25519 key signs with crypto::eddsa or crypto::eddsa_prehashed.}} +// expected-error@webcpp/crypto/curves/ed25519.hpp:* {{webcpp::crypto: an Ed25519 key signs with crypto::signing_schemes::eddsa or crypto::signing_schemes::eddsa_prehashed.}} // clang-format on #include #include @@ -24,5 +24,5 @@ int main() { std::array const seed{}; std::array const message{1, 2, 3}; auto const key = crypto::curves::ed25519::keypair::from_secret(seed); - return key && key->sign(crypto::ecdsa_keccak256_recoverable, message) ? 0 : 1; + return key && key->sign(crypto::signing_schemes::ecdsa_keccak256_recoverable, message) ? 0 : 1; } diff --git a/test/messages/sign_ed25519_prehashed/sign_ed25519_prehashed.cpp b/test/messages/sign_ed25519_prehashed/sign_ed25519_prehashed.cpp index d030bd5b..056738f3 100644 --- a/test/messages/sign_ed25519_prehashed/sign_ed25519_prehashed.cpp +++ b/test/messages/sign_ed25519_prehashed/sign_ed25519_prehashed.cpp @@ -4,14 +4,15 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// An Ed25519 key pair asked to sign a digest marked as one, crypto::prehashed{digest}, with -// crypto::eddsa stops at the input's check, which says that pure Ed25519 signs the message itself -// and names crypto::eddsa_prehashed (Ed25519ph), and with that error alone. +// An Ed25519 key pair asked to sign a digest marked as one, +// crypto::signing_schemes::prehashed{digest}, with crypto::signing_schemes::eddsa stops at the +// input's check, which says that pure Ed25519 signs the message itself and names +// crypto::signing_schemes::eddsa_prehashed (Ed25519ph), and with that error alone. // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/signing.hpp:* {{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).}} +// expected-error@webcpp/crypto/signing.hpp:* {{webcpp::crypto: crypto::signing_schemes::eddsa signs the message itself (RFC 8032's pure Ed25519) and takes no digest; a message's SHA-512 is signed with crypto::signing_schemes::eddsa_prehashed (Ed25519ph).}} // clang-format on #include #include @@ -24,5 +25,8 @@ int main() { std::array const seed{}; std::array const digest{}; auto const key = crypto::curves::ed25519::keypair::from_secret(seed); - return key && key->sign(crypto::eddsa, crypto::prehashed{digest}) ? 0 : 1; + return key && key->sign(crypto::signing_schemes::eddsa, + crypto::signing_schemes::prehashed{digest}) + ? 0 + : 1; } diff --git a/test/messages/sign_eddsa_prehashed_asynchronous_backend/sign_eddsa_prehashed_asynchronous_backend.cpp b/test/messages/sign_eddsa_prehashed_asynchronous_backend/sign_eddsa_prehashed_asynchronous_backend.cpp index e56e236b..a32b9efe 100644 --- a/test/messages/sign_eddsa_prehashed_asynchronous_backend/sign_eddsa_prehashed_asynchronous_backend.cpp +++ b/test/messages/sign_eddsa_prehashed_asynchronous_backend/sign_eddsa_prehashed_asynchronous_backend.cpp @@ -4,17 +4,17 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// The free crypto::sign under crypto::eddsa_prehashed with an Ed25519 key pair of a backend that -// completes by itself (a stand-in whose detail::asynchronous_backend_v is true) stops at the key -// pair's sign, which it calls, at its first statement after the guard, with the refusal that says -// WebCrypto has no Ed25519ph, before the text that names async_sign, and with that error alone: -// no engine is reached. The key pair is a parameter, since making one would run the stand-in's -// engine. +// The free crypto::sign under crypto::signing_schemes::eddsa_prehashed with an Ed25519 key pair of +// a backend that completes by itself (a stand-in whose detail::asynchronous_backend_v is true) +// stops at the key pair's sign, which it calls, at its first statement after the guard, with the +// refusal that says WebCrypto has no Ed25519ph, before the text that names async_sign, and with +// that error alone: no engine is reached. The key pair is a parameter, since making one would run +// the stand-in's engine. // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/signing.hpp:* {{webcpp::crypto: WebCrypto has no Ed25519ph: crypto::eddsa_prehashed's sign, verify, async_sign and async_verify run on a native backend.}} +// expected-error@webcpp/crypto/signing.hpp:* {{webcpp::crypto: WebCrypto has no Ed25519ph: crypto::signing_schemes::eddsa_prehashed's sign, verify, async_sign and async_verify run on a native backend.}} // clang-format on #include #include @@ -38,7 +38,9 @@ namespace { bool signed_digest(webcpp::crypto::curves::ed25519::basic_keypair const& key) { namespace crypto = webcpp::crypto; std::array const digest{}; - return crypto::sign(key, crypto::eddsa_prehashed, crypto::prehashed{digest}).has_value(); + return crypto::sign(key, crypto::signing_schemes::eddsa_prehashed, + crypto::signing_schemes::prehashed{digest}) + .has_value(); } } // namespace diff --git a/test/messages/sign_eddsa_prehashed_digest_32/sign_eddsa_prehashed_digest_32.cpp b/test/messages/sign_eddsa_prehashed_digest_32/sign_eddsa_prehashed_digest_32.cpp index fe47902b..19fc990a 100644 --- a/test/messages/sign_eddsa_prehashed_digest_32/sign_eddsa_prehashed_digest_32.cpp +++ b/test/messages/sign_eddsa_prehashed_digest_32/sign_eddsa_prehashed_digest_32.cpp @@ -4,13 +4,13 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// An Ed25519 key pair asked to sign a 32-byte digest under crypto::eddsa_prehashed stops at the -// input's check, which names SHA-512's 64 bytes, and with that error alone. +// An Ed25519 key pair asked to sign a 32-byte digest under crypto::signing_schemes::eddsa_prehashed +// stops at the input's check, which names SHA-512's 64 bytes, and with that error alone. // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/signing.hpp:* {{webcpp::crypto: crypto::eddsa_prehashed takes a 64-byte digest, SHA-512's: crypto::prehashed{digest} of a std::array.}} +// expected-error@webcpp/crypto/signing.hpp:* {{webcpp::crypto: crypto::signing_schemes::eddsa_prehashed takes a 64-byte digest, SHA-512's: crypto::signing_schemes::prehashed{digest} of a std::array.}} // clang-format on #include #include @@ -23,5 +23,8 @@ int main() { std::array const seed{}; std::array const digest{}; auto const key = crypto::curves::ed25519::keypair::from_secret(seed); - return key && key->sign(crypto::eddsa_prehashed, crypto::prehashed{digest}) ? 0 : 1; + return key && key->sign(crypto::signing_schemes::eddsa_prehashed, + crypto::signing_schemes::prehashed{digest}) + ? 0 + : 1; } diff --git a/test/messages/sign_eddsa_prehashed_message/sign_eddsa_prehashed_message.cpp b/test/messages/sign_eddsa_prehashed_message/sign_eddsa_prehashed_message.cpp index c0c8365f..7869059b 100644 --- a/test/messages/sign_eddsa_prehashed_message/sign_eddsa_prehashed_message.cpp +++ b/test/messages/sign_eddsa_prehashed_message/sign_eddsa_prehashed_message.cpp @@ -4,15 +4,15 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// An Ed25519 key pair asked to sign a message under crypto::eddsa_prehashed, a 64-byte -// std::array, which is a message although it has a digest's size, stops at the input's check, -// which names crypto::prehashed{digest} of SHA-512's 64 bytes, crypto::eddsa and the streaming -// signer, and with that error alone. +// An Ed25519 key pair asked to sign a message under crypto::signing_schemes::eddsa_prehashed, a +// 64-byte std::array, which is a message although it has a digest's size, stops at the input's +// check, which names crypto::signing_schemes::prehashed{digest} of SHA-512's 64 bytes, +// crypto::signing_schemes::eddsa and the streaming signer, and with that error alone. // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/signing.hpp:* {{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.}} +// expected-error@webcpp/crypto/signing.hpp:* {{webcpp::crypto: crypto::signing_schemes::eddsa_prehashed (RFC 8032's Ed25519ph) signs a digest, the message's SHA-512: crypto::signing_schemes::prehashed{digest} of a std::array; sign the message itself with crypto::signing_schemes::eddsa, or give it in pieces to curves::ed25519::prehashed_signer.}} // clang-format on #include #include @@ -24,5 +24,8 @@ int main() { namespace crypto = webcpp::crypto; std::array const seed{}; auto const key = crypto::curves::ed25519::keypair::from_secret(seed); - return key && key->sign(crypto::eddsa_prehashed, std::array{}) ? 0 : 1; + return key && key->sign(crypto::signing_schemes::eddsa_prehashed, + std::array{}) + ? 0 + : 1; } diff --git a/test/messages/sign_free_ed25519_ecdsa/sign_free_ed25519_ecdsa.cpp b/test/messages/sign_free_ed25519_ecdsa/sign_free_ed25519_ecdsa.cpp index 561ae7b3..322d22ca 100644 --- a/test/messages/sign_free_ed25519_ecdsa/sign_free_ed25519_ecdsa.cpp +++ b/test/messages/sign_free_ed25519_ecdsa/sign_free_ed25519_ecdsa.cpp @@ -10,7 +10,7 @@ // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/curves/ed25519.hpp:* {{webcpp::crypto: an Ed25519 key signs with crypto::eddsa or crypto::eddsa_prehashed.}} +// expected-error@webcpp/crypto/curves/ed25519.hpp:* {{webcpp::crypto: an Ed25519 key signs with crypto::signing_schemes::eddsa or crypto::signing_schemes::eddsa_prehashed.}} // clang-format on #include #include @@ -23,5 +23,5 @@ int main() { std::array const seed{}; auto const key = crypto::curves::ed25519::keypair::from_secret(seed); std::array const message{'h', 'e', 'l', 'l', 'o'}; - return key && crypto::sign(*key, crypto::ecdsa_sha256, message) ? 0 : 1; + return key && crypto::sign(*key, crypto::signing_schemes::ecdsa_sha256, message) ? 0 : 1; } diff --git a/test/messages/sign_free_public_key/sign_free_public_key.cpp b/test/messages/sign_free_public_key/sign_free_public_key.cpp index 994422e9..15f190f3 100644 --- a/test/messages/sign_free_public_key/sign_free_public_key.cpp +++ b/test/messages/sign_free_public_key/sign_free_public_key.cpp @@ -24,5 +24,5 @@ int main() { auto const public_key = crypto::curves::ed25519::public_key::from_bytes(std::array{}); std::array const message{'h', 'e', 'l', 'l', 'o'}; - return public_key && crypto::sign(*public_key, crypto::eddsa, message) ? 0 : 1; + return public_key && crypto::sign(*public_key, crypto::signing_schemes::eddsa, message) ? 0 : 1; } diff --git a/test/messages/sign_keccak_digest_20/sign_keccak_digest_20.cpp b/test/messages/sign_keccak_digest_20/sign_keccak_digest_20.cpp index 2088fa39..bc39e092 100644 --- a/test/messages/sign_keccak_digest_20/sign_keccak_digest_20.cpp +++ b/test/messages/sign_keccak_digest_20/sign_keccak_digest_20.cpp @@ -11,7 +11,7 @@ // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/signing.hpp:* {{webcpp::crypto: crypto::ecdsa_keccak256_recoverable takes a 32-byte digest, Keccak-256's: crypto::prehashed{digest} of a std::array.}} +// expected-error@webcpp/crypto/signing.hpp:* {{webcpp::crypto: crypto::signing_schemes::ecdsa_keccak256_recoverable takes a 32-byte digest, Keccak-256's: crypto::signing_schemes::prehashed{digest} of a std::array.}} // clang-format on #include #include @@ -24,8 +24,8 @@ int main() { std::array secret_key{}; secret_key.back() = 1; auto const key = crypto::curves::secp256k1::keypair::from_secret(secret_key); - return key && key->sign(crypto::ecdsa_keccak256_recoverable, - crypto::prehashed{std::array{}}) + return key && key->sign(crypto::signing_schemes::ecdsa_keccak256_recoverable, + crypto::signing_schemes::prehashed{std::array{}}) ? 0 : 1; } diff --git a/test/messages/sign_keccak_without_xkcp/sign_keccak_without_xkcp.cpp b/test/messages/sign_keccak_without_xkcp/sign_keccak_without_xkcp.cpp index dcc006c6..f0f19c81 100644 --- a/test/messages/sign_keccak_without_xkcp/sign_keccak_without_xkcp.cpp +++ b/test/messages/sign_keccak_without_xkcp/sign_keccak_without_xkcp.cpp @@ -11,7 +11,7 @@ // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/curves/secp256k1.hpp:* {{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}.}} +// expected-error@webcpp/crypto/curves/secp256k1.hpp:* {{webcpp::crypto: crypto::signing_schemes::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::signing_schemes::prehashed{digest}.}} // clang-format on #include #include @@ -25,5 +25,5 @@ int main() { secret_key.back() = 1; std::array const message{'h', 'e', 'l', 'l', 'o'}; auto const key = crypto::curves::secp256k1::keypair::from_secret(secret_key); - return key && key->sign(crypto::ecdsa_keccak256_recoverable, message) ? 0 : 1; + return key && key->sign(crypto::signing_schemes::ecdsa_keccak256_recoverable, message) ? 0 : 1; } diff --git a/test/messages/sign_p256_digest_48/sign_p256_digest_48.cpp b/test/messages/sign_p256_digest_48/sign_p256_digest_48.cpp index cfc44aa1..eebe6ab0 100644 --- a/test/messages/sign_p256_digest_48/sign_p256_digest_48.cpp +++ b/test/messages/sign_p256_digest_48/sign_p256_digest_48.cpp @@ -10,7 +10,7 @@ // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/signing.hpp:* {{webcpp::crypto: crypto::ecdsa_sha256 takes a 32-byte digest, SHA-256's: crypto::prehashed{digest} of a std::array.}} +// expected-error@webcpp/crypto/signing.hpp:* {{webcpp::crypto: crypto::signing_schemes::ecdsa_sha256 takes a 32-byte digest, SHA-256's: crypto::signing_schemes::prehashed{digest} of a std::array.}} // clang-format on #include #include @@ -24,7 +24,8 @@ int main() { std::array scalar{}; scalar.back() = 1; auto const key = crypto::curves::p256::keypair::from_secret(scalar); - return key && key->sign(crypto::ecdsa_sha256, crypto::prehashed{std::array{}}) + return key && key->sign(crypto::signing_schemes::ecdsa_sha256, + crypto::signing_schemes::prehashed{std::array{}}) ? 0 : 1; } diff --git a/test/messages/sign_p256_keccak/sign_p256_keccak.cpp b/test/messages/sign_p256_keccak/sign_p256_keccak.cpp index 7181e35e..d853f5d9 100644 --- a/test/messages/sign_p256_keccak/sign_p256_keccak.cpp +++ b/test/messages/sign_p256_keccak/sign_p256_keccak.cpp @@ -10,7 +10,7 @@ // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/curves/p256.hpp:* {{webcpp::crypto: a P-256 key signs with crypto::ecdsa_sha256.}} +// expected-error@webcpp/crypto/curves/p256.hpp:* {{webcpp::crypto: a P-256 key signs with crypto::signing_schemes::ecdsa_sha256.}} // clang-format on #include #include @@ -25,5 +25,5 @@ int main() { scalar.back() = 1; auto const key = crypto::curves::p256::keypair::from_secret(scalar); std::array const message{'h', 'e', 'l', 'l', 'o'}; - return key && key->sign(crypto::ecdsa_keccak256_recoverable, message) ? 0 : 1; + return key && key->sign(crypto::signing_schemes::ecdsa_keccak256_recoverable, message) ? 0 : 1; } diff --git a/test/messages/sign_p256_schnorr/sign_p256_schnorr.cpp b/test/messages/sign_p256_schnorr/sign_p256_schnorr.cpp index 2335a062..6d31aeb2 100644 --- a/test/messages/sign_p256_schnorr/sign_p256_schnorr.cpp +++ b/test/messages/sign_p256_schnorr/sign_p256_schnorr.cpp @@ -10,7 +10,7 @@ // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/curves/p256.hpp:* {{webcpp::crypto: a P-256 key signs with crypto::ecdsa_sha256.}} +// expected-error@webcpp/crypto/curves/p256.hpp:* {{webcpp::crypto: a P-256 key signs with crypto::signing_schemes::ecdsa_sha256.}} // clang-format on #include #include @@ -25,5 +25,5 @@ int main() { scalar.back() = 1; auto const key = crypto::curves::p256::keypair::from_secret(scalar); std::array const message{'h', 'e', 'l', 'l', 'o'}; - return key && key->sign(crypto::schnorr, message) ? 0 : 1; + return key && key->sign(crypto::signing_schemes::schnorr, message) ? 0 : 1; } diff --git a/test/messages/sign_schnorr_prehashed/sign_schnorr_prehashed.cpp b/test/messages/sign_schnorr_prehashed/sign_schnorr_prehashed.cpp index b7d69189..d6c65d92 100644 --- a/test/messages/sign_schnorr_prehashed/sign_schnorr_prehashed.cpp +++ b/test/messages/sign_schnorr_prehashed/sign_schnorr_prehashed.cpp @@ -4,14 +4,15 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// A secp256k1 key pair asked to sign a digest marked as one, crypto::prehashed{digest}, with -// BIP340's crypto::schnorr stops at the input's check, which says that Schnorr signs the message -// itself, and with that error alone. +// A secp256k1 key pair asked to sign a digest marked as one, +// crypto::signing_schemes::prehashed{digest}, with BIP340's crypto::signing_schemes::schnorr stops +// at the input's check, which says that Schnorr signs the message itself, and with that error +// alone. // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/signing.hpp:* {{webcpp::crypto: crypto::schnorr (BIP340) signs a message of any length and has no prehash mode: pass the message.}} +// expected-error@webcpp/crypto/signing.hpp:* {{webcpp::crypto: crypto::signing_schemes::schnorr (BIP340) signs a message of any length and has no prehash mode: pass the message.}} // clang-format on #include #include @@ -25,5 +26,8 @@ int main() { secret.fill(0x42); std::array const digest{}; auto const key = crypto::curves::secp256k1::keypair::from_secret(secret); - return key && key->sign(crypto::schnorr, crypto::prehashed{digest}) ? 0 : 1; + return key && key->sign(crypto::signing_schemes::schnorr, + crypto::signing_schemes::prehashed{digest}) + ? 0 + : 1; } diff --git a/test/messages/sign_secp256k1_eddsa/sign_secp256k1_eddsa.cpp b/test/messages/sign_secp256k1_eddsa/sign_secp256k1_eddsa.cpp index 7f1813df..cdcce241 100644 --- a/test/messages/sign_secp256k1_eddsa/sign_secp256k1_eddsa.cpp +++ b/test/messages/sign_secp256k1_eddsa/sign_secp256k1_eddsa.cpp @@ -4,13 +4,13 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// A secp256k1 key pair asked to sign with Ed25519's crypto::eddsa, a scheme of another curve, -// stops at its sign with the schemes it has, and with that error alone. +// A secp256k1 key pair asked to sign with Ed25519's crypto::signing_schemes::eddsa, a scheme of +// another curve, stops at its sign with the schemes it has, and with that error alone. // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/curves/secp256k1.hpp:* {{webcpp::crypto: a secp256k1 key signs with crypto::ecdsa_sha256, crypto::ecdsa_sha256_recoverable, crypto::ecdsa_keccak256_recoverable or crypto::schnorr.}} +// expected-error@webcpp/crypto/curves/secp256k1.hpp:* {{webcpp::crypto: a secp256k1 key signs with crypto::signing_schemes::ecdsa_sha256, crypto::signing_schemes::ecdsa_sha256_recoverable, crypto::signing_schemes::ecdsa_keccak256_recoverable or crypto::signing_schemes::schnorr.}} // clang-format on #include #include @@ -24,5 +24,5 @@ int main() { secret.fill(0x42); std::array const message{'h', 'e', 'l', 'l', 'o'}; auto const key = crypto::curves::secp256k1::keypair::from_secret(secret); - return key && key->sign(crypto::eddsa, message) ? 0 : 1; + return key && key->sign(crypto::signing_schemes::eddsa, message) ? 0 : 1; } diff --git a/test/messages/sign_secp256k1_not_a_scheme/sign_secp256k1_not_a_scheme.cpp b/test/messages/sign_secp256k1_not_a_scheme/sign_secp256k1_not_a_scheme.cpp index 96c20fd6..d2e2ee81 100644 --- a/test/messages/sign_secp256k1_not_a_scheme/sign_secp256k1_not_a_scheme.cpp +++ b/test/messages/sign_secp256k1_not_a_scheme/sign_secp256k1_not_a_scheme.cpp @@ -10,7 +10,7 @@ // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/curves/secp256k1.hpp:* {{webcpp::crypto: a secp256k1 key signs with crypto::ecdsa_sha256, crypto::ecdsa_sha256_recoverable, crypto::ecdsa_keccak256_recoverable or crypto::schnorr.}} +// expected-error@webcpp/crypto/curves/secp256k1.hpp:* {{webcpp::crypto: a secp256k1 key signs with crypto::signing_schemes::ecdsa_sha256, crypto::signing_schemes::ecdsa_sha256_recoverable, crypto::signing_schemes::ecdsa_keccak256_recoverable or crypto::signing_schemes::schnorr.}} // clang-format on #include #include diff --git a/test/messages/sign_secp256k1_recoverable_digest_48/sign_secp256k1_recoverable_digest_48.cpp b/test/messages/sign_secp256k1_recoverable_digest_48/sign_secp256k1_recoverable_digest_48.cpp index 647b42c7..58e9b694 100644 --- a/test/messages/sign_secp256k1_recoverable_digest_48/sign_secp256k1_recoverable_digest_48.cpp +++ b/test/messages/sign_secp256k1_recoverable_digest_48/sign_secp256k1_recoverable_digest_48.cpp @@ -11,7 +11,7 @@ // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/signing.hpp:* {{webcpp::crypto: crypto::ecdsa_sha256_recoverable takes a 32-byte digest, SHA-256's: crypto::prehashed{digest} of a std::array.}} +// expected-error@webcpp/crypto/signing.hpp:* {{webcpp::crypto: crypto::signing_schemes::ecdsa_sha256_recoverable takes a 32-byte digest, SHA-256's: crypto::signing_schemes::prehashed{digest} of a std::array.}} // clang-format on #include #include @@ -24,8 +24,8 @@ int main() { std::array secret_key{}; secret_key.back() = 1; auto const key = crypto::curves::secp256k1::keypair::from_secret(secret_key); - return key && key->sign(crypto::ecdsa_sha256_recoverable, - crypto::prehashed{std::array{}}) + return key && key->sign(crypto::signing_schemes::ecdsa_sha256_recoverable, + crypto::signing_schemes::prehashed{std::array{}}) ? 0 : 1; } diff --git a/test/messages/sign_x25519/sign_x25519.cpp b/test/messages/sign_x25519/sign_x25519.cpp index 4aaf4464..10efe8e9 100644 --- a/test/messages/sign_x25519/sign_x25519.cpp +++ b/test/messages/sign_x25519/sign_x25519.cpp @@ -25,5 +25,5 @@ int main() { std::array const secret_bytes{1}; auto const key = crypto::curves::x25519::keypair::from_secret(secret_bytes); std::array const message{'h', 'e', 'l', 'l', 'o'}; - return key && crypto::sign(*key, crypto::eddsa, message) ? 0 : 1; + return key && crypto::sign(*key, crypto::signing_schemes::eddsa, message) ? 0 : 1; } diff --git a/test/messages/verify_asynchronous_backend/verify_asynchronous_backend.cpp b/test/messages/verify_asynchronous_backend/verify_asynchronous_backend.cpp index b1d4bd40..b1563ee2 100644 --- a/test/messages/verify_asynchronous_backend/verify_asynchronous_backend.cpp +++ b/test/messages/verify_asynchronous_backend/verify_asynchronous_backend.cpp @@ -35,7 +35,8 @@ int main() { crypto::curves::ed25519::public_key::from_bytes(std::array{}); crypto::curves::ed25519::signature const signature{}; std::array const message{'h', 'e', 'l', 'l', 'o'}; - return public_key && public_key->verify(crypto::eddsa, signature, message) + return public_key && public_key->verify(crypto::signing_schemes::eddsa, + signature, message) ? 0 : 1; } diff --git a/test/messages/verify_ecdsa_bytes_key/verify_ecdsa_bytes_key.cpp b/test/messages/verify_ecdsa_bytes_key/verify_ecdsa_bytes_key.cpp index d1765c50..7a9a9fe0 100644 --- a/test/messages/verify_ecdsa_bytes_key/verify_ecdsa_bytes_key.cpp +++ b/test/messages/verify_ecdsa_bytes_key/verify_ecdsa_bytes_key.cpp @@ -6,12 +6,12 @@ // ECDSA's verification given a public key as 33 bytes, not as a parsed key, stops at the // catch-all verify, which says which key goes with which scheme, and with that error alone: -// bytes never decide between P-256 and secp256k1 under crypto::ecdsa_sha256. +// bytes never decide between P-256 and secp256k1 under crypto::signing_schemes::ecdsa_sha256. // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/signing.hpp:* {{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.}} +// expected-error@webcpp/crypto/signing.hpp:* {{webcpp::crypto: verify: this public key does not go with this scheme: crypto::signing_schemes::eddsa and crypto::signing_schemes::eddsa_prehashed take a curves::ed25519::public_key, crypto::signing_schemes::ecdsa_sha256 a curves::p256::basic_public_key or a curves::secp256k1::public_key, crypto::signing_schemes::schnorr a curves::secp256k1::public_key or a 32-byte x-only key; a crypto::signing_schemes::ecdsa_sha256_recoverable or a crypto::signing_schemes::ecdsa_keccak256_recoverable signature gives its key to curves::secp256k1::recover.}} // clang-format on #include #include @@ -23,7 +23,8 @@ int main() { namespace crypto = webcpp::crypto; crypto::curves::secp256k1::ecdsa_signature const signature{}; std::array const message{'h', 'e', 'l', 'l', 'o'}; - return crypto::verify(crypto::ecdsa_sha256, signature, message, std::array{}) + return crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, message, + std::array{}) ? 0 : 1; } diff --git a/test/messages/verify_ed25519_bytes_signature/verify_ed25519_bytes_signature.cpp b/test/messages/verify_ed25519_bytes_signature/verify_ed25519_bytes_signature.cpp index 428d258f..08f4cd7a 100644 --- a/test/messages/verify_ed25519_bytes_signature/verify_ed25519_bytes_signature.cpp +++ b/test/messages/verify_ed25519_bytes_signature/verify_ed25519_bytes_signature.cpp @@ -11,7 +11,7 @@ // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/signing.hpp:* {{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.}} +// expected-error@webcpp/crypto/signing.hpp:* {{webcpp::crypto: verify: an Ed25519 key verifies a curves::ed25519::signature under crypto::signing_schemes::eddsa: make one from 64 bytes with curves::ed25519::signature::from_bytes.}} // clang-format on #include #include @@ -25,5 +25,8 @@ int main() { crypto::curves::ed25519::public_key::from_bytes(std::array{}); std::array const signature{}; std::array const message{'h', 'e', 'l', 'l', 'o'}; - return public_key && crypto::verify(crypto::eddsa, signature, message, *public_key) ? 0 : 1; + return public_key && + crypto::verify(crypto::signing_schemes::eddsa, signature, message, *public_key) + ? 0 + : 1; } diff --git a/test/messages/verify_eddsa_bytes_key/verify_eddsa_bytes_key.cpp b/test/messages/verify_eddsa_bytes_key/verify_eddsa_bytes_key.cpp index d56b56c3..b2e71f47 100644 --- a/test/messages/verify_eddsa_bytes_key/verify_eddsa_bytes_key.cpp +++ b/test/messages/verify_eddsa_bytes_key/verify_eddsa_bytes_key.cpp @@ -11,7 +11,7 @@ // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/signing.hpp:* {{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.}} +// expected-error@webcpp/crypto/signing.hpp:* {{webcpp::crypto: verify: this public key does not go with this scheme: crypto::signing_schemes::eddsa and crypto::signing_schemes::eddsa_prehashed take a curves::ed25519::public_key, crypto::signing_schemes::ecdsa_sha256 a curves::p256::basic_public_key or a curves::secp256k1::public_key, crypto::signing_schemes::schnorr a curves::secp256k1::public_key or a 32-byte x-only key; a crypto::signing_schemes::ecdsa_sha256_recoverable or a crypto::signing_schemes::ecdsa_keccak256_recoverable signature gives its key to curves::secp256k1::recover.}} // clang-format on #include #include @@ -23,6 +23,8 @@ int main() { namespace crypto = webcpp::crypto; crypto::curves::ed25519::signature const signature{}; std::array const message{'h', 'e', 'l', 'l', 'o'}; - return crypto::verify(crypto::eddsa, signature, message, std::array{}) ? 0 - : 1; + return crypto::verify(crypto::signing_schemes::eddsa, signature, message, + std::array{}) + ? 0 + : 1; } diff --git a/test/messages/verify_eddsa_prehashed_asynchronous_backend/verify_eddsa_prehashed_asynchronous_backend.cpp b/test/messages/verify_eddsa_prehashed_asynchronous_backend/verify_eddsa_prehashed_asynchronous_backend.cpp index 9ede86d0..ba691c64 100644 --- a/test/messages/verify_eddsa_prehashed_asynchronous_backend/verify_eddsa_prehashed_asynchronous_backend.cpp +++ b/test/messages/verify_eddsa_prehashed_asynchronous_backend/verify_eddsa_prehashed_asynchronous_backend.cpp @@ -4,16 +4,17 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// crypto::verify and the public key's own verify under crypto::eddsa_prehashed, named with a -// backend that completes by itself (a stand-in whose detail::asynchronous_backend_v is true), each -// stop at their first statement after the guard with the refusal that says WebCrypto has no -// Ed25519ph, and with those two errors alone: no engine is reached. Each form names a stand-in of -// its own, since one refusal of one backend is reported once however many calls reach it. +// crypto::verify and the public key's own verify under crypto::signing_schemes::eddsa_prehashed, +// named with a backend that completes by itself (a stand-in whose detail::asynchronous_backend_v is +// true), each stop at their first statement after the guard with the refusal that says WebCrypto +// has no Ed25519ph, and with those two errors alone: no engine is reached. Each form names a +// stand-in of its own, since one refusal of one backend is reported once however many calls reach +// it. // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/signing.hpp:* 2 {{webcpp::crypto: WebCrypto has no Ed25519ph: crypto::eddsa_prehashed's sign, verify, async_sign and async_verify run on a native backend.}} +// expected-error@webcpp/crypto/signing.hpp:* 2 {{webcpp::crypto: WebCrypto has no Ed25519ph: crypto::signing_schemes::eddsa_prehashed's sign, verify, async_sign and async_verify run on a native backend.}} // clang-format on #include #include @@ -44,10 +45,12 @@ bool verified(webcpp::crypto::curves::ed25519::public_key const& public_key) { namespace crypto = webcpp::crypto; crypto::curves::ed25519::signature const signature{}; std::array const digest{}; - auto const free_verified = crypto::verify( - crypto::eddsa_prehashed, signature, crypto::prehashed{digest}, public_key); + auto const free_verified = + crypto::verify(crypto::signing_schemes::eddsa_prehashed, signature, + crypto::signing_schemes::prehashed{digest}, public_key); auto const member_verified = public_key.verify( - crypto::eddsa_prehashed, signature, crypto::prehashed{digest}); + crypto::signing_schemes::eddsa_prehashed, signature, + crypto::signing_schemes::prehashed{digest}); return free_verified && member_verified; } diff --git a/test/messages/verify_eddsa_prehashed_message/verify_eddsa_prehashed_message.cpp b/test/messages/verify_eddsa_prehashed_message/verify_eddsa_prehashed_message.cpp index c3d3bfe0..8aa4c53b 100644 --- a/test/messages/verify_eddsa_prehashed_message/verify_eddsa_prehashed_message.cpp +++ b/test/messages/verify_eddsa_prehashed_message/verify_eddsa_prehashed_message.cpp @@ -4,14 +4,14 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// crypto::verify under crypto::eddsa_prehashed given a message stops at the input's check, as the -// key pair's sign does, which names crypto::prehashed{digest} of SHA-512's 64 bytes, and with -// that error alone. +// crypto::verify under crypto::signing_schemes::eddsa_prehashed given a message stops at the +// input's check, as the key pair's sign does, which names +// crypto::signing_schemes::prehashed{digest} of SHA-512's 64 bytes, and with that error alone. // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/signing.hpp:* {{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.}} +// expected-error@webcpp/crypto/signing.hpp:* {{webcpp::crypto: crypto::signing_schemes::eddsa_prehashed (RFC 8032's Ed25519ph) signs a digest, the message's SHA-512: crypto::signing_schemes::prehashed{digest} of a std::array; sign the message itself with crypto::signing_schemes::eddsa, or give it in pieces to curves::ed25519::prehashed_signer.}} // clang-format on #include #include @@ -25,7 +25,8 @@ int main() { crypto::curves::ed25519::public_key::from_bytes(std::array{}); crypto::curves::ed25519::signature const signature{}; std::array const message{'h', 'e', 'l', 'l', 'o'}; - return public_key && crypto::verify(crypto::eddsa_prehashed, signature, message, *public_key) + return public_key && crypto::verify(crypto::signing_schemes::eddsa_prehashed, signature, + message, *public_key) ? 0 : 1; } diff --git a/test/messages/verify_free_asynchronous_backend/verify_free_asynchronous_backend.cpp b/test/messages/verify_free_asynchronous_backend/verify_free_asynchronous_backend.cpp index bc410043..21c46701 100644 --- a/test/messages/verify_free_asynchronous_backend/verify_free_asynchronous_backend.cpp +++ b/test/messages/verify_free_asynchronous_backend/verify_free_asynchronous_backend.cpp @@ -37,7 +37,8 @@ bool verified(webcpp::crypto::curves::p256::basic_public_key c namespace crypto = webcpp::crypto; crypto::curves::p256::ecdsa_signature const signature{}; std::array const message{'h', 'e', 'l', 'l', 'o'}; - return crypto::verify(crypto::ecdsa_sha256, signature, message, public_key).has_value(); + return crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, message, public_key) + .has_value(); } } // namespace diff --git a/test/messages/verify_free_secp256k1_recoverable/verify_free_secp256k1_recoverable.cpp b/test/messages/verify_free_secp256k1_recoverable/verify_free_secp256k1_recoverable.cpp index 0b668c10..cf08fbae 100644 --- a/test/messages/verify_free_secp256k1_recoverable/verify_free_secp256k1_recoverable.cpp +++ b/test/messages/verify_free_secp256k1_recoverable/verify_free_secp256k1_recoverable.cpp @@ -12,7 +12,7 @@ // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/signing.hpp:* {{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.}} +// expected-error@webcpp/crypto/signing.hpp:* {{webcpp::crypto: verify: this public key does not go with this scheme: crypto::signing_schemes::eddsa and crypto::signing_schemes::eddsa_prehashed take a curves::ed25519::public_key, crypto::signing_schemes::ecdsa_sha256 a curves::p256::basic_public_key or a curves::secp256k1::public_key, crypto::signing_schemes::schnorr a curves::secp256k1::public_key or a 32-byte x-only key; a crypto::signing_schemes::ecdsa_sha256_recoverable or a crypto::signing_schemes::ecdsa_keccak256_recoverable signature gives its key to curves::secp256k1::recover.}} // clang-format on #include #include @@ -31,8 +31,8 @@ int main() { auto const public_key = key->public_key(); crypto::curves::secp256k1::recoverable_signature const signature{}; std::array const message{'h', 'e', 'l', 'l', 'o'}; - return public_key && - crypto::verify(crypto::ecdsa_sha256_recoverable, signature, message, *public_key) + return public_key && crypto::verify(crypto::signing_schemes::ecdsa_sha256_recoverable, + signature, message, *public_key) ? 0 : 1; } diff --git a/test/messages/verify_keccak_recoverable/verify_keccak_recoverable.cpp b/test/messages/verify_keccak_recoverable/verify_keccak_recoverable.cpp index 231e74bd..f0e485c5 100644 --- a/test/messages/verify_keccak_recoverable/verify_keccak_recoverable.cpp +++ b/test/messages/verify_keccak_recoverable/verify_keccak_recoverable.cpp @@ -11,7 +11,7 @@ // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/signing.hpp:* {{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.}} +// expected-error@webcpp/crypto/signing.hpp:* {{webcpp::crypto: verify: this public key does not go with this scheme: crypto::signing_schemes::eddsa and crypto::signing_schemes::eddsa_prehashed take a curves::ed25519::public_key, crypto::signing_schemes::ecdsa_sha256 a curves::p256::basic_public_key or a curves::secp256k1::public_key, crypto::signing_schemes::schnorr a curves::secp256k1::public_key or a 32-byte x-only key; a crypto::signing_schemes::ecdsa_sha256_recoverable or a crypto::signing_schemes::ecdsa_keccak256_recoverable signature gives its key to curves::secp256k1::recover.}} // clang-format on #include #include @@ -29,11 +29,11 @@ int main() { } auto const public_key = key->public_key(); std::array const digest{}; - auto const signature = - key->sign(crypto::ecdsa_keccak256_recoverable, crypto::prehashed{digest}); + auto const signature = key->sign(crypto::signing_schemes::ecdsa_keccak256_recoverable, + crypto::signing_schemes::prehashed{digest}); return public_key && signature && - crypto::verify(crypto::ecdsa_keccak256_recoverable, *signature, - crypto::prehashed{digest}, *public_key) + crypto::verify(crypto::signing_schemes::ecdsa_keccak256_recoverable, *signature, + crypto::signing_schemes::prehashed{digest}, *public_key) ? 0 : 1; } diff --git a/test/messages/verify_member_ed25519_ecdsa/verify_member_ed25519_ecdsa.cpp b/test/messages/verify_member_ed25519_ecdsa/verify_member_ed25519_ecdsa.cpp index 0e67c28f..87cb7d58 100644 --- a/test/messages/verify_member_ed25519_ecdsa/verify_member_ed25519_ecdsa.cpp +++ b/test/messages/verify_member_ed25519_ecdsa/verify_member_ed25519_ecdsa.cpp @@ -10,7 +10,7 @@ // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/curves/ed25519.hpp:* {{webcpp::crypto: an Ed25519 public key verifies crypto::eddsa or crypto::eddsa_prehashed.}} +// expected-error@webcpp/crypto/curves/ed25519.hpp:* {{webcpp::crypto: an Ed25519 public key verifies crypto::signing_schemes::eddsa or crypto::signing_schemes::eddsa_prehashed.}} // clang-format on #include #include @@ -24,5 +24,8 @@ int main() { crypto::curves::ed25519::public_key::from_bytes(std::array{}); crypto::curves::ed25519::signature const signature{}; std::array const message{'h', 'e', 'l', 'l', 'o'}; - return public_key && public_key->verify(crypto::ecdsa_sha256, signature, message) ? 0 : 1; + return public_key && + public_key->verify(crypto::signing_schemes::ecdsa_sha256, signature, message) + ? 0 + : 1; } diff --git a/test/messages/verify_member_eddsa_prehashed/verify_member_eddsa_prehashed.cpp b/test/messages/verify_member_eddsa_prehashed/verify_member_eddsa_prehashed.cpp index c8a0a3d1..b3588dd1 100644 --- a/test/messages/verify_member_eddsa_prehashed/verify_member_eddsa_prehashed.cpp +++ b/test/messages/verify_member_eddsa_prehashed/verify_member_eddsa_prehashed.cpp @@ -4,15 +4,15 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// An Ed25519 public key's own verify given a digest marked as one, crypto::prehashed{digest}, -// under crypto::eddsa stops at the input's check, as crypto::verify does, which says that pure -// Ed25519 verifies the message itself and names crypto::eddsa_prehashed (Ed25519ph), and with that -// error alone. +// An Ed25519 public key's own verify given a digest marked as one, +// crypto::signing_schemes::prehashed{digest}, under crypto::signing_schemes::eddsa stops at the +// input's check, as crypto::verify does, which says that pure Ed25519 verifies the message itself +// and names crypto::signing_schemes::eddsa_prehashed (Ed25519ph), and with that error alone. // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/signing.hpp:* {{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).}} +// expected-error@webcpp/crypto/signing.hpp:* {{webcpp::crypto: crypto::signing_schemes::eddsa signs the message itself (RFC 8032's pure Ed25519) and takes no digest; a message's SHA-512 is signed with crypto::signing_schemes::eddsa_prehashed (Ed25519ph).}} // clang-format on #include #include @@ -26,7 +26,8 @@ int main() { crypto::curves::ed25519::public_key::from_bytes(std::array{}); crypto::curves::ed25519::signature const signature{}; std::array const digest{}; - return public_key && public_key->verify(crypto::eddsa, signature, crypto::prehashed{digest}) + return public_key && public_key->verify(crypto::signing_schemes::eddsa, signature, + crypto::signing_schemes::prehashed{digest}) ? 0 : 1; } diff --git a/test/messages/verify_member_p256_eddsa/verify_member_p256_eddsa.cpp b/test/messages/verify_member_p256_eddsa/verify_member_p256_eddsa.cpp index 093598f6..54679cb8 100644 --- a/test/messages/verify_member_p256_eddsa/verify_member_p256_eddsa.cpp +++ b/test/messages/verify_member_p256_eddsa/verify_member_p256_eddsa.cpp @@ -10,7 +10,7 @@ // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/curves/p256.hpp:* {{webcpp::crypto: a P-256 public key verifies crypto::ecdsa_sha256.}} +// expected-error@webcpp/crypto/curves/p256.hpp:* {{webcpp::crypto: a P-256 public key verifies crypto::signing_schemes::ecdsa_sha256.}} // clang-format on #include #include @@ -30,5 +30,6 @@ int main() { auto const public_key = key->public_key(); crypto::curves::p256::ecdsa_signature const signature{}; std::array const message{'h', 'e', 'l', 'l', 'o'}; - return public_key && public_key->verify(crypto::eddsa, signature, message) ? 0 : 1; + return public_key && public_key->verify(crypto::signing_schemes::eddsa, signature, message) ? 0 + : 1; } diff --git a/test/messages/verify_member_secp256k1_recoverable/verify_member_secp256k1_recoverable.cpp b/test/messages/verify_member_secp256k1_recoverable/verify_member_secp256k1_recoverable.cpp index d6e80ccd..a0626f1b 100644 --- a/test/messages/verify_member_secp256k1_recoverable/verify_member_secp256k1_recoverable.cpp +++ b/test/messages/verify_member_secp256k1_recoverable/verify_member_secp256k1_recoverable.cpp @@ -11,7 +11,7 @@ // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/curves/secp256k1.hpp:* {{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.}} +// expected-error@webcpp/crypto/curves/secp256k1.hpp:* {{webcpp::crypto: a secp256k1 public key verifies crypto::signing_schemes::ecdsa_sha256 or crypto::signing_schemes::schnorr; a crypto::signing_schemes::ecdsa_sha256_recoverable or a crypto::signing_schemes::ecdsa_keccak256_recoverable signature gives its key to curves::secp256k1::recover.}} // clang-format on #include #include @@ -30,7 +30,8 @@ int main() { auto const public_key = key->public_key(); crypto::curves::secp256k1::recoverable_signature const signature{}; std::array const message{'h', 'e', 'l', 'l', 'o'}; - return public_key && public_key->verify(crypto::ecdsa_sha256_recoverable, signature, message) + return public_key && public_key->verify(crypto::signing_schemes::ecdsa_sha256_recoverable, + signature, message) ? 0 : 1; } diff --git a/test/messages/verify_p256_secp256k1_signature/verify_p256_secp256k1_signature.cpp b/test/messages/verify_p256_secp256k1_signature/verify_p256_secp256k1_signature.cpp index 04c0be5f..33025259 100644 --- a/test/messages/verify_p256_secp256k1_signature/verify_p256_secp256k1_signature.cpp +++ b/test/messages/verify_p256_secp256k1_signature/verify_p256_secp256k1_signature.cpp @@ -32,6 +32,8 @@ int main() { auto const public_key = key->public_key(); crypto::curves::secp256k1::ecdsa_signature const signature{}; std::array const message{'h', 'e', 'l', 'l', 'o'}; - return public_key && crypto::verify(crypto::ecdsa_sha256, signature, message, *public_key) ? 0 - : 1; + return public_key && crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, message, + *public_key) + ? 0 + : 1; } diff --git a/test/messages/verify_schnorr_as_ecdsa/verify_schnorr_as_ecdsa.cpp b/test/messages/verify_schnorr_as_ecdsa/verify_schnorr_as_ecdsa.cpp index 0f630d0c..209f59a3 100644 --- a/test/messages/verify_schnorr_as_ecdsa/verify_schnorr_as_ecdsa.cpp +++ b/test/messages/verify_schnorr_as_ecdsa/verify_schnorr_as_ecdsa.cpp @@ -11,7 +11,7 @@ // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/signing.hpp:* {{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.}} +// expected-error@webcpp/crypto/signing.hpp:* {{webcpp::crypto: verify: a secp256k1 key verifies a curves::secp256k1::ecdsa_signature under crypto::signing_schemes::ecdsa_sha256: make one from 64 bytes with curves::secp256k1::ecdsa_signature::from_bytes.}} // clang-format on #include #include @@ -29,9 +29,10 @@ int main() { } auto const public_key = key->public_key(); std::array const message{'h', 'e', 'l', 'l', 'o'}; - auto const signature = key->sign(crypto::schnorr, message); + auto const signature = key->sign(crypto::signing_schemes::schnorr, message); return public_key && signature && - crypto::verify(crypto::ecdsa_sha256, *signature, message, *public_key) + crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signature, message, + *public_key) ? 0 : 1; } diff --git a/test/msvc/async_sign_secp256k1/app.cpp b/test/msvc/async_sign_secp256k1/app.cpp index 74a8f312..0f06ef1f 100644 --- a/test/msvc/async_sign_secp256k1/app.cpp +++ b/test/msvc/async_sign_secp256k1/app.cpp @@ -26,7 +26,7 @@ int main() { return 1; } webcpp::asio::io_context context; - crypto::async_sign(context.get_executor(), *made, crypto::ecdsa_sha256, message, - [](boost::system::error_code, std::array) {}); + crypto::async_sign(context.get_executor(), *made, crypto::signing_schemes::ecdsa_sha256, + message, [](boost::system::error_code, std::array) {}); return 0; } diff --git a/test/msvc/canary_secp256k1_missing/app.cpp b/test/msvc/canary_secp256k1_missing/app.cpp index 9c74a121..c936e3b7 100644 --- a/test/msvc/canary_secp256k1_missing/app.cpp +++ b/test/msvc/canary_secp256k1_missing/app.cpp @@ -18,5 +18,5 @@ int main() { std::array const message{}; std::array const aux{}; auto key = webcpp::crypto::curves::secp256k1::keypair::from_secret(secret); - return key && key->sign(webcpp::crypto::schnorr, message, aux) ? 0 : 1; + return key && key->sign(webcpp::crypto::signing_schemes::schnorr, message, aux) ? 0 : 1; } diff --git a/test/msvc/canary_secp256k1_small/app.cpp b/test/msvc/canary_secp256k1_small/app.cpp index 9c74a121..c936e3b7 100644 --- a/test/msvc/canary_secp256k1_small/app.cpp +++ b/test/msvc/canary_secp256k1_small/app.cpp @@ -18,5 +18,5 @@ int main() { std::array const message{}; std::array const aux{}; auto key = webcpp::crypto::curves::secp256k1::keypair::from_secret(secret); - return key && key->sign(webcpp::crypto::schnorr, message, aux) ? 0 : 1; + return key && key->sign(webcpp::crypto::signing_schemes::schnorr, message, aux) ? 0 : 1; } diff --git a/test/msvc/canary_secp256k1_two_files/app.cpp b/test/msvc/canary_secp256k1_two_files/app.cpp index 46c94371..4a70e2fb 100644 --- a/test/msvc/canary_secp256k1_two_files/app.cpp +++ b/test/msvc/canary_secp256k1_two_files/app.cpp @@ -22,5 +22,7 @@ int main() { std::array const message{}; std::array const aux{}; auto key = webcpp::crypto::curves::secp256k1::keypair::from_secret(secret); - return key && key->sign(webcpp::crypto::schnorr, message, aux) && sign_other() ? 0 : 1; + return key && key->sign(webcpp::crypto::signing_schemes::schnorr, message, aux) && sign_other() + ? 0 + : 1; } diff --git a/test/msvc/canary_secp256k1_two_files/other.cpp b/test/msvc/canary_secp256k1_two_files/other.cpp index 22da0902..f17436fa 100644 --- a/test/msvc/canary_secp256k1_two_files/other.cpp +++ b/test/msvc/canary_secp256k1_two_files/other.cpp @@ -28,5 +28,5 @@ bool sign_other() { std::array const message{}; std::array const aux{}; auto key = webcpp::crypto::curves::secp256k1::keypair::from_secret(secret); - return key && key->sign(webcpp::crypto::schnorr, message, aux); + return key && key->sign(webcpp::crypto::signing_schemes::schnorr, message, aux); } diff --git a/test/msvc/ed25519_unknown_policy/app.cpp b/test/msvc/ed25519_unknown_policy/app.cpp index 81e6cd29..67bb2cde 100644 --- a/test/msvc/ed25519_unknown_policy/app.cpp +++ b/test/msvc/ed25519_unknown_policy/app.cpp @@ -26,7 +26,7 @@ int main() { webcpp::crypto::curves::ed25519::public_key::from_bytes(std::array{}); webcpp::crypto::curves::ed25519::signature const signature{}; return public_key && - webcpp::crypto::verify(webcpp::crypto::eddsa, signature, + webcpp::crypto::verify(webcpp::crypto::signing_schemes::eddsa, signature, std::span{}, *public_key, lenient{}) ? 0 : 1; diff --git a/test/msvc/sign_eddsa_prehashed_message/app.cpp b/test/msvc/sign_eddsa_prehashed_message/app.cpp index 36956cb4..4ab22f05 100644 --- a/test/msvc/sign_eddsa_prehashed_message/app.cpp +++ b/test/msvc/sign_eddsa_prehashed_message/app.cpp @@ -4,9 +4,9 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// An Ed25519 key pair asked to sign a message under crypto::eddsa_prehashed, a 64-byte -// std::array, stops at the input's check: on MSVC the compile fails. The text is checked on clang, -// in test/messages/sign_eddsa_prehashed_message. +// An Ed25519 key pair asked to sign a message under crypto::signing_schemes::eddsa_prehashed, a +// 64-byte std::array, stops at the input's check: on MSVC the compile fails. The text is checked on +// clang, in test/messages/sign_eddsa_prehashed_message. #include #include @@ -17,5 +17,8 @@ int main() { namespace crypto = webcpp::crypto; std::array const seed{}; auto const key = crypto::curves::ed25519::keypair::from_secret(seed); - return key && key->sign(crypto::eddsa_prehashed, std::array{}) ? 0 : 1; + return key && key->sign(crypto::signing_schemes::eddsa_prehashed, + std::array{}) + ? 0 + : 1; } diff --git a/test/msvc/sign_keccak_without_xkcp/app.cpp b/test/msvc/sign_keccak_without_xkcp/app.cpp index 213dab9f..80545000 100644 --- a/test/msvc/sign_keccak_without_xkcp/app.cpp +++ b/test/msvc/sign_keccak_without_xkcp/app.cpp @@ -19,5 +19,5 @@ int main() { secret_key.back() = 1; std::array const message{'h', 'e', 'l', 'l', 'o'}; auto const key = crypto::curves::secp256k1::keypair::from_secret(secret_key); - return key && key->sign(crypto::ecdsa_keccak256_recoverable, message) ? 0 : 1; + return key && key->sign(crypto::signing_schemes::ecdsa_keccak256_recoverable, message) ? 0 : 1; } diff --git a/test/oracle_25519_test.cpp b/test/oracle_25519_test.cpp index 64acf307..a1ae554c 100644 --- a/test/oracle_25519_test.cpp +++ b/test/oracle_25519_test.cpp @@ -164,13 +164,14 @@ bool ed25519_case(std::mt19937_64& rng, std::size_t index) { return false; } auto const public_key = pair->public_key(); - auto const signed_message = pair->sign(crypto::eddsa, message); + auto const signed_message = pair->sign(crypto::signing_schemes::eddsa, message); BOOST_TEST(public_key.has_value()); BOOST_TEST(signed_message.has_value()); if (!public_key || !signed_message) { return false; } - BOOST_TEST(crypto::verify(crypto::eddsa, *signed_message, message, *public_key).has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, *signed_message, message, *public_key) + .has_value()); // The signature's bytes, as WebCrypto is given them. auto signature = signed_message->bytes(); if (corrupted && index == corrupted_ed25519) { diff --git a/test/p256_ecdsa_bearssl_test.cpp b/test/p256_ecdsa_bearssl_test.cpp index 76376a79..aa9b5812 100644 --- a/test/p256_ecdsa_bearssl_test.cpp +++ b/test/p256_ecdsa_bearssl_test.cpp @@ -138,13 +138,16 @@ void rfc6979_signatures() { if (!BOOST_TEST(key.has_value())) { return; } - auto const sample = key->sign(crypto::ecdsa_sha256, crypto::prehashed{sha256("sample")}); - auto const test = key->sign(crypto::ecdsa_sha256, crypto::prehashed{sha256("test")}); + auto const sample = key->sign(crypto::signing_schemes::ecdsa_sha256, + crypto::signing_schemes::prehashed{sha256("sample")}); + auto const test = key->sign(crypto::signing_schemes::ecdsa_sha256, + crypto::signing_schemes::prehashed{sha256("test")}); if (BOOST_TEST(sample.has_value()) && BOOST_TEST(test.has_value())) { BOOST_TEST(sample->bytes() == data::rfc6979_sample_low_s); BOOST_TEST(test->bytes() == data::rfc6979_test); } - auto const again = key->sign(crypto::ecdsa_sha256, crypto::prehashed{sha256("sample")}); + auto const again = key->sign(crypto::signing_schemes::ecdsa_sha256, + crypto::signing_schemes::prehashed{sha256("sample")}); if (BOOST_TEST(again.has_value()) && sample.has_value()) { BOOST_TEST(*again == *sample); } @@ -159,8 +162,8 @@ void sign_normalizes_raw_s() { if (!BOOST_TEST(key.has_value())) { return; } - auto const sample = key->sign(crypto::ecdsa_sha256, text_bytes("sample")); - auto const test = key->sign(crypto::ecdsa_sha256, text_bytes("test")); + auto const sample = key->sign(crypto::signing_schemes::ecdsa_sha256, text_bytes("sample")); + auto const test = key->sign(crypto::signing_schemes::ecdsa_sha256, text_bytes("test")); if (BOOST_TEST(sample.has_value()) && BOOST_TEST(test.has_value())) { BOOST_TEST(std::ranges::equal(r_of(*sample), r_of(data::rfc6979_sample))); BOOST_TEST(std::ranges::equal(s_of(*sample), negated(s_of(data::rfc6979_sample)))); @@ -201,7 +204,8 @@ void rfc6979_sample_message() { auto const section_s = hex<32>("f7cb1c942d657c41d436c7a1b6e29f65f3e900dbb9aff4064dc4ab2f843acda8"); auto const received = signature::from_bytes(joined(section_r, section_s)); - auto const signed_message = key->sign(crypto::ecdsa_sha256, text_bytes("sample")); + auto const signed_message = + key->sign(crypto::signing_schemes::ecdsa_sha256, text_bytes("sample")); if (!BOOST_TEST(received.has_value()) || !BOOST_TEST(signed_message.has_value())) { return; } @@ -209,11 +213,12 @@ void rfc6979_sample_message() { auto const& section = *received; BOOST_TEST(std::ranges::equal(r_of(*signed_message), section_r)); BOOST_TEST(std::ranges::equal(s_of(*signed_message), negated(section_s))); - BOOST_TEST( - crypto::verify(crypto::ecdsa_sha256, section, text_bytes("sample"), *verifier).has_value()); - BOOST_TEST( - crypto::verify(crypto::ecdsa_sha256, *signed_message, text_bytes("sample"), *verifier) - .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, section, text_bytes("sample"), + *verifier) + .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signed_message, + text_bytes("sample"), *verifier) + .has_value()); BOOST_TEST(!p256::is_low_s(section)); BOOST_TEST(p256::is_low_s(*signed_message)); auto const normalized = p256::normalize_low_s(section); @@ -231,8 +236,8 @@ void verify_both_forms() { auto const test = sha256("test"); auto const verified = [](signature_bytes const& value, digest const& hash, public_key const& verifier) { - return crypto::verify(crypto::ecdsa_sha256, typed(value), crypto::prehashed{hash}, - verifier); + return crypto::verify(crypto::signing_schemes::ecdsa_sha256, typed(value), + crypto::signing_schemes::prehashed{hash}, verifier); }; BOOST_TEST(verified(data::rfc6979_sample, sample, *key).has_value()); BOOST_TEST(verified(data::rfc6979_sample_low_s, sample, *key).has_value()); @@ -287,20 +292,24 @@ void message_is_hashed() { for (std::size_t i = 0; i < message.size(); ++i) { message[i] = static_cast((i * 7) + 1); } - auto const of_message = key->sign(crypto::ecdsa_sha256, message); + auto const of_message = key->sign(crypto::signing_schemes::ecdsa_sha256, message); auto const of_digest = - key->sign(crypto::ecdsa_sha256, crypto::prehashed{crypto::detail::sha256_of(message)}); - auto const of_marker = key->sign(crypto::ecdsa_sha256, crypto::prehashed{message}); + key->sign(crypto::signing_schemes::ecdsa_sha256, + crypto::signing_schemes::prehashed{crypto::detail::sha256_of(message)}); + auto const of_marker = key->sign(crypto::signing_schemes::ecdsa_sha256, + crypto::signing_schemes::prehashed{message}); if (!BOOST_TEST(of_message.has_value()) || !BOOST_TEST(of_digest.has_value()) || !BOOST_TEST(of_marker.has_value())) { return; } BOOST_TEST(*of_message == *of_digest); BOOST_TEST(*of_message != *of_marker); - BOOST_TEST(crypto::verify(crypto::ecdsa_sha256, *of_message, message, *verifier).has_value()); BOOST_TEST( - crypto::verify(crypto::ecdsa_sha256, *of_message, crypto::prehashed{message}, *verifier) - .error() == error::invalid_signature); + crypto::verify(crypto::signing_schemes::ecdsa_sha256, *of_message, message, *verifier) + .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *of_message, + crypto::signing_schemes::prehashed{message}, *verifier) + .error() == error::invalid_signature); } // The empty message is a message: signed, its SHA-256 signed, and verified. @@ -311,17 +320,20 @@ void empty_message() { return; } std::span const empty{}; - auto const signed_empty = key->sign(crypto::ecdsa_sha256, empty); + auto const signed_empty = key->sign(crypto::signing_schemes::ecdsa_sha256, empty); if (!BOOST_TEST(signed_empty.has_value())) { return; } - BOOST_TEST(crypto::verify(crypto::ecdsa_sha256, *signed_empty, empty, *verifier).has_value()); - BOOST_TEST(crypto::verify(crypto::ecdsa_sha256, *signed_empty, - crypto::prehashed{crypto::detail::sha256_of(empty)}, *verifier) - .has_value()); BOOST_TEST( - crypto::verify(crypto::ecdsa_sha256, *signed_empty, text_bytes("x"), *verifier).error() == - error::invalid_signature); + crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signed_empty, empty, *verifier) + .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signed_empty, + crypto::signing_schemes::prehashed{crypto::detail::sha256_of(empty)}, + *verifier) + .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signed_empty, text_bytes("x"), + *verifier) + .error() == error::invalid_signature); } // A digest that is 0 modulo n (32 zero bytes, or n) signs, and BearSSL's verification refuses @@ -335,10 +347,11 @@ void zero_digest() { return; } for (digest const& hash : {digest{}, data::order}) { - auto const signed_hash = key->sign(crypto::ecdsa_sha256, crypto::prehashed{hash}); + auto const signed_hash = key->sign(crypto::signing_schemes::ecdsa_sha256, + crypto::signing_schemes::prehashed{hash}); if (BOOST_TEST(signed_hash.has_value())) { - BOOST_TEST(crypto::verify(crypto::ecdsa_sha256, *signed_hash, crypto::prehashed{hash}, - *verifier) + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signed_hash, + crypto::signing_schemes::prehashed{hash}, *verifier) .error() == error::invalid_signature); } } @@ -418,17 +431,19 @@ void low_s_random(std::uint64_t seed) { for (int i = 0; i < 1000; ++i) { digest hash{}; draw(generator, hash); - auto const signed_hash = key.sign(crypto::ecdsa_sha256, crypto::prehashed{hash}); + auto const signed_hash = key.sign(crypto::signing_schemes::ecdsa_sha256, + crypto::signing_schemes::prehashed{hash}); if (!BOOST_TEST(signed_hash.has_value())) { return; } BOOST_TEST(p256::is_low_s(*signed_hash)); - BOOST_TEST( - crypto::verify(crypto::ecdsa_sha256, *signed_hash, crypto::prehashed{hash}, *verifier) - .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signed_hash, + crypto::signing_schemes::prehashed{hash}, *verifier) + .has_value()); auto const high = typed(joined(r_of(*signed_hash), negated(s_of(*signed_hash)))); BOOST_TEST(!p256::is_low_s(high)); - BOOST_TEST(crypto::verify(crypto::ecdsa_sha256, high, crypto::prehashed{hash}, *verifier) + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, high, + crypto::signing_schemes::prehashed{hash}, *verifier) .has_value()); auto const normalized = p256::normalize_low_s(high); if (!BOOST_TEST(normalized.has_value())) { @@ -447,13 +462,14 @@ void always_low_s(std::uint64_t seed) { auto const verifier = key.public_key(); bytes message(static_cast(generator() % 200)); draw(generator, message); - auto const signed_message = key.sign(crypto::ecdsa_sha256, message); + auto const signed_message = key.sign(crypto::signing_schemes::ecdsa_sha256, message); if (!BOOST_TEST(signed_message.has_value()) || !BOOST_TEST(verifier.has_value())) { return; } BOOST_TEST(p256::is_low_s(*signed_message)); - BOOST_TEST( - crypto::verify(crypto::ecdsa_sha256, *signed_message, message, *verifier).has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signed_message, message, + *verifier) + .has_value()); } } @@ -569,7 +585,8 @@ void signature_from_vector() { if (!BOOST_TEST(key.has_value()) || !BOOST_TEST(verifier.has_value())) { return; } - auto const signed_message = key->sign(crypto::ecdsa_sha256, text_bytes("sample")); + auto const signed_message = + key->sign(crypto::signing_schemes::ecdsa_sha256, text_bytes("sample")); if (!BOOST_TEST(signed_message.has_value())) { return; } @@ -579,9 +596,11 @@ void signature_from_vector() { return; } BOOST_TEST(*made == *signed_message); - BOOST_TEST(verifier->verify(crypto::ecdsa_sha256, *made, text_bytes("sample")).has_value()); - BOOST_TEST( - crypto::verify(crypto::ecdsa_sha256, *made, text_bytes("sample"), *verifier).has_value()); + BOOST_TEST(verifier->verify(crypto::signing_schemes::ecdsa_sha256, *made, text_bytes("sample")) + .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *made, text_bytes("sample"), + *verifier) + .has_value()); BOOST_TEST(crypto::from_bytes(received).has_value()); for (std::size_t const size : {std::size_t{63}, std::size_t{65}}) { bytes resized = received; @@ -591,27 +610,31 @@ void signature_from_vector() { } // A key pair signs and its public key verifies; never the other way round. -static_assert(crypto::can_sign>); -static_assert(crypto::can_sign>); -static_assert(crypto::can_verify, - public_key>); -static_assert(!crypto::can_sign, - crypto::ecdsa_sha256_t, std::span>); +static_assert(crypto::can_sign>); +static_assert(crypto::can_sign>); +static_assert(crypto::can_verify, public_key>); static_assert( - !crypto::can_verify, keypair>); + !crypto::can_sign, + crypto::signing_schemes::ecdsa_sha256_t, std::span>); +static_assert(!crypto::can_verify, keypair>); // Bytes are no P-256 key: ECDSA never infers its curve from a number of bytes. -static_assert(!crypto::can_verify, - std::array>); +static_assert(!crypto::can_verify, std::array>); // Bytes are no P-256 signature (design R1): verify takes the type alone. -static_assert(!crypto::can_verify, public_key>); -static_assert(!crypto::can_verify, +static_assert(!crypto::can_verify, public_key>); -// sign gives the type. static_assert( - std::is_same_v().sign( - crypto::ecdsa_sha256, std::declval>())), - boost::system::result>); + !crypto::can_verify, + std::span, public_key>); +// sign gives the type. +static_assert(std::is_same_v().sign( + crypto::signing_schemes::ecdsa_sha256, + std::declval>())), + boost::system::result>); } // namespace diff --git a/test/p256_keys_bearssl_test.cpp b/test/p256_keys_bearssl_test.cpp index f753e3ab..d3bdb453 100644 --- a/test/p256_keys_bearssl_test.cpp +++ b/test/p256_keys_bearssl_test.cpp @@ -233,9 +233,11 @@ void moved_from() { BOOST_TEST(a.public_key().error() == error::invalid_state); BOOST_TEST(a.secret().error() == error::invalid_state); std::array const digest{}; - BOOST_TEST(a.sign(crypto::ecdsa_sha256, digest).error() == error::invalid_state); - BOOST_TEST(a.sign(crypto::ecdsa_sha256, crypto::prehashed{digest}).error() == + BOOST_TEST(a.sign(crypto::signing_schemes::ecdsa_sha256, digest).error() == error::invalid_state); + BOOST_TEST( + a.sign(crypto::signing_schemes::ecdsa_sha256, crypto::signing_schemes::prehashed{digest}) + .error() == error::invalid_state); auto const peer = b.public_key(); BOOST_TEST(peer.has_value() && a.agree(*peer).error() == error::invalid_state); // NOLINTEND(bugprone-use-after-move,clang-analyzer-cplusplus.Move) @@ -326,9 +328,11 @@ void secret_round_trip() { BOOST_TEST(first_point && again_point && first_point->uncompressed() == again_point->uncompressed()); std::array const message{'a', 'b', 'c'}; - auto const signature = again->sign(crypto::ecdsa_sha256, message); - BOOST_TEST(signature && first_point && - crypto::verify(crypto::ecdsa_sha256, *signature, message, *first_point).has_value()); + auto const signature = again->sign(crypto::signing_schemes::ecdsa_sha256, message); + BOOST_TEST( + signature && first_point && + crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signature, message, *first_point) + .has_value()); } } // namespace diff --git a/test/p256_openssl_oracle_test.cpp b/test/p256_openssl_oracle_test.cpp index 6bea4b3a..f85cf6b5 100644 --- a/test/p256_openssl_oracle_test.cpp +++ b/test/p256_openssl_oracle_test.cpp @@ -315,9 +315,9 @@ bool signature_case(std::mt19937_64& generator, std::size_t index) { auto const digest = drawn_digest(generator); auto const pair = p256::keypair::from_secret(scalar); auto const public_key = pair ? pair->public_key() : webcpp::crypto::error::backend_failure; - auto const ours = - pair ? pair->sign(webcpp::crypto::ecdsa_sha256, webcpp::crypto::prehashed{digest}) - : webcpp::crypto::error::backend_failure; + auto const ours = pair ? pair->sign(webcpp::crypto::signing_schemes::ecdsa_sha256, + webcpp::crypto::signing_schemes::prehashed{digest}) + : webcpp::crypto::error::backend_failure; pkey_ptr const key = openssl_key(scalar); if (!BOOST_TEST(public_key.has_value()) || !BOOST_TEST(ours.has_value()) || !BOOST_TEST(key)) { return false; @@ -335,8 +335,9 @@ bool signature_case(std::mt19937_64& generator, std::size_t index) { BOOST_TEST(der_size.has_value()) && BOOST_TEST(openssl_verifies(key.get(), std::span(der).first(*der_size), digest)); bool const we_verify_theirs = - BOOST_TEST(theirs && webcpp::crypto::verify(webcpp::crypto::ecdsa_sha256, *theirs, - webcpp::crypto::prehashed{digest}, *public_key) + BOOST_TEST(theirs && webcpp::crypto::verify( + webcpp::crypto::signing_schemes::ecdsa_sha256, *theirs, + webcpp::crypto::signing_schemes::prehashed{digest}, *public_key) .has_value()); bool const agrees = same_point && same_signature && openssl_verifies_ours && we_verify_theirs; if (!agrees) { diff --git a/test/p256_webcrypto_oracle_test.cpp b/test/p256_webcrypto_oracle_test.cpp index a7711c3d..70c62636 100644 --- a/test/p256_webcrypto_oracle_test.cpp +++ b/test/p256_webcrypto_oracle_test.cpp @@ -257,8 +257,10 @@ void judge(our_case const& ours, oracle_answer const& answer, p256::public_key c auto const theirs = p256::ecdsa_signature::from_bytes(answer.signature); bool const we_verify = ran && theirs.has_value() && - crypto::verify(crypto::ecdsa_sha256, *theirs, ours.message, public_key).has_value() && - crypto::verify(crypto::ecdsa_sha256, *theirs, crypto::prehashed{ours.digest}, public_key) + crypto::verify(crypto::signing_schemes::ecdsa_sha256, *theirs, ours.message, public_key) + .has_value() && + crypto::verify(crypto::signing_schemes::ecdsa_sha256, *theirs, + crypto::signing_schemes::prehashed{ours.digest}, public_key) .has_value(); found.check(we_verify, "we verify WebCrypto's", index); if (ran && theirs.has_value() && p256::is_low_s(*theirs)) { @@ -295,7 +297,7 @@ void one_case(std::mt19937_64& rng, std::size_t index, tally& found) { return; } ours.digest = sha256(ours.message); - auto const signature = pair->sign(crypto::ecdsa_sha256, ours.message); + auto const signature = pair->sign(crypto::signing_schemes::ecdsa_sha256, ours.message); auto const shared = pair->agree(*peer_public_key); BOOST_TEST(p256::encode_spki(*public_key, ours.spki).has_value()); BOOST_TEST(p256::encode_pkcs8(*pair, ours.pkcs8).has_value()); @@ -304,7 +306,8 @@ void one_case(std::mt19937_64& rng, std::size_t index, tally& found) { } BOOST_TEST(p256::is_low_s(*signature)); BOOST_TEST( - crypto::verify(crypto::ecdsa_sha256, *signature, ours.message, *public_key).has_value()); + crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signature, ours.message, *public_key) + .has_value()); ours.signature = signature->bytes(); if (corrupted && index == corrupted_signature) { ours.signature[5] ^= 0x01U; diff --git a/test/p256_wycheproof_bearssl_test.cpp b/test/p256_wycheproof_bearssl_test.cpp index 86e963ef..00525397 100644 --- a/test/p256_wycheproof_bearssl_test.cpp +++ b/test/p256_wycheproof_bearssl_test.cpp @@ -87,9 +87,11 @@ struct counts { // differ is reported. bool verified_both_ways(std::string const& name, json::value const& t, signature const& value, std::span message, p256::public_key const& key) { - bool const verified = crypto::verify(crypto::ecdsa_sha256, value, message, key).has_value(); + bool const verified = + crypto::verify(crypto::signing_schemes::ecdsa_sha256, value, message, key).has_value(); bool const verified_digest = - crypto::verify(crypto::ecdsa_sha256, value, crypto::prehashed{sha256(message)}, key) + crypto::verify(crypto::signing_schemes::ecdsa_sha256, value, + crypto::signing_schemes::prehashed{sha256(message)}, key) .has_value(); if (verified != verified_digest) { report(name, t, "message and digest verified differently"); diff --git a/test/secp256k1_allocation_test.cpp b/test/secp256k1_allocation_test.cpp index 1f669fda..d912285f 100644 --- a/test/secp256k1_allocation_test.cpp +++ b/test/secp256k1_allocation_test.cpp @@ -203,11 +203,11 @@ int main() { BOOST_TEST_EQ(resource.alignment, alignof(std::max_align_t)); secp::keypair key = std::move(*made); - crypto::prehashed const digest{message}; - auto const schnorr = key.sign(crypto::schnorr, message, aux); - auto const drawn = key.sign(crypto::schnorr, message); - auto const ecdsa = key.sign(crypto::ecdsa_sha256, digest); - auto const of_message = key.sign(crypto::ecdsa_sha256, message); + crypto::signing_schemes::prehashed const digest{message}; + auto const schnorr = key.sign(crypto::signing_schemes::schnorr, message, aux); + auto const drawn = key.sign(crypto::signing_schemes::schnorr, message); + auto const ecdsa = key.sign(crypto::signing_schemes::ecdsa_sha256, digest); + auto const of_message = key.sign(crypto::signing_schemes::ecdsa_sha256, message); auto const public_key = key.public_key(); auto const secret_key = key.secret(); if (!BOOST_TEST(public_key.has_value())) { @@ -217,18 +217,23 @@ int main() { auto const shared = key.agree_hashed(*public_key); auto const shared_x = key.agree(*public_key); auto const shared_point = key.agree_point(*public_key); - auto const hedged = key.sign(crypto::ecdsa_sha256, digest, aux); - auto const recoverable = key.sign(crypto::ecdsa_sha256_recoverable, digest); + auto const hedged = key.sign(crypto::signing_schemes::ecdsa_sha256, digest, aux); + auto const recoverable = + key.sign(crypto::signing_schemes::ecdsa_sha256_recoverable, digest); auto const uncompressed = public_key->uncompressed(); auto const compressed = public_key->compressed(); auto const verifier = secp::public_key::from_bytes(compressed); BOOST_TEST(schnorr && ecdsa && secret_key && shared && shared_x && shared_point); BOOST_TEST(drawn && of_message && hedged && recoverable && verifier); - BOOST_TEST(crypto::verify(crypto::schnorr, *schnorr, message, xonly).has_value()); - BOOST_TEST(crypto::verify(crypto::schnorr, *drawn, message, *public_key).has_value()); - BOOST_TEST(crypto::verify(crypto::ecdsa_sha256, *ecdsa, digest, *verifier).has_value()); BOOST_TEST( - crypto::verify(crypto::ecdsa_sha256, *of_message, message, *verifier).has_value()); + crypto::verify(crypto::signing_schemes::schnorr, *schnorr, message, xonly).has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, *drawn, message, *public_key) + .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *ecdsa, digest, *verifier) + .has_value()); + BOOST_TEST( + crypto::verify(crypto::signing_schemes::ecdsa_sha256, *of_message, message, *verifier) + .has_value()); BOOST_TEST_EQ(webcpp::test::allocations(), before); // Each of the DER and low-S functions and the x-only tweak, alone: no allocation. @@ -256,8 +261,10 @@ int main() { none("public_key::compressed", [&] { return parsed->compressed() == compressed; }); none("public_key::uncompressed", [&] { return parsed->uncompressed() == uncompressed; }); none("public_key::xonly", [&] { return parsed->xonly() == xonly; }); - none("recover", - [&] { return secp::recover(crypto::ecdsa_sha256_recoverable, *recoverable, digest); }); + none("recover", [&] { + return secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, *recoverable, + digest); + }); none("public_key <=>", [&] { return (*parsed <=> *parsed) == 0; }); none("keypair::tweak_xonly", [&] { return key.tweak_xonly(message); }); diff --git a/test/secp256k1_bip340_test.cpp b/test/secp256k1_bip340_test.cpp index 1c0397a7..63a83f0f 100644 --- a/test/secp256k1_bip340_test.cpp +++ b/test/secp256k1_bip340_test.cpp @@ -5,9 +5,10 @@ // https://www.boost.org/LICENSE_1_0.txt) // secp256k1 against BIP340's test vectors (bip-0340/test-vectors.csv), through -// key.sign(crypto::schnorr, message, aux_rand) and crypto::verify(crypto::schnorr, ...): each row -// with a secret key gives its public key and its signature, every row verifies as its result -// says, and the refusals are the error the row's reason names. +// key.sign(crypto::signing_schemes::schnorr, message, aux_rand) and +// crypto::verify(crypto::signing_schemes::schnorr, ...): each row with a secret key gives its +// public key and its signature, every row verifies as its result says, and the refusals are the +// error the row's reason names. #include #include @@ -76,7 +77,8 @@ void check_signing(std::vector const& f, std::vector } auto const public_key = key->public_key(); BOOST_TEST(public_key.has_value() && std::ranges::equal(public_key->xonly(), pub)); - auto const made = key->sign(crypto::schnorr, message, std::span(aux)); + auto const made = key->sign(crypto::signing_schemes::schnorr, message, + std::span(aux)); BOOST_TEST(made.has_value()); if (made.has_value() && !std::ranges::equal(made->bytes(), signature)) { fail("row " + f[0] + ": signature differs: " + test::to_hex(made->bytes())); @@ -100,9 +102,9 @@ void check_row(std::vector const& f, tally& t) { ++t.signed_rows; check_signing(f, pub, message, signature); } - auto const result = - crypto::verify(crypto::schnorr, secp::schnorr_signature::from_bytes(signature).value(), - message, std::span(pub)); + auto const result = crypto::verify(crypto::signing_schemes::schnorr, + secp::schnorr_signature::from_bytes(signature).value(), + message, std::span(pub)); if (f[6] == "TRUE") { ++t.accepted; BOOST_TEST(result.has_value()); diff --git a/test/secp256k1_c_api_test.cpp b/test/secp256k1_c_api_test.cpp index 8f06a5ea..aa17a96c 100644 --- a/test/secp256k1_c_api_test.cpp +++ b/test/secp256k1_c_api_test.cpp @@ -80,9 +80,9 @@ void recovery(secp256k1_context const* context, secret_key const& secret, with_id[64] = static_cast(id); auto const typed = secp::recoverable_signature::from_bytes(with_id); BOOST_TEST(typed.has_value()); - auto const wrapped = - typed ? secp::recover(crypto::ecdsa_sha256_recoverable, *typed, crypto::prehashed{hash}) - : boost::system::result(typed.error()); + auto const wrapped = typed ? secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, + *typed, crypto::signing_schemes::prehashed{hash}) + : boost::system::result(typed.error()); auto const expected_key = secp::public_key::from_bytes(expected); if (BOOST_TEST(wrapped && expected_key)) { BOOST_TEST(*wrapped == *expected_key); diff --git a/test/secp256k1_der_test.cpp b/test/secp256k1_der_test.cpp index aa6163c2..4dccfb71 100644 --- a/test/secp256k1_der_test.cpp +++ b/test/secp256k1_der_test.cpp @@ -5,10 +5,10 @@ // https://www.boost.org/LICENSE_1_0.txt) // secp256k1's ECDSA encodings, each taking or giving a secp256k1::ecdsa_signature: compact to -// strict DER and back for signatures of sign(crypto::ecdsa_sha256, message), the strict decoder -// against Wycheproof's Bitcoin ECDSA vectors (DER, counted per flag), every refusal of to_der, -// low-S normalization of a high-S signature, and is_low_s's answer on each form and on numbers -// out of range. +// strict DER and back for signatures of sign(crypto::signing_schemes::ecdsa_sha256, message), the +// strict decoder against Wycheproof's Bitcoin ECDSA vectors (DER, counted per flag), every refusal +// of to_der, low-S normalization of a high-S signature, and is_low_s's answer on each form and on +// numbers out of range. #include #include @@ -91,7 +91,7 @@ void round_trips() { for (unsigned i = 0; i < 256; ++i) { auto const key = key_of(static_cast(i)); std::array const message{0x6d, static_cast(i)}; - auto const signature = key.sign(crypto::ecdsa_sha256, message); + auto const signature = key.sign(crypto::signing_schemes::ecdsa_sha256, message); BOOST_TEST(signature.has_value()); std::array der{}; auto const written = secp::to_der(*signature, der); @@ -121,7 +121,8 @@ void to_der_refusals() { auto const key = key_of(1); std::array hash{}; hash.fill(0x31); - auto const signature = *key.sign(crypto::ecdsa_sha256, crypto::prehashed{hash}); + auto const signature = + *key.sign(crypto::signing_schemes::ecdsa_sha256, crypto::signing_schemes::prehashed{hash}); // Too short for the longest encoding, even when this one would fit: nothing is written. std::array short_out{}; @@ -148,17 +149,18 @@ void normalization() { auto const key = key_of(2); std::array hash{}; hash.fill(0x77); - crypto::prehashed const digest{hash}; - auto const signature = *key.sign(crypto::ecdsa_sha256, digest); + crypto::signing_schemes::prehashed const digest{hash}; + auto const signature = *key.sign(crypto::signing_schemes::ecdsa_sha256, digest); auto const public_key = *key.public_key(); auto const high = typed(test::negate_s(signature.bytes())); BOOST_TEST(high != signature); - BOOST_TEST(crypto::verify(crypto::ecdsa_sha256, high, digest, public_key).error() == - crypto::error::invalid_signature); + BOOST_TEST( + crypto::verify(crypto::signing_schemes::ecdsa_sha256, high, digest, public_key).error() == + crypto::error::invalid_signature); auto const normalized = secp::normalize_low_s(high); BOOST_TEST(normalized.has_value() && *normalized == signature); - BOOST_TEST(normalized.has_value() && - crypto::verify(crypto::ecdsa_sha256, *normalized, digest, public_key)); + BOOST_TEST(normalized.has_value() && crypto::verify(crypto::signing_schemes::ecdsa_sha256, + *normalized, digest, public_key)); // Already low-S: unchanged. auto const again = secp::normalize_low_s(signature); BOOST_TEST(again.has_value() && *again == signature); @@ -185,7 +187,8 @@ void low_s_answers() { auto const key = key_of(3); std::array hash{}; hash.fill(0x51); - auto const signature = *key.sign(crypto::ecdsa_sha256, crypto::prehashed{hash}); + auto const signature = + *key.sign(crypto::signing_schemes::ecdsa_sha256, crypto::signing_schemes::prehashed{hash}); BOOST_TEST(secp::is_low_s(signature)); BOOST_TEST(!secp::is_low_s(typed(test::negate_s(signature.bytes())))); constexpr std::string_view one = diff --git a/test/secp256k1_ethereum_test.cpp b/test/secp256k1_ethereum_test.cpp index 593d3342..38b5ab5d 100644 --- a/test/secp256k1_ethereum_test.cpp +++ b/test/secp256k1_ethereum_test.cpp @@ -4,14 +4,15 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// Ethereum's recoverable ECDSA, crypto::ecdsa_keccak256_recoverable (design D8, R18 to R20): -// go-ethereum's recovery vector; web3.js's personal_sign vector, its EIP-191 digest built here -// with webcpp::hash's keccak_256; Keccak-256's original padding, never SHA3-256's; a message -// hashed inside with Keccak-256, of any size, empty and 32 bytes included, signed as its digest -// is and recovered from it; always a low S; a high S recovered as libsecp256k1 and Ethereum's -// ecrecover recover it; the refusals of an id above 3 and of an r of zero; a keccak signature -// recovered under ecdsa_sha256_recoverable, which gives another key; the free crypto::sign; and -// the scheme's traits: its signature type, no crypto::verify of it, a 32-byte digest alone. +// Ethereum's recoverable ECDSA, crypto::signing_schemes::ecdsa_keccak256_recoverable (design D8, +// R18 to R20): go-ethereum's recovery vector; web3.js's personal_sign vector, its EIP-191 digest +// built here with webcpp::hash's keccak_256; Keccak-256's original padding, never SHA3-256's; a +// message hashed inside with Keccak-256, of any size, empty and 32 bytes included, signed as its +// digest is and recovered from it; always a low S; a high S recovered as libsecp256k1 and +// Ethereum's ecrecover recover it; the refusals of an id above 3 and of an r of zero; a keccak +// signature recovered under ecdsa_sha256_recoverable, which gives another key; the free +// crypto::sign; and the scheme's traits: its signature type, no crypto::verify of it, a 32-byte +// digest alone. #include #include @@ -46,7 +47,7 @@ namespace { using webcpp::test::hex; using bytes32 = std::array; -using keccak_scheme = crypto::ecdsa_keccak256_recoverable_t; +using keccak_scheme = crypto::signing_schemes::ecdsa_keccak256_recoverable_t; // The scheme's traits: the recoverable signature type of ecdsa_sha256_recoverable (R20), 65 // bytes over a 32-byte digest, a message or a marker of 32 bytes alone. @@ -57,15 +58,19 @@ static_assert(crypto::detail::signs_with_v); static_assert(std::is_same_v, secp::recoverable_signature>); static_assert(crypto::can_sign>); -static_assert(crypto::can_sign>); -static_assert(!crypto::can_sign>); +static_assert( + crypto::can_sign>); +static_assert( + !crypto::can_sign>); static_assert(std::is_same_v().sign( - crypto::ecdsa_keccak256_recoverable, std::declval())), + crypto::signing_schemes::ecdsa_keccak256_recoverable, + std::declval())), boost::system::result>); -static_assert(std::is_same_v(), - crypto::prehashed<32>(bytes32{}))), - boost::system::result>); +static_assert( + std::is_same_v(), + crypto::signing_schemes::prehashed<32>(bytes32{}))), + boost::system::result>); // No crypto::verify of the scheme (R18): a public key does not verify it, and the catch-all, // which stops the build, is the one candidate. static_assert(!crypto::detail::verifies_with_v); @@ -169,8 +174,9 @@ secp::ecdsa_signature ecdsa_of(secp::recoverable_signature const& signature) { // go-ethereum's digest and signature recover its uncompressed key. void geth_recover() { - auto const recovered = secp::recover(crypto::ecdsa_keccak256_recoverable, typed(geth_signature), - crypto::prehashed{geth_message}); + auto const recovered = + secp::recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, typed(geth_signature), + crypto::signing_schemes::prehashed{geth_message}); if (BOOST_TEST(recovered.has_value())) { BOOST_TEST(recovered->uncompressed() == geth_public_key); auto const expected = secp::public_key::from_bytes(geth_public_key); @@ -184,7 +190,8 @@ void personal_sign() { auto const digest = personal_sign_digest(web3_message); BOOST_TEST(digest == web3_message_hash); auto const key = key_of(web3_secret); - auto const signature = key.sign(crypto::ecdsa_keccak256_recoverable, crypto::prehashed{digest}); + auto const signature = key.sign(crypto::signing_schemes::ecdsa_keccak256_recoverable, + crypto::signing_schemes::prehashed{digest}); if (!BOOST_TEST(signature.has_value())) { return; } @@ -192,8 +199,8 @@ void personal_sign() { BOOST_TEST(std::ranges::equal(std::span(signed_bytes).first<32>(), web3_r)); BOOST_TEST(std::ranges::equal(std::span(signed_bytes).subspan<32, 32>(), web3_s)); BOOST_TEST_EQ(static_cast(signature->recovery_id()), web3_v - 27); - auto const recovered = - secp::recover(crypto::ecdsa_keccak256_recoverable, *signature, crypto::prehashed{digest}); + auto const recovered = secp::recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, + *signature, crypto::signing_schemes::prehashed{digest}); if (BOOST_TEST(recovered.has_value())) { BOOST_TEST(*recovered == public_of(key)); auto const uncompressed = recovered->uncompressed(); @@ -212,22 +219,24 @@ void keccak_not_sha3() { // A message is hashed with Keccak-256 inside: its signature is the one of the marker of its // Keccak-256 digest, not of its SHA3-256 digest, and recover with the message gives the signer. void message_is_hashed_one(secp::keypair const& key, std::span message) { - auto const of_message = key.sign(crypto::ecdsa_keccak256_recoverable, message); + auto const of_message = key.sign(crypto::signing_schemes::ecdsa_keccak256_recoverable, message); auto const keccak_digest = keccak_of(message); auto const sha3_digest = sha3_of(message); - auto const of_keccak = - key.sign(crypto::ecdsa_keccak256_recoverable, crypto::prehashed{keccak_digest}); - auto const of_sha3 = - key.sign(crypto::ecdsa_keccak256_recoverable, crypto::prehashed{sha3_digest}); + auto const of_keccak = key.sign(crypto::signing_schemes::ecdsa_keccak256_recoverable, + crypto::signing_schemes::prehashed{keccak_digest}); + auto const of_sha3 = key.sign(crypto::signing_schemes::ecdsa_keccak256_recoverable, + crypto::signing_schemes::prehashed{sha3_digest}); if (!BOOST_TEST(of_message && of_keccak && of_sha3)) { return; } BOOST_TEST(*of_message == *of_keccak); BOOST_TEST(*of_message != *of_sha3); - auto const recovered = secp::recover(crypto::ecdsa_keccak256_recoverable, *of_message, message); + auto const recovered = + secp::recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, *of_message, message); BOOST_TEST(recovered.has_value() && *recovered == public_of(key)); // The free form gives the member's signature. - auto const free_form = crypto::sign(key, crypto::ecdsa_keccak256_recoverable, message); + auto const free_form = + crypto::sign(key, crypto::signing_schemes::ecdsa_keccak256_recoverable, message); BOOST_TEST(free_form.has_value() && *free_form == *of_message); } @@ -244,13 +253,13 @@ void message_is_hashed() { void empty_message() { auto const key = key_of(web3_secret); std::span const nothing{}; - auto const of_nothing = key.sign(crypto::ecdsa_keccak256_recoverable, nothing); - auto const of_digest = - key.sign(crypto::ecdsa_keccak256_recoverable, crypto::prehashed{keccak_of_nothing}); + auto const of_nothing = key.sign(crypto::signing_schemes::ecdsa_keccak256_recoverable, nothing); + auto const of_digest = key.sign(crypto::signing_schemes::ecdsa_keccak256_recoverable, + crypto::signing_schemes::prehashed{keccak_of_nothing}); if (BOOST_TEST(of_nothing && of_digest)) { BOOST_TEST(*of_nothing == *of_digest); - auto const recovered = - secp::recover(crypto::ecdsa_keccak256_recoverable, *of_nothing, nothing); + auto const recovered = secp::recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, + *of_nothing, nothing); BOOST_TEST(recovered.has_value() && *recovered == public_of(key)); } } @@ -272,15 +281,16 @@ void always_low_s() { if (!made) { continue; } - auto const signature = - made->sign(crypto::ecdsa_keccak256_recoverable, crypto::prehashed{digest}); + auto const signature = made->sign(crypto::signing_schemes::ecdsa_keccak256_recoverable, + crypto::signing_schemes::prehashed{digest}); if (!BOOST_TEST(signature.has_value())) { return; } BOOST_TEST(secp::is_low_s(ecdsa_of(*signature))); BOOST_TEST(signature->recovery_id() <= 3); - auto const recovered = secp::recover(crypto::ecdsa_keccak256_recoverable, *signature, - crypto::prehashed{digest}); + auto const recovered = + secp::recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, *signature, + crypto::signing_schemes::prehashed{digest}); BOOST_TEST(recovered.has_value() && *recovered == public_of(*made)); ++signed_count; } @@ -297,8 +307,8 @@ void high_s_recovered() { high_bytes[64] ^= 1U; auto const high = typed(high_bytes); BOOST_TEST(!secp::is_low_s(ecdsa_of(high))); - auto const recovered = - secp::recover(crypto::ecdsa_keccak256_recoverable, high, crypto::prehashed{geth_message}); + auto const recovered = secp::recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, high, + crypto::signing_schemes::prehashed{geth_message}); BOOST_TEST(recovered.has_value() && recovered->uncompressed() == geth_public_key); } @@ -307,14 +317,16 @@ void refusals() { for (std::uint8_t const id : std::to_array({4, 27, 28, 255})) { auto bad_bytes = geth_signature; bad_bytes[64] = id; - auto const refused = secp::recover(crypto::ecdsa_keccak256_recoverable, typed(bad_bytes), - crypto::prehashed{geth_message}); + auto const refused = + secp::recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, typed(bad_bytes), + crypto::signing_schemes::prehashed{geth_message}); BOOST_TEST(refused.has_error() && refused.error() == crypto::error::invalid_signature); } auto zero_r = geth_signature; std::fill_n(zero_r.begin(), 32, std::uint8_t{0}); - auto const refused = secp::recover(crypto::ecdsa_keccak256_recoverable, typed(zero_r), - crypto::prehashed{geth_message}); + auto const refused = + secp::recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, typed(zero_r), + crypto::signing_schemes::prehashed{geth_message}); BOOST_TEST(refused.has_error() && refused.error() == crypto::error::invalid_signature); } @@ -323,13 +335,15 @@ void refusals() { void wrong_scheme_key() { auto const key = key_of(web3_secret); auto const message = bytes_of(web3_message); - auto const signature = key.sign(crypto::ecdsa_keccak256_recoverable, message); + auto const signature = key.sign(crypto::signing_schemes::ecdsa_keccak256_recoverable, message); if (!BOOST_TEST(signature.has_value())) { return; } - auto const other = secp::recover(crypto::ecdsa_sha256_recoverable, *signature, message); + auto const other = + secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, *signature, message); BOOST_TEST(!other.has_value() || *other != public_of(key)); - auto const same = secp::recover(crypto::ecdsa_keccak256_recoverable, *signature, message); + auto const same = + secp::recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, *signature, message); BOOST_TEST(same.has_value() && *same == public_of(key)); } @@ -339,7 +353,8 @@ void moved_from() { auto const target = std::move(source); static_cast(target); // NOLINTNEXTLINE(bugprone-use-after-move): the moved-from key pair is the point - auto const refused = source.sign(crypto::ecdsa_keccak256_recoverable, bytes_of(web3_message)); + auto const refused = + source.sign(crypto::signing_schemes::ecdsa_keccak256_recoverable, bytes_of(web3_message)); BOOST_TEST(refused.has_error() && refused.error() == crypto::error::invalid_state); } diff --git a/test/secp256k1_formats_test.cpp b/test/secp256k1_formats_test.cpp index 314510ec..e3a12faa 100644 --- a/test/secp256k1_formats_test.cpp +++ b/test/secp256k1_formats_test.cpp @@ -275,8 +275,12 @@ void pkcs8_round_trip(secp::keypair const& key, bytes const& secret) { BOOST_TEST(public_of(*decoded) == public_of(key)); BOOST_TEST(pkcs8(*decoded) == private_encoding); std::array const hash{1, 2, 3}; - BOOST_TEST(decoded->sign(crypto::ecdsa_sha256, crypto::prehashed{hash}).value() == - key.sign(crypto::ecdsa_sha256, crypto::prehashed{hash}).value()); + BOOST_TEST( + decoded + ->sign(crypto::signing_schemes::ecdsa_sha256, crypto::signing_schemes::prehashed{hash}) + .value() == + key.sign(crypto::signing_schemes::ecdsa_sha256, crypto::signing_schemes::prehashed{hash}) + .value()); } // One key pair's SPKI in both forms and its PKCS#8, armoured as PEM under their labels: the text diff --git a/test/secp256k1_generate_test.cpp b/test/secp256k1_generate_test.cpp index 8657fea7..dbc99139 100644 --- a/test/secp256k1_generate_test.cpp +++ b/test/secp256k1_generate_test.cpp @@ -10,9 +10,9 @@ // script is spent. generate draws 32 bytes again when they are not a secret key (0xFF repeated // is above the group order), at most four draws in all; the source failing, or four refusals, // is entropy_unavailable; a failure allocates nothing; the one allocation of a success is the -// context's, from the resource given. sign(crypto::schnorr, message) draws its 32 bytes of -// auxiliary randomness from the same source: the signature is the one made with those bytes -// given, and a failing source is entropy_unavailable, after one draw. +// context's, from the resource given. sign(crypto::signing_schemes::schnorr, message) draws its 32 +// bytes of auxiliary randomness from the same source: the signature is the one made with those +// bytes given, and a failing source is entropy_unavailable, after one draw. #include #include @@ -160,15 +160,15 @@ void schnorr_draws_from_the_source() { aux.fill(0x3c); script = {0x3c}; calls = 0; - auto const drawn = key->sign(crypto::schnorr, message); + auto const drawn = key->sign(crypto::signing_schemes::schnorr, message); BOOST_TEST_EQ(calls, 1U); - auto const given = key->sign(crypto::schnorr, message, aux); + auto const given = key->sign(crypto::signing_schemes::schnorr, message, aux); BOOST_TEST_EQ(calls, 1U); if (BOOST_TEST(drawn.has_value()) && BOOST_TEST(given.has_value())) { BOOST_TEST(*drawn == *given); } // The script is spent: the source fails. - auto const refused = key->sign(crypto::schnorr, message); + auto const refused = key->sign(crypto::signing_schemes::schnorr, message); BOOST_TEST(!refused && refused.error() == crypto::error::entropy_unavailable); BOOST_TEST_EQ(calls, 2U); // A moved-from key pair answers invalid_state before it draws. @@ -176,7 +176,8 @@ void schnorr_draws_from_the_source() { script = {}; calls = 0; // NOLINTNEXTLINE(bugprone-use-after-move): the moved-from key pair is what this checks - BOOST_TEST(key->sign(crypto::schnorr, message).error() == crypto::error::invalid_state); + BOOST_TEST(key->sign(crypto::signing_schemes::schnorr, message).error() == + crypto::error::invalid_state); BOOST_TEST_EQ(calls, 0U); BOOST_TEST(moved.public_key().has_value()); } diff --git a/test/secp256k1_keccak_alone_test.cpp b/test/secp256k1_keccak_alone_test.cpp index 2b36b94e..92ecdf74 100644 --- a/test/secp256k1_keccak_alone_test.cpp +++ b/test/secp256k1_keccak_alone_test.cpp @@ -6,8 +6,8 @@ // alone, first, in a program that links XKCP: its branch for // WEBCPP_HASH_HAS_XKCP, which includes , compiles with nothing before it, -// and crypto::ecdsa_keccak256_recoverable's sign and recover of a message are instantiated -// through it alone. +// and crypto::signing_schemes::ecdsa_keccak256_recoverable's sign and recover of a message are +// instantiated through it alone. #include @@ -22,8 +22,9 @@ namespace crypto = webcpp::crypto; namespace secp = webcpp::crypto::curves::secp256k1; -static_assert(crypto::can_sign>); +static_assert( + crypto::can_sign>); int main() { std::array secret{}; @@ -33,10 +34,11 @@ int main() { if (!key) { return 1; } - auto const signature = key->sign(crypto::ecdsa_keccak256_recoverable, message); + auto const signature = key->sign(crypto::signing_schemes::ecdsa_keccak256_recoverable, message); if (!signature) { return 1; } - auto const recovered = secp::recover(crypto::ecdsa_keccak256_recoverable, *signature, message); + auto const recovered = + secp::recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, *signature, message); return recovered && *recovered == *key->public_key() ? 0 : 1; } diff --git a/test/secp256k1_musig_test.cpp b/test/secp256k1_musig_test.cpp index 35950a68..3443c85d 100644 --- a/test/secp256k1_musig_test.cpp +++ b/test/secp256k1_musig_test.cpp @@ -15,16 +15,16 @@ // cases that need no secret nonce of the vector's are refused at parsing (a sign_error case that // needs one is counted as skipped). tweak: the 5 valid cases verify after their tweaks, the // error case's tweak is refused. sig_agg: the 4 valid cases give the vector's signature, which -// crypto::verify(crypto::schnorr, ...) accepts under the aggregate key, and a partial signature not -// below the group order is refused. The vectors' secret nonces (sign_verify's and tweak's -// secnonces, det_sign_vectors.json, nonce_gen_vectors.json) are not reachable through crypto's -// interface by design: a secret_nonce exists only from generate_nonce, with fresh randomness; -// libsecp256k1's own tests run them in the c-suites lane. Round trips: 2-of-2 and 3-of-3 over -// seeded key pairs and messages, plain and with an x-only tweak, each partial signature verified, -// the aggregate verified with crypto::verify(crypto::schnorr, ...), and a partial signature changed -// in one bit refused. The nonce: consumed by partial_sign, refused when used again or given to -// another key pair. The refusals of a moved-from key pair, of sizes and of workspaces; every -// workspace is zero afterwards. +// crypto::verify(crypto::signing_schemes::schnorr, ...) accepts under the aggregate key, and a +// partial signature not below the group order is refused. The vectors' secret nonces (sign_verify's +// and tweak's secnonces, det_sign_vectors.json, nonce_gen_vectors.json) are not reachable through +// crypto's interface by design: a secret_nonce exists only from generate_nonce, with fresh +// randomness; libsecp256k1's own tests run them in the c-suites lane. Round trips: 2-of-2 and +// 3-of-3 over seeded key pairs and messages, plain and with an x-only tweak, each partial signature +// verified, the aggregate verified with crypto::verify(crypto::signing_schemes::schnorr, ...), and +// a partial signature changed in one bit refused. The nonce: consumed by partial_sign, refused when +// used again or given to another key pair. The refusals of a moved-from key pair, of sizes and of +// workspaces; every workspace is zero afterwards. #include #include @@ -510,9 +510,10 @@ void sig_agg() { continue; } BOOST_TEST(std::ranges::equal(signature->bytes(), hex(c.at("expected")))); - aggregated_count += static_cast( - BOOST_TEST(crypto::verify(crypto::schnorr, *signature, message, key.xonly_public_key()) - .has_value())); + aggregated_count += + static_cast(BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, *signature, + message, key.xonly_public_key()) + .has_value())); } int refused = 0; for (auto const& c : doc.at("error_test_cases").as_array()) { @@ -607,13 +608,14 @@ void aggregate_verifies(std::span parts, musig::partial_signature_aggregate(signing_session, parts, signature_space); BOOST_TEST(all_zero(signature_space)); if (BOOST_TEST(signature.has_value())) { - BOOST_TEST(crypto::verify(crypto::schnorr, *signature, message, key.xonly_public_key()) + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, *signature, message, + key.xonly_public_key()) .has_value()); auto other_message = message; other_message[0] ^= 0x01U; - BOOST_TEST( - crypto::verify(crypto::schnorr, *signature, other_message, key.xonly_public_key()) - .error() == crypto::error::invalid_signature); + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, *signature, other_message, + key.xonly_public_key()) + .error() == crypto::error::invalid_signature); } } diff --git a/test/secp256k1_recovery_test.cpp b/test/secp256k1_recovery_test.cpp index 9d0d1a26..6d56031f 100644 --- a/test/secp256k1_recovery_test.cpp +++ b/test/secp256k1_recovery_test.cpp @@ -4,8 +4,8 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// secp256k1's recoverable ECDSA signatures (crypto::ecdsa_sha256_recoverable) and hedged ECDSA: -// 64 seeded key pairs and digests, each recovered to its key from the signature, a +// secp256k1's recoverable ECDSA signatures (crypto::signing_schemes::ecdsa_sha256_recoverable) and +// hedged ECDSA: 64 seeded key pairs and digests, each recovered to its key from the signature, a // secp256k1::recoverable_signature, and the same input as signing, a digest or a message; // libsecp256k1's own recovery edge cases; the refusals of an id above 3 (from_bytes makes one, // recovery_id() gives the raw byte, recover refuses it), of an r or an s out of range, and of a @@ -60,10 +60,11 @@ secp::ecdsa_signature ecdsa_of(recoverable const& signature) { } static_assert(secp::recoverable_signature_size == 65); -static_assert(std::is_same_v(), - crypto::prehashed<32>(hash_bytes{}))), - boost::system::result>); +static_assert( + std::is_same_v(), + crypto::signing_schemes::prehashed<32>(hash_bytes{}))), + boost::system::result>); // A key pair from the generator: a secret from_secret refuses is drawn again. secp::keypair draw(std::mt19937_64& generator, hash_bytes& secret) { @@ -104,8 +105,9 @@ void refuses_bad_ids(recoverable const& signature, hash_bytes const& hash) { bad_bytes[64] = id; auto const bad_id = typed(bad_bytes); BOOST_TEST_EQ(bad_id.recovery_id(), id); - BOOST_TEST(refused_as_signature( - secp::recover(crypto::ecdsa_sha256_recoverable, bad_id, crypto::prehashed{hash}))); + BOOST_TEST( + refused_as_signature(secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, + bad_id, crypto::signing_schemes::prehashed{hash}))); } } @@ -114,8 +116,8 @@ bool another_hash_finds_another_key(secp::keypair const& key, recoverable const& hash_bytes const& hash) { auto other_hash = hash; other_hash[0] ^= 0x80U; - auto const other = - secp::recover(crypto::ecdsa_sha256_recoverable, signature, crypto::prehashed{other_hash}); + auto const other = secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, signature, + crypto::signing_schemes::prehashed{other_hash}); if (!other) { BOOST_TEST(other.error() == crypto::error::invalid_signature); return false; @@ -130,15 +132,17 @@ bool round_trip(std::mt19937_64& generator) { hash_bytes secret{}; auto const key = draw(generator, secret); auto const hash = draw_hash(generator); - auto const signature = key.sign(crypto::ecdsa_sha256_recoverable, crypto::prehashed{hash}); - auto const plain = key.sign(crypto::ecdsa_sha256, crypto::prehashed{hash}); + auto const signature = key.sign(crypto::signing_schemes::ecdsa_sha256_recoverable, + crypto::signing_schemes::prehashed{hash}); + auto const plain = + key.sign(crypto::signing_schemes::ecdsa_sha256, crypto::signing_schemes::prehashed{hash}); if (!BOOST_TEST(signature && plain)) { return false; } BOOST_TEST(signature->recovery_id() <= 3); BOOST_TEST(std::ranges::equal(std::span(signature->bytes()).first(64), plain->bytes())); - auto const recovered = - secp::recover(crypto::ecdsa_sha256_recoverable, *signature, crypto::prehashed{hash}); + auto const recovered = secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, + *signature, crypto::signing_schemes::prehashed{hash}); if (BOOST_TEST(recovered.has_value())) { BOOST_TEST(*recovered == key_of(key)); } @@ -156,15 +160,17 @@ void message_round_trip() { } std::array message{}; message.fill(0x6d); - auto const signature = made->sign(crypto::ecdsa_sha256_recoverable, message); + auto const signature = made->sign(crypto::signing_schemes::ecdsa_sha256_recoverable, message); if (!BOOST_TEST(signature.has_value())) { return; } - auto const from_message = secp::recover(crypto::ecdsa_sha256_recoverable, *signature, message); - auto const from_digest = secp::recover(crypto::ecdsa_sha256_recoverable, *signature, - crypto::prehashed{crypto::detail::sha256_of(message)}); - auto const from_marker = - secp::recover(crypto::ecdsa_sha256_recoverable, *signature, crypto::prehashed{message}); + auto const from_message = + secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, *signature, message); + auto const from_digest = + secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, *signature, + crypto::signing_schemes::prehashed{crypto::detail::sha256_of(message)}); + auto const from_marker = secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, + *signature, crypto::signing_schemes::prehashed{message}); if (BOOST_TEST(from_message.has_value()) && BOOST_TEST(from_digest.has_value())) { BOOST_TEST(*from_message == key_of(*made)); BOOST_TEST(*from_digest == key_of(*made)); @@ -172,10 +178,11 @@ void message_round_trip() { BOOST_TEST(!from_marker || *from_marker != key_of(*made)); // The empty message too. std::span const empty{}; - auto const signed_empty = made->sign(crypto::ecdsa_sha256_recoverable, empty); + auto const signed_empty = made->sign(crypto::signing_schemes::ecdsa_sha256_recoverable, empty); auto const recovered_empty = - signed_empty ? secp::recover(crypto::ecdsa_sha256_recoverable, *signed_empty, empty) - : boost::system::result(crypto::error::backend_failure); + signed_empty + ? secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, *signed_empty, empty) + : boost::system::result(crypto::error::backend_failure); BOOST_TEST(recovered_empty.has_value() && *recovered_empty == key_of(*made)); } @@ -225,8 +232,9 @@ void edge_signature_ids() { recoverable_bytes signature{}; std::ranges::copy(edge_signature, signature.begin()); signature[64] = id; - auto const recovered = secp::recover(crypto::ecdsa_sha256_recoverable, typed(signature), - crypto::prehashed{edge_message}); + auto const recovered = + secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, typed(signature), + crypto::signing_schemes::prehashed{edge_message}); if (id == 1) { BOOST_TEST(recovered.has_value()); } else { @@ -240,30 +248,31 @@ void edge_signature_ids() { void small_signatures_recover() { for (std::uint8_t id = 0; id < 4; ++id) { auto const signature = small_signature(4, 4, id); - auto const recovered = secp::recover(crypto::ecdsa_sha256_recoverable, signature, - crypto::prehashed{edge_message}); + auto const recovered = + secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, signature, + crypto::signing_schemes::prehashed{edge_message}); if (!BOOST_TEST(recovered.has_value())) { continue; } - BOOST_TEST(crypto::verify(crypto::ecdsa_sha256, ecdsa_of(signature), - crypto::prehashed{edge_message}, *recovered) + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, ecdsa_of(signature), + crypto::signing_schemes::prehashed{edge_message}, *recovered) .has_value()); } auto const one_one = small_signature(1, 1, 0); - auto const recovered = - secp::recover(crypto::ecdsa_sha256_recoverable, one_one, crypto::prehashed{edge_message}); + auto const recovered = secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, one_one, + crypto::signing_schemes::prehashed{edge_message}); if (BOOST_TEST(recovered.has_value())) { - BOOST_TEST(crypto::verify(crypto::ecdsa_sha256, ecdsa_of(one_one), - crypto::prehashed{edge_message}, *recovered) + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, ecdsa_of(one_one), + crypto::signing_schemes::prehashed{edge_message}, *recovered) .has_value()); } } // The key recovered from a signature of edge_message, the digest. boost::system::result recover_edge(recoverable const& signature) { - return secp::recover(crypto::ecdsa_sha256_recoverable, signature, - crypto::prehashed{edge_message}); + return secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, signature, + crypto::signing_schemes::prehashed{edge_message}); } // r = 0 or s = 0: no key; r or s equal to the group order n, or above it: refused by the parser. @@ -316,11 +325,11 @@ void hedged_round(secp256k1_context const* context, std::mt19937_64& generator) second_entropy[31] ^= 0x01U; hash_bytes const zero{}; - crypto::prehashed const digest{hash}; - auto const first = key.sign(crypto::ecdsa_sha256, digest, first_entropy); - auto const second = key.sign(crypto::ecdsa_sha256, digest, second_entropy); - auto const zeroed = key.sign(crypto::ecdsa_sha256, digest, zero); - auto const plain = key.sign(crypto::ecdsa_sha256, digest); + crypto::signing_schemes::prehashed const digest{hash}; + auto const first = key.sign(crypto::signing_schemes::ecdsa_sha256, digest, first_entropy); + auto const second = key.sign(crypto::signing_schemes::ecdsa_sha256, digest, second_entropy); + auto const zeroed = key.sign(crypto::signing_schemes::ecdsa_sha256, digest, zero); + auto const plain = key.sign(crypto::signing_schemes::ecdsa_sha256, digest); if (!BOOST_TEST(first && second && zeroed && plain)) { return; } @@ -328,16 +337,20 @@ void hedged_round(secp256k1_context const* context, std::mt19937_64& generator) BOOST_TEST(*zeroed != *plain); BOOST_TEST(*first != *plain); auto const public_key = key_of(key); - BOOST_TEST(crypto::verify(crypto::ecdsa_sha256, *first, digest, public_key).has_value()); - BOOST_TEST(crypto::verify(crypto::ecdsa_sha256, *second, digest, public_key).has_value()); - BOOST_TEST(crypto::verify(crypto::ecdsa_sha256, *zeroed, digest, public_key).has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *first, digest, public_key) + .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *second, digest, public_key) + .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *zeroed, digest, public_key) + .has_value()); BOOST_TEST(first->bytes() == reference_signature(context, secret, hash, &first_entropy)); BOOST_TEST(second->bytes() == reference_signature(context, secret, hash, &second_entropy)); BOOST_TEST(zeroed->bytes() == reference_signature(context, secret, hash, &zero)); BOOST_TEST(plain->bytes() == reference_signature(context, secret, hash, nullptr)); // Hedged twice with the same entropy, the signature is the same: the hedging is // deterministic given its input. - BOOST_TEST(key.sign(crypto::ecdsa_sha256, digest, first_entropy).value() == *first); + BOOST_TEST(key.sign(crypto::signing_schemes::ecdsa_sha256, digest, first_entropy).value() == + *first); } // The hedged form: different entropy gives different signatures, both valid, each libsecp256k1's @@ -366,13 +379,20 @@ void moved_from() { secp::keypair source = std::move(*made); secp::keypair const target = std::move(source); hash_bytes const hash{}; - BOOST_TEST(source.sign(crypto::ecdsa_sha256_recoverable, crypto::prehashed{hash}).error() == - crypto::error::invalid_state); - BOOST_TEST(source.sign(crypto::ecdsa_sha256, crypto::prehashed{hash}, hash).error() == - crypto::error::invalid_state); + BOOST_TEST(source + .sign(crypto::signing_schemes::ecdsa_sha256_recoverable, + crypto::signing_schemes::prehashed{hash}) + .error() == crypto::error::invalid_state); + BOOST_TEST(source + .sign(crypto::signing_schemes::ecdsa_sha256, + crypto::signing_schemes::prehashed{hash}, hash) + .error() == crypto::error::invalid_state); BOOST_TEST(source.secret().error() == crypto::error::invalid_state); test::expect_empty_keypair(source); - BOOST_TEST(target.sign(crypto::ecdsa_sha256_recoverable, crypto::prehashed{hash}).has_value()); + BOOST_TEST(target + .sign(crypto::signing_schemes::ecdsa_sha256_recoverable, + crypto::signing_schemes::prehashed{hash}) + .has_value()); } // NOLINTEND(bugprone-use-after-move) diff --git a/test/secp256k1_silent_payments_test.cpp b/test/secp256k1_silent_payments_test.cpp index 505f72ee..dc1b68f8 100644 --- a/test/secp256k1_silent_payments_test.cpp +++ b/test/secp256k1_silent_payments_test.cpp @@ -412,7 +412,7 @@ void check_found(bip352_receive_subtest const& subtest, sp::found_output const& return; } auto const spending = keypair_of(spend_tweaked->bytes()); - auto const signature = spending.sign(crypto::schnorr, message, aux); + auto const signature = spending.sign(crypto::signing_schemes::schnorr, message, aux); if (BOOST_TEST(signature.has_value())) { BOOST_TEST(std::ranges::equal(signature->bytes(), subtest.found_signatures[at])); } diff --git a/test/secp256k1_test.cpp b/test/secp256k1_test.cpp index a24f2bb3..56b73456 100644 --- a/test/secp256k1_test.cpp +++ b/test/secp256k1_test.cpp @@ -4,17 +4,18 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// secp256k1's key pair, key.sign with crypto::schnorr, crypto::ecdsa_sha256 and -// crypto::ecdsa_sha256_recoverable, each giving its own type (schnorr_signature, ecdsa_signature, -// recoverable_signature), and crypto::verify: signatures that verify and a changed message that -// does not; each type made from bytes received as a std::vector, verified (recovered, for the -// recoverable one) through the key's verify and crypto::verify, and refused by from_bytes at one -// byte fewer or more; Schnorr's auxiliary randomness given and drawn; ECDSA's message hashed -// inside, a sighash signed as libsecp256k1 signs it, hedged signing, low S, the empty message; -// Schnorr verified against the typed public key and its x-only bytes alike; the secret key given -// back by secret(), which makes the same key pair again; agree, agree_hashed and agree_point -// agreeing between two parties, agree_hashed as libsecp256k1's own secp256k1_ecdh; every error of -// from_secret, a moved-from key pair, and public keys refused in every way they can be wrong. +// secp256k1's key pair, key.sign with crypto::signing_schemes::schnorr, +// crypto::signing_schemes::ecdsa_sha256 and crypto::signing_schemes::ecdsa_sha256_recoverable, each +// giving its own type (schnorr_signature, ecdsa_signature, recoverable_signature), and +// crypto::verify: signatures that verify and a changed message that does not; each type made from +// bytes received as a std::vector, verified (recovered, for the recoverable one) through the key's +// verify and crypto::verify, and refused by from_bytes at one byte fewer or more; Schnorr's +// auxiliary randomness given and drawn; ECDSA's message hashed inside, a sighash signed as +// libsecp256k1 signs it, hedged signing, low S, the empty message; Schnorr verified against the +// typed public key and its x-only bytes alike; the secret key given back by secret(), which makes +// the same key pair again; agree, agree_hashed and agree_point agreeing between two parties, +// agree_hashed as libsecp256k1's own secp256k1_ecdh; every error of from_secret, a moved-from key +// pair, and public keys refused in every way they can be wrong. #include #include @@ -85,30 +86,34 @@ void schnorr() { std::array message{}; message.fill(0x17); std::array const aux{}; - auto const signature = key.sign(crypto::schnorr, message, aux); + auto const signature = key.sign(crypto::signing_schemes::schnorr, message, aux); auto const public_key = key.public_key(); if (!BOOST_TEST(signature && public_key)) { return; } // The typed key and its 32 x-only bytes verify alike. auto const xonly = public_key->xonly(); - BOOST_TEST(crypto::verify(crypto::schnorr, *signature, message, *public_key).has_value()); - BOOST_TEST(crypto::verify(crypto::schnorr, *signature, message, xonly).has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, *signature, message, *public_key) + .has_value()); + BOOST_TEST( + crypto::verify(crypto::signing_schemes::schnorr, *signature, message, xonly).has_value()); auto flipped_bytes = signature->bytes(); flipped_bytes[0] ^= 1U; auto const flipped = typed(flipped_bytes); - BOOST_TEST(crypto::verify(crypto::schnorr, flipped, message, *public_key).error() == - crypto::error::invalid_signature); - BOOST_TEST(crypto::verify(crypto::schnorr, flipped, message, xonly).error() == + BOOST_TEST( + crypto::verify(crypto::signing_schemes::schnorr, flipped, message, *public_key).error() == + crypto::error::invalid_signature); + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, flipped, message, xonly).error() == crypto::error::invalid_signature); message[0] ^= 1U; - BOOST_TEST(crypto::verify(crypto::schnorr, *signature, message, *public_key).error() == - crypto::error::invalid_signature); - BOOST_TEST(crypto::verify(crypto::schnorr, *signature, message, xonly).error() == - crypto::error::invalid_signature); + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, *signature, message, *public_key) + .error() == crypto::error::invalid_signature); + BOOST_TEST( + crypto::verify(crypto::signing_schemes::schnorr, *signature, message, xonly).error() == + crypto::error::invalid_signature); std::array const not_a_point{}; // x = 0 has no point - BOOST_TEST(crypto::verify(crypto::schnorr, *signature, message, not_a_point).error() == - crypto::error::invalid_public_key); + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, *signature, message, not_a_point) + .error() == crypto::error::invalid_public_key); } // sign(schnorr, message) draws its auxiliary randomness: two signatures of one message differ, @@ -117,15 +122,17 @@ void schnorr_draws_aux() { auto const key = from_byte(0x42); std::array message{}; message.fill(0x17); - auto const first = key.sign(crypto::schnorr, message); - auto const second = key.sign(crypto::schnorr, message); + auto const first = key.sign(crypto::signing_schemes::schnorr, message); + auto const second = key.sign(crypto::signing_schemes::schnorr, message); auto const public_key = key.public_key(); if (!BOOST_TEST(first && second && public_key)) { return; } BOOST_TEST(*first != *second); - BOOST_TEST(crypto::verify(crypto::schnorr, *first, message, *public_key).has_value()); - BOOST_TEST(crypto::verify(crypto::schnorr, *second, message, *public_key).has_value()); + BOOST_TEST( + crypto::verify(crypto::signing_schemes::schnorr, *first, message, *public_key).has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, *second, message, *public_key) + .has_value()); } // The empty message is a message under every scheme: it signs and verifies, and another @@ -137,25 +144,31 @@ void empty_message() { std::array const other{'x'}; auto const parsed = key.public_key(); auto const xonly = parsed->xonly(); - auto const schnorr_empty = key.sign(crypto::schnorr, empty, aux); - auto const drawn_empty = key.sign(crypto::schnorr, empty); - auto const ecdsa_empty = key.sign(crypto::ecdsa_sha256, empty); + auto const schnorr_empty = key.sign(crypto::signing_schemes::schnorr, empty, aux); + auto const drawn_empty = key.sign(crypto::signing_schemes::schnorr, empty); + auto const ecdsa_empty = key.sign(crypto::signing_schemes::ecdsa_sha256, empty); if (!BOOST_TEST(parsed && schnorr_empty && drawn_empty && ecdsa_empty)) { return; } - BOOST_TEST(crypto::verify(crypto::schnorr, *schnorr_empty, empty, xonly).has_value()); - BOOST_TEST(crypto::verify(crypto::schnorr, *drawn_empty, empty, *parsed).has_value()); - BOOST_TEST(crypto::verify(crypto::schnorr, *schnorr_empty, other, xonly).error() == - crypto::error::invalid_signature); - BOOST_TEST(crypto::verify(crypto::ecdsa_sha256, *ecdsa_empty, empty, *parsed).has_value()); - BOOST_TEST(crypto::verify(crypto::ecdsa_sha256, *ecdsa_empty, - crypto::prehashed{crypto::detail::sha256_of(empty)}, *parsed) + BOOST_TEST( + crypto::verify(crypto::signing_schemes::schnorr, *schnorr_empty, empty, xonly).has_value()); + BOOST_TEST( + crypto::verify(crypto::signing_schemes::schnorr, *drawn_empty, empty, *parsed).has_value()); + BOOST_TEST( + crypto::verify(crypto::signing_schemes::schnorr, *schnorr_empty, other, xonly).error() == + crypto::error::invalid_signature); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *ecdsa_empty, empty, *parsed) .has_value()); - BOOST_TEST(crypto::verify(crypto::ecdsa_sha256, *ecdsa_empty, other, *parsed).error() == - crypto::error::invalid_signature); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *ecdsa_empty, + crypto::signing_schemes::prehashed{crypto::detail::sha256_of(empty)}, + *parsed) + .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *ecdsa_empty, other, *parsed) + .error() == crypto::error::invalid_signature); // A vector converts to a message too, of any size. std::vector const none; - BOOST_TEST(crypto::verify(crypto::ecdsa_sha256, *ecdsa_empty, none, *parsed).has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *ecdsa_empty, none, *parsed) + .has_value()); } // A key pair generated from the system's source signs and verifies as one made from a secret. @@ -167,10 +180,11 @@ void generated() { std::array message{}; message.fill(0x29); std::array const aux{}; - auto const signature = key->sign(crypto::schnorr, message, aux); + auto const signature = key->sign(crypto::signing_schemes::schnorr, message, aux); auto const public_key = key->public_key(); BOOST_TEST(signature && public_key); - BOOST_TEST(crypto::verify(crypto::schnorr, *signature, message, *public_key).has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, *signature, message, *public_key) + .has_value()); auto const other = secp::keypair::generate(); BOOST_TEST(other.has_value() && *other->public_key() != *public_key); } @@ -179,33 +193,35 @@ void ecdsa() { auto const key = from_byte(0x24); std::array hash{}; hash.fill(0x99); - auto const signature = key.sign(crypto::ecdsa_sha256, crypto::prehashed{hash}); + auto const signature = + key.sign(crypto::signing_schemes::ecdsa_sha256, crypto::signing_schemes::prehashed{hash}); auto const public_key = key.public_key(); if (!BOOST_TEST(signature && public_key)) { return; } - BOOST_TEST( - crypto::verify(crypto::ecdsa_sha256, *signature, crypto::prehashed{hash}, *public_key) - .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signature, + crypto::signing_schemes::prehashed{hash}, *public_key) + .has_value()); // Low-S: s is at most half the group order, so its first byte is below 0x80. BOOST_TEST(signature->bytes()[32] < 0x80); BOOST_TEST(secp::is_low_s(*signature)); // The high-S form of the same signature is refused, as libsecp256k1's verify refuses it. auto const high = typed(webcpp::test::negate_s(signature->bytes())); BOOST_TEST(!secp::is_low_s(high)); - BOOST_TEST( - crypto::verify(crypto::ecdsa_sha256, high, crypto::prehashed{hash}, *public_key).error() == - crypto::error::invalid_signature); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, high, + crypto::signing_schemes::prehashed{hash}, *public_key) + .error() == crypto::error::invalid_signature); std::array overflow{}; overflow.fill(0xff); // r and s not below the order: the compact parser refuses it - BOOST_TEST(crypto::verify(crypto::ecdsa_sha256, typed(overflow), - crypto::prehashed{hash}, *public_key) + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + typed(overflow), + crypto::signing_schemes::prehashed{hash}, *public_key) .error() == crypto::error::invalid_signature); // The uncompressed form parses to the same key, which verifies. auto const full = secp::public_key::from_bytes(uncompressed(key)); - BOOST_TEST(full.has_value() && - crypto::verify(crypto::ecdsa_sha256, *signature, crypto::prehashed{hash}, *full) - .has_value()); + BOOST_TEST(full.has_value() && crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signature, + crypto::signing_schemes::prehashed{hash}, *full) + .has_value()); } // The public key of ECDSA's verification is made first: every way 33 or 65 bytes can be no @@ -240,21 +256,25 @@ void ecdsa_message_is_hashed() { for (std::size_t i = 0; i < message.size(); ++i) { message[i] = static_cast((i * 7) + 1); } - auto const of_message = key.sign(crypto::ecdsa_sha256, message); + auto const of_message = key.sign(crypto::signing_schemes::ecdsa_sha256, message); auto const of_digest = - key.sign(crypto::ecdsa_sha256, crypto::prehashed{crypto::detail::sha256_of(message)}); - auto const of_marker = key.sign(crypto::ecdsa_sha256, crypto::prehashed{message}); + key.sign(crypto::signing_schemes::ecdsa_sha256, + crypto::signing_schemes::prehashed{crypto::detail::sha256_of(message)}); + auto const of_marker = key.sign(crypto::signing_schemes::ecdsa_sha256, + crypto::signing_schemes::prehashed{message}); if (!BOOST_TEST(public_key && of_message && of_digest && of_marker)) { return; } BOOST_TEST(*of_message == *of_digest); BOOST_TEST(*of_message != *of_marker); - BOOST_TEST(crypto::verify(crypto::ecdsa_sha256, *of_message, message, *public_key).has_value()); BOOST_TEST( - crypto::verify(crypto::ecdsa_sha256, *of_message, crypto::prehashed{message}, *public_key) - .error() == crypto::error::invalid_signature); + crypto::verify(crypto::signing_schemes::ecdsa_sha256, *of_message, message, *public_key) + .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *of_message, + crypto::signing_schemes::prehashed{message}, *public_key) + .error() == crypto::error::invalid_signature); // The recoverable signature's r and s are the same as ecdsa_sha256's. - auto const recoverable = key.sign(crypto::ecdsa_sha256_recoverable, message); + auto const recoverable = key.sign(crypto::signing_schemes::ecdsa_sha256_recoverable, message); BOOST_TEST( recoverable.has_value() && std::ranges::equal(std::span(recoverable->bytes()).first<64>(), of_message->bytes())); @@ -270,7 +290,8 @@ void sighash() { for (std::size_t i = 0; i < digest.size(); ++i) { digest[i] = static_cast(0xa0U ^ i); } - auto const signature = key.sign(crypto::ecdsa_sha256, crypto::prehashed{digest}); + auto const signature = + key.sign(crypto::signing_schemes::ecdsa_sha256, crypto::signing_schemes::prehashed{digest}); auto const public_key = key.public_key(); if (!BOOST_TEST(signature && public_key)) { return; @@ -288,9 +309,9 @@ void sighash() { secp256k1_ecdsa_signature_serialize_compact(context, compact.data(), &reference); secp256k1_context_destroy(context); BOOST_TEST(signature->bytes() == compact); - BOOST_TEST( - crypto::verify(crypto::ecdsa_sha256, *signature, crypto::prehashed{digest}, *public_key) - .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signature, + crypto::signing_schemes::prehashed{digest}, *public_key) + .has_value()); } // Hedged ECDSA differs from the plain one and verifies, of a message as of a digest. @@ -300,16 +321,18 @@ void hedged_differs() { std::array const message{'h', 'e', 'l', 'l', 'o'}; std::array entropy{}; entropy.fill(0x5a); - auto const plain = key.sign(crypto::ecdsa_sha256, message); - auto const hedged = key.sign(crypto::ecdsa_sha256, message, entropy); + auto const plain = key.sign(crypto::signing_schemes::ecdsa_sha256, message); + auto const hedged = key.sign(crypto::signing_schemes::ecdsa_sha256, message, entropy); auto const digest = crypto::detail::sha256_of(message); - auto const hedged_digest = key.sign(crypto::ecdsa_sha256, crypto::prehashed{digest}, entropy); + auto const hedged_digest = key.sign(crypto::signing_schemes::ecdsa_sha256, + crypto::signing_schemes::prehashed{digest}, entropy); if (!BOOST_TEST(public_key && plain && hedged && hedged_digest)) { return; } BOOST_TEST(*hedged != *plain); BOOST_TEST(*hedged == *hedged_digest); - BOOST_TEST(crypto::verify(crypto::ecdsa_sha256, *hedged, message, *public_key).has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *hedged, message, *public_key) + .has_value()); } // A signature's bytes as they are received, in a vector. @@ -335,26 +358,31 @@ void verified_from_vectors() { auto const key = from_byte(0x24); auto const public_key = key.public_key(); std::array const message{'h', 'e', 'l', 'l', 'o'}; - auto const ecdsa_signed = key.sign(crypto::ecdsa_sha256, message); - auto const schnorr_signed = key.sign(crypto::schnorr, message); + auto const ecdsa_signed = key.sign(crypto::signing_schemes::ecdsa_sha256, message); + auto const schnorr_signed = key.sign(crypto::signing_schemes::schnorr, message); if (!BOOST_TEST(public_key && ecdsa_signed && schnorr_signed)) { return; } auto const ecdsa_bytes = received_bytes(*ecdsa_signed); auto const ecdsa_made = secp::ecdsa_signature::from_bytes(ecdsa_bytes); if (BOOST_TEST(ecdsa_made.has_value())) { - BOOST_TEST(public_key->verify(crypto::ecdsa_sha256, *ecdsa_made, message).has_value()); + BOOST_TEST(public_key->verify(crypto::signing_schemes::ecdsa_sha256, *ecdsa_made, message) + .has_value()); BOOST_TEST( - crypto::verify(crypto::ecdsa_sha256, *ecdsa_made, message, *public_key).has_value()); + crypto::verify(crypto::signing_schemes::ecdsa_sha256, *ecdsa_made, message, *public_key) + .has_value()); } other_sizes_refused(ecdsa_bytes); auto const schnorr_bytes = received_bytes(*schnorr_signed); auto const schnorr_made = secp::schnorr_signature::from_bytes(schnorr_bytes); if (BOOST_TEST(schnorr_made.has_value())) { - BOOST_TEST(public_key->verify(crypto::schnorr, *schnorr_made, message).has_value()); + BOOST_TEST(public_key->verify(crypto::signing_schemes::schnorr, *schnorr_made, message) + .has_value()); BOOST_TEST( - crypto::verify(crypto::schnorr, *schnorr_made, message, *public_key).has_value()); - BOOST_TEST(crypto::verify(crypto::schnorr, *schnorr_made, message, public_key->xonly()) + crypto::verify(crypto::signing_schemes::schnorr, *schnorr_made, message, *public_key) + .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, *schnorr_made, message, + public_key->xonly()) .has_value()); } other_sizes_refused(schnorr_bytes); @@ -366,89 +394,98 @@ void recovered_from_vector() { auto const key = from_byte(0x24); auto const public_key = key.public_key(); std::array const message{'h', 'e', 'l', 'l', 'o'}; - auto const recoverable_signed = key.sign(crypto::ecdsa_sha256_recoverable, message); + auto const recoverable_signed = + key.sign(crypto::signing_schemes::ecdsa_sha256_recoverable, message); if (!BOOST_TEST(public_key && recoverable_signed)) { return; } auto const recoverable_bytes = received_bytes(*recoverable_signed); auto const recoverable_made = secp::recoverable_signature::from_bytes(recoverable_bytes); if (BOOST_TEST(recoverable_made.has_value())) { - auto const recovered = - secp::recover(crypto::ecdsa_sha256_recoverable, *recoverable_made, message); + auto const recovered = secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, + *recoverable_made, message); BOOST_TEST(recovered.has_value() && *recovered == *public_key); } other_sizes_refused(recoverable_bytes); } // The pairs that go together, and those that do not. +static_assert(crypto::can_sign>); +static_assert(crypto::can_sign>); +static_assert(crypto::can_sign>); static_assert( - crypto::can_sign>); -static_assert(crypto::can_sign>); -static_assert( - crypto::can_sign>); -static_assert(crypto::can_sign>); -static_assert(!crypto::can_sign>); -static_assert(!crypto::can_sign>); -static_assert(!crypto::can_sign>); -static_assert( - !crypto::can_sign>); + crypto::can_sign>); +static_assert(!crypto::can_sign>); +static_assert(!crypto::can_sign>); +static_assert(!crypto::can_sign>); +static_assert(!crypto::can_sign>); using message_span = std::span; -static_assert(crypto::can_verify); -static_assert(crypto::can_verify, secp::public_key>); -static_assert(crypto::can_verify>); -static_assert(crypto::can_verify>); -static_assert(!crypto::can_verify, - std::array>); +static_assert(crypto::can_verify); +static_assert(crypto::can_verify, secp::public_key>); +static_assert(crypto::can_verify>); +static_assert(crypto::can_verify>); +static_assert( + !crypto::can_verify, std::array>); // Bytes of another size, or of a size known only at run time, are no x-only key. -static_assert(!crypto::can_verify>); -static_assert(!crypto::can_verify>); +static_assert(!crypto::can_verify>); +static_assert(!crypto::can_verify>); // Bytes are no secp256k1 ECDSA key: ECDSA never infers its curve from a number of bytes. -static_assert(!crypto::can_verify>); -static_assert(!crypto::can_verify); +static_assert(!crypto::can_verify>); +static_assert(!crypto::can_verify); // The typed key verifies Schnorr beside its 32 x-only bytes; a marker is no Schnorr input. -static_assert( - crypto::can_verify); -static_assert(!crypto::can_verify, - secp::public_key>); +static_assert(crypto::can_verify); +static_assert(!crypto::can_verify, secp::public_key>); // Each scheme verifies its own type alone: bytes, and the other scheme's type, are none // (design R1), the recoverable one included, which recover takes. -static_assert(!crypto::can_verify); -static_assert( - !crypto::can_verify); -static_assert(!crypto::can_verify); -static_assert(!crypto::can_verify, +static_assert(!crypto::can_verify); -static_assert(!crypto::can_verify, message_span, - std::array>); +static_assert(!crypto::can_verify); +static_assert(!crypto::can_verify); +static_assert(!crypto::can_verify, message_span, secp::public_key>); +static_assert(!crypto::can_verify, + message_span, std::array>); static_assert(std::is_same_v().sign( - crypto::ecdsa_sha256_recoverable, + crypto::signing_schemes::ecdsa_sha256_recoverable, std::declval>())), boost::system::result>); static_assert(std::is_same_v().sign( - crypto::schnorr, std::declval>())), + crypto::signing_schemes::schnorr, + std::declval>())), boost::system::result>); -static_assert( - std::is_same_v().sign( - crypto::ecdsa_sha256, std::declval>())), - boost::system::result>); +static_assert(std::is_same_v().sign( + crypto::signing_schemes::ecdsa_sha256, + std::declval>())), + boost::system::result>); // The hedged and the explicit-aux forms give the types too. -static_assert( - std::is_same_v().sign( - crypto::ecdsa_sha256, std::declval>(), - std::declval>())), - boost::system::result>); static_assert(std::is_same_v().sign( - crypto::schnorr, std::declval>(), + crypto::signing_schemes::ecdsa_sha256, + std::declval>(), + std::declval>())), + boost::system::result>); +static_assert(std::is_same_v().sign( + crypto::signing_schemes::schnorr, + std::declval>(), std::declval>())), boost::system::result>); static_assert( @@ -521,10 +558,10 @@ void secret_round_trip() { } BOOST_TEST(*again->public_key() == *key->public_key()); std::array const message{'a', 'b', 'c'}; - auto const signature = again->sign(crypto::schnorr, message); - BOOST_TEST( - signature.has_value() && - crypto::verify(crypto::schnorr, *signature, message, *key->public_key()).has_value()); + auto const signature = again->sign(crypto::signing_schemes::schnorr, message); + BOOST_TEST(signature.has_value() && crypto::verify(crypto::signing_schemes::schnorr, *signature, + message, *key->public_key()) + .has_value()); } // A public key's three byte forms: the uncompressed one is libsecp256k1's, the compressed one and @@ -576,20 +613,23 @@ void moved_from() { std::array const aux{}; BOOST_TEST(key.public_key().error() == crypto::error::invalid_state); BOOST_TEST(key.secret().error() == crypto::error::invalid_state); - BOOST_TEST(key.sign(crypto::schnorr, message, aux).error() == crypto::error::invalid_state); - BOOST_TEST(key.sign(crypto::schnorr, message).error() == crypto::error::invalid_state); - BOOST_TEST(key.sign(crypto::ecdsa_sha256, message).error() == crypto::error::invalid_state); + BOOST_TEST(key.sign(crypto::signing_schemes::schnorr, message, aux).error() == + crypto::error::invalid_state); + BOOST_TEST(key.sign(crypto::signing_schemes::schnorr, message).error() == + crypto::error::invalid_state); + BOOST_TEST(key.sign(crypto::signing_schemes::ecdsa_sha256, message).error() == + crypto::error::invalid_state); BOOST_TEST(key.agree(*moved.public_key()).error() == crypto::error::invalid_state); BOOST_TEST(key.agree_hashed(*moved.public_key()).error() == crypto::error::invalid_state); BOOST_TEST(key.agree_point(*moved.public_key()).error() == crypto::error::invalid_state); - BOOST_TEST(moved.sign(crypto::schnorr, message, aux).has_value()); + BOOST_TEST(moved.sign(crypto::signing_schemes::schnorr, message, aux).has_value()); // A key pair moved from a moved-from one is empty too (I1). secp::keypair again = std::move(key); BOOST_TEST(again.public_key().error() == crypto::error::invalid_state); std::swap(again, moved); BOOST_TEST(moved.public_key().error() == crypto::error::invalid_state); key = std::move(again); - BOOST_TEST(key.sign(crypto::schnorr, message, aux).has_value()); + BOOST_TEST(key.sign(crypto::signing_schemes::schnorr, message, aux).has_value()); } // NOLINTEND(bugprone-use-after-move) diff --git a/test/secp256k1_wycheproof_test.cpp b/test/secp256k1_wycheproof_test.cpp index ad4599f8..547d8334 100644 --- a/test/secp256k1_wycheproof_test.cpp +++ b/test/secp256k1_wycheproof_test.cpp @@ -5,8 +5,9 @@ // https://www.boost.org/LICENSE_1_0.txt) // secp256k1 against Wycheproof (spec 8.1): the Bitcoin ECDSA vectors through -// crypto::verify(crypto::ecdsa_sha256, ...), the message hashed inside, each verdict the same as -// for its SHA-256 given as crypto::prehashed. The ECDH vectors are secp256k1_ecdh_test.cpp's. +// crypto::verify(crypto::signing_schemes::ecdsa_sha256, ...), the message hashed inside, each +// verdict the same as for its SHA-256 given as crypto::signing_schemes::prehashed. The ECDH vectors +// are secp256k1_ecdh_test.cpp's. #include #include @@ -88,9 +89,10 @@ void ecdsa_bitcoin() { compact.data(), &parsed), 1); auto const signature = secp::ecdsa_signature::from_bytes(compact).value(); - auto const result = crypto::verify(crypto::ecdsa_sha256, signature, message, *key); - auto const of_digest = - crypto::verify(crypto::ecdsa_sha256, signature, crypto::prehashed{hash}, *key); + auto const result = + crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, message, *key); + auto const of_digest = crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, + crypto::signing_schemes::prehashed{hash}, *key); BOOST_TEST_EQ(result.has_value(), of_digest.has_value()); auto const verdict = str(t.at("result")); if (verdict == "valid") { diff --git a/test/secp256k1_xonly_tweak_test.cpp b/test/secp256k1_xonly_tweak_test.cpp index 40594926..a98c3356 100644 --- a/test/secp256k1_xonly_tweak_test.cpp +++ b/test/secp256k1_xonly_tweak_test.cpp @@ -126,7 +126,7 @@ void check_input(json::value const& input, int index) { // bytes (a 65th is the hash type, when it is not SIGHASH_DEFAULT). std::array const aux{}; auto const sighash = fixed<32>(intermediary.at("sigHash")); - auto const signature = key.sign(crypto::schnorr, sighash, aux); + auto const signature = key.sign(crypto::signing_schemes::schnorr, sighash, aux); auto const& expected = input.at("expected"); auto const& witnesses = expected.at("witness").as_array(); auto const witness = test::from_hex(str(witnesses.at(0))); @@ -142,7 +142,8 @@ void check_input(json::value const& input, int index) { !std::ranges::equal(signature->bytes(), std::span(witness).first(64))) { fail("keyPathSpending input " + std::to_string(index) + ": signature differs"); } - BOOST_TEST(signature && crypto::verify(crypto::schnorr, *signature, sighash, output->key)); + BOOST_TEST(signature && + crypto::verify(crypto::signing_schemes::schnorr, *signature, sighash, output->key)); } int key_path_inputs(json::value const& doc) { diff --git a/test/signature_types_test.cpp b/test/signature_types_test.cpp index 34a90820..08fc37b5 100644 --- a/test/signature_types_test.cpp +++ b/test/signature_types_test.cpp @@ -98,47 +98,64 @@ static_assert(!has_recovery_id); using crypto::detail::signature_of_t; +static_assert(std::is_same_v, + ed25519::signature>); +static_assert(std::is_same_v, + ed25519::signature>); +static_assert(std::is_same_v, + p256::ecdsa_signature>); static_assert( - std::is_same_v, ed25519::signature>); -static_assert( - std::is_same_v, ed25519::signature>); + std::is_same_v, + p256::ecdsa_signature>); static_assert( - std::is_same_v, p256::ecdsa_signature>); -static_assert(std::is_same_v, - p256::ecdsa_signature>); -static_assert(std::is_same_v, - secp256k1::ecdsa_signature>); -static_assert(std::is_same_v, + std::is_same_v, + secp256k1::ecdsa_signature>); +static_assert(std::is_same_v, secp256k1::recoverable_signature>); -static_assert( - std::is_same_v, - secp256k1::recoverable_signature>); -static_assert(std::is_same_v, - secp256k1::schnorr_signature>); -static_assert(std::is_same_v, - secp256k1::ecdsa_signature>); -static_assert(std::is_same_v, - secp256k1::schnorr_signature>); -static_assert(std::is_same_v, crypto::schnorr_t>, - secp256k1::schnorr_signature>); -static_assert(std::is_same_v, crypto::schnorr_t>, +static_assert(std::is_same_v, + secp256k1::recoverable_signature>); +static_assert(std::is_same_v, secp256k1::schnorr_signature>); +static_assert( + std::is_same_v, + secp256k1::ecdsa_signature>); +static_assert( + std::is_same_v, + secp256k1::schnorr_signature>); +static_assert( + std::is_same_v, crypto::signing_schemes::schnorr_t>, + secp256k1::schnorr_signature>); +static_assert(std::is_same_v< + signature_of_t, crypto::signing_schemes::schnorr_t>, + secp256k1::schnorr_signature>); // A pair that neither signs nor verifies has none. -static_assert(std::is_same_v, void>); -static_assert(std::is_same_v, void>); -static_assert(std::is_same_v, void>); -static_assert(std::is_same_v< - signature_of_t, void>); +static_assert( + std::is_same_v, void>); static_assert(std::is_same_v< - signature_of_t, void>); + signature_of_t, void>); static_assert( - std::is_same_v, void>); + std::is_same_v, void>); +static_assert(std::is_same_v, + void>); +static_assert(std::is_same_v, + void>); +static_assert(std::is_same_v< + signature_of_t, + void>); +static_assert(std::is_same_v, + void>); static_assert( - std::is_same_v, void>); -static_assert(std::is_same_v, crypto::eddsa_t>, void>); + std::is_same_v, crypto::signing_schemes::eddsa_t>, + void>); static_assert( - std::is_same_v, crypto::schnorr_t>, void>); + std::is_same_v, crypto::signing_schemes::schnorr_t>, + void>); // Bytes 1, 2, ..., count. std::vector counting_bytes(std::size_t count) { diff --git a/test/signing_curves_test.cpp b/test/signing_curves_test.cpp index 2e0c08bf..dbba182c 100644 --- a/test/signing_curves_test.cpp +++ b/test/signing_curves_test.cpp @@ -5,16 +5,16 @@ // https://www.boost.org/LICENSE_1_0.txt) // Every curve's crypto::verify in one program: a 32-byte array is BIP340's x-only key under -// crypto::schnorr and no key under crypto::eddsa, which takes curves::ed25519::public_key (design -// R17), each call resolved to its curve's overload with no ambiguity and no catch-all, and each -// signature verifying under its own scheme alone: its type is its curve's and scheme's (design -// R1), so a signature of another curve or scheme is refused by can_verify and by the build, and -// its bytes made into the other type are refused at run time; ECDSA takes each curve's key object -// and no bytes. The backend, named, comes first on every curve and picks its own curve's overload -// alone; Ed25519's policy is the fifth argument. Every signing key pair (crypto::signing_keypair: -// Ed25519's, P-256's and secp256k1's, not X25519's) signs through crypto::sign, used through the -// concept alone, a signature its public key verifies with crypto::verify under each scheme that -// verifies. +// crypto::signing_schemes::schnorr and no key under crypto::signing_schemes::eddsa, which takes +// curves::ed25519::public_key (design R17), each call resolved to its curve's overload with no +// ambiguity and no catch-all, and each signature verifying under its own scheme alone: its type is +// its curve's and scheme's (design R1), so a signature of another curve or scheme is refused by +// can_verify and by the build, and its bytes made into the other type are refused at run time; +// ECDSA takes each curve's key object and no bytes. The backend, named, comes first on every curve +// and picks its own curve's overload alone; Ed25519's policy is the fifth argument. Every signing +// key pair (crypto::signing_keypair: Ed25519's, P-256's and secp256k1's, not X25519's) signs +// through crypto::sign, used through the concept alone, a signature its public key verifies with +// crypto::verify under each scheme that verifies. #include #include @@ -49,47 +49,50 @@ using p256_ecdsa_signature = crypto::curves::p256::ecdsa_signature; using p256_bearssl_key = crypto::curves::p256::basic_public_key; // A 32-byte array is a key of schnorr alone; eddsa's key is Ed25519's object. -static_assert(!crypto::detail::has_verifier_v); -static_assert(crypto::detail::has_verifier_v); -static_assert(!crypto::detail::has_verifier_v); -static_assert(!crypto::can_verify); -static_assert(crypto::can_verify); -static_assert(!crypto::can_verify); -static_assert(crypto::can_verify); +static_assert(crypto::detail::has_verifier_v); +static_assert(!crypto::detail::has_verifier_v); +static_assert(!crypto::can_verify); +static_assert(crypto::can_verify); +static_assert(!crypto::can_verify); +static_assert(crypto::can_verify); -static_assert(!crypto::can_verify); +static_assert(!crypto::can_verify); // A span of a size known only at run time is no key. -static_assert(!crypto::can_verify>); -static_assert(!crypto::can_verify>); +static_assert(!crypto::can_verify>); +static_assert(!crypto::can_verify>); // ECDSA's key is each curve's object, and its signature each curve's type. -static_assert(crypto::can_verify); -static_assert(crypto::can_verify); +static_assert(crypto::can_verify); +static_assert(crypto::can_verify); // The wrong curve (the spec's scenario): a secp256k1 signature is no P-256 signature, and the // other way round, though both are 64 bytes, r then s. -static_assert(!crypto::can_verify); -static_assert(!crypto::can_verify); +static_assert(!crypto::can_verify); +static_assert(!crypto::can_verify); // The wrong scheme: Ed25519's and BIP340's signatures, both 64 bytes, are not each other's. -static_assert(!crypto::can_verify); -static_assert(!crypto::can_verify); +static_assert(!crypto::can_verify); +static_assert(!crypto::can_verify); -// Whether crypto::verify(crypto::ecdsa_sha256, ...) is callable with `Key` and its -// signature type: a P-256 key takes its own backend alone, which is deduced and which an explicit -// other one contradicts. +// Whether crypto::verify(crypto::signing_schemes::ecdsa_sha256, ...) is callable with +// `Key` and its signature type: a P-256 key takes its own backend alone, which is deduced and which +// an explicit other one contradicts. template -concept verifies_ecdsa_on = - requires(crypto::detail::signature_of_t const& signature, - message_bytes message, Key const& key) { - crypto::verify(crypto::ecdsa_sha256, signature, message, key); - }; +concept verifies_ecdsa_on = requires( + crypto::detail::signature_of_t const& signature, + message_bytes message, Key const& key) { + crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, message, key); +}; static_assert(verifies_ecdsa_on); static_assert(!verifies_ecdsa_on); static_assert( @@ -109,22 +112,29 @@ void byte_keys() { } auto const ed25519_key = *ed25519->public_key(); key_bytes const xonly_key = secp256k1->public_key()->xonly(); - auto const eddsa_signature = ed25519->sign(crypto::eddsa, message); - auto const schnorr_signature = secp256k1->sign(crypto::schnorr, message); + auto const eddsa_signature = ed25519->sign(crypto::signing_schemes::eddsa, message); + auto const schnorr_signature = secp256k1->sign(crypto::signing_schemes::schnorr, message); if (!BOOST_TEST(eddsa_signature.has_value()) || !BOOST_TEST(schnorr_signature.has_value())) { return; } - BOOST_TEST(crypto::verify(crypto::eddsa, *eddsa_signature, message, ed25519_key).has_value()); - BOOST_TEST(crypto::verify(crypto::schnorr, *schnorr_signature, message, xonly_key).has_value()); + BOOST_TEST( + crypto::verify(crypto::signing_schemes::eddsa, *eddsa_signature, message, ed25519_key) + .has_value()); + BOOST_TEST( + crypto::verify(crypto::signing_schemes::schnorr, *schnorr_signature, message, xonly_key) + .has_value()); auto const schnorr_as_eddsa = ed25519_signature::from_bytes(schnorr_signature->bytes()); auto const eddsa_as_schnorr = crypto::curves::secp256k1::schnorr_signature::from_bytes(eddsa_signature->bytes()); if (!BOOST_TEST(schnorr_as_eddsa.has_value()) || !BOOST_TEST(eddsa_as_schnorr.has_value())) { return; } - BOOST_TEST(crypto::verify(crypto::eddsa, *schnorr_as_eddsa, message, ed25519_key).error() == - crypto::error::invalid_signature); - BOOST_TEST(crypto::verify(crypto::schnorr, *eddsa_as_schnorr, message, xonly_key).has_error()); + BOOST_TEST( + crypto::verify(crypto::signing_schemes::eddsa, *schnorr_as_eddsa, message, ed25519_key) + .error() == crypto::error::invalid_signature); + BOOST_TEST( + crypto::verify(crypto::signing_schemes::schnorr, *eddsa_as_schnorr, message, xonly_key) + .has_error()); } using hello = std::array; @@ -142,25 +152,25 @@ void backend_first_ed25519() { return; } auto const ed25519_key = *ed25519->public_key(); - auto const signature = ed25519->sign(crypto::eddsa, hello_message); + auto const signature = ed25519->sign(crypto::signing_schemes::eddsa, hello_message); if (!BOOST_TEST(signature.has_value())) { return; } - BOOST_TEST(crypto::verify(crypto::eddsa, *signature, hello_message, - ed25519_key) + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, *signature, + hello_message, ed25519_key) .has_value()); - BOOST_TEST(crypto::verify(crypto::eddsa, *signature, hello_message, - ed25519_key, + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, *signature, + hello_message, ed25519_key, crypto::curves::ed25519::strict) .has_value()); - BOOST_TEST(crypto::verify(crypto::eddsa, *signature, hello_message, ed25519_key, - crypto::curves::ed25519::strict) + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, *signature, hello_message, + ed25519_key, crypto::curves::ed25519::strict) .has_value()); auto altered_bytes = signature->bytes(); altered_bytes[0] ^= 0x01U; auto const altered = ed25519_signature::from_bytes(altered_bytes).value(); - BOOST_TEST(crypto::verify(crypto::eddsa, altered, hello_message, - ed25519_key, + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, altered, + hello_message, ed25519_key, crypto::curves::ed25519::strict) .error() == crypto::error::invalid_signature); } @@ -182,29 +192,32 @@ void backend_first_ecdsa() { return; } auto const xonly_key = secp256k1_key->xonly(); - auto const schnorr_signature = secp256k1->sign(crypto::schnorr, hello_message); - auto const ecdsa_signature = secp256k1->sign(crypto::ecdsa_sha256, hello_message); + auto const schnorr_signature = secp256k1->sign(crypto::signing_schemes::schnorr, hello_message); + auto const ecdsa_signature = + secp256k1->sign(crypto::signing_schemes::ecdsa_sha256, hello_message); auto const recoverable_signature = - secp256k1->sign(crypto::ecdsa_sha256_recoverable, hello_message); - auto const p256_signature = p256->sign(crypto::ecdsa_sha256, hello_message); + secp256k1->sign(crypto::signing_schemes::ecdsa_sha256_recoverable, hello_message); + auto const p256_signature = p256->sign(crypto::signing_schemes::ecdsa_sha256, hello_message); if (!BOOST_TEST(schnorr_signature.has_value()) || !BOOST_TEST(ecdsa_signature.has_value()) || !BOOST_TEST(recoverable_signature.has_value()) || !BOOST_TEST(p256_signature.has_value())) { return; } - BOOST_TEST(crypto::verify(crypto::schnorr, *schnorr_signature, - hello_message, xonly_key) + BOOST_TEST(crypto::verify( + crypto::signing_schemes::schnorr, *schnorr_signature, hello_message, xonly_key) .has_value()); - BOOST_TEST(crypto::verify(crypto::schnorr, *schnorr_signature, - hello_message, *secp256k1_key) + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, + *schnorr_signature, hello_message, + *secp256k1_key) .has_value()); - BOOST_TEST(crypto::verify(crypto::ecdsa_sha256, *ecdsa_signature, - hello_message, *secp256k1_key) + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + *ecdsa_signature, hello_message, + *secp256k1_key) .has_value()); auto const recovered = crypto::curves::secp256k1::recover( - crypto::ecdsa_sha256_recoverable, *recoverable_signature, hello_message); + crypto::signing_schemes::ecdsa_sha256_recoverable, *recoverable_signature, hello_message); BOOST_TEST((recovered.has_value() && *recovered == *secp256k1_key)); - BOOST_TEST(crypto::verify(crypto::ecdsa_sha256, *p256_signature, - hello_message, *p256_key) + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + *p256_signature, hello_message, *p256_key) .has_value()); } @@ -247,13 +260,16 @@ int main() { backend_first_ed25519(); backend_first_ecdsa(); signs_what_its_public_key_verifies< - crypto::curves::ed25519::basic_keypair>(crypto::eddsa); + crypto::curves::ed25519::basic_keypair>( + crypto::signing_schemes::eddsa); signs_what_its_public_key_verifies< - crypto::curves::p256::basic_keypair>(crypto::ecdsa_sha256); + crypto::curves::p256::basic_keypair>( + crypto::signing_schemes::ecdsa_sha256); signs_what_its_public_key_verifies< crypto::curves::secp256k1::basic_keypair>( - crypto::ecdsa_sha256); + crypto::signing_schemes::ecdsa_sha256); signs_what_its_public_key_verifies< - crypto::curves::secp256k1::basic_keypair>(crypto::schnorr); + crypto::curves::secp256k1::basic_keypair>( + crypto::signing_schemes::schnorr); return webcpp::test::exit_status(boost::report_errors()); } diff --git a/test/signing_namespaces_test.cpp b/test/signing_namespaces_test.cpp new file mode 100644 index 00000000..919d541c --- /dev/null +++ b/test/signing_namespaces_test.cpp @@ -0,0 +1,100 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The scheme tags and prehashed are in crypto::signing_schemes (design D1): each of the six tags is +// a scheme of the library's one list, is made by naming it and from no braces, and a P-256 key +// pair signs a digest under the marker as it signs the message that digest hashes. The old names +// in crypto itself are gone, with no alias: test/messages/scheme_in_crypto_namespace stops a +// program that names one. + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include + +namespace crypto = webcpp::crypto; +namespace signing_schemes = webcpp::crypto::signing_schemes; + +namespace probes { + +// A function that takes a tag by value, declared only: the probe below never evaluates a call. It +// is in a named namespace, as the unused-template check reads an unnamed one as the file's alone. +template +void take_tag(Tag); + +// Whether `{}` makes a `Tag` where one is expected: it does not for a tag whose default +// constructor is explicit. +template +concept from_braces = requires { take_tag({}); }; + +} // namespace probes + +namespace { + +using probes::from_braces; + +static_assert(crypto::detail::is_scheme_v); +static_assert(crypto::detail::is_scheme_v); +static_assert(crypto::detail::is_scheme_v); +static_assert(crypto::detail::is_scheme_v); +static_assert(crypto::detail::is_scheme_v); +static_assert(crypto::detail::is_scheme_v); + +static_assert(std::is_default_constructible_v); +static_assert(std::is_default_constructible_v); +static_assert(std::is_default_constructible_v); +static_assert(std::is_default_constructible_v); +static_assert(std::is_default_constructible_v); +static_assert(std::is_default_constructible_v); + +static_assert(!from_braces); +static_assert(!from_braces); +static_assert(!from_braces); +static_assert(!from_braces); +static_assert(!from_braces); +static_assert(!from_braces); + +static_assert(std::is_same_v); +static_assert(std::is_same_v); + +// A P-256 key pair signs a digest under the marker as it signs the message that digest hashes. +void prehashed_equals_message() { + std::array scalar{}; + scalar.back() = 1; + auto const key = crypto::curves::p256::keypair::from_secret(scalar); + if (!BOOST_TEST(key.has_value())) { + return; + } + std::array const message{'h', 'e', 'l', 'l', 'o'}; + std::array digest{}; + BOOST_TEST(webcpp::hash::digest_of(digest, std::span(message)) + .has_value()); + auto const of_message = key->sign(signing_schemes::ecdsa_sha256, message); + auto const of_digest = + key->sign(signing_schemes::ecdsa_sha256, signing_schemes::prehashed{digest}); + if (BOOST_TEST(of_message.has_value()) && BOOST_TEST(of_digest.has_value())) { + BOOST_TEST(of_message->bytes() == of_digest->bytes()); + } + auto const free_form = crypto::sign(*key, signing_schemes::ecdsa_sha256, message); + if (BOOST_TEST(free_form.has_value()) && BOOST_TEST(of_message.has_value())) { + BOOST_TEST(free_form->bytes() == of_message->bytes()); + } +} + +} // namespace + +int main() { + prehashed_equals_message(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/signing_test.cpp b/test/signing_test.cpp index ae3c7f00..8d5b6667 100644 --- a/test/signing_test.cpp +++ b/test/signing_test.cpp @@ -75,13 +75,13 @@ struct plain_tag {}; namespace webcpp::crypto::detail { template <> -inline constexpr bool signs_with_v = true; +inline constexpr bool signs_with_v = true; template <> -inline constexpr bool verifies_with_v = true; +inline constexpr bool verifies_with_v = true; template <> -struct signature_of { +struct signature_of { using type = stand_in_signature; }; @@ -91,7 +91,7 @@ struct key_backend { }; template <> -inline constexpr bool signs_with_v = true; +inline constexpr bool signs_with_v = true; template <> struct key_backend { @@ -102,7 +102,7 @@ template <> inline constexpr bool asynchronous_backend_v = true; template <> -inline constexpr bool has_verifier_v = true; +inline constexpr bool has_verifier_v = true; } // namespace webcpp::crypto::detail @@ -131,57 +131,73 @@ constexpr bool none_from_empty_braces(crypto::detail::scheme_list /* } static_assert(none_from_empty_braces(crypto::detail::all_schemes{})); -static_assert(!std::is_constructible_v); -static_assert(std::is_same_v); -static_assert(std::is_same_v); -static_assert(std::is_same_v); -static_assert(std::is_same_v); -static_assert(std::is_same_v); -static_assert(std::is_same_v); +static_assert(!std::is_constructible_v); +static_assert(std::is_same_v); +static_assert(std::is_same_v); +static_assert(std::is_same_v); +static_assert(std::is_same_v); +static_assert(std::is_same_v); +static_assert(std::is_same_v); // The schemes' sizes. -static_assert(crypto::detail::scheme_traits::signature_size == 64); -static_assert(crypto::detail::scheme_traits::digest_size == 0); -static_assert(crypto::detail::scheme_traits::signature_size == 64); -static_assert(crypto::detail::scheme_traits::digest_size == 64); -static_assert(crypto::detail::scheme_traits::signature_size == 64); -static_assert(crypto::detail::scheme_traits::digest_size == 32); -static_assert(crypto::detail::scheme_traits::signature_size == - 65); -static_assert(crypto::detail::scheme_traits::digest_size == 32); +static_assert(crypto::detail::scheme_traits::signature_size == + 64); +static_assert(crypto::detail::scheme_traits::digest_size == 0); static_assert( - crypto::detail::scheme_traits::signature_size == 65); -static_assert(crypto::detail::scheme_traits::digest_size == + crypto::detail::scheme_traits::signature_size == + 64); +static_assert( + crypto::detail::scheme_traits::digest_size == 64); +static_assert( + crypto::detail::scheme_traits::signature_size == 64); +static_assert(crypto::detail::scheme_traits::digest_size == 32); -static_assert(crypto::detail::scheme_traits::signature_size == 64); -static_assert(crypto::detail::scheme_traits::digest_size == 0); +static_assert(crypto::detail::scheme_traits< + crypto::signing_schemes::ecdsa_sha256_recoverable_t>::signature_size == 65); +static_assert(crypto::detail::scheme_traits< + crypto::signing_schemes::ecdsa_sha256_recoverable_t>::digest_size == 32); +static_assert(crypto::detail::scheme_traits< + crypto::signing_schemes::ecdsa_keccak256_recoverable_t>::signature_size == 65); +static_assert(crypto::detail::scheme_traits< + crypto::signing_schemes::ecdsa_keccak256_recoverable_t>::digest_size == 32); +static_assert(crypto::detail::scheme_traits::signature_size == + 64); +static_assert(crypto::detail::scheme_traits::digest_size == 0); // The marker deduces its size from a fixed-size digest of each kind. -static_assert(std::is_same_v>); -static_assert( - std::is_same_v{}}), crypto::prehashed<32>>); +static_assert(std::is_same_v>); static_assert( - std::is_same_v>()}), - crypto::prehashed<48>>); -static_assert( - std::is_same_v>()}), - crypto::prehashed<32>>); + std::is_same_v{}}), + crypto::signing_schemes::prehashed<32>>); +static_assert(std::is_same_v>()}), + crypto::signing_schemes::prehashed<48>>); +static_assert(std::is_same_v>()}), + crypto::signing_schemes::prehashed<32>>); // No conversion turns a span or an array into a marker, or a marker into a span. -static_assert(!std::is_convertible_v, crypto::prehashed<32>>); -static_assert(!std::is_convertible_v, message_span>); -static_assert(!std::is_convertible_v>); -static_assert(!std::is_convertible_v, crypto::prehashed<32>>); +static_assert(!std::is_convertible_v, + crypto::signing_schemes::prehashed<32>>); +static_assert(!std::is_convertible_v, message_span>); +static_assert(!std::is_convertible_v>); +static_assert( + !std::is_convertible_v, crypto::signing_schemes::prehashed<32>>); // What is a message and what is a marker. static_assert(crypto::detail::is_message_v); static_assert(crypto::detail::is_message_v); static_assert(crypto::detail::is_message_v>); -static_assert(!crypto::detail::is_message_v>); +static_assert(!crypto::detail::is_message_v>); static_assert(!crypto::detail::is_message_v); -static_assert(crypto::detail::is_prehashed_v>); +static_assert(crypto::detail::is_prehashed_v>); static_assert(!crypto::detail::is_prehashed_v); // A backend signs a digest unless it completes by itself; a byte key has no backend. @@ -191,43 +207,54 @@ static_assert(!crypto::detail::signs_prehashed_v); static_assert(std::is_void_v::type>); // can_sign: a message of any size, or a marker of the scheme's digest size. -static_assert(crypto::can_sign); -static_assert(crypto::can_sign); -static_assert(crypto::can_sign); -static_assert(crypto::can_sign>); -static_assert(!crypto::can_sign>); -static_assert(!crypto::can_sign); -static_assert(!crypto::can_sign); -static_assert(!crypto::can_sign); +static_assert( + crypto::can_sign); +static_assert( + crypto::can_sign); +static_assert( + crypto::can_sign); +static_assert(crypto::can_sign>); +static_assert(!crypto::can_sign>); +static_assert(!crypto::can_sign); +static_assert( + !crypto::can_sign); +static_assert(!crypto::can_sign); // On a backend that completes by itself, the message alone. -static_assert(crypto::can_sign); -static_assert( - !crypto::can_sign>); +static_assert(crypto::can_sign); +static_assert(!crypto::can_sign>); // can_verify: the same, over the public key, with the key's signature type. -static_assert(crypto::can_verify); -static_assert(crypto::can_verify, stand_in_public_key const&>); -static_assert(!crypto::can_verify, - stand_in_public_key>); +static_assert(crypto::can_verify); static_assert( - !crypto::can_verify); -// Another type of the same size, and bytes, are no signature of the key's (design R1). -static_assert(!crypto::can_verify); -static_assert(!crypto::can_verify, + crypto::can_verify, stand_in_public_key const&>); +static_assert(!crypto::can_verify, stand_in_public_key>); +static_assert(!crypto::can_verify); -static_assert(!crypto::can_verify, +// Another type of the same size, and bytes, are no signature of the key's (design R1). +static_assert(!crypto::can_verify); +static_assert(!crypto::can_verify, message_span, stand_in_public_key>); +static_assert( + !crypto::can_verify, + message_span, stand_in_public_key>); // A key whose curve names no signature type verifies nothing. -static_assert(std::is_void_v>); +static_assert(std::is_void_v< + crypto::detail::signature_of_t>); // The two traits are apart: a key pair does not verify, a public key does not sign. -static_assert(!crypto::can_sign); -static_assert(!crypto::can_verify); +static_assert( + !crypto::can_sign); +static_assert(!crypto::can_verify); // The catch-all verify is a candidate where no curve declares a verifier, and steps aside where // one does; a requires-expression reads its declaration alone, never its refusal. @@ -235,10 +262,11 @@ template concept catch_all_verify = requires(std::array const& signature, message_span message, PublicKey const& public_key) { { - crypto::verify(crypto::ecdsa_sha256, signature, message, public_key) + crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, message, public_key) } -> std::same_as>; }; -static_assert(!crypto::detail::has_verifier_v); +static_assert( + !crypto::detail::has_verifier_v); static_assert(catch_all_verify); static_assert(!catch_all_verify); @@ -248,10 +276,10 @@ static_assert(!catch_all_verify); template concept catch_all_verify_on = requires(std::array const& signature, message_span message, PublicKey const& public_key) { - crypto::verify(crypto::ecdsa_sha256, signature, message, public_key); + crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, message, public_key); }; static_assert(!catch_all_verify_on); -static_assert(catch_all_verify_on); +static_assert(catch_all_verify_on); // The catch-all takes a scheme tag alone: a four-argument verify whose first argument is not a // scheme, found by argument-dependent lookup through a crypto type, is not captured. @@ -268,35 +296,39 @@ constexpr bool catch_all_takes_each(crypto::detail::scheme_list /*li static_assert(catch_all_takes_each(crypto::detail::all_schemes{})); static_assert(!catch_all_takes); -static_assert(!catch_all_takes>); -static_assert(crypto::detail::is_scheme_v); -static_assert(crypto::detail::is_scheme_v); +static_assert(!catch_all_takes>); +static_assert(crypto::detail::is_scheme_v); +static_assert(crypto::detail::is_scheme_v); // Ethereum's scheme takes a message or Keccak-256's 32-byte digest, and no other size. -static_assert( - crypto::detail::input_valid_v); -static_assert(crypto::detail::input_valid_v, void>); -static_assert(!crypto::detail::input_valid_v, void>); +static_assert(crypto::detail::input_valid_v); +static_assert(crypto::detail::input_valid_v, void>); +static_assert(!crypto::detail::input_valid_v, void>); // Ed25519ph takes SHA-512's 64-byte digest alone: no message, of any size, and no other digest. -static_assert(crypto::detail::is_scheme_v); -static_assert(!crypto::detail::takes_message_v); -static_assert(crypto::detail::takes_message_v); +static_assert(crypto::detail::is_scheme_v); +static_assert(!crypto::detail::takes_message_v); +static_assert(crypto::detail::takes_message_v); // The fact lives in the scheme's traits; a type with none, a test's own scheme, takes a message. -static_assert(!crypto::detail::scheme_traits::takes_message); -static_assert(crypto::detail::scheme_traits::takes_message); -static_assert(crypto::detail::takes_message_v); static_assert( - crypto::detail::input_valid_v, void>); -static_assert(!crypto::detail::input_valid_v); + !crypto::detail::scheme_traits::takes_message); +static_assert(crypto::detail::scheme_traits::takes_message); +static_assert(crypto::detail::takes_message_v); +static_assert(crypto::detail::input_valid_v, void>); static_assert( - !crypto::detail::input_valid_v, void>); + !crypto::detail::input_valid_v); +static_assert(!crypto::detail::input_valid_v, void>); +static_assert(!crypto::detail::input_valid_v, void>); static_assert( - !crypto::detail::input_valid_v, void>); -static_assert(!crypto::detail::input_valid_v, - stand_in_async_backend>); -static_assert(!crypto::detail::input_valid_v, void>); -static_assert(!crypto::detail::is_scheme_v); + !crypto::detail::input_valid_v, stand_in_async_backend>); +static_assert(!crypto::detail::input_valid_v, void>); +static_assert(!crypto::detail::is_scheme_v); // The library's one list of schemes: is_scheme_v is true of each of its members, each has its // traits, and the list is the six tags. @@ -308,15 +340,18 @@ constexpr bool all_are_schemes(crypto::detail::scheme_list /*list*/) static_assert(all_are_schemes(crypto::detail::all_schemes{})); static_assert( - std::is_same_v< - crypto::detail::all_schemes, - crypto::detail::scheme_list>); + std::is_same_v>); static_assert(!crypto::detail::is_scheme_v); -static_assert(!crypto::detail::is_scheme_v>); -static_assert(!crypto::detail::in_scheme_list_v); -static_assert(!crypto::detail::in_scheme_list_v>); +static_assert(!crypto::detail::is_scheme_v>); +static_assert(!crypto::detail::in_scheme_list_v); +static_assert(!crypto::detail::in_scheme_list_v>); // sha256_of is SHA-256: FIPS 180-2's "abc" and the empty message. void sha256_of_is_sha256() { @@ -341,18 +376,22 @@ void message_bytes_views_the_message() { // The marker views the digest it is given, and the valid inputs pass the checks. void prehashed_views_the_digest() { digest32 const digest = crypto::detail::sha256_of(message_span{}); - crypto::prehashed const marker{digest}; + crypto::signing_schemes::prehashed const marker{digest}; BOOST_TEST_EQ(marker.digest.data(), digest.data()); boost::hash2::digest<32> hashed{}; - crypto::prehashed const from_hash2{hashed}; + crypto::signing_schemes::prehashed const from_hash2{hashed}; BOOST_TEST_EQ(from_hash2.digest.data(), hashed.data()); - crypto::detail::check_input, stand_in_backend>(); - crypto::detail::check_input, void>(); - crypto::detail::check_input, - void>(); - crypto::detail::check_input(); - crypto::detail::check_input, void>(); - crypto::detail::check_input(); + crypto::detail::check_input, stand_in_backend>(); + crypto::detail::check_input, void>(); + crypto::detail::check_input, void>(); + crypto::detail::check_input(); + crypto::detail::check_input, void>(); + crypto::detail::check_input(); } } // namespace diff --git a/test/support/secp256k1_checks.hpp b/test/support/secp256k1_checks.hpp index c80050bf..c9f3e06a 100644 --- a/test/support/secp256k1_checks.hpp +++ b/test/support/secp256k1_checks.hpp @@ -126,19 +126,20 @@ inline void expect_empty_keypair(webcpp::crypto::curves::secp256k1::keypair& key std::array const tweak{}; BOOST_TEST(key.public_key().error() == webcpp::crypto::error::invalid_state); BOOST_TEST(key.secret().error() == webcpp::crypto::error::invalid_state); - BOOST_TEST(key.sign(webcpp::crypto::schnorr, message, aux).error() == + BOOST_TEST(key.sign(webcpp::crypto::signing_schemes::schnorr, message, aux).error() == webcpp::crypto::error::invalid_state); - BOOST_TEST(key.sign(webcpp::crypto::schnorr, message).error() == + BOOST_TEST(key.sign(webcpp::crypto::signing_schemes::schnorr, message).error() == webcpp::crypto::error::invalid_state); - BOOST_TEST(key.sign(webcpp::crypto::ecdsa_sha256, message).error() == + BOOST_TEST(key.sign(webcpp::crypto::signing_schemes::ecdsa_sha256, message).error() == webcpp::crypto::error::invalid_state); - BOOST_TEST(key.sign(webcpp::crypto::ecdsa_sha256, message, aux).error() == - webcpp::crypto::error::invalid_state); - BOOST_TEST(key.sign(webcpp::crypto::ecdsa_sha256_recoverable, message).error() == + BOOST_TEST(key.sign(webcpp::crypto::signing_schemes::ecdsa_sha256, message, aux).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); + key.sign(webcpp::crypto::signing_schemes::ecdsa_sha256_recoverable, message).error() == + webcpp::crypto::error::invalid_state); + BOOST_TEST(key.sign(webcpp::crypto::signing_schemes::ecdsa_keccak256_recoverable, + webcpp::crypto::signing_schemes::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 59a2fcaf..f43216ae 100644 --- a/test/support/timing_coverage.hpp +++ b/test/support/timing_coverage.hpp @@ -602,52 +602,53 @@ void cover_async_ed25519(std::string const& backend) { return; } covered("ed25519::async_sign" + on, "crypto::async_sign", [&] { - crypto::async_sign(executor, *made, crypto::eddsa, message, keeping); + crypto::async_sign(executor, *made, crypto::signing_schemes::eddsa, message, keeping); deliver(); }); covered("ed25519::async_verify" + on, "crypto::async_verify", [&] { - crypto::async_verify(executor, crypto::eddsa, kept, message, *public_key, - counted); + crypto::async_verify(executor, crypto::signing_schemes::eddsa, kept, message, + *public_key, counted); deliver(); }); covered("ed25519::async_verify with its policy" + on, "crypto::async_verify", [&] { - crypto::async_verify(executor, crypto::eddsa, kept, message, *public_key, - crypto::curves::ed25519::strict, counted); + crypto::async_verify(executor, crypto::signing_schemes::eddsa, kept, message, + *public_key, crypto::curves::ed25519::strict, counted); deliver(); }); covered("ed25519::async_verify with a zero signature" + on, "crypto::async_verify", [&] { - crypto::async_verify(executor, crypto::eddsa, zero_signature, message, - *public_key, counted); + crypto::async_verify(executor, crypto::signing_schemes::eddsa, zero_signature, + message, *public_key, counted); deliver(); }); covered("ed25519::basic_keypair::async_sign" + on, [&] { - made->async_sign(executor, crypto::eddsa, message, counted); + made->async_sign(executor, crypto::signing_schemes::eddsa, message, counted); deliver(); }); covered("ed25519::public_key::async_verify" + on, [&] { - public_key->template async_verify(executor, crypto::eddsa, kept, message, - counted); + public_key->template async_verify(executor, crypto::signing_schemes::eddsa, + kept, message, counted); deliver(); }); covered("ed25519::public_key::async_verify with its policy" + on, [&] { - public_key->template async_verify(executor, crypto::eddsa, kept, message, + public_key->template async_verify(executor, crypto::signing_schemes::eddsa, + kept, message, crypto::curves::ed25519::strict, counted); deliver(); }); covered("ed25519::public_key::async_verify with a zero signature" + on, [&] { - public_key->template async_verify(executor, crypto::eddsa, zero_signature, - message, counted); + public_key->template async_verify(executor, crypto::signing_schemes::eddsa, + zero_signature, message, counted); deliver(); }); [[maybe_unused]] Keypair const taken(std::move(*made)); covered("ed25519::async_sign moved from" + on, "crypto::async_sign", [&] { // NOLINTNEXTLINE(bugprone-use-after-move): the moved-from key pair's refusal - crypto::async_sign(executor, *made, crypto::eddsa, message, counted); + crypto::async_sign(executor, *made, crypto::signing_schemes::eddsa, message, counted); deliver(); }); covered("ed25519::basic_keypair::async_sign moved from" + on, [&] { // NOLINTNEXTLINE(bugprone-use-after-move): the moved-from key pair's refusal - made->async_sign(executor, crypto::eddsa, message, counted); + made->async_sign(executor, crypto::signing_schemes::eddsa, message, counted); deliver(); }); BOOST_TEST_EQ(completions, 16); diff --git a/test/synchronous_forms_test.cpp b/test/synchronous_forms_test.cpp index 9594a44f..e2019819 100644 --- a/test/synchronous_forms_test.cpp +++ b/test/synchronous_forms_test.cpp @@ -278,21 +278,22 @@ void ed25519_forms() { return; } auto const public_key = made->public_key(); - auto const member_signed = made->sign(crypto::eddsa, message); - auto const free_signed = crypto::sign(*made, crypto::eddsa, message); + auto const member_signed = made->sign(crypto::signing_schemes::eddsa, message); + auto const free_signed = crypto::sign(*made, crypto::signing_schemes::eddsa, message); static_assert(std::is_same_v); if (!BOOST_TEST(public_key.has_value()) || !BOOST_TEST(member_signed.has_value()) || !BOOST_TEST(free_signed.has_value())) { return; } BOOST_TEST(*free_signed == *member_signed); - verify_forms(crypto::eddsa, *member_signed, message, *public_key); + verify_forms(crypto::signing_schemes::eddsa, *member_signed, message, *public_key); BOOST_TEST(public_key - ->verify(crypto::eddsa, *member_signed, message, - ed25519::strict) + ->verify(crypto::signing_schemes::eddsa, + *member_signed, message, ed25519::strict) .has_value()); - BOOST_TEST(crypto::verify(crypto::eddsa, *member_signed, message, - *public_key, ed25519::strict) + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, + *member_signed, message, *public_key, + ed25519::strict) .has_value()); // A key's 32 bytes, where the signature goes, are no signature. BOOST_TEST(ed25519::signature::from_bytes(public_key->bytes()).error() == @@ -307,10 +308,10 @@ void p256_forms() { } auto const public_key = made->public_key(); auto const digest = digest_of_message(); - auto const member_signed = made->sign(crypto::ecdsa_sha256, message); - auto const free_signed = crypto::sign(*made, crypto::ecdsa_sha256, message); - auto const free_prehashed = - crypto::sign(*made, crypto::ecdsa_sha256, crypto::prehashed{digest}); + auto const member_signed = made->sign(crypto::signing_schemes::ecdsa_sha256, message); + auto const free_signed = crypto::sign(*made, crypto::signing_schemes::ecdsa_sha256, message); + auto const free_prehashed = crypto::sign(*made, crypto::signing_schemes::ecdsa_sha256, + crypto::signing_schemes::prehashed{digest}); static_assert(std::is_same_v); if (!BOOST_TEST(public_key.has_value()) || !BOOST_TEST(member_signed.has_value()) || !BOOST_TEST(free_signed.has_value()) || !BOOST_TEST(free_prehashed.has_value())) { @@ -319,8 +320,9 @@ void p256_forms() { // RFC 6979's nonce: the same key and input give the same signature. BOOST_TEST(*free_signed == *member_signed); BOOST_TEST(*free_prehashed == *member_signed); - verify_forms(crypto::ecdsa_sha256, *member_signed, message, *public_key); - verify_forms(crypto::ecdsa_sha256, *member_signed, crypto::prehashed{digest}, *public_key); + verify_forms(crypto::signing_schemes::ecdsa_sha256, *member_signed, message, *public_key); + verify_forms(crypto::signing_schemes::ecdsa_sha256, *member_signed, + crypto::signing_schemes::prehashed{digest}, *public_key); } /** secp256k1: every sign, member and free, the same signatures and types. */ @@ -331,15 +333,16 @@ void secp256k1_sign_forms() { } auto const digest = digest_of_message(); std::array const extra = secret_bytes(7); - auto const ecdsa = made->sign(crypto::ecdsa_sha256, message); - same_result(ecdsa, crypto::sign(*made, crypto::ecdsa_sha256, message)); - same_result(ecdsa, crypto::sign(*made, crypto::ecdsa_sha256, crypto::prehashed{digest})); - same_result(made->sign(crypto::ecdsa_sha256, message, extra), - crypto::sign(*made, crypto::ecdsa_sha256, message, extra)); - same_result(made->sign(crypto::ecdsa_sha256_recoverable, message), - crypto::sign(*made, crypto::ecdsa_sha256_recoverable, message)); - same_result(made->sign(crypto::schnorr, message, extra), - crypto::sign(*made, crypto::schnorr, message, extra)); + auto const ecdsa = made->sign(crypto::signing_schemes::ecdsa_sha256, message); + same_result(ecdsa, crypto::sign(*made, crypto::signing_schemes::ecdsa_sha256, message)); + same_result(ecdsa, crypto::sign(*made, crypto::signing_schemes::ecdsa_sha256, + crypto::signing_schemes::prehashed{digest})); + same_result(made->sign(crypto::signing_schemes::ecdsa_sha256, message, extra), + crypto::sign(*made, crypto::signing_schemes::ecdsa_sha256, message, extra)); + same_result(made->sign(crypto::signing_schemes::ecdsa_sha256_recoverable, message), + crypto::sign(*made, crypto::signing_schemes::ecdsa_sha256_recoverable, message)); + same_result(made->sign(crypto::signing_schemes::schnorr, message, extra), + crypto::sign(*made, crypto::signing_schemes::schnorr, message, extra)); } /** @@ -398,23 +401,28 @@ void secp256k1_verify_forms() { } auto const public_key = made->public_key(); std::array const extra = secret_bytes(7); - auto const ecdsa = made->sign(crypto::ecdsa_sha256, message); - auto const hedged = made->sign(crypto::ecdsa_sha256, message, extra); - auto const schnorr = made->sign(crypto::schnorr, message, extra); + auto const ecdsa = made->sign(crypto::signing_schemes::ecdsa_sha256, message); + auto const hedged = made->sign(crypto::signing_schemes::ecdsa_sha256, message, extra); + auto const schnorr = made->sign(crypto::signing_schemes::schnorr, message, extra); // BIP340's auxiliary randomness drawn by the call: another signature. - auto const drawn = crypto::sign(*made, crypto::schnorr, message); + auto const drawn = crypto::sign(*made, crypto::signing_schemes::schnorr, message); if (!BOOST_TEST(public_key.has_value()) || !BOOST_TEST(ecdsa.has_value()) || !BOOST_TEST(hedged.has_value()) || !BOOST_TEST(schnorr.has_value()) || !BOOST_TEST(drawn.has_value())) { return; } auto const digest = digest_of_message(); - verify_forms(crypto::ecdsa_sha256, *ecdsa, message, *public_key); - verify_forms(crypto::ecdsa_sha256, *hedged, crypto::prehashed{digest}, *public_key); - verify_forms(crypto::schnorr, *schnorr, message, *public_key); - verify_forms(crypto::schnorr, *drawn, message, *public_key); - BOOST_TEST(crypto::verify(crypto::schnorr, *schnorr, message, public_key->xonly()).has_value()); - BOOST_TEST(public_key->verify(crypto::schnorr, *schnorr, message) + verify_forms(crypto::signing_schemes::ecdsa_sha256, *ecdsa, message, *public_key); + verify_forms(crypto::signing_schemes::ecdsa_sha256, *hedged, + crypto::signing_schemes::prehashed{digest}, *public_key); + verify_forms(crypto::signing_schemes::schnorr, *schnorr, message, *public_key); + verify_forms(crypto::signing_schemes::schnorr, *drawn, message, *public_key); + BOOST_TEST( + crypto::verify(crypto::signing_schemes::schnorr, *schnorr, message, public_key->xonly()) + .has_value()); + BOOST_TEST(public_key + ->verify(crypto::signing_schemes::schnorr, *schnorr, + message) .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 @@ -424,23 +432,26 @@ void secp256k1_verify_forms() { if (!BOOST_TEST(received_signature.has_value())) { return; } - BOOST_TEST(crypto::verify(crypto::schnorr, *received_signature, message, public_key->xonly()) + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, *received_signature, message, + public_key->xonly()) .has_value()); auto const short_one = std::span(received).first(63); 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, *received_signature, message, no_point).error() == - crypto::error::invalid_public_key); + BOOST_TEST( + crypto::verify(crypto::signing_schemes::schnorr, *received_signature, message, no_point) + .error() == crypto::error::invalid_public_key); // 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); + BOOST_TEST(public_key->verify(crypto::signing_schemes::schnorr, *ecdsa_as_schnorr, message) + .error() == crypto::error::invalid_signature); + BOOST_TEST( + public_key->verify(crypto::signing_schemes::ecdsa_sha256, *schnorr_as_ecdsa, message) + .error() == crypto::error::invalid_signature); } } @@ -455,7 +466,7 @@ void secp256k1_recover_sizes() { return; } auto const public_key = made->public_key(); - auto const recoverable = made->sign(crypto::ecdsa_sha256_recoverable, message); + auto const recoverable = made->sign(crypto::signing_schemes::ecdsa_sha256_recoverable, message); if (!BOOST_TEST(public_key.has_value()) || !BOOST_TEST(recoverable.has_value())) { return; } @@ -465,8 +476,8 @@ void secp256k1_recover_sizes() { if (!BOOST_TEST(received_signature.has_value())) { return; } - auto const recovered = - secp256k1::recover(crypto::ecdsa_sha256_recoverable, *received_signature, message); + auto const recovered = secp256k1::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, + *received_signature, message); if (BOOST_TEST(recovered.has_value())) { BOOST_TEST(*recovered == *public_key); } @@ -540,10 +551,10 @@ int main() { from_secret_forms(); from_secret_forms(); from_secret_forms(); - generate_forms(crypto::eddsa); - generate_forms(crypto::ecdsa_sha256); - generate_forms(crypto::schnorr); - generate_forms(crypto::ecdsa_sha256); + generate_forms(crypto::signing_schemes::eddsa); + generate_forms(crypto::signing_schemes::ecdsa_sha256); + generate_forms(crypto::signing_schemes::schnorr); + generate_forms(crypto::signing_schemes::ecdsa_sha256); agree_forms(); agree_forms(); ed25519_forms(); diff --git a/test/timing_coverage_bearssl_test.cpp b/test/timing_coverage_bearssl_test.cpp index 42c8cf0f..de5d241d 100644 --- a/test/timing_coverage_bearssl_test.cpp +++ b/test/timing_coverage_bearssl_test.cpp @@ -165,12 +165,15 @@ void cover_p256_sign_moved_from(std::array const& digest) { auto source = keypair::from_secret(data::rfc6979_scalar); if (BOOST_TEST(source.has_value())) { keypair const taken = std::move(*source); - webcpp::test::covered( - "p256::basic_keypair::sign moved from on bearssl", [&source, &digest] { - // NOLINTNEXTLINE(bugprone-use-after-move,clang-analyzer-cplusplus.Move): tested - BOOST_TEST(source->sign(crypto::ecdsa_sha256, crypto::prehashed{digest}).error() == - crypto::error::invalid_state); - }); + webcpp::test::covered("p256::basic_keypair::sign moved from on bearssl", + [&source, &digest] { + // NOLINTNEXTLINE(bugprone-use-after-move,clang-analyzer-cplusplus.Move): + // tested + BOOST_TEST(source + ->sign(crypto::signing_schemes::ecdsa_sha256, + crypto::signing_schemes::prehashed{digest}) + .error() == crypto::error::invalid_state); + }); } } @@ -196,23 +199,24 @@ void cover_p256_verify() { !BOOST_TEST(zero_r.has_value())) { return; } - 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", + webcpp::test::covered("p256 crypto::verify of a message on bearssl", "crypto::verify", [&key, &test] { - BOOST_TEST(crypto::verify(crypto::ecdsa_sha256, *test, - crypto::prehashed{p256_test_digest}, *key) + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + *test, p256_test_message, *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, - crypto::prehashed{p256_test_digest}, *key) - .error() == crypto::error::invalid_signature); - }); + webcpp::test::covered( + "p256 crypto::verify of a digest on bearssl", "crypto::verify", [&key, &test] { + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *test, + crypto::signing_schemes::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::signing_schemes::ecdsa_sha256, *zero_r, + crypto::signing_schemes::prehashed{p256_test_digest}, *key) + .error() == crypto::error::invalid_signature); + }); } // P-256's basic_public_key::verify of ECDSA over SHA-256, of the message and of its digest, and @@ -230,14 +234,17 @@ void cover_p256_public_key_verify() { return; } 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()); + BOOST_TEST(key->verify(crypto::signing_schemes::ecdsa_sha256, *test, p256_test_message) + .has_value()); }); 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}) + BOOST_TEST(key->verify(crypto::signing_schemes::ecdsa_sha256, *test, + crypto::signing_schemes::prehashed{p256_test_digest}) .has_value()); }); 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::signing_schemes::ecdsa_sha256, *zero_r, + crypto::signing_schemes::prehashed{p256_test_digest}) .error() == crypto::error::invalid_signature); }); } @@ -276,7 +283,8 @@ void cover_p256_free_forms() { return; } webcpp::test::covered("p256 crypto::sign on bearssl", "crypto::sign", [&made] { - auto const signature = crypto::sign(*made, crypto::ecdsa_sha256, p256_test_message); + auto const signature = + crypto::sign(*made, crypto::signing_schemes::ecdsa_sha256, p256_test_message); BOOST_TEST(signature.has_value() && signature->bytes() == data::rfc6979_test); }); webcpp::test::covered("p256 crypto::agree on bearssl", "crypto::agree", @@ -284,8 +292,9 @@ void cover_p256_free_forms() { keypair const taken = std::move(*made); webcpp::test::covered("p256 crypto::sign moved from on bearssl", "crypto::sign", [&made] { // NOLINTNEXTLINE(bugprone-use-after-move,clang-analyzer-cplusplus.Move): tested - BOOST_TEST(crypto::sign(*made, crypto::ecdsa_sha256, p256_test_message).error() == - crypto::error::invalid_state); + BOOST_TEST( + crypto::sign(*made, crypto::signing_schemes::ecdsa_sha256, p256_test_message).error() == + crypto::error::invalid_state); }); webcpp::test::covered( "p256 crypto::agree moved from on bearssl", "crypto::agree", [&made, &peer] { @@ -334,13 +343,14 @@ void cover_p256_ecdsa() { } 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); + auto const signature = + made->sign(crypto::signing_schemes::ecdsa_sha256, p256_test_message); 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}); + auto const signature = made->sign(crypto::signing_schemes::ecdsa_sha256, + crypto::signing_schemes::prehashed{p256_test_digest}); BOOST_TEST(signature.has_value() && signature->bytes() == data::rfc6979_test); }); cover_p256_sign_moved_from(p256_test_digest); @@ -474,25 +484,28 @@ void cover_async_p256() { return; } webcpp::test::covered("p256::async_sign on bearssl", "crypto::async_sign", [&] { - crypto::async_sign(executor, *made, crypto::ecdsa_sha256, message, keeping); + crypto::async_sign(executor, *made, crypto::signing_schemes::ecdsa_sha256, message, + keeping); deliver(); }); webcpp::test::covered("p256::async_sign of a digest on bearssl", "crypto::async_sign", [&] { - crypto::async_sign(executor, *made, crypto::ecdsa_sha256, - crypto::prehashed{p256_test_digest}, counted); + crypto::async_sign(executor, *made, crypto::signing_schemes::ecdsa_sha256, + crypto::signing_schemes::prehashed{p256_test_digest}, counted); deliver(); }); webcpp::test::covered("p256::async_verify on bearssl", "crypto::async_verify", [&] { - crypto::async_verify(executor, crypto::ecdsa_sha256, kept, message, *key, counted); + crypto::async_verify(executor, crypto::signing_schemes::ecdsa_sha256, kept, message, *key, + counted); deliver(); }); webcpp::test::covered("p256::async_verify of a digest on bearssl", "crypto::async_verify", [&] { - crypto::async_verify(executor, crypto::ecdsa_sha256, *rfc_test, - crypto::prehashed{p256_test_digest}, *key, counted); + crypto::async_verify(executor, crypto::signing_schemes::ecdsa_sha256, *rfc_test, + crypto::signing_schemes::prehashed{p256_test_digest}, *key, counted); deliver(); }); 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); + crypto::async_verify(executor, crypto::signing_schemes::ecdsa_sha256, *zero_r, message, + *key, counted); deliver(); }); webcpp::test::covered("p256::async_agree on bearssl", "crypto::async_agree", [&] { @@ -500,25 +513,26 @@ void cover_async_p256() { deliver(); }); webcpp::test::covered("p256::basic_keypair::async_sign on bearssl", [&] { - made->async_sign(executor, crypto::ecdsa_sha256, message, counted); + made->async_sign(executor, crypto::signing_schemes::ecdsa_sha256, message, counted); deliver(); }); webcpp::test::covered("p256::basic_keypair::async_sign of a digest on bearssl", [&] { - made->async_sign(executor, crypto::ecdsa_sha256, crypto::prehashed{p256_test_digest}, - counted); + made->async_sign(executor, crypto::signing_schemes::ecdsa_sha256, + crypto::signing_schemes::prehashed{p256_test_digest}, counted); deliver(); }); webcpp::test::covered("p256::basic_public_key::async_verify on bearssl", [&] { - key->async_verify(executor, crypto::ecdsa_sha256, kept, message, counted); + key->async_verify(executor, crypto::signing_schemes::ecdsa_sha256, kept, message, counted); deliver(); }); webcpp::test::covered("p256::basic_public_key::async_verify of a digest on bearssl", [&] { - key->async_verify(executor, crypto::ecdsa_sha256, *rfc_test, - crypto::prehashed{p256_test_digest}, counted); + key->async_verify(executor, crypto::signing_schemes::ecdsa_sha256, *rfc_test, + crypto::signing_schemes::prehashed{p256_test_digest}, counted); deliver(); }); 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); + key->async_verify(executor, crypto::signing_schemes::ecdsa_sha256, *zero_r, message, + counted); deliver(); }); webcpp::test::covered("p256::basic_keypair::async_agree on bearssl", [&] { @@ -528,7 +542,8 @@ void cover_async_p256() { [[maybe_unused]] keypair const taken(std::move(*made)); webcpp::test::covered("p256::async_sign moved from on bearssl", "crypto::async_sign", [&] { // NOLINTNEXTLINE(bugprone-use-after-move,clang-analyzer-cplusplus.Move): tested - crypto::async_sign(executor, *made, crypto::ecdsa_sha256, message, counted); + crypto::async_sign(executor, *made, crypto::signing_schemes::ecdsa_sha256, message, + counted); deliver(); }); webcpp::test::covered("p256::async_agree moved from on bearssl", "crypto::async_agree", [&] { @@ -538,7 +553,7 @@ void cover_async_p256() { }); webcpp::test::covered("p256::basic_keypair::async_sign moved from on bearssl", [&] { // NOLINTNEXTLINE(bugprone-use-after-move,clang-analyzer-cplusplus.Move): tested - made->async_sign(executor, crypto::ecdsa_sha256, message, counted); + made->async_sign(executor, crypto::signing_schemes::ecdsa_sha256, message, counted); deliver(); }); webcpp::test::covered("p256::basic_keypair::async_agree moved from on bearssl", [&] { diff --git a/test/timing_coverage_secp256k1_test.cpp b/test/timing_coverage_secp256k1_test.cpp index e518c1b2..d0681012 100644 --- a/test/timing_coverage_secp256k1_test.cpp +++ b/test/timing_coverage_secp256k1_test.cpp @@ -172,29 +172,42 @@ void cover_keypair_signing() { [&] { BOOST_TEST(made.public_key().has_value()); }); covered("secp256k1::basic_keypair::secret on secp256k1", [&] { BOOST_TEST(made.secret().has_value()); }); - crypto::prehashed const digest{hash}; - covered("secp256k1::basic_keypair::sign with ecdsa_sha256 of a message on secp256k1", - [&] { BOOST_TEST(made.sign(crypto::ecdsa_sha256, hash).has_value()); }); - covered("secp256k1::basic_keypair::sign with ecdsa_sha256 of a digest on secp256k1", - [&] { 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()); }); + crypto::signing_schemes::prehashed const digest{hash}; + covered("secp256k1::basic_keypair::sign with ecdsa_sha256 of a message on secp256k1", [&] { + BOOST_TEST(made.sign(crypto::signing_schemes::ecdsa_sha256, hash).has_value()); + }); + covered("secp256k1::basic_keypair::sign with ecdsa_sha256 of a digest on secp256k1", [&] { + BOOST_TEST(made.sign(crypto::signing_schemes::ecdsa_sha256, digest).has_value()); + }); + covered("secp256k1::basic_keypair::sign with ecdsa_sha256_recoverable on secp256k1", [&] { + BOOST_TEST( + made.sign(crypto::signing_schemes::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()); }); + "secp256k1::basic_keypair::sign", [&] { + BOOST_TEST( + made.sign(crypto::signing_schemes::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()); }); + "secp256k1::basic_keypair::sign", [&] { + BOOST_TEST(made.sign(crypto::signing_schemes::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", - "secp256k1::basic_keypair::sign(ecdsa_sha256_t", - [&] { BOOST_TEST(made.sign(crypto::ecdsa_sha256, digest, randomness).has_value()); }); - covered("secp256k1::basic_keypair::sign with schnorr's randomness given on secp256k1", - "secp256k1::basic_keypair::sign(schnorr_t", - [&] { BOOST_TEST(made.sign(crypto::schnorr, hash, randomness).has_value()); }); + [&] { BOOST_TEST(made.sign(crypto::signing_schemes::schnorr, hash).has_value()); }); + covered( + "secp256k1::basic_keypair::sign hedged on secp256k1", + "secp256k1::basic_keypair::sign(ecdsa_sha256_t", [&] { + BOOST_TEST( + made.sign(crypto::signing_schemes::ecdsa_sha256, digest, randomness).has_value()); + }); + covered( + "secp256k1::basic_keypair::sign with schnorr's randomness given on secp256k1", + "secp256k1::basic_keypair::sign(schnorr_t", [&] { + BOOST_TEST(made.sign(crypto::signing_schemes::schnorr, hash, randomness).has_value()); + }); } /** @@ -209,37 +222,42 @@ void cover_keypair_signing_moved_from() { [&] { BOOST_TEST(empty.public_key().error() == crypto::error::invalid_state); }); covered("secp256k1::basic_keypair::secret moved from on secp256k1", [&] { BOOST_TEST(empty.secret().error() == crypto::error::invalid_state); }); - crypto::prehashed const digest{hash}; + crypto::signing_schemes::prehashed const digest{hash}; covered("secp256k1::basic_keypair::sign with ecdsa_sha256 moved from on secp256k1", [&] { - BOOST_TEST(empty.sign(crypto::ecdsa_sha256, hash).error() == crypto::error::invalid_state); + BOOST_TEST(empty.sign(crypto::signing_schemes::ecdsa_sha256, hash).error() == + crypto::error::invalid_state); }); covered( "secp256k1::basic_keypair::sign with ecdsa_sha256_recoverable moved from on " "secp256k1", "secp256k1::basic_keypair::sign", [&] { - BOOST_TEST(empty.sign(crypto::ecdsa_sha256_recoverable, digest).error() == - crypto::error::invalid_state); + BOOST_TEST( + empty.sign(crypto::signing_schemes::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); + BOOST_TEST( + empty.sign(crypto::signing_schemes::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); + BOOST_TEST(empty.sign(crypto::signing_schemes::schnorr, hash).error() == + crypto::error::invalid_state); }); covered("secp256k1::basic_keypair::sign hedged moved from on secp256k1", "secp256k1::basic_keypair::sign(ecdsa_sha256_t", [&] { - BOOST_TEST(empty.sign(crypto::ecdsa_sha256, digest, randomness).error() == - crypto::error::invalid_state); + BOOST_TEST( + empty.sign(crypto::signing_schemes::ecdsa_sha256, digest, randomness).error() == + crypto::error::invalid_state); }); covered( "secp256k1::basic_keypair::sign with schnorr's randomness given moved from on " "secp256k1", "secp256k1::basic_keypair::sign(schnorr_t", [&] { - BOOST_TEST(empty.sign(crypto::schnorr, hash, randomness).error() == + BOOST_TEST(empty.sign(crypto::signing_schemes::schnorr, hash, randomness).error() == crypto::error::invalid_state); }); } @@ -293,11 +311,11 @@ void cover_verification() { auto const signer = keypair_of(0x51); bytes32 const hash = secret_bytes(0x5c); auto const hashed = crypto::detail::sha256_of(hash); - crypto::prehashed const digest{hashed}; + crypto::signing_schemes::prehashed const digest{hashed}; auto const public_key = signer.public_key(); - auto const schnorr = signer.sign(crypto::schnorr, hash, secret_bytes(0x01)); - auto const ecdsa = signer.sign(crypto::ecdsa_sha256, hash); - auto recoverable = signer.sign(crypto::ecdsa_sha256_recoverable, hash); + auto const schnorr = signer.sign(crypto::signing_schemes::schnorr, hash, secret_bytes(0x01)); + auto const ecdsa = signer.sign(crypto::signing_schemes::ecdsa_sha256, hash); + auto recoverable = signer.sign(crypto::signing_schemes::ecdsa_sha256_recoverable, hash); if (!BOOST_TEST(public_key.has_value()) || !BOOST_TEST(schnorr.has_value()) || !BOOST_TEST(ecdsa.has_value()) || !BOOST_TEST(recoverable.has_value())) { return; @@ -305,35 +323,43 @@ void cover_verification() { auto const xonly_key = public_key->xonly(); bytes32 const not_a_key = secret_bytes(0xff); covered("secp256k1::recover of a message on secp256k1", [&] { - BOOST_TEST(secp::recover(crypto::ecdsa_sha256_recoverable, *recoverable, hash).has_value()); + BOOST_TEST( + secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, *recoverable, hash) + .has_value()); }); covered("secp256k1::recover of a digest on secp256k1", [&] { BOOST_TEST( - secp::recover(crypto::ecdsa_sha256_recoverable, *recoverable, digest).has_value()); + secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, *recoverable, digest) + .has_value()); }); covered("secp256k1 crypto::verify of schnorr on secp256k1", "crypto::verify(schnorr_t", [&] { - BOOST_TEST(crypto::verify(crypto::schnorr, *schnorr, hash, xonly_key).has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, *schnorr, hash, xonly_key) + .has_value()); }); covered( "secp256k1 crypto::verify of schnorr with the typed key on secp256k1", "crypto::verify(schnorr_t", [&] { - BOOST_TEST(crypto::verify(crypto::schnorr, *schnorr, hash, *public_key).has_value()); - }); - covered( - "secp256k1 crypto::verify of ecdsa_sha256 of a message on secp256k1", - "crypto::verify(ecdsa_sha256_t", [&] { - BOOST_TEST(crypto::verify(crypto::ecdsa_sha256, *ecdsa, hash, *public_key).has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, *schnorr, hash, *public_key) + .has_value()); }); - covered("secp256k1 crypto::verify of ecdsa_sha256 of a digest on secp256k1", + covered("secp256k1 crypto::verify of ecdsa_sha256 of a message on secp256k1", "crypto::verify(ecdsa_sha256_t", [&] { BOOST_TEST( - crypto::verify(crypto::ecdsa_sha256, *ecdsa, digest, *public_key).has_value()); + crypto::verify(crypto::signing_schemes::ecdsa_sha256, *ecdsa, hash, *public_key) + .has_value()); }); - covered("secp256k1 crypto::verify of schnorr with a key off the curve on secp256k1", - "crypto::verify(schnorr_t", [&] { - BOOST_TEST(crypto::verify(crypto::schnorr, *schnorr, hash, not_a_key).error() == - crypto::error::invalid_public_key); + covered("secp256k1 crypto::verify of ecdsa_sha256 of a digest on secp256k1", + "crypto::verify(ecdsa_sha256_t", [&] { + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *ecdsa, digest, + *public_key) + .has_value()); }); + covered( + "secp256k1 crypto::verify of schnorr with a key off the curve on secp256k1", + "crypto::verify(schnorr_t", [&] { + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, *schnorr, hash, not_a_key) + .error() == crypto::error::invalid_public_key); + }); auto id_of_four = recoverable->bytes(); id_of_four[64] = 4; auto const bad_id = secp::recoverable_signature::from_bytes(id_of_four); @@ -341,8 +367,8 @@ void cover_verification() { return; } covered("secp256k1::recover with a recovery id of 4 on secp256k1", [&] { - BOOST_TEST(secp::recover(crypto::ecdsa_sha256_recoverable, *bad_id, hash).error() == - crypto::error::invalid_signature); + BOOST_TEST(secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, *bad_id, hash) + .error() == crypto::error::invalid_signature); }); } @@ -350,8 +376,8 @@ void cover_verification() { 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); + crypto::signing_schemes::prehashed const digest{hash}; + auto const keccak = signer.sign(crypto::signing_schemes::ecdsa_keccak256_recoverable, hash); if (!BOOST_TEST(keccak.has_value())) { return; } @@ -363,21 +389,23 @@ void cover_ethereum_recovery() { } 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()); + BOOST_TEST(secp::recover(crypto::signing_schemes::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::signing_schemes::ecdsa_keccak256_recoverable, + *keccak, digest) + .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); + BOOST_TEST( + secp::recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, *bad_id, hash) + .error() == crypto::error::invalid_signature); }); } @@ -386,8 +414,8 @@ void cover_public_key_verify() { auto const signer = keypair_of(0x52); bytes32 const hash = secret_bytes(0x5d); auto const public_key = signer.public_key(); - auto const schnorr = signer.sign(crypto::schnorr, hash, secret_bytes(0x01)); - auto const ecdsa = signer.sign(crypto::ecdsa_sha256, hash); + auto const schnorr = signer.sign(crypto::signing_schemes::schnorr, hash, secret_bytes(0x01)); + auto const ecdsa = signer.sign(crypto::signing_schemes::ecdsa_sha256, hash); if (!BOOST_TEST(public_key.has_value()) || !BOOST_TEST(schnorr.has_value()) || !BOOST_TEST(ecdsa.has_value())) { return; @@ -399,17 +427,22 @@ void cover_public_key_verify() { return; } covered("secp256k1::public_key::verify of ecdsa_sha256 on secp256k1", [&] { - BOOST_TEST(public_key->verify(crypto::ecdsa_sha256, *ecdsa, hash).has_value()); + BOOST_TEST( + public_key->verify(crypto::signing_schemes::ecdsa_sha256, *ecdsa, hash).has_value()); + }); + covered("secp256k1::public_key::verify of schnorr on secp256k1", [&] { + BOOST_TEST( + public_key->verify(crypto::signing_schemes::schnorr, *schnorr, 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_as_ecdsa, hash).error() == - crypto::error::invalid_signature); + BOOST_TEST( + public_key->verify(crypto::signing_schemes::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_as_schnorr, hash).error() == - crypto::error::invalid_signature); + BOOST_TEST( + public_key->verify(crypto::signing_schemes::schnorr, *ecdsa_as_schnorr, hash).error() == + crypto::error::invalid_signature); }); } @@ -451,33 +484,41 @@ void cover_free_forms() { auto const peer = keypair_of(0x63).public_key(); bytes32 const hash = secret_bytes(0x5e); bytes32 const randomness = secret_bytes(0x5f); - covered("secp256k1 crypto::sign with ecdsa_sha256 on secp256k1", "crypto::sign", - [&] { BOOST_TEST(crypto::sign(made, crypto::ecdsa_sha256, hash).has_value()); }); + covered("secp256k1 crypto::sign with ecdsa_sha256 on secp256k1", "crypto::sign", [&] { + BOOST_TEST(crypto::sign(made, crypto::signing_schemes::ecdsa_sha256, hash).has_value()); + }); covered("secp256k1 crypto::sign hedged on secp256k1", "crypto::sign", [&] { - BOOST_TEST(crypto::sign(made, crypto::ecdsa_sha256, hash, randomness).has_value()); + BOOST_TEST(crypto::sign(made, crypto::signing_schemes::ecdsa_sha256, hash, randomness) + .has_value()); }); - covered("secp256k1 crypto::sign with schnorr's randomness given on secp256k1", "crypto::sign", - [&] { BOOST_TEST(crypto::sign(made, crypto::schnorr, hash, randomness).has_value()); }); - covered("secp256k1 crypto::sign with ecdsa_sha256_recoverable on secp256k1", "crypto::sign", - [&] { - 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()); + "secp256k1 crypto::sign with schnorr's randomness given on secp256k1", "crypto::sign", [&] { + BOOST_TEST( + crypto::sign(made, crypto::signing_schemes::schnorr, hash, randomness).has_value()); + }); + covered( + "secp256k1 crypto::sign with ecdsa_sha256_recoverable on secp256k1", "crypto::sign", [&] { + BOOST_TEST(crypto::sign(made, crypto::signing_schemes::ecdsa_sha256_recoverable, hash) + .has_value()); }); - covered("secp256k1 crypto::sign with ecdsa_keccak256_recoverable of a digest on secp256k1", + covered("secp256k1 crypto::sign with ecdsa_keccak256_recoverable of a message on secp256k1", "crypto::sign", [&] { BOOST_TEST( - crypto::sign(made, crypto::ecdsa_keccak256_recoverable, crypto::prehashed{hash}) + crypto::sign(made, crypto::signing_schemes::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::signing_schemes::ecdsa_keccak256_recoverable, + crypto::signing_schemes::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()); }); + "crypto::sign", [&] { + BOOST_TEST(crypto::sign(made, crypto::signing_schemes::schnorr, hash).has_value()); + }); covered("secp256k1 crypto::sign moved from on secp256k1", "crypto::sign", [&] { - BOOST_TEST(crypto::sign(empty, crypto::ecdsa_sha256, hash).error() == + BOOST_TEST(crypto::sign(empty, crypto::signing_schemes::ecdsa_sha256, hash).error() == crypto::error::invalid_state); }); covered("secp256k1 crypto::agree on secp256k1", "crypto::agree", @@ -490,7 +531,8 @@ void cover_free_forms() { /** ECDSA's DER form and the free x-only tweak, a refusal of each. */ void cover_signature_forms() { auto const signer = keypair_of(0x61); - auto const ecdsa = signer.sign(crypto::ecdsa_sha256, crypto::prehashed{secret_bytes(0x5d)}); + auto const ecdsa = signer.sign(crypto::signing_schemes::ecdsa_sha256, + crypto::signing_schemes::prehashed{secret_bytes(0x5d)}); auto const public_key = signer.public_key(); if (!BOOST_TEST(ecdsa.has_value()) || !BOOST_TEST(public_key.has_value())) { return; @@ -526,7 +568,8 @@ void cover_signature_forms() { /** ECDSA's low-S functions, a refusal of each. */ void cover_low_s() { auto const signer = keypair_of(0x62); - auto const ecdsa = signer.sign(crypto::ecdsa_sha256, crypto::prehashed{secret_bytes(0x5e)}); + auto const ecdsa = signer.sign(crypto::signing_schemes::ecdsa_sha256, + crypto::signing_schemes::prehashed{secret_bytes(0x5e)}); if (!BOOST_TEST(ecdsa.has_value())) { return; } diff --git a/test/timing_coverage_sodium_test.cpp b/test/timing_coverage_sodium_test.cpp index f5764a97..786012cb 100644 --- a/test/timing_coverage_sodium_test.cpp +++ b/test/timing_coverage_sodium_test.cpp @@ -502,7 +502,7 @@ void cover_ed25519_keypair() { covered("ed25519::basic_keypair::secret on sodium", [&] { BOOST_TEST(made->secret().has_value()); }); covered("ed25519::basic_keypair::sign on sodium", - [&] { BOOST_TEST(made->sign(crypto::eddsa, message).has_value()); }); + [&] { BOOST_TEST(made->sign(crypto::signing_schemes::eddsa, message).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)); @@ -516,7 +516,8 @@ void cover_ed25519_keypair() { }); covered("ed25519::basic_keypair::sign moved from on sodium", [&] { // NOLINTNEXTLINE(bugprone-use-after-move): the moved-from key pair's refusal - BOOST_TEST(made->sign(crypto::eddsa, message).error() == crypto::error::invalid_state); + BOOST_TEST(made->sign(crypto::signing_schemes::eddsa, message).error() == + crypto::error::invalid_state); }); covered("ed25519::basic_keypair::to_x25519 moved from on sodium", [&] { // NOLINTNEXTLINE(bugprone-use-after-move): the moved-from key pair's refusal @@ -555,14 +556,15 @@ void cover_ed25519_free_forms() { 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::sign on sodium", "crypto::sign", [&] { + BOOST_TEST(crypto::sign(*made, crypto::signing_schemes::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() == + BOOST_TEST(crypto::sign(*made, crypto::signing_schemes::eddsa, message).error() == crypto::error::invalid_state); }); covered("ed25519 crypto::to_x25519 of a key pair moved from on sodium", "crypto::to_x25519", @@ -585,29 +587,31 @@ void cover_ed25519_free() { return; } auto const public_key = made->public_key(); - auto const signature = made->sign(crypto::eddsa, message); + auto const signature = made->sign(crypto::signing_schemes::eddsa, message); if (!BOOST_TEST(public_key.has_value()) || !BOOST_TEST(signature.has_value())) { return; } covered("ed25519 crypto::verify on sodium", "crypto::verify", [&] { - BOOST_TEST(( - crypto::verify(crypto::eddsa, *signature, message, *public_key, ed25519::strict) - .has_value())); + BOOST_TEST((crypto::verify(crypto::signing_schemes::eddsa, *signature, message, + *public_key, ed25519::strict) + .has_value())); }); // 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) + BOOST_TEST((crypto::verify(crypto::signing_schemes::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()); + BOOST_TEST( + public_key->verify(crypto::signing_schemes::eddsa, *signature, message).has_value()); }); 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); + BOOST_TEST( + public_key->verify(crypto::signing_schemes::eddsa, zero_signature, message).error() == + crypto::error::invalid_signature); }); covered("ed25519::public_key::to_x25519 on sodium", [&] { BOOST_TEST(public_key->to_x25519().has_value()); }); @@ -642,43 +646,48 @@ void cover_ed25519_prehashed() { auto made = keypair::from_secret(webcpp::test::coverage_key<32>()); std::array digest{}; digest.fill(0x5a); - crypto::prehashed const marker{digest}; + crypto::signing_schemes::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); + auto const signature = made->sign(crypto::signing_schemes::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::basic_keypair::sign under eddsa_prehashed on sodium", [&] { + BOOST_TEST(made->sign(crypto::signing_schemes::eddsa_prehashed, marker).has_value()); + }); + covered("ed25519 crypto::sign under eddsa_prehashed on sodium", "crypto::sign", [&] { + BOOST_TEST( + crypto::sign(*made, crypto::signing_schemes::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) + BOOST_TEST(crypto::verify(crypto::signing_schemes::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", + covered("ed25519 crypto::verify under eddsa_prehashed with a zero signature on sodium", + "crypto::verify(eddsa_prehashed_t", [&] { + BOOST_TEST(crypto::verify(crypto::signing_schemes::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, zero_signature, marker).error() == - crypto::error::invalid_signature); + public_key->verify(crypto::signing_schemes::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::signing_schemes::eddsa_prehashed, zero_signature, marker) + .error() == crypto::error::invalid_signature); + }); webcpp::asio::io_context context; auto const executor = context.get_executor(); @@ -691,35 +700,37 @@ void cover_ed25519_prehashed() { 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); + made->async_sign(executor, crypto::signing_schemes::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); + crypto::async_sign(executor, *made, crypto::signing_schemes::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); + public_key->async_verify(executor, crypto::signing_schemes::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); + public_key->async_verify(executor, crypto::signing_schemes::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); + crypto::async_verify(executor, crypto::signing_schemes::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); + crypto::async_verify(executor, crypto::signing_schemes::eddsa_prehashed, + zero_signature, marker, *public_key, ed25519::strict, + counted); deliver(); }); BOOST_TEST_EQ(completions, 6); @@ -727,7 +738,7 @@ void cover_ed25519_prehashed() { [[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() == + BOOST_TEST(made->sign(crypto::signing_schemes::eddsa_prehashed, marker).error() == crypto::error::invalid_state); }); } diff --git a/test/timing_sodium_test.cpp b/test/timing_sodium_test.cpp index 2dc26d99..d66bb330 100644 --- a/test/timing_sodium_test.cpp +++ b/test/timing_sodium_test.cpp @@ -48,7 +48,8 @@ void sign_test_1() { if (!BOOST_TEST(made.has_value())) { return; } - auto const signature = made->sign(webcpp::crypto::eddsa, std::span()); + auto const signature = + made->sign(webcpp::crypto::signing_schemes::eddsa, std::span()); if (BOOST_TEST(signature.has_value())) { BOOST_TEST(std::ranges::equal(signature->bytes(), expected)); } From c34dc49feb2a77057f808eb217d5eb71f15c2a9d Mon Sep 17 00:00:00 2001 From: R Date: Mon, 30 Nov 2026 17:22:51 -0300 Subject: [PATCH 02/81] crypto: the signing_schemes move lint fix --- example/Jamfile | 6 +++--- test/Jamfile | 7 ++++--- test/secp256k1_ethereum_test.cpp | 3 ++- 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/example/Jamfile b/example/Jamfile index 8d0ba3ea..c4b72012 100644 --- a/example/Jamfile +++ b/example/Jamfile @@ -63,8 +63,8 @@ webcpp.example ecdh_x_coordinate.cpp : /third_party//secp256k1 ; 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::signing_schemes::ecdsa_keccak256_recoverable, r, s and v -# printed, and the signer's address recovered (web3.js's documented vector). +# Keccak-256, signed with signing_schemes::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 ; @@ -107,7 +107,7 @@ webcpp.example wallet_key.cpp : /third_party//secp256k1 /webcp webcpp.example ecdsa_der.cpp : /third_party//secp256k1 ; # A Bitcoin legacy or segwit v0 sighash: SHA-256d computed with webcpp::hash, -# signed as crypto::signing_schemes::prehashed under crypto::signing_schemes::ecdsa_sha256, verified, as DER. +# signed as signing_schemes::prehashed under signing_schemes::ecdsa_sha256, verified, as DER. webcpp.example bitcoin_sighash.cpp : /third_party//secp256k1 ; # BIP341 key-path tweak of an internal key and a signature under the output key. diff --git a/test/Jamfile b/test/Jamfile index 58cf0db0..49f8b682 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -203,7 +203,8 @@ crypto-run error : error_test.cpp ; # concepts, over stand-in key types; the catch-all verify; sha256_of. crypto-run signing : signing_test.cpp ; # The scheme tags and prehashed in crypto::signing_schemes: each of the six is a -# scheme, constructible by name and from no braces; prehashed signs what the message signs. +# scheme, constructible by name and from no braces; prehashed signs what the +# message signs. crypto-run signing_namespaces : signing_namespaces_test.cpp : /third_party//bearssl ; # The three key pair concepts, keypair, signing_keypair and agreement_keypair: @@ -404,7 +405,7 @@ crypto-run secp256k1_keys : secp256k1_keys_test.cpp : /third_party//sec # Recoverable ECDSA signatures, libsecp256k1's edge cases, and hedged ECDSA. crypto-run secp256k1_recovery : secp256k1_recovery_test.cpp : /third_party//secp256k1 ; # Ethereum's recoverable ECDSA over Keccak-256 -# (crypto::signing_schemes::ecdsa_keccak256_recoverable): go-ethereum's recovery vector, +# (signing_schemes::ecdsa_keccak256_recoverable): go-ethereum's recovery vector, # web3.js's personal_sign, a message hashed with Keccak-256 (XKCP's) and never # SHA3-256, low S, and a signature recovered under the other recoverable scheme # giving another key. @@ -622,7 +623,7 @@ crypto-run ed25519_sodium : ed25519_sodium_test.cpp crypto-run ed25519_wycheproof_sodium : ed25519_wycheproof_sodium_test.cpp : /third_party//sodium /third_party//wycheproof /webcpp//boost_json ; -# Ed25519ph on libsodium, the scheme crypto::signing_schemes::eddsa_prehashed and the streaming +# Ed25519ph on libsodium, the scheme signing_schemes::eddsa_prehashed and the streaming # signer: RFC 8032 section 7.3's case, the signer equal to the scheme, the two # Ed25519 schemes not interchangeable; P-256's and secp256k1's key pairs, which # do not sign under the scheme, are linked for can_sign's checks. diff --git a/test/secp256k1_ethereum_test.cpp b/test/secp256k1_ethereum_test.cpp index 38b5ab5d..e4fea58c 100644 --- a/test/secp256k1_ethereum_test.cpp +++ b/test/secp256k1_ethereum_test.cpp @@ -352,9 +352,10 @@ void moved_from() { auto source = key_of(web3_secret); auto const target = std::move(source); static_cast(target); - // NOLINTNEXTLINE(bugprone-use-after-move): the moved-from key pair is the point + // NOLINTBEGIN(bugprone-use-after-move): the moved-from key pair is the point auto const refused = source.sign(crypto::signing_schemes::ecdsa_keccak256_recoverable, bytes_of(web3_message)); + // NOLINTEND(bugprone-use-after-move) BOOST_TEST(refused.has_error() && refused.error() == crypto::error::invalid_state); } From cb92afc830e529056eff760461441006be3ccde4 Mon Sep 17 00:00:00 2001 From: R Date: Mon, 30 Nov 2026 17:36:00 -0300 Subject: [PATCH 03/81] crypto: the signing_schemes move lint fix, Jamfile comments --- example/Jamfile | 7 ++++--- test/Jamfile | 9 +++++---- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/example/Jamfile b/example/Jamfile index c4b72012..586be947 100644 --- a/example/Jamfile +++ b/example/Jamfile @@ -63,8 +63,8 @@ webcpp.example ecdh_x_coordinate.cpp : /third_party//secp256k1 ; 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 signing_schemes::ecdsa_keccak256_recoverable, r, s and v printed, -# and the signer's address recovered (web3.js's documented vector). +# Keccak-256, signed with signing_schemes::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 ; @@ -107,7 +107,8 @@ webcpp.example wallet_key.cpp : /third_party//secp256k1 /webcp webcpp.example ecdsa_der.cpp : /third_party//secp256k1 ; # A Bitcoin legacy or segwit v0 sighash: SHA-256d computed with webcpp::hash, -# signed as signing_schemes::prehashed under signing_schemes::ecdsa_sha256, verified, as DER. +# signed as signing_schemes::prehashed under signing_schemes::ecdsa_sha256, +# verified, as DER. webcpp.example bitcoin_sighash.cpp : /third_party//secp256k1 ; # BIP341 key-path tweak of an internal key and a signature under the output key. diff --git a/test/Jamfile b/test/Jamfile index 49f8b682..6324eb79 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -623,10 +623,11 @@ crypto-run ed25519_sodium : ed25519_sodium_test.cpp crypto-run ed25519_wycheproof_sodium : ed25519_wycheproof_sodium_test.cpp : /third_party//sodium /third_party//wycheproof /webcpp//boost_json ; -# Ed25519ph on libsodium, the scheme signing_schemes::eddsa_prehashed and the streaming -# signer: RFC 8032 section 7.3's case, the signer equal to the scheme, the two -# Ed25519 schemes not interchangeable; P-256's and secp256k1's key pairs, which -# do not sign under the scheme, are linked for can_sign's checks. +# Ed25519ph on libsodium, the scheme signing_schemes::eddsa_prehashed and the +# streaming signer: RFC 8032 section 7.3's case, the signer equal to the +# scheme, the two Ed25519 schemes not interchangeable; P-256's and secp256k1's +# key pairs, which do not sign under the scheme, are linked for can_sign's +# checks. crypto-run ed25519ph_sodium : ed25519ph_sodium_test.cpp : /third_party//sodium /third_party//bearssl /third_party//secp256k1 ; From 924da0e1a8a1633f8bc9867572978e70c9db75e6 Mon Sep 17 00:00:00 2001 From: R Date: Mon, 30 Nov 2026 19:01:35 -0300 Subject: [PATCH 04/81] crypto: the examples' tag lines stand alone, the static_assert texts are rejoined, the signing_schemes docs agree --- doc/llms.txt | 20 ++-- doc/tables/generate.py | 2 +- example/async_seal.cpp | 4 +- example/async_sign.cpp | 4 +- example/ed25519_sign.cpp | 4 +- example/ethereum_personal_sign.cpp | 10 +- example/four_forms.cpp | 4 +- include/webcpp/crypto/async.hpp | 29 +++--- include/webcpp/crypto/config.hpp | 7 +- include/webcpp/crypto/curves/ed25519.hpp | 14 +-- include/webcpp/crypto/curves/p256.hpp | 4 +- include/webcpp/crypto/curves/secp256k1.hpp | 21 ++-- include/webcpp/crypto/signing.hpp | 110 ++++++++++----------- test/signing_namespaces_test.cpp | 2 +- 14 files changed, 121 insertions(+), 114 deletions(-) diff --git a/doc/llms.txt b/doc/llms.txt index 831fd92c..3327ced1 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -20,7 +20,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - 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(signing_schemes::eddsa, ...)` 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::signing_schemes::eddsa, ...)` 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`. @@ -29,7 +29,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - 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(signing_schemes::ecdsa_sha256, ...)` 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::signing_schemes::prehashed{digest}` gives its digest. + - async_verify: Verifies a P-256 ECDSA signature over SHA-256, asynchronously: `crypto::verify(crypto::signing_schemes::ecdsa_sha256, ...)` 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::signing_schemes::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. - [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. @@ -117,7 +117,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - 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::signing_schemes::schnorr, signature, message, key)`, or an ECDSA one against a `curves::secp256k1::public_key`, `crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, input, public_key)`, refusing a high S; `recover(crypto::signing_schemes::ecdsa_sha256_recoverable, signature, input)` and `recover(crypto::signing_schemes::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`) of ECDSA over SHA-256: the same inputs as `sign(signing_schemes::ecdsa_sha256_recoverable, ...)`. + - recover: The public key that made a recoverable signature (`secp256k1_ecdsa_recover`) of ECDSA over SHA-256: the same inputs as `sign(crypto::signing_schemes::ecdsa_sha256_recoverable, ...)`. - [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. @@ -138,7 +138,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [curves::ed25519::public_key](https://webcpporg.github.io/libs/crypto/#crypto-ed25519): An Ed25519 public key, its 32 bytes, which `crypto::verify(crypto::signing_schemes::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(signing_schemes::eddsa, ...)`, of which it is the member form, with the same work, results and refusals. + - verify: Verifies an Ed25519 signature (RFC 8032's pure Ed25519) with this key, under a verification policy (design D31): `crypto::verify(crypto::signing_schemes::eddsa, ...)`, 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::signing_schemes::eddsa, signature, message, public_key)`, or an Ed25519ph one, `crypto::verify(crypto::signing_schemes::eddsa_prehashed, signature, crypto::signing_schemes::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. @@ -173,7 +173,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - 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::secp256k1::recover](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-recovery): The public key that made a recoverable ECDSA signature, `recover(crypto::signing_schemes::ecdsa_sha256_recoverable, signature, input)` or Ethereum's `recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, signature, input)`, the input as signing took it: a message hashed inside (with SHA-256, or Keccak-256) or `crypto::signing_schemes::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(signing_schemes::ecdsa_sha256_recoverable, ...)`. + - recover: The public key that made a recoverable signature (`secp256k1_ecdsa_recover`) of ECDSA over SHA-256: the same inputs as `sign(crypto::signing_schemes::ecdsa_sha256_recoverable, ...)`. - [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. - 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. @@ -396,8 +396,8 @@ 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 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::signing_schemes::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. tag::program[] +- 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. +- 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::signing_schemes::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::signing_schemes::ecdsa_sha256. A taproot sighash, BIP341's tagged hash, is the message of crypto::signing_schemes::schnorr instead (musig_taproot.cpp, taproot_tweak.cpp). - example/box_messages.cpp: Two people who know each other's X25519 public keys exchange messages in libsodium's box: each makes a box from the own key pair and the other's public key, agreeing one key for the pair, then seals each message with a nonce drawn at random. What one seals the other opens; a stranger's box, from another key pair, does not. Prints what each reads. @@ -405,12 +405,12 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - 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::signing_schemes::eddsa, message)` and `crypto::verify(crypto::signing_schemes::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::signing_schemes::eddsa_prehashed`, which gives the same signature, and verifies it with `crypto::verify(crypto::signing_schemes::eddsa_prehashed, signature, crypto::signing_schemes::prehashed{digest}, public_key)`. Prints each key and signature in hex, and whether the two Ed25519ph signatures are equal. tag::program[] +- 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::signing_schemes::eddsa, message)` and `crypto::verify(crypto::signing_schemes::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::signing_schemes::eddsa_prehashed`, which gives the same signature, and verifies it with `crypto::verify(crypto::signing_schemes::eddsa_prehashed, signature, crypto::signing_schemes::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/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::signing_schemes::prehashed with crypto::signing_schemes::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[] +- 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::signing_schemes::prehashed with crypto::signing_schemes::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::signing_schemes::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. tag::program[] +- example/four_forms.cpp: Makes RFC 6979's P-256 key pair (a published scalar, never a real key), signs "sample" with crypto::signing_schemes::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. diff --git a/doc/tables/generate.py b/doc/tables/generate.py index d4df791f..ab8a095f 100644 --- a/doc/tables/generate.py +++ b/doc/tables/generate.py @@ -1833,7 +1833,7 @@ def first_comment(source: Path) -> str: if not line.startswith('//') or line.startswith('// tag::'): break words.append(line[2:].strip()) - return ' '.join(words) + return ' '.join(words).strip() def llms_default(data: Data, operation: Data) -> str: diff --git a/example/async_seal.cpp b/example/async_seal.cpp index c2320627..65942f2c 100644 --- a/example/async_seal.cpp +++ b/example/async_seal.cpp @@ -8,7 +8,9 @@ // (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[] +// plaintext. The loop ends when no operation is pending: nothing waits for a time. +// +// tag::program[] #include #include diff --git a/example/async_sign.cpp b/example/async_sign.cpp index c75c7ff7..da4ff831 100644 --- a/example/async_sign.cpp +++ b/example/async_sign.cpp @@ -8,7 +8,9 @@ // published seed, never a real key), signs the test's message with crypto::signing_schemes::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. tag::program[] +// has run: nothing waits for a time. +// +// tag::program[] #include #include diff --git a/example/ed25519_sign.cpp b/example/ed25519_sign.cpp index 8540c061..ce3fc67a 100644 --- a/example/ed25519_sign.cpp +++ b/example/ed25519_sign.cpp @@ -13,7 +13,9 @@ // under the scheme `crypto::signing_schemes::eddsa_prehashed`, which gives the same signature, and // verifies it with `crypto::verify(crypto::signing_schemes::eddsa_prehashed, signature, // crypto::signing_schemes::prehashed{digest}, public_key)`. Prints each key and signature in hex, -// and whether the two Ed25519ph signatures are equal. tag::program[] +// and whether the two Ed25519ph signatures are equal. +// +// tag::program[] #include #include diff --git a/example/ethereum_personal_sign.cpp b/example/ethereum_personal_sign.cpp index bf24fde8..65284801 100644 --- a/example/ethereum_personal_sign.cpp +++ b/example/ethereum_personal_sign.cpp @@ -9,10 +9,12 @@ // Keccak-256, signs it as crypto::signing_schemes::prehashed with // crypto::signing_schemes::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[] +// 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 diff --git a/example/four_forms.cpp b/example/four_forms.cpp index 85f4990a..ef8fe1d1 100644 --- a/example/four_forms.cpp +++ b/example/four_forms.cpp @@ -8,7 +8,9 @@ // crypto::signing_schemes::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. tag::program[] +// verifications agree. +// +// tag::program[] #include #include #include diff --git a/include/webcpp/crypto/async.hpp b/include/webcpp/crypto/async.hpp index 440017ec..0a97fc90 100644 --- a/include/webcpp/crypto/async.hpp +++ b/include/webcpp/crypto/async.hpp @@ -350,11 +350,12 @@ inline constexpr bool has_async_verifier_v = template 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::signing_schemes::eddsa or " - "crypto::signing_schemes::eddsa_prehashed, a " - "P-256 key pair with crypto::signing_schemes::ecdsa_sha256."); + static_assert( + refused_v, + "webcpp::crypto: async_sign: this key pair does not sign with this scheme: an " + "Ed25519 key pair signs with crypto::signing_schemes::eddsa or " + "crypto::signing_schemes::eddsa_prehashed, a P-256 key pair with " + "crypto::signing_schemes::ecdsa_sha256."); } else { check_input::type>(); } @@ -1010,8 +1011,8 @@ void async_sign([[maybe_unused]] Executor const& completion_executor, /** * Verifies an Ed25519 signature (RFC 8032's pure Ed25519), asynchronously, strictly: - * `crypto::verify(signing_schemes::eddsa, ...)` run when the operation is initiated, its - * result posted to `completion_executor`. + * `crypto::verify(crypto::signing_schemes::eddsa, ...)` 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::signing_schemes::eddsa` among them, and @@ -1178,10 +1179,9 @@ auto async_verify(Executor const& completion_executor, /** * Verifies a P-256 ECDSA signature over SHA-256, asynchronously: - * `crypto::verify(signing_schemes::ecdsa_sha256, ...)` 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::signing_schemes::prehashed{digest}` gives its digest. + * `crypto::verify(crypto::signing_schemes::ecdsa_sha256, ...)` 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::signing_schemes::prehashed{digest}` gives its digest. * * The free form of the member `public_key.async_verify`, which it calls with the arguments * other than `public_key`, the scheme `crypto::signing_schemes::ecdsa_sha256` among them, and which @@ -1257,10 +1257,9 @@ void async_verify([[maybe_unused]] Executor const& completion_executor, static_assert( detail::refused_v, "webcpp::crypto: async_verify takes crypto::signing_schemes::eddsa or " - "crypto::signing_schemes::eddsa_prehashed " - "with a curves::ed25519::public_key or crypto::signing_schemes::ecdsa_sha256 with a " - "curves::p256::basic_public_key, the algorithms WebCrypto has: call " - "crypto::verify for the others."); + "crypto::signing_schemes::eddsa_prehashed with a curves::ed25519::public_key or " + "crypto::signing_schemes::ecdsa_sha256 with a curves::p256::basic_public_key, the " + "algorithms WebCrypto has: call crypto::verify for the others."); } /** diff --git a/include/webcpp/crypto/config.hpp b/include/webcpp/crypto/config.hpp index 0004ffe5..7152a23a 100644 --- a/include/webcpp/crypto/config.hpp +++ b/include/webcpp/crypto/config.hpp @@ -193,9 +193,10 @@ namespace webcpp::crypto { /** - The formats of keys and signatures: the tags that name one, `formats::raw`, `formats::spki` and - the others, and the lists that say which a type has. Each curve's header and - `` fill it; a format is named in it and nowhere else. + The formats of keys and signatures: the namespace in which each format is named, by a tag such + as `formats::raw` or `formats::spki`. This header only declares it; the headers that define a + format, `` and each curve's, put its tag here, and a format is named in + this namespace and nowhere else. */ namespace formats {} diff --git a/include/webcpp/crypto/curves/ed25519.hpp b/include/webcpp/crypto/curves/ed25519.hpp index 62593405..fa80f7e2 100644 --- a/include/webcpp/crypto/curves/ed25519.hpp +++ b/include/webcpp/crypto/curves/ed25519.hpp @@ -112,9 +112,9 @@ struct strict_t { inline constexpr strict_t strict{}; /** - * An Ed25519 signature (RFC 8032), 64 bytes, R then S: what `sign(signing_schemes::eddsa, ...)`, - * `sign(signing_schemes::eddsa_prehashed, ...)` and `prehashed_signer::sign` give, and - * `crypto::verify` of either scheme takes. + * An Ed25519 signature (RFC 8032), 64 bytes, R then S: what `sign` gives under + * `crypto::signing_schemes::eddsa` or `crypto::signing_schemes::eddsa_prehashed`, as does + * `prehashed_signer::sign`, 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. @@ -229,8 +229,8 @@ class public_key { /** * Verifies an Ed25519 signature (RFC 8032's pure Ed25519) with this key, under a verification * policy (design D31): - * `crypto::verify(signing_schemes::eddsa, ...)`, of which it is the member form, with the same - * work, results and refusals. + * `crypto::verify(crypto::signing_schemes::eddsa, ...)`, of which it is the member form, with + * the same work, results and refusals. * * Ed25519ph's is the overload of `crypto::signing_schemes::eddsa_prehashed`. * @@ -279,8 +279,8 @@ class public_key { /** * Verifies an Ed25519ph signature (RFC 8032's Ed25519 over a message's SHA-512) with this key, * under a verification policy, strictly as `crypto::signing_schemes::eddsa`'s: - * `crypto::verify(signing_schemes::eddsa_prehashed, ...)`, of which it is the member form, with - * the same work, results and refusals. + * `crypto::verify(crypto::signing_schemes::eddsa_prehashed, ...)`, 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). diff --git a/include/webcpp/crypto/curves/p256.hpp b/include/webcpp/crypto/curves/p256.hpp index 181cad9f..b22e3072 100644 --- a/include/webcpp/crypto/curves/p256.hpp +++ b/include/webcpp/crypto/curves/p256.hpp @@ -117,8 +117,8 @@ template namespace webcpp::crypto::curves::p256 { /** - * A P-256 ECDSA signature, 64 bytes, r then s: what `sign(signing_schemes::ecdsa_sha256, ...)` - * gives and `crypto::verify(signing_schemes::ecdsa_sha256, ...)` takes. + * A P-256 ECDSA signature, 64 bytes, r then s: what `sign` gives under + * `crypto::signing_schemes::ecdsa_sha256` and `crypto::verify` of that scheme 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 diff --git a/include/webcpp/crypto/curves/secp256k1.hpp b/include/webcpp/crypto/curves/secp256k1.hpp index 46924869..255aa221 100644 --- a/include/webcpp/crypto/curves/secp256k1.hpp +++ b/include/webcpp/crypto/curves/secp256k1.hpp @@ -445,9 +445,9 @@ template #else static_assert(refused_v, "webcpp::crypto: crypto::signing_schemes::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::signing_schemes::prehashed{digest}."); + "a message with webcpp::hash's keccak_256, which needs XKCP: add " + "/third_party//xkcp to the program's Jamfile, or sign " + "crypto::signing_schemes::prehashed{digest}."); #endif } return digest_bytes; @@ -625,8 +625,8 @@ namespace webcpp::crypto::curves::secp256k1 { /** * A secp256k1 ECDSA signature, 64 bytes, r then s: what - * `sign(signing_schemes::ecdsa_sha256, ...)` gives and - * `crypto::verify(signing_schemes::ecdsa_sha256, ...)` takes. + * `sign(crypto::signing_schemes::ecdsa_sha256, ...)` gives and + * `crypto::verify(crypto::signing_schemes::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 @@ -647,8 +647,8 @@ using recoverable_signature = detail::basic_signature; /** - * A BIP340 Schnorr signature, 64 bytes, R's x then s: what `sign(signing_schemes::schnorr, ...)` - * gives and `crypto::verify(signing_schemes::schnorr, ...)` takes. + * A BIP340 Schnorr signature, 64 bytes, R's x then s: what `sign` gives under + * `crypto::signing_schemes::schnorr` and `crypto::verify` of that scheme takes. * * `from_bytes` checks the size alone. */ @@ -809,9 +809,8 @@ class public_key { static_assert( is_ecdsa || is_schnorr, "webcpp::crypto: a secp256k1 public key verifies crypto::signing_schemes::ecdsa_sha256 " - "or " - "crypto::signing_schemes::schnorr; a crypto::signing_schemes::ecdsa_sha256_recoverable " - "or a " + "or crypto::signing_schemes::schnorr; a " + "crypto::signing_schemes::ecdsa_sha256_recoverable or a " "crypto::signing_schemes::ecdsa_keccak256_recoverable signature gives its key to " "curves::secp256k1::recover."); if constexpr (is_ecdsa) { @@ -1539,7 +1538,7 @@ namespace webcpp::crypto::curves::secp256k1 { /** * The public key that made a recoverable signature (`secp256k1_ecdsa_recover`) of ECDSA over - * SHA-256: the same inputs as `sign(signing_schemes::ecdsa_sha256_recoverable, ...)`. + * SHA-256: the same inputs as `sign(crypto::signing_schemes::ecdsa_sha256_recoverable, ...)`. * * 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. diff --git a/include/webcpp/crypto/signing.hpp b/include/webcpp/crypto/signing.hpp index 79b45c35..57066db7 100644 --- a/include/webcpp/crypto/signing.hpp +++ b/include/webcpp/crypto/signing.hpp @@ -6,8 +6,9 @@ /** What every curve's signing shares (design D1 to D3): the scheme tags, `eddsa`, `eddsa_prehashed`, - `ecdsa_sha256`, `ecdsa_sha256_recoverable`, `ecdsa_keccak256_recoverable` and `schnorr`, and the - library's one list of them, `detail::all_schemes`; the marker of a digest, `prehashed{digest}`; the + `ecdsa_sha256`, `ecdsa_sha256_recoverable`, `ecdsa_keccak256_recoverable` and `schnorr`, all in + the namespace `crypto::signing_schemes`, and the library's one list of them, + `detail::all_schemes`; the marker of a digest, `signing_schemes::prehashed{digest}`; the concepts `can_sign` and `can_verify`, which say which key, scheme, signature and input go together; `detail::check_signature` and `detail::checked_signature_bytes`, which stop a `verify` or a `recover` given a signature of another curve or scheme, naming the type expected (design R1); @@ -16,9 +17,9 @@ `keypair.hpp`, constrained by `crypto::signing_keypair`. A signature's input is a message, any bytes that convert to `std::span`, of - any size, empty included, or a digest marked as one, `prehashed{digest}`: no call tells the two - apart by a span's size. Each curve's header includes this one and declares, for its own key - types, the schemes they have, through the traits of `detail`. + any size, empty included, or a digest marked as one, `signing_schemes::prehashed{digest}`: no call + tells the two apart by a span's size. Each curve's header includes this one and declares, for its + own key types, the schemes they have, through the traits of `detail`. @see "Signatures: the scheme and the input", in the guide. */ @@ -494,54 +495,52 @@ constexpr void check_input() noexcept { static_assert( refused_v, "webcpp::crypto: crypto::signing_schemes::eddsa_prehashed (RFC 8032's Ed25519ph) signs " - "a " - "digest, the message's SHA-512: crypto::signing_schemes::prehashed{digest} of a " + "a digest, the message's SHA-512: crypto::signing_schemes::prehashed{digest} of a " "std::array; sign the message itself with " - "crypto::signing_schemes::eddsa, " - "or give it in pieces to curves::ed25519::prehashed_signer."); + "crypto::signing_schemes::eddsa, or give it in pieces to " + "curves::ed25519::prehashed_signer."); } else if constexpr (!is_prehashed_v) { static_assert( is_message_v, - "webcpp::crypto: a signature's input is a message (bytes, as " - "std::span) or crypto::signing_schemes::prehashed{digest}."); + "webcpp::crypto: a signature's input is a message (bytes, as std::span) or crypto::signing_schemes::prehashed{digest}."); } else if constexpr (std::is_same_v) { - static_assert(refused_v, - "webcpp::crypto: crypto::signing_schemes::eddsa signs the message itself " - "(RFC 8032's pure " - "Ed25519) and takes no digest; a message's SHA-512 is signed with " - "crypto::signing_schemes::eddsa_prehashed (Ed25519ph)."); + static_assert( + refused_v, + "webcpp::crypto: crypto::signing_schemes::eddsa signs the message itself (RFC " + "8032's pure Ed25519) and takes no digest; a message's SHA-512 is signed with " + "crypto::signing_schemes::eddsa_prehashed (Ed25519ph)."); } else if constexpr (decltype(Input::digest)::extent != scheme_traits::digest_size && std::is_same_v) { static_assert( refused_v, "webcpp::crypto: crypto::signing_schemes::eddsa_prehashed takes a 64-byte digest, " - "SHA-512's: " - "crypto::signing_schemes::prehashed{digest} of a std::array."); + "SHA-512's: crypto::signing_schemes::prehashed{digest} of a std::array."); } else if constexpr (std::is_same_v) { - static_assert(refused_v, - "webcpp::crypto: crypto::signing_schemes::schnorr (BIP340) signs a message " - "of any length and " - "has no prehash mode: pass the message."); + static_assert( + refused_v, + "webcpp::crypto: crypto::signing_schemes::schnorr (BIP340) signs a message of " + "any length and has no prehash mode: pass the message."); } else if constexpr (decltype(Input::digest)::extent != scheme_traits::digest_size && std::is_same_v) { static_assert(refused_v, "webcpp::crypto: crypto::signing_schemes::ecdsa_sha256_recoverable takes a " - "32-byte digest, " - "SHA-256's: crypto::signing_schemes::prehashed{digest} of a " + "32-byte digest, SHA-256's: crypto::signing_schemes::prehashed{digest} of a " "std::array."); } else if constexpr (decltype(Input::digest)::extent != scheme_traits::digest_size && std::is_same_v) { - static_assert(refused_v, - "webcpp::crypto: crypto::signing_schemes::ecdsa_keccak256_recoverable takes " - "a 32-byte digest, " - "Keccak-256's: crypto::signing_schemes::prehashed{digest} of a " - "std::array."); + static_assert( + refused_v, + "webcpp::crypto: crypto::signing_schemes::ecdsa_keccak256_recoverable takes a " + "32-byte digest, Keccak-256's: crypto::signing_schemes::prehashed{digest} of " + "a std::array."); } else if constexpr (decltype(Input::digest)::extent != scheme_traits::digest_size) { static_assert( refused_v, "webcpp::crypto: crypto::signing_schemes::ecdsa_sha256 takes a 32-byte digest, " - "SHA-256's: " - "crypto::signing_schemes::prehashed{digest} of a std::array."); + "SHA-256's: crypto::signing_schemes::prehashed{digest} of a std::array."); } else if constexpr (!signs_prehashed_v) { static_assert(refused_v, "webcpp::crypto: this backend cannot sign or verify a digest (WebCrypto has " @@ -563,8 +562,8 @@ template constexpr void refuse_ed25519ph_on_asynchronous_backend() noexcept { static_assert(refused_v, "webcpp::crypto: WebCrypto has no Ed25519ph: " - "crypto::signing_schemes::eddsa_prehashed's sign, " - "verify, async_sign and async_verify run on a native backend."); + "crypto::signing_schemes::eddsa_prehashed's sign, verify, async_sign and " + "async_verify run on a native backend."); } /** @@ -643,18 +642,18 @@ template "webcpp::crypto: verify: Ed25519ph verifies a curves::ed25519::signature: " "make one from 64 bytes with curves::ed25519::signature::from_bytes."); } else if constexpr (ed25519_expected && std::is_same_v) { - static_assert(signature_matches, - "webcpp::crypto: verify: an Ed25519 key verifies a " - "curves::ed25519::signature under crypto::signing_schemes::eddsa: make one " - "from 64 bytes " - "with curves::ed25519::signature::from_bytes."); + static_assert( + signature_matches, + "webcpp::crypto: verify: an Ed25519 key verifies a curves::ed25519::signature " + "under crypto::signing_schemes::eddsa: make one from 64 bytes with " + "curves::ed25519::signature::from_bytes."); } else if constexpr (ed25519_expected && std::is_same_v) { - static_assert(signature_matches, - "webcpp::crypto: verify: an Ed25519 key verifies a " - "curves::ed25519::signature under crypto::signing_schemes::eddsa_prehashed: " - "make one from 64 " - "bytes with curves::ed25519::signature::from_bytes."); + static_assert( + signature_matches, + "webcpp::crypto: verify: an Ed25519 key verifies a curves::ed25519::signature " + "under crypto::signing_schemes::eddsa_prehashed: make one from 64 bytes with " + "curves::ed25519::signature::from_bytes."); } else if constexpr (is_signature_of_tag_v && std::is_same_v) { static_assert(signature_matches, @@ -680,8 +679,8 @@ template static_assert(signature_matches, "webcpp::crypto: verify: a secp256k1 key verifies a " "curves::secp256k1::ecdsa_signature under " - "crypto::signing_schemes::ecdsa_sha256: make one " - "from 64 bytes with curves::secp256k1::ecdsa_signature::from_bytes."); + "crypto::signing_schemes::ecdsa_sha256: make one from 64 bytes with " + "curves::secp256k1::ecdsa_signature::from_bytes."); } else { static_assert(refused_v, "webcpp::crypto: check_signature: no verifier takes this signature type " @@ -790,17 +789,16 @@ template [[maybe_unused]] Scheme signing_scheme, [[maybe_unused]] Signature const& signature_value, [[maybe_unused]] Input const& signing_input, [[maybe_unused]] PublicKey const& public_key) noexcept { - static_assert(detail::refused_v, - "webcpp::crypto: verify: this public key does not go with this scheme: " - "crypto::signing_schemes::eddsa and crypto::signing_schemes::eddsa_prehashed " - "take a curves::ed25519::public_key, " - "crypto::signing_schemes::ecdsa_sha256 a " - "curves::p256::basic_public_key or a curves::secp256k1::public_key, " - "crypto::signing_schemes::schnorr a curves::secp256k1::public_key or a 32-byte " - "x-only key; a " - "crypto::signing_schemes::ecdsa_sha256_recoverable or a " - "crypto::signing_schemes::ecdsa_keccak256_recoverable " - "signature gives its key to curves::secp256k1::recover."); + static_assert( + detail::refused_v, + "webcpp::crypto: verify: this public key does not go with this scheme: " + "crypto::signing_schemes::eddsa and crypto::signing_schemes::eddsa_prehashed take " + "a curves::ed25519::public_key, crypto::signing_schemes::ecdsa_sha256 a " + "curves::p256::basic_public_key or a curves::secp256k1::public_key, " + "crypto::signing_schemes::schnorr a curves::secp256k1::public_key or a 32-byte " + "x-only key; a crypto::signing_schemes::ecdsa_sha256_recoverable or a " + "crypto::signing_schemes::ecdsa_keccak256_recoverable signature gives its key to " + "curves::secp256k1::recover."); return {}; } diff --git a/test/signing_namespaces_test.cpp b/test/signing_namespaces_test.cpp index 919d541c..7e820703 100644 --- a/test/signing_namespaces_test.cpp +++ b/test/signing_namespaces_test.cpp @@ -87,7 +87,7 @@ void prehashed_equals_message() { BOOST_TEST(of_message->bytes() == of_digest->bytes()); } auto const free_form = crypto::sign(*key, signing_schemes::ecdsa_sha256, message); - if (BOOST_TEST(free_form.has_value()) && BOOST_TEST(of_message.has_value())) { + if (BOOST_TEST(free_form.has_value()) && of_message) { BOOST_TEST(free_form->bytes() == of_message->bytes()); } } From 0db68e1b92ce2e7bc01e6103c5ea8187372a75d3 Mon Sep 17 00:00:00 2001 From: R Date: Mon, 30 Nov 2026 20:00:54 -0300 Subject: [PATCH 05/81] crypto: verify, async_verify and recover take a mandatory verification policy (low_s_only, any_s, canonical) each scheme declares; Ed25519's strict goes --- bench/operations.hpp | 37 +- doc/async.adoc | 17 +- doc/curves.adoc | 86 ++- doc/ed25519.adoc | 47 +- doc/generated/defaults.adoc | 2 +- doc/generated/ed25519-cases.adoc | 2 +- doc/generated/messages.adoc | 86 ++- doc/generated/namespace-curves.adoc | 2 +- doc/generated/namespace-root.adoc | 8 +- doc/llms.txt | 34 +- doc/overview.adoc | 5 +- doc/p256.adoc | 53 +- doc/p2p.adoc | 10 +- doc/secp256k1.adoc | 34 +- doc/tables/crypto.json | 31 +- doc/tables/generate.py | 9 +- doc/tables/generate_test.py | 10 +- doc/wallets.adoc | 5 +- example/arena_signer.cpp | 3 +- example/async_sign.cpp | 1 + example/bitcoin_sighash.cpp | 3 +- example/ecdsa_der.cpp | 9 +- example/ed25519_sign.cpp | 24 +- example/ethereum_personal_sign.cpp | 3 +- example/four_forms.cpp | 14 +- example/key_formats.cpp | 3 +- example/key_tweak.cpp | 3 +- example/musig_network.cpp | 5 +- example/musig_taproot.cpp | 6 +- example/musig_wallet.cpp | 5 +- example/p256_handshake.cpp | 24 +- example/p256_handshake.expected | 2 +- example/p256_sign.cpp | 13 +- example/recover_signer.cpp | 6 +- example/schnorr_sign.cpp | 4 +- example/signed_message.cpp | 9 +- example/signed_update.cpp | 6 +- example/taproot_tweak.cpp | 3 +- include/webcpp/crypto/async.hpp | 314 +++++----- include/webcpp/crypto/backends/sodium.hpp | 2 +- include/webcpp/crypto/config.hpp | 5 +- include/webcpp/crypto/curves/ed25519.hpp | 301 +++++----- include/webcpp/crypto/curves/p256.hpp | 214 +++++-- include/webcpp/crypto/curves/secp256k1.hpp | 267 +++++++-- .../webcpp/crypto/curves/secp256k1/musig.hpp | 4 +- include/webcpp/crypto/detail/signature.hpp | 2 +- include/webcpp/crypto/signing.hpp | 341 ++++++++++- meta/ed25519_cases.json | 2 +- test/Jamfile | 14 + test/allocation_bearssl_test.cpp | 6 +- test/allocation_sodium_test.cpp | 28 +- test/async_25519_test.cpp | 93 +-- test/async_p256_test.cpp | 79 ++- test/async_post_test.cpp | 5 +- test/crypto_secp256k1_test.cpp | 8 +- test/ed25519_sodium_test.cpp | 128 ++-- test/ed25519_speccheck_test.cpp | 44 +- test/ed25519_wycheproof_sodium_test.cpp | 9 +- test/ed25519ph_sodium_test.cpp | 56 +- test/keypair_test.cpp | 31 +- test/messages/Jamfile | 7 + .../async_verify_eddsa_bytes_key.cpp | 5 +- ...y_eddsa_prehashed_asynchronous_backend.cpp | 6 +- .../async_verify_named_backend.cpp | 3 +- .../async_verify_p256_bytes_signature.cpp | 5 +- .../async_verify_without_policy/Jamfile | 14 + .../async_verify_without_policy.cpp | 46 ++ .../async_verify_wrong_key.cpp | 9 +- .../ed25519_unknown_policy.cpp | 11 +- test/messages/recover_any_s/Jamfile | 14 + test/messages/recover_any_s/recover_any_s.cpp | 40 ++ .../recover_ecdsa_signature.cpp | 3 +- .../verify_asynchronous_backend.cpp | 5 +- .../verify_ecdsa_bytes_key.cpp | 3 +- .../verify_ed25519_bytes_signature.cpp | 5 +- .../verify_eddsa_bytes_key.cpp | 4 +- test/messages/verify_eddsa_low_s_only/Jamfile | 14 + .../verify_eddsa_low_s_only.cpp | 34 ++ ...y_eddsa_prehashed_asynchronous_backend.cpp | 10 +- .../verify_eddsa_prehashed_message.cpp | 3 +- .../verify_free_asynchronous_backend.cpp | 3 +- .../verify_free_secp256k1_recoverable.cpp | 3 +- .../verify_keccak_recoverable.cpp | 3 +- .../verify_member_ed25519_ecdsa.cpp | 3 +- .../verify_member_eddsa_prehashed.cpp | 3 +- .../verify_member_p256_eddsa.cpp | 7 +- .../verify_member_secp256k1_recoverable.cpp | 5 +- test/messages/verify_p256_canonical/Jamfile | 14 + .../verify_p256_canonical.cpp | 41 ++ .../verify_p256_secp256k1_signature.cpp | 5 +- test/messages/verify_schnorr_any_s/Jamfile | 14 + .../verify_schnorr_any_s.cpp | 40 ++ .../verify_schnorr_as_ecdsa.cpp | 3 +- test/messages/verify_secp256k1_any_s/Jamfile | 14 + .../verify_secp256k1_any_s.cpp | 40 ++ test/messages/verify_without_policy/Jamfile | 14 + .../verify_without_policy.cpp | 33 + test/msvc/Jamfile | 7 + test/msvc/async_verify_without_policy/Jamfile | 11 + test/msvc/async_verify_without_policy/app.cpp | 40 ++ test/msvc/ed25519_unknown_policy/app.cpp | 11 +- test/msvc/recover_any_s/Jamfile | 11 + test/msvc/recover_any_s/app.cpp | 34 ++ test/msvc/verify_eddsa_low_s_only/Jamfile | 11 + test/msvc/verify_eddsa_low_s_only/app.cpp | 28 + test/msvc/verify_p256_canonical/Jamfile | 11 + test/msvc/verify_p256_canonical/app.cpp | 35 ++ test/msvc/verify_schnorr_any_s/Jamfile | 11 + test/msvc/verify_schnorr_any_s/app.cpp | 34 ++ test/msvc/verify_secp256k1_any_s/Jamfile | 11 + test/msvc/verify_secp256k1_any_s/app.cpp | 34 ++ test/msvc/verify_without_policy/Jamfile | 11 + test/msvc/verify_without_policy/app.cpp | 27 + test/oracle_25519_test.cpp | 4 +- test/p256_ecdsa_bearssl_test.cpp | 89 ++- test/p256_keys_bearssl_test.cpp | 9 +- test/p256_openssl_oracle_test.cpp | 3 +- test/p256_webcrypto_oracle_test.cpp | 14 +- test/p256_wycheproof_bearssl_test.cpp | 21 +- test/secp256k1_allocation_test.cpp | 25 +- test/secp256k1_bip340_test.cpp | 13 +- test/secp256k1_c_api_test.cpp | 3 +- test/secp256k1_der_test.cpp | 7 +- test/secp256k1_ethereum_test.cpp | 67 ++- test/secp256k1_keccak_alone_test.cpp | 3 +- test/secp256k1_musig_test.cpp | 34 +- test/secp256k1_recovery_test.cpp | 54 +- test/secp256k1_test.cpp | 214 ++++--- test/secp256k1_wycheproof_test.cpp | 14 +- test/secp256k1_xonly_tweak_test.cpp | 5 +- test/signing_curves_test.cpp | 137 +++-- test/signing_test.cpp | 106 +++- test/sizes/p256_bearssl_verify_ecdsa.cpp | 6 +- test/support/timing_coverage.hpp | 17 +- test/synchronous_forms_test.cpp | 121 ++-- test/timing_coverage_bearssl_test.cpp | 37 +- test/timing_coverage_secp256k1_test.cpp | 91 +-- test/timing_coverage_sodium_test.cpp | 65 +- test/verification_policies_test.cpp | 564 ++++++++++++++++++ 139 files changed, 3801 insertions(+), 1312 deletions(-) create mode 100644 test/messages/async_verify_without_policy/Jamfile create mode 100644 test/messages/async_verify_without_policy/async_verify_without_policy.cpp create mode 100644 test/messages/recover_any_s/Jamfile create mode 100644 test/messages/recover_any_s/recover_any_s.cpp create mode 100644 test/messages/verify_eddsa_low_s_only/Jamfile create mode 100644 test/messages/verify_eddsa_low_s_only/verify_eddsa_low_s_only.cpp create mode 100644 test/messages/verify_p256_canonical/Jamfile create mode 100644 test/messages/verify_p256_canonical/verify_p256_canonical.cpp create mode 100644 test/messages/verify_schnorr_any_s/Jamfile create mode 100644 test/messages/verify_schnorr_any_s/verify_schnorr_any_s.cpp create mode 100644 test/messages/verify_secp256k1_any_s/Jamfile create mode 100644 test/messages/verify_secp256k1_any_s/verify_secp256k1_any_s.cpp create mode 100644 test/messages/verify_without_policy/Jamfile create mode 100644 test/messages/verify_without_policy/verify_without_policy.cpp create mode 100644 test/msvc/async_verify_without_policy/Jamfile create mode 100644 test/msvc/async_verify_without_policy/app.cpp create mode 100644 test/msvc/recover_any_s/Jamfile create mode 100644 test/msvc/recover_any_s/app.cpp create mode 100644 test/msvc/verify_eddsa_low_s_only/Jamfile create mode 100644 test/msvc/verify_eddsa_low_s_only/app.cpp create mode 100644 test/msvc/verify_p256_canonical/Jamfile create mode 100644 test/msvc/verify_p256_canonical/app.cpp create mode 100644 test/msvc/verify_schnorr_any_s/Jamfile create mode 100644 test/msvc/verify_schnorr_any_s/app.cpp create mode 100644 test/msvc/verify_secp256k1_any_s/Jamfile create mode 100644 test/msvc/verify_secp256k1_any_s/app.cpp create mode 100644 test/msvc/verify_without_policy/Jamfile create mode 100644 test/msvc/verify_without_policy/app.cpp create mode 100644 test/verification_policies_test.cpp diff --git a/bench/operations.hpp b/bench/operations.hpp index 23be8def..ec50e419 100644 --- a/bench/operations.hpp +++ b/bench/operations.hpp @@ -194,7 +194,8 @@ class secp256k1 { bool check() { auto const signature = take(key_.sign(signing_schemes::schnorr, message_, aux_), "sign"); auto const public_key = take(key_.public_key(), "public_key"); - return crypto::verify(signing_schemes::schnorr, signature, message_, public_key) + return crypto::verify(signing_schemes::schnorr, verification_policies::canonical, signature, + message_, public_key) .has_value(); } @@ -259,7 +260,8 @@ class secp256k1_recover { std::uint8_t run() { auto const recovered = take(curves::secp256k1::recover(signing_schemes::ecdsa_sha256_recoverable, - signature_, signing_schemes::prehashed{hash_}), + verification_policies::low_s_only, signature_, + signing_schemes::prehashed{hash_}), "recover"); return recovered.compressed()[1]; } @@ -267,7 +269,8 @@ class secp256k1_recover { bool check() { auto const recovered = take(curves::secp256k1::recover(signing_schemes::ecdsa_sha256_recoverable, - signature_, signing_schemes::prehashed{hash_}), + verification_policies::low_s_only, signature_, + signing_schemes::prehashed{hash_}), "recover"); return recovered == take(key_.public_key(), "public_key"); } @@ -346,8 +349,8 @@ class secp256k1_musig { std::uint8_t run() { return sign().bytes()[0]; } bool check() { - return crypto::verify(signing_schemes::schnorr, sign(), message_, - signers_key_.xonly_public_key()) + return crypto::verify(signing_schemes::schnorr, verification_policies::canonical, sign(), + message_, signers_key_.xonly_public_key()) .has_value(); } @@ -483,8 +486,8 @@ class p256 { auto const signature = take( key_.sign(signing_schemes::ecdsa_sha256, signing_schemes::prehashed{digest_}), "sign"); auto const public_key = take(key_.public_key(), "public_key"); - return crypto::verify(signing_schemes::ecdsa_sha256, signature, - signing_schemes::prehashed{digest_}, public_key) + return crypto::verify(signing_schemes::ecdsa_sha256, verification_policies::low_s_only, + signature, signing_schemes::prehashed{digest_}, public_key) .has_value() && curves::p256::is_low_s(signature); } @@ -495,8 +498,8 @@ class p256 { }; // The verification of an ECDSA signature of a 32-byte SHA-256 digest on P-256, `crypto::verify( -// ecdsa_sha256, signature, prehashed{digest}, public_key)`; the signature and the public key are -// made once, outside what is measured. +// ecdsa_sha256, low_s_only, signature, prehashed{digest}, public_key)`, the policy of a signature +// crypto made; the signature and the public key are made once, outside what is measured. template class p256_verify_ecdsa { public: @@ -513,8 +516,8 @@ class p256_verify_ecdsa { "sign")) {} std::uint8_t run() { - take(crypto::verify(signing_schemes::ecdsa_sha256, signature_, - signing_schemes::prehashed{digest_}, public_key_), + take(crypto::verify(signing_schemes::ecdsa_sha256, verification_policies::low_s_only, + signature_, signing_schemes::prehashed{digest_}, public_key_), "verify"); return signature_.bytes()[0]; } @@ -524,11 +527,11 @@ class p256_verify_ecdsa { other_bytes[63] ^= 1U; auto const other = take(curves::p256::ecdsa_signature::from_bytes(other_bytes), "from_bytes"); - return crypto::verify(signing_schemes::ecdsa_sha256, signature_, - signing_schemes::prehashed{digest_}, public_key_) + return crypto::verify(signing_schemes::ecdsa_sha256, verification_policies::low_s_only, + signature_, signing_schemes::prehashed{digest_}, public_key_) .has_value() && - !crypto::verify(signing_schemes::ecdsa_sha256, other, - signing_schemes::prehashed{digest_}, public_key_) + !crypto::verify(signing_schemes::ecdsa_sha256, verification_policies::low_s_only, + other, signing_schemes::prehashed{digest_}, public_key_) .has_value(); } @@ -591,8 +594,8 @@ class ed25519 { bool check() { auto const signature = take(key_.sign(signing_schemes::eddsa, message_), "sign"); auto const public_key = take(key_.public_key(), "public_key"); - return crypto::verify(signing_schemes::eddsa, signature, message_, public_key, - curves::ed25519::strict) + return crypto::verify(signing_schemes::eddsa, verification_policies::canonical, + signature, message_, public_key) .has_value(); } diff --git a/doc/async.adoc b/doc/async.adoc index c57c5c2b..d0dcd425 100644 --- a/doc/async.adoc +++ b/doc/async.adoc @@ -52,7 +52,7 @@ its own, and the handler would run off the program's loop. | `void(error_code, Secretbox)` for `async_from_key`, `void(error_code, tag)` for `async_seal`, `void(error_code)` for `async_open` | Ed25519 (<>) -| `async_from_secret(executor, seed, token)`, `async_generate(executor, token)`, `async_sign(executor, key_pair, crypto::signing_schemes::eddsa, message, token)`, `async_verify(executor, crypto::signing_schemes::eddsa, signature, message, public_key, token)`, the policy optional before the token; on a native backend the same under `crypto::signing_schemes::eddsa_prehashed` with `+crypto::signing_schemes::prehashed{digest}+`, the message's SHA-512 (<>), which the browser's backend refuses at compile time +| `async_from_secret(executor, seed, token)`, `async_generate(executor, token)`, `async_sign(executor, key_pair, crypto::signing_schemes::eddsa, message, token)`, `async_verify(executor, crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, signature, message, public_key, token)`; on a native backend the same under `crypto::signing_schemes::eddsa_prehashed` with `+crypto::signing_schemes::prehashed{digest}+`, the message's SHA-512 (<>), which the browser's backend refuses at compile time | `void(error_code, Keypair)` for `async_from_secret` and `async_generate`, `void(error_code, signature)` for `async_sign`, `void(error_code)` for `async_verify` | X25519 (<>) @@ -60,7 +60,7 @@ its own, and the handler would run off the program's loop. | `void(error_code, Keypair)` for `async_from_secret` and `async_generate`, `void(error_code, secure::secret<32>)` for `async_agree` | P-256 (<>) -| `async_from_secret(executor, scalar, token)`, `async_generate(executor, token)`, `async_sign(executor, key_pair, crypto::signing_schemes::ecdsa_sha256, input, token)`, `async_verify(executor, crypto::signing_schemes::ecdsa_sha256, signature, input, public_key, token)`, `async_agree(executor, key_pair, peer_public_key, token)` +| `async_from_secret(executor, scalar, token)`, `async_generate(executor, token)`, `async_sign(executor, key_pair, crypto::signing_schemes::ecdsa_sha256, input, token)`, `async_verify(executor, crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::low_s_only, 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, secure::secret<32>)` for `async_agree` |=== @@ -68,7 +68,7 @@ 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)`, +`public_key.async_verify(executor, scheme, policy, signature, input, token)`, `key_pair.async_agree(executor, peer, token)` on X25519 and P-256, and every AEAD's and secret box's `C::async_from_key`, `aead.async_seal` and `aead.async_open`, and a crypto_box's `box.async_seal` and `box.async_open`. @@ -82,8 +82,9 @@ the call does not compile, the compiler saying that the member's deduced return type is used before it is defined (<>). `async_sign` and `async_verify` take the scheme and the input of the -synchronous `sign` and `crypto::verify`, and check them as `crypto::can_sign` -and `crypto::can_verify` do before anything else, so that a pair the +synchronous `sign` and `crypto::verify`, `async_verify` the policy after the +scheme too, and check them as `crypto::can_sign` and `crypto::can_verify` do +before anything else, so that a pair the synchronous call refuses stops the build here too (<>). P-256's input is the message, which they hash with SHA-256, as WebCrypto's `+sign({name: "ECDSA", hash: "SHA-256"}, ...)+` @@ -92,8 +93,10 @@ hashes and signs in one call operations]), or `+crypto::signing_schemes::prehashed{digest}+`, signed as given. WebCrypto has no prehash mode, so a backend that completes by itself, as the browser's will (<>), refuses the marker at compile time. The signature -is r then s, 64 bytes, WebCrypto's form, low S as `sign` gives it; one of -another size completes `async_verify` with `invalid_signature`. Their keys are +is r then s, 64 bytes, WebCrypto's form, low S as `sign` gives it, verified +under `crypto::verification_policies::low_s_only` or `any_s` as the synchronous +call is (<>); one of another size completes `async_verify` +with `invalid_signature`. Their keys are 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 (<>). diff --git a/doc/curves.adoc b/doc/curves.adoc index b8753084..64fb78da 100644 --- a/doc/curves.adoc +++ b/doc/curves.adoc @@ -91,8 +91,9 @@ include::generated/namespace-curves.adoc[] `` gives every curve one way to sign and one way to verify. A key pair signs with `key.sign(scheme, input)`, and -`crypto::verify(scheme, signature, input, public_key)`, in the namespace -`webcpp::crypto`, checks a signature with the public key alone. The scheme is a +`crypto::verify(scheme, policy, signature, input, public_key)`, in the namespace +`webcpp::crypto`, checks a signature with the public key alone, under a +verification policy the scheme accepts (<>). The scheme is a 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 @@ -184,7 +185,7 @@ 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 +`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::signing_schemes::ecdsa_sha256` never infers its curve from a number of bytes. BIP 340's keys are bytes on the @@ -193,15 +194,52 @@ wire, so `crypto::signing_schemes::schnorr` also takes the 32-byte x-only key. The signature is a type of its curve and scheme, the table's last column, and nothing else is taken where one is expected (<>). +[#crypto-curves-policies] +*Verification policies.* Every verification takes a policy second, after the +scheme, from `crypto::verification_policies`, and each scheme accepts its own; +another one, or none, stops the build with a message that names the ones it +accepts (design D9): + +.The policies each scheme accepts +[cols="2,2,2,4",options="header"] +|=== +| Scheme | Key | Policies | What the policy does + +| `ecdsa_sha256` +| `curves::secp256k1::public_key` +| `low_s_only` +| a high S is `invalid_signature`, as libsecp256k1 and Bitcoin's policy refuse it +(link:https://github.com/bitcoin/bips/blob/master/bip-0146.mediawiki[BIP 146]) + +| `ecdsa_sha256_recoverable`, `ecdsa_keccak256_recoverable` (`recover`) +| none: recovered +| `low_s_only` +| a high S is `invalid_signature` before recovery, as EIP-2 refuses one in a +transaction + +| `ecdsa_sha256` +| `curves::p256::basic_public_key` +| `low_s_only`, `any_s` +| `low_s_only`: a high S is `invalid_signature` before any backend call, for a +signature crypto made; `any_s`: either form, as FIPS 186-5 and WebCrypto accept, +for a signature a browser or a passkey made + +| `eddsa`, `eddsa_prehashed` +| `curves::ed25519::public_key` +| `canonical` +| libsodium's rules: S below L, canonical R and A, A not of small order + +| `schnorr` +| `curves::secp256k1::public_key`, its 32-byte x-only key +| `canonical` +| BIP 340's verification, which accepts only r below p and s below n +|=== + 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 -selected by a mask, without a branch on the secret. Verification differs on -purpose. secp256k1's `crypto::verify` refuses a high S, as libsecp256k1 and -Bitcoin's policy do -(link:https://github.com/bitcoin/bips/blob/master/bip-0146.mediawiki[BIP -146]); P-256's accepts both forms, as FIPS 186-5 and WebCrypto do, whose own -signatures may be high. A protocol that requires low S from a P-256 peer -checks `is_low_s` before `crypto::verify` (<>). +selected by a mask, without a branch on the secret. So `low_s_only` verifies +what crypto signs on either curve; P-256 also takes `any_s` because WebCrypto's +own signatures may be high (<>). secp256k1 keeps a third argument where it has a reason of its own: hedged ECDSA, `sign(crypto::signing_schemes::ecdsa_sha256, input, extra_entropy)`, mixes 32 fresh bytes of the @@ -210,20 +248,18 @@ auxiliary_random_bytes)` takes BIP 340's auxiliary randomness from the caller, for test vectors; `sign(crypto::signing_schemes::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::signing_schemes::ecdsa_sha256_recoverable, signature, input)` or -`recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, signature, input)` +`recover(crypto::signing_schemes::ecdsa_sha256_recoverable, crypto::verification_policies::low_s_only, signature, input)` or +`recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, crypto::verification_policies::low_s_only, signature, input)` (<>). Every `crypto::verify` takes its backend as its first template parameter, -`crypto::verify(scheme, signature, input, public_key)`, so that the -call reads the same on every curve: P-256 deduces it from the key, Ed25519 +`crypto::verify(scheme, policy, signature, input, public_key)`, so that +the call reads the same on every curve: P-256 deduces it from the key, Ed25519 takes its family's default, and secp256k1 libsecp256k1, its only backend. -`recover` and `async_verify` take it first too. Ed25519's verification policy -is a trailing argument, `curves::ed25519::strict` by default -(<>). +`recover` and `async_verify` take it first too. In an event loop, `async_sign(executor, key_pair, scheme, input, token)` and -`async_verify(executor, scheme, signature, input, public_key, token)`, and the +`async_verify(executor, scheme, policy, signature, input, public_key, token)`, and the members `key_pair.async_sign` and `public_key.async_verify`, take the same schemes and inputs on the curves WebCrypto has, Ed25519 and P-256, and check them as `crypto::can_sign` and `crypto::can_verify` do @@ -480,14 +516,14 @@ event loop. | Member | `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)`, +`key_pair.agree(peer)`, `public_key.verify(scheme, policy, signature, input)`, `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)`, +`public_key.async_verify(executor, scheme, policy, signature, input, token)`, `aead.async_seal(executor, nonce, associated_data, data, token)`, `aead.async_open(executor, nonce, associated_data, data, tag, token)` @@ -495,7 +531,7 @@ event loop. | `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::verify(scheme, policy, signature, input, public_key)`, `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)`, @@ -503,7 +539,7 @@ event loop. `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_verify(executor, scheme, policy, signature, input, public_key, token)`, `secret_key_encryption::aead::async_seal(executor, aead, nonce, associated_data, data, token)`, `secret_key_encryption::aead::async_open(executor, aead, nonce, @@ -520,8 +556,8 @@ 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 +(`async_from_key`) only. The verification policy follows the scheme in all +four (<>); secp256k1's 32 bytes of extra entropy or auxiliary randomness follow the input of `sign` and `crypto::sign`. @@ -544,7 +580,7 @@ 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::signing_schemes::eddsa, signature, +tag being of the namespace `webcpp::crypto`: `verify(crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, signature, message, public_key)` is `crypto::verify`. The catch-alls that stop the build with a message, those of `crypto::sign`, `crypto::verify` and `crypto::async_verify`, take only a scheme tag in the place of the scheme, and diff --git a/doc/ed25519.adoc b/doc/ed25519.adoc index 0c4afaf7..9a99abcf 100644 --- a/doc/ed25519.adoc +++ b/doc/ed25519.adoc @@ -28,7 +28,7 @@ its seed back (`secret()`, a `secure::secret<32>`), signs (`sign(crypto::signing_schemes::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::signing_schemes::eddsa, signature, message, public_key)` +destroyed. `crypto::verify(crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, signature, message, public_key)` checks a signature with the public key alone. The scheme `crypto::signing_schemes::eddsa` signs the message itself, of any length: a `crypto::signing_schemes::prehashed` digest does not compile, and the key pair is a `crypto::signing_keypair` and no @@ -43,8 +43,8 @@ Each operation has its four forms, the member and its free form, synchronous and asynchronous, with the same work, errors and refusals (<>); `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 +Verification takes the policy second, after the scheme, in every form: +`crypto::verification_policies::canonical`, the only one Ed25519 takes. An asynchronous form needs `` and `/webcpp/asio//asio` in the Jamfile: .Ed25519's operations in their four forms @@ -71,10 +71,10 @@ in the asynchronous forms. An asynchronous form needs `crypto::async_sign(executor, key_pair, crypto::signing_schemes::eddsa, message, token)` | Verify -| `public_key.verify(crypto::signing_schemes::eddsa, signature, message)` + -`crypto::verify(crypto::signing_schemes::eddsa, signature, message, public_key)` -| `public_key.async_verify(executor, crypto::signing_schemes::eddsa, signature, message, token)` + -`crypto::async_verify(executor, crypto::signing_schemes::eddsa, signature, message, public_key, token)` +| `public_key.verify(crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, signature, message)` + +`crypto::verify(crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, signature, message, public_key)` +| `public_key.async_verify(executor, crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, signature, message, token)` + +`crypto::async_verify(executor, crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, signature, message, public_key, token)` |=== *Ed25519ph* signs the SHA-512 of a message instead of the message (RFC 8032's @@ -82,9 +82,9 @@ prehashed form). A program that has the digest already signs it under the scheme `crypto::signing_schemes::eddsa_prehashed`, marked as one: `+key_pair.sign(crypto::signing_schemes::eddsa_prehashed, crypto::signing_schemes::prehashed{digest})+`, `digest` the 64 bytes of the message's SHA-512 (webcpp::hash's `sha2_512` computes it), -and `+crypto::verify(crypto::signing_schemes::eddsa_prehashed, signature, crypto::signing_schemes::prehashed{digest}, -public_key)+` or `+public_key.verify(crypto::signing_schemes::eddsa_prehashed, signature, -crypto::signing_schemes::prehashed{digest})+` checks it, strictly, as `crypto::signing_schemes::eddsa` does. The +and `+crypto::verify(crypto::signing_schemes::eddsa_prehashed, crypto::verification_policies::canonical, signature, crypto::signing_schemes::prehashed{digest}, +public_key)+` or `+public_key.verify(crypto::signing_schemes::eddsa_prehashed, crypto::verification_policies::canonical, signature, +crypto::signing_schemes::prehashed{digest})+` checks it, under `canonical`, as `crypto::signing_schemes::eddsa` does. The scheme takes the digest alone: a message, even one of 64 bytes, and a digest of another size do not compile. @@ -123,10 +123,10 @@ its sources, and RFC 8032's Ed25519ph vectors check the result on every target. `+crypto::async_sign(executor, key_pair, crypto::signing_schemes::eddsa_prehashed, crypto::signing_schemes::prehashed{digest}, token)+` | Verify a digest -| `+public_key.verify(crypto::signing_schemes::eddsa_prehashed, signature, crypto::signing_schemes::prehashed{digest})+` + -`+crypto::verify(crypto::signing_schemes::eddsa_prehashed, signature, crypto::signing_schemes::prehashed{digest}, public_key)+` -| `+public_key.async_verify(executor, crypto::signing_schemes::eddsa_prehashed, signature, crypto::signing_schemes::prehashed{digest}, token)+` + -`+crypto::async_verify(executor, crypto::signing_schemes::eddsa_prehashed, signature, crypto::signing_schemes::prehashed{digest}, public_key, token)+` +| `+public_key.verify(crypto::signing_schemes::eddsa_prehashed, crypto::verification_policies::canonical, signature, crypto::signing_schemes::prehashed{digest})+` + +`+crypto::verify(crypto::signing_schemes::eddsa_prehashed, crypto::verification_policies::canonical, signature, crypto::signing_schemes::prehashed{digest}, public_key)+` +| `+public_key.async_verify(executor, crypto::signing_schemes::eddsa_prehashed, crypto::verification_policies::canonical, signature, crypto::signing_schemes::prehashed{digest}, token)+` + +`+crypto::async_verify(executor, crypto::signing_schemes::eddsa_prehashed, crypto::verification_policies::canonical, signature, crypto::signing_schemes::prehashed{digest}, public_key, token)+` | A message in pieces | `prehashed_signer::begin()`, `update(piece)`, then @@ -156,12 +156,13 @@ include::{examples}/ed25519_sign.cpp[tag=program] include::{examples}/ed25519_sign.expected[] ---- -*Strict verification.* Implementations of Ed25519 disagree on some signatures +*Canonical verification.* Implementations of Ed25519 disagree on some signatures that no honest signer produces: a scalar `S` not reduced below the group order, a point encoded in a non-canonical form, a public key of small order. -`crypto::verify` takes a verification policy as its last argument, -`curves::ed25519::strict` by default and the only one in this version: -libsodium's rules, which refuse all three +`crypto::verify` takes a verification policy second, after the scheme, +`crypto::verification_policies::canonical`, the only one `eddsa` and +`eddsa_prehashed` take (another one, or none, stops the build with the policy +they take): libsodium's rules, which refuse all three (link:https://doc.libsodium.org/public-key_cryptography/public-key_signatures[libsodium's documentation]). Every valid signature of Wycheproof's EdDSA file is accepted and every invalid one refused (`ed25519_wycheproof_sodium`). @@ -171,11 +172,11 @@ EdDSAs" (link:https://eprint.iacr.org/2020/1244[IACR ePrint 2020/1244]), give twelve signatures on which implementations disagree, in their suite (link:https://github.com/novifinancial/ed25519-speccheck[novifinancial/ed25519-speccheck]). They run against every Ed25519 backend: its own verdict (raw), and its verdict -under `strict`, which is libsodium's on every backend. The test +under `canonical`, which is libsodium's on every backend. The test `ed25519_speccheck` asserts the table below, so that a new version of a backend that changes a verdict fails until the table is regenerated. WebCrypto in node is an outside view, recorded with the node and the OpenSSL that gave it (node's -Ed25519 is OpenSSL's) and never held to `strict`. The suite's results of 2021 +Ed25519 is OpenSSL's) and never held to `canonical`. The suite's results of 2021 show OpenSSL 3.0 accepting cases 0 to 2 and 11; the newer OpenSSL of the column's node refuses them, as libsodium does. @@ -187,11 +188,11 @@ for them. In the suite's results of 2021 (link:https://github.com/novifinancial/ed25519-speccheck#results[the suite's results], whose `Cargo.toml` pins them), Rust peers that used the default `verify` of ed25519-dalek 1.0.0-pre.4 accepted cases 0 to 2 and 11, which -`strict` refuses, and ed25519-zebra 2.1.1, a ZIP-215 verifier +`canonical` refuses, and ed25519-zebra 2.1.1, a ZIP-215 verifier (link:https://zips.z.cash/zip-0215[ZIP 215], the rule of Zcash), accepted every case but 6 to 8. ZIP-215 does so by design: it verifies with the cofactor and accepts non-canonical encodings of `A` and `R`, so that every -ZIP-215 verifier agrees on every signature. `strict` refuses the cases ZIP-215 +ZIP-215 verifier agrees on every signature. `canonical` refuses the cases ZIP-215 accepts beyond it; `zip215` is not a policy of this version, and waits for a mature C or {cpp} implementation of ZIP-215. @@ -204,7 +205,7 @@ print fixed signatures. that must refuse a replayed message signs a counter, a time or a context with it. -Parts of this section, libsodium's rules of strict verification, are adapted +Parts of this section, libsodium's rules of canonical verification, 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/generated/defaults.adoc b/doc/generated/defaults.adoc index 20318d22..1748f80e 100644 --- a/doc/generated/defaults.adoc +++ b/doc/generated/defaults.adoc @@ -62,7 +62,7 @@ |Ed25519 |native, wasip2, wasip3, emscripten |libsodium -|the only backend in this version, on every target, and its verification is the policy `strict` (link:https://doc.libsodium.org/public-key_cryptography/public-key_signatures[libsodium's documentation, public-key signatures]; link:https://www.rfc-editor.org/rfc/rfc8032[RFC 8032, the Edwards-curve Digital Signature Algorithm (EdDSA)]) +|the only backend in this version, on every target, and its verification is the policy `canonical` (link:https://doc.libsodium.org/public-key_cryptography/public-key_signatures[libsodium's documentation, public-key signatures]; link:https://www.rfc-editor.org/rfc/rfc8032[RFC 8032, the Edwards-curve Digital Signature Algorithm (EdDSA)]) |`+ed25519_sodium+`, `+default_backend_none_linked+` |X25519 diff --git a/doc/generated/ed25519-cases.adoc b/doc/generated/ed25519-cases.adoc index 9cb99e4f..01e416a4 100644 --- a/doc/generated/ed25519-cases.adoc +++ b/doc/generated/ed25519-cases.adoc @@ -9,7 +9,7 @@ [cols="1,5,2,2,2",options="header"] |=== -|Case |What it tests |libsodium, raw |libsodium, strict |WebCrypto in node 26.13.0 (OpenSSL 4.1.0), outside view +|Case |What it tests |libsodium, raw |libsodium, canonical |WebCrypto in node 26.13.0 (OpenSSL 4.1.0), outside view |0 |`+S+` = 0, `+A+` and `+R+` of small order diff --git a/doc/generated/messages.adoc b/doc/generated/messages.adoc index b90657b7..3d3af892 100644 --- a/doc/generated/messages.adoc +++ b/doc/generated/messages.adoc @@ -215,6 +215,12 @@ The fix: As `+async_verify_wrong_key+`: naming the backend does not add a scheme 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_without_policy+` +|native, wasip2, wasip3 +|`+webcpp::crypto: verify takes a verification policy after the scheme: crypto::signing_schemes::ecdsa_sha256 on a P-256 key takes crypto::verification_policies::low_s_only or any_s.+` + +The fix: As `+verify_without_policy+`: `+async_verify(executor, crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::low_s_only, signature, input, public_key, token)+` for a signature crypto made, `+any_s+` for one a browser's WebCrypto or a passkey made, whose S may be high. + |`+async_verify_wrong_key+` |native, wasip2, wasip3 |`+webcpp::crypto: async_verify takes crypto::signing_schemes::eddsa or crypto::signing_schemes::eddsa_prehashed with a curves::ed25519::public_key or crypto::signing_schemes::ecdsa_sha256 with a curves::p256::basic_public_key, the algorithms WebCrypto has: call crypto::verify for the others.+` @@ -313,9 +319,9 @@ The fix: Leave the backend out, as in `+curves::ed25519::keypair+`, or name `+ba |`+ed25519_unknown_policy+` |native, wasip2, wasip3 -|`+webcpp::crypto: Ed25519's only verification policy is curves::ed25519::strict.+` +|`+webcpp::crypto: verify: crypto::signing_schemes::eddsa and eddsa_prehashed take crypto::verification_policies::canonical.+` -The fix: Leave the policy out, as in `+crypto::verify(crypto::signing_schemes::eddsa, signature, message, public_key)+`, or name `+curves::ed25519::strict+`. +The fix: Name `+crypto::verification_policies::canonical+` after the scheme, Ed25519's only policy: `+crypto::verify(crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, signature, message, public_key)+`. |`+ed25519ph_sha256+` |native, wasip2, wasip3 @@ -521,6 +527,12 @@ The fix: Name silent_payments::previous_outputs_summary and make_previous_output The fix: As `+prevouts_summary_removed+`. +|`+recover_any_s+` +|native, wasip2, wasip3 +|`+webcpp::crypto: curves::secp256k1::recover takes crypto::verification_policies::low_s_only.+` + +The fix: Recover under `+crypto::verification_policies::low_s_only+`, its only policy: a signature whose S is high is refused before recovery; made low first, n - s with bit 0 of the recovery id flipped, it keeps its signer. + |`+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.+` @@ -715,7 +727,7 @@ The fix: As `+sign_ed25519_ecdsa+`: `+crypto::sign+` calls the key pair's own `+ |native, wasip2, wasip3 |`+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.+` -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)+`. +The fix: Give `+crypto::sign+` the key pair, whose public key verifies: `+crypto::sign(key_pair, scheme, input)+`, then `+crypto::verify(scheme, policy, signature, input, public_key)+` or `+public_key.verify(scheme, policy, signature, input)+`. |`+sign_keccak_digest_20+` |native, wasip2, wasip3 @@ -813,6 +825,12 @@ The fix: Make the 64 bytes received into a `+curves::ed25519::signature+` with ` The fix: Give `+crypto::signing_schemes::eddsa+` (or `+crypto::signing_schemes::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. +|`+verify_eddsa_low_s_only+` +|native, wasip2, wasip3 +|`+webcpp::crypto: verify: crypto::signing_schemes::eddsa and eddsa_prehashed take crypto::verification_policies::canonical.+` + +The fix: Verify Ed25519 and Ed25519ph under `+crypto::verification_policies::canonical+`, libsodium's rules, their only policy; `+low_s_only+` and `+any_s+` are ECDSA's. + |`+verify_eddsa_prehashed_asynchronous_backend+` |native, wasip2, wasip3 |`+webcpp::crypto: WebCrypto has no Ed25519ph: crypto::signing_schemes::eddsa_prehashed's sign, verify, async_sign and async_verify run on a native backend.+` @@ -841,7 +859,7 @@ The fix: As `+verify_member_secp256k1_recoverable+`: give a recoverable signatur |native, wasip2, wasip3 |`+webcpp::crypto: verify: this public key does not go with this scheme: crypto::signing_schemes::eddsa and crypto::signing_schemes::eddsa_prehashed take a curves::ed25519::public_key, crypto::signing_schemes::ecdsa_sha256 a curves::p256::basic_public_key or a curves::secp256k1::public_key, crypto::signing_schemes::schnorr a curves::secp256k1::public_key or a 32-byte x-only key; a crypto::signing_schemes::ecdsa_sha256_recoverable or a crypto::signing_schemes::ecdsa_keccak256_recoverable signature gives its key to curves::secp256k1::recover.+` -The fix: Give the signature to `+curves::secp256k1::recover(crypto::signing_schemes::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+`. +The fix: Give the signature to `+curves::secp256k1::recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, crypto::verification_policies::low_s_only, 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 @@ -865,7 +883,13 @@ The fix: Verify with `+crypto::signing_schemes::ecdsa_sha256+`, P-256's scheme; |native, wasip2, wasip3 |`+webcpp::crypto: a secp256k1 public key verifies crypto::signing_schemes::ecdsa_sha256 or crypto::signing_schemes::schnorr; a crypto::signing_schemes::ecdsa_sha256_recoverable or a crypto::signing_schemes::ecdsa_keccak256_recoverable signature gives its key to curves::secp256k1::recover.+` -The fix: Give a recoverable signature to `+curves::secp256k1::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, signature, input)+`, which gives the signer's key; a public key verifies `+crypto::signing_schemes::ecdsa_sha256+` and `+crypto::signing_schemes::schnorr+`. +The fix: Give a recoverable signature to `+curves::secp256k1::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, crypto::verification_policies::low_s_only, signature, input)+`, which gives the signer's key; a public key verifies `+crypto::signing_schemes::ecdsa_sha256+` and `+crypto::signing_schemes::schnorr+`. + +|`+verify_p256_canonical+` +|native, wasip2, wasip3 +|`+webcpp::crypto: verify: crypto::signing_schemes::ecdsa_sha256 on a P-256 key takes crypto::verification_policies::low_s_only or any_s.+` + +The fix: Verify P-256's ECDSA under `+crypto::verification_policies::low_s_only+`, for a signature crypto made, or `+any_s+`, for one a browser's WebCrypto or a passkey made, whose S may be high; `+canonical+` is Ed25519's and BIP340's. |`+verify_p256_secp256k1_signature+` |native, wasip2, wasip3 @@ -873,12 +897,30 @@ The fix: Give a recoverable signature to `+curves::secp256k1::recover(crypto::si 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_any_s+` +|native, wasip2, wasip3 +|`+webcpp::crypto: verify: crypto::signing_schemes::schnorr takes crypto::verification_policies::canonical.+` + +The fix: Verify BIP340 under `+crypto::verification_policies::canonical+`, its only policy; `+low_s_only+` and `+any_s+` are ECDSA's. + |`+verify_schnorr_as_ecdsa+` |native, wasip2, wasip3 |`+webcpp::crypto: verify: a secp256k1 key verifies a curves::secp256k1::ecdsa_signature under crypto::signing_schemes::ecdsa_sha256: make one from 64 bytes with curves::secp256k1::ecdsa_signature::from_bytes.+` The fix: Verify a BIP340 signature with `+crypto::signing_schemes::schnorr+`, its scheme; `+crypto::signing_schemes::ecdsa_sha256+` takes a `+curves::secp256k1::ecdsa_signature+`, which `+sign(crypto::signing_schemes::ecdsa_sha256, input)+` gives. +|`+verify_secp256k1_any_s+` +|native, wasip2, wasip3 +|`+webcpp::crypto: verify: crypto::signing_schemes::ecdsa_sha256 on a secp256k1 key takes crypto::verification_policies::low_s_only.+` + +The fix: Verify secp256k1's ECDSA under `+crypto::verification_policies::low_s_only+`, its only policy, as libsecp256k1 and Bitcoin's rule; a signature whose S is high is made low with `+normalize_low_s+` first. + +|`+verify_without_policy+` +|native, wasip2, wasip3 +|`+webcpp::crypto: verify takes a verification policy after the scheme: crypto::signing_schemes::eddsa takes crypto::verification_policies::canonical.+` + +The fix: Name the verification policy after the scheme: `+crypto::verify(crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, signature, message, public_key)+`; each scheme takes its own, `+canonical+` for Ed25519 and BIP340, `+low_s_only+` for secp256k1's ECDSA and `+recover+`, `+low_s_only+` or `+any_s+` for P-256's ECDSA. + |`+wipe_removed+` |native, wasip2, wasip3 |`+no type named 'wipe' in namespace 'webcpp::crypto'+` @@ -1334,7 +1376,7 @@ On each target, the build's output contains: * emscripten: ** `+webcpp::crypto: bearssl has no Ed25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten).+` -`+ed25519_unknown_policy_on_emscripten+`:: A program for Emscripten that names a policy of its own in Ed25519's `+crypto::verify+`. The fix: As `+ed25519_unknown_policy+`. +`+ed25519_unknown_policy_on_emscripten+`:: A program for Emscripten that names a policy of its own after the scheme in Ed25519's `+crypto::verify+`. The fix: As `+ed25519_unknown_policy+`. + Its Jamfile: + @@ -1346,7 +1388,7 @@ include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/ed25519_unknown_polic On each target, the build's output contains: + * emscripten: -** `+webcpp::crypto: Ed25519's only verification policy is curves::ed25519::strict.+` +** `+webcpp::crypto: verify: crypto::signing_schemes::eddsa and eddsa_prehashed take crypto::verification_policies::canonical.+` `+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+`. + @@ -1588,6 +1630,10 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |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_verify_without_policy+` +|the compile +|As `+verify_without_policy+`: `+async_verify(executor, crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::low_s_only, signature, input, public_key, token)+` for a signature crypto made, `+any_s+` for one a browser's WebCrypto or a passkey made, whose S may be high. + |`+bearssl_not_linked+` |the compile |Add `+/third_party//bearssl+`. @@ -1674,7 +1720,7 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |`+ed25519_unknown_policy+` |the compile -|Leave the policy out, as in `+crypto::verify(crypto::signing_schemes::eddsa, signature, message, public_key)+`, or name `+curves::ed25519::strict+`. +|Name `+crypto::verification_policies::canonical+` after the scheme, Ed25519's only policy: `+crypto::verify(crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, signature, message, public_key)+`. |`+ed25519ph_sha256+` |the compile @@ -1748,6 +1794,10 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |Add `+/webcpp/crypto//pem-default+`, which links `+/third_party//sodium+` on every target. +|`+recover_any_s+` +|the compile +|Recover under `+crypto::verification_policies::low_s_only+`, its only policy: a signature whose S is high is refused before recovery; made low first, n - s with bit 0 of the recovery id flipped, it keeps its signer. + |`+secp256k1_not_linked+` |the compile |Add `+/third_party//secp256k1+`. @@ -1772,6 +1822,26 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |Add `+/third_party//sodium+`. +|`+verify_eddsa_low_s_only+` +|the compile +|Verify Ed25519 and Ed25519ph under `+crypto::verification_policies::canonical+`, libsodium's rules, their only policy; `+low_s_only+` and `+any_s+` are ECDSA's. + +|`+verify_p256_canonical+` +|the compile +|Verify P-256's ECDSA under `+crypto::verification_policies::low_s_only+`, for a signature crypto made, or `+any_s+`, for one a browser's WebCrypto or a passkey made, whose S may be high; `+canonical+` is Ed25519's and BIP340's. + +|`+verify_schnorr_any_s+` +|the compile +|Verify BIP340 under `+crypto::verification_policies::canonical+`, its only policy; `+low_s_only+` and `+any_s+` are ECDSA's. + +|`+verify_secp256k1_any_s+` +|the compile +|Verify secp256k1's ECDSA under `+crypto::verification_policies::low_s_only+`, its only policy, as libsecp256k1 and Bitcoin's rule; a signature whose S is high is made low with `+normalize_low_s+` first. + +|`+verify_without_policy+` +|the compile +|Name the verification policy after the scheme: `+crypto::verify(crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, signature, message, public_key)+`; each scheme takes its own, `+canonical+` for Ed25519 and BIP340, `+low_s_only+` for secp256k1's ECDSA and `+recover+`, `+low_s_only+` or `+any_s+` for P-256's ECDSA. + |`+x25519_default_not_linked+` |the compile |Add `+/webcpp/crypto//x25519-default+`, which links `+/third_party//sodium+` on every target. diff --git a/doc/generated/namespace-curves.adoc b/doc/generated/namespace-curves.adoc index a24a3b36..d822fc8b 100644 --- a/doc/generated/namespace-curves.adoc +++ b/doc/generated/namespace-curves.adoc @@ -67,7 +67,7 @@ |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 +|SSH, Tor and Solana keys and signatures, and any protocol that names RFC 8032's Ed25519 or Ed25519ph; verification is canonical (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 `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-root.adoc b/doc/generated/namespace-root.adoc index 15013edd..5e7abe97 100644 --- a/doc/generated/namespace-root.adoc +++ b/doc/generated/namespace-root.adoc @@ -19,7 +19,7 @@ | | | -|`eddsa`, `eddsa_prehashed`, `ecdsa_sha256`, `ecdsa_sha256_recoverable`, `ecdsa_keccak256_recoverable`, `schnorr`, `prehashed`, `can_sign`, `can_verify`, `verify` +|`eddsa`, `eddsa_prehashed`, `ecdsa_sha256`, `ecdsa_sha256_recoverable`, `ecdsa_keccak256_recoverable`, `schnorr`, `prehashed`, `can_sign`, `can_verify`, `verify`, `low_s_only`, `any_s`, `canonical` |`keypair`, `signing_keypair`, `agreement_keypair`, `sign`, `agree` |`from_secret`, `from_bytes`, `from_key`, `generate` @@ -31,7 +31,7 @@ |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, a digest as a digest, and a signature as a value of its curve and scheme, on every curve +|Naming the scheme and the verification policy 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 @@ -55,7 +55,7 @@ |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 +|`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, and a policy the scheme does not take or none, stop the build |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 @@ -79,7 +79,7 @@ |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, 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 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, policy, signature, input)` or `verify(scheme, policy, signature, input, public_key)`, the policy one the scheme takes (<>); 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/llms.txt b/doc/llms.txt index 3327ced1..a2ccd735 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -20,7 +20,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - 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::signing_schemes::eddsa, ...)` run when the operation is initiated, its result posted to `completion_executor`. + - async_verify: Verifies an Ed25519 signature (RFC 8032's pure Ed25519) under a verification policy, asynchronously: `crypto::verify(crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, ...)` 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`. @@ -29,7 +29,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - 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::signing_schemes::ecdsa_sha256, ...)` 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::signing_schemes::prehashed{digest}` gives its digest. + - async_verify: Verifies a P-256 ECDSA signature over SHA-256 under a verification policy, asynchronously: `crypto::verify(crypto::signing_schemes::ecdsa_sha256, verification_policy, ...)` 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::signing_schemes::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. - [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. @@ -115,7 +115,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - 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::signing_schemes::schnorr, signature, message, key)`, or an ECDSA one against a `curves::secp256k1::public_key`, `crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, input, public_key)`, refusing a high S; `recover(crypto::signing_schemes::ecdsa_sha256_recoverable, signature, input)` and `recover(crypto::signing_schemes::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. +- [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::signing_schemes::schnorr, crypto::verification_policies::canonical, signature, message, key)`, or an ECDSA one against a `curves::secp256k1::public_key`, `crypto::verify(crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::low_s_only, signature, input, public_key)`, refusing a high S; `recover(crypto::signing_schemes::ecdsa_sha256_recoverable, crypto::verification_policies::low_s_only, signature, input)` and `recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, crypto::verification_policies::low_s_only, signature, input)` give the signer's key, refusing a high S before recovery. 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`) of ECDSA over SHA-256: the same inputs as `sign(crypto::signing_schemes::ecdsa_sha256_recoverable, ...)`. - [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. @@ -138,16 +138,16 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [curves::ed25519::public_key](https://webcpporg.github.io/libs/crypto/#crypto-ed25519): An Ed25519 public key, its 32 bytes, which `crypto::verify(crypto::signing_schemes::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::signing_schemes::eddsa, ...)`, 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. + - verify: Verifies an Ed25519 signature (RFC 8032's pure Ed25519) with this key under a verification policy (design D9): `crypto::verify(crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, ...)`, of which it is the member form, with the same work, results and refusals. + - async_verify: Verifies an Ed25519 signature with this key under a verification policy, 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. - 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::signing_schemes::eddsa, signature, message, public_key)`, or an Ed25519ph one, `crypto::verify(crypto::signing_schemes::eddsa_prehashed, signature, crypto::signing_schemes::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). +- [crypto::verify](https://webcpporg.github.io/libs/crypto/#crypto-ed25519): Verifies an Ed25519 signature with a public key alone, `crypto::verify(crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, signature, message, public_key)`, or an Ed25519ph one, `crypto::verify(crypto::signing_schemes::eddsa_prehashed, crypto::verification_policies::canonical, signature, crypto::signing_schemes::prehashed{digest}, public_key)`, under the policy `canonical`, the only one Ed25519 takes: 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 D9), `crypto::verification_policies::canonical`: libsodium's rules. - [curves::ed25519::prehashed_signer](https://webcpporg.github.io/libs/crypto/#crypto-ed25519): Ed25519ph (RFC 8032), the streaming form of the scheme `crypto::signing_schemes::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::signing_schemes::eddsa_prehashed, crypto::signing_schemes::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). + - verify: Verifies a signature of the message given, which it ends, under libsodium's rules, as `crypto::verification_policies::canonical` verifies (design D9). - [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 `secure::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. @@ -172,14 +172,14 @@ 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::secp256k1::recover](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-recovery): The public key that made a recoverable ECDSA signature, `recover(crypto::signing_schemes::ecdsa_sha256_recoverable, signature, input)` or Ethereum's `recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, signature, input)`, the input as signing took it: a message hashed inside (with SHA-256, or Keccak-256) or `crypto::signing_schemes::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). +- [curves::secp256k1::recover](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-recovery): The public key that made a recoverable ECDSA signature, `recover(crypto::signing_schemes::ecdsa_sha256_recoverable, crypto::verification_policies::low_s_only, signature, input)` or Ethereum's `recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, crypto::verification_policies::low_s_only, signature, input)`, the input as signing took it: a message hashed inside (with SHA-256, or Keccak-256) or `crypto::signing_schemes::prehashed{digest}`; a high S is refused before recovery. 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::signing_schemes::ecdsa_sha256_recoverable, ...)`. - [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. - 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::signing_schemes::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_value, signing_input, key)`, of which it is the member form, with the same work, results and refusals. + - verify: Verifies a signature with this key under a verification policy, of ECDSA over SHA-256 or of BIP340's Schnorr (design R22, D9): `crypto::verify(signing_scheme, verification_policy, 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`). @@ -210,7 +210,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - 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. - partial_signature_verify: Verifies one signer's partial signature (`secp256k1_musig_partial_sig_verify`), which tells a dishonest or faulty signer apart before the signature is aggregated. - - partial_signature_aggregate: The BIP 340 signature of the partial signatures (`secp256k1_musig_partial_sig_agg`), which `crypto::verify(crypto::signing_schemes::schnorr, signature, message, key)` checks under `aggregate_key::xonly_public_key()`. + - partial_signature_aggregate: The BIP 340 signature of the partial signatures (`secp256k1_musig_partial_sig_agg`), which `crypto::verify(crypto::signing_schemes::schnorr, crypto::verification_policies::canonical, signature, message, key)` checks under `aggregate_key::xonly_public_key()`. - parse_public_nonce: Parses a signer's public nonce (`secp256k1_musig_pubnonce_parse`): two compressed points. - serialize_public_nonce: Serialises a signer's public nonce (`secp256k1_musig_pubnonce_serialize`). - parse_aggregate_nonce: Parses an aggregate nonce (`secp256k1_musig_aggnonce_parse`): two compressed points, either of which may be the point at infinity, written as 33 zero bytes. @@ -237,12 +237,12 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - 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::signing_schemes::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::signing_schemes::ecdsa_sha256, input)` and `crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, input, public_key)`, the input a message hashed inside or `crypto::signing_schemes::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. + - verify: Verifies an ECDSA signature over SHA-256 with this key under a verification policy: `crypto::verify(crypto::signing_schemes::ecdsa_sha256, verification_policy, 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 under a verification policy, 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::signing_schemes::ecdsa_sha256, input)` and `crypto::verify(crypto::signing_schemes::ecdsa_sha256, policy, signature, input, public_key)`, the input a message hashed inside or `crypto::signing_schemes::prehashed{digest}`; the signature a `curves::p256::ecdsa_signature`, r and s, signed low S, verified under `crypto::verification_policies::low_s_only` (a high S refused before BearSSL) or `any_s` (WebCrypto's and a passkey's, 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 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. + - verify: Verifies an ECDSA signature over SHA-256 with a P-256 public key under a verification policy. - 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. - normalize_low_s: The low-S form of a signature: s replaced by n - s when s is above (n - 1) / 2, returned unchanged otherwise. @@ -295,7 +295,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - AES block cipher, native, MSVC: OpenSSL; the same rule as with Clang and GCC, but here OpenSSL is built no-asm: table-based AES, no AES-NI, not constant time ([OpenSSL's INSTALL.md, no-asm](https://github.com/openssl/openssl/blob/master/INSTALL.md)); where timing attacks matter, link ctaes and name `aes256`. - AES block cipher, wasip2, wasip3, emscripten: ctaes; constant time by design ([ctaes, constant-time AES](https://github.com/bitcoin/bitcoin/tree/master/src/crypto/ctaes)), where OpenSSL is built no-asm and its AES is table-based ([OpenSSL's INSTALL.md, no-asm](https://github.com/openssl/openssl/blob/master/INSTALL.md)), and webcpp does not build OpenSSL for Emscripten. - secp256k1, native, wasip2, wasip3, emscripten: libsecp256k1; the only backend ([libsecp256k1's README](https://github.com/bitcoin-core/secp256k1#readme)). -- Ed25519, native, wasip2, wasip3, emscripten: libsodium; the only backend in this version, on every target, and its verification is the policy `strict` ([libsodium's documentation, public-key signatures](https://doc.libsodium.org/public-key_cryptography/public-key_signatures); [RFC 8032, the Edwards-curve Digital Signature Algorithm (EdDSA)](https://www.rfc-editor.org/rfc/rfc8032)). +- Ed25519, native, wasip2, wasip3, emscripten: libsodium; the only backend in this version, on every target, and its verification is the policy `canonical` ([libsodium's documentation, public-key signatures](https://doc.libsodium.org/public-key_cryptography/public-key_signatures); [RFC 8032, the Edwards-curve Digital Signature Algorithm (EdDSA)](https://www.rfc-editor.org/rfc/rfc8032)). - X25519, native, wasip2, wasip3, emscripten: libsodium; the only backend in this version, on every target; it refuses an all-zero shared secret itself ([RFC 7748, Elliptic Curves for Security (X25519 and X448)](https://www.rfc-editor.org/rfc/rfc7748)). - crypto_kx, native, wasip2, wasip3, emscripten: libsodium; the only backend that has it: libsodium's own construction, whose session keys only another `crypto_kx` derives ([libsodium's documentation, key exchange](https://doc.libsodium.org/key_exchange)). - PEM, native, wasip2, wasip3, emscripten: libsodium; the only backend in this version, on every target; its base64 runs in a time that does not depend on the bytes, a private key's in a PKCS#8 ([libsodium's documentation, helpers: base64 encoding and decoding](https://doc.libsodium.org/helpers#base64-encoding-decoding)). @@ -405,7 +405,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - 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::signing_schemes::eddsa, message)` and `crypto::verify(crypto::signing_schemes::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::signing_schemes::eddsa_prehashed`, which gives the same signature, and verifies it with `crypto::verify(crypto::signing_schemes::eddsa_prehashed, signature, crypto::signing_schemes::prehashed{digest}, public_key)`. Prints each key and signature in hex, and whether the two Ed25519ph signatures are equal. +- 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::signing_schemes::eddsa, message)` and `crypto::verify(crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, 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::signing_schemes::eddsa_prehashed`, which gives the same signature, and verifies it with `crypto::verify(crypto::signing_schemes::eddsa_prehashed, crypto::verification_policies::canonical, signature, crypto::signing_schemes::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/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::signing_schemes::prehashed with crypto::signing_schemes::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. diff --git a/doc/overview.adoc b/doc/overview.adoc index d6d052ed..b21d9d36 100644 --- a/doc/overview.adoc +++ b/doc/overview.adoc @@ -27,8 +27,9 @@ through libsecp256k1. * *P-256.* ECDSA over SHA-256, signed low S, ECDH, strict DER and low-S forms, and SPKI and PKCS#8 keys, through BearSSL. * *One way to sign.* Every key pair signs with `sign(scheme, input)`, and -`crypto::verify(scheme, signature, input, public_key)` checks the signature, -the scheme named at every call and a digest given only as +`crypto::verify(scheme, policy, signature, input, public_key)` checks the +signature, the scheme and its verification policy named at every call and a +digest given only as `+crypto::signing_schemes::prehashed{digest}+` (<>). Each operation has the member and its free form, and, where WebCrypto has the algorithm, their asynchronous forms, with one implementation diff --git a/doc/p256.adoc b/doc/p256.adoc index 29490767..88b66dfc 100644 --- a/doc/p256.adoc +++ b/doc/p256.adoc @@ -47,7 +47,7 @@ other's; its ECDH gives the same x; its SPKI and its PKCS#8 are the bytes the encoders write, and it reads theirs as the same key. node's WebCrypto, on Emscripten (`p256_webcrypto_oracle`, the ECDSA and ECDH that Trystero's peers run): it verifies the signatures of `sign`, which are low S, its own -signatures verify with `crypto::verify`, whatever their S, its `deriveBits` gives +signatures verify with `crypto::verify` under `any_s`, whatever their S, its `deriveBits` gives the bytes of `agree`, and its `exportKey` of the keys it imported gives the bytes of `encode_spki`, of `encode_pkcs8` and of `uncompressed()`, byte for byte. @@ -115,10 +115,10 @@ asynchronous form needs `` and `crypto::async_sign(executor, key_pair, crypto::signing_schemes::ecdsa_sha256, input, token)` | Verify -| `public_key.verify(crypto::signing_schemes::ecdsa_sha256, signature, input)` + -`crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, input, public_key)` -| `public_key.async_verify(executor, crypto::signing_schemes::ecdsa_sha256, signature, input, token)` + -`crypto::async_verify(executor, crypto::signing_schemes::ecdsa_sha256, signature, input, public_key, token)` +| `public_key.verify(crypto::signing_schemes::ecdsa_sha256, policy, signature, input)` + +`crypto::verify(crypto::signing_schemes::ecdsa_sha256, policy, signature, input, public_key)` +| `public_key.async_verify(executor, crypto::signing_schemes::ecdsa_sha256, policy, signature, input, token)` + +`crypto::async_verify(executor, crypto::signing_schemes::ecdsa_sha256, policy, signature, input, public_key, token)` | Agree | `key_pair.agree(peer)` + @@ -196,13 +196,15 @@ number, a weak generator cannot leak the key, and the same key and digest give the same signature. Every verifier accepts it, WebCrypto's and OpenSSL's included: a verifier cannot tell how a nonce was made, and the signature is an ordinary ECDSA signature (link:https://csrc.nist.gov/pubs/fips/186-5/final[FIPS -186-5]). `crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, input, public_key)`, +186-5]). `crypto::verify(crypto::signing_schemes::ecdsa_sha256, policy, signature, input, public_key)`, the input the message or the marked digest, succeeds or returns `invalid_signature`, also for an r or an s that is 0 or not below the group -order n, refused before BearSSL sees it. +order n, refused before BearSSL sees it. The policy, second after the scheme in +every form, is `crypto::verification_policies::low_s_only` or `any_s` (*Low S* +below says which); another one, or none, stops the build with these two. In an event loop, `async_sign(executor, key_pair, crypto::signing_schemes::ecdsa_sha256, input, -token)` and `async_verify(executor, crypto::signing_schemes::ecdsa_sha256, signature, input, +token)` and `async_verify(executor, crypto::signing_schemes::ecdsa_sha256, policy, signature, input, public_key, token)` do the same through a completion, with the same inputs (<>). @@ -230,7 +232,8 @@ same digest too: anyone can turn one into the other without the key. That is signed the same digest, but a protocol that names a message by its signature's bytes sees two names for one message. FIPS 186-5 and WebCrypto accept both forms (link:https://csrc.nist.gov/pubs/fips/186-5/final[FIPS 186-5]; -link:https://www.w3.org/TR/WebCryptoAPI/[W3C]), and so does `crypto::verify`. +link:https://www.w3.org/TR/WebCryptoAPI/[W3C]), and so does `crypto::verify` +under `crypto::verification_policies::any_s`. `sign` gives the *low-S* form, s at most (n - 1) / 2: RFC 6979's S is replaced by n - s when it is high, without a branch on the secret, as libsecp256k1 signs. Some protocols accept only the low-S form: Bitcoin's @@ -239,15 +242,20 @@ and Trystero's, which normalizes what it signs and refuses a high S in what it reads (link:https://github.com/dmotz/trystero/blob/0.27.0/packages/core/src/crypto.ts[Trystero 0.27.0]). What such a protocol sends, `sign` already gives; what it receives, it -checks with `is_low_s(signature)`, true exactly when r is between 1 and n - 1 -and s between 1 and (n - 1) / 2, before the signature is verified. +verifies under `crypto::verification_policies::low_s_only`, which refuses a high +S with `invalid_signature` before BearSSL is called. So the policy says whose +signature it is: `low_s_only` for a signature crypto made, or a peer of a +protocol that requires low S; `any_s` for one a browser's WebCrypto or a passkey +made, whose S may be high. `is_low_s(signature)`, true exactly when r is between +1 and n - 1 and s between 1 and (n - 1) / 2, tells a program which form it holds. `normalize_low_s(signature)` returns the low-S form of a signature made elsewhere, such as WebCrypto's, whose S may be high, and the same signature when S is already low. Neither calls BearSSL: both are arithmetic on public bytes. *Example.* RFC 6979's key signs "sample", whose signature in the RFC has a -high S: `sign` gives its low-S form. Its DER, the signature verified with the -message and with its digest marked as one, and another message refused: +high S: `sign` gives its low-S form. Its DER, the signature verified under +`low_s_only` with the message and with its digest marked as one, and another +message refused: [source,cpp] ---- @@ -261,14 +269,15 @@ include::{examples}/p256_sign.expected[] *Pitfalls.* -* A protocol that requires low S and forgets `is_low_s` accepts both forms of -every signature it receives: `crypto::verify` accepts a high S, as WebCrypto -does. Tests with webcpp on both sides pass every time, `sign` giving the low -form; a program sees it at the first peer whose S is high, which a WebCrypto -peer's is about one signature in two. Check every signature such a protocol -receives. -* `is_low_s` does not verify: a forged signature can have a low S. Check low -S, then verify, and accept the signature only when both succeed. +* A protocol that requires low S and verifies under `any_s` accepts both forms +of every signature it receives, as WebCrypto does. Tests with webcpp on both +sides pass every time, `sign` giving the low form; a program sees it at the +first peer whose S is high, which a WebCrypto peer's is about one signature in +two. Such a protocol verifies under `low_s_only`. +* The opposite: a program that verifies a browser's or a passkey's signatures +under `low_s_only` refuses about one in two of them. Their policy is `any_s`. +* `is_low_s` does not verify: a forged signature can have a low S. Verifying +under `low_s_only` checks both. * A 32-byte message is a message: `sign(crypto::signing_schemes::ecdsa_sha256, message)` hashes it, and only `+crypto::signing_schemes::prehashed{digest}+` is signed as given. A digest of another hash than SHA-256, marked as one, signs, and no WebCrypto peer @@ -279,7 +288,7 @@ compile. signature arrives in DER (link:https://www.w3.org/TR/webauthn-2/#sctn-signature-attestation-types[W3C Web Authentication, section 6.5.5]): `from_der`, then -`+crypto::verify(crypto::signing_schemes::ecdsa_sha256, ...)+` of what the authenticator signed, +`+crypto::verify(crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::any_s, ...)+` of what the authenticator signed, which it hashes with SHA-256. Reading the COSE key and building those signed bytes are WebAuthn's, and stay outside crypto. diff --git a/doc/p2p.adoc b/doc/p2p.adoc index e5a4e7a9..ef32c4f2 100644 --- a/doc/p2p.adoc +++ b/doc/p2p.adoc @@ -263,9 +263,11 @@ WebCrypto's `exportKey("raw")`, and the receiver makes each a `public_key`, which checks the point once. Both sides hash the handshake's bytes with SHA-256 and each signs the digest, marked `+crypto::signing_schemes::prehashed{digest}+`, with its identity, as WebCrypto's ECDSA with SHA-256 signs (<>). A -signature has two forms, s and n - s, and both verify; a protocol that requires -one form, low S, gets it from `sign`, which signs no other, and its receiver -refuses the other form with `is_low_s` before it verifies. The session key comes +signature has two forms, s and n - s, and both verify under +`crypto::verification_policies::any_s`; a protocol that requires one form, low +S, gets it from `sign`, which signs no other, and its receiver verifies under +`low_s_only`, which refuses the other form before BearSSL is called; the +example checks `is_low_s` first too, so that its verdict names the reason. The session key comes from ECDH's x of the two session key pairs, which is not a key by itself, through HKDF (<>; link:https://www.rfc-editor.org/rfc/rfc5869[RFC 5869]). The example builds this @@ -305,7 +307,7 @@ include::{examples}/p256_handshake.cpp[tag=session,indent=0] ---- The two peers' run, and the same signature in its high-S form, as another -implementation may send it, refused though it would verify: +implementation may send it, refused though it verifies under `any_s`: [listing] ---- diff --git a/doc/secp256k1.adoc b/doc/secp256k1.adoc index e8c3bdeb..5a998d97 100644 --- a/doc/secp256k1.adoc +++ b/doc/secp256k1.adoc @@ -46,7 +46,11 @@ secp256k1 is not in WebCrypto, whose algorithms the asynchronous family follows. `sign` and `crypto::sign` take the 32 bytes of hedged ECDSA's extra entropy or BIP 340's auxiliary randomness after the input; `public_key.verify` takes `crypto::signing_schemes::ecdsa_sha256` and `crypto::signing_schemes::schnorr`, and `crypto::verify` with -`crypto::signing_schemes::schnorr` also takes the 32-byte x-only key: +`crypto::signing_schemes::schnorr` also takes the 32-byte x-only key. Every +verification takes a policy second, after the scheme: ECDSA +`crypto::verification_policies::low_s_only` alone, Schnorr +`crypto::verification_policies::canonical`, and `recover` `low_s_only`; another +one, or none, stops the build with the one the scheme takes: .secp256k1's operations in their two forms [cols="1,3,3",options="header"] @@ -66,8 +70,8 @@ takes `crypto::signing_schemes::ecdsa_sha256` and `crypto::signing_schemes::schn | `crypto::sign(key_pair, scheme, input)` | Verify -| `public_key.verify(scheme, signature, input)` -| `crypto::verify(scheme, signature, input, public_key)` +| `public_key.verify(scheme, policy, signature, input)` +| `crypto::verify(scheme, policy, signature, input, public_key)` | Agree | `key_pair.agree(peer)` @@ -164,8 +168,8 @@ pair wipes its copy, the program wipes its own. 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::signing_schemes::ecdsa_sha256, ...)+` refuses a high-S signature, as -libsecp256k1 does: `normalize_low_s` gives the low-S form of a signature from a +* `+crypto::verify(crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::low_s_only, ...)+` refuses a high-S signature, as +libsecp256k1 does, and secp256k1's ECDSA takes no other policy: `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 accepts both forms of a signature, so it must not rely on the signature's bytes being unique @@ -270,7 +274,7 @@ the uncompressed form without its prefix `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::signing_schemes::schnorr, ...)+` takes +coordinate alone, 32 bytes, which `+crypto::verify(crypto::signing_schemes::schnorr, crypto::verification_policies::canonical, ...)+` takes as it takes the `public_key` itself. Two `public_key` values compare with `==`, and order with `+<=>+` as their compressed encodings do, the order MuSig2's key sorting uses @@ -307,12 +311,12 @@ recovery id, 0 to 3, names the one that made it `sign(crypto::signing_schemes::ecdsa_sha256_recoverable, input)` gives a `recoverable_signature`, 65 bytes, r, s and the id, with the same r and s as `sign(crypto::signing_schemes::ecdsa_sha256, input)`, and -`recover(crypto::signing_schemes::ecdsa_sha256_recoverable, signature, input)` returns the +`recover(crypto::signing_schemes::ecdsa_sha256_recoverable, crypto::verification_policies::low_s_only, signature, input)` returns the `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::signing_schemes::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: its scheme +above 3, an r or an s not below the group order, a high S, before recovery, and +a signature from which no key is recovered. Ethereum's digest is Keccak-256's, not SHA-256's: its scheme is `crypto::signing_schemes::ecdsa_keccak256_recoverable` (<>). include::generated/backends-recovery.adoc[] @@ -367,7 +371,7 @@ paper, appendix F]), the scheme `crypto::signing_schemes::ecdsa_keccak256_recove `sign(crypto::signing_schemes::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::signing_schemes::ecdsa_keccak256_recoverable, signature, +recovery id, and `recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, crypto::verification_policies::low_s_only, 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 @@ -448,9 +452,11 @@ 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. +* `recover` takes `low_s_only` alone and refuses a high S before recovery, as +EIP-2 does for a transaction, although libsecp256k1's recovery and Ethereum's +`ecrecover` precompile accept one; `sign` gives a low S always. A program that +must recover a high-S signature makes it low first with `normalize_low_s` of +its r and s and the recovery id's bit 0 flipped, which keeps the signer. [#crypto-secp256k1-tweaks] ==== Tweaks, negation and combination @@ -721,7 +727,7 @@ send; * `partial_sign` signs this signer's part, consuming its secret nonce; `partial_signature_verify` checks one signer's part, and `partial_signature_aggregate` adds the parts into 64 bytes that -`+crypto::verify(crypto::signing_schemes::schnorr, ...)+` checks; +`+crypto::verify(crypto::signing_schemes::schnorr, crypto::verification_policies::canonical, ...)+` checks; * `parse_public_nonce`, `parse_aggregate_nonce` and `parse_partial_signature` read what the other signers send, and the `serialize_` functions write it. diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index d41b9747..cad08d2d 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -369,7 +369,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::signing_schemes::schnorr, signature, message, key)`, or an ECDSA one against a `curves::secp256k1::public_key`, `crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, input, public_key)`, refusing a high S; `recover(crypto::signing_schemes::ecdsa_sha256_recoverable, signature, input)` and `recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, signature, input)` give 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::signing_schemes::schnorr, crypto::verification_policies::canonical, signature, message, key)`, or an ECDSA one against a `curves::secp256k1::public_key`, `crypto::verify(crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::low_s_only, signature, input, public_key)`, refusing a high S; `recover(crypto::signing_schemes::ecdsa_sha256_recoverable, crypto::verification_policies::low_s_only, signature, input)` and `recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, crypto::verification_policies::low_s_only, signature, input)` give the signer's key, refusing a high S before recovery.", "section": "crypto-secp256k1", "backends": {"secp256k1": {"tests": ["secp256k1_bip340", "secp256k1_wycheproof", "secp256k1_recovery", "signing_curves"]}} }, @@ -445,7 +445,7 @@ "namespace": "curves", "api": "crypto::verify", "header": "", - "what": "Verifies an Ed25519 signature with a public key alone, `crypto::verify(crypto::signing_schemes::eddsa, signature, message, public_key)`, or an Ed25519ph one, `crypto::verify(crypto::signing_schemes::eddsa_prehashed, signature, crypto::signing_schemes::prehashed{digest}, 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::signing_schemes::eddsa, crypto::verification_policies::canonical, signature, message, public_key)`, or an Ed25519ph one, `crypto::verify(crypto::signing_schemes::eddsa_prehashed, crypto::verification_policies::canonical, signature, crypto::signing_schemes::prehashed{digest}, public_key)`, under the policy `canonical`, the only one Ed25519 takes: 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"]}} }, @@ -665,7 +665,7 @@ "namespace": "curves", "api": "curves::secp256k1::recover", "header": "", - "what": "The public key that made a recoverable ECDSA signature, `recover(crypto::signing_schemes::ecdsa_sha256_recoverable, signature, input)` or Ethereum's `recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, signature, input)`, the input as signing took it: a message hashed inside (with SHA-256, or Keccak-256) or `crypto::signing_schemes::prehashed{digest}`.", + "what": "The public key that made a recoverable ECDSA signature, `recover(crypto::signing_schemes::ecdsa_sha256_recoverable, crypto::verification_policies::low_s_only, signature, input)` or Ethereum's `recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, crypto::verification_policies::low_s_only, signature, input)`, the input as signing took it: a message hashed inside (with SHA-256, or Keccak-256) or `crypto::signing_schemes::prehashed{digest}`; a high S is refused before recovery.", "section": "crypto-secp256k1-recovery", "backends": {"secp256k1": {"tests": ["secp256k1_recovery"]}} }, @@ -779,7 +779,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::signing_schemes::ecdsa_sha256, input)` and `crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, input, public_key)`, the input a message hashed inside or `crypto::signing_schemes::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.", + "what": "ECDSA over SHA-256 with RFC 6979's nonce, `sign(crypto::signing_schemes::ecdsa_sha256, input)` and `crypto::verify(crypto::signing_schemes::ecdsa_sha256, policy, signature, input, public_key)`, the input a message hashed inside or `crypto::signing_schemes::prehashed{digest}`; the signature a `curves::p256::ecdsa_signature`, r and s, signed low S, verified under `crypto::verification_policies::low_s_only` (a high S refused before BearSSL) or `any_s` (WebCrypto's and a passkey's, 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"]}, @@ -894,7 +894,7 @@ {"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})"} + {"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 `canonical` ({libsodium-signatures}; {rfc8032})"} ], "backends": { "sodium": {"targets": "all", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect"]}} @@ -1201,7 +1201,7 @@ ["`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`, `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` (<>)"], + ["`eddsa`, `eddsa_prehashed`, `ecdsa_sha256`, `ecdsa_sha256_recoverable`, `ecdsa_keccak256_recoverable`, `schnorr`, `prehashed`, `can_sign`, `can_verify`, `verify`, `low_s_only`, `any_s`, `canonical`: Signatures", "Naming the scheme and the verification policy 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, and a policy the scheme does not take or none, 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, policy, signature, input)` or `verify(scheme, policy, signature, input, public_key)`, the policy one the scheme takes (<>); 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 (<>)"] ] @@ -1243,7 +1243,7 @@ "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, of a digest (`crypto::signing_schemes::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"], + ["`ed25519`", "Ed25519 signatures, and Ed25519ph over SHA-512, of a digest (`crypto::signing_schemes::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 canonical (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"] ] @@ -1375,7 +1375,7 @@ "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.", "chacha_openssl_on_emscripten": "A program for Emscripten that names OpenSSL, which is not built there, in ChaCha20-Poly1305's type.", - "ed25519_unknown_policy_on_emscripten": "A program for Emscripten that names a policy of its own in Ed25519's `crypto::verify`." + "ed25519_unknown_policy_on_emscripten": "A program for Emscripten that names a policy of its own after the scheme in Ed25519's `crypto::verify`." }, "fixes": { "gcm_default_openssl_not_linked": "Natively the default is OpenSSL: add `/webcpp/crypto//gcm-default`, which links `/webcpp/crypto//openssl` there, or name BearSSL in the type, as in `gcm>`.", @@ -1463,10 +1463,10 @@ "verify_eddsa_bytes_key": "Give `crypto::signing_schemes::eddsa` (or `crypto::signing_schemes::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::signing_schemes::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::signing_schemes::eddsa` or `crypto::signing_schemes::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)`.", + "sign_free_public_key": "Give `crypto::sign` the key pair, whose public key verifies: `crypto::sign(key_pair, scheme, input)`, then `crypto::verify(scheme, policy, signature, input, public_key)` or `public_key.verify(scheme, policy, signature, input)`.", "verify_member_eddsa_prehashed": "Verify the message itself with `crypto::signing_schemes::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::signing_schemes::eddsa_prehashed`, or for a message given in pieces with `curves::ed25519::prehashed_signer`.", "verify_member_ed25519_ecdsa": "Verify with `crypto::signing_schemes::eddsa` or `crypto::signing_schemes::eddsa_prehashed`, Ed25519's schemes; `crypto::signing_schemes::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::signing_schemes::ecdsa_sha256_recoverable, signature, input)`, which gives the signer's key; a public key verifies `crypto::signing_schemes::ecdsa_sha256` and `crypto::signing_schemes::schnorr`.", + "verify_member_secp256k1_recoverable": "Give a recoverable signature to `curves::secp256k1::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, crypto::verification_policies::low_s_only, signature, input)`, which gives the signer's key; a public key verifies `crypto::signing_schemes::ecdsa_sha256` and `crypto::signing_schemes::schnorr`.", "verify_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::signing_schemes::ecdsa_sha256` and `crypto::signing_schemes::schnorr` with a secp256k1 key.", "verify_member_p256_eddsa": "Verify with `crypto::signing_schemes::ecdsa_sha256`, P-256's scheme; `crypto::signing_schemes::eddsa` is Ed25519's, whose key is a `curves::ed25519::public_key`.", "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`.", @@ -1494,7 +1494,7 @@ "sign_keccak_digest_20": "As `sign_p256_digest_48`: give `crypto::signing_schemes::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::signing_schemes::ecdsa_sha256`, P-256's scheme; Ethereum's `crypto::signing_schemes::ecdsa_keccak256_recoverable` is secp256k1's.", "sign_ed25519_keccak": "Sign with `crypto::signing_schemes::eddsa` or `crypto::signing_schemes::eddsa_prehashed`, Ed25519's schemes; Ethereum's `crypto::signing_schemes::ecdsa_keccak256_recoverable` is secp256k1's.", - "verify_keccak_recoverable": "Give the signature to `curves::secp256k1::recover(crypto::signing_schemes::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_keccak_recoverable": "Give the signature to `curves::secp256k1::recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, crypto::verification_policies::low_s_only, 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::signing_schemes::prehashed{digest}`, which needs no XKCP.", "sign_eddsa_prehashed_message": "Give `crypto::signing_schemes::eddsa_prehashed` the message's SHA-512 marked as a digest, `crypto::signing_schemes::prehashed{digest}` of a `std::array`; sign the message itself with `crypto::signing_schemes::eddsa`, or give it in pieces to `curves::ed25519::prehashed_signer`.", "sign_eddsa_prehashed_digest_32": "Give `crypto::signing_schemes::eddsa_prehashed` SHA-512's 64-byte digest, `crypto::signing_schemes::prehashed{digest}` of a `std::array`: RFC 8032 defines Ed25519ph over SHA-512.", @@ -1515,7 +1515,14 @@ "pem_default_not_linked": "Add `/webcpp/crypto//pem-default`, which links `/third_party//sodium` on every target.", "chacha_header_not_included": "Include the backend's header the message names, as ``, and add its library, as `/third_party//bearssl`.", "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::signing_schemes::eddsa, signature, message, public_key)`, or name `curves::ed25519::strict`.", + "ed25519_unknown_policy": "Name `crypto::verification_policies::canonical` after the scheme, Ed25519's only policy: `crypto::verify(crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, signature, message, public_key)`.", + "verify_without_policy": "Name the verification policy after the scheme: `crypto::verify(crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, signature, message, public_key)`; each scheme takes its own, `canonical` for Ed25519 and BIP340, `low_s_only` for secp256k1's ECDSA and `recover`, `low_s_only` or `any_s` for P-256's ECDSA.", + "async_verify_without_policy": "As `verify_without_policy`: `async_verify(executor, crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::low_s_only, signature, input, public_key, token)` for a signature crypto made, `any_s` for one a browser's WebCrypto or a passkey made, whose S may be high.", + "verify_secp256k1_any_s": "Verify secp256k1's ECDSA under `crypto::verification_policies::low_s_only`, its only policy, as libsecp256k1 and Bitcoin's rule; a signature whose S is high is made low with `normalize_low_s` first.", + "verify_p256_canonical": "Verify P-256's ECDSA under `crypto::verification_policies::low_s_only`, for a signature crypto made, or `any_s`, for one a browser's WebCrypto or a passkey made, whose S may be high; `canonical` is Ed25519's and BIP340's.", + "verify_eddsa_low_s_only": "Verify Ed25519 and Ed25519ph under `crypto::verification_policies::canonical`, libsodium's rules, their only policy; `low_s_only` and `any_s` are ECDSA's.", + "verify_schnorr_any_s": "Verify BIP340 under `crypto::verification_policies::canonical`, its only policy; `low_s_only` and `any_s` are ECDSA's.", + "recover_any_s": "Recover under `crypto::verification_policies::low_s_only`, its only policy: a signature whose S is high is refused before recovery; made low first, n - s with bit 0 of the recovery id flipped, it keeps its signer.", "equal_header_removed": "Include ``, the header of `secure::constant_time_equal`; `equal.hpp` is gone, with no header left at its path.", "equal_removed": "Call `webcpp::secure::constant_time_equal`, the same comparison of two byte sequences in constant time; `crypto::equal` is gone, with no alias.", "wipe_removed": "Call `webcpp::secure::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.", diff --git a/doc/tables/generate.py b/doc/tables/generate.py index ab8a095f..32f9abe0 100644 --- a/doc/tables/generate.py +++ b/doc/tables/generate.py @@ -80,7 +80,8 @@ FIXTURES = 'tools/test/fixtures/crypto_jamfiles' ED25519_CASES = Path('meta/ed25519_cases.json') # The outside views of the edge cases, by their key in meta/ed25519_cases.json: verdicts recorded -# beside the backends', which strict is never compared with, headed by the versions that gave them. +# beside the backends', which canonical is never compared with, headed by the versions that gave +# them. OUTSIDE_TITLES = {'webcrypto-node': 'WebCrypto in node {node} (OpenSSL {openssl}), outside view'} VERDICTS = ('accept', 'reject') RUN_RULES = ('crypto-run', 'memory-run', 'webcpp.run', 'webcpp.compile', @@ -1556,7 +1557,7 @@ def sizes_page(data: Data, sizes: Data) -> str: def ed25519_cases_page(data: Data, cases: Data) -> str: """The twelve Ed25519 edge cases of meta/ed25519_cases.json: a row per case, what it tests, - then each backend's raw verdict and its verdict under `strict`, then each outside view's, + then each backend's raw verdict and its verdict under `canonical`, then each outside view's, headed by the node and OpenSSL that gave it. A backend or an outside view the generator does not know, an outside view without its node and OpenSSL, a row whose length is not the cases' and a verdict other than accept or reject are faults.""" @@ -1571,8 +1572,8 @@ def ed25519_cases_page(data: Data, cases: Data) -> str: if rows is None: continue title = data['backends'][backend]['title'] - columns += [f'{title}, raw', f'{title}, strict'] - verdicts += [rows['raw'], rows['strict']] + columns += [f'{title}, raw', f'{title}, canonical'] + verdicts += [rows['raw'], rows['canonical']] for name, view in cases['outside'].items(): if name not in OUTSIDE_TITLES: raise Fault(f'{ED25519_CASES} names the outside view {name}, which generate.py does ' diff --git a/doc/tables/generate_test.py b/doc/tables/generate_test.py index 8cdc8eec..f55ba8c3 100644 --- a/doc/tables/generate_test.py +++ b/doc/tables/generate_test.py @@ -244,18 +244,18 @@ def test_the_edge_cases_table_has_a_row_per_case_and_a_column_per_verdict(_: Pat data = {'backends': {'sodium': {'title': 'libsodium'}}} cases = {'source': {'repository': 'novifinancial/ed25519-speccheck', 'commit': '65519336', 'file': 'cases.json'}, - 'backends': {'sodium': {'raw': ['reject', 'accept'], 'strict': ['reject', 'accept']}}, + 'backends': {'sodium': {'raw': ['reject', 'accept'], 'canonical': ['reject', 'accept']}}, 'outside': {'webcrypto-node': {'node': '26.13.0', 'openssl': '4.1.0', 'verdicts': ['accept', 'accept']}}, 'cases': ['`S` = 0', '`A` non-canonical']} page = generate.ed25519_cases_page(data, cases) - header = ('|Case |What it tests |libsodium, raw |libsodium, strict ' + header = ('|Case |What it tests |libsodium, raw |libsodium, canonical ' '|WebCrypto in node 26.13.0 (OpenSSL 4.1.0), outside view') assert header in page, page assert '\n|0\n|`+S+` = 0\n|reject\n|reject\n|accept\n' in page, page assert '\n|1\n|`+A+` non-canonical\n|accept\n|accept\n|accept\n' in page, page - for broken in ({'raw': ['reject'], 'strict': ['reject', 'accept']}, - {'raw': ['reject', 'maybe'], 'strict': ['reject', 'accept']}): + for broken in ({'raw': ['reject'], 'canonical': ['reject', 'accept']}, + {'raw': ['reject', 'maybe'], 'canonical': ['reject', 'accept']}): try: generate.ed25519_cases_page(data, {**cases, 'backends': {'sodium': broken}}) except generate.Fault: @@ -268,7 +268,7 @@ def test_an_edge_cases_key_the_generator_does_not_know_is_a_fault(_: Path) -> No # A backend misnamed, an outside view without a title, or one whose node or OpenSSL is not # recorded would leave the page silently short of a row or of its provenance. data = {'backends': {'sodium': {'title': 'libsodium'}}} - row = {'raw': ['reject'], 'strict': ['reject']} + row = {'raw': ['reject'], 'canonical': ['reject']} view = {'node': '26.13.0', 'openssl': '4.1.0', 'verdicts': ['reject']} for backends, outside in (({'libsodium': row}, {'webcrypto-node': view}), ({'sodium': row}, {'webcrypto-deno': view}), diff --git a/doc/wallets.adoc b/doc/wallets.adoc index 0c554466..ba63cb03 100644 --- a/doc/wallets.adoc +++ b/doc/wallets.adoc @@ -82,7 +82,8 @@ include::{examples}/bitcoin_sighash.expected[] ---- `from_der` decodes strict DER and refuses anything else. A signature from a -signer that does not enforce low S is refused by `crypto::verify` as it is; +signer that does not enforce low S is refused by `crypto::verify` under +`crypto::verification_policies::low_s_only`, secp256k1's ECDSA's only policy; `normalize_low_s` gives its low-S form. The same steps in a program of its own, then the high-S form of its signature, refused, and normalized: @@ -167,7 +168,7 @@ 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::signing_schemes::ecdsa_sha256_recoverable, input)` makes the 65-byte `recoverable_signature`, and -`recover(crypto::signing_schemes::ecdsa_sha256_recoverable, signature, input)` finds the key (<>). Recovery finds some key for almost any +`recover(crypto::signing_schemes::ecdsa_sha256_recoverable, crypto::verification_policies::low_s_only, 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. diff --git a/example/arena_signer.cpp b/example/arena_signer.cpp index 81ebec36..7ab3179b 100644 --- a/example/arena_signer.cpp +++ b/example/arena_signer.cpp @@ -77,7 +77,8 @@ int main() { auto const public_key = key->public_key(); auto const signature = key->sign(crypto::signing_schemes::schnorr, message, aux); if (!public_key || !signature || - !crypto::verify(crypto::signing_schemes::schnorr, *signature, message, *public_key)) { + !crypto::verify(crypto::signing_schemes::schnorr, crypto::verification_policies::canonical, + *signature, message, *public_key)) { return 1; } std::printf("allocations in the arena: %zu\n", counting.allocations()); diff --git a/example/async_sign.cpp b/example/async_sign.cpp index da4ff831..ac2ebccf 100644 --- a/example/async_sign.cpp +++ b/example/async_sign.cpp @@ -83,6 +83,7 @@ asio::awaitable sign_and_verify() { 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::signing_schemes::eddsa, + crypto::verification_policies::canonical, signature, message, *public_key, use); if (verified) { std::printf("verify: %s\n", verified.message().c_str()); diff --git a/example/bitcoin_sighash.cpp b/example/bitcoin_sighash.cpp index cec5f8a6..c2fb6e5d 100644 --- a/example/bitcoin_sighash.cpp +++ b/example/bitcoin_sighash.cpp @@ -76,7 +76,8 @@ int main() { // The sighash is a SHA-256 digest: marked as one, ECDSA over SHA-256 signs it as given. auto const signature = key->sign(crypto::signing_schemes::ecdsa_sha256, crypto::signing_schemes::prehashed{sighash}); - if (!signature || !crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signature, + if (!signature || !crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *signature, crypto::signing_schemes::prehashed{sighash}, *public_key)) { return 1; } diff --git a/example/ecdsa_der.cpp b/example/ecdsa_der.cpp index 0da1b4f7..9a7253b0 100644 --- a/example/ecdsa_der.cpp +++ b/example/ecdsa_der.cpp @@ -114,7 +114,8 @@ int main() { } std::printf("strict der round trip ok\n"); if (!secp256k1::is_low_s(*signature) || - !crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signature, + !crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *signature, crypto::signing_schemes::prehashed{sighash}, *public_key)) { return 1; } @@ -130,7 +131,8 @@ int main() { return 1; } auto const& high = *received; - auto const refused = crypto::verify(crypto::signing_schemes::ecdsa_sha256, high, + auto const refused = crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, high, crypto::signing_schemes::prehashed{sighash}, *public_key); if (refused || refused.error() != crypto::error::invalid_signature) { return 1; @@ -139,7 +141,8 @@ int main() { // A signature from elsewhere can be brought to the low-S form before it is checked. auto const normalized = secp256k1::normalize_low_s(high); if (secp256k1::is_low_s(high) || !normalized || *normalized != *signature || - !crypto::verify(crypto::signing_schemes::ecdsa_sha256, *normalized, + !crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *normalized, crypto::signing_schemes::prehashed{sighash}, *public_key)) { return 1; } diff --git a/example/ed25519_sign.cpp b/example/ed25519_sign.cpp index ce3fc67a..f8faf280 100644 --- a/example/ed25519_sign.cpp +++ b/example/ed25519_sign.cpp @@ -6,14 +6,16 @@ // 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::signing_schemes::eddsa, message)` and -// `crypto::verify(crypto::signing_schemes::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::signing_schemes::eddsa_prehashed`, which gives the same signature, and -// verifies it with `crypto::verify(crypto::signing_schemes::eddsa_prehashed, signature, -// crypto::signing_schemes::prehashed{digest}, public_key)`. Prints each key and signature in hex, -// and whether the two Ed25519ph signatures are equal. +// `crypto::verify(crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, +// 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::signing_schemes::eddsa_prehashed`, which gives +// the same signature, and verifies it with +// `crypto::verify(crypto::signing_schemes::eddsa_prehashed, +// crypto::verification_policies::canonical, signature, crypto::signing_schemes::prehashed{digest}, +// public_key)`. Prints each key and signature in hex, and whether the two Ed25519ph signatures are +// equal. // // tag::program[] #include @@ -67,7 +69,8 @@ bool sign_whole() { print("public key", public_key->bytes()); print("signature ", signature->bytes()); // The verifier holds the public key, the message and the signature; nothing secret. - return crypto::verify(crypto::signing_schemes::eddsa, *signature, message, *public_key) + return crypto::verify(crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, + *signature, message, *public_key) .has_value(); } @@ -115,7 +118,8 @@ bool sign_in_pieces() { std::printf("eddsa_prehashed gives the same signature: %s\n", *from_digest == *signature ? "yes" : "no"); return *from_digest == *signature && - crypto::verify(crypto::signing_schemes::eddsa_prehashed, *from_digest, + crypto::verify(crypto::signing_schemes::eddsa_prehashed, + crypto::verification_policies::canonical, *from_digest, crypto::signing_schemes::prehashed{digest}, *public_key) .has_value(); } diff --git a/example/ethereum_personal_sign.cpp b/example/ethereum_personal_sign.cpp index 65284801..6526d9f8 100644 --- a/example/ethereum_personal_sign.cpp +++ b/example/ethereum_personal_sign.cpp @@ -100,7 +100,8 @@ int main() { // 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::signing_schemes::ecdsa_keccak256_recoverable, - *signature, crypto::signing_schemes::prehashed{digest}); + crypto::verification_policies::low_s_only, *signature, + crypto::signing_schemes::prehashed{digest}); if (!signer) { return 1; } diff --git a/example/four_forms.cpp b/example/four_forms.cpp index ef8fe1d1..fb343ba8 100644 --- a/example/four_forms.cpp +++ b/example/four_forms.cpp @@ -118,17 +118,23 @@ int main() { // tag::verify[] // Synchronous: the public key's member, and its free form, crypto::verify. bool const verified = - public_key->verify(crypto::signing_schemes::ecdsa_sha256, *signature, message).has_value(); + public_key + ->verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *signature, message) + .has_value(); bool const free_verified = - crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signature, message, *public_key) + crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *signature, message, *public_key) .has_value(); // Asynchronous: the member and its free form complete with the error code alone. bool async_verified = false; bool free_async_verified = false; - public_key->async_verify(executor, crypto::signing_schemes::ecdsa_sha256, *signature, message, + public_key->async_verify(executor, crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *signature, message, [&](boost::system::error_code code) { async_verified = !code; }); - crypto::async_verify(executor, crypto::signing_schemes::ecdsa_sha256, *signature, message, + crypto::async_verify(executor, crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *signature, message, *public_key, [&](boost::system::error_code code) { free_async_verified = !code; }); loop.restart(); diff --git a/example/key_formats.cpp b/example/key_formats.cpp index 7975d4e1..b3f1549e 100644 --- a/example/key_formats.cpp +++ b/example/key_formats.cpp @@ -77,7 +77,8 @@ bool ed25519_from_pem() { std::array const message{'h', 'e', 'l', 'l', 'o'}; auto const signature = pair->sign(crypto::signing_schemes::eddsa, message); return signature && - crypto::verify(crypto::signing_schemes::eddsa, *signature, message, *public_key); + crypto::verify(crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, + *signature, message, *public_key); } // An X25519 public key of RFC 7748's Alice, as SPKI in PEM. diff --git a/example/key_tweak.cpp b/example/key_tweak.cpp index c63ab724..1bb2f26e 100644 --- a/example/key_tweak.cpp +++ b/example/key_tweak.cpp @@ -120,7 +120,8 @@ int main() { auto const signature = payment_key->sign(crypto::signing_schemes::schnorr, message, aux); auto const xonly = watched->xonly(); if (!signature || - !crypto::verify(crypto::signing_schemes::schnorr, *signature, message, xonly)) { + !crypto::verify(crypto::signing_schemes::schnorr, crypto::verification_policies::canonical, + *signature, message, xonly)) { return 1; } std::printf("signature verifies under the tweaked public key\n"); diff --git a/example/musig_network.cpp b/example/musig_network.cpp index d1bc3ddf..1f672564 100644 --- a/example/musig_network.cpp +++ b/example/musig_network.cpp @@ -177,8 +177,9 @@ int main() { // The parts add up to one BIP 340 signature under the wallet's one x-only key. std::array const parts{*phone_part_in, *laptop_part_in}; auto const signature = musig::partial_signature_aggregate(*signing_session, parts, space); - if (!signature || !crypto::verify(crypto::signing_schemes::schnorr, *signature, message, - wallet_key->xonly_public_key())) { + if (!signature || + !crypto::verify(crypto::signing_schemes::schnorr, crypto::verification_policies::canonical, + *signature, message, wallet_key->xonly_public_key())) { return 1; } std::printf("the aggregate signature verifies as one BIP 340 signature: %zu bytes\n", diff --git a/example/musig_taproot.cpp b/example/musig_taproot.cpp index d1c58cbf..19ed7404 100644 --- a/example/musig_taproot.cpp +++ b/example/musig_taproot.cpp @@ -138,12 +138,14 @@ int main() { std::array const parts{*phone_part, *laptop_part}; auto const signature = musig::partial_signature_aggregate(*signing_session, parts, space); if (!signature || - !crypto::verify(crypto::signing_schemes::schnorr, *signature, message, output_key)) { + !crypto::verify(crypto::signing_schemes::schnorr, crypto::verification_policies::canonical, + *signature, message, output_key)) { return 1; } std::printf("the signature verifies under the output key\n"); auto const under_internal = - crypto::verify(crypto::signing_schemes::schnorr, *signature, message, internal_key); + crypto::verify(crypto::signing_schemes::schnorr, crypto::verification_policies::canonical, + *signature, message, internal_key); if (under_internal) { return 1; } diff --git a/example/musig_wallet.cpp b/example/musig_wallet.cpp index 614842a4..82f25c91 100644 --- a/example/musig_wallet.cpp +++ b/example/musig_wallet.cpp @@ -103,8 +103,9 @@ int main() { // The parts add up to one BIP 340 signature under the wallet's one x-only key. std::array const parts{*phone_part, *laptop_part}; auto const signature = musig::partial_signature_aggregate(*signing_session, parts, space); - if (!signature || !crypto::verify(crypto::signing_schemes::schnorr, *signature, message, - wallet_key->xonly_public_key())) { + if (!signature || + !crypto::verify(crypto::signing_schemes::schnorr, crypto::verification_policies::canonical, + *signature, message, wallet_key->xonly_public_key())) { return 1; } std::printf("the aggregate signature verifies as one BIP 340 signature\n"); diff --git a/example/p256_handshake.cpp b/example/p256_handshake.cpp index 40c1128e..171fce14 100644 --- a/example/p256_handshake.cpp +++ b/example/p256_handshake.cpp @@ -163,10 +163,10 @@ struct peer { // tag::receive[] // 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. + // p256::ecdsa_signature (64 bytes, r then s): low S first, as the protocol requires, so that + // the verdict names it, then the signature itself under low_s_only, the policy of a protocol + // whose peers sign low S, 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 received_signature) { @@ -181,7 +181,8 @@ struct peer { if (!p256::is_low_s(*signature)) { return verdict::high_s; } - if (!crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signature, + if (!crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *signature, crypto::signing_schemes::prehashed{digest}, *identity_key)) { return verdict::bad_signature; } @@ -269,20 +270,21 @@ int main() { 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. + // protocol's rule before it is verified, though crypto::verify under any_s, WebCrypto's policy, + // accepts it. auto const high = high_s_form(*alice_signature); 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 = - crypto::verify(crypto::signing_schemes::ecdsa_sha256, *high, - crypto::signing_schemes::prehashed{*digest}, *alice_identity) + bool const verifies_any_s = + crypto::verify(crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::any_s, + *high, crypto::signing_schemes::prehashed{*digest}, *alice_identity) .has_value(); - std::printf("high S: %s; crypto::verify alone: %s\n", + std::printf("high S: %s; crypto::verify under any_s: %s\n", text_of(peer::check(*alice_hello, *digest, high->bytes())), - verifies_alone ? "verified" : "refused"); + verifies_any_s ? "verified" : "refused"); auto const alice_key = alice->session_key(*bob_hello, *digest); auto const bob_key = bob->session_key(*alice_hello, *digest); diff --git a/example/p256_handshake.expected b/example/p256_handshake.expected index db448d97..29a6d970 100644 --- a/example/p256_handshake.expected +++ b/example/p256_handshake.expected @@ -5,6 +5,6 @@ bob signs cc8dcf4a649d262048a38c8b22d3a42c391d511aec2aa768cd9fc85210255ffe 43484db9140fe5007791c35016facbfa6c82429d056d4ac4db997ba163fdc736 bob checks alice: ok; alice checks bob: ok tampered: refused: the signature does not verify -high S: refused: high S, against the protocol's low-S rule; crypto::verify alone: verified +high S: refused: high S, against the protocol's low-S rule; crypto::verify under any_s: verified session keys agree session key 048b5927238ca3e923d3fbadc05deca38404588154e9b52c4b5faa33ef765ed3 diff --git a/example/p256_sign.cpp b/example/p256_sign.cpp index 24e0ae71..06537992 100644 --- a/example/p256_sign.cpp +++ b/example/p256_sign.cpp @@ -84,18 +84,23 @@ int main() { print("DER ", std::span(der).first(*length)); // The verifier holds the public key, the message and the signature; nothing secret. A digest - // computed elsewhere is marked as one, crypto::signing_schemes::prehashed{digest}. + // computed elsewhere is marked as one, crypto::signing_schemes::prehashed{digest}. The policy + // is low_s_only, since crypto signs low S; a signature WebCrypto or a passkey made, whose S may + // be high, is verified under crypto::verification_policies::any_s. auto const decoded = p256::from_der(std::span(der).first(*length)); std::array digest{}; auto const hashed = webcpp::hash::digest_of(digest, bytes_of("sample")); bool const both = decoded && hashed && - crypto::verify(crypto::signing_schemes::ecdsa_sha256, *decoded, + crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *decoded, bytes_of("sample"), *public_key) && - crypto::verify(crypto::signing_schemes::ecdsa_sha256, *decoded, + crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *decoded, crypto::signing_schemes::prehashed{digest}, *public_key); std::printf("verified %s\n", both ? "message and digest" : "FAILED"); - auto const other = crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signature, + auto const other = crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *signature, bytes_of("test"), *public_key); std::string const outcome = other ? std::string("verified") : other.error().message(); std::printf("other text %s\n", outcome.c_str()); diff --git a/example/recover_signer.cpp b/example/recover_signer.cpp index c5251f07..65fcfddf 100644 --- a/example/recover_signer.cpp +++ b/example/recover_signer.cpp @@ -78,7 +78,8 @@ int main() { // signer's key from the 65-byte signature and the message, and compares the two. auto const expected = secp256k1::public_key::from_bytes(published); auto const signer = secp256k1::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, - *signature, bytes_of(message)); + crypto::verification_policies::low_s_only, *signature, + bytes_of(message)); if (!expected || !signer || *signer != *expected) { return 1; } @@ -87,7 +88,8 @@ int main() { // A changed message still recovers a key, but not the wallet's. message = "pay 99 to bob"; auto const other = secp256k1::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, - *signature, bytes_of(message)); + crypto::verification_policies::low_s_only, *signature, + bytes_of(message)); if (other && *other == *expected) { return 1; } diff --git a/example/schnorr_sign.cpp b/example/schnorr_sign.cpp index 906d4f05..49e4c503 100644 --- a/example/schnorr_sign.cpp +++ b/example/schnorr_sign.cpp @@ -50,7 +50,9 @@ bool sign_and_verify(secp256k1::keypair const& key, std::spanxonly()); print("signature ", signature->bytes()); - return crypto::verify(crypto::signing_schemes::schnorr, *signature, message, *public_key) + return crypto::verify(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, *signature, message, + *public_key) .has_value(); } diff --git a/example/signed_message.cpp b/example/signed_message.cpp index 28d35f4a..cf7ca156 100644 --- a/example/signed_message.cpp +++ b/example/signed_message.cpp @@ -84,13 +84,14 @@ int main() { // tag::verify[] // The reader needs only the message, the signature and the public key. - if (!crypto::verify(crypto::signing_schemes::schnorr, *signature, id_of("meet at noon"), - *public_key)) { + if (!crypto::verify(crypto::signing_schemes::schnorr, crypto::verification_policies::canonical, + *signature, id_of("meet at noon"), *public_key)) { return 1; } std::printf("verified\n"); - auto const altered = crypto::verify(crypto::signing_schemes::schnorr, *signature, - id_of("meet at nine"), *public_key); + auto const altered = + crypto::verify(crypto::signing_schemes::schnorr, crypto::verification_policies::canonical, + *signature, id_of("meet at nine"), *public_key); if (altered || altered.error() != crypto::error::invalid_signature) { return 1; } diff --git a/example/signed_update.cpp b/example/signed_update.cpp index f7180a9e..69602b25 100644 --- a/example/signed_update.cpp +++ b/example/signed_update.cpp @@ -73,14 +73,16 @@ int main() { // 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::from_bytes(shipped_key); - if (!publisher_key || !crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signature, + if (!publisher_key || !crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *signature, bytes_of(update), *publisher_key)) { return 1; } std::printf("update accepted\n"); update[7] = update[7] == '2' ? '3' : '2'; - auto const tampered = crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signature, + auto const tampered = crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *signature, bytes_of(update), *publisher_key); if (tampered || tampered.error() != crypto::error::invalid_signature) { return 1; diff --git a/example/taproot_tweak.cpp b/example/taproot_tweak.cpp index 7f7df292..92126218 100644 --- a/example/taproot_tweak.cpp +++ b/example/taproot_tweak.cpp @@ -97,7 +97,8 @@ int main() { std::array const aux{}; auto const signature = key->sign(crypto::signing_schemes::schnorr, message, aux); if (!signature || - !crypto::verify(crypto::signing_schemes::schnorr, *signature, message, output->key)) { + !crypto::verify(crypto::signing_schemes::schnorr, crypto::verification_policies::canonical, + *signature, message, output->key)) { return 1; } std::printf("key-path signature verified\n"); diff --git a/include/webcpp/crypto/async.hpp b/include/webcpp/crypto/async.hpp index 0a97fc90..1fcc7819 100644 --- a/include/webcpp/crypto/async.hpp +++ b/include/webcpp/crypto/async.hpp @@ -32,24 +32,26 @@ AES-GCM seals and opens there. - Ed25519: `async_from_secret` (a key pair from its seed), `async_generate`, `async_sign(executor, key_pair, crypto::signing_schemes::eddsa, message, token)` and - `async_verify(executor, crypto::signing_schemes::eddsa, signature, message, public_key[, - policy], token)`, over `curves::ed25519::basic_keypair::sign` and `crypto::verify`, with their - inputs: the message itself, never a digest, the typed `curves::ed25519::signature` and the typed - `curves::ed25519::public_key`. Under `crypto::signing_schemes::eddsa_prehashed` (Ed25519ph), - the same functions take `crypto::signing_schemes::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`. + `async_verify(executor, crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, signature, message, public_key, token)`, over + `curves::ed25519::basic_keypair::sign` and `crypto::verify`, with their inputs: the message itself, + never a digest, the typed `curves::ed25519::signature` and the typed `curves::ed25519::public_key`. + Under `crypto::signing_schemes::eddsa_prehashed` (Ed25519ph), the same functions take + `crypto::signing_schemes::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_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::signing_schemes::ecdsa_sha256, input, token)` and - `async_verify(executor, crypto::signing_schemes::ecdsa_sha256, signature, input, public_key, - token)`, ECDSA 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::signing_schemes::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`. + `async_verify(executor, crypto::signing_schemes::ecdsa_sha256, policy, signature, input, + public_key, token)`, the policy `crypto::verification_policies::low_s_only` or `any_s`, ECDSA 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::signing_schemes::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`. - The heavy functions (design D32's list) take the work executor first (a `webcpp::asio::thread_pool`'s): they check their guards on the caller's thread, run the work on the work executor and complete on the handler's associated executor, with webcpp::hash's @@ -61,7 +63,7 @@ `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 + `public_key.async_verify(executor, scheme, policy, signature, input, token)`, and every AEAD's and box's `aead.async_seal` and `aead.async_open`. The classes declare them and this header defines them, so that a curve's or a cipher's header never includes Asio; the free function calls the member, which runs the synchronous member, so that the four forms of an operation share their @@ -162,12 +164,14 @@ namespace detail { * `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 `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; + * - `verify(executor, scheme, policy, signature, input, public_key, token)`: for Ed25519, the + * policy `verification_policies::canonical_t`, its signature `curves::ed25519::signature`, its + * message span and its key `curves::ed25519::public_key`, by value; for P-256, the policy + * `verification_policies::low_s_only_t` or `any_s_t`, which the engine applies to the public + * signature before the browser is called (a high S under `low_s_only` is `invalid_signature`), + * 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 @@ -547,29 +551,28 @@ auto initiate_sign(Executor const& completion_executor, Keypair const& key_pair, } /** - * Ed25519's `async_verify` once its guard is held, for the free functions and the members, with - * 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. + * Ed25519's `async_verify` once its guard is held, for the free functions and the members, under + * `eddsa` and `eddsa_prehashed`: the scheme, the policy, 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` or `eddsa_prehashed_t`; another scheme stops the build. + * @tparam Policy `verification_policies::canonical_t`; another type 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 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& 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) { @@ -577,20 +580,23 @@ auto initiate_verify_ed25519(Executor const& completion_executor, Signature cons refused_v, "webcpp::crypto: an Ed25519 public key verifies crypto::signing_schemes::eddsa or " "crypto::signing_schemes::eddsa_prehashed."); + } else if constexpr (!check_policy()) { + // Never compiled into a program: check_policy stopped the build. } 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( - completion_executor, signing_schemes::eddsa, signature_value, kept_input(signing_input), - public_key, verification_policy, std::forward(completion_token)); + return async_engine::verify(completion_executor, signing_schemes::eddsa, + verification_policies::canonical, signature_value, + kept_input(signing_input), public_key, + std::forward(completion_token)); } else { 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); + return public_key.template verify( + Scheme{}, verification_policies::canonical, signature_value, kept); }); } } @@ -1010,26 +1016,29 @@ void async_sign([[maybe_unused]] Executor const& completion_executor, } /** - * Verifies an Ed25519 signature (RFC 8032's pure Ed25519), asynchronously, strictly: - * `crypto::verify(crypto::signing_schemes::eddsa, ...)` run when the operation is - * initiated, its result posted to `completion_executor`. + * Verifies an Ed25519 signature (RFC 8032's pure Ed25519) under a verification policy, + * asynchronously: `crypto::verify(crypto::signing_schemes::eddsa, + * crypto::verification_policies::canonical, ...)` 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::signing_schemes::eddsa` among them, and * which runs the key's `verify`, with the same work. * - * 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. + * The policy, the signature and the input are checked as `crypto::can_verify` checks them, before + * anything else: another policy than `canonical` stops the build, as does a signature of another + * type, bytes included, and 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 Policy `crypto::verification_policies::canonical_t`; anything else stops the build. * @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 `completion_token` states. * @param completion_executor The executor the completion is posted to. * @param signing_scheme `crypto::signing_schemes::eddsa`. + * @param verification_policy `crypto::verification_policies::canonical` (libsodium's rules). * @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. @@ -1038,76 +1047,43 @@ void async_sign([[maybe_unused]] Executor const& completion_executor, * `invalid_signature` for a signature that does not verify; `backend_failure`. * @return What the completion token's `async_result` gives. */ -template , class Executor, +template , class Executor, class Policy, class Signature, class Input, class CompletionToken> auto async_verify(Executor const& completion_executor, signing_schemes::eddsa_t signing_scheme, - Signature const& signature_value, Input const& message_bytes, - curves::ed25519::public_key const& public_key, + Policy verification_policy, Signature const& signature_value, + Input const& message_bytes, curves::ed25519::public_key const& public_key, CompletionToken&& completion_token) { secure::timing_guard const timing_scope; return public_key.template async_verify( - completion_executor, signing_scheme, signature_value, message_bytes, + completion_executor, signing_scheme, verification_policy, signature_value, message_bytes, std::forward(completion_token)); } /** - * Verifies an Ed25519 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 A message, bytes that convert to `std::span`. - * @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::signing_schemes::eddsa`. - * @param signature_value The signature. - * @param message_bytes The signed bytes. - * @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, signing_schemes::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) { - secure::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::signing_schemes::eddsa_prehashed` run when the - * operation is initiated, its result posted to `completion_executor`. + * Verifies an Ed25519ph signature (RFC 8032's Ed25519 over a message's SHA-512) under a + * verification policy, asynchronously: `crypto::verify` of + * `crypto::signing_schemes::eddsa_prehashed` and `crypto::verification_policies::canonical` 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::signing_schemes::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. + * The policy, the signature and the input are checked as `crypto::can_verify` checks them, before + * anything else: another policy than `canonical` stops the build, as does a signature of another + * type, bytes included, 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 Policy `crypto::verification_policies::canonical_t`; anything else stops the build. * @tparam Signature `curves::ed25519::signature`; another type stops the build. * @tparam Input `crypto::signing_schemes::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::signing_schemes::eddsa_prehashed`. + * @param verification_policy `crypto::verification_policies::canonical` (libsodium's rules). * @param signature_value The signature; bytes from a peer are made into one by * `curves::ed25519::signature::from_bytes`. * @param digest_input `crypto::signing_schemes::prehashed{digest}`, the 64 bytes of the message's @@ -1118,10 +1094,10 @@ auto async_verify(Executor const& completion_executor, signing_schemes::eddsa_t * `backend_failure`. * @return What the completion token's `async_result` gives. */ -template , class Executor, +template , class Executor, class Policy, class Signature, class Input, class CompletionToken> auto async_verify(Executor const& completion_executor, - signing_schemes::eddsa_prehashed_t signing_scheme, + signing_schemes::eddsa_prehashed_t signing_scheme, Policy verification_policy, Signature const& signature_value, Input const& digest_input, curves::ed25519::public_key const& public_key, CompletionToken&& completion_token) { @@ -1130,78 +1106,41 @@ auto async_verify(Executor const& completion_executor, detail::refuse_ed25519ph_on_asynchronous_backend(); } else { return public_key.template async_verify( - completion_executor, signing_scheme, signature_value, digest_input, + completion_executor, signing_scheme, verification_policy, 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::signing_schemes::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::signing_schemes::eddsa_prehashed`. - * @param signature_value The signature. - * @param digest_input `crypto::signing_schemes::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, - signing_schemes::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) { - secure::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::signing_schemes::ecdsa_sha256, ...)` 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::signing_schemes::prehashed{digest}` gives its digest. + * Verifies a P-256 ECDSA signature over SHA-256 under a verification policy, asynchronously: + * `crypto::verify(crypto::signing_schemes::ecdsa_sha256, verification_policy, ...)` 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::signing_schemes::prehashed{digest}` gives its digest. * * The free form of the member `public_key.async_verify`, which it calls with the arguments * other than `public_key`, the scheme `crypto::signing_schemes::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 + * Under `crypto::verification_policies::low_s_only` a high S is refused before any backend call; + * under `any_s` a high S and a low S are both accepted, as WebCrypto accepts them. The policy, 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 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. + * another policy stops the build, as does a signature of another type, bytes included, and 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 Policy `crypto::verification_policies::low_s_only_t` or `any_s_t`; anything else stops + * the build. * @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::signing_schemes::prehashed<32>`. * @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::signing_schemes::ecdsa_sha256`. + * @param verification_policy `crypto::verification_policies::low_s_only` or `any_s`. * @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`. @@ -1209,18 +1148,21 @@ auto async_verify(Executor const& completion_executor, * 32-byte SHA-256 digest. * @param public_key The signer's public key, validated when it was made. * @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. + * `invalid_signature` for an r or an s that is 0 or not below n, a high S under `low_s_only`, and + * one that does not verify. * @return What the completion token's `async_result` gives. */ -template +template auto async_verify(Executor const& completion_executor, - signing_schemes::ecdsa_sha256_t signing_scheme, Signature const& signature_value, - Input const& signing_input, + signing_schemes::ecdsa_sha256_t signing_scheme, Policy verification_policy, + Signature const& signature_value, Input const& signing_input, curves::p256::basic_public_key const& public_key, CompletionToken&& completion_token) { secure::timing_guard const timing_scope; - return public_key.async_verify(completion_executor, signing_scheme, signature_value, - signing_input, std::forward(completion_token)); + return public_key.async_verify(completion_executor, signing_scheme, verification_policy, + signature_value, signing_input, + std::forward(completion_token)); } /** @@ -1233,23 +1175,26 @@ auto async_verify(Executor const& completion_executor, * @tparam Backend Ignored: the first template parameter, as on every `async_verify`. * @tparam Executor The executor's type. * @tparam Scheme A scheme tag. + * @tparam Policy The policy's type. * @tparam Signature The signature's type. * @tparam Input The input's type. * @tparam PublicKey The public key's type. * @tparam CompletionToken The completion token's type. * @param completion_executor The executor. * @param signing_scheme The scheme. + * @param verification_policy The policy. * @param signature_value The signature. * @param signing_input The message or the marker. * @param public_key The public key. * @param completion_token The completion token. */ -template +template requires(detail::is_scheme_v && !detail::has_async_verifier_v>) void async_verify([[maybe_unused]] Executor const& completion_executor, [[maybe_unused]] Scheme signing_scheme, + [[maybe_unused]] Policy verification_policy, [[maybe_unused]] Signature const& signature_value, [[maybe_unused]] Input const& signing_input, [[maybe_unused]] PublicKey const& public_key, @@ -1262,6 +1207,37 @@ void async_verify([[maybe_unused]] Executor const& completion_executor, "algorithms WebCrypto has: call crypto::verify for the others."); } +/** + * Stops the build: an `async_verify` of the arity before the verification policies, + * `async_verify(executor, scheme, signature, input, public_key, token)`, with no policy after the + * scheme. The message names the policies the scheme takes on the key (design D9). + * + * @tparam Backend Ignored: the first template parameter, as on every `async_verify`. + * @tparam Executor The executor's type. + * @tparam Scheme A scheme tag. + * @tparam Signature The signature's type, which is no policy. + * @tparam Input The input's type. + * @tparam PublicKey The public key's type. + * @tparam CompletionToken The completion token's type. + * @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 completion_token The completion token. + */ +template + requires(detail::is_scheme_v && !detail::is_policy_v) +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&& completion_token) { + detail::refuse_missing_policy>(); +} + /** * 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 @@ -1561,10 +1537,11 @@ auto curves::ed25519::basic_keypair::async_sign(Executor const& complet } } -template auto curves::ed25519::public_key::async_verify(Executor const& completion_executor, [[maybe_unused]] Scheme signing_scheme, + [[maybe_unused]] Policy verification_policy, Signature const& signature_value, Input const& message_input, CompletionToken&& completion_token) const { @@ -1573,26 +1550,8 @@ auto curves::ed25519::public_key::async_verify(Executor const& completion_execut 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 { - secure::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, + return detail::initiate_verify_ed25519( + completion_executor, signature_value, message_input, *this, std::forward(completion_token)); } } @@ -1678,16 +1637,20 @@ auto curves::p256::basic_keypair::async_agree(Executor const& completio } template -template +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, + Policy verification_policy, Signature const& signature_value, Input const& signing_input, CompletionToken&& completion_token) const { secure::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::signing_schemes::ecdsa_sha256."); + } else if constexpr (!detail::check_policy()) { + // Never compiled into a program: check_policy stopped the build. } else if constexpr (!detail::check_signature()) { // Never compiled into a program: check_signature stopped the build. @@ -1695,15 +1658,16 @@ auto curves::p256::basic_public_key::async_verify( detail::check_input(); } else if constexpr (detail::asynchronous_backend_v) { return detail::async_engine::verify( - completion_executor, signing_schemes::ecdsa_sha256, signature_value, - detail::kept_input(signing_input), *this, + completion_executor, signing_schemes::ecdsa_sha256, verification_policy, + signature_value, detail::kept_input(signing_input), *this, std::forward(completion_token)); } else { return detail::complete_by_post( completion_executor, completion_token, - [this, signature_value, + [this, verification_policy, signature_value, kept = detail::kept_input(signing_input)]() noexcept -> boost::system::result { - return verify(signing_schemes::ecdsa_sha256, signature_value, kept); + return verify(signing_schemes::ecdsa_sha256, verification_policy, signature_value, + kept); }); } } diff --git a/include/webcpp/crypto/backends/sodium.hpp b/include/webcpp/crypto/backends/sodium.hpp index f5dd7d39..9f43c8ea 100644 --- a/include/webcpp/crypto/backends/sodium.hpp +++ b/include/webcpp/crypto/backends/sodium.hpp @@ -683,7 +683,7 @@ struct ed25519_engine { } /** - * Verifies a signature, `crypto_sign_ed25519_verify_detached`: the policy `strict`. + * Verifies a signature, `crypto_sign_ed25519_verify_detached`: the policy `canonical`. * * @return Nothing; `invalid_signature`; `backend_failure`. */ diff --git a/include/webcpp/crypto/config.hpp b/include/webcpp/crypto/config.hpp index 7152a23a..c0c98f22 100644 --- a/include/webcpp/crypto/config.hpp +++ b/include/webcpp/crypto/config.hpp @@ -209,8 +209,9 @@ namespace formats {} namespace signing_schemes {} /** - The verification policies, which `verify` takes to say what a signature must be besides valid: - the names of the policies are declared in it. + The verification policies, which every `verify`, `async_verify` and `recover` takes after the + scheme to say what a signature must be besides valid: `verification_policies::low_s_only`, + `any_s` and `canonical`, declared in ``; each scheme accepts its own. */ namespace verification_policies {} diff --git a/include/webcpp/crypto/curves/ed25519.hpp b/include/webcpp/crypto/curves/ed25519.hpp index fa80f7e2..c375c4f0 100644 --- a/include/webcpp/crypto/curves/ed25519.hpp +++ b/include/webcpp/crypto/curves/ed25519.hpp @@ -8,9 +8,9 @@ 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, `curves::ed25519::signature` of 64 bytes, `key.sign(crypto::signing_schemes::eddsa, message)`, and their verification, - `crypto::verify(crypto::signing_schemes::eddsa, signature, message, public_key)`, strict on - libsodium; Ed25519ph, the signature of a message's SHA-512, under the scheme - `crypto::signing_schemes::eddsa_prehashed` from the digest and by + `crypto::verify(crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, + signature, message, public_key)`, libsodium's rules; Ed25519ph, the signature of a message's + SHA-512, under the scheme `crypto::signing_schemes::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. @@ -95,22 +95,6 @@ namespace webcpp::crypto::curves::ed25519 { template class prehashed_signer; -/** - * The type of the verification policy `strict`. - * - * Its explicit default constructor keeps `{}` from standing for a policy. - */ -struct strict_t { - /** Makes the tag. */ - explicit strict_t() = default; -}; - -/** - * Ed25519 verification as libsodium does it: `S` below the group order, `A` and `R` canonical, - * neither of small order (design D31); `crypto::verify`'s policy by default. - */ -inline constexpr strict_t strict{}; - /** * An Ed25519 signature (RFC 8032), 64 bytes, R then S: what `sign` gives under * `crypto::signing_schemes::eddsa` or `crypto::signing_schemes::eddsa_prehashed`, as does @@ -120,7 +104,7 @@ inline constexpr strict_t strict{}; * 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. + * verification policy's judgment, `crypto::verification_policies::canonical`'s. */ using signature = detail::basic_signature; @@ -133,7 +117,7 @@ namespace webcpp::crypto::detail { * and of `crypto::verify` of `eddsa`, which hold the guard. * * @tparam Backend The backend. - * @tparam Policy `curves::ed25519::strict_t`; anything else stops the build. + * @tparam Policy `verification_policies::canonical_t`, which its callers have checked. * @tparam Input A message; anything else stops the build. * @param signature_bytes The signature's 64 bytes. * @param message_input The signed bytes. @@ -144,8 +128,9 @@ template [[nodiscard]] boost::system::result ed25519_verify( 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."); + static_assert( + std::is_same_v, + "webcpp::crypto: Ed25519 verifies under crypto::verification_policies::canonical."); check_input(); if constexpr (input_valid_v) { return ed25519_engine::verify( @@ -161,7 +146,7 @@ template * `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 Policy `verification_policies::canonical_t`, which its callers have checked. * @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. @@ -172,8 +157,9 @@ 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."); + static_assert( + std::is_same_v, + "webcpp::crypto: Ed25519 verifies under crypto::verification_policies::canonical."); check_input(); if constexpr (input_valid_v) { return ed25519ph_engine::verify_digest( @@ -193,7 +179,7 @@ namespace webcpp::crypto::curves::ed25519 { * `crypto::verify(crypto::signing_schemes::eddsa, ...)` takes. * * `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 + * order is the verification policy's judgment (`canonical` 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 `from_bytes` and by a key pair's `public_key()`. */ @@ -227,35 +213,35 @@ class public_key { [[nodiscard]] std::array bytes() const noexcept { return bytes_; } /** - * Verifies an Ed25519 signature (RFC 8032's pure Ed25519) with this key, under a verification - * policy (design D31): - * `crypto::verify(crypto::signing_schemes::eddsa, ...)`, of which it is the member form, with - * the same work, results and refusals. + * Verifies an Ed25519 signature (RFC 8032's pure Ed25519) with this key under a verification + * policy (design D9): `crypto::verify(crypto::signing_schemes::eddsa, + * crypto::verification_policies::canonical, ...)`, of which it is the member form, with the + * same work, results and refusals. * * Ed25519ph's is the overload of `crypto::signing_schemes::eddsa_prehashed`. * * @tparam Backend The backend; by default the family's. * @tparam Scheme `crypto::signing_schemes::eddsa_t`; another scheme stops the build. + * @tparam Policy `crypto::verification_policies::canonical_t` (libsodium's rules), the only + * policy Ed25519 takes; anything else 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::signing_schemes::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::signing_schemes::eddsa`. + * @param verification_policy `crypto::verification_policies::canonical`. * @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 that does not verify, a key that is not * canonical or of small order included. */ - template , class Scheme, class Signature, - class Input, class Policy = strict_t> - [[nodiscard]] boost::system::result verify( - [[maybe_unused]] Scheme signing_scheme, Signature const& signature_value, - Input const& message_input, - [[maybe_unused]] Policy verify_policy = Policy{}) const noexcept { + template , class Scheme, class Policy, + class Signature, class Input> + [[nodiscard]] boost::system::result verify([[maybe_unused]] Scheme signing_scheme, + [[maybe_unused]] Policy verification_policy, + Signature const& signature_value, + Input const& message_input) const noexcept { secure::timing_guard const timing_scope; static_assert( std::is_same_v, @@ -264,71 +250,103 @@ class public_key { 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) { + if constexpr (!std::is_same_v || + detail::asynchronous_backend_v) { + // Never compiled into a program: an assertion above stopped the build. + return error::invalid_signature; + } else if constexpr (!detail::check_policy()) { + // Never compiled into a program: check_policy stopped the build. + return error::invalid_signature; + } else { 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::signing_schemes::eddsa`'s: - * `crypto::verify(crypto::signing_schemes::eddsa_prehashed, ...)`, of which it is the member - * form, with the same work, results and refusals. + * under a verification policy, as `crypto::signing_schemes::eddsa`'s: + * `crypto::verify(crypto::signing_schemes::eddsa_prehashed, + * crypto::verification_policies::canonical, ...)`, 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 Policy `crypto::verification_policies::canonical_t` (libsodium's rules), the only + * policy Ed25519ph takes; anything else stops the build. * @tparam Signature `curves::ed25519::signature`; another type, bytes included, stops the * build. * @tparam Input `crypto::signing_schemes::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::signing_schemes::eddsa_prehashed`. + * @param verification_policy `crypto::verification_policies::canonical`. * @param signature_value The signature; bytes from a peer are made into one by * `curves::ed25519::signature::from_bytes`. * @param digest_input `crypto::signing_schemes::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> + template , class Policy, class Signature, + class Input> [[nodiscard]] boost::system::result verify( [[maybe_unused]] signing_schemes::eddsa_prehashed_t signing_scheme, - Signature const& signature_value, Input const& digest_input, - [[maybe_unused]] Policy verify_policy = Policy{}) const noexcept { + [[maybe_unused]] Policy verification_policy, Signature const& signature_value, + Input const& digest_input) const noexcept { secure::timing_guard const timing_scope; if constexpr (detail::asynchronous_backend_v) { detail::refuse_ed25519ph_on_asynchronous_backend(); - } - if constexpr (!detail::asynchronous_backend_v) { + // Never compiled into a program: the assertion above stopped the build. + return error::invalid_signature; + } else if constexpr (!detail::check_policy()) { + // Never compiled into a program: check_policy stopped the build. + return error::invalid_signature; + } else { 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 the - * free `crypto::async_verify`, with the same arguments and this key, which calls it. + * Stops the build: a `verify` of the arity before the verification policies, + * `key.verify(scheme, signature, input)`, with no policy after the scheme; the message names + * the policy of the scheme, `crypto::verification_policies::canonical`. + * + * @tparam Backend The backend; by default the family's. + * @tparam Scheme A scheme tag. + * @tparam Signature The signature's type, which is no policy. + * @tparam Input The input's type. + * @param signing_scheme The scheme. + * @param signature_value The signature. + * @param signing_input The message or the marker. + * @return Never: the call does not compile. + */ + template , class Scheme, class Signature, + class Input> + requires(detail::is_scheme_v && !detail::is_policy_v) + [[nodiscard]] boost::system::result verify( + [[maybe_unused]] Scheme signing_scheme, [[maybe_unused]] Signature const& signature_value, + [[maybe_unused]] Input const& signing_input) const noexcept { + detail::refuse_missing_policy(); + return error::invalid_signature; + } + + /** + * Verifies an Ed25519 signature with this key under a verification policy, 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. * - * The message's bytes are the caller's until the completion; the signature and the key are - * copied. + * The policy is a policy tag, checked before anything else but the scheme. 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 @@ -340,6 +358,8 @@ class public_key { * @tparam Scheme `crypto::signing_schemes::eddsa_t`, or * `crypto::signing_schemes::eddsa_prehashed_t` on a native backend; another scheme stops the * build. + * @tparam Policy `crypto::verification_policies::canonical_t`, the only policy Ed25519 takes; + * anything else 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 @@ -349,6 +369,7 @@ class public_key { * @param completion_executor The executor the completion is posted to. * @param signing_scheme `crypto::signing_schemes::eddsa` or * `crypto::signing_schemes::eddsa_prehashed`. + * @param verification_policy `crypto::verification_policies::canonical`. * @param signature_value The signature. * @param message_input The signed bytes, or the marker of their SHA-512, the caller's until the * completion. @@ -357,50 +378,38 @@ class public_key { * @return What the completion token's `async_result` gives. */ template , class Executor, - class Scheme, class Signature, class Input, class CompletionToken> + class Scheme, class Policy, class Signature, class Input, class CompletionToken> auto async_verify(Executor const& completion_executor, Scheme signing_scheme, - Signature const& signature_value, Input const& message_input, - CompletionToken&& completion_token) const; + Policy verification_policy, Signature const& signature_value, + Input const& message_input, CompletionToken&& completion_token) const; /** - * Verifies an Ed25519 signature with this key under the verification policy given, - * 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 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 - * "deduced return type used before it is defined". + * Stops the build: an `async_verify` of the arity before the verification policies, + * `key.async_verify(executor, scheme, signature, input, token)`, with no policy after the + * scheme; the message names the policy of the scheme. * - * @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::signing_schemes::eddsa_t`, or - * `crypto::signing_schemes::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::signing_schemes::eddsa`; `crypto::signing_schemes::prehashed<64>` under - * `crypto::signing_schemes::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::signing_schemes::eddsa` or - * `crypto::signing_schemes::eddsa_prehashed`. + * @tparam Backend The backend; by default the asynchronous family's. + * @tparam Executor The executor's type. + * @tparam Scheme A scheme tag. + * @tparam Signature The signature's type, which is no policy. + * @tparam Input The input's type. + * @tparam CompletionToken The completion token's type. + * @param completion_executor The executor. + * @param signing_scheme The scheme. * @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. + * @param signing_input The message or the marker. + * @param completion_token The completion token. */ template , class Executor, class Scheme, class Signature, class Input, class CompletionToken> - auto async_verify(Executor const& completion_executor, Scheme signing_scheme, - Signature const& signature_value, Input const& message_input, - strict_t verify_policy, CompletionToken&& completion_token) const; + requires(detail::is_scheme_v && !detail::is_policy_v) + 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]] CompletionToken&& completion_token) const { + detail::refuse_missing_policy(); + } /** * The X25519 public key of this key (the birational map from edwards25519 to Curve25519), so @@ -937,7 +946,8 @@ class prehashed_signer { } /** - * Verifies a signature of the message given, which it ends, strictly (design D31). + * Verifies a signature of the message given, which it ends, under libsodium's rules, as + * `crypto::verification_policies::canonical` verifies (design D9). * * @tparam Signature `curves::ed25519::signature`; another type, bytes included, stops the * build. @@ -982,54 +992,58 @@ class prehashed_signer { namespace webcpp::crypto { /** - * Verifies an Ed25519 signature (RFC 8032's pure Ed25519) under a verification policy (design - * D31). + * Verifies an Ed25519 signature (RFC 8032's pure Ed25519) under a verification policy (design D9), + * `crypto::verification_policies::canonical`: libsodium's rules. * - * 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. + * The scheme and the policy come first, then the signature, and both the signature and the key + * are typed (design R1, R17, R27): the arguments of another order 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 Policy `crypto::verification_policies::canonical_t` (libsodium's rules), the only policy + * Ed25519 takes; anything else 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::signing_schemes::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::signing_schemes::eddsa`. + * @param verification_policy `crypto::verification_policies::canonical`. * @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 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> +template , class Policy, class Signature, + class Input> [[nodiscard]] boost::system::result verify( - [[maybe_unused]] signing_schemes::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 { + [[maybe_unused]] signing_schemes::eddsa_t signing_scheme, + [[maybe_unused]] Policy verification_policy, Signature const& signature_value, + Input const& message_input, curves::ed25519::public_key const& public_key) noexcept { secure::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) { + if constexpr (detail::asynchronous_backend_v) { + // Never compiled into a program: the assertion above stopped the build. + return error::invalid_signature; + } else if constexpr (!detail::check_policy()) { + // Never compiled into a program: check_policy stopped the build. + return error::invalid_signature; + } else { auto const key_bytes = public_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::signing_schemes::prehashed{digest}`) under a verification policy, strictly as - * `crypto::signing_schemes::eddsa`'s. + * as `crypto::signing_schemes::prehashed{digest}`) under a verification policy, + * `crypto::verification_policies::canonical`, as `crypto::signing_schemes::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 @@ -1037,41 +1051,42 @@ template , class Signature, * Ed25519ph). * * @tparam Backend The backend; by default the family's. + * @tparam Policy `crypto::verification_policies::canonical_t` (libsodium's rules), the only policy + * Ed25519ph takes; anything else stops the build. * @tparam Signature `curves::ed25519::signature`; another type, bytes included, stops the build. * @tparam Input `crypto::signing_schemes::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::signing_schemes::eddsa_prehashed`. + * @param verification_policy `crypto::verification_policies::canonical`. * @param signature_value The signature; bytes from a peer are made into one by * `curves::ed25519::signature::from_bytes`. * @param digest_input `crypto::signing_schemes::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> +template , class Policy, class Signature, + class Input> [[nodiscard]] boost::system::result verify( [[maybe_unused]] signing_schemes::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 { + [[maybe_unused]] Policy verification_policy, Signature const& signature_value, + Input const& digest_input, curves::ed25519::public_key const& public_key) noexcept { secure::timing_guard const timing_scope; if constexpr (detail::asynchronous_backend_v) { detail::refuse_ed25519ph_on_asynchronous_backend(); - } - if constexpr (!detail::asynchronous_backend_v) { + // Never compiled into a program: the assertion above stopped the build. + return error::invalid_signature; + } else if constexpr (!detail::check_policy()) { + // Never compiled into a program: check_policy stopped the build. + return error::invalid_signature; + } else { 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; } } @@ -1179,6 +1194,24 @@ struct signature_of +struct accepted_policies { + /** The policies. */ + using type = policy_list; +}; + +/** + * `eddsa_prehashed` on an Ed25519 public key accepts `canonical` alone (design D9), as `eddsa`. + */ +template <> +struct accepted_policies { + /** The policies. */ + using type = policy_list; +}; + /** * `crypto::verify` of `eddsa` against an Ed25519 public key is Ed25519's, so that the catch-all * steps aside. diff --git a/include/webcpp/crypto/curves/p256.hpp b/include/webcpp/crypto/curves/p256.hpp index b22e3072..54a0dd1f 100644 --- a/include/webcpp/crypto/curves/p256.hpp +++ b/include/webcpp/crypto/curves/p256.hpp @@ -9,9 +9,10 @@ `secret()` gives back, or drawn from the system's generator, and a public key validated once, as SEC 1's uncompressed point; ECDSA over SHA-256 with RFC 6979's nonce, `key.sign(crypto::signing_schemes::ecdsa_sha256, input)` - and `crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, input, public_key)`, the - input a message, hashed inside, or `crypto::signing_schemes::prehashed{digest}`, the signature a - `curves::p256::ecdsa_signature`: signing gives low S, verification accepts high and low S; the + and `crypto::verify(crypto::signing_schemes::ecdsa_sha256, policy, signature, input, public_key)`, + the input a message, hashed inside, or `crypto::signing_schemes::prehashed{digest}`, the + signature a `curves::p256::ecdsa_signature`: signing gives low S, verification under + `crypto::verification_policies::low_s_only` accepts low S alone and under `any_s` both; 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. @@ -74,18 +75,47 @@ struct p256_ecdsa_signature_tag { }; /** - * 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. + * Whether a P-256 ECDSA signature passes the verification policy's check, made on the public + * signature before any backend call: r and s in range, 0 < r, s < n, under both policies, and + * under `low_s_only` s at most (n - 1) / 2 too (design D9). + * + * @tparam Policy `verification_policies::low_s_only_t` or `verification_policies::any_s_t`. + * @param signature_bytes The signature's 64 bytes, r then s. + * @return Whether the backend is to verify it; false is `invalid_signature`. + */ +template +[[nodiscard]] bool p256_policy_admits( + std::span signature_bytes) noexcept { + if (!p_curve_signature_in_range(signature_bytes)) { + return false; + } + if constexpr (std::is_same_v) { + return p_curve_low_s( + signature_bytes.template last()); + } else { + static_assert(std::is_same_v, + "webcpp::crypto: P-256 verifies under crypto::verification_policies::" + "low_s_only or any_s."); + return true; + } +} + +/** + * Verifies an ECDSA signature over SHA-256 with a P-256 point on `Backend` under `Policy`: the + * work of `basic_public_key::verify` and of `crypto::verify` of `ecdsa_sha256`, which hold the + * guard and have checked the policy. * * @tparam Backend The key's backend. + * @tparam Policy `verification_policies::low_s_only_t` or `verification_policies::any_s_t`. * @tparam Input A message or `crypto::signing_schemes::prehashed<32>`; anything else stops the * build. * @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 out of range or that does not verify. + * @return Nothing; `invalid_signature` for a signature out of range, a high S under `low_s_only`, + * both refused before the backend, and a signature that does not verify. */ -template +template [[nodiscard]] boost::system::result p256_verify( std::span signature_bytes, Input const& signing_input, @@ -93,15 +123,15 @@ template check_input(); if constexpr (input_valid_v) { using engine = p_curve_engine; + if (!p256_policy_admits(signature_bytes)) { + return error::invalid_signature; + } 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(signature_bytes)) { - return error::invalid_signature; - } if (!engine::verify(point_bytes, digest_bytes, signature_bytes)) { return error::invalid_signature; } @@ -199,28 +229,35 @@ class basic_public_key { } /** - * Verifies an ECDSA signature over SHA-256 with this key: - * `crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature_value, signing_input, key)`, - * of which it is the member form, with the same work, results and refusals. + * Verifies an ECDSA signature over SHA-256 with this key under a verification policy: + * `crypto::verify(crypto::signing_schemes::ecdsa_sha256, verification_policy, 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. + * Under `crypto::verification_policies::low_s_only` a high S is refused before any backend + * call, as a signature crypto made is checked; under `any_s` a high S and a low S are both + * accepted, as FIPS 186-5 and WebCrypto accept them, for a signature a browser or a passkey + * made. * * @tparam Scheme `crypto::signing_schemes::ecdsa_sha256_t`; another scheme stops the build. + * @tparam Policy `crypto::verification_policies::low_s_only_t` or `any_s_t`; anything else + * 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::signing_schemes::prehashed<32>`; anything else stops the build. * @param signing_scheme `crypto::signing_schemes::ecdsa_sha256`. + * @param verification_policy `crypto::verification_policies::low_s_only` or `any_s`. * @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::signing_schemes::prehashed{digest}`, its 32-byte SHA-256 digest. - * @return Nothing; `invalid_signature` for 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, a high S + * under `low_s_only`, and a signature that does not verify. */ - template + template [[nodiscard]] boost::system::result verify([[maybe_unused]] Scheme signing_scheme, + [[maybe_unused]] Policy verification_policy, Signature const& signature_value, Input const& signing_input) const noexcept { secure::timing_guard const timing_scope; @@ -230,25 +267,53 @@ class basic_public_key { 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::p256_verify( + if constexpr (!std::is_same_v || + detail::asynchronous_backend_v) { + // Never compiled into a program: an assertion above stopped the build. + return error::invalid_signature; + } else if constexpr (!detail::check_policy()) { + // Never compiled into a program: check_policy stopped the build. + return error::invalid_signature; + } else { + 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; } } /** - * 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. + * Stops the build: a `verify` of the arity before the verification policies, + * `key.verify(scheme, signature, input)`, with no policy after the scheme; the message names + * the policies `crypto::signing_schemes::ecdsa_sha256` takes on a P-256 key. + * + * @tparam Scheme A scheme tag. + * @tparam Signature The signature's type, which is no policy. + * @tparam Input The input's type. + * @param signing_scheme The scheme. + * @param signature_value The signature. + * @param signing_input The message or the marker. + * @return Never: the call does not compile. + */ + template + requires(detail::is_scheme_v && !detail::is_policy_v) + [[nodiscard]] boost::system::result verify( + [[maybe_unused]] Scheme signing_scheme, [[maybe_unused]] Signature const& signature_value, + [[maybe_unused]] Input const& signing_input) const noexcept { + detail::refuse_missing_policy(); + return error::invalid_signature; + } + + /** + * Verifies an ECDSA signature over SHA-256 with this key under a verification policy, + * 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. * * The key and the bytes the input views are the caller's until the completion; the signature - * is copied. + * is copied. On a backend that completes by itself, the engine gets the policy, and refuses a + * high S under `low_s_only` before the browser is called. * * 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 @@ -256,6 +321,8 @@ class basic_public_key { * * @tparam Executor The executor's type, an Asio executor (an `io_context`'s or a strand's). * @tparam Scheme `crypto::signing_schemes::ecdsa_sha256_t`; another scheme stops the build. + * @tparam Policy `crypto::verification_policies::low_s_only_t` or `any_s_t`; anything else + * 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, @@ -263,17 +330,47 @@ class basic_public_key { * @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::signing_schemes::ecdsa_sha256`. + * @param verification_policy `crypto::verification_policies::low_s_only` or `any_s`. * @param signature_value The signature, r then s (IEEE P1363, WebCrypto's form). * @param signing_input The signed message, or `crypto::signing_schemes::prehashed{digest}`, its * 32-byte SHA-256 digest. * @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. + * `invalid_signature` for an r or an s that is 0 or not below n, a high S under `low_s_only`, + * 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, - Signature const& signature_value, Input const& signing_input, - CompletionToken&& completion_token) const; + Policy verification_policy, Signature const& signature_value, + Input const& signing_input, CompletionToken&& completion_token) const; + + /** + * Stops the build: an `async_verify` of the arity before the verification policies, + * `key.async_verify(executor, scheme, signature, input, token)`, with no policy after the + * scheme; the message names the policies `crypto::signing_schemes::ecdsa_sha256` takes on a + * P-256 key. + * + * @tparam Executor The executor's type. + * @tparam Scheme A scheme tag. + * @tparam Signature The signature's type, which is no policy. + * @tparam Input The input's type. + * @tparam CompletionToken The completion token's type. + * @param completion_executor The executor. + * @param signing_scheme The scheme. + * @param signature_value The signature. + * @param signing_input The message or the marker. + * @param completion_token The completion token. + */ + template + requires(detail::is_scheme_v && !detail::is_policy_v) + 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]] CompletionToken&& completion_token) const { + detail::refuse_missing_policy(); + } /** * Whether two keys are the same point. @@ -780,47 +877,57 @@ template > namespace webcpp::crypto { /** - * Verifies an ECDSA signature over SHA-256 with a P-256 public key. + * Verifies an ECDSA signature over SHA-256 with a P-256 public key under a verification policy. * - * The key's own `verify` is its member form, with the same work. A high S and a low S are both - * accepted, as FIPS 186-5 and WebCrypto accept them (WebCrypto's own signatures may be high); a - * protocol that requires low S checks `curves::p256::is_low_s` too. + * The key's own `verify` is its member form, with the same work. Under + * `crypto::verification_policies::low_s_only` a high S is refused before any backend call: the + * policy of a signature crypto made, whose S is low. Under `any_s` a high S and a low S are both + * accepted, as FIPS 186-5 and WebCrypto accept them: the policy of a signature a browser's + * WebCrypto or a passkey made, whose S may be high. * * @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 Policy `crypto::verification_policies::low_s_only_t` or `any_s_t`; anything else stops + * the build. * @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::signing_schemes::prehashed<32>`; anything else stops the build. * @param signing_scheme `crypto::signing_schemes::ecdsa_sha256`. + * @param verification_policy `crypto::verification_policies::low_s_only` or `any_s`. * @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::signing_schemes::prehashed{digest}`, its 32-byte SHA-256 digest. * @param public_key The signer's public key. - * @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. + * @return Nothing; `invalid_signature` for an r or an s that is 0 or not below n, and a high S + * under `low_s_only`, 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]] signing_schemes::ecdsa_sha256_t signing_scheme, - Signature const& signature_value, Input const& signing_input, + [[maybe_unused]] Policy verification_policy, Signature const& signature_value, + Input const& signing_input, curves::p256::basic_public_key const& public_key) noexcept { secure::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( + if constexpr (detail::asynchronous_backend_v) { + // Never compiled into a program: the assertion above stopped the build. + return error::invalid_signature; + } else if constexpr (!detail::check_policy>()) { + // Never compiled into a program: check_policy stopped the build. + return error::invalid_signature; + } else { + 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; } } @@ -891,6 +998,19 @@ struct key_backend> { using type = Backend; }; +/** + * ECDSA over SHA-256 on a P-256 public key accepts `low_s_only` and `any_s` (design D9): the + * first for a signature crypto made, the second for WebCrypto's and a passkey's, whose S may be + * high. + * + * @tparam Backend The public key's backend. + */ +template +struct accepted_policies> { + /** The policies. */ + using type = policy_list; +}; + /** * `crypto::verify` of ECDSA over SHA-256 against a P-256 public key is P-256's, so that the * catch-all steps aside. diff --git a/include/webcpp/crypto/curves/secp256k1.hpp b/include/webcpp/crypto/curves/secp256k1.hpp index 255aa221..feb8dc54 100644 --- a/include/webcpp/crypto/curves/secp256k1.hpp +++ b/include/webcpp/crypto/curves/secp256k1.hpp @@ -14,8 +14,10 @@ needs `/third_party//xkcp`) and `crypto::signing_schemes::schnorr` (BIP340), the input a message or, for ECDSA, `crypto::signing_schemes::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 + `crypto::verify` of ECDSA against the public key, under + `crypto::verification_policies::low_s_only`, and of Schnorr against the public key or its + 32-byte x-only form, under `crypto::verification_policies::canonical`; `recover`, the signer's + key, under either recoverable scheme and `low_s_only`; 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. @@ -773,15 +775,20 @@ 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_value, signing_input, key)`, of which it is - * the member form, with the same work, results and refusals. + * Verifies a signature with this key under a verification policy, of ECDSA over SHA-256 or of + * BIP340's Schnorr (design R22, D9): `crypto::verify(signing_scheme, verification_policy, + * 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. + * ECDSA takes `crypto::verification_policies::low_s_only` alone, and refuses a high S, as + * libsecp256k1 refuses it; Schnorr takes `crypto::verification_policies::canonical` and reads + * the key's x-only form. * * @tparam Backend The backend, `backends::secp256k1`, the only one; another stops the build. * @tparam Scheme `crypto::signing_schemes::ecdsa_sha256_t` or * `crypto::signing_schemes::schnorr_t`; another scheme stops the build. + * @tparam Policy `crypto::verification_policies::low_s_only_t` for ECDSA, + * `crypto::verification_policies::canonical_t` for Schnorr; anything else 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, @@ -789,6 +796,8 @@ class public_key { * the build. * @param signing_scheme `crypto::signing_schemes::ecdsa_sha256` or * `crypto::signing_schemes::schnorr`. + * @param verification_policy `crypto::verification_policies::low_s_only` for ECDSA, + * `crypto::verification_policies::canonical` 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 @@ -796,9 +805,10 @@ class public_key { * @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 Signature, - class Input> + template , class Scheme, class Policy, + class Signature, class Input> [[nodiscard]] boost::system::result verify([[maybe_unused]] Scheme signing_scheme, + [[maybe_unused]] Policy verification_policy, Signature const& signature_value, Input const& signing_input) const noexcept { secure::timing_guard const timing_scope; @@ -813,24 +823,52 @@ class public_key { "crypto::signing_schemes::ecdsa_sha256_recoverable or a " "crypto::signing_schemes::ecdsa_keccak256_recoverable signature gives its key to " "curves::secp256k1::recover."); - if constexpr (is_ecdsa) { + if constexpr (!is_ecdsa && !is_schnorr) { + // Never compiled into a program: an assertion above stopped the build. + return error::invalid_signature; + } else if constexpr (!webcpp::crypto::detail::check_policy()) { + // Never compiled into a program: check_policy stopped the build. + return error::invalid_signature; + } else if constexpr (is_ecdsa) { return webcpp::crypto::detail::secp256k1_verify_ecdsa( webcpp::crypto::detail::checked_signature_bytes( signature_value), signing_input, point_value_); - } else if constexpr (is_schnorr) { + } else { return webcpp::crypto::detail::secp256k1_verify_schnorr_key( 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; } } + /** + * Stops the build: a `verify` of the arity before the verification policies, + * `key.verify(scheme, signature, input)`, with no policy after the scheme; the message names + * the policy of the scheme on a secp256k1 key. + * + * @tparam Backend The backend. + * @tparam Scheme A scheme tag. + * @tparam Signature The signature's type, which is no policy. + * @tparam Input The input's type. + * @param signing_scheme The scheme. + * @param signature_value The signature. + * @param signing_input The message or the marker. + * @return Never: the call does not compile. + */ + template , class Scheme, class Signature, + class Input> + requires(webcpp::crypto::detail::is_scheme_v && + !webcpp::crypto::detail::is_policy_v) + [[nodiscard]] boost::system::result verify( + [[maybe_unused]] Scheme signing_scheme, [[maybe_unused]] Signature const& signature_value, + [[maybe_unused]] Input const& signing_input) const noexcept { + webcpp::crypto::detail::refuse_missing_policy(); + return error::invalid_signature; + } + /** * Equal when the points are equal. * @@ -1502,14 +1540,16 @@ inline curves::secp256k1::public_key secp256k1_access::make_public_key() noexcep /** * 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. + * each `recover` holds the guard and has checked the policy, `low_s_only`. * - * A high S is accepted, as libsecp256k1's recovery and Ethereum's `ecrecover` accept it. + * A high S is refused before recovery (design R28), which libsecp256k1's recovery and Ethereum's + * `ecrecover` would accept: `secp256k1_ecdsa_signature_normalize` on the compact signature, with no + * output, says whether S is high. * * @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. + * group order, a high S, or a signature from which no key is recovered. */ [[nodiscard]] inline boost::system::result secp256k1_recovered( std::array const& signature_bytes, @@ -1521,6 +1561,13 @@ inline curves::secp256k1::public_key secp256k1_access::make_public_key() noexcep return error::invalid_signature; } secp256k1_selftest(); + secp256k1_ecdsa_signature compact_value{}; + if (secp256k1_ecdsa_signature_parse_compact(secp256k1_context_static, &compact_value, + signature_bytes.data()) == 0 || + secp256k1_ecdsa_signature_normalize(secp256k1_context_static, nullptr, &compact_value) != + 0) { + return error::invalid_signature; + } secp256k1_ecdsa_recoverable_signature parsed_value{}; curves::secp256k1::public_key recovered_key = secp256k1_access::make_public_key(); if (secp256k1_ecdsa_recoverable_signature_parse_compact( @@ -1540,28 +1587,41 @@ namespace webcpp::crypto::curves::secp256k1 { * The public key that made a recoverable signature (`secp256k1_ecdsa_recover`) of ECDSA over * SHA-256: the same inputs as `sign(crypto::signing_schemes::ecdsa_sha256_recoverable, ...)`. * + * It takes `crypto::verification_policies::low_s_only` alone (design R28): a high S is + * `invalid_signature` before recovery; `low_s()` makes a high one low, flipping the recovery id, + * and keeps the signer. + * * 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 Policy `crypto::verification_policies::low_s_only_t`; anything else stops the build. * @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::signing_schemes::prehashed<32>`; anything else stops the build. * @param signing_scheme `crypto::signing_schemes::ecdsa_sha256_recoverable`. + * @param verification_policy `crypto::verification_policies::low_s_only`. * @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::signing_schemes::prehashed{digest}`, 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. + * group order, a high S, or a signature from which no key is recovered. */ -template , class Signature, class Input> +template , class Policy, class Signature, + class Input> [[nodiscard]] boost::system::result recover( [[maybe_unused]] signing_schemes::ecdsa_sha256_recoverable_t signing_scheme, - Signature const& signature_value, Input const& signing_input) noexcept { + [[maybe_unused]] Policy verification_policy, Signature const& signature_value, + Input const& signing_input) noexcept { secure::timing_guard const timing_scope; static_assert(webcpp::crypto::detail::secp256k1_refuses_others); + if constexpr (!detail::check_policy()) { + // Never compiled into a program: check_policy stopped the build. + return error::invalid_signature; + } auto const& signature_bytes = detail::checked_signature_bytes< recoverable_signature, signing_schemes::ecdsa_sha256_recoverable_t>(signature_value); detail::check_input(); @@ -1584,33 +1644,44 @@ template , class Signatur * 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. + * It takes `crypto::verification_policies::low_s_only` alone (design R28): a high S is + * `invalid_signature` before recovery, as EIP-2 refuses one in a transaction, although + * Ethereum's `ecrecover` precompile accepts it; a program recovering such a signature makes it + * low first with `low_s()`, which flips the recovery id and keeps the signer. * * 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 Policy `crypto::verification_policies::low_s_only_t`; anything else stops the build. * @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::signing_schemes::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::signing_schemes::ecdsa_keccak256_recoverable`. + * @param verification_policy `crypto::verification_policies::low_s_only`. * @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::signing_schemes::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. + * group order, a high S, or a signature from which no key is recovered. */ -template , class Signature, class Input> +template , class Policy, class Signature, + class Input> [[nodiscard]] boost::system::result recover( [[maybe_unused]] signing_schemes::ecdsa_keccak256_recoverable_t signing_scheme, - Signature const& signature_value, Input const& signing_input) noexcept { + [[maybe_unused]] Policy verification_policy, Signature const& signature_value, + Input const& signing_input) noexcept { secure::timing_guard const timing_scope; static_assert(webcpp::crypto::detail::secp256k1_refuses_others); + if constexpr (!detail::check_policy()) { + // Never compiled into a program: check_policy stopped the build. + return error::invalid_signature; + } auto const& signature_bytes = detail::checked_signature_bytes< recoverable_signature, signing_schemes::ecdsa_keccak256_recoverable_t>(signature_value); detail::check_input(); @@ -1624,6 +1695,30 @@ template , class Signatur } } +/** + * Stops the build: a `recover` of the arity before the verification policies, + * `recover(scheme, signature, input)`, with no policy after the scheme; the message names the + * policy `recover` takes, `crypto::verification_policies::low_s_only`. + * + * @tparam Backend The backend. + * @tparam Scheme A scheme tag. + * @tparam Signature The signature's type, which is no policy. + * @tparam Input The input's type. + * @param signing_scheme The scheme. + * @param signature_value The signature. + * @param signing_input The message or the marker. + * @return Never: the call does not compile. + */ +template , class Scheme, class Signature, + class Input> + requires(detail::is_scheme_v && !detail::is_policy_v) +[[nodiscard]] boost::system::result recover( + [[maybe_unused]] Scheme signing_scheme, [[maybe_unused]] Signature const& signature_value, + [[maybe_unused]] Input const& signing_input) noexcept { + detail::refuse_missing_policy(); + return error::invalid_signature; +} + /** * Encodes a compact ECDSA signature as strict DER (BIP66), with libsecp256k1's own encoder. * @@ -1791,15 +1886,18 @@ namespace webcpp::crypto { * Verifies an ECDSA signature over SHA-256 with a secp256k1 public key, with libsecp256k1's * static context, which allocates nothing, after its self-test. * - * A high S is refused, as libsecp256k1 refuses it (Bitcoin's policy); `sign` gives low S, and + * It takes `crypto::verification_policies::low_s_only` alone (design D9): a high S is refused, as + * libsecp256k1 refuses it (Bitcoin's policy); `sign` gives low S, and * `curves::secp256k1::normalize_low_s` makes a high one low. * * @tparam Backend The backend, `backends::secp256k1`, the only one; another stops the build. + * @tparam Policy `crypto::verification_policies::low_s_only_t`; anything else 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::signing_schemes::prehashed<32>`; anything else stops the build. * @param signing_scheme `crypto::signing_schemes::ecdsa_sha256`. + * @param verification_policy `crypto::verification_policies::low_s_only`. * @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 @@ -1809,29 +1907,39 @@ namespace webcpp::crypto { * @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 Signature, class Input> +template , class Policy, class Signature, + class Input> [[nodiscard]] boost::system::result verify( [[maybe_unused]] signing_schemes::ecdsa_sha256_t signing_scheme, - Signature const& signature_value, Input const& signing_input, - curves::secp256k1::public_key const& public_key) noexcept { + [[maybe_unused]] Policy verification_policy, Signature const& signature_value, + Input const& signing_input, curves::secp256k1::public_key const& public_key) noexcept { secure::timing_guard const timing_scope; static_assert(detail::secp256k1_refuses_others); - return detail::secp256k1_verify_ecdsa( - detail::checked_signature_bytes(signature_value), - signing_input, detail::secp256k1_access::point(public_key)); + if constexpr (!detail::check_policy()) { + // Never compiled into a program: check_policy stopped the build. + return error::invalid_signature; + } else { + return detail::secp256k1_verify_ecdsa( + detail::checked_signature_bytes(signature_value), + signing_input, detail::secp256k1_access::point(public_key)); + } } /** - * Verifies a BIP340 signature with libsecp256k1's static context, which allocates nothing, after - * its self-test (`include/secp256k1.h:235-247`). + * Verifies a BIP340 signature under `crypto::verification_policies::canonical`, BIP340's + * verification, with libsecp256k1's static context, which allocates nothing, after its self-test + * (`include/secp256k1.h:235-247`). * * @tparam Backend The backend, `backends::secp256k1`, the only one; another stops the build. + * @tparam Policy `crypto::verification_policies::canonical_t`; anything else 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::signing_schemes::prehashed` marker, or anything else, stops the build. * @param signing_scheme `crypto::signing_schemes::schnorr`. + * @param verification_policy `crypto::verification_policies::canonical`. * @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. @@ -1840,12 +1948,19 @@ template , class Signatur * @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 Signature, class Input> +template , class Policy, class Signature, + class Input> [[nodiscard]] boost::system::result verify( - [[maybe_unused]] signing_schemes::schnorr_t signing_scheme, Signature const& signature_value, + [[maybe_unused]] signing_schemes::schnorr_t signing_scheme, + [[maybe_unused]] Policy verification_policy, Signature const& signature_value, Input const& message_input, std::span xonly_public_key) noexcept { secure::timing_guard const timing_scope; static_assert(detail::secp256k1_refuses_others); + if constexpr (!detail::check_policy>()) { + // Never compiled into a program: check_policy stopped the build. + return error::invalid_signature; + } auto const& signature_bytes = detail::checked_signature_bytes(signature_value); @@ -1867,32 +1982,42 @@ template , class Signatur } /** - * Verifies a BIP340 signature against a secp256k1 public key, whose x-only form BIP340 reads - * (the parity of y is dropped), with libsecp256k1's static context, which allocates nothing, - * after its self-test. + * Verifies a BIP340 signature under `crypto::verification_policies::canonical`, BIP340's + * verification, against a secp256k1 public key, whose x-only form BIP340 reads (the parity of y is + * dropped), with libsecp256k1's static context, which allocates nothing, after its self-test. * * @tparam Backend The backend, `backends::secp256k1`, the only one; another stops the build. + * @tparam Policy `crypto::verification_policies::canonical_t`; anything else 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::signing_schemes::prehashed` marker, or anything else, stops the build. * @param signing_scheme `crypto::signing_schemes::schnorr`. + * @param verification_policy `crypto::verification_policies::canonical`. * @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 that does not verify. */ -template , class Signature, class Input> +template , class Policy, class Signature, + class Input> [[nodiscard]] boost::system::result verify( - [[maybe_unused]] signing_schemes::schnorr_t signing_scheme, Signature const& signature_value, + [[maybe_unused]] signing_schemes::schnorr_t signing_scheme, + [[maybe_unused]] Policy verification_policy, Signature const& signature_value, Input const& message_input, curves::secp256k1::public_key const& public_key) noexcept { secure::timing_guard const timing_scope; static_assert(detail::secp256k1_refuses_others); - return detail::secp256k1_verify_schnorr_key( - detail::checked_signature_bytes(signature_value), - message_input, detail::secp256k1_access::point(public_key)); + if constexpr (!detail::check_policy()) { + // Never compiled into a program: check_policy stopped the build. + return error::invalid_signature; + } else { + return detail::secp256k1_verify_schnorr_key( + detail::checked_signature_bytes(signature_value), + message_input, detail::secp256k1_access::point(public_key)); + } } } // namespace webcpp::crypto @@ -2056,6 +2181,58 @@ struct key_backend { using type = backends::secp256k1; }; +/** + * ECDSA over SHA-256 on a secp256k1 public key accepts `low_s_only` alone (design D9): + * libsecp256k1's rule, Bitcoin's. + */ +template <> +struct accepted_policies { + /** The policies. */ + using type = policy_list; +}; + +/** + * BIP340's Schnorr on a secp256k1 public key accepts `canonical` alone (design D9): BIP340's + * verification, which accepts only r below p and s below n. + */ +template <> +struct accepted_policies { + /** The policies. */ + using type = policy_list; +}; + +/** + * BIP340's Schnorr on a 32-byte x-only key accepts `canonical` alone, as on the typed key. + * + * @tparam Key The public key's type. + */ +template + requires std::is_convertible_v> +struct accepted_policies { + /** The policies. */ + using type = policy_list; +}; + +/** + * `recover` under ECDSA over SHA-256 with the recovery id accepts `low_s_only` alone (design + * R28): a high S is refused before recovery. It has no key: `void` stands for the one it gives. + */ +template <> +struct accepted_policies { + /** The policies. */ + using type = policy_list; +}; + +/** + * `recover` under Ethereum's recoverable ECDSA over Keccak-256 accepts `low_s_only` alone (design + * R28), as EIP-2 for a transaction. + */ +template <> +struct accepted_policies { + /** The policies. */ + using type = policy_list; +}; + /** * `crypto::verify` of ECDSA over SHA-256 against a secp256k1 public key is secp256k1's, so that * the catch-all steps aside. diff --git a/include/webcpp/crypto/curves/secp256k1/musig.hpp b/include/webcpp/crypto/curves/secp256k1/musig.hpp index f08f33f4..6e38fae1 100644 --- a/include/webcpp/crypto/curves/secp256k1/musig.hpp +++ b/include/webcpp/crypto/curves/secp256k1/musig.hpp @@ -559,8 +559,8 @@ template > /** * The BIP 340 signature of the partial signatures (`secp256k1_musig_partial_sig_agg`), which - * `crypto::verify(crypto::signing_schemes::schnorr, signature, message, key)` checks under - * `aggregate_key::xonly_public_key()`. + * `crypto::verify(crypto::signing_schemes::schnorr, crypto::verification_policies::canonical, + * signature, message, key)` checks under `aggregate_key::xonly_public_key()`. * * @tparam Backend The backend, `backends::secp256k1`. * @param signing_session The session of the message. diff --git a/include/webcpp/crypto/detail/signature.hpp b/include/webcpp/crypto/detail/signature.hpp index 3d79dbab..cf2deab2 100644 --- a/include/webcpp/crypto/detail/signature.hpp +++ b/include/webcpp/crypto/detail/signature.hpp @@ -55,7 +55,7 @@ class basic_signature { /** * Makes a signature from its bytes, as a peer sends them. The size alone is checked (design * R2): whether the values it holds are in range is verification's judgment, so a signature - * `verify` refuses may still be made, normalised and refused with its curve's policy. + * `verify` refuses may still be made, normalised and refused under its verification policy. * * @param signature_bytes `size` bytes. * @return The signature; `invalid_signature` for another size. diff --git a/include/webcpp/crypto/signing.hpp b/include/webcpp/crypto/signing.hpp index 57066db7..fec61aa0 100644 --- a/include/webcpp/crypto/signing.hpp +++ b/include/webcpp/crypto/signing.hpp @@ -8,11 +8,18 @@ What every curve's signing shares (design D1 to D3): the scheme tags, `eddsa`, `eddsa_prehashed`, `ecdsa_sha256`, `ecdsa_sha256_recoverable`, `ecdsa_keccak256_recoverable` and `schnorr`, all in the namespace `crypto::signing_schemes`, and the library's one list of them, - `detail::all_schemes`; the marker of a digest, `signing_schemes::prehashed{digest}`; the - concepts `can_sign` and `can_verify`, which say which key, scheme, signature and input go - together; `detail::check_signature` and `detail::checked_signature_bytes`, which stop a `verify` or - a `recover` given a signature of another curve or scheme, naming the type expected (design R1); - and the catch-all of `verify`, which stops the build with what goes together. The free + `detail::all_schemes`; the verification policies, `low_s_only`, `any_s` and `canonical`, in the + namespace `crypto::verification_policies`, their one list, `detail::all_policies`, and + `detail::accepted_policies`, which each curve specialises beside its verifier with the policies + each scheme takes on its keys (design D9); the marker of a digest, + `signing_schemes::prehashed{digest}`; the concepts `can_sign` and `can_verify`, which say which + key, scheme, policy, signature and input go together; `detail::check_policy`, which stops a + `verify`, an `async_verify` or a `recover` given a policy its scheme does not take, naming the + ones it takes, and `detail::check_signature` and `detail::checked_signature_bytes`, which stop one + given a signature of another curve or scheme, naming the type expected (design R1); and the + catch-alls of `verify`, which stop the build with what goes together, and with the policies of + the scheme when the call has none. Every verification takes its policy second, after the scheme: + `verify(scheme, policy, signature, input, public_key)` (design R27). The free synchronous `sign(key_pair, scheme, input)`, the key pair's `sign` (design D9), is in `keypair.hpp`, constrained by `crypto::signing_keypair`. @@ -158,6 +165,115 @@ inline constexpr bool is_scheme_v = in_scheme_list_v; } // namespace detail +namespace verification_policies { + +/** + * The type of @ref low_s_only, ECDSA's verification that refuses a high S. + * + * Its explicit default constructor keeps `{}` from standing for a policy. + */ +struct low_s_only_t { + /** Makes the tag; explicit, so that only its name makes one. */ + explicit low_s_only_t() = default; +}; + +/** + * The type of @ref any_s, ECDSA's verification that accepts a valid signature whatever its S. + * + * Its explicit default constructor keeps `{}` from standing for a policy. + */ +struct any_s_t { + /** Makes the tag; explicit, so that only its name makes one. */ + explicit any_s_t() = default; +}; + +/** + * The type of @ref canonical, the verification of Ed25519 and of BIP340 that accepts only + * canonical encodings. + * + * Its explicit default constructor keeps `{}` from standing for a policy. + */ +struct canonical_t { + /** Makes the tag; explicit, so that only its name makes one. */ + explicit canonical_t() = default; +}; + +} // namespace verification_policies + +namespace detail { + +/** + * A list of verification policy tags: the library's own, and the ones a scheme accepts on a key. + * + * @tparam Policies Policy tags. + */ +template +struct policy_list {}; + +/** + * The library's one list of verification policies, every policy tag: `is_policy_v` takes it from + * this list. + */ +using all_policies = + policy_list; + +/** + * Whether `Type` is a member of the list `List`: false for a type that is not a `policy_list`. + * + * @tparam Type Any type. + * @tparam List A `policy_list`. + */ +template +inline constexpr bool in_policy_list_v = false; + +/** + * Whether `Type` is one of `Policies`. + * + * @tparam Type Any type. + * @tparam Policies The list's policy tags. + */ +template +inline constexpr bool in_policy_list_v> = + (std::is_same_v || ...); + +/** + * Whether `Type` is one of the verification policy tags, a member of `all_policies`. + * + * @tparam Type Any type. + */ +template +inline constexpr bool is_policy_v = in_policy_list_v; + +/** + * The verification policies the scheme `Scheme` accepts on the public key `Key`: none here; each + * curve declares its own beside its verifier (design D9), `void` standing for the key a + * `recover` gives. The curve's header is included before a call or the trait names its keys. + * + * @tparam Scheme A scheme tag. + * @tparam Key The public key's type, without its reference and qualifiers, or `void` for + * `curves::secp256k1::recover`. + */ +template +struct accepted_policies { + /** The policies, none. */ + using type = policy_list<>; +}; + +/** + * Whether the scheme `Scheme` accepts the verification policy `Policy` on the key `Key`: when + * the policy is in the curve's `accepted_policies`. + * + * @tparam Policy The policy's type, or any type. + * @tparam Scheme A scheme tag. + * @tparam Key The public key's type, without its reference and qualifiers, or `void`. + */ +template +inline constexpr bool policy_accepted_v = + in_policy_list_v::type>; + +} // namespace detail + namespace signing_schemes { /** @@ -281,6 +397,32 @@ template prehashed(boost::hash2::digest const&) -> prehashed; } // namespace signing_schemes +namespace verification_policies { + +/** + * ECDSA's verification that refuses a signature whose S is above (n - 1) / 2, as + * `invalid_signature` before any backend call on P-256 and before recovery in + * `curves::secp256k1::recover`: Bitcoin's rule (BIP 146), Ethereum's for a transaction (EIP-2), and + * libsecp256k1's own. secp256k1's ECDSA, the recoverable schemes included, takes it alone; P-256's + * takes it or `any_s`. + */ +inline constexpr low_s_only_t low_s_only{}; + +/** + * ECDSA's verification that accepts a valid signature whatever its S, as FIPS 186-5 and + * WebCrypto do: P-256's, for a signature a browser or a passkey made, whose S may be high. + */ +inline constexpr any_s_t any_s{}; + +/** + * The verification of `eddsa`, `eddsa_prehashed` and `schnorr`, the only policy they take: for + * Ed25519, libsodium's rules, S below the group order, canonical encodings of R and A, neither of + * small order; for BIP340, its verification, which accepts only r below p and s below n. + */ +inline constexpr canonical_t canonical{}; + +} // namespace verification_policies + namespace detail { /** False for every type, so that a refusal's `static_assert` fires only when it is reached. */ @@ -731,6 +873,123 @@ template template inline constexpr bool has_verifier_v = false; +/** + * Whether the scheme is one of the two recoverable ones, which `curves::secp256k1::recover` takes. + * + * @tparam Scheme A scheme tag. + */ +template +inline constexpr bool is_recoverable_scheme_v = + std::is_same_v || + std::is_same_v; + +/** + * Whether `ecdsa_sha256` on the key `Key` accepts exactly the policies `List`: how a refusal + * tells P-256's key from secp256k1's without naming either curve. + * + * @tparam Key The public key's type. + * @tparam List A `policy_list`. + */ +template +inline constexpr bool ecdsa_accepts_v = + std::is_same_v::type, List>; + +/** + * Whether `Policy` is a policy `Scheme` accepts on `Key`, and, when it is not, stops the build with + * the message that names the policies the scheme accepts, one fixed text per row of design D9: + * every `verify`, `async_verify` and `recover`, member and free, asks it after its scheme and + * before the signature, and goes on only when it is true. The failed requirement of the static + * assertion, `policy_accepted_v`, names the three types. + * + * @tparam Policy The policy's type, without its reference and qualifiers, or any type. + * @tparam Scheme The scheme tag the call verifies or recovers under. + * @tparam Key The public key's type, or `void` for `curves::secp256k1::recover`. + * @return Whether the scheme accepts the policy on the key; false only in a build that stops. + */ +template +[[nodiscard]] constexpr bool check_policy() noexcept { + if constexpr (std::is_same_v || + std::is_same_v) { + static_assert(policy_accepted_v, + "webcpp::crypto: verify: crypto::signing_schemes::eddsa and eddsa_prehashed " + "take crypto::verification_policies::canonical."); + } else if constexpr (std::is_same_v) { + static_assert(policy_accepted_v, + "webcpp::crypto: verify: crypto::signing_schemes::schnorr takes " + "crypto::verification_policies::canonical."); + } else if constexpr (is_recoverable_scheme_v) { + static_assert(policy_accepted_v, + "webcpp::crypto: curves::secp256k1::recover takes " + "crypto::verification_policies::low_s_only."); + } else if constexpr (ecdsa_accepts_v>) { + static_assert( + policy_accepted_v, + "webcpp::crypto: verify: crypto::signing_schemes::ecdsa_sha256 on a P-256 key " + "takes crypto::verification_policies::low_s_only or any_s."); + } else if constexpr (ecdsa_accepts_v>) { + static_assert( + policy_accepted_v, + "webcpp::crypto: verify: crypto::signing_schemes::ecdsa_sha256 on a secp256k1 " + "key takes crypto::verification_policies::low_s_only."); + } else { + static_assert(refused_v, + "webcpp::crypto: check_policy: no row of policies for this scheme and key; a " + "curve or a scheme that adds a verifier adds its row."); + } + return policy_accepted_v; +} + +/** + * Stops the build: a `verify`, an `async_verify` or a `recover` of the arity before the policies, + * with no policy after the scheme. The message names the policies of the scheme, and of the key's + * curve for `ecdsa_sha256` (design D9; one fixed text per case), or all three for a key no curve + * declares a verifier for. + * + * @tparam Scheme The scheme tag given. + * @tparam Key The public key's type, or `void` for `curves::secp256k1::recover`. + */ +template +constexpr void refuse_missing_policy() noexcept { + if constexpr (std::is_same_v) { + static_assert(refused_v, + "webcpp::crypto: verify takes a verification policy after the scheme: " + "crypto::signing_schemes::eddsa takes " + "crypto::verification_policies::canonical."); + } else if constexpr (std::is_same_v) { + static_assert(refused_v, + "webcpp::crypto: verify takes a verification policy after the scheme: " + "crypto::signing_schemes::eddsa_prehashed takes " + "crypto::verification_policies::canonical."); + } else if constexpr (std::is_same_v) { + static_assert(refused_v, + "webcpp::crypto: verify takes a verification policy after the scheme: " + "crypto::signing_schemes::schnorr takes " + "crypto::verification_policies::canonical."); + } else if constexpr (is_recoverable_scheme_v) { + static_assert(refused_v, + "webcpp::crypto: recover takes a verification policy after the scheme: " + "curves::secp256k1::recover takes " + "crypto::verification_policies::low_s_only."); + } else if constexpr (ecdsa_accepts_v>) { + static_assert(refused_v, + "webcpp::crypto: verify takes a verification policy after the scheme: " + "crypto::signing_schemes::ecdsa_sha256 on a P-256 key takes " + "crypto::verification_policies::low_s_only or any_s."); + } else if constexpr (ecdsa_accepts_v>) { + static_assert(refused_v, + "webcpp::crypto: verify takes a verification policy after the scheme: " + "crypto::signing_schemes::ecdsa_sha256 on a secp256k1 key takes " + "crypto::verification_policies::low_s_only."); + } else { + static_assert(refused_v, + "webcpp::crypto: verify takes a verification policy after the scheme: " + "crypto::verification_policies::low_s_only, any_s or canonical, as the " + "scheme accepts."); + } +} + } // namespace detail /** @@ -749,18 +1008,22 @@ concept can_sign = /** * Whether `crypto::verify` checks a signature of the type `Signature` and of `Scheme` over `Input` - * against `PublicKey`: when the key's curve has the scheme, the signature is the type of the - * key's curve and scheme (`curves::p256::ecdsa_signature` for a P-256 key, ...), and the input is - * a message, or a marker of the scheme's digest size on a backend that verifies one. + * against `PublicKey` under `Policy`: when the key's curve has the scheme, the scheme accepts the + * policy on that key (design D9), the signature is the type of the key's curve and scheme + * (`curves::p256::ecdsa_signature` for a P-256 key, ...), and the input is a message, or a marker + * of the scheme's digest size on a backend that verifies one. * * @tparam Scheme A scheme tag. + * @tparam Policy A verification policy's type. * @tparam Signature The signature's type. * @tparam Input The input's type: a message, or `prehashed`. * @tparam PublicKey The public key's type, a curve's type or bytes. */ -template +template concept can_verify = detail::verifies_with_v, Scheme> && + detail::policy_accepted_v, Scheme, + std::remove_cvref_t> && std::is_same_v, detail::signature_of_t, Scheme>> && detail::input_valid_v, @@ -773,21 +1036,23 @@ concept can_verify = * none of them is, and says which keys go with which scheme. * * @tparam Scheme A scheme tag. + * @tparam Policy The policy's type. * @tparam Signature The signature's type. * @tparam Input The input's type. * @tparam PublicKey The public key's type. * @param signing_scheme The scheme. + * @param verification_policy The policy. * @param signature_value The signature. * @param signing_input The message or the marker. * @param public_key The public key. * @return Never: the call does not compile. */ -template +template requires(detail::is_scheme_v && !detail::has_verifier_v>) [[nodiscard]] boost::system::result verify( - [[maybe_unused]] Scheme signing_scheme, [[maybe_unused]] Signature const& signature_value, - [[maybe_unused]] Input const& signing_input, + [[maybe_unused]] Scheme signing_scheme, [[maybe_unused]] Policy verification_policy, + [[maybe_unused]] Signature const& signature_value, [[maybe_unused]] Input const& signing_input, [[maybe_unused]] PublicKey const& public_key) noexcept { static_assert( detail::refused_v, @@ -802,6 +1067,58 @@ template return {}; } +/** + * Stops the build: a `verify` of the arity before the verification policies, + * `verify(scheme, signature, input, public_key)`, with no policy after the scheme. The message + * names the policies the scheme takes on the key (design D9). + * + * @tparam Scheme A scheme tag. + * @tparam Signature The signature's type, which is no policy. + * @tparam Input The input's type. + * @tparam PublicKey The public key's type. + * @param signing_scheme The scheme. + * @param signature_value The signature. + * @param signing_input The message or the marker. + * @param public_key The public key. + * @return Never: the call does not compile. + */ +template + requires(detail::is_scheme_v && !detail::is_policy_v) +[[nodiscard]] boost::system::result verify( + [[maybe_unused]] Scheme signing_scheme, [[maybe_unused]] Signature const& signature_value, + [[maybe_unused]] Input const& signing_input, + [[maybe_unused]] PublicKey const& public_key) noexcept { + detail::refuse_missing_policy>(); + return {}; +} + +/** + * Stops the build: a `verify` of the arity before the verification policies with its backend + * named first, `verify(scheme, signature, input, public_key)`, as the overload without + * the backend. + * + * @tparam Backend The backend named, which is no scheme. + * @tparam Scheme A scheme tag. + * @tparam Signature The signature's type, which is no policy. + * @tparam Input The input's type. + * @tparam PublicKey The public key's type. + * @param signing_scheme The scheme. + * @param signature_value The signature. + * @param signing_input The message or the marker. + * @param public_key The public key. + * @return Never: the call does not compile. + */ +template + requires(!detail::is_scheme_v && detail::is_scheme_v && + !detail::is_policy_v) +[[nodiscard]] boost::system::result verify( + [[maybe_unused]] Scheme signing_scheme, [[maybe_unused]] Signature const& signature_value, + [[maybe_unused]] Input const& signing_input, + [[maybe_unused]] PublicKey const& public_key) noexcept { + detail::refuse_missing_policy>(); + return {}; +} + } // namespace webcpp::crypto #endif // WEBCPP_CRYPTO_SIGNING_HPP diff --git a/meta/ed25519_cases.json b/meta/ed25519_cases.json index 421ecf6f..fa5c6879 100644 --- a/meta/ed25519_cases.json +++ b/meta/ed25519_cases.json @@ -1,6 +1,6 @@ {"source": {"repository": "novifinancial/ed25519-speccheck", "commit": "65519336", "file": "cases.json"}, "backends": {"sodium": {"raw": ["reject", "reject", "reject", "accept", "reject", "reject", "reject", "reject", "reject", "reject", "reject", "reject"], - "strict": ["reject", "reject", "reject", "accept", "reject", "reject", "reject", "reject", "reject", "reject", "reject", "reject"]}}, + "canonical": ["reject", "reject", "reject", "accept", "reject", "reject", "reject", "reject", "reject", "reject", "reject", "reject"]}}, "outside": {"webcrypto-node": {"node": "26.13.0", "openssl": "4.1.0", "verdicts": ["reject", "reject", "reject", "accept", "reject", "reject", "reject", "reject", "reject", "reject", "reject", "reject"]}}, "cases": ["`S` = 0, `A` and `R` of small order", diff --git a/test/Jamfile b/test/Jamfile index 6324eb79..c01d0b56 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -649,6 +649,20 @@ crypto-run ed25519_speccheck : ed25519_speccheck_test.cpp [ webcpp.data $(CRYPTO_TEST_META) ] ../meta/ed25519_cases.json emscripten:-sJSPI ; +# The verification policies (design D9): P-256's low_s_only and any_s on BearSSL, +# the RFC's high S and every Wycheproof P1363 case under both, a refusal before +# the engine; secp256k1's low_s_only against Wycheproof's Bitcoin and P1363 +# files; recover's low_s_only under both recoverable schemes; Ed25519's and +# BIP340's canonical; the asynchronous forms on Ed25519 and P-256. +crypto-run verification_policies : verification_policies_test.cpp + : /third_party//bearssl /third_party//secp256k1 + /third_party//xkcp /third_party//sodium + /third_party//wycheproof /third_party//bips + /third_party//ed25519-speccheck /webcpp/asio//asio + /webcpp//boost_json + "\"WEBCPP_TEST_CRYPTO_META=\\\"$(.crypto-meta)\\\"\"" + [ webcpp.data $(CRYPTO_TEST_META) ] + ../meta/ed25519_cases.json ; # X25519 on libsodium: RFC 7748's scalar multiplications and Alice and Bob, a # peer of order 8 refused as weak, the guards and the conversion from Ed25519; diff --git a/test/allocation_bearssl_test.cpp b/test/allocation_bearssl_test.cpp index 9eb12d2a..5e0fbe4a 100644 --- a/test/allocation_bearssl_test.cpp +++ b/test/allocation_bearssl_test.cpp @@ -65,10 +65,12 @@ void p256_calls() { !BOOST_TEST(key.has_value())) { return; } - BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signature, + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *signature, crypto::signing_schemes::prehashed{digest}, *key) .has_value()); - BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *of_message, digest, *key) + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *of_message, digest, *key) .has_value()); std::array der{}; auto const written = p256::to_der(*signature, der); diff --git a/test/allocation_sodium_test.cpp b/test/allocation_sodium_test.cpp index 043b2631..a16ff882 100644 --- a/test/allocation_sodium_test.cpp +++ b/test/allocation_sodium_test.cpp @@ -5,14 +5,14 @@ // https://www.boost.org/LICENSE_1_0.txt) // On libsodium nothing allocates: from_key, seal and open of the three ChaCha20-Poly1305 AEADs and -// of the two secret boxes, a failed open included; Ed25519's key pair, signature, strict -// verification, Ed25519ph and the conversion to X25519; X25519's public key and agreement, a -// refused one included; crypto_kx's key pairs, from a seed and from an X25519 key pair, and session -// keys, a refused peer included; RFC 8410's SPKI and PKCS#8 of both curves and their PEM, both -// ways; the two boxes' from_keys, seal and open, a refused peer key and a failed open included; and -// the sealed boxes' seal and open, a failed open included, make no call of operator new, nor of the -// C library's allocator where the target lets a program count it; a control proves the counter -// moves. Each later family on libsodium adds its calls here. +// of the two secret boxes, a failed open included; Ed25519's key pair, signature, +// verification under canonical, Ed25519ph and the conversion to X25519; X25519's public key and +// agreement, a refused one included; crypto_kx's key pairs, from a seed and from an X25519 key +// pair, and session keys, a refused peer included; RFC 8410's SPKI and PKCS#8 of both curves and +// their PEM, both ways; the two boxes' from_keys, seal and open, a refused peer key and a failed +// open included; and the sealed boxes' seal and open, a failed open included, make no call of +// operator new, nor of the C library's allocator where the target lets a program count it; a +// control proves the counter moves. Each later family on libsodium adds its calls here. #include #include @@ -103,9 +103,9 @@ void expect_no_allocation_ed25519() { // Strict verification on libsodium, named once: a call's commas would split a macro's // argument. auto const verify = [](auto const& signature, auto const& message, auto const& public_key) { - return crypto::verify(crypto::signing_schemes::eddsa, signature, - message, public_key, - crypto::curves::ed25519::strict); + return crypto::verify(crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, + signature, message, public_key); }; std::array seed{}; seed.fill(5); @@ -143,9 +143,9 @@ void expect_no_allocation_ed25519() { crypto::signing_schemes::prehashed{digest}); BOOST_TEST(scheme_signature.has_value() && *scheme_signature == *streamed_signature); BOOST_TEST(crypto::verify( - crypto::signing_schemes::eddsa_prehashed, *scheme_signature, - crypto::signing_schemes::prehashed{digest}, *public_key, - crypto::curves::ed25519::strict) + crypto::signing_schemes::eddsa_prehashed, + crypto::verification_policies::canonical, *scheme_signature, + crypto::signing_schemes::prehashed{digest}, *public_key) .has_value()); auto const converted_pair = made->to_x25519(); BOOST_TEST(converted_pair.has_value()); diff --git a/test/async_25519_test.cpp b/test/async_25519_test.cpp index 63bd50cd..6070e51e 100644 --- a/test/async_25519_test.cpp +++ b/test/async_25519_test.cpp @@ -5,11 +5,12 @@ // https://www.boost.org/LICENSE_1_0.txt) // Ed25519's and X25519's asynchronous functions on libsodium, on a callback and in a coroutine. -// async_sign and async_verify take the scheme, crypto::signing_schemes::eddsa, and the synchronous -// calls' inputs, the message and, for async_verify, the policy before the token, strict by default: +// async_sign and async_verify take the scheme, crypto::signing_schemes::eddsa, async_verify the +// policy after it, crypto::verification_policies::canonical, and the synchronous calls' inputs, the +// message: // - async_rfc8032: RFC 8032 section 7.1's tests 1, 2 and 3 through async_from_secret and async_sign // give the RFC's signatures and the synchronous ones, and async_verify accepts them, with the -// backend named and its policy given, and with the defaults; each completion arrives after the +// backend named and with the default; each completion arrives after the // initiating call returned. // - async_verify_changed: a changed byte of the signature or of the message completes with // invalid_signature; a signature of 63 bytes, and the key's bytes where the signature goes, as @@ -35,15 +36,15 @@ // free, synchronous and asynchronous, gives the same result: from_secret (the same public key, // and the same refusal of a short seed), generate (a key pair whose signature verifies), sign // (RFC 8032's signature, an ed25519::signature, and an empty key pair's invalid_state and -// zeros), verify with the defaults and with the backend and the policy named (each accepts the +// zeros), verify with the default backend and with the backend named (each accepts the // signature, received as a std::vector and made into the type with from_bytes, and refuses a // changed one with invalid_signature; from_bytes refuses 63 and 65 bytes with // invalid_signature); each asynchronous completion arrives after the initiating call returned. // - eddsa_prehashed_async: under crypto::signing_schemes::eddsa_prehashed, RFC 8032 section 7.3's -// key pair signs -// the marker of "abc"'s SHA-512 through key.async_sign and crypto::async_sign into the -// synchronous signature, which async_verify, member and free, accepts, with the defaults and with -// the backend and the policy named; each completion arrives after the initiating call returned. +// key pair signs the marker of "abc"'s SHA-512 through key.async_sign and crypto::async_sign into +// the synchronous signature, which async_verify, member and free, accepts, with the default +// backend and with the backend named; each completion arrives after the initiating call +// returned. #include #include @@ -240,14 +241,15 @@ void async_rfc8032(asio::io_context& context) { BOOST_TEST(signed_sync.has_value() && *signed_sync == signature); auto const verified = complete_code(context, [&](auto const& executor, auto&& token) { return crypto::async_verify( - executor, crypto::signing_schemes::eddsa, signature, message, public_key, - ed25519::strict, std::forward(token)); + executor, crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, + signature, message, public_key, std::forward(token)); }); BOOST_TEST(!verified); // The defaults name the same backend. auto const verified_default = complete_code(context, [&](auto const& executor, auto&& token) { - return crypto::async_verify(executor, crypto::signing_schemes::eddsa, signature, + return crypto::async_verify(executor, crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, signature, message, public_key, std::forward(token)); }); BOOST_TEST(!verified_default); @@ -262,9 +264,9 @@ void async_verify_changed(asio::io_context& context) { auto const verify = [&](ed25519::public_key const& key, std::span signed_bytes) { return complete_code(context, [&](auto const& executor, auto&& token) { - return crypto::async_verify(executor, crypto::signing_schemes::eddsa, - typed(signed_bytes), message, key, - std::forward(token)); + return crypto::async_verify( + executor, crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, + typed(signed_bytes), message, key, std::forward(token)); }); }; BOOST_TEST(!verify(public_key, signature)); @@ -299,7 +301,8 @@ void generated(asio::io_context& context) { return; } auto const verified_sync = crypto::verify( - crypto::signing_schemes::eddsa, *signature, message, *public_key, ed25519::strict); + crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, *signature, + message, *public_key); BOOST_TEST(verified_sync.has_value()); auto const signed_async = complete(context, [&](auto const& executor, auto&& token) { @@ -309,7 +312,8 @@ void generated(asio::io_context& context) { BOOST_TEST(!signed_async.code); BOOST_TEST(signed_async.value.has_value() && std::get<0>(*signed_async.value) == *signature); auto const verified = complete_code(context, [&](auto const& executor, auto&& token) { - return crypto::async_verify(executor, crypto::signing_schemes::eddsa, *signature, message, + return crypto::async_verify(executor, crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, *signature, message, *public_key, std::forward(token)); }); BOOST_TEST(!verified); @@ -542,8 +546,8 @@ void async_coroutine(asio::io_context& context) { BOOST_TEST(!sign_code); BOOST_TEST(std::ranges::equal(signature.bytes(), test::from_hex(tested.signature))); auto [verify_code] = co_await crypto::async_verify( - executor, crypto::signing_schemes::eddsa, signature, message, public_key, - asio::as_tuple(asio::use_awaitable)); + executor, crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, + signature, message, public_key, asio::as_tuple(asio::use_awaitable)); BOOST_TEST(!verify_code); auto generate_code_result = co_await crypto::async_generate(executor, asio::as_tuple(asio::use_awaitable)); @@ -607,7 +611,9 @@ bool signs_and_verifies(keypair const& key) { auto const signature = key.sign(crypto::signing_schemes::eddsa, message); auto const own = key.public_key(); return signature.has_value() && own.has_value() && - own->verify(crypto::signing_schemes::eddsa, *signature, message).has_value(); + own->verify(crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, + *signature, message) + .has_value(); } // generate in its four forms: each a key pair whose signature verifies. @@ -667,8 +673,7 @@ void check_four_signatures(asio::io_context& context, keypair const& key, BOOST_TEST(std::get<0>(*free_async.value) == *member_sync); } -// verify in its four forms, with the defaults and with the backend and the policy named: the -// same answer. +// verify in its four forms, with the default backend and with the backend named: the same answer. void check_four_verifications(asio::io_context& context, ed25519::public_key const& key, signature_type const& signature, std::span message, @@ -677,30 +682,38 @@ void check_four_verifications(asio::io_context& context, ed25519::public_key con auto const code_of = [](boost::system::result const& done) { return done ? boost::system::error_code{} : done.error(); }; - BOOST_TEST(code_of(key.verify(crypto::signing_schemes::eddsa, signature, message)) == - expected_code); - BOOST_TEST(code_of(key.verify(crypto::signing_schemes::eddsa, signature, message, - ed25519::strict)) == expected_code); - BOOST_TEST(code_of(crypto::verify(crypto::signing_schemes::eddsa, signature, message, key)) == + BOOST_TEST(code_of(key.verify(crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, signature, message)) == expected_code); - BOOST_TEST(code_of(crypto::verify(crypto::signing_schemes::eddsa, signature, message, - key, ed25519::strict)) == expected_code); + BOOST_TEST(code_of(key.verify(crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, signature, + message)) == expected_code); + BOOST_TEST(code_of(crypto::verify(crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, signature, message, + key)) == expected_code); + BOOST_TEST(code_of(crypto::verify(crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, signature, + message, key)) == expected_code); BOOST_TEST(complete_code(context, [&](auto const& executor, auto&& token) { - return key.async_verify(executor, crypto::signing_schemes::eddsa, signature, + return key.async_verify(executor, crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, signature, message, std::forward(token)); }) == expected_code); BOOST_TEST(complete_code(context, [&](auto const& executor, auto&& token) { return key.async_verify(executor, crypto::signing_schemes::eddsa, - signature, message, ed25519::strict, + crypto::verification_policies::canonical, + signature, message, std::forward(token)); }) == expected_code); BOOST_TEST(complete_code(context, [&](auto const& executor, auto&& token) { - return crypto::async_verify(executor, crypto::signing_schemes::eddsa, signature, + return crypto::async_verify(executor, crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, signature, message, key, std::forward(token)); }) == expected_code); BOOST_TEST(complete_code(context, [&](auto const& executor, auto&& token) { return crypto::async_verify(executor, crypto::signing_schemes::eddsa, - signature, message, key, ed25519::strict, + crypto::verification_policies::canonical, + signature, message, key, std::forward(token)); }) == expected_code); } @@ -773,26 +786,30 @@ void eddsa_prehashed_async(asio::io_context& context) { BOOST_TEST(!complete_code(context, [&](auto const& executor, auto&& token) { return public_key.async_verify(executor, crypto::signing_schemes::eddsa_prehashed, - *expected, marker, std::forward(token)); + crypto::verification_policies::canonical, *expected, marker, + std::forward(token)); })); BOOST_TEST(!complete_code(context, [&](auto const& executor, auto&& token) { return public_key.async_verify(executor, crypto::signing_schemes::eddsa_prehashed, - *expected, marker, ed25519::strict, - std::forward(token)); + crypto::verification_policies::canonical, *expected, + marker, std::forward(token)); })); BOOST_TEST(!complete_code(context, [&](auto const& executor, auto&& token) { - return crypto::async_verify(executor, crypto::signing_schemes::eddsa_prehashed, *expected, - marker, public_key, std::forward(token)); + return crypto::async_verify(executor, crypto::signing_schemes::eddsa_prehashed, + crypto::verification_policies::canonical, *expected, marker, + public_key, std::forward(token)); })); BOOST_TEST(!complete_code(context, [&](auto const& executor, auto&& token) { return crypto::async_verify(executor, crypto::signing_schemes::eddsa_prehashed, - *expected, marker, public_key, ed25519::strict, + crypto::verification_policies::canonical, *expected, + marker, public_key, std::forward(token)); })); // The pure scheme's signature of the same message is refused under eddsa_prehashed. BOOST_TEST(complete_code(context, [&](auto const& executor, auto&& token) { return crypto::async_verify( executor, crypto::signing_schemes::eddsa_prehashed, + crypto::verification_policies::canonical, key.sign(crypto::signing_schemes::eddsa, abc).value(), marker, public_key, std::forward(token)); }) == crypto::error::invalid_signature); diff --git a/test/async_p256_test.cpp b/test/async_p256_test.cpp index 0b8e432b..64322442 100644 --- a/test/async_p256_test.cpp +++ b/test/async_p256_test.cpp @@ -5,15 +5,17 @@ // https://www.boost.org/LICENSE_1_0.txt) // P-256's asynchronous functions on BearSSL, on a callback and in a coroutine. async_sign and -// async_verify take the scheme, crypto::signing_schemes::ecdsa_sha256, and the synchronous calls' -// inputs: the message, which they hash with SHA-256, as WebCrypto's ECDSA with SHA-256 does, or -// crypto::signing_schemes::prehashed{digest}; the synchronous answers they are checked against are -// sign(ecdsa_sha256, prehashed{digest}) and crypto::verify(ecdsa_sha256, signature, -// prehashed{digest}, key) of its digest, computed here. +// async_verify take the scheme, crypto::signing_schemes::ecdsa_sha256, async_verify the policy +// after it (any_s for a signature WebCrypto or the RFC made, low_s_only for crypto's own), and the +// synchronous calls' inputs: the message, which they hash with SHA-256, as WebCrypto's ECDSA with +// SHA-256 does, or crypto::signing_schemes::prehashed{digest}; the synchronous answers they are +// checked against are sign(ecdsa_sha256, prehashed{digest}) and crypto::verify(ecdsa_sha256, +// policy, signature, prehashed{digest}, key) of its digest, computed here. // - async_rfc6979: RFC 6979 section A.2.5's key through async_from_secret, its messages "sample" // and "test" through async_sign give the RFC's signatures in their low-S form ("sample"'s S is // high in the RFC) and the synchronous ones, and async_verify accepts them, and the RFC's high-S -// "sample" too; each completion arrives after the initiating call returned. +// "sample" too under any_s, which low_s_only refuses; each completion arrives after the +// initiating call returned. // - async_wycheproof_ecdsa: the first 50 valid cases of Wycheproof's ECDSA P-256 SHA-256 file in // WebCrypto's form (IEEE P1363's r || s) verify through async_verify as through crypto::verify; // with a changed byte of the message both refuse them with invalid_signature. @@ -119,10 +121,12 @@ static_assert(!crypto::can_sign, static_assert( crypto::can_sign, crypto::signing_schemes::ecdsa_sha256_t, std::span>); -static_assert(!crypto::can_verify, +static_assert(!crypto::can_verify, p256::basic_public_key>); -static_assert(crypto::can_verify, p256::basic_public_key>); @@ -231,12 +235,16 @@ completed sign_async(asio::io_context& context, keypair const& k }); } +// async_verify under a policy, any_s by default: the RFC's and Wycheproof's signatures, whose S +// may be high, as WebCrypto's. +template boost::system::error_code verify_async(asio::io_context& context, public_key const& key, std::span message, - signature_type const& signature) { + signature_type const& signature, + Policy policy = crypto::verification_policies::any_s) { return complete_code(context, [&](auto const& executor, auto&& token) { - return crypto::async_verify(executor, crypto::signing_schemes::ecdsa_sha256, signature, - message, key, std::forward(token)); + return crypto::async_verify(executor, crypto::signing_schemes::ecdsa_sha256, policy, + signature, message, key, std::forward(token)); }); } @@ -274,8 +282,12 @@ void async_rfc6979(asio::io_context& context) { BOOST_TEST(signed_sync.has_value() && *signed_sync == signature); BOOST_TEST(!verify_async(context, *own, message, signature)); } - // The RFC's own "sample" signature, whose S is high: accepted too. + // The RFC's own "sample" signature, whose S is high: accepted under any_s, refused under + // low_s_only. BOOST_TEST(!verify_async(context, *own, bytes_of("sample"), typed(data::rfc6979_sample))); + BOOST_TEST(verify_async(context, *own, bytes_of("sample"), typed(data::rfc6979_sample), + crypto::verification_policies::low_s_only) == + crypto::error::invalid_signature); } json::value load(std::string const& name) { @@ -301,14 +313,15 @@ void check_wycheproof_ecdsa_case(asio::io_context& context, public_key const& ke } auto const signature = typed(encoded); auto const verified_sync = - crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, - crypto::signing_schemes::prehashed{sha256(message)}, key); + crypto::verify(crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::any_s, + signature, crypto::signing_schemes::prehashed{sha256(message)}, key); BOOST_TEST(verified_sync.has_value()); BOOST_TEST(!verify_async(context, key, message, signature)); // A changed byte of the message: both refuse it. message.push_back(0); message.front() ^= 1U; - BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::any_s, signature, crypto::signing_schemes::prehashed{sha256(message)}, key) .error() == crypto::error::invalid_signature); BOOST_TEST(verify_async(context, key, message, signature) == crypto::error::invalid_signature); @@ -432,7 +445,8 @@ void async_prehashed(asio::io_context& context) { BOOST_TEST(std::get<0>(*signed_digest.value) == *signed_sync); auto const verify_digest = [&] { return complete_code(context, [&](auto const& executor, auto&& token) { - return crypto::async_verify(executor, crypto::signing_schemes::ecdsa_sha256, signature, + return crypto::async_verify(executor, crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, signature, crypto::signing_schemes::prehashed{digest}, *own, std::forward(token)); }); @@ -486,12 +500,14 @@ void generated(asio::io_context& context) { return; } auto const& signature = std::get<0>(*signed_async.value); - BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, signature, crypto::signing_schemes::prehashed{sha256(message)}, *own) .has_value()); auto const verified = complete_code(context, [&](auto const& executor, auto&& token) { - return crypto::async_verify(executor, crypto::signing_schemes::ecdsa_sha256, signature, - message, *own, std::forward(token)); + return crypto::async_verify(executor, crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, signature, message, + *own, std::forward(token)); }); BOOST_TEST(!verified); } @@ -621,9 +637,9 @@ asio::awaitable coroutine_body(bool& done) { if (!BOOST_TEST(own.has_value())) { co_return; } - auto [verify_code] = - co_await crypto::async_verify(executor, crypto::signing_schemes::ecdsa_sha256, signature, - message, *own, asio::as_tuple(asio::use_awaitable)); + auto [verify_code] = co_await crypto::async_verify( + executor, crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::low_s_only, + signature, message, *own, asio::as_tuple(asio::use_awaitable)); BOOST_TEST(!verify_code); co_await coroutine_agreement(executor, key, *own, done); } @@ -680,7 +696,9 @@ bool signs_and_verifies(keypair const& key) { auto const signature = key.sign(crypto::signing_schemes::ecdsa_sha256, message); auto const own = key.public_key(); return signature.has_value() && own.has_value() && - own->verify(crypto::signing_schemes::ecdsa_sha256, *signature, message).has_value(); + own->verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *signature, message) + .has_value(); } // generate in its four forms: each a key pair whose signature verifies. @@ -747,18 +765,21 @@ void check_four_verifications(asio::io_context& context, public_key const& key, auto const code_of = [](boost::system::result const& done) { return done ? boost::system::error_code{} : done.error(); }; - BOOST_TEST(code_of(key.verify(crypto::signing_schemes::ecdsa_sha256, signature, input)) == + BOOST_TEST(code_of(key.verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, signature, input)) == expected_code); - BOOST_TEST(code_of(crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, input, + BOOST_TEST(code_of(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, signature, input, key)) == expected_code); BOOST_TEST(complete_code(context, [&](auto const& executor, auto&& token) { return key.async_verify(executor, crypto::signing_schemes::ecdsa_sha256, - signature, input, std::forward(token)); + crypto::verification_policies::low_s_only, signature, + input, std::forward(token)); }) == expected_code); BOOST_TEST(complete_code(context, [&](auto const& executor, auto&& token) { return crypto::async_verify(executor, crypto::signing_schemes::ecdsa_sha256, - signature, input, key, - std::forward(token)); + crypto::verification_policies::low_s_only, signature, + input, key, std::forward(token)); }) == expected_code); } diff --git a/test/async_post_test.cpp b/test/async_post_test.cpp index 3f6474a7..b55471e0 100644 --- a/test/async_post_test.cpp +++ b/test/async_post_test.cpp @@ -832,7 +832,8 @@ struct verify_fixture { auto verify() { return [this](auto const& executor, auto&& token) { - return crypto::async_verify(executor, crypto::signing_schemes::eddsa, typed_signature(), + return crypto::async_verify(executor, crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, typed_signature(), message, public_key, std::forward(token)); }; } @@ -843,7 +844,7 @@ struct verify_fixture { auto changed = typed_signature().bytes(); ++changed[3]; return crypto::async_verify( - executor, crypto::signing_schemes::eddsa, + executor, crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, crypto::curves::ed25519::signature::from_bytes(changed).value(), message, public_key, std::forward(token)); }; diff --git a/test/crypto_secp256k1_test.cpp b/test/crypto_secp256k1_test.cpp index 4d60841f..fa80e658 100644 --- a/test/crypto_secp256k1_test.cpp +++ b/test/crypto_secp256k1_test.cpp @@ -26,10 +26,12 @@ namespace secp = webcpp::crypto::curves::secp256k1; static_assert(std::is_same_v); static_assert(webcpp::crypto::can_sign>); -static_assert( - webcpp::crypto::can_verify, std::array>); +static_assert(webcpp::crypto::can_verify, + std::array>); static_assert(webcpp::crypto::can_verify, secp::public_key>); static_assert(std::is_function_v)>); diff --git a/test/ed25519_sodium_test.cpp b/test/ed25519_sodium_test.cpp index 010cde61..4537355f 100644 --- a/test/ed25519_sodium_test.cpp +++ b/test/ed25519_sodium_test.cpp @@ -7,20 +7,20 @@ // Ed25519 on libsodium: RFC 8032 section 7.1's tests 1, 2, 3 and SHA(abc), each key pair made // from the RFC's secret key, its public key and signature the RFC's, signed with // sign(crypto::signing_schemes::eddsa, message) and accepted by -// crypto::verify(crypto::signing_schemes::eddsa, signature, message, public_key), the key pair's -// typed public key or one made from the RFC's bytes, its policy and backend deduced and named; -// secret() gives the seed back, which makes the same key pair; public_key::from_bytes checks the -// size alone; the empty message; the arguments of the order before it (key, message, signature) -// refused as a signature; speccheck's small-order key refused under strict; the guards (a seed of -// 31 bytes, a moved-from key pair, a signature changed in one bit, keys of other sizes, and -// signatures of other sizes refused by ed25519::signature::from_bytes); a signature received as a -// std::vector, made into the type, verified by the key's verify and crypto::verify; generate() -// under the planted entropy source of the test seam WEBCPP_CRYPTO_DETAIL_TEST_ENTROPY, failing and -// answering; and the conversion to X25519, to_x25519() of the key pair and of its public key, -// member and free, equal to libsodium's crypto_sign_ed25519_sk_to_curve25519 and pk_to_curve25519, -// the converted key pair agreeing with an X25519 peer, and keys of small order or not canonical -// refused; the key pair's x25519_secret() and the free to_x25519_public, which to_x25519() -// replaced, are not public. +// crypto::verify(crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, +// signature, message, public_key), the key pair's typed public key or one made from the RFC's +// bytes, its backend deduced and named; secret() gives the seed back, which makes the +// same key pair; public_key::from_bytes checks the size alone; the empty message; the arguments of +// the order before it (key, message, signature) refused as a signature; speccheck's small-order key +// refused under canonical; the guards (a seed of 31 bytes, a moved-from key pair, a signature +// changed in one bit, keys of other sizes, and signatures of other sizes refused by +// ed25519::signature::from_bytes); a signature received as a std::vector, made into the type, +// verified by the key's verify and crypto::verify; generate() under the planted entropy source of +// the test seam WEBCPP_CRYPTO_DETAIL_TEST_ENTROPY, failing and answering; and the conversion to +// X25519, to_x25519() of the key pair and of its public key, member and free, equal to libsodium's +// crypto_sign_ed25519_sk_to_curve25519 and pk_to_curve25519, the converted key pair agreeing with +// an X25519 peer, and keys of small order or not canonical refused; the key pair's x25519_secret() +// and the free to_x25519_public, which to_x25519() replaced, are not public. #include #include @@ -142,16 +142,19 @@ void rfc8032() { if (!signature || !public_key || !expected_key) { continue; } - // The default policy, and strict named, on the default backend and on libsodium named: - // the explicit arguments pick Ed25519's verify, never P-256's or the catch-all. - BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, *signature, message, *public_key) + // Under canonical, on the default backend and on libsodium named: the explicit arguments + // pick Ed25519's verify, never P-256's or the catch-all. + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, *signature, message, + *public_key) .has_value()); - BOOST_TEST( - (crypto::verify(crypto::signing_schemes::eddsa, *signature, - message, *public_key, ed25519::strict) - .has_value())); - BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, typed(expected_signature), - message, *expected_key) + BOOST_TEST((crypto::verify( + crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, + *signature, message, *public_key) + .has_value())); + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, + typed(expected_signature), message, *expected_key) .has_value()); } } @@ -218,14 +221,16 @@ void refusals() { auto changed = good; changed[index] ^= 0x01U; auto const refused = - crypto::verify(crypto::signing_schemes::eddsa, typed(changed), message, public_key); + crypto::verify(crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, + typed(changed), message, public_key); BOOST_TEST(refused.has_error() && refused.error() == crypto::error::invalid_signature); } auto changed_message = message; changed_message[0] ^= 0x01U; - BOOST_TEST( - crypto::verify(crypto::signing_schemes::eddsa, typed(good), changed_message, public_key) - .error() == crypto::error::invalid_signature); + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, typed(good), + changed_message, public_key) + .error() == crypto::error::invalid_signature); // A signature of another size is no signature: from_bytes refuses it, before any verify. BOOST_TEST(ed25519::signature::from_bytes(std::span(good).first(63)).error() == @@ -247,9 +252,13 @@ void signature_from_vector() { if (!BOOST_TEST(public_key.has_value()) || !BOOST_TEST(made.has_value())) { return; } - BOOST_TEST(public_key->verify(crypto::signing_schemes::eddsa, *made, message).has_value()); - BOOST_TEST( - crypto::verify(crypto::signing_schemes::eddsa, *made, message, *public_key).has_value()); + BOOST_TEST(public_key + ->verify(crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, *made, message) + .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, *made, message, *public_key) + .has_value()); for (std::size_t const size : {std::size_t{63}, std::size_t{65}}) { auto resized = received; resized.resize(size); @@ -275,15 +284,16 @@ void old_order_fails_closed() { if (!public_key) { return; } - BOOST_TEST( - crypto::verify(crypto::signing_schemes::eddsa, typed(signature), message, *public_key) - .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, typed(signature), message, + *public_key) + .has_value()); auto const swapped = ed25519::signature::from_bytes(key_bytes); BOOST_TEST(swapped.has_error() && swapped.error() == crypto::error::invalid_signature); } // The public key holds 32 bytes, checked for their size alone (design R16): another size is -// invalid_public_key; a key of small order is made, and strict verification refuses it. +// invalid_public_key; a key of small order is made, and verification under canonical refuses it. void public_keys() { auto const bytes = test::from_hex(rfc8032_cases[1].public_key); auto const made = ed25519::public_key::from_bytes(bytes); @@ -341,18 +351,20 @@ void empty_message() { if (!public_key || !signature) { return; } - BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, *signature, + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, *signature, std::span{}, *public_key) .has_value()); std::array const one_byte{}; - BOOST_TEST( - crypto::verify(crypto::signing_schemes::eddsa, *signature, one_byte, *public_key).error() == - crypto::error::invalid_signature); + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, *signature, one_byte, + *public_key) + .error() == crypto::error::invalid_signature); } // ed25519-speccheck's case 0 (Chalkias, Garillot and Nikolaenko; Wycheproof's EdDSA file has no // small-order key): A and R of small order, S zero, which a cofactored or cofactorless verifier -// accepts; strict, on libsodium named, refuses it. +// accepts; canonical, on libsodium named, refuses it. void small_order_key() { auto const public_key = test::from_hex("c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa"); @@ -368,7 +380,8 @@ void small_order_key() { return; } auto const refused = crypto::verify( - crypto::signing_schemes::eddsa, typed(signature), message, *key, ed25519::strict); + crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, typed(signature), + message, *key); BOOST_TEST(refused.has_error() && refused.error() == crypto::error::invalid_signature); } @@ -554,30 +567,41 @@ int main() { crypto::signing_schemes::prehashed<32>>); static_assert(!crypto::can_sign>); - static_assert(crypto::can_verify, ed25519::public_key>); - static_assert(!crypto::can_verify, ed25519::public_key>); - static_assert(!crypto::can_verify, std::array>); + static_assert( + !crypto::can_verify, ed25519::public_key>); + static_assert( + !crypto::can_verify, std::array>); // The signature is the type: bytes are none (design R1), nor another curve's signature. + static_assert(!crypto::can_verify< + crypto::signing_schemes::eddsa_t, crypto::verification_policies::canonical_t, + std::array, std::vector, ed25519::public_key>); static_assert( - !crypto::can_verify, + !crypto::can_verify, std::vector, ed25519::public_key>); - static_assert(!crypto::can_verify, - std::vector, ed25519::public_key>); // Bytes never sign, whatever their size, and a key pair is no public key: it verifies // nothing, its public key does. static_assert(!crypto::can_sign, crypto::signing_schemes::eddsa_t, std::span>); static_assert(!crypto::can_sign, crypto::signing_schemes::eddsa_t, std::span>); - static_assert(!crypto::can_verify, ed25519::keypair>); + static_assert( + !crypto::can_verify, ed25519::keypair>); static_assert(crypto::can_sign>); - static_assert(crypto::can_verify, ed25519::public_key const&>); + static_assert( + crypto::can_verify, ed25519::public_key const&>); static_assert(std::is_same_v().sign( crypto::signing_schemes::eddsa, std::declval>())), diff --git a/test/ed25519_speccheck_test.cpp b/test/ed25519_speccheck_test.cpp index 968ac0fe..60e0e441 100644 --- a/test/ed25519_speccheck_test.cpp +++ b/test/ed25519_speccheck_test.cpp @@ -7,12 +7,12 @@ // The twelve Ed25519 edge cases of Chalkias, Garillot and Nikolaenko, "Taming the many EdDSAs" // (2020), novifinancial/ed25519-speccheck's cases.json, against every Ed25519 backend linked // (design D31): each backend's raw verdict, its own library called directly, and the verdict of -// crypto::verify(crypto::signing_schemes::eddsa, ..., strict), compared with the verdicts -// committed in meta/ed25519_cases.json. Under strict every backend gives libsodium's verdicts. On -// Emscripten, node's WebCrypto verify (Ed25519) gives the row webcrypto-node, an outside view that -// is compared with its committed row but never with strict's. A pin move that changes a verdict -// fails here until the data and the page are regenerated. Each row is printed, so that a first run -// gives the data to review. +// crypto::verify(crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, +// ...), compared with the verdicts committed in meta/ed25519_cases.json. Under canonical every +// backend gives libsodium's verdicts. On Emscripten, node's WebCrypto verify (Ed25519) gives the +// row webcrypto-node, an outside view that is compared with its committed row but never with +// canonical's. A pin move that changes a verdict fails here until the data and the page are +// regenerated. Each row is printed, so that a first run gives the data to review. #include #include @@ -168,10 +168,10 @@ void compare(std::string const& label, verdicts const& computed, verdicts const& } } -// libsodium's raw verdicts, crypto_sign_ed25519_verify_detached called directly, and strict's, -// crypto::verify(crypto::signing_schemes::eddsa, ..., strict), whose refusal is -// invalid_signature. -void sodium_rows(std::vector const& cases, verdicts& raw, verdicts& strict) { +// libsodium's raw verdicts, crypto_sign_ed25519_verify_detached called directly, and canonical's, +// crypto::verify(crypto::signing_schemes::eddsa, +// crypto::verification_policies::canonical, ...), whose refusal is invalid_signature. +void sodium_rows(std::vector const& cases, verdicts& raw, verdicts& canonical) { for (auto const& tested : cases) { raw.emplace_back(verdict(crypto_sign_ed25519_verify_detached( tested.signature.data(), tested.message.data(), @@ -180,23 +180,23 @@ void sodium_rows(std::vector const& cases, verdicts& raw, verdicts& s auto const public_key = ed25519::public_key::from_bytes(tested.public_key); BOOST_TEST(public_key.has_value()); if (!public_key) { - strict.emplace_back(verdict(false)); + canonical.emplace_back(verdict(false)); continue; } // Every case's signature is 64 bytes (checked where the cases are read). auto const signature = ed25519::signature::from_bytes(tested.signature); BOOST_TEST(signature.has_value()); if (!signature) { - strict.emplace_back(verdict(false)); + canonical.emplace_back(verdict(false)); continue; } - auto const verified = - crypto::verify(crypto::signing_schemes::eddsa, *signature, - tested.message, *public_key, ed25519::strict); + auto const verified = crypto::verify( + crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, *signature, + tested.message, *public_key); if (!verified) { BOOST_TEST(verified.error() == crypto::error::invalid_signature); } - strict.emplace_back(verdict(static_cast(verified))); + canonical.emplace_back(verdict(static_cast(verified))); } } @@ -319,8 +319,8 @@ int main() { } // Every committed backend is one this test runs (libsodium alone in this version), and each - // backend's strict verdicts are compared with libsodium's committed row: under strict every - // backend gives libsodium's verdicts. + // backend's canonical verdicts are compared with libsodium's committed row: under canonical + // every backend gives libsodium's verdicts. auto const* backends = object_in(*root, "backends"); auto const* sodium = backends == nullptr ? nullptr : object_in(*backends, "sodium"); BOOST_TEST(sodium != nullptr); @@ -328,7 +328,7 @@ int main() { return test::exit_status(boost::report_errors()); } auto const sodium_raw = committed_row(value_at(*sodium, "raw"), "sodium raw"); - auto const sodium_strict = committed_row(value_at(*sodium, "strict"), "sodium strict"); + auto const sodium_canonical = committed_row(value_at(*sodium, "canonical"), "sodium canonical"); // A backend's rows are committed with its run here. for (auto const& entry : *backends) { if (entry.key() != "sodium") { @@ -338,10 +338,10 @@ int main() { } verdicts raw; - verdicts strict; - sodium_rows(cases, raw, strict); + verdicts canonical; + sodium_rows(cases, raw, canonical); compare("sodium raw", raw, sodium_raw); - compare("sodium strict", strict, sodium_strict); + compare("sodium canonical", canonical, sodium_canonical); if (!outside_agrees(*root, cases)) { return test::exit_status(boost::report_errors()); diff --git a/test/ed25519_wycheproof_sodium_test.cpp b/test/ed25519_wycheproof_sodium_test.cpp index 09b88d49..490b9339 100644 --- a/test/ed25519_wycheproof_sodium_test.cpp +++ b/test/ed25519_wycheproof_sodium_test.cpp @@ -5,9 +5,9 @@ // https://www.boost.org/LICENSE_1_0.txt) // Ed25519 against Wycheproof's EdDSA file (testvectors_v1/ed25519_test.json) through -// crypto::verify(crypto::signing_schemes::eddsa, ...) on libsodium, strict: every valid case -// accepted and every invalid case refused with invalid_signature, without exception (a disagreement -// is reported, never listed away). +// crypto::verify(crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, ...) on +// libsodium: every valid case accepted and every invalid case refused with +// invalid_signature, without exception (a disagreement is reported, never listed away). #include #include @@ -47,7 +47,8 @@ boost::system::result verified_case(std::span signatur if (!made) { return made.error(); } - return crypto::verify(crypto::signing_schemes::eddsa, *made, message, public_key); + return crypto::verify(crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, + *made, message, public_key); } } // namespace diff --git a/test/ed25519ph_sodium_test.cpp b/test/ed25519ph_sodium_test.cpp index 1ad4ce13..03bfd086 100644 --- a/test/ed25519ph_sodium_test.cpp +++ b/test/ed25519ph_sodium_test.cpp @@ -142,8 +142,9 @@ void rfc8032_ph() { BOOST_TEST(other.verify(expected, public_key).error() == crypto::error::invalid_signature); // Ed25519ph's signature is not Ed25519's of the same message. - BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, expected, abc, public_key).error() == - crypto::error::invalid_signature); + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, expected, abc, public_key) + .error() == crypto::error::invalid_signature); // The arguments in the other order, (public_key, signature): the key's 32 bytes are no // signature, refused by from_bytes (bytes where the signature goes do not compile); the @@ -212,36 +213,44 @@ void rfc8032_ph_scheme() { BOOST_TEST(signature && *signature == expected); auto const signed_free = crypto::sign(key, crypto::signing_schemes::eddsa_prehashed, marker); BOOST_TEST(signed_free && *signed_free == expected); - BOOST_TEST( - crypto::verify(crypto::signing_schemes::eddsa_prehashed, expected, marker, public_key) - .has_value()); - BOOST_TEST( - public_key.verify(crypto::signing_schemes::eddsa_prehashed, expected, marker).has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa_prehashed, + crypto::verification_policies::canonical, expected, marker, + public_key) + .has_value()); + BOOST_TEST(public_key + .verify(crypto::signing_schemes::eddsa_prehashed, + crypto::verification_policies::canonical, expected, marker) + .has_value()); BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa_prehashed, - expected, marker, public_key, - ed25519::strict) + crypto::verification_policies::canonical, + expected, marker, public_key) .has_value()); BOOST_TEST(public_key .verify(crypto::signing_schemes::eddsa_prehashed, - expected, marker, ed25519::strict) + crypto::verification_policies::canonical, + expected, marker) .has_value()); // A flipped byte of the signature, and of the digest, are refused. auto changed_signature = test::from_hex(signature_hex); changed_signature[5] ^= 0x01U; auto const changed = ed25519::signature::from_bytes(changed_signature).value(); - BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa_prehashed, changed, marker, public_key) + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa_prehashed, + crypto::verification_policies::canonical, changed, marker, public_key) + .error() == crypto::error::invalid_signature); + BOOST_TEST(public_key + .verify(crypto::signing_schemes::eddsa_prehashed, + crypto::verification_policies::canonical, changed, marker) .error() == crypto::error::invalid_signature); - BOOST_TEST( - public_key.verify(crypto::signing_schemes::eddsa_prehashed, changed, marker).error() == - crypto::error::invalid_signature); auto changed_digest = digest; changed_digest[0] ^= 0x01U; - BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa_prehashed, expected, + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa_prehashed, + crypto::verification_policies::canonical, expected, crypto::signing_schemes::prehashed{changed_digest}, public_key) .error() == crypto::error::invalid_signature); BOOST_TEST(public_key - .verify(crypto::signing_schemes::eddsa_prehashed, expected, + .verify(crypto::signing_schemes::eddsa_prehashed, + crypto::verification_policies::canonical, expected, crypto::signing_schemes::prehashed{changed_digest}) .error() == crypto::error::invalid_signature); } @@ -285,7 +294,8 @@ void streaming_equals_scheme() { auto verifying = begun(pieces); BOOST_TEST(verifying.verify(*scheme_signature, public_key).has_value()); if (streamed) { - BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa_prehashed, *streamed, + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa_prehashed, + crypto::verification_policies::canonical, *streamed, crypto::signing_schemes::prehashed{digest}, public_key) .has_value()); } @@ -300,10 +310,12 @@ void not_interchangeable() { auto const prehashed_signature_value = key.sign(crypto::signing_schemes::eddsa_prehashed, crypto::signing_schemes::prehashed{sha512(abc)}) .value(); - BOOST_TEST( - crypto::verify(crypto::signing_schemes::eddsa, prehashed_signature_value, abc, public_key) - .error() == crypto::error::invalid_signature); + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, prehashed_signature_value, + abc, public_key) + .error() == crypto::error::invalid_signature); BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa_prehashed, + crypto::verification_policies::canonical, key.sign(crypto::signing_schemes::eddsa, abc).value(), crypto::signing_schemes::prehashed{sha512(abc)}, public_key) .error() == crypto::error::invalid_signature); @@ -340,9 +352,11 @@ void typed() { static_assert(!crypto::can_sign>); - static_assert(crypto::can_verify, ed25519::public_key>); static_assert(!crypto::can_verify); static_assert(crypto::detail::has_verifier_v); diff --git a/test/keypair_test.cpp b/test/keypair_test.cpp index 066f185a..5f670a0b 100644 --- a/test/keypair_test.cpp +++ b/test/keypair_test.cpp @@ -559,15 +559,16 @@ void prehashed_round_trip() { auto const signature = again->sign(crypto::signing_schemes::eddsa_prehashed, crypto::signing_schemes::prehashed{digest}); BOOST_TEST(signature.has_value()); - BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa_prehashed, *signature, + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa_prehashed, + crypto::verification_policies::canonical, *signature, crypto::signing_schemes::prehashed{digest}, *key->public_key()) .has_value()); } // Each signing curve's key pair, used through signing_keypair alone: the key pair made again from -// its secret() signs what the first one's public key verifies. -template -void signing_round_trip(Scheme scheme) { +// its secret() signs what the first one's public key verifies under the scheme's policy. +template +void signing_round_trip(Scheme scheme, Policy policy) { auto const key = Keypair::generate(); BOOST_TEST(key.has_value()); auto const exported = key->secret(); @@ -577,11 +578,12 @@ void signing_round_trip(Scheme scheme) { std::array const message{'a', 'b', 'c'}; auto const signature = crypto::sign(*again, scheme, message); BOOST_TEST(signature.has_value()); - BOOST_TEST(crypto::verify(scheme, *signature, message, *key->public_key()).has_value()); + BOOST_TEST(crypto::verify(scheme, policy, *signature, message, *key->public_key()).has_value()); } // A recoverable scheme of secp256k1's key pair, through signing_keypair: the key pair made again -// from its secret() signs a digest marker, and recover gives the first one's public key. +// from its secret() signs a digest marker, and recover, under low_s_only, gives the first one's +// public key. template void recovered_round_trip(Scheme scheme) { auto const key = Keypair::generate(); @@ -594,8 +596,9 @@ void recovered_round_trip(Scheme scheme) { digest.fill(0x3c); auto const signature = again->sign(scheme, crypto::signing_schemes::prehashed{digest}); BOOST_TEST(signature.has_value()); - auto const recovered = crypto::curves::secp256k1::recover( - scheme, *signature, crypto::signing_schemes::prehashed{digest}); + auto const recovered = + crypto::curves::secp256k1::recover(scheme, crypto::verification_policies::low_s_only, + *signature, crypto::signing_schemes::prehashed{digest}); BOOST_TEST(recovered.has_value() && *recovered == *key->public_key()); } @@ -619,11 +622,15 @@ int main() { from_secret_round_trip(); from_secret_round_trip(); from_secret_round_trip(); - signing_round_trip(crypto::signing_schemes::eddsa); + signing_round_trip(crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical); prehashed_round_trip(); - signing_round_trip(crypto::signing_schemes::ecdsa_sha256); - signing_round_trip(crypto::signing_schemes::ecdsa_sha256); - signing_round_trip(crypto::signing_schemes::schnorr); + signing_round_trip(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only); + signing_round_trip(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only); + signing_round_trip(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical); recovered_round_trip(crypto::signing_schemes::ecdsa_sha256_recoverable); recovered_round_trip(crypto::signing_schemes::ecdsa_keccak256_recoverable); agreement_round_trip(); diff --git a/test/messages/Jamfile b/test/messages/Jamfile index ebd6feb4..18b9aa87 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -149,3 +149,10 @@ build-project async_seal_member_asynchronous_backend ; build-project async_from_key_secretbox_asynchronous_backend ; build-project seal_secretbox_asynchronous_backend ; build-project seal_box_asynchronous_backend ; +build-project verify_without_policy ; +build-project async_verify_without_policy ; +build-project verify_secp256k1_any_s ; +build-project verify_schnorr_any_s ; +build-project verify_eddsa_low_s_only ; +build-project verify_p256_canonical ; +build-project recover_any_s ; diff --git a/test/messages/async_verify_eddsa_bytes_key/async_verify_eddsa_bytes_key.cpp b/test/messages/async_verify_eddsa_bytes_key/async_verify_eddsa_bytes_key.cpp index 7a2f121b..ed89615e 100644 --- a/test/messages/async_verify_eddsa_bytes_key/async_verify_eddsa_bytes_key.cpp +++ b/test/messages/async_verify_eddsa_bytes_key/async_verify_eddsa_bytes_key.cpp @@ -30,7 +30,8 @@ int main() { std::array const message{'h', 'e', 'l', 'l', 'o'}; std::array const key_bytes{}; webcpp::asio::io_context context; - crypto::async_verify(context.get_executor(), crypto::signing_schemes::eddsa, signature, message, - key_bytes, [](boost::system::error_code) {}); + crypto::async_verify(context.get_executor(), crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, signature, message, key_bytes, + [](boost::system::error_code) {}); return 0; } diff --git a/test/messages/async_verify_eddsa_prehashed_asynchronous_backend/async_verify_eddsa_prehashed_asynchronous_backend.cpp b/test/messages/async_verify_eddsa_prehashed_asynchronous_backend/async_verify_eddsa_prehashed_asynchronous_backend.cpp index ec8d5243..9c0809c4 100644 --- a/test/messages/async_verify_eddsa_prehashed_asynchronous_backend/async_verify_eddsa_prehashed_asynchronous_backend.cpp +++ b/test/messages/async_verify_eddsa_prehashed_asynchronous_backend/async_verify_eddsa_prehashed_asynchronous_backend.cpp @@ -52,10 +52,12 @@ void verified(webcpp::asio::io_context& context, crypto::curves::ed25519::signature const signature{}; std::array const digest{}; crypto::async_verify( - context.get_executor(), crypto::signing_schemes::eddsa_prehashed, signature, + context.get_executor(), crypto::signing_schemes::eddsa_prehashed, + crypto::verification_policies::canonical, signature, crypto::signing_schemes::prehashed{digest}, public_key, [](boost::system::error_code) {}); public_key.async_verify( - context.get_executor(), crypto::signing_schemes::eddsa_prehashed, signature, + context.get_executor(), crypto::signing_schemes::eddsa_prehashed, + crypto::verification_policies::canonical, signature, crypto::signing_schemes::prehashed{digest}, [](boost::system::error_code) {}); } diff --git a/test/messages/async_verify_named_backend/async_verify_named_backend.cpp b/test/messages/async_verify_named_backend/async_verify_named_backend.cpp index 7e6b8294..fdd5a080 100644 --- a/test/messages/async_verify_named_backend/async_verify_named_backend.cpp +++ b/test/messages/async_verify_named_backend/async_verify_named_backend.cpp @@ -33,7 +33,8 @@ int main() { std::array const xonly_key{}; webcpp::asio::io_context context; crypto::async_verify( - context.get_executor(), crypto::signing_schemes::schnorr, signature, message, xonly_key, + context.get_executor(), crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, signature, message, xonly_key, [](boost::system::error_code) {}); return 0; } diff --git a/test/messages/async_verify_p256_bytes_signature/async_verify_p256_bytes_signature.cpp b/test/messages/async_verify_p256_bytes_signature/async_verify_p256_bytes_signature.cpp index ee20f23a..34e22e88 100644 --- a/test/messages/async_verify_p256_bytes_signature/async_verify_p256_bytes_signature.cpp +++ b/test/messages/async_verify_p256_bytes_signature/async_verify_p256_bytes_signature.cpp @@ -42,7 +42,8 @@ int main() { std::array const signature{}; std::array const message{'h', 'e', 'l', 'l', 'o'}; webcpp::asio::io_context context; - crypto::async_verify(context.get_executor(), crypto::signing_schemes::ecdsa_sha256, signature, - message, *public_key, [](boost::system::error_code) {}); + crypto::async_verify(context.get_executor(), crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, signature, message, *public_key, + [](boost::system::error_code) {}); return 0; } diff --git a/test/messages/async_verify_without_policy/Jamfile b/test/messages/async_verify_without_policy/Jamfile new file mode 100644 index 00000000..4baf0764 --- /dev/null +++ b/test/messages/async_verify_without_policy/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic async_verify_without_policy : async_verify_without_policy.cpp + : /webcpp/asio//asio /third_party//bearssl : native wasip2 wasip3 : alone ; diff --git a/test/messages/async_verify_without_policy/async_verify_without_policy.cpp b/test/messages/async_verify_without_policy/async_verify_without_policy.cpp new file mode 100644 index 00000000..191d599d --- /dev/null +++ b/test/messages/async_verify_without_policy/async_verify_without_policy.cpp @@ -0,0 +1,46 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// crypto::async_verify of crypto::signing_schemes::ecdsa_sha256 against a P-256 public key in the +// arity before the verification policies, async_verify(executor, scheme, signature, message, +// public_key, token), stops at the catch-all, whose message names the policies P-256's ECDSA +// takes, low_s_only or any_s, and with that error alone. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/signing.hpp:* {{webcpp::crypto: verify takes a verification policy after the scheme: crypto::signing_schemes::ecdsa_sha256 on a P-256 key takes crypto::verification_policies::low_s_only or any_s.}} +// clang-format on + +#include +#include +#include + +#include + +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const scalar{1}; + std::array const message{'h', 'e', 'l', 'l', 'o'}; + auto const made = crypto::curves::p256::keypair::from_secret(scalar); + if (!made) { + return 1; + } + auto const public_key = made->public_key(); + auto const signature = made->sign(crypto::signing_schemes::ecdsa_sha256, message); + if (!public_key || !signature) { + return 1; + } + webcpp::asio::io_context context; + crypto::async_verify(context.get_executor(), crypto::signing_schemes::ecdsa_sha256, *signature, + message, *public_key, [](boost::system::error_code) {}); + return 0; +} diff --git a/test/messages/async_verify_wrong_key/async_verify_wrong_key.cpp b/test/messages/async_verify_wrong_key/async_verify_wrong_key.cpp index 09061032..5c446e83 100644 --- a/test/messages/async_verify_wrong_key/async_verify_wrong_key.cpp +++ b/test/messages/async_verify_wrong_key/async_verify_wrong_key.cpp @@ -39,11 +39,14 @@ int main() { return 1; } // The synchronous verification compiles. - if (!crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signature, message, *public_key)) { + if (!crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *signature, message, + *public_key)) { return 1; } webcpp::asio::io_context context; - crypto::async_verify(context.get_executor(), crypto::signing_schemes::ecdsa_sha256, *signature, - message, *public_key, [](boost::system::error_code) {}); + crypto::async_verify(context.get_executor(), crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *signature, message, + *public_key, [](boost::system::error_code) {}); return 0; } diff --git a/test/messages/ed25519_unknown_policy/ed25519_unknown_policy.cpp b/test/messages/ed25519_unknown_policy/ed25519_unknown_policy.cpp index b4579461..00264155 100644 --- a/test/messages/ed25519_unknown_policy/ed25519_unknown_policy.cpp +++ b/test/messages/ed25519_unknown_policy/ed25519_unknown_policy.cpp @@ -4,13 +4,14 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// A program that names a policy of its own in Ed25519's crypto::verify, on its default backend -// linked, stops where it calls it, with the one policy there is. +// A program that names a policy of its own in Ed25519's crypto::verify, in the policy's place after +// the scheme, on its default backend linked, stops where it calls it, with the one policy Ed25519 +// takes. // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. // clang-format off -// expected-error@webcpp/crypto/curves/ed25519.hpp:* {{webcpp::crypto: Ed25519's only verification policy is curves::ed25519::strict.}} +// expected-error@webcpp/crypto/signing.hpp:* {{webcpp::crypto: verify: crypto::signing_schemes::eddsa and eddsa_prehashed take crypto::verification_policies::canonical.}} // clang-format on #include @@ -32,8 +33,8 @@ int main() { webcpp::crypto::curves::ed25519::public_key::from_bytes(std::array{}); webcpp::crypto::curves::ed25519::signature const signature{}; return public_key && - webcpp::crypto::verify(webcpp::crypto::signing_schemes::eddsa, signature, - std::span{}, *public_key, lenient{}) + webcpp::crypto::verify(webcpp::crypto::signing_schemes::eddsa, lenient{}, + signature, std::span{}, *public_key) ? 0 : 1; } diff --git a/test/messages/recover_any_s/Jamfile b/test/messages/recover_any_s/Jamfile new file mode 100644 index 00000000..783d1e1e --- /dev/null +++ b/test/messages/recover_any_s/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic recover_any_s : recover_any_s.cpp + : /third_party//secp256k1 : native wasip2 wasip3 : alone ; diff --git a/test/messages/recover_any_s/recover_any_s.cpp b/test/messages/recover_any_s/recover_any_s.cpp new file mode 100644 index 00000000..03071baa --- /dev/null +++ b/test/messages/recover_any_s/recover_any_s.cpp @@ -0,0 +1,40 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// curves::secp256k1::recover of crypto::signing_schemes::ecdsa_sha256_recoverable under +// crypto::verification_policies::any_s, which recovery does not take, stops with the message that +// names the one it takes, low_s_only, and with that error alone. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/signing.hpp:* {{webcpp::crypto: curves::secp256k1::recover takes crypto::verification_policies::low_s_only.}} +// clang-format on + +#include +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const seed{1}; + std::array const message{'h', 'e', 'l', 'l', 'o'}; + auto const made = crypto::curves::secp256k1::keypair::from_secret(seed); + if (!made) { + return 1; + } + auto const signature = made->sign(crypto::signing_schemes::ecdsa_sha256_recoverable, message); + if (!signature) { + return 1; + } + return crypto::curves::secp256k1::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, + crypto::verification_policies::any_s, *signature, + message) + ? 0 + : 1; +} diff --git a/test/messages/recover_ecdsa_signature/recover_ecdsa_signature.cpp b/test/messages/recover_ecdsa_signature/recover_ecdsa_signature.cpp index 5f52f0e5..3b03f53a 100644 --- a/test/messages/recover_ecdsa_signature/recover_ecdsa_signature.cpp +++ b/test/messages/recover_ecdsa_signature/recover_ecdsa_signature.cpp @@ -30,7 +30,8 @@ int main() { std::array const message{'h', 'e', 'l', 'l', 'o'}; auto const signature = key->sign(crypto::signing_schemes::ecdsa_sha256, message); return signature && crypto::curves::secp256k1::recover( - crypto::signing_schemes::ecdsa_sha256_recoverable, *signature, message) + crypto::signing_schemes::ecdsa_sha256_recoverable, + crypto::verification_policies::low_s_only, *signature, message) ? 0 : 1; } diff --git a/test/messages/verify_asynchronous_backend/verify_asynchronous_backend.cpp b/test/messages/verify_asynchronous_backend/verify_asynchronous_backend.cpp index b1563ee2..99a4a01f 100644 --- a/test/messages/verify_asynchronous_backend/verify_asynchronous_backend.cpp +++ b/test/messages/verify_asynchronous_backend/verify_asynchronous_backend.cpp @@ -35,8 +35,9 @@ int main() { crypto::curves::ed25519::public_key::from_bytes(std::array{}); crypto::curves::ed25519::signature const signature{}; std::array const message{'h', 'e', 'l', 'l', 'o'}; - return public_key && public_key->verify(crypto::signing_schemes::eddsa, - signature, message) + return public_key && public_key->verify( + crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, signature, message) ? 0 : 1; } diff --git a/test/messages/verify_ecdsa_bytes_key/verify_ecdsa_bytes_key.cpp b/test/messages/verify_ecdsa_bytes_key/verify_ecdsa_bytes_key.cpp index 7a9a9fe0..5f92b7f1 100644 --- a/test/messages/verify_ecdsa_bytes_key/verify_ecdsa_bytes_key.cpp +++ b/test/messages/verify_ecdsa_bytes_key/verify_ecdsa_bytes_key.cpp @@ -23,7 +23,8 @@ int main() { namespace crypto = webcpp::crypto; crypto::curves::secp256k1::ecdsa_signature const signature{}; std::array const message{'h', 'e', 'l', 'l', 'o'}; - return crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, message, + return crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, signature, message, std::array{}) ? 0 : 1; diff --git a/test/messages/verify_ed25519_bytes_signature/verify_ed25519_bytes_signature.cpp b/test/messages/verify_ed25519_bytes_signature/verify_ed25519_bytes_signature.cpp index 08f4cd7a..6cba2c3a 100644 --- a/test/messages/verify_ed25519_bytes_signature/verify_ed25519_bytes_signature.cpp +++ b/test/messages/verify_ed25519_bytes_signature/verify_ed25519_bytes_signature.cpp @@ -25,8 +25,9 @@ int main() { crypto::curves::ed25519::public_key::from_bytes(std::array{}); std::array const signature{}; std::array const message{'h', 'e', 'l', 'l', 'o'}; - return public_key && - crypto::verify(crypto::signing_schemes::eddsa, signature, message, *public_key) + return public_key && crypto::verify(crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, signature, + message, *public_key) ? 0 : 1; } diff --git a/test/messages/verify_eddsa_bytes_key/verify_eddsa_bytes_key.cpp b/test/messages/verify_eddsa_bytes_key/verify_eddsa_bytes_key.cpp index b2e71f47..35b0b274 100644 --- a/test/messages/verify_eddsa_bytes_key/verify_eddsa_bytes_key.cpp +++ b/test/messages/verify_eddsa_bytes_key/verify_eddsa_bytes_key.cpp @@ -23,8 +23,8 @@ int main() { namespace crypto = webcpp::crypto; crypto::curves::ed25519::signature const signature{}; std::array const message{'h', 'e', 'l', 'l', 'o'}; - return crypto::verify(crypto::signing_schemes::eddsa, signature, message, - std::array{}) + return crypto::verify(crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, + signature, message, std::array{}) ? 0 : 1; } diff --git a/test/messages/verify_eddsa_low_s_only/Jamfile b/test/messages/verify_eddsa_low_s_only/Jamfile new file mode 100644 index 00000000..306d61db --- /dev/null +++ b/test/messages/verify_eddsa_low_s_only/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic verify_eddsa_low_s_only : verify_eddsa_low_s_only.cpp + : /third_party//sodium : native wasip2 wasip3 : alone ; diff --git a/test/messages/verify_eddsa_low_s_only/verify_eddsa_low_s_only.cpp b/test/messages/verify_eddsa_low_s_only/verify_eddsa_low_s_only.cpp new file mode 100644 index 00000000..369f8e8c --- /dev/null +++ b/test/messages/verify_eddsa_low_s_only/verify_eddsa_low_s_only.cpp @@ -0,0 +1,34 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// crypto::verify of crypto::signing_schemes::eddsa under crypto::verification_policies::low_s_only, +// ECDSA's policy, which Ed25519 does not take, stops with the message that names the one it takes, +// canonical, and with that error alone. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/signing.hpp:* {{webcpp::crypto: verify: crypto::signing_schemes::eddsa and eddsa_prehashed take crypto::verification_policies::canonical.}} +// clang-format on + +#include +#include + +#include +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + auto const public_key = + crypto::curves::ed25519::public_key::from_bytes(std::array{}); + crypto::curves::ed25519::signature const signature{}; + return public_key && crypto::verify(crypto::signing_schemes::eddsa, + crypto::verification_policies::low_s_only, signature, + std::span{}, *public_key) + ? 0 + : 1; +} diff --git a/test/messages/verify_eddsa_prehashed_asynchronous_backend/verify_eddsa_prehashed_asynchronous_backend.cpp b/test/messages/verify_eddsa_prehashed_asynchronous_backend/verify_eddsa_prehashed_asynchronous_backend.cpp index ba691c64..e3af2f5a 100644 --- a/test/messages/verify_eddsa_prehashed_asynchronous_backend/verify_eddsa_prehashed_asynchronous_backend.cpp +++ b/test/messages/verify_eddsa_prehashed_asynchronous_backend/verify_eddsa_prehashed_asynchronous_backend.cpp @@ -45,12 +45,12 @@ bool verified(webcpp::crypto::curves::ed25519::public_key const& public_key) { namespace crypto = webcpp::crypto; crypto::curves::ed25519::signature const signature{}; std::array const digest{}; - auto const free_verified = - crypto::verify(crypto::signing_schemes::eddsa_prehashed, signature, - crypto::signing_schemes::prehashed{digest}, public_key); + auto const free_verified = crypto::verify( + crypto::signing_schemes::eddsa_prehashed, crypto::verification_policies::canonical, + signature, crypto::signing_schemes::prehashed{digest}, public_key); auto const member_verified = public_key.verify( - crypto::signing_schemes::eddsa_prehashed, signature, - crypto::signing_schemes::prehashed{digest}); + crypto::signing_schemes::eddsa_prehashed, crypto::verification_policies::canonical, + signature, crypto::signing_schemes::prehashed{digest}); return free_verified && member_verified; } diff --git a/test/messages/verify_eddsa_prehashed_message/verify_eddsa_prehashed_message.cpp b/test/messages/verify_eddsa_prehashed_message/verify_eddsa_prehashed_message.cpp index 8aa4c53b..d5c9f880 100644 --- a/test/messages/verify_eddsa_prehashed_message/verify_eddsa_prehashed_message.cpp +++ b/test/messages/verify_eddsa_prehashed_message/verify_eddsa_prehashed_message.cpp @@ -25,7 +25,8 @@ int main() { crypto::curves::ed25519::public_key::from_bytes(std::array{}); crypto::curves::ed25519::signature const signature{}; std::array const message{'h', 'e', 'l', 'l', 'o'}; - return public_key && crypto::verify(crypto::signing_schemes::eddsa_prehashed, signature, + return public_key && crypto::verify(crypto::signing_schemes::eddsa_prehashed, + crypto::verification_policies::canonical, signature, message, *public_key) ? 0 : 1; diff --git a/test/messages/verify_free_asynchronous_backend/verify_free_asynchronous_backend.cpp b/test/messages/verify_free_asynchronous_backend/verify_free_asynchronous_backend.cpp index 21c46701..9e2f7825 100644 --- a/test/messages/verify_free_asynchronous_backend/verify_free_asynchronous_backend.cpp +++ b/test/messages/verify_free_asynchronous_backend/verify_free_asynchronous_backend.cpp @@ -37,7 +37,8 @@ bool verified(webcpp::crypto::curves::p256::basic_public_key c namespace crypto = webcpp::crypto; crypto::curves::p256::ecdsa_signature const signature{}; std::array const message{'h', 'e', 'l', 'l', 'o'}; - return crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, message, public_key) + return crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, signature, message, public_key) .has_value(); } diff --git a/test/messages/verify_free_secp256k1_recoverable/verify_free_secp256k1_recoverable.cpp b/test/messages/verify_free_secp256k1_recoverable/verify_free_secp256k1_recoverable.cpp index cf08fbae..aa824465 100644 --- a/test/messages/verify_free_secp256k1_recoverable/verify_free_secp256k1_recoverable.cpp +++ b/test/messages/verify_free_secp256k1_recoverable/verify_free_secp256k1_recoverable.cpp @@ -32,7 +32,8 @@ int main() { crypto::curves::secp256k1::recoverable_signature const signature{}; std::array const message{'h', 'e', 'l', 'l', 'o'}; return public_key && crypto::verify(crypto::signing_schemes::ecdsa_sha256_recoverable, - signature, message, *public_key) + crypto::verification_policies::low_s_only, signature, + message, *public_key) ? 0 : 1; } diff --git a/test/messages/verify_keccak_recoverable/verify_keccak_recoverable.cpp b/test/messages/verify_keccak_recoverable/verify_keccak_recoverable.cpp index f0e485c5..ff1d0e34 100644 --- a/test/messages/verify_keccak_recoverable/verify_keccak_recoverable.cpp +++ b/test/messages/verify_keccak_recoverable/verify_keccak_recoverable.cpp @@ -32,7 +32,8 @@ int main() { auto const signature = key->sign(crypto::signing_schemes::ecdsa_keccak256_recoverable, crypto::signing_schemes::prehashed{digest}); return public_key && signature && - crypto::verify(crypto::signing_schemes::ecdsa_keccak256_recoverable, *signature, + crypto::verify(crypto::signing_schemes::ecdsa_keccak256_recoverable, + crypto::verification_policies::low_s_only, *signature, crypto::signing_schemes::prehashed{digest}, *public_key) ? 0 : 1; diff --git a/test/messages/verify_member_ed25519_ecdsa/verify_member_ed25519_ecdsa.cpp b/test/messages/verify_member_ed25519_ecdsa/verify_member_ed25519_ecdsa.cpp index 87cb7d58..9de404cf 100644 --- a/test/messages/verify_member_ed25519_ecdsa/verify_member_ed25519_ecdsa.cpp +++ b/test/messages/verify_member_ed25519_ecdsa/verify_member_ed25519_ecdsa.cpp @@ -25,7 +25,8 @@ int main() { crypto::curves::ed25519::signature const signature{}; std::array const message{'h', 'e', 'l', 'l', 'o'}; return public_key && - public_key->verify(crypto::signing_schemes::ecdsa_sha256, signature, message) + public_key->verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, signature, message) ? 0 : 1; } diff --git a/test/messages/verify_member_eddsa_prehashed/verify_member_eddsa_prehashed.cpp b/test/messages/verify_member_eddsa_prehashed/verify_member_eddsa_prehashed.cpp index b3588dd1..79d23060 100644 --- a/test/messages/verify_member_eddsa_prehashed/verify_member_eddsa_prehashed.cpp +++ b/test/messages/verify_member_eddsa_prehashed/verify_member_eddsa_prehashed.cpp @@ -26,7 +26,8 @@ int main() { crypto::curves::ed25519::public_key::from_bytes(std::array{}); crypto::curves::ed25519::signature const signature{}; std::array const digest{}; - return public_key && public_key->verify(crypto::signing_schemes::eddsa, signature, + return public_key && public_key->verify(crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, signature, crypto::signing_schemes::prehashed{digest}) ? 0 : 1; diff --git a/test/messages/verify_member_p256_eddsa/verify_member_p256_eddsa.cpp b/test/messages/verify_member_p256_eddsa/verify_member_p256_eddsa.cpp index 54679cb8..e6c4985c 100644 --- a/test/messages/verify_member_p256_eddsa/verify_member_p256_eddsa.cpp +++ b/test/messages/verify_member_p256_eddsa/verify_member_p256_eddsa.cpp @@ -30,6 +30,9 @@ int main() { auto const public_key = key->public_key(); crypto::curves::p256::ecdsa_signature const signature{}; std::array const message{'h', 'e', 'l', 'l', 'o'}; - return public_key && public_key->verify(crypto::signing_schemes::eddsa, signature, message) ? 0 - : 1; + return public_key && + public_key->verify(crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, signature, message) + ? 0 + : 1; } diff --git a/test/messages/verify_member_secp256k1_recoverable/verify_member_secp256k1_recoverable.cpp b/test/messages/verify_member_secp256k1_recoverable/verify_member_secp256k1_recoverable.cpp index a0626f1b..e2393803 100644 --- a/test/messages/verify_member_secp256k1_recoverable/verify_member_secp256k1_recoverable.cpp +++ b/test/messages/verify_member_secp256k1_recoverable/verify_member_secp256k1_recoverable.cpp @@ -30,8 +30,9 @@ int main() { auto const public_key = key->public_key(); crypto::curves::secp256k1::recoverable_signature const signature{}; std::array const message{'h', 'e', 'l', 'l', 'o'}; - return public_key && public_key->verify(crypto::signing_schemes::ecdsa_sha256_recoverable, - signature, message) + return public_key && + public_key->verify(crypto::signing_schemes::ecdsa_sha256_recoverable, + crypto::verification_policies::low_s_only, signature, message) ? 0 : 1; } diff --git a/test/messages/verify_p256_canonical/Jamfile b/test/messages/verify_p256_canonical/Jamfile new file mode 100644 index 00000000..2af95ce9 --- /dev/null +++ b/test/messages/verify_p256_canonical/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic verify_p256_canonical : verify_p256_canonical.cpp + : /third_party//bearssl : native wasip2 wasip3 : alone ; diff --git a/test/messages/verify_p256_canonical/verify_p256_canonical.cpp b/test/messages/verify_p256_canonical/verify_p256_canonical.cpp new file mode 100644 index 00000000..3b963cfe --- /dev/null +++ b/test/messages/verify_p256_canonical/verify_p256_canonical.cpp @@ -0,0 +1,41 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// crypto::verify of crypto::signing_schemes::ecdsa_sha256 against a P-256 public key under +// crypto::verification_policies::canonical, which P-256's ECDSA does not take, stops with the +// message that names the two it takes, low_s_only and any_s, and with that error alone. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/signing.hpp:* {{webcpp::crypto: verify: crypto::signing_schemes::ecdsa_sha256 on a P-256 key takes crypto::verification_policies::low_s_only or any_s.}} +// clang-format on + +#include +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const scalar{1}; + std::array const message{'h', 'e', 'l', 'l', 'o'}; + auto const made = crypto::curves::p256::keypair::from_secret(scalar); + if (!made) { + return 1; + } + auto const public_key = made->public_key(); + auto const signature = made->sign(crypto::signing_schemes::ecdsa_sha256, message); + if (!public_key || !signature) { + return 1; + } + return crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::canonical, *signature, message, + *public_key) + ? 0 + : 1; +} diff --git a/test/messages/verify_p256_secp256k1_signature/verify_p256_secp256k1_signature.cpp b/test/messages/verify_p256_secp256k1_signature/verify_p256_secp256k1_signature.cpp index 33025259..8989c79b 100644 --- a/test/messages/verify_p256_secp256k1_signature/verify_p256_secp256k1_signature.cpp +++ b/test/messages/verify_p256_secp256k1_signature/verify_p256_secp256k1_signature.cpp @@ -32,8 +32,9 @@ int main() { auto const public_key = key->public_key(); crypto::curves::secp256k1::ecdsa_signature const signature{}; std::array const message{'h', 'e', 'l', 'l', 'o'}; - return public_key && crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, message, - *public_key) + return public_key && crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, signature, + message, *public_key) ? 0 : 1; } diff --git a/test/messages/verify_schnorr_any_s/Jamfile b/test/messages/verify_schnorr_any_s/Jamfile new file mode 100644 index 00000000..25b6f126 --- /dev/null +++ b/test/messages/verify_schnorr_any_s/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic verify_schnorr_any_s : verify_schnorr_any_s.cpp + : /third_party//secp256k1 : native wasip2 wasip3 : alone ; diff --git a/test/messages/verify_schnorr_any_s/verify_schnorr_any_s.cpp b/test/messages/verify_schnorr_any_s/verify_schnorr_any_s.cpp new file mode 100644 index 00000000..428f3dd2 --- /dev/null +++ b/test/messages/verify_schnorr_any_s/verify_schnorr_any_s.cpp @@ -0,0 +1,40 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// crypto::verify of crypto::signing_schemes::schnorr under crypto::verification_policies::any_s, +// a policy BIP340 does not take, stops with the message that names the one it takes, canonical, +// and with that error alone. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/signing.hpp:* {{webcpp::crypto: verify: crypto::signing_schemes::schnorr takes crypto::verification_policies::canonical.}} +// clang-format on + +#include +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const seed{1}; + std::array const message{'h', 'e', 'l', 'l', 'o'}; + auto const made = crypto::curves::secp256k1::keypair::from_secret(seed); + if (!made) { + return 1; + } + auto const public_key = made->public_key(); + auto const signature = made->sign(crypto::signing_schemes::schnorr, message); + if (!public_key || !signature) { + return 1; + } + return crypto::verify(crypto::signing_schemes::schnorr, crypto::verification_policies::any_s, + *signature, message, *public_key) + ? 0 + : 1; +} diff --git a/test/messages/verify_schnorr_as_ecdsa/verify_schnorr_as_ecdsa.cpp b/test/messages/verify_schnorr_as_ecdsa/verify_schnorr_as_ecdsa.cpp index 209f59a3..38ada8f1 100644 --- a/test/messages/verify_schnorr_as_ecdsa/verify_schnorr_as_ecdsa.cpp +++ b/test/messages/verify_schnorr_as_ecdsa/verify_schnorr_as_ecdsa.cpp @@ -31,7 +31,8 @@ int main() { std::array const message{'h', 'e', 'l', 'l', 'o'}; auto const signature = key->sign(crypto::signing_schemes::schnorr, message); return public_key && signature && - crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signature, message, + crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *signature, message, *public_key) ? 0 : 1; diff --git a/test/messages/verify_secp256k1_any_s/Jamfile b/test/messages/verify_secp256k1_any_s/Jamfile new file mode 100644 index 00000000..fb4fa70e --- /dev/null +++ b/test/messages/verify_secp256k1_any_s/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic verify_secp256k1_any_s : verify_secp256k1_any_s.cpp + : /third_party//secp256k1 : native wasip2 wasip3 : alone ; diff --git a/test/messages/verify_secp256k1_any_s/verify_secp256k1_any_s.cpp b/test/messages/verify_secp256k1_any_s/verify_secp256k1_any_s.cpp new file mode 100644 index 00000000..2df1d2d4 --- /dev/null +++ b/test/messages/verify_secp256k1_any_s/verify_secp256k1_any_s.cpp @@ -0,0 +1,40 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// crypto::verify of crypto::signing_schemes::ecdsa_sha256 against a secp256k1 public key under +// crypto::verification_policies::any_s, a policy secp256k1's ECDSA does not take, stops with the +// message that names the one it takes, low_s_only, and with that error alone. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/signing.hpp:* {{webcpp::crypto: verify: crypto::signing_schemes::ecdsa_sha256 on a secp256k1 key takes crypto::verification_policies::low_s_only.}} +// clang-format on + +#include +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const seed{1}; + std::array const message{'h', 'e', 'l', 'l', 'o'}; + auto const made = crypto::curves::secp256k1::keypair::from_secret(seed); + if (!made) { + return 1; + } + auto const public_key = made->public_key(); + auto const signature = made->sign(crypto::signing_schemes::ecdsa_sha256, message); + if (!public_key || !signature) { + return 1; + } + return crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::any_s, *signature, message, *public_key) + ? 0 + : 1; +} diff --git a/test/messages/verify_without_policy/Jamfile b/test/messages/verify_without_policy/Jamfile new file mode 100644 index 00000000..6b83682f --- /dev/null +++ b/test/messages/verify_without_policy/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic verify_without_policy : verify_without_policy.cpp + : /third_party//sodium : native wasip2 wasip3 : alone ; diff --git a/test/messages/verify_without_policy/verify_without_policy.cpp b/test/messages/verify_without_policy/verify_without_policy.cpp new file mode 100644 index 00000000..dc074cce --- /dev/null +++ b/test/messages/verify_without_policy/verify_without_policy.cpp @@ -0,0 +1,33 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// crypto::verify of crypto::signing_schemes::eddsa in the arity before the verification policies, +// verify(scheme, signature, message, public_key), stops at the catch-all, whose message says that +// verify takes a policy after the scheme and names Ed25519's, canonical, and with that error alone. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/signing.hpp:* {{webcpp::crypto: verify takes a verification policy after the scheme: crypto::signing_schemes::eddsa takes crypto::verification_policies::canonical.}} +// clang-format on + +#include +#include + +#include +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + auto const public_key = + crypto::curves::ed25519::public_key::from_bytes(std::array{}); + crypto::curves::ed25519::signature const signature{}; + return public_key && crypto::verify(crypto::signing_schemes::eddsa, signature, + std::span{}, *public_key) + ? 0 + : 1; +} diff --git a/test/msvc/Jamfile b/test/msvc/Jamfile index 5d8f116f..8b190b44 100644 --- a/test/msvc/Jamfile +++ b/test/msvc/Jamfile @@ -74,3 +74,10 @@ build-project p256_on_sodium ; build-project aes_block_default_not_linked ; build-project sign_keccak_without_xkcp ; build-project sign_eddsa_prehashed_message ; +build-project verify_without_policy ; +build-project async_verify_without_policy ; +build-project verify_secp256k1_any_s ; +build-project verify_schnorr_any_s ; +build-project verify_eddsa_low_s_only ; +build-project verify_p256_canonical ; +build-project recover_any_s ; diff --git a/test/msvc/async_verify_without_policy/Jamfile b/test/msvc/async_verify_without_policy/Jamfile new file mode 100644 index 00000000..9abba745 --- /dev/null +++ b/test/msvc/async_verify_without_policy/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail async_verify_without_policy : app.cpp + : /webcpp/crypto//crypto /webcpp/asio//asio /third_party//bearssl + : native ; diff --git a/test/msvc/async_verify_without_policy/app.cpp b/test/msvc/async_verify_without_policy/app.cpp new file mode 100644 index 00000000..891c8754 --- /dev/null +++ b/test/msvc/async_verify_without_policy/app.cpp @@ -0,0 +1,40 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// crypto::async_verify of crypto::signing_schemes::ecdsa_sha256 against a P-256 public key in the +// arity before the verification policies, async_verify(executor, scheme, signature, message, +// public_key, token), stops at the catch-all, whose message names the policies P-256's ECDSA +// takes, low_s_only or any_s, and with that error alone. On MSVC the compile fails; the text is +// checked on clang, in test/messages/async_verify_without_policy. +#include +#include +#include + +#include + +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const scalar{1}; + std::array const message{'h', 'e', 'l', 'l', 'o'}; + auto const made = crypto::curves::p256::keypair::from_secret(scalar); + if (!made) { + return 1; + } + auto const public_key = made->public_key(); + auto const signature = made->sign(crypto::signing_schemes::ecdsa_sha256, message); + if (!public_key || !signature) { + return 1; + } + webcpp::asio::io_context context; + crypto::async_verify(context.get_executor(), crypto::signing_schemes::ecdsa_sha256, *signature, + message, *public_key, [](boost::system::error_code) {}); + return 0; +} diff --git a/test/msvc/ed25519_unknown_policy/app.cpp b/test/msvc/ed25519_unknown_policy/app.cpp index 67bb2cde..9260c93c 100644 --- a/test/msvc/ed25519_unknown_policy/app.cpp +++ b/test/msvc/ed25519_unknown_policy/app.cpp @@ -4,9 +4,10 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// A program that names a policy of its own in Ed25519's crypto::verify, on its default backend -// linked, stops where it calls it, with the one policy there is. On MSVC the compile fails; the -// text is checked on clang, in test/messages/ed25519_unknown_policy. +// A program that names a policy of its own in Ed25519's crypto::verify, in the policy's place after +// the scheme, on its default backend linked, stops where it calls it, with the one policy Ed25519 +// takes. On MSVC the compile fails; the text is checked on clang, in +// test/messages/ed25519_unknown_policy. #include #include @@ -26,8 +27,8 @@ int main() { webcpp::crypto::curves::ed25519::public_key::from_bytes(std::array{}); webcpp::crypto::curves::ed25519::signature const signature{}; return public_key && - webcpp::crypto::verify(webcpp::crypto::signing_schemes::eddsa, signature, - std::span{}, *public_key, lenient{}) + webcpp::crypto::verify(webcpp::crypto::signing_schemes::eddsa, lenient{}, + signature, std::span{}, *public_key) ? 0 : 1; } diff --git a/test/msvc/recover_any_s/Jamfile b/test/msvc/recover_any_s/Jamfile new file mode 100644 index 00000000..a77ff5d3 --- /dev/null +++ b/test/msvc/recover_any_s/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail recover_any_s : app.cpp + : /webcpp/crypto//crypto /third_party//secp256k1 + : native ; diff --git a/test/msvc/recover_any_s/app.cpp b/test/msvc/recover_any_s/app.cpp new file mode 100644 index 00000000..60f06ab1 --- /dev/null +++ b/test/msvc/recover_any_s/app.cpp @@ -0,0 +1,34 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// curves::secp256k1::recover of crypto::signing_schemes::ecdsa_sha256_recoverable under +// crypto::verification_policies::any_s, which recovery does not take, stops with the message that +// names the one it takes, low_s_only, and with that error alone. On MSVC the compile fails; the +// text is checked on clang, in test/messages/recover_any_s. +#include +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const seed{1}; + std::array const message{'h', 'e', 'l', 'l', 'o'}; + auto const made = crypto::curves::secp256k1::keypair::from_secret(seed); + if (!made) { + return 1; + } + auto const signature = made->sign(crypto::signing_schemes::ecdsa_sha256_recoverable, message); + if (!signature) { + return 1; + } + return crypto::curves::secp256k1::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, + crypto::verification_policies::any_s, *signature, + message) + ? 0 + : 1; +} diff --git a/test/msvc/verify_eddsa_low_s_only/Jamfile b/test/msvc/verify_eddsa_low_s_only/Jamfile new file mode 100644 index 00000000..10f39e70 --- /dev/null +++ b/test/msvc/verify_eddsa_low_s_only/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail verify_eddsa_low_s_only : app.cpp + : /webcpp/crypto//crypto /third_party//sodium + : native ; diff --git a/test/msvc/verify_eddsa_low_s_only/app.cpp b/test/msvc/verify_eddsa_low_s_only/app.cpp new file mode 100644 index 00000000..7bc74763 --- /dev/null +++ b/test/msvc/verify_eddsa_low_s_only/app.cpp @@ -0,0 +1,28 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// crypto::verify of crypto::signing_schemes::eddsa under crypto::verification_policies::low_s_only, +// ECDSA's policy, which Ed25519 does not take, stops with the message that names the one it takes, +// canonical, and with that error alone. On MSVC the compile fails; the text is checked on clang, in +// test/messages/verify_eddsa_low_s_only. +#include +#include + +#include +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + auto const public_key = + crypto::curves::ed25519::public_key::from_bytes(std::array{}); + crypto::curves::ed25519::signature const signature{}; + return public_key && crypto::verify(crypto::signing_schemes::eddsa, + crypto::verification_policies::low_s_only, signature, + std::span{}, *public_key) + ? 0 + : 1; +} diff --git a/test/msvc/verify_p256_canonical/Jamfile b/test/msvc/verify_p256_canonical/Jamfile new file mode 100644 index 00000000..1cba09b0 --- /dev/null +++ b/test/msvc/verify_p256_canonical/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail verify_p256_canonical : app.cpp + : /webcpp/crypto//crypto /third_party//bearssl + : native ; diff --git a/test/msvc/verify_p256_canonical/app.cpp b/test/msvc/verify_p256_canonical/app.cpp new file mode 100644 index 00000000..c6f4849d --- /dev/null +++ b/test/msvc/verify_p256_canonical/app.cpp @@ -0,0 +1,35 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the 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::verify of crypto::signing_schemes::ecdsa_sha256 against a P-256 public key under +// crypto::verification_policies::canonical, which P-256's ECDSA does not take, stops with the +// message that names the two it takes, low_s_only and any_s, and with that error alone. On MSVC the +// compile fails; the text is checked on clang, in test/messages/verify_p256_canonical. +#include +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const scalar{1}; + std::array const message{'h', 'e', 'l', 'l', 'o'}; + auto const made = crypto::curves::p256::keypair::from_secret(scalar); + if (!made) { + return 1; + } + auto const public_key = made->public_key(); + auto const signature = made->sign(crypto::signing_schemes::ecdsa_sha256, message); + if (!public_key || !signature) { + return 1; + } + return crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::canonical, *signature, message, + *public_key) + ? 0 + : 1; +} diff --git a/test/msvc/verify_schnorr_any_s/Jamfile b/test/msvc/verify_schnorr_any_s/Jamfile new file mode 100644 index 00000000..93c3eff6 --- /dev/null +++ b/test/msvc/verify_schnorr_any_s/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail verify_schnorr_any_s : app.cpp + : /webcpp/crypto//crypto /third_party//secp256k1 + : native ; diff --git a/test/msvc/verify_schnorr_any_s/app.cpp b/test/msvc/verify_schnorr_any_s/app.cpp new file mode 100644 index 00000000..ed1803d1 --- /dev/null +++ b/test/msvc/verify_schnorr_any_s/app.cpp @@ -0,0 +1,34 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// crypto::verify of crypto::signing_schemes::schnorr under crypto::verification_policies::any_s, +// a policy BIP340 does not take, stops with the message that names the one it takes, canonical, +// and with that error alone. On MSVC the compile fails; the text is checked on clang, in +// test/messages/verify_schnorr_any_s. +#include +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const seed{1}; + std::array const message{'h', 'e', 'l', 'l', 'o'}; + auto const made = crypto::curves::secp256k1::keypair::from_secret(seed); + if (!made) { + return 1; + } + auto const public_key = made->public_key(); + auto const signature = made->sign(crypto::signing_schemes::schnorr, message); + if (!public_key || !signature) { + return 1; + } + return crypto::verify(crypto::signing_schemes::schnorr, crypto::verification_policies::any_s, + *signature, message, *public_key) + ? 0 + : 1; +} diff --git a/test/msvc/verify_secp256k1_any_s/Jamfile b/test/msvc/verify_secp256k1_any_s/Jamfile new file mode 100644 index 00000000..7ea94a19 --- /dev/null +++ b/test/msvc/verify_secp256k1_any_s/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail verify_secp256k1_any_s : app.cpp + : /webcpp/crypto//crypto /third_party//secp256k1 + : native ; diff --git a/test/msvc/verify_secp256k1_any_s/app.cpp b/test/msvc/verify_secp256k1_any_s/app.cpp new file mode 100644 index 00000000..6c1fb3ac --- /dev/null +++ b/test/msvc/verify_secp256k1_any_s/app.cpp @@ -0,0 +1,34 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// crypto::verify of crypto::signing_schemes::ecdsa_sha256 against a secp256k1 public key under +// crypto::verification_policies::any_s, a policy secp256k1's ECDSA does not take, stops with the +// message that names the one it takes, low_s_only, and with that error alone. On MSVC the compile +// fails; the text is checked on clang, in test/messages/verify_secp256k1_any_s. +#include +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const seed{1}; + std::array const message{'h', 'e', 'l', 'l', 'o'}; + auto const made = crypto::curves::secp256k1::keypair::from_secret(seed); + if (!made) { + return 1; + } + auto const public_key = made->public_key(); + auto const signature = made->sign(crypto::signing_schemes::ecdsa_sha256, message); + if (!public_key || !signature) { + return 1; + } + return crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::any_s, *signature, message, *public_key) + ? 0 + : 1; +} diff --git a/test/msvc/verify_without_policy/Jamfile b/test/msvc/verify_without_policy/Jamfile new file mode 100644 index 00000000..b7687262 --- /dev/null +++ b/test/msvc/verify_without_policy/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail verify_without_policy : app.cpp + : /webcpp/crypto//crypto /third_party//sodium + : native ; diff --git a/test/msvc/verify_without_policy/app.cpp b/test/msvc/verify_without_policy/app.cpp new file mode 100644 index 00000000..ce850337 --- /dev/null +++ b/test/msvc/verify_without_policy/app.cpp @@ -0,0 +1,27 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// crypto::verify of crypto::signing_schemes::eddsa in the arity before the verification policies, +// verify(scheme, signature, message, public_key), stops at the catch-all, whose message says that +// verify takes a policy after the scheme and names Ed25519's, canonical, and with that error alone. +// On MSVC the compile fails; the text is checked on clang, in test/messages/verify_without_policy. +#include +#include + +#include +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + auto const public_key = + crypto::curves::ed25519::public_key::from_bytes(std::array{}); + crypto::curves::ed25519::signature const signature{}; + return public_key && crypto::verify(crypto::signing_schemes::eddsa, signature, + std::span{}, *public_key) + ? 0 + : 1; +} diff --git a/test/oracle_25519_test.cpp b/test/oracle_25519_test.cpp index a1ae554c..c5049328 100644 --- a/test/oracle_25519_test.cpp +++ b/test/oracle_25519_test.cpp @@ -170,7 +170,9 @@ bool ed25519_case(std::mt19937_64& rng, std::size_t index) { if (!public_key || !signed_message) { return false; } - BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, *signed_message, message, *public_key) + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, *signed_message, message, + *public_key) .has_value()); // The signature's bytes, as WebCrypto is given them. auto signature = signed_message->bytes(); diff --git a/test/p256_ecdsa_bearssl_test.cpp b/test/p256_ecdsa_bearssl_test.cpp index aa9b5812..d0ba14ab 100644 --- a/test/p256_ecdsa_bearssl_test.cpp +++ b/test/p256_ecdsa_bearssl_test.cpp @@ -8,8 +8,9 @@ // p256::ecdsa_signature, and verify takes one, made from 64 bytes received (a vector) with // from_bytes, which refuses 63 and 65; RFC 6979's two SHA-256 // signatures byte for byte, low S (the "sample" one normalized), the same on every signing, from -// the message and from its digest; verification of both forms of a signature and every refusal -// (a bit of the digest, of r or of s, another key, r or s 0 or n), and the digests 0 modulo n +// the message and from its digest; verification of both forms of a signature under any_s, the +// high one refused under low_s_only, and every refusal (a bit of the digest, of r or of s, another +// key, r or s 0 or n), and the digests 0 modulo n // that BearSSL refuses; a 32-byte message hashed, never read as a digest; the empty message; // is_low_s and normalize_low_s at their boundary; low S over 1,000 signatures of random digests // under a key and 256 of random messages under keys of their own, all drawn from a printed seed @@ -213,10 +214,17 @@ void rfc6979_sample_message() { auto const& section = *received; BOOST_TEST(std::ranges::equal(r_of(*signed_message), section_r)); BOOST_TEST(std::ranges::equal(s_of(*signed_message), negated(section_s))); - BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, section, text_bytes("sample"), + // The RFC's signature, whose S is high: any_s accepts it, low_s_only refuses it. + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::any_s, section, text_bytes("sample"), *verifier) .has_value()); - BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signed_message, + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, section, + text_bytes("sample"), *verifier) + .error() == error::invalid_signature); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *signed_message, text_bytes("sample"), *verifier) .has_value()); BOOST_TEST(!p256::is_low_s(section)); @@ -236,7 +244,8 @@ void verify_both_forms() { auto const test = sha256("test"); auto const verified = [](signature_bytes const& value, digest const& hash, public_key const& verifier) { - return crypto::verify(crypto::signing_schemes::ecdsa_sha256, typed(value), + return crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::any_s, typed(value), crypto::signing_schemes::prehashed{hash}, verifier); }; BOOST_TEST(verified(data::rfc6979_sample, sample, *key).has_value()); @@ -304,10 +313,12 @@ void message_is_hashed() { } BOOST_TEST(*of_message == *of_digest); BOOST_TEST(*of_message != *of_marker); - BOOST_TEST( - crypto::verify(crypto::signing_schemes::ecdsa_sha256, *of_message, message, *verifier) - .has_value()); - BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *of_message, + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *of_message, message, + *verifier) + .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *of_message, crypto::signing_schemes::prehashed{message}, *verifier) .error() == error::invalid_signature); } @@ -324,15 +335,18 @@ void empty_message() { if (!BOOST_TEST(signed_empty.has_value())) { return; } - BOOST_TEST( - crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signed_empty, empty, *verifier) - .has_value()); - BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signed_empty, - crypto::signing_schemes::prehashed{crypto::detail::sha256_of(empty)}, + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *signed_empty, empty, *verifier) .has_value()); - BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signed_empty, text_bytes("x"), + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *signed_empty, + crypto::signing_schemes::prehashed{crypto::detail::sha256_of(empty)}, *verifier) + .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *signed_empty, + text_bytes("x"), *verifier) .error() == error::invalid_signature); } @@ -350,7 +364,8 @@ void zero_digest() { auto const signed_hash = key->sign(crypto::signing_schemes::ecdsa_sha256, crypto::signing_schemes::prehashed{hash}); if (BOOST_TEST(signed_hash.has_value())) { - BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signed_hash, + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *signed_hash, crypto::signing_schemes::prehashed{hash}, *verifier) .error() == error::invalid_signature); } @@ -437,14 +452,20 @@ void low_s_random(std::uint64_t seed) { return; } BOOST_TEST(p256::is_low_s(*signed_hash)); - BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signed_hash, + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *signed_hash, crypto::signing_schemes::prehashed{hash}, *verifier) .has_value()); auto const high = typed(joined(r_of(*signed_hash), negated(s_of(*signed_hash)))); BOOST_TEST(!p256::is_low_s(high)); - BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, high, + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::any_s, high, crypto::signing_schemes::prehashed{hash}, *verifier) .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, high, + crypto::signing_schemes::prehashed{hash}, *verifier) + .error() == error::invalid_signature); auto const normalized = p256::normalize_low_s(high); if (!BOOST_TEST(normalized.has_value())) { return; @@ -467,8 +488,9 @@ void always_low_s(std::uint64_t seed) { return; } BOOST_TEST(p256::is_low_s(*signed_message)); - BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signed_message, message, - *verifier) + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *signed_message, + message, *verifier) .has_value()); } } @@ -596,10 +618,13 @@ void signature_from_vector() { return; } BOOST_TEST(*made == *signed_message); - BOOST_TEST(verifier->verify(crypto::signing_schemes::ecdsa_sha256, *made, text_bytes("sample")) + BOOST_TEST(verifier + ->verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *made, text_bytes("sample")) .has_value()); - BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *made, text_bytes("sample"), - *verifier) + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *made, + text_bytes("sample"), *verifier) .has_value()); BOOST_TEST(crypto::from_bytes(received).has_value()); for (std::size_t const size : {std::size_t{63}, std::size_t{65}}) { @@ -614,22 +639,26 @@ static_assert(crypto::can_sign>); static_assert(crypto::can_sign>); -static_assert(crypto::can_verify, public_key>); static_assert( !crypto::can_sign, crypto::signing_schemes::ecdsa_sha256_t, std::span>); -static_assert(!crypto::can_verify, keypair>); // Bytes are no P-256 key: ECDSA never infers its curve from a number of bytes. -static_assert(!crypto::can_verify, std::array>); // Bytes are no P-256 signature (design R1): verify takes the type alone. -static_assert(!crypto::can_verify, public_key>); -static_assert( - !crypto::can_verify, - std::span, public_key>); +static_assert(!crypto::can_verify< + crypto::signing_schemes::ecdsa_sha256_t, crypto::verification_policies::low_s_only_t, + std::span, std::span, public_key>); // sign gives the type. static_assert(std::is_same_v().sign( crypto::signing_schemes::ecdsa_sha256, diff --git a/test/p256_keys_bearssl_test.cpp b/test/p256_keys_bearssl_test.cpp index d3bdb453..a01de349 100644 --- a/test/p256_keys_bearssl_test.cpp +++ b/test/p256_keys_bearssl_test.cpp @@ -329,10 +329,11 @@ void secret_round_trip() { first_point->uncompressed() == again_point->uncompressed()); std::array const message{'a', 'b', 'c'}; auto const signature = again->sign(crypto::signing_schemes::ecdsa_sha256, message); - BOOST_TEST( - signature && first_point && - crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signature, message, *first_point) - .has_value()); + BOOST_TEST(signature && first_point && + crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *signature, message, + *first_point) + .has_value()); } } // namespace diff --git a/test/p256_openssl_oracle_test.cpp b/test/p256_openssl_oracle_test.cpp index f85cf6b5..10b21f4e 100644 --- a/test/p256_openssl_oracle_test.cpp +++ b/test/p256_openssl_oracle_test.cpp @@ -336,7 +336,8 @@ bool signature_case(std::mt19937_64& generator, std::size_t index) { BOOST_TEST(openssl_verifies(key.get(), std::span(der).first(*der_size), digest)); bool const we_verify_theirs = BOOST_TEST(theirs && webcpp::crypto::verify( - webcpp::crypto::signing_schemes::ecdsa_sha256, *theirs, + webcpp::crypto::signing_schemes::ecdsa_sha256, + webcpp::crypto::verification_policies::any_s, *theirs, webcpp::crypto::signing_schemes::prehashed{digest}, *public_key) .has_value()); bool const agrees = same_point && same_signature && openssl_verifies_ours && we_verify_theirs; diff --git a/test/p256_webcrypto_oracle_test.cpp b/test/p256_webcrypto_oracle_test.cpp index 70c62636..6b669114 100644 --- a/test/p256_webcrypto_oracle_test.cpp +++ b/test/p256_webcrypto_oracle_test.cpp @@ -257,10 +257,11 @@ void judge(our_case const& ours, oracle_answer const& answer, p256::public_key c auto const theirs = p256::ecdsa_signature::from_bytes(answer.signature); bool const we_verify = ran && theirs.has_value() && - crypto::verify(crypto::signing_schemes::ecdsa_sha256, *theirs, ours.message, public_key) + crypto::verify(crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::any_s, + *theirs, ours.message, public_key) .has_value() && - crypto::verify(crypto::signing_schemes::ecdsa_sha256, *theirs, - crypto::signing_schemes::prehashed{ours.digest}, public_key) + crypto::verify(crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::any_s, + *theirs, crypto::signing_schemes::prehashed{ours.digest}, public_key) .has_value(); found.check(we_verify, "we verify WebCrypto's", index); if (ran && theirs.has_value() && p256::is_low_s(*theirs)) { @@ -305,9 +306,10 @@ void one_case(std::mt19937_64& rng, std::size_t index, tally& found) { return; } BOOST_TEST(p256::is_low_s(*signature)); - BOOST_TEST( - crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signature, ours.message, *public_key) - .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::any_s, *signature, ours.message, + *public_key) + .has_value()); ours.signature = signature->bytes(); if (corrupted && index == corrupted_signature) { ours.signature[5] ^= 0x01U; diff --git a/test/p256_wycheproof_bearssl_test.cpp b/test/p256_wycheproof_bearssl_test.cpp index 00525397..de48cbf9 100644 --- a/test/p256_wycheproof_bearssl_test.cpp +++ b/test/p256_wycheproof_bearssl_test.cpp @@ -5,12 +5,12 @@ // https://www.boost.org/LICENSE_1_0.txt) // P-256 ECDSA on BearSSL against Wycheproof (spec 8.1): the SHA-256 vectors in the raw form, -// IEEE P1363's r || s, through crypto::verify(ecdsa_sha256, ...), and in DER through from_der -// then crypto::verify, each case verified from its message and from its digest, with the same -// verdict. A valid case verifies, an invalid one is refused, and an acceptable one, which neither -// file has at its pinned commit, fails the test so that it is read. The valid cases whose S is -// high (is_low_s false) are counted: crypto::verify accepts both forms, as FIPS 186-5 and -// WebCrypto do (design D36). +// IEEE P1363's r || s, through crypto::verify(ecdsa_sha256, any_s, ...), and in DER through +// from_der then crypto::verify, each case verified from its message and from its digest, with the +// same verdict. A valid case verifies, an invalid one is refused, and an acceptable one, which +// neither file has at its pinned commit, fails the test so that it is read. The valid cases whose S +// is high (is_low_s false) are counted: crypto::verify under any_s accepts both forms, as FIPS +// 186-5 and WebCrypto do (design D36, D9); verification_policies_test checks low_s_only's refusals. #include #include @@ -87,11 +87,12 @@ struct counts { // differ is reported. bool verified_both_ways(std::string const& name, json::value const& t, signature const& value, std::span message, p256::public_key const& key) { - bool const verified = - crypto::verify(crypto::signing_schemes::ecdsa_sha256, value, message, key).has_value(); + bool const verified = crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::any_s, value, message, key) + .has_value(); bool const verified_digest = - crypto::verify(crypto::signing_schemes::ecdsa_sha256, value, - crypto::signing_schemes::prehashed{sha256(message)}, key) + crypto::verify(crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::any_s, + value, crypto::signing_schemes::prehashed{sha256(message)}, key) .has_value(); if (verified != verified_digest) { report(name, t, "message and digest verified differently"); diff --git a/test/secp256k1_allocation_test.cpp b/test/secp256k1_allocation_test.cpp index d912285f..1b17134f 100644 --- a/test/secp256k1_allocation_test.cpp +++ b/test/secp256k1_allocation_test.cpp @@ -225,15 +225,22 @@ int main() { auto const verifier = secp::public_key::from_bytes(compressed); BOOST_TEST(schnorr && ecdsa && secret_key && shared && shared_x && shared_point); BOOST_TEST(drawn && of_message && hedged && recoverable && verifier); - BOOST_TEST( - crypto::verify(crypto::signing_schemes::schnorr, *schnorr, message, xonly).has_value()); - BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, *drawn, message, *public_key) + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, *schnorr, message, + xonly) .has_value()); - BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *ecdsa, digest, *verifier) + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, *drawn, message, + *public_key) + .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *ecdsa, digest, + *verifier) + .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *of_message, message, + *verifier) .has_value()); - BOOST_TEST( - crypto::verify(crypto::signing_schemes::ecdsa_sha256, *of_message, message, *verifier) - .has_value()); BOOST_TEST_EQ(webcpp::test::allocations(), before); // Each of the DER and low-S functions and the x-only tweak, alone: no allocation. @@ -262,8 +269,8 @@ int main() { none("public_key::uncompressed", [&] { return parsed->uncompressed() == uncompressed; }); none("public_key::xonly", [&] { return parsed->xonly() == xonly; }); none("recover", [&] { - return secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, *recoverable, - digest); + return secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, + crypto::verification_policies::low_s_only, *recoverable, digest); }); none("public_key <=>", [&] { return (*parsed <=> *parsed) == 0; }); none("keypair::tweak_xonly", [&] { return key.tweak_xonly(message); }); diff --git a/test/secp256k1_bip340_test.cpp b/test/secp256k1_bip340_test.cpp index 63a83f0f..41211adc 100644 --- a/test/secp256k1_bip340_test.cpp +++ b/test/secp256k1_bip340_test.cpp @@ -6,9 +6,9 @@ // secp256k1 against BIP340's test vectors (bip-0340/test-vectors.csv), through // key.sign(crypto::signing_schemes::schnorr, message, aux_rand) and -// crypto::verify(crypto::signing_schemes::schnorr, ...): each row with a secret key gives its -// public key and its signature, every row verifies as its result says, and the refusals are the -// error the row's reason names. +// crypto::verify(crypto::signing_schemes::schnorr, crypto::verification_policies::canonical, ...): +// each row with a secret key gives its public key and its signature, every row verifies as its +// result says, and the refusals are the error the row's reason names. #include #include @@ -102,9 +102,10 @@ void check_row(std::vector const& f, tally& t) { ++t.signed_rows; check_signing(f, pub, message, signature); } - auto const result = crypto::verify(crypto::signing_schemes::schnorr, - secp::schnorr_signature::from_bytes(signature).value(), - message, std::span(pub)); + auto const result = + crypto::verify(crypto::signing_schemes::schnorr, crypto::verification_policies::canonical, + secp::schnorr_signature::from_bytes(signature).value(), message, + std::span(pub)); if (f[6] == "TRUE") { ++t.accepted; BOOST_TEST(result.has_value()); diff --git a/test/secp256k1_c_api_test.cpp b/test/secp256k1_c_api_test.cpp index aa17a96c..9f0ccf35 100644 --- a/test/secp256k1_c_api_test.cpp +++ b/test/secp256k1_c_api_test.cpp @@ -81,7 +81,8 @@ void recovery(secp256k1_context const* context, secret_key const& secret, auto const typed = secp::recoverable_signature::from_bytes(with_id); BOOST_TEST(typed.has_value()); auto const wrapped = typed ? secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, - *typed, crypto::signing_schemes::prehashed{hash}) + crypto::verification_policies::low_s_only, *typed, + crypto::signing_schemes::prehashed{hash}) : boost::system::result(typed.error()); auto const expected_key = secp::public_key::from_bytes(expected); if (BOOST_TEST(wrapped && expected_key)) { diff --git a/test/secp256k1_der_test.cpp b/test/secp256k1_der_test.cpp index 4dccfb71..7c895ee7 100644 --- a/test/secp256k1_der_test.cpp +++ b/test/secp256k1_der_test.cpp @@ -154,12 +154,13 @@ void normalization() { auto const public_key = *key.public_key(); auto const high = typed(test::negate_s(signature.bytes())); BOOST_TEST(high != signature); - BOOST_TEST( - crypto::verify(crypto::signing_schemes::ecdsa_sha256, high, digest, public_key).error() == - crypto::error::invalid_signature); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, high, digest, public_key) + .error() == crypto::error::invalid_signature); auto const normalized = secp::normalize_low_s(high); BOOST_TEST(normalized.has_value() && *normalized == signature); BOOST_TEST(normalized.has_value() && crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *normalized, digest, public_key)); // Already low-S: unchanged. auto const again = secp::normalize_low_s(signature); diff --git a/test/secp256k1_ethereum_test.cpp b/test/secp256k1_ethereum_test.cpp index e4fea58c..7a067b02 100644 --- a/test/secp256k1_ethereum_test.cpp +++ b/test/secp256k1_ethereum_test.cpp @@ -8,8 +8,9 @@ // R18 to R20): go-ethereum's recovery vector; web3.js's personal_sign vector, its EIP-191 digest // built here with webcpp::hash's keccak_256; Keccak-256's original padding, never SHA3-256's; a // message hashed inside with Keccak-256, of any size, empty and 32 bytes included, signed as its -// digest is and recovered from it; always a low S; a high S recovered as libsecp256k1 and -// Ethereum's ecrecover recover it; the refusals of an id above 3 and of an r of zero; a keccak +// digest is and recovered from it; always a low S; a high S refused by recover under low_s_only +// (design R28), which libsecp256k1's recovery and Ethereum's ecrecover would accept, and its low +// form recovered; the refusals of an id above 3 and of an r of zero; a keccak // signature recovered under ecdsa_sha256_recoverable, which gives another key; the free // crypto::sign; and the scheme's traits: its signature type, no crypto::verify of it, a 32-byte // digest alone. @@ -68,6 +69,7 @@ static_assert(std::is_same_v().sign( boost::system::result>); static_assert( std::is_same_v(), crypto::signing_schemes::prehashed<32>(bytes32{}))), boost::system::result>); @@ -75,8 +77,9 @@ static_assert( // which stops the build, is the one candidate. static_assert(!crypto::detail::verifies_with_v); static_assert(!crypto::detail::has_verifier_v); -static_assert(!crypto::can_verify, secp::public_key>); +static_assert(!crypto::can_verify, + secp::public_key>); // go-ethereum's crypto/signature_test.go, testmsg, testsig and testpubkey, at commit // e0feab5218041fda40a8de64500a625bac146db6: @@ -175,7 +178,8 @@ secp::ecdsa_signature ecdsa_of(secp::recoverable_signature const& signature) { // go-ethereum's digest and signature recover its uncompressed key. void geth_recover() { auto const recovered = - secp::recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, typed(geth_signature), + secp::recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, + crypto::verification_policies::low_s_only, typed(geth_signature), crypto::signing_schemes::prehashed{geth_message}); if (BOOST_TEST(recovered.has_value())) { BOOST_TEST(recovered->uncompressed() == geth_public_key); @@ -200,7 +204,8 @@ void personal_sign() { BOOST_TEST(std::ranges::equal(std::span(signed_bytes).subspan<32, 32>(), web3_s)); BOOST_TEST_EQ(static_cast(signature->recovery_id()), web3_v - 27); auto const recovered = secp::recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, - *signature, crypto::signing_schemes::prehashed{digest}); + crypto::verification_policies::low_s_only, *signature, + crypto::signing_schemes::prehashed{digest}); if (BOOST_TEST(recovered.has_value())) { BOOST_TEST(*recovered == public_of(key)); auto const uncompressed = recovered->uncompressed(); @@ -232,7 +237,8 @@ void message_is_hashed_one(secp::keypair const& key, std::spanrecovery_id() <= 3); - auto const recovered = - secp::recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, *signature, - crypto::signing_schemes::prehashed{digest}); + auto const recovered = secp::recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, + crypto::verification_policies::low_s_only, *signature, + crypto::signing_schemes::prehashed{digest}); BOOST_TEST(recovered.has_value() && *recovered == public_of(*made)); ++signed_count; } } -// A high S, n - s with the id's parity flipped, recovers the same key: libsecp256k1's recovery -// and Ethereum's ecrecover accept it (only a transaction's signature is refused one, by EIP-2). -void high_s_recovered() { +// A high S, n - s with the id's parity flipped, the same signer's signature in its high form: +// libsecp256k1's recovery and Ethereum's ecrecover accept it, recover under low_s_only refuses it +// with invalid_signature before recovery (design R28, EIP-2's rule for a transaction), and its low +// form, the vector itself, recovers the key. +void high_s_refused() { auto high_bytes = geth_signature; bytes32 s_value{}; std::copy_n(high_bytes.begin() + 32, 32, s_value.begin()); @@ -307,8 +316,14 @@ void high_s_recovered() { high_bytes[64] ^= 1U; auto const high = typed(high_bytes); BOOST_TEST(!secp::is_low_s(ecdsa_of(high))); - auto const recovered = secp::recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, high, - crypto::signing_schemes::prehashed{geth_message}); + auto const refused = secp::recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, + crypto::verification_policies::low_s_only, high, + crypto::signing_schemes::prehashed{geth_message}); + BOOST_TEST(refused.has_error() && refused.error() == crypto::error::invalid_signature); + auto const recovered = + secp::recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, + crypto::verification_policies::low_s_only, typed(geth_signature), + crypto::signing_schemes::prehashed{geth_message}); BOOST_TEST(recovered.has_value() && recovered->uncompressed() == geth_public_key); } @@ -318,15 +333,16 @@ void refusals() { auto bad_bytes = geth_signature; bad_bytes[64] = id; auto const refused = - secp::recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, typed(bad_bytes), + secp::recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, + crypto::verification_policies::low_s_only, typed(bad_bytes), crypto::signing_schemes::prehashed{geth_message}); BOOST_TEST(refused.has_error() && refused.error() == crypto::error::invalid_signature); } auto zero_r = geth_signature; std::fill_n(zero_r.begin(), 32, std::uint8_t{0}); - auto const refused = - secp::recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, typed(zero_r), - crypto::signing_schemes::prehashed{geth_message}); + auto const refused = secp::recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, + crypto::verification_policies::low_s_only, typed(zero_r), + crypto::signing_schemes::prehashed{geth_message}); BOOST_TEST(refused.has_error() && refused.error() == crypto::error::invalid_signature); } @@ -340,10 +356,11 @@ void wrong_scheme_key() { return; } auto const other = - secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, *signature, message); + secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, + crypto::verification_policies::low_s_only, *signature, message); BOOST_TEST(!other.has_value() || *other != public_of(key)); - auto const same = - secp::recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, *signature, message); + auto const same = secp::recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, + crypto::verification_policies::low_s_only, *signature, message); BOOST_TEST(same.has_value() && *same == public_of(key)); } @@ -368,7 +385,7 @@ int main() { message_is_hashed(); empty_message(); always_low_s(); - high_s_recovered(); + high_s_refused(); refusals(); wrong_scheme_key(); moved_from(); diff --git a/test/secp256k1_keccak_alone_test.cpp b/test/secp256k1_keccak_alone_test.cpp index 92ecdf74..b39011d3 100644 --- a/test/secp256k1_keccak_alone_test.cpp +++ b/test/secp256k1_keccak_alone_test.cpp @@ -39,6 +39,7 @@ int main() { return 1; } auto const recovered = - secp::recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, *signature, message); + secp::recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, + crypto::verification_policies::low_s_only, *signature, message); return recovered && *recovered == *key->public_key() ? 0 : 1; } diff --git a/test/secp256k1_musig_test.cpp b/test/secp256k1_musig_test.cpp index 3443c85d..370fee45 100644 --- a/test/secp256k1_musig_test.cpp +++ b/test/secp256k1_musig_test.cpp @@ -15,16 +15,17 @@ // cases that need no secret nonce of the vector's are refused at parsing (a sign_error case that // needs one is counted as skipped). tweak: the 5 valid cases verify after their tweaks, the // error case's tweak is refused. sig_agg: the 4 valid cases give the vector's signature, which -// crypto::verify(crypto::signing_schemes::schnorr, ...) accepts under the aggregate key, and a -// partial signature not below the group order is refused. The vectors' secret nonces (sign_verify's -// and tweak's secnonces, det_sign_vectors.json, nonce_gen_vectors.json) are not reachable through -// crypto's interface by design: a secret_nonce exists only from generate_nonce, with fresh -// randomness; libsecp256k1's own tests run them in the c-suites lane. Round trips: 2-of-2 and -// 3-of-3 over seeded key pairs and messages, plain and with an x-only tweak, each partial signature -// verified, the aggregate verified with crypto::verify(crypto::signing_schemes::schnorr, ...), and -// a partial signature changed in one bit refused. The nonce: consumed by partial_sign, refused when -// used again or given to another key pair. The refusals of a moved-from key pair, of sizes and of -// workspaces; every workspace is zero afterwards. +// crypto::verify(crypto::signing_schemes::schnorr, crypto::verification_policies::canonical, ...) +// accepts under the aggregate key, and a partial signature not below the group order is refused. +// The vectors' secret nonces (sign_verify's and tweak's secnonces, det_sign_vectors.json, +// nonce_gen_vectors.json) are not reachable through crypto's interface by design: a secret_nonce +// exists only from generate_nonce, with fresh randomness; libsecp256k1's own tests run them in the +// c-suites lane. Round trips: 2-of-2 and 3-of-3 over seeded key pairs and messages, plain and with +// an x-only tweak, each partial signature verified, the aggregate verified with +// crypto::verify(crypto::signing_schemes::schnorr, crypto::verification_policies::canonical, ...), +// and a partial signature changed in one bit refused. The nonce: consumed by partial_sign, refused +// when used again or given to another key pair. The refusals of a moved-from key pair, of sizes and +// of workspaces; every workspace is zero afterwards. #include #include @@ -511,8 +512,9 @@ void sig_agg() { } BOOST_TEST(std::ranges::equal(signature->bytes(), hex(c.at("expected")))); aggregated_count += - static_cast(BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, *signature, - message, key.xonly_public_key()) + static_cast(BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, + *signature, message, key.xonly_public_key()) .has_value())); } int refused = 0; @@ -608,13 +610,15 @@ void aggregate_verifies(std::span parts, musig::partial_signature_aggregate(signing_session, parts, signature_space); BOOST_TEST(all_zero(signature_space)); if (BOOST_TEST(signature.has_value())) { - BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, *signature, message, + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, *signature, message, key.xonly_public_key()) .has_value()); auto other_message = message; other_message[0] ^= 0x01U; - BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, *signature, other_message, - key.xonly_public_key()) + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, *signature, + other_message, key.xonly_public_key()) .error() == crypto::error::invalid_signature); } } diff --git a/test/secp256k1_recovery_test.cpp b/test/secp256k1_recovery_test.cpp index 6d56031f..f16062f0 100644 --- a/test/secp256k1_recovery_test.cpp +++ b/test/secp256k1_recovery_test.cpp @@ -62,6 +62,7 @@ secp::ecdsa_signature ecdsa_of(recoverable const& signature) { static_assert(secp::recoverable_signature_size == 65); static_assert( std::is_same_v(), crypto::signing_schemes::prehashed<32>(hash_bytes{}))), boost::system::result>); @@ -107,7 +108,8 @@ void refuses_bad_ids(recoverable const& signature, hash_bytes const& hash) { BOOST_TEST_EQ(bad_id.recovery_id(), id); BOOST_TEST( refused_as_signature(secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, - bad_id, crypto::signing_schemes::prehashed{hash}))); + crypto::verification_policies::low_s_only, bad_id, + crypto::signing_schemes::prehashed{hash}))); } } @@ -116,7 +118,8 @@ bool another_hash_finds_another_key(secp::keypair const& key, recoverable const& hash_bytes const& hash) { auto other_hash = hash; other_hash[0] ^= 0x80U; - auto const other = secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, signature, + auto const other = secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, + crypto::verification_policies::low_s_only, signature, crypto::signing_schemes::prehashed{other_hash}); if (!other) { BOOST_TEST(other.error() == crypto::error::invalid_signature); @@ -142,7 +145,8 @@ bool round_trip(std::mt19937_64& generator) { BOOST_TEST(signature->recovery_id() <= 3); BOOST_TEST(std::ranges::equal(std::span(signature->bytes()).first(64), plain->bytes())); auto const recovered = secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, - *signature, crypto::signing_schemes::prehashed{hash}); + crypto::verification_policies::low_s_only, *signature, + crypto::signing_schemes::prehashed{hash}); if (BOOST_TEST(recovered.has_value())) { BOOST_TEST(*recovered == key_of(key)); } @@ -165,12 +169,15 @@ void message_round_trip() { return; } auto const from_message = - secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, *signature, message); + secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, + crypto::verification_policies::low_s_only, *signature, message); auto const from_digest = - secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, *signature, + secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, + crypto::verification_policies::low_s_only, *signature, crypto::signing_schemes::prehashed{crypto::detail::sha256_of(message)}); auto const from_marker = secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, - *signature, crypto::signing_schemes::prehashed{message}); + crypto::verification_policies::low_s_only, *signature, + crypto::signing_schemes::prehashed{message}); if (BOOST_TEST(from_message.has_value()) && BOOST_TEST(from_digest.has_value())) { BOOST_TEST(*from_message == key_of(*made)); BOOST_TEST(*from_digest == key_of(*made)); @@ -181,7 +188,8 @@ void message_round_trip() { auto const signed_empty = made->sign(crypto::signing_schemes::ecdsa_sha256_recoverable, empty); auto const recovered_empty = signed_empty - ? secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, *signed_empty, empty) + ? secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, + crypto::verification_policies::low_s_only, *signed_empty, empty) : boost::system::result(crypto::error::backend_failure); BOOST_TEST(recovered_empty.has_value() && *recovered_empty == key_of(*made)); } @@ -233,7 +241,8 @@ void edge_signature_ids() { std::ranges::copy(edge_signature, signature.begin()); signature[64] = id; auto const recovered = - secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, typed(signature), + secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, + crypto::verification_policies::low_s_only, typed(signature), crypto::signing_schemes::prehashed{edge_message}); if (id == 1) { BOOST_TEST(recovered.has_value()); @@ -248,22 +257,25 @@ void edge_signature_ids() { void small_signatures_recover() { for (std::uint8_t id = 0; id < 4; ++id) { auto const signature = small_signature(4, 4, id); - auto const recovered = - secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, signature, - crypto::signing_schemes::prehashed{edge_message}); + auto const recovered = secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, + crypto::verification_policies::low_s_only, signature, + crypto::signing_schemes::prehashed{edge_message}); if (!BOOST_TEST(recovered.has_value())) { continue; } - BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, ecdsa_of(signature), + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, ecdsa_of(signature), crypto::signing_schemes::prehashed{edge_message}, *recovered) .has_value()); } auto const one_one = small_signature(1, 1, 0); - auto const recovered = secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, one_one, + auto const recovered = secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, + crypto::verification_policies::low_s_only, one_one, crypto::signing_schemes::prehashed{edge_message}); if (BOOST_TEST(recovered.has_value())) { - BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, ecdsa_of(one_one), + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, ecdsa_of(one_one), crypto::signing_schemes::prehashed{edge_message}, *recovered) .has_value()); } @@ -271,7 +283,8 @@ void small_signatures_recover() { // The key recovered from a signature of edge_message, the digest. boost::system::result recover_edge(recoverable const& signature) { - return secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, signature, + return secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, + crypto::verification_policies::low_s_only, signature, crypto::signing_schemes::prehashed{edge_message}); } @@ -337,11 +350,16 @@ void hedged_round(secp256k1_context const* context, std::mt19937_64& generator) BOOST_TEST(*zeroed != *plain); BOOST_TEST(*first != *plain); auto const public_key = key_of(key); - BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *first, digest, public_key) + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *first, digest, public_key) .has_value()); - BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *second, digest, public_key) + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *second, digest, + public_key) .has_value()); - BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *zeroed, digest, public_key) + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *zeroed, digest, + public_key) .has_value()); BOOST_TEST(first->bytes() == reference_signature(context, secret, hash, &first_entropy)); BOOST_TEST(second->bytes() == reference_signature(context, secret, hash, &second_entropy)); diff --git a/test/secp256k1_test.cpp b/test/secp256k1_test.cpp index 56b73456..dbcc0605 100644 --- a/test/secp256k1_test.cpp +++ b/test/secp256k1_test.cpp @@ -93,26 +93,35 @@ void schnorr() { } // The typed key and its 32 x-only bytes verify alike. auto const xonly = public_key->xonly(); - BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, *signature, message, *public_key) + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, *signature, message, + *public_key) + .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, *signature, message, xonly) .has_value()); - BOOST_TEST( - crypto::verify(crypto::signing_schemes::schnorr, *signature, message, xonly).has_value()); auto flipped_bytes = signature->bytes(); flipped_bytes[0] ^= 1U; auto const flipped = typed(flipped_bytes); - BOOST_TEST( - crypto::verify(crypto::signing_schemes::schnorr, flipped, message, *public_key).error() == - crypto::error::invalid_signature); - BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, flipped, message, xonly).error() == - crypto::error::invalid_signature); + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, flipped, message, + *public_key) + .error() == crypto::error::invalid_signature); + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, flipped, message, xonly) + .error() == crypto::error::invalid_signature); message[0] ^= 1U; - BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, *signature, message, *public_key) + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, *signature, message, + *public_key) + .error() == crypto::error::invalid_signature); + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, *signature, message, xonly) .error() == crypto::error::invalid_signature); - BOOST_TEST( - crypto::verify(crypto::signing_schemes::schnorr, *signature, message, xonly).error() == - crypto::error::invalid_signature); std::array const not_a_point{}; // x = 0 has no point - BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, *signature, message, not_a_point) + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, *signature, message, + not_a_point) .error() == crypto::error::invalid_public_key); } @@ -129,9 +138,13 @@ void schnorr_draws_aux() { return; } BOOST_TEST(*first != *second); - BOOST_TEST( - crypto::verify(crypto::signing_schemes::schnorr, *first, message, *public_key).has_value()); - BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, *second, message, *public_key) + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, *first, message, + *public_key) + .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, *second, message, + *public_key) .has_value()); } @@ -150,24 +163,36 @@ void empty_message() { if (!BOOST_TEST(parsed && schnorr_empty && drawn_empty && ecdsa_empty)) { return; } - BOOST_TEST( - crypto::verify(crypto::signing_schemes::schnorr, *schnorr_empty, empty, xonly).has_value()); - BOOST_TEST( - crypto::verify(crypto::signing_schemes::schnorr, *drawn_empty, empty, *parsed).has_value()); - BOOST_TEST( - crypto::verify(crypto::signing_schemes::schnorr, *schnorr_empty, other, xonly).error() == - crypto::error::invalid_signature); - BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *ecdsa_empty, empty, *parsed) + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, *schnorr_empty, empty, + xonly) .has_value()); - BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *ecdsa_empty, + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, *drawn_empty, empty, + *parsed) + .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, *schnorr_empty, other, + xonly) + .error() == crypto::error::invalid_signature); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *ecdsa_empty, empty, + *parsed) + .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *ecdsa_empty, crypto::signing_schemes::prehashed{crypto::detail::sha256_of(empty)}, *parsed) .has_value()); - BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *ecdsa_empty, other, *parsed) + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *ecdsa_empty, other, + *parsed) .error() == crypto::error::invalid_signature); // A vector converts to a message too, of any size. std::vector const none; - BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *ecdsa_empty, none, *parsed) + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *ecdsa_empty, none, + *parsed) .has_value()); } @@ -183,7 +208,9 @@ void generated() { auto const signature = key->sign(crypto::signing_schemes::schnorr, message, aux); auto const public_key = key->public_key(); BOOST_TEST(signature && public_key); - BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, *signature, message, *public_key) + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, *signature, message, + *public_key) .has_value()); auto const other = secp::keypair::generate(); BOOST_TEST(other.has_value() && *other->public_key() != *public_key); @@ -199,7 +226,8 @@ void ecdsa() { if (!BOOST_TEST(signature && public_key)) { return; } - BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signature, + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *signature, crypto::signing_schemes::prehashed{hash}, *public_key) .has_value()); // Low-S: s is at most half the group order, so its first byte is below 0x80. @@ -208,20 +236,24 @@ void ecdsa() { // The high-S form of the same signature is refused, as libsecp256k1's verify refuses it. auto const high = typed(webcpp::test::negate_s(signature->bytes())); BOOST_TEST(!secp::is_low_s(high)); - BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, high, + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, high, crypto::signing_schemes::prehashed{hash}, *public_key) .error() == crypto::error::invalid_signature); std::array overflow{}; overflow.fill(0xff); // r and s not below the order: the compact parser refuses it BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, typed(overflow), crypto::signing_schemes::prehashed{hash}, *public_key) .error() == crypto::error::invalid_signature); // The uncompressed form parses to the same key, which verifies. auto const full = secp::public_key::from_bytes(uncompressed(key)); - BOOST_TEST(full.has_value() && crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signature, - crypto::signing_schemes::prehashed{hash}, *full) - .has_value()); + BOOST_TEST(full.has_value() && + crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *signature, + crypto::signing_schemes::prehashed{hash}, *full) + .has_value()); } // The public key of ECDSA's verification is made first: every way 33 or 65 bytes can be no @@ -267,10 +299,12 @@ void ecdsa_message_is_hashed() { } BOOST_TEST(*of_message == *of_digest); BOOST_TEST(*of_message != *of_marker); - BOOST_TEST( - crypto::verify(crypto::signing_schemes::ecdsa_sha256, *of_message, message, *public_key) - .has_value()); - BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *of_message, + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *of_message, message, + *public_key) + .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *of_message, crypto::signing_schemes::prehashed{message}, *public_key) .error() == crypto::error::invalid_signature); // The recoverable signature's r and s are the same as ecdsa_sha256's. @@ -309,7 +343,8 @@ void sighash() { secp256k1_ecdsa_signature_serialize_compact(context, compact.data(), &reference); secp256k1_context_destroy(context); BOOST_TEST(signature->bytes() == compact); - BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *signature, + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *signature, crypto::signing_schemes::prehashed{digest}, *public_key) .has_value()); } @@ -331,7 +366,9 @@ void hedged_differs() { } BOOST_TEST(*hedged != *plain); BOOST_TEST(*hedged == *hedged_digest); - BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *hedged, message, *public_key) + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *hedged, message, + *public_key) .has_value()); } @@ -366,22 +403,29 @@ void verified_from_vectors() { auto const ecdsa_bytes = received_bytes(*ecdsa_signed); auto const ecdsa_made = secp::ecdsa_signature::from_bytes(ecdsa_bytes); if (BOOST_TEST(ecdsa_made.has_value())) { - BOOST_TEST(public_key->verify(crypto::signing_schemes::ecdsa_sha256, *ecdsa_made, message) + BOOST_TEST(public_key + ->verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *ecdsa_made, message) + .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *ecdsa_made, message, + *public_key) .has_value()); - BOOST_TEST( - crypto::verify(crypto::signing_schemes::ecdsa_sha256, *ecdsa_made, message, *public_key) - .has_value()); } other_sizes_refused(ecdsa_bytes); auto const schnorr_bytes = received_bytes(*schnorr_signed); auto const schnorr_made = secp::schnorr_signature::from_bytes(schnorr_bytes); if (BOOST_TEST(schnorr_made.has_value())) { - BOOST_TEST(public_key->verify(crypto::signing_schemes::schnorr, *schnorr_made, message) + BOOST_TEST(public_key + ->verify(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, *schnorr_made, message) + .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, *schnorr_made, message, + *public_key) .has_value()); - BOOST_TEST( - crypto::verify(crypto::signing_schemes::schnorr, *schnorr_made, message, *public_key) - .has_value()); - BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, *schnorr_made, message, + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, *schnorr_made, message, public_key->xonly()) .has_value()); } @@ -402,8 +446,9 @@ void recovered_from_vector() { auto const recoverable_bytes = received_bytes(*recoverable_signed); auto const recoverable_made = secp::recoverable_signature::from_bytes(recoverable_bytes); if (BOOST_TEST(recoverable_made.has_value())) { - auto const recovered = secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, - *recoverable_made, message); + auto const recovered = + secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, + crypto::verification_policies::low_s_only, *recoverable_made, message); BOOST_TEST(recovered.has_value() && *recovered == *public_key); } other_sizes_refused(recoverable_bytes); @@ -427,44 +472,60 @@ static_assert(!crypto::can_sign>); using message_span = std::span; -static_assert(crypto::can_verify); -static_assert(crypto::can_verify, secp::public_key>); -static_assert(crypto::can_verify>); -static_assert(crypto::can_verify>); +static_assert(crypto::can_verify< + crypto::signing_schemes::schnorr_t, crypto::verification_policies::canonical_t, + secp::schnorr_signature, message_span, std::array>); +static_assert(crypto::can_verify< + crypto::signing_schemes::schnorr_t, crypto::verification_policies::canonical_t, + secp::schnorr_signature, message_span, std::span>); static_assert( - !crypto::can_verify, std::array>); // Bytes of another size, or of a size known only at run time, are no x-only key. -static_assert(!crypto::can_verify>); -static_assert(!crypto::can_verify>); +static_assert(!crypto::can_verify< + crypto::signing_schemes::schnorr_t, crypto::verification_policies::canonical_t, + secp::schnorr_signature, message_span, std::array>); +static_assert(!crypto::can_verify< + crypto::signing_schemes::schnorr_t, crypto::verification_policies::canonical_t, + secp::schnorr_signature, message_span, std::span>); // Bytes are no secp256k1 ECDSA key: ECDSA never infers its curve from a number of bytes. -static_assert(!crypto::can_verify>); -static_assert(!crypto::can_verify); +static_assert(!crypto::can_verify< + crypto::signing_schemes::ecdsa_sha256_t, crypto::verification_policies::low_s_only_t, + secp::ecdsa_signature, message_span, std::array>); +static_assert(!crypto::can_verify); // The typed key verifies Schnorr beside its 32 x-only bytes; a marker is no Schnorr input. -static_assert(crypto::can_verify); -static_assert(!crypto::can_verify, secp::public_key>); +static_assert(crypto::can_verify); +static_assert(!crypto::can_verify< + crypto::signing_schemes::schnorr_t, crypto::verification_policies::canonical_t, + secp::schnorr_signature, crypto::signing_schemes::prehashed<32>, secp::public_key>); // Each scheme verifies its own type alone: bytes, and the other scheme's type, are none // (design R1), the recoverable one included, which recover takes. -static_assert(!crypto::can_verify); -static_assert(!crypto::can_verify); +static_assert(!crypto::can_verify); static_assert(!crypto::can_verify); static_assert(!crypto::can_verify, message_span, secp::public_key>); -static_assert(!crypto::can_verify, - message_span, std::array>); +static_assert(!crypto::can_verify< + crypto::signing_schemes::schnorr_t, crypto::verification_policies::canonical_t, + std::array, message_span, std::array>); static_assert(std::is_same_v().sign( crypto::signing_schemes::ecdsa_sha256_recoverable, std::declval>())), @@ -559,8 +620,9 @@ void secret_round_trip() { BOOST_TEST(*again->public_key() == *key->public_key()); std::array const message{'a', 'b', 'c'}; auto const signature = again->sign(crypto::signing_schemes::schnorr, message); - BOOST_TEST(signature.has_value() && crypto::verify(crypto::signing_schemes::schnorr, *signature, - message, *key->public_key()) + BOOST_TEST(signature.has_value() && crypto::verify(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, + *signature, message, *key->public_key()) .has_value()); } diff --git a/test/secp256k1_wycheproof_test.cpp b/test/secp256k1_wycheproof_test.cpp index 547d8334..d3bbaf9d 100644 --- a/test/secp256k1_wycheproof_test.cpp +++ b/test/secp256k1_wycheproof_test.cpp @@ -5,9 +5,9 @@ // https://www.boost.org/LICENSE_1_0.txt) // secp256k1 against Wycheproof (spec 8.1): the Bitcoin ECDSA vectors through -// crypto::verify(crypto::signing_schemes::ecdsa_sha256, ...), the message hashed inside, each -// verdict the same as for its SHA-256 given as crypto::signing_schemes::prehashed. The ECDH vectors -// are secp256k1_ecdh_test.cpp's. +// crypto::verify(crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::low_s_only, +// ...), the message hashed inside, each verdict the same as for its SHA-256 given as +// crypto::signing_schemes::prehashed. The ECDH vectors are secp256k1_ecdh_test.cpp's. #include #include @@ -90,9 +90,11 @@ void ecdsa_bitcoin() { 1); auto const signature = secp::ecdsa_signature::from_bytes(compact).value(); auto const result = - crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, message, *key); - auto const of_digest = crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, - crypto::signing_schemes::prehashed{hash}, *key); + crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, signature, message, *key); + auto const of_digest = crypto::verify( + crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::low_s_only, + signature, crypto::signing_schemes::prehashed{hash}, *key); BOOST_TEST_EQ(result.has_value(), of_digest.has_value()); auto const verdict = str(t.at("result")); if (verdict == "valid") { diff --git a/test/secp256k1_xonly_tweak_test.cpp b/test/secp256k1_xonly_tweak_test.cpp index a98c3356..21199474 100644 --- a/test/secp256k1_xonly_tweak_test.cpp +++ b/test/secp256k1_xonly_tweak_test.cpp @@ -142,8 +142,9 @@ void check_input(json::value const& input, int index) { !std::ranges::equal(signature->bytes(), std::span(witness).first(64))) { fail("keyPathSpending input " + std::to_string(index) + ": signature differs"); } - BOOST_TEST(signature && - crypto::verify(crypto::signing_schemes::schnorr, *signature, sighash, output->key)); + BOOST_TEST(signature && crypto::verify(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, *signature, + sighash, output->key)); } int key_path_inputs(json::value const& doc) { diff --git a/test/signing_curves_test.cpp b/test/signing_curves_test.cpp index dbba182c..b4ca3563 100644 --- a/test/signing_curves_test.cpp +++ b/test/signing_curves_test.cpp @@ -52,46 +52,61 @@ using p256_bearssl_key = crypto::curves::p256::basic_public_key); static_assert(crypto::detail::has_verifier_v); static_assert(!crypto::detail::has_verifier_v); -static_assert(!crypto::can_verify); -static_assert(crypto::can_verify); static_assert(!crypto::can_verify); -static_assert(crypto::can_verify); -static_assert(!crypto::can_verify); +static_assert(!crypto::can_verify); // A span of a size known only at run time is no key. -static_assert(!crypto::can_verify>); -static_assert(!crypto::can_verify>); // ECDSA's key is each curve's object, and its signature each curve's type. -static_assert(crypto::can_verify); -static_assert(crypto::can_verify); +static_assert(crypto::can_verify); // The wrong curve (the spec's scenario): a secp256k1 signature is no P-256 signature, and the // other way round, though both are 64 bytes, r then s. static_assert(!crypto::can_verify); -static_assert(!crypto::can_verify); // The wrong scheme: Ed25519's and BIP340's signatures, both 64 bytes, are not each other's. -static_assert(!crypto::can_verify); -static_assert(!crypto::can_verify); -// Whether crypto::verify(crypto::signing_schemes::ecdsa_sha256, ...) is callable with -// `Key` and its signature type: a P-256 key takes its own backend alone, which is deduced and which -// an explicit other one contradicts. +// Whether crypto::verify(crypto::signing_schemes::ecdsa_sha256, +// crypto::verification_policies::low_s_only, ...) is callable with `Key` and its signature type: a +// P-256 key takes its own backend alone, which is deduced and which an explicit other one +// contradicts. template concept verifies_ecdsa_on = requires( crypto::detail::signature_of_t const& signature, message_bytes message, Key const& key) { - crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, message, key); + crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, signature, message, key); }; static_assert(verifies_ecdsa_on); static_assert(!verifies_ecdsa_on); @@ -117,24 +132,28 @@ void byte_keys() { if (!BOOST_TEST(eddsa_signature.has_value()) || !BOOST_TEST(schnorr_signature.has_value())) { return; } - BOOST_TEST( - crypto::verify(crypto::signing_schemes::eddsa, *eddsa_signature, message, ed25519_key) - .has_value()); - BOOST_TEST( - crypto::verify(crypto::signing_schemes::schnorr, *schnorr_signature, message, xonly_key) - .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, *eddsa_signature, message, + ed25519_key) + .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, *schnorr_signature, message, + xonly_key) + .has_value()); auto const schnorr_as_eddsa = ed25519_signature::from_bytes(schnorr_signature->bytes()); auto const eddsa_as_schnorr = crypto::curves::secp256k1::schnorr_signature::from_bytes(eddsa_signature->bytes()); if (!BOOST_TEST(schnorr_as_eddsa.has_value()) || !BOOST_TEST(eddsa_as_schnorr.has_value())) { return; } - BOOST_TEST( - crypto::verify(crypto::signing_schemes::eddsa, *schnorr_as_eddsa, message, ed25519_key) - .error() == crypto::error::invalid_signature); - BOOST_TEST( - crypto::verify(crypto::signing_schemes::schnorr, *eddsa_as_schnorr, message, xonly_key) - .has_error()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, *schnorr_as_eddsa, message, + ed25519_key) + .error() == crypto::error::invalid_signature); + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, *eddsa_as_schnorr, message, + xonly_key) + .has_error()); } using hello = std::array; @@ -156,22 +175,24 @@ void backend_first_ed25519() { if (!BOOST_TEST(signature.has_value())) { return; } - BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, *signature, - hello_message, ed25519_key) + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, + *signature, hello_message, ed25519_key) .has_value()); - BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, *signature, - hello_message, ed25519_key, - crypto::curves::ed25519::strict) + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, + *signature, hello_message, ed25519_key) .has_value()); - BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, *signature, hello_message, - ed25519_key, crypto::curves::ed25519::strict) + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, *signature, hello_message, + ed25519_key) .has_value()); auto altered_bytes = signature->bytes(); altered_bytes[0] ^= 0x01U; auto const altered = ed25519_signature::from_bytes(altered_bytes).value(); - BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, altered, - hello_message, ed25519_key, - crypto::curves::ed25519::strict) + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, + altered, hello_message, ed25519_key) .error() == crypto::error::invalid_signature); } @@ -203,28 +224,32 @@ void backend_first_ecdsa() { return; } BOOST_TEST(crypto::verify( - crypto::signing_schemes::schnorr, *schnorr_signature, hello_message, xonly_key) + crypto::signing_schemes::schnorr, crypto::verification_policies::canonical, + *schnorr_signature, hello_message, xonly_key) .has_value()); - BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, - *schnorr_signature, hello_message, - *secp256k1_key) + BOOST_TEST(crypto::verify( + crypto::signing_schemes::schnorr, crypto::verification_policies::canonical, + *schnorr_signature, hello_message, *secp256k1_key) .has_value()); - BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, - *ecdsa_signature, hello_message, - *secp256k1_key) + BOOST_TEST(crypto::verify( + crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::low_s_only, + *ecdsa_signature, hello_message, *secp256k1_key) .has_value()); auto const recovered = crypto::curves::secp256k1::recover( - crypto::signing_schemes::ecdsa_sha256_recoverable, *recoverable_signature, hello_message); + crypto::signing_schemes::ecdsa_sha256_recoverable, + crypto::verification_policies::low_s_only, *recoverable_signature, hello_message); BOOST_TEST((recovered.has_value() && *recovered == *secp256k1_key)); BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *p256_signature, hello_message, *p256_key) .has_value()); } // A signing key pair, through crypto::signing_keypair alone: crypto::sign gives the scheme's -// signature type for its curve, which its public key verifies, and refuses with a changed message. -template -void signs_what_its_public_key_verifies(Scheme scheme) { +// signature type for its curve, which its public key verifies under the scheme's policy, and +// refuses with a changed message. +template +void signs_what_its_public_key_verifies(Scheme scheme, Policy policy) { static_assert(std::is_same_v(), scheme, hello_message))>, crypto::detail::signature_of_t>); @@ -237,9 +262,9 @@ void signs_what_its_public_key_verifies(Scheme scheme) { if (!BOOST_TEST(public_key.has_value()) || !BOOST_TEST(signature.has_value())) { return; } - BOOST_TEST(crypto::verify(scheme, *signature, hello_message, *public_key).has_value()); + BOOST_TEST(crypto::verify(scheme, policy, *signature, hello_message, *public_key).has_value()); hello const changed{'h', 'e', 'l', 'l', 'p'}; - BOOST_TEST(crypto::verify(scheme, *signature, changed, *public_key) == + BOOST_TEST(crypto::verify(scheme, policy, *signature, changed, *public_key) == crypto::error::invalid_signature); } @@ -261,15 +286,15 @@ int main() { backend_first_ecdsa(); signs_what_its_public_key_verifies< crypto::curves::ed25519::basic_keypair>( - crypto::signing_schemes::eddsa); + crypto::signing_schemes::eddsa, crypto::verification_policies::canonical); signs_what_its_public_key_verifies< crypto::curves::p256::basic_keypair>( - crypto::signing_schemes::ecdsa_sha256); + crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::low_s_only); signs_what_its_public_key_verifies< crypto::curves::secp256k1::basic_keypair>( - crypto::signing_schemes::ecdsa_sha256); + crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::low_s_only); signs_what_its_public_key_verifies< crypto::curves::secp256k1::basic_keypair>( - crypto::signing_schemes::schnorr); + crypto::signing_schemes::schnorr, crypto::verification_policies::canonical); return webcpp::test::exit_status(boost::report_errors()); } diff --git a/test/signing_test.cpp b/test/signing_test.cpp index 8d5b6667..51e3878f 100644 --- a/test/signing_test.cpp +++ b/test/signing_test.cpp @@ -4,13 +4,14 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// signing.hpp's vocabulary, over stand-in key types that this test declares: the tags take no -// `{}`, prehashed deduces its size from a fixed-size digest and converts to and from nothing, -// can_sign and can_verify accept a message or a marker of the scheme's digest size, and refuse -// a marker on a backend that completes by itself; can_verify takes the signature type the key's -// curve names for the scheme (detail::signature_of) and no other, bytes included; the catch-all -// verify is a candidate only where -// no curve declares a verifier; sha256_of gives FIPS 180-2's digest. +// signing.hpp's vocabulary, over stand-in key types that this test declares: the scheme and +// policy tags take no `{}`, prehashed deduces its size from a fixed-size digest and converts to +// and from nothing, can_sign and can_verify accept a message or a marker of the scheme's digest +// size, and refuse a marker on a backend that completes by itself; can_verify takes a policy the +// key's curve accepts for the scheme (detail::accepted_policies) and no other, and the signature +// type the key's curve names for the scheme (detail::signature_of) and no other, bytes included; +// the catch-all verify is a candidate only where no curve declares a verifier, and the one of the +// arity before the policies takes every scheme; sha256_of gives FIPS 180-2's digest. #include #include @@ -85,6 +86,11 @@ struct signature_of { using type = stand_in_signature; }; +template <> +struct accepted_policies { + using type = policy_list; +}; + template <> struct key_backend { using type = stand_in_backend; @@ -131,6 +137,37 @@ constexpr bool none_from_empty_braces(crypto::detail::scheme_list /* } static_assert(none_from_empty_braces(crypto::detail::all_schemes{})); + +// The policies, the same: no `{}`, each one in the library's one list, and nothing else. +template +constexpr bool no_policy_from_empty_braces( + crypto::detail::policy_list /*list*/) noexcept { + return (!from_empty_braces && ...); +} + +static_assert(no_policy_from_empty_braces(crypto::detail::all_policies{})); +static_assert(std::is_same_v); +static_assert(std::is_same_v); +static_assert(std::is_same_v); +static_assert(crypto::detail::is_policy_v); +static_assert(crypto::detail::is_policy_v); +static_assert(crypto::detail::is_policy_v); +static_assert(!crypto::detail::is_policy_v); +static_assert(!crypto::detail::is_policy_v); +static_assert(!crypto::detail::is_scheme_v); +// A key no curve declares policies for accepts none; the stand-in's, the two of its row. +static_assert(!crypto::detail::policy_accepted_v); +static_assert(crypto::detail::policy_accepted_v); +static_assert(!crypto::detail::policy_accepted_v); static_assert(!std::is_constructible_v); static_assert(std::is_same_v); @@ -229,23 +266,38 @@ static_assert(!crypto::can_sign>); // can_verify: the same, over the public key, with the key's signature type. -static_assert(crypto::can_verify); static_assert( - crypto::can_verify, stand_in_public_key const&>); -static_assert(!crypto::can_verify, stand_in_public_key>); -static_assert(!crypto::can_verify); +// A policy the scheme does not accept on the key, and a type that is no policy, are refused. +static_assert(!crypto::can_verify); +static_assert(!crypto::can_verify); +static_assert(crypto::can_verify); // Another type of the same size, and bytes, are no signature of the key's (design R1). -static_assert(!crypto::can_verify); static_assert(!crypto::can_verify, message_span, stand_in_public_key>); -static_assert( - !crypto::can_verify, - message_span, stand_in_public_key>); +static_assert(!crypto::can_verify< + crypto::signing_schemes::ecdsa_sha256_t, crypto::verification_policies::low_s_only_t, + std::span, message_span, stand_in_public_key>); // A key whose curve names no signature type verifies nothing. static_assert(std::is_void_v< crypto::detail::signature_of_t>); @@ -253,7 +305,8 @@ static_assert(std::is_void_v< // The two traits are apart: a key pair does not verify, a public key does not sign. static_assert( !crypto::can_sign); -static_assert(!crypto::can_verify); // The catch-all verify is a candidate where no curve declares a verifier, and steps aside where @@ -262,7 +315,8 @@ template concept catch_all_verify = requires(std::array const& signature, message_span message, PublicKey const& public_key) { { - crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, message, public_key) + crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, signature, message, public_key) } -> std::same_as>; }; static_assert( @@ -276,13 +330,17 @@ static_assert(!catch_all_verify); template concept catch_all_verify_on = requires(std::array const& signature, message_span message, PublicKey const& public_key) { - crypto::verify(crypto::signing_schemes::ecdsa_sha256, signature, message, public_key); + crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, signature, message, + public_key); }; static_assert(!catch_all_verify_on); static_assert(catch_all_verify_on); -// The catch-all takes a scheme tag alone: a four-argument verify whose first argument is not a -// scheme, found by argument-dependent lookup through a crypto type, is not captured. +// The catch-all of the arity before the policies, verify(scheme, signature, input, key), takes a +// scheme tag alone: a four-argument verify whose first argument is not a scheme, found by +// argument-dependent lookup through a crypto type, is not captured; one whose second argument is +// a policy is not either (it lacks its key, and no verify takes it). template concept catch_all_takes = requires(Scheme scheme, std::array const& signature, message_span message, stand_in_public_key const& public_key) { @@ -296,6 +354,14 @@ constexpr bool catch_all_takes_each(crypto::detail::scheme_list /*li static_assert(catch_all_takes_each(crypto::detail::all_schemes{})); static_assert(!catch_all_takes); + +template +concept catch_all_takes_policy = + requires(Policy policy, message_span message, stand_in_public_key const& public_key) { + crypto::verify(crypto::signing_schemes::ecdsa_sha256, policy, message, public_key); + }; +static_assert(!catch_all_takes_policy); +static_assert(catch_all_takes_policy); static_assert(!catch_all_takes>); static_assert(crypto::detail::is_scheme_v); static_assert(crypto::detail::is_scheme_v); diff --git a/test/sizes/p256_bearssl_verify_ecdsa.cpp b/test/sizes/p256_bearssl_verify_ecdsa.cpp index 2ba91671..b9fa52b8 100644 --- a/test/sizes/p256_bearssl_verify_ecdsa.cpp +++ b/test/sizes/p256_bearssl_verify_ecdsa.cpp @@ -5,9 +5,9 @@ // https://www.boost.org/LICENSE_1_0.txt) // The size of P-256's ECDSA verification of a digest on BearSSL, -// crypto::verify(ecdsa_sha256, signature, prehashed{digest}, public_key): bench/operations.hpp's -// p256_verify_ecdsa, once (test/sizes/Jamfile); the program keeps its name, crypto.json's -// sized operation `verify_ecdsa`. +// crypto::verify(ecdsa_sha256, low_s_only, signature, prehashed{digest}, public_key): +// bench/operations.hpp's p256_verify_ecdsa, once (test/sizes/Jamfile); the program keeps its name, +// crypto.json's sized operation `verify_ecdsa`. #include diff --git a/test/support/timing_coverage.hpp b/test/support/timing_coverage.hpp index f43216ae..052f0532 100644 --- a/test/support/timing_coverage.hpp +++ b/test/support/timing_coverage.hpp @@ -606,17 +606,20 @@ void cover_async_ed25519(std::string const& backend) { deliver(); }); covered("ed25519::async_verify" + on, "crypto::async_verify", [&] { - crypto::async_verify(executor, crypto::signing_schemes::eddsa, kept, message, + crypto::async_verify(executor, crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, kept, message, *public_key, counted); deliver(); }); covered("ed25519::async_verify with its policy" + on, "crypto::async_verify", [&] { - crypto::async_verify(executor, crypto::signing_schemes::eddsa, kept, message, - *public_key, crypto::curves::ed25519::strict, counted); + crypto::async_verify(executor, crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, kept, message, + *public_key, counted); deliver(); }); covered("ed25519::async_verify with a zero signature" + on, "crypto::async_verify", [&] { - crypto::async_verify(executor, crypto::signing_schemes::eddsa, zero_signature, + crypto::async_verify(executor, crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, zero_signature, message, *public_key, counted); deliver(); }); @@ -626,17 +629,19 @@ void cover_async_ed25519(std::string const& backend) { }); covered("ed25519::public_key::async_verify" + on, [&] { public_key->template async_verify(executor, crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, kept, message, counted); deliver(); }); covered("ed25519::public_key::async_verify with its policy" + on, [&] { public_key->template async_verify(executor, crypto::signing_schemes::eddsa, - kept, message, - crypto::curves::ed25519::strict, counted); + crypto::verification_policies::canonical, + kept, message, counted); deliver(); }); covered("ed25519::public_key::async_verify with a zero signature" + on, [&] { public_key->template async_verify(executor, crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, zero_signature, message, counted); deliver(); }); diff --git a/test/synchronous_forms_test.cpp b/test/synchronous_forms_test.cpp index e2019819..876308b9 100644 --- a/test/synchronous_forms_test.cpp +++ b/test/synchronous_forms_test.cpp @@ -17,9 +17,10 @@ // - 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 +// - verify: pub.verify(scheme, policy, signature, input) and crypto::verify(scheme, policy, +// 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 backend named, on +// both. Both take the // 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 @@ -191,10 +192,12 @@ void from_secret_forms() { * * @tparam Keypair A key pair's type. * @tparam Scheme One of its schemes. + * @tparam Policy A verification policy the scheme accepts on the key. * @param scheme The scheme. + * @param policy The verification policy. */ -template -void generate_forms(Scheme scheme) { +template +void generate_forms(Scheme scheme, Policy policy) { auto const generated = crypto::generate(); static_assert(std::is_same_v); if (!BOOST_TEST(generated.has_value())) { @@ -203,7 +206,7 @@ void generate_forms(Scheme scheme) { auto const signature = crypto::sign(*generated, scheme, message); auto const public_key = generated->public_key(); if (BOOST_TEST(signature.has_value()) && BOOST_TEST(public_key.has_value())) { - BOOST_TEST(public_key->verify(scheme, *signature, message).has_value()); + BOOST_TEST(public_key->verify(scheme, policy, *signature, message).has_value()); } } @@ -233,25 +236,29 @@ void agree_forms() { /** * A signature and a changed copy of it, verified by a public key's verify and by - * crypto::verify: both accept the first and refuse the second with invalid_signature. + * crypto::verify under the scheme's policy: both accept the first and refuse the second with + * invalid_signature. * * @tparam Scheme The scheme. + * @tparam Policy The verification policy. * @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. + * @param policy The verification policy, one the scheme accepts on the key. * @param signature A valid signature of `input`. * @param input The message or the marker. * @param public_key The signer's public key. */ -template -void verify_forms(Scheme scheme, Signature const& signature, Input const& input, +template +void verify_forms(Scheme scheme, Policy policy, 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()); + BOOST_TEST(public_key.verify(scheme, policy, signature, input).has_value()); + BOOST_TEST(crypto::verify(scheme, policy, signature, input, public_key).has_value()); auto const wrong = changed(signature); - BOOST_TEST(public_key.verify(scheme, wrong, input).error() == crypto::error::invalid_signature); - BOOST_TEST(crypto::verify(scheme, wrong, input, public_key).error() == + BOOST_TEST(public_key.verify(scheme, policy, wrong, input).error() == + crypto::error::invalid_signature); + BOOST_TEST(crypto::verify(scheme, policy, wrong, input, public_key).error() == crypto::error::invalid_signature); // The signature as bytes off the wire, a std::vector, made into the type, by its own // from_bytes and by crypto::from_bytes. @@ -259,8 +266,8 @@ void verify_forms(Scheme scheme, Signature const& signature, Input const& input, 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()); + BOOST_TEST(public_key.verify(scheme, policy, *made, input).has_value()); + BOOST_TEST(crypto::verify(scheme, policy, *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); @@ -286,14 +293,16 @@ void ed25519_forms() { return; } BOOST_TEST(*free_signed == *member_signed); - verify_forms(crypto::signing_schemes::eddsa, *member_signed, message, *public_key); + verify_forms(crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, + *member_signed, message, *public_key); BOOST_TEST(public_key ->verify(crypto::signing_schemes::eddsa, - *member_signed, message, ed25519::strict) + crypto::verification_policies::canonical, + *member_signed, message) .has_value()); BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, - *member_signed, message, *public_key, - ed25519::strict) + crypto::verification_policies::canonical, + *member_signed, message, *public_key) .has_value()); // A key's 32 bytes, where the signature goes, are no signature. BOOST_TEST(ed25519::signature::from_bytes(public_key->bytes()).error() == @@ -320,9 +329,10 @@ void p256_forms() { // RFC 6979's nonce: the same key and input give the same signature. BOOST_TEST(*free_signed == *member_signed); BOOST_TEST(*free_prehashed == *member_signed); - verify_forms(crypto::signing_schemes::ecdsa_sha256, *member_signed, message, *public_key); - verify_forms(crypto::signing_schemes::ecdsa_sha256, *member_signed, - crypto::signing_schemes::prehashed{digest}, *public_key); + verify_forms(crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::low_s_only, + *member_signed, message, *public_key); + verify_forms(crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::low_s_only, + *member_signed, crypto::signing_schemes::prehashed{digest}, *public_key); } /** secp256k1: every sign, member and free, the same signatures and types. */ @@ -412,17 +422,22 @@ void secp256k1_verify_forms() { return; } auto const digest = digest_of_message(); - verify_forms(crypto::signing_schemes::ecdsa_sha256, *ecdsa, message, *public_key); - verify_forms(crypto::signing_schemes::ecdsa_sha256, *hedged, - crypto::signing_schemes::prehashed{digest}, *public_key); - verify_forms(crypto::signing_schemes::schnorr, *schnorr, message, *public_key); - verify_forms(crypto::signing_schemes::schnorr, *drawn, message, *public_key); - BOOST_TEST( - crypto::verify(crypto::signing_schemes::schnorr, *schnorr, message, public_key->xonly()) - .has_value()); + verify_forms(crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::low_s_only, + *ecdsa, message, *public_key); + verify_forms(crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::low_s_only, + *hedged, crypto::signing_schemes::prehashed{digest}, *public_key); + verify_forms(crypto::signing_schemes::schnorr, crypto::verification_policies::canonical, + *schnorr, message, *public_key); + verify_forms(crypto::signing_schemes::schnorr, crypto::verification_policies::canonical, *drawn, + message, *public_key); + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, *schnorr, message, + public_key->xonly()) + .has_value()); BOOST_TEST(public_key - ->verify(crypto::signing_schemes::schnorr, *schnorr, - message) + ->verify(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, + *schnorr, message) .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 @@ -432,26 +447,33 @@ void secp256k1_verify_forms() { if (!BOOST_TEST(received_signature.has_value())) { return; } - BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, *received_signature, message, - public_key->xonly()) + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, *received_signature, + message, public_key->xonly()) .has_value()); auto const short_one = std::span(received).first(63); BOOST_TEST(secp256k1::schnorr_signature::from_bytes(short_one).error() == crypto::error::invalid_signature); std::array const no_point{}; - BOOST_TEST( - crypto::verify(crypto::signing_schemes::schnorr, *received_signature, message, no_point) - .error() == crypto::error::invalid_public_key); + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, *received_signature, + message, no_point) + .error() == crypto::error::invalid_public_key); // 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::signing_schemes::schnorr, *ecdsa_as_schnorr, message) + BOOST_TEST(public_key + ->verify(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, *ecdsa_as_schnorr, + message) + .error() == crypto::error::invalid_signature); + BOOST_TEST(public_key + ->verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *schnorr_as_ecdsa, + message) .error() == crypto::error::invalid_signature); - BOOST_TEST( - public_key->verify(crypto::signing_schemes::ecdsa_sha256, *schnorr_as_ecdsa, message) - .error() == crypto::error::invalid_signature); } } @@ -476,8 +498,9 @@ void secp256k1_recover_sizes() { if (!BOOST_TEST(received_signature.has_value())) { return; } - auto const recovered = secp256k1::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, - *received_signature, message); + auto const recovered = + secp256k1::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, + crypto::verification_policies::low_s_only, *received_signature, message); if (BOOST_TEST(recovered.has_value())) { BOOST_TEST(*recovered == *public_key); } @@ -551,10 +574,14 @@ int main() { from_secret_forms(); from_secret_forms(); from_secret_forms(); - generate_forms(crypto::signing_schemes::eddsa); - generate_forms(crypto::signing_schemes::ecdsa_sha256); - generate_forms(crypto::signing_schemes::schnorr); - generate_forms(crypto::signing_schemes::ecdsa_sha256); + generate_forms(crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical); + generate_forms(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only); + generate_forms(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical); + generate_forms(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only); agree_forms(); agree_forms(); ed25519_forms(); diff --git a/test/timing_coverage_bearssl_test.cpp b/test/timing_coverage_bearssl_test.cpp index de5d241d..0383d96d 100644 --- a/test/timing_coverage_bearssl_test.cpp +++ b/test/timing_coverage_bearssl_test.cpp @@ -202,18 +202,21 @@ void cover_p256_verify() { webcpp::test::covered("p256 crypto::verify of a message on bearssl", "crypto::verify", [&key, &test] { BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *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::signing_schemes::ecdsa_sha256, *test, + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *test, crypto::signing_schemes::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::signing_schemes::ecdsa_sha256, *zero_r, + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *zero_r, crypto::signing_schemes::prehashed{p256_test_digest}, *key) .error() == crypto::error::invalid_signature); }); @@ -234,16 +237,19 @@ void cover_p256_public_key_verify() { return; } webcpp::test::covered("p256::basic_public_key::verify of a message on bearssl", [&key, &test] { - BOOST_TEST(key->verify(crypto::signing_schemes::ecdsa_sha256, *test, p256_test_message) + BOOST_TEST(key->verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *test, p256_test_message) .has_value()); }); webcpp::test::covered("p256::basic_public_key::verify of a digest on bearssl", [&key, &test] { - BOOST_TEST(key->verify(crypto::signing_schemes::ecdsa_sha256, *test, + BOOST_TEST(key->verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *test, crypto::signing_schemes::prehashed{p256_test_digest}) .has_value()); }); webcpp::test::covered("p256::basic_public_key::verify of r = 0 on bearssl", [&key, &zero_r] { - BOOST_TEST(key->verify(crypto::signing_schemes::ecdsa_sha256, *zero_r, + BOOST_TEST(key->verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *zero_r, crypto::signing_schemes::prehashed{p256_test_digest}) .error() == crypto::error::invalid_signature); }); @@ -494,18 +500,21 @@ void cover_async_p256() { deliver(); }); webcpp::test::covered("p256::async_verify on bearssl", "crypto::async_verify", [&] { - crypto::async_verify(executor, crypto::signing_schemes::ecdsa_sha256, kept, message, *key, + crypto::async_verify(executor, crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, kept, message, *key, counted); deliver(); }); webcpp::test::covered("p256::async_verify of a digest on bearssl", "crypto::async_verify", [&] { - crypto::async_verify(executor, crypto::signing_schemes::ecdsa_sha256, *rfc_test, + crypto::async_verify(executor, crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *rfc_test, crypto::signing_schemes::prehashed{p256_test_digest}, *key, counted); deliver(); }); webcpp::test::covered("p256::async_verify of r = 0 on bearssl", "crypto::async_verify", [&] { - crypto::async_verify(executor, crypto::signing_schemes::ecdsa_sha256, *zero_r, message, - *key, counted); + crypto::async_verify(executor, crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *zero_r, message, *key, + counted); deliver(); }); webcpp::test::covered("p256::async_agree on bearssl", "crypto::async_agree", [&] { @@ -522,17 +531,19 @@ void cover_async_p256() { deliver(); }); webcpp::test::covered("p256::basic_public_key::async_verify on bearssl", [&] { - key->async_verify(executor, crypto::signing_schemes::ecdsa_sha256, kept, message, counted); + key->async_verify(executor, crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, kept, message, counted); deliver(); }); webcpp::test::covered("p256::basic_public_key::async_verify of a digest on bearssl", [&] { - key->async_verify(executor, crypto::signing_schemes::ecdsa_sha256, *rfc_test, + key->async_verify(executor, crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *rfc_test, crypto::signing_schemes::prehashed{p256_test_digest}, counted); deliver(); }); webcpp::test::covered("p256::basic_public_key::async_verify of r = 0 on bearssl", [&] { - key->async_verify(executor, crypto::signing_schemes::ecdsa_sha256, *zero_r, message, - counted); + key->async_verify(executor, crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *zero_r, message, counted); deliver(); }); webcpp::test::covered("p256::basic_keypair::async_agree on bearssl", [&] { diff --git a/test/timing_coverage_secp256k1_test.cpp b/test/timing_coverage_secp256k1_test.cpp index d0681012..ec32ea1c 100644 --- a/test/timing_coverage_secp256k1_test.cpp +++ b/test/timing_coverage_secp256k1_test.cpp @@ -323,43 +323,49 @@ void cover_verification() { auto const xonly_key = public_key->xonly(); bytes32 const not_a_key = secret_bytes(0xff); covered("secp256k1::recover of a message on secp256k1", [&] { - BOOST_TEST( - secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, *recoverable, hash) - .has_value()); + BOOST_TEST(secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, + crypto::verification_policies::low_s_only, *recoverable, hash) + .has_value()); }); covered("secp256k1::recover of a digest on secp256k1", [&] { - BOOST_TEST( - secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, *recoverable, digest) - .has_value()); + BOOST_TEST(secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, + crypto::verification_policies::low_s_only, *recoverable, digest) + .has_value()); }); covered("secp256k1 crypto::verify of schnorr on secp256k1", "crypto::verify(schnorr_t", [&] { - BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, *schnorr, hash, xonly_key) + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, *schnorr, hash, + xonly_key) .has_value()); }); - covered( - "secp256k1 crypto::verify of schnorr with the typed key on secp256k1", - "crypto::verify(schnorr_t", [&] { - BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, *schnorr, hash, *public_key) - .has_value()); - }); + covered("secp256k1 crypto::verify of schnorr with the typed key on secp256k1", + "crypto::verify(schnorr_t", [&] { + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, *schnorr, hash, + *public_key) + .has_value()); + }); covered("secp256k1 crypto::verify of ecdsa_sha256 of a message on secp256k1", "crypto::verify(ecdsa_sha256_t", [&] { - BOOST_TEST( - crypto::verify(crypto::signing_schemes::ecdsa_sha256, *ecdsa, hash, *public_key) - .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *ecdsa, hash, + *public_key) + .has_value()); }); covered("secp256k1 crypto::verify of ecdsa_sha256 of a digest on secp256k1", "crypto::verify(ecdsa_sha256_t", [&] { - BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, *ecdsa, digest, + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *ecdsa, digest, *public_key) .has_value()); }); - covered( - "secp256k1 crypto::verify of schnorr with a key off the curve on secp256k1", - "crypto::verify(schnorr_t", [&] { - BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, *schnorr, hash, not_a_key) - .error() == crypto::error::invalid_public_key); - }); + covered("secp256k1 crypto::verify of schnorr with a key off the curve on secp256k1", + "crypto::verify(schnorr_t", [&] { + BOOST_TEST(crypto::verify(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, *schnorr, hash, + not_a_key) + .error() == crypto::error::invalid_public_key); + }); auto id_of_four = recoverable->bytes(); id_of_four[64] = 4; auto const bad_id = secp::recoverable_signature::from_bytes(id_of_four); @@ -367,7 +373,8 @@ void cover_verification() { return; } covered("secp256k1::recover with a recovery id of 4 on secp256k1", [&] { - BOOST_TEST(secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, *bad_id, hash) + BOOST_TEST(secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, + crypto::verification_policies::low_s_only, *bad_id, hash) .error() == crypto::error::invalid_signature); }); } @@ -390,22 +397,22 @@ void cover_ethereum_recovery() { covered("secp256k1::recover with ecdsa_keccak256_recoverable of a message on secp256k1", "secp256k1::recover(ecdsa_keccak256_recoverable_t", [&] { BOOST_TEST(secp::recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, - *keccak, hash) + crypto::verification_policies::low_s_only, *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::signing_schemes::ecdsa_keccak256_recoverable, - *keccak, digest) + crypto::verification_policies::low_s_only, *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::signing_schemes::ecdsa_keccak256_recoverable, *bad_id, hash) - .error() == crypto::error::invalid_signature); + BOOST_TEST(secp::recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, + crypto::verification_policies::low_s_only, *bad_id, hash) + .error() == crypto::error::invalid_signature); }); } @@ -427,22 +434,28 @@ void cover_public_key_verify() { return; } covered("secp256k1::public_key::verify of ecdsa_sha256 on secp256k1", [&] { - BOOST_TEST( - public_key->verify(crypto::signing_schemes::ecdsa_sha256, *ecdsa, hash).has_value()); + BOOST_TEST(public_key + ->verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *ecdsa, hash) + .has_value()); }); covered("secp256k1::public_key::verify of schnorr on secp256k1", [&] { - BOOST_TEST( - public_key->verify(crypto::signing_schemes::schnorr, *schnorr, hash).has_value()); + BOOST_TEST(public_key + ->verify(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, *schnorr, hash) + .has_value()); }); covered("secp256k1::public_key::verify of ecdsa_sha256 of another signature on secp256k1", [&] { - BOOST_TEST( - public_key->verify(crypto::signing_schemes::ecdsa_sha256, *schnorr_as_ecdsa, hash) - .error() == crypto::error::invalid_signature); + BOOST_TEST(public_key + ->verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *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::signing_schemes::schnorr, *ecdsa_as_schnorr, hash).error() == - crypto::error::invalid_signature); + BOOST_TEST(public_key + ->verify(crypto::signing_schemes::schnorr, + crypto::verification_policies::canonical, *ecdsa_as_schnorr, hash) + .error() == crypto::error::invalid_signature); }); } diff --git a/test/timing_coverage_sodium_test.cpp b/test/timing_coverage_sodium_test.cpp index 786012cb..a2921da4 100644 --- a/test/timing_coverage_sodium_test.cpp +++ b/test/timing_coverage_sodium_test.cpp @@ -592,26 +592,31 @@ void cover_ed25519_free() { return; } covered("ed25519 crypto::verify on sodium", "crypto::verify", [&] { - BOOST_TEST((crypto::verify(crypto::signing_schemes::eddsa, *signature, message, - *public_key, ed25519::strict) + BOOST_TEST((crypto::verify(crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, *signature, + message, *public_key) .has_value())); }); // 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::signing_schemes::eddsa, zero_signature, message, - *public_key, ed25519::strict) + BOOST_TEST((crypto::verify(crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, zero_signature, + message, *public_key) .error() == crypto::error::invalid_signature)); }); covered("ed25519::public_key::verify on sodium", [&] { - BOOST_TEST( - public_key->verify(crypto::signing_schemes::eddsa, *signature, message).has_value()); + BOOST_TEST(public_key + ->verify(crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, *signature, message) + .has_value()); }); covered("ed25519::public_key::verify with a zero signature on sodium", [&] { - BOOST_TEST( - public_key->verify(crypto::signing_schemes::eddsa, zero_signature, message).error() == - crypto::error::invalid_signature); + BOOST_TEST(public_key + ->verify(crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, zero_signature, message) + .error() == crypto::error::invalid_signature); }); covered("ed25519::public_key::to_x25519 on sodium", [&] { BOOST_TEST(public_key->to_x25519().has_value()); }); @@ -666,28 +671,33 @@ void cover_ed25519_prehashed() { covered("ed25519 crypto::verify under eddsa_prehashed on sodium", "crypto::verify(eddsa_prehashed_t", [&] { BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa_prehashed, - *signature, marker, *public_key, ed25519::strict) + crypto::verification_policies::canonical, + *signature, marker, *public_key) .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::signing_schemes::eddsa_prehashed, zero_signature, + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa_prehashed, + crypto::verification_policies::canonical, 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::signing_schemes::eddsa_prehashed, *signature, marker) - .has_value()); - }); covered( - "ed25519::public_key::verify under eddsa_prehashed with a zero signature on sodium", + "ed25519::public_key::verify under eddsa_prehashed on sodium", "ed25519::public_key::verify(eddsa_prehashed_t", [&] { - BOOST_TEST( - public_key->verify(crypto::signing_schemes::eddsa_prehashed, zero_signature, marker) - .error() == crypto::error::invalid_signature); + BOOST_TEST(public_key + ->verify(crypto::signing_schemes::eddsa_prehashed, + crypto::verification_policies::canonical, *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::signing_schemes::eddsa_prehashed, + crypto::verification_policies::canonical, zero_signature, + marker) + .error() == crypto::error::invalid_signature); + }); webcpp::asio::io_context context; auto const executor = context.get_executor(); @@ -711,26 +721,29 @@ void cover_ed25519_prehashed() { }); covered("ed25519::public_key::async_verify under eddsa_prehashed on sodium", [&] { public_key->async_verify(executor, crypto::signing_schemes::eddsa_prehashed, - *signature, marker, counted); + crypto::verification_policies::canonical, *signature, + marker, counted); deliver(); }); covered("ed25519::public_key::async_verify under eddsa_prehashed with its policy on sodium", [&] { public_key->async_verify(executor, crypto::signing_schemes::eddsa_prehashed, - *signature, marker, ed25519::strict, counted); + crypto::verification_policies::canonical, + *signature, marker, counted); deliver(); }); covered("ed25519 crypto::async_verify under eddsa_prehashed on sodium", "crypto::async_verify(eddsa_prehashed_t", [&] { crypto::async_verify(executor, crypto::signing_schemes::eddsa_prehashed, - *signature, marker, *public_key, counted); + crypto::verification_policies::canonical, *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::signing_schemes::eddsa_prehashed, - zero_signature, marker, *public_key, ed25519::strict, - counted); + crypto::verification_policies::canonical, + zero_signature, marker, *public_key, counted); deliver(); }); BOOST_TEST_EQ(completions, 6); diff --git a/test/verification_policies_test.cpp b/test/verification_policies_test.cpp new file mode 100644 index 00000000..490e947e --- /dev/null +++ b/test/verification_policies_test.cpp @@ -0,0 +1,564 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the 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 verification policies (design D9, owner decision 17), each scheme under the policies it +// accepts, at run time: +// - p256_rfc6979: RFC 6979 section A.2.5's key and its "sample" signature, whose S is high, on +// BearSSL: accepted under any_s; refused under low_s_only with invalid_signature, before any +// backend call (the P-curve engine's seam counts none for the refusal); its low-S form, +// r || n - s, accepted under both; the member and the free verify alike. +// - p256_wycheproof: every case of Wycheproof's ecdsa_secp256r1_sha256_p1363_test.json: under any_s +// the file's verdict; under low_s_only invalid_signature for every valid case whose s is above +// (n - 1) / 2, computed here from p256_data.hpp's n, and the file's verdict for the others. +// - secp256k1_wycheproof: every case of ecdsa_secp256k1_sha256_bitcoin_test.json (DER, Bitcoin's +// low-S rule) gives its verdict under low_s_only; the valid high-S cases of +// ecdsa_secp256k1_sha256_p1363_test.json give invalid_signature, its low-S ones verify. +// - recover_low_s: a signature of sign(ecdsa_sha256_recoverable, m) recovers the signer's key +// under low_s_only; the same with s replaced by n - s and bit 0 of the recovery id flipped, the +// same key's signature in its high-S form, is invalid_signature; Ethereum's Keccak scheme alike. +// - ed25519_canonical: under canonical, one valid speccheck case (3) and one with a non-canonical +// R (8) give meta/ed25519_cases.json's verdicts (the twelve are ed25519_speccheck_test's), and +// Ed25519ph's signature verifies. +// - schnorr_canonical: BIP340's test-vectors.csv row 0 accepted under canonical, against the +// 32-byte x-only key and the typed key. +// - asynchronous: async_verify on Ed25519 under canonical and on P-256 under any_s and low_s_only, +// member and free, with the answers of the synchronous calls. +// The policies the schemes do not accept are refused at compile time: the message tests +// verify_secp256k1_any_s, verify_p256_canonical, verify_eddsa_low_s_only, verify_schnorr_any_s, +// recover_any_s, verify_without_policy and async_verify_without_policy. + +#include + +namespace { + +// The engine's calls: the seam of detail/p_curves.hpp, defined before any crypto header. +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the seam's counter +std::size_t engine_calls = 0; + +} // namespace + +/** Counts a call of the P-curve engine. */ +#define WEBCPP_CRYPTO_DETAIL_P_CURVE_ENGINE_ENTERED() (++engine_calls) + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "support/hex.hpp" +#include "support/p256_data.hpp" +#include "support/secp256k1_data.hpp" +#include "support/test_data.hpp" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace { + +namespace asio = webcpp::asio; +namespace crypto = webcpp::crypto; +namespace ed25519 = webcpp::crypto::curves::ed25519; +namespace p256 = webcpp::crypto::curves::p256; +namespace secp = webcpp::crypto::curves::secp256k1; +namespace json = boost::json; +namespace test = webcpp::test; +namespace policies = webcpp::crypto::verification_policies; +namespace schemes = webcpp::crypto::signing_schemes; + +using bytes = std::vector; +using scalar = std::array; + +// Compile-time: what each scheme accepts on each key, and can_verify with it. +static_assert(crypto::can_verify); +static_assert(crypto::can_verify); +static_assert(!crypto::can_verify); +static_assert(crypto::can_verify); +static_assert(!crypto::can_verify); +static_assert(crypto::can_verify); +static_assert(crypto::can_verify>); +static_assert(!crypto::can_verify); +static_assert(crypto::can_verify); +static_assert(!crypto::can_verify); +static_assert(crypto::detail::policy_accepted_v); +static_assert(crypto::detail::policy_accepted_v); +static_assert(!crypto::detail::policy_accepted_v); + +std::string str(json::value const& value) { + return std::string(std::string_view(value.as_string())); +} + +json::value load_json(std::string const& path) { + boost::system::error_code parse_error; + auto value = json::parse(test::read_file(path), parse_error); + BOOST_TEST(!parse_error); + return value; +} + +json::value wycheproof(std::string const& name) { + return load_json(WEBCPP_TEST_WYCHEPROOF "/testvectors_v1/" + name + ".json"); +} + +// Reports a case that went wrong, by its file and its number. +void report(std::string const& name, json::value const& tested, std::string_view what) { + std::string message = name + " tcId " + + std::to_string(tested.at("tcId").to_number()) + ": " + + std::string(what); + BOOST_ERROR(message.c_str()); +} + +// (n - 1) / 2 of an odd n, big-endian: n shifted right by one bit. +scalar half_of(scalar const& order) { + scalar half{}; + unsigned carried = 0; + for (std::size_t index = 0; index < order.size(); ++index) { + half[index] = static_cast((carried << 7U) | (order[index] >> 1U)); + carried = order[index] & 1U; + } + return half; +} + +// Whether the s of a 64-byte r || s is above `half`, compared as big-endian numbers. +bool high_s(std::span signature_bytes, scalar const& half) { + auto const s_bytes = signature_bytes.subspan(32, 32); + return std::ranges::lexicographical_compare(half, s_bytes); +} + +// r || n - s of a 64-byte P-256 signature. +p256::ecdsa_signature p256_negated(std::span signature_bytes) { + std::array out{}; + std::ranges::copy(signature_bytes, out.begin()); + unsigned borrow = 0; + for (std::size_t index = 32; index-- > 0;) { + unsigned const difference = + unsigned{test::p256::order[index]} - unsigned{signature_bytes[32 + index]} - borrow; + out[32 + index] = static_cast(difference & 0xffU); + borrow = (difference >> 8U) & 1U; + } + return p256::ecdsa_signature::from_bytes(out).value(); +} + +std::vector text_bytes(std::string_view text) { + return {text.begin(), text.end()}; +} + +void p256_rfc6979() { + auto const key = p256::public_key::from_bytes(test::p256::rfc6979_public); + if (!BOOST_TEST(key.has_value())) { + return; + } + auto const sample = text_bytes("sample"); + auto const high = p256::ecdsa_signature::from_bytes(test::p256::rfc6979_sample).value(); + BOOST_TEST(high_s(high.bytes(), test::p256::half_order)); + BOOST_TEST(crypto::verify(schemes::ecdsa_sha256, policies::any_s, high, sample, *key)); + BOOST_TEST(key->verify(schemes::ecdsa_sha256, policies::any_s, high, sample)); + // Refused before the backend: the engine is not entered. + engine_calls = 0; + BOOST_TEST( + crypto::verify(schemes::ecdsa_sha256, policies::low_s_only, high, sample, *key).error() == + crypto::error::invalid_signature); + BOOST_TEST(key->verify(schemes::ecdsa_sha256, policies::low_s_only, high, sample).error() == + crypto::error::invalid_signature); + BOOST_TEST(crypto::verify(schemes::ecdsa_sha256, policies::low_s_only, high, + schemes::prehashed{crypto::detail::sha256_of(sample)}, *key) + .error() == crypto::error::invalid_signature); + BOOST_TEST_EQ(engine_calls, 0U); + // Its low-S form, r || n - s: accepted under both, through the engine. + auto const low = p256_negated(high.bytes()); + BOOST_TEST(low.bytes() == test::p256::rfc6979_sample_low_s); + BOOST_TEST(crypto::verify(schemes::ecdsa_sha256, policies::any_s, low, sample, *key)); + BOOST_TEST(crypto::verify(schemes::ecdsa_sha256, policies::low_s_only, low, sample, *key)); + BOOST_TEST(key->verify(schemes::ecdsa_sha256, policies::low_s_only, low, sample)); + BOOST_TEST(engine_calls > 0U); + // The largest low S, (n - 1) / 2, passes the policy; the next one up does not. + std::array boundary{}; + std::ranges::copy(high.bytes() | std::views::take(32), boundary.begin()); + std::ranges::copy(test::p256::half_order, boundary.begin() + 32); + engine_calls = 0; + BOOST_TEST(crypto::verify(schemes::ecdsa_sha256, policies::low_s_only, + p256::ecdsa_signature::from_bytes(boundary).value(), sample, *key) + .error() == crypto::error::invalid_signature); + BOOST_TEST_EQ(engine_calls, 1U); + boundary.back() = static_cast(boundary.back() + 1U); + engine_calls = 0; + BOOST_TEST(crypto::verify(schemes::ecdsa_sha256, policies::low_s_only, + p256::ecdsa_signature::from_bytes(boundary).value(), sample, *key) + .error() == crypto::error::invalid_signature); + BOOST_TEST_EQ(engine_calls, 0U); +} + +void p256_wycheproof() { + std::string const name = "ecdsa_secp256r1_sha256_p1363_test"; + auto const document = wycheproof(name); + auto const half = half_of(test::p256::order); + BOOST_TEST(half == test::p256::half_order); + int cases = 0; + int high_valid = 0; + for (auto const& group : document.at("testGroups").as_array()) { + auto const key = p256::public_key::from_bytes( + test::from_hex(str(group.at("publicKey").at("uncompressed")))); + if (!BOOST_TEST(key.has_value())) { + continue; + } + for (auto const& tested : group.at("tests").as_array()) { + ++cases; + auto const message = test::from_hex(str(tested.at("msg"))); + auto const encoded = test::from_hex(str(tested.at("sig"))); + auto const verdict = str(tested.at("result")); + if (verdict != "valid" && verdict != "invalid") { + report(name, tested, verdict + ", not expected"); + continue; + } + bool const valid = verdict == "valid"; + auto const signature = p256::ecdsa_signature::from_bytes(encoded); + if (!signature) { + if (valid) { + report(name, tested, "a valid signature of another size"); + } + continue; + } + bool const any_s = + crypto::verify(schemes::ecdsa_sha256, policies::any_s, *signature, message, *key) + .has_value(); + bool const low_s_only = crypto::verify(schemes::ecdsa_sha256, policies::low_s_only, + *signature, message, *key) + .has_value(); + if (any_s != valid) { + report(name, tested, "any_s does not give the file's verdict"); + } + bool const high = high_s(encoded, half); + if (valid && high) { + ++high_valid; + } + if (low_s_only != (valid && !high)) { + report(name, tested, "low_s_only does not give the expected verdict"); + } + } + } + std::cout << name << ": cases=" << cases << " valid_high_s=" << high_valid << '\n'; + BOOST_TEST(high_valid > 0); +} + +void secp256k1_bitcoin() { + std::string const name = "ecdsa_secp256k1_sha256_bitcoin_test"; + auto const document = wycheproof(name); + int cases = 0; + for (auto const& group : document.at("testGroups").as_array()) { + auto const key = secp::public_key::from_bytes( + test::from_hex(str(group.at("publicKey").at("uncompressed")))); + if (!BOOST_TEST(key.has_value())) { + continue; + } + for (auto const& tested : group.at("tests").as_array()) { + ++cases; + auto const message = test::from_hex(str(tested.at("msg"))); + auto const decoded = secp::from_der(test::from_hex(str(tested.at("sig")))); + bool const verified = + decoded.has_value() && + crypto::verify(schemes::ecdsa_sha256, policies::low_s_only, *decoded, message, *key) + .has_value(); + auto const verdict = str(tested.at("result")); + if (verdict == "valid" ? !verified : verdict != "invalid" || verified) { + report(name, tested, "low_s_only does not give the file's verdict " + verdict); + } + } + } + std::cout << name << ": cases=" << cases << '\n'; + BOOST_TEST(cases > 0); +} + +void secp256k1_p1363() { + std::string const name = "ecdsa_secp256k1_sha256_p1363_test"; + auto const document = wycheproof(name); + auto const half = + half_of(test::hex<32>("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141")); + int high_refused = 0; + int low_verified = 0; + for (auto const& group : document.at("testGroups").as_array()) { + auto const key = secp::public_key::from_bytes( + test::from_hex(str(group.at("publicKey").at("uncompressed")))); + if (!BOOST_TEST(key.has_value())) { + continue; + } + for (auto const& tested : group.at("tests").as_array()) { + if (str(tested.at("result")) != "valid") { + continue; + } + auto const message = test::from_hex(str(tested.at("msg"))); + auto const encoded = test::from_hex(str(tested.at("sig"))); + auto const signature = secp::ecdsa_signature::from_bytes(encoded); + if (!BOOST_TEST(signature.has_value())) { + continue; + } + auto const verified = crypto::verify(schemes::ecdsa_sha256, policies::low_s_only, + *signature, message, *key); + if (high_s(encoded, half)) { + ++high_refused; + if (verified || verified.error() != crypto::error::invalid_signature) { + report(name, tested, "a high S not refused under low_s_only"); + } + } else { + ++low_verified; + if (!verified) { + report(name, tested, "a valid low S refused"); + } + } + } + } + std::cout << name << ": valid_high_s=" << high_refused << " valid_low_s=" << low_verified + << '\n'; + BOOST_TEST(high_refused > 0); + BOOST_TEST(low_verified > 0); +} + +// The high-S form of a recoverable signature: s replaced by n - s, bit 0 of the id flipped, which +// recovers the same key without the low-S rule. +secp::recoverable_signature high_form(secp::recoverable_signature const& signature) { + auto const& signature_bytes = signature.bytes(); + auto const negated = + test::negate_s(std::span(signature_bytes.data(), 64)); + std::array out{}; + std::ranges::copy(negated, out.begin()); + out[64] = static_cast(signature_bytes[64] ^ 1U); + return secp::recoverable_signature::from_bytes(out).value(); +} + +template +void recover_low_s(Scheme scheme) { + scalar seed{}; + seed.fill(0x2a); + auto const key = secp::keypair::from_secret(seed); + if (!BOOST_TEST(key.has_value())) { + return; + } + auto const public_key = key->public_key(); + auto const message = text_bytes("the policy of recovery"); + auto const signature = key->sign(scheme, message); + if (!BOOST_TEST(public_key.has_value()) || !BOOST_TEST(signature.has_value())) { + return; + } + auto const recovered = secp::recover(scheme, policies::low_s_only, *signature, message); + BOOST_TEST(recovered.has_value() && *recovered == *public_key); + auto const high = high_form(*signature); + BOOST_TEST(secp::recover(scheme, policies::low_s_only, high, message).error() == + crypto::error::invalid_signature); + // libsecp256k1's own recovery, which has no low-S rule, gives the signer's key from it: the + // refusal is the policy's. + secp256k1_ecdsa_recoverable_signature parsed{}; + secp256k1_pubkey point{}; + std::array digest{}; + if constexpr (std::is_same_v) { + digest = crypto::detail::secp256k1_digest(message); + } else { + digest = crypto::detail::secp256k1_keccak_digest(message); + } + BOOST_TEST(secp256k1_ecdsa_recoverable_signature_parse_compact( + secp256k1_context_static, &parsed, high.bytes().data(), high.bytes()[64]) == 1); + BOOST_TEST(secp256k1_ecdsa_recover(secp256k1_context_static, &point, &parsed, digest.data()) == + 1); + std::array compressed{}; + std::size_t length = compressed.size(); + BOOST_TEST(secp256k1_ec_pubkey_serialize(secp256k1_context_static, compressed.data(), &length, + &point, SECP256K1_EC_COMPRESSED) == 1); + BOOST_TEST(compressed == public_key->compressed()); +} + +// One speccheck case, by its index in cases.json. +struct speccheck_case { + bytes message; + bytes public_key; + bytes signature; +}; + +speccheck_case speccheck(json::value const& cases, std::size_t index) { + auto const& entry = cases.as_array().at(index).as_object(); + return {test::from_hex(str(entry.at("message"))), test::from_hex(str(entry.at("pub_key"))), + test::from_hex(str(entry.at("signature")))}; +} + +void ed25519_canonical() { + auto const cases = load_json(WEBCPP_TEST_ED25519_SPECCHECK "/cases.json"); + auto const committed = load_json(WEBCPP_TEST_CRYPTO_META "/ed25519_cases.json"); + auto const& canonical_row = committed.at("backends").at("sodium").at("canonical").as_array(); + for (std::size_t const index : {std::size_t{3}, std::size_t{8}}) { + auto const tested = speccheck(cases, index); + auto const key = ed25519::public_key::from_bytes(tested.public_key); + auto const signature = ed25519::signature::from_bytes(tested.signature); + if (!BOOST_TEST(key.has_value()) || !BOOST_TEST(signature.has_value())) { + continue; + } + auto const verified = crypto::verify( + schemes::eddsa, policies::canonical, *signature, tested.message, *key); + BOOST_TEST_EQ(verified ? "accept" : "reject", str(canonical_row.at(index))); + BOOST_TEST(key->verify(schemes::eddsa, policies::canonical, *signature, tested.message) + .has_value() == verified.has_value()); + } + // Ed25519ph under the same policy. + std::array seed{}; + seed.fill(7); + auto const key = ed25519::keypair::from_secret(seed); + if (!BOOST_TEST(key.has_value())) { + return; + } + std::array digest{}; + digest.fill(0x5a); + auto const signature = key->sign(schemes::eddsa_prehashed, schemes::prehashed{digest}); + auto const public_key = key->public_key(); + if (BOOST_TEST(signature.has_value()) && BOOST_TEST(public_key.has_value())) { + BOOST_TEST(crypto::verify(schemes::eddsa_prehashed, policies::canonical, *signature, + schemes::prehashed{digest}, *public_key)); + } +} + +std::vector csv_fields(std::string const& line) { + std::vector fields; + std::string field; + std::istringstream in(line); + while (std::getline(in, field, ',')) { + fields.push_back(field); + } + return fields; +} + +void schnorr_canonical() { + std::istringstream rows(test::read_file(WEBCPP_TEST_BIPS "/bip-0340/test-vectors.csv")); + std::string line; + std::getline(rows, line); // the header + std::getline(rows, line); + auto const fields = csv_fields(line); + if (!BOOST_TEST(fields.size() >= 7U) || !BOOST_TEST_EQ(fields[0], "0")) { + return; + } + BOOST_TEST_EQ(fields[6], "TRUE"); + auto const xonly = test::from_hex(fields[2]); + auto const message = test::from_hex(fields[4]); + auto const signature = secp::schnorr_signature::from_bytes(test::from_hex(fields[5])); + auto const secret_key = secp::keypair::from_secret(test::from_hex(fields[1])); + if (!BOOST_TEST_EQ(xonly.size(), 32U) || !BOOST_TEST(signature.has_value()) || + !BOOST_TEST(secret_key.has_value())) { + return; + } + BOOST_TEST(crypto::verify(schemes::schnorr, policies::canonical, *signature, message, + std::span(xonly.data(), 32))); + auto const public_key = secret_key->public_key(); + if (BOOST_TEST(public_key.has_value())) { + BOOST_TEST(crypto::verify(schemes::schnorr, policies::canonical, *signature, message, + *public_key)); + BOOST_TEST(public_key->verify(schemes::schnorr, policies::canonical, *signature, message)); + } +} + +// Runs an asynchronous verify with a callback and gives its error code. +template +boost::system::error_code completed(asio::io_context& context, Start start) { + boost::system::error_code code = crypto::error::backend_failure; + int calls = 0; + start(context.get_executor(), [&code, &calls](boost::system::error_code given) { + code = given; + ++calls; + }); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(calls, 1); + return code; +} + +void asynchronous() { + asio::io_context context; + // Ed25519 under canonical, member and free. + std::array seed{}; + seed.fill(3); + auto const ed25519_key = ed25519::keypair::from_secret(seed); + auto const message = text_bytes("asynchronous"); + if (!BOOST_TEST(ed25519_key.has_value())) { + return; + } + auto const ed25519_public = ed25519_key->public_key(); + auto const ed25519_signature = ed25519_key->sign(schemes::eddsa, message); + if (!BOOST_TEST(ed25519_public.has_value()) || !BOOST_TEST(ed25519_signature.has_value())) { + return; + } + BOOST_TEST(!completed(context, [&](auto const& executor, auto&& token) { + return crypto::async_verify(executor, schemes::eddsa, policies::canonical, + *ed25519_signature, message, *ed25519_public, + std::forward(token)); + })); + BOOST_TEST(!completed(context, [&](auto const& executor, auto&& token) { + return ed25519_public->async_verify(executor, schemes::eddsa, policies::canonical, + *ed25519_signature, message, + std::forward(token)); + })); + // P-256: the RFC's high-S signature, accepted under any_s and refused under low_s_only, as + // the synchronous verify answers. + auto const p256_key = p256::public_key::from_bytes(test::p256::rfc6979_public); + if (!BOOST_TEST(p256_key.has_value())) { + return; + } + auto const sample = text_bytes("sample"); + auto const high = p256::ecdsa_signature::from_bytes(test::p256::rfc6979_sample).value(); + BOOST_TEST(!completed(context, [&](auto const& executor, auto&& token) { + return crypto::async_verify(executor, schemes::ecdsa_sha256, policies::any_s, high, sample, + *p256_key, std::forward(token)); + })); + BOOST_TEST(completed(context, [&](auto const& executor, auto&& token) { + return p256_key->async_verify(executor, schemes::ecdsa_sha256, + policies::low_s_only, high, sample, + std::forward(token)); + }) == crypto::error::invalid_signature); +} + +} // namespace + +int main() { + p256_rfc6979(); + p256_wycheproof(); + secp256k1_bitcoin(); + secp256k1_p1363(); + recover_low_s(crypto::signing_schemes::ecdsa_sha256_recoverable); + recover_low_s(crypto::signing_schemes::ecdsa_keccak256_recoverable); + ed25519_canonical(); + schnorr_canonical(); + asynchronous(); + return test::exit_status(boost::report_errors()); +} From 5d27179e8204706567e4c2c0d9bd5ba4362c97af Mon Sep 17 00:00:00 2001 From: R Date: Mon, 30 Nov 2026 20:18:19 -0300 Subject: [PATCH 06/81] crypto: the verification policies lint fix --- doc/tables/generate_test.py | 3 +- include/webcpp/crypto/async.hpp | 14 +-- include/webcpp/crypto/curves/ed25519.hpp | 67 +++++----- include/webcpp/crypto/curves/p256.hpp | 47 +++---- include/webcpp/crypto/curves/secp256k1.hpp | 33 ++--- test/Jamfile | 11 +- test/verification_policies_test.cpp | 136 ++++++++++++--------- 7 files changed, 171 insertions(+), 140 deletions(-) diff --git a/doc/tables/generate_test.py b/doc/tables/generate_test.py index f55ba8c3..ad742143 100644 --- a/doc/tables/generate_test.py +++ b/doc/tables/generate_test.py @@ -244,7 +244,8 @@ def test_the_edge_cases_table_has_a_row_per_case_and_a_column_per_verdict(_: Pat data = {'backends': {'sodium': {'title': 'libsodium'}}} cases = {'source': {'repository': 'novifinancial/ed25519-speccheck', 'commit': '65519336', 'file': 'cases.json'}, - 'backends': {'sodium': {'raw': ['reject', 'accept'], 'canonical': ['reject', 'accept']}}, + 'backends': {'sodium': {'raw': ['reject', 'accept'], + 'canonical': ['reject', 'accept']}}, 'outside': {'webcrypto-node': {'node': '26.13.0', 'openssl': '4.1.0', 'verdicts': ['accept', 'accept']}}, 'cases': ['`S` = 0', '`A` non-canonical']} diff --git a/include/webcpp/crypto/async.hpp b/include/webcpp/crypto/async.hpp index 1fcc7819..86ea99bc 100644 --- a/include/webcpp/crypto/async.hpp +++ b/include/webcpp/crypto/async.hpp @@ -580,10 +580,9 @@ auto initiate_verify_ed25519(Executor const& completion_executor, Signature cons refused_v, "webcpp::crypto: an Ed25519 public key verifies crypto::signing_schemes::eddsa or " "crypto::signing_schemes::eddsa_prehashed."); - } else if constexpr (!check_policy()) { - // Never compiled into a program: check_policy stopped the build. - } else if constexpr (!check_signature()) { - // Never compiled into a program: check_signature stopped the build. + } else if constexpr (!check_policy() || + !check_signature()) { + // Never compiled into a program: check_policy or check_signature stopped the build. } else if constexpr (!input_valid_v) { check_input(); } else if constexpr (asynchronous_backend_v) { @@ -1649,11 +1648,10 @@ auto curves::p256::basic_public_key::async_verify( detail::refused_v, "webcpp::crypto: a P-256 public key verifies crypto::signing_schemes::ecdsa_sha256."); } else if constexpr (!detail::check_policy()) { - // Never compiled into a program: check_policy stopped the build. - } else if constexpr (!detail::check_signature() || + !detail::check_signature()) { - // Never compiled into a program: check_signature stopped the build. + // Never compiled into a program: check_policy or check_signature stopped the build. } else if constexpr (!detail::input_valid_v) { detail::check_input(); } else if constexpr (detail::asynchronous_backend_v) { diff --git a/include/webcpp/crypto/curves/ed25519.hpp b/include/webcpp/crypto/curves/ed25519.hpp index c375c4f0..fdb43006 100644 --- a/include/webcpp/crypto/curves/ed25519.hpp +++ b/include/webcpp/crypto/curves/ed25519.hpp @@ -250,19 +250,20 @@ class public_key { 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) { + if constexpr (std::is_same_v && + !detail::asynchronous_backend_v) { + if constexpr (detail::check_policy()) { + return detail::ed25519_verify( + detail::checked_signature_bytes( + signature_value), + message_input, bytes_); + } else { + // Never compiled into a program: check_policy stopped the build. + return error::invalid_signature; + } + } else { // Never compiled into a program: an assertion above stopped the build. return error::invalid_signature; - } else if constexpr (!detail::check_policy()) { - // Never compiled into a program: check_policy stopped the build. - return error::invalid_signature; - } else { - return detail::ed25519_verify( - detail::checked_signature_bytes( - signature_value), - message_input, bytes_); } } @@ -303,15 +304,15 @@ class public_key { detail::refuse_ed25519ph_on_asynchronous_backend(); // Never compiled into a program: the assertion above stopped the build. return error::invalid_signature; - } else if constexpr (!detail::check_policy()) { - // Never compiled into a program: check_policy stopped the build. - return error::invalid_signature; - } else { + } else if constexpr (detail::check_policy()) { return detail::ed25519ph_verify( detail::checked_signature_bytes( signature_value), digest_input, bytes_); + } else { + // Never compiled into a program: check_policy stopped the build. + return error::invalid_signature; } } @@ -1024,19 +1025,21 @@ template , class Policy, cl static_assert(!detail::asynchronous_backend_v, "webcpp::crypto: verify on this backend completes asynchronously: call " "async_verify."); - if constexpr (detail::asynchronous_backend_v) { + if constexpr (!detail::asynchronous_backend_v) { + if constexpr (detail::check_policy()) { + auto const key_bytes = public_key.bytes(); + return detail::ed25519_verify( + detail::checked_signature_bytes(signature_value), + message_input, key_bytes); + } else { + // Never compiled into a program: check_policy stopped the build. + return error::invalid_signature; + } + } else { // Never compiled into a program: the assertion above stopped the build. return error::invalid_signature; - } else if constexpr (!detail::check_policy()) { - // Never compiled into a program: check_policy stopped the build. - return error::invalid_signature; - } else { - auto const key_bytes = public_key.bytes(); - return detail::ed25519_verify( - detail::checked_signature_bytes( - signature_value), - message_input, key_bytes); } } @@ -1077,16 +1080,16 @@ template , class Policy, cl detail::refuse_ed25519ph_on_asynchronous_backend(); // Never compiled into a program: the assertion above stopped the build. return error::invalid_signature; - } else if constexpr (!detail::check_policy()) { - // Never compiled into a program: check_policy stopped the build. - return error::invalid_signature; - } else { + } else if constexpr (detail::check_policy()) { 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: check_policy stopped the build. + return error::invalid_signature; } } diff --git a/include/webcpp/crypto/curves/p256.hpp b/include/webcpp/crypto/curves/p256.hpp index 54a0dd1f..b4b24098 100644 --- a/include/webcpp/crypto/curves/p256.hpp +++ b/include/webcpp/crypto/curves/p256.hpp @@ -267,19 +267,22 @@ class basic_public_key { 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) { + if constexpr (std::is_same_v && + !detail::asynchronous_backend_v) { + if constexpr (detail::check_policy()) { + return detail::p256_verify( + detail::checked_signature_bytes( + signature_value), + signing_input, point_); + } else { + // Never compiled into a program: check_policy stopped the build. + return error::invalid_signature; + } + } else { // Never compiled into a program: an assertion above stopped the build. return error::invalid_signature; - } else if constexpr (!detail::check_policy()) { - // Never compiled into a program: check_policy stopped the build. - return error::invalid_signature; - } else { - return detail::p256_verify( - detail::checked_signature_bytes( - signature_value), - signing_input, point_); } } @@ -916,18 +919,20 @@ template static_assert(!detail::asynchronous_backend_v, "webcpp::crypto: verify on this backend completes asynchronously: call " "async_verify."); - if constexpr (detail::asynchronous_backend_v) { + if constexpr (!detail::asynchronous_backend_v) { + if constexpr (detail::check_policy>()) { + 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: check_policy stopped the build. + return error::invalid_signature; + } + } else { // Never compiled into a program: the assertion above stopped the build. return error::invalid_signature; - } else if constexpr (!detail::check_policy>()) { - // Never compiled into a program: check_policy stopped the build. - return error::invalid_signature; - } else { - return detail::p256_verify( - detail::checked_signature_bytes(signature_value), - signing_input, detail::p_curve_access::point(public_key)); } } diff --git a/include/webcpp/crypto/curves/secp256k1.hpp b/include/webcpp/crypto/curves/secp256k1.hpp index feb8dc54..60b42dbc 100644 --- a/include/webcpp/crypto/curves/secp256k1.hpp +++ b/include/webcpp/crypto/curves/secp256k1.hpp @@ -823,24 +823,25 @@ class public_key { "crypto::signing_schemes::ecdsa_sha256_recoverable or a " "crypto::signing_schemes::ecdsa_keccak256_recoverable signature gives its key to " "curves::secp256k1::recover."); - if constexpr (!is_ecdsa && !is_schnorr) { + if constexpr (is_ecdsa || is_schnorr) { + if constexpr (!webcpp::crypto::detail::check_policy()) { + // Never compiled into a program: check_policy stopped the build. + return error::invalid_signature; + } else if constexpr (is_ecdsa) { + return webcpp::crypto::detail::secp256k1_verify_ecdsa( + webcpp::crypto::detail::checked_signature_bytes< + ecdsa_signature, signing_schemes::ecdsa_sha256_t>(signature_value), + signing_input, point_value_); + } else { + return webcpp::crypto::detail::secp256k1_verify_schnorr_key( + 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; - } else if constexpr (!webcpp::crypto::detail::check_policy()) { - // Never compiled into a program: check_policy stopped the build. - return error::invalid_signature; - } else if constexpr (is_ecdsa) { - return webcpp::crypto::detail::secp256k1_verify_ecdsa( - webcpp::crypto::detail::checked_signature_bytes( - signature_value), - signing_input, point_value_); - } else { - return webcpp::crypto::detail::secp256k1_verify_schnorr_key( - webcpp::crypto::detail::checked_signature_bytes( - signature_value), - signing_input, point_value_); } } diff --git a/test/Jamfile b/test/Jamfile index c01d0b56..59781db2 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -649,11 +649,12 @@ crypto-run ed25519_speccheck : ed25519_speccheck_test.cpp [ webcpp.data $(CRYPTO_TEST_META) ] ../meta/ed25519_cases.json emscripten:-sJSPI ; -# The verification policies (design D9): P-256's low_s_only and any_s on BearSSL, -# the RFC's high S and every Wycheproof P1363 case under both, a refusal before -# the engine; secp256k1's low_s_only against Wycheproof's Bitcoin and P1363 -# files; recover's low_s_only under both recoverable schemes; Ed25519's and -# BIP340's canonical; the asynchronous forms on Ed25519 and P-256. +# The verification policies (design D9): P-256's low_s_only and any_s on +# BearSSL, the RFC's high S and every Wycheproof P1363 case under both, a +# refusal before the engine; secp256k1's low_s_only against Wycheproof's +# Bitcoin and P1363 files; recover's low_s_only under both recoverable +# schemes; Ed25519's and BIP340's canonical; the asynchronous forms on +# Ed25519 and P-256. crypto-run verification_policies : verification_policies_test.cpp : /third_party//bearssl /third_party//secp256k1 /third_party//xkcp /third_party//sodium diff --git a/test/verification_policies_test.cpp b/test/verification_policies_test.cpp index 490e947e..286a2c6a 100644 --- a/test/verification_policies_test.cpp +++ b/test/verification_policies_test.cpp @@ -142,9 +142,9 @@ json::value wycheproof(std::string const& name) { // Reports a case that went wrong, by its file and its number. void report(std::string const& name, json::value const& tested, std::string_view what) { - std::string message = name + " tcId " + - std::to_string(tested.at("tcId").to_number()) + ": " + - std::string(what); + std::string const message = name + " tcId " + + std::to_string(tested.at("tcId").to_number()) + ": " + + std::string(what); BOOST_ERROR(message.c_str()); } @@ -153,8 +153,9 @@ scalar half_of(scalar const& order) { scalar half{}; unsigned carried = 0; for (std::size_t index = 0; index < order.size(); ++index) { - half[index] = static_cast((carried << 7U) | (order[index] >> 1U)); - carried = order[index] & 1U; + unsigned const byte = order[index]; + half[index] = static_cast((carried << 7U) | (byte >> 1U)); + carried = byte & 1U; } return half; } @@ -228,6 +229,42 @@ void p256_rfc6979() { BOOST_TEST_EQ(engine_calls, 0U); } +// The verdicts of one case of the P-256 P1363 file under both policies, reported where they +// differ from the expected ones: the file's under any_s; under low_s_only, invalid_signature for a +// valid case whose s is above `half`, the file's for the others. Whether it is a valid high S. +bool p256_case(std::string const& name, json::value const& tested, p256::public_key const& key, + scalar const& half) { + auto const message = test::from_hex(str(tested.at("msg"))); + auto const encoded = test::from_hex(str(tested.at("sig"))); + auto const verdict = str(tested.at("result")); + if (verdict != "valid" && verdict != "invalid") { + report(name, tested, verdict + ", not expected"); + return false; + } + bool const valid = verdict == "valid"; + auto const signature = p256::ecdsa_signature::from_bytes(encoded); + if (!signature) { + if (valid) { + report(name, tested, "a valid signature of another size"); + } + return false; + } + bool const any_s = + crypto::verify(schemes::ecdsa_sha256, policies::any_s, *signature, message, key) + .has_value(); + bool const low_s_only = + crypto::verify(schemes::ecdsa_sha256, policies::low_s_only, *signature, message, key) + .has_value(); + bool const high = high_s(encoded, half); + if (any_s != valid) { + report(name, tested, "any_s does not give the file's verdict"); + } + if (low_s_only != (valid && !high)) { + report(name, tested, "low_s_only does not give the expected verdict"); + } + return valid && high; +} + void p256_wycheproof() { std::string const name = "ecdsa_secp256r1_sha256_p1363_test"; auto const document = wycheproof(name); @@ -243,37 +280,7 @@ void p256_wycheproof() { } for (auto const& tested : group.at("tests").as_array()) { ++cases; - auto const message = test::from_hex(str(tested.at("msg"))); - auto const encoded = test::from_hex(str(tested.at("sig"))); - auto const verdict = str(tested.at("result")); - if (verdict != "valid" && verdict != "invalid") { - report(name, tested, verdict + ", not expected"); - continue; - } - bool const valid = verdict == "valid"; - auto const signature = p256::ecdsa_signature::from_bytes(encoded); - if (!signature) { - if (valid) { - report(name, tested, "a valid signature of another size"); - } - continue; - } - bool const any_s = - crypto::verify(schemes::ecdsa_sha256, policies::any_s, *signature, message, *key) - .has_value(); - bool const low_s_only = crypto::verify(schemes::ecdsa_sha256, policies::low_s_only, - *signature, message, *key) - .has_value(); - if (any_s != valid) { - report(name, tested, "any_s does not give the file's verdict"); - } - bool const high = high_s(encoded, half); - if (valid && high) { - ++high_valid; - } - if (low_s_only != (valid && !high)) { - report(name, tested, "low_s_only does not give the expected verdict"); - } + high_valid += p256_case(name, tested, *key, half) ? 1 : 0; } } std::cout << name << ": cases=" << cases << " valid_high_s=" << high_valid << '\n'; @@ -308,6 +315,28 @@ void secp256k1_bitcoin() { BOOST_TEST(cases > 0); } +// One valid case of the secp256k1 P1363 file under low_s_only: refused with invalid_signature +// when its s is above `half`, verified otherwise, reported where not. Whether its S is high. +bool secp256k1_p1363_case(std::string const& name, json::value const& tested, + secp::public_key const& key, scalar const& half) { + auto const message = test::from_hex(str(tested.at("msg"))); + auto const encoded = test::from_hex(str(tested.at("sig"))); + auto const signature = secp::ecdsa_signature::from_bytes(encoded); + if (!BOOST_TEST(signature.has_value())) { + return false; + } + auto const verified = + crypto::verify(schemes::ecdsa_sha256, policies::low_s_only, *signature, message, key); + bool const high = high_s(encoded, half); + if (high && (verified || verified.error() != crypto::error::invalid_signature)) { + report(name, tested, "a high S not refused under low_s_only"); + } + if (!high && !verified) { + report(name, tested, "a valid low S refused"); + } + return high; +} + void secp256k1_p1363() { std::string const name = "ecdsa_secp256k1_sha256_p1363_test"; auto const document = wycheproof(name); @@ -325,24 +354,10 @@ void secp256k1_p1363() { if (str(tested.at("result")) != "valid") { continue; } - auto const message = test::from_hex(str(tested.at("msg"))); - auto const encoded = test::from_hex(str(tested.at("sig"))); - auto const signature = secp::ecdsa_signature::from_bytes(encoded); - if (!BOOST_TEST(signature.has_value())) { - continue; - } - auto const verified = crypto::verify(schemes::ecdsa_sha256, policies::low_s_only, - *signature, message, *key); - if (high_s(encoded, half)) { + if (secp256k1_p1363_case(name, tested, *key, half)) { ++high_refused; - if (verified || verified.error() != crypto::error::invalid_signature) { - report(name, tested, "a high S not refused under low_s_only"); - } } else { ++low_verified; - if (!verified) { - report(name, tested, "a valid low S refused"); - } } } } @@ -360,7 +375,8 @@ secp::recoverable_signature high_form(secp::recoverable_signature const& signatu test::negate_s(std::span(signature_bytes.data(), 64)); std::array out{}; std::ranges::copy(negated, out.begin()); - out[64] = static_cast(signature_bytes[64] ^ 1U); + unsigned const recovery_id = signature_bytes[64]; + out[64] = static_cast(recovery_id ^ 1U); return secp::recoverable_signature::from_bytes(out).value(); } @@ -400,7 +416,7 @@ void recover_low_s(Scheme scheme) { std::array compressed{}; std::size_t length = compressed.size(); BOOST_TEST(secp256k1_ec_pubkey_serialize(secp256k1_context_static, compressed.data(), &length, - &point, SECP256K1_EC_COMPRESSED) == 1); + &point, crypto::detail::secp256k1_compressed) == 1); BOOST_TEST(compressed == public_key->compressed()); } @@ -412,15 +428,21 @@ struct speccheck_case { }; speccheck_case speccheck(json::value const& cases, std::size_t index) { - auto const& entry = cases.as_array().at(index).as_object(); - return {test::from_hex(str(entry.at("message"))), test::from_hex(str(entry.at("pub_key"))), - test::from_hex(str(entry.at("signature")))}; + auto const& entries = cases.as_array(); + auto const& entry = entries.at(index).as_object(); + return { + .message = test::from_hex(str(entry.at("message"))), + .public_key = test::from_hex(str(entry.at("pub_key"))), + .signature = test::from_hex(str(entry.at("signature"))), + }; } void ed25519_canonical() { auto const cases = load_json(WEBCPP_TEST_ED25519_SPECCHECK "/cases.json"); auto const committed = load_json(WEBCPP_TEST_CRYPTO_META "/ed25519_cases.json"); - auto const& canonical_row = committed.at("backends").at("sodium").at("canonical").as_array(); + auto const& backends = committed.at("backends"); + auto const& sodium = backends.at("sodium"); + auto const& canonical_row = sodium.at("canonical").as_array(); for (std::size_t const index : {std::size_t{3}, std::size_t{8}}) { auto const tested = speccheck(cases, index); auto const key = ed25519::public_key::from_bytes(tested.public_key); From 26df1ef23237030d5952efbec7a806f4272b4bd9 Mon Sep 17 00:00:00 2001 From: R Date: Mon, 30 Nov 2026 20:50:15 -0300 Subject: [PATCH 07/81] crypto: the verification policies' doc comments, one catch-all of the arity before the policies --- doc/llms.txt | 2 +- include/webcpp/crypto/async.hpp | 4 +- .../webcpp/crypto/curves/secp256k1/musig.hpp | 4 +- include/webcpp/crypto/signing.hpp | 46 ++++++------------- 4 files changed, 19 insertions(+), 37 deletions(-) diff --git a/doc/llms.txt b/doc/llms.txt index a2ccd735..49bf8a00 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -210,7 +210,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - 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. - partial_signature_verify: Verifies one signer's partial signature (`secp256k1_musig_partial_sig_verify`), which tells a dishonest or faulty signer apart before the signature is aggregated. - - partial_signature_aggregate: The BIP 340 signature of the partial signatures (`secp256k1_musig_partial_sig_agg`), which `crypto::verify(crypto::signing_schemes::schnorr, crypto::verification_policies::canonical, signature, message, key)` checks under `aggregate_key::xonly_public_key()`. + - partial_signature_aggregate: The BIP 340 signature of the partial signatures (`secp256k1_musig_partial_sig_agg`), which `crypto::verify` of `crypto::signing_schemes::schnorr`, under `crypto::verification_policies::canonical`, checks under `aggregate_key::xonly_public_key()`. - parse_public_nonce: Parses a signer's public nonce (`secp256k1_musig_pubnonce_parse`): two compressed points. - serialize_public_nonce: Serialises a signer's public nonce (`secp256k1_musig_pubnonce_serialize`). - parse_aggregate_nonce: Parses an aggregate nonce (`secp256k1_musig_aggnonce_parse`): two compressed points, either of which may be the point at infinity, written as 33 zero bytes. diff --git a/include/webcpp/crypto/async.hpp b/include/webcpp/crypto/async.hpp index 86ea99bc..71771b16 100644 --- a/include/webcpp/crypto/async.hpp +++ b/include/webcpp/crypto/async.hpp @@ -1209,7 +1209,9 @@ void async_verify([[maybe_unused]] Executor const& completion_executor, /** * Stops the build: an `async_verify` of the arity before the verification policies, * `async_verify(executor, scheme, signature, input, public_key, token)`, with no policy after the - * scheme. The message names the policies the scheme takes on the key (design D9). + * scheme. + * + * The message names the policies the scheme takes on the key (design D9). * * @tparam Backend Ignored: the first template parameter, as on every `async_verify`. * @tparam Executor The executor's type. diff --git a/include/webcpp/crypto/curves/secp256k1/musig.hpp b/include/webcpp/crypto/curves/secp256k1/musig.hpp index 6e38fae1..2303fc9e 100644 --- a/include/webcpp/crypto/curves/secp256k1/musig.hpp +++ b/include/webcpp/crypto/curves/secp256k1/musig.hpp @@ -559,8 +559,8 @@ template > /** * The BIP 340 signature of the partial signatures (`secp256k1_musig_partial_sig_agg`), which - * `crypto::verify(crypto::signing_schemes::schnorr, crypto::verification_policies::canonical, - * signature, message, key)` checks under `aggregate_key::xonly_public_key()`. + * `crypto::verify` of `crypto::signing_schemes::schnorr`, under + * `crypto::verification_policies::canonical`, checks under `aggregate_key::xonly_public_key()`. * * @tparam Backend The backend, `backends::secp256k1`. * @param signing_session The session of the message. diff --git a/include/webcpp/crypto/signing.hpp b/include/webcpp/crypto/signing.hpp index fec61aa0..fabe7a77 100644 --- a/include/webcpp/crypto/signing.hpp +++ b/include/webcpp/crypto/signing.hpp @@ -402,9 +402,11 @@ namespace verification_policies { /** * ECDSA's verification that refuses a signature whose S is above (n - 1) / 2, as * `invalid_signature` before any backend call on P-256 and before recovery in - * `curves::secp256k1::recover`: Bitcoin's rule (BIP 146), Ethereum's for a transaction (EIP-2), and - * libsecp256k1's own. secp256k1's ECDSA, the recoverable schemes included, takes it alone; P-256's - * takes it or `any_s`. + * `curves::secp256k1::recover`. + * + * It is Bitcoin's rule (BIP 146), Ethereum's for a transaction (EIP-2), and libsecp256k1's own. + * secp256k1's ECDSA, the recoverable schemes included, takes it alone; P-256's takes it or + * `any_s`. */ inline constexpr low_s_only_t low_s_only{}; @@ -1068,36 +1070,14 @@ template - requires(detail::is_scheme_v && !detail::is_policy_v) -[[nodiscard]] boost::system::result verify( - [[maybe_unused]] Scheme signing_scheme, [[maybe_unused]] Signature const& signature_value, - [[maybe_unused]] Input const& signing_input, - [[maybe_unused]] PublicKey const& public_key) noexcept { - detail::refuse_missing_policy>(); - return {}; -} - -/** - * Stops the build: a `verify` of the arity before the verification policies with its backend - * named first, `verify(scheme, signature, input, public_key)`, as the overload without - * the backend. + * It takes `verify(scheme, signature, input, public_key)` and, with the backend named first, as + * every curve's verify takes it, `verify(scheme, signature, input, public_key)`; the + * message names the policies the scheme takes on the key (design D9). * - * @tparam Backend The backend named, which is no scheme. + * @tparam Named The backend, when the call names one first; nothing otherwise. * @tparam Scheme A scheme tag. * @tparam Signature The signature's type, which is no policy. * @tparam Input The input's type. @@ -1108,8 +1088,8 @@ template * @param public_key The public key. * @return Never: the call does not compile. */ -template - requires(!detail::is_scheme_v && detail::is_scheme_v && +template + requires(sizeof...(Named) <= 1 && detail::is_scheme_v && !detail::is_policy_v) [[nodiscard]] boost::system::result verify( [[maybe_unused]] Scheme signing_scheme, [[maybe_unused]] Signature const& signature_value, From 27cbd795a8868b78150272a812fc6e2f7d8dd34e Mon Sep 17 00:00:00 2001 From: R Date: Mon, 30 Nov 2026 21:58:13 -0300 Subject: [PATCH 08/81] crypto: P-256's async_verify applies the policy before the engine, prehashed_signer::verify takes the policy, one row of policies per scheme, the guide's lookup sentence --- doc/curves.adoc | 17 +- doc/ed25519.adoc | 7 +- doc/generated/messages.adoc | 40 +++++ doc/llms.txt | 6 +- doc/tables/crypto.json | 6 +- example/ed25519_sign.cpp | 8 +- include/webcpp/crypto/async.hpp | 93 +++++++++-- include/webcpp/crypto/curves/ed25519.hpp | 38 ++++- include/webcpp/crypto/curves/p256.hpp | 5 +- include/webcpp/crypto/curves/secp256k1.hpp | 14 +- include/webcpp/crypto/signing.hpp | 96 +++++++---- test/Jamfile | 7 + test/allocation_sodium_test.cpp | 5 +- test/async_verify_engine_test.cpp | 155 ++++++++++++++++++ test/ed25519ph_sodium_test.cpp | 23 ++- test/messages/Jamfile | 4 + .../Jamfile | 14 ++ .../async_verify_secp256k1_without_policy.cpp | 46 ++++++ .../Jamfile | 14 ++ ...prehashed_signer_verify_without_policy.cpp | 29 ++++ .../recover_ecdsa_without_policy/Jamfile | 14 ++ .../recover_ecdsa_without_policy.cpp | 39 +++++ test/messages/recover_without_policy/Jamfile | 14 ++ .../recover_without_policy.cpp | 39 +++++ test/msvc/Jamfile | 4 + .../Jamfile | 12 ++ .../app.cpp | 40 +++++ .../Jamfile | 11 ++ .../app.cpp | 23 +++ .../msvc/recover_ecdsa_without_policy/Jamfile | 11 ++ .../msvc/recover_ecdsa_without_policy/app.cpp | 33 ++++ test/msvc/recover_without_policy/Jamfile | 11 ++ test/msvc/recover_without_policy/app.cpp | 33 ++++ test/timing_coverage_sodium_test.cpp | 14 +- test/verification_policies_test.cpp | 30 ++-- 35 files changed, 859 insertions(+), 96 deletions(-) create mode 100644 test/async_verify_engine_test.cpp create mode 100644 test/messages/async_verify_secp256k1_without_policy/Jamfile create mode 100644 test/messages/async_verify_secp256k1_without_policy/async_verify_secp256k1_without_policy.cpp create mode 100644 test/messages/prehashed_signer_verify_without_policy/Jamfile create mode 100644 test/messages/prehashed_signer_verify_without_policy/prehashed_signer_verify_without_policy.cpp create mode 100644 test/messages/recover_ecdsa_without_policy/Jamfile create mode 100644 test/messages/recover_ecdsa_without_policy/recover_ecdsa_without_policy.cpp create mode 100644 test/messages/recover_without_policy/Jamfile create mode 100644 test/messages/recover_without_policy/recover_without_policy.cpp create mode 100644 test/msvc/async_verify_secp256k1_without_policy/Jamfile create mode 100644 test/msvc/async_verify_secp256k1_without_policy/app.cpp create mode 100644 test/msvc/prehashed_signer_verify_without_policy/Jamfile create mode 100644 test/msvc/prehashed_signer_verify_without_policy/app.cpp create mode 100644 test/msvc/recover_ecdsa_without_policy/Jamfile create mode 100644 test/msvc/recover_ecdsa_without_policy/app.cpp create mode 100644 test/msvc/recover_without_policy/Jamfile create mode 100644 test/msvc/recover_without_policy/app.cpp diff --git a/doc/curves.adoc b/doc/curves.adoc index 64fb78da..b965c1c7 100644 --- a/doc/curves.adoc +++ b/doc/curves.adoc @@ -579,14 +579,15 @@ 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::signing_schemes::eddsa, crypto::verification_policies::canonical, signature, -message, public_key)` is `crypto::verify`. The catch-alls that stop the build -with a message, those of `crypto::sign`, `crypto::verify` and -`crypto::async_verify`, take only a scheme tag in the place of the scheme, and -the one of `crypto::agree` only a key pair of the contract, so that a function -`sign` or `verify` of the program, of the same arity, called unqualified on the -program's own types, is never captured by one of them. +The free forms are called qualified, `crypto::verify(...)`, or after +`using webcpp::crypto::verify;`: argument-dependent lookup does not find them, the +scheme and policy tags being of the nested namespaces `crypto::signing_schemes` +and `crypto::verification_policies`, not of `webcpp::crypto` itself. The +catch-alls that stop the build with a message, those of `crypto::sign`, +`crypto::verify` and `crypto::async_verify`, take only a scheme tag in the place +of the scheme, and the one of `crypto::agree` only a key pair of the contract, +so that a function `sign` or `verify` of the program, of the same arity, called +on the program's own types, is never captured by one of them. The asynchronous members are declared in their classes and defined in ``, so that a curve's or a cipher's header never diff --git a/doc/ed25519.adoc b/doc/ed25519.adoc index 9a99abcf..dde1cd0b 100644 --- a/doc/ed25519.adoc +++ b/doc/ed25519.adoc @@ -92,8 +92,9 @@ 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 +key pair, `sign(key_pair)`, and verifies with +`verify(crypto::verification_policies::canonical, signature, public_key)`, the +policy first and then the signature, 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. @@ -130,7 +131,7 @@ its sources, and RFC 8032's Ed25519ph vectors check the result on every target. | A message in pieces | `prehashed_signer::begin()`, `update(piece)`, then -`sign(key_pair)` or `verify(signature, public_key)` +`sign(key_pair)` or `verify(crypto::verification_policies::canonical, signature, public_key)` | none |=== diff --git a/doc/generated/messages.adoc b/doc/generated/messages.adoc index 3d3af892..87369369 100644 --- a/doc/generated/messages.adoc +++ b/doc/generated/messages.adoc @@ -215,6 +215,12 @@ The fix: As `+async_verify_wrong_key+`: naming the backend does not add a scheme 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_secp256k1_without_policy+` +|native, wasip2, wasip3 +|`+webcpp::crypto: async_verify takes crypto::signing_schemes::eddsa or crypto::signing_schemes::eddsa_prehashed with a curves::ed25519::public_key or crypto::signing_schemes::ecdsa_sha256 with a curves::p256::basic_public_key, the algorithms WebCrypto has: call crypto::verify for the others.+` + +The fix: As `+async_verify_wrong_key+`: call `+crypto::verify(crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::low_s_only, signature, input, public_key)+` for a secp256k1 key, which the asynchronous family lacks. + |`+async_verify_without_policy+` |native, wasip2, wasip3 |`+webcpp::crypto: verify takes a verification policy after the scheme: crypto::signing_schemes::ecdsa_sha256 on a P-256 key takes crypto::verification_policies::low_s_only or any_s.+` @@ -513,6 +519,12 @@ The fix: Name Ed25519ph's streaming signer `+curves::ed25519::prehashed_signer+`, a `+std::span+` or a `+boost::hash2::digest<32>+`. +|`+prehashed_signer_verify_without_policy+` +|native, wasip2, wasip3 +|`+webcpp::crypto: curves::ed25519::prehashed_signer::verify takes a verification policy first: crypto::verification_policies::canonical.+` + +The fix: Name the policy first: `+signer.verify(crypto::verification_policies::canonical, signature, public_key)+`, Ed25519ph's only policy. + |`+prevouts_summary_removed+` |native, wasip2 |`+no member named 'prevouts_summary' in namespace 'webcpp::crypto::curves::secp256k1::silent_payments'+` @@ -539,6 +551,18 @@ The fix: Recover under `+crypto::verification_policies::low_s_only+`, its only p The fix: Give `+recover+` a `+curves::secp256k1::recoverable_signature+`, which `+sign(crypto::signing_schemes::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. +|`+recover_ecdsa_without_policy+` +|native, wasip2, wasip3 +|`+webcpp::crypto: curves::secp256k1::recover takes crypto::signing_schemes::ecdsa_sha256_recoverable or crypto::signing_schemes::ecdsa_keccak256_recoverable, then crypto::verification_policies::low_s_only; another scheme's signature verifies with crypto::verify.+` + +The fix: Give `+recover+` a recoverable scheme and its policy, `+recover(crypto::signing_schemes::ecdsa_sha256_recoverable, crypto::verification_policies::low_s_only, signature, input)+` of a `+curves::secp256k1::recoverable_signature+`; an ECDSA signature without its recovery id verifies with `+crypto::verify+` and the signer's public key. + +|`+recover_without_policy+` +|native, wasip2, wasip3 +|`+webcpp::crypto: recover takes a verification policy after the scheme: curves::secp256k1::recover takes crypto::verification_policies::low_s_only.+` + +The fix: Name the policy after the scheme: `+curves::secp256k1::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, crypto::verification_policies::low_s_only, signature, input)+`, its only policy. + |`+scheme_in_crypto_namespace+` |native, wasip2, wasip3 |`+no member named 'ecdsa_sha256' in namespace 'webcpp::crypto'+` @@ -1630,6 +1654,10 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |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_verify_secp256k1_without_policy+` +|the compile +|As `+async_verify_wrong_key+`: call `+crypto::verify(crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::low_s_only, signature, input, public_key)+` for a secp256k1 key, which the asynchronous family lacks. + |`+async_verify_without_policy+` |the compile |As `+verify_without_policy+`: `+async_verify(executor, crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::low_s_only, signature, input, public_key, token)+` for a signature crypto made, `+any_s+` for one a browser's WebCrypto or a passkey made, whose S may be high. @@ -1794,10 +1822,22 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |Add `+/webcpp/crypto//pem-default+`, which links `+/third_party//sodium+` on every target. +|`+prehashed_signer_verify_without_policy+` +|the compile +|Name the policy first: `+signer.verify(crypto::verification_policies::canonical, signature, public_key)+`, Ed25519ph's only policy. + |`+recover_any_s+` |the compile |Recover under `+crypto::verification_policies::low_s_only+`, its only policy: a signature whose S is high is refused before recovery; made low first, n - s with bit 0 of the recovery id flipped, it keeps its signer. +|`+recover_ecdsa_without_policy+` +|the compile +|Give `+recover+` a recoverable scheme and its policy, `+recover(crypto::signing_schemes::ecdsa_sha256_recoverable, crypto::verification_policies::low_s_only, signature, input)+` of a `+curves::secp256k1::recoverable_signature+`; an ECDSA signature without its recovery id verifies with `+crypto::verify+` and the signer's public key. + +|`+recover_without_policy+` +|the compile +|Name the policy after the scheme: `+curves::secp256k1::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, crypto::verification_policies::low_s_only, signature, input)+`, its only policy. + |`+secp256k1_not_linked+` |the compile |Add `+/third_party//secp256k1+`. diff --git a/doc/llms.txt b/doc/llms.txt index 49bf8a00..24cf2cfd 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -143,11 +143,11 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - 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::signing_schemes::eddsa, crypto::verification_policies::canonical, signature, message, public_key)`, or an Ed25519ph one, `crypto::verify(crypto::signing_schemes::eddsa_prehashed, crypto::verification_policies::canonical, signature, crypto::signing_schemes::prehashed{digest}, public_key)`, under the policy `canonical`, the only one Ed25519 takes: 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 D9), `crypto::verification_policies::canonical`: libsodium's rules. -- [curves::ed25519::prehashed_signer](https://webcpporg.github.io/libs/crypto/#crypto-ed25519): Ed25519ph (RFC 8032), the streaming form of the scheme `crypto::signing_schemes::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::signing_schemes::eddsa_prehashed, crypto::signing_schemes::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. +- [curves::ed25519::prehashed_signer](https://webcpporg.github.io/libs/crypto/#crypto-ed25519): Ed25519ph (RFC 8032), the streaming form of the scheme `crypto::signing_schemes::eddsa_prehashed`: a message given in pieces, hashed with SHA-512, then signed with a key pair or verified with `verify(crypto::verification_policies::canonical, signature, public_key)`, the signature `sign(crypto::signing_schemes::eddsa_prehashed, crypto::signing_schemes::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, under libsodium's rules, as `crypto::verification_policies::canonical` verifies (design D9). + - verify: Verifies a signature of the message given, which it ends, under a verification policy, `crypto::verification_policies::canonical`, libsodium's rules, the only one Ed25519ph takes (design D9). - [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 `secure::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. @@ -405,7 +405,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - 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::signing_schemes::eddsa, message)` and `crypto::verify(crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, 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::signing_schemes::eddsa_prehashed`, which gives the same signature, and verifies it with `crypto::verify(crypto::signing_schemes::eddsa_prehashed, crypto::verification_policies::canonical, signature, crypto::signing_schemes::prehashed{digest}, public_key)`. Prints each key and signature in hex, and whether the two Ed25519ph signatures are equal. +- 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::signing_schemes::eddsa, message)` and `crypto::verify(crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, 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(crypto::verification_policies::canonical, signature, public_key)`; then signs the message's SHA-512, a digest the program has, under the scheme `crypto::signing_schemes::eddsa_prehashed`, which gives the same signature, and verifies it with `crypto::verify(crypto::signing_schemes::eddsa_prehashed, crypto::verification_policies::canonical, signature, crypto::signing_schemes::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/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::signing_schemes::prehashed with crypto::signing_schemes::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. diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index cad08d2d..d253015c 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -456,7 +456,7 @@ "namespace": "curves", "api": "curves::ed25519::prehashed_signer", "header": "", - "what": "Ed25519ph (RFC 8032), the streaming form of the scheme `crypto::signing_schemes::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::signing_schemes::eddsa_prehashed, crypto::signing_schemes::prehashed{digest})` gives of its SHA-512.", + "what": "Ed25519ph (RFC 8032), the streaming form of the scheme `crypto::signing_schemes::eddsa_prehashed`: a message given in pieces, hashed with SHA-512, then signed with a key pair or verified with `verify(crypto::verification_policies::canonical, signature, public_key)`, the signature `sign(crypto::signing_schemes::eddsa_prehashed, crypto::signing_schemes::prehashed{digest})` gives of its SHA-512.", "section": "crypto-ed25519", "backends": {"sodium": {"tests": ["ed25519ph_sodium"]}} }, @@ -1522,6 +1522,10 @@ "verify_p256_canonical": "Verify P-256's ECDSA under `crypto::verification_policies::low_s_only`, for a signature crypto made, or `any_s`, for one a browser's WebCrypto or a passkey made, whose S may be high; `canonical` is Ed25519's and BIP340's.", "verify_eddsa_low_s_only": "Verify Ed25519 and Ed25519ph under `crypto::verification_policies::canonical`, libsodium's rules, their only policy; `low_s_only` and `any_s` are ECDSA's.", "verify_schnorr_any_s": "Verify BIP340 under `crypto::verification_policies::canonical`, its only policy; `low_s_only` and `any_s` are ECDSA's.", + "recover_without_policy": "Name the policy after the scheme: `curves::secp256k1::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, crypto::verification_policies::low_s_only, signature, input)`, its only policy.", + "recover_ecdsa_without_policy": "Give `recover` a recoverable scheme and its policy, `recover(crypto::signing_schemes::ecdsa_sha256_recoverable, crypto::verification_policies::low_s_only, signature, input)` of a `curves::secp256k1::recoverable_signature`; an ECDSA signature without its recovery id verifies with `crypto::verify` and the signer's public key.", + "async_verify_secp256k1_without_policy": "As `async_verify_wrong_key`: call `crypto::verify(crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::low_s_only, signature, input, public_key)` for a secp256k1 key, which the asynchronous family lacks.", + "prehashed_signer_verify_without_policy": "Name the policy first: `signer.verify(crypto::verification_policies::canonical, signature, public_key)`, Ed25519ph's only policy.", "recover_any_s": "Recover under `crypto::verification_policies::low_s_only`, its only policy: a signature whose S is high is refused before recovery; made low first, n - s with bit 0 of the recovery id flipped, it keeps its signer.", "equal_header_removed": "Include ``, the header of `secure::constant_time_equal`; `equal.hpp` is gone, with no header left at its path.", "equal_removed": "Call `webcpp::secure::constant_time_equal`, the same comparison of two byte sequences in constant time; `crypto::equal` is gone, with no alias.", diff --git a/example/ed25519_sign.cpp b/example/ed25519_sign.cpp index f8faf280..7178f4eb 100644 --- a/example/ed25519_sign.cpp +++ b/example/ed25519_sign.cpp @@ -9,9 +9,9 @@ // `crypto::verify(crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, // 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::signing_schemes::eddsa_prehashed`, which gives -// the same signature, and verifies it with +// does, and verifies it with `verify(crypto::verification_policies::canonical, signature, +// public_key)`; then signs the message's SHA-512, a digest the program has, under the scheme +// `crypto::signing_schemes::eddsa_prehashed`, which gives the same signature, and verifies it with // `crypto::verify(crypto::signing_schemes::eddsa_prehashed, // crypto::verification_policies::canonical, signature, crypto::signing_schemes::prehashed{digest}, // public_key)`. Prints each key and signature in hex, and whether the two Ed25519ph signatures are @@ -100,7 +100,7 @@ bool sign_in_pieces() { print("signature ", signature->bytes()); auto verifying = signer::begin(); if (!verifying || !verifying->update(first) || !verifying->update(second) || - !verifying->verify(*signature, *public_key)) { + !verifying->verify(crypto::verification_policies::canonical, *signature, *public_key)) { return false; } diff --git a/include/webcpp/crypto/async.hpp b/include/webcpp/crypto/async.hpp index 71771b16..0819a8ea 100644 --- a/include/webcpp/crypto/async.hpp +++ b/include/webcpp/crypto/async.hpp @@ -167,11 +167,11 @@ namespace detail { * - `verify(executor, scheme, policy, signature, input, public_key, token)`: for Ed25519, the * policy `verification_policies::canonical_t`, its signature `curves::ed25519::signature`, its * message span and its key `curves::ed25519::public_key`, by value; for P-256, the policy - * `verification_policies::low_s_only_t` or `any_s_t`, which the engine applies to the public - * signature before the browser is called (a high S under `low_s_only` is `invalid_signature`), - * 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; + * `verification_policies::low_s_only_t` or `any_s_t`, which crypto has applied to the public + * signature before the engine is named (`p256_engine_verify_initiation`: a high S under + * `low_s_only` completes with `invalid_signature`, the engine never called), 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 @@ -265,6 +265,47 @@ auto complete_by_post(Executor const& completion_executor, CompletionToken& comp post_initiation{}, completion_token, completion_executor, std::move(bound_call)); } +/** + * The initiation of P-256's `async_verify` on a backend that completes by itself: the verification + * policy is applied to the public signature first, as the synchronous `verify` applies it before + * any backend call (design D9), so that a signature it refuses, a high S under `low_s_only` or an r + * or an s out of range, completes with `invalid_signature` through a post to the executor and the + * engine is never called; any other is given to the engine's `verify` with the concrete handler. + * Both arms take the same handler, so the completion token's `async_result` is the one of + * `void(boost::system::error_code)` whatever the arm. + * + * @tparam Backend The backend that completes by itself. + */ +template +struct p256_engine_verify_initiation { + /** + * Applies the policy, then posts the refusal or calls the engine. + * + * @param completion_handler The completion handler. + * @param completion_executor The executor the completion is posted to. + * @param verification_policy `verification_policies::low_s_only` or `any_s`. + * @param signature_value The signature, copied into the operation. + * @param signing_input The message's view, kept by value. + * @param public_key The caller's key, which is the caller's until the completion. + */ + template + void operator()(Handler&& completion_handler, Executor const& completion_executor, + Policy verification_policy, Signature const& signature_value, + Input signing_input, PublicKey const* public_key) const { + if (!p256_policy_admits(signature_value.bytes())) { + boost::system::error_code const refused = error::invalid_signature; + webcpp::asio::post( + completion_executor, + webcpp::asio::append(std::forward(completion_handler), refused)); + return; + } + async_engine::verify(completion_executor, signing_schemes::ecdsa_sha256, + verification_policy, signature_value, signing_input, + *public_key, std::forward(completion_handler)); + } +}; + /** Whether `Type` is an AES-GCM, `ciphers::gcm`. */ template inline constexpr bool is_gcm_v = false; @@ -342,6 +383,23 @@ inline constexpr bool has_async_verifier_v = std::is_same_v) || (std::is_same_v && is_p256_public_key_v); +/** + * Stops the build: no `async_verify` checks a signature of `Scheme` against this public key; the + * message names the keys and schemes the asynchronous family has. Both catch-alls of + * `async_verify`, with a policy and of the arity before the policies, give it. + * + * @tparam Scheme The scheme tag given, which makes the refusal dependent. + */ +template +constexpr void refuse_async_verify_key() noexcept { + static_assert( + refused_v, + "webcpp::crypto: async_verify takes crypto::signing_schemes::eddsa or " + "crypto::signing_schemes::eddsa_prehashed with a curves::ed25519::public_key or " + "crypto::signing_schemes::ecdsa_sha256 with a curves::p256::basic_public_key, the " + "algorithms WebCrypto has: call crypto::verify for the others."); +} + /** * Stops the build with the one reason the key pair `Keypair` does not sign `Input` with `Scheme`: * the scheme is not the key pair's, or the input is not one of the scheme's on the key pair's @@ -1198,12 +1256,7 @@ void async_verify([[maybe_unused]] Executor const& completion_executor, [[maybe_unused]] Input const& signing_input, [[maybe_unused]] PublicKey const& public_key, [[maybe_unused]] CompletionToken&& completion_token) { - static_assert( - detail::refused_v, - "webcpp::crypto: async_verify takes crypto::signing_schemes::eddsa or " - "crypto::signing_schemes::eddsa_prehashed with a curves::ed25519::public_key or " - "crypto::signing_schemes::ecdsa_sha256 with a curves::p256::basic_public_key, the " - "algorithms WebCrypto has: call crypto::verify for the others."); + detail::refuse_async_verify_key(); } /** @@ -1211,7 +1264,9 @@ void async_verify([[maybe_unused]] Executor const& completion_executor, * `async_verify(executor, scheme, signature, input, public_key, token)`, with no policy after the * scheme. * - * The message names the policies the scheme takes on the key (design D9). + * The message names the policies the scheme takes on the key (design D9); for a key that has no + * asynchronous form, it names first the keys `async_verify` takes, as the catch-all of the arity + * with a policy does, so that adding a policy does not meet a second refusal. * * @tparam Backend Ignored: the first template parameter, as on every `async_verify`. * @tparam Executor The executor's type. @@ -1236,7 +1291,11 @@ void async_verify([[maybe_unused]] Executor const& completion_executor, [[maybe_unused]] Input const& signing_input, [[maybe_unused]] PublicKey const& public_key, [[maybe_unused]] CompletionToken&& completion_token) { - detail::refuse_missing_policy>(); + if constexpr (detail::has_async_verifier_v>) { + detail::refuse_missing_policy>(); + } else { + detail::refuse_async_verify_key(); + } } /** @@ -1657,10 +1716,10 @@ auto curves::p256::basic_public_key::async_verify( } else if constexpr (!detail::input_valid_v) { detail::check_input(); } else if constexpr (detail::asynchronous_backend_v) { - return detail::async_engine::verify( - completion_executor, signing_schemes::ecdsa_sha256, verification_policy, - signature_value, detail::kept_input(signing_input), *this, - std::forward(completion_token)); + return webcpp::asio_backend::async_initiate( + detail::p256_engine_verify_initiation{}, completion_token, completion_executor, + verification_policy, signature_value, detail::kept_input(signing_input), this); } else { return detail::complete_by_post( completion_executor, completion_token, diff --git a/include/webcpp/crypto/curves/ed25519.hpp b/include/webcpp/crypto/curves/ed25519.hpp index fdb43006..061ba76a 100644 --- a/include/webcpp/crypto/curves/ed25519.hpp +++ b/include/webcpp/crypto/curves/ed25519.hpp @@ -947,22 +947,30 @@ class prehashed_signer { } /** - * Verifies a signature of the message given, which it ends, under libsodium's rules, as - * `crypto::verification_policies::canonical` verifies (design D9). + * Verifies a signature of the message given, which it ends, under a verification policy, + * `crypto::verification_policies::canonical`, libsodium's rules, the only one Ed25519ph takes + * (design D9). * + * @tparam Policy `crypto::verification_policies::canonical_t`; anything else stops the build. * @tparam Signature `curves::ed25519::signature`; another type, bytes included, stops the * build. + * @param verification_policy `crypto::verification_policies::canonical`. * @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 that does not verify. */ - template + template [[nodiscard]] boost::system::result verify( - Signature const& signature_value, + [[maybe_unused]] Policy verification_policy, Signature const& signature_value, ::webcpp::crypto::curves::ed25519::public_key const& verifying_key) noexcept { secure::timing_guard const timing_scope; + if constexpr (!detail::check_policy()) { + // Never compiled into a program: check_policy stopped the build. + return error::invalid_signature; + } auto const& signature_bytes = detail::checked_signature_bytes<::webcpp::crypto::curves::ed25519::signature, detail::ed25519ph_verifier_t>(signature_value); @@ -975,6 +983,28 @@ class prehashed_signer { return verify_result; } + /** + * Stops the build: a `verify` of the arity before the verification policies, + * `signer.verify(signature, public_key)`, with no policy first; the message names + * `crypto::verification_policies::canonical`. + * + * @tparam Signature The signature's type, which is no policy. + * @param signature_value The signature. + * @param verifying_key The signer's public key. + * @return Never: the call does not compile. + */ + template + requires(!detail::is_policy_v) + [[nodiscard]] boost::system::result verify( + [[maybe_unused]] Signature const& signature_value, + [[maybe_unused]] ::webcpp::crypto::curves::ed25519::public_key const& + verifying_key) noexcept { + static_assert(detail::refused_v, + "webcpp::crypto: curves::ed25519::prehashed_signer::verify takes a " + "verification policy first: crypto::verification_policies::canonical."); + return error::invalid_signature; + } + private: prehashed_signer() noexcept = default; diff --git a/include/webcpp/crypto/curves/p256.hpp b/include/webcpp/crypto/curves/p256.hpp index b4b24098..f2b4772a 100644 --- a/include/webcpp/crypto/curves/p256.hpp +++ b/include/webcpp/crypto/curves/p256.hpp @@ -315,8 +315,9 @@ class basic_public_key { * arguments and this key, which calls it. * * The key and the bytes the input views are the caller's until the completion; the signature - * is copied. On a backend that completes by itself, the engine gets the policy, and refuses a - * high S under `low_s_only` before the browser is called. + * is copied. On a backend that completes by itself, crypto applies the policy before the engine + * is called, as `verify` does: a high S under `low_s_only` completes with `invalid_signature` + * and the engine is never called. * * 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 diff --git a/include/webcpp/crypto/curves/secp256k1.hpp b/include/webcpp/crypto/curves/secp256k1.hpp index 60b42dbc..96ae150b 100644 --- a/include/webcpp/crypto/curves/secp256k1.hpp +++ b/include/webcpp/crypto/curves/secp256k1.hpp @@ -1699,7 +1699,8 @@ template , class Policy, /** * Stops the build: a `recover` of the arity before the verification policies, * `recover(scheme, signature, input)`, with no policy after the scheme; the message names the - * policy `recover` takes, `crypto::verification_policies::low_s_only`. + * policy `recover` takes, `crypto::verification_policies::low_s_only`, and for a scheme that is not + * recoverable the two schemes `recover` takes. * * @tparam Backend The backend. * @tparam Scheme A scheme tag. @@ -1716,7 +1717,16 @@ template , class Scheme, [[nodiscard]] boost::system::result recover( [[maybe_unused]] Scheme signing_scheme, [[maybe_unused]] Signature const& signature_value, [[maybe_unused]] Input const& signing_input) noexcept { - detail::refuse_missing_policy(); + if constexpr (detail::is_recoverable_scheme_v) { + detail::refuse_missing_policy(); + } else { + static_assert(detail::refused_v, + "webcpp::crypto: curves::secp256k1::recover takes " + "crypto::signing_schemes::ecdsa_sha256_recoverable or " + "crypto::signing_schemes::ecdsa_keccak256_recoverable, then " + "crypto::verification_policies::low_s_only; another scheme's signature " + "verifies with crypto::verify."); + } return error::invalid_signature; } diff --git a/include/webcpp/crypto/signing.hpp b/include/webcpp/crypto/signing.hpp index fabe7a77..bf42ba29 100644 --- a/include/webcpp/crypto/signing.hpp +++ b/include/webcpp/crypto/signing.hpp @@ -886,22 +886,63 @@ inline constexpr bool is_recoverable_scheme_v = std::is_same_v; /** - * Whether `ecdsa_sha256` on the key `Key` accepts exactly the policies `List`: how a refusal - * tells P-256's key from secp256k1's without naming either curve. + * The row of design D9's table a scheme and a key fall in, which names the policies a refusal + * gives: `check_policy` and `refuse_missing_policy` both read it, so that a curve or a scheme that + * adds a row adds it here once. + */ +enum class policy_row { + /** `eddsa` on its key. */ + eddsa, + /** `eddsa_prehashed` on its key. */ + eddsa_prehashed, + /** `schnorr` on either of its keys. */ + schnorr, + /** A recoverable scheme, in `curves::secp256k1::recover`. */ + recover, + /** `ecdsa_sha256` on a key that accepts `low_s_only` and `any_s`, P-256's. */ + ecdsa_p256, + /** `ecdsa_sha256` on a key that accepts `low_s_only` alone, secp256k1's. */ + ecdsa_secp256k1, + /** No row: a key no curve declares policies for. */ + none, +}; + +/** + * The row of `Scheme` on `Key`: by the scheme, and for `ecdsa_sha256` by the policies the key's + * curve declares, so that this header names no curve. * - * @tparam Key The public key's type. - * @tparam List A `policy_list`. + * @tparam Scheme A scheme tag. + * @tparam Key The public key's type, or `void` for `curves::secp256k1::recover`. + * @return Its row. */ -template -inline constexpr bool ecdsa_accepts_v = - std::is_same_v::type, List>; +template +[[nodiscard]] consteval policy_row policy_row_of() noexcept { + using accepted = typename accepted_policies::type; + if constexpr (std::is_same_v) { + return policy_row::eddsa; + } else if constexpr (std::is_same_v) { + return policy_row::eddsa_prehashed; + } else if constexpr (std::is_same_v) { + return policy_row::schnorr; + } else if constexpr (is_recoverable_scheme_v) { + return policy_row::recover; + } else if constexpr (std::is_same_v>) { + return policy_row::ecdsa_p256; + } else if constexpr (std::is_same_v>) { + return policy_row::ecdsa_secp256k1; + } else { + return policy_row::none; + } +} /** * Whether `Policy` is a policy `Scheme` accepts on `Key`, and, when it is not, stops the build with - * the message that names the policies the scheme accepts, one fixed text per row of design D9: - * every `verify`, `async_verify` and `recover`, member and free, asks it after its scheme and - * before the signature, and goes on only when it is true. The failed requirement of the static - * assertion, `policy_accepted_v`, names the three types. + * the message that names the policies the scheme accepts, one fixed text per row of design D9 + * (`policy_row_of`): every `verify`, `async_verify` and `recover`, member and free, asks it after + * its scheme and before the signature, and goes on only when it is true. The failed requirement of + * the static assertion, `policy_accepted_v`, names the three types. * * @tparam Policy The policy's type, without its reference and qualifiers, or any type. * @tparam Scheme The scheme tag the call verifies or recovers under. @@ -910,26 +951,25 @@ inline constexpr bool ecdsa_accepts_v = */ template [[nodiscard]] constexpr bool check_policy() noexcept { - if constexpr (std::is_same_v || - std::is_same_v) { + constexpr policy_row row = policy_row_of(); + if constexpr (row == policy_row::eddsa || row == policy_row::eddsa_prehashed) { static_assert(policy_accepted_v, "webcpp::crypto: verify: crypto::signing_schemes::eddsa and eddsa_prehashed " "take crypto::verification_policies::canonical."); - } else if constexpr (std::is_same_v) { + } else if constexpr (row == policy_row::schnorr) { static_assert(policy_accepted_v, "webcpp::crypto: verify: crypto::signing_schemes::schnorr takes " "crypto::verification_policies::canonical."); - } else if constexpr (is_recoverable_scheme_v) { + } else if constexpr (row == policy_row::recover) { static_assert(policy_accepted_v, "webcpp::crypto: curves::secp256k1::recover takes " "crypto::verification_policies::low_s_only."); - } else if constexpr (ecdsa_accepts_v>) { + } else if constexpr (row == policy_row::ecdsa_p256) { static_assert( policy_accepted_v, "webcpp::crypto: verify: crypto::signing_schemes::ecdsa_sha256 on a P-256 key " "takes crypto::verification_policies::low_s_only or any_s."); - } else if constexpr (ecdsa_accepts_v>) { + } else if constexpr (row == policy_row::ecdsa_secp256k1) { static_assert( policy_accepted_v, "webcpp::crypto: verify: crypto::signing_schemes::ecdsa_sha256 on a secp256k1 " @@ -944,42 +984,42 @@ template /** * Stops the build: a `verify`, an `async_verify` or a `recover` of the arity before the policies, - * with no policy after the scheme. The message names the policies of the scheme, and of the key's - * curve for `ecdsa_sha256` (design D9; one fixed text per case), or all three for a key no curve - * declares a verifier for. + * with no policy after the scheme. The message names the policies of the scheme's row + * (`policy_row_of`; design D9, one fixed text per case), or all three for a key no curve declares + * a verifier for. * * @tparam Scheme The scheme tag given. * @tparam Key The public key's type, or `void` for `curves::secp256k1::recover`. */ template constexpr void refuse_missing_policy() noexcept { - if constexpr (std::is_same_v) { + constexpr policy_row row = policy_row_of(); + if constexpr (row == policy_row::eddsa) { static_assert(refused_v, "webcpp::crypto: verify takes a verification policy after the scheme: " "crypto::signing_schemes::eddsa takes " "crypto::verification_policies::canonical."); - } else if constexpr (std::is_same_v) { + } else if constexpr (row == policy_row::eddsa_prehashed) { static_assert(refused_v, "webcpp::crypto: verify takes a verification policy after the scheme: " "crypto::signing_schemes::eddsa_prehashed takes " "crypto::verification_policies::canonical."); - } else if constexpr (std::is_same_v) { + } else if constexpr (row == policy_row::schnorr) { static_assert(refused_v, "webcpp::crypto: verify takes a verification policy after the scheme: " "crypto::signing_schemes::schnorr takes " "crypto::verification_policies::canonical."); - } else if constexpr (is_recoverable_scheme_v) { + } else if constexpr (row == policy_row::recover) { static_assert(refused_v, "webcpp::crypto: recover takes a verification policy after the scheme: " "curves::secp256k1::recover takes " "crypto::verification_policies::low_s_only."); - } else if constexpr (ecdsa_accepts_v>) { + } else if constexpr (row == policy_row::ecdsa_p256) { static_assert(refused_v, "webcpp::crypto: verify takes a verification policy after the scheme: " "crypto::signing_schemes::ecdsa_sha256 on a P-256 key takes " "crypto::verification_policies::low_s_only or any_s."); - } else if constexpr (ecdsa_accepts_v>) { + } else if constexpr (row == policy_row::ecdsa_secp256k1) { static_assert(refused_v, "webcpp::crypto: verify takes a verification policy after the scheme: " "crypto::signing_schemes::ecdsa_sha256 on a secp256k1 key takes " diff --git a/test/Jamfile b/test/Jamfile index 59781db2..cd359fde 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -191,6 +191,13 @@ crypto-run async_p256 : async_p256_test.cpp # pair and peer, and complete through the executor. crypto-run async_agree_engine : async_agree_engine_test.cpp : /webcpp/asio//asio : native ; +# P-256's async_verify on a stand-in backend that completes by itself, +# natively: the verification policy is applied before the stand-in's engine is +# named, so the RFC's high S under low_s_only completes with invalid_signature +# and no engine call, and under any_s reaches the engine once; the free form +# and the member alike. +crypto-run async_verify_engine : async_verify_engine_test.cpp + : /webcpp/asio//asio : native ; # Without threads (WEBCPP_CRYPTO_NO_THREADS natively; WASI has none), a heavy # operation's async_ variant that forgets its refusal stops at # detail::run_on_work's stand-in, which names the refusal, and with that diff --git a/test/allocation_sodium_test.cpp b/test/allocation_sodium_test.cpp index a16ff882..f81e4489 100644 --- a/test/allocation_sodium_test.cpp +++ b/test/allocation_sodium_test.cpp @@ -134,7 +134,10 @@ void expect_no_allocation_ed25519() { auto verifier = prehashed_signer::begin(); BOOST_TEST(verifier.has_value()); BOOST_TEST(verifier->update(message).has_value()); - BOOST_TEST(verifier->verify(*streamed_signature, *public_key).has_value()); + BOOST_TEST( + verifier + ->verify(crypto::verification_policies::canonical, *streamed_signature, *public_key) + .has_value()); // The same signature under the scheme eddsa_prehashed, from the message's SHA-512. webcpp::hash::sha2_512 hasher; hasher.update(message.data(), message.size()); diff --git a/test/async_verify_engine_test.cpp b/test/async_verify_engine_test.cpp new file mode 100644 index 00000000..18a555f6 --- /dev/null +++ b/test/async_verify_engine_test.cpp @@ -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) + +// P-256's async_verify on a backend that completes by itself, natively: a stand-in whose +// detail::asynchronous_backend_v is true and whose detail::async_engine answers verify, as the +// browser's backend will, with success, counting its calls. crypto applies the verification policy +// before it names the engine (design D9): RFC 6979 section A.2.5's "sample" signature, whose S is +// high, completes with invalid_signature under low_s_only with the engine never called, and reaches +// the engine once under any_s, which completes without error; its low-S form reaches the engine +// under low_s_only; a signature whose r is 0 is refused under both without the engine. The free +// form and the member alike, each completion after the initiating call returned. + +#include +#include +#include +#include +#include +#include + +#include + +#include "support/p256_data.hpp" + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace crypto = webcpp::crypto; +namespace asio = webcpp::asio; + +namespace { + +// A backend that completes by itself, as the browser's does. +struct stand_in_browser {}; + +// The stand-in engine's calls of verify, which the test resets before each operation. +int& engine_verifications() { + static int calls = 0; + return calls; +} + +} // namespace + +namespace webcpp::crypto::detail { + +template <> +inline constexpr bool asynchronous_backend_v = true; + +// P-256's types name their engine: the stand-in's has nothing to reset and is never asked a point. +template <> +struct p_curve_engine { + using state = p_curve_state; + + static void reset(state& /*engine_state*/) noexcept {} +}; + +// The stand-in's engine: verify counts its call and completes, through a post, without error, as +// a browser that found the signature valid. +template <> +struct async_engine { + template + static auto verify(Executor const& completion_executor, Scheme /*signing_scheme*/, + Policy /*verification_policy*/, Signature const& /*signature_value*/, + Input const& /*signing_input*/, PublicKey const& /*public_key*/, + CompletionToken&& completion_token) { + ++engine_verifications(); + return complete_by_post(completion_executor, completion_token, + []() noexcept -> boost::system::result { return {}; }); + } +}; + +} // namespace webcpp::crypto::detail + +namespace { + +using public_key = crypto::curves::p256::basic_public_key; +using signature_type = crypto::curves::p256::ecdsa_signature; + +// Runs `start(executor, handler)`, then the context: one completion, after the initiating call +// returned; its error code, and the engine's calls in `calls`. +template +boost::system::error_code completed(asio::io_context& context, int& calls, Start start) { + engine_verifications() = 0; + int completions = 0; + bool returned = false; + bool after_return = false; + boost::system::error_code completion_code; + start(context.get_executor(), [&](boost::system::error_code code) { + ++completions; + after_return = returned; + completion_code = code; + }); + returned = true; + BOOST_TEST_EQ(completions, 0); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(completions, 1); + BOOST_TEST(after_return); + calls = engine_verifications(); + return completion_code; +} + +// The free form and the member of async_verify under `policy`: each its error code, and the +// engine's calls, `expected_calls` in each. +template +void both_forms(asio::io_context& context, public_key const& key, signature_type const& signature, + Policy policy, boost::system::error_code expected_code, int expected_calls) { + std::array const message{'s', 'a', 'm', 'p', 'l', 'e'}; + auto const message_bytes = std::span(message); + int calls = -1; + BOOST_TEST(completed(context, calls, [&](auto const& executor, auto handler) { + crypto::async_verify(executor, crypto::signing_schemes::ecdsa_sha256, policy, + signature, message_bytes, key, std::move(handler)); + }) == expected_code); + BOOST_TEST_EQ(calls, expected_calls); + calls = -1; + BOOST_TEST(completed(context, calls, [&](auto const& executor, auto handler) { + key.async_verify(executor, crypto::signing_schemes::ecdsa_sha256, policy, + signature, message_bytes, std::move(handler)); + }) == expected_code); + BOOST_TEST_EQ(calls, expected_calls); +} + +} // namespace + +int main() { + asio::io_context context; + auto const key = crypto::detail::p_curve_access::blank(); + auto const high = signature_type::from_bytes(webcpp::test::p256::rfc6979_sample); + auto const low = signature_type::from_bytes(webcpp::test::p256::rfc6979_sample_low_s); + std::array zero_r = webcpp::test::p256::rfc6979_sample_low_s; + std::fill_n(zero_r.begin(), 32, std::uint8_t{0}); + auto const out_of_range = signature_type::from_bytes(zero_r); + if (!BOOST_TEST(high.has_value()) || !BOOST_TEST(low.has_value()) || + !BOOST_TEST(out_of_range.has_value())) { + return webcpp::test::exit_status(boost::report_errors()); + } + boost::system::error_code const refused = crypto::error::invalid_signature; + both_forms(context, key, *high, crypto::verification_policies::low_s_only, refused, 0); + both_forms(context, key, *high, crypto::verification_policies::any_s, {}, 1); + both_forms(context, key, *low, crypto::verification_policies::low_s_only, {}, 1); + both_forms(context, key, *out_of_range, crypto::verification_policies::any_s, refused, 0); + both_forms(context, key, *out_of_range, crypto::verification_policies::low_s_only, refused, 0); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/ed25519ph_sodium_test.cpp b/test/ed25519ph_sodium_test.cpp index 03bfd086..fdf62947 100644 --- a/test/ed25519ph_sodium_test.cpp +++ b/test/ed25519ph_sodium_test.cpp @@ -8,7 +8,8 @@ // signer curves::ed25519::prehashed_signer: // - rfc8032_ph: RFC 8032 section 7.3's test, the message "abc" given to the signer in one piece and // in two, signed into the RFC's signature, a curves::ed25519::signature, and verified with -// verify(signature, public_key), the signature first, of that type, and the key a +// verify(canonical, signature, public_key), the policy first, the signature of that type, and +// the key a // curves::ed25519::public_key; the key's bytes, and 63 bytes, refused as a signature by // from_bytes; a signature changed in one bit and a different message refused. // - rfc8032_ph_scheme: the same key pair signs crypto::signing_schemes::prehashed{sha512("abc")} @@ -128,18 +129,22 @@ void rfc8032_ph() { auto const signature = signing.sign(*key); BOOST_TEST(signature && *signature == expected); auto verifying = begun(pieces); - BOOST_TEST(verifying.verify(expected, public_key).has_value()); + BOOST_TEST(verifying.verify(crypto::verification_policies::canonical, expected, public_key) + .has_value()); } // Changed in one bit, the signature is refused; so is another message. auto changed = expected_bytes; changed[40] ^= 0x01U; auto verifying = begun(two_pieces); + BOOST_TEST(verifying + .verify(crypto::verification_policies::canonical, + ed25519::signature::from_bytes(changed).value(), public_key) + .error() == crypto::error::invalid_signature); + auto other = begun({{0x61, 0x62}}); BOOST_TEST( - verifying.verify(ed25519::signature::from_bytes(changed).value(), public_key).error() == + other.verify(crypto::verification_policies::canonical, expected, public_key).error() == crypto::error::invalid_signature); - auto other = begun({{0x61, 0x62}}); - BOOST_TEST(other.verify(expected, public_key).error() == crypto::error::invalid_signature); // Ed25519ph's signature is not Ed25519's of the same message. BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, @@ -175,7 +180,8 @@ void spent_and_moved() { BOOST_TEST(signing.sign(*key).error() == crypto::error::invalid_state); auto const public_key = ed25519::public_key::from_bytes(test::from_hex(public_key_hex)); BOOST_TEST(public_key && - signing.verify(ed25519::signature::from_bytes(test::from_hex(signature_hex)).value(), + signing.verify(crypto::verification_policies::canonical, + ed25519::signature::from_bytes(test::from_hex(signature_hex)).value(), *public_key) .error() == crypto::error::invalid_state); @@ -292,7 +298,10 @@ void streaming_equals_scheme() { auto const streamed = signing.sign(key); BOOST_TEST(streamed && *streamed == *scheme_signature); auto verifying = begun(pieces); - BOOST_TEST(verifying.verify(*scheme_signature, public_key).has_value()); + BOOST_TEST( + verifying + .verify(crypto::verification_policies::canonical, *scheme_signature, public_key) + .has_value()); if (streamed) { BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa_prehashed, crypto::verification_policies::canonical, *streamed, diff --git a/test/messages/Jamfile b/test/messages/Jamfile index 18b9aa87..bddb1d0f 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -156,3 +156,7 @@ build-project verify_schnorr_any_s ; build-project verify_eddsa_low_s_only ; build-project verify_p256_canonical ; build-project recover_any_s ; +build-project prehashed_signer_verify_without_policy ; +build-project recover_without_policy ; +build-project recover_ecdsa_without_policy ; +build-project async_verify_secp256k1_without_policy ; diff --git a/test/messages/async_verify_secp256k1_without_policy/Jamfile b/test/messages/async_verify_secp256k1_without_policy/Jamfile new file mode 100644 index 00000000..ddabaaf9 --- /dev/null +++ b/test/messages/async_verify_secp256k1_without_policy/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic async_verify_secp256k1_without_policy : async_verify_secp256k1_without_policy.cpp + : /webcpp/asio//asio /third_party//sodium /third_party//secp256k1 : native wasip2 wasip3 : alone ; diff --git a/test/messages/async_verify_secp256k1_without_policy/async_verify_secp256k1_without_policy.cpp b/test/messages/async_verify_secp256k1_without_policy/async_verify_secp256k1_without_policy.cpp new file mode 100644 index 00000000..9e27d097 --- /dev/null +++ b/test/messages/async_verify_secp256k1_without_policy/async_verify_secp256k1_without_policy.cpp @@ -0,0 +1,46 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// async_verify of crypto::signing_schemes::ecdsa_sha256 against a secp256k1 public key, an +// algorithm WebCrypto lacks, in the arity before the verification policies, stops with the message +// that names the keys async_verify takes, not with the policy, which would meet that refusal next, +// and with that error alone. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/async.hpp:* {{webcpp::crypto: async_verify takes crypto::signing_schemes::eddsa or crypto::signing_schemes::eddsa_prehashed with a curves::ed25519::public_key or crypto::signing_schemes::ecdsa_sha256 with a curves::p256::basic_public_key, the algorithms WebCrypto has: call crypto::verify for the others.}} +// clang-format on + +#include +#include +#include + +#include + +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const seed{1}; + std::array const message{'h', 'e', 'l', 'l', 'o'}; + auto const made = crypto::curves::secp256k1::keypair::from_secret(seed); + if (!made) { + return 1; + } + auto const public_key = made->public_key(); + auto const signature = made->sign(crypto::signing_schemes::ecdsa_sha256, message); + if (!public_key || !signature) { + return 1; + } + webcpp::asio::io_context context; + crypto::async_verify(context.get_executor(), crypto::signing_schemes::ecdsa_sha256, *signature, + message, *public_key, [](boost::system::error_code) {}); + return 0; +} diff --git a/test/messages/prehashed_signer_verify_without_policy/Jamfile b/test/messages/prehashed_signer_verify_without_policy/Jamfile new file mode 100644 index 00000000..c468a061 --- /dev/null +++ b/test/messages/prehashed_signer_verify_without_policy/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto /webcpp/crypto//ed25519-default ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic prehashed_signer_verify_without_policy : prehashed_signer_verify_without_policy.cpp + : : native wasip2 wasip3 : alone ; diff --git a/test/messages/prehashed_signer_verify_without_policy/prehashed_signer_verify_without_policy.cpp b/test/messages/prehashed_signer_verify_without_policy/prehashed_signer_verify_without_policy.cpp new file mode 100644 index 00000000..13e318a2 --- /dev/null +++ b/test/messages/prehashed_signer_verify_without_policy/prehashed_signer_verify_without_policy.cpp @@ -0,0 +1,29 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Ed25519ph's streaming signer verified in the arity before the verification policies, +// signer.verify(signature, public_key), stops with the message that the policy comes first, +// crypto::verification_policies::canonical, and with that error alone. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/curves/ed25519.hpp:* {{webcpp::crypto: curves::ed25519::prehashed_signer::verify takes a verification policy first: crypto::verification_policies::canonical.}} +// clang-format on + +#include +#include + +#include +#include + +int main() { + namespace ed25519 = webcpp::crypto::curves::ed25519; + auto signer = ed25519::prehashed_signer::begin(); + auto const public_key = ed25519::public_key::from_bytes(std::array{}); + ed25519::signature const signature{}; + return signer && public_key && signer->verify(signature, *public_key) ? 0 : 1; +} diff --git a/test/messages/recover_ecdsa_without_policy/Jamfile b/test/messages/recover_ecdsa_without_policy/Jamfile new file mode 100644 index 00000000..0bae54f9 --- /dev/null +++ b/test/messages/recover_ecdsa_without_policy/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic recover_ecdsa_without_policy : recover_ecdsa_without_policy.cpp + : /third_party//secp256k1 : native wasip2 wasip3 : alone ; diff --git a/test/messages/recover_ecdsa_without_policy/recover_ecdsa_without_policy.cpp b/test/messages/recover_ecdsa_without_policy/recover_ecdsa_without_policy.cpp new file mode 100644 index 00000000..5d21695e --- /dev/null +++ b/test/messages/recover_ecdsa_without_policy/recover_ecdsa_without_policy.cpp @@ -0,0 +1,39 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// curves::secp256k1::recover of crypto::signing_schemes::ecdsa_sha256, a scheme that is not +// recoverable, in the arity before the verification policies, stops with the message that names +// the two schemes recover takes and its policy, and with that error alone. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/curves/secp256k1.hpp:* {{webcpp::crypto: curves::secp256k1::recover takes crypto::signing_schemes::ecdsa_sha256_recoverable or crypto::signing_schemes::ecdsa_keccak256_recoverable, then crypto::verification_policies::low_s_only; another scheme's signature verifies with crypto::verify.}} +// clang-format on + +#include +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const seed{1}; + std::array const message{'h', 'e', 'l', 'l', 'o'}; + auto const made = crypto::curves::secp256k1::keypair::from_secret(seed); + if (!made) { + return 1; + } + auto const signature = made->sign(crypto::signing_schemes::ecdsa_sha256, message); + if (!signature) { + return 1; + } + return crypto::curves::secp256k1::recover(crypto::signing_schemes::ecdsa_sha256, *signature, + message) + ? 0 + : 1; +} diff --git a/test/messages/recover_without_policy/Jamfile b/test/messages/recover_without_policy/Jamfile new file mode 100644 index 00000000..20d375af --- /dev/null +++ b/test/messages/recover_without_policy/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic recover_without_policy : recover_without_policy.cpp + : /third_party//secp256k1 : native wasip2 wasip3 : alone ; diff --git a/test/messages/recover_without_policy/recover_without_policy.cpp b/test/messages/recover_without_policy/recover_without_policy.cpp new file mode 100644 index 00000000..bdf59a69 --- /dev/null +++ b/test/messages/recover_without_policy/recover_without_policy.cpp @@ -0,0 +1,39 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// curves::secp256k1::recover in the arity before the verification policies, recover(scheme, +// signature, message), stops at the catch-all, whose message says that recover takes a policy after +// the scheme, low_s_only, and with that error alone. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/signing.hpp:* {{webcpp::crypto: recover takes a verification policy after the scheme: curves::secp256k1::recover takes crypto::verification_policies::low_s_only.}} +// clang-format on + +#include +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const seed{1}; + std::array const message{'h', 'e', 'l', 'l', 'o'}; + auto const made = crypto::curves::secp256k1::keypair::from_secret(seed); + if (!made) { + return 1; + } + auto const signature = made->sign(crypto::signing_schemes::ecdsa_sha256_recoverable, message); + if (!signature) { + return 1; + } + return crypto::curves::secp256k1::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, + *signature, message) + ? 0 + : 1; +} diff --git a/test/msvc/Jamfile b/test/msvc/Jamfile index 8b190b44..42adf1e6 100644 --- a/test/msvc/Jamfile +++ b/test/msvc/Jamfile @@ -81,3 +81,7 @@ build-project verify_schnorr_any_s ; build-project verify_eddsa_low_s_only ; build-project verify_p256_canonical ; build-project recover_any_s ; +build-project prehashed_signer_verify_without_policy ; +build-project recover_without_policy ; +build-project recover_ecdsa_without_policy ; +build-project async_verify_secp256k1_without_policy ; diff --git a/test/msvc/async_verify_secp256k1_without_policy/Jamfile b/test/msvc/async_verify_secp256k1_without_policy/Jamfile new file mode 100644 index 00000000..eec3687d --- /dev/null +++ b/test/msvc/async_verify_secp256k1_without_policy/Jamfile @@ -0,0 +1,12 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail async_verify_secp256k1_without_policy : app.cpp + : /webcpp/crypto//crypto /webcpp/asio//asio /third_party//sodium + /third_party//secp256k1 + : native ; diff --git a/test/msvc/async_verify_secp256k1_without_policy/app.cpp b/test/msvc/async_verify_secp256k1_without_policy/app.cpp new file mode 100644 index 00000000..6f4bd224 --- /dev/null +++ b/test/msvc/async_verify_secp256k1_without_policy/app.cpp @@ -0,0 +1,40 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// async_verify of crypto::signing_schemes::ecdsa_sha256 against a secp256k1 public key, an +// algorithm WebCrypto lacks, in the arity before the verification policies, stops with the message +// that names the keys async_verify takes, not with the policy, which would meet that refusal next, +// and with that error alone. On MSVC the compile fails; the text is checked on clang, in +// test/messages/async_verify_secp256k1_without_policy. +#include +#include +#include + +#include + +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const seed{1}; + std::array const message{'h', 'e', 'l', 'l', 'o'}; + auto const made = crypto::curves::secp256k1::keypair::from_secret(seed); + if (!made) { + return 1; + } + auto const public_key = made->public_key(); + auto const signature = made->sign(crypto::signing_schemes::ecdsa_sha256, message); + if (!public_key || !signature) { + return 1; + } + webcpp::asio::io_context context; + crypto::async_verify(context.get_executor(), crypto::signing_schemes::ecdsa_sha256, *signature, + message, *public_key, [](boost::system::error_code) {}); + return 0; +} diff --git a/test/msvc/prehashed_signer_verify_without_policy/Jamfile b/test/msvc/prehashed_signer_verify_without_policy/Jamfile new file mode 100644 index 00000000..bd92c5d8 --- /dev/null +++ b/test/msvc/prehashed_signer_verify_without_policy/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail prehashed_signer_verify_without_policy : app.cpp + : /webcpp/crypto//crypto /webcpp/crypto//ed25519-default + : native ; diff --git a/test/msvc/prehashed_signer_verify_without_policy/app.cpp b/test/msvc/prehashed_signer_verify_without_policy/app.cpp new file mode 100644 index 00000000..935aaaa7 --- /dev/null +++ b/test/msvc/prehashed_signer_verify_without_policy/app.cpp @@ -0,0 +1,23 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Ed25519ph's streaming signer verified in the arity before the verification policies, +// signer.verify(signature, public_key), stops with the message that the policy comes first, +// crypto::verification_policies::canonical, and with that error alone. On MSVC the compile fails; +// the text is checked on clang, in test/messages/prehashed_signer_verify_without_policy. +#include +#include + +#include +#include + +int main() { + namespace ed25519 = webcpp::crypto::curves::ed25519; + auto signer = ed25519::prehashed_signer::begin(); + auto const public_key = ed25519::public_key::from_bytes(std::array{}); + ed25519::signature const signature{}; + return signer && public_key && signer->verify(signature, *public_key) ? 0 : 1; +} diff --git a/test/msvc/recover_ecdsa_without_policy/Jamfile b/test/msvc/recover_ecdsa_without_policy/Jamfile new file mode 100644 index 00000000..26765015 --- /dev/null +++ b/test/msvc/recover_ecdsa_without_policy/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail recover_ecdsa_without_policy : app.cpp + : /webcpp/crypto//crypto /third_party//secp256k1 + : native ; diff --git a/test/msvc/recover_ecdsa_without_policy/app.cpp b/test/msvc/recover_ecdsa_without_policy/app.cpp new file mode 100644 index 00000000..dd154d29 --- /dev/null +++ b/test/msvc/recover_ecdsa_without_policy/app.cpp @@ -0,0 +1,33 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// curves::secp256k1::recover of crypto::signing_schemes::ecdsa_sha256, a scheme that is not +// recoverable, in the arity before the verification policies, stops with the message that names +// the two schemes recover takes and its policy, and with that error alone. On MSVC the compile +// fails; the text is checked on clang, in test/messages/recover_ecdsa_without_policy. +#include +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const seed{1}; + std::array const message{'h', 'e', 'l', 'l', 'o'}; + auto const made = crypto::curves::secp256k1::keypair::from_secret(seed); + if (!made) { + return 1; + } + auto const signature = made->sign(crypto::signing_schemes::ecdsa_sha256, message); + if (!signature) { + return 1; + } + return crypto::curves::secp256k1::recover(crypto::signing_schemes::ecdsa_sha256, *signature, + message) + ? 0 + : 1; +} diff --git a/test/msvc/recover_without_policy/Jamfile b/test/msvc/recover_without_policy/Jamfile new file mode 100644 index 00000000..cfddb6f9 --- /dev/null +++ b/test/msvc/recover_without_policy/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail recover_without_policy : app.cpp + : /webcpp/crypto//crypto /third_party//secp256k1 + : native ; diff --git a/test/msvc/recover_without_policy/app.cpp b/test/msvc/recover_without_policy/app.cpp new file mode 100644 index 00000000..e4b14baa --- /dev/null +++ b/test/msvc/recover_without_policy/app.cpp @@ -0,0 +1,33 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// curves::secp256k1::recover in the arity before the verification policies, recover(scheme, +// signature, message), stops at the catch-all, whose message says that recover takes a policy after +// the scheme, low_s_only, and with that error alone. On MSVC the compile fails; the text is checked +// on clang, in test/messages/recover_without_policy. +#include +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const seed{1}; + std::array const message{'h', 'e', 'l', 'l', 'o'}; + auto const made = crypto::curves::secp256k1::keypair::from_secret(seed); + if (!made) { + return 1; + } + auto const signature = made->sign(crypto::signing_schemes::ecdsa_sha256_recoverable, message); + if (!signature) { + return 1; + } + return crypto::curves::secp256k1::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, + *signature, message) + ? 0 + : 1; +} diff --git a/test/timing_coverage_sodium_test.cpp b/test/timing_coverage_sodium_test.cpp index a2921da4..81fa8b38 100644 --- a/test/timing_coverage_sodium_test.cpp +++ b/test/timing_coverage_sodium_test.cpp @@ -783,8 +783,11 @@ void cover_ed25519ph() { signature = *signed_message; } }); - covered("ed25519::prehashed_signer::verify on sodium", - [&] { BOOST_TEST(verifier->verify(signature, *public_key).has_value()); }); + covered("ed25519::prehashed_signer::verify on sodium", [&] { + BOOST_TEST( + verifier->verify(crypto::verification_policies::canonical, signature, *public_key) + .has_value()); + }); } /** @@ -812,11 +815,12 @@ void cover_ed25519ph_refusals() { covered("ed25519::prehashed_signer::sign of an ended message on sodium", [&] { BOOST_TEST(ended->sign(*key).error() == crypto::error::invalid_state); }); covered("ed25519::prehashed_signer::verify of an ended message on sodium", [&] { - BOOST_TEST(ended->verify(signature, *public_key).error() == crypto::error::invalid_state); + BOOST_TEST(ended->verify(crypto::verification_policies::canonical, signature, *public_key) + .error() == crypto::error::invalid_state); }); covered("ed25519::prehashed_signer::verify with a zero signature on sodium", [&] { - BOOST_TEST(refused->verify(signature, *public_key).error() == - crypto::error::invalid_signature); + BOOST_TEST(refused->verify(crypto::verification_policies::canonical, signature, *public_key) + .error() == crypto::error::invalid_signature); }); } diff --git a/test/verification_policies_test.cpp b/test/verification_policies_test.cpp index 286a2c6a..602b6517 100644 --- a/test/verification_policies_test.cpp +++ b/test/verification_policies_test.cpp @@ -24,8 +24,8 @@ // Ed25519ph's signature verifies. // - schnorr_canonical: BIP340's test-vectors.csv row 0 accepted under canonical, against the // 32-byte x-only key and the typed key. -// - asynchronous: async_verify on Ed25519 under canonical and on P-256 under any_s and low_s_only, -// member and free, with the answers of the synchronous calls. +// - asynchronous: async_verify on Ed25519 under canonical, member and free, and on P-256, member +// and free each under any_s and under low_s_only, with the answers of the synchronous calls. // The policies the schemes do not accept are refused at compile time: the message tests // verify_secp256k1_any_s, verify_p256_canonical, verify_eddsa_low_s_only, verify_schnorr_any_s, // recover_any_s, verify_without_policy and async_verify_without_policy. @@ -559,15 +559,23 @@ void asynchronous() { } auto const sample = text_bytes("sample"); auto const high = p256::ecdsa_signature::from_bytes(test::p256::rfc6979_sample).value(); - BOOST_TEST(!completed(context, [&](auto const& executor, auto&& token) { - return crypto::async_verify(executor, schemes::ecdsa_sha256, policies::any_s, high, sample, - *p256_key, std::forward(token)); - })); - BOOST_TEST(completed(context, [&](auto const& executor, auto&& token) { - return p256_key->async_verify(executor, schemes::ecdsa_sha256, - policies::low_s_only, high, sample, - std::forward(token)); - }) == crypto::error::invalid_signature); + // The free form and the member, each under both policies. + auto const free_form = [&](auto policy) { + return completed(context, [&](auto const& executor, auto&& token) { + return crypto::async_verify(executor, schemes::ecdsa_sha256, policy, high, sample, + *p256_key, std::forward(token)); + }); + }; + auto const member_form = [&](auto policy) { + return completed(context, [&](auto const& executor, auto&& token) { + return p256_key->async_verify(executor, schemes::ecdsa_sha256, policy, high, sample, + std::forward(token)); + }); + }; + BOOST_TEST(!free_form(policies::any_s)); + BOOST_TEST(!member_form(policies::any_s)); + BOOST_TEST(free_form(policies::low_s_only) == crypto::error::invalid_signature); + BOOST_TEST(member_form(policies::low_s_only) == crypto::error::invalid_signature); } } // namespace From 9710e5d868b93469760f05a74807b48419aa416f Mon Sep 17 00:00:00 2001 From: R Date: Mon, 30 Nov 2026 21:59:15 -0300 Subject: [PATCH 09/81] crypto: the guide's lookup sentence keeps its code as written --- doc/curves.adoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/curves.adoc b/doc/curves.adoc index b965c1c7..a93ef85a 100644 --- a/doc/curves.adoc +++ b/doc/curves.adoc @@ -579,7 +579,7 @@ 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 (<>). -The free forms are called qualified, `crypto::verify(...)`, or after +The free forms are called qualified, `+crypto::verify(...)+`, or after `using webcpp::crypto::verify;`: argument-dependent lookup does not find them, the scheme and policy tags being of the nested namespaces `crypto::signing_schemes` and `crypto::verification_policies`, not of `webcpp::crypto` itself. The From ea8fab7582b214fc17985fc817909d190b7dc3b5 Mon Sep 17 00:00:00 2001 From: R Date: Mon, 30 Nov 2026 22:04:15 -0300 Subject: [PATCH 10/81] crypto: the policy row lint fix --- include/webcpp/crypto/signing.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/webcpp/crypto/signing.hpp b/include/webcpp/crypto/signing.hpp index bf42ba29..f716a129 100644 --- a/include/webcpp/crypto/signing.hpp +++ b/include/webcpp/crypto/signing.hpp @@ -917,7 +917,7 @@ enum class policy_row { */ template [[nodiscard]] consteval policy_row policy_row_of() noexcept { - using accepted = typename accepted_policies::type; + using accepted = accepted_policies::type; if constexpr (std::is_same_v) { return policy_row::eddsa; } else if constexpr (std::is_same_v) { From 2d7f4cbc1f9b6b2faadb58df4edfe5d7c362c6e2 Mon Sep 17 00:00:00 2001 From: R Date: Mon, 30 Nov 2026 23:00:32 -0300 Subject: [PATCH 11/81] crypto: is_low_s() and low_s() are members of the ECDSA signatures, a recoverable one flipping its recovery id; the free normalize_low_s and is_low_s go --- bench/operations.hpp | 2 +- doc/backends.adoc | 4 +- doc/curves.adoc | 14 +- doc/generated/backends-encodings.adoc | 2 +- doc/generated/backends-p256_ecdsa.adoc | 2 +- doc/generated/constant-time.adoc | 2 +- doc/generated/matrix.adoc | 10 +- doc/generated/messages.adoc | 14 +- doc/generated/namespace-curves.adoc | 2 +- doc/generated/use-cases.adoc | 6 +- doc/llms.txt | 16 +- doc/p256.adoc | 8 +- doc/p2p.adoc | 2 +- doc/secp256k1.adoc | 9 +- doc/tables/crypto.json | 23 +- doc/wallets.adoc | 2 +- example/bitcoin_sighash.cpp | 2 +- example/ecdsa_der.cpp | 6 +- example/p256_handshake.cpp | 2 +- example/p256_sign.cpp | 2 +- include/webcpp/crypto/curves/ed25519.hpp | 2 + include/webcpp/crypto/curves/p256.hpp | 98 +++---- include/webcpp/crypto/curves/secp256k1.hpp | 204 +++++++++---- include/webcpp/crypto/detail/p_curves.hpp | 4 +- include/webcpp/crypto/detail/signature.hpp | 41 ++- test/Jamfile | 3 + test/allocation_bearssl_test.cpp | 6 +- test/constant_time/paths.hpp | 8 +- test/crypto_secp256k1_test.cpp | 2 - test/messages/Jamfile | 1 + test/messages/low_s_on_ed25519/Jamfile | 12 + .../low_s_on_ed25519/low_s_on_ed25519.cpp | 16 + test/msvc/Jamfile | 1 + test/msvc/low_s_on_ed25519/Jamfile | 9 + test/msvc/low_s_on_ed25519/app.cpp | 14 + test/p256_ecdsa_bearssl_test.cpp | 40 +-- test/p256_openssl_oracle_test.cpp | 4 +- test/p256_webcrypto_oracle_test.cpp | 4 +- test/p256_wycheproof_bearssl_test.cpp | 2 +- test/secp256k1_allocation_test.cpp | 4 +- test/secp256k1_der_test.cpp | 31 +- test/secp256k1_ethereum_test.cpp | 4 +- test/secp256k1_test.cpp | 6 +- test/signature_low_s_test.cpp | 275 ++++++++++++++++++ test/timing_coverage_bearssl_test.cpp | 2 +- test/timing_coverage_secp256k1_test.cpp | 53 ++-- test/timing_test.cpp | 9 +- 47 files changed, 734 insertions(+), 251 deletions(-) create mode 100644 test/messages/low_s_on_ed25519/Jamfile create mode 100644 test/messages/low_s_on_ed25519/low_s_on_ed25519.cpp create mode 100644 test/msvc/low_s_on_ed25519/Jamfile create mode 100644 test/msvc/low_s_on_ed25519/app.cpp create mode 100644 test/signature_low_s_test.cpp diff --git a/bench/operations.hpp b/bench/operations.hpp index ec50e419..be4f3afa 100644 --- a/bench/operations.hpp +++ b/bench/operations.hpp @@ -489,7 +489,7 @@ class p256 { return crypto::verify(signing_schemes::ecdsa_sha256, verification_policies::low_s_only, signature, signing_schemes::prehashed{digest_}, public_key) .has_value() && - curves::p256::is_low_s(signature); + signature.is_low_s(); } private: diff --git a/doc/backends.adoc b/doc/backends.adoc index e77ecdd3..5df37f7c 100644 --- a/doc/backends.adoc +++ b/doc/backends.adoc @@ -138,7 +138,7 @@ ElligatorSwift's `ellswift_create` and `ellswift_xdh`, MuSig2's `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::signing_schemes::prehashed`), which makes its -signature low S without a branch, then `normalize_low_s` and `is_low_s` on the +signature low S without a branch, then `low_s()` and `is_low_s()` of 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 @@ -217,7 +217,7 @@ check of a scalar and its low-S test, and each verdict of libsecp256k1's that webcpp reads), so that the checkers report every other branch. A signature is public once it is made, but one fresh from `sign` is computed from the scalar: the low-S step of `sign` selects n - s by a mask, without a branch and without -marking anything public, and `normalize_low_s` and `is_low_s` mark their verdict +marking anything public, and `low_s()` and `is_low_s()` of a signature mark their verdict public, so that a program that checks its own signatures under a checker sees no report. libsecp256k1 marks its own public values (a nonce's retry, a verdict, a public key it loads) when its context is made with diff --git a/doc/curves.adoc b/doc/curves.adoc index a93ef85a..d4ea4617 100644 --- a/doc/curves.adoc +++ b/doc/curves.adoc @@ -34,7 +34,7 @@ by header: `agree`, `agree_hashed`, `agree_point` and `tweak_xonly`; the `public_key` type's `from_bytes`, `compressed`, `uncompressed` and `xonly`; `crypto::verify` with `crypto::signing_schemes::schnorr` and `crypto::signing_schemes::ecdsa_sha256`, `recover`, `to_der`, -`from_der`, `normalize_low_s`, `is_low_s` and the x-only key's `tweak_xonly`; +`from_der`, the low-S members of its ECDSA signatures 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: `secret_key_tweak_add`, `secret_key_tweak_mul`, `secret_key_negate`, `public_key_tweak_add`, @@ -353,10 +353,14 @@ 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 +`ecdsa_signature`. Low S is a member of each ECDSA signature type (and of +secp256k1's `recoverable_signature`), not a function of the namespace: +`signature.low_s()` returns the low-S form, and `invalid_signature` for an r or +an s that is 0 or not below n (and, for a recoverable signature, a recovery id +above 3), flipping the bit 0 of a recoverable signature's recovery id when it +replaces s, which keeps the signer; `signature.is_low_s()` is true exactly when +r is between 1 and n - 1 and s between 1 and (n - 1) / 2, and does not verify. +An Ed25519 or Schnorr signature has neither. A P-256 signature given to secp256k1's functions, or the reverse, stops the build. [#crypto-curves-factories] diff --git a/doc/generated/backends-encodings.adoc b/doc/generated/backends-encodings.adoc index 95f009a0..d68e19a1 100644 --- a/doc/generated/backends-encodings.adoc +++ b/doc/generated/backends-encodings.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::to_der+`, `+from_der+`, `+normalize_low_s+`, `+is_low_s+`, from the test programs that run it: +The backends of `+curves::secp256k1::to_der+`, `+from_der; ecdsa_signature::is_low_s+`, `+low_s; recoverable_signature::is_low_s+`, `+low_s+`, from the test programs that run it: [cols="1,2,2,4",options="header"] |=== diff --git a/doc/generated/backends-p256_ecdsa.adoc b/doc/generated/backends-p256_ecdsa.adoc index 35e2ec80..2b07a9d1 100644 --- a/doc/generated/backends-p256_ecdsa.adoc +++ b/doc/generated/backends-p256_ecdsa.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::p256::keypair::sign; crypto::verify+`, `+to_der+`, `+from_der+`, `+normalize_low_s+`, `+is_low_s+`, from the test programs that run it: +The backends of `+curves::p256::keypair::sign; crypto::verify+`, `+to_der+`, `+from_der; ecdsa_signature::is_low_s+`, `+low_s+`, 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 f58e2ce9..1618abf1 100644 --- a/doc/generated/constant-time.adoc +++ b/doc/generated/constant-time.adoc @@ -13,7 +13,7 @@ |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::signing_schemes::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)) +|Valgrind's memcheck (Linux): AES-GCM, ChaCha20-Poly1305, P-256 (the key pair's making, `+sign+` of a digest (`+crypto::signing_schemes::prehashed+`), which makes its signature low S without a branch, then `+low_s()+` and `+is_low_s()+` of it, `+agree+` and `+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 diff --git a/doc/generated/matrix.adoc b/doc/generated/matrix.adoc index 0d59f2c1..e652223a 100644 --- a/doc/generated/matrix.adoc +++ b/doc/generated/matrix.adoc @@ -91,7 +91,7 @@ |native, wasip2, wasip3, emscripten |`+secp256k1_bip340+`, `+secp256k1_wycheproof+`, `+secp256k1_recovery+`, `+signing_curves+` -|`+curves::secp256k1::to_der+`, `+from_der+`, `+normalize_low_s+`, `+is_low_s+` +|`+curves::secp256k1::to_der+`, `+from_der; ecdsa_signature::is_low_s+`, `+low_s; recoverable_signature::is_low_s+`, `+low_s+` |libsecp256k1 |native, wasip2, wasip3, emscripten |`+secp256k1_der+` @@ -281,12 +281,12 @@ |refused at compile time |`+p256_on_sodium+` -|`+curves::p256::keypair::sign; crypto::verify+`, `+to_der+`, `+from_der+`, `+normalize_low_s+`, `+is_low_s+` +|`+curves::p256::keypair::sign; crypto::verify+`, `+to_der+`, `+from_der; ecdsa_signature::is_low_s+`, `+low_s+` |BearSSL |native, wasip2, wasip3, emscripten |`+p256_ecdsa_bearssl+`, `+p256_wycheproof_bearssl+`, `+p256_openssl_oracle+`, `+p256_webcrypto_oracle+`, `+allocation_bearssl+` -|`+curves::p256::keypair::sign; crypto::verify+`, `+to_der+`, `+from_der+`, `+normalize_low_s+`, `+is_low_s+` +|`+curves::p256::keypair::sign; crypto::verify+`, `+to_der+`, `+from_der; ecdsa_signature::is_low_s+`, `+low_s+` |libsodium |refused at compile time |`+p256_on_sodium+` @@ -378,7 +378,7 @@ The same, by target: the backends each operation runs on. |libsecp256k1 |libsecp256k1 -|`+curves::secp256k1::to_der+`, `+from_der+`, `+normalize_low_s+`, `+is_low_s+` +|`+curves::secp256k1::to_der+`, `+from_der; ecdsa_signature::is_low_s+`, `+low_s; recoverable_signature::is_low_s+`, `+low_s+` |libsecp256k1 |libsecp256k1 |libsecp256k1 @@ -564,7 +564,7 @@ The same, by target: the backends each operation runs on. |BearSSL |BearSSL -|`+curves::p256::keypair::sign; crypto::verify+`, `+to_der+`, `+from_der+`, `+normalize_low_s+`, `+is_low_s+` +|`+curves::p256::keypair::sign; crypto::verify+`, `+to_der+`, `+from_der; ecdsa_signature::is_low_s+`, `+low_s+` |BearSSL |BearSSL |BearSSL diff --git a/doc/generated/messages.adoc b/doc/generated/messages.adoc index 87369369..05d5dc85 100644 --- a/doc/generated/messages.adoc +++ b/doc/generated/messages.adoc @@ -417,6 +417,12 @@ 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. +|`+low_s_on_ed25519+` +|native, wasip2, wasip3 +|`+invalid reference to function 'low_s': constraints not satisfied+` + +The fix: Only an ECDSA signature has low S: Ed25519 and Schnorr signatures have no `+is_low_s()+` or `+low_s()+`, and need none, for no other S verifies as theirs. + |`+make_removed+` |native, wasip2, wasip3 |`+no member named 'make' in+` @@ -937,7 +943,7 @@ The fix: Verify a BIP340 signature with `+crypto::signing_schemes::schnorr+`, it |native, wasip2, wasip3 |`+webcpp::crypto: verify: crypto::signing_schemes::ecdsa_sha256 on a secp256k1 key takes crypto::verification_policies::low_s_only.+` -The fix: Verify secp256k1's ECDSA under `+crypto::verification_policies::low_s_only+`, its only policy, as libsecp256k1 and Bitcoin's rule; a signature whose S is high is made low with `+normalize_low_s+` first. +The fix: Verify secp256k1's ECDSA under `+crypto::verification_policies::low_s_only+`, its only policy, as libsecp256k1 and Bitcoin's rule; a signature whose S is high is made low with `+signature.low_s()+` first. |`+verify_without_policy+` |native, wasip2, wasip3 @@ -1778,6 +1784,10 @@ 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. +|`+low_s_on_ed25519+` +|the compile +|Only an ECDSA signature has low S: Ed25519 and Schnorr signatures have no `+is_low_s()+` or `+low_s()+`, and need none, for no other S verifies as theirs. + |`+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. @@ -1876,7 +1886,7 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |`+verify_secp256k1_any_s+` |the compile -|Verify secp256k1's ECDSA under `+crypto::verification_policies::low_s_only+`, its only policy, as libsecp256k1 and Bitcoin's rule; a signature whose S is high is made low with `+normalize_low_s+` first. +|Verify secp256k1's ECDSA under `+crypto::verification_policies::low_s_only+`, its only policy, as libsecp256k1 and Bitcoin's rule; a signature whose S is high is made low with `+signature.low_s()+` first. |`+verify_without_policy+` |the compile diff --git a/doc/generated/namespace-curves.adoc b/doc/generated/namespace-curves.adoc index d822fc8b..bb179b56 100644 --- a/doc/generated/namespace-curves.adoc +++ b/doc/generated/namespace-curves.adoc @@ -45,7 +45,7 @@ |libsecp256k1: native, Valgrind's memcheck (Linux; 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), MemorySanitizer (Linux, clang; the same paths as memcheck's) and dudect (judged; on a runner GitHub hosts, by two of three runs; `+agree+`), nothing found; wasip2, dudect (judged; on a runner GitHub hosts, by two of three runs; `+agree+`), nothing found; not measured yet on wasip3, emscripten (<>) |libsodium: native, Valgrind's memcheck (Linux), MemorySanitizer (Linux, clang) and dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; wasip2, dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; not measured yet on wasip3, emscripten (<>) |libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found, and dudect (judged; on a runner GitHub hosts, by two of three runs): nothing found with arm64's DIT (data-independent timing) bit set, which webcpp sets around every call on 64-bit ARM under macOS, iOS, Linux, Android and Windows where the CPU has it, as Apple requires 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, Writing ARM64 code for Apple platforms: enable DIT for constant-time cryptographic operations]); the lane's dudect sets nothing itself and measures what a program gets: \|t\| 1.8 to 2.8 against the threshold 10 (2026-11-21, five runs), while its `dudect_planted`, an early-exit scan of the secret key run inside the same guard, reads \|t\| 66.72 and 65.53 (2026-11-21): DIT does not hide a leak. Without DIT, dudect times `agree` with an all-zero secret key against random ones at \|t\| 6.7 to 14.5 (2026-11-19) and 4.3 to 7.8 (2026-11-21, three runs): about one nanosecond in 15 µs. Each on an Apple M5 Max, from a release build. libsodium does not set DIT, and webcpp sets nothing on x86 or WebAssembly; wasip2, dudect (judged; on a runner GitHub hosts, by two of three runs): an open finding, its cause measured: dudect times `agree` with an all-zero secret key against random ones at \|t\| 13 to 32 (2026-11-18; a fixed key against another fixed key: 22.9) and 107 to 260 (2026-11-19), and 25.25 in the lane on 2026-11-21, against the threshold 10, under wasmtime 47 on an Apple M5 Max, from a release build. The cause is Apple silicon's DIT (data-independent timing), which wasmtime does not set (link:https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Enable-DIT-for-constant-time-cryptographic-operations[Apple, Writing ARM64 code for Apple platforms: enable DIT for constant-time cryptographic operations]): with DIT set in wasmtime's main thread, an experiment and not the lane, the same case reads \|t\| 1.5 to 2.1; no branch on a secret was found in the WebAssembly or in wasmtime's compiled code. The lane cannot set DIT from inside the WebAssembly, so it prints this value on wasip2 without judging it; the CI's x86-64 run measures it next; not measured yet on wasip3, emscripten (<>) -|BearSSL: native, Valgrind's memcheck (Linux; the key pair's making, `+sign+` of a digest (`+crypto::signing_schemes::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 (<>) +|BearSSL: native, Valgrind's memcheck (Linux; the key pair's making, `+sign+` of a digest (`+crypto::signing_schemes::prehashed+`), which makes its signature low S without a branch, then `+low_s()+` and `+is_low_s()+` of it, `+agree+` and `+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 (<>) |Standards |link:https://www.secg.org/sec2-v2.pdf[SEC 2, Recommended Elliptic Curve Domain Parameters], link:https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki[BIP 340, Schnorr signatures for secp256k1], link:https://www.rfc-editor.org/rfc/rfc6979[RFC 6979, deterministic ECDSA nonces], link:https://github.com/bitcoin/bips/blob/master/bip-0324.mediawiki[BIP 324, version 2 P2P encrypted transport protocol], link:https://github.com/bitcoin/bips/blob/master/bip-0327.mediawiki[BIP 327, MuSig2 for BIP340-compatible multi-signatures], link:https://github.com/bitcoin/bips/blob/master/bip-0352.mediawiki[BIP 352, Silent Payments] diff --git a/doc/generated/use-cases.adoc b/doc/generated/use-cases.adoc index 9db7cb62..a407310e 100644 --- a/doc/generated/use-cases.adoc +++ b/doc/generated/use-cases.adoc @@ -154,7 +154,7 @@ |<> |Sign a Bitcoin SegWit v0 input (a domain library's job) -|In `+curves::secp256k1+`: `+keypair::sign(crypto::signing_schemes::ecdsa_sha256, crypto::signing_schemes::prehashed{sighash})+`, `+to_der+`, `+is_low_s+`, `+normalize_low_s+` +|In `+curves::secp256k1+`: `+keypair::sign(crypto::signing_schemes::ecdsa_sha256, crypto::signing_schemes::prehashed{sighash})+`, `+to_der+`, `+signature.is_low_s()+`, `+signature.low_s()+` |libsecp256k1 |`+/webcpp/crypto//crypto+` + `+/third_party//secp256k1+` @@ -268,7 +268,7 @@ |<> |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 -|In `+curves::p256+`: `+keypair::sign(crypto::signing_schemes::ecdsa_sha256, message)+`, `+crypto::verify+`, `+is_low_s+`, `+normalize_low_s+`; `+to_der+`, `+from_der+` for X.509 +|In `+curves::p256+`: `+keypair::sign(crypto::signing_schemes::ecdsa_sha256, message)+`, `+crypto::verify+`, `+signature.is_low_s()+`, `+signature.low_s()+`; `+to_der+`, `+from_der+` for X.509 |BearSSL |`+/webcpp/crypto//crypto+` + `+/webcpp/crypto//p256-default+` @@ -290,7 +290,7 @@ |<> |Sign a peer-to-peer handshake a browser's WebCrypto verifies, low S, check the peer's, and derive the session key from ECDH (Trystero's protocol is webcpp::trystero's) -|In `+curves::p256+`: `+keypair::sign(crypto::signing_schemes::ecdsa_sha256, crypto::signing_schemes::prehashed{digest})+`, `+is_low_s+`, `+crypto::verify+`, `+keypair::agree+`; `+webcpp::hash::hkdf+` for the key +|In `+curves::p256+`: `+keypair::sign(crypto::signing_schemes::ecdsa_sha256, crypto::signing_schemes::prehashed{digest})+`, `+signature.is_low_s()+`, `+crypto::verify+`, `+keypair::agree+`; `+webcpp::hash::hkdf+` for the key |BearSSL |`+/webcpp/crypto//crypto+` + `+/webcpp/crypto//p256-default+` diff --git a/doc/llms.txt b/doc/llms.txt index 24cf2cfd..160bc820 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -118,11 +118,9 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [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::signing_schemes::schnorr, crypto::verification_policies::canonical, signature, message, key)`, or an ECDSA one against a `curves::secp256k1::public_key`, `crypto::verify(crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::low_s_only, signature, input, public_key)`, refusing a high S; `recover(crypto::signing_schemes::ecdsa_sha256_recoverable, crypto::verification_policies::low_s_only, signature, input)` and `recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, crypto::verification_policies::low_s_only, signature, input)` give the signer's key, refusing a high S before recovery. 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`) of ECDSA over SHA-256: the same inputs as `sign(crypto::signing_schemes::ecdsa_sha256_recoverable, ...)`. -- [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. +- [curves::secp256k1::to_der, from_der; ecdsa_signature::is_low_s, low_s; recoverable_signature::is_low_s, low_s](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1): ECDSA's strict DER encoding, and low S as the members `is_low_s()` and `low_s()` of the ECDSA signatures, a recoverable one's `low_s()` flipping its recovery id. 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. - - normalize_low_s: The low-S form of a compact ECDSA signature (`secp256k1_ecdsa_signature_normalize`), the only form `crypto::verify` accepts on secp256k1; a low-S signature is returned unchanged. - - 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::signing_schemes::eddsa, message)`, and of a message's SHA-512 with `sign(crypto::signing_schemes::eddsa_prehashed, crypto::signing_schemes::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. @@ -239,14 +237,12 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - uncompressed: The point, as WebCrypto's `exportKey("raw")` writes it. - verify: Verifies an ECDSA signature over SHA-256 with this key under a verification policy: `crypto::verify(crypto::signing_schemes::ecdsa_sha256, verification_policy, 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 under a verification policy, 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::signing_schemes::ecdsa_sha256, input)` and `crypto::verify(crypto::signing_schemes::ecdsa_sha256, policy, signature, input, public_key)`, the input a message hashed inside or `crypto::signing_schemes::prehashed{digest}`; the signature a `curves::p256::ecdsa_signature`, r and s, signed low S, verified under `crypto::verification_policies::low_s_only` (a high S refused before BearSSL) or `any_s` (WebCrypto's and a passkey's, 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. +- [curves::p256::keypair::sign; crypto::verify, to_der, from_der; ecdsa_signature::is_low_s, low_s](https://webcpporg.github.io/libs/crypto/#crypto-p256-ecdsa): ECDSA over SHA-256 with RFC 6979's nonce, `sign(crypto::signing_schemes::ecdsa_sha256, input)` and `crypto::verify(crypto::signing_schemes::ecdsa_sha256, policy, signature, input, public_key)`, the input a message hashed inside or `crypto::signing_schemes::prehashed{digest}`; the signature a `curves::p256::ecdsa_signature`, r and s, signed low S, verified under `crypto::verification_policies::low_s_only` (a high S refused before BearSSL) or `any_s` (WebCrypto's and a passkey's, whatever its S); strict DER both ways; `is_low_s()` and `low_s()` of the signature, for one 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 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 under a verification policy. - 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. - - normalize_low_s: The low-S form of a signature: s replaced by n - s when s is above (n - 1) / 2, returned unchanged otherwise. - - is_low_s: Whether a signature is in its low-S form, as a protocol that requires low S checks what it receives before `crypto::verify`, which accepts both forms; `sign` gives the low form. - [curves::p256::keypair::agree](https://webcpporg.github.io/libs/crypto/#crypto-p256-ecdh): ECDH with a validated public key: the shared point's raw x coordinate, 32 bytes in a `secure::secret<32>`, as WebCrypto's `deriveBits` gives it; a protocol hashes it into its keys. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten. Default: BearSSL on native, wasip2, wasip3, emscripten. Use it to: 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. - agree: ECDH with a peer's public key: the x coordinate of the shared point d * Q, raw, as WebCrypto's `deriveBits` with ECDH on P-256 gives its 256 bits. - 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. @@ -332,7 +328,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - 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 `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::signing_schemes::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. +- P-256: BearSSL: native, Valgrind's memcheck (Linux; the key pair's making, `sign` of a digest (`crypto::signing_schemes::prehashed`), which makes its signature low S without a branch, then `low_s()` and `is_low_s()` of it, `agree` and `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 @@ -371,7 +367,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [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::signing_schemes::ecdsa_sha256, crypto::signing_schemes::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. +- [Sign a Bitcoin SegWit v0 input (a domain library's job)](https://webcpporg.github.io/libs/crypto/#crypto-wallets-der): `keypair::sign(crypto::signing_schemes::ecdsa_sha256, crypto::signing_schemes::prehashed{sighash})`, `to_der`, `signature.is_low_s()`, `signature.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::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. @@ -387,10 +383,10 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [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::signing_schemes::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. +- [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::signing_schemes::ecdsa_sha256, message)`, `crypto::verify`, `signature.is_low_s()`, `signature.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. -- [Sign a peer-to-peer handshake a browser's WebCrypto verifies, low S, check the peer's, and derive the session key from ECDH (Trystero's protocol is webcpp::trystero's)](https://webcpporg.github.io/libs/crypto/#crypto-p2p-handshake): `keypair::sign(crypto::signing_schemes::ecdsa_sha256, crypto::signing_schemes::prehashed{digest})`, `is_low_s`, `crypto::verify`, `keypair::agree`; `webcpp::hash::hkdf` for the key (webcpp::crypto::curves::p256); backend BearSSL; Jamfile /webcpp/crypto//crypto /webcpp/crypto//p256-default. Example: example/p256_handshake.cpp. +- [Sign a peer-to-peer handshake a browser's WebCrypto verifies, low S, check the peer's, and derive the session key from ECDH (Trystero's protocol is webcpp::trystero's)](https://webcpporg.github.io/libs/crypto/#crypto-p2p-handshake): `keypair::sign(crypto::signing_schemes::ecdsa_sha256, crypto::signing_schemes::prehashed{digest})`, `signature.is_low_s()`, `crypto::verify`, `keypair::agree`; `webcpp::hash::hkdf` for the key (webcpp::crypto::curves::p256); backend BearSSL; Jamfile /webcpp/crypto//crypto /webcpp/crypto//p256-default. Example: example/p256_handshake.cpp. ## Examples diff --git a/doc/p256.adoc b/doc/p256.adoc index 88b66dfc..b1e3c507 100644 --- a/doc/p256.adoc +++ b/doc/p256.adoc @@ -246,11 +246,11 @@ verifies under `crypto::verification_policies::low_s_only`, which refuses a high S with `invalid_signature` before BearSSL is called. So the policy says whose signature it is: `low_s_only` for a signature crypto made, or a peer of a protocol that requires low S; `any_s` for one a browser's WebCrypto or a passkey -made, whose S may be high. `is_low_s(signature)`, true exactly when r is between +made, whose S may be high. `signature.is_low_s()`, true exactly when r is between 1 and n - 1 and s between 1 and (n - 1) / 2, tells a program which form it holds. -`normalize_low_s(signature)` returns the low-S form of a signature made +`signature.low_s()` returns the low-S form of a signature made elsewhere, such as WebCrypto's, whose S may be high, and the same signature when -S is already low. Neither calls BearSSL: both are arithmetic on public bytes. +S is already low. Neither calls BearSSL: both members are arithmetic on public bytes. *Example.* RFC 6979's key signs "sample", whose signature in the RFC has a high S: `sign` gives its low-S form. Its DER, the signature verified under @@ -276,7 +276,7 @@ first peer whose S is high, which a WebCrypto peer's is about one signature in two. Such a protocol verifies under `low_s_only`. * The opposite: a program that verifies a browser's or a passkey's signatures under `low_s_only` refuses about one in two of them. Their policy is `any_s`. -* `is_low_s` does not verify: a forged signature can have a low S. Verifying +* `is_low_s()` does not verify: a forged signature can have a low S. Verifying under `low_s_only` checks both. * A 32-byte message is a message: `sign(crypto::signing_schemes::ecdsa_sha256, message)` hashes it, and only `+crypto::signing_schemes::prehashed{digest}+` is signed as given. A digest diff --git a/doc/p2p.adoc b/doc/p2p.adoc index ef32c4f2..0f0ed4b2 100644 --- a/doc/p2p.adoc +++ b/doc/p2p.adoc @@ -267,7 +267,7 @@ signature has two forms, s and n - s, and both verify under `crypto::verification_policies::any_s`; a protocol that requires one form, low S, gets it from `sign`, which signs no other, and its receiver verifies under `low_s_only`, which refuses the other form before BearSSL is called; the -example checks `is_low_s` first too, so that its verdict names the reason. The session key comes +example checks `is_low_s()` first too, so that its verdict names the reason. The session key comes from ECDH's x of the two session key pairs, which is not a key by itself, through HKDF (<>; link:https://www.rfc-editor.org/rfc/rfc5869[RFC 5869]). The example builds this diff --git a/doc/secp256k1.adoc b/doc/secp256k1.adoc index 5a998d97..6a78bde9 100644 --- a/doc/secp256k1.adoc +++ b/doc/secp256k1.adoc @@ -98,7 +98,8 @@ public key alone; `recover`, which finds the key of a recoverable signature `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 +ECDSA's DER form, and the low-S members `is_low_s()` and `low_s()` of the ECDSA +signatures; and `tweak_xonly`, the tweak of an x-only public key; * ``: `secret_key_tweak_add`, `secret_key_tweak_mul` and `secret_key_negate`, `public_key_tweak_add`, @@ -169,7 +170,7 @@ 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::signing_schemes::ecdsa_sha256, crypto::verification_policies::low_s_only, ...)+` refuses a high-S signature, as -libsecp256k1 does, and secp256k1's ECDSA takes no other policy: `normalize_low_s` gives the low-S form of a signature from a +libsecp256k1 does, and secp256k1's ECDSA takes no other policy: the signature's `low_s()` gives its low-S form for a signature from a signer that does not enforce it. A verifier that normalizes before verifying accepts both forms of a signature, so it must not rely on the signature's bytes being unique @@ -455,8 +456,8 @@ EIP-191's digest is hashed without its prefix and recovers another key. * `recover` takes `low_s_only` alone and refuses a high S before recovery, as EIP-2 does for a transaction, although libsecp256k1's recovery and Ethereum's `ecrecover` precompile accept one; `sign` gives a low S always. A program that -must recover a high-S signature makes it low first with `normalize_low_s` of -its r and s and the recovery id's bit 0 flipped, which keeps the signer. +must recover a high-S signature makes it low first with the recoverable signature's `low_s()`, which +replaces s and flips the recovery id's bit 0, which keeps the signer. [#crypto-secp256k1-tweaks] ==== Tweaks, negation and combination diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index d253015c..d52b81e6 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -376,11 +376,11 @@ { "id": "encodings", "family": "secp256k1", - "functions": ["to_der", "from_der", "normalize_low_s", "is_low_s"], + "functions": ["to_der", "from_der"], "namespace": "curves", - "api": "curves::secp256k1::to_der, from_der, normalize_low_s, is_low_s", + "api": "curves::secp256k1::to_der, from_der; ecdsa_signature::is_low_s, low_s; recoverable_signature::is_low_s, low_s", "header": "", - "what": "ECDSA's strict DER encoding, and low S as two functions, `normalize_low_s` and `is_low_s`.", + "what": "ECDSA's strict DER encoding, and low S as the members `is_low_s()` and `low_s()` of the ECDSA signatures, a recoverable one's `low_s()` flipping its recovery id.", "section": "crypto-secp256k1", "backends": {"secp256k1": {"tests": ["secp256k1_der"]}} }, @@ -775,11 +775,11 @@ "family": "p256", "free": true, "functions": ["basic_keypair::sign", "basic_keypair::async_sign", "verify", "to_der", - "from_der", "normalize_low_s", "is_low_s"], + "from_der"], "namespace": "curves", - "api": "curves::p256::keypair::sign; crypto::verify, to_der, from_der, normalize_low_s, is_low_s", + "api": "curves::p256::keypair::sign; crypto::verify, to_der, from_der; ecdsa_signature::is_low_s, low_s", "header": "", - "what": "ECDSA over SHA-256 with RFC 6979's nonce, `sign(crypto::signing_schemes::ecdsa_sha256, input)` and `crypto::verify(crypto::signing_schemes::ecdsa_sha256, policy, signature, input, public_key)`, the input a message hashed inside or `crypto::signing_schemes::prehashed{digest}`; the signature a `curves::p256::ecdsa_signature`, r and s, signed low S, verified under `crypto::verification_policies::low_s_only` (a high S refused before BearSSL) or `any_s` (WebCrypto's and a passkey's, 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::signing_schemes::ecdsa_sha256, input)` and `crypto::verify(crypto::signing_schemes::ecdsa_sha256, policy, signature, input, public_key)`, the input a message hashed inside or `crypto::signing_schemes::prehashed{digest}`; the signature a `curves::p256::ecdsa_signature`, r and s, signed low S, verified under `crypto::verification_policies::low_s_only` (a high S refused before BearSSL) or `any_s` (WebCrypto's and a passkey's, whatever its S); strict DER both ways; `is_low_s()` and `low_s()` of the signature, for one made elsewhere.", "section": "crypto-p256-ecdsa", "backends": { "bearssl": {"tests": ["p256_ecdsa_bearssl", "p256_wycheproof_bearssl", "p256_openssl_oracle", "p256_webcrypto_oracle", "allocation_bearssl"]}, @@ -1158,7 +1158,7 @@ {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "bearssl", "tests": ["p256_keys_bearssl", "p256_ecdsa_bearssl", "p256_ecdh_bearssl", "default_backend_none_linked"], "why": "the one backend of the P-curves on all four targets, constant time by design and allocating nothing ({bearssl}); OpenSSL and Botan join in increments 8 and 7"} ], "backends": { - "bearssl": {"targets": "all", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect"]}, "lane_note": {"memcheck": "the key pair's making, `sign` of a digest (`crypto::signing_schemes::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)", "msan": "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": "`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)"}} + "bearssl": {"targets": "all", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect"]}, "lane_note": {"memcheck": "the key pair's making, `sign` of a digest (`crypto::signing_schemes::prehashed`), which makes its signature low S without a branch, then `low_s()` and `is_low_s()` of it, `agree` and `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)", "msan": "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": "`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)"}} } } ], @@ -1288,7 +1288,7 @@ {"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::signing_schemes::ecdsa_sha256, crypto::signing_schemes::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": "Sign a Bitcoin SegWit v0 input (a domain library's job)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::sign(crypto::signing_schemes::ecdsa_sha256, crypto::signing_schemes::prehashed{sighash})`, `to_der`, `signature.is_low_s()`, `signature.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::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"}, @@ -1304,10 +1304,10 @@ {"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::signing_schemes::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": "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::signing_schemes::ecdsa_sha256, message)`, `crypto::verify`, `signature.is_low_s()`, `signature.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"}, - {"need": "Sign a peer-to-peer handshake a browser's WebCrypto verifies, low S, check the peer's, and derive the session key from ECDH (Trystero's protocol is webcpp::trystero's)", "namespace": "webcpp::crypto::curves::p256", "api": "`keypair::sign(crypto::signing_schemes::ecdsa_sha256, crypto::signing_schemes::prehashed{digest})`, `is_low_s`, `crypto::verify`, `keypair::agree`; `webcpp::hash::hkdf` for the key", "backend": "BearSSL", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//p256-default", "example": "p256_handshake", "section": "crypto-p2p-handshake"} + {"need": "Sign a peer-to-peer handshake a browser's WebCrypto verifies, low S, check the peer's, and derive the session key from ECDH (Trystero's protocol is webcpp::trystero's)", "namespace": "webcpp::crypto::curves::p256", "api": "`keypair::sign(crypto::signing_schemes::ecdsa_sha256, crypto::signing_schemes::prehashed{digest})`, `signature.is_low_s()`, `crypto::verify`, `keypair::agree`; `webcpp::hash::hkdf` for the key", "backend": "BearSSL", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//p256-default", "example": "p256_handshake", "section": "crypto-p2p-handshake"} ], "fixtures": { "web": "A web application: AES-256-GCM on BearSSL, the default on WebAssembly.", @@ -1472,6 +1472,7 @@ "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::signing_schemes::schnorr`, its scheme; `crypto::signing_schemes::ecdsa_sha256` takes a `curves::secp256k1::ecdsa_signature`, which `sign(crypto::signing_schemes::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.", + "low_s_on_ed25519": "Only an ECDSA signature has low S: Ed25519 and Schnorr signatures have no `is_low_s()` or `low_s()`, and need none, for no other S verifies as theirs.", "recover_ecdsa_signature": "Give `recover` a `curves::secp256k1::recoverable_signature`, which `sign(crypto::signing_schemes::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.", @@ -1518,7 +1519,7 @@ "ed25519_unknown_policy": "Name `crypto::verification_policies::canonical` after the scheme, Ed25519's only policy: `crypto::verify(crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, signature, message, public_key)`.", "verify_without_policy": "Name the verification policy after the scheme: `crypto::verify(crypto::signing_schemes::eddsa, crypto::verification_policies::canonical, signature, message, public_key)`; each scheme takes its own, `canonical` for Ed25519 and BIP340, `low_s_only` for secp256k1's ECDSA and `recover`, `low_s_only` or `any_s` for P-256's ECDSA.", "async_verify_without_policy": "As `verify_without_policy`: `async_verify(executor, crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::low_s_only, signature, input, public_key, token)` for a signature crypto made, `any_s` for one a browser's WebCrypto or a passkey made, whose S may be high.", - "verify_secp256k1_any_s": "Verify secp256k1's ECDSA under `crypto::verification_policies::low_s_only`, its only policy, as libsecp256k1 and Bitcoin's rule; a signature whose S is high is made low with `normalize_low_s` first.", + "verify_secp256k1_any_s": "Verify secp256k1's ECDSA under `crypto::verification_policies::low_s_only`, its only policy, as libsecp256k1 and Bitcoin's rule; a signature whose S is high is made low with `signature.low_s()` first.", "verify_p256_canonical": "Verify P-256's ECDSA under `crypto::verification_policies::low_s_only`, for a signature crypto made, or `any_s`, for one a browser's WebCrypto or a passkey made, whose S may be high; `canonical` is Ed25519's and BIP340's.", "verify_eddsa_low_s_only": "Verify Ed25519 and Ed25519ph under `crypto::verification_policies::canonical`, libsodium's rules, their only policy; `low_s_only` and `any_s` are ECDSA's.", "verify_schnorr_any_s": "Verify BIP340 under `crypto::verification_policies::canonical`, its only policy; `low_s_only` and `any_s` are ECDSA's.", diff --git a/doc/wallets.adoc b/doc/wallets.adoc index ba63cb03..857e2724 100644 --- a/doc/wallets.adoc +++ b/doc/wallets.adoc @@ -84,7 +84,7 @@ include::{examples}/bitcoin_sighash.expected[] `from_der` decodes strict DER and refuses anything else. A signature from a signer that does not enforce low S is refused by `crypto::verify` under `crypto::verification_policies::low_s_only`, secp256k1's ECDSA's only policy; -`normalize_low_s` gives its low-S form. The same steps in a program of its own, +the signature's `low_s()` gives its low-S form. The same steps in a program of its own, then the high-S form of its signature, refused, and normalized: [source,cpp] diff --git a/example/bitcoin_sighash.cpp b/example/bitcoin_sighash.cpp index c2fb6e5d..02972fe1 100644 --- a/example/bitcoin_sighash.cpp +++ b/example/bitcoin_sighash.cpp @@ -89,7 +89,7 @@ int main() { } print("der ", std::span(der).first(*der_size)); // end::sighash[] - std::printf("verified, low S: %s\n", secp256k1::is_low_s(*signature) ? "yes" : "no"); + std::printf("verified, low S: %s\n", signature->is_low_s() ? "yes" : "no"); return 0; } diff --git a/example/ecdsa_der.cpp b/example/ecdsa_der.cpp index 9a7253b0..f4f395ad 100644 --- a/example/ecdsa_der.cpp +++ b/example/ecdsa_der.cpp @@ -113,7 +113,7 @@ int main() { return 1; } std::printf("strict der round trip ok\n"); - if (!secp256k1::is_low_s(*signature) || + if (!signature->is_low_s() || !crypto::verify(crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::low_s_only, *signature, crypto::signing_schemes::prehashed{sighash}, *public_key)) { @@ -139,8 +139,8 @@ int main() { } std::printf("high-S refused: invalid_signature\n"); // A signature from elsewhere can be brought to the low-S form before it is checked. - auto const normalized = secp256k1::normalize_low_s(high); - if (secp256k1::is_low_s(high) || !normalized || *normalized != *signature || + auto const normalized = high.low_s(); + if (high.is_low_s() || !normalized || *normalized != *signature || !crypto::verify(crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::low_s_only, *normalized, crypto::signing_schemes::prehashed{sighash}, *public_key)) { diff --git a/example/p256_handshake.cpp b/example/p256_handshake.cpp index 171fce14..bace14c7 100644 --- a/example/p256_handshake.cpp +++ b/example/p256_handshake.cpp @@ -178,7 +178,7 @@ struct peer { if (!signature) { return verdict::bad_signature; } - if (!p256::is_low_s(*signature)) { + if (!signature->is_low_s()) { return verdict::high_s; } if (!crypto::verify(crypto::signing_schemes::ecdsa_sha256, diff --git a/example/p256_sign.cpp b/example/p256_sign.cpp index 06537992..914bf34c 100644 --- a/example/p256_sign.cpp +++ b/example/p256_sign.cpp @@ -72,7 +72,7 @@ int main() { } 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"); + std::printf("low S %s\n", signature->is_low_s() ? "yes" : "no"); // DER, for X.509 and OpenSSL: at most max_der_size bytes, its length returned. std::array der{}; diff --git a/include/webcpp/crypto/curves/ed25519.hpp b/include/webcpp/crypto/curves/ed25519.hpp index 061ba76a..311be69c 100644 --- a/include/webcpp/crypto/curves/ed25519.hpp +++ b/include/webcpp/crypto/curves/ed25519.hpp @@ -86,6 +86,8 @@ struct ed25519_keypair_access; struct ed25519_signature_tag { /** No recovery id. */ static constexpr bool recoverable = false; + /** Not ECDSA: no low S. */ + static constexpr bool ecdsa = false; }; } // namespace webcpp::crypto::detail diff --git a/include/webcpp/crypto/curves/p256.hpp b/include/webcpp/crypto/curves/p256.hpp index f2b4772a..5a23257e 100644 --- a/include/webcpp/crypto/curves/p256.hpp +++ b/include/webcpp/crypto/curves/p256.hpp @@ -13,8 +13,8 @@ the input a message, hashed inside, or `crypto::signing_schemes::prehashed{digest}`, the signature a `curves::p256::ecdsa_signature`: signing gives low S, verification under `crypto::verification_policies::low_s_only` accepts low S alone and under `any_s` both; 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. + signature's DER form, and low S as the members `is_low_s()` and `low_s()` of the signature; 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; a program that uses the family without linking it stops where it calls it, with the Jamfile @@ -68,12 +68,6 @@ 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; -}; - /** * Whether a P-256 ECDSA signature passes the verification policy's check, made on the public * signature before any backend call: r and s in range, 0 < r, s < n, under both policies, and @@ -100,6 +94,50 @@ template } } +/** The tag of `curves::p256::ecdsa_signature`. */ +struct p256_ecdsa_signature_tag { + /** No recovery id. */ + static constexpr bool recoverable = false; + /** ECDSA: `is_low_s()` and `low_s()`. */ + static constexpr bool ecdsa = true; + + /** + * Whether a signature is in its low-S form: 0 < r < n and 0 < s <= (n - 1) / 2. Arithmetic on + * public bytes, with no backend; the one predicate `low_s_only` applies as well. + * + * @param signature_bytes The signature's 64 bytes, r then s. + * @return Whether it is low S. + */ + [[nodiscard]] static bool is_low_s( + std::span signature_bytes) noexcept { + return p256_policy_admits(signature_bytes); + } + + /** + * The low-S form of a signature: s replaced by n - s when it is above (n - 1) / 2. Arithmetic + * on public bytes, with no backend. + * + * @param signature_bytes The signature's 64 bytes, r then s. + * @return The bytes with s at most (n - 1) / 2; `invalid_signature` when r or s is 0 or not + * below n. + */ + [[nodiscard]] static boost::system::result< + std::array> + low_s(std::span signature_bytes) noexcept { + if (!p_curve_signature_in_range(signature_bytes)) { + return error::invalid_signature; + } + std::array low_bytes{}; + std::ranges::copy(signature_bytes, low_bytes.begin()); + auto const s_value = signature_bytes.last(); + if (!p_curve_low_s(s_value)) { + p_curve_negate_scalar( + s_value, std::span(low_bytes).last()); + } + return low_bytes; + } +}; + /** * Verifies an ECDSA signature over SHA-256 with a P-256 point on `Backend` under `Policy`: the * work of `basic_public_key::verify` and of `crypto::verify` of `ecdsa_sha256`, which hold the @@ -151,7 +189,7 @@ namespace webcpp::crypto::curves::p256 { * `crypto::signing_schemes::ecdsa_sha256` and `crypto::verify` of that scheme 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 + * size alone; whether r and s are in range, and s low, is verification's and `low_s()`'s * judgment. */ using ecdsa_signature = detail::basic_signature; @@ -834,48 +872,6 @@ template > return detail::signature_access::of(signature_bytes); } -/** - * The low-S form of a signature: s replaced by n - s when s is above (n - 1) / 2, returned - * unchanged otherwise. - * - * Both forms verify with `crypto::verify`; `sign` gives the low form already, so this is for a - * signature made elsewhere, such as WebCrypto's, whose S may be high. Arithmetic on public bytes, - * with no backend. - * - * @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( - 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 = 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 detail::signature_access::of(normalized_signature); -} - -/** - * Whether a signature is in its low-S form, as a protocol that requires low S checks what it - * receives before `crypto::verify`, which accepts both forms; `sign` gives the low form. - * - * Arithmetic on public bytes, with no backend; it does not verify the signature. - * - * @param signature_value The signature. - * @return True exactly when 0 < r < n and 0 < s <= (n - 1) / 2. - */ -[[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()); -} - } // namespace webcpp::crypto::curves::p256 namespace webcpp::crypto { diff --git a/include/webcpp/crypto/curves/secp256k1.hpp b/include/webcpp/crypto/curves/secp256k1.hpp index 96ae150b..f25889f8 100644 --- a/include/webcpp/crypto/curves/secp256k1.hpp +++ b/include/webcpp/crypto/curves/secp256k1.hpp @@ -19,7 +19,7 @@ 32-byte x-only form, under `crypto::verification_policies::canonical`; `recover`, the signer's key, under either recoverable scheme and `low_s_only`; 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 + secret; ECDSA's DER form, the tweak of an x-only key, and the workspace a function over many keys borrows. @see "secp256k1", in the guide. @@ -77,18 +77,65 @@ namespace webcpp::crypto::detail { struct secp256k1_ecdsa_signature_tag { /** No recovery id. */ static constexpr bool recoverable = false; + /** ECDSA: `is_low_s()` and `low_s()`. */ + static constexpr bool ecdsa = true; + + /** + * Whether the signature is in its low-S form: 0 < r < n and 0 < s <= (n - 1) / 2 + * (`secp256k1_ecdsa_signature_normalize`), under libsecp256k1's guard, canary and self-test. It + * does not verify the signature. + * + * @param signature_bytes The signature's 64 bytes. + * @return Whether it is low S. + */ + [[nodiscard]] static bool is_low_s(std::span signature_bytes) noexcept; + + /** + * The low-S form of the signature: s replaced by n - s when it is above (n - 1) / 2. + * + * @param signature_bytes The signature's 64 bytes. + * @return The low-S bytes; `invalid_signature` when r or s is 0 or not below n. + */ + [[nodiscard]] static boost::system::result> low_s( + std::span signature_bytes) noexcept; }; /** The tag of `curves::secp256k1::recoverable_signature`. */ struct secp256k1_recoverable_signature_tag { /** The last byte is the recovery id. */ static constexpr bool recoverable = true; + /** ECDSA: `is_low_s()` and `low_s()`. */ + static constexpr bool ecdsa = true; + + /** + * Whether the signature is in its low-S form: 0 < r < n and 0 < s <= (n - 1) / 2, and the + * recovery id 0 to 3 + * (`secp256k1_ecdsa_signature_normalize`), under libsecp256k1's guard, canary and self-test. It + * does not verify the signature. + * + * @param signature_bytes The signature's 65 bytes. + * @return Whether it is low S. + */ + [[nodiscard]] static bool is_low_s(std::span signature_bytes) noexcept; + + /** + * The low-S form of the signature: s replaced by n - s when it is above (n - 1) / 2, with bit 0 + * of the recovery id flipped, which keeps the signer. + * + * @param signature_bytes The signature's 65 bytes. + * @return The low-S bytes; `invalid_signature` when r or s is 0 or not below n, or the recovery + * id is above 3. + */ + [[nodiscard]] static boost::system::result> low_s( + std::span signature_bytes) noexcept; }; /** The tag of `curves::secp256k1::schnorr_signature`. */ struct secp256k1_schnorr_signature_tag { /** No recovery id. */ static constexpr bool recoverable = false; + /** Not ECDSA: no low S. */ + static constexpr bool ecdsa = false; }; /** @@ -401,6 +448,32 @@ class secp256k1_workspace { secp256k1_nonzero(std::span(output_bytes).last<32>()); } +/** + * The low-S form of a compact ECDSA signature, under libsecp256k1's canary and self-test; the work + * of both tags' `is_low_s` and `low_s`, whose public functions hold the guard. + * + * @param compact_signature The 64 bytes, r then s. + * @param low_bytes Where the low-S 64 bytes go. + * @param was_high Whether s was above half the group order, so that it was replaced. + * @return Whether r and s are in range: false is `invalid_signature` to the caller. + */ +[[nodiscard]] inline bool secp256k1_low_s_of(std::span compact_signature, + std::array& low_bytes, + bool& was_high) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_selftest(); + secp256k1_ecdsa_signature parsed_value{}; + if (!secp256k1_parse_compact(compact_signature, parsed_value)) { + return false; + } + // libsecp256k1 returns 1 when s was high, and normalizes in place. + was_high = secp256k1_ecdsa_signature_normalize(secp256k1_context_static, &parsed_value, + &parsed_value) != 0; + secp256k1_ecdsa_signature_serialize_compact(secp256k1_context_static, low_bytes.data(), + &parsed_value); + return true; +} + /** * The 32-byte digest ECDSA over SHA-256 signs and verifies: a marker's digest, copied, or the * SHA-256 of a message. @@ -536,6 +609,75 @@ struct secp256k1_refusal { template inline constexpr bool secp256k1_refuses_others = sizeof(secp256k1_refusal) != 0; +inline bool secp256k1_ecdsa_signature_tag::is_low_s( + std::span signature_bytes) noexcept { + secure::timing_guard const timing_scope; + static_assert( + secp256k1_refuses_others>); + read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_selftest(); + secp256k1_ecdsa_signature parsed_value{}; + if (!secp256k1_parse_compact(signature_bytes, parsed_value)) { + return false; + } + // libsecp256k1 returns 1 when s was high, and writes nothing when the output is null. + return secp256k1_ecdsa_signature_normalize(secp256k1_context_static, nullptr, &parsed_value) == + 0; +} + +inline boost::system::result> secp256k1_ecdsa_signature_tag::low_s( + std::span signature_bytes) noexcept { + secure::timing_guard const timing_scope; + static_assert( + secp256k1_refuses_others>); + std::array low_bytes{}; + bool was_high = false; + if (!secp256k1_low_s_of(signature_bytes, low_bytes, was_high)) { + return error::invalid_signature; + } + return low_bytes; +} + +inline bool secp256k1_recoverable_signature_tag::is_low_s( + std::span signature_bytes) noexcept { + secure::timing_guard const timing_scope; + static_assert( + secp256k1_refuses_others>); + if (signature_bytes[64] > 3) { + return false; + } + read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_selftest(); + secp256k1_ecdsa_signature parsed_value{}; + if (!secp256k1_parse_compact(signature_bytes.first<64>(), parsed_value)) { + return false; + } + return secp256k1_ecdsa_signature_normalize(secp256k1_context_static, nullptr, &parsed_value) == + 0; +} + +inline boost::system::result> +secp256k1_recoverable_signature_tag::low_s( + std::span signature_bytes) noexcept { + secure::timing_guard const timing_scope; + static_assert( + secp256k1_refuses_others>); + if (signature_bytes[64] > 3) { + return error::invalid_signature; + } + std::array compact_bytes{}; + bool was_high = false; + if (!secp256k1_low_s_of(signature_bytes.first<64>(), compact_bytes, was_high)) { + return error::invalid_signature; + } + std::array low_bytes{}; + std::ranges::copy(compact_bytes, low_bytes.begin()); + // n - s is the other s of the same signature: R's y flips with it, and so does the id's parity. + low_bytes[64] = + was_high ? static_cast(signature_bytes[64] ^ 1U) : signature_bytes[64]; + return low_bytes; +} + /** * Verifies a BIP340 signature against an x-only key already parsed, with libsecp256k1's static * context: the end of every verification of `schnorr`, whose public functions hold the guard. @@ -631,7 +773,7 @@ namespace webcpp::crypto::curves::secp256k1 { * `crypto::verify(crypto::signing_schemes::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 + * size alone; whether r and s are in range, and s low, is verification's and `low_s()`'s * judgment. */ using ecdsa_signature = detail::basic_signature; @@ -1793,62 +1935,6 @@ template > return webcpp::crypto::detail::signature_access::of(output_bytes); } -/** - * The low-S form of a compact ECDSA signature (`secp256k1_ecdsa_signature_normalize`), the - * only form `crypto::verify` accepts on secp256k1; a low-S signature is returned unchanged. - * - * Tip: `sign` gives the low form already; normalizing makes a signature malleable on purpose, - * only for signatures from a signer that does not enforce low S. - * - * @tparam Backend The backend, `backends::secp256k1`. - * @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( - ecdsa_signature const& signature_value) noexcept { - secure::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(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 webcpp::crypto::detail::signature_access::of(output_bytes); -} - -/** - * 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. - * - * It does not verify the signature. - * - * @tparam Backend The backend, `backends::secp256k1`. - * @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(ecdsa_signature const& signature_value) noexcept { - secure::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(signature_value.bytes(), parsed_value)) { - return false; - } - // libsecp256k1 returns 1 when s was high, and writes nothing when the output is null. - return secp256k1_ecdsa_signature_normalize(secp256k1_context_static, nullptr, &parsed_value) == - 0; -} - /** * 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`). @@ -1899,7 +1985,7 @@ namespace webcpp::crypto { * * It takes `crypto::verification_policies::low_s_only` alone (design D9): a high S is refused, as * libsecp256k1 refuses it (Bitcoin's policy); `sign` gives low S, and - * `curves::secp256k1::normalize_low_s` makes a high one low. + * `ecdsa_signature::low_s()` makes a high one low. * * @tparam Backend The backend, `backends::secp256k1`, the only one; another stops the build. * @tparam Policy `crypto::verification_policies::low_s_only_t`; anything else stops the build. diff --git a/include/webcpp/crypto/detail/p_curves.hpp b/include/webcpp/crypto/detail/p_curves.hpp index b73f17e3..b2f7e3a0 100644 --- a/include/webcpp/crypto/detail/p_curves.hpp +++ b/include/webcpp/crypto/detail/p_curves.hpp @@ -112,8 +112,8 @@ template * of (n - 1) / 2 - s over every byte, the same arithmetic as `p_curve_scalar_valid`'s. The * verdict alone is declassified: a signature is public once it is made, but a constant-time * checker (memcheck, MemorySanitizer) still holds secret one computed from the secret scalar where - * `normalize_low_s` or `is_low_s` branches on this verdict; `sign` itself normalizes without a - * branch, with `p_curve_high_s_mask`. + * `is_low_s()` or `low_s()` of the signature branches on this verdict; `sign` itself normalizes + * without a branch, with `p_curve_high_s_mask`. * * @tparam Curve The curve's family tag. * @param s_bytes The signature's s, big-endian. diff --git a/include/webcpp/crypto/detail/signature.hpp b/include/webcpp/crypto/detail/signature.hpp index cf2deab2..ed6d43ef 100644 --- a/include/webcpp/crypto/detail/signature.hpp +++ b/include/webcpp/crypto/detail/signature.hpp @@ -40,7 +40,9 @@ struct signature_access; * alone, and by the `sign` of its curve and scheme. * * @tparam Tag The type's tag, an empty struct with `static constexpr bool recoverable`, true - * for a signature whose last byte is a recovery id. + * for a signature whose last byte is a recovery id, and `static constexpr bool ecdsa`, true for + * the tags of the ECDSA signatures, which also have the static functions `is_low_s` and `low_s` + * over the signature's bytes that the members of the same names call. * @tparam Size The signature's size in bytes. */ template @@ -91,6 +93,43 @@ class basic_signature { return signature_bytes_[Size - 1]; } + /** + * Whether the signature is in its low-S form: 0 < r < n and 0 < s <= (n - 1) / 2, n the + * group order, and for a recoverable signature a recovery id of 0 to 3. The verdict is + * arithmetic on public bytes; it does not verify the signature. Only an ECDSA signature has + * it (another's type has no such member), and a protocol that requires low S checks what it + * receives with it before `crypto::verify`, whose policy `low_s_only` refuses a high S too. + * + * @return Whether the signature is low S; false for an r or an s that is 0 or not below n. + */ + [[nodiscard]] bool is_low_s() const noexcept + requires Tag::ecdsa + { + return Tag::is_low_s(std::span(signature_bytes_)); + } + + /** + * The signature's low-S form: s replaced by n - s when it is above (n - 1) / 2, and a + * recoverable signature's recovery id with its bit 0 flipped then, so that it recovers the + * same key; a low-S signature is returned as it is. Both forms verify under `any_s`, and + * `sign` gives the low form already, so this is for a signature made elsewhere, such as + * WebCrypto's. Only an ECDSA signature has it. + * + * @return The low-S signature; `invalid_signature` when r or s is 0 or not below n, or a + * recovery id is above 3. + */ + [[nodiscard]] boost::system::result low_s() const noexcept + requires Tag::ecdsa + { + auto const low_form = Tag::low_s(std::span(signature_bytes_)); + if (low_form.has_error()) { + return low_form.error(); + } + basic_signature made_signature; + made_signature.signature_bytes_ = *low_form; + return made_signature; + } + /** * Whether two signatures hold the same bytes; a signature is public, so the comparison need * not take a constant time. diff --git a/test/Jamfile b/test/Jamfile index cd359fde..02abfc6d 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -396,6 +396,9 @@ webcpp.compile secp256k1_keccak_alone : secp256k1_keccak_alone_test.cpp crypto-run crypto_openssl_alone : crypto_openssl_alone_test.cpp : /webcpp/crypto//openssl : native wasip2 wasip3 ; crypto-run secp256k1 : secp256k1_test.cpp : /third_party//secp256k1 ; +# Low S as members of the ECDSA signatures: P-256's call no backend, secp256k1's enter +# libsecp256k1's, and a recoverable one's flips its recovery id with its s. +crypto-run signature_low_s : signature_low_s_test.cpp : /third_party//secp256k1 ; crypto-run secp256k1_allocation : secp256k1_allocation_test.cpp : /third_party//secp256k1 ; crypto-run secp256k1_bip340 : secp256k1_bip340_test.cpp diff --git a/test/allocation_bearssl_test.cpp b/test/allocation_bearssl_test.cpp index 5e0fbe4a..b98614a1 100644 --- a/test/allocation_bearssl_test.cpp +++ b/test/allocation_bearssl_test.cpp @@ -8,7 +8,7 @@ // equal and random_device's fill, ChaCha20-Poly1305's from_key, seal, open (good and failed) // and move, and P-256's key pair from_secret and generate, public key from_bytes and // from_coordinates, sign(ecdsa_sha256, ...) and crypto::verify of a message and of a digest, -// to_der, from_der, normalize_low_s, is_low_s, agree, encode_spki, decode_spki, encode_pkcs8 and +// to_der, from_der, low_s, is_low_s, agree, encode_spki, decode_spki, encode_pkcs8 and // decode_pkcs8 make no call of operator new, nor of the C library's allocator where the target lets // a program count it; a control proves the counter moves. @@ -77,8 +77,8 @@ void p256_calls() { if (BOOST_TEST(written.has_value())) { BOOST_TEST(p256::from_der(std::span(der).first(*written)).has_value()); } - BOOST_TEST(p256::normalize_low_s(*signature).has_value()); - BOOST_TEST(p256::is_low_s(*signature)); + BOOST_TEST(signature->low_s().has_value()); + BOOST_TEST(signature->is_low_s()); BOOST_TEST(pair->agree(*key).has_value()); std::array spki{}; std::array pkcs8{}; diff --git a/test/constant_time/paths.hpp b/test/constant_time/paths.hpp index 368cfa6a..21d1ef3c 100644 --- a/test/constant_time/paths.hpp +++ b/test/constant_time/paths.hpp @@ -802,7 +802,7 @@ int bearssl_p256_make() { * and made low S by `sign` without a branch (`detail::p_curve_high_s_mask`); then made low S and * checked low S again as a protocol that requires it does with a signature it has just made. * BearSSL's own branches on its verdicts, the scalar's decoding and the nonce's retry, are its - * function's (bearssl_verdicts.supp); `normalize_low_s` and `is_low_s` branch only on verdicts the + * function's (bearssl_verdicts.supp); `low_s` and `is_low_s` branch only on verdicts the * library declassifies, a signature being public once it is made (`detail::p_curve_low_s`). */ template @@ -821,12 +821,12 @@ int bearssl_p256_sign() { } int const failures = check(carries_mark(signature->bytes()), "P-256's sign on BearSSL, traced"); - auto const low = p256::normalize_low_s(*signature); + auto const low = signature->low_s(); // Not const: the mark changes the object in the checker's shadow, so it is read again. // NOLINTNEXTLINE(misc-const-correctness): see above - bool low_verdict = low.has_value() && p256::is_low_s(*low); + bool low_verdict = low.has_value() && low->is_low_s(); Checker::verdict(low_verdict); - return failures + check(low_verdict, "P-256's normalize_low_s and is_low_s"); + return failures + check(low_verdict, "P-256's low_s and is_low_s"); } /** diff --git a/test/crypto_secp256k1_test.cpp b/test/crypto_secp256k1_test.cpp index fa80e658..005a47f7 100644 --- a/test/crypto_secp256k1_test.cpp +++ b/test/crypto_secp256k1_test.cpp @@ -34,8 +34,6 @@ static_assert(webcpp::crypto::can_verify, secp::public_key>); -static_assert(std::is_function_v)>); -static_assert(std::is_function_v)>); static_assert(std::is_function_v)>); static_assert(std::is_function_v)>); static_assert(std::is_function_v)>); diff --git a/test/messages/Jamfile b/test/messages/Jamfile index bddb1d0f..d584a654 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -118,6 +118,7 @@ build-project verify_p256_secp256k1_signature ; build-project verify_schnorr_as_ecdsa ; build-project verify_ed25519_bytes_signature ; build-project recover_ecdsa_signature ; +build-project low_s_on_ed25519 ; build-project async_verify_p256_bytes_signature ; build-project sign_keccak_digest_20 ; build-project sign_p256_keccak ; diff --git a/test/messages/low_s_on_ed25519/Jamfile b/test/messages/low_s_on_ed25519/Jamfile new file mode 100644 index 00000000..5ba1e3d3 --- /dev/null +++ b/test/messages/low_s_on_ed25519/Jamfile @@ -0,0 +1,12 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +webcpp.compile-diagnostic low_s_on_ed25519 : low_s_on_ed25519.cpp + : : native wasip2 wasip3 : alone ; diff --git a/test/messages/low_s_on_ed25519/low_s_on_ed25519.cpp b/test/messages/low_s_on_ed25519/low_s_on_ed25519.cpp new file mode 100644 index 00000000..9107f1fe --- /dev/null +++ b/test/messages/low_s_on_ed25519/low_s_on_ed25519.cpp @@ -0,0 +1,16 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// An Ed25519 signature given low_s(): only an ECDSA signature has low S, so the member's +// constraint (Tag::ecdsa) is not satisfied and the call does not compile (design D10). + +#include + +int main() { + webcpp::crypto::curves::ed25519::signature const signature{}; + // expected-error@+1 {{invalid reference to function 'low_s': constraints not satisfied}} + return signature.low_s().has_value() ? 0 : 1; +} diff --git a/test/msvc/Jamfile b/test/msvc/Jamfile index 42adf1e6..a03406d1 100644 --- a/test/msvc/Jamfile +++ b/test/msvc/Jamfile @@ -45,6 +45,7 @@ build-project memory_two_files ; build-project sodium_not_linked ; build-project canary_sodium_other_commit ; build-project ed25519_on_bearssl ; +build-project low_s_on_ed25519 ; build-project ed25519ph_sha256 ; build-project ed25519_default_not_linked ; build-project heavy_without_threads ; diff --git a/test/msvc/low_s_on_ed25519/Jamfile b/test/msvc/low_s_on_ed25519/Jamfile new file mode 100644 index 00000000..39e04c26 --- /dev/null +++ b/test/msvc/low_s_on_ed25519/Jamfile @@ -0,0 +1,9 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail low_s_on_ed25519 : app.cpp : /webcpp/crypto//crypto : native ; diff --git a/test/msvc/low_s_on_ed25519/app.cpp b/test/msvc/low_s_on_ed25519/app.cpp new file mode 100644 index 00000000..143cc04b --- /dev/null +++ b/test/msvc/low_s_on_ed25519/app.cpp @@ -0,0 +1,14 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// An Ed25519 signature given low_s(): only an ECDSA signature has low S, so the call does not +// compile on MSVC. The text is checked on clang, in test/messages/low_s_on_ed25519. +#include + +int main() { + webcpp::crypto::curves::ed25519::signature const signature{}; + return signature.low_s().has_value() ? 0 : 1; +} diff --git a/test/p256_ecdsa_bearssl_test.cpp b/test/p256_ecdsa_bearssl_test.cpp index d0ba14ab..3c90680c 100644 --- a/test/p256_ecdsa_bearssl_test.cpp +++ b/test/p256_ecdsa_bearssl_test.cpp @@ -12,7 +12,7 @@ // high one refused under low_s_only, and every refusal (a bit of the digest, of r or of s, another // key, r or s 0 or n), and the digests 0 modulo n // that BearSSL refuses; a 32-byte message hashed, never read as a digest; the empty message; -// is_low_s and normalize_low_s at their boundary; low S over 1,000 signatures of random digests +// is_low_s and low_s at their boundary; low S over 1,000 signatures of random digests // under a key and 256 of random messages under keys of their own, all drawn from a printed seed // that a define replays; DER both ways against encodings written by hand, the short buffer, the // strict decoder's refusals and integers shorter than 32 bytes, typed both ways. @@ -193,7 +193,7 @@ void sign_normalizes_raw_s() { // RFC 6979, section A.2.5, the message "sample" itself, hashed inside sign: the section's r, and // n - s for the section's s, which is high; crypto::verify accepts the section's own high-S // signature, made with from_bytes as one received is, as well as sign's; is_low_s tells the two -// apart, and normalize_low_s of the section's signature is sign's. +// apart, and low_s of the section's signature is sign's. void rfc6979_sample_message() { auto const key = keypair::from_secret(data::rfc6979_scalar); auto const verifier = public_key::from_bytes(data::rfc6979_public); @@ -227,9 +227,9 @@ void rfc6979_sample_message() { crypto::verification_policies::low_s_only, *signed_message, text_bytes("sample"), *verifier) .has_value()); - BOOST_TEST(!p256::is_low_s(section)); - BOOST_TEST(p256::is_low_s(*signed_message)); - auto const normalized = p256::normalize_low_s(section); + BOOST_TEST(!section.is_low_s()); + BOOST_TEST(signed_message->is_low_s()); + auto const normalized = section.low_s(); if (BOOST_TEST(normalized.has_value())) { BOOST_TEST(*normalized == *signed_message); } @@ -373,14 +373,14 @@ void zero_digest() { } void low_s() { - BOOST_TEST(!p256::is_low_s(typed(data::rfc6979_sample))); - BOOST_TEST(p256::is_low_s(typed(data::rfc6979_sample_low_s))); - BOOST_TEST(p256::is_low_s(typed(data::rfc6979_test))); - auto const normalized = p256::normalize_low_s(typed(data::rfc6979_sample)); + BOOST_TEST(!typed(data::rfc6979_sample).is_low_s()); + BOOST_TEST(typed(data::rfc6979_sample_low_s).is_low_s()); + BOOST_TEST(typed(data::rfc6979_test).is_low_s()); + auto const normalized = typed(data::rfc6979_sample).low_s(); if (BOOST_TEST(normalized.has_value())) { BOOST_TEST(normalized->bytes() == data::rfc6979_sample_low_s); } - auto const unchanged = p256::normalize_low_s(typed(data::rfc6979_test)); + auto const unchanged = typed(data::rfc6979_test).low_s(); if (BOOST_TEST(unchanged.has_value())) { BOOST_TEST(unchanged->bytes() == data::rfc6979_test); } @@ -390,9 +390,9 @@ void low_s() { auto const half = typed(joined(r, data::half_order)); auto above_half = data::half_order; ++above_half.back(); // ends with a8: no carry - BOOST_TEST(p256::is_low_s(half)); - BOOST_TEST(!p256::is_low_s(typed(joined(r, above_half)))); - auto const lowered = p256::normalize_low_s(typed(joined(r, above_half))); + BOOST_TEST(half.is_low_s()); + BOOST_TEST(!typed(joined(r, above_half)).is_low_s()); + auto const lowered = typed(joined(r, above_half)).low_s(); if (BOOST_TEST(lowered.has_value())) { BOOST_TEST(*lowered == half); } @@ -401,8 +401,8 @@ void low_s() { auto const s = s_of(data::rfc6979_test); for (auto const& out_of_range : {joined(zero, s), joined(r, zero), joined(data::order, s), joined(r, data::order)}) { - BOOST_TEST(p256::normalize_low_s(typed(out_of_range)).error() == error::invalid_signature); - BOOST_TEST(!p256::is_low_s(typed(out_of_range))); + BOOST_TEST(typed(out_of_range).low_s().error() == error::invalid_signature); + BOOST_TEST(!typed(out_of_range).is_low_s()); } } @@ -435,7 +435,7 @@ keypair drawn_keypair(std::mt19937_64& generator) { } // 1,000 signatures of random digests under a key: each low S, verified, and its high-S form, -// n - s, verified too, is_low_s false on it, and normalize_low_s of it gives the signature back. +// n - s, verified too, is_low_s false on it, and low_s of it gives the signature back. void low_s_random(std::uint64_t seed) { std::mt19937_64 generator(seed); auto const key = drawn_keypair(generator); @@ -451,13 +451,13 @@ void low_s_random(std::uint64_t seed) { if (!BOOST_TEST(signed_hash.has_value())) { return; } - BOOST_TEST(p256::is_low_s(*signed_hash)); + BOOST_TEST(signed_hash->is_low_s()); BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::low_s_only, *signed_hash, crypto::signing_schemes::prehashed{hash}, *verifier) .has_value()); auto const high = typed(joined(r_of(*signed_hash), negated(s_of(*signed_hash)))); - BOOST_TEST(!p256::is_low_s(high)); + BOOST_TEST(!high.is_low_s()); BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::any_s, high, crypto::signing_schemes::prehashed{hash}, *verifier) @@ -466,7 +466,7 @@ void low_s_random(std::uint64_t seed) { crypto::verification_policies::low_s_only, high, crypto::signing_schemes::prehashed{hash}, *verifier) .error() == error::invalid_signature); - auto const normalized = p256::normalize_low_s(high); + auto const normalized = high.low_s(); if (!BOOST_TEST(normalized.has_value())) { return; } @@ -487,7 +487,7 @@ void always_low_s(std::uint64_t seed) { if (!BOOST_TEST(signed_message.has_value()) || !BOOST_TEST(verifier.has_value())) { return; } - BOOST_TEST(p256::is_low_s(*signed_message)); + BOOST_TEST(signed_message->is_low_s()); BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::low_s_only, *signed_message, message, *verifier) diff --git a/test/p256_openssl_oracle_test.cpp b/test/p256_openssl_oracle_test.cpp index 10b21f4e..711182cf 100644 --- a/test/p256_openssl_oracle_test.cpp +++ b/test/p256_openssl_oracle_test.cpp @@ -12,7 +12,7 @@ // EVP_PKEY_fromdata), OpenSSL's point equal to ours; a random 32-byte digest; OpenSSL signs it // with RFC 6979's nonce over SHA-256 (the parameters `nonce-type` 1 and `digest` "SHA256", // OpenSSL 3.2 and later), and its DER signature through from_der, made low S by -// normalize_low_s, equals the bytes of sign(ecdsa_sha256, prehashed{digest}), which signs low +// low_s, equals the bytes of sign(ecdsa_sha256, prehashed{digest}), which signs low // S; OpenSSL verifies to_der of ours, and crypto::verify accepts OpenSSL's as it signed it, // high S or low. // - ECDH: two random key pairs; EVP_PKEY_derive of the first with the second's public key equals @@ -326,7 +326,7 @@ bool signature_case(std::mt19937_64& generator, std::size_t index) { BOOST_TEST(openssl_point(key.get()) == bytes_of(public_key->uncompressed())); bytes const theirs_der = openssl_sign(key.get(), digest); auto const theirs = p256::from_der(theirs_der); - auto const theirs_low = theirs ? p256::normalize_low_s(*theirs) : theirs; + auto const theirs_low = theirs ? theirs->low_s() : theirs; bool const same_signature = BOOST_TEST(theirs_low.has_value()) && BOOST_TEST(*theirs_low == *ours); std::array der{}; diff --git a/test/p256_webcrypto_oracle_test.cpp b/test/p256_webcrypto_oracle_test.cpp index 6b669114..78585ee2 100644 --- a/test/p256_webcrypto_oracle_test.cpp +++ b/test/p256_webcrypto_oracle_test.cpp @@ -264,7 +264,7 @@ void judge(our_case const& ours, oracle_answer const& answer, p256::public_key c *theirs, crypto::signing_schemes::prehashed{ours.digest}, public_key) .has_value(); found.check(we_verify, "we verify WebCrypto's", index); - if (ran && theirs.has_value() && p256::is_low_s(*theirs)) { + if (ran && theirs.has_value() && theirs->is_low_s()) { ++found.low_s; } found.check(ran && bytes_of(answer.shared) == ours.shared_x, "ECDH", index); @@ -305,7 +305,7 @@ void one_case(std::mt19937_64& rng, std::size_t index, tally& found) { if (!BOOST_TEST(signature.has_value()) || !BOOST_TEST(shared.has_value())) { return; } - BOOST_TEST(p256::is_low_s(*signature)); + BOOST_TEST(signature->is_low_s()); BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::any_s, *signature, ours.message, *public_key) diff --git a/test/p256_wycheproof_bearssl_test.cpp b/test/p256_wycheproof_bearssl_test.cpp index de48cbf9..e9ebccf1 100644 --- a/test/p256_wycheproof_bearssl_test.cpp +++ b/test/p256_wycheproof_bearssl_test.cpp @@ -123,7 +123,7 @@ counts run(std::string const& name, Decode decode) { ++seen.valid; if (!verified) { report(name, t, "valid signature refused"); - } else if (!p256::is_low_s(*decoded)) { + } else if (!decoded->is_low_s()) { ++seen.valid_high_s; } } else if (verdict == "invalid") { diff --git a/test/secp256k1_allocation_test.cpp b/test/secp256k1_allocation_test.cpp index 1b17134f..d7623799 100644 --- a/test/secp256k1_allocation_test.cpp +++ b/test/secp256k1_allocation_test.cpp @@ -260,8 +260,8 @@ int main() { }); auto const encoded = std::span(der).first(der_size); none("from_der", [&] { return secp::from_der(encoded); }); - none("normalize_low_s", [&] { return secp::normalize_low_s(*ecdsa); }); - none("is_low_s", [&] { return secp::is_low_s(*ecdsa); }); + none("low_s", [&] { return ecdsa->low_s(); }); + none("is_low_s", [&] { return ecdsa->is_low_s(); }); none("tweak_xonly", [&] { return secp::tweak_xonly(xonly, message); }); auto const parsed = secp::public_key::from_bytes(uncompressed); none("public_key::from_bytes", [&] { return secp::public_key::from_bytes(compressed); }); diff --git a/test/secp256k1_der_test.cpp b/test/secp256k1_der_test.cpp index 7c895ee7..a9fd6e6e 100644 --- a/test/secp256k1_der_test.cpp +++ b/test/secp256k1_der_test.cpp @@ -157,19 +157,18 @@ void normalization() { BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::low_s_only, high, digest, public_key) .error() == crypto::error::invalid_signature); - auto const normalized = secp::normalize_low_s(high); + auto const normalized = high.low_s(); BOOST_TEST(normalized.has_value() && *normalized == signature); BOOST_TEST(normalized.has_value() && crypto::verify(crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::low_s_only, *normalized, digest, public_key)); // Already low-S: unchanged. - auto const again = secp::normalize_low_s(signature); + auto const again = signature.low_s(); BOOST_TEST(again.has_value() && *again == signature); // Not a signature. std::array overflowing{}; overflowing.fill(0xff); - BOOST_TEST(secp::normalize_low_s(typed(overflowing)).error() == - crypto::error::invalid_signature); + BOOST_TEST(typed(overflowing).low_s().error() == crypto::error::invalid_signature); } // A compact signature of r and s, each a 32-byte big-endian number given in hex. @@ -190,8 +189,8 @@ void low_s_answers() { hash.fill(0x51); auto const signature = *key.sign(crypto::signing_schemes::ecdsa_sha256, crypto::signing_schemes::prehashed{hash}); - BOOST_TEST(secp::is_low_s(signature)); - BOOST_TEST(!secp::is_low_s(typed(test::negate_s(signature.bytes())))); + BOOST_TEST(signature.is_low_s()); + BOOST_TEST(!typed(test::negate_s(signature.bytes())).is_low_s()); constexpr std::string_view one = "0000000000000000000000000000000000000000000000000000000000000001"; constexpr std::string_view zero = @@ -204,18 +203,18 @@ void low_s_answers() { "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"; constexpr std::string_view below_order = "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140"; - BOOST_TEST(secp::is_low_s(compact_of(one, one))); - BOOST_TEST(secp::is_low_s(compact_of(one, half))); - BOOST_TEST(!secp::is_low_s(compact_of(one, above_half))); - BOOST_TEST(!secp::is_low_s(compact_of(one, below_order))); - BOOST_TEST(secp::is_low_s(compact_of(below_order, one))); - BOOST_TEST(!secp::is_low_s(compact_of(zero, one))); - BOOST_TEST(!secp::is_low_s(compact_of(one, zero))); - BOOST_TEST(!secp::is_low_s(compact_of(order, one))); - BOOST_TEST(!secp::is_low_s(compact_of(one, order))); + BOOST_TEST(compact_of(one, one).is_low_s()); + BOOST_TEST(compact_of(one, half).is_low_s()); + BOOST_TEST(!compact_of(one, above_half).is_low_s()); + BOOST_TEST(!compact_of(one, below_order).is_low_s()); + BOOST_TEST(compact_of(below_order, one).is_low_s()); + BOOST_TEST(!compact_of(zero, one).is_low_s()); + BOOST_TEST(!compact_of(one, zero).is_low_s()); + BOOST_TEST(!compact_of(order, one).is_low_s()); + BOOST_TEST(!compact_of(one, order).is_low_s()); std::array all_ones{}; all_ones.fill(0xff); - BOOST_TEST(!secp::is_low_s(typed(all_ones))); + BOOST_TEST(!typed(all_ones).is_low_s()); } // How many of a flag's cases the strict decoder accepts. diff --git a/test/secp256k1_ethereum_test.cpp b/test/secp256k1_ethereum_test.cpp index 7a067b02..38e6d028 100644 --- a/test/secp256k1_ethereum_test.cpp +++ b/test/secp256k1_ethereum_test.cpp @@ -293,7 +293,7 @@ void always_low_s() { if (!BOOST_TEST(signature.has_value())) { return; } - BOOST_TEST(secp::is_low_s(ecdsa_of(*signature))); + BOOST_TEST(ecdsa_of(*signature).is_low_s()); BOOST_TEST(signature->recovery_id() <= 3); auto const recovered = secp::recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, crypto::verification_policies::low_s_only, *signature, @@ -315,7 +315,7 @@ void high_s_refused() { std::ranges::copy(s_value, high_bytes.begin() + 32); high_bytes[64] ^= 1U; auto const high = typed(high_bytes); - BOOST_TEST(!secp::is_low_s(ecdsa_of(high))); + BOOST_TEST(!ecdsa_of(high).is_low_s()); auto const refused = secp::recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, crypto::verification_policies::low_s_only, high, crypto::signing_schemes::prehashed{geth_message}); diff --git a/test/secp256k1_test.cpp b/test/secp256k1_test.cpp index dbcc0605..8b18a96b 100644 --- a/test/secp256k1_test.cpp +++ b/test/secp256k1_test.cpp @@ -232,10 +232,10 @@ void ecdsa() { .has_value()); // Low-S: s is at most half the group order, so its first byte is below 0x80. BOOST_TEST(signature->bytes()[32] < 0x80); - BOOST_TEST(secp::is_low_s(*signature)); + BOOST_TEST(signature->is_low_s()); // The high-S form of the same signature is refused, as libsecp256k1's verify refuses it. auto const high = typed(webcpp::test::negate_s(signature->bytes())); - BOOST_TEST(!secp::is_low_s(high)); + BOOST_TEST(!high.is_low_s()); BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::low_s_only, high, crypto::signing_schemes::prehashed{hash}, *public_key) @@ -550,7 +550,7 @@ static_assert(std::is_same_v().sign( std::declval>())), boost::system::result>); static_assert( - std::is_same_v())), bool>); + std::is_same_v().is_low_s()), bool>); // The three agreements of two key pairs agree; agree is agree_point's x, and agree_hashed is // libsecp256k1's own secp256k1_ecdh with its default hash; the peer's uncompressed form makes the diff --git a/test/signature_low_s_test.cpp b/test/signature_low_s_test.cpp new file mode 100644 index 00000000..7092bd78 --- /dev/null +++ b/test/signature_low_s_test.cpp @@ -0,0 +1,275 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Low S as members of the ECDSA signatures (design D10, R29): `is_low_s()` and `low_s()` of +// curves::p256::ecdsa_signature, curves::secp256k1::ecdsa_signature and +// curves::secp256k1::recoverable_signature. RFC 6979 A.2.5's high "sample" signature on P-256 and +// a secp256k1 signature of `sign` with its s replaced by n - s: `is_low_s()` false, `low_s()` the +// original, `is_low_s()` true after; a low signature's `low_s()` is itself; an r or an s of 0 or +// n is `invalid_signature` (a recoverable id above 3 too); a recoverable signature's `low_s()` +// flips its recovery id, and `recover` under `low_s_only` of the result gives the signer's key. +// P-256's members call no backend (the seam's recorder stays empty). An Ed25519 signature has no +// such member (test/messages/low_s_on_ed25519). + +#include "support/timing_seam.hpp" + +#include +#include +#include +#include +#include +#include + +#include "support/hex.hpp" +#include "support/p256_data.hpp" +#include "support/secp256k1_data.hpp" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace crypto = webcpp::crypto; +namespace p256 = webcpp::crypto::curves::p256; +namespace secp = webcpp::crypto::curves::secp256k1; +namespace test = webcpp::test; + +namespace { + +using bytes32 = std::array; + +template +concept has_low_s = requires(Signature const& value) { + value.is_low_s(); + value.low_s(); +}; + +// An Ed25519 signature and a Schnorr one have no low S: the members' constraint is not satisfied. +static_assert(!has_low_s); +static_assert(!has_low_s); +static_assert(has_low_s); +static_assert(has_low_s); +static_assert(has_low_s); +static_assert( + std::is_same_v().is_low_s()), bool>); +static_assert(std::is_same_v().low_s()), + boost::system::result>); + +// secp256k1's group order n and (n - 1) / 2, SEC 2. +bytes32 const secp_order = + test::hex<32>("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); +bytes32 const secp_half_order = + test::hex<32>("7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0"); + +/** Adds one to a big-endian number, which does not overflow in these tests. */ +bytes32 plus_one(bytes32 value) { + for (std::size_t index = value.size(); index-- > 0;) { + if (++value[index] != 0) { + break; + } + } + return value; +} + +/** A signature of the type from r and s, and the recovery id where the type has one. */ +template +Signature made(bytes32 const& r_value, bytes32 const& s_value, std::uint8_t recovery_id = 0) { + std::array wire_bytes{}; + std::ranges::copy(r_value, wire_bytes.begin()); + std::ranges::copy(s_value, wire_bytes.begin() + 32); + if constexpr (Signature::size == 65) { + wire_bytes[64] = recovery_id; + } + auto const signature = Signature::from_bytes(wire_bytes); + BOOST_TEST(signature.has_value()); + return signature ? *signature : Signature{}; +} + +bytes32 const one = [] { + bytes32 value{}; + value.back() = 1; + return value; +}(); +bytes32 const zero{}; + +/** + * The boundaries of one curve: s at (n - 1) / 2 is low and one above it is not; r and s of 0 and + * of n are out of range, so that `is_low_s()` is false and `low_s()` is `invalid_signature`. + */ +template +void boundaries(bytes32 const& order, bytes32 const& half_order) { + BOOST_TEST(made(one, one).is_low_s()); + BOOST_TEST(made(one, half_order).is_low_s()); + BOOST_TEST(!made(one, plus_one(half_order)).is_low_s()); + auto const above_half = made(one, plus_one(half_order)).low_s(); + if (BOOST_TEST(above_half.has_value())) { + // n - ((n - 1) / 2 + 1) = (n - 1) / 2: the other side of the boundary. + BOOST_TEST(above_half->is_low_s()); + // The recovery id of a recoverable signature is the one flipped with s. + BOOST_TEST( + std::ranges::equal(made(one, half_order).bytes() | std::views::take(64), + above_half->bytes() | std::views::take(64))); + } + auto const lowest = made(one, one).low_s(); + BOOST_TEST(lowest.has_value() && *lowest == made(one, one)); + for (auto const& bad : {made(zero, one), made(one, zero), + made(order, one), made(one, order), + made(zero, zero), made(order, order)}) { + BOOST_TEST(!bad.is_low_s()); + BOOST_TEST(bad.low_s().error() == crypto::error::invalid_signature); + } +} + +/** P-256: RFC 6979 A.2.5's high "sample", its low form, and "test", which is low. */ +void p256_members() { + auto const sample = p256::ecdsa_signature::from_bytes(test::p256::rfc6979_sample); + auto const sample_low = p256::ecdsa_signature::from_bytes(test::p256::rfc6979_sample_low_s); + auto const low = p256::ecdsa_signature::from_bytes(test::p256::rfc6979_test); + if (!BOOST_TEST(sample.has_value()) || !BOOST_TEST(sample_low.has_value()) || + !BOOST_TEST(low.has_value())) { + return; + } + // The members call no backend, and hold no guard of crypto's. + test::uncovered("p256::ecdsa_signature::is_low_s of a high signature", + [&] { BOOST_TEST(!sample->is_low_s()); }); + test::uncovered("p256::ecdsa_signature::low_s of a high signature", [&] { + auto const lowered = sample->low_s(); + BOOST_TEST(lowered.has_value() && *lowered == *sample_low); + }); + test::uncovered("p256::ecdsa_signature::low_s of an out-of-range signature", [&] { + BOOST_TEST(made(zero, one).low_s().error() == + crypto::error::invalid_signature); + }); + BOOST_TEST(sample_low->is_low_s()); + BOOST_TEST(low->is_low_s()); + auto const unchanged = low->low_s(); + BOOST_TEST(unchanged.has_value() && *unchanged == *low); + auto const again = sample_low->low_s(); + BOOST_TEST(again.has_value() && *again == *sample_low); + // low_s() is idempotent, and its result is low. + auto const lowered = sample->low_s(); + if (BOOST_TEST(lowered.has_value())) { + BOOST_TEST(lowered->is_low_s()); + BOOST_TEST(lowered->low_s().value() == *lowered); + } + boundaries(test::p256::order, test::p256::half_order); +} + +/** secp256k1's key pair, which signs. */ +boost::system::result signer() { + bytes32 secret{}; + for (std::size_t index = 0; index < secret.size(); ++index) { + secret[index] = static_cast(index + 0x21); + } + return secp::keypair::from_secret(secret); +} + +bytes32 const digest = [] { + bytes32 value{}; + value.fill(0x5e); + return value; +}(); + +/** secp256k1's ECDSA signature: sign's, its high twin, and the members between them. */ +void secp256k1_ecdsa_members() { + auto const key_pair = signer(); + if (!BOOST_TEST(key_pair.has_value())) { + return; + } + auto const original = key_pair->sign(crypto::signing_schemes::ecdsa_sha256, + crypto::signing_schemes::prehashed{digest}); + if (!BOOST_TEST(original.has_value())) { + return; + } + auto const high = secp::ecdsa_signature::from_bytes(test::negate_s(original->bytes())); + if (!BOOST_TEST(high.has_value())) { + return; + } + BOOST_TEST(original->is_low_s()); + BOOST_TEST(!high->is_low_s()); + auto const lowered = high->low_s(); + BOOST_TEST(lowered.has_value() && *lowered == *original); + BOOST_TEST(lowered.has_value() && lowered->is_low_s()); + auto const unchanged = original->low_s(); + BOOST_TEST(unchanged.has_value() && *unchanged == *original); + boundaries(secp_order, secp_half_order); +} + +/** secp256k1's recoverable signature: low_s() flips the id with s, and the signer is recovered. */ +void secp256k1_recoverable_members() { + auto const key_pair = signer(); + if (!BOOST_TEST(key_pair.has_value())) { + return; + } + auto const signer_key = key_pair->public_key(); + auto const original = key_pair->sign(crypto::signing_schemes::ecdsa_sha256_recoverable, + crypto::signing_schemes::prehashed{digest}); + if (!BOOST_TEST(signer_key.has_value()) || !BOOST_TEST(original.has_value())) { + return; + } + auto high_bytes = original->bytes(); + auto const negated = test::negate_s(std::span(high_bytes).first<64>()); + std::ranges::copy(negated, high_bytes.begin()); + high_bytes[64] ^= 1U; + auto const high = secp::recoverable_signature::from_bytes(high_bytes); + if (!BOOST_TEST(high.has_value())) { + return; + } + BOOST_TEST(original->is_low_s()); + BOOST_TEST(!high->is_low_s()); + auto const refused = secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, + crypto::verification_policies::low_s_only, *high, + crypto::signing_schemes::prehashed{digest}); + BOOST_TEST(refused.has_error() && refused.error() == crypto::error::invalid_signature); + auto const lowered = high->low_s(); + if (BOOST_TEST(lowered.has_value())) { + // The high form's id with bit 0 flipped is the original's, and so is every other byte. + BOOST_TEST(*lowered == *original); + BOOST_TEST(lowered->is_low_s()); + auto const recovered = secp::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, + crypto::verification_policies::low_s_only, *lowered, + crypto::signing_schemes::prehashed{digest}); + BOOST_TEST(recovered.has_value() && *recovered == *signer_key); + } + auto const unchanged = original->low_s(); + BOOST_TEST(unchanged.has_value() && *unchanged == *original); + boundaries(secp_order, secp_half_order); + // The id above 3 is refused by both members, with a low s. + for (unsigned id : {4U, 5U, 255U}) { + auto const bad = made(one, one, static_cast(id)); + BOOST_TEST(!bad.is_low_s()); + BOOST_TEST(bad.low_s().error() == crypto::error::invalid_signature); + } + for (unsigned id : {0U, 1U, 2U, 3U}) { + auto const fine = + made(one, one, static_cast(id)); + BOOST_TEST(fine.is_low_s()); + BOOST_TEST(fine.low_s().value() == fine); + // A high s with id 2 or 3 flips to 3 or 2. + auto const high_s = made(one, plus_one(secp_half_order), + static_cast(id)); + auto const flipped = high_s.low_s(); + BOOST_TEST(flipped.has_value() && flipped->recovery_id() == (id ^ 1U)); + } +} + +} // namespace + +int main() { + p256_members(); + secp256k1_ecdsa_members(); + secp256k1_recoverable_members(); + 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 0383d96d..0329e22e 100644 --- a/test/timing_coverage_bearssl_test.cpp +++ b/test/timing_coverage_bearssl_test.cpp @@ -27,7 +27,7 @@ // 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 +// encode_pkcs8, basic_keypair's move constructor and move assignment, and 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 diff --git a/test/timing_coverage_secp256k1_test.cpp b/test/timing_coverage_secp256k1_test.cpp index ec32ea1c..ccf3bc97 100644 --- a/test/timing_coverage_secp256k1_test.cpp +++ b/test/timing_coverage_secp256k1_test.cpp @@ -28,12 +28,12 @@ // 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 +// key and against x-only bytes), to_der, from_der, the ECDSA signatures' low_s and 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, @@ -578,24 +578,43 @@ void cover_signature_forms() { }); } -/** ECDSA's low-S functions, a refusal of each. */ +/** The ECDSA signatures' low-S members, a refusal of each. */ void cover_low_s() { auto const signer = keypair_of(0x62); auto const ecdsa = signer.sign(crypto::signing_schemes::ecdsa_sha256, crypto::signing_schemes::prehashed{secret_bytes(0x5e)}); - if (!BOOST_TEST(ecdsa.has_value())) { + auto const recoverable = signer.sign(crypto::signing_schemes::ecdsa_sha256_recoverable, + crypto::signing_schemes::prehashed{secret_bytes(0x5e)}); + if (!BOOST_TEST(ecdsa.has_value()) || !BOOST_TEST(recoverable.has_value())) { return; } 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)); }); - covered("secp256k1::normalize_low_s of a zero signature on secp256k1", [&] { - BOOST_TEST(secp::normalize_low_s(zero_signature).error() == - crypto::error::invalid_signature); - }); - covered("secp256k1::is_low_s of a zero signature on secp256k1", - [&] { BOOST_TEST(!secp::is_low_s(zero_signature)); }); + secp::recoverable_signature const zero_recoverable{}; + constexpr char const* ecdsa_tag = "secp256k1_ecdsa_signature_tag::"; + constexpr char const* recoverable_tag = "secp256k1_recoverable_signature_tag::"; + covered("secp256k1::ecdsa_signature::low_s on secp256k1", std::string(ecdsa_tag) + "low_s", + [&] { BOOST_TEST(ecdsa->low_s().has_value()); }); + covered("secp256k1::ecdsa_signature::is_low_s on secp256k1", + std::string(ecdsa_tag) + "is_low_s", [&] { BOOST_TEST(ecdsa->is_low_s()); }); + covered("secp256k1::ecdsa_signature::low_s of a zero signature on secp256k1", + std::string(ecdsa_tag) + "low_s", [&] { + BOOST_TEST(zero_signature.low_s().error() == crypto::error::invalid_signature); + }); + covered("secp256k1::ecdsa_signature::is_low_s of a zero signature on secp256k1", + std::string(ecdsa_tag) + "is_low_s", [&] { BOOST_TEST(!zero_signature.is_low_s()); }); + covered("secp256k1::recoverable_signature::low_s on secp256k1", + std::string(recoverable_tag) + "low_s", + [&] { BOOST_TEST(recoverable->low_s().has_value()); }); + covered("secp256k1::recoverable_signature::is_low_s on secp256k1", + std::string(recoverable_tag) + "is_low_s", + [&] { BOOST_TEST(recoverable->is_low_s()); }); + covered("secp256k1::recoverable_signature::low_s of a zero signature on secp256k1", + std::string(recoverable_tag) + "low_s", [&] { + BOOST_TEST(zero_recoverable.low_s().error() == crypto::error::invalid_signature); + }); + covered("secp256k1::recoverable_signature::is_low_s of a zero signature on secp256k1", + std::string(recoverable_tag) + "is_low_s", + [&] { BOOST_TEST(!zero_recoverable.is_low_s()); }); } // --------------------------------------------------------------------------------------------- diff --git a/test/timing_test.cpp b/test/timing_test.cpp index 6ed62281..d40340c8 100644 --- a/test/timing_test.cpp +++ b/test/timing_test.cpp @@ -10,7 +10,7 @@ // crypto's guards by their file 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. 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 +// on one thread leaves another's DIT clear. P-256's low_s and is_low_s, which call no // backend, enter no guard of crypto's: this program links none, and curves/p256.hpp needs none to // declare them; secure's erase_secret, which only stores zeroes, enters no guard at all. @@ -285,11 +285,12 @@ void p256_low_s_unguarded() { 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); + webcpp::test::uncovered("p256::ecdsa_signature::low_s", [&sample] { + auto const normalized = sample->low_s(); 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)); }); + webcpp::test::uncovered("p256::ecdsa_signature::is_low_s", + [&test] { BOOST_TEST(test->is_low_s()); }); } // secure's erase_secret, which crypto's code calls to wipe, calls no backend: it stores zeroes, and From 6655a3b7dedf904e916b6ab406ae80c04ce30ef2 Mon Sep 17 00:00:00 2001 From: R Date: Mon, 30 Nov 2026 23:06:09 -0300 Subject: [PATCH 12/81] crypto: low S members lint fix --- include/webcpp/crypto/detail/signature.hpp | 3 +- test/Jamfile | 4 +- test/signature_low_s_test.cpp | 60 +++++++++++++--------- 3 files changed, 39 insertions(+), 28 deletions(-) diff --git a/include/webcpp/crypto/detail/signature.hpp b/include/webcpp/crypto/detail/signature.hpp index ed6d43ef..11beeeb9 100644 --- a/include/webcpp/crypto/detail/signature.hpp +++ b/include/webcpp/crypto/detail/signature.hpp @@ -126,7 +126,8 @@ class basic_signature { return low_form.error(); } basic_signature made_signature; - made_signature.signature_bytes_ = *low_form; + // The result holds a value: its pointer reads it without the check that throws. + std::copy(low_form->begin(), low_form->end(), made_signature.signature_bytes_.begin()); return made_signature; } diff --git a/test/Jamfile b/test/Jamfile index 02abfc6d..e34c946d 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -396,8 +396,8 @@ webcpp.compile secp256k1_keccak_alone : secp256k1_keccak_alone_test.cpp crypto-run crypto_openssl_alone : crypto_openssl_alone_test.cpp : /webcpp/crypto//openssl : native wasip2 wasip3 ; crypto-run secp256k1 : secp256k1_test.cpp : /third_party//secp256k1 ; -# Low S as members of the ECDSA signatures: P-256's call no backend, secp256k1's enter -# libsecp256k1's, and a recoverable one's flips its recovery id with its s. +# Low S as members of the ECDSA signatures: P-256's call no backend, secp256k1's +# enter libsecp256k1's, and a recoverable one's flips its recovery id with s. crypto-run signature_low_s : signature_low_s_test.cpp : /third_party//secp256k1 ; crypto-run secp256k1_allocation : secp256k1_allocation_test.cpp : /third_party//secp256k1 ; diff --git a/test/signature_low_s_test.cpp b/test/signature_low_s_test.cpp index 7092bd78..f74f0b1f 100644 --- a/test/signature_low_s_test.cpp +++ b/test/signature_low_s_test.cpp @@ -68,9 +68,9 @@ static_assert(std::is_same_v>); // secp256k1's group order n and (n - 1) / 2, SEC 2. -bytes32 const secp_order = +constexpr bytes32 secp_order = test::hex<32>("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); -bytes32 const secp_half_order = +constexpr bytes32 secp_half_order = test::hex<32>("7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0"); /** Adds one to a big-endian number, which does not overflow in these tests. */ @@ -97,12 +97,12 @@ Signature made(bytes32 const& r_value, bytes32 const& s_value, std::uint8_t reco return signature ? *signature : Signature{}; } -bytes32 const one = [] { +constexpr bytes32 one = [] { bytes32 value{}; value.back() = 1; return value; }(); -bytes32 const zero{}; +constexpr bytes32 zero{}; /** * The boundaries of one curve: s at (n - 1) / 2 is low and one above it is not; r and s of 0 and @@ -124,9 +124,14 @@ void boundaries(bytes32 const& order, bytes32 const& half_order) { } auto const lowest = made(one, one).low_s(); BOOST_TEST(lowest.has_value() && *lowest == made(one, one)); - for (auto const& bad : {made(zero, one), made(one, zero), - made(order, one), made(one, order), - made(zero, zero), made(order, order)}) { + for (auto const& bad : { + made(zero, one), + made(one, zero), + made(order, one), + made(one, order), + made(zero, zero), + made(order, order), + }) { BOOST_TEST(!bad.is_low_s()); BOOST_TEST(bad.low_s().error() == crypto::error::invalid_signature); } @@ -176,7 +181,7 @@ boost::system::result signer() { return secp::keypair::from_secret(secret); } -bytes32 const digest = [] { +constexpr bytes32 digest = [] { bytes32 value{}; value.fill(0x5e); return value; @@ -207,6 +212,27 @@ void secp256k1_ecdsa_members() { boundaries(secp_order, secp_half_order); } +/** The recovery ids: above 3 refused by both members, and a high s flips the id's bit 0. */ +void recovery_ids() { + // The id above 3 is refused by both members, with a low s. + for (unsigned const id : {4U, 5U, 255U}) { + auto const bad = made(one, one, static_cast(id)); + BOOST_TEST(!bad.is_low_s()); + BOOST_TEST(bad.low_s().error() == crypto::error::invalid_signature); + } + for (unsigned const id : {0U, 1U, 2U, 3U}) { + auto const fine = + made(one, one, static_cast(id)); + BOOST_TEST(fine.is_low_s()); + BOOST_TEST(fine.low_s().value() == fine); + // A high s with id 2 or 3 flips to 3 or 2. + auto const high_s = made(one, plus_one(secp_half_order), + static_cast(id)); + auto const flipped = high_s.low_s(); + BOOST_TEST(flipped.has_value() && flipped->recovery_id() == (id ^ 1U)); + } +} + /** secp256k1's recoverable signature: low_s() flips the id with s, and the signer is recovered. */ void secp256k1_recoverable_members() { auto const key_pair = signer(); @@ -246,23 +272,7 @@ void secp256k1_recoverable_members() { auto const unchanged = original->low_s(); BOOST_TEST(unchanged.has_value() && *unchanged == *original); boundaries(secp_order, secp_half_order); - // The id above 3 is refused by both members, with a low s. - for (unsigned id : {4U, 5U, 255U}) { - auto const bad = made(one, one, static_cast(id)); - BOOST_TEST(!bad.is_low_s()); - BOOST_TEST(bad.low_s().error() == crypto::error::invalid_signature); - } - for (unsigned id : {0U, 1U, 2U, 3U}) { - auto const fine = - made(one, one, static_cast(id)); - BOOST_TEST(fine.is_low_s()); - BOOST_TEST(fine.low_s().value() == fine); - // A high s with id 2 or 3 flips to 3 or 2. - auto const high_s = made(one, plus_one(secp_half_order), - static_cast(id)); - auto const flipped = high_s.low_s(); - BOOST_TEST(flipped.has_value() && flipped->recovery_id() == (id ^ 1U)); - } + recovery_ids(); } } // namespace From 6f37a64ac85e22d477c2e0f91c1bba1452562c8c Mon Sep 17 00:00:00 2001 From: R Date: Mon, 30 Nov 2026 23:11:18 -0300 Subject: [PATCH 13/81] crypto: low S members lint fix 2 --- include/webcpp/crypto/detail/signature.hpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/include/webcpp/crypto/detail/signature.hpp b/include/webcpp/crypto/detail/signature.hpp index 11beeeb9..b7b66949 100644 --- a/include/webcpp/crypto/detail/signature.hpp +++ b/include/webcpp/crypto/detail/signature.hpp @@ -118,6 +118,8 @@ class basic_signature { * @return The low-S signature; `invalid_signature` when r or s is 0 or not below n, or a * recovery id is above 3. */ + // NOLINTNEXTLINE(bugprone-exception-escape): the result's accessor throws only on an error, + // which the branch below has returned; the rest allocates nothing. [[nodiscard]] boost::system::result low_s() const noexcept requires Tag::ecdsa { @@ -126,7 +128,6 @@ class basic_signature { return low_form.error(); } basic_signature made_signature; - // The result holds a value: its pointer reads it without the check that throws. std::copy(low_form->begin(), low_form->end(), made_signature.signature_bytes_.begin()); return made_signature; } From c3e55034da3ac54b9cabd55067017e1b8f6c54de Mon Sep 17 00:00:00 2001 From: R Date: Mon, 30 Nov 2026 23:12:29 -0300 Subject: [PATCH 14/81] crypto: low S members lint fix 3 --- include/webcpp/crypto/detail/signature.hpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/include/webcpp/crypto/detail/signature.hpp b/include/webcpp/crypto/detail/signature.hpp index b7b66949..fc9dd6cf 100644 --- a/include/webcpp/crypto/detail/signature.hpp +++ b/include/webcpp/crypto/detail/signature.hpp @@ -118,8 +118,8 @@ class basic_signature { * @return The low-S signature; `invalid_signature` when r or s is 0 or not below n, or a * recovery id is above 3. */ - // NOLINTNEXTLINE(bugprone-exception-escape): the result's accessor throws only on an error, - // which the branch below has returned; the rest allocates nothing. + // The result's accessor throws only on an error value, which the branch below has returned. + // NOLINTNEXTLINE(bugprone-exception-escape): see above [[nodiscard]] boost::system::result low_s() const noexcept requires Tag::ecdsa { From 30128d9e8389fe686f76fa20846c5d1842a141c8 Mon Sep 17 00:00:00 2001 From: R Date: Mon, 30 Nov 2026 23:52:59 -0300 Subject: [PATCH 15/81] crypto: one secp256k1 low-S predicate for the members and recover, the members' briefs in llms.txt, the recoverable members in the allocation and Ethereum tests, text wraps --- doc/curves.adoc | 2 +- doc/llms.txt | 4 ++ doc/secp256k1.adoc | 5 ++- doc/tables/crypto.json | 6 ++- doc/tables/generate.py | 8 +++- doc/tables/generate_test.py | 20 +++++++++ include/webcpp/crypto/curves/secp256k1.hpp | 51 ++++++++++------------ include/webcpp/crypto/detail/signature.hpp | 4 +- test/secp256k1_allocation_test.cpp | 2 + test/secp256k1_ethereum_test.cpp | 11 +---- 10 files changed, 66 insertions(+), 47 deletions(-) diff --git a/doc/curves.adoc b/doc/curves.adoc index d4ea4617..c0cb24f5 100644 --- a/doc/curves.adoc +++ b/doc/curves.adoc @@ -357,7 +357,7 @@ allocating nothing; `from_der(der)` reads strict DER back into the curve's secp256k1's `recoverable_signature`), not a function of the namespace: `signature.low_s()` returns the low-S form, and `invalid_signature` for an r or an s that is 0 or not below n (and, for a recoverable signature, a recovery id -above 3), flipping the bit 0 of a recoverable signature's recovery id when it +above 3), flipping bit 0 of a recoverable signature's recovery id when it replaces s, which keeps the signer; `signature.is_low_s()` is true exactly when r is between 1 and n - 1 and s between 1 and (n - 1) / 2, and does not verify. An Ed25519 or Schnorr signature has neither. A P-256 signature given to diff --git a/doc/llms.txt b/doc/llms.txt index 160bc820..a88903ec 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -121,6 +121,8 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [curves::secp256k1::to_der, from_der; ecdsa_signature::is_low_s, low_s; recoverable_signature::is_low_s, low_s](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1): ECDSA's strict DER encoding, and low S as the members `is_low_s()` and `low_s()` of the ECDSA signatures, a recoverable one's `low_s()` flipping its recovery id. 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. + - is_low_s: Whether the signature is in its low-S form: 0 < r < n and 0 < s <= (n - 1) / 2, n the group order, and for a recoverable signature a recovery id of 0 to 3. + - low_s: The signature's low-S form: s replaced by n - s when it is above (n - 1) / 2, and a recoverable signature's recovery id with its bit 0 flipped then, so that it recovers the same key; a low-S signature is returned as it is. - [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::signing_schemes::eddsa, message)`, and of a message's SHA-512 with `sign(crypto::signing_schemes::eddsa_prehashed, crypto::signing_schemes::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. @@ -243,6 +245,8 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - verify: Verifies an ECDSA signature over SHA-256 with a P-256 public key under a verification policy. - 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. + - is_low_s: Whether the signature is in its low-S form: 0 < r < n and 0 < s <= (n - 1) / 2, n the group order, and for a recoverable signature a recovery id of 0 to 3. + - low_s: The signature's low-S form: s replaced by n - s when it is above (n - 1) / 2, and a recoverable signature's recovery id with its bit 0 flipped then, so that it recovers the same key; a low-S signature is returned as it is. - [curves::p256::keypair::agree](https://webcpporg.github.io/libs/crypto/#crypto-p256-ecdh): ECDH with a validated public key: the shared point's raw x coordinate, 32 bytes in a `secure::secret<32>`, as WebCrypto's `deriveBits` gives it; a protocol hashes it into its keys. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten. Default: BearSSL on native, wasip2, wasip3, emscripten. Use it to: 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. - agree: ECDH with a peer's public key: the x coordinate of the shared point d * Q, raw, as WebCrypto's `deriveBits` with ECDH on P-256 gives its 256 bits. - 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. diff --git a/doc/secp256k1.adoc b/doc/secp256k1.adoc index 6a78bde9..93bdff0a 100644 --- a/doc/secp256k1.adoc +++ b/doc/secp256k1.adoc @@ -456,8 +456,9 @@ EIP-191's digest is hashed without its prefix and recovers another key. * `recover` takes `low_s_only` alone and refuses a high S before recovery, as EIP-2 does for a transaction, although libsecp256k1's recovery and Ethereum's `ecrecover` precompile accept one; `sign` gives a low S always. A program that -must recover a high-S signature makes it low first with the recoverable signature's `low_s()`, which -replaces s and flips the recovery id's bit 0, which keeps the signer. +must recover a high-S signature makes it low first with the recoverable +signature's `low_s()`, which replaces s and flips the recovery id's bit 0, +which keeps the signer. [#crypto-secp256k1-tweaks] ==== Tweaks, negation and combination diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index d52b81e6..5e99a22a 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -376,7 +376,8 @@ { "id": "encodings", "family": "secp256k1", - "functions": ["to_der", "from_der"], + "functions": ["to_der", "from_der", "basic_signature::is_low_s", "basic_signature::low_s"], + "function_headers": {"basic_signature::is_low_s": "", "basic_signature::low_s": ""}, "namespace": "curves", "api": "curves::secp256k1::to_der, from_der; ecdsa_signature::is_low_s, low_s; recoverable_signature::is_low_s, low_s", "header": "", @@ -775,7 +776,8 @@ "family": "p256", "free": true, "functions": ["basic_keypair::sign", "basic_keypair::async_sign", "verify", "to_der", - "from_der"], + "from_der", "basic_signature::is_low_s", "basic_signature::low_s"], + "function_headers": {"basic_signature::is_low_s": "", "basic_signature::low_s": ""}, "namespace": "curves", "api": "curves::p256::keypair::sign; crypto::verify, to_der, from_der; ecdsa_signature::is_low_s, low_s", "header": "", diff --git a/doc/tables/generate.py b/doc/tables/generate.py index 32f9abe0..934b1efc 100644 --- a/doc/tables/generate.py +++ b/doc/tables/generate.py @@ -1784,7 +1784,8 @@ def declared_brief(library: Path, operation: Data, function: str) -> str: """The first sentence of the Doc Comment of a function an operation names, read from the operation's headers: the description llms.txt gives it. A function written `class::name` is read in that class's body alone, for a name that another class of the header declares first. - A function the operation's `overloads` name is read in the first declaration that holds the + A function the operation's `function_headers` map to a header is read in that header instead + of the operation's. A function the operation's `overloads` name is read in the first declaration that holds the text they give it, for a name another family's overload declares first. A function no header declares is a fault.""" scope, _, name = function.rpartition('::') @@ -1793,7 +1794,10 @@ def declared_brief(library: Path, operation: Data, function: str) -> str: pattern = re.compile(r'\boperator\(\)\(') else: pattern = re.compile(rf'(?:\b{re.escape(name)}|\({re.escape(name)}\))\s*\(') - for header in HEADER.findall(operation['header']): + # A function whose declaration is in another header than the operation's, such as a member of + # the signature template, names it in `function_headers`. + headers = operation.get('function_headers', {}).get(function, operation['header']) + for header in HEADER.findall(headers): text = (library / 'include' / header).read_text(encoding='utf-8') if scope: text = class_body(text, scope) diff --git a/doc/tables/generate_test.py b/doc/tables/generate_test.py index ad742143..650417b0 100644 --- a/doc/tables/generate_test.py +++ b/doc/tables/generate_test.py @@ -1212,6 +1212,26 @@ def test_a_use_case_listing_an_unknown_operation_is_a_fault(scratch: Path) -> No raise AssertionError('a use case naming an unknown operation was accepted') +def test_a_function_is_read_in_the_header_the_operation_maps_it_to(scratch: Path) -> None: + written(scratch, 'include/webcpp/crypto/own.hpp', ( + 'namespace webcpp::crypto {\n/** Its own. */\nint low_s();\n}\n')) + written(scratch, 'include/webcpp/crypto/detail/sig.hpp', ( + 'namespace webcpp::crypto::detail {\n' + 'class basic_signature {\npublic:\n/** Whether it is low. */\nbool is_low_s() const;\n};\n}\n')) + operation = {'id': 'e', 'header': '', 'free': True, + 'function_headers': { + 'basic_signature::is_low_s': ''}} + brief = generate.declared_brief(scratch, operation, 'basic_signature::is_low_s') + assert brief == 'Whether it is low.', brief + try: + generate.declared_brief(scratch, dict(operation, function_headers={}), + 'basic_signature::is_low_s') + except generate.Fault as fault: + assert 'basic_signature::is_low_s' in str(fault), fault + else: + raise AssertionError('a member no header of the operation declares was given a brief') + + def test_an_overload_is_read_in_the_declaration_that_holds_its_text(scratch: Path) -> None: written(scratch, 'include/webcpp/crypto/over.hpp', ( 'namespace webcpp::crypto {\n' diff --git a/include/webcpp/crypto/curves/secp256k1.hpp b/include/webcpp/crypto/curves/secp256k1.hpp index f25889f8..4619746b 100644 --- a/include/webcpp/crypto/curves/secp256k1.hpp +++ b/include/webcpp/crypto/curves/secp256k1.hpp @@ -109,9 +109,8 @@ struct secp256k1_recoverable_signature_tag { /** * Whether the signature is in its low-S form: 0 < r < n and 0 < s <= (n - 1) / 2, and the - * recovery id 0 to 3 - * (`secp256k1_ecdsa_signature_normalize`), under libsecp256k1's guard, canary and self-test. It - * does not verify the signature. + * recovery id 0 to 3 (`secp256k1_ecdsa_signature_normalize`), under libsecp256k1's guard, + * canary and self-test. It does not verify the signature. * * @param signature_bytes The signature's 65 bytes. * @return Whether it is low S. @@ -609,15 +608,18 @@ struct secp256k1_refusal { template inline constexpr bool secp256k1_refuses_others = sizeof(secp256k1_refusal) != 0; -inline bool secp256k1_ecdsa_signature_tag::is_low_s( - std::span signature_bytes) noexcept { - secure::timing_guard const timing_scope; - static_assert( - secp256k1_refuses_others>); - read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); - secp256k1_selftest(); +/** + * Whether a compact ECDSA signature is low S: 0 < r < n and 0 < s <= (n - 1) / 2, the one verdict + * of both tags' `is_low_s` and of `recover` under `low_s_only`. The caller has read the canary + * and run the self-test, and holds the guard. + * + * @param compact_signature The 64 bytes, r then s. + * @return Whether it is low S. + */ +[[nodiscard]] inline bool secp256k1_low_s_verdict( + std::span compact_signature) noexcept { secp256k1_ecdsa_signature parsed_value{}; - if (!secp256k1_parse_compact(signature_bytes, parsed_value)) { + if (!secp256k1_parse_compact(compact_signature, parsed_value)) { return false; } // libsecp256k1 returns 1 when s was high, and writes nothing when the output is null. @@ -625,11 +627,17 @@ inline bool secp256k1_ecdsa_signature_tag::is_low_s( 0; } +inline bool secp256k1_ecdsa_signature_tag::is_low_s( + std::span signature_bytes) noexcept { + secure::timing_guard const timing_scope; + read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_selftest(); + return secp256k1_low_s_verdict(signature_bytes); +} + inline boost::system::result> secp256k1_ecdsa_signature_tag::low_s( std::span signature_bytes) noexcept { secure::timing_guard const timing_scope; - static_assert( - secp256k1_refuses_others>); std::array low_bytes{}; bool was_high = false; if (!secp256k1_low_s_of(signature_bytes, low_bytes, was_high)) { @@ -641,27 +649,18 @@ inline boost::system::result> secp256k1_ecdsa_signa inline bool secp256k1_recoverable_signature_tag::is_low_s( std::span signature_bytes) noexcept { secure::timing_guard const timing_scope; - static_assert( - secp256k1_refuses_others>); if (signature_bytes[64] > 3) { return false; } read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); secp256k1_selftest(); - secp256k1_ecdsa_signature parsed_value{}; - if (!secp256k1_parse_compact(signature_bytes.first<64>(), parsed_value)) { - return false; - } - return secp256k1_ecdsa_signature_normalize(secp256k1_context_static, nullptr, &parsed_value) == - 0; + return secp256k1_low_s_verdict(signature_bytes.first<64>()); } inline boost::system::result> secp256k1_recoverable_signature_tag::low_s( std::span signature_bytes) noexcept { secure::timing_guard const timing_scope; - static_assert( - secp256k1_refuses_others>); if (signature_bytes[64] > 3) { return error::invalid_signature; } @@ -1704,11 +1703,7 @@ inline curves::secp256k1::public_key secp256k1_access::make_public_key() noexcep return error::invalid_signature; } secp256k1_selftest(); - secp256k1_ecdsa_signature compact_value{}; - if (secp256k1_ecdsa_signature_parse_compact(secp256k1_context_static, &compact_value, - signature_bytes.data()) == 0 || - secp256k1_ecdsa_signature_normalize(secp256k1_context_static, nullptr, &compact_value) != - 0) { + if (!secp256k1_low_s_verdict(std::span(signature_bytes).first<64>())) { return error::invalid_signature; } secp256k1_ecdsa_recoverable_signature parsed_value{}; diff --git a/include/webcpp/crypto/detail/signature.hpp b/include/webcpp/crypto/detail/signature.hpp index fc9dd6cf..e11df14a 100644 --- a/include/webcpp/crypto/detail/signature.hpp +++ b/include/webcpp/crypto/detail/signature.hpp @@ -118,8 +118,6 @@ class basic_signature { * @return The low-S signature; `invalid_signature` when r or s is 0 or not below n, or a * recovery id is above 3. */ - // The result's accessor throws only on an error value, which the branch below has returned. - // NOLINTNEXTLINE(bugprone-exception-escape): see above [[nodiscard]] boost::system::result low_s() const noexcept requires Tag::ecdsa { @@ -128,7 +126,7 @@ class basic_signature { return low_form.error(); } basic_signature made_signature; - std::copy(low_form->begin(), low_form->end(), made_signature.signature_bytes_.begin()); + std::ranges::copy(low_form.unsafe_value(), made_signature.signature_bytes_.begin()); return made_signature; } diff --git a/test/secp256k1_allocation_test.cpp b/test/secp256k1_allocation_test.cpp index d7623799..0d05571b 100644 --- a/test/secp256k1_allocation_test.cpp +++ b/test/secp256k1_allocation_test.cpp @@ -262,6 +262,8 @@ int main() { none("from_der", [&] { return secp::from_der(encoded); }); none("low_s", [&] { return ecdsa->low_s(); }); none("is_low_s", [&] { return ecdsa->is_low_s(); }); + none("recoverable low_s", [&] { return recoverable->low_s(); }); + none("recoverable is_low_s", [&] { return recoverable->is_low_s(); }); none("tweak_xonly", [&] { return secp::tweak_xonly(xonly, message); }); auto const parsed = secp::public_key::from_bytes(uncompressed); none("public_key::from_bytes", [&] { return secp::public_key::from_bytes(compressed); }); diff --git a/test/secp256k1_ethereum_test.cpp b/test/secp256k1_ethereum_test.cpp index 38e6d028..6248cb8c 100644 --- a/test/secp256k1_ethereum_test.cpp +++ b/test/secp256k1_ethereum_test.cpp @@ -168,13 +168,6 @@ secp::recoverable_signature typed(std::span signature_bytes) return made ? *made : secp::recoverable_signature{}; } -// The ECDSA signature of a recoverable one's first 64 bytes, r and s. -secp::ecdsa_signature ecdsa_of(secp::recoverable_signature const& signature) { - auto made = secp::ecdsa_signature::from_bytes(std::span(signature.bytes()).first<64>()); - BOOST_TEST(made.has_value()); - return made ? *made : secp::ecdsa_signature{}; -} - // go-ethereum's digest and signature recover its uncompressed key. void geth_recover() { auto const recovered = @@ -293,7 +286,7 @@ void always_low_s() { if (!BOOST_TEST(signature.has_value())) { return; } - BOOST_TEST(ecdsa_of(*signature).is_low_s()); + BOOST_TEST(signature->is_low_s()); BOOST_TEST(signature->recovery_id() <= 3); auto const recovered = secp::recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, crypto::verification_policies::low_s_only, *signature, @@ -315,7 +308,7 @@ void high_s_refused() { std::ranges::copy(s_value, high_bytes.begin() + 32); high_bytes[64] ^= 1U; auto const high = typed(high_bytes); - BOOST_TEST(!ecdsa_of(high).is_low_s()); + BOOST_TEST(!high.is_low_s()); auto const refused = secp::recover(crypto::signing_schemes::ecdsa_keccak256_recoverable, crypto::verification_policies::low_s_only, high, crypto::signing_schemes::prehashed{geth_message}); From 1fddaecc51475be92ca8eb0e5617d5e4ee458e79 Mon Sep 17 00:00:00 2001 From: R Date: Mon, 30 Nov 2026 23:53:24 -0300 Subject: [PATCH 16/81] crypto: generator lines lint fix --- doc/tables/generate.py | 6 +++--- doc/tables/generate_test.py | 3 ++- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/doc/tables/generate.py b/doc/tables/generate.py index 934b1efc..f89e0876 100644 --- a/doc/tables/generate.py +++ b/doc/tables/generate.py @@ -1785,9 +1785,9 @@ def declared_brief(library: Path, operation: Data, function: str) -> str: operation's headers: the description llms.txt gives it. A function written `class::name` is read in that class's body alone, for a name that another class of the header declares first. A function the operation's `function_headers` map to a header is read in that header instead - of the operation's. A function the operation's `overloads` name is read in the first declaration that holds the - text they give it, for a name another family's overload declares first. A function no header - declares is a fault.""" + of the operation's. A function the operation's `overloads` name is read in the first + declaration that holds the text they give it, for a name another family's overload declares + first. A function no header declares is a fault.""" scope, _, name = function.rpartition('::') overload = operation.get('overloads', {}).get(function) if name == 'operator()': diff --git a/doc/tables/generate_test.py b/doc/tables/generate_test.py index 650417b0..4a53b4f1 100644 --- a/doc/tables/generate_test.py +++ b/doc/tables/generate_test.py @@ -1217,7 +1217,8 @@ def test_a_function_is_read_in_the_header_the_operation_maps_it_to(scratch: Path 'namespace webcpp::crypto {\n/** Its own. */\nint low_s();\n}\n')) written(scratch, 'include/webcpp/crypto/detail/sig.hpp', ( 'namespace webcpp::crypto::detail {\n' - 'class basic_signature {\npublic:\n/** Whether it is low. */\nbool is_low_s() const;\n};\n}\n')) + 'class basic_signature {\npublic:\n/** Whether it is low. */\nbool is_low_s() const;\n};\n' + '}\n')) operation = {'id': 'e', 'header': '', 'free': True, 'function_headers': { 'basic_signature::is_low_s': ''}} From 413df0e561aa1057a88cb56fb7e50c701387d8d3 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 1 Dec 2026 00:26:30 -0300 Subject: [PATCH 17/81] crypto: formats on codecs: the tags, the point forms, pem over codecs' armor, one list, the verbs with crypto's check and the in-place PEM decode, proven on a toy type --- AGENTS.md | 6 +- build.jam | 11 +- doc/generated/messages.adoc | 70 ++ doc/tables/crypto.json | 7 + include/webcpp/crypto/formats.hpp | 1000 +++++++++++++++++ meta/include-boundaries.json | 14 + test/Jamfile | 26 +- test/formats_pem_test.cpp | 366 ++++++ test/formats_stand_in_test.cpp | 97 ++ test/formats_verbs_test.cpp | 263 +++++ test/formats_vocabulary_test.cpp | 168 +++ test/messages/Jamfile | 7 + test/messages/decode_bound_differs/Jamfile | 14 + .../decode_bound_differs.cpp | 52 + test/messages/decode_bound_missing/Jamfile | 14 + .../decode_bound_missing.cpp | 51 + .../format_header_missing_toy/Jamfile | 14 + .../format_header_missing_toy.cpp | 27 + test/messages/format_refused_toy/Jamfile | 14 + .../format_refused_toy/format_refused_toy.cpp | 26 + test/messages/format_without_header/Jamfile | 14 + .../format_without_header.cpp | 18 + test/messages/pem_of_der/Jamfile | 14 + test/messages/pem_of_der/pem_of_der.cpp | 22 + test/messages/pem_of_raw/Jamfile | 14 + test/messages/pem_of_raw/pem_of_raw.cpp | 22 + test/msvc/Jamfile | 7 + test/msvc/decode_bound_differs/Jamfile | 9 + test/msvc/decode_bound_differs/app.cpp | 44 + test/msvc/decode_bound_missing/Jamfile | 9 + test/msvc/decode_bound_missing/app.cpp | 43 + test/msvc/format_header_missing_toy/Jamfile | 9 + test/msvc/format_header_missing_toy/app.cpp | 18 + test/msvc/format_refused_toy/Jamfile | 9 + test/msvc/format_refused_toy/app.cpp | 17 + test/msvc/format_without_header/Jamfile | 9 + test/msvc/format_without_header/app.cpp | 15 + test/msvc/pem_of_der/Jamfile | 9 + test/msvc/pem_of_der/app.cpp | 15 + test/msvc/pem_of_raw/Jamfile | 9 + test/msvc/pem_of_raw/app.cpp | 15 + test/support/format_checks.hpp | 255 +++++ test/support/formats_toy.hpp | 542 +++++++++ test/support/wipe_record.hpp | 120 ++ test/user_globals_test.cpp | 3 + 45 files changed, 3501 insertions(+), 7 deletions(-) create mode 100644 include/webcpp/crypto/formats.hpp create mode 100644 test/formats_pem_test.cpp create mode 100644 test/formats_stand_in_test.cpp create mode 100644 test/formats_verbs_test.cpp create mode 100644 test/formats_vocabulary_test.cpp create mode 100644 test/messages/decode_bound_differs/Jamfile create mode 100644 test/messages/decode_bound_differs/decode_bound_differs.cpp create mode 100644 test/messages/decode_bound_missing/Jamfile create mode 100644 test/messages/decode_bound_missing/decode_bound_missing.cpp create mode 100644 test/messages/format_header_missing_toy/Jamfile create mode 100644 test/messages/format_header_missing_toy/format_header_missing_toy.cpp create mode 100644 test/messages/format_refused_toy/Jamfile create mode 100644 test/messages/format_refused_toy/format_refused_toy.cpp create mode 100644 test/messages/format_without_header/Jamfile create mode 100644 test/messages/format_without_header/format_without_header.cpp create mode 100644 test/messages/pem_of_der/Jamfile create mode 100644 test/messages/pem_of_der/pem_of_der.cpp create mode 100644 test/messages/pem_of_raw/Jamfile create mode 100644 test/messages/pem_of_raw/pem_of_raw.cpp create mode 100644 test/msvc/decode_bound_differs/Jamfile create mode 100644 test/msvc/decode_bound_differs/app.cpp create mode 100644 test/msvc/decode_bound_missing/Jamfile create mode 100644 test/msvc/decode_bound_missing/app.cpp create mode 100644 test/msvc/format_header_missing_toy/Jamfile create mode 100644 test/msvc/format_header_missing_toy/app.cpp create mode 100644 test/msvc/format_refused_toy/Jamfile create mode 100644 test/msvc/format_refused_toy/app.cpp create mode 100644 test/msvc/format_without_header/Jamfile create mode 100644 test/msvc/format_without_header/app.cpp create mode 100644 test/msvc/pem_of_der/Jamfile create mode 100644 test/msvc/pem_of_der/app.cpp create mode 100644 test/msvc/pem_of_raw/Jamfile create mode 100644 test/msvc/pem_of_raw/app.cpp create mode 100644 test/support/format_checks.hpp create mode 100644 test/support/formats_toy.hpp create mode 100644 test/support/wipe_record.hpp diff --git a/AGENTS.md b/AGENTS.md index 7f729c4f..80956c4e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,9 +12,11 @@ specific to crypto. - **webcpp's own library** (`"port-of": null`) over C backends: BearSSL, OpenSSL, ctaes, libsecp256k1 and libsodium (the superproject's `/third_party//sodium`, shared with webcpp::hash). The algorithms are the backends'; crypto is the interface shaped as Boost.Hash2's. - crypto depends on config, hash and secure: the timing guard, `erase_secret`, + crypto depends on config, hash, secure and codecs: the timing guard, `erase_secret`, `constant_time_equal`, `secret` and `declassify` are webcpp::secure's, with no copy and no - alias in crypto. + alias in crypto; the key formats are codecs formats, registered through `codecs::value_codec`, + and only `include/webcpp/crypto/formats.hpp` and each `curves//formats.hpp` include a + codecs header (an include boundary). - **No oracle.** No original runs beside crypto: the evidence is the published vectors (the GCM specification's cases, Wycheproof, FIPS 197, RFC 8439 and RFC 8032, BIP340 and BIP341), the backends' own suites in the lane `c-suites`, and the agreement tests, which compare two backends diff --git a/build.jam b/build.jam index cc0f05d1..f26c419a 100644 --- a/build.jam +++ b/build.jam @@ -19,14 +19,17 @@ project /webcpp/crypto ; # Header-only, on webcpp's configuration, with webcpp::hash's header-only # alias, whose algorithms name a signature's prehash (Ed25519ph's SHA-512; -# design D1), and webcpp::secure's, whose timing guard, erase_secret, +# design D1), webcpp::secure's, whose timing guard, erase_secret, # constant_time_equal, secret and declassify crypto's code holds and -# returns. random_device reads Windows' generator through bcrypt -# (BCryptGenRandom), a system library. +# returns, and webcpp::codecs', header-only on config and secure, into which +# the key formats register (formats.hpp and each curve's formats.hpp, the +# only headers that include codecs'; design R32). +# random_device reads Windows' generator through bcrypt (BCryptGenRandom), a +# system library. # tag::crypto[] alias crypto : : : : include /boost//headers /webcpp/config//config /webcpp/hash//hash - /webcpp/secure//secure + /webcpp/secure//secure /webcpp/codecs//codecs windows:bcrypt ; # end::crypto[] diff --git a/doc/generated/messages.adoc b/doc/generated/messages.adoc index 05d5dc85..3e4bd11a 100644 --- a/doc/generated/messages.adoc +++ b/doc/generated/messages.adoc @@ -299,6 +299,18 @@ The fix: Call `+webcpp::secure::constant_time_equal+`, from `+>.+` @@ -359,6 +371,24 @@ The fix: Call `+webcpp::secure::constant_time_equal+`, the same comparison of tw The fix: Call `+webcpp::secure::erase_secret+`, from `++`, the same erasure; `+crypto::erase_secret+` moved to webcpp::secure, with no alias. +|`+format_header_missing_toy+` +|native, wasip2, wasip3 +|`+webcpp::crypto: include to encode or decode this type+` + +The fix: Include the formats header of the type's curve, the one the assertion names, `+/formats.hpp>+`, beside the curve's own header, which declares no format. + +|`+format_refused_toy+` +|native, wasip2, wasip3 +|`+webcpp::crypto::detail::format_list, webcpp::crypto::formats::spki_t, webcpp::codecs::over, std::allocator>>>': webcpp::crypto: this type has no such format; the formats it has are the format_list named in this assertion+` + +The fix: Encode or decode a type in a format of its list, the `+format_list+` the assertion names: another type's format (`+der+` is an ECDSA signature's, `+pkcs8+` a key pair's) does not convert it. + +|`+format_without_header+` +|native, wasip2, wasip3 +|`+no member named 'spki' in namespace 'webcpp::crypto::formats'+` + +The fix: Include `++`, or the curve's `+/formats.hpp>+`, which includes it: `+crypto::formats+` is declared by `+config.hpp+` and filled by the formats headers alone. + |`+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)+` @@ -513,6 +543,18 @@ 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. +|`+pem_of_der+` +|native, wasip2, wasip3 +|`+webcpp::crypto: PEM carries a DER key: pem(formats::spki) or pem(formats::pkcs8)+` + +The fix: Armor the DER of a key: `+crypto::formats::pem(crypto::formats::spki)+` for a public key, `+crypto::formats::pem(crypto::formats::pkcs8)+` for a key pair; a signature's DER has no PEM. + +|`+pem_of_raw+` +|native, wasip2, wasip3 +|`+webcpp::crypto: PEM carries a DER key: pem(formats::spki) or pem(formats::pkcs8)+` + +The fix: As `+pem_of_der+`: armor the DER of a key, `+crypto::formats::pem(crypto::formats::spki)+` or `+crypto::formats::pem(crypto::formats::pkcs8)+`; a key's raw bytes have no PEM. + |`+ph_removed+` |native, wasip2, wasip3 |`+no member named 'ph' in namespace+` @@ -1736,6 +1778,14 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |Add `+/third_party//ctaes+`. +|`+decode_bound_differs+` +|the compile +|Make `+max_decode_input_size+` equal to `+max_encoded_size+`, or, where a change rules that the decode accepts a longer form (as PKCS#8 version 2 will), specialize `+detail::bounds_may_differ_v+` for the pair beside its value codec. + +|`+decode_bound_missing+` +|the compile +|State `+static constexpr std::size_t max_decode_input_size+` in the value codec that decodes: the longest encoded input its `+decode+` accepts, equal to its `+max_encoded_size+` unless a change rules otherwise. + |`+default_openssl_wasm+` |the compile |Remove the define, and name `+gcm>+` where the program wants OpenSSL. @@ -1764,6 +1814,18 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |Name `+backends::secp256k1+`, or leave the backend out: `+curves::secp256k1::ellswift_decode(encoded_key)+`. +|`+format_header_missing_toy+` +|the compile +|Include the formats header of the type's curve, the one the assertion names, `+/formats.hpp>+`, beside the curve's own header, which declares no format. + +|`+format_refused_toy+` +|the compile +|Encode or decode a type in a format of its list, the `+format_list+` the assertion names: another type's format (`+der+` is an ECDSA signature's, `+pkcs8+` a key pair's) does not convert it. + +|`+format_without_header+` +|the compile +|Include `++`, or the curve's `+/formats.hpp>+`, which includes it: `+crypto::formats+` is declared by `+config.hpp+` and filled by the formats headers alone. + |`+gcm_default_openssl_not_linked+` |the compile |Natively the default is OpenSSL: add `+/webcpp/crypto//gcm-default+`, which links `+/webcpp/crypto//openssl+` there, or name BearSSL in the type, as in `+gcm>+`. @@ -1832,6 +1894,14 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |Add `+/webcpp/crypto//pem-default+`, which links `+/third_party//sodium+` on every target. +|`+pem_of_der+` +|the compile +|Armor the DER of a key: `+crypto::formats::pem(crypto::formats::spki)+` for a public key, `+crypto::formats::pem(crypto::formats::pkcs8)+` for a key pair; a signature's DER has no PEM. + +|`+pem_of_raw+` +|the compile +|As `+pem_of_der+`: armor the DER of a key, `+crypto::formats::pem(crypto::formats::spki)+` or `+crypto::formats::pem(crypto::formats::pkcs8)+`; a key's raw bytes have no PEM. + |`+prehashed_signer_verify_without_policy+` |the compile |Name the policy first: `+signer.verify(crypto::verification_policies::canonical, signature, public_key)+`, Ed25519ph's only policy. diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 5e99a22a..aa533714 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -1475,6 +1475,13 @@ "verify_schnorr_as_ecdsa": "Verify a BIP340 signature with `crypto::signing_schemes::schnorr`, its scheme; `crypto::signing_schemes::ecdsa_sha256` takes a `curves::secp256k1::ecdsa_signature`, which `sign(crypto::signing_schemes::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.", "low_s_on_ed25519": "Only an ECDSA signature has low S: Ed25519 and Schnorr signatures have no `is_low_s()` or `low_s()`, and need none, for no other S verifies as theirs.", + "format_refused_toy": "Encode or decode a type in a format of its list, the `format_list` the assertion names: another type's format (`der` is an ECDSA signature's, `pkcs8` a key pair's) does not convert it.", + "pem_of_der": "Armor the DER of a key: `crypto::formats::pem(crypto::formats::spki)` for a public key, `crypto::formats::pem(crypto::formats::pkcs8)` for a key pair; a signature's DER has no PEM.", + "pem_of_raw": "As `pem_of_der`: armor the DER of a key, `crypto::formats::pem(crypto::formats::spki)` or `crypto::formats::pem(crypto::formats::pkcs8)`; a key's raw bytes have no PEM.", + "format_header_missing_toy": "Include the formats header of the type's curve, the one the assertion names, `/formats.hpp>`, beside the curve's own header, which declares no format.", + "decode_bound_missing": "State `static constexpr std::size_t max_decode_input_size` in the value codec that decodes: the longest encoded input its `decode` accepts, equal to its `max_encoded_size` unless a change rules otherwise.", + "decode_bound_differs": "Make `max_decode_input_size` equal to `max_encoded_size`, or, where a change rules that the decode accepts a longer form (as PKCS#8 version 2 will), specialize `detail::bounds_may_differ_v` for the pair beside its value codec.", + "format_without_header": "Include ``, or the curve's `/formats.hpp>`, which includes it: `crypto::formats` is declared by `config.hpp` and filled by the formats headers alone.", "recover_ecdsa_signature": "Give `recover` a `curves::secp256k1::recoverable_signature`, which `sign(crypto::signing_schemes::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.", diff --git a/include/webcpp/crypto/formats.hpp b/include/webcpp/crypto/formats.hpp new file mode 100644 index 00000000..e58482a6 --- /dev/null +++ b/include/webcpp/crypto/formats.hpp @@ -0,0 +1,1000 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the 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 formats of keys and signatures, registered into webcpp::codecs (design D1, D2, D3 and D11): + the format tags `formats::raw`, `formats::spki`, `formats::pkcs8` and `formats::der`, each a + `codecs::format`; the point forms `formats::compressed`, `formats::uncompressed` and + `formats::xonly`, which `raw(form)` and `spki(form)` take; `formats::pem(inner)`, codecs' armor + over `spki` or `pkcs8` with the label of the inner format; the library's one list of formats, + `detail::all_formats`, and the traits each value type declares its own with + (`detail::formats_of`, `detail::forms_of`, `detail::curve_of_v`, the refusal reasons); the two + bounds of a value codec, `formats::max_encoded_size` and `formats::max_decode_input_size`; and the + verbs `crypto::encode` and `crypto::decode`, which check a pair of crypto's against the type's + list and then call codecs' verbs, decoding a PEM in place. + + Each pair of a format and a type is a `codecs::value_codec` specialization in the type's curve's + `curves//formats.hpp`; this header includes no curve and no backend, and is the only one, + with those, that includes a codecs header. A program may call `codecs::encode` and + `codecs::decode` with the same formats: it gets the same bytes and the same values, and + codecs' generic diagnostic for a pair that does not exist. + + @see "Key formats: SPKI, PKCS#8 and PEM", in the guide. +*/ +#ifndef WEBCPP_CRYPTO_FORMATS_HPP +#define WEBCPP_CRYPTO_FORMATS_HPP + +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::crypto { +namespace formats { + +/** + * The type of the default point form of `raw` and `spki`: the uncompressed point on every EC curve + * (design D5), the key's only form on Ed25519 and X25519. + * + * Its explicit default constructor keeps `{}` from standing for a form. + */ +struct default_form_t { + /** Makes the tag; explicit, so that only its name makes one. */ + explicit default_form_t() = default; +}; + +/** + * The type of @ref compressed, the compressed point of an EC curve: a prefix byte and x. + * + * Its explicit default constructor keeps `{}` from standing for a form. + */ +struct compressed_t { + /** Makes the tag; explicit, so that only its name makes one. */ + explicit compressed_t() = default; +}; + +/** + * The type of @ref uncompressed, the uncompressed point of an EC curve, named: the default form + * written out. + * + * Its explicit default constructor keeps `{}` from standing for a form. + */ +struct uncompressed_t { + /** Makes the tag; explicit, so that only its name makes one. */ + explicit uncompressed_t() = default; +}; + +/** + * The type of @ref xonly, BIP340's x-only point of secp256k1: x alone, 32 bytes. + * + * Its explicit default constructor keeps `{}` from standing for a form. + */ +struct xonly_t { + /** Makes the tag; explicit, so that only its name makes one. */ + explicit xonly_t() = default; +}; + +/** The compressed point: `formats::raw(formats::compressed)`, `formats::spki(formats::compressed)`. + */ +inline constexpr compressed_t compressed{}; + +/** The uncompressed point, named: `formats::raw(formats::uncompressed)`. */ +inline constexpr uncompressed_t uncompressed{}; + +/** The x-only point of secp256k1: `formats::raw(formats::xonly)`. */ +inline constexpr xonly_t xonly{}; + +} // namespace formats + +namespace detail { + +/** + * Whether `Form` is one of the four point form types, `formats::default_form_t`, + * `formats::compressed_t`, `formats::uncompressed_t` and `formats::xonly_t`. + * + * @tparam Form The type to check. + */ +template +inline constexpr bool is_point_form_v = false; + +/** The default form is a point form. */ +template <> +inline constexpr bool is_point_form_v = true; + +/** The compressed form is a point form. */ +template <> +inline constexpr bool is_point_form_v = true; + +/** The uncompressed form is a point form. */ +template <> +inline constexpr bool is_point_form_v = true; + +/** The x-only form is a point form. */ +template <> +inline constexpr bool is_point_form_v = true; + +} // namespace detail + +namespace formats { + +/** + * The type of @ref raw, a value's own bytes: a public key's point, a key pair's secret (its + * `secret()`, and `from_secret` on decoding), a signature's bytes. + * + * `Form` is the point form of a public key of an EC curve, `default_form_t` (the uncompressed + * point) unless a call to `raw` names another. Its name is `"raw"` whatever the form (design R25), + * and its explicit default constructor keeps `{}` from standing for a format. + * + * @tparam Form The point form. + */ +template +struct raw_t { + /** The format's name, `codecs::format`'s. */ + static constexpr std::string_view name = "raw"; + + /** Makes the tag; explicit, so that only its name makes one. */ + explicit raw_t() = default; + + /** + * The format of the point form `form`: `formats::raw(formats::compressed)`. + * + * @tparam Other The point form's type. + * @return The format of that form. + */ + template + requires detail::is_point_form_v + [[nodiscard]] constexpr raw_t operator()(Other /*form*/) const noexcept { + return raw_t{}; + } +}; + +/** + * The type of @ref spki, RFC 5280's SubjectPublicKeyInfo of a public key, in DER. + * + * `Form` is the point form of the key inside, `default_form_t` unless a call to `spki` names + * `compressed` or `uncompressed`: an x-only key has no SPKI. Its name is `"spki"` whatever the + * form, and its explicit default constructor keeps `{}` from standing for a format. + * + * @tparam Form The point form. + */ +template +struct spki_t { + /** The format's name, `codecs::format`'s. */ + static constexpr std::string_view name = "spki"; + + /** Makes the tag; explicit, so that only its name makes one. */ + explicit spki_t() = default; + + /** + * The format of the point form `form`: `formats::spki(formats::compressed)`. + * + * @tparam Other The point form's type, `compressed_t` or `uncompressed_t`. + * @return The format of that form. + */ + template + requires(detail::is_point_form_v && !std::is_same_v) + [[nodiscard]] constexpr spki_t operator()(Other /*form*/) const noexcept { + return spki_t{}; + } +}; + +/** + * The type of @ref pkcs8, RFC 5208's and RFC 5958's PrivateKeyInfo of a key pair, in DER: a + * private format, whose results are secret. + * + * Its explicit default constructor keeps `{}` from standing for a format. + */ +struct pkcs8_t { + /** The format's name, `codecs::format`'s. */ + static constexpr std::string_view name = "pkcs8"; + + /** Makes the tag; explicit, so that only its name makes one. */ + explicit pkcs8_t() = default; +}; + +/** + * The type of @ref der, the DER of an ECDSA signature (RFC 3279's `Ecdsa-Sig-Value`). + * + * Its explicit default constructor keeps `{}` from standing for a format. + */ +struct der_t { + /** The format's name, `codecs::format`'s. */ + static constexpr std::string_view name = "der"; + + /** Makes the tag; explicit, so that only its name makes one. */ + explicit der_t() = default; +}; + +/** A value's own bytes, the uncompressed point for an EC public key. */ +inline constexpr raw_t<> raw{}; + +/** The SubjectPublicKeyInfo of a public key, the uncompressed point inside for an EC key. */ +inline constexpr spki_t<> spki{}; + +/** The PrivateKeyInfo of a key pair. */ +inline constexpr pkcs8_t pkcs8{}; + +/** The DER of an ECDSA signature. */ +inline constexpr der_t der{}; + +} // namespace formats + +namespace detail { + +/** + * The label of the PEM of `Inner`: `"PUBLIC KEY"` for every `formats::spki_t
` and + * `"PRIVATE KEY"` for `formats::pkcs8_t` (RFC 7468); empty for any other, which `pem` refuses. + * + * @tparam Inner The format inside the armor. + */ +template +inline constexpr std::string_view pem_label_v{}; + +/** An SPKI's armor is labelled `PUBLIC KEY`, whatever its point form. */ +template +inline constexpr std::string_view pem_label_v> = "PUBLIC KEY"; + +/** A PKCS#8's armor is labelled `PRIVATE KEY`. */ +template <> +inline constexpr std::string_view pem_label_v = "PRIVATE KEY"; + +/** + * Whether `pem` takes `Inner`: an `formats::spki_t` or `formats::pkcs8_t`, the DER formats + * of a key. + * + * @tparam Inner The format inside the armor. + */ +template +inline constexpr bool is_pem_inner_v = false; + +/** An SPKI goes inside an armor, whatever its point form. */ +template +inline constexpr bool is_pem_inner_v> = true; + +/** A PKCS#8 goes inside an armor. */ +template <> +inline constexpr bool is_pem_inner_v = true; + +} // namespace detail + +namespace formats { + +/** + * The type of `formats::pem(inner)`: codecs' armor over `Inner` (design R23). + * + * The armor is configured with `Inner`'s label. The links are the chain's members `outer`, the + * armor, and `inner`. + * + * @tparam Inner The DER format inside the armor, `spki_t` or `pkcs8_t`. + */ +template +using pem_t = codecs::over; + +/** + * The type of @ref pem, which makes the PEM format of a DER format of a key. + * + * Its explicit default constructor keeps `{}` from standing for it. + */ +struct pem_builder_t { + /** Makes the builder; explicit, so that only its name makes one. */ + explicit pem_builder_t() = default; + + /** + * The PEM of `inner`: codecs' `formats::armor` with `inner`'s label over `inner`. + * + * The label is `PUBLIC KEY` for `spki` (any point form) and `PRIVATE KEY` for `pkcs8`: no + * function of crypto takes a label from its caller. Any other `inner`, `raw` or `der`, stops + * the build. + * + * @tparam Inner The inner format's type. + * @param inner The inner format. + * @return The PEM format. + */ + template + [[nodiscard]] constexpr pem_t operator()(Inner inner) const noexcept { + static_assert(detail::is_pem_inner_v, + "webcpp::crypto: PEM carries a DER key: pem(formats::spki) or " + "pem(formats::pkcs8)"); + if constexpr (detail::is_pem_inner_v) { + return pem_t{codecs::formats::armor(detail::pem_label_v), inner}; + } else { + return pem_t{codecs::formats::armor, inner}; + } + } +}; + +/** + * RFC 7468's PEM of a DER format of a key: `formats::pem(formats::spki)` and + * `formats::pem(formats::pkcs8)`, text. + */ +inline constexpr pem_builder_t pem{}; + +/** + * The longest encoding the value codec of `Format` and `T` writes: the capacity of the default + * result of `crypto::encode(format, value)` (design R20). + * + * @tparam Format The format's type. + * @tparam T The value's type. + */ +template +inline constexpr std::size_t max_encoded_size = codecs::value_codec::max_encoded_size; + +/** + * The decode bound of the value codec of `Format` and `T`: the longest encoded input its decode + * accepts (owner decision 23, design R37). + * + * It sizes the in-place decode of the pair's PEM, and equals @ref max_encoded_size for every pair + * of crypto's until a change rules otherwise. + * + * @tparam Format The format's type. + * @tparam T The value's type. + */ +template +inline constexpr std::size_t max_decode_input_size = + codecs::value_codec::max_decode_input_size; + +} // namespace formats + +namespace detail { + +/** + * A list of formats: crypto's own, `all_formats`, and each value type's, `formats_of`. + * + * @tparam Formats The formats, each a format of the base form. + */ +template +struct format_list {}; + +/** + * The library's one list of formats (design D1): the formats of keys and signatures, each of its + * base form, from which `is_format_v`, the check of every pair, the tests and the guide's table + * derive. A later format (JWK) is one more entry. + */ +using all_formats = + format_list, formats::spki_t<>, formats::pkcs8_t, formats::der_t, + formats::pem_t>, formats::pem_t>; + +/** + * A list of point forms: the ones a value type accepts for a format, `forms_of`. + * + * @tparam Forms The point forms. + */ +template +struct form_list {}; + +/** + * Whether `Item` is one of a `format_list`'s formats or a `form_list`'s forms. + * + * @tparam Item The type to look for. + * @tparam List The list. + */ +template +inline constexpr bool in_list_v = false; + +/** A format is in a list of formats when it is one of them. */ +template +inline constexpr bool in_list_v> = + (std::is_same_v || ...); + +/** A form is in a list of forms when it is one of them. */ +template +inline constexpr bool in_list_v> = (std::is_same_v || ...); + +/** + * The base form of `Format`, as the lists hold it: `raw_t` is `raw_t<>`, `spki_t` is + * `spki_t<>`, `pem_t>` is `pem_t>`; any other format is itself. + * + * @tparam Format The format's type. + */ +template +struct base_format { + /** The format itself. */ + using type = Format; +}; + +/** `raw` of any point form is `raw`. */ +template +struct base_format> { + /** The default form. */ + using type = formats::raw_t<>; +}; + +/** `spki` of any point form is `spki`. */ +template +struct base_format> { + /** The default form. */ + using type = formats::spki_t<>; +}; + +/** The PEM of a format is the PEM of its base form. */ +template +struct base_format> { + /** The PEM of the inner format's base form. */ + using type = formats::pem_t::type>; +}; + +/** + * The base form of `Format`. + * + * @tparam Format The format's type. + */ +template +using base_format_t = typename base_format::type; + +/** + * The point form `Format` names: `Form` for `raw_t` and `spki_t`, the inner format's + * for a PEM, `formats::default_form_t` for any other. + * + * @tparam Format The format's type. + */ +template +struct point_form_of { + /** A format without forms has the default. */ + using type = formats::default_form_t; +}; + +/** `raw`'s form. */ +template +struct point_form_of> { + /** The form it names. */ + using type = Form; +}; + +/** `spki`'s form. */ +template +struct point_form_of> { + /** The form it names. */ + using type = Form; +}; + +/** A PEM's form is its inner format's. */ +template +struct point_form_of> { + /** The inner format's form. */ + using type = typename point_form_of::type; +}; + +/** + * The format whose `forms_of` lists the point forms `Format` may name: a PEM's inner format's base + * form, `Format`'s base form otherwise, so that `pem(spki(compressed))` is accepted exactly where + * `spki(compressed)` is. + * + * @tparam Format The format's type. + */ +template +struct form_owner { + /** The base form. */ + using type = base_format_t; +}; + +/** A PEM's forms are its inner format's. */ +template +struct form_owner> { + /** The inner format's base form. */ + using type = base_format_t; +}; + +/** + * Whether `Format` is one of crypto's formats: its base form is in `all_formats`. + * + * @tparam Format The format's type. + */ +template +inline constexpr bool is_format_v = in_list_v, all_formats>; + +/** + * Whether every format of `List` is one of `all_formats`: what a curve's formats header asserts + * beside each `formats_of` it declares (design D1). + * + * @tparam List A `format_list`. + */ +template +inline constexpr bool known_formats_v = false; + +/** A list of formats is known when each of its formats is in `all_formats`. */ +template +inline constexpr bool known_formats_v> = + (in_list_v && ...); + +/** + * The formats a value type of crypto's has: a `format_list` of formats of `all_formats`, declared + * by the type's curve's `formats.hpp`, in one place beside its value codecs; `void` for a type + * whose formats header is not included. + * + * @tparam T The value's type. + */ +template +struct formats_of { + /** No formats declared. */ + using type = void; +}; + +/** + * The formats `T` has, or `void`. + * + * @tparam T The value's type. + */ +template +using formats_of_t = typename formats_of::type; + +/** + * The point forms `T` accepts for `Format`, a base form of its list: the default form alone unless + * the type's formats header specializes it. + * + * @tparam Format The base form of a format. + * @tparam T The value's type. + */ +template +struct forms_of { + /** The default form alone. */ + using type = form_list; +}; + +/** + * The point forms `T` accepts for `Format`. + * + * @tparam Format The base form of a format. + * @tparam T The value's type. + */ +template +using forms_of_t = typename forms_of::type; + +/** + * Whether the value type `T`, whose formats are `List`, refuses `Format`: the base form of + * `Format` is not in `List`, or the point form it names is not in `forms_of`. Its template + * arguments, the type's list among them, are what a compiler prints in the failed requirement of + * crypto's check (design D3); false for a type that declares no list. + * + * @tparam Format The format's type. + * @tparam T The value's type. + * @tparam List The type's `format_list`. + */ +template +inline constexpr bool format_refused = false; + +/** Refused when the base form is not listed, or the point form is not accepted. */ +template +inline constexpr bool format_refused> = + !in_list_v, format_list> || + !in_list_v::type, + forms_of_t::type, T>>; + +/** The curves whose types have formats: the one a type's formats header belongs to. */ +enum class curve_id : unsigned char { + /** Not a type of crypto's: the verbs leave the check to codecs. */ + none, + /** Ed25519's, `curves/ed25519/formats.hpp`. */ + ed25519, + /** X25519's, `curves/x25519/formats.hpp`. */ + x25519, + /** P-256's, `curves/p256/formats.hpp`. */ + p256, + /** secp256k1's, `curves/secp256k1/formats.hpp`. */ + secp256k1, +}; + +/** + * The curve of a value type of crypto's, which its curve's main header specializes, so that a call + * whose curve's formats header is not included says which header to include. + * + * @tparam T The value's type. + */ +template +inline constexpr curve_id curve_of_v = curve_id::none; + +/** + * Whether `T`'s formats are declared: its curve's formats header is included. + * + * @tparam T The value's type. + */ +template +inline constexpr bool formats_declared_v = !std::is_void_v>; + +/** + * A pair's own reason for its refusal, which adds a fixed sentence to crypto's check (design D3). + */ +enum class refusal_reason : unsigned char { + /** No reason of its own: the type's list says it. */ + none, + /** `der` of an Ed25519 or BIP340 signature, which has no DER form. */ + no_der_ed25519_bip340, + /** `der` of a recoverable signature, which has no DER form. */ + no_der_recoverable, + /** `raw(xonly)` decoded into a `curves::secp256k1::public_key`. */ + xonly_into_public_key, + /** A private format of a key pair whose secret lives in WebCrypto. */ + private_on_asynchronous, +}; + +/** + * The reason a curve gives for refusing `Format` on `T` in both directions; `none` unless the + * curve's formats header specializes it. + * + * @tparam Format The format's type. + * @tparam T The value's type. + */ +template +inline constexpr refusal_reason refusal_reason_v = refusal_reason::none; + +/** + * The reason a curve gives for refusing `Format` on `T` when decoding alone, consulted by + * `crypto::decode` before `refusal_reason_v` (an encode-only pair, as `raw(xonly)` of a + * `curves::secp256k1::public_key`); `none` unless the curve's formats header specializes it. + * + * @tparam Format The format's type. + * @tparam T The value's type. + */ +template +inline constexpr refusal_reason decode_refusal_reason_v = refusal_reason::none; + +/** + * Whether a change has ruled that the decode bound of the value codec of `Format` and `T` may + * differ from its `max_encoded_size`: false for every pair of this library. + * + * @tparam Format The format's type. + * @tparam T The value's type. + */ +template +inline constexpr bool bounds_may_differ_v = false; + +/** + * Stops the build when the value codec of `Format` and `T`, one of crypto's that decodes, states no + * decode bound, or states one other than its `max_encoded_size` where no change has ruled that + * they differ (design R37). A curve's formats header calls it beside its `formats_of`, once per + * pair of the list that decodes and is not a PEM, whose bound is its inner format's. + * + * @tparam Format The format's type. + * @tparam T The value's type. + * @return True, for the `static_assert` that calls it. + */ +template +consteval bool check_bounds() noexcept { + static_assert( + requires { codecs::value_codec::max_decode_input_size; }, + "webcpp::crypto: a value codec that decodes states max_decode_input_size, its " + "decode bound"); + if constexpr (requires { codecs::value_codec::max_decode_input_size; }) { + static_assert( + webcpp::crypto::detail::bounds_may_differ_v || + formats::max_decode_input_size == formats::max_encoded_size, + "webcpp::crypto: the decode bound equals max_encoded_size until a change " + "rules otherwise"); + } + return true; +} + +/** + * Whether the value codec of `Format` and `Value` is secret: it states `secret`, and it is true. + * The member is optional in codecs' contract, and absent from a public value codec. + * + * @tparam Format The format's type. + * @tparam Value The value's type. + */ +template +inline constexpr bool value_codec_secret_v = + requires { requires static_cast(codecs::value_codec::secret); }; + +/** + * Whether crypto checks a call of `Format` on `Value`: `Value` is a type of crypto's and `Format` + * a format of crypto's. Any other pair is codecs' to check. + * + * @tparam Format The format's type. + * @tparam Value The value's type. + */ +template +inline constexpr bool checked_by_crypto_v = + curve_of_v != curve_id::none && is_format_v; + +/** + * Whether the pair passes crypto's check, in the direction `Decoding` says: always for a pair + * crypto does not check; else the type's formats are declared, the pair has no reason of its own, + * its list holds the format and its form, and codecs converts it. + * + * @tparam Decoding Whether the call decodes. + * @tparam Format The format's type. + * @tparam Value The value's type. + * @return Whether the call may proceed to codecs. + */ +template +constexpr bool pair_accepted() noexcept { + if constexpr (!checked_by_crypto_v) { + return true; + } else if constexpr (!formats_declared_v) { + return false; + } else if constexpr (Decoding && + decode_refusal_reason_v != refusal_reason::none) { + return false; + } else if constexpr (refusal_reason_v != refusal_reason::none) { + return false; + } else if constexpr (format_refused>) { + return false; + } else if constexpr (Decoding) { + return codecs::decodable; + } else { + return codecs::encodable; + } +} + +/** + * Stops the build with the sentence of `Reason` (design D3). + * + * @tparam Reason The pair's reason, not `none`. + */ +template +constexpr void refuse_for_reason() noexcept { + static_assert(Reason != refusal_reason::no_der_ed25519_bip340, + "webcpp::crypto: Ed25519 and BIP340 signatures have no DER form; their 64 bytes " + "are the signature"); + static_assert(Reason != refusal_reason::no_der_recoverable, + "webcpp::crypto: a recoverable signature has no DER form"); + static_assert(Reason != refusal_reason::xonly_into_public_key, + "webcpp::crypto: an x-only key decodes into " + "curves::secp256k1::xonly_public_key"); + static_assert(Reason != refusal_reason::private_on_asynchronous, + "webcpp::crypto: this key pair's secret lives in WebCrypto: export it with " + "WebCrypto's exportKey, which this backend does not offer synchronously"); +} + +/** + * Stops the build for a pair `pair_accepted` refuses, with the first of crypto's sentences that + * applies (design D3): the formats header to include; the pair's own reason; that the type has no + * such format, the type's list printed in the failed requirement; or that codecs does not convert + * the pair in this direction. + * + * @tparam Decoding Whether the call decodes. + * @tparam Format The format's type. + * @tparam Value The value's type. + */ +template +constexpr void refuse_pair() noexcept { + if constexpr (!formats_declared_v) { + static_assert(curve_of_v != curve_id::ed25519 || formats_declared_v, + "webcpp::crypto: include to " + "encode or decode this type"); + static_assert(curve_of_v != curve_id::x25519 || formats_declared_v, + "webcpp::crypto: include to " + "encode or decode this type"); + static_assert(curve_of_v != curve_id::p256 || formats_declared_v, + "webcpp::crypto: include to encode " + "or decode this type"); + static_assert(curve_of_v != curve_id::secp256k1 || formats_declared_v, + "webcpp::crypto: include to " + "encode or decode this type"); + } else if constexpr (Decoding && + decode_refusal_reason_v != refusal_reason::none) { + refuse_for_reason>(); + } else if constexpr (refusal_reason_v != refusal_reason::none) { + refuse_for_reason>(); + } else if constexpr (format_refused>) { + // Qualified, so that the failed requirement names the trait and the type's list. + static_assert(!webcpp::crypto::detail::format_refused>, + "webcpp::crypto: this type has no such format; the formats it has are the " + "format_list named in this assertion"); + } else if constexpr (Decoding) { + static_assert(codecs::decodable, + "webcpp::crypto: this type lists the format, and no codecs::value_codec of " + "the pair decodes it"); + } else { + static_assert(codecs::encodable, + "webcpp::crypto: this type lists the format, and no codecs::value_codec of " + "the pair encodes it"); + } +} + +/** + * Whether `crypto::encode` of the pair, with `Rest`, cannot throw: codecs' verb's own answer for a + * pair that passes the check (a pair of crypto's is `noexcept`). + * + * @tparam Format The format's type. + * @tparam Value The value's type. + * @tparam Rest The output or the token, if any. + * @return Whether the call is `noexcept`. + */ +template +constexpr bool encode_is_noexcept() noexcept { + if constexpr (pair_accepted()) { + return noexcept(codecs::encode(std::declval(), std::declval(), + std::declval()...)); + } else { + return true; + } +} + +/** + * The inner format of a PEM format, `type`; none for another format. + * + * @tparam Format The format's type. + */ +template +struct pem_inner {}; + +/** The inner link of a PEM. */ +template +struct pem_inner> { + /** The DER format inside the armor. */ + using type = Inner; +}; + +/** + * Whether `crypto::decode(format, input)` decodes in place (design R24): `Format` is a PEM, + * `Input` is a text, and the inner value codec decodes bytes into `Value` and states its decode + * bound. + * + * @tparam Value The value's type. + * @tparam Format The format's type. + * @tparam Input The input's type. + */ +template +inline constexpr bool decodes_in_place_v = false; + +/** A PEM of a text, whose inner value codec states its decode bound, decodes in place. */ +template +inline constexpr bool decodes_in_place_v, Input> = requires { + requires std::is_convertible_v; + requires codecs::decodable; + requires codecs::value_codec::output == codecs::output_kind::bytes; + requires codecs::value_codec::max_decode_input_size > 0; +}; + +/** + * Whether `crypto::decode` of `Input` in `Format` cannot throw: the in-place PEM decode is + * `noexcept`; any other is as codecs' verb, `noexcept` for every pair of crypto's. + * + * @tparam Value The value's type. + * @tparam Format The format's type. + * @tparam Input The input's type. + * @return Whether the call is `noexcept`. + */ +template +constexpr bool decode_is_noexcept() noexcept { + if constexpr (!pair_accepted() || + decodes_in_place_v) { + return true; + } else { + return noexcept( + codecs::decode(std::declval(), std::declval())); + } +} + +/** + * The two steps of the in-place PEM decode into `der`: the armor through codecs' buffer form, then + * the inner value codec over the bytes it wrote. A payload longer than `der` is crypto's + * `invalid_encoding`; every other error of either step is returned unchanged. + * + * @tparam Value The value's type. + * @tparam Format The PEM format's type. + * @tparam Text The text's type. + * @param format The PEM format. + * @param text The PEM text. + * @param der The buffer of the inner format's decode bound. + * @return The value, or the error. + */ +template +[[nodiscard]] codecs::result decode_pem_into(Format const& format, Text const& text, + std::span der) noexcept { + codecs::result const written = codecs::decode(format.outer, text, der); + if (!written) { + if (written.error() == codecs::error::output_too_small) { + return error::invalid_encoding; + } + return written.error(); + } + // Read unchecked: the error was returned above. + return codecs::decode(format.inner, + std::span(der.first(written.unsafe_value()))); +} + +/** + * Decodes the PEM `text` into a `Value` in place (design R24): the armor through codecs' buffer + * form into a stack buffer of the inner format's decode bound, `max_decode_input_size` (owner + * decision 23), then the inner value codec, allocating nothing. A payload longer than that buffer + * is crypto's `invalid_encoding`; the armor's errors are codecs', unchanged, and come first, as + * `codecs::decode` gives them. When the inner value codec is secret, or the value is + * (`codecs::is_secret_v`), the call holds `secure::timing_guard` and the buffer is wiped by + * `secure::erase_secret` on every path. + * + * @tparam Value The value's type. + * @tparam Format The PEM format's type, `formats::pem_t`. + * @tparam Text The text's type. + * @param format The PEM format. + * @param text The PEM text. + * @return The value, or the error. + */ +template +[[nodiscard]] codecs::result decode_pem(Format const& format, Text const& text) noexcept { + using inner_type = typename pem_inner::type; + constexpr bool secret = value_codec_secret_v || codecs::is_secret_v; + secure::timing_guard const timing_scope{secret}; + std::array> der{}; + codecs::result decoded = decode_pem_into(format, text, std::span(der)); + if constexpr (secret) { + secure::erase_secret(der); + } + return decoded; +} + +} // namespace detail + +/** + * Encodes `value` in `format`: checks the pair against crypto's list, then returns + * `codecs::encode(format, value, rest...)` (design R18), codecs' default result (`bytes`, + * `text`, `secret_bytes`, `secret_text`, `N` the value codec's `max_encoded_size`), the + * result of a token of codecs' (`codecs::tokens::append_to(text)`), or, into a caller's + * `std::span` or `std::span`, the size written. + * + * For a type of crypto's and a format of crypto's, the build stops when the type's curve's formats + * header is not included, when the pair has a reason of its own (an Ed25519 signature has no DER + * form), when the type's list lacks the format or its point form (the list printed in the failed + * requirement), or when no value codec encodes the pair. Any other pair is passed to codecs + * untouched. The span form refuses an output shorter than the exact encoding with + * `codecs::error::output_too_small` and writes nothing on any error (design R34). + * + * @tparam Format The format's type. + * @tparam Value The value's type. + * @tparam Rest The output or the token, if any. + * @param format The format. + * @param value The value. + * @param rest Nothing, a token of codecs', or the caller's output. + * @return The encoding, or the error. + */ +template +[[nodiscard]] auto encode(Format const& format, Value const& value, Rest&&... rest) noexcept( + detail::encode_is_noexcept()) { + if constexpr (detail::pair_accepted()) { + return codecs::encode(format, value, std::forward(rest)...); + } else { + detail::refuse_pair(); + return codecs::result{std::size_t{0}}; + } +} + +/** + * Decodes `input` in `format` into a `Value`: checks the pair against crypto's list, as `encode` + * does, then decodes a PEM text in place (design R24), and anything else with + * `codecs::decode(format, input)` (design R18). + * + * `input` is a `std::span` (or any byte input) for a binary format and a + * `std::string_view` (or any text) for a PEM, as the value codec's output kind says (design R4). + * The PEM's armor is codecs': lines ended by a line feed or a carriage return and a line feed, the + * last ending optional, nothing before BEGIN or after END; its errors are codecs'; a payload longer + * than the inner format's decode bound is `crypto::error::invalid_encoding`. `noexcept` on every + * pair of crypto's; a pair crypto does not check is as `codecs::decode` is, which allocates + * for a heap result. + * + * @tparam Value The value's type. + * @tparam Format The format's type. + * @tparam Input The input's type. + * @param format The format. + * @param input The bytes, or the text. + * @return The value, or the error. + */ +template +[[nodiscard]] codecs::result decode(Format const& format, Input const& input) noexcept( + detail::decode_is_noexcept()) { + if constexpr (!detail::pair_accepted()) { + detail::refuse_pair(); + return error::invalid_encoding; + } else if constexpr (detail::decodes_in_place_v) { + return detail::decode_pem(format, input); + } else { + return codecs::decode(format, input); + } +} + +} // namespace webcpp::crypto + +#endif // WEBCPP_CRYPTO_FORMATS_HPP diff --git a/meta/include-boundaries.json b/meta/include-boundaries.json index 93471c56..81ef461d 100644 --- a/meta/include-boundaries.json +++ b/meta/include-boundaries.json @@ -16,6 +16,20 @@ ], "must-not-include": ["bearssl", "openssl/", "ctaes", "secp256k1", "webcpp/crypto/backends/"], "why": "a program that only draws random bytes names no backend library (spec section 2.2), nor does the signing vocabulary every curve shares, nor the key pair concepts with their free sign and agree, which give webcpp::secure's self-wiping secret, nor the free factories (from_secret, from_bytes, from_key, generate) every AEAD's header includes, nor the AEAD and box contracts with their free seal and open, which every AEAD's and box's header includes; the detail headers these include are in the boundary too, since the rule is not transitive" + }, + { + "headers": [ + "include/webcpp/crypto.hpp", + "include/webcpp/crypto/*.hpp", + "include/webcpp/crypto/*/*.hpp", + "include/webcpp/crypto/*/*/*.hpp" + ], + "except": [ + "include/webcpp/crypto/formats.hpp", + "include/webcpp/crypto/curves/*/formats.hpp" + ], + "must-not-include": ["webcpp/codecs"], + "why": "only the formats headers register into codecs: formats.hpp and each curve's formats.hpp include a codecs header, and no other header of crypto includes one: a curve's own header never includes its formats header (design D2), so that a program that includes a curve's header and not its formats header compiles no codecs (design R32)" } ] } diff --git a/test/Jamfile b/test/Jamfile index e34c946d..bc18430a 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -41,7 +41,7 @@ webcpp.headers-alone crypto : ../include : crypto.hpp crypto/config.hpp crypto/secret_key_encryption/secretbox.hpp crypto/detail/p_curves.hpp crypto/signing.hpp crypto/keypair.hpp crypto/factories.hpp crypto/detail/asynchronous.hpp - crypto/detail/signature.hpp ; + crypto/detail/signature.hpp crypto/formats.hpp ; # detail/heavy.hpp compiles alone only with webcpp::asio, which it includes # where the build has threads; async.hpp, which includes it, only with # webcpp::asio on every target. @@ -214,6 +214,30 @@ crypto-run signing : signing_test.cpp ; # message signs. crypto-run signing_namespaces : signing_namespaces_test.cpp : /third_party//bearssl ; +# The formats' vocabulary (design D1): each tag a codecs::format, named +# whatever its point form and made from no braces; raw and spki take a point +# form, spki no x-only one; pem's label from the inner format; the one list, +# is_format_v and base_format_t. +crypto-run formats_vocabulary : formats_vocabulary_test.cpp ; +# The verbs over the tests' toy type (support/formats_toy.hpp): every form +# gives one encoding, nothing on the heap, strict decoding, secret results +# wiped when moved from, the two bounds and check_bounds, a moved-from key +# pair refused, a type crypto does not own passed to codecs untouched; the +# wipes through secure's seam (support/wipe_record.hpp). +crypto-run formats_verbs : formats_verbs_test.cpp + : WEBCPP_SECURE_TEST_WIPE_RECORD ; +# The in-place PEM decode over the toy (design R24): the text OpenSSL writes, +# its CRLF form and one without the final line feed, no heap where codecs' +# decode of a std::string_view has one, the armor's refusals, a payload past +# the decode bound (an RSA key's) invalid_encoding, the DER buffer wiped after +# a pkcs8, the guard held for a private format alone, the same values and +# errors as codecs::decode. +crypto-run formats_pem : formats_pem_test.cpp + : WEBCPP_SECURE_TEST_WIPE_RECORD ; +# The room for JWK (design R17): a stand-in text format of the tests' own, +# added to a copy of the list, through crypto::encode and crypto::decode with +# no change to either. +crypto-run formats_stand_in : formats_stand_in_test.cpp ; # The three key pair concepts, keypair, signing_keypair and agreement_keypair: # stand-ins that sign, agree, do both, lack a member or sign or agree into # another type give each verdict; the four curves' key pairs give D4's table, diff --git a/test/formats_pem_test.cpp b/test/formats_pem_test.cpp new file mode 100644 index 00000000..9922d9a1 --- /dev/null +++ b/test/formats_pem_test.cpp @@ -0,0 +1,366 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// PEM over the tests' toy type (design R23, R24, owner decision 23, Review Focus 1 and 5): +// crypto::encode(pem(spki), key) is codecs' armor of the SPKI, labelled from the inner format; +// crypto::decode reads it back in place, also with CRLF lines and without its final line feed, +// allocating nothing where codecs::decode of a std::string_view puts its intermediate on the heap +// (the documented difference); the armor's refusals are codecs' (a CERTIFICATE label, text before +// BEGIN); a payload past the inner format's decode bound, an RSA key's SPKI, and an armor of no +// bytes are invalid_encoding, nothing on the heap; the DER buffer is sized by the decode bound, so +// that pkcs8's 16-byte "version 2" decodes where a buffer of max_encoded_size would refuse it, and +// is wiped after a pkcs8, the guard held for a private format alone; every text gives the same +// value or the same error through crypto::decode and codecs::decode. + +// The timing seam is defined before any webcpp header reads secure's guard. +#include "support/timing_seam.hpp" + +#include "support/format_checks.hpp" +#include "support/formats_toy.hpp" + +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace crypto = webcpp::crypto; +namespace codecs = webcpp::codecs; +namespace formats = webcpp::crypto::formats; +using webcpp::crypto::test::toy_key; +using webcpp::crypto::test::toy_keypair; + +namespace { + +constexpr std::array key_bytes{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}; +constexpr std::array secret_bytes{0xa1, 0xb2, 0xc3, 0xd4, 0xe5, 0xf6, 0x07, 0x18}; +constexpr std::array key_spki{0x30, 0x0a, 0x30, 0x00, 0x01, 0x02, + 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}; +constexpr std::array key_pair_pkcs8_v2{ + 0x30, 0x0e, 0x02, 0x01, 0xa1, 0xb2, 0xc3, 0xd4, 0xe5, 0xf6, 0x07, 0x18, 0xa1, 0x02, 0xa1, 0xb2}; + +// The PEM of key_spki, as OpenSSL's PEM_write_bio writes an armor: the base64 of the 12 bytes. +constexpr std::string_view key_pem = + "-----BEGIN PUBLIC KEY-----\nMAowAAECAwQFBgcI\n-----END PUBLIC KEY-----\n"; + +// A 2048-bit RSA public key, whose SubjectPublicKeyInfo is 294 bytes of DER (Review Focus 5), made +// once with OpenSSL 4.1: +// openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 | openssl pkey -pubout +constexpr std::string_view rsa_pem = + "-----BEGIN PUBLIC KEY-----\n" + "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArpJaM2Yn8RLXSleDrssG\n" + "eF2cVvTEVY39sZVHIru8gHpPYSiI6DZJM7T2m1xRk7dPwzeH9DMNMrLRXwDkBUh0\n" + "1/utEVq5f/fPZyHkvk0D+QRWJl5vytW6cKd0Ppziei8fs31HxysqJgddGeFHcxlW\n" + "rEP5MDs3grF+laLFQpAGgm0Ad2XKTy1Z6ESgHunEyIyovcnZuu1GKL1ygROsj8ih\n" + "RySEfJ3CjofcaqGCK9qV/2bXE1ALXk8qEpU/LZ6jQ5XHqxUG3GAAQnXe+Usi/4UT\n" + "8JD+90Gi8/JBHn5LCQEVIQa595+1mBc/hylfLMz44cgjJ4wkG1c0NRcE8tzPd7Ys\n" + "DwIDAQAB\n" + "-----END PUBLIC KEY-----\n"; + +/** `text` with every line feed made a carriage return and a line feed. */ +std::string with_crlf(std::string_view text) { + std::string crlf; + for (char const character : text) { + if (character == '\n') { + crlf += '\r'; + } + crlf += character; + } + return crlf; +} + +/** The armor of `der` under `label`, through codecs' own armor. */ +std::string armored(std::string_view label, std::span der) { + auto const text = + codecs::encode(codecs::formats::armor(label), der, codecs::tokens::return_string); + BOOST_TEST(text.has_value()); + return text ? *text : std::string{}; +} + +/** The PEM of the toy key is the armor of its SPKI, labelled PUBLIC KEY; every form gives it. */ +void encode_public() { + toy_key const key{key_bytes}; + auto const encoded = crypto::encode(formats::pem(formats::spki), key); + using result_type = decltype(encoded)::value_type; + constexpr std::size_t capacity = + codecs::value_codec>, toy_key>::max_encoded_size; + static_assert(std::is_same_v>); + static_assert(formats::max_encoded_size>, toy_key> == + capacity); + auto const payload = codecs::encode(codecs::formats::base64, key_spki); + if (BOOST_TEST(encoded.has_value()) && BOOST_TEST(payload.has_value())) { + BOOST_TEST(encoded->view() == key_pem); + std::string const oracle = "-----BEGIN PUBLIC KEY-----\n" + std::string(payload->view()) + + "\n-----END PUBLIC KEY-----\n"; + BOOST_TEST(encoded->view() == oracle); + BOOST_TEST_EQ(encoded->capacity(), capacity); + } + std::vector const pem_bytes(key_pem.begin(), key_pem.end()); + crypto::test::check_every_form(formats::pem(formats::spki), key, pem_bytes); +} + +/** The PEM of the toy key pair is the armor of its PKCS#8, labelled PRIVATE KEY, secret. */ +void encode_private() { + auto const key_pair = toy_keypair::from_secret(secret_bytes); + auto const encoded = crypto::encode(formats::pem(formats::pkcs8), key_pair); + using result_type = decltype(encoded)::value_type; + static_assert(std::is_same_v, toy_keypair>>>); + std::array const pkcs8{0x30, 0x0a, 0x02, 0x00, 0xa1, 0xb2, + 0xc3, 0xd4, 0xe5, 0xf6, 0x07, 0x18}; + std::string const expected = armored("PRIVATE KEY", pkcs8); + if (BOOST_TEST(encoded.has_value())) { + BOOST_TEST(encoded->view() == expected); + BOOST_TEST(encoded->view().starts_with("-----BEGIN PRIVATE KEY-----\n")); + } + std::vector const pem_bytes(expected.begin(), expected.end()); + crypto::test::check_every_form(formats::pem(formats::pkcs8), key_pair, pem_bytes); + crypto::test::check_secret_result(formats::pem(formats::pkcs8), key_pair); +} + +/** + * The text OpenSSL's tools write, its CRLF form and one without the final line feed decode to the + * key (Review Focus 1). + */ +void decode_variants() { + toy_key const key{key_bytes}; + std::string const crlf = with_crlf(key_pem); + std::string_view const no_final_line_feed = key_pem.substr(0, key_pem.size() - 1); + for (std::string_view const text : {key_pem, std::string_view{crlf}, no_final_line_feed}) { + auto const decoded = crypto::decode(formats::pem(formats::spki), text); + if (BOOST_TEST(decoded.has_value())) { + BOOST_TEST(*decoded == key); + } + } + auto const from_string = + crypto::decode(formats::pem(formats::spki), std::string{key_pem}); + if (BOOST_TEST(from_string.has_value())) { + BOOST_TEST(*from_string == key); + } +} + +/** + * The in-place decode allocates nothing; codecs::decode of the same std::string_view holds its + * intermediate on the heap (design R24, the guide's documented difference). + */ +void decode_in_place() { + std::size_t const before = webcpp::test::allocations(); + auto const in_place = crypto::decode(formats::pem(formats::spki), key_pem); + std::size_t const after_in_place = webcpp::test::allocations(); + auto const through_codecs = codecs::decode(formats::pem(formats::spki), key_pem); + std::size_t const after_codecs = webcpp::test::allocations(); + BOOST_TEST_EQ(after_in_place, before); + BOOST_TEST_GT(after_codecs, after_in_place); + BOOST_TEST(in_place.has_value()); + BOOST_TEST(through_codecs.has_value()); +} + +/** + * The armor's refusals are codecs': a certificate given as a key and explanatory text before BEGIN + * are invalid_prefix, never a key (Review Focus 1). + */ +void armor_refusals() { + std::string const certificate = armored("CERTIFICATE", key_spki); + BOOST_TEST(crypto::decode(formats::pem(formats::spki), certificate).error() == + codecs::error::invalid_prefix); + std::string const explained = "Public-Key: (64 bit)\n" + std::string{key_pem}; + BOOST_TEST(crypto::decode(formats::pem(formats::spki), explained).error() == + codecs::error::invalid_prefix); + BOOST_TEST(crypto::decode(formats::pem(formats::pkcs8), key_pem).error() == + codecs::error::invalid_prefix); +} + +/** + * A payload past the inner format's decode bound, an RSA key's SPKI of 294 bytes, and an armor of + * no bytes are invalid_encoding, with nothing on the heap (Review Focus 5); the payload of 294 + * bytes is written nowhere past the stack buffer (the fuzz lane's address sanitizer reads that). + */ +void payload_past_the_bound() { + std::size_t const before = webcpp::test::allocations(); + auto const rsa = crypto::decode(formats::pem(formats::spki), rsa_pem); + std::size_t const after = webcpp::test::allocations(); + BOOST_TEST_EQ(after, before); + BOOST_TEST(rsa.error() == crypto::error::invalid_encoding); + auto const rsa_der = codecs::decode(codecs::formats::armor("PUBLIC KEY"), rsa_pem); + if (BOOST_TEST(rsa_der.has_value())) { + BOOST_TEST_EQ(rsa_der->size(), 294U); + } + std::string const empty = armored("PUBLIC KEY", {}); + BOOST_TEST_EQ(empty, std::string{"-----BEGIN PUBLIC KEY-----\n-----END PUBLIC KEY-----\n"}); + BOOST_TEST(crypto::decode(formats::pem(formats::spki), empty).error() == + crypto::error::invalid_encoding); +} + +/** + * The DER buffer is sized by the inner format's decode bound (owner decision 23): the toy key + * pair's pkcs8 "version 2", 16 bytes, past its max_encoded_size of 12, decodes in place; 17 bytes + * are invalid_encoding. + */ +void decode_bound_sizes_the_buffer() { + static_assert(formats::max_encoded_size == 12); + static_assert(formats::max_decode_input_size == 16); + std::string const version_2 = armored("PRIVATE KEY", key_pair_pkcs8_v2); + std::size_t const before = webcpp::test::allocations(); + auto const decoded = crypto::decode(formats::pem(formats::pkcs8), version_2); + std::size_t const after = webcpp::test::allocations(); + BOOST_TEST_EQ(after, before); + if (BOOST_TEST(decoded.has_value())) { + BOOST_TEST(std::ranges::equal(decoded->secret(), secret_bytes)); + } + std::array longer{}; + std::ranges::copy(key_pair_pkcs8_v2, longer.begin()); + BOOST_TEST( + crypto::decode(formats::pem(formats::pkcs8), armored("PRIVATE KEY", longer)) + .error() == crypto::error::invalid_encoding); +} + +/** + * The DER buffer of a pkcs8 is wiped, its whole decode bound, on success and on error; the one of a + * public decode is not. secure's wipe record sees every wipe leave only zero bytes. + */ +void buffer_wiped() { + auto const key_pair = toy_keypair::from_secret(secret_bytes); + auto const encoded = crypto::encode(formats::pem(formats::pkcs8), key_pair); + if (!BOOST_TEST(encoded.has_value())) { + return; + } + constexpr std::size_t buffer_size = + formats::max_decode_input_size; + webcpp::test::clear_wipes(); + { + auto const decoded = + crypto::decode(formats::pem(formats::pkcs8), encoded->view()); + BOOST_TEST(decoded.has_value()); + std::vector const sizes = webcpp::test::wiped_sizes(); + BOOST_TEST(std::ranges::count(sizes, buffer_size) == 1); + } + webcpp::test::clear_wipes(); + { + std::string const corrupt = armored("PRIVATE KEY", std::span(key_pair_pkcs8_v2).first(15)); + auto const refused = crypto::decode(formats::pem(formats::pkcs8), corrupt); + BOOST_TEST(refused.error() == crypto::error::invalid_encoding); + std::vector const sizes = webcpp::test::wiped_sizes(); + BOOST_TEST(std::ranges::count(sizes, buffer_size) == 1); + } + { + auto const refused = crypto::decode(formats::pem(formats::pkcs8), + armored("CERTIFICATE", key_spki)); + BOOST_TEST(refused.error() == codecs::error::invalid_prefix); + std::vector const sizes = webcpp::test::wiped_sizes(); + BOOST_TEST(std::ranges::count(sizes, buffer_size) == 1); + } + { + auto const decoded = crypto::decode(formats::pem(formats::spki), key_pem); + BOOST_TEST(decoded.has_value()); + // codecs' armor wipes its own state on every call; crypto wipes no buffer of a public key. + std::vector const sizes = webcpp::test::wiped_sizes(); + BOOST_TEST(std::ranges::count( + sizes, formats::max_decode_input_size, toy_key>) == 0); + } +} + +/** + * The in-place decode of a private format holds crypto's guard, decode_pem's, first; a public one + * enters none of crypto's. + */ +void guard_for_a_private_format() { + auto const key_pair = toy_keypair::from_secret(secret_bytes); + auto const encoded = crypto::encode(formats::pem(formats::pkcs8), key_pair); + if (!BOOST_TEST(encoded.has_value())) { + return; + } + webcpp::test::require_enters("detail::decode_pem of pem(pkcs8)", [&] { + BOOST_TEST( + crypto::decode(formats::pem(formats::pkcs8), encoded->view()).has_value()); + }); + webcpp::test::require_enters("detail::decode_pem of pem(pkcs8), refused", [&] { + BOOST_TEST(crypto::decode(formats::pem(formats::pkcs8), key_pem).error() == + codecs::error::invalid_prefix); + }); + webcpp::test::uncovered("detail::decode_pem of pem(spki)", [&] { + BOOST_TEST(crypto::decode(formats::pem(formats::spki), key_pem).has_value()); + }); +} + +/** crypto::decode and codecs::decode give the same value, or the same error, on every text. */ +void same_as_codecs() { + std::string const crlf = with_crlf(key_pem); + std::string const certificate = armored("CERTIFICATE", key_spki); + std::string const explained = "Public-Key: (64 bit)\n" + std::string{key_pem}; + std::string const empty = armored("PUBLIC KEY", {}); + std::string const version_2 = armored("PRIVATE KEY", key_pair_pkcs8_v2); + std::array longer{}; + std::ranges::copy(key_pair_pkcs8_v2, longer.begin()); + std::string const too_long = armored("PRIVATE KEY", longer); + auto const key_pair = toy_keypair::from_secret(secret_bytes); + auto const private_pem = crypto::encode(formats::pem(formats::pkcs8), key_pair); + if (!BOOST_TEST(private_pem.has_value())) { + return; + } + std::string const private_text{private_pem->view()}; + std::vector const texts{std::string{key_pem}, + crlf, + std::string{key_pem.substr(0, key_pem.size() - 1)}, + certificate, + explained, + std::string{rsa_pem}, + empty, + version_2, + too_long, + private_text, + "", + "-----BEGIN PUBLIC KEY-----\n"}; + for (std::string const& text : texts) { + auto const in_place = crypto::decode(formats::pem(formats::spki), text); + auto const through_codecs = codecs::decode(formats::pem(formats::spki), text); + BOOST_TEST_EQ(in_place.has_value(), through_codecs.has_value()); + if (in_place && through_codecs) { + BOOST_TEST(*in_place == *through_codecs); + } else if (!in_place && !through_codecs) { + BOOST_TEST(in_place.error() == through_codecs.error()); + } + auto const private_in_place = + crypto::decode(formats::pem(formats::pkcs8), text); + auto const private_through_codecs = + codecs::decode(formats::pem(formats::pkcs8), text); + BOOST_TEST_EQ(private_in_place.has_value(), private_through_codecs.has_value()); + if (private_in_place && private_through_codecs) { + BOOST_TEST( + std::ranges::equal(private_in_place->secret(), private_through_codecs->secret())); + } else if (!private_in_place && !private_through_codecs) { + BOOST_TEST(private_in_place.error() == private_through_codecs.error()); + } + } +} + +} // namespace + +int main() { + encode_public(); + encode_private(); + decode_variants(); + decode_in_place(); + armor_refusals(); + payload_past_the_bound(); + decode_bound_sizes_the_buffer(); + buffer_wiped(); + guard_for_a_private_format(); + same_as_codecs(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/formats_stand_in_test.cpp b/test/formats_stand_in_test.cpp new file mode 100644 index 00000000..e9a7f9f6 --- /dev/null +++ b/test/formats_stand_in_test.cpp @@ -0,0 +1,97 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the 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 room for JWK (design D1, R17): a text format of the tests' own, the stand-in of +// support/formats_toy.hpp, added to a copy of the library's one list, goes through crypto::encode +// and crypto::decode, which give codecs' text result and take a std::string_view, with no change to +// either; over the toy key's list with the stand-in added, crypto's check accepts it and still +// refuses der, as it does on the toy key's own list. + +#include "support/formats_toy.hpp" + +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include + +namespace crypto = webcpp::crypto; +namespace codecs = webcpp::codecs; +namespace formats = webcpp::crypto::formats; +namespace detail = webcpp::crypto::detail; +using webcpp::crypto::test::all_formats_with_stand_in; +using webcpp::crypto::test::stand_in_text_t; +using webcpp::crypto::test::toy_key; + +namespace { + +/** The toy key's list with the stand-in added, as a type that had a JWK would list it. */ +using toy_key_formats_with_stand_in = + webcpp::crypto::test::appended, stand_in_text_t>::type; + +// The copy holds the library's six formats and the stand-in; the library's own list is unchanged. +static_assert( + std::is_same_v, formats::spki_t<>, formats::pkcs8_t, + formats::der_t, formats::pem_t>, + formats::pem_t, stand_in_text_t>>); +static_assert(detail::in_list_v); +static_assert(!detail::in_list_v); +static_assert(!detail::is_format_v); + +// crypto's check over the list with the stand-in: the stand-in is no refusal, der still is. +static_assert(!detail::format_refused); +static_assert(detail::format_refused); +static_assert(detail::format_refused>); +static_assert(!detail::format_refused, toy_key, toy_key_formats_with_stand_in>); + +// codecs' concepts and results take the stand-in as they take crypto's formats. +static_assert(codecs::format); +static_assert(codecs::encodable); +static_assert(codecs::decodable); +static_assert(formats::max_encoded_size == 16); +static_assert(formats::max_decode_input_size == 16); + +/** The stand-in through crypto's verbs, which give codecs' text result and take a text. */ +void through_the_verbs() { + toy_key const key{std::array{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}}; + auto const encoded = crypto::encode(webcpp::crypto::test::stand_in_text, key); + static_assert(std::is_same_v>); + if (BOOST_TEST(encoded.has_value())) { + BOOST_TEST(encoded->view() == std::string_view{"0102030405060708"}); + } + std::string appended = "jwk: "; + auto const token = crypto::encode(webcpp::crypto::test::stand_in_text, key, + codecs::tokens::append_to(appended)); + BOOST_TEST(token.has_value()); + BOOST_TEST_EQ(appended, std::string{"jwk: 0102030405060708"}); + + auto const decoded = crypto::decode(webcpp::crypto::test::stand_in_text, + std::string_view{"0102030405060708"}); + if (BOOST_TEST(decoded.has_value())) { + BOOST_TEST(*decoded == key); + } + BOOST_TEST(crypto::decode(webcpp::crypto::test::stand_in_text, + std::string_view{"010203040506070G"}) + .error() == crypto::error::invalid_encoding); + BOOST_TEST(crypto::decode(webcpp::crypto::test::stand_in_text, + std::string_view{"01020304050607"}) + .error() == crypto::error::invalid_encoding); +} + +} // namespace + +int main() { + through_the_verbs(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/formats_verbs_test.cpp b/test/formats_verbs_test.cpp new file mode 100644 index 00000000..7846d5d2 --- /dev/null +++ b/test/formats_verbs_test.cpp @@ -0,0 +1,263 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the 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::encode and crypto::decode over the tests' toy type (support/formats_toy.hpp), the +// contract every curve's formats stand on (design D2, D3, D11, R18 to R22, R34, R35, R37, owner +// decision 23): every form of each pair gives one encoding and decodes it back, a short span +// untouched; nothing on the heap; strict decoding; the private results secret and wiped when moved +// from; the two bounds, equal but on the one pair that rules otherwise, whose longer form decodes +// and re-encodes as the shorter; a moved-from key pair refused with invalid_state, nothing written; +// crypto's check of the type's list, and a type crypto does not own passed to codecs untouched. +// test/messages/format_refused_toy, decode_bound_missing and decode_bound_differs stop the pairs +// this cannot compile. + +#include "support/format_checks.hpp" +#include "support/formats_toy.hpp" + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace crypto = webcpp::crypto; +namespace codecs = webcpp::codecs; +namespace formats = webcpp::crypto::formats; +namespace detail = webcpp::crypto::detail; +using webcpp::crypto::test::toy_key; +using webcpp::crypto::test::toy_keypair; +using webcpp::crypto::test::toy_signature; + +namespace { + +constexpr std::array key_bytes{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}; +constexpr std::array secret_bytes{0xa1, 0xb2, 0xc3, 0xd4, 0xe5, 0xf6, 0x07, 0x18}; +constexpr std::array signature_bytes{0x5a, 0x00, 0xff, 0x11}; +constexpr std::array key_spki{0x30, 0x0a, 0x30, 0x00, 0x01, 0x02, + 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}; +constexpr std::array key_pair_pkcs8{0x30, 0x0a, 0x02, 0x00, 0xa1, 0xb2, + 0xc3, 0xd4, 0xe5, 0xf6, 0x07, 0x18}; +// The "version 2": the prefix 30 0e 02 01, the secret, a1 02 and the secret's first 2 bytes. +constexpr std::array key_pair_pkcs8_v2{ + 0x30, 0x0e, 0x02, 0x01, 0xa1, 0xb2, 0xc3, 0xd4, 0xe5, 0xf6, 0x07, 0x18, 0xa1, 0x02, 0xa1, 0xb2}; + +// The two bounds (owner decision 23): stated by every pair that decodes, equal but on the toy key +// pair's pkcs8, which a change of its own (the toy's) rules longer. +static_assert(formats::max_encoded_size, toy_key> == 8); +static_assert(formats::max_decode_input_size, toy_key> == 8); +static_assert(formats::max_encoded_size, toy_key> == 12); +static_assert(formats::max_decode_input_size, toy_key> == 12); +static_assert(formats::max_encoded_size == 12); +static_assert(formats::max_decode_input_size == 16); +static_assert(detail::bounds_may_differ_v); +static_assert(!detail::bounds_may_differ_v, toy_key>); +static_assert(!detail::bounds_may_differ_v, toy_keypair>); +static_assert(detail::check_bounds, toy_key>()); +static_assert(detail::check_bounds, toy_key>()); +static_assert(detail::check_bounds, toy_keypair>()); +static_assert(detail::check_bounds()); +static_assert(detail::check_bounds, toy_signature>()); + +// The concepts are codecs' (design R22): exactly the toy's pairs convert. +static_assert(codecs::encodable>); +static_assert(codecs::encodable>); +static_assert(codecs::encodable>>); +static_assert(codecs::decodable>>); +static_assert(codecs::encodable); +static_assert(!codecs::encodable); +static_assert(!codecs::decodable); +static_assert(!codecs::encodable); +static_assert(!codecs::encodable>); + +// crypto's check of the type's list (design D3): the base form and the point form. +static_assert(!detail::format_refused, toy_key, detail::formats_of_t>); +static_assert(!detail::format_refused>, toy_key, + detail::formats_of_t>); +static_assert(detail::format_refused>); +static_assert(detail::format_refused>); +static_assert(detail::format_refused, toy_key, + detail::formats_of_t>); +static_assert(detail::format_refused>, + toy_key, detail::formats_of_t>); +static_assert(!detail::format_refused); +static_assert(detail::formats_declared_v); +static_assert(!detail::formats_declared_v); +static_assert(detail::pair_accepted, toy_key>()); +static_assert(detail::pair_accepted, toy_keypair>()); +static_assert(!detail::pair_accepted()); +static_assert(!detail::pair_accepted, toy_key>()); +static_assert(detail::checked_by_crypto_v, toy_signature>); +static_assert(!detail::checked_by_crypto_v); +static_assert(!detail::checked_by_crypto_v, std::array>); + +// The secrecy decode_pem reads through a requires check: absent on the public value codecs. +static_assert(!detail::value_codec_secret_v, toy_key>); +static_assert(detail::value_codec_secret_v); +static_assert(detail::value_codec_secret_v, toy_keypair>); +static_assert(!detail::value_codec_secret_v); + +// Every pair of crypto's is noexcept; a pair crypto does not own is as codecs' verb is. +static_assert(noexcept(crypto::encode(formats::spki, std::declval()))); +static_assert(noexcept(crypto::encode(formats::pkcs8, std::declval()))); +static_assert(noexcept(crypto::decode(formats::spki, + std::declval>()))); +static_assert(noexcept(crypto::decode(formats::pem(formats::spki), + std::declval()))); +static_assert(!noexcept(crypto::decode>( + codecs::formats::base64, std::declval()))); + +/** Every form of every pair of the toy gives one encoding and decodes it back. */ +void every_form() { + toy_key const key{key_bytes}; + auto const key_pair = toy_keypair::from_secret(secret_bytes); + toy_signature const signature{signature_bytes}; + crypto::test::check_every_form(formats::raw, key, key_bytes); + crypto::test::check_every_form(formats::spki, key, key_spki); + crypto::test::check_every_form(formats::raw, key_pair, secret_bytes); + crypto::test::check_every_form(formats::pkcs8, key_pair, key_pair_pkcs8); + crypto::test::check_every_form(formats::raw, signature, signature_bytes); +} + +/** No form of the toy's pairs allocates (owner decision 3). */ +void no_heap() { + toy_key const key{key_bytes}; + auto const key_pair = toy_keypair::from_secret(secret_bytes); + toy_signature const signature{signature_bytes}; + crypto::test::check_no_heap(formats::raw, key); + crypto::test::check_no_heap(formats::spki, key); + crypto::test::check_no_heap(formats::pem(formats::spki), key); + crypto::test::check_no_heap(formats::raw, key_pair); + crypto::test::check_no_heap(formats::pkcs8, key_pair); + crypto::test::check_no_heap(formats::pem(formats::pkcs8), key_pair); + crypto::test::check_no_heap(formats::raw, signature); +} + +/** Every change of a valid encoding is refused, or is the encoding of what it decodes to. */ +void strict() { + crypto::test::check_strict, toy_key>(formats::raw, key_bytes); + crypto::test::check_strict, toy_key>(formats::spki, key_spki); + crypto::test::check_strict(formats::pkcs8, key_pair_pkcs8); + crypto::test::check_strict, toy_signature>(formats::raw, signature_bytes); + BOOST_TEST(crypto::decode(formats::spki, std::span(key_spki).first(11)).error() == + crypto::error::invalid_encoding); +} + +/** A key pair's raw and pkcs8 give secret results, wiped when moved from. */ +void secret_results() { + auto const key_pair = toy_keypair::from_secret(secret_bytes); + crypto::test::check_secret_result(formats::pkcs8, key_pair); + crypto::test::check_secret_result(formats::raw, key_pair); + crypto::test::check_secret_result(formats::pem(formats::pkcs8), key_pair); + using pkcs8_result = decltype(crypto::encode(formats::pkcs8, key_pair))::value_type; + static_assert(std::is_same_v>); + using raw_result = decltype(crypto::encode(formats::raw, key_pair))::value_type; + static_assert(std::is_same_v>); + using public_result = decltype(crypto::encode(formats::spki, toy_key{}))::value_type; + static_assert(std::is_same_v>); +} + +/** + * The toy key pair's pkcs8 decodes its "version 2", 16 bytes, past its max_encoded_size, and + * encodes the key pair it gives as the 12-byte form; a mismatching repeat is refused. + */ +void decode_bound_past_the_encoding() { + auto const decoded = crypto::decode(formats::pkcs8, key_pair_pkcs8_v2); + if (BOOST_TEST(decoded.has_value())) { + BOOST_TEST(std::ranges::equal(decoded->secret(), secret_bytes)); + auto const encoded = crypto::encode(formats::pkcs8, *decoded); + if (BOOST_TEST(encoded.has_value())) { + BOOST_TEST(std::ranges::equal(encoded->view(), key_pair_pkcs8)); + } + } + std::array mismatching = key_pair_pkcs8_v2; + mismatching.back() ^= 0x01U; + BOOST_TEST(crypto::decode(formats::pkcs8, mismatching).error() == + crypto::error::invalid_encoding); + std::array longer{}; + std::ranges::copy(key_pair_pkcs8_v2, longer.begin()); + BOOST_TEST(crypto::decode(formats::pkcs8, longer).error() == + crypto::error::invalid_encoding); +} + +/** + * A moved-from key pair given to a private format (Review Focus 3): invalid_state from every form, + * nothing written to a span, no partial secret in a result. + */ +void moved_from_key_pair() { + auto key_pair = toy_keypair::from_secret(secret_bytes); + toy_keypair const moved_to = std::move(key_pair); + BOOST_TEST(moved_to.valid()); + // NOLINTBEGIN(bugprone-use-after-move): the moved-from key pair is the case + BOOST_TEST(!key_pair.valid()); + BOOST_TEST(crypto::encode(formats::pkcs8, key_pair).error() == crypto::error::invalid_state); + BOOST_TEST(crypto::encode(formats::raw, key_pair).error() == crypto::error::invalid_state); + BOOST_TEST(crypto::encode(formats::pem(formats::pkcs8), key_pair).error() == + crypto::error::invalid_state); + BOOST_TEST(codecs::encode(formats::pkcs8, key_pair).error() == crypto::error::invalid_state); + + constexpr std::uint8_t untouched = 0xa5; + std::array buffer{}; + buffer.fill(untouched); + BOOST_TEST(crypto::encode(formats::pkcs8, key_pair, std::span(buffer)).error() == + crypto::error::invalid_state); + BOOST_TEST(crypto::encode(formats::raw, key_pair, std::span(buffer)).error() == + crypto::error::invalid_state); + BOOST_TEST(std::ranges::all_of(buffer, [](std::uint8_t held) { return held == untouched; })); + std::array, toy_keypair>> + text_buffer{}; + text_buffer.fill('x'); + BOOST_TEST( + crypto::encode(formats::pem(formats::pkcs8), key_pair, std::span(text_buffer)).error() == + crypto::error::invalid_state); + BOOST_TEST(std::ranges::all_of(text_buffer, [](char held) { return held == 'x'; })); + std::vector appended{0x3e}; + BOOST_TEST( + crypto::encode(formats::pkcs8, key_pair, codecs::tokens::append_to(appended)).error() == + crypto::error::invalid_state); + BOOST_TEST(appended == std::vector{0x3e}); + // NOLINTEND(bugprone-use-after-move) +} + +/** A value crypto does not own, or a format crypto does not own, goes to codecs untouched. */ +void foreign_pairs() { + std::array const bytes{0x30, 0x0a, 0x30}; + auto const through_crypto = crypto::encode(codecs::formats::base64, bytes); + auto const through_codecs = codecs::encode(codecs::formats::base64, bytes); + if (BOOST_TEST(through_crypto.has_value()) && BOOST_TEST(through_codecs.has_value())) { + BOOST_TEST(through_crypto->view() == through_codecs->view()); + BOOST_TEST(through_crypto->view() == "MAow"); + } + auto const decoded = + crypto::decode>(codecs::formats::base64, std::string{"MAow"}); + if (BOOST_TEST(decoded.has_value())) { + BOOST_TEST(std::ranges::equal(*decoded, bytes)); + } +} + +} // namespace + +int main() { + every_form(); + no_heap(); + strict(); + secret_results(); + decode_bound_past_the_encoding(); + moved_from_key_pair(); + foreign_pairs(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/formats_vocabulary_test.cpp b/test/formats_vocabulary_test.cpp new file mode 100644 index 00000000..c1bc1b5e --- /dev/null +++ b/test/formats_vocabulary_test.cpp @@ -0,0 +1,168 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the 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 vocabulary of crypto::formats (design D1, R23, R25): each format tag is a codecs::format +// named whatever its point form, made by naming it and from no braces; raw and spki take a point +// form, spki not the x-only one; pem takes spki (any form) or pkcs8 and labels the armor from the +// inner format; the one list, detail::all_formats, holds the six base forms, from which +// detail::is_format_v and detail::base_format_t derive. test/messages/pem_of_der and pem_of_raw +// stop a pem of another format, and test/messages/format_without_header a format named without +// this header. + +#include +#include + +#include +#include + +#include + +#include +#include + +namespace crypto = webcpp::crypto; +namespace codecs = webcpp::codecs; +namespace formats = webcpp::crypto::formats; +namespace detail = webcpp::crypto::detail; + +namespace probes { + +// A function that takes a tag by value, declared only: the probe below never evaluates a call. It +// is in a named namespace, as the unused-template check reads an unnamed one as the file's alone. +template +void take_tag(Tag); + +// Whether `{}` makes a `Tag` where one is expected: it does not for a tag whose default +// constructor is explicit. +template +concept from_braces = requires { take_tag({}); }; + +// Whether the format `Format` takes the point form `Form`. +template +concept takes_form = requires(Format format, Form form) { format(form); }; + +} // namespace probes + +namespace { + +using probes::from_braces; +using probes::takes_form; + +// Each base form is a codecs::format: copyable, with a name. +static_assert(codecs::format>); +static_assert(codecs::format>); +static_assert(codecs::format); +static_assert(codecs::format); +static_assert(codecs::format>>); +static_assert(codecs::format>); + +// The names, the same whatever the form (design R25). +static_assert(formats::raw_t<>::name == "raw"); +static_assert(formats::raw_t::name == "raw"); +static_assert(formats::spki_t<>::name == "spki"); +static_assert(formats::spki_t::name == "spki"); +static_assert(formats::pkcs8_t::name == "pkcs8"); +static_assert(formats::der_t::name == "der"); + +// The objects, and the point forms raw and spki take. +static_assert(std::is_same_v const>); +static_assert(std::is_same_v const>); +static_assert(std::is_same_v); +static_assert(std::is_same_v); +static_assert(std::is_same_v, formats::raw_t>); +static_assert(std::is_same_v>); +static_assert(std::is_same_v>); +static_assert( + std::is_same_v>); +static_assert(std::is_same_v>); +static_assert(std::is_same_v>); +static_assert(takes_form, formats::xonly_t>); +static_assert(!takes_form, formats::xonly_t>); +static_assert(!takes_form, int>); +static_assert(!takes_form, formats::der_t>); + +// The explicit default constructors (design R25): a tag is made by its name, never by `{}`. +static_assert(std::is_default_constructible_v>); +static_assert(std::is_default_constructible_v>); +static_assert(std::is_default_constructible_v); +static_assert(std::is_default_constructible_v); +static_assert(!from_braces>); +static_assert(!from_braces>); +static_assert(!from_braces>); +static_assert(!from_braces); +static_assert(!from_braces); +static_assert(!from_braces); +static_assert(!from_braces); +static_assert(!from_braces); +static_assert(!from_braces); +static_assert(!from_braces); + +// pem: codecs' armor over the inner format. +static_assert(std::is_same_v>>); +static_assert(std::is_same_v>>); +static_assert( + std::is_same_v>); + +// The one list and what derives from it. +static_assert( + std::is_same_v< + detail::all_formats, + detail::format_list, formats::spki_t<>, formats::pkcs8_t, formats::der_t, + formats::pem_t>, formats::pem_t>>); +static_assert(detail::is_format_v>); +static_assert(detail::is_format_v>); +static_assert(detail::is_format_v); +static_assert(detail::is_format_v); +static_assert(detail::is_format_v>>); +static_assert(detail::is_format_v>); +static_assert(detail::is_format_v>); +static_assert(detail::is_format_v>); +static_assert(detail::is_format_v>>); +static_assert(!detail::is_format_v); +static_assert(!detail::is_format_v); +static_assert(!detail::is_format_v); +static_assert( + std::is_same_v>, formats::raw_t<>>); +static_assert(std::is_same_v>, + formats::spki_t<>>); +static_assert( + std::is_same_v>>, + formats::pem_t>>); +static_assert(std::is_same_v, formats::pkcs8_t>); +static_assert(detail::known_formats_v); +static_assert(!detail::known_formats_v>>); +static_assert(!detail::known_formats_v>); + +// The labels, taken from the inner format (design R23). +static_assert(detail::pem_label_v> == "PUBLIC KEY"); +static_assert(detail::pem_label_v> == "PUBLIC KEY"); +static_assert(detail::pem_label_v == "PRIVATE KEY"); + +/** The armor of each PEM format holds the inner format's label. */ +void labels_follow_the_inner_format() { + BOOST_TEST(formats::pem(formats::spki).outer.label() == std::string_view{"PUBLIC KEY"}); + BOOST_TEST(formats::pem(formats::spki(formats::compressed)).outer.label() == + std::string_view{"PUBLIC KEY"}); + BOOST_TEST(formats::pem(formats::spki(formats::uncompressed)).outer.label() == + std::string_view{"PUBLIC KEY"}); + BOOST_TEST(formats::pem(formats::pkcs8).outer.label() == std::string_view{"PRIVATE KEY"}); + constexpr auto public_pem = formats::pem(formats::spki); + static_assert(public_pem.outer.label() == "PUBLIC KEY"); + static_assert(formats::pem_t>::name == "armor over spki"); +} + +} // namespace + +int main() { + labels_follow_the_inner_format(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/messages/Jamfile b/test/messages/Jamfile index d584a654..e977f225 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -161,3 +161,10 @@ build-project prehashed_signer_verify_without_policy ; build-project recover_without_policy ; build-project recover_ecdsa_without_policy ; build-project async_verify_secp256k1_without_policy ; +build-project format_refused_toy ; +build-project pem_of_der ; +build-project pem_of_raw ; +build-project format_header_missing_toy ; +build-project decode_bound_missing ; +build-project decode_bound_differs ; +build-project format_without_header ; diff --git a/test/messages/decode_bound_differs/Jamfile b/test/messages/decode_bound_differs/Jamfile new file mode 100644 index 00000000..4bd33d4d --- /dev/null +++ b/test/messages/decode_bound_differs/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic decode_bound_differs : decode_bound_differs.cpp + : : native wasip2 wasip3 : alone ; diff --git a/test/messages/decode_bound_differs/decode_bound_differs.cpp b/test/messages/decode_bound_differs/decode_bound_differs.cpp new file mode 100644 index 00000000..e9838e4f --- /dev/null +++ b/test/messages/decode_bound_differs/decode_bound_differs.cpp @@ -0,0 +1,52 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A value codec whose decode bound differs from its max_encoded_size, where no change has ruled +// that they may (detail::bounds_may_differ_v), stops the build at detail::check_bounds (design +// R37) with the second of its texts, and with that error alone. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/formats.hpp:* {{webcpp::crypto: the decode bound equals max_encoded_size until a change rules otherwise}} +// clang-format on + +#include "../../support/formats_toy.hpp" + +#include +#include + +#include +#include +#include +#include + +namespace decode_bound_test { + +/** A format of the test's own, whose value codec states a decode bound past its encoding's. */ +struct longer_t { + static constexpr std::string_view name = "longer"; +}; + +} // namespace decode_bound_test + +template <> +struct webcpp::codecs::value_codec { + static constexpr output_kind output = output_kind::bytes; + static constexpr std::size_t max_encoded_size = 8; + static constexpr std::size_t max_decode_input_size = 9; + + static result decode( + decode_bound_test::longer_t const& /*format*/, + std::span /*input_bytes*/) noexcept { + return webcpp::crypto::test::toy_key{}; + } +}; + +static_assert(webcpp::crypto::detail::check_bounds()); + +int main() {} diff --git a/test/messages/decode_bound_missing/Jamfile b/test/messages/decode_bound_missing/Jamfile new file mode 100644 index 00000000..df012ae2 --- /dev/null +++ b/test/messages/decode_bound_missing/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic decode_bound_missing : decode_bound_missing.cpp + : : native wasip2 wasip3 : alone ; diff --git a/test/messages/decode_bound_missing/decode_bound_missing.cpp b/test/messages/decode_bound_missing/decode_bound_missing.cpp new file mode 100644 index 00000000..d186d6f5 --- /dev/null +++ b/test/messages/decode_bound_missing/decode_bound_missing.cpp @@ -0,0 +1,51 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A value codec that decodes and states no max_decode_input_size, its decode bound, stops the +// build at detail::check_bounds, which each curve's formats header calls beside its formats_of +// (design R37), with the first of its texts, and with that error alone. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/formats.hpp:* {{webcpp::crypto: a value codec that decodes states max_decode_input_size, its decode bound}} +// clang-format on + +#include "../../support/formats_toy.hpp" + +#include +#include + +#include +#include +#include +#include + +namespace decode_bound_test { + +/** A format of the test's own, whose value codec decodes and states no decode bound. */ +struct unbounded_t { + static constexpr std::string_view name = "unbounded"; +}; + +} // namespace decode_bound_test + +template <> +struct webcpp::codecs::value_codec { + static constexpr output_kind output = output_kind::bytes; + static constexpr std::size_t max_encoded_size = 8; + + static result decode( + decode_bound_test::unbounded_t const& /*format*/, + std::span /*input_bytes*/) noexcept { + return webcpp::crypto::test::toy_key{}; + } +}; + +static_assert(webcpp::crypto::detail::check_bounds()); + +int main() {} diff --git a/test/messages/format_header_missing_toy/Jamfile b/test/messages/format_header_missing_toy/Jamfile new file mode 100644 index 00000000..9b2a83ba --- /dev/null +++ b/test/messages/format_header_missing_toy/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic format_header_missing_toy : format_header_missing_toy.cpp + : : native wasip2 wasip3 : alone ; diff --git a/test/messages/format_header_missing_toy/format_header_missing_toy.cpp b/test/messages/format_header_missing_toy/format_header_missing_toy.cpp new file mode 100644 index 00000000..8efc7eff --- /dev/null +++ b/test/messages/format_header_missing_toy/format_header_missing_toy.cpp @@ -0,0 +1,27 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A program that includes the toy types without the part that declares their formats, as a +// program that includes a curve's header and not its formats header, encodes a toy key: crypto's +// check names the formats header of the toy's curve, Ed25519's, which it borrows (design D3), and +// with that error alone. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/formats.hpp:* {{webcpp::crypto: include to encode or decode this type}} +// clang-format on + +#define WEBCPP_TEST_CRYPTO_TOY_FORMATS_UNDECLARED +#include "../../support/formats_toy.hpp" + +#include + +int main() { + namespace crypto = webcpp::crypto; + auto const encoded = crypto::encode(crypto::formats::raw, crypto::test::toy_key{}); + return encoded ? 0 : 1; +} diff --git a/test/messages/format_refused_toy/Jamfile b/test/messages/format_refused_toy/Jamfile new file mode 100644 index 00000000..7d0a4e4f --- /dev/null +++ b/test/messages/format_refused_toy/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic format_refused_toy : format_refused_toy.cpp + : : native wasip2 wasip3 : alone ; diff --git a/test/messages/format_refused_toy/format_refused_toy.cpp b/test/messages/format_refused_toy/format_refused_toy.cpp new file mode 100644 index 00000000..06e9168e --- /dev/null +++ b/test/messages/format_refused_toy/format_refused_toy.cpp @@ -0,0 +1,26 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// crypto::encode of the toy key in der, a format of crypto's list that the toy key does not have, +// stops at crypto's check: the fixed text, and the failed requirement, which names the type's +// format_list, so that the diagnostic says which formats the type has (design D3), and with that +// error alone. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/formats.hpp:* {{webcpp::crypto::detail::format_list, webcpp::crypto::formats::spki_t, webcpp::codecs::over, std::allocator>>>': webcpp::crypto: this type has no such format; the formats it has are the format_list named in this assertion}} +// clang-format on + +#include "../../support/formats_toy.hpp" + +#include + +int main() { + namespace crypto = webcpp::crypto; + auto const encoded = crypto::encode(crypto::formats::der, crypto::test::toy_key{}); + return encoded ? 0 : 1; +} diff --git a/test/messages/format_without_header/Jamfile b/test/messages/format_without_header/Jamfile new file mode 100644 index 00000000..bd71232b --- /dev/null +++ b/test/messages/format_without_header/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic format_without_header : format_without_header.cpp + : /third_party//bearssl : native wasip2 wasip3 : alone ; diff --git a/test/messages/format_without_header/format_without_header.cpp b/test/messages/format_without_header/format_without_header.cpp new file mode 100644 index 00000000..a3af6497 --- /dev/null +++ b/test/messages/format_without_header/format_without_header.cpp @@ -0,0 +1,18 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A program that includes only P-256's header and names crypto::formats::spki stops at a missing +// member of the namespace crypto::formats, which config.hpp declares and only the formats headers +// fill (the spec's scenario "A format named without its header"), and with that error alone. + +#include + +int main() { + namespace crypto = webcpp::crypto; + // expected-error@+1 {{no member named 'spki' in namespace 'webcpp::crypto::formats'}} + auto const format = crypto::formats::spki; + return format.name.empty() ? 0 : 1; +} diff --git a/test/messages/pem_of_der/Jamfile b/test/messages/pem_of_der/Jamfile new file mode 100644 index 00000000..bc73d9fa --- /dev/null +++ b/test/messages/pem_of_der/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic pem_of_der : pem_of_der.cpp + : : native wasip2 wasip3 : alone ; diff --git a/test/messages/pem_of_der/pem_of_der.cpp b/test/messages/pem_of_der/pem_of_der.cpp new file mode 100644 index 00000000..383262e3 --- /dev/null +++ b/test/messages/pem_of_der/pem_of_der.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) + +// formats::pem of der, a format that is no DER key, stops the build with the text that says what +// PEM carries (design D1), and with that error alone. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/formats.hpp:* {{webcpp::crypto: PEM carries a DER key: pem(formats::spki) or pem(formats::pkcs8)}} +// clang-format on + +#include + +int main() { + namespace formats = webcpp::crypto::formats; + auto const format = formats::pem(formats::der); + return format.outer.label().empty() ? 0 : 1; +} diff --git a/test/messages/pem_of_raw/Jamfile b/test/messages/pem_of_raw/Jamfile new file mode 100644 index 00000000..55c7fe96 --- /dev/null +++ b/test/messages/pem_of_raw/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic pem_of_raw : pem_of_raw.cpp + : : native wasip2 wasip3 : alone ; diff --git a/test/messages/pem_of_raw/pem_of_raw.cpp b/test/messages/pem_of_raw/pem_of_raw.cpp new file mode 100644 index 00000000..0c7319b8 --- /dev/null +++ b/test/messages/pem_of_raw/pem_of_raw.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) + +// formats::pem of raw, a key's own bytes and no DER, stops the build with the text that says what +// PEM carries (design D1), and with that error alone. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/formats.hpp:* {{webcpp::crypto: PEM carries a DER key: pem(formats::spki) or pem(formats::pkcs8)}} +// clang-format on + +#include + +int main() { + namespace formats = webcpp::crypto::formats; + auto const format = formats::pem(formats::raw); + return format.outer.label().empty() ? 0 : 1; +} diff --git a/test/msvc/Jamfile b/test/msvc/Jamfile index a03406d1..1059bcb9 100644 --- a/test/msvc/Jamfile +++ b/test/msvc/Jamfile @@ -86,3 +86,10 @@ build-project prehashed_signer_verify_without_policy ; build-project recover_without_policy ; build-project recover_ecdsa_without_policy ; build-project async_verify_secp256k1_without_policy ; +build-project format_refused_toy ; +build-project pem_of_der ; +build-project pem_of_raw ; +build-project format_header_missing_toy ; +build-project decode_bound_missing ; +build-project decode_bound_differs ; +build-project format_without_header ; diff --git a/test/msvc/decode_bound_differs/Jamfile b/test/msvc/decode_bound_differs/Jamfile new file mode 100644 index 00000000..ed63be4f --- /dev/null +++ b/test/msvc/decode_bound_differs/Jamfile @@ -0,0 +1,9 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail decode_bound_differs : app.cpp : /webcpp/crypto//crypto : native ; diff --git a/test/msvc/decode_bound_differs/app.cpp b/test/msvc/decode_bound_differs/app.cpp new file mode 100644 index 00000000..d2574dd5 --- /dev/null +++ b/test/msvc/decode_bound_differs/app.cpp @@ -0,0 +1,44 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A value codec whose decode bound differs from its encoding's, unruled, does not compile on MSVC. +// The text is checked on clang, in test/messages/decode_bound_differs. +#include "../../support/formats_toy.hpp" + +#include +#include + +#include +#include +#include +#include + +namespace decode_bound_test { + +/** A format of the test's own, whose value codec states a decode bound past its encoding's. */ +struct longer_t { + static constexpr std::string_view name = "longer"; +}; + +} // namespace decode_bound_test + +template <> +struct webcpp::codecs::value_codec { + static constexpr output_kind output = output_kind::bytes; + static constexpr std::size_t max_encoded_size = 8; + static constexpr std::size_t max_decode_input_size = 9; + + static result decode( + decode_bound_test::longer_t const& /*format*/, + std::span /*input_bytes*/) noexcept { + return webcpp::crypto::test::toy_key{}; + } +}; + +static_assert(webcpp::crypto::detail::check_bounds()); + +int main() {} diff --git a/test/msvc/decode_bound_missing/Jamfile b/test/msvc/decode_bound_missing/Jamfile new file mode 100644 index 00000000..e2f9d9ae --- /dev/null +++ b/test/msvc/decode_bound_missing/Jamfile @@ -0,0 +1,9 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail decode_bound_missing : app.cpp : /webcpp/crypto//crypto : native ; diff --git a/test/msvc/decode_bound_missing/app.cpp b/test/msvc/decode_bound_missing/app.cpp new file mode 100644 index 00000000..37e0daa4 --- /dev/null +++ b/test/msvc/decode_bound_missing/app.cpp @@ -0,0 +1,43 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A value codec that decodes and states no decode bound does not compile on MSVC. The text is +// checked on clang, in test/messages/decode_bound_missing. +#include "../../support/formats_toy.hpp" + +#include +#include + +#include +#include +#include +#include + +namespace decode_bound_test { + +/** A format of the test's own, whose value codec decodes and states no decode bound. */ +struct unbounded_t { + static constexpr std::string_view name = "unbounded"; +}; + +} // namespace decode_bound_test + +template <> +struct webcpp::codecs::value_codec { + static constexpr output_kind output = output_kind::bytes; + static constexpr std::size_t max_encoded_size = 8; + + static result decode( + decode_bound_test::unbounded_t const& /*format*/, + std::span /*input_bytes*/) noexcept { + return webcpp::crypto::test::toy_key{}; + } +}; + +static_assert(webcpp::crypto::detail::check_bounds()); + +int main() {} diff --git a/test/msvc/format_header_missing_toy/Jamfile b/test/msvc/format_header_missing_toy/Jamfile new file mode 100644 index 00000000..52c51212 --- /dev/null +++ b/test/msvc/format_header_missing_toy/Jamfile @@ -0,0 +1,9 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail format_header_missing_toy : app.cpp : /webcpp/crypto//crypto : native ; diff --git a/test/msvc/format_header_missing_toy/app.cpp b/test/msvc/format_header_missing_toy/app.cpp new file mode 100644 index 00000000..2bc13d7c --- /dev/null +++ b/test/msvc/format_header_missing_toy/app.cpp @@ -0,0 +1,18 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The toy types without their formats, encoded, do not compile on MSVC. The text is checked on +// clang, in test/messages/format_header_missing_toy. +#define WEBCPP_TEST_CRYPTO_TOY_FORMATS_UNDECLARED +#include "../../support/formats_toy.hpp" + +#include + +int main() { + namespace crypto = webcpp::crypto; + auto const encoded = crypto::encode(crypto::formats::raw, crypto::test::toy_key{}); + return encoded ? 0 : 1; +} diff --git a/test/msvc/format_refused_toy/Jamfile b/test/msvc/format_refused_toy/Jamfile new file mode 100644 index 00000000..1440948d --- /dev/null +++ b/test/msvc/format_refused_toy/Jamfile @@ -0,0 +1,9 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail format_refused_toy : app.cpp : /webcpp/crypto//crypto : native ; diff --git a/test/msvc/format_refused_toy/app.cpp b/test/msvc/format_refused_toy/app.cpp new file mode 100644 index 00000000..30f408b2 --- /dev/null +++ b/test/msvc/format_refused_toy/app.cpp @@ -0,0 +1,17 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// crypto::encode of the toy key in der, a format the toy key does not have, does not compile on +// MSVC. The text is checked on clang, in test/messages/format_refused_toy. +#include "../../support/formats_toy.hpp" + +#include + +int main() { + namespace crypto = webcpp::crypto; + auto const encoded = crypto::encode(crypto::formats::der, crypto::test::toy_key{}); + return encoded ? 0 : 1; +} diff --git a/test/msvc/format_without_header/Jamfile b/test/msvc/format_without_header/Jamfile new file mode 100644 index 00000000..58247e23 --- /dev/null +++ b/test/msvc/format_without_header/Jamfile @@ -0,0 +1,9 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail format_without_header : app.cpp : /webcpp/crypto//crypto /third_party//bearssl : native ; diff --git a/test/msvc/format_without_header/app.cpp b/test/msvc/format_without_header/app.cpp new file mode 100644 index 00000000..1bbdc831 --- /dev/null +++ b/test/msvc/format_without_header/app.cpp @@ -0,0 +1,15 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// crypto::formats::spki named without does not compile on MSVC. The +// text is checked on clang, in test/messages/format_without_header. +#include + +int main() { + namespace crypto = webcpp::crypto; + auto const format = crypto::formats::spki; + return format.name.empty() ? 0 : 1; +} diff --git a/test/msvc/pem_of_der/Jamfile b/test/msvc/pem_of_der/Jamfile new file mode 100644 index 00000000..b0fcee73 --- /dev/null +++ b/test/msvc/pem_of_der/Jamfile @@ -0,0 +1,9 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail pem_of_der : app.cpp : /webcpp/crypto//crypto : native ; diff --git a/test/msvc/pem_of_der/app.cpp b/test/msvc/pem_of_der/app.cpp new file mode 100644 index 00000000..23ae8c3f --- /dev/null +++ b/test/msvc/pem_of_der/app.cpp @@ -0,0 +1,15 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// formats::pem of der does not compile on MSVC. The text is checked on clang, in +// test/messages/pem_of_der. +#include + +int main() { + namespace formats = webcpp::crypto::formats; + auto const format = formats::pem(formats::der); + return format.outer.label().empty() ? 0 : 1; +} diff --git a/test/msvc/pem_of_raw/Jamfile b/test/msvc/pem_of_raw/Jamfile new file mode 100644 index 00000000..8bc6d82a --- /dev/null +++ b/test/msvc/pem_of_raw/Jamfile @@ -0,0 +1,9 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail pem_of_raw : app.cpp : /webcpp/crypto//crypto : native ; diff --git a/test/msvc/pem_of_raw/app.cpp b/test/msvc/pem_of_raw/app.cpp new file mode 100644 index 00000000..45a3a42e --- /dev/null +++ b/test/msvc/pem_of_raw/app.cpp @@ -0,0 +1,15 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// formats::pem of raw does not compile on MSVC. The text is checked on clang, in +// test/messages/pem_of_raw. +#include + +int main() { + namespace formats = webcpp::crypto::formats; + auto const format = formats::pem(formats::raw); + return format.outer.label().empty() ? 0 : 1; +} diff --git a/test/support/format_checks.hpp b/test/support/format_checks.hpp new file mode 100644 index 00000000..008bdb86 --- /dev/null +++ b/test/support/format_checks.hpp @@ -0,0 +1,255 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the 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 generic checks of a pair of a format and a value type, which the formats test of each curve +// calls (design D2, D11, R18 to R20, R34, R35): every form gives the same encoding, decoding gives +// the value back, a short span is refused untouched (check_every_form); nothing is allocated +// (check_no_heap); every change of a valid encoding is refused or is the encoding of what it +// decodes to (check_strict); a private result is a secret type, move-only and wiped when moved from +// (check_secret_result). A program that includes this header is built with +// WEBCPP_SECURE_TEST_WIPE_RECORD, and includes it once: it defines the allocation counter +// (support/counting.hpp) and the wipe record (support/wipe_record.hpp). + +#ifndef WEBCPP_TEST_CRYPTO_SUPPORT_FORMAT_CHECKS_HPP +#define WEBCPP_TEST_CRYPTO_SUPPORT_FORMAT_CHECKS_HPP + +#include "counting.hpp" +#include "wipe_record.hpp" + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::crypto::test { + +/** Whether the value codec of `Format` and `Value` writes bytes, rather than text. */ +template +inline constexpr bool writes_bytes = + codecs::value_codec::output == codecs::output_kind::bytes; + +/** The element the pair's encoding is made of: `std::uint8_t`, or `char` for a text. */ +template +using element_of = std::conditional_t, std::uint8_t, char>; + +/** The container `codecs::tokens::append_to` takes for the pair's encoding. */ +template +using appended_container_of = + std::conditional_t, std::vector, std::string>; + +/** Whether `Value` has the member forms, `value.encode(format)` and `Value::decode`. */ +template +concept has_members = + requires(Format const& format, Value const& value, std::span input_bytes) { + value.encode(format); + Value::decode(format, input_bytes); + } || requires(Format const& format, Value const& value, std::string_view input_text) { + value.encode(format); + Value::decode(format, input_text); + }; + +/** Whether the elements of `actual` are, one by one, the bytes `expected`. */ +template +bool same_bytes(Range const& actual, std::span expected) { + return std::ranges::equal(actual, expected, [](auto element, std::uint8_t byte) { + return static_cast(element) == byte; + }); +} + +/** `encoding` as the pair's decode takes it: the bytes, or a text of the same characters. */ +template +auto as_input(std::span encoding) { + if constexpr (writes_bytes) { + return encoding; + } else { + // The bytes of a text are its characters. + return std::string_view(reinterpret_cast(encoding.data()), encoding.size()); + } +} + +/** + * Checks that `crypto::encode` of `value` in `format`, `codecs::encode`, the member when the type + * has it, the span form and `codecs::tokens::append_to` give `expected`; that `crypto::decode` + * (and the member) of `expected` gives a value that encodes to it again; and that a span one + * element short is `codecs::error::output_too_small`, written nowhere. + */ +template +void check_every_form(Format format, Value const& value, std::span expected) { + using element = element_of; + constexpr std::size_t capacity = formats::max_encoded_size; + + auto const free_form = crypto::encode(format, value); + if (BOOST_TEST(free_form.has_value())) { + BOOST_TEST(same_bytes(free_form->view(), expected)); + } + auto const codecs_form = codecs::encode(format, value); + if (BOOST_TEST(codecs_form.has_value())) { + BOOST_TEST(same_bytes(codecs_form->view(), expected)); + } + if constexpr (has_members) { + auto const member_form = value.encode(format); + if (BOOST_TEST(member_form.has_value())) { + BOOST_TEST(same_bytes(member_form->view(), expected)); + } + } + + std::array buffer{}; + auto const written = crypto::encode(format, value, std::span(buffer)); + if (BOOST_TEST(written.has_value()) && BOOST_TEST_EQ(*written, expected.size())) { + BOOST_TEST(same_bytes(std::span(buffer).first(*written), expected)); + } + + // The container holds an element already: the encoding is appended after it. + constexpr auto marker = static_cast(0x3e); + appended_container_of appended(1, marker); + auto const token_form = crypto::encode(format, value, codecs::tokens::append_to(appended)); + if (BOOST_TEST(token_form.has_value()) && BOOST_TEST_EQ(appended.size(), expected.size() + 1)) { + BOOST_TEST(appended.front() == marker); + BOOST_TEST(same_bytes(std::span(appended).subspan(1), expected)); + } + + auto const decoded = crypto::decode(format, as_input(expected)); + if (BOOST_TEST(decoded.has_value())) { + auto const again = crypto::encode(format, *decoded); + if (BOOST_TEST(again.has_value())) { + BOOST_TEST(same_bytes(again->view(), expected)); + } + } + if constexpr (has_members) { + auto const member_decoded = Value::decode(format, as_input(expected)); + if (BOOST_TEST(member_decoded.has_value())) { + auto const again = crypto::encode(format, *member_decoded); + if (BOOST_TEST(again.has_value())) { + BOOST_TEST(same_bytes(again->view(), expected)); + } + } + } + + if (!expected.empty()) { + constexpr auto untouched = static_cast(0xa5); + std::array short_buffer{}; + short_buffer.fill(untouched); + auto const short_written = crypto::encode( + format, value, std::span(short_buffer).first(expected.size() - 1)); + if (BOOST_TEST(!short_written.has_value())) { + BOOST_TEST(short_written.error() == codecs::error::output_too_small); + } + BOOST_TEST( + std::ranges::all_of(short_buffer, [&](element held) { return held == untouched; })); + } +} + +/** + * Checks that `crypto::encode` of `value` in `format`, the span form, and `crypto::decode` of the + * encoding allocate nothing: the counter of support/counting.hpp is unchanged. + */ +template +void check_no_heap(Format format, Value const& value) { + using element = element_of; + std::array> buffer{}; + + std::size_t const before = webcpp::test::allocations(); + auto const encoded = crypto::encode(format, value); + auto const written = crypto::encode(format, value, std::span(buffer)); + std::size_t const after_encode = webcpp::test::allocations(); + BOOST_TEST_EQ(after_encode, before); + if (!BOOST_TEST(encoded.has_value()) || !BOOST_TEST(written.has_value())) { + return; + } + + auto const bytes = std::span(buffer).first(*written); + std::size_t const before_decode = webcpp::test::allocations(); + if constexpr (writes_bytes) { + auto const decoded = crypto::decode(format, std::span(bytes)); + std::size_t const after_decode = webcpp::test::allocations(); + BOOST_TEST_EQ(after_decode, before_decode); + BOOST_TEST(decoded.has_value()); + } else { + auto const decoded = + crypto::decode(format, std::string_view(bytes.data(), bytes.size())); + std::size_t const after_decode = webcpp::test::allocations(); + BOOST_TEST_EQ(after_decode, before_decode); + BOOST_TEST(decoded.has_value()); + } +} + +/** + * Checks that every change of one byte of `valid`, to each of the 255 other values, and every + * truncation of it, is refused by `crypto::decode`, or decodes to a value that encodes back + * to the changed input: no two encodings decode to one value. + */ +template +void check_strict(Format format, std::span valid) { + auto const decodes_back = [&](std::span changed) { + auto const decoded = crypto::decode(format, as_input(changed)); + if (!decoded) { + return true; + } + auto const again = crypto::encode(format, *decoded); + return again.has_value() && same_bytes(again->view(), changed); + }; + std::vector changed(valid.begin(), valid.end()); + for (std::size_t index = 0; index < changed.size(); ++index) { + std::uint8_t const original = changed[index]; + for (unsigned delta = 1; delta < 256; ++delta) { + changed[index] = static_cast(original + delta); + BOOST_TEST(decodes_back(changed)); + } + changed[index] = original; + } + for (std::size_t size = 0; size < valid.size(); ++size) { + BOOST_TEST(decodes_back(valid.first(size))); + } +} + +/** Whether `T` is one of codecs' fixed secret results, `secret_bytes` or `secret_text`. */ +template +inline constexpr bool is_secret_result = false; + +/** A secret bytes result. */ +template +inline constexpr bool is_secret_result> = true; + +/** A secret text result. */ +template +inline constexpr bool is_secret_result> = true; + +/** + * Checks that `crypto::encode` of `value` in `format`, a private format, gives a + * `codecs::secret_bytes` or `codecs::secret_text`, which is not copy-constructible, and whose + * storage, its whole capacity, secure's wipe record sees erased when it is moved from. + */ +template +void check_secret_result(Format format, Value const& value) { + auto encoded = crypto::encode(format, value); + using result_type = typename decltype(encoded)::value_type; + static_assert(is_secret_result); + static_assert(!std::is_copy_constructible_v); + if (!BOOST_TEST(encoded.has_value())) { + return; + } + void const* const storage = encoded->view().data(); + webcpp::test::clear_wipes(); + result_type const moved_to = std::move(*encoded); + BOOST_TEST(webcpp::test::wiped(storage, result_type::capacity())); + BOOST_TEST(moved_to.size() > 0U); + webcpp::test::clear_wipes(); +} + +} // namespace webcpp::crypto::test + +#endif // WEBCPP_TEST_CRYPTO_SUPPORT_FORMAT_CHECKS_HPP diff --git a/test/support/formats_toy.hpp b/test/support/formats_toy.hpp new file mode 100644 index 00000000..1124a29c --- /dev/null +++ b/test/support/formats_toy.hpp @@ -0,0 +1,542 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the 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 toy value type of the tests' own, on which is proven before any +// curve registers into it (design D1 to D3, D11, R17 to R25, R37): a public key of 8 bytes, +// toy_key; a key pair of 8 secret bytes, move-only and wiped, toy_keypair; a signature of 4 bytes, +// toy_signature. Each borrows Ed25519's curve id, so that crypto's check treats it as a type of +// crypto's, and so that a translation unit that defines WEBCPP_TEST_CRYPTO_TOY_FORMATS_UNDECLARED +// before including this header, which then leaves out the part that declares the toy's formats, +// sees crypto's sentence for a formats header not included. +// +// The formats part: toy_key has raw (its 8 bytes), spki (the prefix 30 0a 30 00, then the 8 bytes) +// and pem(spki); toy_keypair has raw (its 8 secret bytes), pkcs8 (the prefix 30 0a 02 00, then the +// 8 secret bytes) and pem(pkcs8); toy_signature has raw (its 4 bytes). Every value codec is strict +// (any other input is crypto::error::invalid_encoding) and states equal bounds but one: +// toy_keypair's pkcs8 also decodes a "version 2" of 16 bytes (30 0e 02 01, the 8 secret bytes, a1 +// 02 and the secret's first 2 bytes, which must match), so that its max_decode_input_size is 16 +// while its max_encoded_size is 12, the shape of the deferred PKCS#8 version 2 (owner decision 23), +// and detail::bounds_may_differ_v is true for that pair alone. The private value codecs hold +// secure::timing_guard and refuse a moved-from key pair with crypto::error::invalid_state, writing +// nothing. The stand-in text format, stand_in_text_t (name "stand_in", toy_key's 8 bytes as 16 +// lower-case hexadecimal digits), added to a copy of the library's list, all_formats_with_stand_in, +// proves the room for JWK (design R17). + +#ifndef WEBCPP_TEST_CRYPTO_SUPPORT_FORMATS_TOY_HPP +#define WEBCPP_TEST_CRYPTO_SUPPORT_FORMATS_TOY_HPP + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace webcpp::crypto::test { + +/** A public key of 8 bytes. */ +class toy_key { +public: + /** Its size, in bytes. */ + static constexpr std::size_t size = 8; + + /** A key of 8 zero bytes. */ + toy_key() = default; + + /** The key of `key_bytes`. */ + explicit toy_key(std::array const& key_bytes) noexcept + : bytes_(key_bytes) {} + + /** Its bytes. */ + [[nodiscard]] std::array const& bytes() const noexcept { return bytes_; } + + /** Encodes the key in `format`, as `crypto::encode(format, key)`: the member form. */ + template + [[nodiscard]] auto encode(Format const& format) const + noexcept(detail::encode_is_noexcept()) { + return crypto::encode(format, *this); + } + + /** Decodes a key from `input` in `format`, as `crypto::decode`: the member form. */ + template + [[nodiscard]] static codecs::result decode(Format const& format, + Input const& input) noexcept { + return crypto::decode(format, input); + } + + /** Whether two keys hold the same bytes. */ + friend bool operator==(toy_key const&, toy_key const&) = default; + +private: + std::array bytes_{}; +}; + +/** A key pair of 8 secret bytes: move-only, wiped when destroyed and when moved from. */ +class toy_keypair { +public: + /** The size of its secret, in bytes. */ + static constexpr std::size_t size = 8; + + /** The key pair of `secret_bytes`. */ + [[nodiscard]] static toy_keypair from_secret( + std::span secret_bytes) noexcept { + toy_keypair made; + std::ranges::copy(secret_bytes, made.secret_.begin()); + made.valid_ = true; + return made; + } + + /** Takes `other`'s secret, and leaves `other` wiped and invalid. */ + toy_keypair(toy_keypair&& other) noexcept : secret_(other.secret_), valid_(other.valid_) { + secure::erase_secret(other.secret_); + other.valid_ = false; + } + + /** Takes `other`'s secret, and leaves `other` wiped and invalid. */ + toy_keypair& operator=(toy_keypair&& other) noexcept { + if (this != &other) { + secret_ = other.secret_; + valid_ = other.valid_; + secure::erase_secret(other.secret_); + other.valid_ = false; + } + return *this; + } + + toy_keypair(toy_keypair const&) = delete; + toy_keypair& operator=(toy_keypair const&) = delete; + + /** Wipes the secret. */ + ~toy_keypair() { secure::erase_secret(secret_); } + + /** Whether it holds a secret: false once moved from. */ + [[nodiscard]] bool valid() const noexcept { return valid_; } + + /** Its secret bytes. */ + [[nodiscard]] std::span secret() const noexcept { return secret_; } + + /** Encodes the key pair in `format`, as `crypto::encode(format, key_pair)`. */ + template + [[nodiscard]] auto encode(Format const& format) const + noexcept(detail::encode_is_noexcept()) { + return crypto::encode(format, *this); + } + + /** Decodes a key pair from `input` in `format`, as `crypto::decode`. */ + template + [[nodiscard]] static codecs::result decode(Format const& format, + Input const& input) noexcept { + return crypto::decode(format, input); + } + +private: + toy_keypair() = default; + + std::array secret_{}; + bool valid_ = false; +}; + +/** A signature of 4 bytes. */ +class toy_signature { +public: + /** Its size, in bytes. */ + static constexpr std::size_t size = 4; + + /** A signature of 4 zero bytes. */ + toy_signature() = default; + + /** The signature of `signature_bytes`. */ + explicit toy_signature(std::array const& signature_bytes) noexcept + : bytes_(signature_bytes) {} + + /** Its bytes. */ + [[nodiscard]] std::array const& bytes() const noexcept { return bytes_; } + + /** Whether two signatures hold the same bytes. */ + friend bool operator==(toy_signature const&, toy_signature const&) = default; + +private: + std::array bytes_{}; +}; + +} // namespace webcpp::crypto::test + +namespace webcpp::crypto::detail { + +/** The toy key borrows Ed25519's curve id. */ +template <> +inline constexpr curve_id curve_of_v = curve_id::ed25519; + +/** The toy key pair borrows Ed25519's curve id. */ +template <> +inline constexpr curve_id curve_of_v = curve_id::ed25519; + +/** The toy signature borrows Ed25519's curve id. */ +template <> +inline constexpr curve_id curve_of_v = curve_id::ed25519; + +} // namespace webcpp::crypto::detail + +#ifndef WEBCPP_TEST_CRYPTO_TOY_FORMATS_UNDECLARED + +namespace webcpp::crypto::test { + +/** The prefix of the toy key's SPKI. */ +inline constexpr std::array toy_spki_prefix{0x30, 0x0a, 0x30, 0x00}; + +/** The prefix of the toy key pair's PKCS#8. */ +inline constexpr std::array toy_pkcs8_prefix{0x30, 0x0a, 0x02, 0x00}; + +/** The prefix of the toy key pair's PKCS#8 "version 2". */ +inline constexpr std::array toy_pkcs8_v2_prefix{0x30, 0x0e, 0x02, 0x01}; + +/** The tag and length between the secret and its repeated first 2 bytes in the "version 2". */ +inline constexpr std::array toy_pkcs8_v2_tail{0xa1, 0x02}; + +/** + * The type of @ref stand_in_text, a text format of the tests' own, not in crypto's list: a JWK's + * stand-in (design R17). + */ +struct stand_in_text_t { + /** The format's name. */ + static constexpr std::string_view name = "stand_in"; + + /** Makes the tag; explicit, as crypto's are. */ + explicit stand_in_text_t() = default; +}; + +/** The stand-in text format: toy_key's 8 bytes as 16 lower-case hexadecimal digits. */ +inline constexpr stand_in_text_t stand_in_text{}; + +/** + * `List` with `Format` added at its end. + * + * @tparam List A `detail::format_list`. + * @tparam Format The format to add. + */ +template +struct appended; + +/** A format list with one more format. */ +template +struct appended, Format> { + /** The list, then `Format`. */ + using type = detail::format_list; +}; + +/** A copy of the library's one list with the stand-in text format added. */ +using all_formats_with_stand_in = appended::type; + +/** Writes `prefix` then `body` at the start of `output`, or nothing when it is too short. */ +inline codecs::result write_toy(std::span prefix, + std::span body, + std::span output) noexcept { + std::size_t const total = prefix.size() + body.size(); + if (output.size() < total) { + return codecs::error::output_too_small; + } + std::ranges::copy(body, std::ranges::copy(prefix, output.begin()).out); + return total; +} + +/** Whether `input` is `prefix` followed by `body_size` bytes. */ +inline bool toy_layout(std::span input, std::span prefix, + std::size_t body_size) noexcept { + return input.size() == prefix.size() + body_size && + std::ranges::equal(input.first(prefix.size()), prefix); +} + +} // namespace webcpp::crypto::test + +namespace webcpp::crypto::detail { + +/** The toy key has raw, spki and pem(spki). */ +template <> +struct formats_of { + /** Its formats. */ + using type = + format_list, formats::spki_t<>, formats::pem_t>>; +}; + +/** The toy key pair has raw, pkcs8 and pem(pkcs8). */ +template <> +struct formats_of { + /** Its formats. */ + using type = format_list, formats::pkcs8_t, formats::pem_t>; +}; + +/** The toy signature has raw. */ +template <> +struct formats_of { + /** Its formats. */ + using type = format_list>; +}; + +/** The toy key pair's pkcs8 decodes a "version 2" longer than its encoding. */ +template <> +inline constexpr bool bounds_may_differ_v = true; + +} // namespace webcpp::crypto::detail + +namespace webcpp::codecs { + +/** The toy key's raw: its 8 bytes. */ +template <> +struct value_codec, crypto::test::toy_key> { + static constexpr output_kind output = output_kind::bytes; + static constexpr std::size_t max_encoded_size = 8; + static constexpr std::size_t max_decode_input_size = 8; + + static std::size_t encoded_size(crypto::formats::raw_t<> const& /*format*/, + crypto::test::toy_key const& /*key*/) noexcept { + return 8; + } + + static result encode(crypto::formats::raw_t<> const& /*format*/, + crypto::test::toy_key const& key, + std::span output_bytes) noexcept { + return crypto::test::write_toy({}, key.bytes(), output_bytes); + } + + static result decode( + crypto::formats::raw_t<> const& /*format*/, + std::span input_bytes) noexcept { + if (!crypto::test::toy_layout(input_bytes, {}, crypto::test::toy_key::size)) { + return crypto::error::invalid_encoding; + } + std::array key_bytes{}; + std::ranges::copy(input_bytes, key_bytes.begin()); + return crypto::test::toy_key{key_bytes}; + } +}; + +/** The toy key's spki: the prefix 30 0a 30 00, then its 8 bytes. */ +template <> +struct value_codec, crypto::test::toy_key> { + static constexpr output_kind output = output_kind::bytes; + static constexpr std::size_t max_encoded_size = 12; + static constexpr std::size_t max_decode_input_size = 12; + + static std::size_t encoded_size(crypto::formats::spki_t<> const& /*format*/, + crypto::test::toy_key const& /*key*/) noexcept { + return 12; + } + + static result encode(crypto::formats::spki_t<> const& /*format*/, + crypto::test::toy_key const& key, + std::span output_bytes) noexcept { + return crypto::test::write_toy(crypto::test::toy_spki_prefix, key.bytes(), output_bytes); + } + + static result decode( + crypto::formats::spki_t<> const& /*format*/, + std::span input_bytes) noexcept { + if (!crypto::test::toy_layout(input_bytes, crypto::test::toy_spki_prefix, + crypto::test::toy_key::size)) { + return crypto::error::invalid_encoding; + } + std::array key_bytes{}; + std::ranges::copy(input_bytes.subspan(crypto::test::toy_spki_prefix.size()), + key_bytes.begin()); + return crypto::test::toy_key{key_bytes}; + } +}; + +/** The toy key pair's raw: its 8 secret bytes. */ +template <> +struct value_codec, crypto::test::toy_keypair> { + static constexpr output_kind output = output_kind::bytes; + static constexpr bool secret = true; + static constexpr std::size_t max_encoded_size = 8; + static constexpr std::size_t max_decode_input_size = 8; + + static std::size_t encoded_size(crypto::formats::raw_t<> const& /*format*/, + crypto::test::toy_keypair const& /*key_pair*/) noexcept { + return 8; + } + + static result encode(crypto::formats::raw_t<> const& /*format*/, + crypto::test::toy_keypair const& key_pair, + std::span output_bytes) noexcept { + secure::timing_guard const timing_scope{true}; + if (!key_pair.valid()) { + return crypto::error::invalid_state; + } + return crypto::test::write_toy({}, key_pair.secret(), output_bytes); + } + + static result decode( + crypto::formats::raw_t<> const& /*format*/, + std::span input_bytes) noexcept { + secure::timing_guard const timing_scope{true}; + if (!crypto::test::toy_layout(input_bytes, {}, crypto::test::toy_keypair::size)) { + return crypto::error::invalid_encoding; + } + return crypto::test::toy_keypair::from_secret( + input_bytes.first()); + } +}; + +/** + * The toy key pair's pkcs8: the prefix 30 0a 02 00, then its 8 secret bytes; its decode also takes + * the "version 2" of 16 bytes. + */ +template <> +struct value_codec { + static constexpr output_kind output = output_kind::bytes; + static constexpr bool secret = true; + static constexpr std::size_t max_encoded_size = 12; + static constexpr std::size_t max_decode_input_size = 16; + + static std::size_t encoded_size(crypto::formats::pkcs8_t const& /*format*/, + crypto::test::toy_keypair const& /*key_pair*/) noexcept { + return 12; + } + + static result encode(crypto::formats::pkcs8_t const& /*format*/, + crypto::test::toy_keypair const& key_pair, + std::span output_bytes) noexcept { + secure::timing_guard const timing_scope{true}; + if (!key_pair.valid()) { + return crypto::error::invalid_state; + } + return crypto::test::write_toy(crypto::test::toy_pkcs8_prefix, key_pair.secret(), + output_bytes); + } + + static result decode( + crypto::formats::pkcs8_t const& /*format*/, + std::span input_bytes) noexcept { + secure::timing_guard const timing_scope{true}; + constexpr std::size_t secret_offset = crypto::test::toy_pkcs8_prefix.size(); + constexpr std::size_t secret_size = crypto::test::toy_keypair::size; + if (crypto::test::toy_layout(input_bytes, crypto::test::toy_pkcs8_prefix, secret_size)) { + return crypto::test::toy_keypair::from_secret( + input_bytes.subspan()); + } + constexpr std::size_t tail_offset = secret_offset + secret_size; + constexpr std::size_t repeated_offset = + tail_offset + crypto::test::toy_pkcs8_v2_tail.size(); + if (crypto::test::toy_layout(input_bytes, crypto::test::toy_pkcs8_v2_prefix, + secret_size + crypto::test::toy_pkcs8_v2_tail.size() + 2) && + std::ranges::equal( + input_bytes.subspan(tail_offset, crypto::test::toy_pkcs8_v2_tail.size()), + crypto::test::toy_pkcs8_v2_tail) && + secure::constant_time_equal(input_bytes.subspan(), + input_bytes.subspan())) { + return crypto::test::toy_keypair::from_secret( + input_bytes.subspan()); + } + return crypto::error::invalid_encoding; + } +}; + +/** The toy signature's raw: its 4 bytes. */ +template <> +struct value_codec, crypto::test::toy_signature> { + static constexpr output_kind output = output_kind::bytes; + static constexpr std::size_t max_encoded_size = 4; + static constexpr std::size_t max_decode_input_size = 4; + + static std::size_t encoded_size(crypto::formats::raw_t<> const& /*format*/, + crypto::test::toy_signature const& /*signature*/) noexcept { + return 4; + } + + static result encode(crypto::formats::raw_t<> const& /*format*/, + crypto::test::toy_signature const& signature, + std::span output_bytes) noexcept { + return crypto::test::write_toy({}, signature.bytes(), output_bytes); + } + + static result decode( + crypto::formats::raw_t<> const& /*format*/, + std::span input_bytes) noexcept { + if (!crypto::test::toy_layout(input_bytes, {}, crypto::test::toy_signature::size)) { + return crypto::error::invalid_encoding; + } + std::array signature_bytes{}; + std::ranges::copy(input_bytes, signature_bytes.begin()); + return crypto::test::toy_signature{signature_bytes}; + } +}; + +/** The stand-in text format of the toy key: its 8 bytes as 16 lower-case hexadecimal digits. */ +template <> +struct value_codec { + static constexpr output_kind output = output_kind::text; + static constexpr std::size_t max_encoded_size = 16; + static constexpr std::size_t max_decode_input_size = 16; + + static std::size_t encoded_size(crypto::test::stand_in_text_t const& /*format*/, + crypto::test::toy_key const& /*key*/) noexcept { + return 16; + } + + static result encode(crypto::test::stand_in_text_t const& /*format*/, + crypto::test::toy_key const& key, + std::span output_text) noexcept { + constexpr std::string_view digits = "0123456789abcdef"; + if (output_text.size() < 16) { + return error::output_too_small; + } + for (std::size_t index = 0; index < crypto::test::toy_key::size; ++index) { + output_text[2 * index] = digits[key.bytes()[index] >> 4U]; + output_text[(2 * index) + 1] = digits[key.bytes()[index] & 0x0fU]; + } + return std::size_t{16}; + } + + static result decode(crypto::test::stand_in_text_t const& /*format*/, + std::string_view input_text) noexcept { + constexpr std::string_view digits = "0123456789abcdef"; + if (input_text.size() != 16) { + return crypto::error::invalid_encoding; + } + std::array key_bytes{}; + for (std::size_t index = 0; index < input_text.size(); ++index) { + std::size_t const digit = digits.find(input_text[index]); + if (digit == std::string_view::npos) { + return crypto::error::invalid_encoding; + } + key_bytes[index / 2] = static_cast((key_bytes[index / 2] << 4U) | digit); + } + return crypto::test::toy_key{key_bytes}; + } +}; + +} // namespace webcpp::codecs + +// Beside the formats_of declarations, as each curve's formats header does: every listed format is +// one of the library's, and each pair that decodes, a PEM's aside, states its decode bound, equal +// to max_encoded_size but where bounds_may_differ_v says otherwise. +static_assert(webcpp::crypto::detail::known_formats_v< + webcpp::crypto::detail::formats_of_t>); +static_assert(webcpp::crypto::detail::known_formats_v< + webcpp::crypto::detail::formats_of_t>); +static_assert(webcpp::crypto::detail::known_formats_v< + webcpp::crypto::detail::formats_of_t>); +static_assert(webcpp::crypto::detail::check_bounds, + webcpp::crypto::test::toy_key>()); +static_assert(webcpp::crypto::detail::check_bounds, + webcpp::crypto::test::toy_key>()); +static_assert(webcpp::crypto::detail::check_bounds, + webcpp::crypto::test::toy_keypair>()); +static_assert(webcpp::crypto::detail::check_bounds()); +static_assert(webcpp::crypto::detail::check_bounds, + webcpp::crypto::test::toy_signature>()); + +#endif // WEBCPP_TEST_CRYPTO_TOY_FORMATS_UNDECLARED + +#endif // WEBCPP_TEST_CRYPTO_SUPPORT_FORMATS_TOY_HPP diff --git a/test/support/wipe_record.hpp b/test/support/wipe_record.hpp new file mode 100644 index 00000000..32fc95ba --- /dev/null +++ b/test/support/wipe_record.hpp @@ -0,0 +1,120 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The test seam of webcpp::secure::detail::wipe, which every secure::erase_secret runs (crypto's, +// and codecs' in its secret results), recorded, as hash's test/support/wipe_record.hpp records it: +// a program built with WEBCPP_SECURE_TEST_WIPE_RECORD includes this header once, which defines the +// seam's function webcpp::secure::test::wipe_record. Each wipe is recorded in wipes, with where it +// began; wiped_sizes() returns the sizes of the wipes since its last call, wiped(first, count) says +// whether one of them covered count bytes from first, and clear_wipes() discards them, however +// many. Every one of them must have left only zero bytes. + +#ifndef WEBCPP_TEST_CRYPTO_SUPPORT_WIPE_RECORD_HPP +#define WEBCPP_TEST_CRYPTO_SUPPORT_WIPE_RECORD_HPP + +#ifndef WEBCPP_SECURE_TEST_WIPE_RECORD +#error "support/wipe_record.hpp is for a program built with WEBCPP_SECURE_TEST_WIPE_RECORD" +#endif + +#include + +#include + +#include +#include +#include +#include +#include + +namespace webcpp::test { + +/** One wipe: the address of its first byte, as a number, and its size. */ +struct wipe_entry { + std::uintptr_t first = 0; + std::size_t size = 0; +}; + +/** + * The wipes since the last clear: the first ones, in order, how many, and how many found a byte + * that was not zero. Fixed storage: the seam is noexcept and allocates nothing, so a wipe past the + * storage is counted but not kept, and wiped_sizes() and wiped() report it. + */ +struct wipe_log { + std::array entries{}; + std::size_t count = 0; + std::size_t not_zero = 0; +}; + +/** The seam's record, which secure::detail::wipe reaches through secure::test::wipe_record. */ +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the seam's record +inline wipe_log wipes; + +/** The entries kept since the last clear; every wipe must have fit the record's storage. */ +inline std::vector kept_wipes() { + BOOST_TEST_LE(wipes.count, wipes.entries.size()); + return {wipes.entries.begin(), wipes.entries.begin() + static_cast(std::min( + wipes.count, wipes.entries.size()))}; +} + +/** + * The sizes of the wipes since the last call, which clears the record; every wipe must have left + * only zero bytes, and every one must have fit the record's storage. + */ +inline std::vector wiped_sizes() { + std::vector sizes; + for (wipe_entry const& entry : kept_wipes()) { + sizes.push_back(entry.size); + } + BOOST_TEST_EQ(wipes.not_zero, 0U); + wipes = {}; + return sizes; +} + +/** + * Whether a wipe since the last clear covered the `byte_count` bytes from `first`; every wipe must + * have left only zero bytes. The record is kept. + */ +inline bool wiped(void const* first, std::size_t byte_count) { + BOOST_TEST_EQ(wipes.not_zero, 0U); + auto const begin = reinterpret_cast(first); + std::vector const kept = kept_wipes(); + return std::any_of(kept.begin(), kept.end(), [&](wipe_entry const& entry) { + return entry.first <= begin && begin + byte_count <= entry.first + entry.size; + }); +} + +/** + * Clears the record without reading it, however many wipes it counted (the work before a checked + * step, which may wipe more often than the record keeps); every wipe must still have left only + * zero bytes. + */ +inline void clear_wipes() { + BOOST_TEST_EQ(wipes.not_zero, 0U); + wipes = {}; +} + +} // namespace webcpp::test + +// The seam's function, declared by , defined once by the program +// that includes this header. +// NOLINTBEGIN(misc-definitions-in-headers) +void webcpp::secure::test::wipe_record(void const* wiped_data, std::size_t byte_count) noexcept { + auto& log = ::webcpp::test::wipes; + auto const* const bytes = static_cast(wiped_data); + // Checked here, so that the store cannot throw: the seam is noexcept. A wipe past the storage + // is only counted, and the readers fail the test on it. + if (log.count < log.entries.size()) { + log.entries[log.count] = {reinterpret_cast(wiped_data), byte_count}; + } + ++log.count; + if (!std::all_of(bytes, bytes + byte_count, [](unsigned char b) { return b == 0; })) { + ++log.not_zero; + } +} + +// NOLINTEND(misc-definitions-in-headers) + +#endif // WEBCPP_TEST_CRYPTO_SUPPORT_WIPE_RECORD_HPP diff --git a/test/user_globals_test.cpp b/test/user_globals_test.cpp index a6ea271e..e76cd327 100644 --- a/test/user_globals_test.cpp +++ b/test/user_globals_test.cpp @@ -48,6 +48,8 @@ #include #include #include +#include +#include #include #include #include @@ -140,6 +142,7 @@ extern int const encrypt; #include #include #include +#include int main() { return 0; From be1bab70b7cf8e82823b47e11b51d396fc5d7434 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 1 Dec 2026 00:48:07 -0300 Subject: [PATCH 18/81] crypto: formats on codecs lint fix --- include/webcpp/crypto/formats.hpp | 36 ++++++------- test/formats_pem_test.cpp | 41 +++++++------- test/formats_verbs_test.cpp | 15 +++--- test/formats_vocabulary_test.cpp | 1 - test/support/format_checks.hpp | 89 +++++++++++++++++++------------ test/support/formats_toy.hpp | 18 +++++-- test/support/wipe_record.hpp | 5 +- 7 files changed, 122 insertions(+), 83 deletions(-) diff --git a/include/webcpp/crypto/formats.hpp b/include/webcpp/crypto/formats.hpp index e58482a6..77eeda2a 100644 --- a/include/webcpp/crypto/formats.hpp +++ b/include/webcpp/crypto/formats.hpp @@ -433,7 +433,7 @@ struct base_format> { * @tparam Format The format's type. */ template -using base_format_t = typename base_format::type; +using base_format_t = base_format::type; /** * The point form `Format` names: `Form` for `raw_t` and `spki_t`, the inner format's @@ -465,7 +465,7 @@ struct point_form_of> { template struct point_form_of> { /** The inner format's form. */ - using type = typename point_form_of::type; + using type = point_form_of::type; }; /** @@ -529,7 +529,7 @@ struct formats_of { * @tparam T The value's type. */ template -using formats_of_t = typename formats_of::type; +using formats_of_t = formats_of::type; /** * The point forms `T` accepts for `Format`, a base form of its list: the default form alone unless @@ -551,7 +551,7 @@ struct forms_of { * @tparam T The value's type. */ template -using forms_of_t = typename forms_of::type; +using forms_of_t = forms_of::type; /** * Whether the value type `T`, whose formats are `List`, refuses `Format`: the base form of @@ -710,22 +710,20 @@ inline constexpr bool checked_by_crypto_v = * @return Whether the call may proceed to codecs. */ template -constexpr bool pair_accepted() noexcept { +consteval bool pair_accepted() noexcept { if constexpr (!checked_by_crypto_v) { return true; - } else if constexpr (!formats_declared_v) { - return false; - } else if constexpr (Decoding && - decode_refusal_reason_v != refusal_reason::none) { - return false; - } else if constexpr (refusal_reason_v != refusal_reason::none) { - return false; - } else if constexpr (format_refused>) { - return false; } else if constexpr (Decoding) { - return codecs::decodable; + return formats_declared_v && + decode_refusal_reason_v == refusal_reason::none && + refusal_reason_v == refusal_reason::none && + !format_refused> && + codecs::decodable; } else { - return codecs::encodable; + return formats_declared_v && + refusal_reason_v == refusal_reason::none && + !format_refused> && + codecs::encodable; } } @@ -805,7 +803,7 @@ constexpr void refuse_pair() noexcept { * @return Whether the call is `noexcept`. */ template -constexpr bool encode_is_noexcept() noexcept { +consteval bool encode_is_noexcept() { if constexpr (pair_accepted()) { return noexcept(codecs::encode(std::declval(), std::declval(), std::declval()...)); @@ -860,7 +858,7 @@ inline constexpr bool decodes_in_place_v, Input> = * @return Whether the call is `noexcept`. */ template -constexpr bool decode_is_noexcept() noexcept { +consteval bool decode_is_noexcept() { if constexpr (!pair_accepted() || decodes_in_place_v) { return true; @@ -916,7 +914,7 @@ template */ template [[nodiscard]] codecs::result decode_pem(Format const& format, Text const& text) noexcept { - using inner_type = typename pem_inner::type; + using inner_type = pem_inner::type; constexpr bool secret = value_codec_secret_v || codecs::is_secret_v; secure::timing_guard const timing_scope{secret}; std::array> der{}; diff --git a/test/formats_pem_test.cpp b/test/formats_pem_test.cpp index 9922d9a1..1f336e01 100644 --- a/test/formats_pem_test.cpp +++ b/test/formats_pem_test.cpp @@ -43,6 +43,7 @@ namespace crypto = webcpp::crypto; namespace codecs = webcpp::codecs; namespace formats = webcpp::crypto::formats; +using webcpp::crypto::test::joined; using webcpp::crypto::test::toy_key; using webcpp::crypto::test::toy_keypair; @@ -50,10 +51,13 @@ namespace { constexpr std::array key_bytes{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}; constexpr std::array secret_bytes{0xa1, 0xb2, 0xc3, 0xd4, 0xe5, 0xf6, 0x07, 0x18}; -constexpr std::array key_spki{0x30, 0x0a, 0x30, 0x00, 0x01, 0x02, - 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}; -constexpr std::array key_pair_pkcs8_v2{ - 0x30, 0x0e, 0x02, 0x01, 0xa1, 0xb2, 0xc3, 0xd4, 0xe5, 0xf6, 0x07, 0x18, 0xa1, 0x02, 0xa1, 0xb2}; +// The SPKI: the toy's prefix 30 0a 30 00, then the key's bytes. +constexpr auto key_spki = joined(std::array{0x30, 0x0a, 0x30, 0x00}, key_bytes); +// The "version 2" of the PKCS#8: the prefix 30 0e 02 01, the secret, a1 02 and the secret's +// first 2 bytes. +constexpr auto key_pair_pkcs8_v2 = + joined(joined(std::array{0x30, 0x0e, 0x02, 0x01}, secret_bytes), + std::array{0xa1, 0x02, 0xa1, 0xb2}); // The PEM of key_spki, as OpenSSL's PEM_write_bio writes an armor: the base64 of the 12 bytes. constexpr std::string_view key_pem = @@ -122,8 +126,7 @@ void encode_private() { using result_type = decltype(encoded)::value_type; static_assert(std::is_same_v, toy_keypair>>>); - std::array const pkcs8{0x30, 0x0a, 0x02, 0x00, 0xa1, 0xb2, - 0xc3, 0xd4, 0xe5, 0xf6, 0x07, 0x18}; + auto const pkcs8 = joined(std::array{0x30, 0x0a, 0x02, 0x00}, secret_bytes); std::string const expected = armored("PRIVATE KEY", pkcs8); if (BOOST_TEST(encoded.has_value())) { BOOST_TEST(encoded->view() == expected); @@ -314,18 +317,20 @@ void same_as_codecs() { return; } std::string const private_text{private_pem->view()}; - std::vector const texts{std::string{key_pem}, - crlf, - std::string{key_pem.substr(0, key_pem.size() - 1)}, - certificate, - explained, - std::string{rsa_pem}, - empty, - version_2, - too_long, - private_text, - "", - "-----BEGIN PUBLIC KEY-----\n"}; + std::vector const texts{ + std::string{key_pem}, + crlf, + std::string{key_pem.substr(0, key_pem.size() - 1)}, + certificate, + explained, + std::string{rsa_pem}, + empty, + version_2, + too_long, + private_text, + "", + "-----BEGIN PUBLIC KEY-----\n", + }; for (std::string const& text : texts) { auto const in_place = crypto::decode(formats::pem(formats::spki), text); auto const through_codecs = codecs::decode(formats::pem(formats::spki), text); diff --git a/test/formats_verbs_test.cpp b/test/formats_verbs_test.cpp index 7846d5d2..413816a1 100644 --- a/test/formats_verbs_test.cpp +++ b/test/formats_verbs_test.cpp @@ -39,6 +39,7 @@ namespace crypto = webcpp::crypto; namespace codecs = webcpp::codecs; namespace formats = webcpp::crypto::formats; namespace detail = webcpp::crypto::detail; +using webcpp::crypto::test::joined; using webcpp::crypto::test::toy_key; using webcpp::crypto::test::toy_keypair; using webcpp::crypto::test::toy_signature; @@ -48,13 +49,15 @@ namespace { constexpr std::array key_bytes{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}; constexpr std::array secret_bytes{0xa1, 0xb2, 0xc3, 0xd4, 0xe5, 0xf6, 0x07, 0x18}; constexpr std::array signature_bytes{0x5a, 0x00, 0xff, 0x11}; -constexpr std::array key_spki{0x30, 0x0a, 0x30, 0x00, 0x01, 0x02, - 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}; -constexpr std::array key_pair_pkcs8{0x30, 0x0a, 0x02, 0x00, 0xa1, 0xb2, - 0xc3, 0xd4, 0xe5, 0xf6, 0x07, 0x18}; +// The SPKI: the toy's prefix 30 0a 30 00, then the key's bytes. +constexpr auto key_spki = joined(std::array{0x30, 0x0a, 0x30, 0x00}, key_bytes); +// The PKCS#8: the toy's prefix 30 0a 02 00, then the secret. +constexpr auto key_pair_pkcs8 = + joined(std::array{0x30, 0x0a, 0x02, 0x00}, secret_bytes); // The "version 2": the prefix 30 0e 02 01, the secret, a1 02 and the secret's first 2 bytes. -constexpr std::array key_pair_pkcs8_v2{ - 0x30, 0x0e, 0x02, 0x01, 0xa1, 0xb2, 0xc3, 0xd4, 0xe5, 0xf6, 0x07, 0x18, 0xa1, 0x02, 0xa1, 0xb2}; +constexpr auto key_pair_pkcs8_v2 = + joined(joined(std::array{0x30, 0x0e, 0x02, 0x01}, secret_bytes), + std::array{0xa1, 0x02, 0xa1, 0xb2}); // The two bounds (owner decision 23): stated by every pair that decodes, equal but on the toy key // pair's pkcs8, which a change of its own (the toy's) rules longer. diff --git a/test/formats_vocabulary_test.cpp b/test/formats_vocabulary_test.cpp index c1bc1b5e..caf5314e 100644 --- a/test/formats_vocabulary_test.cpp +++ b/test/formats_vocabulary_test.cpp @@ -23,7 +23,6 @@ #include #include -namespace crypto = webcpp::crypto; namespace codecs = webcpp::codecs; namespace formats = webcpp::crypto::formats; namespace detail = webcpp::crypto::detail; diff --git a/test/support/format_checks.hpp b/test/support/format_checks.hpp index 008bdb86..6aa5f00f 100644 --- a/test/support/format_checks.hpp +++ b/test/support/format_checks.hpp @@ -82,16 +82,12 @@ auto as_input(std::span encoding) { } /** - * Checks that `crypto::encode` of `value` in `format`, `codecs::encode`, the member when the type - * has it, the span form and `codecs::tokens::append_to` give `expected`; that `crypto::decode` - * (and the member) of `expected` gives a value that encodes to it again; and that a span one - * element short is `codecs::error::output_too_small`, written nowhere. + * Checks that `crypto::encode`, `codecs::encode` and the member, when the type has it, give + * `expected`. */ template -void check_every_form(Format format, Value const& value, std::span expected) { - using element = element_of; - constexpr std::size_t capacity = formats::max_encoded_size; - +void check_default_results(Format format, Value const& value, + std::span expected) { auto const free_form = crypto::encode(format, value); if (BOOST_TEST(free_form.has_value())) { BOOST_TEST(same_bytes(free_form->view(), expected)); @@ -106,6 +102,17 @@ void check_every_form(Format format, Value const& value, std::spanview(), expected)); } } +} + +/** + * Checks that the span form and `codecs::tokens::append_to` give `expected`, and that a span one + * element short is `codecs::error::output_too_small`, written nowhere. + */ +template +void check_caller_outputs(Format format, Value const& value, + std::span expected) { + using element = element_of; + constexpr std::size_t capacity = formats::max_encoded_size; std::array buffer{}; auto const written = crypto::encode(format, value, std::span(buffer)); @@ -122,34 +129,48 @@ void check_every_form(Format format, Value const& value, std::span(format, as_input(expected)); - if (BOOST_TEST(decoded.has_value())) { - auto const again = crypto::encode(format, *decoded); - if (BOOST_TEST(again.has_value())) { - BOOST_TEST(same_bytes(again->view(), expected)); - } + if (expected.empty()) { + return; } - if constexpr (has_members) { - auto const member_decoded = Value::decode(format, as_input(expected)); - if (BOOST_TEST(member_decoded.has_value())) { - auto const again = crypto::encode(format, *member_decoded); - if (BOOST_TEST(again.has_value())) { - BOOST_TEST(same_bytes(again->view(), expected)); - } - } + constexpr auto untouched = static_cast(0xa5); + std::array short_buffer{}; + short_buffer.fill(untouched); + auto const short_written = + crypto::encode(format, value, std::span(short_buffer).first(expected.size() - 1)); + if (BOOST_TEST(!short_written.has_value())) { + BOOST_TEST(short_written.error() == codecs::error::output_too_small); } + BOOST_TEST(std::ranges::all_of(short_buffer, [&](element held) { return held == untouched; })); +} - if (!expected.empty()) { - constexpr auto untouched = static_cast(0xa5); - std::array short_buffer{}; - short_buffer.fill(untouched); - auto const short_written = crypto::encode( - format, value, std::span(short_buffer).first(expected.size() - 1)); - if (BOOST_TEST(!short_written.has_value())) { - BOOST_TEST(short_written.error() == codecs::error::output_too_small); - } - BOOST_TEST( - std::ranges::all_of(short_buffer, [&](element held) { return held == untouched; })); +/** Checks that `decoded` holds a value that encodes to `expected` again. */ +template +void check_encodes_back(Format format, codecs::result const& decoded, + std::span expected) { + if (!BOOST_TEST(decoded.has_value())) { + return; + } + auto const again = crypto::encode(format, *decoded); + if (BOOST_TEST(again.has_value())) { + BOOST_TEST(same_bytes(again->view(), expected)); + } +} + +/** + * Checks that `crypto::encode` of `value` in `format`, `codecs::encode`, the member when the type + * has it, the span form and `codecs::tokens::append_to` give `expected`; that `crypto::decode` + * (and the member) of `expected` gives a value that encodes to it again; and that a span one + * element short is `codecs::error::output_too_small`, written nowhere. + */ +template +void check_every_form(Format format, Value const& value, std::span expected) { + check_default_results(format, value, expected); + check_caller_outputs(format, value, expected); + check_encodes_back(format, crypto::decode(format, as_input(expected)), + expected); + if constexpr (has_members) { + check_encodes_back(format, Value::decode(format, as_input(expected)), + expected); } } @@ -236,7 +257,7 @@ inline constexpr bool is_secret_result> = true; template void check_secret_result(Format format, Value const& value) { auto encoded = crypto::encode(format, value); - using result_type = typename decltype(encoded)::value_type; + using result_type = decltype(encoded)::value_type; static_assert(is_secret_result); static_assert(!std::is_copy_constructible_v); if (!BOOST_TEST(encoded.has_value())) { diff --git a/test/support/formats_toy.hpp b/test/support/formats_toy.hpp index 1124a29c..fa4e80ec 100644 --- a/test/support/formats_toy.hpp +++ b/test/support/formats_toy.hpp @@ -237,6 +237,16 @@ struct appended, Format> { /** A copy of the library's one list with the stand-in text format added. */ using all_formats_with_stand_in = appended::type; +/** The bytes of `first` followed by those of `second`. */ +template +constexpr std::array joined( + std::array const& first, + std::array const& second) noexcept { + std::array both{}; + std::ranges::copy(second, std::ranges::copy(first, both.begin()).out); + return both; +} + /** Writes `prefix` then `body` at the start of `output`, or nothing when it is too short. */ inline codecs::result write_toy(std::span prefix, std::span body, @@ -491,8 +501,9 @@ struct value_codec { return error::output_too_small; } for (std::size_t index = 0; index < crypto::test::toy_key::size; ++index) { - output_text[2 * index] = digits[key.bytes()[index] >> 4U]; - output_text[(2 * index) + 1] = digits[key.bytes()[index] & 0x0fU]; + unsigned const byte = key.bytes()[index]; + output_text[2 * index] = digits[byte >> 4U]; + output_text[(2 * index) + 1] = digits[byte & 0x0fU]; } return std::size_t{16}; } @@ -509,7 +520,8 @@ struct value_codec { if (digit == std::string_view::npos) { return crypto::error::invalid_encoding; } - key_bytes[index / 2] = static_cast((key_bytes[index / 2] << 4U) | digit); + std::size_t const high = key_bytes[index / 2]; + key_bytes[index / 2] = static_cast((high << 4U) | digit); } return crypto::test::toy_key{key_bytes}; } diff --git a/test/support/wipe_record.hpp b/test/support/wipe_record.hpp index 32fc95ba..4fe719ec 100644 --- a/test/support/wipe_record.hpp +++ b/test/support/wipe_record.hpp @@ -81,7 +81,7 @@ inline bool wiped(void const* first, std::size_t byte_count) { BOOST_TEST_EQ(wipes.not_zero, 0U); auto const begin = reinterpret_cast(first); std::vector const kept = kept_wipes(); - return std::any_of(kept.begin(), kept.end(), [&](wipe_entry const& entry) { + return std::ranges::any_of(kept, [&](wipe_entry const& entry) { return entry.first <= begin && begin + byte_count <= entry.first + entry.size; }); } @@ -107,7 +107,8 @@ void webcpp::secure::test::wipe_record(void const* wiped_data, std::size_t byte_ // Checked here, so that the store cannot throw: the seam is noexcept. A wipe past the storage // is only counted, and the readers fail the test on it. if (log.count < log.entries.size()) { - log.entries[log.count] = {reinterpret_cast(wiped_data), byte_count}; + log.entries[log.count] = {.first = reinterpret_cast(wiped_data), + .size = byte_count}; } ++log.count; if (!std::all_of(bytes, bytes + byte_count, [](unsigned char b) { return b == 0; })) { From a80b06567509f51e9773db52fb29f9725ffb8c2d Mon Sep 17 00:00:00 2001 From: R Date: Tue, 1 Dec 2026 00:49:29 -0300 Subject: [PATCH 19/81] crypto: formats on codecs lint fix 2 --- test/support/wipe_record.hpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/support/wipe_record.hpp b/test/support/wipe_record.hpp index 4fe719ec..11caff2c 100644 --- a/test/support/wipe_record.hpp +++ b/test/support/wipe_record.hpp @@ -107,8 +107,8 @@ void webcpp::secure::test::wipe_record(void const* wiped_data, std::size_t byte_ // Checked here, so that the store cannot throw: the seam is noexcept. A wipe past the storage // is only counted, and the readers fail the test on it. if (log.count < log.entries.size()) { - log.entries[log.count] = {.first = reinterpret_cast(wiped_data), - .size = byte_count}; + auto const first = reinterpret_cast(wiped_data); + log.entries[log.count] = {.first = first, .size = byte_count}; } ++log.count; if (!std::all_of(bytes, bytes + byte_count, [](unsigned char b) { return b == 0; })) { From fb503f7dc51135853536eb5bcc4b8a26564ca9af Mon Sep 17 00:00:00 2001 From: R Date: Tue, 1 Dec 2026 01:11:41 -0300 Subject: [PATCH 20/81] crypto: formats on codecs lint fix 3 --- test/support/format_checks.hpp | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/test/support/format_checks.hpp b/test/support/format_checks.hpp index 6aa5f00f..473a7e81 100644 --- a/test/support/format_checks.hpp +++ b/test/support/format_checks.hpp @@ -86,7 +86,7 @@ auto as_input(std::span encoding) { * `expected`. */ template -void check_default_results(Format format, Value const& value, +void check_default_results(Format const& format, Value const& value, std::span expected) { auto const free_form = crypto::encode(format, value); if (BOOST_TEST(free_form.has_value())) { @@ -109,7 +109,7 @@ void check_default_results(Format format, Value const& value, * element short is `codecs::error::output_too_small`, written nowhere. */ template -void check_caller_outputs(Format format, Value const& value, +void check_caller_outputs(Format const& format, Value const& value, std::span expected) { using element = element_of; constexpr std::size_t capacity = formats::max_encoded_size; @@ -145,7 +145,7 @@ void check_caller_outputs(Format format, Value const& value, /** Checks that `decoded` holds a value that encodes to `expected` again. */ template -void check_encodes_back(Format format, codecs::result const& decoded, +void check_encodes_back(Format const& format, codecs::result const& decoded, std::span expected) { if (!BOOST_TEST(decoded.has_value())) { return; @@ -163,7 +163,8 @@ void check_encodes_back(Format format, codecs::result const& decoded, * element short is `codecs::error::output_too_small`, written nowhere. */ template -void check_every_form(Format format, Value const& value, std::span expected) { +void check_every_form(Format const& format, Value const& value, + std::span expected) { check_default_results(format, value, expected); check_caller_outputs(format, value, expected); check_encodes_back(format, crypto::decode(format, as_input(expected)), @@ -179,7 +180,7 @@ void check_every_form(Format format, Value const& value, std::span -void check_no_heap(Format format, Value const& value) { +void check_no_heap(Format const& format, Value const& value) { using element = element_of; std::array> buffer{}; @@ -214,7 +215,7 @@ void check_no_heap(Format format, Value const& value) { * to the changed input: no two encodings decode to one value. */ template -void check_strict(Format format, std::span valid) { +void check_strict(Format const& format, std::span valid) { auto const decodes_back = [&](std::span changed) { auto const decoded = crypto::decode(format, as_input(changed)); if (!decoded) { @@ -255,7 +256,7 @@ inline constexpr bool is_secret_result> = true; * storage, its whole capacity, secure's wipe record sees erased when it is moved from. */ template -void check_secret_result(Format format, Value const& value) { +void check_secret_result(Format const& format, Value const& value) { auto encoded = crypto::encode(format, value); using result_type = decltype(encoded)::value_type; static_assert(is_secret_result); From ba72c80f7361a2900b9abc8f41bd658e05c81965 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 1 Dec 2026 01:28:57 -0300 Subject: [PATCH 21/81] crypto: user_globals leaves codecs' headers out: MSVC instantiates their templates after the globals --- test/user_globals_test.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/test/user_globals_test.cpp b/test/user_globals_test.cpp index e76cd327..a6ea271e 100644 --- a/test/user_globals_test.cpp +++ b/test/user_globals_test.cpp @@ -48,8 +48,6 @@ #include #include #include -#include -#include #include #include #include @@ -142,7 +140,6 @@ extern int const encrypt; #include #include #include -#include int main() { return 0; From ba9ab6a71c4446db35979e7b8abcdceb8339798c Mon Sep 17 00:00:00 2001 From: R Date: Tue, 1 Dec 2026 01:58:19 -0300 Subject: [PATCH 22/81] crypto: a PEM of crypto's pair decodes in place from every text, the reasons and the default form tested on the toy, the DER buffer's wipe found by its address --- doc/generated/messages.adoc | 40 +++++ doc/tables/crypto.json | 4 + include/webcpp/crypto/formats.hpp | 140 ++++++++++++++---- test/formats_pem_test.cpp | 47 ++++++ test/formats_verbs_test.cpp | 34 +++++ test/messages/Jamfile | 4 + .../decode_refusal_reason_toy/Jamfile | 14 ++ .../decode_refusal_reason_toy.cpp | 30 ++++ test/messages/forms_without_default/Jamfile | 14 ++ .../forms_without_default.cpp | 32 ++++ test/messages/pem_decode_from_bytes/Jamfile | 14 ++ .../pem_decode_from_bytes.cpp | 31 ++++ test/messages/refusal_reason_toy/Jamfile | 14 ++ .../refusal_reason_toy/refusal_reason_toy.cpp | 24 +++ test/msvc/Jamfile | 4 + test/msvc/decode_refusal_reason_toy/Jamfile | 9 ++ test/msvc/decode_refusal_reason_toy/app.cpp | 22 +++ test/msvc/forms_without_default/Jamfile | 9 ++ test/msvc/forms_without_default/app.cpp | 24 +++ test/msvc/pem_decode_from_bytes/Jamfile | 9 ++ test/msvc/pem_decode_from_bytes/app.cpp | 23 +++ test/msvc/refusal_reason_toy/Jamfile | 9 ++ test/msvc/refusal_reason_toy/app.cpp | 17 +++ test/support/formats_toy.hpp | 127 +++++++++++++++- test/user_globals_test.cpp | 7 + 25 files changed, 668 insertions(+), 34 deletions(-) create mode 100644 test/messages/decode_refusal_reason_toy/Jamfile create mode 100644 test/messages/decode_refusal_reason_toy/decode_refusal_reason_toy.cpp create mode 100644 test/messages/forms_without_default/Jamfile create mode 100644 test/messages/forms_without_default/forms_without_default.cpp create mode 100644 test/messages/pem_decode_from_bytes/Jamfile create mode 100644 test/messages/pem_decode_from_bytes/pem_decode_from_bytes.cpp create mode 100644 test/messages/refusal_reason_toy/Jamfile create mode 100644 test/messages/refusal_reason_toy/refusal_reason_toy.cpp create mode 100644 test/msvc/decode_refusal_reason_toy/Jamfile create mode 100644 test/msvc/decode_refusal_reason_toy/app.cpp create mode 100644 test/msvc/forms_without_default/Jamfile create mode 100644 test/msvc/forms_without_default/app.cpp create mode 100644 test/msvc/pem_decode_from_bytes/Jamfile create mode 100644 test/msvc/pem_decode_from_bytes/app.cpp create mode 100644 test/msvc/refusal_reason_toy/Jamfile create mode 100644 test/msvc/refusal_reason_toy/app.cpp diff --git a/doc/generated/messages.adoc b/doc/generated/messages.adoc index 3e4bd11a..a0b79059 100644 --- a/doc/generated/messages.adoc +++ b/doc/generated/messages.adoc @@ -311,6 +311,12 @@ The fix: Make `+max_decode_input_size+` equal to `+max_encoded_size+`, or, where The fix: State `+static constexpr std::size_t max_decode_input_size+` in the value codec that decodes: the longest encoded input its `+decode+` accepts, equal to its `+max_encoded_size+` unless a change rules otherwise. +|`+decode_refusal_reason_toy+` +|native, wasip2, wasip3 +|`+webcpp::crypto: an x-only key decodes into curves::secp256k1::xonly_public_key+` + +The fix: Decode the x-only form into the type that holds it, as secp256k1's `+curves::secp256k1::xonly_public_key+`; the type this refuses has the form to encode only. + |`+default_openssl_wasm+` |native, wasip2, wasip3 |`+webcpp::crypto: WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL no longer chooses a default. Write the backend in the type where the program wants it, as in ciphers::gcm>.+` @@ -389,6 +395,12 @@ The fix: Encode or decode a type in a format of its list, the `+format_list+` th The fix: Include `++`, or the curve's `+/formats.hpp>+`, which includes it: `+crypto::formats+` is declared by `+config.hpp+` and filled by the formats headers alone. +|`+forms_without_default+` +|native, wasip2, wasip3 +|`+webcpp::crypto: a forms_of specialization lists formats::default_form_t, the form of a format named without one+` + +The fix: List `+crypto::formats::default_form_t+` first in each `+detail::forms_of+` specialization, with the other point forms the type accepts. + |`+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)+` @@ -537,6 +549,12 @@ The fix: Add `+/webcpp/crypto//p256-default+`, which links `+/third_party//bears The fix: Leave the backend out, as in `+curves::p256::keypair+`, or name `+backends::bearssl+`, and add `+/third_party//bearssl+`. +|`+pem_decode_from_bytes+` +|native, wasip2, wasip3 +|`+webcpp::crypto: a PEM decodes from a text: a std::string_view, or a contiguous range of char+` + +The fix: Give a PEM to `+crypto::decode+` as a text: a `+std::string_view+`, a `+std::string+`, or a contiguous range of `+char+` such as `+std::span+`; DER bytes decode with `+crypto::formats::spki+` or `+crypto::formats::pkcs8+` themselves. + |`+pem_default_not_linked+` |native, wasip2, wasip3 |`+webcpp::crypto: PEM's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//pem-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//pem-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)+` @@ -611,6 +629,12 @@ The fix: Give `+recover+` a recoverable scheme and its policy, `+recover(crypto: The fix: Name the policy after the scheme: `+curves::secp256k1::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, crypto::verification_policies::low_s_only, signature, input)+`, its only policy. +|`+refusal_reason_toy+` +|native, wasip2, wasip3 +|`+webcpp::crypto: Ed25519 and BIP340 signatures have no DER form; their 64 bytes are the signature+` + +The fix: Encode the signature with `+crypto::formats::raw+`: an Ed25519 or BIP340 signature has no DER form, its 64 bytes are the signature. + |`+scheme_in_crypto_namespace+` |native, wasip2, wasip3 |`+no member named 'ecdsa_sha256' in namespace 'webcpp::crypto'+` @@ -1786,6 +1810,10 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |State `+static constexpr std::size_t max_decode_input_size+` in the value codec that decodes: the longest encoded input its `+decode+` accepts, equal to its `+max_encoded_size+` unless a change rules otherwise. +|`+decode_refusal_reason_toy+` +|the compile +|Decode the x-only form into the type that holds it, as secp256k1's `+curves::secp256k1::xonly_public_key+`; the type this refuses has the form to encode only. + |`+default_openssl_wasm+` |the compile |Remove the define, and name `+gcm>+` where the program wants OpenSSL. @@ -1826,6 +1854,10 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |Include `++`, or the curve's `+/formats.hpp>+`, which includes it: `+crypto::formats+` is declared by `+config.hpp+` and filled by the formats headers alone. +|`+forms_without_default+` +|the compile +|List `+crypto::formats::default_form_t+` first in each `+detail::forms_of+` specialization, with the other point forms the type accepts. + |`+gcm_default_openssl_not_linked+` |the compile |Natively the default is OpenSSL: add `+/webcpp/crypto//gcm-default+`, which links `+/webcpp/crypto//openssl+` there, or name BearSSL in the type, as in `+gcm>+`. @@ -1890,6 +1922,10 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |Leave the backend out, as in `+curves::p256::keypair+`, or name `+backends::bearssl+`, and add `+/third_party//bearssl+`. +|`+pem_decode_from_bytes+` +|the compile +|Give a PEM to `+crypto::decode+` as a text: a `+std::string_view+`, a `+std::string+`, or a contiguous range of `+char+` such as `+std::span+`; DER bytes decode with `+crypto::formats::spki+` or `+crypto::formats::pkcs8+` themselves. + |`+pem_default_not_linked+` |the compile |Add `+/webcpp/crypto//pem-default+`, which links `+/third_party//sodium+` on every target. @@ -1918,6 +1954,10 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |Name the policy after the scheme: `+curves::secp256k1::recover(crypto::signing_schemes::ecdsa_sha256_recoverable, crypto::verification_policies::low_s_only, signature, input)+`, its only policy. +|`+refusal_reason_toy+` +|the compile +|Encode the signature with `+crypto::formats::raw+`: an Ed25519 or BIP340 signature has no DER form, its 64 bytes are the signature. + |`+secp256k1_not_linked+` |the compile |Add `+/third_party//secp256k1+`. diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index aa533714..28169cf5 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -1482,6 +1482,10 @@ "decode_bound_missing": "State `static constexpr std::size_t max_decode_input_size` in the value codec that decodes: the longest encoded input its `decode` accepts, equal to its `max_encoded_size` unless a change rules otherwise.", "decode_bound_differs": "Make `max_decode_input_size` equal to `max_encoded_size`, or, where a change rules that the decode accepts a longer form (as PKCS#8 version 2 will), specialize `detail::bounds_may_differ_v` for the pair beside its value codec.", "format_without_header": "Include ``, or the curve's `/formats.hpp>`, which includes it: `crypto::formats` is declared by `config.hpp` and filled by the formats headers alone.", + "decode_refusal_reason_toy": "Decode the x-only form into the type that holds it, as secp256k1's `curves::secp256k1::xonly_public_key`; the type this refuses has the form to encode only.", + "refusal_reason_toy": "Encode the signature with `crypto::formats::raw`: an Ed25519 or BIP340 signature has no DER form, its 64 bytes are the signature.", + "pem_decode_from_bytes": "Give a PEM to `crypto::decode` as a text: a `std::string_view`, a `std::string`, or a contiguous range of `char` such as `std::span`; DER bytes decode with `crypto::formats::spki` or `crypto::formats::pkcs8` themselves.", + "forms_without_default": "List `crypto::formats::default_form_t` first in each `detail::forms_of` specialization, with the other point forms the type accepts.", "recover_ecdsa_signature": "Give `recover` a `curves::secp256k1::recoverable_signature`, which `sign(crypto::signing_schemes::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.", diff --git a/include/webcpp/crypto/formats.hpp b/include/webcpp/crypto/formats.hpp index 77eeda2a..aa5914d9 100644 --- a/include/webcpp/crypto/formats.hpp +++ b/include/webcpp/crypto/formats.hpp @@ -38,6 +38,7 @@ #include #include #include +#include #include #include #include @@ -535,6 +536,11 @@ using formats_of_t = formats_of::type; * The point forms `T` accepts for `Format`, a base form of its list: the default form alone unless * the type's formats header specializes it. * + * A specialization lists `formats::default_form_t` among its forms: a format named without a + * point form names it, and every pair of design D4 has its default form (the uncompressed point, + * or the x-only key's own 32 bytes). The verbs' check stops the build on a list without it, before + * the type's list is read. + * * @tparam Format The base form of a format. * @tparam T The value's type. */ @@ -699,6 +705,17 @@ template inline constexpr bool checked_by_crypto_v = curve_of_v != curve_id::none && is_format_v; +/** + * Whether `T`'s `forms_of` for `Format` lists `formats::default_form_t`, as every specialization + * must (a format named without a point form names it). + * + * @tparam Format The format's type. + * @tparam T The value's type. + */ +template +inline constexpr bool default_form_listed_v = + in_list_v::type, T>>; + /** * Whether the pair passes crypto's check, in the direction `Decoding` says: always for a pair * crypto does not check; else the type's formats are declared, the pair has no reason of its own, @@ -714,13 +731,13 @@ consteval bool pair_accepted() noexcept { if constexpr (!checked_by_crypto_v) { return true; } else if constexpr (Decoding) { - return formats_declared_v && + return formats_declared_v && default_form_listed_v && decode_refusal_reason_v == refusal_reason::none && refusal_reason_v == refusal_reason::none && !format_refused> && codecs::decodable; } else { - return formats_declared_v && + return formats_declared_v && default_form_listed_v && refusal_reason_v == refusal_reason::none && !format_refused> && codecs::encodable; @@ -749,9 +766,9 @@ constexpr void refuse_for_reason() noexcept { /** * Stops the build for a pair `pair_accepted` refuses, with the first of crypto's sentences that - * applies (design D3): the formats header to include; the pair's own reason; that the type has no - * such format, the type's list printed in the failed requirement; or that codecs does not convert - * the pair in this direction. + * applies (design D3): the formats header to include; a `forms_of` without the default form; the + * pair's own reason; that the type has no such format, the type's list printed in the failed + * requirement; or that codecs does not convert the pair in this direction. * * @tparam Decoding Whether the call decodes. * @tparam Format The format's type. @@ -772,6 +789,10 @@ constexpr void refuse_pair() noexcept { static_assert(curve_of_v != curve_id::secp256k1 || formats_declared_v, "webcpp::crypto: include to " "encode or decode this type"); + } else if constexpr (!default_form_listed_v) { + static_assert(default_form_listed_v, + "webcpp::crypto: a forms_of specialization lists formats::default_form_t, " + "the form of a format named without one"); } else if constexpr (Decoding && decode_refusal_reason_v != refusal_reason::none) { refuse_for_reason>(); @@ -827,10 +848,35 @@ struct pem_inner> { using type = Inner; }; +/** + * Whether `Text` is a text a PEM decodes from, as codecs takes one: a type that converts to + * `std::string_view`, or a contiguous sized range of `char` (`std::span`, + * `std::vector`). + * + * @tparam Text The input's type. + */ +template +concept pem_text = + std::is_convertible_v || + (std::ranges::contiguous_range && std::ranges::sized_range && + std::is_same_v, char>); + +/** + * Whether the inner value codec of a PEM of `Value` states its decode bound, which sizes the + * in-place decode (owner decision 23). + * + * @tparam Inner The PEM's inner format. + * @tparam Value The value's type. + */ +template +inline constexpr bool states_decode_bound_v = + requires { codecs::value_codec::max_decode_input_size; }; + /** * Whether `crypto::decode(format, input)` decodes in place (design R24): `Format` is a PEM, - * `Input` is a text, and the inner value codec decodes bytes into `Value` and states its decode - * bound. + * and either the pair is crypto's, which never goes to codecs' heap path (`decode_pem` stops the + * build on an input that is no text or an inner pair without its decode bound), or `Input` is a + * text and the inner value codec decodes bytes into `Value` and states its decode bound. * * @tparam Value The value's type. * @tparam Format The format's type. @@ -839,14 +885,15 @@ struct pem_inner> { template inline constexpr bool decodes_in_place_v = false; -/** A PEM of a text, whose inner value codec states its decode bound, decodes in place. */ +/** A PEM of crypto's pair, or of a text whose inner value codec states its bound, is in place. */ template -inline constexpr bool decodes_in_place_v, Input> = requires { - requires std::is_convertible_v; - requires codecs::decodable; - requires codecs::value_codec::output == codecs::output_kind::bytes; - requires codecs::value_codec::max_decode_input_size > 0; -}; +inline constexpr bool decodes_in_place_v, Input> = + checked_by_crypto_v, Value> || requires { + requires pem_text; + requires codecs::decodable; + requires codecs::value_codec::output == codecs::output_kind::bytes; + requires codecs::value_codec::max_decode_input_size > 0; + }; /** * Whether `crypto::decode` of `Input` in `Format` cannot throw: the in-place PEM decode is @@ -868,6 +915,22 @@ consteval bool decode_is_noexcept() { } } +/** + * The text of `text` as a `std::string_view`: its conversion, or its characters. + * + * @tparam Text A `pem_text`. + * @param text The text. + * @return A view of its characters. + */ +template +[[nodiscard]] std::string_view pem_text_view(Text const& text) noexcept { + if constexpr (std::is_convertible_v) { + return text; + } else { + return {std::ranges::data(text), std::ranges::size(text)}; + } +} + /** * The two steps of the in-place PEM decode into `der`: the armor through codecs' buffer form, then * the inner value codec over the bytes it wrote. A payload longer than `der` is crypto's @@ -875,14 +938,13 @@ consteval bool decode_is_noexcept() { * * @tparam Value The value's type. * @tparam Format The PEM format's type. - * @tparam Text The text's type. * @param format The PEM format. * @param text The PEM text. * @param der The buffer of the inner format's decode bound. * @return The value, or the error. */ -template -[[nodiscard]] codecs::result decode_pem_into(Format const& format, Text const& text, +template +[[nodiscard]] codecs::result decode_pem_into(Format const& format, std::string_view text, std::span der) noexcept { codecs::result const written = codecs::decode(format.outer, text, der); if (!written) { @@ -899,11 +961,14 @@ template /** * Decodes the PEM `text` into a `Value` in place (design R24): the armor through codecs' buffer * form into a stack buffer of the inner format's decode bound, `max_decode_input_size` (owner - * decision 23), then the inner value codec, allocating nothing. A payload longer than that buffer - * is crypto's `invalid_encoding`; the armor's errors are codecs', unchanged, and come first, as - * `codecs::decode` gives them. When the inner value codec is secret, or the value is - * (`codecs::is_secret_v`), the call holds `secure::timing_guard` and the buffer is wiped by - * `secure::erase_secret` on every path. + * decision 23), then the inner value codec, allocating nothing. + * + * `text` converts to a `std::string_view` or is a contiguous sized range of `char`, as codecs + * takes a text; any other input, and an inner pair that states no decode bound, stop the build. A + * payload longer than the buffer is crypto's `invalid_encoding`; the armor's errors are codecs', + * unchanged, and come first, as `codecs::decode` gives them. When the inner value codec is secret, + * or the value is (`codecs::is_secret_v`), the call holds `secure::timing_guard` and the buffer is + * wiped by `secure::erase_secret` on every path. * * @tparam Value The value's type. * @tparam Format The PEM format's type, `formats::pem_t`. @@ -917,12 +982,27 @@ template using inner_type = pem_inner::type; constexpr bool secret = value_codec_secret_v || codecs::is_secret_v; secure::timing_guard const timing_scope{secret}; - std::array> der{}; - codecs::result decoded = decode_pem_into(format, text, std::span(der)); - if constexpr (secret) { - secure::erase_secret(der); + static_assert(pem_text, + "webcpp::crypto: a PEM decodes from a text: a std::string_view, or a contiguous " + "range of char"); + if constexpr (pem_text) { + static_assert(states_decode_bound_v, + "webcpp::crypto: a value codec that decodes states max_decode_input_size, " + "its decode bound"); + if constexpr (states_decode_bound_v) { + std::array> der{}; + codecs::result decoded = + decode_pem_into(format, pem_text_view(text), std::span(der)); + if constexpr (secret) { + secure::erase_secret(der); + } + return decoded; + } else { + return error::invalid_encoding; + } + } else { + return error::invalid_encoding; } - return decoded; } } // namespace detail @@ -969,9 +1049,9 @@ template * `std::string_view` (or any text) for a PEM, as the value codec's output kind says (design R4). * The PEM's armor is codecs': lines ended by a line feed or a carriage return and a line feed, the * last ending optional, nothing before BEGIN or after END; its errors are codecs'; a payload longer - * than the inner format's decode bound is `crypto::error::invalid_encoding`. `noexcept` on every - * pair of crypto's; a pair crypto does not check is as `codecs::decode` is, which allocates - * for a heap result. + * than the inner format's decode bound is `crypto::error::invalid_encoding`. A PEM of crypto's pair + * is always decoded in place, never on codecs' heap path. `noexcept` on every pair of crypto's; a + * pair crypto does not check is as `codecs::decode` is, which allocates for a heap result. * * @tparam Value The value's type. * @tparam Format The format's type. diff --git a/test/formats_pem_test.cpp b/test/formats_pem_test.cpp index 1f336e01..1bd5042f 100644 --- a/test/formats_pem_test.cpp +++ b/test/formats_pem_test.cpp @@ -172,6 +172,20 @@ void decode_in_place() { BOOST_TEST_GT(after_codecs, after_in_place); BOOST_TEST(in_place.has_value()); BOOST_TEST(through_codecs.has_value()); + + // Every text codecs takes decodes in place too, never on codecs' heap path: a span of + // characters and a vector of them, the vector made before the count. + std::vector const characters(key_pem.begin(), key_pem.end()); + std::span const span_text(key_pem.data(), key_pem.size()); + std::size_t const before_ranges = webcpp::test::allocations(); + auto const from_span = crypto::decode(formats::pem(formats::spki), span_text); + auto const from_vector = crypto::decode(formats::pem(formats::spki), characters); + std::size_t const after_ranges = webcpp::test::allocations(); + BOOST_TEST_EQ(after_ranges, before_ranges); + if (BOOST_TEST(from_span.has_value()) && BOOST_TEST(from_vector.has_value()) && in_place) { + BOOST_TEST(*from_span == *in_place); + BOOST_TEST(*from_vector == *in_place); + } } /** @@ -245,11 +259,17 @@ void buffer_wiped() { } constexpr std::size_t buffer_size = formats::max_decode_input_size; + // The buffer is found by its address, which the toy's pkcs8 decode records as its input. + webcpp::crypto::test::toy_pkcs8_decoded_from = nullptr; webcpp::test::clear_wipes(); + void const* buffer = nullptr; { auto const decoded = crypto::decode(formats::pem(formats::pkcs8), encoded->view()); BOOST_TEST(decoded.has_value()); + buffer = webcpp::crypto::test::toy_pkcs8_decoded_from; + BOOST_TEST(buffer != nullptr); + BOOST_TEST(webcpp::test::wiped(buffer, buffer_size)); std::vector const sizes = webcpp::test::wiped_sizes(); BOOST_TEST(std::ranges::count(sizes, buffer_size) == 1); } @@ -258,6 +278,20 @@ void buffer_wiped() { std::string const corrupt = armored("PRIVATE KEY", std::span(key_pair_pkcs8_v2).first(15)); auto const refused = crypto::decode(formats::pem(formats::pkcs8), corrupt); BOOST_TEST(refused.error() == crypto::error::invalid_encoding); + BOOST_TEST(webcpp::test::wiped(webcpp::crypto::test::toy_pkcs8_decoded_from, buffer_size)); + std::vector const sizes = webcpp::test::wiped_sizes(); + BOOST_TEST(std::ranges::count(sizes, buffer_size) == 1); + } + { + // A payload past the decode bound (Review Focus 5 for a secret): the armor refuses to + // write it, and the buffer, whose address the same call made before gave, is wiped all + // the same. + std::array longer{}; + std::ranges::copy(key_pair_pkcs8_v2, longer.begin()); + auto const refused = crypto::decode(formats::pem(formats::pkcs8), + armored("PRIVATE KEY", longer)); + BOOST_TEST(refused.error() == crypto::error::invalid_encoding); + BOOST_TEST(webcpp::test::wiped(buffer, buffer_size)); std::vector const sizes = webcpp::test::wiped_sizes(); BOOST_TEST(std::ranges::count(sizes, buffer_size) == 1); } @@ -340,6 +374,19 @@ void same_as_codecs() { } else if (!in_place && !through_codecs) { BOOST_TEST(in_place.error() == through_codecs.error()); } + std::span const span_text(text.data(), text.size()); + std::vector const characters(text.begin(), text.end()); + auto const from_span = crypto::decode(formats::pem(formats::spki), span_text); + auto const from_vector = crypto::decode(formats::pem(formats::spki), characters); + BOOST_TEST_EQ(from_span.has_value(), in_place.has_value()); + BOOST_TEST_EQ(from_vector.has_value(), in_place.has_value()); + if (in_place && from_span && from_vector) { + BOOST_TEST(*from_span == *in_place); + BOOST_TEST(*from_vector == *in_place); + } else if (!in_place && !from_span && !from_vector) { + BOOST_TEST(from_span.error() == in_place.error()); + BOOST_TEST(from_vector.error() == in_place.error()); + } auto const private_in_place = crypto::decode(formats::pem(formats::pkcs8), text); auto const private_through_codecs = diff --git a/test/formats_verbs_test.cpp b/test/formats_verbs_test.cpp index 413816a1..9feb8cda 100644 --- a/test/formats_verbs_test.cpp +++ b/test/formats_verbs_test.cpp @@ -42,6 +42,7 @@ namespace detail = webcpp::crypto::detail; using webcpp::crypto::test::joined; using webcpp::crypto::test::toy_key; using webcpp::crypto::test::toy_keypair; +using webcpp::crypto::test::toy_point; using webcpp::crypto::test::toy_signature; namespace { @@ -108,6 +109,24 @@ static_assert(detail::checked_by_crypto_v, toy_signature>); static_assert(!detail::checked_by_crypto_v); static_assert(!detail::checked_by_crypto_v, std::array>); +// A pair's own reasons (design D3, F14's direction): the toy point's raw(xonly) encodes and does +// not decode into it; the toy signature's der is refused both ways, though der is not in its list, +// by its reason first. +static_assert(detail::pair_accepted, toy_point>()); +static_assert(!detail::pair_accepted, toy_point>()); +static_assert(!detail::format_refused, toy_point, + detail::formats_of_t>); +static_assert(detail::decode_refusal_reason_v, toy_point> == + detail::refusal_reason::xonly_into_public_key); +static_assert(detail::refusal_reason_v, toy_point> == + detail::refusal_reason::none); +static_assert(detail::pair_accepted, toy_point>()); +static_assert(!detail::pair_accepted()); +static_assert(!detail::pair_accepted()); +static_assert(detail::refusal_reason_v == + detail::refusal_reason::no_der_ed25519_bip340); +static_assert(detail::pair_accepted, toy_signature>()); + // The secrecy decode_pem reads through a requires check: absent on the public value codecs. static_assert(!detail::value_codec_secret_v, toy_key>); static_assert(detail::value_codec_secret_v); @@ -121,9 +140,23 @@ static_assert(noexcept(crypto::decode(formats::spki, std::declval>()))); static_assert(noexcept(crypto::decode(formats::pem(formats::spki), std::declval()))); +static_assert(noexcept(crypto::decode(formats::pem(formats::spki), + std::declval>()))); +static_assert(noexcept(crypto::decode(formats::pem(formats::pkcs8), + std::declval const&>()))); static_assert(!noexcept(crypto::decode>( codecs::formats::base64, std::declval()))); +/** The toy point's raw(xonly), which only encodes, gives its first 4 bytes. */ +void encode_only_form() { + toy_point const point{key_bytes}; + auto const xonly = crypto::encode(formats::raw(formats::xonly), point); + if (BOOST_TEST(xonly.has_value())) { + BOOST_TEST(std::ranges::equal(xonly->view(), std::span(key_bytes).first(4))); + } + crypto::test::check_every_form(formats::raw, point, key_bytes); +} + /** Every form of every pair of the toy gives one encoding and decodes it back. */ void every_form() { toy_key const key{key_bytes}; @@ -256,6 +289,7 @@ void foreign_pairs() { int main() { every_form(); + encode_only_form(); no_heap(); strict(); secret_results(); diff --git a/test/messages/Jamfile b/test/messages/Jamfile index e977f225..44b716f7 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -168,3 +168,7 @@ build-project format_header_missing_toy ; build-project decode_bound_missing ; build-project decode_bound_differs ; build-project format_without_header ; +build-project decode_refusal_reason_toy ; +build-project refusal_reason_toy ; +build-project pem_decode_from_bytes ; +build-project forms_without_default ; diff --git a/test/messages/decode_refusal_reason_toy/Jamfile b/test/messages/decode_refusal_reason_toy/Jamfile new file mode 100644 index 00000000..d2300b4a --- /dev/null +++ b/test/messages/decode_refusal_reason_toy/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic decode_refusal_reason_toy : decode_refusal_reason_toy.cpp + : : native wasip2 wasip3 : alone ; diff --git a/test/messages/decode_refusal_reason_toy/decode_refusal_reason_toy.cpp b/test/messages/decode_refusal_reason_toy/decode_refusal_reason_toy.cpp new file mode 100644 index 00000000..5583bead --- /dev/null +++ b/test/messages/decode_refusal_reason_toy/decode_refusal_reason_toy.cpp @@ -0,0 +1,30 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// crypto::decode of the toy point from its raw(xonly), a form it encodes and does not decode +// into, stops at the pair's reason of decoding alone (decode_refusal_reason_v, F14's direction): +// the sentence secp256k1's x-only form will give, and with that error alone. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/formats.hpp:* {{webcpp::crypto: an x-only key decodes into curves::secp256k1::xonly_public_key}} +// clang-format on + +#include "../../support/formats_toy.hpp" + +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const bytes{}; + auto const decoded = crypto::decode( + crypto::formats::raw(crypto::formats::xonly), bytes); + return decoded ? 0 : 1; +} diff --git a/test/messages/forms_without_default/Jamfile b/test/messages/forms_without_default/Jamfile new file mode 100644 index 00000000..9e15a43a --- /dev/null +++ b/test/messages/forms_without_default/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic forms_without_default : forms_without_default.cpp + : : native wasip2 wasip3 : alone ; diff --git a/test/messages/forms_without_default/forms_without_default.cpp b/test/messages/forms_without_default/forms_without_default.cpp new file mode 100644 index 00000000..d30ae53b --- /dev/null +++ b/test/messages/forms_without_default/forms_without_default.cpp @@ -0,0 +1,32 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A forms_of specialization that leaves out formats::default_form_t, here the toy key's spki +// given the compressed form alone, stops crypto::encode of the plain format, which names the +// default form, and with that error alone. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/formats.hpp:* {{webcpp::crypto: a forms_of specialization lists formats::default_form_t, the form of a format named without one}} +// clang-format on + +#include "../../support/formats_toy.hpp" + +#include + +/** The toy key's spki with the compressed form alone, the default left out. */ +template <> +struct webcpp::crypto::detail::forms_of, + webcpp::crypto::test::toy_key> { + using type = form_list; +}; + +int main() { + namespace crypto = webcpp::crypto; + auto const encoded = crypto::encode(crypto::formats::spki, crypto::test::toy_key{}); + return encoded ? 0 : 1; +} diff --git a/test/messages/pem_decode_from_bytes/Jamfile b/test/messages/pem_decode_from_bytes/Jamfile new file mode 100644 index 00000000..4488dee2 --- /dev/null +++ b/test/messages/pem_decode_from_bytes/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic pem_decode_from_bytes : pem_decode_from_bytes.cpp + : : native wasip2 wasip3 : alone ; diff --git a/test/messages/pem_decode_from_bytes/pem_decode_from_bytes.cpp b/test/messages/pem_decode_from_bytes/pem_decode_from_bytes.cpp new file mode 100644 index 00000000..b88b3c49 --- /dev/null +++ b/test/messages/pem_decode_from_bytes/pem_decode_from_bytes.cpp @@ -0,0 +1,31 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// crypto::decode of a PEM pair of crypto's from bytes, not a text, stops at the in-place decode, +// which never hands a pair of crypto's to codecs' heap path (design R24), and with that error +// alone. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/formats.hpp:* {{webcpp::crypto: a PEM decodes from a text: a std::string_view, or a contiguous range of char}} +// clang-format on + +#include "../../support/formats_toy.hpp" + +#include + +#include +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const bytes{}; + auto const decoded = crypto::decode( + crypto::formats::pem(crypto::formats::spki), std::span(bytes)); + return decoded ? 0 : 1; +} diff --git a/test/messages/refusal_reason_toy/Jamfile b/test/messages/refusal_reason_toy/Jamfile new file mode 100644 index 00000000..767d7d4f --- /dev/null +++ b/test/messages/refusal_reason_toy/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic refusal_reason_toy : refusal_reason_toy.cpp + : : native wasip2 wasip3 : alone ; diff --git a/test/messages/refusal_reason_toy/refusal_reason_toy.cpp b/test/messages/refusal_reason_toy/refusal_reason_toy.cpp new file mode 100644 index 00000000..4c42c442 --- /dev/null +++ b/test/messages/refusal_reason_toy/refusal_reason_toy.cpp @@ -0,0 +1,24 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// crypto::encode of the toy signature in der stops at the pair's reason of both directions +// (refusal_reason_v), before the type's list, with Ed25519's sentence, and with that error alone. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/formats.hpp:* {{webcpp::crypto: Ed25519 and BIP340 signatures have no DER form; their 64 bytes are the signature}} +// clang-format on + +#include "../../support/formats_toy.hpp" + +#include + +int main() { + namespace crypto = webcpp::crypto; + auto const encoded = crypto::encode(crypto::formats::der, crypto::test::toy_signature{}); + return encoded ? 0 : 1; +} diff --git a/test/msvc/Jamfile b/test/msvc/Jamfile index 1059bcb9..979a7cde 100644 --- a/test/msvc/Jamfile +++ b/test/msvc/Jamfile @@ -93,3 +93,7 @@ build-project format_header_missing_toy ; build-project decode_bound_missing ; build-project decode_bound_differs ; build-project format_without_header ; +build-project decode_refusal_reason_toy ; +build-project refusal_reason_toy ; +build-project pem_decode_from_bytes ; +build-project forms_without_default ; diff --git a/test/msvc/decode_refusal_reason_toy/Jamfile b/test/msvc/decode_refusal_reason_toy/Jamfile new file mode 100644 index 00000000..89957f39 --- /dev/null +++ b/test/msvc/decode_refusal_reason_toy/Jamfile @@ -0,0 +1,9 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail decode_refusal_reason_toy : app.cpp : /webcpp/crypto//crypto : native ; diff --git a/test/msvc/decode_refusal_reason_toy/app.cpp b/test/msvc/decode_refusal_reason_toy/app.cpp new file mode 100644 index 00000000..7fe3452c --- /dev/null +++ b/test/msvc/decode_refusal_reason_toy/app.cpp @@ -0,0 +1,22 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The toy point decoded from its encode-only raw(xonly) does not compile on MSVC. The text is +// checked on clang, in test/messages/decode_refusal_reason_toy. +#include "../../support/formats_toy.hpp" + +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const bytes{}; + auto const decoded = crypto::decode( + crypto::formats::raw(crypto::formats::xonly), bytes); + return decoded ? 0 : 1; +} diff --git a/test/msvc/forms_without_default/Jamfile b/test/msvc/forms_without_default/Jamfile new file mode 100644 index 00000000..b9031b89 --- /dev/null +++ b/test/msvc/forms_without_default/Jamfile @@ -0,0 +1,9 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail forms_without_default : app.cpp : /webcpp/crypto//crypto : native ; diff --git a/test/msvc/forms_without_default/app.cpp b/test/msvc/forms_without_default/app.cpp new file mode 100644 index 00000000..ad25fc3d --- /dev/null +++ b/test/msvc/forms_without_default/app.cpp @@ -0,0 +1,24 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A forms_of without the default form does not compile on MSVC. The text is checked on clang, in +// test/messages/forms_without_default. +#include "../../support/formats_toy.hpp" + +#include + +/** The toy key's spki with the compressed form alone, the default left out. */ +template <> +struct webcpp::crypto::detail::forms_of, + webcpp::crypto::test::toy_key> { + using type = form_list; +}; + +int main() { + namespace crypto = webcpp::crypto; + auto const encoded = crypto::encode(crypto::formats::spki, crypto::test::toy_key{}); + return encoded ? 0 : 1; +} diff --git a/test/msvc/pem_decode_from_bytes/Jamfile b/test/msvc/pem_decode_from_bytes/Jamfile new file mode 100644 index 00000000..828c581b --- /dev/null +++ b/test/msvc/pem_decode_from_bytes/Jamfile @@ -0,0 +1,9 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail pem_decode_from_bytes : app.cpp : /webcpp/crypto//crypto : native ; diff --git a/test/msvc/pem_decode_from_bytes/app.cpp b/test/msvc/pem_decode_from_bytes/app.cpp new file mode 100644 index 00000000..cf9148f6 --- /dev/null +++ b/test/msvc/pem_decode_from_bytes/app.cpp @@ -0,0 +1,23 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A PEM decoded from bytes does not compile on MSVC. The text is checked on clang, in +// test/messages/pem_decode_from_bytes. +#include "../../support/formats_toy.hpp" + +#include + +#include +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + std::array const bytes{}; + auto const decoded = crypto::decode( + crypto::formats::pem(crypto::formats::spki), std::span(bytes)); + return decoded ? 0 : 1; +} diff --git a/test/msvc/refusal_reason_toy/Jamfile b/test/msvc/refusal_reason_toy/Jamfile new file mode 100644 index 00000000..38798bfd --- /dev/null +++ b/test/msvc/refusal_reason_toy/Jamfile @@ -0,0 +1,9 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail refusal_reason_toy : app.cpp : /webcpp/crypto//crypto : native ; diff --git a/test/msvc/refusal_reason_toy/app.cpp b/test/msvc/refusal_reason_toy/app.cpp new file mode 100644 index 00000000..d8f9a842 --- /dev/null +++ b/test/msvc/refusal_reason_toy/app.cpp @@ -0,0 +1,17 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The toy signature encoded in der does not compile on MSVC. The text is checked on clang, in +// test/messages/refusal_reason_toy. +#include "../../support/formats_toy.hpp" + +#include + +int main() { + namespace crypto = webcpp::crypto; + auto const encoded = crypto::encode(crypto::formats::der, crypto::test::toy_signature{}); + return encoded ? 0 : 1; +} diff --git a/test/support/formats_toy.hpp b/test/support/formats_toy.hpp index fa4e80ec..2b470cbe 100644 --- a/test/support/formats_toy.hpp +++ b/test/support/formats_toy.hpp @@ -7,10 +7,12 @@ // A toy value type of the tests' own, on which is proven before any // curve registers into it (design D1 to D3, D11, R17 to R25, R37): a public key of 8 bytes, // toy_key; a key pair of 8 secret bytes, move-only and wiped, toy_keypair; a signature of 4 bytes, -// toy_signature. Each borrows Ed25519's curve id, so that crypto's check treats it as a type of -// crypto's, and so that a translation unit that defines WEBCPP_TEST_CRYPTO_TOY_FORMATS_UNDECLARED -// before including this header, which then leaves out the part that declares the toy's formats, -// sees crypto's sentence for a formats header not included. +// toy_signature; a point of 8 bytes, toy_point, whose raw(xonly), its first 4 bytes, encodes and +// does not decode into it (decode_refusal_reason_v), while toy_signature has no DER for a reason of +// both directions (refusal_reason_v). Each borrows Ed25519's curve id, so that crypto's check +// treats it as a type of crypto's, and so that a translation unit that defines +// WEBCPP_TEST_CRYPTO_TOY_FORMATS_UNDECLARED before including this header, which then leaves out the +// part that declares the toy's formats, sees crypto's sentence for a formats header not included. // // The formats part: toy_key has raw (its 8 bytes), spki (the prefix 30 0a 30 00, then the 8 bytes) // and pem(spki); toy_keypair has raw (its 8 secret bytes), pkcs8 (the prefix 30 0a 02 00, then the @@ -169,6 +171,33 @@ class toy_signature { std::array bytes_{}; }; +/** + * A public key of 8 bytes with an x-only form, its first 4 bytes, which encodes and does not decode + * into this type: the shape of secp256k1's `raw(xonly)` (design D4, the refusal of F14's + * direction). + */ +class toy_point { +public: + /** Its size, in bytes. */ + static constexpr std::size_t size = 8; + + /** A point of 8 zero bytes. */ + toy_point() = default; + + /** The point of `point_bytes`. */ + explicit toy_point(std::array const& point_bytes) noexcept + : bytes_(point_bytes) {} + + /** Its bytes. */ + [[nodiscard]] std::array const& bytes() const noexcept { return bytes_; } + + /** Whether two points hold the same bytes. */ + friend bool operator==(toy_point const&, toy_point const&) = default; + +private: + std::array bytes_{}; +}; + } // namespace webcpp::crypto::test namespace webcpp::crypto::detail { @@ -185,6 +214,10 @@ inline constexpr curve_id curve_of_v = curve_id::ed25519; template <> inline constexpr curve_id curve_of_v = curve_id::ed25519; +/** The toy point borrows Ed25519's curve id. */ +template <> +inline constexpr curve_id curve_of_v = curve_id::ed25519; + } // namespace webcpp::crypto::detail #ifndef WEBCPP_TEST_CRYPTO_TOY_FORMATS_UNDECLARED @@ -259,6 +292,13 @@ inline codecs::result write_toy(std::span prefi return total; } +/** + * Where the toy key pair's pkcs8 decode last read its input: the DER buffer of the in-place PEM + * decode, which a test finds again in secure's wipe record. + */ +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the test's record +inline std::uint8_t const* toy_pkcs8_decoded_from = nullptr; + /** Whether `input` is `prefix` followed by `body_size` bytes. */ inline bool toy_layout(std::span input, std::span prefix, std::size_t body_size) noexcept { @@ -292,6 +332,31 @@ struct formats_of { using type = format_list>; }; +/** The toy point has raw, and raw(xonly) to encode only. */ +template <> +struct formats_of { + /** Its formats. */ + using type = format_list>; +}; + +/** The toy point's raw takes its default form and the x-only one. */ +template <> +struct forms_of, test::toy_point> { + /** Its forms. */ + using type = form_list; +}; + +/** An x-only point does not decode into the toy point: the reason of decoding alone. */ +template <> +inline constexpr refusal_reason + decode_refusal_reason_v, test::toy_point> = + refusal_reason::xonly_into_public_key; + +/** The toy signature has no DER form, as Ed25519's: the reason of both directions. */ +template <> +inline constexpr refusal_reason refusal_reason_v = + refusal_reason::no_der_ed25519_bip340; + /** The toy key pair's pkcs8 decodes a "version 2" longer than its encoding. */ template <> inline constexpr bool bounds_may_differ_v = true; @@ -428,6 +493,7 @@ struct value_codec { crypto::formats::pkcs8_t const& /*format*/, std::span input_bytes) noexcept { secure::timing_guard const timing_scope{true}; + crypto::test::toy_pkcs8_decoded_from = input_bytes.data(); constexpr std::size_t secret_offset = crypto::test::toy_pkcs8_prefix.size(); constexpr std::size_t secret_size = crypto::test::toy_keypair::size; if (crypto::test::toy_layout(input_bytes, crypto::test::toy_pkcs8_prefix, secret_size)) { @@ -451,6 +517,55 @@ struct value_codec { } }; +/** The toy point's raw: its 8 bytes. */ +template <> +struct value_codec, crypto::test::toy_point> { + static constexpr output_kind output = output_kind::bytes; + static constexpr std::size_t max_encoded_size = 8; + static constexpr std::size_t max_decode_input_size = 8; + + static std::size_t encoded_size(crypto::formats::raw_t<> const& /*format*/, + crypto::test::toy_point const& /*point*/) noexcept { + return 8; + } + + static result encode(crypto::formats::raw_t<> const& /*format*/, + crypto::test::toy_point const& point, + std::span output_bytes) noexcept { + return crypto::test::write_toy({}, point.bytes(), output_bytes); + } + + static result decode( + crypto::formats::raw_t<> const& /*format*/, + std::span input_bytes) noexcept { + if (!crypto::test::toy_layout(input_bytes, {}, crypto::test::toy_point::size)) { + return crypto::error::invalid_encoding; + } + std::array point_bytes{}; + std::ranges::copy(input_bytes, point_bytes.begin()); + return crypto::test::toy_point{point_bytes}; + } +}; + +/** The toy point's raw(xonly): its first 4 bytes, to encode only. */ +template <> +struct value_codec, crypto::test::toy_point> { + static constexpr output_kind output = output_kind::bytes; + static constexpr std::size_t max_encoded_size = 4; + + static std::size_t encoded_size( + crypto::formats::raw_t const& /*format*/, + crypto::test::toy_point const& /*point*/) noexcept { + return 4; + } + + static result encode( + crypto::formats::raw_t const& /*format*/, + crypto::test::toy_point const& point, std::span output_bytes) noexcept { + return crypto::test::write_toy({}, std::span(point.bytes()).first<4>(), output_bytes); + } +}; + /** The toy signature's raw: its 4 bytes. */ template <> struct value_codec, crypto::test::toy_signature> { @@ -548,6 +663,10 @@ static_assert(webcpp::crypto::detail::check_bounds()); static_assert(webcpp::crypto::detail::check_bounds, webcpp::crypto::test::toy_signature>()); +static_assert(webcpp::crypto::detail::known_formats_v< + webcpp::crypto::detail::formats_of_t>); +static_assert(webcpp::crypto::detail::check_bounds, + webcpp::crypto::test::toy_point>()); #endif // WEBCPP_TEST_CRYPTO_TOY_FORMATS_UNDECLARED diff --git a/test/user_globals_test.cpp b/test/user_globals_test.cpp index a6ea271e..455898f6 100644 --- a/test/user_globals_test.cpp +++ b/test/user_globals_test.cpp @@ -29,6 +29,13 @@ // `size` (ed25519's `public_key::size`) and `order` (`p_curve_traits`) are static data members // too, listed only because they were also locals. // +// The formats headers, formats.hpp and each curves//formats.hpp, are left out, and so is +// every header that includes one: they include webcpp::codecs' headers, whose templates' locals +// (`value`, `code`, `label`) are names of this list, and MSVC instantiates a template at the end +// of the translation unit, after the globals, whatever the order of the includes. codecs' locals +// are not renamed, and the owner rejected the two-word naming rule for new code; the formats +// headers' own code is checked by the formats tests. +// // 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. From c74dbdfe4f8ead3b50a709f2df58d8ec3c4d8f78 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 1 Dec 2026 02:03:18 -0300 Subject: [PATCH 23/81] crypto: PEM fix round lint fix --- test/formats_pem_test.cpp | 72 ++++++++++++++++++++++----------------- 1 file changed, 40 insertions(+), 32 deletions(-) diff --git a/test/formats_pem_test.cpp b/test/formats_pem_test.cpp index 1bd5042f..2d59cc77 100644 --- a/test/formats_pem_test.cpp +++ b/test/formats_pem_test.cpp @@ -335,6 +335,45 @@ void guard_for_a_private_format() { }); } +/** Whether two results hold equal values, or the same error. */ +template +void same_results(codecs::result const& expected, codecs::result const& actual, + Equal equal) { + BOOST_TEST_EQ(actual.has_value(), expected.has_value()); + if (expected && actual) { + BOOST_TEST(equal(*expected, *actual)); + } else if (!expected && !actual) { + BOOST_TEST(actual.error() == expected.error()); + } +} + +/** + * crypto::decode of `text`, as a std::string, a span of characters and a vector of them, and + * codecs::decode of it give the same value, or the same error, for both PEM pairs. + */ +void same_as_codecs_on(std::string const& text) { + auto const same_key = [](toy_key const& first, toy_key const& second) { + return first == second; + }; + auto const same_key_pair = [](toy_keypair const& first, toy_keypair const& second) { + return std::ranges::equal(first.secret(), second.secret()); + }; + std::span const span_text(text.data(), text.size()); + std::vector const characters(text.begin(), text.end()); + auto const in_place = crypto::decode(formats::pem(formats::spki), text); + same_results(in_place, codecs::decode(formats::pem(formats::spki), text), same_key); + same_results(in_place, crypto::decode(formats::pem(formats::spki), span_text), + same_key); + same_results(in_place, crypto::decode(formats::pem(formats::spki), characters), + same_key); + auto const private_in_place = crypto::decode(formats::pem(formats::pkcs8), text); + same_results(private_in_place, codecs::decode(formats::pem(formats::pkcs8), text), + same_key_pair); + same_results(private_in_place, + crypto::decode(formats::pem(formats::pkcs8), characters), + same_key_pair); +} + /** crypto::decode and codecs::decode give the same value, or the same error, on every text. */ void same_as_codecs() { std::string const crlf = with_crlf(key_pem); @@ -366,38 +405,7 @@ void same_as_codecs() { "-----BEGIN PUBLIC KEY-----\n", }; for (std::string const& text : texts) { - auto const in_place = crypto::decode(formats::pem(formats::spki), text); - auto const through_codecs = codecs::decode(formats::pem(formats::spki), text); - BOOST_TEST_EQ(in_place.has_value(), through_codecs.has_value()); - if (in_place && through_codecs) { - BOOST_TEST(*in_place == *through_codecs); - } else if (!in_place && !through_codecs) { - BOOST_TEST(in_place.error() == through_codecs.error()); - } - std::span const span_text(text.data(), text.size()); - std::vector const characters(text.begin(), text.end()); - auto const from_span = crypto::decode(formats::pem(formats::spki), span_text); - auto const from_vector = crypto::decode(formats::pem(formats::spki), characters); - BOOST_TEST_EQ(from_span.has_value(), in_place.has_value()); - BOOST_TEST_EQ(from_vector.has_value(), in_place.has_value()); - if (in_place && from_span && from_vector) { - BOOST_TEST(*from_span == *in_place); - BOOST_TEST(*from_vector == *in_place); - } else if (!in_place && !from_span && !from_vector) { - BOOST_TEST(from_span.error() == in_place.error()); - BOOST_TEST(from_vector.error() == in_place.error()); - } - auto const private_in_place = - crypto::decode(formats::pem(formats::pkcs8), text); - auto const private_through_codecs = - codecs::decode(formats::pem(formats::pkcs8), text); - BOOST_TEST_EQ(private_in_place.has_value(), private_through_codecs.has_value()); - if (private_in_place && private_through_codecs) { - BOOST_TEST( - std::ranges::equal(private_in_place->secret(), private_through_codecs->secret())); - } else if (!private_in_place && !private_through_codecs) { - BOOST_TEST(private_in_place.error() == private_through_codecs.error()); - } + same_as_codecs_on(text); } } From ecdeff7aa0f5f92423894bf5741b53dfdc1269b0 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 1 Dec 2026 02:24:11 -0300 Subject: [PATCH 24/81] crypto: the PEM test's past-the-bound wipe counted, not found by another call's address; forms_without_default's fix needs the default form listed, not first --- doc/generated/messages.adoc | 4 ++-- doc/tables/crypto.json | 2 +- test/formats_pem_test.cpp | 9 ++++----- 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/doc/generated/messages.adoc b/doc/generated/messages.adoc index a0b79059..ae03d4b6 100644 --- a/doc/generated/messages.adoc +++ b/doc/generated/messages.adoc @@ -399,7 +399,7 @@ The fix: Include `++`, or the curve's `+`; DER bytes decode with `crypto::formats::spki` or `crypto::formats::pkcs8` themselves.", - "forms_without_default": "List `crypto::formats::default_form_t` first in each `detail::forms_of` specialization, with the other point forms the type accepts.", + "forms_without_default": "List `crypto::formats::default_form_t` in each `detail::forms_of` specialization, with the other point forms the type accepts.", "recover_ecdsa_signature": "Give `recover` a `curves::secp256k1::recoverable_signature`, which `sign(crypto::signing_schemes::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.", diff --git a/test/formats_pem_test.cpp b/test/formats_pem_test.cpp index 2d59cc77..69146a07 100644 --- a/test/formats_pem_test.cpp +++ b/test/formats_pem_test.cpp @@ -262,12 +262,11 @@ void buffer_wiped() { // The buffer is found by its address, which the toy's pkcs8 decode records as its input. webcpp::crypto::test::toy_pkcs8_decoded_from = nullptr; webcpp::test::clear_wipes(); - void const* buffer = nullptr; { auto const decoded = crypto::decode(formats::pem(formats::pkcs8), encoded->view()); BOOST_TEST(decoded.has_value()); - buffer = webcpp::crypto::test::toy_pkcs8_decoded_from; + void const* const buffer = webcpp::crypto::test::toy_pkcs8_decoded_from; BOOST_TEST(buffer != nullptr); BOOST_TEST(webcpp::test::wiped(buffer, buffer_size)); std::vector const sizes = webcpp::test::wiped_sizes(); @@ -284,14 +283,14 @@ void buffer_wiped() { } { // A payload past the decode bound (Review Focus 5 for a secret): the armor refuses to - // write it, and the buffer, whose address the same call made before gave, is wiped all - // the same. + // write it, so the toy's decode never sees the buffer and records no address; one wipe of + // the buffer's size is all the record shows (another call's address would not be this + // one's under other inlining or AddressSanitizer's fake stacks). std::array longer{}; std::ranges::copy(key_pair_pkcs8_v2, longer.begin()); auto const refused = crypto::decode(formats::pem(formats::pkcs8), armored("PRIVATE KEY", longer)); BOOST_TEST(refused.error() == crypto::error::invalid_encoding); - BOOST_TEST(webcpp::test::wiped(buffer, buffer_size)); std::vector const sizes = webcpp::test::wiped_sizes(); BOOST_TEST(std::ranges::count(sizes, buffer_size) == 1); } From c17b5f833556c3ad9e2e0f4719819cf31500e387 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 1 Dec 2026 02:58:45 -0300 Subject: [PATCH 25/81] crypto: the fuzz lane on codecs' model, libFuzzer on Linux and a replay on every lane --- .gitattributes | 2 + doc/testing.adoc | 18 +- test/Jamfile | 5 + test/constant_time/Jamfile | 14 +- test/constant_time/dudect.hpp | 33 +++ test/constant_time/dudect_harness_test.cpp | 30 ++- test/constant_time/dudect_test.cpp | 76 +++++- test/constant_time/paths.hpp | 65 ++++- test/fuzz/Jamfile | 86 +++++++ test/fuzz/base58_with_checksum_fuzz.cpp | 150 +++++++++++ .../base58_with_checksum/key_io_valid_00 | 1 + .../base58_with_checksum/key_io_valid_01 | 1 + .../base58_with_checksum/key_io_valid_02 | 1 + .../base58_with_checksum/key_io_valid_03 | 1 + .../base58_with_checksum/key_io_valid_04 | 1 + .../base58_with_checksum/key_io_valid_05 | 1 + .../base58_with_checksum/key_io_valid_06 | 1 + .../base58_with_checksum/key_io_valid_07 | 1 + .../base58_with_checksum/key_io_valid_08 | 1 + .../base58_with_checksum/key_io_valid_09 | 1 + .../base58_with_checksum/key_io_valid_10 | 1 + .../base58_with_checksum/key_io_valid_11 | 1 + .../base58_with_checksum/key_io_valid_12 | 1 + .../base58_with_checksum/key_io_valid_13 | 1 + .../base58_with_checksum/key_io_valid_14 | 1 + .../base58_with_checksum/key_io_valid_15 | 1 + .../base58_with_checksum/key_io_valid_16 | 1 + .../base58_with_checksum/key_io_valid_17 | 1 + .../base58_with_checksum/key_io_valid_18 | 1 + .../base58_with_checksum/key_io_valid_19 | 1 + .../base58_with_checksum/key_io_valid_20 | 1 + .../base58_with_checksum/key_io_valid_21 | 1 + .../base58_with_checksum/key_io_valid_22 | 1 + .../base58_with_checksum/key_io_valid_23 | 1 + .../base58_with_checksum/key_io_valid_24 | 1 + .../base58_with_checksum/key_io_valid_25 | 1 + .../base58_with_checksum/key_io_valid_26 | 1 + .../base58_with_checksum/key_io_valid_27 | 1 + .../base58_with_checksum/key_io_valid_28 | 1 + .../base58_with_checksum/key_io_valid_29 | 1 + .../base58_with_checksum/key_io_valid_30 | 1 + .../base58_with_checksum/key_io_valid_31 | 1 + .../base58_with_checksum/key_io_valid_32 | 1 + .../base58_with_checksum/key_io_valid_33 | 1 + .../base58_with_checksum/key_io_valid_34 | 1 + .../base58_with_checksum/key_io_valid_35 | 1 + .../base58_with_checksum/key_io_valid_36 | 1 + .../base58_with_checksum/key_io_valid_37 | 1 + test/fuzz/corpus/toy_pem_spki/begin_alone | 1 + test/fuzz/corpus/toy_pem_spki/certificate | 3 + test/fuzz/corpus/toy_pem_spki/empty | 0 test/fuzz/corpus/toy_pem_spki/empty_armor | 2 + test/fuzz/corpus/toy_pem_spki/explained | 4 + test/fuzz/corpus/toy_pem_spki/key_pem | 3 + test/fuzz/corpus/toy_pem_spki/key_pem_crlf | 3 + .../toy_pem_spki/key_pem_no_final_line_feed | 3 + test/fuzz/corpus/toy_pem_spki/private | 3 + .../fuzz/corpus/toy_pem_spki/private_too_long | 3 + .../corpus/toy_pem_spki/private_version_2 | 3 + test/fuzz/corpus/toy_pem_spki/rsa | 9 + test/fuzz/fuzz.mjs | 49 ++++ test/fuzz/fuzz_wipes.cpp | 35 +++ test/fuzz/libfuzzer_hooks.cpp | 52 ++++ test/fuzz/package-lock.json | 10 + test/fuzz/package.json | 1 + test/fuzz/target.hpp | 236 ++++++++++++++++++ test/fuzz/toy_pem_spki_fuzz.cpp | 29 +++ test/support/fuzz_replay_main.cpp | 193 ++++++++++++++ 68 files changed, 1150 insertions(+), 9 deletions(-) create mode 100644 test/fuzz/Jamfile create mode 100644 test/fuzz/base58_with_checksum_fuzz.cpp create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_00 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_01 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_02 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_03 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_04 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_05 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_06 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_07 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_08 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_09 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_10 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_11 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_12 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_13 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_14 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_15 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_16 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_17 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_18 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_19 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_20 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_21 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_22 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_23 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_24 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_25 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_26 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_27 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_28 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_29 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_30 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_31 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_32 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_33 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_34 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_35 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_36 create mode 100644 test/fuzz/corpus/base58_with_checksum/key_io_valid_37 create mode 100644 test/fuzz/corpus/toy_pem_spki/begin_alone create mode 100644 test/fuzz/corpus/toy_pem_spki/certificate create mode 100644 test/fuzz/corpus/toy_pem_spki/empty create mode 100644 test/fuzz/corpus/toy_pem_spki/empty_armor create mode 100644 test/fuzz/corpus/toy_pem_spki/explained create mode 100644 test/fuzz/corpus/toy_pem_spki/key_pem create mode 100644 test/fuzz/corpus/toy_pem_spki/key_pem_crlf create mode 100644 test/fuzz/corpus/toy_pem_spki/key_pem_no_final_line_feed create mode 100644 test/fuzz/corpus/toy_pem_spki/private create mode 100644 test/fuzz/corpus/toy_pem_spki/private_too_long create mode 100644 test/fuzz/corpus/toy_pem_spki/private_version_2 create mode 100644 test/fuzz/corpus/toy_pem_spki/rsa create mode 100644 test/fuzz/fuzz.mjs create mode 100644 test/fuzz/fuzz_wipes.cpp create mode 100644 test/fuzz/libfuzzer_hooks.cpp create mode 100644 test/fuzz/package-lock.json create mode 100644 test/fuzz/package.json create mode 100644 test/fuzz/target.hpp create mode 100644 test/fuzz/toy_pem_spki_fuzz.cpp create mode 100644 test/support/fuzz_replay_main.cpp diff --git a/.gitattributes b/.gitattributes index cc23192c..cf5eb6ea 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,4 @@ * text=auto eol=lf *.bat text eol=crlf +# The fuzz corpora are inputs byte for byte: no line ending of theirs is converted. +test/fuzz/corpus/** -text diff --git a/doc/testing.adoc b/doc/testing.adoc index 8a26819a..d0354578 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -49,7 +49,23 @@ macOS, and dudect's under wasmtime on wasip2. On a runner GitHub hosts, each two fresh processes, failing when two of the three values exceed 10 (<> says why); the native lane's command with `libs/crypto/test/constant_time//constant-time` in -place of the two directories. +place of the two directories. Its paths include webcpp::hash's Base58Check, the +secret encode and decode of a WIF key's payload, which hash leaves to crypto's +lane. + +The own lane `fuzz` runs libFuzzer natively on Linux, with clang, +AddressSanitizer and UndefinedBehaviorSanitizer, for 60 seconds a target from a +copy of its corpus, with a fixed seed: one target per decoder of the key +formats (<>), the tests' own toy type in `pem(spki)` among +them, and one for webcpp::hash's Base58Check, which hash leaves to crypto's +lane. Each target checks that nothing crashes, that its decode and the encode +of what decoded allocate nothing, that what decodes encodes back to the input +(a PEM to its lines ended by line feeds, with a final one), and, for a secret +format, that every buffer of crypto's is wiped. Each target is also replayed on +every lane, as an ordinary test with exceptions on and off, over its corpus and +4096 inputs drawn from a fixed stream (`_replay`); a finding prints the +input in base64, which the replay takes into its corpus. The native lane's +command with `libs/crypto/test/fuzz//fuzz` in place of the two directories. What the tests check: diff --git a/test/Jamfile b/test/Jamfile index bc18430a..5db6a5d1 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -555,6 +555,11 @@ build-project c_suites ; # constant-time. build-project constant_time ; +# The own lane fuzz: libFuzzer on Linux over every decoder of crypto's formats +# and over hash's Base58Check, each target replayed here on every lane, over its +# corpus and a fixed stream. +build-project fuzz ; + # A backend named and not called adds no byte (webcpp.same-program). build-project unused ; diff --git a/test/constant_time/Jamfile b/test/constant_time/Jamfile index 28a777c0..fd611a1e 100644 --- a/test/constant_time/Jamfile +++ b/test/constant_time/Jamfile @@ -21,7 +21,9 @@ # agree_point), the secret key's tweaks, PKCS#8, ElligatorSwift, MuSig2's nonce # and partial signature, and silent payments' outputs, label and scan, and # BearSSL's P-256: the key pair's making, ECDSA with its low-S normalisation and -# check, ECDH's x and PKCS#8's decoding. Both checkers run the same paths, +# check, ECDH's x and PKCS#8's decoding, and hash's Base58Check, the secret +# encode and decode of a WIF key's payload (hash's design D4: hash has no +# constant-time lane of its own). Both checkers run the same paths, # paths.hpp, memcheck OpenSSL's besides. BearSSL's own branches on a verdict in # its ECDSA signing are listed in bearssl_verdicts.supp, as libsodium's are in # sodium_verdicts.supp. @@ -73,7 +75,8 @@ rule clang-on-linux ( properties * ) # Keccak-256 hashes the public message Ethereum's recoverable ECDSA signs. CTGRIND = /third_party//bearssl /webcpp/crypto//openssl /third_party//ctaes /third_party//sodium - secp256k1_ctgrind /third_party//xkcp release + secp256k1_ctgrind /third_party//xkcp + /webcpp/hash//base58_with_checksum release on @linux-only WEBCPP_SECURE_CT_VALGRIND 300 ; @@ -203,6 +206,7 @@ explicit secp256k1_msan ; # webcpp::hash's keccak_256 initialises before XKCP writes them. MSAN = bearssl_msan ctaes_msan sodium_msan secp256k1_msan /third_party//xkcp + /webcpp/hash//base58_with_checksum WEBCPP_CRYPTO_DETAIL_BEARSSL_PORTABLE WEBCPP_SECURE_CT_MSAN $(MSAN_FLAGS) -fsanitize=memory release on @clang-on-linux ; @@ -237,7 +241,8 @@ webcpp.run secp256k1_ctime_msan : $(SECP256K1_CTIME) off $(MSAN_FLAGS) -fsanitize=memory release on @clang-on-linux : native ; -# dudect's statistics on BearSSL, ctaes and constant_time_equal, on libsodium's +# dudect's statistics on BearSSL, ctaes, constant_time_equal and hash's +# Base58Check's secret decode of a WIF key, on libsodium's # X25519 and Ed25519, and on libsecp256k1's agree, natively and under wasmtime. # The programs never set DIT: they measure what a program gets, the library's # own guard (webcpp::secure::timing_guard), which sets DIT in each call on @@ -258,7 +263,8 @@ if [ os.environ RUNNER_ENVIRONMENT ] = github-hosted DUDECT += WEBCPP_TEST_DUDECT_UNJUDGED ; } webcpp.run dudect_bearssl : dudect_test.cpp - : /third_party//bearssl /third_party//ctaes $(DUDECT) + : /third_party//bearssl /third_party//ctaes + /webcpp/hash//base58_with_checksum $(DUDECT) : native wasip2 ; # On wasip2, X25519's agreement is measured and printed but not judged: an # open finding, whose numbers doc/tables/crypto.json holds (the X25519 diff --git a/test/constant_time/dudect.hpp b/test/constant_time/dudect.hpp index 48282fd2..36f66f22 100644 --- a/test/constant_time/dudect.hpp +++ b/test/constant_time/dudect.hpp @@ -257,6 +257,39 @@ void choose(int which, Generator& generator, std::array cons } } +/** + * Writes `first` into `input` for class 0 and `second` for class 1, by the instructions of + * `choose`: the same draws, then both inputs read through a volatile and blended through the + * same volatile mask, so that what the preparation does is the same for both classes; the two + * classes of a case that compares two fixed inputs of one length (two WIF keys' texts). + * @param which The class, 0 or 1. + * @param generator The seeded generator. + * @param first The class 0 input. + * @param second The class 1 input. + * @param input Where the input of the class is written. + */ +template +void choose_between(int which, Generator& generator, std::array const& first, + std::array const& second, + std::array& input) { + std::array drawn{}; + for (auto& byte : drawn) { + byte = static_cast(generator()); + } + // Read through a volatile, as choose reads its fixed input, so that the compiler blends + // as every case does. + for (std::size_t index = 0; index < Size; ++index) { + drawn[index] = static_cast(second[index]); + } + std::uint8_t volatile const chosen = which == 0 ? 0xFFU : 0x00U; + unsigned const keep = chosen; + unsigned const drop = keep ^ 0xFFU; + for (std::size_t index = 0; index < Size; ++index) { + input[index] = static_cast((unsigned{first[index]} & keep) | + (unsigned{drawn[index]} & drop)); + } +} + /** * The largest |t| of `count` measurements of `run`, each after `prepare(class, generator)` * with a class drawn at random from the seeded generator, prepare unmeasured; each clock read diff --git a/test/constant_time/dudect_harness_test.cpp b/test/constant_time/dudect_harness_test.cpp index f2897987..330ac976 100644 --- a/test/constant_time/dudect_harness_test.cpp +++ b/test/constant_time/dudect_harness_test.cpp @@ -6,8 +6,8 @@ // dudect.hpp's statistics, its class-blind preparation, its argument parser and its lines, on // synthetic data and without timing anything: the largest |t| with its cropping and the classes' -// counts and means there, the A/A control's preparation, `--case`, and the exact text of a case -// line, its evidence and its addresses, which the CI's judge reads. +// counts and means there, the A/A control's preparation and that of two fixed inputs, `--case`, and +// the exact text of a case line, its evidence and its addresses, which the CI's judge reads. #include "dudect.hpp" @@ -99,6 +99,31 @@ void choose_control() { BOOST_TEST(input != fixed); } +/** + * choose_between writes the first input for class 0 and the second for class 1, after the draws + * choose makes. + */ +void choose_between() { + std::array first{}; + std::array second{}; + for (std::size_t i = 0; i < first.size(); ++i) { + first[i] = static_cast(0xA0U + i); + second[i] = static_cast(0x30U + i); + } + for (int which = 0; which < 2; ++which) { + // NOLINTNEXTLINE(bugprone-random-generator-seed,cert-msc32-c,cert-msc51-cpp): reproducible + std::mt19937_64 between(7); + // NOLINTNEXTLINE(bugprone-random-generator-seed,cert-msc32-c,cert-msc51-cpp): reproducible + std::mt19937_64 plain(7); + std::array input{}; + test::choose_between(which, between, first, second, input); + BOOST_TEST(input == (which == 0 ? first : second)); + std::array ignored{}; + test::choose(which, plain, first, ignored); + BOOST_TEST_EQ(between(), plain()); + } +} + /** `--case` selects one case; no argument selects every one; an unknown name none. */ void select_case() { std::string program = "dudect_x"; @@ -221,6 +246,7 @@ void report_case_format() { int main() { largest_t_whole_set(); choose_control(); + choose_between(); select_case(); printed_boundary(); cpuinfo(); diff --git a/test/constant_time/dudect_test.cpp b/test/constant_time/dudect_test.cpp index 6ebe42ac..bd308569 100644 --- a/test/constant_time/dudect_test.cpp +++ b/test/constant_time/dudect_test.cpp @@ -12,7 +12,11 @@ // unmeasured; natively and under wasmtime, where the engine's compiler decides whether BearSSL's // 64-bit multiplication stays constant time. ChaCha20-Poly1305's open is measured once more as the // program's A/A control (chacha_open_aa), both classes the same nearly right tag, prepared by -// the same instructions. `--case ` measures one case alone. +// the same instructions. hash's Base58Check's secret decode of a WIF key (case base58_decode, +// hash's design D4) is measured against its text: two fixed texts of one length, two compressed +// WIF keys of Bitcoin Core's key_io_valid.json, decoded into a codecs::secret_bytes, codecs' +// constant-time conversion, with its A/A control (base58_decode_aa); on wasip2 the decode is +// printed and not judged, an open finding. `--case ` measures one case alone. #include "dudect.hpp" @@ -23,6 +27,7 @@ #include #include #include +#include #include #include @@ -31,6 +36,7 @@ #include #include #include +#include #include namespace { @@ -172,6 +178,70 @@ bool measure_p256(test::case_results& results, test::case_selection const& selec return true; } +/** + * Times hash's Base58Check's secret decode of a WIF key's text into a codecs::secret_bytes (case + * base58_decode), the two classes two fixed texts of one length, both valid: two compressed WIF + * keys of Bitcoin Core's key_io_valid.json on the main chain, whose payloads are 34 bytes; and its + * A/A control (base58_decode_aa), both classes the first text, prepared by the same instructions. + * @param results Where each case measured is recorded. + * @param selection The cases to measure. + */ +void measure_base58(test::case_results& results, test::case_selection const& selection) { + bool const decode = selection.runs("base58_decode"); + bool const control = selection.runs("base58_decode_aa"); + if (!decode && !control) { + return; + } + namespace codecs = webcpp::codecs; + // A decode takes under 5 microseconds natively and under wasmtime (a release build on an + // Apple M5 Max under load, 2026-12-01): the program's 2,000,000 measurements take about ten + // seconds natively and twenty under wasmtime. + constexpr std::string_view first_key = "L5nJeqKmpHp4P7F8ZYyjwc5a7P4d8EabuGAzfGJk7yC1BJyzNaEd"; + constexpr std::string_view second_key = "KwuVvu6hsuEMHrfFWJQV64tRrWX3QzqHH18JuAHYqYV6dqBvNKxd"; + static_assert(first_key.size() == second_key.size()); + std::array first{}; + std::array second{}; + std::ranges::copy(first_key, first.begin()); + std::ranges::copy(second_key, second.begin()); + std::array text{}; + auto const measure_decode = [&](bool judged_case, + std::array const& other) { + return test::measure_case( + judged_case, count, + [&](int which, auto& generator) { + test::choose_between(which, generator, first, other, text); + }, + [&] { + static_cast(codecs::decode>( + webcpp::hash::formats::base58_with_checksum, + std::string_view{reinterpret_cast(text.data()), text.size()})); + }); + }; +#ifdef __wasip2__ + // Under wasmtime the decode is an open finding, measured and printed but left out of the + // verdict on wasip2, as X25519's agreement is (dudect_sodium_test.cpp): |t| 15 to 18 there on + // an Apple M5 Max (2026-12-01), class 0 about 1.5 ns slower in 5 us, where its A/A control + // reads below 3 and the decode below 3 natively, where secure's guard sets DIT; the public + // decode of the same texts reads 200 to 340, the checksum alone (hash's double_sha256) below 2 + // and base58's secret decode with no checksum 8 to 10. Its cause is codecs' secret + // conversion without DIT, which the WebAssembly cannot set, X25519's measured cause, not + // measured here. Another WASI target is judged; the A/A control is judged everywhere. + bool const decode_judged = false; + char const* const decode_note = " (wasip2: printed, not judged; an open finding)"; +#else + bool const decode_judged = true; + char const* const decode_note = ""; +#endif + if (decode) { + results.record("base58_decode", "base58 decode", measure_decode(decode_judged, second), + decode_judged, {{"text", text.data()}}, decode_note); + } + if (control) { + results.record("base58_decode_aa", "base58 decode A/A", measure_decode(true, first), true, + {{"text", text.data()}}); + } +} + } // namespace // NOLINTNEXTLINE(misc-const-correctness): main's arguments have the type the standard gives them @@ -187,6 +257,8 @@ int main(int argc, char** argv) { "chacha_open_aa", "p256_sign", "p256_ecdh_x", + "base58_decode", + "base58_decode_aa", }); if (!selection) { return 2; @@ -238,6 +310,8 @@ int main(int argc, char** argv) { return 1; } + measure_base58(results, *selection); + results.print(); return test::verdict(results.passes()); } diff --git a/test/constant_time/paths.hpp b/test/constant_time/paths.hpp index 21d1ef3c..e8d8ce74 100644 --- a/test/constant_time/paths.hpp +++ b/test/constant_time/paths.hpp @@ -27,6 +27,7 @@ #ifndef WEBCPP_TEST_CRYPTO_CONSTANT_TIME_PATHS_HPP #define WEBCPP_TEST_CRYPTO_CONSTANT_TIME_PATHS_HPP +#include #include #include #include @@ -51,6 +52,7 @@ #include #include #include +#include #include #include #include @@ -65,6 +67,7 @@ #include #include #include +#include #include namespace webcpp::test::constant_time { @@ -938,6 +941,66 @@ int secp256k1_paths() { secp256k1_silent_payments(); } +/** + * hash's Base58Check, hash::formats::base58_with_checksum (hash's design D4: hash's constant-time + * lane is crypto's), as a WIF key is read and written: the secret encode of a 34-byte secret, the + * payload of a compressed WIF key (0x80, the key, 0x01); then the secret decode of its text, made + * secret, into a codecs::secret_bytes. codecs runs base58's constant-time conversion for a secret + * operation, and declassifies the checksum's verdict where it branches on it. Each output carries + * the mark where the checker's shadow follows a subtraction's carry (codecs' lookups reduce a + * secret through one), then, marked public, equals the plain value: the public encode's text, made + * before the mark, and the payload. + */ +template +int base58_with_checksum_path() { + namespace codecs = webcpp::codecs; + constexpr auto const& format = webcpp::hash::formats::base58_with_checksum; + secure::secret<34> payload; + std::ranges::fill(payload.writable(), std::uint8_t{0x42}); + payload.writable().front() = 0x80; + payload.writable().back() = 0x01; + std::array plain_payload{}; + std::ranges::copy(payload.bytes(), plain_payload.begin()); + auto const plain_text = codecs::encode(format, plain_payload); + if (!plain_text) { + return check(false, "Base58Check's public encode"); + } + auto const traced_and_equal = [](std::span output, + std::span expected, char const* what) { + int const untraced = + Checker::exact_subtraction ? check(carries_mark(output), what) : 0; + Checker::mark_public(output); + return untraced + check(std::ranges::equal(output, expected), what); + }; + auto const characters = [](std::string_view text) { + return std::span{reinterpret_cast(text.data()), + text.size()}; + }; + + Checker::mark_secret(payload.writable()); + auto const encoded = codecs::encode(format, payload); + if (!encoded) { + return check(false, "Base58Check's secret encode"); + } + int const failures = traced_and_equal( + characters(encoded->view()), characters(plain_text->view()), "Base58Check's secret encode"); + + // The text, a copy marked secret on its own, as a WIF key read from a file is. + std::array + text{}; + std::ranges::copy(plain_text->view(), text.begin()); + std::span const text_bytes = std::span{text}.first(plain_text->view().size()); + Checker::mark_secret(text_bytes); + auto const decoded = codecs::decode>( + format, + std::string_view{reinterpret_cast(text_bytes.data()), text_bytes.size()}); + if (!decoded) { + return failures + check(false, "Base58Check's secret decode"); + } + return failures + + traced_and_equal(decoded->view(), plain_payload, "Base58Check's secret decode"); +} + /** Every path above, on the checker: the number of failed checks. */ template int common_paths() { @@ -966,7 +1029,7 @@ int common_paths() { crypto::families::box_xchacha20poly1305, sodium>>( "box_xchacha20poly1305 on libsodium") + sodium_sealed_box() + sodium_kx() + secp256k1_paths() + - bearssl_p256_paths(); + bearssl_p256_paths() + base58_with_checksum_path(); } } // namespace webcpp::test::constant_time diff --git a/test/fuzz/Jamfile b/test/fuzz/Jamfile new file mode 100644 index 00000000..9a254ef7 --- /dev/null +++ b/test/fuzz/Jamfile @@ -0,0 +1,86 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +# Fuzzing (design R33, the spec's "Formats: every decoder is fuzzed"): the own +# lane fuzz, on webcpp::codecs' model (its test/fuzz/), one target per decoder, +# each _fuzz.cpp a libFuzzer target whose checks are target.hpp's: no +# crash, no heap, what decodes encodes back to the input (a PEM to its lines +# ended by line feeds), and, for a secret format, every buffer of crypto's +# wiped. The first targets are the tests' toy PEM and hash's Base58Check +# (hash's design D4: hash has no fuzz lane of its own); each curve's task adds +# one target per decoder, its corpus, its line below and its name to the lane. +project : requirements /webcpp/crypto//crypto ; + +import webcpp regex ; + +webcpp.targets native wasip2 wasip3 emscripten ; + +webcpp.original node ; + +# libFuzzer is clang's, and the lane runs it on Linux: elsewhere, and with +# GCC, the targets are not built. codecs' test/fuzz/Jamfile rule, copied. +rule clang-on-linux ( properties * ) +{ + if ! linux in $(properties) || ! clang in $(properties) + { + return no ; + } +} + +# libFuzzer with AddressSanitizer and UndefinedBehaviorSanitizer, which stops +# at its first report (it would otherwise print and go on, and libFuzzer exit +# 0). 240 s for the driver: 60 of fuzzing, the corpus's copy, the start and a +# crash's report. +FUZZ_FLAGS = -fsanitize=fuzzer,address,undefined -fno-sanitize-recover=all ; +FUZZ = $(FUZZ_FLAGS) $(FUZZ_FLAGS) release + on @clang-on-linux 240 ; + +# The corpora, one directory a target, one input a file, as is, with no end of +# line added (crypto's targets do not stream, so no input holds a split seed). +# Read by the replays at run time from the directory +# WEBCPP_TEST_CRYPTO_FUZZ_CORPUS names, with forward slashes and quoted whole +# as codecs' corpus is, so that a path with a space or a backslash survives; +# webcpp.data gives WASI the directory. +path-constant FUZZ_CORPUS : corpus ; +.corpus = [ regex.replace $(FUZZ_CORPUS) "\\\\" "/" ] ; + +# Each target is replayed on every lane, with exceptions on and off, over its +# corpus and 4096 inputs of a fixed xorshift stream: the assertions run +# everywhere with no fuzzing engine (support/fuzz_replay_main.cpp, which +# counts the heap through support/counting.hpp). libFuzzer runs it natively on +# Linux for 60 s from a copy of its corpus (fuzz.mjs), with the heap counted +# by the sanitizer's hooks (libfuzzer_hooks.cpp). Every program records +# secure's wipes (support/wipe_record.hpp, through fuzz_wipes.cpp), which a +# secret format's target reads. requirements go to the three programs. +rule crypto-fuzz ( name : requirements * ) +{ + local replay = $(name)_fuzz.cpp ../support/fuzz_replay_main.cpp fuzz_wipes.cpp ; + local inputs = [ glob corpus/$(name)/* ] ; + local data = "\"WEBCPP_TEST_CRYPTO_FUZZ_CORPUS=\\\"$(.corpus)/$(name)\\\"\"" + [ webcpp.data $(FUZZ_CORPUS)/$(name) ] $(inputs) + WEBCPP_SECURE_TEST_WIPE_RECORD ; + webcpp.run $(name)_replay : $(replay) : $(data) $(requirements) ; + webcpp.run $(name)_replay_no_exceptions : $(replay) + : $(data) $(requirements) off ; + webcpp.drive $(name)_fuzz : $(name)_fuzz.cpp libfuzzer_hooks.cpp fuzz_wipes.cpp + : $(FUZZ) $(requirements) WEBCPP_SECURE_TEST_WIPE_RECORD : fuzz.mjs + : --corpus $(FUZZ_CORPUS)/$(name) --seconds 60 : native ; +} + +# The tests' toy public key in pem(spki) (support/formats_toy.hpp): the texts +# of formats_pem_test.cpp, one a file: the key's PEM, with CRLF lines and +# without its final line feed, a certificate's label, explanatory text before +# BEGIN, an RSA key's PEM, whose payload passes the decode bound, an armor of +# no bytes, the toy key pair's PEM and its "version 2" and one byte longer, an +# empty text and a BEGIN line alone. +crypto-fuzz toy_pem_spki ; + +# hash's Base58Check, hash::formats::base58_with_checksum: the 22 addresses and +# 16 WIF keys of Bitcoin Core's key_io_valid.json, one a file, in the file's +# order (key_io_valid_00 to key_io_valid_37). +crypto-fuzz base58_with_checksum : /webcpp/hash//base58_with_checksum ; + +webcpp.lane fuzz : toy_pem_spki_fuzz base58_with_checksum_fuzz : native ; diff --git a/test/fuzz/base58_with_checksum_fuzz.cpp b/test/fuzz/base58_with_checksum_fuzz.cpp new file mode 100644 index 00000000..926d922d --- /dev/null +++ b/test/fuzz/base58_with_checksum_fuzz.cpp @@ -0,0 +1,150 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The fuzz target of hash's Base58Check, hash::formats::base58_with_checksum (hash's design D4: +// hash has no fuzz lane of its own, crypto's runs its target). Every input is a text decoded +// through codecs' buffer form into a stack buffer and into a codecs::secret_bytes<100>, the secret +// decode of a WIF key, with no heap: the two give the same bytes or the same error (a checksum +// that does not match, a text past the bound among them); what decodes encodes back to the same +// text, through the buffer form and as a secret into a stack buffer (a token of the target's own), +// with no heap. The input's first 100 bytes are +// also encoded with their checksum and their text checked alike, which must decode to them: the +// one way the fuzzer's inputs reach a valid checksum. + +#include "target.hpp" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +using format_type = webcpp::hash::formats::base58_with_checksum_t; +using webcpp::crypto::test::fuzz_allocations; +using webcpp::crypto::test::fuzz_detail::expect; + +/** The format. */ +constexpr format_type const& format = webcpp::hash::formats::base58_with_checksum; + +/** The payload of a text, at most the format's bound, as the buffer form writes it. */ +using payload_buffer = std::array; + +/** + A token of the target's own (codecs' "A token of the program's own"), which makes the encode + secret and writes its text into the caller's stack buffer: a secret encode of bytes whose size is + not known at compile time, with no heap. +*/ +class secret_into { +public: + /** The size of the text written. */ + using result_type = std::size_t; + /** A secret operation. */ + static constexpr bool secret = true; + /** The longest text. */ + static constexpr std::size_t capacity = format_type::maximum_characters; + + /** + The token over `text`. + + @param text Where the text is written. + */ + explicit secret_into(std::span text) noexcept : text_(text) {} + + /** + The room for exactly the text. + + @param size The text's size, at most `capacity`. + @return Its first character. + */ + char* prepare(std::size_t size) noexcept { + size_ = size; + return text_.data(); + } + + /** + The size of the text written. + + @return The size. + */ + result_type result() const noexcept { return size_; } + +private: + std::span text_; + std::size_t size_ = 0; +}; + +/** + Checks `text`: its public decode into a stack buffer and its secret decode allocate nothing and + agree; what decodes encodes back to `text`, publicly into a stack buffer and as a secret, + allocating nothing. + + @param text The text. + @param payload Where its public decode is written. + @return The size of the payload decoded, or the decode's error. +*/ +codecs::result check_text(std::string_view text, payload_buffer& payload) { + std::size_t const before = fuzz_allocations(); + codecs::result const written = codecs::decode(format, text, std::span{payload}); + auto const secret = + codecs::decode>(format, text); + expect(fuzz_allocations() == before, "the decode allocated"); + expect(written.has_value() == secret.has_value(), + "the secret decode's verdict differs from the public decode's"); + if (!written) { + expect(written.error() == secret.error(), + "the secret decode's error differs from the public decode's"); + return written; + } + std::span const bytes = std::span{payload}.first(*written); + expect(std::ranges::equal(bytes, secret->view()), + "the secret decode's bytes differ from the public decode's"); + + std::array encoded{}; + std::size_t const before_encode = fuzz_allocations(); + codecs::result const encoded_size = + codecs::encode(format, bytes, std::span{encoded}); + std::array secret_text{}; + codecs::result const secret_size = + codecs::encode(format, secret->view(), secret_into{secret_text}); + expect(fuzz_allocations() == before_encode, "the encode allocated"); + expect(encoded_size.has_value(), "what decoded does not encode"); + expect(std::string_view{encoded.data(), *encoded_size} == text, + "what decoded encodes to another text"); + expect(secret_size.has_value(), "what decoded does not encode as a secret"); + expect(std::string_view{secret_text.data(), *secret_size} == text, + "what decoded encodes as a secret to another text"); + webcpp::secure::erase_secret(secret_text); + return written; +} + +} // namespace + +// NOLINTNEXTLINE(readability-identifier-naming): libFuzzer's name for the target +extern "C" int LLVMFuzzerTestOneInput(std::uint8_t const* data, std::size_t size) { + std::span const input{data, size}; + payload_buffer payload{}; + static_cast( + check_text({reinterpret_cast(input.data()), input.size()}, payload)); + + std::span const kept = + input.first(std::min(input.size(), format_type::maximum_bytes)); + std::array text{}; + codecs::result const text_size = codecs::encode(format, kept, std::span{text}); + expect(text_size.has_value(), "the input's first bytes do not encode"); + codecs::result const decoded = check_text({text.data(), *text_size}, payload); + expect(decoded.has_value(), "the text of the input's first bytes does not decode"); + expect(std::ranges::equal(std::span{payload}.first(*decoded), kept), + "the text of the input's first bytes decodes to other bytes"); + return 0; +} diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_00 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_00 new file mode 100644 index 00000000..33ac7676 --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_00 @@ -0,0 +1 @@ +1FsSia9rv4NeEwvJ2GvXrX7LyxYspbN2mo \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_01 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_01 new file mode 100644 index 00000000..008b94ca --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_01 @@ -0,0 +1 @@ +36j4NfKv6Akva9amjWrLG6MuSQym1GuEmm \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_02 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_02 new file mode 100644 index 00000000..c87b1329 --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_02 @@ -0,0 +1 @@ +mzK2FFDEhxqHcmrJw1ysqFkVyhUULo45hZ \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_03 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_03 new file mode 100644 index 00000000..5524b72b --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_03 @@ -0,0 +1 @@ +2NC2hEhe28ULKAJkW5MjZ3jtTMJdvXmByvK \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_04 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_04 new file mode 100644 index 00000000..37fc807f --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_04 @@ -0,0 +1 @@ +mww4LvqtTMKvmeQvizPz2EQv26xTneWrbg \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_05 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_05 new file mode 100644 index 00000000..261eaf6c --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_05 @@ -0,0 +1 @@ +2N1r7aC69VHeE7yQJPDLi9T1PYq4wnwvjuT \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_06 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_06 new file mode 100644 index 00000000..52129526 --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_06 @@ -0,0 +1 @@ +n4fajahJrAuKbN7uNsKjLjQkz9Qn5ewJXQ \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_07 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_07 new file mode 100644 index 00000000..f5547549 --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_07 @@ -0,0 +1 @@ +2MxFajLApXpYk4VodBSZSt7rw8y4ryABkfA \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_08 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_08 new file mode 100644 index 00000000..50da000e --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_08 @@ -0,0 +1 @@ +5JuW2AMDYu4xVwRG9DZW18VbzQrGcd5RCgb99sS6ehJsNQXu5b9 \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_09 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_09 new file mode 100644 index 00000000..c2aa32ac --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_09 @@ -0,0 +1 @@ +L5nJeqKmpHp4P7F8ZYyjwc5a7P4d8EabuGAzfGJk7yC1BJyzNaEd \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_10 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_10 new file mode 100644 index 00000000..cc5a6515 --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_10 @@ -0,0 +1 @@ +92ZdE5HoLafywnTBbzPxbvRmp75pSfzvdU3XaZGh1cToipgdHVh \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_11 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_11 new file mode 100644 index 00000000..8538bc90 --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_11 @@ -0,0 +1 @@ +cV83kKisF3RQSvXbUCm9ox3kaz5JjEUBWcx8tNydfGJcyeUxuH47 \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_12 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_12 new file mode 100644 index 00000000..4bad24a5 --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_12 @@ -0,0 +1 @@ +92QuSnywrhsV7WPZChTgSQA23uSmj9MCEEno1eRBDG9sg8M29cX \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_13 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_13 new file mode 100644 index 00000000..67056679 --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_13 @@ -0,0 +1 @@ +cND53Dhp8eCZqG2ghe8YhSCGesXZ8fE5PGD1khrqNvEi4RBoXhEK \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_14 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_14 new file mode 100644 index 00000000..3c341cf7 --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_14 @@ -0,0 +1 @@ +91mn1wYKEB1zyof1VFm8tMtocZx1oBrKKRCu9GCpgZvPmBLEJjp \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_15 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_15 new file mode 100644 index 00000000..b3e0cff3 --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_15 @@ -0,0 +1 @@ +cPisAUdLvqqAr6MYtXnrWvgvyUAwuNyuTvZkDGw6miPhZdaiSDNH \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_16 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_16 new file mode 100644 index 00000000..1e5df219 --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_16 @@ -0,0 +1 @@ +1FjL87pn8ky6Vbavd1ZHeChRXtoxwRGCRd \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_17 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_17 new file mode 100644 index 00000000..f6b07aaa --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_17 @@ -0,0 +1 @@ +3BZECeAH8gSKkjrTx8PwMrNQBLG18yHpvf \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_18 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_18 new file mode 100644 index 00000000..2b6820f0 --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_18 @@ -0,0 +1 @@ +n4YNbYuFdPwFrxSP8sjHFbAhUbLMUiY9jE \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_19 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_19 new file mode 100644 index 00000000..136f1e35 --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_19 @@ -0,0 +1 @@ +2NAeQVZayzVFAtgeC3iYJsjpjWDmsDph71A \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_20 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_20 new file mode 100644 index 00000000..478e8514 --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_20 @@ -0,0 +1 @@ +mnCBpkNMJEJLehgdEkzSo2eioniyJMxLpZ \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_21 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_21 new file mode 100644 index 00000000..102e1b3a --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_21 @@ -0,0 +1 @@ +2N5sNHomeNJDZv67AcFx9ES7FBZY4jx9KDA \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_22 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_22 new file mode 100644 index 00000000..fe16c688 --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_22 @@ -0,0 +1 @@ +mfhE6jAUwjUDNZhaX1PAsDTKfneQF2Nshc \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_23 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_23 new file mode 100644 index 00000000..81beb898 --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_23 @@ -0,0 +1 @@ +2MxNm1VHyVU4RuP3u1c1v5aQLk2dQjwy1Qk \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_24 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_24 new file mode 100644 index 00000000..4f2c52f3 --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_24 @@ -0,0 +1 @@ +5HsL2nZuEebU5nM3RxNVQD9GcAnvNMahqQskf4fkqHe54zwd14e \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_25 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_25 new file mode 100644 index 00000000..ee760ebe --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_25 @@ -0,0 +1 @@ +KwuVvu6hsuEMHrfFWJQV64tRrWX3QzqHH18JuAHYqYV6dqBvNKxd \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_26 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_26 new file mode 100644 index 00000000..4929cad5 --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_26 @@ -0,0 +1 @@ +921M1RNxghFcsVGqAJksQVbSgx36Yz4u6vebfz1wDujNvgNt93B \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_27 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_27 new file mode 100644 index 00000000..ce7f03b6 --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_27 @@ -0,0 +1 @@ +cNEnbfF2fcxmmCLWqMAaq6fxJvVkwMbyU3kCbpQznz4Z1j6TZDGb \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_28 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_28 new file mode 100644 index 00000000..39215a15 --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_28 @@ -0,0 +1 @@ +93BcpCMKPmFCuY8bqS4k3HFrhJ1Afxi4uSsEeJFvX86GYW7PC7W \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_29 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_29 new file mode 100644 index 00000000..a70c1ac2 --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_29 @@ -0,0 +1 @@ +cUtwbyxoL1owPxUafgH2meEpydeywjhnTYv2mJaFHHchz39AaEgy \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_30 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_30 new file mode 100644 index 00000000..8ceaa6e5 --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_30 @@ -0,0 +1 @@ +927zPWny2SiNaUmHF5NnGQXQWDwbByfFzXGgu88j91ZoutSosvE \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_31 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_31 new file mode 100644 index 00000000..8f6b0a82 --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_31 @@ -0,0 +1 @@ +cRez45VGSp5EXNqm89K3NJJPSKKapJg5Kbw3atxr2337x2gtgYed \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_32 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_32 new file mode 100644 index 00000000..1a65de62 --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_32 @@ -0,0 +1 @@ +1G9A9j6W8TLuh6dEeVwWeyibK1Uc5MfVFV \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_33 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_33 new file mode 100644 index 00000000..b9b958ea --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_33 @@ -0,0 +1 @@ +33GA3ZXbw5o5HeUrBEaqkWXFYYZmdxGRRP \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_34 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_34 new file mode 100644 index 00000000..e5002b0c --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_34 @@ -0,0 +1 @@ +mwgS2HRbjyfYxFnR1nF9VKLvmdgMfFBmGq \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_35 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_35 new file mode 100644 index 00000000..86be76ff --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_35 @@ -0,0 +1 @@ +2MwBVrJQ76BdaGD76CTmou8cZzQYLpe4NqU \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_36 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_36 new file mode 100644 index 00000000..58a8db18 --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_36 @@ -0,0 +1 @@ +mfnJ8tEkqKNFE5YaHTXFxyHk2mnDK2fvDh \ No newline at end of file diff --git a/test/fuzz/corpus/base58_with_checksum/key_io_valid_37 b/test/fuzz/corpus/base58_with_checksum/key_io_valid_37 new file mode 100644 index 00000000..8b8a6ed8 --- /dev/null +++ b/test/fuzz/corpus/base58_with_checksum/key_io_valid_37 @@ -0,0 +1 @@ +2My83D67ir7K8PPzeT6mE2oth3ZwNTVRS9F \ No newline at end of file diff --git a/test/fuzz/corpus/toy_pem_spki/begin_alone b/test/fuzz/corpus/toy_pem_spki/begin_alone new file mode 100644 index 00000000..0d08e1e1 --- /dev/null +++ b/test/fuzz/corpus/toy_pem_spki/begin_alone @@ -0,0 +1 @@ +-----BEGIN PUBLIC KEY----- diff --git a/test/fuzz/corpus/toy_pem_spki/certificate b/test/fuzz/corpus/toy_pem_spki/certificate new file mode 100644 index 00000000..649b065d --- /dev/null +++ b/test/fuzz/corpus/toy_pem_spki/certificate @@ -0,0 +1,3 @@ +-----BEGIN CERTIFICATE----- +MAowAAECAwQFBgcI +-----END CERTIFICATE----- diff --git a/test/fuzz/corpus/toy_pem_spki/empty b/test/fuzz/corpus/toy_pem_spki/empty new file mode 100644 index 00000000..e69de29b diff --git a/test/fuzz/corpus/toy_pem_spki/empty_armor b/test/fuzz/corpus/toy_pem_spki/empty_armor new file mode 100644 index 00000000..2b8fd9a7 --- /dev/null +++ b/test/fuzz/corpus/toy_pem_spki/empty_armor @@ -0,0 +1,2 @@ +-----BEGIN PUBLIC KEY----- +-----END PUBLIC KEY----- diff --git a/test/fuzz/corpus/toy_pem_spki/explained b/test/fuzz/corpus/toy_pem_spki/explained new file mode 100644 index 00000000..da4d725c --- /dev/null +++ b/test/fuzz/corpus/toy_pem_spki/explained @@ -0,0 +1,4 @@ +Public-Key: (64 bit) +-----BEGIN PUBLIC KEY----- +MAowAAECAwQFBgcI +-----END PUBLIC KEY----- diff --git a/test/fuzz/corpus/toy_pem_spki/key_pem b/test/fuzz/corpus/toy_pem_spki/key_pem new file mode 100644 index 00000000..496bafc9 --- /dev/null +++ b/test/fuzz/corpus/toy_pem_spki/key_pem @@ -0,0 +1,3 @@ +-----BEGIN PUBLIC KEY----- +MAowAAECAwQFBgcI +-----END PUBLIC KEY----- diff --git a/test/fuzz/corpus/toy_pem_spki/key_pem_crlf b/test/fuzz/corpus/toy_pem_spki/key_pem_crlf new file mode 100644 index 00000000..b859cdeb --- /dev/null +++ b/test/fuzz/corpus/toy_pem_spki/key_pem_crlf @@ -0,0 +1,3 @@ +-----BEGIN PUBLIC KEY----- +MAowAAECAwQFBgcI +-----END PUBLIC KEY----- diff --git a/test/fuzz/corpus/toy_pem_spki/key_pem_no_final_line_feed b/test/fuzz/corpus/toy_pem_spki/key_pem_no_final_line_feed new file mode 100644 index 00000000..95c2bd3a --- /dev/null +++ b/test/fuzz/corpus/toy_pem_spki/key_pem_no_final_line_feed @@ -0,0 +1,3 @@ +-----BEGIN PUBLIC KEY----- +MAowAAECAwQFBgcI +-----END PUBLIC KEY----- \ No newline at end of file diff --git a/test/fuzz/corpus/toy_pem_spki/private b/test/fuzz/corpus/toy_pem_spki/private new file mode 100644 index 00000000..debd7426 --- /dev/null +++ b/test/fuzz/corpus/toy_pem_spki/private @@ -0,0 +1,3 @@ +-----BEGIN PRIVATE KEY----- +MAoCAKGyw9Tl9gcY +-----END PRIVATE KEY----- diff --git a/test/fuzz/corpus/toy_pem_spki/private_too_long b/test/fuzz/corpus/toy_pem_spki/private_too_long new file mode 100644 index 00000000..d61414cd --- /dev/null +++ b/test/fuzz/corpus/toy_pem_spki/private_too_long @@ -0,0 +1,3 @@ +-----BEGIN PRIVATE KEY----- +MA4CAaGyw9Tl9gcYoQKhsgA= +-----END PRIVATE KEY----- diff --git a/test/fuzz/corpus/toy_pem_spki/private_version_2 b/test/fuzz/corpus/toy_pem_spki/private_version_2 new file mode 100644 index 00000000..e49bf21a --- /dev/null +++ b/test/fuzz/corpus/toy_pem_spki/private_version_2 @@ -0,0 +1,3 @@ +-----BEGIN PRIVATE KEY----- +MA4CAaGyw9Tl9gcYoQKhsg== +-----END PRIVATE KEY----- diff --git a/test/fuzz/corpus/toy_pem_spki/rsa b/test/fuzz/corpus/toy_pem_spki/rsa new file mode 100644 index 00000000..52fc5966 --- /dev/null +++ b/test/fuzz/corpus/toy_pem_spki/rsa @@ -0,0 +1,9 @@ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArpJaM2Yn8RLXSleDrssG +eF2cVvTEVY39sZVHIru8gHpPYSiI6DZJM7T2m1xRk7dPwzeH9DMNMrLRXwDkBUh0 +1/utEVq5f/fPZyHkvk0D+QRWJl5vytW6cKd0Ppziei8fs31HxysqJgddGeFHcxlW +rEP5MDs3grF+laLFQpAGgm0Ad2XKTy1Z6ESgHunEyIyovcnZuu1GKL1ygROsj8ih +RySEfJ3CjofcaqGCK9qV/2bXE1ALXk8qEpU/LZ6jQ5XHqxUG3GAAQnXe+Usi/4UT +8JD+90Gi8/JBHn5LCQEVIQa595+1mBc/hylfLMz44cgjJ4wkG1c0NRcE8tzPd7Ys +DwIDAQAB +-----END PUBLIC KEY----- diff --git a/test/fuzz/fuzz.mjs b/test/fuzz/fuzz.mjs new file mode 100644 index 00000000..a7fc2a29 --- /dev/null +++ b/test/fuzz/fuzz.mjs @@ -0,0 +1,49 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Runs a libFuzzer target for --seconds from a scratch copy of the corpus --corpus names, so that +// the inputs libFuzzer adds to its corpus never reach the source tree, with a fixed seed and 10 s +// for any one input, and passes with its exit status: libFuzzer exits 0 when the time ran out with +// no crash, and with another status on a crash, a sanitizer's report (UndefinedBehaviorSanitizer +// stops at its first, -fno-sanitize-recover=all), a timeout or a leak. Each input libFuzzer wrote +// as an artifact, the crash's among them, is printed in base64, so that the log alone reproduces +// it: `base64 -d > input`, then the program with that file, or the replay with it in the corpus. +import {spawnSync} from 'node:child_process' +import {cpSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync} from 'node:fs' +import {tmpdir} from 'node:os' +import {join} from 'node:path' + +const option = name => { + const at = process.argv.indexOf(name) + if (at === -1 || at + 1 >= process.argv.length - 1) { + console.error(`fuzz.mjs: ${name} is required, before the program`) + process.exit(1) + } + return process.argv[at + 1] +} +const program = process.argv[process.argv.length - 1] +const corpus = option('--corpus') +const seconds = option('--seconds') +const scratch = mkdtempSync(join(tmpdir(), 'webcpp-crypto-fuzz-')) +const copy = join(scratch, 'corpus') +const artifacts = join(scratch, 'artifacts') +cpSync(corpus, copy, {recursive: true}) +mkdirSync(artifacts) +const run = spawnSync(program, [`-max_total_time=${seconds}`, '-seed=20261126', '-timeout=10', + `-artifact_prefix=${artifacts}/`, copy], {stdio: 'inherit'}) +let status = run.status ?? 1 +if (run.error) { + console.error(`fuzz.mjs: ${program} could not run: ${run.error.message}`) + status = 1 +} else if (run.signal) { + console.error(`fuzz.mjs: ${program} ended by ${run.signal}`) +} +for (const name of readdirSync(artifacts).sort()) { + const input = readFileSync(join(artifacts, name)) + console.error(`fuzz.mjs: ${name}, ${input.length} bytes, in base64: ${input.toString('base64')}`) +} +rmSync(scratch, {recursive: true, force: true}) +process.exit(status) diff --git a/test/fuzz/fuzz_wipes.cpp b/test/fuzz/fuzz_wipes.cpp new file mode 100644 index 00000000..fcc63830 --- /dev/null +++ b/test/fuzz/fuzz_wipes.cpp @@ -0,0 +1,35 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the 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 wipe record of a fuzz program, linked into the replay and the libFuzzer build alike: this +// translation unit includes support/wipe_record.hpp, which defines secure's seam once for the +// program, and reads the record for target.hpp's fuzz_wipes, allocating nothing (the record's +// storage is fixed). Every program of test/fuzz/Jamfile is built with +// WEBCPP_SECURE_TEST_WIPE_RECORD. + +#include "target.hpp" + +#include "../support/wipe_record.hpp" + +#include +#include + +webcpp::crypto::test::fuzz_wipe_summary webcpp::crypto::test::fuzz_wipes( + std::size_t size) noexcept { + ::webcpp::test::wipe_log& log = ::webcpp::test::wipes; + std::size_t const kept = std::min(log.count, log.entries.size()); + fuzz_wipe_summary summary{.count = log.count, + .not_zero = log.not_zero, + .of_size = 0, + .all_kept = log.count <= log.entries.size()}; + for (std::size_t index = 0; index < kept; ++index) { + if (log.entries[index].size == size) { + ++summary.of_size; + } + } + log = {}; + return summary; +} diff --git a/test/fuzz/libfuzzer_hooks.cpp b/test/fuzz/libfuzzer_hooks.cpp new file mode 100644 index 00000000..62a95f21 --- /dev/null +++ b/test/fuzz/libfuzzer_hooks.cpp @@ -0,0 +1,52 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The heap counter of the libFuzzer build, codecs' test/fuzz/libfuzzer_hooks.cpp copied: +// AddressSanitizer owns the allocator there, so the replay's replaced allocation functions +// (support/counting.hpp) cannot be, and the sanitizer's own malloc hooks count instead, called on +// every allocation of the program, through operator new or the C library. A hook counts the calling +// thread's allocations alone, so that another thread of libFuzzer's (its RSS watcher) cannot change +// a target's count; the count is a thread_local of the executable, read without allocating. + +#include "target.hpp" + +#include + +#include + +namespace { + +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the hook's count +thread_local std::size_t counted_allocations = 0; + +/** The malloc hook: counts one allocation of the calling thread. */ +void count_allocation(void const volatile* /*block*/, std::size_t /*size*/) { + ++counted_allocations; +} + +/** The free hook, which the interface requires: a release changes no count. */ +void ignore_release(void const volatile* /*block*/) {} + +/** + Installs the hooks; the sanitizer's C function throws nothing, which its declaration cannot say. + + @return Whether they are installed: the sanitizer holds five pairs at most. +*/ +bool install_hooks() noexcept { + return __sanitizer_install_malloc_and_free_hooks(&count_allocation, &ignore_release) != 0; +} + +/** Whether the hooks are installed, at static initialisation, before libFuzzer runs a target. */ +bool const hooks_installed = install_hooks(); + +} // namespace + +std::size_t webcpp::crypto::test::fuzz_allocations() noexcept { + if (!hooks_installed) { + fuzz_detail::mismatch("the sanitizer's malloc hooks are not installed"); + } + return counted_allocations; +} diff --git a/test/fuzz/package-lock.json b/test/fuzz/package-lock.json new file mode 100644 index 00000000..fe985312 --- /dev/null +++ b/test/fuzz/package-lock.json @@ -0,0 +1,10 @@ +{ + "name": "webcpp-crypto-fuzz", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "webcpp-crypto-fuzz" + } + } +} diff --git a/test/fuzz/package.json b/test/fuzz/package.json new file mode 100644 index 00000000..3a0483c7 --- /dev/null +++ b/test/fuzz/package.json @@ -0,0 +1 @@ +{"name": "webcpp-crypto-fuzz", "private": true} diff --git a/test/fuzz/target.hpp b/test/fuzz/target.hpp new file mode 100644 index 00000000..069f02c4 --- /dev/null +++ b/test/fuzz/target.hpp @@ -0,0 +1,236 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The checks of the own lane fuzz (design R33, the spec's "Formats: every decoder is fuzzed"), +// which every target's LLVMFuzzerTestOneInput calls, on webcpp::codecs' model (its +// test/fuzz/target.hpp). An input is the decoder's input as is: bytes for a binary format, a text +// for a PEM. fuzz_decode decodes it through crypto::decode, with no heap counted, and what decodes +// is encoded again through crypto::encode, with no heap counted, which must give the input back: a +// binary format its bytes, a PEM its text with each carriage return before a line feed removed and +// a final line feed added, the lines as the armor writes them (codecs' armor takes both line ends +// and no final one, and writes line feeds). For a secret format (a secret value codec, or a secret +// value), every wipe secure's record holds must have left only zero bytes, and a PEM's decode must +// have wiped its buffer of the inner format's decode bound, on success and on error. A mismatch +// prints what failed and ends the program by a trap, which libFuzzer reports with the input and +// the replay with the test's failure. +// +// The heap is counted by fuzz_allocations, which this header declares and each program defines +// once: the replay, on every lane, through support/counting.hpp's replaced allocation functions +// (support/fuzz_replay_main.cpp), and the libFuzzer build, whose sanitizer owns the allocator, +// through the sanitizer's malloc hooks (libfuzzer_hooks.cpp). secure's wipes are recorded by +// support/wipe_record.hpp, which fuzz_wipes.cpp includes once in every program, and read through +// fuzz_wipes. + +#ifndef WEBCPP_CRYPTO_TEST_FUZZ_TARGET_HPP +#define WEBCPP_CRYPTO_TEST_FUZZ_TARGET_HPP + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +/** + The fuzz target, libFuzzer's entry point, which each `_fuzz.cpp` defines and the replay + calls (support/fuzz_replay_main.cpp). + + @param data The input's first byte. + @param size The input's size. + @return 0, as libFuzzer asks. +*/ +// NOLINTNEXTLINE(readability-identifier-naming): libFuzzer's name for the target +extern "C" int LLVMFuzzerTestOneInput(std::uint8_t const* data, std::size_t size); + +namespace webcpp::crypto::test { + +/** + The allocations counted so far, through the global operator new and the C library, by the + program's one definition: support/fuzz_replay_main.cpp's or libfuzzer_hooks.cpp's. + + @return The count, which only grows. +*/ +std::size_t fuzz_allocations() noexcept; + +/** What secure's wipe record held, read by fuzz_wipes. */ +struct fuzz_wipe_summary { + /** The wipes recorded. */ + std::size_t count = 0; + /** Those that found a byte that was not zero after the wipe. */ + std::size_t not_zero = 0; + /** Those of the size asked about, among the wipes the record kept. */ + std::size_t of_size = 0; + /** Whether the record kept every wipe: it holds a fixed number. */ + bool all_kept = true; +}; + +/** + Reads secure's wipe record since the last call, and clears it, allocating nothing: the + program's one definition, fuzz_wipes.cpp's, over support/wipe_record.hpp. + + @param size The size of the wipes to count. + @return What the record held. +*/ +fuzz_wipe_summary fuzz_wipes(std::size_t size) noexcept; + +namespace fuzz_detail { + +/** + Prints what failed and ends the program, by a trap where the compiler has one. + + @param what The check that failed. +*/ +[[noreturn]] inline void mismatch(char const* what) noexcept { + // The program ends here: a failure to print changes nothing of that. + static_cast(std::fprintf(stderr, "fuzz: %s\n", what)); + static_cast(std::fflush(stderr)); +#if defined(__GNUC__) || defined(__clang__) + __builtin_trap(); +#else + std::abort(); +#endif +} + +/** + Ends the program, naming `what`, unless `holds`. + + @param holds The check's verdict. + @param what The check. +*/ +inline void expect(bool holds, char const* what) noexcept { + if (!holds) { + mismatch(what); + } +} + +/** + Whether the text encode wrote equals `original` with each carriage return before a line feed + removed and a line feed added at its end when it has none: the lines as the armor writes them. + Compared in place, allocating nothing. + + @param encoded The text encode wrote. + @param original The text that decoded. + @return Whether they are equal. +*/ +[[nodiscard]] inline bool same_lines(std::string_view encoded, std::string_view original) noexcept { + std::size_t at = 0; + for (std::size_t index = 0; index < original.size(); ++index) { + if (original[index] == '\r' && index + 1 < original.size() && original[index + 1] == '\n') { + continue; + } + if (at == encoded.size() || encoded[at] != original[index]) { + return false; + } + ++at; + } + if (!original.ends_with('\n')) { + if (at == encoded.size() || encoded[at] != '\n') { + return false; + } + ++at; + } + return at == encoded.size(); +} + +/** The parts of a format: whether it is a PEM, and the format its payload is in. */ +template +struct format_parts { + /** Not a PEM. */ + static constexpr bool pem = false; + /** The format itself. */ + using inner = Format; +}; + +/** A PEM, over `Inner`. */ +template +struct format_parts> { + /** A PEM. */ + static constexpr bool pem = true; + /** The DER format inside the armor. */ + using inner = Inner; +}; + +/** + Checks secure's wipe record after a secret call: every wipe left only zero bytes and was kept, + and, after a PEM's decode, its buffer of the inner format's decode bound was wiped. + + @param buffer_size The size of the buffer whose wipe is required, or 0 for none. + @param what The call, for the message. +*/ +inline void expect_wiped(std::size_t buffer_size, char const* what) noexcept { + fuzz_wipe_summary const wipes = fuzz_wipes(buffer_size); + expect(wipes.all_kept, what); + expect(wipes.not_zero == 0, what); + expect(buffer_size == 0 || wipes.of_size != 0, what); +} + +} // namespace fuzz_detail + +/** + Checks a decoder of crypto's on a fuzzer's input: `crypto::decode(format, input)`, the + input read as a text for a PEM and as bytes otherwise, allocates nothing; what decodes encodes + back through `crypto::encode(format, value)`, allocating nothing, to the input (a PEM to its lines + as the armor writes them); for a secret format every wipe leaves zero bytes, and a PEM's decode + wipes its buffer. + + @tparam Value The value's type. + @tparam Format The format's type. + @param format The format. + @param input The fuzzer's input. +*/ +template +void fuzz_decode(Format format, std::span input) { + using fuzz_detail::expect; + using parts = fuzz_detail::format_parts; + constexpr bool secret = crypto::detail::value_codec_secret_v || + codecs::is_secret_v; + constexpr std::size_t pem_buffer_size = + parts::pem && secret ? formats::max_decode_input_size : 0; + std::string_view const text{reinterpret_cast(input.data()), input.size()}; + if constexpr (secret) { + // The wipes since the last check, the previous input's values' among them. + expect(fuzz_wipes(0).not_zero == 0, "a wipe left a byte not zero"); + } + + std::size_t const before = fuzz_allocations(); + auto const decoded = [&] { + if constexpr (parts::pem) { + return crypto::decode(format, text); + } else { + return crypto::decode(format, input); + } + }(); + expect(fuzz_allocations() == before, "the decode allocated"); + if constexpr (secret) { + fuzz_detail::expect_wiped(pem_buffer_size, "the decode left a buffer not wiped"); + } + if (!decoded) { + return; + } + + std::size_t const before_encode = fuzz_allocations(); + auto const encoded = crypto::encode(format, *decoded); + expect(fuzz_allocations() == before_encode, "the encode allocated"); + expect(encoded.has_value(), "what decoded does not encode"); + if constexpr (parts::pem) { + expect(fuzz_detail::same_lines(encoded->view(), text), + "what decoded encodes to another text than its lines"); + } else { + expect(std::ranges::equal(encoded->view(), input), + "what decoded encodes to other bytes than the input"); + } + if constexpr (secret) { + fuzz_detail::expect_wiped(0, "the encode left a buffer not wiped"); + } +} + +} // namespace webcpp::crypto::test + +#endif // WEBCPP_CRYPTO_TEST_FUZZ_TARGET_HPP diff --git a/test/fuzz/toy_pem_spki_fuzz.cpp b/test/fuzz/toy_pem_spki_fuzz.cpp new file mode 100644 index 00000000..9129f23a --- /dev/null +++ b/test/fuzz/toy_pem_spki_fuzz.cpp @@ -0,0 +1,29 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The fuzz target of the tests' toy public key in pem(spki) (support/formats_toy.hpp): every input +// is a text decoded in place through crypto::decode, with no heap; what decodes encodes back to the +// text's lines as the armor writes them (target.hpp's fuzz_decode). The toy proves the lane's PEM +// path before any curve registers into it; each curve's pem(spki) and pem(pkcs8) targets call the +// same check. + +#include "target.hpp" + +#include "../support/formats_toy.hpp" + +#include + +#include +#include +#include + +// NOLINTNEXTLINE(readability-identifier-naming): libFuzzer's name for the target +extern "C" int LLVMFuzzerTestOneInput(std::uint8_t const* data, std::size_t size) { + namespace formats = webcpp::crypto::formats; + webcpp::crypto::test::fuzz_decode(formats::pem(formats::spki), + std::span{data, size}); + return 0; +} diff --git a/test/support/fuzz_replay_main.cpp b/test/support/fuzz_replay_main.cpp new file mode 100644 index 00000000..85483e45 --- /dev/null +++ b/test/support/fuzz_replay_main.cpp @@ -0,0 +1,193 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the 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 replay of a fuzz target (test/fuzz/Jamfile), its main, linked with the target's source on +// every lane, with exceptions on and off, where no fuzzing engine runs; codecs' +// test/support/fuzz_replay_main.cpp, with inputs that hold no split seed (crypto's targets do not +// stream). It calls the target's LLVMFuzzerTestOneInput with every file of the target's corpus, in +// the order of their names, and then with 4096 inputs drawn from a xorshift64 stream of a fixed +// seed, so that every lane and every run sees the same: one in four the stream's own bytes, 0 to +// 63 of them; the others a corpus file with one to four edits, each the stream's choice: a byte +// replaced by one of the stream's or by another of the input's, a byte of the input's inserted, a +// byte removed. So the targets' assertions (fuzz/target.hpp) run everywhere, over inputs near the +// valid ones. The heap is counted by support/counting.hpp, which this translation unit alone +// includes, through fuzz_allocations. WEBCPP_TEST_CRYPTO_FUZZ_CORPUS names the corpus's directory, +// which webcpp.data gives a WASI program. + +#include "counting.hpp" + +#include "../fuzz/target.hpp" + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef WEBCPP_TEST_CRYPTO_FUZZ_CORPUS +#error "WEBCPP_TEST_CRYPTO_FUZZ_CORPUS names the target's corpus (test/fuzz/Jamfile)" +#endif + +std::size_t webcpp::crypto::test::fuzz_allocations() noexcept { + return webcpp::test::allocations(); +} + +namespace { + +/** The inputs drawn from the stream after the corpus. */ +constexpr int drawn_inputs = 4096; + +/** Marsaglia's xorshift64, its shifts 13, 7 and 17: a stream every lane computes alike. */ +class xorshift { +public: + /** + Constructs the stream from `seed`, which is not zero. + + @param seed The first state. + */ + explicit xorshift(std::uint64_t seed) noexcept : state_(seed) {} + + /** + The next value of the stream. + + @return The value. + */ + std::uint64_t next() noexcept { + state_ ^= state_ << 13U; + state_ ^= state_ >> 7U; + state_ ^= state_ << 17U; + return state_; + } + + /** + A value of the stream below `bound`, by its remainder, through no distribution. + + @param bound The bound, not zero. + @return The value. + */ + std::size_t below(std::size_t bound) noexcept { + return static_cast(next() % bound); + } + + /** + A byte of the stream. + + @return The byte. + */ + std::uint8_t byte() noexcept { return static_cast(next()); } + +private: + std::uint64_t state_; +}; + +/** + Every file of the corpus, in the order of their names; the test fails when the directory is + unread or holds no file, since a drawn input is an edit of a corpus file. +*/ +std::vector> corpus_inputs() { + std::vector paths; + std::error_code error; + for (std::filesystem::directory_entry const& entry : + std::filesystem::directory_iterator(WEBCPP_TEST_CRYPTO_FUZZ_CORPUS, error)) { + if (entry.is_regular_file()) { + paths.push_back(entry.path()); + } + } + if (error) { + BOOST_ERROR("the corpus directory is unread"); + std::printf("%s: %s\n", WEBCPP_TEST_CRYPTO_FUZZ_CORPUS, error.message().c_str()); + return {}; + } + std::ranges::sort(paths); + std::vector> inputs; + for (std::filesystem::path const& path : paths) { + std::ifstream file{path, std::ios::binary}; + if (!BOOST_TEST(file.is_open())) { + std::printf("%s: not opened\n", path.string().c_str()); + continue; + } + std::vector input{std::istreambuf_iterator{file}, + std::istreambuf_iterator{}}; + BOOST_TEST(!file.bad()); + inputs.push_back(std::move(input)); + } + if (!BOOST_TEST(!inputs.empty())) { + std::printf("no corpus file in %s\n", WEBCPP_TEST_CRYPTO_FUZZ_CORPUS); + } + return inputs; +} + +/** One edit of `input`, the stream's choice: a byte replaced, inserted or removed. */ +void edit(std::vector& input, xorshift& stream) { + if (input.empty()) { + input.push_back(stream.byte()); + return; + } + std::size_t const at = stream.below(input.size()); + auto const place = input.begin() + static_cast(at); + switch (stream.below(4)) { + case 0: *place = stream.byte(); break; + case 1: *place = input[stream.below(input.size())]; break; + case 2: { + std::uint8_t const copied = input[stream.below(input.size())]; + input.insert(place, copied); + break; + } + default: input.erase(place); break; + } +} + +/** An input drawn from the stream: the stream's own bytes, or a corpus file edited. */ +std::vector drawn_input(std::vector> const& corpus, + xorshift& stream) { + if (stream.below(4) == 0) { + std::vector input(stream.below(64)); + std::ranges::generate(input, [&stream] { return stream.byte(); }); + return input; + } + std::vector input = corpus[stream.below(corpus.size())]; + for (std::size_t edits = stream.below(4) + 1; edits > 0; --edits) { + edit(input, stream); + } + return input; +} + +/** + Calls the target with `input`, as libFuzzer would. + + @param input The input. +*/ +void replay(std::vector const& input) { + BOOST_TEST_EQ(LLVMFuzzerTestOneInput(input.data(), input.size()), 0); +} + +} // namespace + +int main() { + std::vector> const corpus = corpus_inputs(); + if (corpus.empty()) { + // corpus_inputs has failed the test; a drawn input needs a corpus file to edit. + return webcpp::test::exit_status(boost::report_errors()); + } + for (std::vector const& input : corpus) { + replay(input); + } + xorshift stream{20261201}; + for (int drawn = 0; drawn < drawn_inputs; ++drawn) { + replay(drawn_input(corpus, stream)); + } + std::printf("replayed %zu inputs of the corpus and %d drawn\n", corpus.size(), drawn_inputs); + return webcpp::test::exit_status(boost::report_errors()); +} From bab571133f7ba40a6fc4626c4c439351ded93b94 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 1 Dec 2026 03:11:03 -0300 Subject: [PATCH 26/81] crypto: fuzz lane lint fix --- test/fuzz/base58_with_checksum_fuzz.cpp | 2 +- test/fuzz/fuzz_wipes.cpp | 10 ++++++---- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/test/fuzz/base58_with_checksum_fuzz.cpp b/test/fuzz/base58_with_checksum_fuzz.cpp index 926d922d..653d308c 100644 --- a/test/fuzz/base58_with_checksum_fuzz.cpp +++ b/test/fuzz/base58_with_checksum_fuzz.cpp @@ -77,7 +77,7 @@ class secret_into { @return The size. */ - result_type result() const noexcept { return size_; } + [[nodiscard]] result_type result() const noexcept { return size_; } private: std::span text_; diff --git a/test/fuzz/fuzz_wipes.cpp b/test/fuzz/fuzz_wipes.cpp index fcc63830..62f2c864 100644 --- a/test/fuzz/fuzz_wipes.cpp +++ b/test/fuzz/fuzz_wipes.cpp @@ -21,10 +21,12 @@ webcpp::crypto::test::fuzz_wipe_summary webcpp::crypto::test::fuzz_wipes( std::size_t size) noexcept { ::webcpp::test::wipe_log& log = ::webcpp::test::wipes; std::size_t const kept = std::min(log.count, log.entries.size()); - fuzz_wipe_summary summary{.count = log.count, - .not_zero = log.not_zero, - .of_size = 0, - .all_kept = log.count <= log.entries.size()}; + fuzz_wipe_summary summary{ + .count = log.count, + .not_zero = log.not_zero, + .of_size = 0, + .all_kept = log.count <= log.entries.size(), + }; for (std::size_t index = 0; index < kept; ++index) { if (log.entries[index].size == size) { ++summary.of_size; From 6ffac84729e497222571fc418113b7c12406da8b Mon Sep 17 00:00:00 2001 From: R Date: Tue, 1 Dec 2026 03:47:43 -0300 Subject: [PATCH 27/81] crypto: the Base58Check fuzz target reads its wipe record; the wasip2 base58 dudect exception noted beside its program and in the testing page; choose_between's docstring says only the second input is read through a volatile --- doc/testing.adoc | 4 +++- test/constant_time/Jamfile | 3 +++ test/constant_time/dudect.hpp | 5 +++-- test/fuzz/base58_with_checksum_fuzz.cpp | 7 ++++++- 4 files changed, 15 insertions(+), 4 deletions(-) diff --git a/doc/testing.adoc b/doc/testing.adoc index d0354578..ad923a8a 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -51,7 +51,9 @@ two fresh processes, failing when two of the three values exceed 10 native lane's command with `libs/crypto/test/constant_time//constant-time` in place of the two directories. Its paths include webcpp::hash's Base58Check, the secret encode and decode of a WIF key's payload, which hash leaves to crypto's -lane. +lane; on wasip2 dudect prints that decode's |t| without judging it, an open +finding of codecs' secret base58 conversion under wasmtime, as X25519's +agreement is there (<>). The own lane `fuzz` runs libFuzzer natively on Linux, with clang, AddressSanitizer and UndefinedBehaviorSanitizer, for 60 seconds a target from a diff --git a/test/constant_time/Jamfile b/test/constant_time/Jamfile index fd611a1e..6cdc9892 100644 --- a/test/constant_time/Jamfile +++ b/test/constant_time/Jamfile @@ -262,6 +262,9 @@ if [ os.environ RUNNER_ENVIRONMENT ] = github-hosted { DUDECT += WEBCPP_TEST_DUDECT_UNJUDGED ; } +# On wasip2, hash's Base58Check secret decode (base58_decode) is measured and +# printed but not judged: an open finding of codecs' secret base58 conversion +# under wasmtime, which dudect_test.cpp's header describes. webcpp.run dudect_bearssl : dudect_test.cpp : /third_party//bearssl /third_party//ctaes /webcpp/hash//base58_with_checksum $(DUDECT) diff --git a/test/constant_time/dudect.hpp b/test/constant_time/dudect.hpp index 36f66f22..981f3569 100644 --- a/test/constant_time/dudect.hpp +++ b/test/constant_time/dudect.hpp @@ -259,8 +259,9 @@ void choose(int which, Generator& generator, std::array cons /** * Writes `first` into `input` for class 0 and `second` for class 1, by the instructions of - * `choose`: the same draws, then both inputs read through a volatile and blended through the - * same volatile mask, so that what the preparation does is the same for both classes; the two + * `choose`: the same draws, then the second input read through a volatile, as `choose` + * reads its fixed input, and both blended through the same volatile mask, so that what the + * preparation does is the same for both classes; the two * classes of a case that compares two fixed inputs of one length (two WIF keys' texts). * @param which The class, 0 or 1. * @param generator The seeded generator. diff --git a/test/fuzz/base58_with_checksum_fuzz.cpp b/test/fuzz/base58_with_checksum_fuzz.cpp index 653d308c..7b252333 100644 --- a/test/fuzz/base58_with_checksum_fuzz.cpp +++ b/test/fuzz/base58_with_checksum_fuzz.cpp @@ -12,7 +12,8 @@ // text, through the buffer form and as a secret into a stack buffer (a token of the target's own), // with no heap. The input's first 100 bytes are // also encoded with their checksum and their text checked alike, which must decode to them: the -// one way the fuzzer's inputs reach a valid checksum. +// one way the fuzzer's inputs reach a valid checksum. After each text, every wipe secure's record +// holds, the secret decode's and codecs' secret scratch's, must have left only zero bytes. #include "target.hpp" @@ -136,6 +137,8 @@ extern "C" int LLVMFuzzerTestOneInput(std::uint8_t const* data, std::size_t size payload_buffer payload{}; static_cast( check_text({reinterpret_cast(input.data()), input.size()}, payload)); + expect(webcpp::crypto::test::fuzz_wipes(0).not_zero == 0, + "a wipe of the input's text left a byte not zero"); std::span const kept = input.first(std::min(input.size(), format_type::maximum_bytes)); @@ -146,5 +149,7 @@ extern "C" int LLVMFuzzerTestOneInput(std::uint8_t const* data, std::size_t size expect(decoded.has_value(), "the text of the input's first bytes does not decode"); expect(std::ranges::equal(std::span{payload}.first(*decoded), kept), "the text of the input's first bytes decodes to other bytes"); + expect(webcpp::crypto::test::fuzz_wipes(0).not_zero == 0, + "a wipe of the first bytes' text left a byte not zero"); return 0; } From 7f2e4b5033f6354b61f16e045a99b68e75ac51cf Mon Sep 17 00:00:00 2001 From: R Date: Tue, 1 Dec 2026 04:13:58 -0300 Subject: [PATCH 28/81] crypto: Ed25519's formats are codecs value codecs, raw, spki, pkcs8 and pem over them; encode_spki, decode_spki, encode_pkcs8, decode_pkcs8 and their sizes go --- doc/ed25519.adoc | 12 + doc/formats.adoc | 99 +- doc/generated/backends-ed25519_formats.adoc | 4 +- doc/generated/backends-pem.adoc | 2 +- doc/generated/backends-x25519_formats.adoc | 2 +- doc/generated/defaults.adoc | 2 +- doc/generated/matrix.adoc | 10 +- doc/generated/messages.adoc | 20 + doc/generated/use-cases.adoc | 2 +- doc/llms.txt | 16 +- doc/tables/crypto.json | 20 +- example/key_formats.cpp | 38 +- include/webcpp/crypto/curves/ed25519.hpp | 75 +- .../webcpp/crypto/curves/ed25519/formats.hpp | 605 ++++++++++-- include/webcpp/crypto/curves/p256.hpp | 21 + include/webcpp/crypto/curves/secp256k1.hpp | 27 + include/webcpp/crypto/curves/x25519.hpp | 13 + include/webcpp/crypto/detail/curve_of.hpp | 46 + include/webcpp/crypto/detail/signature.hpp | 26 + include/webcpp/crypto/formats.hpp | 65 +- test/Jamfile | 10 +- test/allocation_sodium_test.cpp | 52 +- test/constant_time/paths.hpp | 59 +- test/crypto_openssl_alone_test.cpp | 4 +- test/formats_25519_openssl_oracle_test.cpp | 113 ++- test/formats_25519_sodium_test.cpp | 581 ----------- test/formats_25519_webcrypto_oracle_test.cpp | 74 +- test/formats_ed25519_sodium_test.cpp | 899 ++++++++++++++++++ test/fuzz/Jamfile | 23 +- test/fuzz/corpus/ed25519_pem_pkcs8/empty | 0 test/fuzz/corpus/ed25519_pem_pkcs8/explained | 6 + .../corpus/ed25519_pem_pkcs8/public_label | 3 + .../corpus/ed25519_pem_pkcs8/rfc8410_private | 3 + .../ed25519_pem_pkcs8/rfc8410_private_crlf | 3 + .../rfc8410_private_no_final_line_feed | 3 + .../ed25519_pem_pkcs8/rfc8410_private_v2 | 5 + test/fuzz/corpus/ed25519_pem_pkcs8/version_2 | 4 + test/fuzz/corpus/ed25519_pem_spki/empty | 0 test/fuzz/corpus/ed25519_pem_spki/explained | 4 + .../corpus/ed25519_pem_spki/private_label | 3 + .../corpus/ed25519_pem_spki/rfc8410_public | 3 + .../ed25519_pem_spki/rfc8410_public_crlf | 3 + .../rfc8410_public_no_final_line_feed | 3 + .../ed25519_pem_spki/wycheproof_public_key_00 | 3 + test/fuzz/corpus/ed25519_pkcs8/empty | 0 .../corpus/ed25519_pkcs8/marked_version_2 | 1 + .../fuzz/corpus/ed25519_pkcs8/rfc8410_private | Bin 0 -> 48 bytes .../corpus/ed25519_pkcs8/rfc8410_private_v2 | Bin 0 -> 116 bytes test/fuzz/corpus/ed25519_pkcs8/trailing_byte | Bin 0 -> 49 bytes test/fuzz/corpus/ed25519_pkcs8/version_2 | Bin 0 -> 83 bytes test/fuzz/corpus/ed25519_pkcs8/x25519_oid | Bin 0 -> 48 bytes test/fuzz/corpus/ed25519_raw/empty | 0 test/fuzz/corpus/ed25519_raw/one_byte_long | Bin 0 -> 33 bytes test/fuzz/corpus/ed25519_raw/one_byte_short | 1 + .../corpus/ed25519_raw/rfc8410_public_key | 1 + test/fuzz/corpus/ed25519_raw/rfc8410_seed | 1 + .../ed25519_raw/wycheproof_public_key_00 | 1 + .../ed25519_raw/wycheproof_public_key_01 | 1 + .../corpus/ed25519_raw/wycheproof_signature | 1 + test/fuzz/corpus/ed25519_spki/empty | 0 .../fuzz/corpus/ed25519_spki/long_form_length | Bin 0 -> 45 bytes test/fuzz/corpus/ed25519_spki/rfc8410_public | Bin 0 -> 44 bytes test/fuzz/corpus/ed25519_spki/trailing_byte | Bin 0 -> 45 bytes .../ed25519_spki/wycheproof_public_key_00 | Bin 0 -> 44 bytes .../ed25519_spki/wycheproof_public_key_01 | Bin 0 -> 44 bytes test/fuzz/corpus/ed25519_spki/x25519_oid | Bin 0 -> 44 bytes test/fuzz/ed25519_pem_pkcs8_fuzz.cpp | 29 + test/fuzz/ed25519_pem_spki_fuzz.cpp | 28 + test/fuzz/ed25519_pkcs8_fuzz.cpp | 29 + test/fuzz/ed25519_raw_fuzz.cpp | 31 + test/fuzz/ed25519_spki_fuzz.cpp | 28 + test/messages/Jamfile | 2 + test/messages/der_on_ed25519/Jamfile | 14 + .../der_on_ed25519/der_on_ed25519.cpp | 24 + .../ed25519_formats_header_missing/Jamfile | 14 + .../ed25519_formats_header_missing.cpp | 32 + test/msvc/Jamfile | 2 + test/msvc/der_on_ed25519/Jamfile | 10 + test/msvc/der_on_ed25519/app.cpp | 17 + .../ed25519_formats_header_missing/Jamfile | 10 + .../ed25519_formats_header_missing/app.cpp | 25 + test/oracle_25519_test.cpp | 28 +- test/support/format_checks.hpp | 18 +- test/timing_coverage_sodium_test.cpp | 107 ++- test/user_globals_test.cpp | 44 +- 85 files changed, 2556 insertions(+), 909 deletions(-) create mode 100644 include/webcpp/crypto/detail/curve_of.hpp delete mode 100644 test/formats_25519_sodium_test.cpp create mode 100644 test/formats_ed25519_sodium_test.cpp create mode 100644 test/fuzz/corpus/ed25519_pem_pkcs8/empty create mode 100644 test/fuzz/corpus/ed25519_pem_pkcs8/explained create mode 100644 test/fuzz/corpus/ed25519_pem_pkcs8/public_label create mode 100644 test/fuzz/corpus/ed25519_pem_pkcs8/rfc8410_private create mode 100644 test/fuzz/corpus/ed25519_pem_pkcs8/rfc8410_private_crlf create mode 100644 test/fuzz/corpus/ed25519_pem_pkcs8/rfc8410_private_no_final_line_feed create mode 100644 test/fuzz/corpus/ed25519_pem_pkcs8/rfc8410_private_v2 create mode 100644 test/fuzz/corpus/ed25519_pem_pkcs8/version_2 create mode 100644 test/fuzz/corpus/ed25519_pem_spki/empty create mode 100644 test/fuzz/corpus/ed25519_pem_spki/explained create mode 100644 test/fuzz/corpus/ed25519_pem_spki/private_label create mode 100644 test/fuzz/corpus/ed25519_pem_spki/rfc8410_public create mode 100644 test/fuzz/corpus/ed25519_pem_spki/rfc8410_public_crlf create mode 100644 test/fuzz/corpus/ed25519_pem_spki/rfc8410_public_no_final_line_feed create mode 100644 test/fuzz/corpus/ed25519_pem_spki/wycheproof_public_key_00 create mode 100644 test/fuzz/corpus/ed25519_pkcs8/empty create mode 100644 test/fuzz/corpus/ed25519_pkcs8/marked_version_2 create mode 100644 test/fuzz/corpus/ed25519_pkcs8/rfc8410_private create mode 100644 test/fuzz/corpus/ed25519_pkcs8/rfc8410_private_v2 create mode 100644 test/fuzz/corpus/ed25519_pkcs8/trailing_byte create mode 100644 test/fuzz/corpus/ed25519_pkcs8/version_2 create mode 100644 test/fuzz/corpus/ed25519_pkcs8/x25519_oid create mode 100644 test/fuzz/corpus/ed25519_raw/empty create mode 100644 test/fuzz/corpus/ed25519_raw/one_byte_long create mode 100644 test/fuzz/corpus/ed25519_raw/one_byte_short create mode 100644 test/fuzz/corpus/ed25519_raw/rfc8410_public_key create mode 100644 test/fuzz/corpus/ed25519_raw/rfc8410_seed create mode 100644 test/fuzz/corpus/ed25519_raw/wycheproof_public_key_00 create mode 100644 test/fuzz/corpus/ed25519_raw/wycheproof_public_key_01 create mode 100644 test/fuzz/corpus/ed25519_raw/wycheproof_signature create mode 100644 test/fuzz/corpus/ed25519_spki/empty create mode 100644 test/fuzz/corpus/ed25519_spki/long_form_length create mode 100644 test/fuzz/corpus/ed25519_spki/rfc8410_public create mode 100644 test/fuzz/corpus/ed25519_spki/trailing_byte create mode 100644 test/fuzz/corpus/ed25519_spki/wycheproof_public_key_00 create mode 100644 test/fuzz/corpus/ed25519_spki/wycheproof_public_key_01 create mode 100644 test/fuzz/corpus/ed25519_spki/x25519_oid create mode 100644 test/fuzz/ed25519_pem_pkcs8_fuzz.cpp create mode 100644 test/fuzz/ed25519_pem_spki_fuzz.cpp create mode 100644 test/fuzz/ed25519_pkcs8_fuzz.cpp create mode 100644 test/fuzz/ed25519_raw_fuzz.cpp create mode 100644 test/fuzz/ed25519_spki_fuzz.cpp create mode 100644 test/messages/der_on_ed25519/Jamfile create mode 100644 test/messages/der_on_ed25519/der_on_ed25519.cpp create mode 100644 test/messages/ed25519_formats_header_missing/Jamfile create mode 100644 test/messages/ed25519_formats_header_missing/ed25519_formats_header_missing.cpp create mode 100644 test/msvc/der_on_ed25519/Jamfile create mode 100644 test/msvc/der_on_ed25519/app.cpp create mode 100644 test/msvc/ed25519_formats_header_missing/Jamfile create mode 100644 test/msvc/ed25519_formats_header_missing/app.cpp diff --git a/doc/ed25519.adoc b/doc/ed25519.adoc index dde1cd0b..ae89bfb8 100644 --- a/doc/ed25519.adoc +++ b/doc/ed25519.adoc @@ -39,6 +39,18 @@ 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. +`` gives the three types their +formats (<>), synchronous on every backend: +`crypto::encode(crypto::formats::spki, public_key)` and +`crypto::decode(crypto::formats::spki, bytes)`, or the members +`public_key.encode(format)` and `public_key::decode(format, input)`, with +`formats::raw`, `formats::spki` and `formats::pem(formats::spki)` for a public +key; `formats::raw` (the seed, secret), `formats::pkcs8` and +`formats::pem(formats::pkcs8)` for a key pair, whose results are secret and +wiped; and `formats::raw` for a signature, which has no DER form. Without that +header, a member's call is the compiler's "deduced return type used before it +is defined", and `crypto::encode` names the header to include. + Each operation has its four forms, the member and its free form, synchronous and asynchronous, with the same work, errors and refusals (<>); `public_key::from_bytes(bytes)` and diff --git a/doc/formats.adoc b/doc/formats.adoc index 69e828d3..71a83a13 100644 --- a/doc/formats.adoc +++ b/doc/formats.adoc @@ -51,36 +51,69 @@ that carries the curve inside its ECPrivateKey, the form the W3C text gives WebCrypto's `exportKey("pkcs8")`, are refused; `pem` armours both (<>). -`` gives, in -`webcpp::crypto::curves::ed25519`, `encode_spki(public_key, out)`, -`decode_spki(spki)`, `encode_pkcs8(keypair, out)` and `decode_pkcs8(pkcs8)`, -which makes the key pair at once; `` -gives the same four in `webcpp::crypto::curves::x25519`, where a PKCS#8 -holds a 32-byte secret key and `decode_pkcs8` gives it as a `secure::secret<32>`, which -wipes itself. `max_spki_size` and `max_pkcs8_size`, 44 and 48, size the -caller's buffers. `` gives, in `webcpp::crypto::pem`, -`armour(label, der, out)` and `unarmour(label, text, out)`, with the labels -`public_key_label` and `private_key_label`, and `armoured_size`, the text's -size. Each writes into the caller's buffer and returns how many bytes or -characters it wrote; on a refusal it writes nothing. All run on libsodium -(`/third_party//sodium`, or the families' aliases `/webcpp/crypto//ed25519-default`, -`/webcpp/crypto//x25519-default` and `/webcpp/crypto//pem-default`), whose base64 runs -in a time that does not depend on the bytes, those of a private key included -(link:https://doc.libsodium.org/helpers#base64-encoding-decoding[libsodium's documentation]). +`` registers Ed25519's formats into +webcpp::codecs. `crypto::encode(format, value)` and +`crypto::decode(format, input)`, in `webcpp::crypto`, take the formats of +`webcpp::crypto::formats`: a public key's `formats::raw`, its 32 bytes, as +WebCrypto's `exportKey("raw")` writes them, `formats::spki`, 44 bytes, and +`formats::pem(formats::spki)`, 113 characters; a key pair's `formats::raw`, +its seed (`secret()` and `from_secret` under the format's name), +`formats::pkcs8`, 48 bytes, and `formats::pem(formats::pkcs8)`, 119 +characters; and a signature's `formats::raw`, its 64 bytes. `encode` returns +a result held on the stack, `codecs::bytes` or `codecs::text`, read +with `view()`; a key pair's formats hold the seed, and give +`codecs::secret_bytes` and `codecs::secret_text`, which are move-only and +wiped when destroyed or moved from. `crypto::encode(format, value, output)` +writes into the caller's span instead and returns the size written, or +`output_too_small` with nothing written; a token of codecs', such as +`codecs::tokens::append_to(container)`, takes the encoding where the program +wants it. Each type has the same calls as members: +`public_key.encode(formats::spki)`, +`ed25519::keypair::decode(formats::pem(formats::pkcs8), text)`. The calls are +codecs' own (`codecs::encode` and `codecs::decode` give the same bytes); +crypto's check them first, so that a pair the type does not have stops the +build with a sentence that says why: `crypto::encode(formats::der, signature)` +says an Ed25519 signature's 64 bytes are the signature, and a call without the +formats header names the header to include. Nothing allocates: a PEM is +decoded in place, its DER held in a buffer of the format's decode bound, wiped +after a PKCS#8. A public key, which names no backend, is encoded and decoded +on the family's default, libsodium on every target +(`/webcpp/crypto//ed25519-default` links it). + +`` gives, in +`webcpp::crypto::curves::x25519`, `encode_spki(public_key, out)`, +`decode_spki(spki)`, `encode_pkcs8(secret_key, out)` and `decode_pkcs8(pkcs8)`, +where a PKCS#8 holds a 32-byte secret key and `decode_pkcs8` gives it as a +`secure::secret<32>`, which wipes itself. `max_spki_size` and `max_pkcs8_size`, +44 and 48, size the caller's buffers. `` gives, in +`webcpp::crypto::pem`, `armour(label, der, out)` and `unarmour(label, text, out)`, +with the labels `public_key_label` and `private_key_label`, and +`armoured_size`, the text's size. Each writes into the caller's buffer and +returns how many bytes or characters it wrote; on a refusal it writes nothing. +They run on libsodium (`/third_party//sodium`, or the families' aliases +`/webcpp/crypto//x25519-default` and `/webcpp/crypto//pem-default`), whose +base64 runs in a time that does not depend on the bytes, those of a private key +included +(link:https://doc.libsodium.org/helpers#base64-encoding-decoding[libsodium's documentation]); +`formats::pem`'s base64 is codecs', constant time on every call. *Strict decoding.* A decoder accepts an input only if encoding what it decoded gives the same bytes (design D30): the one form that OpenSSL and WebCrypto write, and nothing else. It refuses with `invalid_encoding` another curve's identifier (an Ed25519 key given to X25519's decoder), a byte left -over, a length in BER's long form where DER requires the short one, -PKCS#8 version 2, which carries the public key beside the seed, attributes, -and PEM with another label than the expected, lines of another length than 64, -carriage returns, text before or after the key, or base64 that is not the one -encoding of its bytes. A key that one library accepts and another refuses -lets two programs that should agree on a key disagree on it; one form, and -one verdict on every backend, closes that door. A program that receives -version 2, or PEM with Windows line ends, converts it with OpenSSL's -`openssl pkey` first. +over, a length in BER's long form where DER requires the short one, PKCS#8 +version 2, which carries the public key beside the seed, and attributes. A +key that one library accepts and another refuses lets two programs that +should agree on a key disagree on it; one form, and one verdict on every +backend, closes that door. A program that receives version 2 converts it with +OpenSSL's `openssl pkey` first. `formats::pem` reads PEM as Windows and +OpenSSL's tools write it: lines ended by a line feed or by a carriage return +and a line feed, the last line's end optional; it refuses another label than +the format's, text before BEGIN or after END (what `openssl pkey -text` prints +before the key) with `codecs::error::invalid_prefix`, lines of another length +than 64 and base64 that is not the one encoding of its bytes with codecs' +errors. `pem::unarmour` is stricter still: it refuses carriage returns and a +text without its final line feed too, with `invalid_encoding`. include::generated/backends-ed25519_formats.adoc[] @@ -88,9 +121,10 @@ include::generated/backends-x25519_formats.adoc[] include::generated/backends-pem.adoc[] -*Example.* RFC 8410's own Ed25519 key pair read from PEM, its public key written -back as PEM, which is the RFC's to the character, and a signature; an X25519 -public key's SPKI; and the RFC's version 2 of the same private key refused: +*Example.* RFC 8410's own Ed25519 key pair read from PEM with `crypto::decode`, +its public key written back as PEM with `crypto::encode`, which is the RFC's to +the character, and a signature; an X25519 public key's SPKI; and the RFC's +version 2 of the same private key refused: [source,cpp] ---- @@ -104,10 +138,11 @@ include::{examples}/key_formats.expected[] *Pitfalls.* -* A PKCS#8, as DER or as PEM, is the secret key: kept in a `secure::secret`, as the -example does, it is wiped when it goes; written to a file or a database, it is -sealed first, as any secret at rest (<>). -* `decode_spki` checks the form, not the key: `crypto::verify` with +* A PKCS#8, as DER or as PEM, is the secret key: kept in the secret result +`crypto::encode` gives, or decoded in place as the example does, it is wiped +when it goes; written to a file or a database, it is sealed first, as any +secret at rest (<>). +* Decoding an SPKI checks the form, not the key: `crypto::verify` with `crypto::signing_schemes::eddsa` refuses a public key that is not a point of the curve, and X25519's `agree` one of low order (`weak_public_key`). A key read from outside is used through those, which check it. diff --git a/doc/generated/backends-ed25519_formats.adoc b/doc/generated/backends-ed25519_formats.adoc index fcc9876c..cad5d0c5 100644 --- a/doc/generated/backends-ed25519_formats.adoc +++ b/doc/generated/backends-ed25519_formats.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::encode_spki+`, `+decode_spki+`, `+encode_pkcs8+`, `+decode_pkcs8+`, from the test programs that run it: +The backends of `+crypto::encode+`, `+crypto::decode+`, `+curves::ed25519::public_key::encode+`, `+curves::ed25519::keypair::decode+`, from the test programs that run it: [cols="1,2,2,4",options="header"] |=== @@ -16,7 +16,7 @@ The backends of `+curves::ed25519::encode_spki+`, `+decode_spki+`, `+encode_pkcs |libsodium |`+/third_party//sodium+` |`++` -|native, wasip2, wasip3, emscripten (tested by `+formats_25519_sodium+`, `+formats_25519_openssl_oracle+`, `+formats_25519_webcrypto_oracle+`, `+allocation_sodium+`) +|native, wasip2, wasip3, emscripten (tested by `+formats_ed25519_sodium+`, `+formats_25519_openssl_oracle+`, `+formats_25519_webcrypto_oracle+`, `+allocation_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-pem.adoc b/doc/generated/backends-pem.adoc index f74e7342..e6b519bd 100644 --- a/doc/generated/backends-pem.adoc +++ b/doc/generated/backends-pem.adoc @@ -16,7 +16,7 @@ The backends of `+pem::armour+`, `+pem::unarmour+`, from the test programs that |libsodium |`+/third_party//sodium+` |`++` -|native, wasip2, wasip3, emscripten (tested by `+formats_25519_sodium+`, `+formats_25519_openssl_oracle+`, `+allocation_sodium+`, `+p256_formats_bearssl+`) +|native, wasip2, wasip3, emscripten (tested by `+formats_ed25519_sodium+`, `+formats_25519_openssl_oracle+`, `+allocation_sodium+`, `+p256_formats_bearssl+`) |=== 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-x25519_formats.adoc b/doc/generated/backends-x25519_formats.adoc index 009cdad7..e9d4890d 100644 --- a/doc/generated/backends-x25519_formats.adoc +++ b/doc/generated/backends-x25519_formats.adoc @@ -16,7 +16,7 @@ The backends of `+curves::x25519::encode_spki+`, `+decode_spki+`, `+encode_pkcs8 |libsodium |`+/third_party//sodium+` |`++` -|native, wasip2, wasip3, emscripten (tested by `+formats_25519_sodium+`, `+formats_25519_openssl_oracle+`, `+formats_25519_webcrypto_oracle+`, `+allocation_sodium+`) +|native, wasip2, wasip3, emscripten (tested by `+formats_ed25519_sodium+`, `+formats_25519_openssl_oracle+`, `+formats_25519_webcrypto_oracle+`, `+allocation_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/defaults.adoc b/doc/generated/defaults.adoc index 1748f80e..0d21489d 100644 --- a/doc/generated/defaults.adoc +++ b/doc/generated/defaults.adoc @@ -81,7 +81,7 @@ |native, wasip2, wasip3, emscripten |libsodium |the only backend in this version, on every target; its base64 runs in a time that does not depend on the bytes, a private key's in a PKCS#8 (link:https://doc.libsodium.org/helpers#base64-encoding-decoding[libsodium's documentation, helpers: base64 encoding and decoding]) -|`+formats_25519_sodium+`, `+default_backend_none_linked+` +|`+formats_ed25519_sodium+`, `+default_backend_none_linked+` |ChaCha20-Poly1305 |native, wasip2, wasip3, emscripten diff --git a/doc/generated/matrix.adoc b/doc/generated/matrix.adoc index e652223a..97f9d307 100644 --- a/doc/generated/matrix.adoc +++ b/doc/generated/matrix.adoc @@ -151,20 +151,20 @@ |native, wasip2, wasip3, emscripten |`+x25519_sodium+`, `+oracle_25519+` -|`+curves::ed25519::encode_spki+`, `+decode_spki+`, `+encode_pkcs8+`, `+decode_pkcs8+` +|`+crypto::encode+`, `+crypto::decode+`, `+curves::ed25519::public_key::encode+`, `+curves::ed25519::keypair::decode+` |libsodium |native, wasip2, wasip3, emscripten -|`+formats_25519_sodium+`, `+formats_25519_openssl_oracle+`, `+formats_25519_webcrypto_oracle+`, `+allocation_sodium+` +|`+formats_ed25519_sodium+`, `+formats_25519_openssl_oracle+`, `+formats_25519_webcrypto_oracle+`, `+allocation_sodium+` |`+curves::x25519::encode_spki+`, `+decode_spki+`, `+encode_pkcs8+`, `+decode_pkcs8+` |libsodium |native, wasip2, wasip3, emscripten -|`+formats_25519_sodium+`, `+formats_25519_openssl_oracle+`, `+formats_25519_webcrypto_oracle+`, `+allocation_sodium+` +|`+formats_ed25519_sodium+`, `+formats_25519_openssl_oracle+`, `+formats_25519_webcrypto_oracle+`, `+allocation_sodium+` |`+pem::armour+`, `+pem::unarmour+` |libsodium |native, wasip2, wasip3, emscripten -|`+formats_25519_sodium+`, `+formats_25519_openssl_oracle+`, `+allocation_sodium+`, `+p256_formats_bearssl+` +|`+formats_ed25519_sodium+`, `+formats_25519_openssl_oracle+`, `+allocation_sodium+`, `+p256_formats_bearssl+` |`+key_exchange::kx_keypair+` |libsodium @@ -438,7 +438,7 @@ The same, by target: the backends each operation runs on. |libsodium |libsodium -|`+curves::ed25519::encode_spki+`, `+decode_spki+`, `+encode_pkcs8+`, `+decode_pkcs8+` +|`+crypto::encode+`, `+crypto::decode+`, `+curves::ed25519::public_key::encode+`, `+curves::ed25519::keypair::decode+` |libsodium |libsodium |libsodium diff --git a/doc/generated/messages.adoc b/doc/generated/messages.adoc index ae03d4b6..c4efc191 100644 --- a/doc/generated/messages.adoc +++ b/doc/generated/messages.adoc @@ -329,12 +329,24 @@ The fix: Remove the define, and name `+gcm>+` where th The fix: Remove the define, and name `+gcm>+` where the program wants BearSSL. +|`+der_on_ed25519+` +|native, wasip2, wasip3 +|`+webcpp::crypto: Ed25519 and BIP340 signatures have no DER form; their 64 bytes are the signature+` + +The fix: Encode an Ed25519 signature with `+crypto::formats::raw+`, or its member `+signature.encode(crypto::formats::raw)+`: its 64 bytes are the signature, and it has no DER form. + |`+ed25519_default_not_linked+` |native, wasip2, wasip3 |`+webcpp::crypto: Ed25519's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//ed25519-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//ed25519-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)+` The fix: Add `+/webcpp/crypto//ed25519-default+`, which links `+/third_party//sodium+` on every target. +|`+ed25519_formats_header_missing+` +|native, wasip2, wasip3 +|`+webcpp::crypto: include to encode or decode this type+` + +The fix: Include `++`, which registers Ed25519's formats, beside `++`. + |`+ed25519_on_bearssl+` |native, wasip2, wasip3 |`+webcpp::crypto: bearssl has no Ed25519. The backends that have it: sodium (native, wasip2, wasip3, emscripten).+` @@ -1822,10 +1834,18 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |Remove the define, and name `+gcm>+` where the program wants BearSSL. +|`+der_on_ed25519+` +|the compile +|Encode an Ed25519 signature with `+crypto::formats::raw+`, or its member `+signature.encode(crypto::formats::raw)+`: its 64 bytes are the signature, and it has no DER form. + |`+ed25519_default_not_linked+` |the compile |Add `+/webcpp/crypto//ed25519-default+`, which links `+/third_party//sodium+` on every target. +|`+ed25519_formats_header_missing+` +|the compile +|Include `++`, which registers Ed25519's formats, beside `++`. + |`+ed25519_on_bearssl+` |the compile |Leave the backend out, as in `+curves::ed25519::keypair+`, or name `+backends::sodium+`, and add `+/third_party//sodium+`. diff --git a/doc/generated/use-cases.adoc b/doc/generated/use-cases.adoc index a407310e..e2e9abc0 100644 --- a/doc/generated/use-cases.adoc +++ b/doc/generated/use-cases.adoc @@ -215,7 +215,7 @@ |<> |Export or import an Ed25519 or X25519 key in the standard forms OpenSSL and WebCrypto use: SPKI and PKCS#8 (RFC 8410), as DER or PEM text -|In `+curves+`: `+ed25519::encode_spki+`, `+decode_spki+`, `+encode_pkcs8+`, `+decode_pkcs8+`, the same in `+x25519+`; `+webcpp::crypto::pem::armour+`, `+unarmour+` +|In `+curves+`: Ed25519's `+crypto::encode+` and `+crypto::decode+` with `+crypto::formats::spki+`, `+pkcs8+` and `+pem+`; X25519's `+x25519::encode_spki+`, `+decode_spki+`, `+encode_pkcs8+`, `+decode_pkcs8+`; `+webcpp::crypto::pem::armour+`, `+unarmour+` |libsodium |`+/webcpp/crypto//crypto+` + `+/webcpp/crypto//ed25519-default+` + diff --git a/doc/llms.txt b/doc/llms.txt index a88903ec..1b3281a8 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -162,11 +162,13 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [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. - - encode_pkcs8: Writes a key pair's PKCS#8 (RFC 8410, version 1: the seed, 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 key pair of a PKCS#8, refused unless it is exactly RFC 8410's version 1 form: the 16 bytes of Ed25519's prefix, then the seed, and nothing after. +- [crypto::encode, crypto::decode, curves::ed25519::public_key::encode, curves::ed25519::keypair::decode](https://webcpporg.github.io/libs/crypto/#crypto-key-formats): Ed25519's formats as codecs value codecs: a public key's `formats::raw` (32 bytes), `formats::spki` (RFC 8410, 44 bytes) and `formats::pem(formats::spki)`; a key pair's `formats::raw` (its seed), `formats::pkcs8` (RFC 8410's version 1, 48 bytes) and `formats::pem(formats::pkcs8)`, secret; a signature's `formats::raw` (64 bytes); the forms OpenSSL and WebCrypto write, the DER 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: Encodes the key in `format`, as `crypto::encode(format, key)`: `formats::raw`, its 32 bytes, `formats::spki`, RFC 8410's 44 bytes, or `formats::pem(formats::spki)`, their PEM. + - decode: Decodes a public key from `input` in `format`, as `crypto::decode(format, input)`. + - encode: Encodes the key pair in `format`, as `crypto::encode(format, key_pair)`: `formats::raw`, its seed (`secret()` under the format's name), `formats::pkcs8`, RFC 8410's 48 bytes, or `formats::pem(formats::pkcs8)`, their PEM; each result is secret. + - decode: Decodes a key pair from `input` in `format`, as `crypto::decode(format, input)`. + - encode: Encodes the signature in `format`, as `crypto::encode(format, signature)`: `formats::raw`, its bytes, and, for an ECDSA signature, `formats::der`. + - decode: Decodes a signature from `input` in `format`, as `crypto::decode(format, input)`. - [curves::x25519::encode_spki, decode_spki, encode_pkcs8, decode_pkcs8](https://webcpporg.github.io/libs/crypto/#crypto-key-formats): RFC 8410's SPKI of an X25519 public key (44 bytes) and PKCS#8 of a secret key (version 1, 48 bytes), the forms OpenSSL and WebCrypto write, decoded strictly into a `secure::secret<32>`: 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 X25519's prefix, then the key, and nothing after. @@ -380,7 +382,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [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::signing_schemes::eddsa, message)`, `keypair::sign(crypto::signing_schemes::eddsa_prehashed, crypto::signing_schemes::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. +- [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's `crypto::encode` and `crypto::decode` with `crypto::formats::spki`, `pkcs8` and `pem`; X25519's `x25519::encode_spki`, `decode_spki`, `encode_pkcs8`, `decode_pkcs8`; `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<>`: `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. @@ -411,7 +413,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - 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::signing_schemes::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_formats.cpp: Reads RFC 8410's Ed25519 private key in PEM (section 10.3), as OpenSSL or WebCrypto export it, with crypto::decode, writes its public key as PEM with crypto::encode, 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. diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 0b929b8e..d4107a81 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -501,14 +501,14 @@ { "id": "ed25519_formats", "family": "ed25519", - "free": true, - "functions": ["encode_spki", "decode_spki", "encode_pkcs8", "decode_pkcs8"], + "functions": ["public_key::encode", "public_key::decode", "basic_keypair::encode", "basic_keypair::decode", "basic_signature::encode", "basic_signature::decode"], + "function_headers": {"public_key::encode": "", "public_key::decode": "", "basic_keypair::encode": "", "basic_keypair::decode": "", "basic_signature::encode": "", "basic_signature::decode": ""}, "namespace": "curves", - "api": "curves::ed25519::encode_spki, decode_spki, encode_pkcs8, decode_pkcs8", + "api": "crypto::encode, crypto::decode, curves::ed25519::public_key::encode, curves::ed25519::keypair::decode", "header": "", - "what": "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`.", + "what": "Ed25519's formats as codecs value codecs: a public key's `formats::raw` (32 bytes), `formats::spki` (RFC 8410, 44 bytes) and `formats::pem(formats::spki)`; a key pair's `formats::raw` (its seed), `formats::pkcs8` (RFC 8410's version 1, 48 bytes) and `formats::pem(formats::pkcs8)`, secret; a signature's `formats::raw` (64 bytes); the forms OpenSSL and WebCrypto write, the DER decoded strictly: any other bytes are `invalid_encoding`.", "section": "crypto-key-formats", - "backends": {"sodium": {"tests": ["formats_25519_sodium", "formats_25519_openssl_oracle", "formats_25519_webcrypto_oracle", "allocation_sodium"]}} + "backends": {"sodium": {"tests": ["formats_ed25519_sodium", "formats_25519_openssl_oracle", "formats_25519_webcrypto_oracle", "allocation_sodium"]}} }, { "id": "x25519_formats", @@ -520,7 +520,7 @@ "header": "", "what": "RFC 8410's SPKI of an X25519 public key (44 bytes) and PKCS#8 of a secret key (version 1, 48 bytes), the forms OpenSSL and WebCrypto write, decoded strictly into a `secure::secret<32>`: any other bytes are `invalid_encoding`.", "section": "crypto-key-formats", - "backends": {"sodium": {"tests": ["formats_25519_sodium", "formats_25519_openssl_oracle", "formats_25519_webcrypto_oracle", "allocation_sodium"]}} + "backends": {"sodium": {"tests": ["formats_ed25519_sodium", "formats_25519_openssl_oracle", "formats_25519_webcrypto_oracle", "allocation_sodium"]}} }, { "id": "pem", @@ -532,7 +532,7 @@ "header": "", "what": "PEM (RFC 7468): DER as base64 between `-----BEGIN