diff --git a/doc/backends.adoc b/doc/backends.adoc index a171a07..3d618fc 100644 --- a/doc/backends.adoc +++ b/doc/backends.adoc @@ -16,13 +16,114 @@ that target, and refused where a message test stops it. The data and the tables are regenerated, and checked by the documentation's build, at every change of a test or a pin. -A program asks the same table in {cpp}: `supports_v`, in -``, is `true` exactly where the table says that -the backend has the algorithm on the target being compiled, and needs neither -the backend's header nor its library, so that generic code can choose a -backend at compile time. Each algorithm's type names its family and its -algorithm for it (`family_type` and `name_type`, tags of `families` and -`tags`); the test that asserts every cell is generated from the same data. +A program asks the same table in {cpp}, in ``, +which needs neither the backend's header nor its library, so that generic code +can choose a backend at compile time. `supports_v` is +`true` exactly where the table says that the backend has the algorithm's use +operations on the target being compiled: sign and verify, agree, seal and +open, or the algorithm's one operation. The operations on keys, making, +importing and exporting them, are answered by `supports_capability_v` +(<>). Each algorithm's type +names its family and its algorithm for it (`family_type` and `name_type`, tags +of `families` and `tags`); the test that asserts every cell is generated from +the same data. + +[#crypto-backends-capabilities] +=== What a backend has, operation by operation + +A family's cell for a backend is a list of capabilities: making a key from +secret bytes (import), drawing one (generate), its public key (public), its +secret bytes handed out (export), the operations `supports_v` counts (use), and +the operations on public values the family's types need (auxiliary), such as +a P-256 point's check. `supports_capability_v` answers +each, from the same table and with no header either, the capability named by +its tag of `crypto::capabilities`: a program asks +`supports_capability_v` before it calls +`secret()`. A cell may be partial: `supports_v` is `true` for a backend that +signs and verifies but makes no key from secret bytes, and that backend's +`from_secret` stops the build with a message that names the capability it +lacks (<>). Each capability, by its tag of +`crypto::capabilities`, with the backends whose cell has it: + +include::generated/capabilities.adoc[] + +P-256's ECDSA comes in two forms. The digest form +(`capabilities::p256_ecdsa_signing`, `p256_ecdsa_verifying`) signs and +verifies a SHA-256 digest, BearSSL's form; the message form +(`p256_ecdsa_message_signing`, `p256_ecdsa_message_verifying`) takes the +message and hashes it inside the backend, the form WebCrypto's ECDSA has; no +backend crypto ships has the message form yet. A backend has either or both. +`sign` and `verify` of a message work on either: crypto gives the message to +the backend's message form when it has one, and otherwise hashes it and uses +the digest form; the signature is made low S either way, and the verification +policy is checked before the backend sees the signature. A digest given as +`crypto::signing_schemes::prehashed` needs the digest form, so `supports_v` is +`true` when either form is present, and +`supports_capability_v` tells +whether a prehashed digest can be signed. + +[#crypto-backends-opaque] +==== Keys that never leave their backend + +A backend may keep its keys: the secret is a handle inside the backend, as a +hardware token's or the browser's non-extractable key is, and its bytes never +leave it or enter it. `exports_secret_keys_v` says whether a secret +key's bytes leave the backend, and `imports_secret_keys_v` whether +they enter it; both are `true` for every backend crypto ships: + +include::generated/secret-key-traits.adoc[] + +On a backend whose keys stay inside, a program makes its key pairs with +`generate` (or `async_generate`), which draws the key in the backend, and +keeps the key pair object itself, moved where it is needed. What would carry +the secret's bytes stops the build with a message that names the trait, before +any capability: + +* `from_secret` and `async_from_secret`, the bytes entering; +* `secret()`, the bytes leaving; +* a key pair's private formats, `formats::raw`, `formats::pkcs8` and + `formats::pem(formats::pkcs8)`, both ways, the bytes leaving or entering; +* Ed25519's `to_x25519()` of a key pair, whose X25519 secret is computed from + the Ed25519 secret's bytes. + +Everything else works as on any backend: `public_key()`, signing, verifying, +agreeing, the public key's formats. A program written for both kinds asks the +two traits, or `supports_capability_v` of the import and export capabilities, +and takes the other branch at compile time. + +[#crypto-backends-contract] +==== What every backend gives + +Every backend crypto ships keeps the same promises, which the capability +tests, the coverage tests and the lanes check, so that a program sees the same +behaviour whatever backend it names: + +* Each public function sets the data-independent timing of the CPU where it + has it, around the backend's whole work (<>). +* A backend allocates little, and what it allocates is named in its row of + <>. BearSSL, ctaes and libsodium allocate nothing. + OpenSSL allocates a cipher's context at `from_key`, and Poly1305's MAC + context at each call, through its own allocator, or through + `openssl_memory_resource()` when a native program sets + `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE`; its failure is an error value. + libsecp256k1 allocates a key pair's signing context in the + `std::pmr::memory_resource` the program gives `from_secret` or `decode`, the + default resource (the {cpp} heap unless the program replaced it) when none is + named; its failure is the resource's to report. +* Distinct objects may be used on distinct threads at once; one object is + shared only under the program's own synchronization. A backend's one-time + initialization, libsodium's or libsecp256k1's, is done by crypto, once, + safely. +* A key pair's or a cipher's secret is wiped when the object is destroyed or + moved from, and an output that holds a secret is written only on success. +* Errors are error codes: `crypto::error::backend_failure` for a failure the + backend does not explain, and `errc::not_supported` for a capability decided + at run time that the machine lacks. + +How a backend is written is crypto's own: the interfaces between crypto and +its backends are internal, change with crypto's backends, and are documented +for crypto's maintainers alone. A program names a backend crypto ships; it +does not add one. [#crypto-backends-matrix] === Operations, backends and targets diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 249a722..622a2e2 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -24,6 +24,6 @@ of every version are on webcpp's index page. * Added crypto, C-backed primitives on webcpp::secure's guard (DIT on arm64): errors 1 to 22, `+[[nodiscard]]+` results, typed signatures, key pair concepts, factories, WEBCPP_CRYPTO_HAS_THREADS, Asio's asynchronous functions. * Added random_device, the AES block ciphers, ciphers::gcm, per-target defaults, backends::bearssl (AES-GCM, ChaCha20-Poly1305, curves::p256 keys, low-S ECDSA, agree), backends::openssl and backends::ctaes. * Added curves::secp256k1 (ECDSA, recoverable ECDSA, BIP 340 Schnorr, agree, tweaks, ElligatorSwift, MuSig2, silent payments), and curves::ed25519 and curves::x25519 on libsodium, Ed25519's verification canonical. -* Added public_key_encryption::hpke, RFC 9180's HPKE on X25519 or P-256, HKDF, and AES-GCM or ChaCha20-Poly1305. +* Added public_key_encryption::hpke (RFC 9180's HPKE on X25519 or P-256, HKDF, AES-GCM or ChaCha20-Poly1305), `supports_capability_v`, the secret-key traits and P-256's message-form ECDSA. * Added backends::sodium, ChaCha20-Poly1305 AEADs, secretbox, boxes, sealed boxes, kx_keypair; raw ciphers::chacha20 (unauthenticated_encryption, also BearSSL and OpenSSL) and authenticators::poly1305 (single_use_key_authentication, also OpenSSL); the page: chapters, generated tables, Jamfiles, messages, llms.txt, measurements. // end::unreleased[] diff --git a/doc/choosing_backend.adoc b/doc/choosing_backend.adoc index 423a95e..9157b5d 100644 --- a/doc/choosing_backend.adoc +++ b/doc/choosing_backend.adoc @@ -55,10 +55,13 @@ A program that wants another backend than the default names it as the type's last template argument and links its library, as `ciphers::chacha20_poly1305` with `/third_party//bearssl`, or `ciphers::gcm>` on MSVC. The backend -must have the family on the target being compiled, which -`supports_v` tells at compile time; a backend that lacks -it, or that the program does not link, stops the build with a message that -says what to do (<>). Every backend of a family gives +must have the family's operations on the target being compiled: +`supports_v` tells at compile time whether it has the use +operations, and `supports_capability_v` whether it has +each capability beside them, such as importing or exporting a key +(<>); a backend that lacks one, or that the +program does not link, stops the build with a message that says what to do +(<>). Every backend of a family gives the same bytes: the agreement tests seal with one and open with another. What differs is what each costs and what it promises of its timing: the <>, its diff --git a/doc/formats.adoc b/doc/formats.adoc index 7ae5c75..65515b6 100644 --- a/doc/formats.adoc +++ b/doc/formats.adoc @@ -425,9 +425,10 @@ tests compare every byte with OpenSSL's natively and on WASI (`formats_25519_webcrypto_oracle`), 200 keys per curve each. A key pair's `formats::raw` is its seed (Ed25519) or its secret key (X25519), `secret()` and `from_secret` under the format's name, and an Ed25519 signature's is its 64 -bytes. A public key, which names no backend, is encoded and decoded on its -family's default, libsodium on every target (`/webcpp/crypto//ed25519-default` -and `/webcpp/crypto//x25519-default` link it); +bytes. A public key, which names no backend, is encoded and decoded with none: +RFC 8410 fixes the bytes around the key, so a program that only reads and +writes public keys links no backend (`rfc8410_no_backend`), and a key pair's +PKCS#8 reads its secret through its own backend; `codecs::decode(formats::spki, bytes)` gives the typed key a key pair's `agree` takes. @@ -461,8 +462,12 @@ door. A program that receives version 2 converts it with OpenSSL's `openssl pkey` first; a later version accepts it on decoding (<>). +include::generated/backends-ed25519_public_formats.adoc[] + include::generated/backends-ed25519_formats.adoc[] +include::generated/backends-x25519_public_formats.adoc[] + include::generated/backends-x25519_formats.adoc[] *Example.* RFC 8410's own Ed25519 key pair read from PEM with `codecs::decode`, diff --git a/doc/generated/backend-facts.adoc b/doc/generated/backend-facts.adoc index 34ee42b..080706c 100644 --- a/doc/generated/backend-facts.adoc +++ b/doc/generated/backend-facts.adoc @@ -63,7 +63,7 @@ The library behind each, and what it costs a program: |OpenSSL 3.5.9's libcrypto, built from source and static |Apache-2.0 |`++` -|`+from_key+` allocates the cipher's context through OpenSSL's own allocator, outside the program's resource, unless a native program sets `+WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE+`, which sends every allocation of OpenSSL's in the process to `+openssl_memory_resource()+`; a message allocates nothing after `+from_key+` +|`+from_key+` allocates the cipher's context, and each of Poly1305's calls makes and frees its MAC context, through OpenSSL's own allocator, outside the program's resource, unless a native program sets `+WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE+`, which sends every allocation of OpenSSL's in the process to `+openssl_memory_resource()+`; a cipher's message allocates nothing after `+from_key+` |ctaes |ctaes as Bitcoin Core v31.1 ships it (`+src/crypto/ctaes+`), built from source diff --git a/doc/generated/backends-ed25519_formats.adoc b/doc/generated/backends-ed25519_formats.adoc index 60eed01..fcb7b7e 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 `+codecs::encode+`, `+codecs::decode+`, `+curves::ed25519::public_key::encode+`, `+curves::ed25519::public_key::decode+`, `+curves::ed25519::keypair::encode+`, `+curves::ed25519::keypair::decode+`, `+curves::ed25519::signature::encode+`, `+curves::ed25519::signature::decode+`, from the test programs that run it: +The backends of `+codecs::encode+`, `+codecs::decode+`, `+curves::ed25519::keypair::encode+`, `+curves::ed25519::keypair::decode+`, `+curves::ed25519::signature::encode+`, `+curves::ed25519::signature::decode+`, from the test programs that run it: [cols="1,2,2,4",options="header"] |=== diff --git a/doc/generated/backends-ed25519_public_formats.adoc b/doc/generated/backends-ed25519_public_formats.adoc new file mode 100644 index 0000000..849ba7a --- /dev/null +++ b/doc/generated/backends-ed25519_public_formats.adoc @@ -0,0 +1,20 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, +// the message tests and the Jamfile fixtures: run it again, never edit this file. + +The backends of `+codecs::encode+`, `+codecs::decode+`, `+curves::ed25519::public_key::encode+`, `+curves::ed25519::public_key::decode+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|no backend +|`+/webcpp/crypto//crypto+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+rfc8410_no_backend+`, `+formats_ed25519_sodium+`, `+formats_25519_openssl_oracle+`, `+formats_25519_webcrypto_oracle+`) +|=== diff --git a/doc/generated/backends-x25519_formats.adoc b/doc/generated/backends-x25519_formats.adoc index e975050..99dbf53 100644 --- a/doc/generated/backends-x25519_formats.adoc +++ b/doc/generated/backends-x25519_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 `+codecs::encode+`, `+codecs::decode+`, `+curves::x25519::public_key::encode+`, `+curves::x25519::public_key::decode+`, `+curves::x25519::keypair::encode+`, `+curves::x25519::keypair::decode+`, from the test programs that run it: +The backends of `+codecs::encode+`, `+codecs::decode+`, `+curves::x25519::keypair::encode+`, `+curves::x25519::keypair::decode+`, from the test programs that run it: [cols="1,2,2,4",options="header"] |=== diff --git a/doc/generated/backends-x25519_public_formats.adoc b/doc/generated/backends-x25519_public_formats.adoc new file mode 100644 index 0000000..d5aefad --- /dev/null +++ b/doc/generated/backends-x25519_public_formats.adoc @@ -0,0 +1,20 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, +// the message tests and the Jamfile fixtures: run it again, never edit this file. + +The backends of `+codecs::encode+`, `+codecs::decode+`, `+curves::x25519::public_key::encode+`, `+curves::x25519::public_key::decode+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|no backend +|`+/webcpp/crypto//crypto+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+rfc8410_no_backend+`, `+formats_x25519_sodium+`, `+formats_25519_openssl_oracle+`, `+formats_25519_webcrypto_oracle+`) +|=== diff --git a/doc/generated/capabilities.adoc b/doc/generated/capabilities.adoc new file mode 100644 index 0000000..abb9b6f --- /dev/null +++ b/doc/generated/capabilities.adoc @@ -0,0 +1,298 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, +// the message tests and the Jamfile fixtures: run it again, never edit this file. + +[cols="2h,3,1,4,3",options="header"] +|=== +|Family |Capability |Kind |What it gives |Backends + +|AES-GCM +|`+gcm+` +|use +|AES-GCM's `+seal+` and `+open+`, with a 128-, 192- or 256-bit key +|BearSSL, OpenSSL + +|AES block cipher +|`+aes_block+` +|use +|the AES block cipher, one 16-byte block with a 128-, 192- or 256-bit key +|OpenSSL, ctaes + +.13+|secp256k1 +|`+secp256k1_import+` +|import +|`+from_secret+` of a secp256k1 key pair +|libsecp256k1 + +|`+secp256k1_generate+` +|generate +|`+generate+` of a secp256k1 key pair drawn by the backend +|none yet + +|`+secp256k1_public+` +|public +|`+public_key()+` of a secp256k1 key pair +|libsecp256k1 + +|`+secp256k1_export+` +|export +|`+secret()+`, `+pkcs8+` and the private PEM of a secp256k1 key pair +|libsecp256k1 + +|`+secp256k1_point+` +|auxiliary +|a secp256k1 public key's points and x-only keys: read, written and compared +|libsecp256k1 + +|`+secp256k1_ecdsa_signing+` +|use +|ECDSA signing with a secp256k1 key pair +|libsecp256k1 + +|`+secp256k1_ecdsa_verifying+` +|use +|ECDSA verifying with a secp256k1 public key +|libsecp256k1 + +|`+secp256k1_ecdsa_forms+` +|auxiliary +|a secp256k1 ECDSA signature's forms: compact, low S and DER +|libsecp256k1 + +|`+secp256k1_schnorr_signing+` +|use +|BIP 340's Schnorr signing with a secp256k1 key pair +|libsecp256k1 + +|`+secp256k1_schnorr_verifying+` +|use +|BIP 340's Schnorr verifying with an x-only public key +|libsecp256k1 + +|`+secp256k1_recoverable+` +|use +|recoverable ECDSA: signing, and the public key recovered from a signature +|libsecp256k1 + +|`+secp256k1_ecdh+` +|use +|`+agree+` of a secp256k1 key pair with a peer's public key +|libsecp256k1 + +|`+secp256k1_tweak+` +|auxiliary +|the tweaks of secp256k1's keys (BIP 32, BIP 341): added to or multiplied into a key, and points combined +|libsecp256k1 + +.8+|Ed25519 +|`+ed25519_import+` +|import +|`+from_secret+` of an Ed25519 key pair, from its seed +|libsodium + +|`+ed25519_generate+` +|generate +|`+generate+` of an Ed25519 key pair drawn by the backend +|none yet + +|`+ed25519_public+` +|public +|`+public_key()+` of an Ed25519 key pair +|libsodium + +|`+ed25519_export+` +|export +|`+secret()+`, `+pkcs8+` and the private PEM of an Ed25519 key pair +|libsodium + +|`+ed25519_signing+` +|use +|Ed25519 signing of a message +|libsodium + +|`+ed25519_verifying+` +|use +|Ed25519 verifying of a message +|libsodium + +|`+ed25519_to_x25519+` +|export +|an Ed25519 key pair's X25519 secret and an Ed25519 public key's X25519 public key +|libsodium + +|`+ed25519ph+` +|use +|Ed25519ph, signing and verifying a SHA-512 digest +|libsodium + +.5+|X25519 +|`+x25519_import+` +|import +|`+from_secret+` of an X25519 key pair +|libsodium + +|`+x25519_generate+` +|generate +|`+generate+` of an X25519 key pair drawn by the backend +|none yet + +|`+x25519_public+` +|public +|`+public_key()+` of an X25519 key pair +|libsodium + +|`+x25519_export+` +|export +|`+secret()+`, `+pkcs8+` and the private PEM of an X25519 key pair +|libsodium + +|`+x25519_agreement+` +|use +|`+agree+` of an X25519 key pair with a peer's public key +|libsodium + +|crypto_kx +|`+kx+` +|use +|libsodium's key exchange: a client's and a server's session keys +|libsodium + +|ChaCha20-Poly1305 +|`+chacha20_poly1305+` +|use +|ChaCha20-Poly1305's `+seal+` and `+open+` (RFC 8439) +|BearSSL, OpenSSL, libsodium + +|original ChaCha20-Poly1305 +|`+chacha20_poly1305_original+` +|use +|the original ChaCha20-Poly1305's `+seal+` and `+open+`, its 8-byte nonce +|libsodium + +|XChaCha20-Poly1305 +|`+xchacha20_poly1305+` +|use +|XChaCha20-Poly1305's `+seal+` and `+open+` +|libsodium + +|ChaCha20 +|`+chacha20+` +|use +|ChaCha20's keystream applied to bytes +|BearSSL, OpenSSL, libsodium + +|Poly1305 +|`+poly1305+` +|use +|Poly1305's tag of a message under a single-use key, and its verification +|OpenSSL, libsodium + +|XSalsa20-Poly1305 secret box +|`+secretbox_xsalsa20poly1305+` +|use +|the secret box over XSalsa20-Poly1305: `+seal+` and `+open+` with a shared key +|libsodium + +|XChaCha20-Poly1305 secret box +|`+secretbox_xchacha20poly1305+` +|use +|the secret box over XChaCha20-Poly1305: `+seal+` and `+open+` with a shared key +|libsodium + +|X25519-XSalsa20-Poly1305 box +|`+box_xsalsa20poly1305+` +|use +|the public-key box over XSalsa20-Poly1305: `+seal+` and `+open+` between two key pairs +|libsodium + +|X25519-XChaCha20-Poly1305 box +|`+box_xchacha20poly1305+` +|use +|the public-key box over XChaCha20-Poly1305: `+seal+` and `+open+` between two key pairs +|libsodium + +|X25519-XSalsa20-Poly1305 sealed box +|`+sealed_box+` +|use +|the sealed box: `+seal+` to a public key, `+open+` with its key pair +|libsodium + +|ElligatorSwift +|`+secp256k1_ellswift+` +|use +|ElligatorSwift's encodings and BIP 324's shared secret +|libsecp256k1 + +|MuSig2 +|`+secp256k1_musig+` +|use +|MuSig2's aggregated keys, nonces and partial signatures +|libsecp256k1 + +|BIP 352 silent payments +|`+secp256k1_silent_payments+` +|use +|BIP 352's silent payments: the sender's outputs and the recipient's scan +|libsecp256k1 + +.11+|P-256 +|`+p256_import+` +|import +|`+from_secret+` of a P-256 key pair +|BearSSL + +|`+p256_generate+` +|generate +|`+generate+` of a P-256 key pair drawn by the backend +|none yet + +|`+p256_public+` +|public +|`+public_key()+` of a P-256 key pair +|BearSSL + +|`+p256_export+` +|export +|`+secret()+`, `+pkcs8+` and the private PEM of a P-256 key pair +|BearSSL + +|`+p256_point+` +|auxiliary +|a P-256 public key's points: checked on the curve, and decompressed +|BearSSL + +|`+p256_ecdsa_signing+` +|use +|ECDSA signing of a SHA-256 digest with a P-256 key pair +|BearSSL + +|`+p256_ecdsa_verifying+` +|use +|ECDSA verifying of a SHA-256 digest with a P-256 public key +|BearSSL + +|`+p256_ecdsa_message_signing+` +|use +|ECDSA signing of a message, hashed with SHA-256 inside the backend +|none yet + +|`+p256_ecdsa_message_verifying+` +|use +|ECDSA verifying of a message, hashed with SHA-256 inside the backend +|none yet + +|`+p256_ecdh+` +|use +|`+agree+` of a P-256 key pair with a peer's public key +|BearSSL + +|`+p256_ecdsa_der+` +|auxiliary +|a P-256 ECDSA signature's DER, written and read +|BearSSL +|=== diff --git a/doc/generated/matrix.adoc b/doc/generated/matrix.adoc index 0a64b9f..1f94cbf 100644 --- a/doc/generated/matrix.adoc +++ b/doc/generated/matrix.adoc @@ -166,12 +166,22 @@ |native, wasip2, wasip3, emscripten |`+x25519_sodium+`, `+oracle_25519+` -|`+codecs::encode+`, `+codecs::decode+`, `+curves::ed25519::public_key::encode+`, `+curves::ed25519::public_key::decode+`, `+curves::ed25519::keypair::encode+`, `+curves::ed25519::keypair::decode+`, `+curves::ed25519::signature::encode+`, `+curves::ed25519::signature::decode+` +|`+codecs::encode+`, `+codecs::decode+`, `+curves::ed25519::public_key::encode+`, `+curves::ed25519::public_key::decode+` +|no backend +|native, wasip2, wasip3, emscripten +|`+rfc8410_no_backend+`, `+formats_ed25519_sodium+`, `+formats_25519_openssl_oracle+`, `+formats_25519_webcrypto_oracle+` + +|`+codecs::encode+`, `+codecs::decode+`, `+curves::ed25519::keypair::encode+`, `+curves::ed25519::keypair::decode+`, `+curves::ed25519::signature::encode+`, `+curves::ed25519::signature::decode+` |libsodium |native, wasip2, wasip3, emscripten |`+formats_ed25519_sodium+`, `+formats_25519_openssl_oracle+`, `+formats_25519_webcrypto_oracle+`, `+allocation_sodium+` -|`+codecs::encode+`, `+codecs::decode+`, `+curves::x25519::public_key::encode+`, `+curves::x25519::public_key::decode+`, `+curves::x25519::keypair::encode+`, `+curves::x25519::keypair::decode+` +|`+codecs::encode+`, `+codecs::decode+`, `+curves::x25519::public_key::encode+`, `+curves::x25519::public_key::decode+` +|no backend +|native, wasip2, wasip3, emscripten +|`+rfc8410_no_backend+`, `+formats_x25519_sodium+`, `+formats_25519_openssl_oracle+`, `+formats_25519_webcrypto_oracle+` + +|`+codecs::encode+`, `+codecs::decode+`, `+curves::x25519::keypair::encode+`, `+curves::x25519::keypair::decode+` |libsodium |native, wasip2, wasip3, emscripten |`+formats_x25519_sodium+`, `+formats_25519_openssl_oracle+`, `+formats_25519_webcrypto_oracle+`, `+allocation_sodium+` @@ -539,13 +549,25 @@ The same, by target: the backends each operation runs on. |libsodium |libsodium -|`+codecs::encode+`, `+codecs::decode+`, `+curves::ed25519::public_key::encode+`, `+curves::ed25519::public_key::decode+`, `+curves::ed25519::keypair::encode+`, `+curves::ed25519::keypair::decode+`, `+curves::ed25519::signature::encode+`, `+curves::ed25519::signature::decode+` +|`+codecs::encode+`, `+codecs::decode+`, `+curves::ed25519::public_key::encode+`, `+curves::ed25519::public_key::decode+` +|no backend +|no backend +|no backend +|no backend + +|`+codecs::encode+`, `+codecs::decode+`, `+curves::ed25519::keypair::encode+`, `+curves::ed25519::keypair::decode+`, `+curves::ed25519::signature::encode+`, `+curves::ed25519::signature::decode+` |libsodium |libsodium |libsodium |libsodium -|`+codecs::encode+`, `+codecs::decode+`, `+curves::x25519::public_key::encode+`, `+curves::x25519::public_key::decode+`, `+curves::x25519::keypair::encode+`, `+curves::x25519::keypair::decode+` +|`+codecs::encode+`, `+codecs::decode+`, `+curves::x25519::public_key::encode+`, `+curves::x25519::public_key::decode+` +|no backend +|no backend +|no backend +|no backend + +|`+codecs::encode+`, `+codecs::decode+`, `+curves::x25519::keypair::encode+`, `+curves::x25519::keypair::decode+` |libsodium |libsodium |libsodium diff --git a/doc/generated/messages.adoc b/doc/generated/messages.adoc index b668c14..00f0c32 100644 --- a/doc/generated/messages.adoc +++ b/doc/generated/messages.adoc @@ -337,6 +337,12 @@ The fix: The secret boxes', the boxes' and the sealed boxes' default is libsodiu The fix: Name `+families::box_xsalsa20poly1305+` or `+families::box_xchacha20poly1305+`, or use `+public_key_encryption::box+` or `+public_key_encryption::box_xchacha20poly1305+`. +|`+chacha20_capability_missing+` +|native, wasip2, wasip3 +|`+webcpp::crypto: this backend has ChaCha20 but not crypto::capabilities::chacha20: the stream cipher is not available on it.+` + +The fix: Name a backend whose ChaCha20 has `+crypto::capabilities::chacha20+`, which `+crypto::supports_capability_v+` answers; when `+crypto::supports_capability_v+` says the backend has it, the error is a defect of the backend, not of the program: report it. + |`+chacha20_default_not_linked+` |native, wasip2, wasip3 |`+webcpp::crypto: ChaCha20's default backend on this target is libsodium, which is not linked. Add /webcpp/crypto//chacha20-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//chacha20-default ; or name another backend in the type, as in ciphers::chacha20. The backends that have it: sodium (native, wasip2, wasip3, emscripten), bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)+` @@ -707,6 +713,12 @@ The fix: Name `+crypto::public_key_encryption::box+`, `+box_xchacha20poly1305+` The fix: Name nonce_size, max_nonce_size and error::invalid_nonce_size: crypto spells its names out. +|`+kept_async_engine_imports+` +|native, wasip2, wasip3 +|`+webcpp::crypto: this backend keeps its keys: no secret key enters it (crypto::imports_secret_keys_v is false), so async_from_secret is not available on it; make a key with async_generate.+` + +The fix: Make the key pair with `+async_generate+` on a backend that keeps its keys (`+crypto::imports_secret_keys_v+` is false); no secret key enters it, whatever its engine has. + |`+keypair_decode_resource_composition+` |native, wasip2, wasip3 |`+webcpp::crypto: a key pair decodes with a memory resource from formats::raw, formats::pkcs8 or formats::pem(formats::pkcs8)+` @@ -791,6 +803,44 @@ The fix: Name `+backends::secp256k1+`, or leave the backend out: `+curves::secp2 The fix: On WASI the default is BearSSL: add `+/webcpp/crypto//gcm-default+`, which links `+/third_party//bearssl+` there, or, with OpenSSL linked, name it in the type, as in `+gcm>+`. +|`+opaque_async_engine_missing+` +|native, wasip2, wasip3 +|`+webcpp::crypto: this backend completes by itself, and its engine has no async_verify: async_verify is not available on it.+` + +The fix: Name, for the operation, a backend that completes by itself and whose engine has its asynchronous form, or a synchronous backend, which every `+async_*+` function takes; when `+crypto::supports_v+` says the backend has the operation, the error is a defect of the backend, not of the program: report it. + +|`+opaque_async_from_secret+` +|native, wasip2, wasip3 +|`+webcpp::crypto: this backend keeps its keys: no secret key enters it (crypto::imports_secret_keys_v is false), so async_from_secret is not available on it; make a key with async_generate.+` + +The fix: Make the key pair with `+async_generate+` on a backend that keeps its keys: no secret key enters it, so it has no `+async_from_secret+`; `+crypto::imports_secret_keys_v+` names the backends that take one. + +|`+opaque_async_synchronous+` +|native, wasip2, wasip3 +|`+webcpp::crypto: generate on this backend completes asynchronously: call async_generate.+` + +`+webcpp::crypto: sign on this backend completes asynchronously: call async_sign.+` + +`+webcpp::crypto: agree on this backend completes asynchronously: call async_agree.+` + +The fix: Call `+async_generate+`, `+async_sign+` or `+async_agree+` on a backend that completes by itself: a P-256 or X25519 key pair's synchronous forms cannot wait for it. + +|`+opaque_keys_kept+` +|native, wasip2, wasip3 +|`+webcpp::crypto: this backend keeps its keys: no secret key enters it (crypto::imports_secret_keys_v is false), so P-256's from_secret, which needs crypto::capabilities::p256_import, is not available on it; make a key with generate.+` + +`+webcpp::crypto: this backend keeps its keys: no secret key leaves it (crypto::exports_secret_keys_v is false), so P-256's secret(), which needs crypto::capabilities::p256_export, is not available on it.+` + +`+webcpp::crypto: this backend keeps its keys: no secret key enters it (crypto::imports_secret_keys_v is false), so X25519's from_secret, which needs crypto::capabilities::x25519_import, is not available on it; make a key with generate.+` + +`+webcpp::crypto: this backend keeps its keys: no secret key leaves it (crypto::exports_secret_keys_v is false), so X25519's secret(), which needs crypto::capabilities::x25519_export, is not available on it.+` + +`+webcpp::crypto: this backend keeps its keys: no secret key leaves or enters it (crypto::exports_secret_keys_v or crypto::imports_secret_keys_v is false), so a key pair's formats::raw, its secret key's bytes, is not available on it+` + +`+webcpp::crypto: this backend keeps its keys: no secret key leaves or enters it (crypto::exports_secret_keys_v or crypto::imports_secret_keys_v is false), so a key pair's formats::pkcs8 and formats::pem(formats::pkcs8) are not available on it+` + +The fix: Make the key pair with `+generate+` on a backend that keeps its keys, which no secret key enters or leaves, and keep the key pair itself: `+crypto::imports_secret_keys_v+` and `+crypto::exports_secret_keys_v+` name the backends that take and give secret bytes, through `+from_secret+`, `+secret()+` and a key pair's private formats. + |`+open_asynchronous_backend+` |native, wasip2, wasip3 |`+webcpp::crypto: WebCrypto has no ChaCha20-Poly1305, XChaCha20-Poly1305, secret box or crypto_box: no form of them, synchronous or asynchronous, runs on the browser's backend; name a native backend for them. On the browser's backend only AES-GCM seals and opens.+` @@ -839,6 +889,20 @@ 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+`. +|`+p256_operation_named+` +|native, wasip2, wasip3 +|`+webcpp::crypto: this backend has P-256 but not crypto::capabilities::p256_point: a public key's point cannot be checked, and from_bytes is not available on it.+` + +The fix: Name a backend whose P-256 has `+crypto::capabilities::p256_point+`, which `+crypto::supports_capability_v+` answers, to make a public key from its bytes; when `+crypto::supports_capability_v+` says the backend has it, the error is a defect of the backend, not of the program: report it. + +|`+p256_prehashed_message_only+` +|native, wasip2, wasip3 +|`+webcpp::crypto: this backend has P-256 but not crypto::capabilities::p256_ecdsa_signing: sign of crypto::signing_schemes::prehashed is not available on it; sign the message.+` + +`+webcpp::crypto: this backend has P-256 but not crypto::capabilities::p256_ecdsa_verifying: verify of crypto::signing_schemes::prehashed is not available on it; verify the message.+` + +The fix: Sign and verify the message itself, which a backend with P-256's message form hashes, or name a backend with P-256's digest form, `+crypto::capabilities::p256_ecdsa_signing+` and `+crypto::capabilities::p256_ecdsa_verifying+`, for `+sign+` and `+verify+` of a digest: `+crypto::supports_capability_v+` says which backends have each. + |`+pem_decode_from_bytes+` |native, wasip2, wasip3 |`+static assertion failed due to requirement 'webcpp::codecs::detail::converts, webcpp::codecs::over>>, webcpp::crypto::formats::spki_t, std::allocator>>': webcpp::codecs: this value codec decodes from text: a std::string_view, or a contiguous sized range of char+` @@ -1057,6 +1121,12 @@ The fix: Add `+/third_party//secp256k1+`. The fix: Name `+backends::secp256k1+`, or leave the backend out: `+curves::secp256k1::keypair+`. +|`+secp256k1_other_backend_first+` +|native, wasip2 +|`+webcpp::crypto: bearssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten).+` + +The fix: As `+secp256k1_other_backend+`: name `+crypto::backends::secp256k1+`, libsecp256k1, for a secp256k1 key pair or public key. + |`+secp256k1_tweak_names_removed+` |native, wasip2 |`+no member named 'pubkey_tweak_add' in namespace 'webcpp::crypto::curves::secp256k1'+` @@ -1099,6 +1169,12 @@ The fix: As `+secp256k1_tweak_names_removed+`. The fix: Name `+webcpp::secure::secret+`, from `++`, the type every secret crypto returns; `+crypto::secret+` moved to webcpp::secure, with no alias. +|`+secretbox_capability_missing+` +|native, wasip2, wasip3 +|`+webcpp::crypto: this backend has the XSalsa20-Poly1305 secret box but not crypto::capabilities::secretbox_xsalsa20poly1305: the box is not available on it.+` + +The fix: Name a backend whose secret box has `+crypto::capabilities::secretbox_xsalsa20poly1305+`, which `+crypto::supports_capability_v+` answers; when `+crypto::supports_capability_v+` says the backend has it, the error is a defect of the backend, not of the program: report it. + |`+secretbox_header_removed+` |native, wasip2, wasip3 |`+'webcpp/crypto/ciphers/secretbox.hpp' file not found+` @@ -2318,6 +2394,10 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the link |Compile every file of the program with the same backend settings. +|`+chacha20_capability_missing+` +|the compile +|Name a backend whose ChaCha20 has `+crypto::capabilities::chacha20+`, which `+crypto::supports_capability_v+` answers; when `+crypto::supports_capability_v+` says the backend has it, the error is a defect of the backend, not of the program: report it. + |`+chacha20_default_not_linked+` |the compile |ChaCha20's default is libsodium on every target: add the family's alias, `+/webcpp/crypto//chacha20-default+`, which links `+/third_party//sodium+`, or name another backend in the type, as `+chacha20+`. @@ -2558,6 +2638,10 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |Name nonce_size, max_nonce_size and error::invalid_nonce_size: crypto spells its names out. +|`+kept_async_engine_imports+` +|the compile +|Make the key pair with `+async_generate+` on a backend that keeps its keys (`+crypto::imports_secret_keys_v+` is false); no secret key enters it, whatever its engine has. + |`+keypair_decode_resource_composition+` |the compile |Decode a secp256k1 key pair with a memory resource from `+crypto::formats::raw+`, `+crypto::formats::pkcs8+` or `+crypto::formats::pem(crypto::formats::pkcs8)+`: decode a composition (its base64, its hexadecimal) with `+codecs::decode+` to the PKCS#8's bytes first, `+codecs::decode>(codecs::formats::base64, text)+`, then decode those with `+crypto::formats::pkcs8+`; or decode the key pair with `+codecs::decode+`, its signing context from the default resource. @@ -2622,6 +2706,22 @@ 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::musig::parse_public_nonce(encoded_nonce)+`. +|`+opaque_async_engine_missing+` +|the compile +|Name, for the operation, a backend that completes by itself and whose engine has its asynchronous form, or a synchronous backend, which every `+async_*+` function takes; when `+crypto::supports_v+` says the backend has the operation, the error is a defect of the backend, not of the program: report it. + +|`+opaque_async_from_secret+` +|the compile +|Make the key pair with `+async_generate+` on a backend that keeps its keys: no secret key enters it, so it has no `+async_from_secret+`; `+crypto::imports_secret_keys_v+` names the backends that take one. + +|`+opaque_async_synchronous+` +|the compile +|Call `+async_generate+`, `+async_sign+` or `+async_agree+` on a backend that completes by itself: a P-256 or X25519 key pair's synchronous forms cannot wait for it. + +|`+opaque_keys_kept+` +|the compile +|Make the key pair with `+generate+` on a backend that keeps its keys, which no secret key enters or leaves, and keep the key pair itself: `+crypto::imports_secret_keys_v+` and `+crypto::exports_secret_keys_v+` name the backends that take and give secret bytes, through `+from_secret+`, `+secret()+` and a key pair's private formats. + |`+open_asynchronous_backend+` |the compile |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. @@ -2646,6 +2746,14 @@ 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+`. +|`+p256_operation_named+` +|the compile +|Name a backend whose P-256 has `+crypto::capabilities::p256_point+`, which `+crypto::supports_capability_v+` answers, to make a public key from its bytes; when `+crypto::supports_capability_v+` says the backend has it, the error is a defect of the backend, not of the program: report it. + +|`+p256_prehashed_message_only+` +|the compile +|Sign and verify the message itself, which a backend with P-256's message form hashes, or name a backend with P-256's digest form, `+crypto::capabilities::p256_ecdsa_signing+` and `+crypto::capabilities::p256_ecdsa_verifying+`, for `+sign+` and `+verify+` of a digest: `+crypto::supports_capability_v+` says which backends have each. + |`+pem_decode_from_bytes+` |the compile |Give a PEM to `+codecs::decode+`, or a type's member `+decode+`, as a text: a `+std::string_view+`, a `+std::string+`, or a contiguous sized range of `+char+` such as `+std::span+`; DER bytes decode with `+crypto::formats::spki+` or `+crypto::formats::pkcs8+` themselves. @@ -2782,6 +2890,10 @@ 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::keypair+`. +|`+secp256k1_other_backend_first+` +|the compile +|As `+secp256k1_other_backend+`: name `+crypto::backends::secp256k1+`, libsecp256k1, for a secp256k1 key pair or public key. + |`+secp256k1_tweak_names_removed+` |the compile |Call public_key_tweak_add, public_key_tweak_mul, public_key_negate, public_key_combine, secret_key_tweak_add, secret_key_tweak_mul and secret_key_negate: crypto spells out the names libsecp256k1 abbreviates. @@ -2794,6 +2906,10 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |Name `+webcpp::secure::secret+`, from `++`, the type every secret crypto returns; `+crypto::secret+` moved to webcpp::secure, with no alias. +|`+secretbox_capability_missing+` +|the compile +|Name a backend whose secret box has `+crypto::capabilities::secretbox_xsalsa20poly1305+`, which `+crypto::supports_capability_v+` answers; when `+crypto::supports_capability_v+` says the backend has it, the error is a defect of the backend, not of the program: report it. + |`+secretbox_header_removed+` |the compile |Include `++`, the secret boxes' header; `+ciphers/secretbox.hpp+` is gone, with no header left at its path. diff --git a/doc/generated/secret-key-traits.adoc b/doc/generated/secret-key-traits.adoc new file mode 100644 index 0000000..1b5be0a --- /dev/null +++ b/doc/generated/secret-key-traits.adoc @@ -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) + +// 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. + +[options="header"] +|=== +|Backend |Secret keys leave it (`exports_secret_keys_v`) |Secret keys enter it (`imports_secret_keys_v`) + +|BearSSL +|yes +|yes + +|OpenSSL +|yes +|yes + +|ctaes +|yes +|yes + +|libsecp256k1 +|yes +|yes + +|libsodium +|yes +|yes +|=== diff --git a/doc/generated/use-cases.adoc b/doc/generated/use-cases.adoc index 9c54689..980e34c 100644 --- a/doc/generated/use-cases.adoc +++ b/doc/generated/use-cases.adoc @@ -229,6 +229,12 @@ `+/webcpp/crypto//x25519-default+` |<> +|Read or write an Ed25519 or X25519 public key in the standard forms OpenSSL and WebCrypto use, with no backend: raw or SPKI (RFC 8410), as DER or PEM text +|In `+curves+`: `+codecs::encode+` and `+codecs::decode+` with `+crypto::formats::raw+`, `+spki+` and `+pem(spki)+`, on Ed25519's and X25519's public keys +|none +|`+/webcpp/crypto//crypto+` +|<> + |Encrypt messages in a chat app, on the web and natively, each with a random nonce |In `+ciphers+`: `+xchacha20_poly1305<>+`: `+from_key+`, `+seal+`, `+open+` |libsodium diff --git a/doc/llms.txt b/doc/llms.txt index c84a9c7..244e129 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -132,7 +132,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - verify_tweak: Whether `tweaked` is this key tweaked by `tweak_bytes`, its parity included (`secp256k1_xonly_pubkey_tweak_add_check`), with libsecp256k1's static context, which allocates nothing: a taproot output key checked against its internal key. - [curves::ed25519::keypair](https://webcpporg.github.io/libs/crypto/#crypto-ed25519): An Ed25519 key pair (RFC 8032): made from a 32-byte seed, which `secret()` gives back, or drawn from `random_device`; its public key, a `curves::ed25519::public_key`; 64-byte signatures of a message with `sign(crypto::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. + - generate: Makes a key pair from a fresh seed: the backend's own, on a backend that draws its keys (design R3), else drawn from the system's generator and imported. - 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. @@ -157,7 +157,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - 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. - from_secret: Makes a key pair from its secret key; its public key is computed here, once. - - generate: Makes a key pair from a fresh secret key, drawn from the system's generator. + - generate: Makes a key pair from a fresh secret key: the backend's own, on a backend that draws its keys (design R3), else drawn from the system's generator and imported. - async_from_secret: Makes a key pair from its secret key, asynchronously: `from_secret` run when the operation is initiated, its result posted to `completion_executor`; the member form of the free `crypto::async_from_secret`, with the same arguments, which calls it. - async_generate: Makes a key pair from a fresh secret key, asynchronously: `generate` run when the operation is initiated, its result posted to `completion_executor`; the member form of `crypto::async_generate(completion_executor, completion_token)`, which calls it. - public_key: The public key, which a peer's `agree` takes: a copy of the one computed when the key pair was made. @@ -167,18 +167,20 @@ 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. -- [codecs::encode, codecs::decode, curves::ed25519::public_key::encode, curves::ed25519::public_key::decode, curves::ed25519::keypair::encode, curves::ed25519::keypair::decode, curves::ed25519::signature::encode, curves::ed25519::signature::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`, and an input longer than the pair's bound (32 bytes, 44 for an SPKI, 48 for a PKCS#8, 64 for a signature's `raw`) is `codecs::error::input_too_long`, as a PEM's payload is. 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. - - public_key::encode: Encodes the key in `format`, as `codecs::encode(format, key)` does. - - public_key::decode: Decodes a public key from `input` in `format`, as `codecs::decode` does. +- [codecs::encode, codecs::decode, curves::ed25519::public_key::encode, curves::ed25519::public_key::decode](https://webcpporg.github.io/libs/crypto/#crypto-key-formats): Ed25519's public-key formats as codecs value codecs, with no backend: `formats::raw` (32 bytes), `formats::spki` (RFC 8410, 44 bytes, a fixed prefix and the key) and `formats::pem(formats::spki)`, the forms OpenSSL and WebCrypto write, the DER decoded strictly: any other bytes are `invalid_encoding`, and an input longer than the bound (32 bytes, 44 for an SPKI) is `codecs::error::input_too_long`, as a PEM's payload is. Header . Backends: no backend (/webcpp/crypto//crypto) on native, wasip2, wasip3, emscripten. Use it to: read or write an Ed25519 or X25519 public key in the standard forms OpenSSL and WebCrypto use, with no backend: raw or SPKI (RFC 8410), as DER or PEM text. + - encode: Encodes the key in `format`, as `codecs::encode(format, key)` does. + - decode: Decodes a public key from `input` in `format`, as `codecs::decode` does. +- [codecs::encode, codecs::decode, curves::ed25519::keypair::encode, curves::ed25519::keypair::decode, curves::ed25519::signature::encode, curves::ed25519::signature::decode](https://webcpporg.github.io/libs/crypto/#crypto-key-formats): Ed25519's key pair and signature formats as codecs value codecs, on the key pair's backend: 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`, and an input longer than the pair's bound (32 bytes, 48 for a PKCS#8, 64 for a signature's `raw`) is `codecs::error::input_too_long`, as a PEM's payload is. 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. - basic_keypair::encode: Encodes the key pair in `format`, as `codecs::encode(format, key_pair)` does. - basic_keypair::decode: Decodes a key pair from `input` in `format`, as `codecs::decode` does. - basic_signature::encode: Encodes the signature in `format`, as `codecs::encode(format, signature)` does. - basic_signature::decode: Decodes a signature from `input` in `format`, as `codecs::decode` does. -- [codecs::encode, codecs::decode, curves::x25519::public_key::encode, curves::x25519::public_key::decode, curves::x25519::keypair::encode, curves::x25519::keypair::decode](https://webcpporg.github.io/libs/crypto/#crypto-key-formats): X25519'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 secret key), `formats::pkcs8` (RFC 8410's version 1, 48 bytes) and `formats::pem(formats::pkcs8)`, secret; the forms OpenSSL and WebCrypto write, an SPKI decoded into the typed key, the DER decoded strictly: any other bytes are `invalid_encoding`, and an input longer than the pair's bound (32 bytes, 44 for an SPKI, 48 for a PKCS#8) is `codecs::error::input_too_long`, as a PEM's payload is. 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. - - public_key::encode: Encodes the key in `format`, as `codecs::encode(format, key)` does. - - public_key::decode: Decodes a public key from `input` in `format`, as `codecs::decode` does. - - basic_keypair::encode: Encodes the key pair in `format`, as `codecs::encode(format, key_pair)` does. - - basic_keypair::decode: Decodes a key pair from `input` in `format`, as `codecs::decode` does. +- [codecs::encode, codecs::decode, curves::x25519::public_key::encode, curves::x25519::public_key::decode](https://webcpporg.github.io/libs/crypto/#crypto-key-formats): X25519's public-key formats as codecs value codecs, with no backend: `formats::raw` (32 bytes), `formats::spki` (RFC 8410, 44 bytes, a fixed prefix and the key) and `formats::pem(formats::spki)`, the forms OpenSSL and WebCrypto write, an SPKI decoded into the typed key that a key pair's `agree` takes, the DER decoded strictly: any other bytes are `invalid_encoding`, and an input longer than the bound (32 bytes, 44 for an SPKI) is `codecs::error::input_too_long`, as a PEM's payload is. Header . Backends: no backend (/webcpp/crypto//crypto) on native, wasip2, wasip3, emscripten. Use it to: read or write an Ed25519 or X25519 public key in the standard forms OpenSSL and WebCrypto use, with no backend: raw or SPKI (RFC 8410), as DER or PEM text. + - encode: Encodes the key in `format`, as `codecs::encode(format, key)` does. + - decode: Decodes a public key from `input` in `format`, as `codecs::decode` does. +- [codecs::encode, codecs::decode, curves::x25519::keypair::encode, curves::x25519::keypair::decode](https://webcpporg.github.io/libs/crypto/#crypto-key-formats): X25519's key pair formats as codecs value codecs, on the key pair's backend: a key pair's `formats::raw` (its secret key), `formats::pkcs8` (RFC 8410's version 1, 48 bytes) and `formats::pem(formats::pkcs8)`, secret; the forms OpenSSL and WebCrypto write, the DER decoded strictly: any other bytes are `invalid_encoding`, and an input longer than the pair's bound (32 bytes, 48 for a PKCS#8) is `codecs::error::input_too_long`, as a PEM's payload is. 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 pair in `format`, as `codecs::encode(format, key_pair)` does. + - decode: Decodes a key pair from `input` in `format`, as `codecs::decode` does. - [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 and uncompressed forms and its x-only key, a `curves::secp256k1::xonly_public_key`. Header . Backends: libsecp256k1 (/third_party//secp256k1) on native, wasip2, wasip3, emscripten. Default: libsecp256k1 on native, wasip2, wasip3, emscripten. @@ -240,7 +242,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - scan_outputs: Scans a transaction's x-only outputs (`..._recipient_scan_outputs`) with the scan key pair and the unlabelled spend key; `label_lookup` is called with a candidate label's 33 bytes and returns a span over its tweak, in bytes the lookup owns, or `std::nullopt`, noexcept (no labels: the default). - [curves::p256::keypair](https://webcpporg.github.io/libs/crypto/#crypto-p256-keys): A P-256 key pair: made from its 32-byte scalar, refused unless 0 < d < n, or drawn from `random_device`; its validated public key and its scalar, `secret()`, a `secure::secret<32>`. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten. Default: BearSSL on native, wasip2, wasip3, emscripten. Use it to: make and keep a P-256 key pair, and import a browser's public key (WebCrypto's raw form), as webcpp::trystero's peers do. - from_secret: Makes a key pair from its secret scalar, as a program that kept `secret()` loads it again. - - generate: Makes a key pair from a fresh scalar, drawn from the system's generator until it is below the group order (a draw is refused about once in 2^32). + - generate: Makes a key pair from a fresh scalar: the backend's own, on a backend that draws its keys (design R3), else drawn from the system's generator until it is below the group order (a draw is refused about once in 2^32) and imported. - async_from_secret: Makes a key pair from its secret scalar, asynchronously: `from_secret` run when the operation is initiated, its result posted to `completion_executor`; the member form of the free `crypto::async_from_secret`, with the same arguments, which calls it. - async_generate: Makes a key pair from a fresh scalar, asynchronously: `generate` run when the operation is initiated, its result posted to `completion_executor`; the member form of `crypto::async_generate(completion_executor, completion_token)`, which calls it. - public_key: The public key, computed when the key pair was made. @@ -431,6 +433,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [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): `codecs::encode` and `codecs::decode` with `crypto::formats::raw`, `spki`, `pkcs8` and `pem`, on Ed25519's and X25519's keys (webcpp::crypto::curves); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//ed25519-default /webcpp/crypto//x25519-default. Example: example/key_formats.cpp. +- [Read or write an Ed25519 or X25519 public key in the standard forms OpenSSL and WebCrypto use, with no backend: raw or SPKI (RFC 8410), as DER or PEM text](https://webcpporg.github.io/libs/crypto/#crypto-key-formats): `codecs::encode` and `codecs::decode` with `crypto::formats::raw`, `spki` and `pem(spki)`, on Ed25519's and X25519's public keys (webcpp::crypto::curves); backend none; Jamfile /webcpp/crypto//crypto. Example: example/key_formats.cpp. - [Encrypt messages in a chat app, on the web and natively, each with a random nonce](https://webcpporg.github.io/libs/crypto/#crypto-chacha): `xchacha20_poly1305<>`: `from_key`, `seal`, `open` (webcpp::crypto::ciphers); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//xchacha20_poly1305-default. Example: example/xchacha_seal.cpp. - [Apply ChaCha20's keystream for a protocol that fixes its own construction (NIP-44)](https://webcpporg.github.io/libs/crypto/#crypto-chacha20): `chacha20<>`: `from_key`, `apply_keystream(nonce, data, initial_counter)`; `unauthenticated_encryption::apply_keystream` in code written once for every stream cipher (webcpp::crypto::ciphers); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//chacha20-default. Example: example/chacha20_keystream.cpp. - [Authenticate one message under a one-time key](https://webcpporg.github.io/libs/crypto/#crypto-poly1305): `poly1305<>`: static `authenticate(key, message)`, `verify(key, message, tag)`; `single_use_key_authentication::authenticate` and `verify` in code written once for every single-use key authenticator (webcpp::crypto::authenticators); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//poly1305-default. Example: example/poly1305_one_time_tag.cpp. diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 75d3411..d8cac8a 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -1,5 +1,5 @@ { - "comment": "The data of crypto's generated tables and of llms.txt; doc/tables/generate.py reads it with the test Jamfiles, the message tests and the superproject's Jamfile fixtures, and writes doc/generated/, doc/llms.txt, include/webcpp/crypto/detail/capabilities.hpp, include/webcpp/crypto/detail/defaults.hpp and test/capabilities_test.cpp. The capability table is `families`: per family its algorithms, the targets on which each backend has it (each claimed only where a test of the family's operations on that backend runs), constant time per target where it differs from the backend's own `constant_time` (X25519 on wasip2, an open finding, and natively without arm64's DIT, the cause of both), with `constant_time_checker` naming the checker, or the list of checkers, that measured it where that is not every checker of the target, and the default per target, one whatever the program links (design D32), with its reason and the tests that fix it (a row of some of `compilers` restates its target's default for them, with a reason of their own, and each compiler of a target has one row), from which come include/webcpp/crypto/detail/defaults.hpp and the refusal that says what a program whose default is not linked needs; a backend with `targets`, where it is built, is a tag of `backends`. A name in a text is written between backticks, as Markdown writes code: the tables show it as code and llms.txt keeps the backticks. A comparison table's cell {speed:} or {constant_time:} is written from doc/performance.json or from the family's `constant_time`, and each cell of a column a namespace lists in `cited` cites a source or begins with \"none\". `checkers` names the constant-time lane's checkers; one of `unjudged_checkers` prints what it measures and judges nothing, so a table gives it no result: dudect of the program `dudect_bearssl` (BearSSL, ctaes, `secure::constant_time_equal` and hash's Base58Check) on a WASI target, which judges none of its cases there by the owner's decision of 2026-12-04, as their timing under wasmtime follows the runner's processor. Edit this file, then run python3 libs/crypto/doc/tables/generate.py; the doc build runs it with --check.", + "comment": "The data of crypto's generated tables and of llms.txt; doc/tables/generate.py reads it with the test Jamfiles, the message tests and the superproject's Jamfile fixtures, and writes doc/generated/, doc/llms.txt, include/webcpp/crypto/detail/capabilities.hpp, include/webcpp/crypto/detail/defaults.hpp and test/capabilities_test.cpp. The capability table is `families`: per family its algorithms, the targets on which each backend has it (each claimed only where a test of the family's operations on that backend runs), constant time per target where it differs from the backend's own `constant_time` (X25519 on wasip2, an open finding, and natively without arm64's DIT, the cause of both), with `constant_time_checker` naming the checker, or the list of checkers, that measured it where that is not every checker of the target, and the default per target, one whatever the program links (design D32), with its reason and the tests that fix it (a row of some of `compilers` restates its target's default for them, with a reason of their own, and each compiler of a target has one row), from which come include/webcpp/crypto/detail/defaults.hpp and the refusal that says what a program whose default is not linked needs; a backend with `targets`, where it is built, is a tag of `backends`. Each family lists its `capabilities` (design D5, D7), each a tag of `capabilities`, of a `kind` (`import`, `generate`, `public`, `export`, `use`, which `supports_v` counts, or `auxiliary`), its `text`, what it gives a program in a program's terms, which its tag's comment says (no internal name: design D10), the concept of `detail::backend` it names (its `concept`, else its name), which the generated test alone writes, its `engines` with `{backend}` for the backend, the `arguments` the concept takes after the engine, the `names` of the algorithms whose use it is where not all, and the forms it may stand for, `either`, each of a `form` of its own (P-256's `digest` and `message`); each backend's cell lists the capabilities its engines have, one cell per capability, the use operations of each algorithm among them, in one form at least: a cell that signs a digest and verifies a message alone is refused. capabilities_test checks the cells against the engines both ways. The capabilities are those of the shipped backends: the system's generator (`entropy_source`) and the asynchronous concepts (`async_*`) get theirs with the first backend of the table that has them, part B's browser backend; the test-only opaque backend is outside the table (design R6). A backend row's `exports_secret_keys` and `imports_secret_keys`, true unless the row says false, are `exports_secret_keys_v` and `imports_secret_keys_v`, which a cell's export and import capabilities agree with. A name in a text is written between backticks, as Markdown writes code: the tables show it as code and llms.txt keeps the backticks. A comparison table's cell {speed:} or {constant_time:} is written from doc/performance.json or from the family's `constant_time`, and each cell of a column a namespace lists in `cited` cites a source or begins with \"none\". `checkers` names the constant-time lane's checkers; one of `unjudged_checkers` prints what it measures and judges nothing, so a table gives it no result: dudect of the program `dudect_bearssl` (BearSSL, ctaes, `secure::constant_time_equal` and hash's Base58Check) on a WASI target, which judges none of its cases there by the owner's decision of 2026-12-04, as their timing under wasmtime follows the runner's processor. Edit this file, then run python3 libs/crypto/doc/tables/generate.py; the doc build runs it with --check.", "page": "https://webcpporg.github.io/libs/crypto/", "llms": "Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA and recoverable signatures, ECDH, tweaks, ElligatorSwift, MuSig2, silent payments), Ed25519 and Ed25519ph (RFC 8032), X25519 (RFC 7748), their keys in SPKI, PKCS#8 (RFC 8410) and PEM, P-256 key pairs, ECDSA and ECDH on BearSSL, libsodium's crypto_kx, the ChaCha20-Poly1305 AEADs, libsodium's secret boxes, boxes and sealed boxes, a random_device on the system's generator, each over a widely used, reviewed C library (BearSSL, OpenSSL, ctaes, libsecp256k1, libsodium) that the program names in its Jamfile. Hashing and HMAC are Boost.Hash2's; HKDF and password hashing are webcpp::hash's; the constant-time comparison, the erasure of a buffer and secret are webcpp::secure's. Every failure is a boost::system::result value. Protocols (Bitcoin, Ethereum, Nostr) belong to domain libraries built on these primitives.", "targets": ["native", "wasip2", "wasip3", "emscripten"], @@ -169,7 +169,7 @@ "library": "OpenSSL 3.5.9's libcrypto, built from source and static", "licence": "Apache-2.0", "own_api": "``", - "allocation": "`from_key` allocates the cipher's context through OpenSSL's own allocator, outside the program's resource, unless a native program sets `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE`, which sends every allocation of OpenSSL's in the process to `openssl_memory_resource()`; a message allocates nothing after `from_key`", + "allocation": "`from_key` allocates the cipher's context, and each of Poly1305's calls makes and frees its MAC context, through OpenSSL's own allocator, outside the program's resource, unless a native program sets `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE`, which sends every allocation of OpenSSL's in the process to `openssl_memory_resource()`; a cipher's message allocates nothing after `from_key`", "constant_time": "with assembly (native Clang and GCC), AES-NI and carry-less multiplication where the CPU has them; built no-asm (MSVC, wasip2, wasip3), table-based AES and 4-bit GHASH, neither constant time (`OPENSSL_AES_CONST_TIME` makes only the AES core constant time; GHASH stays table-based)", "constant_time_sources": ["openssl-install", "openssl-aes-core"], "size_note": "its cells differ by a few bytes whatever the operation: each fetches its algorithm by name from OpenSSL's default provider ({openssl-fetch}), and a static link brings the provider's algorithms with it, not the operation's alone." @@ -521,27 +521,51 @@ "section": "crypto-x25519", "backends": {"sodium": {"tests": ["x25519_sodium", "oracle_25519"]}} }, + { + "id": "ed25519_public_formats", + "family": "ed25519", + "functions": ["public_key::encode", "public_key::decode"], + "function_headers": {"public_key::encode": "", "public_key::decode": ""}, + "namespace": "curves", + "api": "codecs::encode, codecs::decode, curves::ed25519::public_key::encode, curves::ed25519::public_key::decode", + "header": "", + "what": "Ed25519's public-key formats as codecs value codecs, with no backend: `formats::raw` (32 bytes), `formats::spki` (RFC 8410, 44 bytes, a fixed prefix and the key) and `formats::pem(formats::spki)`, the forms OpenSSL and WebCrypto write, the DER decoded strictly: any other bytes are `invalid_encoding`, and an input longer than the bound (32 bytes, 44 for an SPKI) is `codecs::error::input_too_long`, as a PEM's payload is.", + "section": "crypto-key-formats", + "backends": {"none": {"tests": ["rfc8410_no_backend", "formats_ed25519_sodium", "formats_25519_openssl_oracle", "formats_25519_webcrypto_oracle"]}} + }, { "id": "ed25519_formats", "family": "ed25519", - "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": ""}, + "functions": ["basic_keypair::encode", "basic_keypair::decode", "basic_signature::encode", "basic_signature::decode"], + "function_headers": {"basic_keypair::encode": "", "basic_keypair::decode": "", "basic_signature::encode": "", "basic_signature::decode": ""}, "namespace": "curves", - "api": "codecs::encode, codecs::decode, curves::ed25519::public_key::encode, curves::ed25519::public_key::decode, curves::ed25519::keypair::encode, curves::ed25519::keypair::decode, curves::ed25519::signature::encode, curves::ed25519::signature::decode", + "api": "codecs::encode, codecs::decode, curves::ed25519::keypair::encode, curves::ed25519::keypair::decode, curves::ed25519::signature::encode, curves::ed25519::signature::decode", "header": "", - "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`, and an input longer than the pair's bound (32 bytes, 44 for an SPKI, 48 for a PKCS#8, 64 for a signature's `raw`) is `codecs::error::input_too_long`, as a PEM's payload is.", + "what": "Ed25519's key pair and signature formats as codecs value codecs, on the key pair's backend: 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`, and an input longer than the pair's bound (32 bytes, 48 for a PKCS#8, 64 for a signature's `raw`) is `codecs::error::input_too_long`, as a PEM's payload is.", "section": "crypto-key-formats", "backends": {"sodium": {"tests": ["formats_ed25519_sodium", "formats_25519_openssl_oracle", "formats_25519_webcrypto_oracle", "allocation_sodium"]}} }, + { + "id": "x25519_public_formats", + "family": "x25519", + "functions": ["public_key::encode", "public_key::decode"], + "function_headers": {"public_key::encode": "", "public_key::decode": ""}, + "namespace": "curves", + "api": "codecs::encode, codecs::decode, curves::x25519::public_key::encode, curves::x25519::public_key::decode", + "header": "", + "what": "X25519's public-key formats as codecs value codecs, with no backend: `formats::raw` (32 bytes), `formats::spki` (RFC 8410, 44 bytes, a fixed prefix and the key) and `formats::pem(formats::spki)`, the forms OpenSSL and WebCrypto write, an SPKI decoded into the typed key that a key pair's `agree` takes, the DER decoded strictly: any other bytes are `invalid_encoding`, and an input longer than the bound (32 bytes, 44 for an SPKI) is `codecs::error::input_too_long`, as a PEM's payload is.", + "section": "crypto-key-formats", + "backends": {"none": {"tests": ["rfc8410_no_backend", "formats_x25519_sodium", "formats_25519_openssl_oracle", "formats_25519_webcrypto_oracle"]}} + }, { "id": "x25519_formats", "family": "x25519", - "functions": ["public_key::encode", "public_key::decode", "basic_keypair::encode", "basic_keypair::decode"], - "function_headers": {"public_key::encode": "", "public_key::decode": "", "basic_keypair::encode": "", "basic_keypair::decode": ""}, + "functions": ["basic_keypair::encode", "basic_keypair::decode"], + "function_headers": {"basic_keypair::encode": "", "basic_keypair::decode": ""}, "namespace": "curves", - "api": "codecs::encode, codecs::decode, curves::x25519::public_key::encode, curves::x25519::public_key::decode, curves::x25519::keypair::encode, curves::x25519::keypair::decode", + "api": "codecs::encode, codecs::decode, curves::x25519::keypair::encode, curves::x25519::keypair::decode", "header": "", - "what": "X25519'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 secret key), `formats::pkcs8` (RFC 8410's version 1, 48 bytes) and `formats::pem(formats::pkcs8)`, secret; the forms OpenSSL and WebCrypto write, an SPKI decoded into the typed key, the DER decoded strictly: any other bytes are `invalid_encoding`, and an input longer than the pair's bound (32 bytes, 44 for an SPKI, 48 for a PKCS#8) is `codecs::error::input_too_long`, as a PEM's payload is.", + "what": "X25519's key pair formats as codecs value codecs, on the key pair's backend: a key pair's `formats::raw` (its secret key), `formats::pkcs8` (RFC 8410's version 1, 48 bytes) and `formats::pem(formats::pkcs8)`, secret; the forms OpenSSL and WebCrypto write, the DER decoded strictly: any other bytes are `invalid_encoding`, and an input longer than the pair's bound (32 bytes, 48 for a PKCS#8) is `codecs::error::input_too_long`, as a PEM's payload is.", "section": "crypto-key-formats", "backends": {"sodium": {"tests": ["formats_x25519_sodium", "formats_25519_openssl_oracle", "formats_25519_webcrypto_oracle", "allocation_sodium"]}} }, @@ -949,9 +973,12 @@ {"targets": ["wasip2", "wasip3"], "backend": "bearssl", "tests": ["default_bearssl", "default_both_wasm", "default_backend_all_linked"], "why": "constant time by design ({bearssl-ct}), where OpenSSL is built no-asm and its AES and GHASH are table-based ({openssl-install}). BearSSL whatever the program links: a program that links OpenSSL alone names `gcm>`"}, {"targets": ["emscripten"], "backend": "bearssl", "tests": ["default_bearssl", "default_backend_all_linked_emscripten"], "why": "the only AES-GCM backend there: webcpp does not build OpenSSL for Emscripten"} ], + "capabilities": [ + {"name": "gcm", "kind": "use", "text": "AES-GCM's `seal` and `open`, with a 128-, 192- or 256-bit key", "engines": ["gcm_engine<{backend}, 16>", "gcm_engine<{backend}, 24>", "gcm_engine<{backend}, 32>"]} + ], "backends": { - "bearssl": {"targets": "all", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect_printed"]}}, - "openssl": {"targets": "all", "lane": {"native": ["memcheck"]}, "lane_note": "seal alone: its open branches on the verdict inside OpenSSL"} + "bearssl": {"capabilities": ["gcm"], "targets": "all", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect_printed"]}}, + "openssl": {"capabilities": ["gcm"], "targets": "all", "lane": {"native": ["memcheck"]}, "lane_note": "seal alone: its open branches on the verdict inside OpenSSL"} } }, { @@ -972,9 +999,12 @@ {"targets": ["native"], "compilers": ["msvc"], "backend": "openssl", "tests": ["default_aes_block"], "why": "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-install}); where timing attacks matter, link ctaes and name `aes256`"}, {"targets": ["wasip2", "wasip3", "emscripten"], "backend": "ctaes", "tests": ["default_aes_block", "default_bearssl"], "why": "constant time by design ({ctaes}), where OpenSSL is built no-asm and its AES is table-based ({openssl-install}), and webcpp does not build OpenSSL for Emscripten"} ], + "capabilities": [ + {"name": "aes_block", "kind": "use", "text": "the AES block cipher, one 16-byte block with a 128-, 192- or 256-bit key", "concept": "block_cipher", "engines": ["block_engine<{backend}, 16>", "block_engine<{backend}, 24>", "block_engine<{backend}, 32>"]} + ], "backends": { - "openssl": {"targets": "all"}, - "ctaes": {"targets": "all", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect_printed"]}} + "openssl": {"capabilities": ["aes_block"], "targets": "all"}, + "ctaes": {"capabilities": ["aes_block"], "targets": "all", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect_printed"]}} } }, { @@ -991,8 +1021,23 @@ "default": [ {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "secp256k1", "tests": ["secp256k1", "default_backend_none_linked"], "why": "the only backend ({libsecp256k1})"} ], + "capabilities": [ + {"name": "secp256k1_import", "kind": "import", "text": "`from_secret` of a secp256k1 key pair", "engines": ["secp256k1_engine"]}, + {"name": "secp256k1_generate", "kind": "generate", "text": "`generate` of a secp256k1 key pair drawn by the backend", "engines": ["secp256k1_engine"]}, + {"name": "secp256k1_public", "kind": "public", "text": "`public_key()` of a secp256k1 key pair", "engines": ["secp256k1_engine"]}, + {"name": "secp256k1_export", "kind": "export", "text": "`secret()`, `pkcs8` and the private PEM of a secp256k1 key pair", "engines": ["secp256k1_engine"]}, + {"name": "secp256k1_point", "kind": "auxiliary", "text": "a secp256k1 public key's points and x-only keys: read, written and compared", "engines": ["secp256k1_engine"]}, + {"name": "secp256k1_ecdsa_signing", "kind": "use", "text": "ECDSA signing with a secp256k1 key pair", "engines": ["secp256k1_engine"]}, + {"name": "secp256k1_ecdsa_verifying", "kind": "use", "text": "ECDSA verifying with a secp256k1 public key", "engines": ["secp256k1_engine"]}, + {"name": "secp256k1_ecdsa_forms", "kind": "auxiliary", "text": "a secp256k1 ECDSA signature's forms: compact, low S and DER", "engines": ["secp256k1_engine"]}, + {"name": "secp256k1_schnorr_signing", "kind": "use", "text": "BIP 340's Schnorr signing with a secp256k1 key pair", "engines": ["secp256k1_engine"]}, + {"name": "secp256k1_schnorr_verifying", "kind": "use", "text": "BIP 340's Schnorr verifying with an x-only public key", "engines": ["secp256k1_engine"]}, + {"name": "secp256k1_recoverable", "kind": "use", "text": "recoverable ECDSA: signing, and the public key recovered from a signature", "engines": ["secp256k1_engine"]}, + {"name": "secp256k1_ecdh", "kind": "use", "text": "`agree` of a secp256k1 key pair with a peer's public key", "engines": ["secp256k1_engine"]}, + {"name": "secp256k1_tweak", "kind": "auxiliary", "text": "the tweaks of secp256k1's keys (BIP 32, BIP 341): added to or multiplied into a key, and points combined", "engines": ["secp256k1_engine"]} + ], "backends": { - "secp256k1": {"targets": "all", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect"]}, "lane_note": {"memcheck": "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", "msan": "the same paths as memcheck's", "dudect": "`agree`"}} + "secp256k1": {"capabilities": ["secp256k1_import", "secp256k1_public", "secp256k1_export", "secp256k1_point", "secp256k1_ecdsa_signing", "secp256k1_ecdsa_verifying", "secp256k1_ecdsa_forms", "secp256k1_schnorr_signing", "secp256k1_schnorr_verifying", "secp256k1_recoverable", "secp256k1_ecdh", "secp256k1_tweak"], "targets": "all", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect"]}, "lane_note": {"memcheck": "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", "msan": "the same paths as memcheck's", "dudect": "`agree`"}} } }, { @@ -1009,8 +1054,18 @@ "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 `canonical` ({libsodium-signatures}; {rfc8032})"} ], + "capabilities": [ + {"name": "ed25519_import", "kind": "import", "text": "`from_secret` of an Ed25519 key pair, from its seed", "engines": ["ed25519_engine"]}, + {"name": "ed25519_generate", "kind": "generate", "text": "`generate` of an Ed25519 key pair drawn by the backend", "engines": ["ed25519_engine"]}, + {"name": "ed25519_public", "kind": "public", "text": "`public_key()` of an Ed25519 key pair", "engines": ["ed25519_engine"]}, + {"name": "ed25519_export", "kind": "export", "text": "`secret()`, `pkcs8` and the private PEM of an Ed25519 key pair", "engines": ["ed25519_engine"]}, + {"name": "ed25519_signing", "kind": "use", "text": "Ed25519 signing of a message", "engines": ["ed25519_engine"], "names": ["ed25519"]}, + {"name": "ed25519_verifying", "kind": "use", "text": "Ed25519 verifying of a message", "engines": ["ed25519_engine"], "names": ["ed25519"]}, + {"name": "ed25519_to_x25519", "kind": "export", "text": "an Ed25519 key pair's X25519 secret and an Ed25519 public key's X25519 public key", "engines": ["ed25519_engine"]}, + {"name": "ed25519ph", "kind": "use", "text": "Ed25519ph, signing and verifying a SHA-512 digest", "engines": ["ed25519ph_engine"], "arguments": ["ed25519_engine"], "names": ["ed25519ph"]} + ], "backends": { - "sodium": {"targets": "all", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect"]}} + "sodium": {"capabilities": ["ed25519_import", "ed25519_public", "ed25519_export", "ed25519_signing", "ed25519_verifying", "ed25519_to_x25519", "ed25519ph"], "targets": "all", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect"]}} } }, { @@ -1026,8 +1081,15 @@ "default": [ {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": ["x25519_sodium", "default_backend_none_linked"], "why": "the only backend in this version, on every target; it refuses an all-zero shared secret itself ({rfc7748})"} ], + "capabilities": [ + {"name": "x25519_import", "kind": "import", "text": "`from_secret` of an X25519 key pair", "engines": ["x25519_engine"]}, + {"name": "x25519_generate", "kind": "generate", "text": "`generate` of an X25519 key pair drawn by the backend", "engines": ["x25519_engine"]}, + {"name": "x25519_public", "kind": "public", "text": "`public_key()` of an X25519 key pair", "engines": ["x25519_engine"]}, + {"name": "x25519_export", "kind": "export", "text": "`secret()`, `pkcs8` and the private PEM of an X25519 key pair", "engines": ["x25519_engine"]}, + {"name": "x25519_agreement", "kind": "use", "text": "`agree` of an X25519 key pair with a peer's public key", "engines": ["x25519_engine"]} + ], "backends": { - "sodium": {"targets": "all", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect"]}, "constant_time_checker": {"native": "dudect"}, "constant_time": {"native": "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 ({apple-dit}); 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": "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 ({apple-dit}): 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"}} + "sodium": {"capabilities": ["x25519_import", "x25519_public", "x25519_export", "x25519_agreement"], "targets": "all", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect"]}, "constant_time_checker": {"native": "dudect"}, "constant_time": {"native": "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 ({apple-dit}); 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": "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 ({apple-dit}): 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"}} } }, { @@ -1043,8 +1105,11 @@ "default": [ {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": ["kx_sodium", "default_backend_none_linked"], "why": "the only backend that has it: libsodium's own construction, whose session keys only another `crypto_kx` derives ({libsodium-kx})"} ], + "capabilities": [ + {"name": "kx", "kind": "use", "text": "libsodium's key exchange: a client's and a server's session keys", "engines": ["kx_engine"]} + ], "backends": { - "sodium": {"targets": "all", "lane": {"native": ["memcheck", "msan"]}} + "sodium": {"capabilities": ["kx"], "targets": "all", "lane": {"native": ["memcheck", "msan"]}} } }, { @@ -1061,10 +1126,13 @@ "default": [ {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": ["chacha_sodium", "default_backend_none_linked"], "why": "one library for the three ChaCha20-Poly1305 AEADs on every target, where BearSSL and OpenSSL have RFC 8439's alone ({libsodium-aead}); a program that links BearSSL or OpenSSL alone names it in the type, as in `chacha20_poly1305`"} ], + "capabilities": [ + {"name": "chacha20_poly1305", "kind": "use", "text": "ChaCha20-Poly1305's `seal` and `open` (RFC 8439)", "concept": "aead", "engines": ["aead_engine"], "arguments": ["families::chacha20_poly1305"]} + ], "backends": { - "sodium": {"targets": "all", "lane": {"native": ["memcheck", "msan"]}}, - "bearssl": {"targets": "all", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect_printed"]}}, - "openssl": {"targets": "all", "lane": {"native": ["memcheck"]}, "lane_note": "seal alone: its open branches on the verdict inside OpenSSL"} + "sodium": {"capabilities": ["chacha20_poly1305"], "targets": "all", "lane": {"native": ["memcheck", "msan"]}}, + "bearssl": {"capabilities": ["chacha20_poly1305"], "targets": "all", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect_printed"]}}, + "openssl": {"capabilities": ["chacha20_poly1305"], "targets": "all", "lane": {"native": ["memcheck"]}, "lane_note": "seal alone: its open branches on the verdict inside OpenSSL"} } }, { @@ -1081,8 +1149,11 @@ "default": [ {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": ["chacha_original_sodium", "default_backend_none_linked"], "why": "the only backend that has it: libsodium's own C code, the same on every target ({libsodium-aead})"} ], + "capabilities": [ + {"name": "chacha20_poly1305_original", "kind": "use", "text": "the original ChaCha20-Poly1305's `seal` and `open`, its 8-byte nonce", "concept": "aead", "engines": ["aead_engine"], "arguments": ["families::chacha20_poly1305_original"]} + ], "backends": { - "sodium": {"targets": "all", "lane": {"native": ["memcheck", "msan"]}} + "sodium": {"capabilities": ["chacha20_poly1305_original"], "targets": "all", "lane": {"native": ["memcheck", "msan"]}} } }, { @@ -1099,8 +1170,11 @@ "default": [ {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": ["xchacha_sodium", "default_backend_none_linked"], "why": "the only backend that has it: libsodium's own C code, the same on every target ({libsodium-aead})"} ], + "capabilities": [ + {"name": "xchacha20_poly1305", "kind": "use", "text": "XChaCha20-Poly1305's `seal` and `open`", "concept": "aead", "engines": ["aead_engine"], "arguments": ["families::xchacha20_poly1305"]} + ], "backends": { - "sodium": {"targets": "all", "lane": {"native": ["memcheck", "msan"]}} + "sodium": {"capabilities": ["xchacha20_poly1305"], "targets": "all", "lane": {"native": ["memcheck", "msan"]}} } }, { @@ -1117,10 +1191,13 @@ "default": [ {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": ["chacha20_sodium", "default_backend_none_linked"], "why": "ChaCha20-Poly1305's default, so that a program that uses both links one library; libsodium's own C code, constant time, the same on every target ({libsodium-stream})"} ], + "capabilities": [ + {"name": "chacha20", "kind": "use", "text": "ChaCha20's keystream applied to bytes", "concept": "stream_cipher", "engines": ["stream_engine"], "arguments": ["families::chacha20"]} + ], "backends": { - "sodium": {"targets": "all", "lane": {"native": ["memcheck", "msan"]}}, - "bearssl": {"targets": "all", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect_printed"]}}, - "openssl": {"targets": "all", "lane": {"native": ["memcheck"]}} + "sodium": {"capabilities": ["chacha20"], "targets": "all", "lane": {"native": ["memcheck", "msan"]}}, + "bearssl": {"capabilities": ["chacha20"], "targets": "all", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect_printed"]}}, + "openssl": {"capabilities": ["chacha20"], "targets": "all", "lane": {"native": ["memcheck"]}} } }, { @@ -1137,9 +1214,12 @@ "default": [ {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": ["poly1305_sodium", "default_backend_none_linked"], "why": "ChaCha20's and ChaCha20-Poly1305's default, so that a program composing them links one library ({libsodium-onetimeauth})"} ], + "capabilities": [ + {"name": "poly1305", "kind": "use", "text": "Poly1305's tag of a message under a single-use key, and its verification", "concept": "authenticator", "engines": ["authenticator_engine"], "arguments": ["families::poly1305"]} + ], "backends": { - "sodium": {"targets": "all", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect"]}, "lane_note": {"memcheck": "`authenticate`, then `verify` with the right tag and with a wrong one, the key, the message and the tags secret; the verdict of `verify` declassified by crypto where it first branches on it", "msan": "the same paths as memcheck's", "dudect": "`authenticate` against its key, the all-zero key against random ones; `verify` against its tag, the right tag with its last byte flipped against it with its first byte flipped, both classes failing: a success and a failure return by different paths, about 0.4 ns apart, which dudect finds and which is public, the verdict being reported"}}, - "openssl": {"targets": "all", "lane": {"native": ["memcheck"]}, "lane_note": "`authenticate` and `verify`, as on libsodium"} + "sodium": {"capabilities": ["poly1305"], "targets": "all", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect"]}, "lane_note": {"memcheck": "`authenticate`, then `verify` with the right tag and with a wrong one, the key, the message and the tags secret; the verdict of `verify` declassified by crypto where it first branches on it", "msan": "the same paths as memcheck's", "dudect": "`authenticate` against its key, the all-zero key against random ones; `verify` against its tag, the right tag with its last byte flipped against it with its first byte flipped, both classes failing: a success and a failure return by different paths, about 0.4 ns apart, which dudect finds and which is public, the verdict being reported"}}, + "openssl": {"capabilities": ["poly1305"], "targets": "all", "lane": {"native": ["memcheck"]}, "lane_note": "`authenticate` and `verify`, as on libsodium"} } }, { @@ -1155,8 +1235,11 @@ "default": [ {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": ["secretbox_sodium", "default_backend_none_linked"], "why": "the only backend that has it: libsodium's own C code, NaCl's `crypto_secretbox`, the same on every target ({libsodium-secretbox})"} ], + "capabilities": [ + {"name": "secretbox_xsalsa20poly1305", "kind": "use", "text": "the secret box over XSalsa20-Poly1305: `seal` and `open` with a shared key", "concept": "authenticated_box", "engines": ["secretbox_engine"], "arguments": ["families::secretbox_xsalsa20poly1305"]} + ], "backends": { - "sodium": {"targets": "all", "lane": {"native": ["memcheck", "msan"]}} + "sodium": {"capabilities": ["secretbox_xsalsa20poly1305"], "targets": "all", "lane": {"native": ["memcheck", "msan"]}} } }, { @@ -1172,8 +1255,11 @@ "default": [ {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": ["secretbox_sodium", "default_backend_none_linked"], "why": "the only backend that has it: libsodium's own C code, the same on every target ({libsodium-secretbox})"} ], + "capabilities": [ + {"name": "secretbox_xchacha20poly1305", "kind": "use", "text": "the secret box over XChaCha20-Poly1305: `seal` and `open` with a shared key", "concept": "authenticated_box", "engines": ["secretbox_engine"], "arguments": ["families::secretbox_xchacha20poly1305"]} + ], "backends": { - "sodium": {"targets": "all", "lane": {"native": ["memcheck", "msan"]}} + "sodium": {"capabilities": ["secretbox_xchacha20poly1305"], "targets": "all", "lane": {"native": ["memcheck", "msan"]}} } }, { @@ -1189,8 +1275,11 @@ "default": [ {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": ["box_sodium", "default_backend_none_linked"], "why": "the only backend that has it: libsodium's own C code, NaCl's `crypto_box`, the same on every target ({libsodium-box})"} ], + "capabilities": [ + {"name": "box_xsalsa20poly1305", "kind": "use", "text": "the public-key box over XSalsa20-Poly1305: `seal` and `open` between two key pairs", "concept": "box", "engines": ["box_engine"]} + ], "backends": { - "sodium": {"targets": "all", "lane": {"native": ["memcheck", "msan"]}} + "sodium": {"capabilities": ["box_xsalsa20poly1305"], "targets": "all", "lane": {"native": ["memcheck", "msan"]}} } }, { @@ -1206,8 +1295,11 @@ "default": [ {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": ["box_sodium", "default_backend_none_linked"], "why": "the only backend that has it: libsodium's own C code, the same on every target ({libsodium-box})"} ], + "capabilities": [ + {"name": "box_xchacha20poly1305", "kind": "use", "text": "the public-key box over XChaCha20-Poly1305: `seal` and `open` between two key pairs", "concept": "box", "engines": ["box_engine"]} + ], "backends": { - "sodium": {"targets": "all", "lane": {"native": ["memcheck", "msan"]}} + "sodium": {"capabilities": ["box_xchacha20poly1305"], "targets": "all", "lane": {"native": ["memcheck", "msan"]}} } }, { @@ -1223,8 +1315,11 @@ "default": [ {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": ["box_sodium", "default_backend_none_linked"], "why": "the only backend that has it: libsodium's own C code, which draws the key pair of each message from its own generator, the same on every target ({libsodium-sealed})"} ], + "capabilities": [ + {"name": "sealed_box", "kind": "use", "text": "the sealed box: `seal` to a public key, `open` with its key pair", "concept": "sealed_box", "engines": ["sealed_box_engine"]} + ], "backends": { - "sodium": {"targets": "all", "lane": {"native": ["memcheck", "msan"]}} + "sodium": {"capabilities": ["sealed_box"], "targets": "all", "lane": {"native": ["memcheck", "msan"]}} } }, { @@ -1240,8 +1335,11 @@ "default": [ {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "secp256k1", "tests": ["secp256k1_ellswift", "default_backend_none_linked"], "why": "the only backend ({libsecp256k1})"} ], + "capabilities": [ + {"name": "secp256k1_ellswift", "kind": "use", "text": "ElligatorSwift's encodings and BIP 324's shared secret", "engines": ["secp256k1_engine"]} + ], "backends": { - "secp256k1": {"targets": "all", "runtime": false, "lane": {"native": ["memcheck", "msan"]}, "lane_note": {"memcheck": "libsecp256k1's own `ctime_tests.c`, and webcpp's `ellswift_create` and `ellswift_xdh` around it", "msan": "the same paths as memcheck's"}} + "secp256k1": {"capabilities": ["secp256k1_ellswift"], "targets": "all", "runtime": false, "lane": {"native": ["memcheck", "msan"]}, "lane_note": {"memcheck": "libsecp256k1's own `ctime_tests.c`, and webcpp's `ellswift_create` and `ellswift_xdh` around it", "msan": "the same paths as memcheck's"}} } }, { @@ -1257,8 +1355,11 @@ "default": [ {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "secp256k1", "tests": ["secp256k1_musig", "default_backend_none_linked"], "why": "the only backend ({libsecp256k1})"} ], + "capabilities": [ + {"name": "secp256k1_musig", "kind": "use", "text": "MuSig2's aggregated keys, nonces and partial signatures", "engines": ["secp256k1_engine"]} + ], "backends": { - "secp256k1": {"targets": "all", "runtime": false, "lane": {"native": ["memcheck", "msan"]}, "lane_note": {"memcheck": "libsecp256k1's own `ctime_tests.c`, and webcpp's `generate_nonce` and `partial_sign` around it", "msan": "the same paths as memcheck's"}} + "secp256k1": {"capabilities": ["secp256k1_musig"], "targets": "all", "runtime": false, "lane": {"native": ["memcheck", "msan"]}, "lane_note": {"memcheck": "libsecp256k1's own `ctime_tests.c`, and webcpp's `generate_nonce` and `partial_sign` around it", "msan": "the same paths as memcheck's"}} } }, { @@ -1274,8 +1375,11 @@ "default": [ {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "secp256k1", "tests": ["secp256k1_silent_payments", "default_backend_none_linked"], "why": "the only backend ({libsecp256k1})"} ], + "capabilities": [ + {"name": "secp256k1_silent_payments", "kind": "use", "text": "BIP 352's silent payments: the sender's outputs and the recipient's scan", "engines": ["secp256k1_engine"]} + ], "backends": { - "secp256k1": {"targets": "all", "runtime": false, "lane": {"native": ["memcheck", "msan"]}, "lane_note": {"memcheck": "libsecp256k1's own `ctime_tests.c`, and webcpp's `create_outputs`, `create_label` and `scan_outputs` around it, each workspace's wipe included", "msan": "the same paths as memcheck's"}} + "secp256k1": {"capabilities": ["secp256k1_silent_payments"], "targets": "all", "runtime": false, "lane": {"native": ["memcheck", "msan"]}, "lane_note": {"memcheck": "libsecp256k1's own `ctime_tests.c`, and webcpp's `create_outputs`, `create_label` and `scan_outputs` around it, each workspace's wipe included", "msan": "the same paths as memcheck's"}} } }, { @@ -1292,8 +1396,21 @@ "default": [ {"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"} ], + "capabilities": [ + {"name": "p256_import", "kind": "import", "text": "`from_secret` of a P-256 key pair", "engines": ["p_curve_engine"]}, + {"name": "p256_generate", "kind": "generate", "text": "`generate` of a P-256 key pair drawn by the backend", "engines": ["p_curve_engine"]}, + {"name": "p256_public", "kind": "public", "text": "`public_key()` of a P-256 key pair", "engines": ["p_curve_engine"]}, + {"name": "p256_export", "kind": "export", "text": "`secret()`, `pkcs8` and the private PEM of a P-256 key pair", "engines": ["p_curve_engine"]}, + {"name": "p256_point", "kind": "auxiliary", "text": "a P-256 public key's points: checked on the curve, and decompressed", "engines": ["p_curve_engine"]}, + {"name": "p256_ecdsa_signing", "kind": "use", "form": "digest", "text": "ECDSA signing of a SHA-256 digest with a P-256 key pair", "engines": ["p_curve_engine"], "either": ["p256_ecdsa_message_signing"]}, + {"name": "p256_ecdsa_verifying", "kind": "use", "form": "digest", "text": "ECDSA verifying of a SHA-256 digest with a P-256 public key", "engines": ["p_curve_engine"], "either": ["p256_ecdsa_message_verifying"]}, + {"name": "p256_ecdsa_message_signing", "kind": "use", "form": "message", "text": "ECDSA signing of a message, hashed with SHA-256 inside the backend", "engines": ["p_curve_engine"], "either": ["p256_ecdsa_signing"]}, + {"name": "p256_ecdsa_message_verifying", "kind": "use", "form": "message", "text": "ECDSA verifying of a message, hashed with SHA-256 inside the backend", "engines": ["p_curve_engine"], "either": ["p256_ecdsa_verifying"]}, + {"name": "p256_ecdh", "kind": "use", "text": "`agree` of a P-256 key pair with a peer's public key", "engines": ["p_curve_engine"]}, + {"name": "p256_ecdsa_der", "kind": "auxiliary", "text": "a P-256 ECDSA signature's DER, written and read", "concept": "ecdsa_der", "engines": ["p_curve_engine"]} + ], "backends": { - "bearssl": {"targets": "all", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect_printed"]}, "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 the private formats, `pkcs8`, `raw` and `pem(pkcs8)` both ways; BearSSL's own branches on its signing's verdicts listed in `bearssl_verdicts.supp`; nothing found at webcpp's pin f8a2f3d, whose patches submitted upstream close upstream's leak of the nonce's bit length in `sign` that this checker found on 2026-11-21 and the jump on the scalar in P-256's scalar check that it found under `agree` on the x86-64 runner on 2026-12-03, `sign` with its low-S step included (Valgrind 3.22, arm64 Linux container, 2026-12-02; x86-64, `ctgrind` and `ctgrind_space`, 2026-12-04)", "msan": "the same paths as memcheck's; the same leak in `sign` on 2026-11-21 on upstream's BearSSL, nothing at webcpp's pin ae63032, `sign` with its low-S step included (clang 18, arm64 Linux container, 2026-12-02); MemorySanitizer checks the select of P-256's scalar check before the code generator makes it a jump, so the second patch changes nothing it sees", "dudect": "`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": {"capabilities": ["p256_import", "p256_public", "p256_export", "p256_point", "p256_ecdsa_signing", "p256_ecdsa_verifying", "p256_ecdh", "p256_ecdsa_der"], "targets": "all", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect_printed"]}, "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 the private formats, `pkcs8`, `raw` and `pem(pkcs8)` both ways; BearSSL's own branches on its signing's verdicts listed in `bearssl_verdicts.supp`; nothing found at webcpp's pin f8a2f3d, whose patches submitted upstream close upstream's leak of the nonce's bit length in `sign` that this checker found on 2026-11-21 and the jump on the scalar in P-256's scalar check that it found under `agree` on the x86-64 runner on 2026-12-03, `sign` with its low-S step included (Valgrind 3.22, arm64 Linux container, 2026-12-02; x86-64, `ctgrind` and `ctgrind_space`, 2026-12-04)", "msan": "the same paths as memcheck's; the same leak in `sign` on 2026-11-21 on upstream's BearSSL, nothing at webcpp's pin ae63032, `sign` with its low-S step included (clang 18, arm64 Linux container, 2026-12-02); MemorySanitizer checks the select of P-256's scalar check before the code generator makes it a jump, so the second patch changes nothing it sees", "dudect": "`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)"}} } } ], @@ -1455,7 +1572,8 @@ {"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": "`codecs::encode` and `codecs::decode` with `crypto::formats::raw`, `spki`, `pkcs8` and `pem`, on Ed25519's and X25519's keys", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//ed25519-default /webcpp/crypto//x25519-default", "example": "key_formats", "section": "crypto-key-formats"}, + {"need": "Export or import an Ed25519 or X25519 key in the standard forms OpenSSL and WebCrypto use: SPKI and PKCS#8 (RFC 8410), as DER or PEM text", "namespace": "webcpp::crypto::curves", "api": "`codecs::encode` and `codecs::decode` with `crypto::formats::raw`, `spki`, `pkcs8` and `pem`, on Ed25519's and X25519's keys", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//ed25519-default /webcpp/crypto//x25519-default", "example": "key_formats", "section": "crypto-key-formats", "operations": ["ed25519_formats", "x25519_formats"]}, + {"need": "Read or write an Ed25519 or X25519 public key in the standard forms OpenSSL and WebCrypto use, with no backend: raw or SPKI (RFC 8410), as DER or PEM text", "namespace": "webcpp::crypto::curves", "api": "`codecs::encode` and `codecs::decode` with `crypto::formats::raw`, `spki` and `pem(spki)`, on Ed25519's and X25519's public keys", "backend": "none", "jamfile": "/webcpp/crypto//crypto", "example": "key_formats", "section": "crypto-key-formats", "operations": ["ed25519_public_formats", "x25519_public_formats"]}, {"need": "Encrypt messages in a chat app, on the web and natively, each with a random nonce", "namespace": "webcpp::crypto::ciphers", "api": "`xchacha20_poly1305<>`: `from_key`, `seal`, `open`", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//xchacha20_poly1305-default", "example": "xchacha_seal", "section": "crypto-chacha"}, {"need": "Apply ChaCha20's keystream for a protocol that fixes its own construction (NIP-44)", "namespace": "webcpp::crypto::ciphers", "api": "`chacha20<>`: `from_key`, `apply_keystream(nonce, data, initial_counter)`; `unauthenticated_encryption::apply_keystream` in code written once for every stream cipher", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//chacha20-default", "example": "chacha20_keystream", "section": "crypto-chacha20"}, {"need": "Authenticate one message under a one-time key", "namespace": "webcpp::crypto::authenticators", "api": "`poly1305<>`: static `authenticate(key, message)`, `verify(key, message, tag)`; `single_use_key_authentication::authenticate` and `verify` in code written once for every single-use key authenticator", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//poly1305-default", "example": "poly1305_one_time_tag", "section": "crypto-poly1305"}, @@ -1711,6 +1829,16 @@ "sign_asynchronous_backend": "Call `async_sign` on a backend that completes by itself: its synchronous forms cannot wait for it.", "agree_asynchronous_backend": "Call `async_agree` on a backend that completes by itself: its synchronous forms cannot wait for it.", "x25519_asynchronous_backend": "Call `async_from_secret`, `async_generate` or `async_agree` on a backend that completes by itself: an X25519 key pair's synchronous forms cannot wait for it.", + "opaque_async_synchronous": "Call `async_generate`, `async_sign` or `async_agree` on a backend that completes by itself: a P-256 or X25519 key pair's synchronous forms cannot wait for it.", + "opaque_keys_kept": "Make the key pair with `generate` on a backend that keeps its keys, which no secret key enters or leaves, and keep the key pair itself: `crypto::imports_secret_keys_v` and `crypto::exports_secret_keys_v` name the backends that take and give secret bytes, through `from_secret`, `secret()` and a key pair's private formats.", + "opaque_async_from_secret": "Make the key pair with `async_generate` on a backend that keeps its keys: no secret key enters it, so it has no `async_from_secret`; `crypto::imports_secret_keys_v` names the backends that take one.", + "opaque_async_engine_missing": "Name, for the operation, a backend that completes by itself and whose engine has its asynchronous form, or a synchronous backend, which every `async_*` function takes; when `crypto::supports_v` says the backend has the operation, the error is a defect of the backend, not of the program: report it.", + "kept_async_engine_imports": "Make the key pair with `async_generate` on a backend that keeps its keys (`crypto::imports_secret_keys_v` is false); no secret key enters it, whatever its engine has.", + "p256_prehashed_message_only": "Sign and verify the message itself, which a backend with P-256's message form hashes, or name a backend with P-256's digest form, `crypto::capabilities::p256_ecdsa_signing` and `crypto::capabilities::p256_ecdsa_verifying`, for `sign` and `verify` of a digest: `crypto::supports_capability_v` says which backends have each.", + "p256_operation_named": "Name a backend whose P-256 has `crypto::capabilities::p256_point`, which `crypto::supports_capability_v` answers, to make a public key from its bytes; when `crypto::supports_capability_v` says the backend has it, the error is a defect of the backend, not of the program: report it.", + "secp256k1_other_backend_first": "As `secp256k1_other_backend`: name `crypto::backends::secp256k1`, libsecp256k1, for a secp256k1 key pair or public key.", + "chacha20_capability_missing": "Name a backend whose ChaCha20 has `crypto::capabilities::chacha20`, which `crypto::supports_capability_v` answers; when `crypto::supports_capability_v` says the backend has it, the error is a defect of the backend, not of the program: report it.", + "secretbox_capability_missing": "Name a backend whose secret box has `crypto::capabilities::secretbox_xsalsa20poly1305`, which `crypto::supports_capability_v` answers; when `crypto::supports_capability_v` says the backend has it, the error is a defect of the backend, not of the program: report it.", "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.", diff --git a/doc/tables/generate.py b/doc/tables/generate.py index 43db1b2..35966f8 100644 --- a/doc/tables/generate.py +++ b/doc/tables/generate.py @@ -36,7 +36,12 @@ claimed only where a named test runs), and its default per target with the reason. From it come the family and algorithm tags, `detail::supported`, which `supports_v` reads, the refusal of a backend without the family, which names the backends that have it, and the test that asserts each -cell and makes each present one. +cell and makes each present one. Each family lists its capabilities and each backend's cell those +its engines have (design D5, D7): from them come the capability tags, +`detail::capability_supported`, which `supports_capability_v` reads, the secret-key traits of each +backend row, `detail::shipped_backends`, and the test's two-way check of each cell against the +engines, which counts an engine only where its specialisation marker, +`detail::specialized_engine_v`, is true. Each fact is checked against the tree: a test, a message case, a fixture or an example that crypto.json names and the tree does not hold is a fault, and so is a fixture or a message case of @@ -122,7 +127,25 @@ TARGET_MACROS = {'native': 'WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE', 'wasip2': 'WEBCPP_TARGET_WASIP2', 'wasip3': 'WEBCPP_TARGET_WASIP3', 'emscripten': 'WEBCPP_TARGET_EMSCRIPTEN'} CAPABILITIES = Path('include/webcpp/crypto/detail/capabilities.hpp') +# The kinds of a family's capability (design D3, D7): what it does to a key (import, generate, +# public, export, which counts Ed25519's conversion to X25519 as it hands out a secret), an +# operation `supports_v` counts (use), or one on public values the family's types need besides +# (auxiliary: P-256's points and DER, secp256k1's points, signature forms and tweaks). +CAPABILITY_KINDS = ('import', 'generate', 'public', 'export', 'use', 'auxiliary') +# What each kind's tag says it is, in its Doc Comment. +CAPABILITY_TEXTS = { + 'import': 'a key made from secret bytes the program gives', + 'generate': 'a key whose secret the backend draws', + 'public': 'the public key of a key', + 'export': 'secret bytes of a key handed out of the backend', + 'use': 'an operation `supports_v` counts', + 'auxiliary': 'an operation on public values the family\'s types need', +} +# A backend row's traits (design D3's and D6's amendments), each true unless the row says false, +# with the kind of capability each governs. +SECRET_KEY_TRAITS = (('exports_secret_keys', 'export'), ('imports_secret_keys', 'import')) CAPABILITIES_TEST = Path('test/capabilities_test.cpp') +HEADER_FREE_TEST = Path('test/supports_header_free_test.cpp') DEFAULTS = Path('include/webcpp/crypto/detail/defaults.hpp') BUILD = Path('build.jam') # The lines around the block of build.jam that default_aliases writes. @@ -617,11 +640,24 @@ def check_user_globals(library: Path) -> None: raise Fault(f'{USER_GLOBALS_TEST}: <{header}> is no header of include/') +def check_header_free(data: Data, library: Path) -> None: + """Checks that test/supports_header_free_test.cpp refuses the header guard of every tag of + `backends`, so that a backend the table gains is one supports.hpp may not include either.""" + text = (library / HEADER_FREE_TEST).read_text(encoding='utf-8') + # The code alone: a guard named in a comment refuses nothing. + text = re.sub(r'/\*.*?\*/|//[^\n]*', '', text, flags=re.S) + for backend in tags_of(data): + guard = f'defined(WEBCPP_CRYPTO_BACKENDS_{backend.upper()}_HPP)' + if guard not in text: + raise Fault(f'{HEADER_FREE_TEST}: {guard} is not refused: supports.hpp may include ' + f'the header of {backend}') + + def check_families(data: Data, declared: Dict[str, List[str]]) -> None: """Checks crypto.json's families against its backends, its operations and the tests: a cell is claimed only for a tag of `backends`, on a target it is built for and where a test of the - family's operations on it runs; each target has one default, a backend that has the family - there, or none.""" + family's operations on it runs, and lists capabilities as check_capabilities asks; each target + has one default, a backend that has the family there, or none.""" names = {family['name'] for family in data['families']} for operation in data['operations']: if 'family' in operation and operation['family'] not in names: @@ -632,12 +668,15 @@ def check_families(data: Data, declared: Dict[str, List[str]]) -> None: if checker not in data.get('checkers', {}): raise Fault(f'crypto.json: unjudged_checkers names the checker {checker}, which ' 'checkers does not list') + for family in data['families']: + for backend in family['backends']: + if backend not in tags: + raise Fault(f'crypto.json: the family {family["name"]} names the backend ' + f'{backend}, which is no tag of backends') + check_capabilities(data) for family in data['families']: name = family['name'] for backend, entry in family['backends'].items(): - if backend not in tags: - raise Fault(f'crypto.json: the family {name} names the backend {backend}, which ' - 'is no tag of backends') built = data['backends'][backend]['targets'] claimed = built if entry['targets'] == 'all' else entry['targets'] tested: List[str] = [] @@ -738,6 +777,140 @@ def check_families(data: Data, declared: Dict[str, List[str]]) -> None: f'with {compiler}') +def concept_of(capability: Data) -> str: + """The concept of `detail::backend` a capability names: its `concept`, else its name.""" + return capability.get('concept', capability['name']) + + +def trait_of(data: Data, backend: str, trait: str) -> bool: + """A backend row's trait (design D3's and D6's amendments), true unless the row says false: + `exports_secret_keys` or `imports_secret_keys`.""" + return bool(data['backends'][backend].get(trait, True)) + + +def cell_capabilities(family: Data, backend: str) -> List[Data]: + """The capabilities a backend's cell of a family lists, in the family's order.""" + listed = family['backends'][backend]['capabilities'] + return [capability for capability in family['capabilities'] if capability['name'] in listed] + + +def uses_of(family: Data, name: str) -> List[List[str]]: + """The use operations `supports_v` counts for an algorithm of a family (design D7, R8), as + groups of which a backend needs one capability each: a use capability alone, or with the + forms it may stand for (`either`, P-256's digest and message forms).""" + groups: List[List[str]] = [] + for capability in family['capabilities']: + if capability['kind'] != 'use' or name not in capability.get('names', [name]): + continue + group = sorted([capability['name']] + capability.get('either', [])) + if group not in groups: + groups.append(group) + return groups + + +def check_capabilities(data: Data) -> None: + """Checks the capability cells (design D5, D7): each family lists its capabilities, each of a + known kind, a name no other family takes, and engines that name the backend; each backend's + cell lists some of them, the use operations of each of the family's algorithms among them; + and a backend row's traits agree with its cells.""" + seen: Dict[str, str] = {} + for family in data['families']: + name = family['name'] + algorithms = [entry['name'] for entry in family['names']] + capabilities = family.get('capabilities') + if not capabilities: + raise Fault(f'crypto.json: the family {name} lists no capabilities') + names = [capability['name'] for capability in capabilities] + for capability in capabilities: + tag = capability['name'] + if tag in seen: + raise Fault(f'crypto.json: the capability {tag} is listed by the families ' + f'{seen[tag]} and {name}') + seen[tag] = name + if capability['kind'] not in CAPABILITY_KINDS: + raise Fault(f'crypto.json: the capability {tag} of the family {name} is of the ' + f'kind {capability["kind"]}, which is none of ' + f'{", ".join(CAPABILITY_KINDS)}') + if not capability['engines'] or any('{backend}' not in engine + for engine in capability['engines']): + raise Fault(f'crypto.json: the capability {tag} of the family {name} names no ' + 'engine, or one that does not name {backend}') + text = capability.get('text', '') + concept = concept_of(capability) + if (not text or any(word in text for word in ('detail::', 'backend::', 'engine')) + or f'`{concept}`' in text or ('_' in concept and concept in text)): + raise Fault(f'crypto.json: the capability {tag} of the family {name} has no ' + 'text in a program\'s terms, which its public tag\'s comment says ' + '(design D10: no internal name)') + for other in capability.get('either', []): + partner = next((entry for entry in capabilities if entry['name'] == other), None) + if (partner is None or capability['kind'] != 'use' or partner['kind'] != 'use' + or tag not in partner.get('either', [])): + raise Fault(f'crypto.json: the capability {tag} of the family {name} may ' + f'stand for {other}, which is no use capability of the family ' + 'that may stand for it') + if 'form' not in capability or capability['form'] == partner.get('form'): + raise Fault(f'crypto.json: the capability {tag} of the family {name} may ' + f'stand for {other}, and the two do not name two forms') + for algorithm in capability.get('names', []): + if algorithm not in algorithms: + raise Fault(f'crypto.json: the capability {tag} of the family {name} is for ' + f'{algorithm}, which is none of its algorithms') + for algorithm in algorithms: + if not uses_of(family, algorithm): + raise Fault(f'crypto.json: the family {name} has no use capability for ' + f'{algorithm}, which supports_v would count') + for backend, entry in family['backends'].items(): + listed = entry.get('capabilities') + if not listed: + raise Fault(f'crypto.json: the family {name} lists no capability of {backend}') + for tag in listed: + if tag not in names: + raise Fault(f'crypto.json: the family {name} gives {backend} the capability ' + f'{tag}, which the family does not list') + if len(set(listed)) != len(listed): + raise Fault(f'crypto.json: the family {name} lists a capability of {backend} ' + 'twice') + for algorithm in algorithms: + for group in uses_of(family, algorithm): + if not any(tag in listed for tag in group): + raise Fault(f'crypto.json: the family {name} claims {backend}, whose ' + f'cell has none of {", ".join(group)}: supports_v counts ' + f'the use operations of {algorithm}') + check_one_form(family, backend, listed) + kinds = {capability['kind'] for capability in cell_capabilities(family, backend)} + if not trait_of(data, backend, 'exports_secret_keys') and 'export' in kinds: + raise Fault(f'crypto.json: {backend} exports no secret keys, and its cell of ' + f'the family {name} lists an export capability') + if not trait_of(data, backend, 'imports_secret_keys'): + if 'import' in kinds: + raise Fault(f'crypto.json: {backend} imports no secret keys, and its cell of ' + f'the family {name} lists an import capability') + if 'generate' not in kinds: + raise Fault(f'crypto.json: {backend} imports no secret keys and does not ' + f'generate the keys of the family {name}: it has no way to make ' + 'one') + + +def check_one_form(family: Data, backend: str, listed: List[str]) -> None: + """Checks that a cell has its uses that come in forms (`either`, P-256's digest and message + forms) in one form at least: a backend that signs a digest and verifies a message alone would + pass `supports_v`, though a program that signs and verifies in one form finds a half + missing.""" + forms = {capability['name']: capability['form'] for capability in family['capabilities'] + if 'form' in capability} + groups = [group for algorithm in family['names'] + for group in uses_of(family, algorithm['name']) if len(group) > 1] + if not groups: + return + common = set.intersection(*({forms[tag] for tag in group if tag in listed} + for group in groups)) + if not common: + raise Fault(f'crypto.json: the family {family["name"]} gives {backend} its uses in no ' + 'one form: a program that uses them in one form finds one missing (' + + '; '.join(', '.join(group) for group in groups) + ')') + + def default_on(family: Data, target: str) -> Optional[str]: """A family's default backend on a target, or None: its first row there (check_families faults a row that names another).""" @@ -846,6 +1019,13 @@ def capabilities_header(data: Data) -> str: f'`families::{family["name"]}`.') + [f'struct {entry["name"]};', ''] out += ['} // namespace webcpp::crypto::tags', ''] + out += ['namespace webcpp::crypto::capabilities {', ''] + for family in data['families']: + for capability in family['capabilities']: + out += doc_comment(f'The capability `{capability["name"]}` of the family ' + f'{family["title"]}, {CAPABILITY_TEXTS[capability["kind"]]}: ' + f'{capability["text"]}.') + [f'struct {capability["name"]};', ''] + out += ['} // namespace webcpp::crypto::capabilities', ''] out += ['namespace webcpp::crypto::detail {', '', '/**', ' * One cell of the capability table, doc/tables/crypto.json, on the target being', @@ -880,6 +1060,58 @@ def capabilities_header(data: Data) -> str: for backend in tags_of(data): out += [f'#ifdef WEBCPP_CRYPTO_HAS_{backend.upper()}', 'template <>', f'inline constexpr bool linked = true;', '#endif'] + out += ['', + '/**', + ' * One capability cell of the table on the target being compiled (design D7, R8):', + ' * whether `Backend`\'s engine has the capability `Capability`. False but where a', + ' * specialisation below makes it true.', + ' *', + ' * @tparam Capability A capability tag of `capabilities`.', + ' * @tparam Backend A backend tag of `backends`.', + ' */', + 'template ', + 'inline constexpr bool capability_supported = false;', '', + '// Each capability cell on its family\'s targets.', + '// clang-format off'] + for family in data['families']: + for backend in family['backends']: + targets = cell_targets(data, family, backend) + for capability in cell_capabilities(family, backend): + out += [opening(targets), 'template <>', + f'inline constexpr bool capability_supported = true;', '#endif'] + out += ['// clang-format on'] + for trait, kind in SECRET_KEY_TRAITS: + words = 'leave' if kind == 'export' else 'enter' + text = (f'Whether secret key bytes may {words} `Backend` (design D3\'s and D6\'s ' + f'amendments): the table\'s `{trait}` of its row, true unless the row says ' + 'false. False for any type that is no backend of the table.') + # The text's lines, then the parameter's paragraph, before the comment's end. + lines = doc_comment(text)[:-1] + out += [''] + lines + [' *', ' * @tparam Backend A backend tag of `backends`.', ' */', + 'template ', + f'inline constexpr bool {trait}_v = false;'] + for backend in tags_of(data): + if trait_of(data, backend, trait): + out += ['template <>', + f'inline constexpr bool {trait}_v = true;'] + shipped = ', '.join(f'backends::{backend}' for backend in tags_of(data)) + out += ['', + '/**', + ' * A list of backend tags.', + ' *', + ' * @tparam Backends The tags.', + ' */', + 'template ', + 'struct backend_list {};', '', + '/**', + ' * The backends crypto ships, every tag of `backends` built for a target of its own:', + ' * the list over which `capabilities_test` checks that an engine meeting a', + ' * capability\'s concept has its cell (design D5, R7).', + ' */', + '// clang-format off', + f'using shipped_backends = backend_list<{shipped}>;', + '// clang-format on'] out += ['', '} // namespace webcpp::crypto::detail', '', '// The body of each family\'s primary engine, which a backend reaches where its', '// header does not specialise the engine, per target: a backend without the family', @@ -1118,7 +1350,10 @@ def capabilities_test(data: Data) -> str: parsed.""" tags = tags_of(data) headers = sorted({family['header'] for family in data['families']} - | {'', ''}) + | {'', '', + '', + '', + ''}) out = ['// What doc/tables/crypto.json says of each cell of the capability table, on the', '// target being compiled: supports_v of each algorithm on each backend, true on the', '// cell\'s targets alone; each present cell made, where its backend is linked, through', @@ -1129,8 +1364,9 @@ def capabilities_test(data: Data) -> str: out += [f'#ifdef WEBCPP_CRYPTO_HAS_{backend.upper()}', f'#include {data["backends"][backend]["header"]}', '#endif'] out += ['', '#include "support/capabilities.hpp"', '', - '#include ', '', - 'namespace {', '', + '#include ', '', '#include ', ''] + out += engines_check(data) + out += ['namespace {', '', 'namespace crypto = webcpp::crypto;', 'namespace backends = webcpp::crypto::backends;', 'namespace families = webcpp::crypto::families;'] @@ -1152,6 +1388,8 @@ def capabilities_test(data: Data) -> str: present = backend in family['backends'] targets = cell_targets(data, family, backend) if present else [] out.append(f'// {family["title"]} on {backend}: {", ".join(targets) or "none"}.') + if not present: + out += capability_cells(family, backend, targets) for entry in family['names']: tag = tag_of(family, entry['name']) trait = (f'crypto::supports_v, ' @@ -1161,6 +1399,8 @@ def capabilities_test(data: Data) -> str: continue out += [opening(targets), f'static_assert({trait});', '#else', f'static_assert(!{trait});', '#endif'] + if entry is family['names'][-1]: + out += capability_cells(family, backend, targets) if 'type' not in entry: # A family of free functions names no type a program makes. continue @@ -1170,6 +1410,10 @@ def capabilities_test(data: Data) -> str: f' BOOST_TEST((webcpp::test::made<{algorithm}, ' f'families::{family["name"]}, {tag}, backends::{backend}>()));', '#endif'] + for backend in tags: + for trait, _ in SECRET_KEY_TRAITS: + value = '' if trait_of(data, backend, trait) else '!' + out.append(f'static_assert({value}crypto::{trait}_v);') # One check per cell, each a BOOST_TEST, which clang-tidy counts as a branch: main grows # with the table, so its complexity is the table's and not a function to split. out += ['// clang-format on', '', @@ -1181,6 +1425,109 @@ def capabilities_test(data: Data) -> str: return '\n'.join(out) +def capability_cells(family: Data, backend: str, targets: List[str]) -> List[str]: + """The test's lines that assert `supports_capability_v` of each capability of a family on a + backend: true on the cell's targets where its cell lists it, false elsewhere.""" + out: List[str] = [] + listed = family['backends'].get(backend, {}).get('capabilities', []) + for capability in family['capabilities']: + trait = (f'crypto::supports_capability_v') + if capability['name'] not in listed: + out.append(f'static_assert(!{trait});') + continue + out += [opening(targets), f'static_assert({trait});', '#else', + f'static_assert(!{trait});', '#endif'] + return out + + +def engines_check(data: Data) -> List[str]: + """The test's two-way check of the table against the engines (design D5, R7), over + `detail::shipped_backends`, on each backend the target links: a capability's cell is present + exactly where each of its engines is a specialisation (`specialized_engine_v`, which never + instantiates a refusing primary) that meets its concept; and the backend's traits agree with + its engines: none that exports no secret keys has an engine meeting an export concept, none + that imports none one meeting an import concept, and a family's key that one may import or + export has its import, or export, wherever it has its public key, or import.""" + out = ['namespace webcpp::crypto::detail::capability_check {', '', 'namespace {', '', + '// Per capability: whether an engine meets its concept, asked only of a marked', + '// engine (the primary false, the specialisation for a marked one reads the', + '// concept), and how many of its engines on a backend do, one engine a line. The', + '// formatter is off: an engine\'s type name, which the generator writes whole, makes', + '// lines it cannot break.', + '// clang-format off', ''] + for family in data['families']: + for capability in family['capabilities']: + name = capability['name'] + concept = concept_of(capability) + engines = [engine.replace('{backend}', 'Backend') for engine in capability['engines']] + arguments = ''.join(', ' + argument.replace('{backend}', 'Backend') + for argument in capability.get('arguments', [])) + out += doc_comment(f'Whether `Engine`, of `Backend`, is marked and meets ' + f'`backend::{concept}`, for the capability `{name}`.') + out += ['template >', + f'constexpr bool meets_{name} = false;', + '/** A marked engine: its concept. */', + 'template ', + f'constexpr bool meets_{name} = ' + f'backend::{concept};', ''] + counted = ' +\n '.join(f'(meets_{name} ? 1U : 0U)' + for engine in engines) + out += doc_comment(f'How many engines of the capability `{name}` on `Backend` are ' + f'marked and meet `backend::{concept}`.') + out += ['template ', f'constexpr std::size_t {name}() {{', + f' return {counted};', '}', ''] + out += ['// clang-format on', ''] + out += ['/**', ' * The table against `Backend`\'s engines, where the target links it: each', + ' * assertion instantiates with the class, which the fold below does.', ' *', + ' * @tparam Backend A backend tag of `detail::shipped_backends`.', ' */', + 'template ', 'struct table_meets_engines {', ' // clang-format off'] + for family in data['families']: + for capability in family['capabilities']: + name = capability['name'] + count = len(capability['engines']) + out += [f' static_assert(!linked || {name}() ==', + f' (capability_supported ' + f'? {count}U : 0U),', + f' "crypto.json\'s cell {name} disagrees with this backend\'s ' + 'engines: it is present exactly where each engine is specialised and meets ' + f'backend::{concept_of(capability)} (design D5)");'] + for trait, kind in SECRET_KEY_TRAITS: + governed = [capability['name'] for family in data['families'] + for capability in family['capabilities'] if capability['kind'] == kind] + total = ' + '.join(f'{name}()' for name in governed) + out += [f' static_assert(!linked || {trait}_v ||', + f' ({total}) == 0U,', + f' "a backend whose {trait}_v is false has an engine that meets ' + f'a {kind} concept");'] + # What the trait, true, asks of each family's key: its import where it has its public + # key, its exports where it has its import. + given, wanted = ('import', 'export') if kind == 'export' else ('public', 'import') + for family in data['families']: + first = [c['name'] for c in family['capabilities'] if c['kind'] == given] + then = [c for c in family['capabilities'] if c['kind'] == wanted] + if not first or not then: + continue + needed = ' && '.join(f'{c["name"]}() == {len(c["engines"])}U' for c in then) + out += [f' static_assert(!linked || !{trait}_v ||', + f' {first[0]}() == 0U || ({needed}),', + f' "a backend whose {trait}_v is true lacks ' + f'{family["title"]}\'s {wanted}, which its {given} asks");'] + out += [' // clang-format on', '', + ' /** Read by the fold below, which instantiates the class. */', + ' static constexpr bool checked = true;', '};', '', + '/**', ' * Checks the table against each shipped backend\'s engines.', ' *', + ' * @tparam Backends The backends of `detail::shipped_backends`.', ' * @return True.', + ' */', 'template ', + 'constexpr bool every_backend_checked(backend_list /*backends*/) {', + ' return (table_meets_engines::checked && ...);', '}', '', + 'static_assert(every_backend_checked(shipped_backends{}));', '', + '} // namespace', '', + '} // namespace webcpp::crypto::detail::capability_check', ''] + return out + + def stale(files: Dict[Path, str]) -> List[Path]: """The files that differ from what generate.py writes, or that do not exist.""" return sorted(path for path, text in files.items() @@ -1399,12 +1746,14 @@ def api_backends(data: Data, matrix: Matrix, operation: Data) -> str: rows: List[List[str]] = [] for backend in matrix.backends_of(operation['id']): facts = data['backends'][backend] - rows.append([facts['title'], code(facts['jamfile']), names(facts['header']), + # No backend has no header of its own: the operation's own header is the one to include. + header = operation['header'] if backend == 'none' else facts['header'] + rows.append([facts['title'], code(facts['jamfile']), names(header), matrix.describe(operation['id'], backend)]) text = (f'The backends of {names(operation["api"])}, from the test programs that run it:\n\n' + table(['Backend', 'Jamfile', 'Header', 'Targets'], rows, 'cols="1,2,2,4",')) name = operation.get('family') - if name is not None: + if name is not None and not runs_on_no_backend(matrix, operation): family = family_of(data, name) defaults = [[target_label(data, entry), default_title(data, entry)] for entry in family['default']] @@ -1442,6 +1791,49 @@ def matrix_page(data: Data, matrix: Matrix) -> str: return text +def capabilities_page(data: Data) -> str: + """The catalogue (design D4) as a program asks it: each family's capabilities, the family's + title spanning its rows, each with its tag of `capabilities`, its kind, what it gives and the + backends whose cell has it, with their targets where fewer than the backend's own.""" + lines = ['[cols="2h,3,1,4,3",options="header"]', '|===', + '|Family |Capability |Kind |What it gives |Backends'] + for family in data['families']: + capabilities = family['capabilities'] + for index, capability in enumerate(capabilities): + having: List[str] = [] + for backend in backend_order(data): + cells = family['backends'].get(backend) + if cells is None or capability['name'] not in cells['capabilities']: + continue + title = data['backends'][backend]['title'] + targets = cell_targets(data, family, backend) + if targets != [target for target in data['targets'] + if target in data['backends'][backend]['targets']]: + title += f" ({', '.join(targets)})" + having.append(title) + lines.append('') + if index == 0: + span = f'.{len(capabilities)}+' if len(capabilities) > 1 else '' + lines.append(f"{span}|{cell(family['title'])}") + lines.extend([f"|{code(capability['name'])}", f"|{capability['kind']}", + f"|{cell(marked(capability['text']))}", + f"|{', '.join(having) if having else 'none yet'}"]) + lines.append('|===') + return '\n'.join(lines) + '\n' + + +def secret_key_traits_page(data: Data) -> str: + """Each tag of `backends` with its secret-key traits (design D3's and D6's amendments): + whether a secret key's bytes leave it and whether they enter it.""" + traits: List[List[str]] = [] + for backend in tags_of(data): + traits.append([data['backends'][backend]['title'], + 'yes' if trait_of(data, backend, 'exports_secret_keys') else 'no', + 'yes' if trait_of(data, backend, 'imports_secret_keys') else 'no']) + return table(['Backend', 'Secret keys leave it (`exports_secret_keys_v`)', + 'Secret keys enter it (`imports_secret_keys_v`)'], traits) + + def facts_page(data: Data, matrix: Matrix) -> str: """Each backend: how a program names it, its Jamfile line, header and targets; then what it is, its library, licence, own API and allocation. Two tables, each as wide as the page.""" @@ -2203,11 +2595,17 @@ def first_comment(source: Path) -> str: return text -def llms_default(data: Data, operation: Data) -> str: +def runs_on_no_backend(matrix: Matrix, operation: Data) -> bool: + """Whether an operation runs on no backend alone (a public key's RFC 8410 formats): it has no + default to name, though its family has one for the family's other operations.""" + return set(matrix.backends_of(operation['id'])) == {'none'} + + +def llms_default(data: Data, matrix: Matrix, operation: Data) -> str: """An operation's default backend per target in llms.txt, from its own family's row ("none" - where the family has none).""" + where the family has none); nothing for an operation that runs on no backend.""" name = operation.get('family') - if name is None: + if name is None or runs_on_no_backend(matrix, operation): return '' defaults = [f'{default_title(data, entry)} on {target_label(data, entry)}' for entry in family_of(data, name)['default']] @@ -2245,7 +2643,7 @@ def llms(data: Data, matrix: Matrix, library: Path) -> str: if (operation['id'], backend) in matrix.supported) out.append(f'- [{operation["api"]}]({page}#{operation["section"]}): ' f'{operation["what"]} Header {operation["header"]}. Backends: {backends}.' - + llms_default(data, operation) + llms_uses(data, operation)) + + llms_default(data, matrix, operation) + llms_uses(data, operation)) out += [llms_entry(library, operation, function) for function in operation['functions']] out.append('') @@ -2322,6 +2720,7 @@ def generate(root: Path, library: Path) -> Dict[Path, str]: check_backend_sources(data, sorted(path.name for path in (library / 'src').glob('*.c'))) check_msvc_twins(library) check_user_globals(library) + check_header_free(data, library) generated = DOC / 'generated' files: Dict[Path, str] = {} performance = read_performance(library) @@ -2333,6 +2732,8 @@ def generate(root: Path, library: Path) -> Dict[Path, str]: operation) files[generated / 'matrix.adoc'] = matrix_page(data, matrix) files[generated / 'backend-facts.adoc'] = facts_page(data, matrix) + files[generated / 'capabilities.adoc'] = capabilities_page(data) + files[generated / 'secret-key-traits.adoc'] = secret_key_traits_page(data) files[generated / 'defaults.adoc'] = defaults_page(data) files[generated / 'constant-time.adoc'] = constant_time_page(data) files[generated / 'sizes.adoc'] = sizes_page(data, read_sizes(library)) diff --git a/doc/tables/generate_test.py b/doc/tables/generate_test.py index e5cfa60..9a280c1 100644 --- a/doc/tables/generate_test.py +++ b/doc/tables/generate_test.py @@ -17,13 +17,15 @@ decision table's link to its example, llms.txt's entry of a function, every backend's facts and own suite, every API page's default per target, the formats table's list read from formats.hpp, a format missing from either list, its columns and its PEM sizes), and the capability table's: its checks of -crypto.json's families, the refusals and cells of include/webcpp/crypto/detail/capabilities.hpp, the -cells test/capabilities_test.cpp asserts, and the comparison --check makes; and the size matrix's: -what each cell adds to the baseline per target, read from the lane sizes' tables (generate.py ---sizes), "not measured yet" where the lane has not built it, and the refusal of a table not built -at release, of a program measured twice or of no cell, and of doc/tables/sizes.json edited by hand. -generate.py --check proves only that the committed tables are what generate.py writes now: a reader -that regresses and is regenerated in the same change would pass it, and fails here. +crypto.json's families and their capability cells, the refusals, cells, capability cells and +traits of include/webcpp/crypto/detail/capabilities.hpp, the cells test/capabilities_test.cpp +asserts and its two-way check against the engines, and the comparison --check makes; and the size +matrix's: what each cell adds to the baseline per target, read from the lane sizes' tables +(generate.py --sizes), "not measured yet" where the lane has not built it, and the refusal of a +table not built at release, of a program measured twice or of no cell, and of +doc/tables/sizes.json edited by hand. generate.py --check proves only that the committed tables are +what generate.py writes now: a reader that regresses and is regenerated in the same change would +pass it, and fails here. Usage: generate_test.py [...]. The doc build runs it before generate.py --check (doc/Jamfile). Exit 0, or 1 at the first failing case. @@ -384,6 +386,12 @@ def test_the_decision_table_writes_no_jamfile_as_prose(scratch: Path) -> None: EVERY_TARGET = ['native', 'wasip2', 'wasip3', 'emscripten'] +# The engine of the small table's capabilities. +ENGINE = 'ed25519_engine' +# What a backend's cell of the small table lists: no generation of its own. +CELL = ['ed25519_import', 'ed25519_export', 'ed25519_signing'] + + def small_table() -> generate.Data: """A capability table of one family, Ed25519, on libsodium alone, beside BearSSL and a backend that is no tag of `backends` (the operating system's generator).""" @@ -405,7 +413,16 @@ def backend(title: str, name: str, jamfile: str) -> generate.Data: 'type': 'curves::ed25519::basic_keypair<{backend}>'}], 'default': [{'targets': EVERY_TARGET, 'backend': 'sodium', 'tests': ['ed25519'], 'why': 'the only backend ({rfc8032})'}], - 'backends': {'sodium': {'targets': 'all'}}}]} + 'capabilities': [ + {'name': 'ed25519_import', 'kind': 'import', 'text': '`from_secret`', + 'engines': [ENGINE]}, + {'name': 'ed25519_generate', 'kind': 'generate', 'text': '`generate`', + 'engines': [ENGINE]}, + {'name': 'ed25519_export', 'kind': 'export', 'text': '`secret()`', + 'engines': [ENGINE]}, + {'name': 'ed25519_signing', 'kind': 'use', 'text': 'signing', + 'engines': [ENGINE]}], + 'backends': {'sodium': {'capabilities': list(CELL), 'targets': 'all'}}}]} def a_fault(data: generate.Data, declared: dict[str, list[str]], wanted: str) -> None: @@ -519,6 +536,23 @@ def test_user_globals_includes_the_umbrella_but_its_formats_headers(scratch: Pat a_library_fault(generate.check_user_globals, scratch, 'is no header of include/') +def test_the_header_free_test_refuses_every_backend_s_header(scratch: Path) -> None: + data = small_table() + test = 'test/supports_header_free_test.cpp' + written(scratch, test, '#if defined(WEBCPP_CRYPTO_BACKENDS_BEARSSL_HPP) || ' + 'defined(WEBCPP_CRYPTO_BACKENDS_SODIUM_HPP)\n#error\n#endif\n') + generate.check_header_free(data, scratch) + written(scratch, test, '#if defined(WEBCPP_CRYPTO_BACKENDS_BEARSSL_HPP)\n#error\n#endif\n') + a_library_fault(lambda library: generate.check_header_free(data, library), scratch, + 'defined(WEBCPP_CRYPTO_BACKENDS_SODIUM_HPP) is not refused') + # A guard named in a comment alone refuses nothing. + written(scratch, test, '// defined(WEBCPP_CRYPTO_BACKENDS_SODIUM_HPP)\n/* also\n' + 'defined(WEBCPP_CRYPTO_BACKENDS_SODIUM_HPP) */\n' + '#if defined(WEBCPP_CRYPTO_BACKENDS_BEARSSL_HPP)\n#error\n#endif\n') + a_library_fault(lambda library: generate.check_header_free(data, library), scratch, + 'defined(WEBCPP_CRYPTO_BACKENDS_SODIUM_HPP) is not refused') + + def test_a_backend_without_a_family_is_refused_naming_those_that_have_it(_: Path) -> None: header = generate.capabilities_header(small_table()) assert ('static_assert(!std::is_same_v, ' @@ -540,7 +574,8 @@ def test_a_backend_without_a_family_is_refused_naming_those_that_have_it(_: Path def test_a_cell_decided_at_run_time_says_so(_: Path) -> None: data = small_table() - data['families'][0]['backends']['sodium'] = {'targets': ['native'], 'runtime': True} + data['families'][0]['backends']['sodium'] = {'capabilities': list(CELL), + 'targets': ['native'], 'runtime': True} assert generate.refusal(data, data['families'][0], 'bearssl') == ( 'webcpp::crypto: bearssl has no Ed25519. The backends that have it: sodium (native, at ' 'run time).') @@ -579,6 +614,217 @@ def test_the_generated_test_asserts_every_cell(_: Path) -> None: assert 'WEBCPP_CRYPTO_DETAIL_REFUSE_ED25519(Backend);' in test, test +def test_a_family_s_capabilities_are_checked(_: Path) -> None: + data = small_table() + del data['families'][0]['capabilities'] + a_fault(data, {'ed25519': EVERY_TARGET}, 'the family ed25519 lists no capabilities') + data = small_table() + data['families'][0]['capabilities'][0]['kind'] = 'secret' + a_fault(data, {'ed25519': EVERY_TARGET}, + 'the capability ed25519_import of the family ed25519 is of the kind secret') + data = small_table() + data['families'][0]['capabilities'][0]['engines'] = ['ed25519_engine'] + a_fault(data, {'ed25519': EVERY_TARGET}, + 'the capability ed25519_import of the family ed25519 names no engine, or one that') + data = small_table() + data['families'].append(dict(data['families'][0], name='x25519')) + a_fault(data, {'ed25519': EVERY_TARGET}, + 'the capability ed25519_import is listed by the families ed25519 and x25519') + data = small_table() + data['families'][0]['capabilities'][3]['names'] = ['ed25519ph'] + a_fault(data, {'ed25519': EVERY_TARGET}, + 'the capability ed25519_signing of the family ed25519 is for ed25519ph, which is ' + 'none of its algorithms') + data = small_table() + data['families'][0]['capabilities'][3]['kind'] = 'auxiliary' + a_fault(data, {'ed25519': EVERY_TARGET}, + 'the family ed25519 has no use capability for ed25519, which supports_v would count') + data = small_table() + del data['families'][0]['capabilities'][0]['text'] + a_fault(data, {'ed25519': EVERY_TARGET}, + 'the capability ed25519_import of the family ed25519 has no text in a program\'s ' + 'terms') + for internal in ('the concept `detail::backend::x`', 'its `backend::x`', + 'what its engine has', 'the `ed25519_import` concept', + 'ed25519_import, its concept'): + data = small_table() + data['families'][0]['capabilities'][0]['text'] = internal + a_fault(data, {'ed25519': EVERY_TARGET}, + 'the capability ed25519_import of the family ed25519 has no text in a ' + 'program\'s terms') + + +def test_a_cell_lists_known_capabilities_its_use_operations_among_them(_: Path) -> None: + data = small_table() + data['families'][0]['backends']['sodium']['capabilities'].append('ed25519_agreement') + a_fault(data, {'ed25519': EVERY_TARGET}, + 'the family ed25519 gives sodium the capability ed25519_agreement, which the family ' + 'does not list') + data = small_table() + data['families'][0]['backends']['sodium']['capabilities'].append('ed25519_import') + a_fault(data, {'ed25519': EVERY_TARGET}, + 'the family ed25519 lists a capability of sodium twice') + data = small_table() + data['families'][0]['backends']['sodium']['capabilities'].remove('ed25519_signing') + a_fault(data, {'ed25519': EVERY_TARGET}, + 'the family ed25519 claims sodium, whose cell has none of ed25519_signing: ' + 'supports_v counts the use operations of ed25519') + + +def two_forms() -> generate.Data: + """The small table with Ed25519's signing and verifying each in a digest and a message form, + as P-256's, and a cell of the digest forms.""" + data = small_table() + capabilities = data['families'][0]['capabilities'] + capabilities[3].update(form='digest', either=['ed25519_message_signing']) + capabilities += [ + {'name': 'ed25519_message_signing', 'kind': 'use', 'text': 'signing a message', + 'form': 'message', 'engines': [ENGINE], 'either': ['ed25519_signing']}, + {'name': 'ed25519_verifying', 'kind': 'use', 'text': 'verifying', 'form': 'digest', + 'engines': [ENGINE], 'either': ['ed25519_message_verifying']}, + {'name': 'ed25519_message_verifying', 'kind': 'use', 'text': 'verifying a message', + 'form': 'message', 'engines': [ENGINE], 'either': ['ed25519_verifying']}] + data['families'][0]['backends']['sodium']['capabilities'].append('ed25519_verifying') + return data + + +def test_a_use_in_either_form_satisfies_the_family_s_use(_: Path) -> None: + data = two_forms() + generate.check_capabilities(data) + assert generate.uses_of(data['families'][0], 'ed25519') == [ + ['ed25519_message_signing', 'ed25519_signing'], + ['ed25519_message_verifying', 'ed25519_verifying']] + # The message forms alone satisfy the uses too. + cell = data['families'][0]['backends']['sodium']['capabilities'] + cell.remove('ed25519_signing') + cell.remove('ed25519_verifying') + cell += ['ed25519_message_signing', 'ed25519_message_verifying'] + generate.check_capabilities(data) + # Neither form of verifying is no use of the algorithm. + cell.remove('ed25519_message_verifying') + a_fault(data, {'ed25519': EVERY_TARGET}, + 'the family ed25519 claims sodium, whose cell has none of ed25519_message_verifying, ' + 'ed25519_verifying: supports_v counts the use operations of ed25519') + data = two_forms() + del data['families'][0]['capabilities'][3]['either'] + a_fault(data, {'ed25519': EVERY_TARGET}, + 'the capability ed25519_message_signing of the family ed25519 may stand for ' + 'ed25519_signing, which is no use capability of the family that may stand for it') + + +def test_a_cell_has_its_uses_in_one_form(_: Path) -> None: + # Signing a digest and verifying a message alone: no one form has both. + data = two_forms() + cell = data['families'][0]['backends']['sodium']['capabilities'] + cell.remove('ed25519_verifying') + cell.append('ed25519_message_verifying') + a_fault(data, {'ed25519': EVERY_TARGET}, + 'the family ed25519 gives sodium its uses in no one form') + # Both forms of signing with one of verifying share that one. + cell.append('ed25519_message_signing') + generate.check_capabilities(data) + # Partners name two forms. + data = two_forms() + data['families'][0]['capabilities'][4]['form'] = 'digest' + a_fault(data, {'ed25519': EVERY_TARGET}, + 'the capability ed25519_signing of the family ed25519 may stand for ' + 'ed25519_message_signing, and the two do not name two forms') + + +def test_a_backend_s_traits_agree_with_its_cells(_: Path) -> None: + data = small_table() + data['backends']['sodium']['exports_secret_keys'] = False + a_fault(data, {'ed25519': EVERY_TARGET}, + 'sodium exports no secret keys, and its cell of the family ed25519 lists an export ' + 'capability') + data = small_table() + data['backends']['sodium']['imports_secret_keys'] = False + a_fault(data, {'ed25519': EVERY_TARGET}, + 'sodium imports no secret keys, and its cell of the family ed25519 lists an import ' + 'capability') + data = small_table() + data['backends']['sodium']['imports_secret_keys'] = False + data['families'][0]['backends']['sodium']['capabilities'].remove('ed25519_import') + a_fault(data, {'ed25519': EVERY_TARGET}, + 'sodium imports no secret keys and does not generate the keys of the family ed25519: ' + 'it has no way to make one') + data['families'][0]['backends']['sodium']['capabilities'].append('ed25519_generate') + generate.check_capabilities(data) + header = generate.capabilities_header(data) + assert ('inline constexpr bool imports_secret_keys_v = false;\ntemplate <>\n' + 'inline constexpr bool imports_secret_keys_v = true;\n\n') in ( + header), header + assert 'inline constexpr bool exports_secret_keys_v = true;\n' in header + + +def test_the_header_writes_each_capability_s_tag_and_cell(_: Path) -> None: + data = small_table() + data['families'][0]['backends']['sodium']['targets'] = ['native', 'wasip3'] + header = generate.capabilities_header(data) + assert ('namespace webcpp::crypto::capabilities {\n\n/**\n * The capability `ed25519_import` ' + 'of the family Ed25519, a key made from secret bytes the program\n * gives: ' + '`from_secret`.\n */\nstruct ed25519_import;\n') in header, header + # The public tags' comments name no internal concept (design D10): the generated test alone + # writes the concepts. + tags = header[header.index('namespace webcpp::crypto::capabilities {'): + header.index('} // namespace webcpp::crypto::capabilities')] + assert 'detail::backend' not in tags and 'backend::' not in tags, tags + assert ('#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP3)\n' + 'template <>\ninline constexpr bool capability_supported = true;\n#endif\n') in header, header + # A capability the cell does not list has no cell. + assert 'capability_supported;\n' + ) in header, header + + +def two_engines() -> generate.Data: + """The small table whose signing has two engines.""" + data = small_table() + data['families'][0]['capabilities'][3]['engines'].append( + 'ed25519ph_engine') + return data + + +def test_the_generated_test_checks_the_engines_both_ways(_: Path) -> None: + test = generate.capabilities_test(small_table()) + # Each capability asks its concept of a marked engine alone, and counts those that meet it. + assert ('template >\n' + 'constexpr bool meets_ed25519_export = false;\n/** A marked engine: its concept. */\n' + 'template \n' + 'constexpr bool meets_ed25519_export = ' + 'backend::ed25519_export;\n') in test, test + assert ('template \nconstexpr std::size_t ed25519_export() {\n return ' + '(meets_ed25519_export> ? 1U : ' + '0U);\n}\n') in test, test + # One engine a line where a capability has several. + test_of_two = generate.capabilities_test(two_engines()) + assert (' return (meets_ed25519_signing> ? 1U : 0U) +\n (meets_ed25519_signing> ? 1U : 0U);\n') in test_of_two, ( + test_of_two) + assert 'engines of the capability `ed25519_signing`' in test_of_two, test_of_two + # The cell is present exactly where they all do, on each backend the target links. + assert ('static_assert(!linked || ed25519_generate() ==\n' + ' (capability_supported ' + '? 1U : 0U),\n "crypto.json\'s cell ed25519_generate disagrees' + ) in test, test + # The traits against the engines: none of the governed kind where false; a key's export + # where it imports, its import where it has its public key, where true. + assert ('static_assert(!linked || exports_secret_keys_v ||\n' + ' (ed25519_export()) == 0U,\n') in test, test + assert ('static_assert(!linked || !exports_secret_keys_v ||\n' + ' ed25519_import() == 0U || ' + '(ed25519_export() == 1U),\n') in test, test + assert 'static_assert(every_backend_checked(shipped_backends{}));\n' in test, test + # supports_capability_v of every capability on every backend, and the traits. + assert ('static_assert(!crypto::supports_capability_v);\n') in test, test + assert ('static_assert(!crypto::supports_capability_v);\n') in test, test + assert 'static_assert(crypto::imports_secret_keys_v);\n' in test, test + + def test_a_family_that_names_an_unknown_backend_is_a_fault(_: Path) -> None: data = small_table() data['families'][0]['backends']['botan'] = {'targets': 'all'} @@ -672,7 +918,7 @@ def two_backends() -> generate.Data: alone, BearSSL elsewhere.""" data = small_table() family = data['families'][0] - family['backends']['bearssl'] = {'targets': 'all'} + family['backends']['bearssl'] = {'capabilities': list(CELL), 'targets': 'all'} family['shown'] = 'ed25519' family['default'] = [a_default(['native'], 'sodium'), a_default(['wasip2', 'wasip3', 'emscripten'], 'bearssl')] @@ -709,18 +955,19 @@ def test_the_other_backend_a_refusal_names_is_chosen_as_stated(_: Path) -> None: # the family on the target when the program is built; the type is the family's shown name. data = two_backends() family = data['families'][0] - family['backends'] = {'sodium': {'targets': 'all'}, 'bearssl': {'targets': 'all'}} + family['backends'] = {'sodium': {'capabilities': list(CELL), 'targets': 'all'}, + 'bearssl': {'capabilities': list(CELL), 'targets': 'all'}} family['names'].append({'name': 'ed25519ph', 'title': 'Ed25519ph', 'type': 'curves::ed25519ph::keypair<{backend}>'}) text = generate.needs(data, family, 'native', 'sodium') assert 'as in curves::ed25519::basic_keypair.' in text, text # A backend that has the family only at run time is never offered in its place. - family['backends']['bearssl'] = {'targets': 'all', 'runtime': True} + family['backends']['bearssl'] = {'capabilities': list(CELL), 'targets': 'all', 'runtime': True} text = generate.needs(data, family, 'native', 'sodium') assert 'and the one backend that has it there' in text, text assert 'name another backend' not in text, text # A family whose default has another backend must say which name its refusal shows. - family['backends']['bearssl'] = {'targets': 'all'} + family['backends']['bearssl'] = {'capabilities': list(CELL), 'targets': 'all'} data['operations'][0]['backends']['bearssl'] = {'tests': ['ed25519']} del family['shown'] a_fault(data, {'ed25519': EVERY_TARGET}, 'the family ed25519 has no shown name, which its ' @@ -995,7 +1242,7 @@ def test_the_size_matrix_reads_the_lane_s_tables(_: Path) -> None: def test_a_cell_the_backend_does_not_have_says_so(_: Path) -> None: data = sized_table() - data['families'][0]['backends']['sodium'] = {'targets': ['native']} + data['families'][0]['backends']['sodium'] = {'capabilities': list(CELL), 'targets': ['native']} sizes = generate.imported([lane_table('native', {'baseline': 0, 'ed25519_sodium': 1})]) page = generate.sizes_page(data, sizes) assert ('|+1 B, gzip +0 B\n' @@ -1412,6 +1659,30 @@ def test_every_backend_s_facts_and_design_are_written_with_its_own_suite(_: Path assert 'The system' not in facts and 'The system' not in page, (facts, page) +def test_the_catalogue_names_each_capability_and_its_backends(_: Path) -> None: + data = small_table() + data['backends']['bearssl']['imports_secret_keys'] = False + family = data['families'][0] + family['backends']['bearssl'] = {'capabilities': ['ed25519_signing'], + 'targets': ['native', 'wasip2']} + page = generate.capabilities_page(data) + # A capability a cell lists names its backends, with the cell's targets where they are fewer + # than the backend's own; one no cell lists says so. Each is named by its tag of + # `capabilities`, which the page's text names once. + # The family's title spans its rows. + assert '\n.4+|Ed25519\n|`+ed25519_import+`\n|import\n' in page, page + assert ('\n|`+ed25519_signing+`\n|use\n|signing\n' + '|BearSSL (native, wasip2), libsodium\n') in page, page + assert '\n|`+ed25519_generate+`\n|generate\n|`+generate+`\n|none yet\n' in page, page + # The catalogue is one table; the traits are a page of their own. + assert page.count('|===') == 2 and 'imports_secret_keys' not in page, page + traits = generate.secret_key_traits_page(data) + # Each tag of `backends` has its traits, true unless its row says false; the system's + # generator, no tag, has none. + assert '\n|BearSSL\n|yes\n|no\n' in traits and '\n|libsodium\n|yes\n|yes\n' in traits, traits + assert 'The system' not in traits, traits + + def test_the_namespaces_and_backends_come_from_the_data(_: Path) -> None: data = {'namespaces': {'pq': {'title': 'webcpp::crypto::post_quantum'}}, 'backends': {'zeta': {}, 'alpha': {}}} @@ -1797,11 +2068,32 @@ def test_llms_gives_no_default_where_the_family_has_none(_: Path) -> None: data = small_table() data['families'][0]['default'] = [{'targets': EVERY_TARGET, 'backend': None, 'tests': [], 'why': 'none'}] - operation = {'family': 'ed25519', 'default': '`x<>` names the default.'} - assert generate.llms_default(data, operation) == ( + operation = dict(data['operations'][0], default='`x<>` names the default.') + matrix = generate.Matrix(data, {'ed25519': EVERY_TARGET}, {}) + assert generate.llms_default(data, matrix, operation) == ( ' Default: none on native, wasip2, wasip3, emscripten.') +def test_an_operation_on_no_backend_names_no_default_and_its_own_header(_: Path) -> None: + data = small_table() + data['backends']['none'] = {'title': 'no backend', 'jamfile': '/webcpp/crypto//crypto', + 'header': '', 'targets': EVERY_TARGET} + data['operations'].append({'id': 'public_formats', 'family': 'ed25519', + 'api': 'curves::ed25519::public_key::encode', + 'header': '', + 'backends': {'none': {'tests': ['rfc8410_no_backend']}}}) + matrix = generate.Matrix( + data, {'ed25519': EVERY_TARGET, 'rfc8410_no_backend': EVERY_TARGET}, {}) + operation = data['operations'][1] + assert generate.llms_default(data, matrix, operation) == '' + assert generate.llms_default(data, matrix, data['operations'][0]) == ( + ' Default: libsodium on native, wasip2, wasip3, emscripten.') + page = generate.api_backends(data, matrix, operation) + assert '' in page, page + assert '' not in page, page + assert 'takes the family\'s default' not in page, page + + def block_and_gcm() -> generate.Data: """A table of AES-GCM and the AES block cipher it is built on, each with its own default: OpenSSL natively for both, then BearSSL for AES-GCM and ctaes for the block cipher on @@ -1819,7 +2111,10 @@ def family(name: str, title: str, wasm_backend: str, shown: str) -> generate.Dat 'why': 'w'}, {'targets': wasm, 'backend': wasm_backend, 'tests': ['t'], 'why': 'w'}], - 'backends': {'openssl': {'targets': 'all'}, wasm_backend: {'targets': 'all'}}} + 'capabilities': [{'name': name, 'kind': 'use', 'text': title, + 'engines': [f'{name}<{{backend}}>']}], + 'backends': {'openssl': {'capabilities': [name], 'targets': 'all'}, + wasm_backend: {'capabilities': [name], 'targets': 'all'}}} return { 'targets': EVERY_TARGET, 'sources': {}, 'compilers': {'clang': 'Clang', 'gcc': 'GCC', 'msvc': 'MSVC'}, @@ -1874,7 +2169,7 @@ def test_a_cipher_has_its_own_default_apart_from_the_mode_built_on_it(_: Path) - 'program links,') in page, page assert '|wasip2, wasip3, emscripten\n|ctaes\n' in page, page assert 'BearSSL\n' not in page.split('reasons and tests:', 1)[1], page - assert generate.llms_default(data, data['operations'][1]) == ( + assert generate.llms_default(data, matrix, data['operations'][1]) == ( ' Default: OpenSSL on native; ctaes on wasip2, wasip3, emscripten.') @@ -1896,6 +2191,27 @@ def test_a_namespace_table_is_split_into_its_parts(_: Path) -> None: else: raise AssertionError('a row left out of every part was written') + +def unlisted_cases(names: dict[str, object], + cases: list[Callable[[Path], None]]) -> list[str]: + """The cases a module defines and does not list: they would never run.""" + return sorted(name for name, value in names.items() + if name.startswith('test_') and callable(value) and value not in cases) + + +def test_a_case_defined_and_not_listed_is_found(_: Path) -> None: + def test_listed(_: Path) -> None: + pass + + def test_forgotten(_: Path) -> None: + pass + + names = {'test_listed': test_listed, 'test_forgotten': test_forgotten, + 'test_data': 'not a case', 'helper': test_forgotten} + assert unlisted_cases(names, [test_listed]) == ['test_forgotten'] + assert unlisted_cases(names, [test_listed, test_forgotten]) == [] + + CASES: list[Callable[[Path], None]] = [ test_a_rule_body_declares_nothing, test_a_program_inside_an_if_is_a_fault, @@ -1922,6 +2238,13 @@ def test_a_namespace_table_is_split_into_its_parts(_: Path) -> None: test_a_cell_decided_at_run_time_says_so, test_each_cell_is_true_on_its_targets_alone, test_the_generated_test_asserts_every_cell, + test_a_family_s_capabilities_are_checked, + test_a_cell_lists_known_capabilities_its_use_operations_among_them, + test_a_use_in_either_form_satisfies_the_family_s_use, + test_a_cell_has_its_uses_in_one_form, + test_a_backend_s_traits_agree_with_its_cells, + test_the_header_writes_each_capability_s_tag_and_cell, + test_the_generated_test_checks_the_engines_both_ways, test_a_family_that_names_an_unknown_backend_is_a_fault, test_a_cell_claimed_where_no_test_runs_is_a_fault, test_a_default_is_a_backend_of_the_family_its_tests_run_on, @@ -1957,6 +2280,7 @@ def test_a_namespace_table_is_split_into_its_parts(_: Path) -> None: test_the_formats_table_has_a_row_per_type_and_the_pem_sizes_of_rfc_7468, test_llms_lists_a_function_with_its_use_case_and_backends, test_every_backend_s_facts_and_design_are_written_with_its_own_suite, + test_the_catalogue_names_each_capability_and_its_backends, test_the_namespaces_and_backends_come_from_the_data, test_every_api_page_lists_its_default_per_target, test_a_use_case_joins_the_operation_it_names, @@ -1981,16 +2305,24 @@ def test_a_namespace_table_is_split_into_its_parts(_: Path) -> None: test_an_unjudged_checker_is_written_with_no_result, test_an_unjudged_checker_must_be_a_checker, test_llms_gives_no_default_where_the_family_has_none, + test_an_operation_on_no_backend_names_no_default_and_its_own_header, test_a_cipher_has_its_own_default_apart_from_the_mode_built_on_it, test_a_namespace_table_is_split_into_its_parts, test_a_without_b2_text_names_every_c_file_of_the_backend, test_a_message_test_without_its_msvc_twin_is_refused, test_a_twin_whose_path_windows_refuses_is_refused_and_a_declared_name_counts, test_user_globals_includes_the_umbrella_but_its_formats_headers, + test_the_header_free_test_refuses_every_backend_s_header, + test_a_case_defined_and_not_listed_is_found, ] def main(argv: list[str]) -> int: + # A case defined and not listed would never run: refuse it. + unlisted = unlisted_cases(globals(), CASES) + if unlisted: + print(f'generate_test: cases not in CASES: {", ".join(unlisted)}', file=sys.stderr) + return 2 unknown = set(argv) - {case.__name__ for case in CASES} if unknown: print(f'generate_test: no case named {", ".join(sorted(unknown))}', file=sys.stderr) diff --git a/include/webcpp/crypto/async.hpp b/include/webcpp/crypto/async.hpp index f0e31e9..c61ae2f 100644 --- a/include/webcpp/crypto/async.hpp +++ b/include/webcpp/crypto/async.hpp @@ -127,6 +127,8 @@ #include #include #include +#include +#include #include #include #include @@ -164,7 +166,8 @@ namespace detail { /** * The operations of a backend that completes by itself: part B specialises it for - * `backends::browser`. Declared only: no synchronous backend reaches it. + * `backends::browser`, and the tests' opaque backend (`test/backends/opaque.hpp`) does too. + * Declared only: no synchronous backend reaches it. * * Each asynchronous function whose backend satisfies @ref asynchronous_backend_v calls one static * member function of the specialisation and returns its result, the completion token's @@ -201,8 +204,14 @@ namespace detail { * The signatures of the completions are the public functions'. The function's guard * (`webcpp::secure::timing_guard`, secure's guard) is held by the public function (the member, and * the free function that calls it) before it calls the engine. - * - * @tparam Backend `backends::browser`. + * These shapes are the asynchronous capability concepts of `detail/backend/asynchronous.hpp` + * (`async_import_secret`, `async_import_key`, `async_generate`, `async_seal`, `async_open`, + * `async_sign`, `async_verify`, `async_agree`); there is no asynchronous export: a backend that + * completes by itself keeps every key non-extractable, so its keys never leave it and there is no + * export to give. + * + * @tparam Backend A backend that completes by itself, part B's `backends::browser` or the tests' + * opaque backend, whose @ref asynchronous_backend_v is true. */ template struct async_engine; @@ -284,6 +293,24 @@ auto complete_by_post(Executor const& completion_executor, CompletionToken& comp post_initiation{}, completion_token, completion_executor, std::move(bound_call)); } +/** + * The completion of an asynchronous operation whose engine lacks its form (design D9), after the + * assertion that names the form stopped the build: never compiled into a program, it gives the + * completion token the signature the operation has, so that the assertion is the build's only + * error. + * + * @tparam Result The operation's result, `boost::system::result` or + * `boost::system::result`. + * @param completion_executor The executor the completion would be posted to. + * @param completion_token The completion token. + * @return What the completion token's `async_result` gives. + */ +template +auto refused_by_engine(Executor const& completion_executor, CompletionToken& completion_token) { + return complete_by_post(completion_executor, completion_token, + []() noexcept { return Result(error::backend_failure); }); +} + /** * 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 @@ -319,9 +346,23 @@ struct p256_engine_verify_initiation { 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)); + constexpr bool verifies = + detail::backend::async_verify, signing_schemes::ecdsa_sha256_t, + Policy, Signature, PublicKey, Executor, Handler>; + static_assert(verifies, + "webcpp::crypto: this backend completes by itself, and its engine has no " + "async_verify: async_verify is not available on it."); + if constexpr (verifies) { + async_engine::verify(completion_executor, signing_schemes::ecdsa_sha256, + verification_policy, signature_value, signing_input, + *public_key, std::forward(completion_handler)); + } else { + // Never compiled into a program: the assertion above stopped the build. + boost::system::error_code const refused = error::backend_failure; + webcpp::asio::post( + completion_executor, + webcpp::asio::append(std::forward(completion_handler), refused)); + } } }; @@ -563,8 +604,26 @@ auto initiate_from_secret(Executor const& completion_executor, CompletionToken&& completion_token) { using backend = Keypair::backend_type; if constexpr (asynchronous_backend_v) { - return async_engine::template from_secret( - completion_executor, secret_bytes, std::forward(completion_token)); + // The trait first, then the capability (design D6's amendment, D9). + constexpr bool imports = + detail::backend::async_import_secret, Keypair, Executor, + CompletionToken>; + static_assert(imports_secret_keys_v, + "webcpp::crypto: this backend keeps its keys: no secret key enters it " + "(crypto::imports_secret_keys_v is false), so async_from_secret is not " + "available on it; make a key with async_generate."); + static_assert(!imports_secret_keys_v || imports, + "webcpp::crypto: this backend completes by itself, and its engine has no " + "async_import_secret: async_from_secret is not available on it."); + if constexpr (imports_secret_keys_v && imports) { + return async_engine::template from_secret( + completion_executor, secret_bytes, std::forward(completion_token)); + } else { + // Never compiled into a program: an assertion above stopped the build. + return complete_by_post(completion_executor, completion_token, []() noexcept { + return boost::system::result(error::backend_failure); + }); + } } else { return complete_by_post(completion_executor, completion_token, [secret_bytes]() noexcept { return Keypair::from_secret(secret_bytes); @@ -588,8 +647,19 @@ auto initiate_from_key(Executor const& completion_executor, std::span) { - return async_engine::template from_key( - completion_executor, key_bytes, std::forward(completion_token)); + constexpr bool imports = detail::backend::async_import_key, Cipher, + Executor, CompletionToken>; + static_assert(imports, + "webcpp::crypto: this backend completes by itself, and its engine has no " + "async_import_key: async_from_key is not available on it."); + if constexpr (imports) { + return async_engine::template from_key( + completion_executor, key_bytes, std::forward(completion_token)); + } else { + // Never compiled into a program: the assertion above stopped the build. + return refused_by_engine>(completion_executor, + completion_token); + } } else { return complete_by_post(completion_executor, completion_token, [key_bytes]() noexcept { return Cipher::from_key(key_bytes); }); @@ -610,8 +680,19 @@ template auto initiate_generate(Executor const& completion_executor, CompletionToken&& completion_token) { using backend = Keypair::backend_type; if constexpr (asynchronous_backend_v) { - return async_engine::template generate( - completion_executor, std::forward(completion_token)); + constexpr bool generates = detail::backend::async_generate, Keypair, + Executor, CompletionToken>; + static_assert(generates, + "webcpp::crypto: this backend completes by itself, and its engine has no " + "async_generate: async_generate is not available on it."); + if constexpr (generates) { + return async_engine::template generate( + completion_executor, std::forward(completion_token)); + } else { + // Never compiled into a program: the assertion above stopped the build. + return refused_by_engine>(completion_executor, + completion_token); + } } else { return complete_by_post(completion_executor, completion_token, []() noexcept { return Keypair::generate(); }); @@ -620,9 +701,10 @@ auto initiate_generate(Executor const& completion_executor, CompletionToken&& co /** * The initiation of `async_sign` once its guard is held, for the free function and the member: - * the key pair, the scheme and the input checked as `crypto::can_sign` checks them, then the - * engine of a backend that completes by itself, or `key_pair.sign` run when the operation is - * initiated. + * the key pair, the scheme and the input checked as `crypto::can_sign` checks the scheme and the + * input (a digest on a synchronous backend without the curve's digest form is refused by + * `key_pair.sign`, by its own message), then the engine of a backend that completes by itself, or + * `key_pair.sign` run when the operation is initiated. * * @tparam Keypair An Ed25519 or a P-256 key pair. * @param completion_executor The executor the completion is posted to. @@ -636,14 +718,28 @@ template ) { + // The scheme and the input as `can_sign` checks them; a digest on a backend without the + // curve's digest form is the synchronous `sign`'s to refuse, by its own message. + if constexpr (!signs_with_v || + !input_valid_v::type>) { refuse_async_sign(); } else { using backend = Keypair::backend_type; if constexpr (asynchronous_backend_v) { - return async_engine::sign(completion_executor, key_pair, signing_scheme, - kept_input(signing_input), - std::forward(completion_token)); + constexpr bool signs = detail::backend::async_sign, Keypair, + Scheme, Executor, CompletionToken>; + static_assert(signs, + "webcpp::crypto: this backend completes by itself, and its engine has no " + "async_sign: async_sign is not available on it."); + if constexpr (signs) { + return async_engine::sign(completion_executor, key_pair, signing_scheme, + kept_input(signing_input), + std::forward(completion_token)); + } else { + // Never compiled into a program: the assertion above stopped the build. + return refused_by_engine>>( + completion_executor, completion_token); + } } else { return complete_by_post( completion_executor, completion_token, @@ -657,7 +753,8 @@ 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, 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 + * `crypto::can_verify` checks the scheme, the policy, the signature and the input, 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. * @@ -690,10 +787,22 @@ auto initiate_verify_ed25519(Executor const& completion_executor, Signature cons } else if constexpr (!input_valid_v) { check_input(); } else if constexpr (asynchronous_backend_v) { - return async_engine::verify(completion_executor, signing_schemes::eddsa, - verification_policies::canonical, signature_value, - kept_input(signing_input), public_key, - std::forward(completion_token)); + constexpr bool verifies = detail::backend::async_verify< + async_engine, signing_schemes::eddsa_t, verification_policies::canonical_t, + curves::ed25519::signature, curves::ed25519::public_key, Executor, CompletionToken>; + static_assert(verifies, + "webcpp::crypto: this backend completes by itself, and its engine has no " + "async_verify: async_verify is not available on it."); + if constexpr (verifies) { + 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 { + // Never compiled into a program: the assertion above stopped the build. + return refused_by_engine>(completion_executor, + completion_token); + } } else { return complete_by_post( completion_executor, completion_token, @@ -1266,9 +1375,11 @@ void async_verify(Arguments&&... /*arguments*/) noexcept { * 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 - * that completes by itself (WebCrypto has no prehash mode). `key_pair` and the bytes the input + * The key pair, the scheme and the input are checked as `crypto::can_sign` checks the scheme and + * the input, before anything else: another pair stops the build with its reason, and so does a + * marker on a backend that completes by itself (WebCrypto has no prehash mode); a digest on a + * synchronous backend without P-256's digest form is refused by the key pair's `sign`, by its own + * message. `key_pair` and the bytes the input * views are the caller's until the completion. * * @tparam Keypair A `curves::ed25519::basic_keypair` or a @@ -1346,10 +1457,11 @@ void async_sign([[maybe_unused]] Executor const& completion_executor, * 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 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. + * The policy, the signature and the input are checked as `crypto::can_verify` checks the scheme, + * the policy, the signature and the input, 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). @@ -1391,10 +1503,11 @@ auto async_verify(Executor const& completion_executor, signing_schemes::eddsa_t * 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 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. + * The policy, the signature and the input are checked as `crypto::can_verify` checks the scheme, + * the policy, the signature and the input, 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). @@ -1445,9 +1558,11 @@ auto async_verify(Executor const& completion_executor, * * 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: - * 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 + * signature and the input are checked as `crypto::can_verify` checks the scheme, the policy, the + * signature and the input, before anything else: another policy stops the build, as does a + * signature of another type, bytes included, and a marker on a backend that completes by itself; + * a digest on a synchronous backend without P-256's digest form is refused by the key's `verify`, + * by its own message. 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 @@ -1663,9 +1778,21 @@ auto ciphers::gcm::async_seal(Executor const& completion_executor, CompletionToken&& completion_token) { secure::timing_guard const timing_scope; if constexpr (detail::asynchronous_backend_v) { - return detail::async_engine::seal(completion_executor, *this, nonce_bytes, - associated_data_bytes, data_bytes, - std::forward(completion_token)); + constexpr bool seals = detail::backend::async_seal, gcm, + Executor, CompletionToken>; + static_assert(seals, + "webcpp::crypto: this backend completes by itself, and its engine has no " + "async_seal: async_seal is not available on it."); + if constexpr (seals) { + return detail::async_engine::seal( + completion_executor, *this, nonce_bytes, associated_data_bytes, data_bytes, + std::forward(completion_token)); + } else { + // Never compiled into a program: the assertion above stopped the build. + return detail::refused_by_engine(completion_executor, + completion_token); + } } else { return detail::complete_by_post( completion_executor, completion_token, @@ -1685,9 +1812,21 @@ auto ciphers::gcm::async_open(Executor const& completion_executor, CompletionToken&& completion_token) { secure::timing_guard const timing_scope; if constexpr (detail::asynchronous_backend_v) { - return detail::async_engine::open(completion_executor, *this, nonce_bytes, - associated_data_bytes, data_bytes, tag_bytes, - std::forward(completion_token)); + constexpr bool opens = detail::backend::async_open, gcm, + Executor, CompletionToken>; + static_assert(opens, + "webcpp::crypto: this backend completes by itself, and its engine has no " + "async_open: async_open is not available on it."); + if constexpr (opens) { + return detail::async_engine::open( + completion_executor, *this, nonce_bytes, associated_data_bytes, data_bytes, + tag_bytes, std::forward(completion_token)); + } else { + // Never compiled into a program: the assertion above stopped the build. + return detail::refused_by_engine(completion_executor, + completion_token); + } } else { return detail::complete_by_post( completion_executor, completion_token, @@ -1975,8 +2114,22 @@ auto curves::x25519::basic_keypair::async_agree(Executor const& complet CompletionToken&& completion_token) const { secure::timing_guard const timing_scope; if constexpr (detail::asynchronous_backend_v) { - return detail::async_engine::agree( - completion_executor, *this, peer_key, std::forward(completion_token)); + constexpr bool agrees = + detail::backend::async_agree, basic_keypair, + std::remove_cvref_t, Executor, + CompletionToken>; + static_assert(agrees, + "webcpp::crypto: this backend completes by itself, and its engine has no " + "async_agree: async_agree is not available on it."); + if constexpr (agrees) { + return detail::async_engine::agree( + completion_executor, *this, peer_key, + std::forward(completion_token)); + } else { + // Never compiled into a program: the assertion above stopped the build. + return detail::refused_by_engine(completion_executor, + completion_token); + } } else { return detail::complete_by_post(completion_executor, completion_token, [this, &peer_key]() noexcept { return agree(peer_key); }); @@ -2020,8 +2173,22 @@ auto curves::p256::basic_keypair::async_agree(Executor const& completio CompletionToken&& completion_token) const { secure::timing_guard const timing_scope; if constexpr (detail::asynchronous_backend_v) { - return detail::async_engine::agree( - completion_executor, *this, peer_key, std::forward(completion_token)); + constexpr bool agrees = + detail::backend::async_agree, basic_keypair, + std::remove_cvref_t, Executor, + CompletionToken>; + static_assert(agrees, + "webcpp::crypto: this backend completes by itself, and its engine has no " + "async_agree: async_agree is not available on it."); + if constexpr (agrees) { + return detail::async_engine::agree( + completion_executor, *this, peer_key, + std::forward(completion_token)); + } else { + // Never compiled into a program: the assertion above stopped the build. + return detail::refused_by_engine(completion_executor, + completion_token); + } } else { return detail::complete_by_post(completion_executor, completion_token, [this, &peer_key]() noexcept { return agree(peer_key); }); diff --git a/include/webcpp/crypto/authenticators/poly1305.hpp b/include/webcpp/crypto/authenticators/poly1305.hpp index 9354648..b0ccfa4 100644 --- a/include/webcpp/crypto/authenticators/poly1305.hpp +++ b/include/webcpp/crypto/authenticators/poly1305.hpp @@ -35,9 +35,11 @@ #include #include +#include #include #include #include +#include #include #include // detail::concept_check_backend #include // its free forms (D13) @@ -57,18 +59,6 @@ #include #endif -namespace webcpp::crypto::families { - -/** RFC 8439's Poly1305: a 32-byte one-time key, r and s, and a 16-byte tag. */ -struct poly1305 { - /** The key's size: r and s, RFC 8439 section 2.5. */ - static constexpr std::size_t key_size = 32; - /** The tag's size. */ - static constexpr std::size_t tag_size = 16; -}; - -} // namespace webcpp::crypto::families - namespace webcpp::crypto::detail { /** @@ -100,6 +90,27 @@ struct authenticator_engine : authenticator_refusal { } }; +/** + * Whether Poly1305's engine on a backend has its capability (design D9): true for the family's + * primary engine, whose generated refusal speaks, and for a test's unmarked stand-in, taken at its + * word; for an engine a backend's header specialises (`specialized_engine_v`), the capability, + * asserted by a message that names it. Each public member that calls the engine asks it first. + * + * @tparam Engine Poly1305's engine on the backend. + * @return Whether the member may call the engine. + */ +template +constexpr bool poly1305_capability_checked() noexcept { + if constexpr (!specialized_engine_v) { + return true; + } else { + static_assert(backend::authenticator, + "webcpp::crypto: this backend has Poly1305 but not " + "crypto::capabilities::poly1305: the authenticator is not available on it."); + return backend::authenticator; + } +} + } // namespace webcpp::crypto::detail namespace webcpp::crypto::authenticators { @@ -286,14 +297,19 @@ class poly1305 { [[nodiscard]] static boost::system::result compute( std::span key_bytes, std::span message_bytes, result_type& tag_bytes) noexcept { - auto const authenticated = - engine::authenticate(key_bytes.first(), message_bytes, - std::span(tag_bytes.data(), tag_size)); - if (!authenticated) { - secure::erase_secret(tag_bytes); - return authenticated.error(); + if constexpr (!detail::poly1305_capability_checked()) { + // Never compiled into a program: the capability's assertion stopped the build. + return error::backend_failure; + } else { + auto const authenticated = + engine::authenticate(key_bytes.first(), message_bytes, + std::span(tag_bytes.data(), tag_size)); + if (!authenticated) { + secure::erase_secret(tag_bytes); + return authenticated.error(); + } + return {}; } - return {}; } }; diff --git a/include/webcpp/crypto/backends/bearssl.hpp b/include/webcpp/crypto/backends/bearssl.hpp index d45f230..ba5ee4b 100644 --- a/include/webcpp/crypto/backends/bearssl.hpp +++ b/include/webcpp/crypto/backends/bearssl.hpp @@ -25,9 +25,12 @@ #else #include +#include +#include #include #include #include +#include #include #include #include @@ -266,6 +269,14 @@ struct gcm_engine { } }; +static_assert(backend::gcm>); +static_assert(backend::gcm>); +static_assert(backend::gcm>); +// The specialisation marker (design D5, R7): a capability of the table, counted by +// capabilities_test. +template +inline constexpr bool specialized_engine_v> = true; + /** * ChaCha20's code: SSE2's where the CPU and the build have it, else the constant-time portable * code. The test seam WEBCPP_CRYPTO_DETAIL_BEARSSL_PORTABLE keeps the portable code on every @@ -407,6 +418,14 @@ struct aead_engine { static void reset(state& engine_state) noexcept { secure::erase_secret(engine_state.key); } }; +static_assert(backend::aead, + families::chacha20_poly1305>); +// The specialisation marker (design D5, R7): a capability of the table, counted by +// capabilities_test. +template <> +inline constexpr bool + specialized_engine_v> = true; + /** ChaCha20's state on BearSSL: the key, in the object, since BearSSL takes it per call. */ template <> struct stream_state { @@ -479,6 +498,14 @@ struct stream_engine { static void reset(state& engine_state) noexcept { secure::erase_secret(engine_state.key); } }; +static_assert(backend::stream_cipher, + families::chacha20>); +// The specialisation marker (design D5, R7): a capability of the table, counted by +// capabilities_test. +template <> +inline constexpr bool specialized_engine_v> = + true; + /** * BearSSL's P-256 code for this target: natively the 64-bit multiplications of br_ec_p256_m62 * where BearSSL has them (__int128, or MSVC's _umul128), else br_ec_p256_m31; on WebAssembly @@ -842,25 +869,42 @@ struct p_curve_engine { } /** - * Copies the public point; no BearSSL call. + * Copies the public point, computed when the key was imported (`p256_public`); no BearSSL + * call. * * @param keyed_state A keyed state. * @param output_bytes 65 bytes. + * @return Nothing. */ - static void public_point(state const& keyed_state, - std::span output_bytes) noexcept { + [[nodiscard]] static boost::system::result public_key( + state const& keyed_state, std::span output_bytes) noexcept { std::ranges::copy(keyed_state.point, output_bytes.begin()); + return {}; } /** - * Copies the secret scalar; no BearSSL call. + * Copies the secret scalar (`p256_export`); no BearSSL call. * * @param keyed_state A keyed state. * @param output_bytes 32 bytes, a `secure::secret<32>`'s. + * @return Nothing. */ - static void scalar(state const& keyed_state, - std::span output_bytes) noexcept { + [[nodiscard]] static boost::system::result export_secret( + state const& keyed_state, std::span output_bytes) noexcept { std::ranges::copy(keyed_state.scalar, output_bytes.begin()); + return {}; + } + + /** + * Moves a key: the target takes the source's scalar and point, and the source is wiped. + * + * @param target_state The state moved to. + * @param source_state The state moved from, empty after. + */ + static void move(state& target_state, state& source_state) noexcept { + target_state.scalar = source_state.scalar; + target_state.point = source_state.point; + reset(source_state); } /** @@ -874,6 +918,20 @@ struct p_curve_engine { } }; +static_assert(backend::p256_import>); +static_assert(backend::p256_public>); +static_assert(backend::p256_export>); +static_assert(backend::p256_point>); +static_assert(backend::p256_ecdsa_signing>); +static_assert(backend::p256_ecdsa_verifying>); +static_assert(backend::p256_ecdh>); +static_assert(backend::ecdsa_der>); +// The specialisation marker (design D5, R7): a capability of the table, counted by +// capabilities_test. +template <> +inline constexpr bool specialized_engine_v> = + true; + /** * BearSSL has no AES block cipher: its state is empty, so `ciphers::aes256` is * complete, and `ciphers::gcm>` can read its key size. diff --git a/include/webcpp/crypto/backends/ctaes.hpp b/include/webcpp/crypto/backends/ctaes.hpp index b05bf75..d7f2ead 100644 --- a/include/webcpp/crypto/backends/ctaes.hpp +++ b/include/webcpp/crypto/backends/ctaes.hpp @@ -22,6 +22,7 @@ #else #include +#include #include #include @@ -200,6 +201,14 @@ struct block_engine { } }; +static_assert(backend::block_cipher>); +static_assert(backend::block_cipher>); +static_assert(backend::block_cipher>); +// The specialisation marker (design D5, R7): a capability of the table, counted by +// capabilities_test. +template +inline constexpr bool specialized_engine_v> = true; + /** ctaes exports no GCM, and webcpp builds none on another library's AES. */ template struct gcm_state { diff --git a/include/webcpp/crypto/backends/openssl.hpp b/include/webcpp/crypto/backends/openssl.hpp index c53d552..c45be28 100644 --- a/include/webcpp/crypto/backends/openssl.hpp +++ b/include/webcpp/crypto/backends/openssl.hpp @@ -46,8 +46,10 @@ "webcpp::crypto: the backend OpenSSL needs OpenSSL 3.0 or later, and the headers found are of an older OpenSSL. In the program's Jamfile, name /webcpp/crypto//openssl, which builds OpenSSL 3.5.9. (without b2: put OpenSSL 3's include/ first)" #else +#include #include #include +#include #include #include #include @@ -585,6 +587,14 @@ struct gcm_engine { } }; +static_assert(backend::gcm>); +static_assert(backend::gcm>); +static_assert(backend::gcm>); +// The specialisation marker (design D5, R7): a capability of the table, counted by +// capabilities_test. +template +inline constexpr bool specialized_engine_v> = true; + /** ChaCha20-Poly1305's state on OpenSSL: one context, keyed once. */ template <> struct aead_state { @@ -703,6 +713,14 @@ struct aead_engine { } }; +static_assert(backend::aead, + families::chacha20_poly1305>); +// The specialisation marker (design D5, R7): a capability of the table, counted by +// capabilities_test. +template <> +inline constexpr bool + specialized_engine_v> = true; + /** ChaCha20's state on OpenSSL: one context, keyed once. */ template <> struct stream_state { @@ -787,6 +805,14 @@ struct stream_engine { } }; +static_assert(backend::stream_cipher, + families::chacha20>); +// The specialisation marker (design D5, R7): a capability of the table, counted by +// capabilities_test. +template <> +inline constexpr bool specialized_engine_v> = + true; + /** * RFC 8439's Poly1305 on OpenSSL, the MAC "POLY1305" fetched by name, one context per tag (design * D14, R26): no object keeps a key, so each call fetches the MAC, makes a context, keys it, feeds @@ -848,6 +874,14 @@ struct authenticator_engine { } }; +static_assert(backend::authenticator, + families::poly1305>); +// The specialisation marker (design D5, R7): a capability of the table, counted by +// capabilities_test. +template <> +inline constexpr bool + specialized_engine_v> = true; + /** * The block cipher's state on OpenSSL: a context per direction, since a context keyed for * encryption keeps the encryption schedule only. @@ -911,6 +945,14 @@ struct block_engine { } }; +static_assert(backend::block_cipher>); +static_assert(backend::block_cipher>); +static_assert(backend::block_cipher>); +// The specialisation marker (design D5, R7): a capability of the table, counted by +// capabilities_test. +template +inline constexpr bool specialized_engine_v> = true; + } // namespace webcpp::crypto::detail #endif // OPENSSL_VERSION_NUMBER diff --git a/include/webcpp/crypto/backends/secp256k1.hpp b/include/webcpp/crypto/backends/secp256k1.hpp index 2a91a0e..50f61dc 100644 --- a/include/webcpp/crypto/backends/secp256k1.hpp +++ b/include/webcpp/crypto/backends/secp256k1.hpp @@ -28,7 +28,11 @@ #else #include +#include #include +#include +#include +#include #include #include @@ -40,7 +44,16 @@ #include #include +#include + +#include +#include +#include +#include +#include +#include #include +#include #ifdef WEBCPP_CRYPTO_SECP256K1_CANARY_CONFIGURATION /** The configuration the canary names: a test's, here. */ @@ -78,5 +91,1791 @@ struct secp256k1 { } // namespace webcpp::crypto::backends +namespace webcpp::crypto::detail { + +// NOLINTBEGIN(bugprone-signed-bitwise): libsecp256k1's macros shift a signed constant +#if defined(WEBCPP_SECURE_CT_VALGRIND) || defined(WEBCPP_SECURE_CT_MSAN) +/** + * The flags of a context that signs and verifies, under a constant-time checker: + * `SECP256K1_CONTEXT_DECLASSIFY`, so that libsecp256k1 marks its own public values public (a + * nonce's retry, a verdict), as its `ctime_tests.c` does; the checker then reports any other + * branch on a secret. + */ +inline constexpr unsigned secp256k1_context_flags = SECP256K1_CONTEXT_DECLASSIFY; +#else +/** The flags of a context that signs and verifies: none. */ +inline constexpr unsigned secp256k1_context_flags = SECP256K1_CONTEXT_NONE; +#endif + +/** The flag of the SEC1 compressed form. */ +inline constexpr unsigned secp256k1_compressed = SECP256K1_EC_COMPRESSED; + +/** The flag of the SEC1 uncompressed form. */ +inline constexpr unsigned secp256k1_uncompressed = SECP256K1_EC_UNCOMPRESSED; + +// NOLINTEND(bugprone-signed-bitwise) + +/** + * Whether libsecp256k1 accepted: what it returned on a secret, marked public for the + * constant-time checks (`secure::declassify`) where webcpp branches on it, as its + * `ctime_tests.c` marks each verdict. + * + * @param returned_code What the function returned: 1, or 0 when it refused. + * @return Whether it accepted. + */ +[[nodiscard]] inline bool secp256k1_accepted(int returned_code) noexcept { + // Not const: the comparison reads it again after the mark (secure::declassify's tip). + // NOLINTNEXTLINE(misc-const-correctness): see above + int accepted_verdict = returned_code; + secure::declassify(accepted_verdict); + return accepted_verdict != 0; +} + +/** + * Secret bytes out of a key pair, its secret key or its context's seed, wiped when the scope + * ends on every path, a failure's or an exception's included. + */ +struct secp256k1_secret { + /** The secret bytes. */ + std::array bytes{}; + + /** Wipes the bytes. */ + ~secp256k1_secret() { secure::erase_secret(bytes); } +}; + +/** + * Reads libsecp256k1's canary and runs its self-test: what every engine function that works on + * the static context does first, as the curve's functions did before the engines. + */ +inline void secp256k1_static_entry() noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_selftest(); +} + +/** + * Whether 32 bytes of a compact signature, its r or its s, are not zero. + * + * @param half_bytes The 32 bytes. + * @return Whether one byte is not zero. + */ +[[nodiscard]] inline bool secp256k1_nonzero(std::span half_bytes) noexcept { + return std::ranges::any_of(half_bytes, + [](std::uint8_t octet_value) { return octet_value != 0; }); +} + +/** + * Parses a compact ECDSA signature, r then s, each below the group order and not zero. + * + * @param compact_signature The 64 bytes. + * @param parsed_value Where the parsed signature goes. + * @return Whether it is a signature: false in every way it can be wrong. + */ +[[nodiscard]] inline bool secp256k1_parse_compact( + std::span compact_signature, + secp256k1_ecdsa_signature& parsed_value) noexcept { + return secp256k1_ecdsa_signature_parse_compact(secp256k1_context_static, &parsed_value, + compact_signature.data()) != 0 && + secp256k1_nonzero(compact_signature.first<32>()) && + secp256k1_nonzero(compact_signature.last<32>()); +} + +/** + * A key pair's public key, marked public (`secure::declassify`): libsecp256k1 derives it from the + * secret and marks it public only where it loads the key pair itself, and its `ctime_tests.c` + * marks a key pair's public key by hand where it reads one. + * + * @param secp_context The key pair's context. + * @param key_pair libsecp256k1's key pair. + * @return The public key. + */ +[[nodiscard]] inline secp256k1_pubkey secp256k1_public_point( + secp256k1_context const* secp_context, secp256k1_keypair const& key_pair) noexcept { + secp256k1_pubkey public_point{}; + // libsecp256k1 returns 1 always: a key pair holds its public key. + static_cast(secp256k1_keypair_pub(secp_context, &public_point, &key_pair)); + secure::declassify(public_point); + return public_point; +} + +extern "C" { + +/** + * libsecp256k1's ECDH hash function that hashes nothing: the shared point's x coordinate, + * 32 bytes, as Wycheproof's and NIP-44's ECDH give it. C linkage, as libsecp256k1's function + * pointer type has. + * + * @return 1, always. + */ +inline int webcpp_crypto_detail_secp256k1_copy_x(unsigned char* output_bytes, + unsigned char const* x_coordinate, + unsigned char const* /*y_coordinate*/, + void* /*user_data*/) noexcept { + std::memcpy(output_bytes, x_coordinate, 32); + return 1; +} + +/** + * libsecp256k1's ECDH hash function that writes the shared point, SEC1 uncompressed: + * 0x04, x, y, 65 bytes. + * + * @return 1, always. + */ +inline int webcpp_crypto_detail_secp256k1_copy_point(unsigned char* output_bytes, + unsigned char const* x_coordinate, + unsigned char const* y_coordinate, + void* /*user_data*/) noexcept { + output_bytes[0] = 0x04; + std::memcpy(output_bytes + 1, x_coordinate, 32); + std::memcpy(output_bytes + 33, y_coordinate, 32); + return 1; +} + +} // extern "C" + +/** + * What `scan` gives libsecp256k1 as its label context: the caller's lookup, and the function that + * calls it, so that the C callback reaches a C++ callable of any type. + */ +struct secp256k1_label_context { + /** The caller's lookup, which outlives the scan. */ + void const* lookup_object; + /** Calls the lookup with a candidate label's 33 bytes: its tweak's 32 bytes, or null. */ + unsigned char const* (*call_lookup)(void const*, unsigned char const*) noexcept; +}; + +extern "C" { + +/** + * libsecp256k1's label lookup callback, which reaches the caller's lookup through the + * `secp256k1_label_context` it is given. C linkage, as libsecp256k1's function pointer type has. + * + * @param label_bytes The candidate label's 33 bytes. + * @param label_context The `secp256k1_label_context`. + * @return The label's tweak, or null. + */ +inline unsigned char const* webcpp_crypto_detail_secp256k1_label_lookup( + unsigned char const* label_bytes, void const* label_context) noexcept { + auto const* const typed_context = static_cast(label_context); + return typed_context->call_lookup(typed_context->lookup_object, label_bytes); +} + +} // extern "C" + +/** + * A secp256k1 key pair's state on libsecp256k1: its signing context, in storage the key pair's + * resource gave, and libsecp256k1's key pair, the secret and public key. Every engine that uses the + * key reads this state, which it names `key_state`. + */ +struct secp256k1_key_state { + /** The randomised signing context; null before `start` and after `reset`. */ + secp256k1_context* context = nullptr; + /** The secret and public key. */ + secp256k1_keypair keypair{}; +}; + +/** + * The key pair on libsecp256k1 (design D8): the context's size, start and randomisation in the + * storage the public layer allocated (an engine never allocates, design D2), the secret's check + * and import, the public key in its forms, the secret back, and `move` and `reset`, which destroy + * the context and wipe the key and leave the storage to the public layer to give back. + */ +template <> +struct secp256k1_engine { + /** The state. */ + using state = secp256k1_key_state; + /** A public point, libsecp256k1's. */ + using point = secp256k1_pubkey; + /** A BIP340 x-only key, libsecp256k1's. */ + using xonly_point = secp256k1_xonly_pubkey; + + /** + * The bytes a signing context takes, which the public layer allocates. + * + * @return libsecp256k1's preallocated size for the context's flags. + */ + [[nodiscard]] static std::size_t context_size() noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + return secp256k1_context_preallocated_size(secp256k1_context_flags); + } + + /** + * Whether 32 bytes are a secret key: not zero and below the group order. + * + * @param secret_bytes The 32 bytes. + * @return Whether libsecp256k1 accepts them, marked public. + */ + [[nodiscard]] static bool valid_secret( + std::span secret_bytes) noexcept { + secp256k1_static_entry(); + return secp256k1_accepted( + secp256k1_ec_seckey_verify(secp256k1_context_static, secret_bytes.data())); + } + + /** + * Makes the signing context in `storage` and randomises it with `seed_bytes`. + * + * @param empty_state A state whose context is null. + * @param context_storage `context_size()` bytes, aligned to `alignof(std::max_align_t)`. + * @param seed_bytes 32 bytes from the random device. + * @return Nothing; `backend_failure` should libsecp256k1 refuse the randomisation, which + * v0.8.0 does only on the static context; the context is made either way, and `reset` + * destroys it. + */ + [[nodiscard]] static boost::system::result start( + state& empty_state, void* context_storage, + std::span seed_bytes) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + empty_state.context = + secp256k1_context_preallocated_create(context_storage, secp256k1_context_flags); + if (!secp256k1_accepted( + secp256k1_context_randomize(empty_state.context, seed_bytes.data()))) { + return error::backend_failure; + } + return {}; + } + + /** + * Makes the key pair from its secret, with the state's context. + * + * @param started_state A state `start` made. + * @param secret_bytes 32 bytes `valid_secret` accepted. + * @return Nothing; `backend_failure` should libsecp256k1 refuse them, which it does only for a + * secret `valid_secret` refuses. + */ + [[nodiscard]] static boost::system::result import_secret( + state& started_state, + std::span secret_bytes) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + if (!secp256k1_accepted(secp256k1_keypair_create( + started_state.context, &started_state.keypair, secret_bytes.data()))) { + return error::backend_failure; + } + return {}; + } + + /** + * The public key, SEC1 compressed. + * + * @param keyed_state A keyed state. + * @param public_output 33 bytes. + * @return Nothing; never an error. + */ + [[nodiscard]] static boost::system::result public_key( + state const& keyed_state, + std::span public_output) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_pubkey const public_point = + secp256k1_public_point(keyed_state.context, keyed_state.keypair); + std::size_t written_size = public_output.size(); + static_cast(secp256k1_ec_pubkey_serialize(secp256k1_context_static, + public_output.data(), &written_size, + &public_point, secp256k1_compressed)); + return {}; + } + + /** + * The public key's point, marked public. + * + * @param keyed_state A keyed state. + * @param point_output The point. + */ + static void public_point(state const& keyed_state, point& point_output) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + point_output = secp256k1_public_point(keyed_state.context, keyed_state.keypair); + } + + /** + * The key pair's x-only key and the parity of its y (`secp256k1_keypair_xonly_pub`), marked + * public, as the point is. + * + * @param keyed_state A keyed state. + * @param xonly_output The x-only key. + * @param parity_output 0 when y is even, 1 when it is odd. + */ + static void xonly_key(state const& keyed_state, xonly_point& xonly_output, + int& parity_output) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + // libsecp256k1 returns 1 always: a key pair holds its public key. + static_cast(secp256k1_keypair_xonly_pub(keyed_state.context, &xonly_output, + &parity_output, &keyed_state.keypair)); + secure::declassify(xonly_output); + secure::declassify(parity_output); + } + + /** + * The secret key (`secp256k1_keypair_sec`). + * + * @param keyed_state A keyed state. + * @param secret_output 32 bytes. + * @return Nothing; never an error. + */ + [[nodiscard]] static boost::system::result export_secret( + state const& keyed_state, + std::span secret_output) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + // libsecp256k1 returns 1 always: a key pair holds its secret key. + static_cast( + secp256k1_keypair_sec(keyed_state.context, secret_output.data(), &keyed_state.keypair)); + return {}; + } + + /** + * Moves a state: the target takes the context and the key, the source is left as `reset` + * leaves it. + * + * @param target_state A state `reset` left, or never started. + * @param source_state The source. + */ + static void move(state& target_state, state& source_state) noexcept { + target_state.context = source_state.context; + target_state.keypair = source_state.keypair; + source_state.context = nullptr; + secure::erase_secret(std::span(&source_state.keypair, 1)); + } + + /** + * Wipes the key and destroys the context, whose storage the public layer gives back. + * + * @param any_state The state. + */ + static void reset(state& any_state) noexcept { + secure::erase_secret(std::span(&any_state.keypair, 1)); + if (any_state.context != nullptr) { + secp256k1_context_preallocated_destroy(any_state.context); + any_state.context = nullptr; + } + } +}; + +/** + * The points and x-only keys on libsecp256k1's static context, which allocates nothing: public + * data only. + */ +template <> +struct secp256k1_engine { + /** A public point, libsecp256k1's. */ + using point = secp256k1_pubkey; + /** A BIP340 x-only key, libsecp256k1's. */ + using xonly_point = secp256k1_xonly_pubkey; + + /** + * Parses a public key of 33 bytes, compressed, or 65, uncompressed. libsecp256k1 also accepts + * X9.62's hybrid forms, prefix 06 or 07, of 65 bytes; they are refused here, as every prefix + * other than 02, 03 and 04 is. + * + * @param encoded_bytes The key, SEC1. + * @param point_output Where the parsed key goes. + * @return Whether it is a key: false in every way it can be wrong. + */ + [[nodiscard]] static bool parse(std::span encoded_bytes, + point& point_output) noexcept { + secp256k1_static_entry(); + bool const is_sized = encoded_bytes.size() == backend::secp256k1_compressed_size || + (encoded_bytes.size() == backend::secp256k1_uncompressed_size && + encoded_bytes[0] == 0x04); + return is_sized && + secp256k1_ec_pubkey_parse(secp256k1_context_static, &point_output, + encoded_bytes.data(), encoded_bytes.size()) != 0; + } + + /** + * The point, SEC1 compressed. + * + * @param point_value A valid point. + * @param compressed_output 33 bytes. + */ + static void serialize( + point const& point_value, + std::span compressed_output) noexcept { + serialized(point_value, compressed_output, secp256k1_compressed); + } + + /** + * The point, SEC1 uncompressed. + * + * @param point_value A valid point. + * @param uncompressed_output 65 bytes. + */ + static void serialize(point const& point_value, + std::span + uncompressed_output) noexcept { + serialized(point_value, uncompressed_output, secp256k1_uncompressed); + } + + /** + * libsecp256k1's comparison of two points, which reads both as compressed encodings. Both are + * valid: no public key is made otherwise, so the illegal callback is never reached. + * + * @return Negative, zero or positive, as `memcmp`. + */ + [[nodiscard]] static int compare(point const& left_point, point const& right_point) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + return secp256k1_ec_pubkey_cmp(secp256k1_context_static, &left_point, &right_point); + } + + /** + * A point's BIP340 x-only form; the parity of y is dropped. + * + * @param point_value A valid point. + * @param xonly_output The x-only key. + */ + static void to_xonly(point const& point_value, xonly_point& xonly_output) noexcept { + secp256k1_static_entry(); + // libsecp256k1 returns 1 always: every valid point has an x-only form. + static_cast(secp256k1_xonly_pubkey_from_pubkey(secp256k1_context_static, + &xonly_output, nullptr, &point_value)); + } + + /** + * BIP340's lift_x of 32 bytes. + * + * @param xonly_bytes 32 bytes, big-endian x. + * @param xonly_output The key. + * @return Whether they are a point's x: below p, and x^3 + 7 a square. + */ + [[nodiscard]] static bool parse_xonly( + std::span xonly_bytes, + xonly_point& xonly_output) noexcept { + secp256k1_static_entry(); + return secp256k1_xonly_pubkey_parse(secp256k1_context_static, &xonly_output, + xonly_bytes.data()) != 0; + } + + /** + * An x-only key's 32 bytes. + * + * @param xonly_value A valid key. + * @param xonly_output 32 bytes. + */ + static void serialize_xonly( + xonly_point const& xonly_value, + std::span xonly_output) noexcept { + secp256k1_static_entry(); + // libsecp256k1 returns 1 always: every key here is valid. + static_cast(secp256k1_xonly_pubkey_serialize(secp256k1_context_static, + xonly_output.data(), &xonly_value)); + } + + /** + * libsecp256k1's comparison of two x-only keys, which reads them as their 32 bytes. Both are + * valid: no key is made otherwise, so the illegal callback is never reached. + * + * @return Negative, zero or positive, as `memcmp`. + */ + [[nodiscard]] static int compare_xonly(xonly_point const& left_key, + xonly_point const& right_key) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + return secp256k1_xonly_pubkey_cmp(secp256k1_context_static, &left_key, &right_key); + } + +private: + /** + * The point in the SEC1 form `encoding_flags` names. + * + * @param point_value A valid point. + * @param output_bytes 33 or 65 bytes. + * @param encoding_flags libsecp256k1's flag of the form. + */ + static void serialized(point const& point_value, std::span output_bytes, + unsigned encoding_flags) noexcept { + secp256k1_static_entry(); + std::size_t written_size = output_bytes.size(); + static_cast(secp256k1_ec_pubkey_serialize(secp256k1_context_static, + output_bytes.data(), &written_size, + &point_value, encoding_flags)); + } +}; + +/** + * ECDSA over a 32-byte digest, RFC 6979's nonce, low S, with the key pair's context; its + * verification and its signature's forms on the static context. + */ +template <> +struct secp256k1_engine { + /** The key pair's state, which signing reads. */ + using key_state = secp256k1_key_state; + /** A public point, libsecp256k1's. */ + using point = secp256k1_pubkey; + + /** + * Signs a digest, `extra_entropy` mixed into the nonce when it is not empty (libsecp256k1's + * `ndata`). + * + * @param signing_key A keyed state. + * @param digest_bytes The 32-byte digest. + * @param extra_entropy Empty, or 32 bytes the caller keeps and wipes. + * @param signature_output r then s, low S. + * @return Nothing; `backend_failure`, for extra entropy of another size too (libsecp256k1 + * reads 32 bytes of it). + */ + [[nodiscard]] static boost::system::result sign( + key_state const& signing_key, + std::span digest_bytes, + std::span extra_entropy, + std::span signature_output) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + if (!extra_entropy.empty() && extra_entropy.size() != backend::secp256k1_element_size) { + return error::backend_failure; + } + secp256k1_secret secret_bytes; + static_cast(secp256k1_keypair_sec(signing_key.context, secret_bytes.bytes.data(), + &signing_key.keypair)); + secp256k1_ecdsa_signature signature_value{}; + if (!secp256k1_accepted( + secp256k1_ecdsa_sign(signing_key.context, &signature_value, digest_bytes.data(), + secret_bytes.bytes.data(), nullptr, + extra_entropy.empty() ? nullptr : extra_entropy.data()))) { + return error::backend_failure; + } + secp256k1_ecdsa_signature_serialize_compact(signing_key.context, signature_output.data(), + &signature_value); + return {}; + } + + /** + * Verifies a signature of a digest; a high S does not verify. + * + * @param point_value The signer's point. + * @param digest_bytes The 32-byte digest. + * @param signature_bytes r then s. + * @return Whether it verifies. + */ + [[nodiscard]] static bool verify( + point const& point_value, + std::span digest_bytes, + std::span signature_bytes) noexcept { + secp256k1_static_entry(); + secp256k1_ecdsa_signature parsed_value{}; + return secp256k1_ecdsa_signature_parse_compact(secp256k1_context_static, &parsed_value, + signature_bytes.data()) != 0 && + secp256k1_ecdsa_verify(secp256k1_context_static, &parsed_value, digest_bytes.data(), + &point_value) != 0; + } + + /** + * Whether a compact signature is valid: 0 < r < n and 0 < s < n. + * + * @param signature_bytes r then s. + * @return Whether it is. + */ + [[nodiscard]] static bool valid_compact( + std::span signature_bytes) noexcept { + secp256k1_static_entry(); + secp256k1_ecdsa_signature parsed_value{}; + return secp256k1_parse_compact(signature_bytes, parsed_value); + } + + /** + * Whether a compact signature is low S: valid, and s <= (n - 1) / 2. + * + * @param signature_bytes r then s. + * @return Whether it is. + */ + [[nodiscard]] static bool is_low_s( + std::span signature_bytes) noexcept { + secp256k1_static_entry(); + 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; + } + + /** + * The low-S form of a compact signature: s replaced by n - s when it is above (n - 1) / 2. + * + * @param signature_bytes r then s. + * @param low_output The low-S 64 bytes. + * @param was_high Whether s was replaced. + * @return Whether the signature is valid; nothing is written when it is not. + */ + [[nodiscard]] static bool low_s( + std::span signature_bytes, + std::span low_output, + bool& was_high) noexcept { + secp256k1_static_entry(); + secp256k1_ecdsa_signature parsed_value{}; + if (!secp256k1_parse_compact(signature_bytes, 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_output.data(), + &parsed_value); + return true; + } + + /** + * A valid compact signature's strict DER. + * + * @param signature_bytes r then s. + * @param der_output 72 bytes, the longest strict DER. + * @param der_size The size written; 0 should libsecp256k1 write none, which a valid signature + * and 72 bytes cannot cause. + * @return Whether the signature is valid; nothing is written when it is not. + */ + [[nodiscard]] static bool to_der( + std::span signature_bytes, + std::span der_output, + std::size_t& der_size) noexcept { + secp256k1_static_entry(); + secp256k1_ecdsa_signature parsed_value{}; + if (!secp256k1_parse_compact(signature_bytes, parsed_value)) { + return false; + } + der_size = der_output.size(); + if (secp256k1_ecdsa_signature_serialize_der(secp256k1_context_static, der_output.data(), + &der_size, &parsed_value) == 0) { + der_size = 0; + } + return true; + } + + /** + * The compact form of a strict DER signature. + * + * @param der_bytes The DER, exactly. + * @param signature_output r then s. + * @return Whether it is strict DER of a valid signature: r and s not zero, which is how + * libsecp256k1's parser gives a number not below the group order. + */ + [[nodiscard]] static bool from_der( + std::span der_bytes, + std::span signature_output) noexcept { + secp256k1_static_entry(); + // An empty view's data may be null, which libsecp256k1's parser takes for a misuse. + if (der_bytes.empty()) { + return false; + } + secp256k1_ecdsa_signature parsed_value{}; + if (secp256k1_ecdsa_signature_parse_der(secp256k1_context_static, &parsed_value, + der_bytes.data(), der_bytes.size()) == 0) { + return false; + } + std::array compact_bytes{}; + secp256k1_ecdsa_signature_serialize_compact(secp256k1_context_static, compact_bytes.data(), + &parsed_value); + std::span const compact_view( + compact_bytes); + if (!secp256k1_nonzero(compact_view.first<32>()) || + !secp256k1_nonzero(compact_view.last<32>())) { + return false; + } + std::ranges::copy(compact_bytes, signature_output.begin()); + return true; + } +}; + +/** BIP340's Schnorr signatures: signing with the key pair's context, verifying on the static one. + */ +template <> +struct secp256k1_engine { + /** The key pair's state, which signing reads. */ + using key_state = secp256k1_key_state; + /** A BIP340 x-only key, libsecp256k1's. */ + using xonly_point = secp256k1_xonly_pubkey; + + /** + * Signs a message of any length with the caller's auxiliary randomness, read in place. + * + * @param signing_key A keyed state. + * @param message_bytes The message. + * @param auxiliary_random 32 bytes the caller keeps and wipes. + * @param signature_output BIP340's 64 bytes. + * @return Nothing; `backend_failure`. + */ + [[nodiscard]] static boost::system::result sign( + key_state const& signing_key, std::span message_bytes, + std::span auxiliary_random, + std::span signature_output) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_schnorrsig_extraparams extra_parameters = SECP256K1_SCHNORRSIG_EXTRAPARAMS_INIT; + // libsecp256k1's parameter is void*, and BIP340's nonce function only reads it. + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast): see above + extra_parameters.ndata = const_cast(auxiliary_random.data()); + if (!secp256k1_accepted(secp256k1_schnorrsig_sign_custom( + signing_key.context, signature_output.data(), message_bytes.data(), + message_bytes.size(), &signing_key.keypair, &extra_parameters))) { + return error::backend_failure; + } + return {}; + } + + /** + * Verifies a signature against an x-only key. + * + * @param xonly_value The signer's x-only key. + * @param message_bytes The message. + * @param signature_bytes BIP340's 64 bytes. + * @return Whether it verifies. + */ + [[nodiscard]] static bool verify( + xonly_point const& xonly_value, std::span message_bytes, + std::span signature_bytes) noexcept { + secp256k1_static_entry(); + return secp256k1_schnorrsig_verify(secp256k1_context_static, signature_bytes.data(), + message_bytes.data(), message_bytes.size(), + &xonly_value) != 0; + } +}; + +/** Recoverable ECDSA: signing with the key pair's context, recovery on the static one. */ +template <> +struct secp256k1_engine { + /** The key pair's state, which signing reads. */ + using key_state = secp256k1_key_state; + /** A public point, libsecp256k1's. */ + using point = secp256k1_pubkey; + + /** + * Signs a digest, RFC 6979's nonce, low S, with the recovery id. + * + * @param signing_key A keyed state. + * @param digest_bytes The 32-byte digest. + * @param signature_output r, s, then the id 0 to 3. + * @return Nothing; `backend_failure`. + */ + [[nodiscard]] static boost::system::result sign( + key_state const& signing_key, + std::span digest_bytes, + std::span signature_output) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_secret secret_bytes; + static_cast(secp256k1_keypair_sec(signing_key.context, secret_bytes.bytes.data(), + &signing_key.keypair)); + secp256k1_ecdsa_recoverable_signature signature_value{}; + if (!secp256k1_accepted(secp256k1_ecdsa_sign_recoverable( + signing_key.context, &signature_value, digest_bytes.data(), + secret_bytes.bytes.data(), nullptr, nullptr))) { + return error::backend_failure; + } + int recovery_id = 0; + secp256k1_ecdsa_recoverable_signature_serialize_compact( + signing_key.context, signature_output.data(), &recovery_id, &signature_value); + signature_output[backend::secp256k1_signature_size] = + static_cast(recovery_id); + return {}; + } + + /** + * The point that made a signature of a digest. It reads no S rule of its own: the caller + * refuses a high S first. + * + * @param signature_bytes r, s, then the recovery id. + * @param digest_bytes The 32-byte digest. + * @param point_output The point recovered. + * @return Whether one is: false for an id above 3 (libsecp256k1's ARG_CHECK, whose callback + * aborts, is never reached), an r or an s not below the group order, or no point. + */ + [[nodiscard]] static bool recover( + std::span signature_bytes, + std::span digest_bytes, + point& point_output) noexcept { + int const recovery_id = signature_bytes[backend::secp256k1_signature_size]; + if (recovery_id > 3) { + return false; + } + secp256k1_static_entry(); + secp256k1_ecdsa_recoverable_signature parsed_value{}; + return secp256k1_ecdsa_recoverable_signature_parse_compact( + secp256k1_context_static, &parsed_value, signature_bytes.data(), recovery_id) != + 0 && + secp256k1_ecdsa_recover(secp256k1_context_static, &point_output, &parsed_value, + digest_bytes.data()) != 0; + } +}; + +/** ECDH with the key pair's context, in libsecp256k1's three outputs. */ +template <> +struct secp256k1_engine { + /** The key pair's state. */ + using key_state = secp256k1_key_state; + /** A public point, libsecp256k1's. */ + using point = secp256k1_pubkey; + + /** + * The shared point's x coordinate, unhashed. + * + * @param agreeing_key A keyed state. + * @param peer_point The peer's point. + * @param shared_output 32 secret bytes. + * @return Nothing; `backend_failure`. + */ + [[nodiscard]] static boost::system::result shared_x( + key_state const& agreeing_key, point const& peer_point, + std::span shared_output) noexcept { + return shared(agreeing_key, peer_point, shared_output.data(), + webcpp_crypto_detail_secp256k1_copy_x); + } + + /** + * libsecp256k1's default: the SHA-256 of the compressed shared point. + * + * @param agreeing_key A keyed state. + * @param peer_point The peer's point. + * @param shared_output 32 secret bytes. + * @return Nothing; `backend_failure`. + */ + [[nodiscard]] static boost::system::result shared_hashed( + key_state const& agreeing_key, point const& peer_point, + std::span shared_output) noexcept { + return shared(agreeing_key, peer_point, shared_output.data(), nullptr); + } + + /** + * The shared point, SEC1 uncompressed. + * + * @param agreeing_key A keyed state. + * @param peer_point The peer's point. + * @param point_output 65 secret bytes. + * @return Nothing; `backend_failure`. + */ + [[nodiscard]] static boost::system::result shared_point( + key_state const& agreeing_key, point const& peer_point, + std::span point_output) noexcept { + return shared(agreeing_key, peer_point, point_output.data(), + webcpp_crypto_detail_secp256k1_copy_point); + } + +private: + /** + * ECDH, its output written by `hash_function`: libsecp256k1's SHA-256 when it is null. + * + * @return Nothing; `backend_failure`, which a valid key pair and a valid point cannot cause. + */ + [[nodiscard]] static boost::system::result shared( + key_state const& agreeing_key, point const& peer_point, unsigned char* output_bytes, + secp256k1_ecdh_hash_function hash_function) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_secret secret_bytes; + static_cast(secp256k1_keypair_sec(agreeing_key.context, secret_bytes.bytes.data(), + &agreeing_key.keypair)); + if (!secp256k1_accepted(secp256k1_ecdh(agreeing_key.context, output_bytes, &peer_point, + secret_bytes.bytes.data(), hash_function, + nullptr))) { + return error::backend_failure; + } + return {}; + } +}; + +/** + * The tweaks on the static context, but the key pair's own, on its context; and the sum of points. + */ +template <> +struct secp256k1_engine { + /** The key pair's state, which `key_xonly_add` tweaks. */ + using key_state = secp256k1_key_state; + /** A public point, libsecp256k1's. */ + using point = secp256k1_pubkey; + /** A BIP340 x-only key, libsecp256k1's. */ + using xonly_point = secp256k1_xonly_pubkey; + + /** + * A secret key plus a tweak modulo the group order. + * + * @return Nothing; `invalid_secret_key` for a key zero or not below n, then for a tweak not + * below n or a sum of zero. + */ + [[nodiscard]] static boost::system::result secret_add( + std::span secret_bytes, + std::span tweak_bytes, + std::span secret_output) noexcept { + return tweaked_secret(secret_bytes, tweak_bytes.data(), secp256k1_ec_seckey_tweak_add, + secret_output); + } + + /** + * A secret key times a tweak modulo the group order. + * + * @return Nothing; `invalid_secret_key` for a key zero or not below n, then for a tweak zero + * or not below n. + */ + [[nodiscard]] static boost::system::result secret_mul( + std::span secret_bytes, + std::span tweak_bytes, + std::span secret_output) noexcept { + return tweaked_secret(secret_bytes, tweak_bytes.data(), secp256k1_ec_seckey_tweak_mul, + secret_output); + } + + /** + * The group order minus a secret key. + * + * @return Nothing; `invalid_secret_key` for a key zero or not below n. + */ + [[nodiscard]] static boost::system::result secret_negate( + std::span secret_bytes, + std::span secret_output) noexcept { + return tweaked_secret(secret_bytes, nullptr, nullptr, secret_output); + } + + /** + * P + t*G, in place; P is unchanged on a refusal. + * + * @return Whether it is a point: false for a tweak not below n or a sum at infinity. + */ + [[nodiscard]] static bool point_add( + point& point_value, + std::span tweak_bytes) noexcept { + secp256k1_static_entry(); + point tweaked_point = point_value; + if (secp256k1_ec_pubkey_tweak_add(secp256k1_context_static, &tweaked_point, + tweak_bytes.data()) == 0) { + return false; + } + point_value = tweaked_point; + return true; + } + + /** + * t*P, in place; P is unchanged on a refusal. + * + * @return Whether it is a point: false for a tweak zero or not below n. + */ + [[nodiscard]] static bool point_mul( + point& point_value, + std::span tweak_bytes) noexcept { + secp256k1_static_entry(); + point tweaked_point = point_value; + if (secp256k1_ec_pubkey_tweak_mul(secp256k1_context_static, &tweaked_point, + tweak_bytes.data()) == 0) { + return false; + } + point_value = tweaked_point; + return true; + } + + /** + * -P, in place. + * + * @return Whether libsecp256k1 negated it, which it always does for a valid point (v0.8.0). + */ + [[nodiscard]] static bool point_negate(point& point_value) noexcept { + secp256k1_static_entry(); + return secp256k1_accepted( + secp256k1_ec_pubkey_negate(secp256k1_context_static, &point_value)); + } + + /** + * An x-only key tweaked by t: the x-only key of P + t*G and the parity of its y. + * + * @return Whether it is a key: false for a tweak not below n, or no key. + */ + [[nodiscard]] static bool xonly_add( + xonly_point const& xonly_value, + std::span tweak_bytes, + xonly_point& xonly_output, int& parity_output) noexcept { + secp256k1_static_entry(); + point tweaked_point{}; + if (secp256k1_xonly_pubkey_tweak_add(secp256k1_context_static, &tweaked_point, &xonly_value, + tweak_bytes.data()) == 0) { + return false; + } + // libsecp256k1 returns 1 always: every valid point has an x-only form. + static_cast(secp256k1_xonly_pubkey_from_pubkey( + secp256k1_context_static, &xonly_output, &parity_output, &tweaked_point)); + return true; + } + + /** + * Whether `tweaked_value` with `tweaked_parity` is `xonly_value` tweaked by t: BIP341's check + * of an output key against its internal key. + * + * @return Whether it is. + */ + [[nodiscard]] static bool xonly_check( + xonly_point const& xonly_value, + std::span tweak_bytes, + xonly_point const& tweaked_value, int tweaked_parity) noexcept { + secp256k1_static_entry(); + std::array tweaked_bytes{}; + // libsecp256k1 returns 1 always: every key here is valid. + static_cast(secp256k1_xonly_pubkey_serialize(secp256k1_context_static, + tweaked_bytes.data(), &tweaked_value)); + return secp256k1_xonly_pubkey_tweak_add_check(secp256k1_context_static, + tweaked_bytes.data(), tweaked_parity, + &xonly_value, tweak_bytes.data()) != 0; + } + + /** + * The key pair tweaked in place, its x-only key P becoming P + t*G and its secret following. + * + * @param keyed_state A keyed state. + * @param tweak_bytes t. + * @return Whether libsecp256k1 accepted, marked public: false for a tweak not below n or no + * key, after which the caller resets the state. + */ + [[nodiscard]] static bool key_xonly_add( + key_state& keyed_state, + std::span tweak_bytes) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + return secp256k1_accepted(secp256k1_keypair_xonly_tweak_add( + keyed_state.context, &keyed_state.keypair, tweak_bytes.data())); + } + + /** + * The sum of points, over an array of pointers the caller carved. + * + * @param point_pointers At least one. + * @param point_output The sum. + * @return Whether it is a point: false for a sum at infinity. + */ + [[nodiscard]] static bool combine(std::span point_pointers, + point& point_output) noexcept { + secp256k1_static_entry(); + return secp256k1_ec_pubkey_combine(secp256k1_context_static, &point_output, + point_pointers.data(), point_pointers.size()) != 0; + } + +private: + /** libsecp256k1's tweak of a secret key: `secp256k1_ec_seckey_tweak_*`. */ + using secret_tweak = int (*)(secp256k1_context const*, unsigned char*, unsigned char const*); + + /** + * A secret key tweaked in a wiped copy, then copied out. + * + * @param secret_bytes The key. + * @param tweak_bytes The tweak, or null for a negation. + * @param tweak_function libsecp256k1's tweak, used when `tweak_bytes` is not null. + * @param secret_output The key tweaked, written on success. + * @return Nothing; `invalid_secret_key`. + */ + [[nodiscard]] static boost::system::result tweaked_secret( + std::span secret_bytes, + unsigned char const* tweak_bytes, secret_tweak tweak_function, + std::span secret_output) noexcept { + secp256k1_static_entry(); + // The key is checked first, so that a refusal names the input that was wrong. + if (!secp256k1_accepted( + secp256k1_ec_seckey_verify(secp256k1_context_static, secret_bytes.data()))) { + return error::invalid_secret_key; + } + secp256k1_secret working_copy; + std::ranges::copy(secret_bytes, working_copy.bytes.begin()); + int const tweak_status = + tweak_bytes == nullptr + ? secp256k1_ec_seckey_negate(secp256k1_context_static, working_copy.bytes.data()) + : tweak_function(secp256k1_context_static, working_copy.bytes.data(), tweak_bytes); + if (!secp256k1_accepted(tweak_status)) { + return error::invalid_secret_key; + } + std::ranges::copy(working_copy.bytes, secret_output.begin()); + return {}; + } +}; + +/** ElligatorSwift: the encodings on the static context, the key pair's on its context. */ +template <> +struct secp256k1_engine { + /** The key pair's state. */ + using key_state = secp256k1_key_state; + /** A public point, libsecp256k1's. */ + using point = secp256k1_pubkey; + + /** + * One of a point's encodings, chosen by the randomness. + * + * @param point_value A valid point. + * @param randomness_bytes 32 fresh bytes. + * @param encoding_output 64 bytes. + */ + static void encode( + point const& point_value, + std::span randomness_bytes, + std::span encoding_output) noexcept { + secp256k1_static_entry(); + // libsecp256k1 returns 1 always: every valid point has encodings. + static_cast(secp256k1_ellswift_encode(secp256k1_context_static, + encoding_output.data(), &point_value, + randomness_bytes.data())); + } + + /** + * The point of any 64 bytes. + * + * @param encoding_bytes 64 bytes. + * @param point_output The point. + */ + static void decode( + std::span encoding_bytes, + point& point_output) noexcept { + secp256k1_static_entry(); + // libsecp256k1 returns 1 always: ElligatorSwift maps every 64 bytes to a point. + static_cast(secp256k1_ellswift_decode(secp256k1_context_static, &point_output, + encoding_bytes.data())); + } + + /** + * The encoding of the key pair's public key, made from its secret. + * + * @return Nothing; `backend_failure`. + */ + [[nodiscard]] static boost::system::result create( + key_state const& keyed_state, + std::span randomness_bytes, + std::span encoding_output) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_secret secret_bytes; + static_cast(secp256k1_keypair_sec(keyed_state.context, secret_bytes.bytes.data(), + &keyed_state.keypair)); + // The key pair's secret is valid: libsecp256k1 refuses only one that is not. + if (!secp256k1_accepted( + secp256k1_ellswift_create(keyed_state.context, encoding_output.data(), + secret_bytes.bytes.data(), randomness_bytes.data()))) { + return error::backend_failure; + } + return {}; + } + + /** + * BIP 324's shared secret of the two encodings, with the key pair's secret. + * + * @param responder_side Whether the key pair is the responder. + * @return Nothing; `backend_failure`. + */ + [[nodiscard]] static boost::system::result xdh( + key_state const& keyed_state, + std::span initiator_encoding, + std::span responder_encoding, + bool responder_side, + std::span shared_output) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_secret secret_bytes; + static_cast(secp256k1_keypair_sec(keyed_state.context, secret_bytes.bytes.data(), + &keyed_state.keypair)); + // The secret is valid and BIP 324's hash never fails: libsecp256k1 returns 1. + if (!secp256k1_accepted(secp256k1_ellswift_xdh( + keyed_state.context, shared_output.data(), initiator_encoding.data(), + responder_encoding.data(), secret_bytes.bytes.data(), responder_side ? 1 : 0, + secp256k1_ellswift_xdh_hash_function_bip324, nullptr))) { + return error::backend_failure; + } + return {}; + } +}; + +/** + * MuSig2 (BIP327) over libsecp256k1's objects: the static context, but nonce generation and + * partial signing, which use the key pair's context. + */ +template <> +struct secp256k1_engine { + /** The key pair's state. */ + using key_state = secp256k1_key_state; + /** A public point, libsecp256k1's. */ + using point = secp256k1_pubkey; + /** The key aggregation cache: the aggregate key and its tweaks. */ + using key_cache = secp256k1_musig_keyagg_cache; + /** A public nonce. */ + using public_nonce = secp256k1_musig_pubnonce; + /** The aggregate nonce. */ + using aggregate_nonce = secp256k1_musig_aggnonce; + /** A signing session. */ + using session = secp256k1_musig_session; + /** A partial signature. */ + using partial_signature = secp256k1_musig_partial_sig; + /** A secret nonce: its magic, two secret scalars and the signer's point. */ + using secret_nonce = secp256k1_musig_secnonce; + + /** + * Aggregates the signers' points. + * + * @param point_pointers At least one. + * @param cache_output The cache. + * @return Whether libsecp256k1 aggregated them. + */ + [[nodiscard]] static bool key_aggregate(std::span point_pointers, + key_cache& cache_output) noexcept { + secp256k1_static_entry(); + return secp256k1_musig_pubkey_agg(secp256k1_context_static, nullptr, &cache_output, + point_pointers.data(), point_pointers.size()) != 0; + } + + /** + * The aggregate as a full point, the tweaks included. + * + * @param cache_value A cache `key_aggregate` made. + * @param point_output The point. + */ + static void aggregate_point(key_cache const& cache_value, point& point_output) noexcept { + secp256k1_static_entry(); + // The cache is valid: libsecp256k1 returns 1. The status is named and dropped, since + // GCC's warn_unused_result does not yield to a cast to void. + int const get_status = + secp256k1_musig_pubkey_get(secp256k1_context_static, &point_output, &cache_value); + static_cast(get_status); + } + + /** + * A plain tweak of the aggregate (BIP 327's ApplyTweak, is_xonly false). + * + * @return Whether libsecp256k1 tweaked it: false for a tweak not below n or a result at + * infinity, after which the cache is unchanged. + */ + [[nodiscard]] static bool tweak_add( + key_cache& cache_value, + std::span tweak_bytes) noexcept { + secp256k1_static_entry(); + return secp256k1_musig_pubkey_ec_tweak_add(secp256k1_context_static, nullptr, &cache_value, + tweak_bytes.data()) != 0; + } + + /** + * An x-only tweak of the aggregate (BIP 327's ApplyTweak, is_xonly true). + * + * @return Whether libsecp256k1 tweaked it, as `tweak_add`. + */ + [[nodiscard]] static bool tweak_xonly_add( + key_cache& cache_value, + std::span tweak_bytes) noexcept { + secp256k1_static_entry(); + return secp256k1_musig_pubkey_xonly_tweak_add(secp256k1_context_static, nullptr, + &cache_value, tweak_bytes.data()) != 0; + } + + /** + * A nonce pair from the session's randomness, which libsecp256k1 zeroes once it is used. + * + * @param signing_key A keyed state. + * @param session_random 32 fresh bytes, zeroed. + * @param message_bytes Empty, or the 32-byte message. + * @param cache_value The signers' cache. + * @param extra_input Empty, or 32 bytes. + * @param secret_output The secret nonce. + * @param public_output The public nonce. + * @return Nothing; `backend_failure`. + */ + [[nodiscard]] static boost::system::result nonce_generate( + key_state const& signing_key, + std::span session_random, + std::span message_bytes, key_cache const& cache_value, + std::span extra_input, secret_nonce& secret_output, + public_nonce& public_output) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_secret secret_bytes; + static_cast(secp256k1_keypair_sec(signing_key.context, secret_bytes.bytes.data(), + &signing_key.keypair)); + point const signer_point = secp256k1_public_point(signing_key.context, signing_key.keypair); + if (!secp256k1_accepted(secp256k1_musig_nonce_gen( + signing_key.context, &secret_output, &public_output, session_random.data(), + secret_bytes.bytes.data(), &signer_point, + message_bytes.empty() ? nullptr : message_bytes.data(), &cache_value, + extra_input.empty() ? nullptr : extra_input.data()))) { + return error::backend_failure; + } + return {}; + } + + /** + * Sums the public nonces. + * + * @param nonce_pointers At least one. + * @param aggregate_output The sum. + * @return Whether libsecp256k1 summed them. + */ + [[nodiscard]] static bool nonce_aggregate(std::span nonce_pointers, + aggregate_nonce& aggregate_output) noexcept { + secp256k1_static_entry(); + return secp256k1_musig_nonce_agg(secp256k1_context_static, &aggregate_output, + nonce_pointers.data(), nonce_pointers.size()) != 0; + } + + /** + * The session of a message under the aggregate nonce and key. + * + * @return Whether libsecp256k1 made it. + */ + [[nodiscard]] static bool nonce_process( + aggregate_nonce const& aggregate_value, + std::span message_bytes, + key_cache const& cache_value, session& session_output) noexcept { + secp256k1_static_entry(); + return secp256k1_musig_nonce_process(secp256k1_context_static, &session_output, + &aggregate_value, message_bytes.data(), + &cache_value) != 0; + } + + /** + * The signer's partial signature, which consumes the secret nonce (libsecp256k1 zeroes it). + * + * @return Nothing; `backend_failure`. + */ + [[nodiscard]] static boost::system::result partial_sign( + key_state const& signing_key, secret_nonce& secret_value, key_cache const& cache_value, + session const& session_value, partial_signature& partial_output) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + if (!secp256k1_accepted(secp256k1_musig_partial_sign(signing_key.context, &partial_output, + &secret_value, &signing_key.keypair, + &cache_value, &session_value))) { + return error::backend_failure; + } + return {}; + } + + /** + * Whether a signer's partial signature verifies. + * + * @return Whether it does. + */ + [[nodiscard]] static bool partial_verify(partial_signature const& partial_value, + public_nonce const& public_value, + point const& point_value, key_cache const& cache_value, + session const& session_value) noexcept { + secp256k1_static_entry(); + return secp256k1_musig_partial_sig_verify(secp256k1_context_static, &partial_value, + &public_value, &point_value, &cache_value, + &session_value) != 0; + } + + /** + * The final BIP340 signature of the partial signatures. + * + * @return Whether libsecp256k1 aggregated them. + */ + [[nodiscard]] static bool partial_aggregate( + session const& session_value, std::span partial_pointers, + std::span signature_output) noexcept { + secp256k1_static_entry(); + return secp256k1_musig_partial_sig_agg(secp256k1_context_static, signature_output.data(), + &session_value, partial_pointers.data(), + partial_pointers.size()) != 0; + } + + /** Parses a public nonce. @return Whether it is one. */ + [[nodiscard]] static bool parse( + std::span nonce_bytes, + public_nonce& public_output) noexcept { + secp256k1_static_entry(); + return secp256k1_musig_pubnonce_parse(secp256k1_context_static, &public_output, + nonce_bytes.data()) != 0; + } + + /** A public nonce's 66 bytes. */ + static void serialize( + public_nonce const& public_value, + std::span nonce_output) noexcept { + secp256k1_static_entry(); + // A parsed or made nonce always serialises: libsecp256k1 returns 1. + static_cast(secp256k1_musig_pubnonce_serialize(secp256k1_context_static, + nonce_output.data(), &public_value)); + } + + /** Parses an aggregate nonce. @return Whether it is one. */ + [[nodiscard]] static bool parse( + std::span nonce_bytes, + aggregate_nonce& aggregate_output) noexcept { + secp256k1_static_entry(); + return secp256k1_musig_aggnonce_parse(secp256k1_context_static, &aggregate_output, + nonce_bytes.data()) != 0; + } + + /** An aggregate nonce's 66 bytes. */ + static void serialize( + aggregate_nonce const& aggregate_value, + std::span nonce_output) noexcept { + secp256k1_static_entry(); + // A parsed or summed nonce always serialises: libsecp256k1 returns 1. + static_cast(secp256k1_musig_aggnonce_serialize( + secp256k1_context_static, nonce_output.data(), &aggregate_value)); + } + + /** Parses a partial signature. @return Whether it is one. */ + [[nodiscard]] static bool parse( + std::span signature_bytes, + partial_signature& partial_output) noexcept { + secp256k1_static_entry(); + return secp256k1_musig_partial_sig_parse(secp256k1_context_static, &partial_output, + signature_bytes.data()) != 0; + } + + /** A partial signature's 32 bytes. */ + static void serialize( + partial_signature const& partial_value, + std::span signature_output) noexcept { + secp256k1_static_entry(); + // A parsed or made partial signature always serialises: libsecp256k1 returns 1. + static_cast(secp256k1_musig_partial_sig_serialize( + secp256k1_context_static, signature_output.data(), &partial_value)); + } +}; + +/** + * Silent payments (BIP352) over libsecp256k1's objects: the sender's outputs, the labels and the + * scan on the key pair's context, the rest on the static one. + */ +template <> +struct secp256k1_engine { + /** The key pair's state. */ + using key_state = secp256k1_key_state; + /** A public point, libsecp256k1's. */ + using point = secp256k1_pubkey; + /** A BIP340 x-only key, libsecp256k1's. */ + using xonly_point = secp256k1_xonly_pubkey; + /** A recipient: its scan and spend points and its index. */ + using recipient = secp256k1_silentpayments_recipient; + /** The summary of a transaction's inputs. */ + using summary = secp256k1_silentpayments_prevouts_summary; + /** An output a scan found. */ + using found_output = secp256k1_silentpayments_found_output; + /** What the sender's outputs take of a taproot input: its key pair. */ + using key_handle = secp256k1_keypair const*; + /** What a scan with labels calls back through. */ + using label_lookup = secp256k1_label_context; + + /** The most outputs one scan key's group may hold (BIP 352's limit). */ + static constexpr std::size_t group_limit = SECP256K1_SILENTPAYMENTS_RECIPIENT_GROUP_LIMIT; + + /** + * A taproot input's handle. + * + * @param keyed_state A keyed state. + * @return Its key pair. + */ + [[nodiscard]] static key_handle key_handle_of(key_state const& keyed_state) noexcept { + return &keyed_state.keypair; + } + + /** + * A recipient. + * + * @param scan_point The scan key. + * @param spend_point The spend key. + * @param recipient_index Its index among the outputs. + * @param recipient_output The recipient. + */ + static void make_recipient(point const& scan_point, point const& spend_point, + std::size_t recipient_index, recipient& recipient_output) noexcept { + recipient_output = recipient{ + .scan_pubkey = scan_point, + .spend_pubkey = spend_point, + .index = recipient_index, + }; + } + + /** + * The sender's outputs, on the first input's context. + * + * @param first_input The first input's state, keyed. + * @param output_pointers One per recipient. + * @param recipient_pointers The recipients, sorted in place. + * @param outpoint_bytes The smallest outpoint. + * @param taproot_handles The taproot inputs; empty with a null data, as libsecp256k1 requires. + * @param plain_secrets The plain inputs' secrets; empty with a null data, likewise. + * @return Whether libsecp256k1 accepted, marked public: false for a sum of zero, or a group + * past the limit (`over_group_limit` tells them apart). + */ + [[nodiscard]] static bool create_outputs( + key_state const& first_input, std::span output_pointers, + std::span recipient_pointers, + std::span outpoint_bytes, + std::span taproot_handles, + std::span plain_secrets) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + return secp256k1_accepted(secp256k1_silentpayments_sender_create_outputs( + first_input.context, output_pointers.data(), recipient_pointers.data(), + recipient_pointers.size(), outpoint_bytes.data(), taproot_handles.data(), + taproot_handles.size(), plain_secrets.data(), plain_secrets.size())); + } + + /** + * Whether more than `group_limit` recipients share one scan key, which libsecp256k1 refuses as + * it refuses a sum of zero. The recipients' pointers are sorted in place by scan key, as + * libsecp256k1 sorts them, and each run of one key is counted: O(n log n), nothing allocated. + * + * @param recipient_pointers The recipients' pointers, in the workspace. + * @return Whether a group is over the limit. + */ + [[nodiscard]] static bool over_group_limit( + std::span recipient_pointers) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + auto const scan_key_order = [](recipient const* left_recipient, + recipient const* right_recipient) { + return secp256k1_ec_pubkey_cmp(secp256k1_context_static, &left_recipient->scan_pubkey, + &right_recipient->scan_pubkey) < 0; + }; + std::ranges::sort(recipient_pointers, scan_key_order); + std::size_t group_size = 0; + for (std::size_t item_index = 0; item_index < recipient_pointers.size(); ++item_index) { + bool const same_group = + item_index != 0 && + !scan_key_order(recipient_pointers[item_index - 1], recipient_pointers[item_index]); + group_size = same_group ? group_size + 1 : 1; + if (group_size > group_limit) { + return true; + } + } + return false; + } + + /** + * A label of the scan key: its point, public, and its tweak. + * + * @return Nothing; `backend_failure`. + */ + [[nodiscard]] static boost::system::result create_label( + key_state const& scan_key, std::uint32_t label_number, + std::span label_output, + std::span tweak_output) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_secret scan_secret; + static_cast( + secp256k1_keypair_sec(scan_key.context, scan_secret.bytes.data(), &scan_key.keypair)); + secp256k1_silentpayments_label made_label{}; + if (!secp256k1_accepted(secp256k1_silentpayments_recipient_label_create( + scan_key.context, &made_label, tweak_output.data(), scan_secret.bytes.data(), + label_number))) { + return error::backend_failure; + } + // The label's point is public, the labelled address's part; libsecp256k1 made it from the + // scan key's secret, so it is marked public here (secure::declassify). A made label always + // serialises: libsecp256k1 returns 1. + secure::declassify(made_label); + static_cast(secp256k1_silentpayments_recipient_label_serialize( + secp256k1_context_static, label_output.data(), &made_label)); + return {}; + } + + /** + * The spend key with a label. + * + * @return Nothing; `invalid_point` for a label that is no point; `invalid_public_key` for a + * sum at infinity. + */ + [[nodiscard]] static boost::system::result labeled_spend_key( + point const& spend_point, + std::span label_bytes, + point& point_output) noexcept { + secp256k1_static_entry(); + secp256k1_silentpayments_label parsed_label{}; + if (secp256k1_silentpayments_recipient_label_parse(secp256k1_context_static, &parsed_label, + label_bytes.data()) == 0) { + return error::invalid_point; + } + if (secp256k1_silentpayments_recipient_create_labeled_spend_pubkey( + secp256k1_context_static, &point_output, &spend_point, &parsed_label) == 0) { + return error::invalid_public_key; + } + return {}; + } + + /** + * The summary of a transaction's inputs. + * + * @param xonly_pointers The taproot inputs' keys; empty with a null data. + * @param point_pointers The plain inputs' keys; empty with a null data. + * @return Whether libsecp256k1 made it: false for a sum of zero. + */ + [[nodiscard]] static bool make_summary( + std::span outpoint_bytes, + std::span xonly_pointers, + std::span point_pointers, summary& summary_output) noexcept { + secp256k1_static_entry(); + return secp256k1_silentpayments_recipient_prevouts_summary_create( + secp256k1_context_static, &summary_output, outpoint_bytes.data(), + xonly_pointers.data(), xonly_pointers.size(), point_pointers.data(), + point_pointers.size()) != 0; + } + + /** + * The recipient's scan, on the scan key pair's context, as a key pair's other functions run, + * so that libsecp256k1 marks its public values public under the constant-time checkers. + * + * @param lookup_context Null for no labels, or the caller's lookup. + * @return Nothing; `backend_failure`. + */ + [[nodiscard]] static boost::system::result scan( + key_state const& scan_key, summary const& summary_value, point const& spend_point, + std::span output_pointers, + std::span found_pointers, std::uint32_t& found_count, + label_lookup const* lookup_context) noexcept { + // The self test too, as the curve's scan ran it before this move (review 2.2 M3). + secp256k1_static_entry(); + secp256k1_secret scan_secret; + static_cast( + secp256k1_keypair_sec(scan_key.context, scan_secret.bytes.data(), &scan_key.keypair)); + if (!secp256k1_accepted(secp256k1_silentpayments_recipient_scan_outputs( + scan_key.context, found_pointers.data(), &found_count, output_pointers.data(), + output_pointers.size(), scan_secret.bytes.data(), &summary_value, &spend_point, + lookup_context == nullptr ? nullptr : &webcpp_crypto_detail_secp256k1_label_lookup, + lookup_context))) { + return error::backend_failure; + } + return {}; + } + + /** + * A found output's x-only key, 32 bytes. + * + * @param found_value An output a scan found. + * @param key_output 32 bytes. + */ + static void found_output_key( + found_output const& found_value, + std::span key_output) noexcept { + secp256k1_static_entry(); + // A found output always serialises: libsecp256k1 returns 1. + static_cast(secp256k1_xonly_pubkey_serialize(secp256k1_context_static, + key_output.data(), &found_value.output)); + } + + /** + * A found output's spend tweak. + * + * @param found_value An output a scan found. + * @return Its 32 secret bytes. + */ + [[nodiscard]] static std::span found_tweak( + found_output const& found_value) noexcept { + return {found_value.tweak}; + } + + /** + * A found output's label, when it was found with one. + * + * @param found_value An output a scan found. + * @param label_output 33 bytes, written when it was. + * @return Whether it was. + */ + [[nodiscard]] static bool found_label( + found_output const& found_value, + std::span label_output) noexcept { + if (found_value.found_with_label == 0) { + return false; + } + secp256k1_static_entry(); + // A found label always serialises: libsecp256k1 returns 1. + static_cast(secp256k1_silentpayments_recipient_label_serialize( + secp256k1_context_static, label_output.data(), &found_value.label)); + return true; + } +}; + +/** + * The engine of a secp256k1 capability on libsecp256k1, the curve's one backend: what the + * curve's headers name, after `secp256k1_refuses_others` has refused any other backend. + * + * @tparam Capability A tag of `backend::secp256k1_capabilities`. + */ +template +using secp256k1_engine_of = secp256k1_engine; + +// Every engine meets its capabilities (design D5). +static_assert(backend::secp256k1_import>); +static_assert(backend::secp256k1_public>); +static_assert(backend::secp256k1_export>); +static_assert( + backend::secp256k1_point>); +static_assert( + backend::secp256k1_ecdsa_signing>); +static_assert(backend::secp256k1_ecdsa_verifying< + secp256k1_engine_of>); +static_assert( + backend::secp256k1_ecdsa_forms>); +static_assert(backend::secp256k1_schnorr_signing< + secp256k1_engine_of>); +static_assert(backend::secp256k1_schnorr_verifying< + secp256k1_engine_of>); +static_assert(backend::secp256k1_recoverable< + secp256k1_engine_of>); +static_assert(backend::secp256k1_ecdh>); +static_assert( + backend::secp256k1_tweak>); +static_assert( + backend::secp256k1_ellswift>); +static_assert( + backend::secp256k1_musig>); +static_assert(backend::secp256k1_silent_payments< + secp256k1_engine_of>); + +// The specialisation markers (design D5, R7): capabilities of the table, counted by +// capabilities_test. +template <> +inline constexpr bool + specialized_engine_v> = true; +template <> +inline constexpr bool + specialized_engine_v> = true; +template <> +inline constexpr bool + specialized_engine_v> = true; +template <> +inline constexpr bool + specialized_engine_v> = true; +template <> +inline constexpr bool + specialized_engine_v> = true; +template <> +inline constexpr bool + specialized_engine_v> = true; +template <> +inline constexpr bool + specialized_engine_v> = true; +template <> +inline constexpr bool + specialized_engine_v> = true; +template <> +inline constexpr bool + specialized_engine_v> = true; +template <> +inline constexpr bool + specialized_engine_v> = + true; + +// The engines read the key engine's state and hold the point engine's types (the curve's one +// backend), so that one engine's object passes to another's. + +/** + * Whether the engines of `Capabilities` read the key engine's state. + * + * @tparam Capabilities Tags of `backend::secp256k1_capabilities`. + */ +template +inline constexpr bool secp256k1_same_key_state = + (std::is_same_v::key_state, + secp256k1_engine_of::state> && + ...); +/** + * Whether the engines of `Capabilities` hold the point engine's point type. + * + * @tparam Capabilities Tags of `backend::secp256k1_capabilities`. + */ +template +inline constexpr bool secp256k1_same_point = + (std::is_same_v::point, + secp256k1_engine_of::point> && + ...); +/** + * Whether the engines of `Capabilities` hold the point engine's x-only point type. + * + * @tparam Capabilities Tags of `backend::secp256k1_capabilities`. + */ +template +inline constexpr bool secp256k1_same_xonly_point = + (std::is_same_v::xonly_point, + secp256k1_engine_of::xonly_point> && + ...); +static_assert( + secp256k1_same_key_state< + backend::secp256k1_capabilities::ecdsa, backend::secp256k1_capabilities::schnorr, + backend::secp256k1_capabilities::recoverable, backend::secp256k1_capabilities::ecdh, + backend::secp256k1_capabilities::tweak, backend::secp256k1_capabilities::ellswift, + backend::secp256k1_capabilities::musig, backend::secp256k1_capabilities::silent_payments>); +static_assert( + secp256k1_same_point< + backend::secp256k1_capabilities::key, backend::secp256k1_capabilities::ecdsa, + backend::secp256k1_capabilities::recoverable, backend::secp256k1_capabilities::ecdh, + backend::secp256k1_capabilities::tweak, backend::secp256k1_capabilities::ellswift, + backend::secp256k1_capabilities::musig, backend::secp256k1_capabilities::silent_payments>); +static_assert( + secp256k1_same_xonly_point< + backend::secp256k1_capabilities::key, backend::secp256k1_capabilities::schnorr, + backend::secp256k1_capabilities::tweak, backend::secp256k1_capabilities::silent_payments>); + +} // namespace webcpp::crypto::detail + #endif // WEBCPP_CRYPTO_HAS_SECP256K1 #endif // WEBCPP_CRYPTO_BACKENDS_SECP256K1_HPP diff --git a/include/webcpp/crypto/backends/sodium.hpp b/include/webcpp/crypto/backends/sodium.hpp index 630d102..4199b1a 100644 --- a/include/webcpp/crypto/backends/sodium.hpp +++ b/include/webcpp/crypto/backends/sodium.hpp @@ -22,8 +22,10 @@ #else #include +#include #include #include +#include #include #include #include @@ -434,6 +436,25 @@ struct aead_engine { static void reset(state& engine_state) noexcept { secure::erase_secret(engine_state.key); } }; +static_assert(backend::aead, + families::chacha20_poly1305>); +static_assert(backend::aead, + families::chacha20_poly1305_original>); +static_assert(backend::aead, + families::xchacha20_poly1305>); +// The specialisation marker (design D5, R7): a capability of the table, counted by +// capabilities_test. +template <> +inline constexpr bool + specialized_engine_v> = true; +template <> +inline constexpr bool + specialized_engine_v> = + true; +template <> +inline constexpr bool + specialized_engine_v> = true; + /** ChaCha20's state on libsodium: the key, in the object, since libsodium takes it per call. */ template <> struct stream_state { @@ -509,6 +530,14 @@ struct stream_engine { static void reset(state& engine_state) noexcept { secure::erase_secret(engine_state.key); } }; +static_assert(backend::stream_cipher, + families::chacha20>); +// The specialisation marker (design D5, R7): a capability of the table, counted by +// capabilities_test. +template <> +inline constexpr bool specialized_engine_v> = + true; + /** * RFC 8439's Poly1305 on libsodium, `crypto_onetimeauth_poly1305`, one call per tag: libsodium * reads the key from the caller's bytes and wipes its own state (design D14). @@ -544,6 +573,14 @@ struct authenticator_engine { } }; +static_assert(backend::authenticator, + families::poly1305>); +// The specialisation marker (design D5, R7): a capability of the table, counted by +// capabilities_test. +template <> +inline constexpr bool + specialized_engine_v> = true; + /** libsodium's detached functions of a secret box family, which differ only by name. */ template struct sodium_secretbox_calls; @@ -683,6 +720,22 @@ struct secretbox_engine { static void reset(state& engine_state) noexcept { secure::erase_secret(engine_state.key); } }; +static_assert(backend::authenticated_box< + secretbox_engine, + families::secretbox_xsalsa20poly1305>); +static_assert(backend::authenticated_box< + secretbox_engine, + families::secretbox_xchacha20poly1305>); +// The specialisation marker (design D5, R7): a capability of the table, counted by +// capabilities_test. +template <> +inline constexpr bool + specialized_engine_v> = + true; +template <> +inline constexpr bool specialized_engine_v< + secretbox_engine> = true; + } // namespace webcpp::crypto::detail #endif // WEBCPP_CRYPTO_HAS_SODIUM @@ -698,6 +751,8 @@ struct secretbox_engine { /** Defined once libsodium's Ed25519 engines are. */ #define WEBCPP_CRYPTO_BACKENDS_SODIUM_ED25519 +#include + #include #include @@ -744,11 +799,11 @@ struct ed25519_engine { using state = ed25519_state; /** - * Makes the secret key of a seed, `crypto_sign_ed25519_seed_keypair`. + * Makes the secret key of a seed, `crypto_sign_ed25519_seed_keypair` (`ed25519_import`). * * @return Nothing; `backend_failure`. */ - [[nodiscard]] static boost::system::result seed_keypair( + [[nodiscard]] static boost::system::result import_secret( state& keyed_state, std::span seed_bytes) noexcept { auto const library_ready = sodium_ready(); if (!library_ready) { @@ -762,19 +817,34 @@ struct ed25519_engine { return {}; } - /** The public key, the secret key's second half. */ - static void public_key(state const& keyed_state, - std::span output_bytes) noexcept { + /** + * The public key, the secret key's second half (`ed25519_public`). + * + * @return Nothing; `backend_failure`. + */ + [[nodiscard]] static boost::system::result public_key( + state const& keyed_state, std::span output_bytes) noexcept { read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); - static_cast( - crypto_sign_ed25519_sk_to_pk(output_bytes.data(), keyed_state.secret_key.data())); + if (crypto_sign_ed25519_sk_to_pk(output_bytes.data(), keyed_state.secret_key.data()) != 0) { + return error::backend_failure; + } + return {}; } - /** The seed, the secret key's first half, `crypto_sign_ed25519_sk_to_seed`. */ - static void seed(state const& keyed_state, std::span output_bytes) noexcept { + /** + * The seed, the secret key's first half, `crypto_sign_ed25519_sk_to_seed` + * (`ed25519_export`). + * + * @return Nothing; `backend_failure`. + */ + [[nodiscard]] static boost::system::result export_secret( + state const& keyed_state, std::span output_bytes) noexcept { read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); - static_cast( - crypto_sign_ed25519_sk_to_seed(output_bytes.data(), keyed_state.secret_key.data())); + if (crypto_sign_ed25519_sk_to_seed(output_bytes.data(), keyed_state.secret_key.data()) != + 0) { + return error::backend_failure; + } + return {}; } /** @@ -847,10 +917,28 @@ struct ed25519_engine { return {}; } + /** Moves a key: the target takes the source's secret key, and the source is wiped. */ + static void move(state& target_state, state& source_state) noexcept { + target_state.secret_key = source_state.secret_key; + secure::erase_secret(source_state.secret_key); + } + /** Wipes the secret key. */ static void reset(state& keyed_state) noexcept { secure::erase_secret(keyed_state.secret_key); } }; +static_assert(backend::ed25519_import>); +static_assert(backend::ed25519_public>); +static_assert(backend::ed25519_export>); +static_assert(backend::ed25519_signing>); +static_assert(backend::ed25519_verifying>); +static_assert(backend::ed25519_to_x25519>); +// The specialisation marker (design D5, R7): a capability of the table, counted by +// capabilities_test. +template <> +inline constexpr bool specialized_engine_v> = + true; + /** What an Ed25519ph signer stores on libsodium: the message's SHA-512 state. */ template <> struct ed25519ph_state { @@ -975,6 +1063,14 @@ struct ed25519ph_engine { } }; +static_assert(backend::ed25519ph, + ed25519_engine>); +// The specialisation marker (design D5, R7): a capability of the table, counted by +// capabilities_test. +template <> +inline constexpr bool specialized_engine_v> = + true; + } // namespace webcpp::crypto::detail #endif // Ed25519 on libsodium @@ -986,56 +1082,116 @@ struct ed25519ph_engine { /** Defined once libsodium's X25519 engine is. */ #define WEBCPP_CRYPTO_BACKENDS_SODIUM_X25519 +#include + #include +#include +#include #include #include namespace webcpp::crypto::detail { +/** What an X25519 key pair stores on libsodium: its secret key. */ +template <> +struct x25519_state { + /** The secret key, as libsodium takes it. */ + std::array secret_key{}; +}; + /** X25519 on libsodium, `crypto_scalarmult_curve25519`. */ template <> struct x25519_engine { + /** The key pair's state. */ + using state = x25519_state; + /** - * The public key of a secret key, `crypto_scalarmult_curve25519_base`. + * Keeps a secret key (`x25519_import`): any 32 bytes are one, RFC 7748 clamping them where they + * are used. * * @return Nothing; `backend_failure`. */ - [[nodiscard]] static boost::system::result base( - std::span secret_key, - std::span output_bytes) noexcept { + [[nodiscard]] static boost::system::result import_secret( + state& keyed_state, std::span secret_bytes) noexcept { auto const library_ready = sodium_ready(); if (!library_ready) { return library_ready; } - if (crypto_scalarmult_curve25519_base(output_bytes.data(), secret_key.data()) != 0) { + std::ranges::copy(secret_bytes, keyed_state.secret_key.begin()); + return {}; + } + + /** + * The public key, `crypto_scalarmult_curve25519_base` (`x25519_public`). + * + * @return Nothing; `backend_failure`. + */ + [[nodiscard]] static boost::system::result public_key( + state const& keyed_state, std::span output_bytes) noexcept { + auto const library_ready = sodium_ready(); + if (!library_ready) { + return library_ready; + } + if (crypto_scalarmult_curve25519_base(output_bytes.data(), keyed_state.secret_key.data()) != + 0) { return error::backend_failure; } return {}; } + /** + * The secret key back (`x25519_export`). + * + * @return Nothing. + */ + [[nodiscard]] static boost::system::result export_secret( + state const& keyed_state, std::span output_bytes) noexcept { + read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); + std::ranges::copy(keyed_state.secret_key, output_bytes.begin()); + return {}; + } + /** * The shared secret, `crypto_scalarmult_curve25519`, which returns -1 for an all-zero - * result. + * result (`x25519_agreement`). * * @return Nothing; `weak_public_key`; `backend_failure`. */ [[nodiscard]] static boost::system::result agree( - std::span secret_key, - std::span peer_public_key, + state const& keyed_state, std::span peer_public_key, std::span output_bytes) noexcept { auto const library_ready = sodium_ready(); if (!library_ready) { return library_ready; } - if (sodium_refused(crypto_scalarmult_curve25519(output_bytes.data(), secret_key.data(), - peer_public_key.data()))) { + if (sodium_refused(crypto_scalarmult_curve25519( + output_bytes.data(), keyed_state.secret_key.data(), peer_public_key.data()))) { return error::weak_public_key; } return {}; } + + /** Moves a key: the target takes the source's secret key, and the source is wiped. */ + static void move(state& target_state, state& source_state) noexcept { + target_state.secret_key = source_state.secret_key; + secure::erase_secret(source_state.secret_key); + } + + /** Wipes the secret key. */ + static void reset(state& keyed_state) noexcept { secure::erase_secret(keyed_state.secret_key); } }; +static_assert(backend::x25519_import>); +static_assert(backend::x25519_public>); +static_assert(backend::x25519_export>); +static_assert(backend::x25519_agreement>); +// The specialisation marker (design D5, R7): a capability of the table, counted by +// capabilities_test. +template <> +inline constexpr bool specialized_engine_v> = + true; + } // namespace webcpp::crypto::detail #endif // X25519 on libsodium @@ -1048,6 +1204,8 @@ struct x25519_engine { /** Defined once libsodium's box engines are. */ #define WEBCPP_CRYPTO_BACKENDS_SODIUM_BOX +#include + #include #include @@ -1161,6 +1319,17 @@ struct box_engine { static void reset(state& engine_state) noexcept { secure::erase_secret(engine_state.key); } }; +static_assert(backend::box>); +static_assert(backend::box>); +// The specialisation marker (design D5, R7): a capability of the table, counted by +// capabilities_test. +template <> +inline constexpr bool + specialized_engine_v> = true; +template <> +inline constexpr bool + specialized_engine_v> = true; + } // namespace webcpp::crypto::detail #endif // the boxes on libsodium @@ -1173,6 +1342,8 @@ struct box_engine { /** Defined once libsodium's sealed box engine is. */ #define WEBCPP_CRYPTO_BACKENDS_SODIUM_SEALED_BOX +#include + #include #include @@ -1235,186 +1406,16 @@ struct sealed_box_engine { } }; -} // namespace webcpp::crypto::detail - -#endif // sealed boxes on libsodium -// RFC 8410's key formats on libsodium, for a program that includes curves/ed25519/formats.hpp or -// curves/x25519/formats.hpp, before this header or after it, as Ed25519's above: each defines -// its macro ..._FORMATS_DECLARED once its declarations are, then includes this header. RFC 8410 -// fixes the layout around the 32 key bytes, so libsodium's engine writes and compares its -// prefixes, constants rather than cryptography (design D30). -#if (defined(WEBCPP_CRYPTO_DETAIL_ED25519_FORMATS_DECLARED) || \ - defined(WEBCPP_CRYPTO_DETAIL_X25519_FORMATS_DECLARED)) && \ - defined(WEBCPP_CRYPTO_HAS_SODIUM) && !defined(WEBCPP_CRYPTO_BACKENDS_SODIUM_RFC8410) -/** Defined once libsodium's RFC 8410 layouts are. */ -#define WEBCPP_CRYPTO_BACKENDS_SODIUM_RFC8410 - -#include - -#include -#include -#include -#include -#include - -namespace webcpp::crypto::detail { - -/** - * RFC 8410's fixed layouts on libsodium: a prefix, then 32 key bytes. A decoding is accepted - * only where its prefix is the one encoding the key gives, compared with `constant_time_equal`, and - * its size the one size (the callers check it), which is design D30's re-encoding test for a fixed - * layout. - */ -struct sodium_rfc8410 { - /** - * Writes the prefix, then the key. - * - * @param prefix_bytes The format's prefix. - * @param key_bytes 32 bytes. - * @param output_bytes The prefix's size and 32 bytes. - */ - template - static void encode(std::array const& prefix_bytes, - std::span key_bytes, - std::span output_bytes) noexcept { - read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); - std::ranges::copy(key_bytes, std::ranges::copy(prefix_bytes, output_bytes.begin()).out); - } - - /** - * Copies the key out of an encoding whose prefix is the format's. - * - * Whether the prefix is the format's is public, since it is reported: marked so for the - * constant-time checks, for an encoding read from a secret text (a PKCS#8's PEM), whose - * prefix carries the text's secrecy through its base64. - * - * @param prefix_bytes The format's prefix. - * @param der_bytes The prefix's size and 32 bytes. - * @param key_bytes 32 bytes, written only when the prefix is the format's. - * @return Nothing; `invalid_encoding`. - */ - template - [[nodiscard]] static boost::system::result decode( - std::array const& prefix_bytes, - std::span der_bytes, - std::span key_bytes) noexcept { - read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); - // Not const: the branch reads it again after the mark (secure::declassify's tip). - // NOLINTNEXTLINE(misc-const-correctness): see above - bool prefix_matches = - secure::constant_time_equal(der_bytes.template first(), prefix_bytes); - secure::declassify(prefix_matches); - if (!prefix_matches) { - return error::invalid_encoding; - } - std::ranges::copy(der_bytes.template last<32>(), key_bytes.begin()); - return {}; - } -}; - -} // namespace webcpp::crypto::detail - -#endif // RFC 8410 on libsodium - -#if defined(WEBCPP_CRYPTO_DETAIL_ED25519_FORMATS_DECLARED) && defined(WEBCPP_CRYPTO_HAS_SODIUM) && \ - !defined(WEBCPP_CRYPTO_BACKENDS_SODIUM_ED25519_FORMATS) -/** Defined once libsodium's Ed25519 formats engine is. */ -#define WEBCPP_CRYPTO_BACKENDS_SODIUM_ED25519_FORMATS - -namespace webcpp::crypto::detail { - -/** Ed25519's SPKI and PKCS#8 on libsodium: RFC 8410's prefixes around the key bytes. */ +static_assert(backend::sealed_box>); +// The specialisation marker (design D5, R7): a capability of the table, counted by +// capabilities_test. template <> -struct ed25519_formats_engine { - /** Writes the SPKI. */ - static void encode_spki(std::span public_key, - std::span output_bytes) noexcept { - sodium_rfc8410::encode(ed25519_spki_prefix, public_key, output_bytes); - } - - /** - * Reads the public key of an SPKI. - * - * @return Nothing; `invalid_encoding`. - */ - [[nodiscard]] static boost::system::result decode_spki( - std::span spki_bytes, - std::span public_key) noexcept { - return sodium_rfc8410::decode(ed25519_spki_prefix, spki_bytes, public_key); - } - - /** Writes the PKCS#8 of the seed, the first half of libsodium's secret key. */ - static void encode_pkcs8(ed25519_state const& keyed_state, - std::span output_bytes) noexcept { - sodium_rfc8410::encode(ed25519_pkcs8_prefix, - std::span(keyed_state.secret_key).first<32>(), - output_bytes); - } - - /** - * Reads the seed of a PKCS#8. - * - * @return Nothing; `invalid_encoding`. - */ - [[nodiscard]] static boost::system::result decode_pkcs8( - std::span pkcs8_bytes, - std::span seed_bytes) noexcept { - return sodium_rfc8410::decode(ed25519_pkcs8_prefix, pkcs8_bytes, seed_bytes); - } -}; - -} // namespace webcpp::crypto::detail - -#endif // Ed25519's formats on libsodium - -#if defined(WEBCPP_CRYPTO_DETAIL_X25519_FORMATS_DECLARED) && defined(WEBCPP_CRYPTO_HAS_SODIUM) && \ - !defined(WEBCPP_CRYPTO_BACKENDS_SODIUM_X25519_FORMATS) -/** Defined once libsodium's X25519 formats engine is. */ -#define WEBCPP_CRYPTO_BACKENDS_SODIUM_X25519_FORMATS - -namespace webcpp::crypto::detail { - -/** X25519's SPKI and PKCS#8 on libsodium: RFC 8410's prefixes around the key bytes. */ -template <> -struct x25519_formats_engine { - /** Writes the SPKI. */ - static void encode_spki(std::span public_key, - std::span output_bytes) noexcept { - sodium_rfc8410::encode(x25519_spki_prefix, public_key, output_bytes); - } - - /** - * Reads the public key of an SPKI. - * - * @return Nothing; `invalid_encoding`. - */ - [[nodiscard]] static boost::system::result decode_spki( - std::span spki_bytes, - std::span public_key) noexcept { - return sodium_rfc8410::decode(x25519_spki_prefix, spki_bytes, public_key); - } - - /** Writes the PKCS#8 of a secret key. */ - static void encode_pkcs8(std::span secret_key, - std::span output_bytes) noexcept { - sodium_rfc8410::encode(x25519_pkcs8_prefix, secret_key, output_bytes); - } - - /** - * Reads the secret key of a PKCS#8. - * - * @return Nothing; `invalid_encoding`. - */ - [[nodiscard]] static boost::system::result decode_pkcs8( - std::span pkcs8_bytes, - std::span secret_key) noexcept { - return sodium_rfc8410::decode(x25519_pkcs8_prefix, pkcs8_bytes, secret_key); - } -}; +inline constexpr bool + specialized_engine_v> = true; } // namespace webcpp::crypto::detail -#endif // X25519's formats on libsodium +#endif // sealed boxes on libsodium // crypto_kx on libsodium, for a program that includes key_exchange/kx.hpp, before this header or // after it, as the boxes above: kx.hpp defines WEBCPP_CRYPTO_DETAIL_KX_DECLARED once its @@ -1424,6 +1425,8 @@ struct x25519_formats_engine { /** Defined once libsodium's crypto_kx engine is. */ #define WEBCPP_CRYPTO_BACKENDS_SODIUM_KX +#include + #include #include @@ -1505,6 +1508,12 @@ struct kx_engine { } }; +static_assert(backend::kx>); +// The specialisation marker (design D5, R7): a capability of the table, counted by +// capabilities_test. +template <> +inline constexpr bool specialized_engine_v> = true; + } // namespace webcpp::crypto::detail #endif // crypto_kx on libsodium diff --git a/include/webcpp/crypto/ciphers/aead.hpp b/include/webcpp/crypto/ciphers/aead.hpp index 09b8568..4c5d1c1 100644 --- a/include/webcpp/crypto/ciphers/aead.hpp +++ b/include/webcpp/crypto/ciphers/aead.hpp @@ -23,8 +23,10 @@ #include #include +#include #include #include +#include #include #include #include // crypto::from_key, which serves its from_key (design R23) @@ -42,55 +44,6 @@ #include #include -namespace webcpp::crypto::families { - -/** RFC 8439's ChaCha20-Poly1305: a 32-byte key, a 12-byte nonce, a 16-byte tag. */ -struct chacha20_poly1305 { - /** The key's size. */ - static constexpr std::size_t key_size = 32; - /** The nonce's size, exactly (RFC 8439 section 2.8). */ - static constexpr std::size_t nonce_size = 12; - /** The tag's size. */ - static constexpr std::size_t tag_size = 16; - /** The longest message, 2^38 - 64 bytes: ChaCha20's 32-bit block counter (section 2.8). */ - static constexpr std::uint64_t max_message_size = (std::uint64_t{1} << 38U) - 64; - /** The longest associated data, 2^64 - 1 bytes (section 2.8). */ - static constexpr std::uint64_t max_associated_data_size = ~std::uint64_t{0}; -}; - -/** - * The original ChaCha20-Poly1305, an 8-byte nonce and a 64-bit block counter, as libsodium's - * `crypto_aead_chacha20poly1305` has it. - */ -struct chacha20_poly1305_original { - /** The key's size. */ - static constexpr std::size_t key_size = 32; - /** The nonce's size, exactly. */ - static constexpr std::size_t nonce_size = 8; - /** The tag's size. */ - static constexpr std::size_t tag_size = 16; - /** The longest message, 2^64 - 17 bytes. */ - static constexpr std::uint64_t max_message_size = ~std::uint64_t{0} - 16; - /** The longest associated data, 2^64 - 1 bytes. */ - static constexpr std::uint64_t max_associated_data_size = ~std::uint64_t{0}; -}; - -/** XChaCha20-Poly1305, a 24-byte nonce safe to draw at random. */ -struct xchacha20_poly1305 { - /** The key's size. */ - static constexpr std::size_t key_size = 32; - /** The nonce's size, exactly. */ - static constexpr std::size_t nonce_size = 24; - /** The tag's size. */ - static constexpr std::size_t tag_size = 16; - /** The longest message, 2^64 - 17 bytes. */ - static constexpr std::uint64_t max_message_size = ~std::uint64_t{0} - 16; - /** The longest associated data, 2^64 - 1 bytes. */ - static constexpr std::uint64_t max_associated_data_size = ~std::uint64_t{0}; -}; - -} // namespace webcpp::crypto::families - namespace webcpp::crypto::detail { /** @@ -207,6 +160,44 @@ struct aead_engine : aead_refusal { static void reset(Arguments&&... /*arguments*/) noexcept {} }; +/** + * Whether the engine of an AEAD family on a backend has its capability (design D9): true for the + * family's primary engine, whose generated refusal speaks, and for a test's unmarked stand-in, + * taken at its word; for an engine a backend's header specialises (`specialized_engine_v`), the + * capability, asserted by a message that names it. Each public member that calls the engine asks it + * first. + * + * @tparam Family The AEAD's family. + * @tparam Engine Its engine on the backend. + * @return Whether the member may call the engine. + */ +template +constexpr bool aead_capability_checked() noexcept { + if constexpr (!specialized_engine_v) { + return true; + } else { + if constexpr (std::is_same_v) { + static_assert( + backend::aead, + "webcpp::crypto: this backend has ChaCha20-Poly1305 but not " + "crypto::capabilities::chacha20_poly1305: the cipher is not available on it."); + } + if constexpr (std::is_same_v) { + static_assert(backend::aead, + "webcpp::crypto: this backend has the original ChaCha20-Poly1305 but not " + "crypto::capabilities::chacha20_poly1305_original: the cipher is not " + "available on it."); + } + if constexpr (std::is_same_v) { + static_assert( + backend::aead, + "webcpp::crypto: this backend has XChaCha20-Poly1305 but not " + "crypto::capabilities::xchacha20_poly1305: the cipher is not available on it."); + } + return backend::aead; + } +} + } // namespace webcpp::crypto::detail namespace webcpp::crypto::ciphers { @@ -267,21 +258,27 @@ class basic_chacha20_poly1305 { [[nodiscard]] static boost::system::result from_key( std::span key_bytes) noexcept { secure::timing_guard const timing_scope; - if constexpr (detail::asynchronous_backend_v) { - // WebCrypto has no such construction: the refusal names a native backend (design D6). - detail::refuse_aead_on_asynchronous_backend(); + if constexpr (!detail::aead_capability_checked()) { + // Never compiled into a program: the capability's assertion stopped the build. return error::backend_failure; } else { - if (key_bytes.size() != key_size) { - return error::invalid_key_size; + if constexpr (detail::asynchronous_backend_v) { + // WebCrypto has no such construction: the refusal names a native backend (design + // D6). + detail::refuse_aead_on_asynchronous_backend(); + return error::backend_failure; + } else { + if (key_bytes.size() != key_size) { + return error::invalid_key_size; + } + basic_chacha20_poly1305 made_object; + auto const key_result = engine::init(made_object.state_, key_bytes); + if (!key_result) { + return key_result.error(); + } + made_object.keyed_ = true; + return made_object; } - basic_chacha20_poly1305 made_object; - auto const key_result = engine::init(made_object.state_, key_bytes); - if (!key_result) { - return key_result.error(); - } - made_object.keyed_ = true; - return made_object; } } @@ -378,24 +375,30 @@ class basic_chacha20_poly1305 { std::span associated_data_bytes, std::span data_bytes) noexcept { secure::timing_guard const timing_scope; - if constexpr (detail::asynchronous_backend_v) { - // WebCrypto has no such construction: the refusal names a native backend (design D6). - detail::refuse_aead_on_asynchronous_backend(); + if constexpr (!detail::aead_capability_checked()) { + // Never compiled into a program: the capability's assertion stopped the build. return error::backend_failure; } else { - auto const guard_result = - guard_message(nonce_bytes, associated_data_bytes, data_bytes.size(), tag_size); - if (!guard_result) { - return guard_result.error(); - } - result_type tag_bytes{}; - auto const seal_result = - engine::seal(state_, nonce_bytes, associated_data_bytes, data_bytes, tag_bytes); - if (!seal_result) { - secure::erase_secret(data_bytes); - return seal_result.error(); + if constexpr (detail::asynchronous_backend_v) { + // WebCrypto has no such construction: the refusal names a native backend (design + // D6). + detail::refuse_aead_on_asynchronous_backend(); + return error::backend_failure; + } else { + auto const guard_result = + guard_message(nonce_bytes, associated_data_bytes, data_bytes.size(), tag_size); + if (!guard_result) { + return guard_result.error(); + } + result_type tag_bytes{}; + auto const seal_result = + engine::seal(state_, nonce_bytes, associated_data_bytes, data_bytes, tag_bytes); + if (!seal_result) { + secure::erase_secret(data_bytes); + return seal_result.error(); + } + return tag_bytes; } - return tag_bytes; } } @@ -448,26 +451,32 @@ class basic_chacha20_poly1305 { std::span associated_data_bytes, std::span data_bytes, std::span tag_bytes) noexcept { secure::timing_guard const timing_scope; - if constexpr (detail::asynchronous_backend_v) { - // WebCrypto has no such construction: the refusal names a native backend (design D6). - detail::refuse_aead_on_asynchronous_backend(); + if constexpr (!detail::aead_capability_checked()) { + // Never compiled into a program: the capability's assertion stopped the build. return error::backend_failure; } else { - auto const guard_result = guard_message(nonce_bytes, associated_data_bytes, - data_bytes.size(), tag_bytes.size()); - if (!guard_result) { - return guard_result.error(); - } - // The tag may lie in data, which decryption overwrites: a copy is checked. - std::array expected_tag{}; - std::ranges::copy(tag_bytes, expected_tag.begin()); - auto const open_result = - engine::open(state_, nonce_bytes, associated_data_bytes, data_bytes, expected_tag); - if (!open_result) { - secure::erase_secret(data_bytes); - return open_result.error(); + if constexpr (detail::asynchronous_backend_v) { + // WebCrypto has no such construction: the refusal names a native backend (design + // D6). + detail::refuse_aead_on_asynchronous_backend(); + return error::backend_failure; + } else { + auto const guard_result = guard_message(nonce_bytes, associated_data_bytes, + data_bytes.size(), tag_bytes.size()); + if (!guard_result) { + return guard_result.error(); + } + // The tag may lie in data, which decryption overwrites: a copy is checked. + std::array expected_tag{}; + std::ranges::copy(tag_bytes, expected_tag.begin()); + auto const open_result = engine::open(state_, nonce_bytes, associated_data_bytes, + data_bytes, expected_tag); + if (!open_result) { + secure::erase_secret(data_bytes); + return open_result.error(); + } + return {}; } - return {}; } } diff --git a/include/webcpp/crypto/ciphers/aes.hpp b/include/webcpp/crypto/ciphers/aes.hpp index 056cf8d..4e349fd 100644 --- a/include/webcpp/crypto/ciphers/aes.hpp +++ b/include/webcpp/crypto/ciphers/aes.hpp @@ -21,6 +21,7 @@ #include +#include #include #include #include @@ -118,6 +119,27 @@ struct block_engine { static void reset(Arguments&&... /*arguments*/) noexcept {} }; +/** + * Whether AES's block engine on a backend has its capability (design D9): true for the family's + * primary engine, whose generated refusal speaks, and for a test's unmarked stand-in, taken at its + * word; for an engine a backend's header specialises (`specialized_engine_v`), the capability, + * asserted by a message that names it. Each public member that calls the engine asks it first. + * + * @tparam Engine AES's block engine on the backend, for one key size. + * @return Whether the member may call the engine. + */ +template +constexpr bool aes_block_capability_checked() noexcept { + if constexpr (!specialized_engine_v) { + return true; + } else { + static_assert(backend::block_cipher, + "webcpp::crypto: this backend has AES but not " + "crypto::capabilities::aes_block: the block cipher is not available on it."); + return backend::block_cipher; + } +} + /** * The AES block cipher with keys of `KeySize` bytes on `Backend`, of which `aes128`, `aes192` * and `aes256` are the named forms. @@ -201,13 +223,18 @@ class basic_aes { [[nodiscard]] boost::system::result encrypt( std::span block_bytes) noexcept { secure::timing_guard const timing_scope; - if (!keyed_) { - return error::invalid_state; - } - if (block_bytes.size() % block_size != 0) { - return error::invalid_input_size; + if constexpr (!aes_block_capability_checked()) { + // Never compiled into a program: the capability's assertion stopped the build. + return error::backend_failure; + } else { + if (!keyed_) { + return error::invalid_state; + } + if (block_bytes.size() % block_size != 0) { + return error::invalid_input_size; + } + return engine::encrypt(state_, block_bytes); } - return engine::encrypt(state_, block_bytes); } /** @@ -220,13 +247,18 @@ class basic_aes { [[nodiscard]] boost::system::result decrypt( std::span block_bytes) noexcept { secure::timing_guard const timing_scope; - if (!keyed_) { - return error::invalid_state; - } - if (block_bytes.size() % block_size != 0) { - return error::invalid_input_size; + if constexpr (!aes_block_capability_checked()) { + // Never compiled into a program: the capability's assertion stopped the build. + return error::backend_failure; + } else { + if (!keyed_) { + return error::invalid_state; + } + if (block_bytes.size() % block_size != 0) { + return error::invalid_input_size; + } + return engine::decrypt(state_, block_bytes); } - return engine::decrypt(state_, block_bytes); } protected: @@ -243,16 +275,21 @@ class basic_aes { template [[nodiscard]] static boost::system::result keyed_as( std::span key_bytes) noexcept { - if (key_bytes.size() != key_size) { - return error::invalid_key_size; - } - Derived made_object; - auto const key_result = engine::init(made_object.state_, key_bytes); - if (!key_result) { - return key_result.error(); + if constexpr (!aes_block_capability_checked()) { + // Never compiled into a program: the capability's assertion stopped the build. + return error::backend_failure; + } else { + if (key_bytes.size() != key_size) { + return error::invalid_key_size; + } + Derived made_object; + auto const key_result = engine::init(made_object.state_, key_bytes); + if (!key_result) { + return key_result.error(); + } + made_object.keyed_ = true; + return made_object; } - made_object.keyed_ = true; - return made_object; } private: diff --git a/include/webcpp/crypto/ciphers/gcm.hpp b/include/webcpp/crypto/ciphers/gcm.hpp index 3146f12..e4ed30c 100644 --- a/include/webcpp/crypto/ciphers/gcm.hpp +++ b/include/webcpp/crypto/ciphers/gcm.hpp @@ -22,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -105,6 +106,27 @@ struct gcm_engine { static void reset(Arguments&&... /*arguments*/) noexcept {} }; +/** + * Whether GCM's engine on a backend has its capability (design D9): true for the family's primary + * engine, whose generated refusal speaks, and for a test's unmarked stand-in, taken at its word; + * for an engine a backend's header specialises (`specialized_engine_v`), the capability, asserted + * by a message that names it. Each public member that calls the engine asks it first. + * + * @tparam Engine GCM's engine on the backend, for one key size. + * @return Whether the member may call the engine. + */ +template +constexpr bool gcm_capability_checked() noexcept { + if constexpr (!specialized_engine_v) { + return true; + } else { + static_assert(backend::gcm, + "webcpp::crypto: this backend has AES-GCM but not crypto::capabilities::gcm: " + "the cipher is not available on it."); + return backend::gcm; + } +} + } // namespace webcpp::crypto::detail namespace webcpp::crypto::ciphers { @@ -170,23 +192,28 @@ class gcm { [[nodiscard]] static boost::system::result from_key( std::span key_bytes) noexcept { secure::timing_guard const timing_scope; - static_assert(!detail::asynchronous_backend_v, - "webcpp::crypto: from_key on this backend completes asynchronously: call " - "async_from_key."); - if constexpr (detail::asynchronous_backend_v) { - // Never compiled into a program: the assertion above stopped the build. + if constexpr (!detail::gcm_capability_checked()) { + // Never compiled into a program: the capability's assertion stopped the build. return error::backend_failure; } else { - if (key_bytes.size() != key_size) { - return error::invalid_key_size; - } - gcm made_object; - auto const key_result = engine::init(made_object.state_, key_bytes); - if (!key_result) { - return key_result.error(); + static_assert(!detail::asynchronous_backend_v, + "webcpp::crypto: from_key on this backend completes asynchronously: call " + "async_from_key."); + if constexpr (detail::asynchronous_backend_v) { + // Never compiled into a program: the assertion above stopped the build. + return error::backend_failure; + } else { + if (key_bytes.size() != key_size) { + return error::invalid_key_size; + } + gcm made_object; + auto const key_result = engine::init(made_object.state_, key_bytes); + if (!key_result) { + return key_result.error(); + } + made_object.keyed_ = true; + return made_object; } - made_object.keyed_ = true; - return made_object; } } @@ -281,31 +308,37 @@ class gcm { std::span associated_data_bytes, std::span data_bytes) noexcept { secure::timing_guard const timing_scope; - static_assert( - !detail::asynchronous_backend_v, - "webcpp::crypto: seal on this backend completes asynchronously: call async_seal."); - if constexpr (detail::asynchronous_backend_v) { - // Never compiled into a program: the assertion above stopped the build. + if constexpr (!detail::gcm_capability_checked()) { + // Never compiled into a program: the capability's assertion stopped the build. return error::backend_failure; } else { - auto const guard_result = - guard_message(nonce_bytes, associated_data_bytes, data_bytes.size(), tag_size); - if (!guard_result) { - return guard_result.error(); - } - auto const start_result = - engine::start(state_, true, nonce_bytes, associated_data_bytes); - auto const run_result = start_result ? engine::run(state_, data_bytes) : start_result; - result_type tag_bytes{}; - auto const tag_result = run_result ? engine::tag(state_, tag_bytes) : run_result; - if (!tag_result) { - // A message without a tag is not to be sent: data is zeroed, and nothing of the - // failed message stays in the context, as after an incremental one. - secure::erase_secret(data_bytes); - engine::abandon(state_); - return tag_result.error(); + static_assert( + !detail::asynchronous_backend_v, + "webcpp::crypto: seal on this backend completes asynchronously: call async_seal."); + if constexpr (detail::asynchronous_backend_v) { + // Never compiled into a program: the assertion above stopped the build. + return error::backend_failure; + } else { + auto const guard_result = + guard_message(nonce_bytes, associated_data_bytes, data_bytes.size(), tag_size); + if (!guard_result) { + return guard_result.error(); + } + auto const start_result = + engine::start(state_, true, nonce_bytes, associated_data_bytes); + auto const run_result = + start_result ? engine::run(state_, data_bytes) : start_result; + result_type tag_bytes{}; + auto const tag_result = run_result ? engine::tag(state_, tag_bytes) : run_result; + if (!tag_result) { + // A message without a tag is not to be sent: data is zeroed, and nothing of the + // failed message stays in the context, as after an incremental one. + secure::erase_secret(data_bytes); + engine::abandon(state_); + return tag_result.error(); + } + return tag_bytes; } - return tag_bytes; } } @@ -358,32 +391,38 @@ class gcm { std::span associated_data_bytes, std::span data_bytes, std::span tag_bytes) noexcept { secure::timing_guard const timing_scope; - static_assert( - !detail::asynchronous_backend_v, - "webcpp::crypto: open on this backend completes asynchronously: call async_open."); - if constexpr (detail::asynchronous_backend_v) { - // Never compiled into a program: the assertion above stopped the build. + if constexpr (!detail::gcm_capability_checked()) { + // Never compiled into a program: the capability's assertion stopped the build. return error::backend_failure; } else { - auto const guard_result = guard_message(nonce_bytes, associated_data_bytes, - data_bytes.size(), tag_bytes.size()); - if (!guard_result) { - return guard_result.error(); - } - // The tag may lie in data, which decryption overwrites: a copy is checked. - std::array expected_tag{}; - std::ranges::copy(tag_bytes, expected_tag.begin()); - auto const start_result = - engine::start(state_, false, nonce_bytes, associated_data_bytes); - auto const open_result = start_result ? engine::run(state_, data_bytes) : start_result; - auto const tag_check_result = - open_result ? engine::check(state_, expected_tag) : open_result; - if (!tag_check_result) { - secure::erase_secret(data_bytes); - engine::abandon(state_); - return tag_check_result.error(); + static_assert( + !detail::asynchronous_backend_v, + "webcpp::crypto: open on this backend completes asynchronously: call async_open."); + if constexpr (detail::asynchronous_backend_v) { + // Never compiled into a program: the assertion above stopped the build. + return error::backend_failure; + } else { + auto const guard_result = guard_message(nonce_bytes, associated_data_bytes, + data_bytes.size(), tag_bytes.size()); + if (!guard_result) { + return guard_result.error(); + } + // The tag may lie in data, which decryption overwrites: a copy is checked. + std::array expected_tag{}; + std::ranges::copy(tag_bytes, expected_tag.begin()); + auto const start_result = + engine::start(state_, false, nonce_bytes, associated_data_bytes); + auto const open_result = + start_result ? engine::run(state_, data_bytes) : start_result; + auto const tag_check_result = + open_result ? engine::check(state_, expected_tag) : open_result; + if (!tag_check_result) { + secure::erase_secret(data_bytes); + engine::abandon(state_); + return tag_check_result.error(); + } + return {}; } - return {}; } } @@ -433,25 +472,32 @@ class gcm { std::span nonce_bytes, std::span associated_data_bytes) noexcept { secure::timing_guard const timing_scope; - if (!keyed_) { - return error::invalid_state; - } - if (phase_ != phase::none) { - abandon(); - return error::invalid_state; - } - auto const guard_result = guard_message(nonce_bytes, associated_data_bytes, 0, tag_size); - if (!guard_result) { - return guard_result.error(); - } - auto const start_result = engine::start(state_, true, nonce_bytes, associated_data_bytes); - if (!start_result) { - engine::abandon(state_); - return start_result.error(); + if constexpr (!detail::gcm_capability_checked()) { + // Never compiled into a program: the capability's assertion stopped the build. + return error::backend_failure; + } else { + if (!keyed_) { + return error::invalid_state; + } + if (phase_ != phase::none) { + abandon(); + return error::invalid_state; + } + auto const guard_result = + guard_message(nonce_bytes, associated_data_bytes, 0, tag_size); + if (!guard_result) { + return guard_result.error(); + } + auto const start_result = + engine::start(state_, true, nonce_bytes, associated_data_bytes); + if (!start_result) { + engine::abandon(state_); + return start_result.error(); + } + phase_ = phase::sealing; + message_bytes_ = 0; + return {}; } - phase_ = phase::sealing; - message_bytes_ = 0; - return {}; } /** @@ -467,22 +513,27 @@ class gcm { */ [[nodiscard]] boost::system::result update(std::span data_bytes) noexcept { secure::timing_guard const timing_scope; - auto const phase_result = require_phase(phase::sealing); - if (!phase_result) { - return phase_result.error(); - } - if (detail::exceeds(data_bytes.size(), max_message_size - message_bytes_)) { - abandon(); - return error::message_too_long; - } - auto const run_result = engine::run(state_, data_bytes); - if (!run_result) { - secure::erase_secret(data_bytes); - abandon(); - return run_result.error(); + if constexpr (!detail::gcm_capability_checked()) { + // Never compiled into a program: the capability's assertion stopped the build. + return error::backend_failure; + } else { + auto const phase_result = require_phase(phase::sealing); + if (!phase_result) { + return phase_result.error(); + } + if (detail::exceeds(data_bytes.size(), max_message_size - message_bytes_)) { + abandon(); + return error::message_too_long; + } + auto const run_result = engine::run(state_, data_bytes); + if (!run_result) { + secure::erase_secret(data_bytes); + abandon(); + return run_result.error(); + } + message_bytes_ += data_bytes.size(); + return {}; } - message_bytes_ += data_bytes.size(); - return {}; } /** @@ -493,18 +544,23 @@ class gcm { */ [[nodiscard]] boost::system::result result() noexcept { secure::timing_guard const timing_scope; - auto const phase_result = require_phase(phase::sealing); - if (!phase_result) { - return phase_result.error(); - } - result_type tag_bytes{}; - auto const tag_result = engine::tag(state_, tag_bytes); - end_message(); - if (!tag_result) { - engine::abandon(state_); - return tag_result.error(); + if constexpr (!detail::gcm_capability_checked()) { + // Never compiled into a program: the capability's assertion stopped the build. + return error::backend_failure; + } else { + auto const phase_result = require_phase(phase::sealing); + if (!phase_result) { + return phase_result.error(); + } + result_type tag_bytes{}; + auto const tag_result = engine::tag(state_, tag_bytes); + end_message(); + if (!tag_result) { + engine::abandon(state_); + return tag_result.error(); + } + return tag_bytes; } - return tag_bytes; } /** @@ -524,29 +580,36 @@ class gcm { std::span nonce_bytes, std::span associated_data_bytes) noexcept { secure::timing_guard const timing_scope; - if (!keyed_) { - return error::invalid_state; - } - if (phase_ != phase::none) { - abandon(); - return error::invalid_state; - } - auto const guard_result = guard_message(nonce_bytes, associated_data_bytes, 0, tag_size); - if (!guard_result) { - return guard_result.error(); - } - std::ranges::copy(nonce_bytes, nonce_.begin()); - nonce_size_ = nonce_bytes.size(); - auto const start_result = engine::start(state_, false, nonce_bytes, associated_data_bytes); - if (!start_result) { - engine::abandon(state_); - end_message(); - return start_result.error(); + if constexpr (!detail::gcm_capability_checked()) { + // Never compiled into a program: the capability's assertion stopped the build. + return error::backend_failure; + } else { + if (!keyed_) { + return error::invalid_state; + } + if (phase_ != phase::none) { + abandon(); + return error::invalid_state; + } + auto const guard_result = + guard_message(nonce_bytes, associated_data_bytes, 0, tag_size); + if (!guard_result) { + return guard_result.error(); + } + std::ranges::copy(nonce_bytes, nonce_.begin()); + nonce_size_ = nonce_bytes.size(); + auto const start_result = + engine::start(state_, false, nonce_bytes, associated_data_bytes); + if (!start_result) { + engine::abandon(state_); + end_message(); + return start_result.error(); + } + phase_ = phase::authenticating; + message_bytes_ = 0; + decrypted_bytes_ = 0; + return {}; } - phase_ = phase::authenticating; - message_bytes_ = 0; - decrypted_bytes_ = 0; - return {}; } /** @@ -564,29 +627,36 @@ class gcm { [[nodiscard]] boost::system::result authenticate( std::span ciphertext_piece) noexcept { secure::timing_guard const timing_scope; - auto const phase_result = require_phase(phase::authenticating); - if (!phase_result) { - return phase_result.error(); - } - if (detail::exceeds(ciphertext_piece.size(), max_message_size - message_bytes_)) { - abandon(); - return error::message_too_long; - } - std::array scratch_bytes{}; - for (std::size_t piece_start = 0; piece_start < ciphertext_piece.size(); - piece_start += scratch_size) { - std::size_t const block_size = - (std::min)(scratch_size, ciphertext_piece.size() - piece_start); - std::copy_n(ciphertext_piece.data() + piece_start, block_size, scratch_bytes.data()); - auto const run_result = engine::run(state_, std::span(scratch_bytes).first(block_size)); - secure::erase_secret(std::span(scratch_bytes).first(block_size)); - if (!run_result) { + if constexpr (!detail::gcm_capability_checked()) { + // Never compiled into a program: the capability's assertion stopped the build. + return error::backend_failure; + } else { + auto const phase_result = require_phase(phase::authenticating); + if (!phase_result) { + return phase_result.error(); + } + if (detail::exceeds(ciphertext_piece.size(), max_message_size - message_bytes_)) { abandon(); - return run_result.error(); + return error::message_too_long; } + std::array scratch_bytes{}; + for (std::size_t piece_start = 0; piece_start < ciphertext_piece.size(); + piece_start += scratch_size) { + std::size_t const block_size = + (std::min)(scratch_size, ciphertext_piece.size() - piece_start); + std::copy_n(ciphertext_piece.data() + piece_start, block_size, + scratch_bytes.data()); + auto const run_result = + engine::run(state_, std::span(scratch_bytes).first(block_size)); + secure::erase_secret(std::span(scratch_bytes).first(block_size)); + if (!run_result) { + abandon(); + return run_result.error(); + } + } + message_bytes_ += ciphertext_piece.size(); + return {}; } - message_bytes_ += ciphertext_piece.size(); - return {}; } /** @@ -601,33 +671,38 @@ class gcm { [[nodiscard]] boost::system::result verify( std::span tag_bytes) noexcept { secure::timing_guard const timing_scope; - auto const phase_result = require_phase(phase::authenticating); - if (!phase_result) { - return phase_result.error(); - } - if (tag_bytes.size() != tag_size) { - abandon(); - return error::invalid_tag_size; - } - std::array expected_tag{}; - std::ranges::copy(tag_bytes, expected_tag.begin()); - auto const check_result = engine::check(state_, expected_tag); - if (!check_result) { - abandon(); - return check_result.error(); - } - // GCM's keystream depends on the key and the nonce alone: the second pass needs no - // associated data, and the tag the engine computes in it is never read. - engine::abandon(state_); - auto const start_result = - engine::start(state_, false, std::span(nonce_).first(nonce_size_), {}); - if (!start_result) { - abandon(); - return start_result.error(); + if constexpr (!detail::gcm_capability_checked()) { + // Never compiled into a program: the capability's assertion stopped the build. + return error::backend_failure; + } else { + auto const phase_result = require_phase(phase::authenticating); + if (!phase_result) { + return phase_result.error(); + } + if (tag_bytes.size() != tag_size) { + abandon(); + return error::invalid_tag_size; + } + std::array expected_tag{}; + std::ranges::copy(tag_bytes, expected_tag.begin()); + auto const check_result = engine::check(state_, expected_tag); + if (!check_result) { + abandon(); + return check_result.error(); + } + // GCM's keystream depends on the key and the nonce alone: the second pass needs no + // associated data, and the tag the engine computes in it is never read. + engine::abandon(state_); + auto const start_result = + engine::start(state_, false, std::span(nonce_).first(nonce_size_), {}); + if (!start_result) { + abandon(); + return start_result.error(); + } + phase_ = phase::decrypting; + decrypted_bytes_ = 0; + return {}; } - phase_ = phase::decrypting; - decrypted_bytes_ = 0; - return {}; } /** @@ -644,22 +719,27 @@ class gcm { */ [[nodiscard]] boost::system::result decrypt(std::span data_piece) noexcept { secure::timing_guard const timing_scope; - auto const phase_result = require_phase(phase::decrypting); - if (!phase_result) { - return phase_result.error(); - } - if (data_piece.size() > message_bytes_ - decrypted_bytes_) { - abandon(); - return error::invalid_input_size; - } - auto const run_result = engine::run(state_, data_piece); - if (!run_result) { - secure::erase_secret(data_piece); - abandon(); - return run_result.error(); + if constexpr (!detail::gcm_capability_checked()) { + // Never compiled into a program: the capability's assertion stopped the build. + return error::backend_failure; + } else { + auto const phase_result = require_phase(phase::decrypting); + if (!phase_result) { + return phase_result.error(); + } + if (data_piece.size() > message_bytes_ - decrypted_bytes_) { + abandon(); + return error::invalid_input_size; + } + auto const run_result = engine::run(state_, data_piece); + if (!run_result) { + secure::erase_secret(data_piece); + abandon(); + return run_result.error(); + } + decrypted_bytes_ += data_piece.size(); + return {}; } - decrypted_bytes_ += data_piece.size(); - return {}; } /** diff --git a/include/webcpp/crypto/ciphers/stream_cipher.hpp b/include/webcpp/crypto/ciphers/stream_cipher.hpp index 1db4e24..44a8c14 100644 --- a/include/webcpp/crypto/ciphers/stream_cipher.hpp +++ b/include/webcpp/crypto/ciphers/stream_cipher.hpp @@ -24,8 +24,10 @@ #include #include +#include #include #include +#include #include #include // crypto::from_key, which serves its from_key #include // its free form (design D3) @@ -41,24 +43,6 @@ #include #include -namespace webcpp::crypto::families { - -/** RFC 8439's ChaCha20: a 32-byte key, a 12-byte nonce, a 32-bit block counter. */ -struct chacha20 { - /** The key's size. */ - static constexpr std::size_t key_size = 32; - /** The nonce's size, exactly (RFC 8439 section 2.3). */ - static constexpr std::size_t nonce_size = 12; - /** The block's size: the keystream is made one 64-byte block per counter value. */ - static constexpr std::size_t block_size = 64; - /** The block counter, RFC 8439's 32 bits. */ - using counter_type = std::uint32_t; - /** The longest data from counter 0, 2^38 bytes: 2^32 blocks of 64 bytes. */ - static constexpr std::uint64_t max_message_size = std::uint64_t{1} << 38U; -}; - -} // namespace webcpp::crypto::families - namespace webcpp::crypto::detail { /** @@ -148,6 +132,29 @@ struct stream_engine : stream_refusal { static void reset(Arguments&&... /*arguments*/) noexcept {} }; +/** + * Whether the engine of a stream cipher family on a backend has its capability (design D9): true + * for the family's primary engine, whose generated refusal speaks, and for a test's unmarked + * stand-in, taken at its word; for an engine a backend's header specialises + * (`specialized_engine_v`), the capability, asserted by a message that names it. Each public member + * that calls the engine asks it first. + * + * @tparam Family The stream cipher's family. + * @tparam Engine Its engine on the backend. + * @return Whether the member may call the engine. + */ +template +constexpr bool stream_capability_checked() noexcept { + if constexpr (!specialized_engine_v) { + return true; + } else { + static_assert(backend::stream_cipher, + "webcpp::crypto: this backend has ChaCha20 but not " + "crypto::capabilities::chacha20: the stream cipher is not available on it."); + return backend::stream_cipher; + } +} + } // namespace webcpp::crypto::detail namespace webcpp::crypto::ciphers { @@ -202,21 +209,26 @@ class basic_chacha20 { [[nodiscard]] static boost::system::result from_key( std::span key_bytes) noexcept { secure::timing_guard const timing_scope; - if constexpr (detail::asynchronous_backend_v) { - // WebCrypto has no ChaCha20: the refusal names a native backend (design D6). - detail::refuse_stream_cipher_on_asynchronous_backend(); + if constexpr (!detail::stream_capability_checked()) { + // Never compiled into a program: the capability's assertion stopped the build. return error::backend_failure; } else { - if (key_bytes.size() != key_size) { - return error::invalid_key_size; - } - basic_chacha20 made_object; - auto const key_result = engine::init(made_object.state_, key_bytes); - if (!key_result) { - return key_result.error(); + if constexpr (detail::asynchronous_backend_v) { + // WebCrypto has no ChaCha20: the refusal names a native backend (design D6). + detail::refuse_stream_cipher_on_asynchronous_backend(); + return error::backend_failure; + } else { + if (key_bytes.size() != key_size) { + return error::invalid_key_size; + } + basic_chacha20 made_object; + auto const key_result = engine::init(made_object.state_, key_bytes); + if (!key_result) { + return key_result.error(); + } + made_object.keyed_ = true; + return made_object; } - made_object.keyed_ = true; - return made_object; } } @@ -313,34 +325,39 @@ class basic_chacha20 { std::span nonce_bytes, std::span data_bytes, counter_type initial_counter) noexcept { secure::timing_guard const timing_scope; - if constexpr (detail::asynchronous_backend_v) { - // WebCrypto has no ChaCha20: the refusal names a native backend (design D6). - detail::refuse_stream_cipher_on_asynchronous_backend(); + if constexpr (!detail::stream_capability_checked()) { + // Never compiled into a program: the capability's assertion stopped the build. return error::backend_failure; } else { - if (!keyed_) { - return error::invalid_state; - } - if (nonce_bytes.size() != nonce_size) { - return error::invalid_nonce_size; - } - if (detail::counter_overflows(data_bytes.size(), initial_counter)) { - return error::counter_overflow; - } - if (data_bytes.empty()) { + if constexpr (detail::asynchronous_backend_v) { + // WebCrypto has no ChaCha20: the refusal names a native backend (design D6). + detail::refuse_stream_cipher_on_asynchronous_backend(); + return error::backend_failure; + } else { + if (!keyed_) { + return error::invalid_state; + } + if (nonce_bytes.size() != nonce_size) { + return error::invalid_nonce_size; + } + if (detail::counter_overflows(data_bytes.size(), initial_counter)) { + return error::counter_overflow; + } + if (data_bytes.empty()) { + return {}; + } + // The nonce may lie in the data, which the backend overwrites: a copy is used. + std::array nonce_copy{}; + std::ranges::copy(nonce_bytes, nonce_copy.begin()); + auto const applied = + engine::apply(state_, std::span(nonce_copy), + initial_counter, data_bytes); + if (!applied) { + secure::erase_secret(data_bytes); + return applied.error(); + } return {}; } - // The nonce may lie in the data, which the backend overwrites: a copy is used. - std::array nonce_copy{}; - std::ranges::copy(nonce_bytes, nonce_copy.begin()); - auto const applied = - engine::apply(state_, std::span(nonce_copy), - initial_counter, data_bytes); - if (!applied) { - secure::erase_secret(data_bytes); - return applied.error(); - } - return {}; } } diff --git a/include/webcpp/crypto/curves/ed25519.hpp b/include/webcpp/crypto/curves/ed25519.hpp index cb5e923..93f2030 100644 --- a/include/webcpp/crypto/curves/ed25519.hpp +++ b/include/webcpp/crypto/curves/ed25519.hpp @@ -32,11 +32,13 @@ #include // to_x25519()'s keys #include +#include #include #include #include #include #include +#include #include #include #include @@ -117,6 +119,50 @@ using signature = detail::basic_signature; namespace webcpp::crypto::detail { +/** + * Whether the Ed25519 engine `Engine` verifies (design D9): true for the family's primary engine, + * whose generated refusal speaks, and for a test's unmarked stand-in, taken at its word; for an + * engine a backend's header specialises (`specialized_engine_v`), `backend::ed25519_verifying`, + * asserted by a message that names it. A function template per engine, so that a refusal is said + * once however many verifications ask it. + * + * @tparam Engine The Ed25519 engine of the key's backend. + * @return Whether the key may call the engine. + */ +template +constexpr bool ed25519_verifying_checked() noexcept { + if constexpr (!specialized_engine_v) { + return true; + } else { + static_assert(backend::ed25519_verifying, + "webcpp::crypto: this backend has Ed25519 but not " + "crypto::capabilities::ed25519_verifying: verify of " + "crypto::signing_schemes::eddsa is not available on it."); + return backend::ed25519_verifying; + } +} + +/** + * Whether the Ed25519ph engine `Engine` verifies a digest beside the key engine `KeyEngine`, as + * `ed25519_verifying_checked` asks Ed25519: `backend::ed25519ph`. + * + * @tparam Engine The Ed25519ph engine of the key's backend. + * @tparam KeyEngine The Ed25519 engine of the key's backend. + * @return Whether the key may call the engine. + */ +template +constexpr bool ed25519ph_verifying_checked() noexcept { + if constexpr (!specialized_engine_v) { + return true; + } else { + static_assert( + backend::ed25519ph, + "webcpp::crypto: this backend has Ed25519 but not crypto::capabilities::ed25519ph: " + "verify of crypto::signing_schemes::eddsa_prehashed is not available on it."); + return backend::ed25519ph; + } +} + /** * Verifies an Ed25519 signature on `Backend` under `Policy`: the work of `public_key::verify` * and of `crypto::verify` of `eddsa`, which hold the guard. @@ -137,11 +183,12 @@ template std::is_same_v, "webcpp::crypto: Ed25519 verifies under crypto::verification_policies::canonical."); check_input(); - if constexpr (input_valid_v) { - return ed25519_engine::verify( - key_bytes, message_bytes(message_input), signature_bytes); + using engine = ed25519_engine; + if constexpr (input_valid_v && + ed25519_verifying_checked()) { + return engine::verify(key_bytes, message_bytes(message_input), signature_bytes); } else { - // Never compiled into a program: check_input stopped the build. + // Never compiled into a program: check_input or the helper's assertion stopped the build. return error::invalid_signature; } } @@ -166,11 +213,13 @@ template 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( - key_bytes, digest_input.digest, signature_bytes); + using engine = ed25519ph_engine; + if constexpr (input_valid_v && + ed25519ph_verifying_checked>()) { + return engine::verify_digest(key_bytes, digest_input.digest, signature_bytes); } else { - // Never compiled into a program: check_input stopped the build. + // Never compiled into a program: check_input or the helper's assertion stopped the build. return error::invalid_signature; } } @@ -432,14 +481,25 @@ class public_key { template > [[nodiscard]] boost::system::result to_x25519() const noexcept { secure::timing_guard const timing_scope; - std::array converted_bytes{}; - auto const engine_done = - detail::ed25519_engine::to_x25519_public(bytes_, - converted_bytes); - if (!engine_done) { - return engine_done.error(); + using engine = detail::ed25519_engine; + if constexpr (detail::specialized_engine_v) { + static_assert(detail::backend::ed25519_to_x25519, + "webcpp::crypto: this backend has Ed25519 but not " + "crypto::capabilities::ed25519_to_x25519: a public key's to_x25519() is " + "not available on it."); + } + if constexpr (!detail::capability_usable_v>) { + // Never compiled into a program: the assertion above stopped the build. + return error::backend_failure; + } else { + std::array converted_bytes{}; + auto const engine_done = engine::to_x25519_public(bytes_, converted_bytes); + if (!engine_done) { + return engine_done.error(); + } + return x25519::public_key::from_bytes(converted_bytes); } - return x25519::public_key::from_bytes(converted_bytes); } /** @@ -539,22 +599,43 @@ class basic_keypair { // Never compiled into a program: the assertion above stopped the build. return error::backend_failure; } else { - if (seed_bytes.size() != seed_size) { - return error::invalid_key_size; + // The trait first, then the capability (design D3's amendment, D9). + static_assert(detail::secret_keys_enter_v, + "webcpp::crypto: this backend keeps its keys: no secret key enters it " + "(crypto::imports_secret_keys_v is false), so Ed25519's from_secret, " + "which needs crypto::capabilities::ed25519_import, is not available on " + "it; make a key with generate."); + if constexpr (detail::specialized_engine_v && + detail::secret_keys_enter_v) { + static_assert(detail::backend::ed25519_import, + "webcpp::crypto: this backend has Ed25519 but not " + "crypto::capabilities::ed25519_import: from_secret is not available " + "on it; make a key with generate."); } - basic_keypair made_pair; - auto const engine_keyed = - engine::seed_keypair(made_pair.state_, seed_bytes.template first()); - if (!engine_keyed) { - return engine_keyed.error(); + if constexpr (!detail::secret_keys_enter_v || + !detail::capability_usable_v>) { + // Never compiled into a program: an assertion above stopped the build. + return error::backend_failure; + } else { + if (seed_bytes.size() != seed_size) { + return error::invalid_key_size; + } + basic_keypair made_pair; + auto const engine_keyed = + engine::import_secret(made_pair.state_, seed_bytes.template first()); + if (!engine_keyed) { + return engine_keyed.error(); + } + made_pair.keyed_ = true; + return made_pair; } - made_pair.keyed_ = true; - return made_pair; } } /** - * Makes a key pair from a fresh seed, drawn from the system's generator. + * Makes a key pair from a fresh seed: the backend's own, on a backend that draws its keys + * (design R3), else drawn from the system's generator and imported. * * @return The key pair; `entropy_unavailable` when the system's generator fails or there is * none; `backend_failure`. @@ -568,15 +649,7 @@ class basic_keypair { // Never compiled into a program: the assertion above stopped the build. return error::backend_failure; } else { - secure::secret seed_secret; - auto const entropy_drawn = - random_device().fill(seed_secret.writable()); // lint-world: the seed - if (!entropy_drawn) { - // The generator's not_supported (an Emscripten audio worklet) is the same failure - // for a key pair: one error to handle. - return error::entropy_unavailable; - } - return from_secret(seed_secret.bytes()); + return generated(); } } @@ -632,8 +705,7 @@ class basic_keypair { */ basic_keypair(basic_keypair&& moved_from) noexcept : keyed_(std::exchange(moved_from.keyed_, false)) { - state_ = moved_from.state_; - engine::reset(moved_from.state_); + engine::move(state_, moved_from.state_); } /** @@ -646,8 +718,7 @@ class basic_keypair { if (this != &moved_from) { engine::reset(state_); keyed_ = std::exchange(moved_from.keyed_, false); - state_ = moved_from.state_; - engine::reset(moved_from.state_); + engine::move(state_, moved_from.state_); } return *this; } @@ -663,32 +734,68 @@ class basic_keypair { /** * The public key, which `crypto::verify` takes. * - * @return The public key; `invalid_state` moved from. + * @return The public key; `invalid_state` moved from; `backend_failure`. */ [[nodiscard]] boost::system::result public_key() const noexcept { secure::timing_guard const timing_scope; - if (!keyed_) { - return error::invalid_state; + if constexpr (detail::specialized_engine_v) { + static_assert(detail::backend::ed25519_public, + "webcpp::crypto: this backend has Ed25519 but not " + "crypto::capabilities::ed25519_public: a key pair's public_key() is not " + "available on it."); + } + if constexpr (!detail::capability_usable_v>) { + // Never compiled into a program: the assertion above stopped the build. + return error::backend_failure; + } else { + if (!keyed_) { + return error::invalid_state; + } + std::array key_bytes{}; + auto const engine_done = engine::public_key(state_, key_bytes); + if (!engine_done) { + return engine_done.error(); + } + return public_key_type::from_bytes(key_bytes); } - std::array key_bytes{}; - engine::public_key(state_, key_bytes); - return public_key_type::from_bytes(key_bytes); } /** * The seed, RFC 8032's secret key, for a program that keeps the key pair and makes it again * with `from_secret`, or exports it (PKCS#8 holds the seed alone). * - * @return 32 secret bytes; `invalid_state` moved from. + * @return 32 secret bytes; `invalid_state` moved from; `backend_failure`. */ [[nodiscard]] boost::system::result> secret() const noexcept { secure::timing_guard const timing_scope; - if (!keyed_) { - return error::invalid_state; + // The trait first, then the capability (design D3's amendment, D9). + static_assert(detail::secret_keys_leave_v, + "webcpp::crypto: this backend keeps its keys: no secret key leaves it " + "(crypto::exports_secret_keys_v is false), so Ed25519's secret(), which " + "needs crypto::capabilities::ed25519_export, is not available on it."); + if constexpr (detail::specialized_engine_v && + detail::secret_keys_leave_v) { + static_assert(detail::backend::ed25519_export, + "webcpp::crypto: this backend has Ed25519 but not " + "crypto::capabilities::ed25519_export: secret() is not available on it."); + } + if constexpr (!detail::secret_keys_leave_v || + !detail::capability_usable_v>) { + // Never compiled into a program: an assertion above stopped the build. + return error::backend_failure; + } else { + if (!keyed_) { + return error::invalid_state; + } + secure::secret seed_secret; + auto const engine_done = engine::export_secret(state_, seed_secret.writable()); + if (!engine_done) { + return engine_done.error(); + } + return seed_secret; } - secure::secret seed_secret; - engine::seed(state_, seed_secret.writable()); - return seed_secret; } /** @@ -798,8 +905,25 @@ class basic_keypair { using converted_type = x25519::basic_keypair; static_assert(supports_v, "webcpp::crypto: to_x25519: this backend has no X25519; libsodium has both."); - if constexpr (!supports_v) { - // Never compiled into a program: the assertion above stopped the build. + // The trait first, then the capability (design D3's amendment, D9): the X25519 secret + // leaves the backend. + static_assert( + !supports_v || detail::secret_keys_leave_v, + "webcpp::crypto: this backend keeps its keys: no secret key leaves it " + "(crypto::exports_secret_keys_v is false), so an Ed25519 key pair's to_x25519(), which " + "needs crypto::capabilities::ed25519_to_x25519, is not available on it."); + if constexpr (detail::specialized_engine_v && supports_v && + detail::secret_keys_leave_v) { + static_assert(detail::backend::ed25519_to_x25519, + "webcpp::crypto: this backend has Ed25519 but not " + "crypto::capabilities::ed25519_to_x25519: a key pair's to_x25519() is " + "not available on it."); + } + if constexpr (!supports_v || + !detail::secret_keys_leave_v || + !detail::capability_usable_v>) { + // Never compiled into a program: an assertion above stopped the build. return error::backend_failure; } else { if (!keyed_) { @@ -852,31 +976,96 @@ class basic_keypair { // The work of sign, which holds the guard: the signature of the message's bytes. [[nodiscard]] boost::system::result signed_message( std::span message_bytes) const noexcept { - if (!keyed_) { - return error::invalid_state; + if constexpr (detail::specialized_engine_v) { + static_assert(detail::backend::ed25519_signing, + "webcpp::crypto: this backend has Ed25519 but not " + "crypto::capabilities::ed25519_signing: sign of " + "crypto::signing_schemes::eddsa is not available on it."); } - std::array signature_bytes{}; - auto const signed_bytes = engine::sign(state_, message_bytes, signature_bytes); - if (!signed_bytes) { - return signed_bytes.error(); + if constexpr (!detail::capability_usable_v>) { + // Never compiled into a program: the assertion above stopped the build. + return error::backend_failure; + } else { + if (!keyed_) { + return error::invalid_state; + } + std::array signature_bytes{}; + auto const signed_bytes = engine::sign(state_, message_bytes, signature_bytes); + if (!signed_bytes) { + return signed_bytes.error(); + } + return detail::signature_access::of(signature_bytes); } - return detail::signature_access::of(signature_bytes); } // The work of sign under eddsa_prehashed, which holds the guard: Ed25519ph's signature of the // digest. [[nodiscard]] boost::system::result signed_digest( std::span digest_bytes) const noexcept { - if (!keyed_) { - return error::invalid_state; + using prehashed_engine = detail::ed25519ph_engine; + if constexpr (detail::specialized_engine_v) { + static_assert( + detail::backend::ed25519ph, + "webcpp::crypto: this backend has Ed25519 but not crypto::capabilities::ed25519ph: " + "sign of crypto::signing_schemes::eddsa_prehashed is not available on it."); } - std::array signature_bytes{}; - auto const signed_bytes = detail::ed25519ph_engine::sign_digest( - state_, digest_bytes, signature_bytes); - if (!signed_bytes) { - return signed_bytes.error(); + if constexpr (!detail::capability_usable_v< + prehashed_engine, detail::backend::ed25519ph>) { + // Never compiled into a program: the assertion above stopped the build. + return error::backend_failure; + } else { + if (!keyed_) { + return error::invalid_state; + } + std::array signature_bytes{}; + auto const signed_bytes = + prehashed_engine::sign_digest(state_, digest_bytes, signature_bytes); + if (!signed_bytes) { + return signed_bytes.error(); + } + return detail::signature_access::of(signature_bytes); + } + } + + // The work of generate, which holds the guard, and of a backend's asynchronous generation + // (detail::async_access): the backend's own key when its engine draws one (design R3), else a + // seed from the system's generator, imported. + [[nodiscard]] static boost::system::result generated() noexcept { + if constexpr (detail::backend::ed25519_generate) { + basic_keypair made_pair; + auto const engine_drawn = engine::generate(made_pair.state_); + if (!engine_drawn) { + return engine_drawn.error(); + } + made_pair.keyed_ = true; + return made_pair; + } else { + // A backend that neither draws its keys nor imports them has no way to make one. + static_assert( + detail::secret_keys_enter_v && + (!detail::specialized_engine_v || + detail::backend::ed25519_import), + "webcpp::crypto: this backend has Ed25519 but neither " + "crypto::capabilities::ed25519_generate nor crypto::capabilities::ed25519_import: " + "generate has no way to make a key on it."); + secure::secret seed_secret; + auto const entropy_drawn = + random_device().fill(seed_secret.writable()); // lint-world: the seed + if (!entropy_drawn) { + // The generator's not_supported (an Emscripten audio worklet) is the same failure + // for a key pair: one error to handle. + return error::entropy_unavailable; + } + if constexpr (!detail::secret_keys_enter_v || + !detail::capability_usable_v>) { + // Never compiled into a program: the assertion above stopped the build. + return error::backend_failure; + } else { + return from_secret(seed_secret.bytes()); + } } - return detail::signature_access::of(signature_bytes); } state_type state_{}; @@ -929,13 +1118,28 @@ class prehashed_signer { */ [[nodiscard]] static boost::system::result begin() noexcept { secure::timing_guard const timing_scope; - prehashed_signer begun_hash; - auto const begin_result = engine::begin(begun_hash.state_); - if (!begin_result) { - return begin_result.error(); + if constexpr (detail::specialized_engine_v) { + static_assert( + detail::backend::ed25519ph>, + "webcpp::crypto: this backend has Ed25519 but not crypto::capabilities::ed25519ph: " + "prehashed_signer is not available on it."); + } + if constexpr (!detail::capability_usable_v< + engine, + detail::backend::ed25519ph< + engine, detail::ed25519_engine>>) { + // Never compiled into a program: the assertion above stopped the build. + return error::backend_failure; + } else { + prehashed_signer begun_hash; + auto const begin_result = engine::begin(begun_hash.state_); + if (!begin_result) { + return begin_result.error(); + } + begun_hash.begun_ = true; + return begun_hash; } - begun_hash.begun_ = true; - return begun_hash; } /** @@ -1357,18 +1561,24 @@ struct ed25519_engine { /** Never called; fails closed. */ template - [[nodiscard]] static boost::system::result seed_keypair( + [[nodiscard]] static boost::system::result import_secret( Arguments&&... /*arguments*/) noexcept { return error::backend_failure; } - /** Never called. */ + /** Never called; fails closed. */ template - static void public_key(Arguments&&... /*arguments*/) noexcept {} + [[nodiscard]] static boost::system::result public_key( + Arguments&&... /*arguments*/) noexcept { + return error::backend_failure; + } - /** Never called. */ + /** Never called; fails closed. */ template - static void seed(Arguments&&... /*arguments*/) noexcept {} + [[nodiscard]] static boost::system::result export_secret( + Arguments&&... /*arguments*/) noexcept { + return error::backend_failure; + } /** Never called; fails closed. */ template @@ -1396,6 +1606,10 @@ struct ed25519_engine { return error::backend_failure; } + /** Never called. */ + template + static void move(Arguments&&... /*arguments*/) noexcept {} + /** Never called. */ template static void reset(Arguments&&... /*arguments*/) noexcept {} diff --git a/include/webcpp/crypto/curves/ed25519/formats.hpp b/include/webcpp/crypto/curves/ed25519/formats.hpp index 5a9d1ba..80066b0 100644 --- a/include/webcpp/crypto/curves/ed25519/formats.hpp +++ b/include/webcpp/crypto/curves/ed25519/formats.hpp @@ -21,7 +21,8 @@ The key pair's private formats exist on a backend whose secret is in the program; on a backend whose key pairs live in WebCrypto (`detail::asynchronous_backend_v`), codecs' verbs refuse them, naming WebCrypto's `exportKey` (design D7). A public key, which names no backend, is - encoded and decoded on the family's default, libsodium on every target. + encoded and decoded with none: RFC 8410's layouts are constants around the key + (`detail/rfc8410.hpp`), and a key pair's need of its backend only its key capabilities. @see "Key formats: raw, SPKI, PKCS#8, DER and PEM", in the guide. */ @@ -34,7 +35,8 @@ #include #include #include -#include +#include +#include #include #include #include @@ -69,16 +71,6 @@ inline constexpr std::array ed25519_pkcs8_prefix{ 0x04, 0x22, 0x04, 0x20, // OCTET STRING, 34 bytes: an OCTET STRING, 32 }; -/** - * Ed25519's key formats on a backend; the primary refuses (defined at the end of this header). A - * backend's specialisation provides `encode_spki(public_key, out)`, - * `decode_spki(spki, public_key)`, `encode_pkcs8(state, out)` and `decode_pkcs8(pkcs8, seed)`, - * over spans of the formats' fixed sizes, the decoders returning `invalid_encoding` for any - * other bytes than the one encoding. - */ -template -struct ed25519_formats_engine; - /** Reads a key pair's state for its PKCS#8, as `basic_keypair` lets it. */ template struct ed25519_keypair_access { @@ -98,7 +90,7 @@ struct ed25519_keypair_access { * * @param key_pair The key pair. * @param output_bytes 48 bytes. - * @return Nothing; `invalid_state` moved from, with nothing written. + * @return Nothing; `invalid_state` moved from, `backend_failure`, with nothing written. */ [[nodiscard]] static boost::system::result encode_pkcs8( curves::ed25519::basic_keypair const& key_pair, @@ -106,8 +98,13 @@ struct ed25519_keypair_access { if (!key_pair.keyed_) { return error::invalid_state; } - ed25519_formats_engine::encode_pkcs8(key_pair.state_, - output_bytes); + secure::secret seed_secret; + auto const exported = ed25519_engine::export_secret( + key_pair.state_, seed_secret.writable()); + if (!exported) { + return exported.error(); + } + rfc8410::encode(ed25519_pkcs8_prefix, seed_secret.bytes(), output_bytes); return {}; } }; @@ -121,14 +118,40 @@ inline constexpr std::size_t ed25519_pkcs8_size = ed25519_pkcs8_prefix.size() + /** The size of an Ed25519 key pair's seed, its secret key, which `raw` writes. */ inline constexpr std::size_t ed25519_seed_size = 32; +/** + * Whether a key pair of `Backend` lets its secret key leave and enter its backend, as its private + * formats do: the backend's secret-key traits, for an engine its header specialises (design D3's + * amendment). + * + * @tparam Backend The key pair's backend. + */ +template +inline constexpr bool ed25519_secret_passes_v = + secret_keys_leave_v, Backend> && + secret_keys_enter_v, Backend>; + /** * Whether a key pair of `Backend` has Ed25519's private formats: its secret is in the program, on - * every backend but one whose key pairs live in WebCrypto (design D7). + * every backend but one that keeps its keys (design D3's amendment) or whose key pairs live in + * WebCrypto (design D7). * * @tparam Backend The key pair's backend. */ template -inline constexpr bool ed25519_private_formats_v = !asynchronous_backend_v; +inline constexpr bool ed25519_private_formats_v = + ed25519_secret_passes_v && !asynchronous_backend_v; + +/** + * Why a key pair of `Backend` has no private format: its backend keeps its keys, which is said + * first, for `raw` apart from `pkcs8` and `pem(pkcs8)`, or its secret lives in WebCrypto. + * + * @tparam Backend The key pair's backend, one without Ed25519's private formats. + * @tparam Raw Whether the format is `raw`. + */ +template +inline constexpr refusal_reason ed25519_private_refusal_v = + ed25519_secret_passes_v ? refusal_reason::private_on_asynchronous + : private_kept_reason_v; /** An Ed25519 public key has `raw`, `spki` and `pem(spki)`. */ template <> @@ -163,37 +186,40 @@ inline constexpr refusal_reason refusal_reason_v requires(!ed25519_private_formats_v) inline constexpr refusal_reason refusal_reason_v, curves::ed25519::basic_keypair> = - refusal_reason::private_on_asynchronous; + ed25519_private_refusal_v; /** - * A key pair whose secret lives in WebCrypto has no `pkcs8` (design D7). + * A key pair whose backend keeps its keys, or whose secret lives in WebCrypto, has no `pkcs8` + * (design D3's amendment, D7). * - * @tparam Backend The key pair's backend, one whose key pairs live in WebCrypto. + * @tparam Backend The key pair's backend, one without private formats. */ template requires(!ed25519_private_formats_v) inline constexpr refusal_reason refusal_reason_v> = - refusal_reason::private_on_asynchronous; + ed25519_private_refusal_v; /** - * A key pair whose secret lives in WebCrypto has no `pem(pkcs8)` (design D7). + * A key pair whose backend keeps its keys, or whose secret lives in WebCrypto, has no `pem(pkcs8)` + * (design D3's amendment, D7). * - * @tparam Backend The key pair's backend, one whose key pairs live in WebCrypto. + * @tparam Backend The key pair's backend, one without private formats. */ template requires(!ed25519_private_formats_v) inline constexpr refusal_reason refusal_reason_v, curves::ed25519::basic_keypair> = - refusal_reason::private_on_asynchronous; + ed25519_private_refusal_v; } // namespace webcpp::crypto::detail @@ -277,36 +303,30 @@ struct value_codec, crypto::curves::ed25519::public_ke } /** - * Writes the key's SPKI. + * Writes the key's SPKI: RFC 8410's layout, constants around the key, with no backend. * - * @tparam Backend The backend whose engine writes it: the family's default, a template - * parameter so that a program that never encodes an SPKI needs no backend linked. * @param key The key. * @param output_bytes The caller's output. * @return 44; `output_too_small`, with nothing written. */ - template > [[nodiscard]] static result encode(crypto::formats::spki_t<> const& /*format*/, crypto::curves::ed25519::public_key const& key, std::span output_bytes) noexcept { if (output_bytes.size() < max_encoded_size) { return error::output_too_small; } - auto const key_bytes = key.bytes(); - crypto::detail::ed25519_formats_engine::encode_spki( - key_bytes, output_bytes.first()); + crypto::detail::rfc8410::encode(crypto::detail::ed25519_spki_prefix, key.bytes(), + output_bytes.first()); return max_encoded_size; } /** * 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. + * Ed25519's prefix, then the key, and nothing after; no backend reads it. * - * @tparam Backend The backend whose engine reads it: the family's default, as `encode`'s. * @param input_bytes The DER. * @return The public key; `invalid_encoding`. */ - template > [[nodiscard]] static result decode( crypto::formats::spki_t<> const& /*format*/, std::span input_bytes) noexcept { @@ -316,8 +336,8 @@ struct value_codec, crypto::curves::ed25519::public_ke } std::array key_bytes{}; auto const decoded_key = - crypto::detail::ed25519_formats_engine::decode_spki( - input_bytes.first(), key_bytes); + crypto::detail::rfc8410::decode(crypto::detail::ed25519_spki_prefix, + input_bytes.first(), key_bytes); if (!decoded_key) { return decoded_key.error(); } @@ -471,9 +491,9 @@ struct value_codec seed_secret; - auto const decoded_seed = - crypto::detail::ed25519_formats_engine:: - decode_pkcs8(input_bytes.first(), seed_secret.writable()); + auto const decoded_seed = crypto::detail::rfc8410::decode( + crypto::detail::ed25519_pkcs8_prefix, input_bytes.first(), + seed_secret.writable()); if (!decoded_seed) { return decoded_seed.error(); } @@ -620,52 +640,4 @@ auto basic_keypair::decode(Format const& format, Input const& input) no } // namespace webcpp::crypto::curves::ed25519 -namespace webcpp::crypto::detail { - -/** - * Ed25519's key formats on a backend whose header does not specialise them: the family's - * refusal, which names what the program needs (`detail/capabilities.hpp`). Its functions are - * never called: the refusal stops the build where the class is instantiated, and they keep the - * compiler from adding errors of their own after it; those that return report - * `backend_failure`, so that a path the refusal missed fails closed. - */ -template -struct ed25519_formats_engine { - WEBCPP_CRYPTO_DETAIL_REFUSE_ED25519(Backend); - - /** Never called. */ - template - static void encode_spki(Arguments&&... /*arguments*/) noexcept {} - - /** Never called; fails closed. */ - template - [[nodiscard]] static boost::system::result decode_spki( - Arguments&&... /*arguments*/) noexcept { - return error::backend_failure; - } - - /** Never called. */ - template - static void encode_pkcs8(Arguments&&... /*arguments*/) noexcept {} - - /** Never called; fails closed. */ - template - [[nodiscard]] static boost::system::result decode_pkcs8( - Arguments&&... /*arguments*/) noexcept { - return error::backend_failure; - } -}; - -} // namespace webcpp::crypto::detail - -/** Defined once this header's declarations are, which libsodium's engine specialises. */ -// NOLINTNEXTLINE(modernize-macro-to-enum): read by backends/sodium.hpp's #if, not a value -#define WEBCPP_CRYPTO_DETAIL_ED25519_FORMATS_DECLARED 1 - -// The default backend's engine, when the program links it (design D32): libsodium on every -// target. Its header specialises it for this header, wherever it was first included. -#if defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_ED25519_SODIUM) && defined(WEBCPP_CRYPTO_HAS_SODIUM) -#include -#endif - #endif // WEBCPP_CRYPTO_CURVES_ED25519_FORMATS_HPP diff --git a/include/webcpp/crypto/curves/p256.hpp b/include/webcpp/crypto/curves/p256.hpp index 90c1252..9e8e479 100644 --- a/include/webcpp/crypto/curves/p256.hpp +++ b/include/webcpp/crypto/curves/p256.hpp @@ -29,11 +29,13 @@ #include #include +#include #include #include #include #include #include +#include #include #include #include @@ -89,8 +91,8 @@ template 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."); + "webcpp::crypto: P-256 verifies under " + "crypto::verification_policies::low_s_only or any_s."); return true; } } @@ -139,20 +141,92 @@ struct p256_ecdsa_signature_tag { } }; +/** + * Whether the P-256 engine `Engine` signs a message, or with `Prehashed` a digest given as + * `crypto::signing_schemes::prehashed` (design D9): a digest on the digest form, + * `backend::p256_ecdsa_signing`; a message on the message form, + * `backend::p256_ecdsa_message_signing`, or else on the digest form after SHA-256, so that `sign` + * agrees with `supports_v`, which counts either form. True for the family's primary engine, whose + * generated refusal speaks, and for a test's unmarked stand-in, taken at its word; for an engine a + * backend's header specialises (`specialized_engine_v`), the form asserted by a message that names + * it. A function template per engine and kind of input, so that a refusal is said once. + * + * @tparam Engine The P-256 engine of the key pair's backend. + * @tparam Prehashed Whether the input is the marker of a digest. + * @return Whether the key pair may call the engine. + */ +template +constexpr bool p256_signing_checked() noexcept { + if constexpr (!specialized_engine_v || + (!Prehashed && backend::p256_ecdsa_message_signing)) { + return true; + } else { + if constexpr (Prehashed) { + static_assert( + backend::p256_ecdsa_signing, + "webcpp::crypto: this backend has P-256 but not " + "crypto::capabilities::p256_ecdsa_signing: sign of " + "crypto::signing_schemes::prehashed is not available on it; sign the message."); + } else { + static_assert(backend::p256_ecdsa_signing, + "webcpp::crypto: this backend has P-256 but neither " + "crypto::capabilities::p256_ecdsa_message_signing nor " + "crypto::capabilities::p256_ecdsa_signing: sign of a message is not " + "available on it."); + } + return backend::p256_ecdsa_signing; + } +} + +/** + * Whether the P-256 engine `Engine` verifies a message, or with `Prehashed` a digest given as + * `crypto::signing_schemes::prehashed`, as `p256_signing_checked` asks the signing forms: a digest + * on `backend::p256_ecdsa_verifying`; a message on `backend::p256_ecdsa_message_verifying`, or else + * on the digest form after SHA-256. + * + * @tparam Engine The P-256 engine of the key's backend. + * @tparam Prehashed Whether the input is the marker of a digest. + * @return Whether the key may call the engine. + */ +template +constexpr bool p256_verifying_checked() noexcept { + if constexpr (!specialized_engine_v || + (!Prehashed && backend::p256_ecdsa_message_verifying)) { + return true; + } else { + if constexpr (Prehashed) { + static_assert( + backend::p256_ecdsa_verifying, + "webcpp::crypto: this backend has P-256 but not " + "crypto::capabilities::p256_ecdsa_verifying: verify of " + "crypto::signing_schemes::prehashed is not available on it; verify the message."); + } else { + static_assert(backend::p256_ecdsa_verifying, + "webcpp::crypto: this backend has P-256 but neither " + "crypto::capabilities::p256_ecdsa_message_verifying nor " + "crypto::capabilities::p256_ecdsa_verifying: verify of a message is not " + "available on it."); + } + return backend::p256_ecdsa_verifying; + } +} + /** * 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. + * guard and have checked the policy. A message goes to the engine's message form when it has one, + * else it is hashed here for the digest form; a digest goes to the digest form. * * @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 signing_input The signed message, 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, a high S under `low_s_only`, - * both refused before the backend, and a signature that does not verify. + * both refused before the backend, and a signature that does not verify; the message form's other + * error when its backend fails. */ template [[nodiscard]] boost::system::result p256_verify( @@ -160,23 +234,31 @@ template Input const& signing_input, std::span point_bytes) noexcept { check_input(); - if constexpr (input_valid_v) { - using engine = p_curve_engine; + using engine = p_curve_engine; + constexpr bool prehashed = is_prehashed_v; + if constexpr (input_valid_v && + p256_verifying_checked()) { 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()); + if constexpr (!prehashed && backend::p256_ecdsa_message_verifying) { + return engine::verify_message(point_bytes, message_bytes(signing_input), + signature_bytes); } else { - digest_bytes = sha256_of(message_bytes(signing_input)); - } - if (!engine::verify(point_bytes, digest_bytes, signature_bytes)) { - return error::invalid_signature; + std::array digest_bytes{}; + if constexpr (prehashed) { + std::ranges::copy(signing_input.digest, digest_bytes.begin()); + } else { + digest_bytes = sha256_of(message_bytes(signing_input)); + } + if (!engine::verify(point_bytes, digest_bytes, signature_bytes)) { + return error::invalid_signature; + } + return {}; } - return {}; } else { - // Never compiled into a program: check_input stopped the build. + // Never compiled into a program: check_input or an assertion of p256_verifying_checked + // stopped the build. return error::invalid_signature; } } @@ -239,23 +321,35 @@ class basic_public_key { [[nodiscard]] static boost::system::result from_bytes( std::span encoded_point) noexcept { secure::timing_guard const timing_scope; - if (encoded_point.size() == 1 + coordinate_size) { - if (encoded_point[0] != 0x02 && encoded_point[0] != 0x03) { - return error::invalid_public_key; + if constexpr (detail::specialized_engine_v) { + static_assert( + detail::backend::p256_point, + "webcpp::crypto: this backend has P-256 but not crypto::capabilities::p256_point: " + "a public key's point cannot be checked, and from_bytes is not available on it."); + } + if constexpr (!detail::capability_usable_v>) { + // Never compiled into a program: the assertion above stopped the build. + return error::invalid_public_key; + } else { + if (encoded_point.size() == 1 + coordinate_size) { + if (encoded_point[0] != 0x02 && encoded_point[0] != 0x03) { + return error::invalid_public_key; + } + std::array point_bytes{0x04}; + auto const x_coordinate = + encoded_point.subspan(1).template first(); + std::ranges::copy(x_coordinate, point_bytes.begin() + 1); + if (!engine::decompress(encoded_point[0], x_coordinate, + std::span(point_bytes).template last())) { + return error::invalid_public_key; + } + return checked(point_bytes); } - std::array point_bytes{0x04}; - auto const x_coordinate = encoded_point.subspan(1).template first(); - std::ranges::copy(x_coordinate, point_bytes.begin() + 1); - if (!engine::decompress(encoded_point[0], x_coordinate, - std::span(point_bytes).template last())) { + if (encoded_point.size() != public_key_size || encoded_point[0] != 0x04) { return error::invalid_public_key; } - return checked(point_bytes); + return checked(encoded_point.template first()); } - if (encoded_point.size() != public_key_size || encoded_point[0] != 0x04) { - return error::invalid_public_key; - } - return checked(encoded_point.template first()); } /** @@ -367,9 +461,9 @@ class basic_public_key { 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."); + 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 (detail::check_policy checked( std::span point_bytes) noexcept { - if (!engine::valid_point(point_bytes)) { + if constexpr (detail::specialized_engine_v) { + static_assert(detail::backend::p256_point, + "webcpp::crypto: this backend has P-256 but not " + "crypto::capabilities::p256_point: a public key's point cannot be " + "checked, and from_coordinates is not available on it."); + } + if constexpr (!detail::capability_usable_v>) { + // Never compiled into a program: the assertion above stopped the build. return error::invalid_public_key; + } else { + if (!engine::valid_point(point_bytes)) { + return error::invalid_public_key; + } + basic_public_key made_key; + std::ranges::copy(point_bytes, made_key.point_.begin()); + return made_key; } - basic_public_key made_key; - std::ranges::copy(point_bytes, made_key.point_.begin()); - return made_key; } std::array point_{}; @@ -554,26 +659,47 @@ class basic_keypair { // Never compiled into a program: the assertion above stopped the build. return error::backend_failure; } else { - if (secret_scalar.size() != secret_key_size) { - return error::invalid_key_size; - } - auto const scalar_bytes = secret_scalar.template first(); - if (!detail::p_curve_scalar_valid(scalar_bytes, traits::order)) { - return error::invalid_secret_key; + // The trait first, then the capability (design D3's amendment, D9). + static_assert(detail::secret_keys_enter_v, + "webcpp::crypto: this backend keeps its keys: no secret key enters it " + "(crypto::imports_secret_keys_v is false), so P-256's from_secret, which " + "needs crypto::capabilities::p256_import, is not available on it; make a " + "key with generate."); + if constexpr (detail::specialized_engine_v && + detail::secret_keys_enter_v) { + static_assert(detail::backend::p256_import, + "webcpp::crypto: this backend has P-256 but not " + "crypto::capabilities::p256_import: from_secret is not available on " + "it; make a key with generate."); } - basic_keypair made_pair; - auto const engine_keyed = engine::import_secret(made_pair.state_, scalar_bytes); - if (!engine_keyed) { - return engine_keyed.error(); + if constexpr (!detail::secret_keys_enter_v || + !detail::capability_usable_v>) { + // Never compiled into a program: an assertion above stopped the build. + return error::backend_failure; + } else { + if (secret_scalar.size() != secret_key_size) { + return error::invalid_key_size; + } + auto const scalar_bytes = secret_scalar.template first(); + if (!detail::p_curve_scalar_valid(scalar_bytes, traits::order)) { + return error::invalid_secret_key; + } + basic_keypair made_pair; + auto const engine_keyed = engine::import_secret(made_pair.state_, scalar_bytes); + if (!engine_keyed) { + return engine_keyed.error(); + } + made_pair.keyed_ = true; + return made_pair; } - made_pair.keyed_ = true; - return made_pair; } } /** - * Makes a key pair from a fresh scalar, drawn from the system's generator until it is below - * the group order (a draw is refused about once in 2^32). + * Makes a key pair from a fresh scalar: the backend's own, on a backend that draws its keys + * (design R3), else drawn from the system's generator until it is below the group order (a + * draw is refused about once in 2^32) and imported. * * @return The key pair; `entropy_unavailable` when the system's generator fails or there is * none; `backend_failure`. @@ -587,16 +713,7 @@ class basic_keypair { // Never compiled into a program: the assertion above stopped the build. return error::backend_failure; } else { - secure::secret scalar_bytes; - random_device random_source; // lint-world: the scalar - do { - if (!random_source.fill(scalar_bytes.writable())) { - // The generator's not_supported (an Emscripten audio worklet) is the same - // failure for a key pair: one error to handle. - return error::entropy_unavailable; - } - } while (!detail::p_curve_scalar_valid(scalar_bytes.bytes(), traits::order)); - return from_secret(scalar_bytes.bytes()); + return generated(); } } @@ -653,8 +770,7 @@ class basic_keypair { */ basic_keypair(basic_keypair&& moved_from) noexcept : keyed_(std::exchange(moved_from.keyed_, false)) { - state_ = moved_from.state_; - engine::reset(moved_from.state_); + engine::move(state_, moved_from.state_); } /** @@ -667,8 +783,7 @@ class basic_keypair { if (this != &moved_from) { engine::reset(state_); keyed_ = std::exchange(moved_from.keyed_, false); - state_ = moved_from.state_; - engine::reset(moved_from.state_); + engine::move(state_, moved_from.state_); } return *this; } @@ -684,30 +799,65 @@ class basic_keypair { /** * The public key, computed when the key pair was made. * - * @return The public key; `invalid_state` moved from. + * @return The public key; `invalid_state` moved from; `backend_failure`. */ [[nodiscard]] boost::system::result> public_key() const noexcept { - if (!keyed_) { - return error::invalid_state; + if constexpr (detail::specialized_engine_v) { + static_assert( + detail::backend::p256_public, + "webcpp::crypto: this backend has P-256 but not crypto::capabilities::p256_public: " + "a key pair's public_key() is not available on it."); + } + if constexpr (!detail::capability_usable_v>) { + // Never compiled into a program: the assertion above stopped the build. + return error::backend_failure; + } else { + if (!keyed_) { + return error::invalid_state; + } + auto made_key = detail::p_curve_access::blank>(); + auto const engine_done = + engine::public_key(state_, detail::p_curve_access::point(made_key)); + if (!engine_done) { + return engine_done.error(); + } + return made_key; } - auto made_key = detail::p_curve_access::blank>(); - engine::public_point(state_, detail::p_curve_access::point(made_key)); - return made_key; } /** * The secret scalar, for a program that keeps the key pair and makes it again with * `from_secret`. * - * @return 32 secret bytes, big-endian; `invalid_state` moved from. + * @return 32 secret bytes, big-endian; `invalid_state` moved from; `backend_failure`. */ [[nodiscard]] boost::system::result> secret() const noexcept { - if (!keyed_) { - return error::invalid_state; + // The trait first, then the capability (design D3's amendment, D9). + static_assert(detail::secret_keys_leave_v, + "webcpp::crypto: this backend keeps its keys: no secret key leaves it " + "(crypto::exports_secret_keys_v is false), so P-256's secret(), which needs " + "crypto::capabilities::p256_export, is not available on it."); + if constexpr (detail::specialized_engine_v && + detail::secret_keys_leave_v) { + static_assert(detail::backend::p256_export, + "webcpp::crypto: this backend has P-256 but not " + "crypto::capabilities::p256_export: secret() is not available on it."); + } + if constexpr (!detail::secret_keys_leave_v || + !detail::capability_usable_v>) { + // Never compiled into a program: an assertion above stopped the build. + return error::backend_failure; + } else { + if (!keyed_) { + return error::invalid_state; + } + secure::secret scalar_bytes; + auto const engine_done = engine::export_secret(state_, scalar_bytes.writable()); + if (!engine_done) { + return engine_done.error(); + } + return scalar_bytes; } - secure::secret scalar_bytes; - engine::scalar(state_, scalar_bytes.writable()); - return scalar_bytes; } /** @@ -732,9 +882,9 @@ class basic_keypair { 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."); + static_assert( + !detail::asynchronous_backend_v, + "webcpp::crypto: sign on this backend completes asynchronously: call async_sign."); if constexpr (std::is_same_v && !detail::asynchronous_backend_v) { detail::check_input(); @@ -742,7 +892,7 @@ class basic_keypair { if constexpr (detail::is_prehashed_v) { return signed_digest(signing_input.digest); } else { - return signed_digest(detail::sha256_of(detail::message_bytes(signing_input))); + return signed_message(detail::message_bytes(signing_input)); } } else { // Never compiled into a program: check_input stopped the build. @@ -805,16 +955,7 @@ class basic_keypair { // Never compiled into a program: the assertion above stopped the build. return error::backend_failure; } else { - if (!keyed_) { - return error::invalid_state; - } - secure::secret shared_bytes; - auto const derive_result = engine::ecdh_x( - state_, detail::p_curve_access::point(peer_key), shared_bytes.writable()); - if (!derive_result) { - return derive_result.error(); - } - return shared_bytes; + return agreed(peer_key); } } @@ -878,20 +1019,120 @@ class basic_keypair { private: basic_keypair() noexcept = default; - // The work of sign, which holds the guard: RFC 6979's signature of a digest, made low S in - // constant time: n - s is computed always and selected with a mask, with no branch on s and - // nothing declassified, so that the signature stays as secret to a constant-time checker as - // the engine made it. + // The work of generate, which holds the guard, and of a backend's asynchronous generation + // (detail::async_access): the backend's own key when its engine draws one (design R3), else a + // scalar from the system's generator, imported. + [[nodiscard]] static boost::system::result generated() noexcept { + if constexpr (detail::backend::p256_generate) { + basic_keypair made_pair; + auto const engine_drawn = engine::generate(made_pair.state_); + if (!engine_drawn) { + return engine_drawn.error(); + } + made_pair.keyed_ = true; + return made_pair; + } else { + // A backend that neither draws its keys nor imports them has no way to make one. + static_assert( + detail::secret_keys_enter_v && + (!detail::specialized_engine_v || detail::backend::p256_import), + "webcpp::crypto: this backend has P-256 but neither " + "crypto::capabilities::p256_generate nor crypto::capabilities::p256_import: " + "generate has no way to make a key on it."); + secure::secret scalar_bytes; + random_device random_source; // lint-world: the scalar + do { + if (!random_source.fill(scalar_bytes.writable())) { + // The generator's not_supported (an Emscripten audio worklet) is the same + // failure for a key pair: one error to handle. + return error::entropy_unavailable; + } + } while (!detail::p_curve_scalar_valid(scalar_bytes.bytes(), traits::order)); + if constexpr (!detail::secret_keys_enter_v || + !detail::capability_usable_v>) { + // Never compiled into a program: the assertion above stopped the build. + return error::backend_failure; + } else { + return from_secret(scalar_bytes.bytes()); + } + } + } + + // The work of agree, which holds the guard, and of a backend's asynchronous agreement. + [[nodiscard]] boost::system::result> agreed( + basic_public_key const& peer_key) const noexcept { + if constexpr (detail::specialized_engine_v) { + static_assert(detail::backend::p256_ecdh, + "webcpp::crypto: this backend has P-256 but not " + "crypto::capabilities::p256_ecdh: agree is not available on it."); + } + if constexpr (!detail::capability_usable_v>) { + // Never compiled into a program: the assertion above stopped the build. + return error::backend_failure; + } else { + if (!keyed_) { + return error::invalid_state; + } + secure::secret shared_bytes; + auto const derive_result = engine::ecdh_x( + state_, detail::p_curve_access::point(peer_key), shared_bytes.writable()); + if (!derive_result) { + return derive_result.error(); + } + return shared_bytes; + } + } + + // The work of sign, which holds the guard, for a message: the engine's message form when it + // has one, else the message's SHA-256 signed on the digest form. + [[nodiscard]] boost::system::result signed_message( + std::span message_bytes) const noexcept { + if constexpr (!detail::p256_signing_checked()) { + // Never compiled into a program: the assertion of p256_signing_checked stopped the + // build. + return error::backend_failure; + } else if constexpr (detail::backend::p256_ecdsa_message_signing) { + if (!keyed_) { + return error::invalid_state; + } + std::array signature_bytes{}; + auto const sign_result = engine::sign_message(state_, message_bytes, signature_bytes); + if (!sign_result) { + return sign_result.error(); + } + return low_s_signature(signature_bytes); + } else { + return signed_digest(detail::sha256_of(message_bytes)); + } + } + + // The work of sign, which holds the guard, for a digest: RFC 6979's signature of it on the + // digest form. [[nodiscard]] boost::system::result signed_digest( std::span digest_bytes) const noexcept { - if (!keyed_) { - return error::invalid_state; - } - std::array signature_bytes{}; - auto const sign_result = engine::sign(state_, digest_bytes, signature_bytes); - if (!sign_result) { - return sign_result.error(); + if constexpr (!detail::p256_signing_checked()) { + // Never compiled into a program: the assertion of p256_signing_checked stopped the + // build. + return error::backend_failure; + } else { + if (!keyed_) { + return error::invalid_state; + } + std::array signature_bytes{}; + auto const sign_result = engine::sign(state_, digest_bytes, signature_bytes); + if (!sign_result) { + return sign_result.error(); + } + return low_s_signature(signature_bytes); } + } + + // The engine's signature made low S in constant time: n - s is computed always and selected + // with a mask, with no branch on s and nothing declassified, so that the signature stays as + // secret to a constant-time checker as the engine made it. + [[nodiscard]] static ecdsa_signature low_s_signature( + std::array& signature_bytes) noexcept { auto const s_value = std::span(signature_bytes) .template last(); std::array negated_s{}; @@ -954,9 +1195,9 @@ template 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."); + 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::check_policy>()) { @@ -1017,6 +1258,62 @@ inline constexpr bool verifies_with_v, signing_schemes::ecdsa_sha256_t> = true; +/** + * Whether the P-256 engine `Engine` signs a digest, as a query: `true` for an engine no backend's + * header specialises, taken at its word (its generated refusal is the key pair's to say, when the + * program uses it), else whether it has `backend::p256_ecdsa_signing`. The concept is formed only + * for a specialised engine, so that asking never instantiates a refusing primary. + * + * @tparam Engine The P-256 engine of the key pair's backend. + * @return Whether `can_sign` admits a prehashed digest. + */ +template +consteval bool p256_signs_digest() noexcept { + if constexpr (!specialized_engine_v) { + return true; + } else { + return backend::p256_ecdsa_signing; + } +} + +/** + * Whether the P-256 engine `Engine` verifies a digest, as `p256_signs_digest` asks the signing + * form. + * + * @tparam Engine The P-256 engine of the key's backend. + * @return Whether `can_verify` admits a prehashed digest. + */ +template +consteval bool p256_verifies_digest() noexcept { + if constexpr (!specialized_engine_v) { + return true; + } else { + return backend::p256_ecdsa_verifying; + } +} + +/** + * A P-256 key pair signs a digest where its backend's engine has the digest form, + * `capabilities::p256_ecdsa_signing`, as `sign` of `signing_schemes::prehashed` asks it. + * + * @tparam Backend The key pair's backend. + */ +template +inline constexpr bool + signs_digest_v, signing_schemes::ecdsa_sha256_t> = + p256_signs_digest>(); + +/** + * A P-256 public key verifies a digest where its backend's engine has the digest form, + * `capabilities::p256_ecdsa_verifying`, as `verify` of `signing_schemes::prehashed` asks it. + * + * @tparam Backend The public key's backend. + */ +template +inline constexpr bool + verifies_digest_v, signing_schemes::ecdsa_sha256_t> = + p256_verifies_digest>(); + /** * A P-256 key pair's signature under ECDSA over SHA-256, `curves::p256::ecdsa_signature`. * @@ -1143,13 +1440,23 @@ struct p_curve_engine { return false; } - /** Never called. */ + /** Never called; fails closed. */ template - static void public_point(Arguments&&... /*arguments*/) noexcept {} + [[nodiscard]] static boost::system::result public_key( + Arguments&&... /*arguments*/) noexcept { + return error::backend_failure; + } + + /** Never called; fails closed. */ + template + [[nodiscard]] static boost::system::result export_secret( + Arguments&&... /*arguments*/) noexcept { + return error::backend_failure; + } /** Never called. */ template - static void scalar(Arguments&&... /*arguments*/) noexcept {} + static void move(Arguments&&... /*arguments*/) noexcept {} /** Never called. */ template diff --git a/include/webcpp/crypto/curves/p256/formats.hpp b/include/webcpp/crypto/curves/p256/formats.hpp index fae47d8..01c4f66 100644 --- a/include/webcpp/crypto/curves/p256/formats.hpp +++ b/include/webcpp/crypto/curves/p256/formats.hpp @@ -37,9 +37,12 @@ #include #include #include +#include #include #include +#include #include +#include #include #include #include @@ -116,14 +119,63 @@ static_assert(p256_spki_size == 91 && p256_spki_compressed_size == 59 && p256_pk /** The longest strict DER of a P-256 signature: 2 + 2 * (2 + 33). */ inline constexpr std::size_t p256_der_size = p_curve_traits::max_der_size; +/** + * Whether a key pair of `Backend` lets its secret key leave and enter its backend, as its private + * formats do: the backend's secret-key traits, for an engine its header specialises (design D3's + * amendment). + * + * @tparam Backend The key pair's backend. + */ +template +inline constexpr bool p256_secret_passes_v = + secret_keys_leave_v, Backend> && + secret_keys_enter_v, Backend>; + /** * Whether a key pair of `Backend` has P-256's private formats: its secret is in the program, on - * every backend but one whose key pairs live in WebCrypto (design D7). + * every backend but one that keeps its keys (design D3's amendment) or whose key pairs live in + * WebCrypto (design D7). * * @tparam Backend The key pair's backend. */ template -inline constexpr bool p256_private_formats_v = !asynchronous_backend_v; +inline constexpr bool p256_private_formats_v = + p256_secret_passes_v && !asynchronous_backend_v; + +/** + * Why a key pair of `Backend` has no private format: its backend keeps its keys, which is said + * first, for `raw` apart from `pkcs8` and `pem(pkcs8)`, or its secret lives in WebCrypto. + * + * @tparam Backend The key pair's backend, one without P-256's private formats. + * @tparam Raw Whether the format is `raw`. + */ +template +inline constexpr refusal_reason p256_private_refusal_v = + p256_secret_passes_v ? refusal_reason::private_on_asynchronous + : private_kept_reason_v; + +/** + * Whether the P-256 engine `Engine` converts a signature to and from DER (design D9): true for the + * family's primary engine, whose generated refusal speaks, and for a test's unmarked stand-in, + * taken at its word; for an engine a backend's header specialises (`specialized_engine_v`), + * `backend::ecdsa_der`, asserted by a message that names it. A function template per engine, so + * that `encode` and `decode` say a refusal once. + * + * @tparam Engine The P-256 engine of the backend. + * @return Whether the codec may call the engine. + */ +template +constexpr bool p256_der_checked() noexcept { + if constexpr (!specialized_engine_v) { + return true; + } else { + static_assert( + backend::ecdsa_der, + "webcpp::crypto: this backend has P-256 but not crypto::capabilities::p256_ecdsa_der: " + "a signature's formats::der is not available on it."); + return backend::ecdsa_der; + } +} /** * The point form a P-256 value codec of `raw` or `spki` writes and reads: the default and @@ -222,37 +274,40 @@ struct formats_of { }; /** - * A key pair whose secret lives in WebCrypto has no `raw` (design D7). + * A key pair whose backend keeps its keys, or whose secret lives in WebCrypto, has no `raw` + * (design D3's amendment, D7). * - * @tparam Backend The key pair's backend, one whose key pairs live in WebCrypto. + * @tparam Backend The key pair's backend, one without private formats. */ template requires(!p256_private_formats_v) inline constexpr refusal_reason refusal_reason_v, curves::p256::basic_keypair> = - refusal_reason::private_on_asynchronous; + p256_private_refusal_v; /** - * A key pair whose secret lives in WebCrypto has no `pkcs8` (design D7). + * A key pair whose backend keeps its keys, or whose secret lives in WebCrypto, has no `pkcs8` + * (design D3's amendment, D7). * - * @tparam Backend The key pair's backend, one whose key pairs live in WebCrypto. + * @tparam Backend The key pair's backend, one without private formats. */ template requires(!p256_private_formats_v) inline constexpr refusal_reason refusal_reason_v> = - refusal_reason::private_on_asynchronous; + p256_private_refusal_v; /** - * A key pair whose secret lives in WebCrypto has no `pem(pkcs8)` (design D7). + * A key pair whose backend keeps its keys, or whose secret lives in WebCrypto, has no `pem(pkcs8)` + * (design D3's amendment, D7). * - * @tparam Backend The key pair's backend, one whose key pairs live in WebCrypto. + * @tparam Backend The key pair's backend, one without private formats. */ template requires(!p256_private_formats_v) inline constexpr refusal_reason refusal_reason_v, curves::p256::basic_keypair> = - refusal_reason::private_on_asynchronous; + p256_private_refusal_v; } // namespace webcpp::crypto::detail @@ -737,23 +792,29 @@ struct value_codec output_bytes) noexcept { secure::timing_guard const timing_scope; using engine = crypto::detail::p_curve_engine; - std::span const signature_bytes( - signature.bytes()); - // The value's fault before the size's, as codecs orders an encode's faults. - if (!crypto::detail::p_curve_signature_in_range(signature_bytes)) { - return crypto::error::invalid_signature; - } - std::size_t const der_size = crypto::detail::p256_der_size_of(signature_bytes); - if (output_bytes.size() < der_size) { - return error::output_too_small; - } - std::array der_bytes{}; - if (engine::to_der(signature_bytes, der_bytes) != der_size) { - return crypto::error::backend_failure; // strict DER has one size: never reached + if constexpr (!crypto::detail::p256_der_checked()) { + // Never compiled into a program: the assertion of p256_der_checked stopped the build. + return crypto::error::backend_failure; + } else { + std::span const + signature_bytes(signature.bytes()); + // The value's fault before the size's, as codecs orders an encode's faults. + if (!crypto::detail::p_curve_signature_in_range( + signature_bytes)) { + return crypto::error::invalid_signature; + } + std::size_t const der_size = crypto::detail::p256_der_size_of(signature_bytes); + if (output_bytes.size() < der_size) { + return error::output_too_small; + } + std::array der_bytes{}; + if (engine::to_der(signature_bytes, der_bytes) != der_size) { + return crypto::error::backend_failure; // strict DER has one size: never reached + } + std::ranges::copy(std::span(der_bytes).first(der_size), + output_bytes.begin()); + return der_size; } - std::ranges::copy(std::span(der_bytes).first(der_size), - output_bytes.begin()); - return der_size; } /** @@ -771,16 +832,22 @@ struct value_codec input_bytes) noexcept { secure::timing_guard const timing_scope; using engine = crypto::detail::p_curve_engine; - if (input_bytes.empty() || input_bytes.size() > max_decode_input_size) { - return crypto::error::invalid_signature; - } - std::array signature_bytes{}; - if (!engine::from_der(input_bytes, signature_bytes) || - !crypto::detail::p_curve_signature_in_range(signature_bytes)) { + if constexpr (!crypto::detail::p256_der_checked()) { + // Never compiled into a program: the assertion of p256_der_checked stopped the build. return crypto::error::invalid_signature; + } else { + if (input_bytes.empty() || input_bytes.size() > max_decode_input_size) { + return crypto::error::invalid_signature; + } + std::array signature_bytes{}; + if (!engine::from_der(input_bytes, signature_bytes) || + !crypto::detail::p_curve_signature_in_range( + signature_bytes)) { + return crypto::error::invalid_signature; + } + return crypto::detail::signature_access::of( + signature_bytes); } - return crypto::detail::signature_access::of( - signature_bytes); } }; diff --git a/include/webcpp/crypto/curves/secp256k1.hpp b/include/webcpp/crypto/curves/secp256k1.hpp index 642c9ec..67f0919 100644 --- a/include/webcpp/crypto/curves/secp256k1.hpp +++ b/include/webcpp/crypto/curves/secp256k1.hpp @@ -42,7 +42,6 @@ #include #include // lint-world: the context's randomisation and generate()'s key #include -#include #include #include #include @@ -60,7 +59,6 @@ #include #include #include -#include #include #include #include @@ -144,10 +142,28 @@ struct secp256k1_schnorr_signature_tag { static constexpr bool ecdsa = false; }; +/** The engine of the key pair (design D8): its state, which every other engine reads. */ +using secp256k1_key_engine = secp256k1_engine_of; +/** The engine of the points and x-only keys. */ +using secp256k1_point_engine = secp256k1_engine_of; +/** The engine of ECDSA and its signature's forms. */ +using secp256k1_ecdsa_engine = secp256k1_engine_of; +/** The engine of BIP340's Schnorr. */ +using secp256k1_schnorr_engine = secp256k1_engine_of; +/** The engine of recoverable ECDSA. */ +using secp256k1_recoverable_engine = + secp256k1_engine_of; +/** The engine of ECDH. */ +using secp256k1_ecdh_engine = secp256k1_engine_of; +/** A public point, the point engine's. */ +using secp256k1_point = secp256k1_point_engine::point; +/** A BIP340 x-only key, the point engine's. */ +using secp256k1_xonly_point = secp256k1_point_engine::xonly_point; + /** * The one door of the module headers (those under `curves/secp256k1/`) into a key pair and a public - * key: the key pair's context and `secp256k1_keypair`, whether it is keyed, and a public key's - * point. It hands out nothing a caller of crypto could not already do through the key pair. + * key: the key pair's engine state, whether it is keyed, and a public key's point. It hands out + * nothing a caller of crypto could not already do through the key pair. */ struct secp256k1_access { /** @@ -161,64 +177,54 @@ struct secp256k1_access { curves::secp256k1::basic_keypair const& key_pair) noexcept; /** - * A key pair's randomised signing context, for the functions that multiply the generator. + * A key pair's engine state, which the engines that use the key read. * * @param key_pair The key pair, keyed. - * @return Its context; null moved from. + * @return Its state: its context and key, wiped moved from. */ template - [[nodiscard]] static secp256k1_context const* context( - curves::secp256k1::basic_keypair const& key_pair) noexcept; - - /** - * A key pair's `secp256k1_keypair`, its secret and public key. - * - * @param key_pair The key pair, keyed. - * @return Its `secp256k1_keypair`, wiped moved from. - */ - template - [[nodiscard]] static secp256k1_keypair const& pair( + [[nodiscard]] static secp256k1_key_engine::state const& key_state( curves::secp256k1::basic_keypair const& key_pair) noexcept; /** * A public key's point. * * @param typed_key The public key. - * @return Its `secp256k1_pubkey`. + * @return Its point, the engines'. */ - [[nodiscard]] static secp256k1_pubkey const& point( + [[nodiscard]] static secp256k1_point const& point( curves::secp256k1::public_key const& typed_key) noexcept; /** * A public key's point, to be written by the function that makes the key. * * @param typed_key The public key. - * @return Its `secp256k1_pubkey`. + * @return Its point, the engines'. */ - [[nodiscard]] static secp256k1_pubkey& point(curves::secp256k1::public_key& typed_key) noexcept; + [[nodiscard]] static secp256k1_point& point(curves::secp256k1::public_key& typed_key) noexcept; /** * A public key whose point is zero, not yet a key: the function that returns it writes its - * point first, and returns an error instead where libsecp256k1 writes none. + * point first, and returns an error instead where the engine writes none. * * @return The unwritten key. */ [[nodiscard]] static curves::secp256k1::public_key make_public_key() noexcept; /** - * An x-only key from libsecp256k1's struct, which the caller's libsecp256k1 function wrote: a - * valid key, as every `xonly_public_key` is. + * An x-only key from the engines' value, which an engine wrote: a valid key, as every + * `xonly_public_key` is. * - * @param native_key The struct, written. + * @param native_key The value, written. * @return The typed key. */ [[nodiscard]] static curves::secp256k1::xonly_public_key make_xonly_public_key( - secp256k1_xonly_pubkey const& native_key) noexcept; + secp256k1_xonly_point const& native_key) noexcept; /** * An object of a module header's opaque type (MuSig2's aggregate key, nonces, session and - * partial signature), not yet written: the function that returns it writes its - * libsecp256k1 struct first, and returns an error instead where libsecp256k1 writes none. + * partial signature), not yet written: the function that returns it writes its engine + * value first, and returns an error instead where the engine writes none. * * @tparam Opaque The type, whose default constructor is private. * @return The unwritten object. @@ -230,8 +236,8 @@ struct secp256k1_access { /** * What an opaque type wraps (a module header's, and `xonly_public_key`), its private member - * `native_value_`: the libsecp256k1 struct, or for a secret nonce the struct and what crypto - * keeps beside it. + * `native_value_`: the engine's value, or for a secret nonce the value and what crypto keeps + * beside it. * * @tparam Opaque The type, `const` for a read. * @param opaque_object The object. @@ -243,62 +249,6 @@ struct secp256k1_access { } }; -// NOLINTBEGIN(bugprone-signed-bitwise): libsecp256k1's macros shift a signed constant -#if defined(WEBCPP_SECURE_CT_VALGRIND) || defined(WEBCPP_SECURE_CT_MSAN) -/** - * The flags of a context that signs and verifies, under a constant-time checker: - * `SECP256K1_CONTEXT_DECLASSIFY`, so that libsecp256k1 marks its own public values public (a - * nonce's retry, a verdict), as its `ctime_tests.c` does; the checker then reports any other - * branch on a secret. - */ -inline constexpr unsigned secp256k1_context_flags = SECP256K1_CONTEXT_DECLASSIFY; -#else -/** The flags of a context that signs and verifies: none. */ -inline constexpr unsigned secp256k1_context_flags = SECP256K1_CONTEXT_NONE; -#endif - -/** The flag of the SEC1 compressed form. */ -inline constexpr unsigned secp256k1_compressed = SECP256K1_EC_COMPRESSED; - -/** The flag of the SEC1 uncompressed form. */ -inline constexpr unsigned secp256k1_uncompressed = SECP256K1_EC_UNCOMPRESSED; - -// NOLINTEND(bugprone-signed-bitwise) - -/** - * Whether libsecp256k1 accepted: what it returned on a secret, marked public for the - * constant-time checks (`secure::declassify`) where webcpp branches on it, as its - * `ctime_tests.c` marks each verdict. - * - * @param returned_code What the function returned: 1, or 0 when it refused. - * @return Whether it accepted. - */ -[[nodiscard]] inline bool secp256k1_accepted(int returned_code) noexcept { - // Not const: the comparison reads it again after the mark (secure::declassify's tip). - // NOLINTNEXTLINE(misc-const-correctness): see above - int accepted_verdict = returned_code; - secure::declassify(accepted_verdict); - return accepted_verdict != 0; -} - -/** - * A key pair's public key, marked public (`secure::declassify`): libsecp256k1 - * derives it from the secret and marks it public only where it loads the key pair itself, and - * its `ctime_tests.c` marks a key pair's public key by hand where it reads one. - * - * @param secp_context The key pair's context, or the static one. - * @param key_pair libsecp256k1's key pair. - * @return The public key. - */ -[[nodiscard]] inline secp256k1_pubkey secp256k1_public_point( - secp256k1_context const* secp_context, secp256k1_keypair const& key_pair) noexcept { - secp256k1_pubkey public_point{}; - // libsecp256k1 returns 1 always: a key pair holds its public key. - static_cast(secp256k1_keypair_pub(secp_context, &public_point, &key_pair)); - secure::declassify(public_point); - return public_point; -} - /** * The error of a key pair whose context could not be randomised: every failure of the * generator is `entropy_unavailable`, the library's one word for it. @@ -312,20 +262,8 @@ inline boost::system::error_code secp256k1_seed_error( } /** - * Secret bytes out of a key pair, its secret key or its context's seed, wiped when the scope - * ends on every path, a failure's or an exception's included. - */ -struct secp256k1_secret { - /** The secret bytes. */ - std::array bytes{}; - - /** Wipes the bytes. */ - ~secp256k1_secret() { secure::erase_secret(bytes); } -}; - -/** - * The carver of a caller's workspace into the arrays of pointers libsecp256k1 takes, which - * wipes the whole workspace when it is destroyed. + * The carver of a caller's workspace into the arrays of pointers the engines take, which wipes + * the whole workspace when it is destroyed. * * Each array is aligned to `alignof(std::max_align_t)`, in the order the function's size * function lists them; an array of no elements takes no bytes and is `nullptr`. @@ -386,111 +324,6 @@ class secp256k1_workspace { std::size_t used_size_ = 0; }; -/** - * Parses a public key of 33 bytes, compressed, or 65, uncompressed. libsecp256k1 also - * accepts X9.62's hybrid forms, prefix 06 or 07, of 65 bytes; they are refused here, as every - * prefix other than 02, 03 and 04 is. - * - * @param key_bytes The key, SEC1. - * @param parsed_value Where the parsed key goes. - * @return Whether it is a key: false in every way it can be wrong, `invalid_public_key` to the - * caller. - */ -[[nodiscard]] inline bool secp256k1_parse_public_key(std::span key_bytes, - secp256k1_pubkey& parsed_value) noexcept { - bool const is_sized = - key_bytes.size() == 33 || (key_bytes.size() == 65 && key_bytes[0] == 0x04); - return is_sized && secp256k1_ec_pubkey_parse(secp256k1_context_static, &parsed_value, - key_bytes.data(), key_bytes.size()) != 0; -} - -/** - * A public key's BIP340 x-only form, with libsecp256k1's static context; the parity of y is - * dropped. The caller has read the canary and run the self-test. - * - * @param point_value A valid point, as every `public_key` holds. - * @return The x-only key. - */ -[[nodiscard]] inline secp256k1_xonly_pubkey secp256k1_xonly_of( - secp256k1_pubkey const& point_value) noexcept { - secp256k1_xonly_pubkey xonly_key{}; - // libsecp256k1 returns 1 always: every valid point has an x-only form. - static_cast(secp256k1_xonly_pubkey_from_pubkey(secp256k1_context_static, &xonly_key, - nullptr, &point_value)); - return xonly_key; -} - -/** - * Whether 32 bytes of a compact signature, its r or its s, are not zero. - * - * @param half_bytes The 32 bytes. - * @return Whether one byte is not zero. - */ -[[nodiscard]] inline bool secp256k1_nonzero(std::span half_bytes) noexcept { - return std::ranges::any_of(half_bytes, - [](std::uint8_t octet_value) { return octet_value != 0; }); -} - -/** - * Parses a compact ECDSA signature, r then s, each below the group order and not zero. - * - * @param compact_signature The 64 bytes. - * @param parsed_value Where the parsed signature goes. - * @return Whether it is a signature: false in every way it can be wrong, `invalid_signature` to - * the caller. - */ -[[nodiscard]] inline bool secp256k1_parse_compact( - std::span compact_signature, - secp256k1_ecdsa_signature& parsed_value) noexcept { - return secp256k1_ecdsa_signature_parse_compact(secp256k1_context_static, &parsed_value, - compact_signature.data()) != 0 && - secp256k1_nonzero(compact_signature.first<32>()) && - secp256k1_nonzero(compact_signature.last<32>()); -} - -/** - * The compact form of a signature a DER parser read, refused when its r or its s is zero, - * which is how libsecp256k1's parsers give a number not below the group order. - * - * @param parsed_value The signature. - * @param output_bytes Where the 64 bytes go. - * @return Whether r and s are both in range. - */ -[[nodiscard]] inline bool secp256k1_compact_of( - secp256k1_ecdsa_signature const& parsed_value, - std::array& output_bytes) noexcept { - secp256k1_ecdsa_signature_serialize_compact(secp256k1_context_static, output_bytes.data(), - &parsed_value); - return secp256k1_nonzero(std::span(output_bytes).first<32>()) && - 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. @@ -545,41 +378,6 @@ template return digest_bytes; } -extern "C" { - -/** - * libsecp256k1's ECDH hash function that hashes nothing: the shared point's x coordinate, - * 32 bytes, as Wycheproof's and NIP-44's ECDH give it. C linkage, as libsecp256k1's function - * pointer type has. - * - * @return 1, always. - */ -inline int webcpp_crypto_detail_secp256k1_copy_x(unsigned char* output_bytes, - unsigned char const* x_coordinate, - unsigned char const* /*y_coordinate*/, - void* /*user_data*/) noexcept { - std::memcpy(output_bytes, x_coordinate, 32); - return 1; -} - -/** - * libsecp256k1's ECDH hash function that writes the shared point, SEC1 uncompressed: - * 0x04, x, y, 65 bytes. - * - * @return 1, always. - */ -inline int webcpp_crypto_detail_secp256k1_copy_point(unsigned char* output_bytes, - unsigned char const* x_coordinate, - unsigned char const* y_coordinate, - void* /*user_data*/) noexcept { - output_bytes[0] = 0x04; - std::memcpy(output_bytes + 1, x_coordinate, 32); - std::memcpy(output_bytes + 33, y_coordinate, 32); - return 1; -} - -} // extern "C" - /** * Whether `Backend` is libsecp256k1, the one backend of `curves::secp256k1`. * @@ -592,10 +390,11 @@ inline constexpr bool secp256k1_backend = std::is_same_v { template inline constexpr bool secp256k1_refuses_others = sizeof(secp256k1_refusal) != 0; -/** - * 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(compact_signature, 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 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); + return secp256k1_ecdsa_engine::is_low_s(signature_bytes); } inline boost::system::result> secp256k1_ecdsa_signature_tag::low_s( @@ -658,7 +436,7 @@ inline boost::system::result> secp256k1_ecdsa_signa secure::timing_guard const timing_scope; std::array low_bytes{}; bool was_high = false; - if (!secp256k1_low_s_of(signature_bytes, low_bytes, was_high)) { + if (!secp256k1_ecdsa_engine::low_s(signature_bytes, low_bytes, was_high)) { return error::invalid_signature; } return low_bytes; @@ -670,9 +448,7 @@ inline bool secp256k1_recoverable_signature_tag::is_low_s( if (signature_bytes[64] > 3) { return false; } - read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); - secp256k1_selftest(); - return secp256k1_low_s_verdict(signature_bytes.first<64>()); + return secp256k1_ecdsa_engine::is_low_s(signature_bytes.first<64>()); } inline boost::system::result> @@ -684,7 +460,7 @@ secp256k1_recoverable_signature_tag::low_s( } std::array compact_bytes{}; bool was_high = false; - if (!secp256k1_low_s_of(signature_bytes.first<64>(), compact_bytes, was_high)) { + if (!secp256k1_ecdsa_engine::low_s(signature_bytes.first<64>(), compact_bytes, was_high)) { return error::invalid_signature; } std::array low_bytes{}; @@ -696,8 +472,8 @@ secp256k1_recoverable_signature_tag::low_s( } /** - * 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. + * Verifies a BIP340 signature against an x-only key already parsed: the end of every verification + * of `schnorr`, whose public functions hold the guard. * * @param signature_bytes 64 bytes. * @param message_bytes The signed message, as given. @@ -706,17 +482,16 @@ secp256k1_recoverable_signature_tag::low_s( */ [[nodiscard]] inline boost::system::result secp256k1_verify_schnorr( std::span signature_bytes, std::span message_bytes, - secp256k1_xonly_pubkey const& xonly_key) noexcept { - if (secp256k1_schnorrsig_verify(secp256k1_context_static, signature_bytes.data(), - message_bytes.data(), message_bytes.size(), &xonly_key) == 0) { + secp256k1_xonly_point const& xonly_key) noexcept { + if (!secp256k1_schnorr_engine::verify(xonly_key, message_bytes, signature_bytes)) { return error::invalid_signature; } return {}; } /** - * Verifies a BIP340 signature against a public key's point, through its x-only form, with - * libsecp256k1's static context: the work of `public_key::verify` and of `crypto::verify` of + * Verifies a BIP340 signature against a public key's point, through its x-only form: the work + * of `public_key::verify` and of `crypto::verify` of * `schnorr` against the typed key, which hold the guard. * * @tparam Backend The backend, libsecp256k1. @@ -729,13 +504,12 @@ secp256k1_recoverable_signature_tag::low_s( template [[nodiscard]] boost::system::result secp256k1_verify_schnorr_key( std::span signature_bytes, Input const& message_input, - secp256k1_pubkey const& point_value) noexcept { + secp256k1_point const& point_value) noexcept { 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(); - auto const xonly_key = secp256k1_xonly_of(point_value); + secp256k1_xonly_point xonly_key{}; + secp256k1_point_engine::to_xonly(point_value, xonly_key); return secp256k1_verify_schnorr(signature_bytes, bytes_of_message, xonly_key); } else { // Never compiled into a program: check_input stopped the build. @@ -744,9 +518,8 @@ template } /** - * Verifies a BIP340 signature against an x-only key, with libsecp256k1's static context: the work - * of `xonly_public_key::verify` and of `crypto::verify` of `schnorr` against the x-only key, which - * hold the guard. + * Verifies a BIP340 signature against an x-only key: the work of `xonly_public_key::verify` and of + * `crypto::verify` of `schnorr` against the x-only key, which hold the guard. * * @tparam Backend The backend, libsecp256k1. * @tparam Input A message; anything else stops the build. @@ -758,12 +531,10 @@ template template [[nodiscard]] boost::system::result secp256k1_verify_schnorr_xonly( std::span signature_bytes, Input const& message_input, - secp256k1_xonly_pubkey const& xonly_key) noexcept { + secp256k1_xonly_point const& xonly_key) noexcept { 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(); return secp256k1_verify_schnorr(signature_bytes, bytes_of_message, xonly_key); } else { // Never compiled into a program: check_input stopped the build. @@ -772,9 +543,8 @@ template } /** - * Verifies an ECDSA signature over SHA-256 against a public key's point, with libsecp256k1's - * static context, after its self-test: the work of `public_key::verify` and of `crypto::verify` - * of `ecdsa_sha256`, which hold the guard. + * Verifies an ECDSA signature over SHA-256 against a public key's point: the work of + * `public_key::verify` and of `crypto::verify` of `ecdsa_sha256`, which hold the guard. * * @tparam Backend The backend, libsecp256k1. * @tparam Input A message or `crypto::signing_schemes::prehashed<32>`; anything else stops the @@ -788,17 +558,11 @@ template template [[nodiscard]] boost::system::result secp256k1_verify_ecdsa( std::span signature_bytes, Input const& signing_input, - secp256k1_pubkey const& point_value) noexcept { + secp256k1_point const& point_value) noexcept { check_input(); if constexpr (input_valid_v) { auto const digest_bytes = secp256k1_digest(signing_input); - read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); - secp256k1_selftest(); - secp256k1_ecdsa_signature parsed_value{}; - if (secp256k1_ecdsa_signature_parse_compact(secp256k1_context_static, &parsed_value, - signature_bytes.data()) == 0 || - secp256k1_ecdsa_verify(secp256k1_context_static, &parsed_value, digest_bytes.data(), - &point_value) == 0) { + if (!secp256k1_ecdsa_engine::verify(point_value, digest_bytes, signature_bytes)) { return error::invalid_signature; } return {}; @@ -913,11 +677,9 @@ class xonly_public_key { if (key_bytes.size() != size) { return error::invalid_public_key; } - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); - secp256k1_selftest(); - secp256k1_xonly_pubkey parsed_key{}; - if (secp256k1_xonly_pubkey_parse(secp256k1_context_static, &parsed_key, key_bytes.data()) == - 0) { + webcpp::crypto::detail::secp256k1_xonly_point parsed_key{}; + if (!webcpp::crypto::detail::secp256k1_point_engine::parse_xonly(key_bytes.first(), + parsed_key)) { return error::invalid_public_key; } return xonly_public_key(parsed_key); @@ -930,12 +692,9 @@ class xonly_public_key { */ [[nodiscard]] std::array bytes() const noexcept { secure::timing_guard const timing_scope; - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); - secp256k1_selftest(); std::array output_bytes{}; - // libsecp256k1 returns 1 always: every key here is valid. - static_cast(secp256k1_xonly_pubkey_serialize(secp256k1_context_static, - output_bytes.data(), &native_value_)); + webcpp::crypto::detail::secp256k1_point_engine::serialize_xonly(native_value_, + output_bytes); return output_bytes; } @@ -1119,28 +878,26 @@ class xonly_public_key { friend struct webcpp::crypto::detail::secp256k1_access; /** - * The key libsecp256k1 wrote. + * The key an engine wrote. * * @param native_key A valid key. */ - explicit xonly_public_key(secp256k1_xonly_pubkey const& native_key) noexcept + explicit xonly_public_key( + webcpp::crypto::detail::secp256k1_xonly_point const& native_key) noexcept : native_value_(native_key) {} /** - * libsecp256k1's comparison of two keys with the static context, which reads them as their - * 32 bytes. Both are valid: no key is made otherwise, so the illegal callback is never - * reached. + * The engine's comparison of two keys, which reads them as their 32 bytes. * * @return Negative, zero or positive, as `memcmp`. */ [[nodiscard]] static int compare(xonly_public_key const& left_key, xonly_public_key const& right_key) noexcept { - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); - return secp256k1_xonly_pubkey_cmp(secp256k1_context_static, &left_key.native_value_, - &right_key.native_value_); + return webcpp::crypto::detail::secp256k1_point_engine::compare_xonly( + left_key.native_value_, right_key.native_value_); } - secp256k1_xonly_pubkey native_value_; + webcpp::crypto::detail::secp256k1_xonly_point native_value_; }; /** An x-only key tweaked by `xonly_public_key::tweak_add`: the key and the parity of its y. */ @@ -1156,18 +913,13 @@ boost::system::result xonly_public_key::tweak_add( std::span tweak_bytes) const 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_pubkey tweaked_point{}; - if (secp256k1_xonly_pubkey_tweak_add(secp256k1_context_static, &tweaked_point, &native_value_, - tweak_bytes.data()) == 0) { + using tweak_engine = webcpp::crypto::detail::secp256k1_engine_of< + webcpp::crypto::detail::backend::secp256k1_capabilities::tweak>; + webcpp::crypto::detail::secp256k1_xonly_point tweaked_native{}; + int tweaked_parity = 0; + if (!tweak_engine::xonly_add(native_value_, tweak_bytes, tweaked_native, tweaked_parity)) { return error::invalid_secret_key; } - secp256k1_xonly_pubkey tweaked_native{}; - int tweaked_parity = 0; - // libsecp256k1 returns 1 always: every valid point has an x-only form. - static_cast(secp256k1_xonly_pubkey_from_pubkey(secp256k1_context_static, &tweaked_native, - &tweaked_parity, &tweaked_point)); return tweaked_xonly_key{.key = xonly_public_key(tweaked_native), .parity = tweaked_parity}; } @@ -1177,15 +929,10 @@ boost::system::result xonly_public_key::verify_tweak( tweaked_xonly_key const& tweaked) const 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(); - std::array tweaked_bytes{}; - // libsecp256k1 returns 1 always: every key here is valid. - static_cast(secp256k1_xonly_pubkey_serialize( - secp256k1_context_static, tweaked_bytes.data(), &tweaked.key.native_value_)); - if (secp256k1_xonly_pubkey_tweak_add_check(secp256k1_context_static, tweaked_bytes.data(), - tweaked.parity, &native_value_, - tweak_bytes.data()) == 0) { + using tweak_engine = webcpp::crypto::detail::secp256k1_engine_of< + webcpp::crypto::detail::backend::secp256k1_capabilities::tweak>; + if (!tweak_engine::xonly_check(native_value_, tweak_bytes, tweaked.key.native_value_, + tweaked.parity)) { return error::invalid_public_key; } return {}; @@ -1220,11 +967,9 @@ class public_key { 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(); public_key made_key; - if (!webcpp::crypto::detail::secp256k1_parse_public_key(encoded_key, - made_key.point_value_)) { + if (!webcpp::crypto::detail::secp256k1_point_engine::parse(encoded_key, + made_key.point_value_)) { return error::invalid_public_key; } return made_key; @@ -1238,8 +983,7 @@ class public_key { [[nodiscard]] std::array> compressed() const noexcept { secure::timing_guard const timing_scope; - return serialized>( - webcpp::crypto::detail::secp256k1_compressed); + return serialized>(); } /** @@ -1250,8 +994,7 @@ class public_key { [[nodiscard]] std::array> uncompressed() const noexcept { secure::timing_guard const timing_scope; - return serialized>( - webcpp::crypto::detail::secp256k1_uncompressed); + return serialized>(); } /** @@ -1263,10 +1006,9 @@ class public_key { */ [[nodiscard]] xonly_public_key xonly() const noexcept { secure::timing_guard const timing_scope; - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); - secp256k1_selftest(); - return webcpp::crypto::detail::secp256k1_access::make_xonly_public_key( - webcpp::crypto::detail::secp256k1_xonly_of(point_value_)); + webcpp::crypto::detail::secp256k1_xonly_point xonly_key{}; + webcpp::crypto::detail::secp256k1_point_engine::to_xonly(point_value_, xonly_key); + return webcpp::crypto::detail::secp256k1_access::make_xonly_public_key(xonly_key); } /** @@ -1430,38 +1172,30 @@ class public_key { public_key() noexcept = default; /** - * The key in the SEC1 form `encoding_flags` names, with libsecp256k1's static context. + * The key in the SEC1 form of `N` bytes. * * @tparam N The form's size, 33 or 65. - * @param encoding_flags libsecp256k1's flag of the form. * @return `N` bytes. */ template - [[nodiscard]] std::array serialized(unsigned encoding_flags) const noexcept { - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); - secp256k1_selftest(); + [[nodiscard]] std::array serialized() const noexcept { std::array output_bytes{}; - std::size_t written_size = output_bytes.size(); - secp256k1_ec_pubkey_serialize(secp256k1_context_static, output_bytes.data(), &written_size, - &point_value_, encoding_flags); + webcpp::crypto::detail::secp256k1_point_engine::serialize(point_value_, output_bytes); return output_bytes; } /** - * libsecp256k1's comparison of two keys with the static context, which reads both as - * compressed encodings. Both are valid points: no key is made otherwise, so the illegal - * callback is never reached. + * The engine's comparison of two keys, which reads both as compressed encodings. * * @return Negative, zero or positive, as `memcmp`. */ [[nodiscard]] static int compare(public_key const& left_key, public_key const& right_key) noexcept { - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); - return secp256k1_ec_pubkey_cmp(secp256k1_context_static, &left_key.point_value_, - &right_key.point_value_); + return webcpp::crypto::detail::secp256k1_point_engine::compare(left_key.point_value_, + right_key.point_value_); } - secp256k1_pubkey point_value_{}; + webcpp::crypto::detail::secp256k1_point point_value_{}; }; /** @@ -1511,10 +1245,8 @@ class basic_keypair { if (secret_bytes.size() != secret_key_size) { return error::invalid_key_size; } - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); - secp256k1_selftest(); - if (!webcpp::crypto::detail::secp256k1_accepted( - secp256k1_ec_seckey_verify(secp256k1_context_static, secret_bytes.data()))) { + auto const checked_secret = secret_bytes.first(); + if (!key_engine::valid_secret(checked_secret)) { return error::invalid_secret_key; } webcpp::crypto::detail::secp256k1_secret context_seed; @@ -1525,14 +1257,11 @@ class basic_keypair { } basic_keypair made_object; made_object.memory_ = memory_resource; - made_object.context_ = secp256k1_context_preallocated_create( - memory_resource->allocate(context_size(), alignof(std::max_align_t)), - webcpp::crypto::detail::secp256k1_context_flags); - bool const context_randomised = webcpp::crypto::detail::secp256k1_accepted( - secp256k1_context_randomize(made_object.context_, context_seed.bytes.data())); - if (!context_randomised || - !webcpp::crypto::detail::secp256k1_accepted(secp256k1_keypair_create( - made_object.context_, &made_object.keypair_, secret_bytes.data()))) { + // The one allocation, the public layer's (design D2): an engine never allocates. + made_object.storage_ = + memory_resource->allocate(key_engine::context_size(), alignof(std::max_align_t)); + if (!key_engine::start(made_object.state_, made_object.storage_, context_seed.bytes) || + !key_engine::import_secret(made_object.state_, checked_secret)) { return error::backend_failure; } made_object.keyed_ = true; @@ -1576,11 +1305,10 @@ class basic_keypair { * @param moved_source The source, empty afterwards. */ basic_keypair(basic_keypair&& moved_source) noexcept - : context_(std::exchange(moved_source.context_, nullptr)), - memory_(moved_source.memory_), - keypair_(moved_source.keypair_), + : memory_(moved_source.memory_), + storage_(std::exchange(moved_source.storage_, nullptr)), keyed_(std::exchange(moved_source.keyed_, false)) { - secure::erase_secret(std::span(&moved_source.keypair_, 1)); + key_engine::move(state_, moved_source.state_); } /** @@ -1592,11 +1320,10 @@ class basic_keypair { basic_keypair& operator=(basic_keypair&& moved_source) noexcept { if (this != &moved_source) { release(); - context_ = std::exchange(moved_source.context_, nullptr); memory_ = moved_source.memory_; - keypair_ = moved_source.keypair_; + storage_ = std::exchange(moved_source.storage_, nullptr); keyed_ = std::exchange(moved_source.keyed_, false); - secure::erase_secret(std::span(&moved_source.keypair_, 1)); + key_engine::move(state_, moved_source.state_); } return *this; } @@ -1620,11 +1347,9 @@ class basic_keypair { if (!keyed_) { return error::invalid_state; } - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); using access = webcpp::crypto::detail::secp256k1_access; public_key_type made_key = access::make_public_key(); - access::point(made_key) = - webcpp::crypto::detail::secp256k1_public_point(context_, keypair_); + key_engine::public_point(state_, access::point(made_key)); return made_key; } @@ -1639,8 +1364,10 @@ class basic_keypair { if (!keyed_) { return error::invalid_state; } - return webcpp::crypto::detail::secp256k1_access::make_xonly_public_key( - xonly_of_pair().first); + webcpp::crypto::detail::secp256k1_xonly_point xonly_key{}; + int key_parity = 0; + key_engine::xonly_key(state_, xonly_key, key_parity); + return webcpp::crypto::detail::secp256k1_access::make_xonly_public_key(xonly_key); } /** @@ -1654,7 +1381,10 @@ class basic_keypair { if (!keyed_) { return error::invalid_state; } - return xonly_of_pair().second; + webcpp::crypto::detail::secp256k1_xonly_point xonly_key{}; + int key_parity = 0; + key_engine::xonly_key(state_, xonly_key, key_parity); + return key_parity; } /** @@ -1668,10 +1398,11 @@ class basic_keypair { if (!keyed_) { return error::invalid_state; } - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); secure::secret secret_key; - // libsecp256k1 returns 1 always: a key pair holds its secret key. - static_cast(secp256k1_keypair_sec(context_, secret_key.writable().data(), &keypair_)); + if (auto const exported = key_engine::export_secret(state_, secret_key.writable()); + !exported) { + return exported.error(); + } return secret_key; } @@ -1786,8 +1517,7 @@ class basic_keypair { } else if constexpr (std::is_same_v) { return signed_schnorr_drawn(detail::message_bytes(signing_input)); } else if constexpr (std::is_same_v) { - return signed_ecdsa(webcpp::crypto::detail::secp256k1_digest(signing_input), - nullptr); + return signed_ecdsa(webcpp::crypto::detail::secp256k1_digest(signing_input), {}); } else if constexpr (std::is_same_v) { return signed_recoverable(webcpp::crypto::detail::secp256k1_digest(signing_input)); @@ -1824,7 +1554,7 @@ class basic_keypair { 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), - nonce_data.bytes.data()); + nonce_data.bytes); } else { // Never compiled into a program: check_input stopped the build. return error::backend_failure; @@ -1871,8 +1601,17 @@ class basic_keypair { [[nodiscard]] boost::system::result> agree( public_key_type const& peer_key) const noexcept { secure::timing_guard const timing_scope; - return ecdh_secret<32>(peer_key, - webcpp::crypto::detail::webcpp_crypto_detail_secp256k1_copy_x); + if (!keyed_) { + return error::invalid_state; + } + secure::secret<32> shared_secret; + if (auto const agreed = webcpp::crypto::detail::secp256k1_ecdh_engine::shared_x( + state_, webcpp::crypto::detail::secp256k1_access::point(peer_key), + shared_secret.writable()); + !agreed) { + return agreed.error(); + } + return shared_secret; } /** @@ -1886,7 +1625,17 @@ class basic_keypair { [[nodiscard]] boost::system::result> agree_hashed( public_key_type const& peer_key) const noexcept { secure::timing_guard const timing_scope; - return ecdh_secret<32>(peer_key, nullptr); + if (!keyed_) { + return error::invalid_state; + } + secure::secret<32> shared_secret; + if (auto const agreed = webcpp::crypto::detail::secp256k1_ecdh_engine::shared_hashed( + state_, webcpp::crypto::detail::secp256k1_access::point(peer_key), + shared_secret.writable()); + !agreed) { + return agreed.error(); + } + return shared_secret; } /** @@ -1899,8 +1648,17 @@ class basic_keypair { [[nodiscard]] boost::system::result> agree_point( public_key_type const& peer_key) const noexcept { secure::timing_guard const timing_scope; - return ecdh_secret<65>(peer_key, - webcpp::crypto::detail::webcpp_crypto_detail_secp256k1_copy_point); + if (!keyed_) { + return error::invalid_state; + } + secure::secret<65> shared_secret; + if (auto const agreed = webcpp::crypto::detail::secp256k1_ecdh_engine::shared_point( + state_, webcpp::crypto::detail::secp256k1_access::point(peer_key), + shared_secret.writable()); + !agreed) { + return agreed.error(); + } + return shared_secret; } /** @@ -1923,9 +1681,9 @@ class basic_keypair { if (!keyed_) { return error::invalid_state; } - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); - if (!webcpp::crypto::detail::secp256k1_accepted( - secp256k1_keypair_xonly_tweak_add(context_, &keypair_, tweak_bytes.data()))) { + using tweak_engine = webcpp::crypto::detail::secp256k1_engine_of< + webcpp::crypto::detail::backend::secp256k1_capabilities::tweak>; + if (!tweak_engine::key_xonly_add(state_, tweak_bytes)) { release(); return error::invalid_secret_key; } @@ -1935,52 +1693,30 @@ class basic_keypair { private: friend struct webcpp::crypto::detail::secp256k1_access; - basic_keypair() noexcept = default; + /** The engine of the key pair, on the family's one backend. */ + using key_engine = webcpp::crypto::detail::secp256k1_key_engine; - /** - * The key pair's x-only key and its parity (`secp256k1_keypair_xonly_pub`), marked public - * (`secure::declassify`), as `public_key()`'s point is; the caller holds the guard and has - * found the pair keyed. - * - * @return The x-only key and the parity of y. - */ - [[nodiscard]] std::pair xonly_of_pair() const noexcept { - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); - secp256k1_xonly_pubkey native_key{}; - int key_parity = 0; - // libsecp256k1 returns 1 always: a key pair holds its public key. - static_cast( - secp256k1_keypair_xonly_pub(context_, &native_key, &key_parity, &keypair_)); - secure::declassify(native_key); - secure::declassify(key_parity); - return {native_key, key_parity}; - } + basic_keypair() noexcept = default; /** - * An ECDSA signature with RFC 6979's nonce, `nonce_data` mixed in when it is not null. + * An ECDSA signature with RFC 6979's nonce, `extra_entropy` mixed in when it is not empty. * * @param message_hash The 32-byte hash signed. - * @param nonce_data 32 bytes of extra entropy, libsecp256k1's `ndata`, or null. + * @param extra_entropy Empty, or 32 bytes of extra entropy, libsecp256k1's `ndata`. * @return The signature, r then s, low-S; `invalid_state`; `backend_failure`. */ [[nodiscard]] boost::system::result signed_ecdsa( std::span message_hash, - unsigned char const* nonce_data) const noexcept { + std::span extra_entropy) const noexcept { if (!keyed_) { return error::invalid_state; } - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); - webcpp::crypto::detail::secp256k1_secret secret_bytes; - secp256k1_keypair_sec(context_, secret_bytes.bytes.data(), &keypair_); - secp256k1_ecdsa_signature signature_bytes{}; std::array output_bytes{}; - if (!webcpp::crypto::detail::secp256k1_accepted( - secp256k1_ecdsa_sign(context_, &signature_bytes, message_hash.data(), - secret_bytes.bytes.data(), nullptr, nonce_data))) { - return error::backend_failure; + if (auto const signed_result = webcpp::crypto::detail::secp256k1_ecdsa_engine::sign( + state_, message_hash, extra_entropy, output_bytes); + !signed_result) { + return signed_result.error(); } - secp256k1_ecdsa_signature_serialize_compact(context_, output_bytes.data(), - &signature_bytes); return webcpp::crypto::detail::signature_access::of(output_bytes); } @@ -1996,20 +1732,12 @@ class basic_keypair { if (!keyed_) { return error::invalid_state; } - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); - webcpp::crypto::detail::secp256k1_secret secret_bytes; - secp256k1_keypair_sec(context_, secret_bytes.bytes.data(), &keypair_); - secp256k1_ecdsa_recoverable_signature signature_value{}; - if (!webcpp::crypto::detail::secp256k1_accepted( - secp256k1_ecdsa_sign_recoverable(context_, &signature_value, message_hash.data(), - secret_bytes.bytes.data(), nullptr, nullptr))) { - return error::backend_failure; - } std::array output_bytes{}; - int recovery_id = 0; - secp256k1_ecdsa_recoverable_signature_serialize_compact(context_, output_bytes.data(), - &recovery_id, &signature_value); - output_bytes[64] = static_cast(recovery_id); + if (auto const signed_result = webcpp::crypto::detail::secp256k1_recoverable_engine::sign( + state_, message_hash, output_bytes); + !signed_result) { + return signed_result.error(); + } return webcpp::crypto::detail::signature_access::of(output_bytes); } @@ -2039,18 +1767,15 @@ class basic_keypair { */ [[nodiscard]] boost::system::result signed_schnorr( std::span message_bytes, - webcpp::crypto::detail::secp256k1_secret& auxiliary_randomness) const noexcept { + webcpp::crypto::detail::secp256k1_secret const& auxiliary_randomness) const noexcept { if (!keyed_) { return error::invalid_state; } - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); - secp256k1_schnorrsig_extraparams extra_parameters = SECP256K1_SCHNORRSIG_EXTRAPARAMS_INIT; - extra_parameters.ndata = auxiliary_randomness.bytes.data(); std::array output_bytes{}; - if (!webcpp::crypto::detail::secp256k1_accepted(secp256k1_schnorrsig_sign_custom( - context_, output_bytes.data(), message_bytes.data(), message_bytes.size(), - &keypair_, &extra_parameters))) { - return error::backend_failure; + if (auto const signed_result = webcpp::crypto::detail::secp256k1_schnorr_engine::sign( + state_, message_bytes, auxiliary_randomness.bytes, output_bytes); + !signed_result) { + return signed_result.error(); } return webcpp::crypto::detail::signature_access::of(output_bytes); } @@ -2078,52 +1803,23 @@ class basic_keypair { } /** - * ECDH with a peer's public key, its output written by `hash_function` into the secret: - * libsecp256k1's SHA-256 when it is null. The worker of `agree`, `agree_hashed` and - * `agree_point`, which hold the guard. - * - * @tparam N The output's size, which `hash_function` writes. - * @param peer_key The peer's public key. - * @param hash_function libsecp256k1's hash function, or null for its default. - * @return `N` secret bytes; `invalid_state`; `backend_failure`. + * Wipes the key, destroys the context through the engine, and gives the context's storage + * back to its resource. */ - template - [[nodiscard]] boost::system::result> ecdh_secret( - public_key_type const& peer_key, - secp256k1_ecdh_hash_function hash_function) const noexcept { - if (!keyed_) { - return error::invalid_state; - } - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); - webcpp::crypto::detail::secp256k1_secret secret_bytes; - secp256k1_keypair_sec(context_, secret_bytes.bytes.data(), &keypair_); - secure::secret shared_secret; - if (!webcpp::crypto::detail::secp256k1_accepted( - secp256k1_ecdh(context_, shared_secret.writable().data(), - &webcpp::crypto::detail::secp256k1_access::point(peer_key), - secret_bytes.bytes.data(), hash_function, nullptr))) { - return error::backend_failure; - } - return shared_secret; - } - - static std::size_t context_size() noexcept { - return secp256k1_context_preallocated_size(webcpp::crypto::detail::secp256k1_context_flags); - } - void release() noexcept { - secure::erase_secret(std::span(&keypair_, 1)); + key_engine::reset(state_); keyed_ = false; - if (context_ != nullptr) { - secp256k1_context_preallocated_destroy(context_); - memory_->deallocate(context_, context_size(), alignof(std::max_align_t)); - context_ = nullptr; + if (storage_ != nullptr) { + memory_->deallocate(storage_, key_engine::context_size(), alignof(std::max_align_t)); + storage_ = nullptr; } } - secp256k1_context* context_ = nullptr; + // The resource first, then the engine's state (its context's pointer, then libsecp256k1's key + // pair), as the wipe test reads the key pair's offset. std::pmr::memory_resource* memory_ = nullptr; - secp256k1_keypair keypair_{}; + key_engine::state state_{}; + void* storage_ = nullptr; bool keyed_ = false; }; @@ -2141,24 +1837,17 @@ inline bool secp256k1_access::keyed( } template -inline secp256k1_context const* secp256k1_access::context( - curves::secp256k1::basic_keypair const& key_pair) noexcept { - return key_pair.context_; -} - -template -inline secp256k1_keypair const& secp256k1_access::pair( +inline secp256k1_key_engine::state const& secp256k1_access::key_state( curves::secp256k1::basic_keypair const& key_pair) noexcept { - return key_pair.keypair_; + return key_pair.state_; } -inline secp256k1_pubkey const& secp256k1_access::point( +inline secp256k1_point const& secp256k1_access::point( curves::secp256k1::public_key const& typed_key) noexcept { return typed_key.point_value_; } -inline secp256k1_pubkey& secp256k1_access::point( - curves::secp256k1::public_key& typed_key) noexcept { +inline secp256k1_point& secp256k1_access::point(curves::secp256k1::public_key& typed_key) noexcept { return typed_key.point_value_; } @@ -2167,7 +1856,7 @@ inline curves::secp256k1::public_key secp256k1_access::make_public_key() noexcep } inline curves::secp256k1::xonly_public_key secp256k1_access::make_xonly_public_key( - secp256k1_xonly_pubkey const& native_key) noexcept { + secp256k1_xonly_point const& native_key) noexcept { return curves::secp256k1::xonly_public_key(native_key); } @@ -2188,22 +1877,17 @@ inline curves::secp256k1::xonly_public_key secp256k1_access::make_xonly_public_k [[nodiscard]] inline boost::system::result secp256k1_recovered( std::array const& signature_bytes, std::span message_hash) noexcept { - read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); - // libsecp256k1 checks the id with ARG_CHECK, whose callback aborts: refused first here. - int const recovery_id = signature_bytes[curves::secp256k1::recoverable_signature_size - 1]; - if (recovery_id > 3) { + // libsecp256k1 checks the id with ARG_CHECK, whose callback aborts: refused first here, and + // again by the engine. + if (signature_bytes[curves::secp256k1::recoverable_signature_size - 1] > 3) { return error::invalid_signature; } - secp256k1_selftest(); - if (!secp256k1_low_s_verdict(std::span(signature_bytes).first<64>())) { + if (!secp256k1_ecdsa_engine::is_low_s(std::span(signature_bytes).first<64>())) { 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( - secp256k1_context_static, &parsed_value, signature_bytes.data(), recovery_id) == 0 || - secp256k1_ecdsa_recover(secp256k1_context_static, &secp256k1_access::point(recovered_key), - &parsed_value, message_hash.data()) == 0) { + if (!secp256k1_recoverable_engine::recover(signature_bytes, message_hash, + secp256k1_access::point(recovered_key))) { return error::invalid_signature; } return recovered_key; diff --git a/include/webcpp/crypto/curves/secp256k1/ellswift.hpp b/include/webcpp/crypto/curves/secp256k1/ellswift.hpp index d004a98..5ec20b9 100644 --- a/include/webcpp/crypto/curves/secp256k1/ellswift.hpp +++ b/include/webcpp/crypto/curves/secp256k1/ellswift.hpp @@ -44,6 +44,9 @@ struct secp256k1_refusal { WEBCPP_CRYPTO_DETAIL_REFUSE_SECP256K1_ELLSWIFT(Backend); }; +/** The engine of ElligatorSwift (design D8). */ +using secp256k1_ellswift_engine = secp256k1_engine_of; + } // namespace webcpp::crypto::detail namespace webcpp::crypto::curves::secp256k1 { @@ -77,13 +80,9 @@ template > 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(); std::array encoded_key{}; - // libsecp256k1 returns 1 always: every valid point has encodings. - static_cast(secp256k1_ellswift_encode( - secp256k1_context_static, encoded_key.data(), - &webcpp::crypto::detail::secp256k1_access::point(parsed_key), randomness_bytes.data())); + webcpp::crypto::detail::secp256k1_ellswift_engine::encode( + webcpp::crypto::detail::secp256k1_access::point(parsed_key), randomness_bytes, encoded_key); return encoded_key; } @@ -100,13 +99,10 @@ template > 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(); using access = webcpp::crypto::detail::secp256k1_access; public_key decoded_key = access::make_public_key(); - // libsecp256k1 returns 1 always: ElligatorSwift maps every 64 bytes to a point. - static_cast(secp256k1_ellswift_decode(secp256k1_context_static, - &access::point(decoded_key), encoded_key.data())); + webcpp::crypto::detail::secp256k1_ellswift_engine::decode(encoded_key, + access::point(decoded_key)); return decoded_key; } @@ -127,20 +123,15 @@ template secure::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); using access = webcpp::crypto::detail::secp256k1_access; if (!access::keyed(key_pair)) { return error::invalid_state; } - webcpp::crypto::detail::secp256k1_secret native_secret; - secp256k1_keypair_sec(access::context(key_pair), native_secret.bytes.data(), - &access::pair(key_pair)); std::array encoded_key{}; - // The key pair's secret is valid: libsecp256k1 refuses only one that is not. - if (!webcpp::crypto::detail::secp256k1_accepted( - secp256k1_ellswift_create(access::context(key_pair), encoded_key.data(), - native_secret.bytes.data(), randomness_bytes.data()))) { - return error::backend_failure; + if (auto const created = webcpp::crypto::detail::secp256k1_ellswift_engine::create( + access::key_state(key_pair), randomness_bytes, encoded_key); + !created) { + return created.error(); } return encoded_key; } @@ -169,21 +160,16 @@ template secure::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); using access = webcpp::crypto::detail::secp256k1_access; if (!access::keyed(key_pair)) { return error::invalid_state; } - webcpp::crypto::detail::secp256k1_secret native_secret; - secp256k1_keypair_sec(access::context(key_pair), native_secret.bytes.data(), - &access::pair(key_pair)); secure::secret<32> shared_secret; - // The secret is valid and BIP 324's hash never fails: libsecp256k1 returns 1. - if (!webcpp::crypto::detail::secp256k1_accepted(secp256k1_ellswift_xdh( - access::context(key_pair), shared_secret.writable().data(), initiator_encoding.data(), - responder_encoding.data(), native_secret.bytes.data(), static_cast(our_party), - secp256k1_ellswift_xdh_hash_function_bip324, nullptr))) { - return error::backend_failure; + if (auto const agreed = webcpp::crypto::detail::secp256k1_ellswift_engine::xdh( + access::key_state(key_pair), initiator_encoding, responder_encoding, + our_party == ellswift_party::responder, shared_secret.writable()); + !agreed) { + return agreed.error(); } return shared_secret; } diff --git a/include/webcpp/crypto/curves/secp256k1/formats.hpp b/include/webcpp/crypto/curves/secp256k1/formats.hpp index 87ab231..8720bbb 100644 --- a/include/webcpp/crypto/curves/secp256k1/formats.hpp +++ b/include/webcpp/crypto/curves/secp256k1/formats.hpp @@ -968,23 +968,19 @@ struct value_codec); - crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); - secp256k1_selftest(); std::span const signature_bytes(signature.bytes()); // The value's fault before the size's, as codecs orders an encode's faults. - secp256k1_ecdsa_signature parsed_value{}; - if (!crypto::detail::secp256k1_parse_compact(signature_bytes, parsed_value)) { + std::array der_bytes{}; + std::size_t written_size = 0; + if (!crypto::detail::secp256k1_ecdsa_engine::to_der(signature_bytes, der_bytes, + written_size)) { return crypto::error::invalid_signature; } std::size_t const der_size = crypto::detail::secp256k1_der_size_of(signature_bytes); if (output_bytes.size() < der_size) { return error::output_too_small; } - std::array der_bytes{}; - std::size_t written_size = der_bytes.size(); - if (secp256k1_ecdsa_signature_serialize_der(secp256k1_context_static, der_bytes.data(), - &written_size, &parsed_value) == 0 || - written_size != der_size) { + if (written_size != der_size) { return crypto::error::backend_failure; // strict DER has one size: never reached } std::ranges::copy(std::span(der_bytes).first(der_size), @@ -1011,13 +1007,8 @@ struct value_codec max_decode_input_size) { return crypto::error::invalid_signature; } - crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); - secp256k1_selftest(); - secp256k1_ecdsa_signature parsed_value{}; std::array signature_bytes{}; - if (secp256k1_ecdsa_signature_parse_der(secp256k1_context_static, &parsed_value, - input_bytes.data(), input_bytes.size()) == 0 || - !crypto::detail::secp256k1_compact_of(parsed_value, signature_bytes)) { + if (!crypto::detail::secp256k1_ecdsa_engine::from_der(input_bytes, signature_bytes)) { return crypto::error::invalid_signature; } return crypto::detail::signature_access::of( diff --git a/include/webcpp/crypto/curves/secp256k1/musig.hpp b/include/webcpp/crypto/curves/secp256k1/musig.hpp index c1578d0..45d789a 100644 --- a/include/webcpp/crypto/curves/secp256k1/musig.hpp +++ b/include/webcpp/crypto/curves/secp256k1/musig.hpp @@ -37,13 +37,16 @@ namespace webcpp::crypto::detail { +/** The engine of MuSig2 (design D8). */ +using secp256k1_musig_engine = secp256k1_engine_of; + /** - * What a MuSig2 secret nonce holds: libsecp256k1's secret nonce first, then the compressed key + * What a MuSig2 secret nonce holds: the engine's secret nonce first, then the compressed key * of the key pair it was made for, and whether it may still sign. */ struct secp256k1_nonce_state { - /** libsecp256k1's secret nonce: its magic, two secret scalars and the signer's point. */ - secp256k1_musig_secnonce nonce_value{}; + /** The engine's secret nonce: its magic, two secret scalars and the signer's point. */ + secp256k1_musig_engine::secret_nonce nonce_value{}; /** The signer's public key, SEC1 compressed, public. */ std::array signer_key{}; /** True from `generate_nonce` until a partial signature, a move or the destructor uses it. */ @@ -93,10 +96,9 @@ class aggregate_key { */ [[nodiscard]] xonly_public_key_type xonly_public_key() const noexcept { secure::timing_guard const timing_scope; - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); - secp256k1_selftest(); - return webcpp::crypto::detail::secp256k1_access::make_xonly_public_key( - webcpp::crypto::detail::secp256k1_xonly_of(full_point())); + webcpp::crypto::detail::secp256k1_xonly_point xonly_key{}; + webcpp::crypto::detail::secp256k1_point_engine::to_xonly(full_point(), xonly_key); + return webcpp::crypto::detail::secp256k1_access::make_xonly_public_key(xonly_key); } /** @@ -106,8 +108,6 @@ class aggregate_key { */ [[nodiscard]] public_key full_public_key() const noexcept { secure::timing_guard const timing_scope; - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); - secp256k1_selftest(); using access = webcpp::crypto::detail::secp256k1_access; public_key full_key = access::make_public_key(); access::point(full_key) = full_point(); @@ -125,7 +125,11 @@ class aggregate_key { [[nodiscard]] boost::system::result tweak_add( std::span tweak_bytes) noexcept { secure::timing_guard const timing_scope; - return tweaked(tweak_bytes, secp256k1_musig_pubkey_ec_tweak_add); + if (!webcpp::crypto::detail::secp256k1_musig_engine::tweak_add(native_value_, + tweak_bytes)) { + return error::invalid_secret_key; + } + return {}; } /** @@ -139,7 +143,11 @@ class aggregate_key { [[nodiscard]] boost::system::result tweak_xonly_add( std::span tweak_bytes) noexcept { secure::timing_guard const timing_scope; - return tweaked(tweak_bytes, secp256k1_musig_pubkey_xonly_tweak_add); + if (!webcpp::crypto::detail::secp256k1_musig_engine::tweak_xonly_add(native_value_, + tweak_bytes)) { + return error::invalid_secret_key; + } + return {}; } private: @@ -148,42 +156,18 @@ class aggregate_key { aggregate_key() noexcept = default; /** - * The aggregate as libsecp256k1's point (`secp256k1_musig_pubkey_get`), the work of both - * public keys' members, which hold the guard, read the canary and run the self-test. + * The aggregate as the engines' point (`secp256k1_musig_pubkey_get`), the work of both public + * keys' members, which hold the guard. * * @return The point, the tweaks included. */ - [[nodiscard]] secp256k1_pubkey full_point() const noexcept { - secp256k1_pubkey point_value{}; - // The cache is valid, made by key_aggregate: libsecp256k1 returns 1. The status is named - // and dropped, since GCC's warn_unused_result does not yield to a cast to void. - int const get_status = - secp256k1_musig_pubkey_get(secp256k1_context_static, &point_value, &native_value_); - static_cast(get_status); + [[nodiscard]] webcpp::crypto::detail::secp256k1_point full_point() const noexcept { + webcpp::crypto::detail::secp256k1_point point_value{}; + webcpp::crypto::detail::secp256k1_musig_engine::aggregate_point(native_value_, point_value); return point_value; } - /** - * The cache tweaked by libsecp256k1, which leaves it as it was when it refuses. - * - * @param tweak_bytes The 32-byte tweak. - * @param tweak_function libsecp256k1's plain or x-only tweak. - * @return Nothing; `invalid_secret_key`. - */ - [[nodiscard]] boost::system::result tweaked( - std::span tweak_bytes, - int (*tweak_function)(secp256k1_context const*, secp256k1_pubkey*, - secp256k1_musig_keyagg_cache*, unsigned char const*)) noexcept { - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); - secp256k1_selftest(); - if (tweak_function(secp256k1_context_static, nullptr, &native_value_, tweak_bytes.data()) == - 0) { - return error::invalid_secret_key; - } - return {}; - } - - secp256k1_musig_keyagg_cache native_value_{}; + webcpp::crypto::detail::secp256k1_musig_engine::key_cache native_value_{}; }; /** @@ -196,7 +180,7 @@ class public_nonce { public_nonce() noexcept = default; - secp256k1_musig_pubnonce native_value_{}; + webcpp::crypto::detail::secp256k1_musig_engine::public_nonce native_value_{}; }; /** @@ -209,7 +193,7 @@ class aggregate_nonce { aggregate_nonce() noexcept = default; - secp256k1_musig_aggnonce native_value_{}; + webcpp::crypto::detail::secp256k1_musig_engine::aggregate_nonce native_value_{}; }; /** @@ -222,7 +206,7 @@ class session { session() noexcept = default; - secp256k1_musig_session native_value_{}; + webcpp::crypto::detail::secp256k1_musig_engine::session native_value_{}; }; /** @@ -235,7 +219,7 @@ class partial_signature { partial_signature() noexcept = default; - secp256k1_musig_partial_sig native_value_{}; + webcpp::crypto::detail::secp256k1_musig_engine::partial_signature native_value_{}; }; /** @@ -328,16 +312,15 @@ template > secure::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); // The carver first: it wipes the workspace on every return, a refusal's included. webcpp::crypto::detail::secp256k1_workspace pointer_carver(pointer_space); // libsecp256k1 checks the count with ARG_CHECK, whose callback aborts: refused first here. if (signer_keys.empty() || pointer_space.size() < workspace_size(signer_keys.size())) { return error::invalid_input_size; } - secp256k1_selftest(); using access = webcpp::crypto::detail::secp256k1_access; - auto* const key_pointers = pointer_carver.take(signer_keys.size()); + auto* const key_pointers = + pointer_carver.take(signer_keys.size()); if (key_pointers == nullptr) { return error::invalid_input_size; } @@ -345,9 +328,8 @@ template > key_pointers[key_index] = &access::point(signer_keys[key_index]); } auto aggregated_key = access::make_opaque(); - if (secp256k1_musig_pubkey_agg(secp256k1_context_static, nullptr, - &access::native(aggregated_key), key_pointers, - signer_keys.size()) == 0) { + if (!webcpp::crypto::detail::secp256k1_musig_engine::key_aggregate( + std::span(key_pointers, signer_keys.size()), access::native(aggregated_key))) { return error::backend_failure; } return aggregated_key; @@ -377,7 +359,6 @@ template secure::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); using access = webcpp::crypto::detail::secp256k1_access; if (!access::keyed(signer_pair)) { return error::invalid_state; @@ -393,25 +374,21 @@ template if (!entropy_drawn) { return webcpp::crypto::detail::secp256k1_seed_error(entropy_drawn.error()); } - webcpp::crypto::detail::secp256k1_secret secret_bytes; - secp256k1_keypair_sec(access::context(signer_pair), secret_bytes.bytes.data(), - &access::pair(signer_pair)); - secp256k1_pubkey const signer_point = webcpp::crypto::detail::secp256k1_public_point( - access::context(signer_pair), access::pair(signer_pair)); auto made_secret = access::make_opaque(); auto made_public = access::make_opaque(); auto& nonce_state = access::native(made_secret); - if (!webcpp::crypto::detail::secp256k1_accepted(secp256k1_musig_nonce_gen( - access::context(signer_pair), &nonce_state.nonce_value, &access::native(made_public), - session_randomness.bytes.data(), secret_bytes.bytes.data(), &signer_point, - message_hash.empty() ? nullptr : message_hash.data(), &access::native(signers_key), - extra_input.empty() ? nullptr : extra_input.data()))) { - return error::backend_failure; + if (auto const generated = webcpp::crypto::detail::secp256k1_musig_engine::nonce_generate( + access::key_state(signer_pair), session_randomness.bytes, message_hash, + access::native(signers_key), extra_input, nonce_state.nonce_value, + access::native(made_public)); + !generated) { + return generated.error(); + } + if (auto const signer_key = webcpp::crypto::detail::secp256k1_key_engine::public_key( + access::key_state(signer_pair), nonce_state.signer_key); + !signer_key) { + return signer_key.error(); } - std::size_t written_size = nonce_state.signer_key.size(); - secp256k1_ec_pubkey_serialize(secp256k1_context_static, nonce_state.signer_key.data(), - &written_size, &signer_point, - webcpp::crypto::detail::secp256k1_compressed); nonce_state.fresh = true; return nonce_pair{.secret_part = std::move(made_secret), .public_part = made_public}; } @@ -433,17 +410,16 @@ template > secure::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); // The carver first: it wipes the workspace on every return, a refusal's included. webcpp::crypto::detail::secp256k1_workspace pointer_carver(pointer_space); // libsecp256k1 checks the count with ARG_CHECK, whose callback aborts: refused first here. if (signer_nonces.empty() || pointer_space.size() < workspace_size(signer_nonces.size())) { return error::invalid_input_size; } - secp256k1_selftest(); using access = webcpp::crypto::detail::secp256k1_access; auto* const nonce_pointers = - pointer_carver.take(signer_nonces.size()); + pointer_carver.take( + signer_nonces.size()); if (nonce_pointers == nullptr) { return error::invalid_input_size; } @@ -451,8 +427,8 @@ template > nonce_pointers[nonce_index] = &access::native(signer_nonces[nonce_index]); } auto nonce_sum = access::make_opaque(); - if (secp256k1_musig_nonce_agg(secp256k1_context_static, &access::native(nonce_sum), - nonce_pointers, signer_nonces.size()) == 0) { + if (!webcpp::crypto::detail::secp256k1_musig_engine::nonce_aggregate( + std::span(nonce_pointers, signer_nonces.size()), access::native(nonce_sum))) { return error::backend_failure; } return nonce_sum; @@ -475,13 +451,11 @@ template > 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(); using access = webcpp::crypto::detail::secp256k1_access; auto signing_session = access::make_opaque(); - if (secp256k1_musig_nonce_process(secp256k1_context_static, &access::native(signing_session), - &access::native(nonce_sum), message_bytes.data(), - &access::native(signers_key)) == 0) { + if (!webcpp::crypto::detail::secp256k1_musig_engine::nonce_process( + access::native(nonce_sum), message_bytes, access::native(signers_key), + access::native(signing_session))) { return error::backend_failure; } return signing_session; @@ -506,7 +480,6 @@ template secure::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); using access = webcpp::crypto::detail::secp256k1_access; auto& nonce_state = access::native(signer_nonce); // libsecp256k1 checks a used nonce and the signer's key with ARG_CHECK, whose callback @@ -514,22 +487,19 @@ template if (!access::keyed(signer_pair) || !nonce_state.fresh) { return error::invalid_state; } - secp256k1_pubkey const signer_point = webcpp::crypto::detail::secp256k1_public_point( - access::context(signer_pair), access::pair(signer_pair)); std::array signer_key{}; - std::size_t written_size = signer_key.size(); - secp256k1_ec_pubkey_serialize(secp256k1_context_static, signer_key.data(), &written_size, - &signer_point, webcpp::crypto::detail::secp256k1_compressed); - if (signer_key != nonce_state.signer_key) { + if (!webcpp::crypto::detail::secp256k1_key_engine::public_key(access::key_state(signer_pair), + signer_key) || + signer_key != nonce_state.signer_key) { return error::invalid_state; } nonce_state.fresh = false; auto signature_part = access::make_opaque(); - if (!webcpp::crypto::detail::secp256k1_accepted(secp256k1_musig_partial_sign( - access::context(signer_pair), &access::native(signature_part), &nonce_state.nonce_value, - &access::pair(signer_pair), &access::native(signers_key), - &access::native(signing_session)))) { - return error::backend_failure; + if (auto const signed_part = webcpp::crypto::detail::secp256k1_musig_engine::partial_sign( + access::key_state(signer_pair), nonce_state.nonce_value, access::native(signers_key), + access::native(signing_session), access::native(signature_part)); + !signed_part) { + return signed_part.error(); } return signature_part; } @@ -554,13 +524,10 @@ template > 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(); using access = webcpp::crypto::detail::secp256k1_access; - if (secp256k1_musig_partial_sig_verify( - secp256k1_context_static, &access::native(signature_part), - &access::native(signer_nonce), &access::point(signer_key), &access::native(signers_key), - &access::native(signing_session)) == 0) { + if (!webcpp::crypto::detail::secp256k1_musig_engine::partial_verify( + access::native(signature_part), access::native(signer_nonce), access::point(signer_key), + access::native(signers_key), access::native(signing_session))) { return error::invalid_signature; } return {}; @@ -586,17 +553,17 @@ template > secure::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); // The carver first: it wipes the workspace on every return, a refusal's included. webcpp::crypto::detail::secp256k1_workspace pointer_carver(pointer_space); // libsecp256k1 checks the count with ARG_CHECK, whose callback aborts: refused first here. if (signature_parts.empty() || pointer_space.size() < workspace_size(signature_parts.size())) { return error::invalid_input_size; } - secp256k1_selftest(); using access = webcpp::crypto::detail::secp256k1_access; auto* const part_pointers = - pointer_carver.take(signature_parts.size()); + pointer_carver + .take( + signature_parts.size()); if (part_pointers == nullptr) { return error::invalid_input_size; } @@ -604,9 +571,9 @@ template > part_pointers[part_index] = &access::native(signature_parts[part_index]); } std::array output_bytes{}; - if (secp256k1_musig_partial_sig_agg(secp256k1_context_static, output_bytes.data(), - &access::native(signing_session), part_pointers, - signature_parts.size()) == 0) { + if (!webcpp::crypto::detail::secp256k1_musig_engine::partial_aggregate( + access::native(signing_session), std::span(part_pointers, signature_parts.size()), + output_bytes)) { return error::backend_failure; } return webcpp::crypto::detail::signature_access::of(output_bytes); @@ -626,15 +593,13 @@ template > secure::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); if (encoded_nonce.size() != public_nonce_size) { return error::invalid_input_size; } - secp256k1_selftest(); using access = webcpp::crypto::detail::secp256k1_access; auto parsed_nonce = access::make_opaque(); - if (secp256k1_musig_pubnonce_parse(secp256k1_context_static, &access::native(parsed_nonce), - encoded_nonce.data()) == 0) { + if (!webcpp::crypto::detail::secp256k1_musig_engine::parse( + encoded_nonce.first(), access::native(parsed_nonce))) { return error::invalid_point; } return parsed_nonce; @@ -653,13 +618,9 @@ template > 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(); std::array output_bytes{}; - // A parsed or made nonce always serialises: libsecp256k1 returns 1. - static_cast(secp256k1_musig_pubnonce_serialize( - secp256k1_context_static, output_bytes.data(), - &webcpp::crypto::detail::secp256k1_access::native(parsed_nonce))); + webcpp::crypto::detail::secp256k1_musig_engine::serialize( + webcpp::crypto::detail::secp256k1_access::native(parsed_nonce), output_bytes); return output_bytes; } @@ -678,15 +639,13 @@ template > secure::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); if (encoded_nonce.size() != aggregate_nonce_size) { return error::invalid_input_size; } - secp256k1_selftest(); using access = webcpp::crypto::detail::secp256k1_access; auto parsed_nonce = access::make_opaque(); - if (secp256k1_musig_aggnonce_parse(secp256k1_context_static, &access::native(parsed_nonce), - encoded_nonce.data()) == 0) { + if (!webcpp::crypto::detail::secp256k1_musig_engine::parse( + encoded_nonce.first(), access::native(parsed_nonce))) { return error::invalid_point; } return parsed_nonce; @@ -705,13 +664,9 @@ template > 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(); std::array output_bytes{}; - // A parsed or summed nonce always serialises: libsecp256k1 returns 1. - static_cast(secp256k1_musig_aggnonce_serialize( - secp256k1_context_static, output_bytes.data(), - &webcpp::crypto::detail::secp256k1_access::native(parsed_nonce))); + webcpp::crypto::detail::secp256k1_musig_engine::serialize( + webcpp::crypto::detail::secp256k1_access::native(parsed_nonce), output_bytes); return output_bytes; } @@ -729,16 +684,13 @@ template > secure::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); if (encoded_signature.size() != partial_signature_size) { return error::invalid_input_size; } - secp256k1_selftest(); using access = webcpp::crypto::detail::secp256k1_access; auto parsed_signature = access::make_opaque(); - if (secp256k1_musig_partial_sig_parse(secp256k1_context_static, - &access::native(parsed_signature), - encoded_signature.data()) == 0) { + if (!webcpp::crypto::detail::secp256k1_musig_engine::parse( + encoded_signature.first(), access::native(parsed_signature))) { return error::invalid_signature; } return parsed_signature; @@ -757,13 +709,9 @@ template > 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(); std::array output_bytes{}; - // A parsed or made partial signature always serialises: libsecp256k1 returns 1. - static_cast(secp256k1_musig_partial_sig_serialize( - secp256k1_context_static, output_bytes.data(), - &webcpp::crypto::detail::secp256k1_access::native(parsed_signature))); + webcpp::crypto::detail::secp256k1_musig_engine::serialize( + webcpp::crypto::detail::secp256k1_access::native(parsed_signature), output_bytes); return output_bytes; } diff --git a/include/webcpp/crypto/curves/secp256k1/silent_payments.hpp b/include/webcpp/crypto/curves/secp256k1/silent_payments.hpp index 1d5278a..afafa2e 100644 --- a/include/webcpp/crypto/curves/secp256k1/silent_payments.hpp +++ b/include/webcpp/crypto/curves/secp256k1/silent_payments.hpp @@ -22,7 +22,6 @@ #include #include #include -#include #include #include @@ -50,16 +49,9 @@ struct secp256k1_refusal { WEBCPP_CRYPTO_DETAIL_REFUSE_SECP256K1_SILENT_PAYMENTS(Backend); }; -/** - * What `scan_outputs` gives libsecp256k1 as its label context: the caller's lookup, and the - * function that calls it, so that the C callback reaches a C++ callable of any type. - */ -struct secp256k1_label_context { - /** The caller's lookup, which outlives the scan. */ - void const* lookup_object; - /** Calls the lookup with a candidate label's 33 bytes: its tweak's 32 bytes, or null. */ - unsigned char const* (*call_lookup)(void const*, unsigned char const*) noexcept; -}; +/** The engine of silent payments (design D8). */ +using secp256k1_silent_payments_engine = + secp256k1_engine_of; /** * Calls a lookup of type `LabelLookup` with a candidate label. @@ -79,24 +71,6 @@ template return found_tweak ? found_tweak->data() : nullptr; } -extern "C" { - -/** - * libsecp256k1's label lookup callback, which reaches the caller's lookup through the - * `secp256k1_label_context` it is given. C linkage, as libsecp256k1's function pointer type has. - * - * @param label_bytes The candidate label's 33 bytes. - * @param label_context The `secp256k1_label_context`. - * @return The label's tweak, or null. - */ -inline unsigned char const* webcpp_crypto_detail_secp256k1_label_lookup( - unsigned char const* label_bytes, void const* label_context) noexcept { - auto const* const typed_context = static_cast(label_context); - return typed_context->call_lookup(typed_context->lookup_object, label_bytes); -} - -} // extern "C" - } // namespace webcpp::crypto::detail namespace webcpp::crypto::curves::secp256k1::silent_payments { @@ -105,7 +79,8 @@ namespace webcpp::crypto::curves::secp256k1::silent_payments { inline constexpr std::size_t outpoint_size = 36; /** The most outputs one scan key's group may hold (BIP 352's limit). */ -inline constexpr std::size_t group_limit = SECP256K1_SILENTPAYMENTS_RECIPIENT_GROUP_LIMIT; +inline constexpr std::size_t group_limit = + webcpp::crypto::detail::secp256k1_silent_payments_engine::group_limit; /** * A recipient as the sender reads it from the address: its scan and spend keys (decoding @@ -150,7 +125,7 @@ class previous_outputs_summary { previous_outputs_summary() noexcept = default; - secp256k1_silentpayments_prevouts_summary native_value_{}; + webcpp::crypto::detail::secp256k1_silent_payments_engine::summary native_value_{}; }; /** @@ -198,8 +173,9 @@ struct no_labels { [[nodiscard]] constexpr std::size_t send_workspace_size(std::size_t recipient_count, std::size_t taproot_input_count, std::size_t plain_input_count) noexcept { - return (recipient_count * (sizeof(secp256k1_silentpayments_recipient) + sizeof(void*) + - sizeof(secp256k1_xonly_pubkey) + sizeof(void*))) + + using engine = webcpp::crypto::detail::secp256k1_silent_payments_engine; + return (recipient_count * (sizeof(engine::recipient) + sizeof(void*) + + sizeof(engine::xonly_point) + sizeof(void*))) + (taproot_input_count * sizeof(void*)) + (plain_input_count * (32 + sizeof(void*))) + (7 * alignof(std::max_align_t)); } @@ -214,7 +190,8 @@ struct no_labels { */ [[nodiscard]] constexpr std::size_t summary_workspace_size(std::size_t taproot_input_count, std::size_t plain_input_count) noexcept { - return (taproot_input_count * (sizeof(secp256k1_xonly_pubkey) + sizeof(void*))) + + using engine = webcpp::crypto::detail::secp256k1_silent_payments_engine; + return (taproot_input_count * (sizeof(engine::xonly_point) + sizeof(void*))) + (plain_input_count * sizeof(void*)) + (3 * alignof(std::max_align_t)); } @@ -226,46 +203,14 @@ struct no_labels { * pointers, and one `alignof(std::max_align_t)` of padding per array. */ [[nodiscard]] constexpr std::size_t scan_workspace_size(std::size_t output_count) noexcept { - return (output_count * (sizeof(secp256k1_xonly_pubkey) + sizeof(void*) + - sizeof(secp256k1_silentpayments_found_output) + sizeof(void*))) + + using engine = webcpp::crypto::detail::secp256k1_silent_payments_engine; + return (output_count * (sizeof(engine::xonly_point) + sizeof(void*) + + sizeof(engine::found_output) + sizeof(void*))) + (4 * alignof(std::max_align_t)); } } // namespace webcpp::crypto::curves::secp256k1::silent_payments -namespace webcpp::crypto::detail { - -/** - * Whether more than `group_limit` recipients share one scan key, which libsecp256k1 refuses as - * it refuses a sum of zero. The recipients' pointers are sorted in place by scan key, as - * libsecp256k1 sorts them, and each run of one key is counted: O(n log n), nothing allocated. - * - * @param recipient_pointers The recipients' pointers, in the workspace. - * @return Whether a group is over the limit. - */ -[[nodiscard]] inline bool secp256k1_over_group_limit( - std::span recipient_pointers) noexcept { - auto const scan_key_order = [](secp256k1_silentpayments_recipient const* left_recipient, - secp256k1_silentpayments_recipient const* right_recipient) { - return secp256k1_ec_pubkey_cmp(secp256k1_context_static, &left_recipient->scan_pubkey, - &right_recipient->scan_pubkey) < 0; - }; - std::ranges::sort(recipient_pointers, scan_key_order); - std::size_t group_size = 0; - for (std::size_t item_index = 0; item_index < recipient_pointers.size(); ++item_index) { - bool const same_group = - item_index != 0 && - !scan_key_order(recipient_pointers[item_index - 1], recipient_pointers[item_index]); - group_size = same_group ? group_size + 1 : 1; - if (group_size > curves::secp256k1::silent_payments::group_limit) { - return true; - } - } - return false; -} - -} // namespace webcpp::crypto::detail - namespace webcpp::crypto::curves::secp256k1::silent_payments { /** @@ -306,7 +251,6 @@ template static_assert( webcpp::crypto::detail::secp256k1_refuses_others); - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); // The carver first: it wipes the workspace, the plain inputs' secrets in it, on every return. webcpp::crypto::detail::secp256k1_workspace pointer_carver(pointer_space); std::size_t const recipient_count = recipient_list.size(); @@ -327,14 +271,13 @@ template !std::ranges::all_of(plain_inputs, usable_input)) { return error::invalid_state; } - auto* const recipient_values = - pointer_carver.take(recipient_count); - auto* const recipient_pointers = - pointer_carver.take(recipient_count); - auto* const output_values = pointer_carver.take(recipient_count); - auto* const output_pointers = pointer_carver.take(recipient_count); + using engine = webcpp::crypto::detail::secp256k1_silent_payments_engine; + auto* const recipient_values = pointer_carver.take(recipient_count); + auto* const recipient_pointers = pointer_carver.take(recipient_count); + auto* const output_values = pointer_carver.take(recipient_count); + auto* const output_pointers = pointer_carver.take(recipient_count); // Arrays of no elements are nullptr, as libsecp256k1 requires of a side with no input. - auto* const taproot_pointers = pointer_carver.take(taproot_count); + auto* const taproot_pointers = pointer_carver.take(taproot_count); auto* const plain_secrets = pointer_carver.take>(plain_count); auto* const plain_pointers = pointer_carver.take(plain_count); if (recipient_values == nullptr || recipient_pointers == nullptr || output_values == nullptr || @@ -343,39 +286,39 @@ template return error::invalid_input_size; } for (std::size_t item_index = 0; item_index < recipient_count; ++item_index) { - recipient_values[item_index] = secp256k1_silentpayments_recipient{ - .scan_pubkey = access::point(recipient_list[item_index].scan_key), - .spend_pubkey = access::point(recipient_list[item_index].spend_key), - .index = item_index, - }; + engine::make_recipient(access::point(recipient_list[item_index].scan_key), + access::point(recipient_list[item_index].spend_key), item_index, + recipient_values[item_index]); recipient_pointers[item_index] = &recipient_values[item_index]; - output_values[item_index] = secp256k1_xonly_pubkey{}; + output_values[item_index] = engine::xonly_point{}; output_pointers[item_index] = &output_values[item_index]; } for (std::size_t item_index = 0; item_index < taproot_count; ++item_index) { - taproot_pointers[item_index] = &access::pair(*taproot_inputs[item_index]); + taproot_pointers[item_index] = + engine::key_handle_of(access::key_state(*taproot_inputs[item_index])); } for (std::size_t item_index = 0; item_index < plain_count; ++item_index) { - secp256k1_keypair_sec(access::context(*plain_inputs[item_index]), - plain_secrets[item_index].data(), - &access::pair(*plain_inputs[item_index])); + if (auto const exported = webcpp::crypto::detail::secp256k1_key_engine::export_secret( + access::key_state(*plain_inputs[item_index]), plain_secrets[item_index]); + !exported) { + return exported.error(); + } plain_pointers[item_index] = plain_secrets[item_index].data(); } auto const* const first_signer = taproot_count != 0 ? taproot_inputs[0] : plain_inputs[0]; - if (!webcpp::crypto::detail::secp256k1_accepted(secp256k1_silentpayments_sender_create_outputs( - access::context(*first_signer), output_pointers, recipient_pointers, recipient_count, - smallest_outpoint.data(), taproot_pointers, taproot_count, plain_pointers, - plain_count))) { - if (recipient_count > group_limit && webcpp::crypto::detail::secp256k1_over_group_limit( - std::span(recipient_pointers, recipient_count))) { + std::span const recipient_span(recipient_pointers, recipient_count); + if (!engine::create_outputs(access::key_state(*first_signer), + std::span(output_pointers, recipient_count), recipient_span, + smallest_outpoint, std::span(taproot_pointers, taproot_count), + std::span(plain_pointers, plain_count))) { + if (recipient_count > group_limit && engine::over_group_limit(recipient_span)) { return error::invalid_input_size; } return error::invalid_secret_key; } for (std::size_t item_index = 0; item_index < recipient_count; ++item_index) { - // A made output always serialises: libsecp256k1 returns 1. - static_cast(secp256k1_xonly_pubkey_serialize( - secp256k1_context_static, output_keys[item_index].data(), &output_values[item_index])); + webcpp::crypto::detail::secp256k1_point_engine::serialize_xonly(output_values[item_index], + output_keys[item_index]); } return {}; } @@ -400,27 +343,16 @@ template static_assert( webcpp::crypto::detail::secp256k1_refuses_others); - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); using access = webcpp::crypto::detail::secp256k1_access; if (!access::keyed(scan_key)) { return error::invalid_state; } - webcpp::crypto::detail::secp256k1_secret scan_secret; - secp256k1_keypair_sec(access::context(scan_key), scan_secret.bytes.data(), - &access::pair(scan_key)); - secp256k1_silentpayments_label made_label{}; label created_label{}; - if (!webcpp::crypto::detail::secp256k1_accepted(secp256k1_silentpayments_recipient_label_create( - access::context(scan_key), &made_label, created_label.tweak.data(), - scan_secret.bytes.data(), label_number))) { - return error::backend_failure; + if (auto const created = webcpp::crypto::detail::secp256k1_silent_payments_engine::create_label( + access::key_state(scan_key), label_number, created_label.point, created_label.tweak); + !created) { + return created.error(); } - // The label's point is public, the labelled address's part; libsecp256k1 made it from the - // scan key's secret, so it is marked public here (secure::declassify). A made label always - // serialises: libsecp256k1 returns 1. - secure::declassify(made_label); - static_cast(secp256k1_silentpayments_recipient_label_serialize( - secp256k1_context_static, created_label.point.data(), &made_label)); return created_label; } @@ -440,19 +372,13 @@ template static_assert( webcpp::crypto::detail::secp256k1_refuses_others); - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); - secp256k1_selftest(); using access = webcpp::crypto::detail::secp256k1_access; - secp256k1_silentpayments_label parsed_label{}; - if (secp256k1_silentpayments_recipient_label_parse(secp256k1_context_static, &parsed_label, - address_label.point.data()) == 0) { - return error::invalid_point; - } public_key labeled_key = access::make_public_key(); - if (secp256k1_silentpayments_recipient_create_labeled_spend_pubkey( - secp256k1_context_static, &access::point(labeled_key), &access::point(spend_key), - &parsed_label) == 0) { - return error::invalid_public_key; + if (auto const labeled = + webcpp::crypto::detail::secp256k1_silent_payments_engine::labeled_spend_key( + access::point(spend_key), address_label.point, access::point(labeled_key)); + !labeled) { + return labeled.error(); } return labeled_key; } @@ -481,7 +407,6 @@ template static_assert( webcpp::crypto::detail::secp256k1_refuses_others); - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); // The carver first: it wipes the workspace on every return, a refusal's included. webcpp::crypto::detail::secp256k1_workspace pointer_carver(pointer_space); std::size_t const taproot_count = taproot_input_keys.size(); @@ -491,19 +416,19 @@ template pointer_space.size() < summary_workspace_size(taproot_count, plain_count)) { return error::invalid_input_size; } - secp256k1_selftest(); using access = webcpp::crypto::detail::secp256k1_access; + using engine = webcpp::crypto::detail::secp256k1_silent_payments_engine; // Arrays of no elements are nullptr, as libsecp256k1 requires of a side with no input. - auto* const xonly_values = pointer_carver.take(taproot_count); - auto* const xonly_pointers = pointer_carver.take(taproot_count); - auto* const plain_pointers = pointer_carver.take(plain_count); + auto* const xonly_values = pointer_carver.take(taproot_count); + auto* const xonly_pointers = pointer_carver.take(taproot_count); + auto* const plain_pointers = pointer_carver.take(plain_count); if ((taproot_count != 0 && (xonly_values == nullptr || xonly_pointers == nullptr)) || (plain_count != 0 && plain_pointers == nullptr)) { return error::invalid_input_size; } for (std::size_t item_index = 0; item_index < taproot_count; ++item_index) { - if (secp256k1_xonly_pubkey_parse(secp256k1_context_static, &xonly_values[item_index], - taproot_input_keys[item_index].data()) == 0) { + if (!webcpp::crypto::detail::secp256k1_point_engine::parse_xonly( + taproot_input_keys[item_index], xonly_values[item_index])) { return error::invalid_public_key; } xonly_pointers[item_index] = &xonly_values[item_index]; @@ -512,9 +437,9 @@ template plain_pointers[item_index] = &access::point(plain_input_keys[item_index]); } auto made_summary = access::make_opaque(); - if (secp256k1_silentpayments_recipient_prevouts_summary_create( - secp256k1_context_static, &access::native(made_summary), smallest_outpoint.data(), - xonly_pointers, taproot_count, plain_pointers, plain_count) == 0) { + if (!engine::make_summary(smallest_outpoint, std::span(xonly_pointers, taproot_count), + std::span(plain_pointers, plain_count), + access::native(made_summary))) { return error::invalid_public_key; } return made_summary; @@ -556,7 +481,6 @@ template static_assert( webcpp::crypto::detail::secp256k1_refuses_others); - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); // The carver first: it wipes the workspace, the found tweaks in it, on every return. webcpp::crypto::detail::secp256k1_workspace pointer_carver(pointer_space); std::size_t const output_count = output_keys.size(); @@ -569,63 +493,53 @@ template if (!access::keyed(scan_key)) { return error::invalid_state; } - secp256k1_selftest(); - auto* const output_values = pointer_carver.take(output_count); - auto* const output_pointers = pointer_carver.take(output_count); - auto* const found_values = - pointer_carver.take(output_count); - auto* const found_pointers = - pointer_carver.take(output_count); + using engine = webcpp::crypto::detail::secp256k1_silent_payments_engine; + auto* const output_values = pointer_carver.take(output_count); + auto* const output_pointers = pointer_carver.take(output_count); + auto* const found_values = pointer_carver.take(output_count); + auto* const found_pointers = pointer_carver.take(output_count); if (output_values == nullptr || output_pointers == nullptr || found_values == nullptr || found_pointers == nullptr) { return error::invalid_input_size; } for (std::size_t item_index = 0; item_index < output_count; ++item_index) { - if (secp256k1_xonly_pubkey_parse(secp256k1_context_static, &output_values[item_index], - output_keys[item_index].data()) == 0) { + if (!webcpp::crypto::detail::secp256k1_point_engine::parse_xonly( + output_keys[item_index], output_values[item_index])) { return error::invalid_public_key; } output_pointers[item_index] = &output_values[item_index]; - found_values[item_index] = secp256k1_silentpayments_found_output{}; + found_values[item_index] = engine::found_output{}; found_pointers[item_index] = &found_values[item_index]; } - webcpp::crypto::detail::secp256k1_secret scan_secret; - secp256k1_keypair_sec(access::context(scan_key), scan_secret.bytes.data(), - &access::pair(scan_key)); std::uint32_t found_count = 0; - // The scan runs on the scan key pair's context, as a key pair's other functions do, so that - // libsecp256k1 marks its public values public under the constant-time checkers. - int scan_status = 0; + std::span const output_span(output_pointers, output_count); + std::span const found_span(found_pointers, output_count); + boost::system::result scanned; if constexpr (std::is_same_v) { - scan_status = secp256k1_silentpayments_recipient_scan_outputs( - access::context(scan_key), found_pointers, &found_count, output_pointers, output_count, - scan_secret.bytes.data(), &access::native(inputs_summary), &access::point(spend_key), - nullptr, nullptr); + scanned = + engine::scan(access::key_state(scan_key), access::native(inputs_summary), + access::point(spend_key), output_span, found_span, found_count, nullptr); } else { - webcpp::crypto::detail::secp256k1_label_context const lookup_context{ + engine::label_lookup const lookup_context{ .lookup_object = &label_lookup, .call_lookup = &webcpp::crypto::detail::secp256k1_call_label_lookup, }; - scan_status = secp256k1_silentpayments_recipient_scan_outputs( - access::context(scan_key), found_pointers, &found_count, output_pointers, output_count, - scan_secret.bytes.data(), &access::native(inputs_summary), &access::point(spend_key), - &webcpp::crypto::detail::webcpp_crypto_detail_secp256k1_label_lookup, &lookup_context); + scanned = engine::scan(access::key_state(scan_key), access::native(inputs_summary), + access::point(spend_key), output_span, found_span, found_count, + &lookup_context); } - if (!webcpp::crypto::detail::secp256k1_accepted(scan_status)) { - return error::backend_failure; + if (!scanned) { + return scanned.error(); } for (std::size_t item_index = 0; item_index < found_count; ++item_index) { auto const& found_value = *found_pointers[item_index]; auto& found_entry = found_outputs[item_index]; - // A found output and its label always serialise: libsecp256k1 returns 1. - static_cast(secp256k1_xonly_pubkey_serialize( - secp256k1_context_static, found_entry.output_key.data(), &found_value.output)); - std::ranges::copy(found_value.tweak, found_entry.spend_tweak.writable().begin()); + engine::found_output_key(found_value, found_entry.output_key); + std::ranges::copy(engine::found_tweak(found_value), + found_entry.spend_tweak.writable().begin()); found_entry.label_point.reset(); - if (found_value.found_with_label != 0) { - std::array label_bytes{}; - static_cast(secp256k1_silentpayments_recipient_label_serialize( - secp256k1_context_static, label_bytes.data(), &found_value.label)); + std::array label_bytes{}; + if (engine::found_label(found_value, label_bytes)) { found_entry.label_point = label_bytes; } } diff --git a/include/webcpp/crypto/curves/secp256k1/tweak.hpp b/include/webcpp/crypto/curves/secp256k1/tweak.hpp index f0fa34d..0d5284a 100644 --- a/include/webcpp/crypto/curves/secp256k1/tweak.hpp +++ b/include/webcpp/crypto/curves/secp256k1/tweak.hpp @@ -26,68 +26,47 @@ #include -#include #include #include #include namespace webcpp::crypto::detail { -/** The function libsecp256k1 runs on a secret key and a tweak: `secp256k1_ec_seckey_tweak_*`. */ -using secp256k1_seckey_tweak = int (*)(secp256k1_context const*, unsigned char*, - unsigned char const*); - -/** The function libsecp256k1 runs on a public key and a tweak: `secp256k1_ec_pubkey_tweak_*`. */ -using secp256k1_pubkey_tweak = int (*)(secp256k1_context const*, secp256k1_pubkey*, - unsigned char const*); +/** The engine of the tweaks and the sum of points (design D8). */ +using secp256k1_tweak_engine = secp256k1_engine_of; /** - * A secret key tweaked by libsecp256k1, computed in a wiped copy of the key and moved into the - * secret returned. + * A secret key tweaked by the engine (`secret_add`, `secret_mul` or `secret_negate`), written into + * the secret returned, which the engine writes only on success. * - * @param secret_key The 32-byte secret key. - * @param tweak_bytes The 32-byte tweak, or null for a negation. - * @param tweak_function libsecp256k1's tweak, used when `tweak_bytes` is not null. - * @return The secret; `invalid_secret_key` for a secret key zero or not below the group order, - * then for a tweak not below it or a result of zero. + * @tparam Tweak A callable that runs the engine's tweak into a 32-byte output. + * @param engine_tweak The tweak. + * @return The secret; the engine's `invalid_secret_key`. */ -[[nodiscard]] inline boost::system::result> secp256k1_tweaked_secret( - std::span secret_key, unsigned char const* tweak_bytes, - secp256k1_seckey_tweak tweak_function) noexcept { - // The key is checked first, so that a refusal names the input that was wrong. - if (!secp256k1_accepted( - secp256k1_ec_seckey_verify(secp256k1_context_static, secret_key.data()))) { - return error::invalid_secret_key; - } - secp256k1_secret working_copy; - std::ranges::copy(secret_key, working_copy.bytes.begin()); - int const tweak_status = - tweak_bytes == nullptr - ? secp256k1_ec_seckey_negate(secp256k1_context_static, working_copy.bytes.data()) - : tweak_function(secp256k1_context_static, working_copy.bytes.data(), tweak_bytes); - if (!secp256k1_accepted(tweak_status)) { - return error::invalid_secret_key; - } +template +[[nodiscard]] boost::system::result> secp256k1_tweaked_secret( + Tweak const& engine_tweak) noexcept { secure::secret<32> tweaked_secret; - std::ranges::copy(working_copy.bytes, tweaked_secret.writable().begin()); + if (auto const tweaked = engine_tweak(tweaked_secret.writable()); !tweaked) { + return tweaked.error(); + } return tweaked_secret; } /** - * A public key tweaked by libsecp256k1 on the static context. + * A public key tweaked by the engine's `point_add` or `point_mul`. * * @param parsed_key The key, valid. * @param tweak_bytes The 32-byte tweak. - * @param tweak_function libsecp256k1's tweak. + * @param tweak_function The engine's tweak. * @return The key; `invalid_secret_key` for a tweak not below the group order, a zero * multiplier, or a result at infinity. */ [[nodiscard]] inline boost::system::result secp256k1_tweaked_key( curves::secp256k1::public_key const& parsed_key, std::span tweak_bytes, - secp256k1_pubkey_tweak tweak_function) noexcept { + bool (*tweak_function)(secp256k1_point&, std::span) noexcept) noexcept { curves::secp256k1::public_key tweaked_key = parsed_key; - if (tweak_function(secp256k1_context_static, &secp256k1_access::point(tweaked_key), - tweak_bytes.data()) == 0) { + if (!tweak_function(secp256k1_access::point(tweaked_key), tweak_bytes)) { return error::invalid_secret_key; } return tweaked_key; @@ -104,7 +83,8 @@ namespace webcpp::crypto::curves::secp256k1 { * @return One pointer per key and one `alignof(std::max_align_t)` of padding. */ [[nodiscard]] constexpr std::size_t combine_workspace_size(std::size_t key_count) noexcept { - return (key_count * sizeof(secp256k1_pubkey const*)) + alignof(std::max_align_t); + return (key_count * sizeof(webcpp::crypto::detail::secp256k1_point const*)) + + alignof(std::max_align_t); } /** @@ -122,10 +102,11 @@ template > std::span tweak_bytes) 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(); - return webcpp::crypto::detail::secp256k1_tweaked_secret(secret_key, tweak_bytes.data(), - secp256k1_ec_seckey_tweak_add); + return webcpp::crypto::detail::secp256k1_tweaked_secret( + [&](std::span secret_output) noexcept { + return webcpp::crypto::detail::secp256k1_tweak_engine::secret_add( + secret_key, tweak_bytes, secret_output); + }); } /** @@ -143,10 +124,11 @@ template > std::span tweak_bytes) 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(); - return webcpp::crypto::detail::secp256k1_tweaked_secret(secret_key, tweak_bytes.data(), - secp256k1_ec_seckey_tweak_mul); + return webcpp::crypto::detail::secp256k1_tweaked_secret( + [&](std::span secret_output) noexcept { + return webcpp::crypto::detail::secp256k1_tweak_engine::secret_mul( + secret_key, tweak_bytes, secret_output); + }); } /** @@ -162,9 +144,11 @@ template > std::span secret_key) 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(); - return webcpp::crypto::detail::secp256k1_tweaked_secret(secret_key, nullptr, nullptr); + return webcpp::crypto::detail::secp256k1_tweaked_secret( + [&](std::span secret_output) noexcept { + return webcpp::crypto::detail::secp256k1_tweak_engine::secret_negate(secret_key, + secret_output); + }); } /** @@ -181,10 +165,8 @@ template > public_key const& parsed_key, std::span tweak_bytes) 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(); - return webcpp::crypto::detail::secp256k1_tweaked_key(parsed_key, tweak_bytes, - secp256k1_ec_pubkey_tweak_add); + return webcpp::crypto::detail::secp256k1_tweaked_key( + parsed_key, tweak_bytes, &webcpp::crypto::detail::secp256k1_tweak_engine::point_add); } /** @@ -201,10 +183,8 @@ template > public_key const& parsed_key, std::span tweak_bytes) 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(); - return webcpp::crypto::detail::secp256k1_tweaked_key(parsed_key, tweak_bytes, - secp256k1_ec_pubkey_tweak_mul); + return webcpp::crypto::detail::secp256k1_tweaked_key( + parsed_key, tweak_bytes, &webcpp::crypto::detail::secp256k1_tweak_engine::point_mul); } /** @@ -220,13 +200,10 @@ template > public_key const& parsed_key) 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(); public_key negated_key = parsed_key; // A valid point always negates: libsecp256k1 returns 1 (v0.8.0), which the check keeps honest. - if (!webcpp::crypto::detail::secp256k1_accepted(secp256k1_ec_pubkey_negate( - secp256k1_context_static, - &webcpp::crypto::detail::secp256k1_access::point(negated_key)))) { + if (!webcpp::crypto::detail::secp256k1_tweak_engine::point_negate( + webcpp::crypto::detail::secp256k1_access::point(negated_key))) { return error::backend_failure; } return negated_key; @@ -252,16 +229,15 @@ template > std::span parsed_keys, workspace pointer_space) 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); // The carver first: it wipes the workspace on every return, a refusal's included. webcpp::crypto::detail::secp256k1_workspace pointer_carver(pointer_space); // libsecp256k1 checks the count with ARG_CHECK, whose callback aborts: refused first here. if (parsed_keys.empty() || pointer_space.size() < combine_workspace_size(parsed_keys.size())) { return error::invalid_input_size; } - secp256k1_selftest(); using access = webcpp::crypto::detail::secp256k1_access; - auto* const key_pointers = pointer_carver.take(parsed_keys.size()); + auto* const key_pointers = + pointer_carver.take(parsed_keys.size()); if (key_pointers == nullptr) { return error::invalid_input_size; } @@ -269,8 +245,8 @@ template > key_pointers[key_index] = &access::point(parsed_keys[key_index]); } public_key combined_key = access::make_public_key(); - if (secp256k1_ec_pubkey_combine(secp256k1_context_static, &access::point(combined_key), - key_pointers, parsed_keys.size()) == 0) { + if (!webcpp::crypto::detail::secp256k1_tweak_engine::combine( + std::span(key_pointers, parsed_keys.size()), access::point(combined_key))) { return error::invalid_public_key; } return combined_key; diff --git a/include/webcpp/crypto/curves/x25519.hpp b/include/webcpp/crypto/curves/x25519.hpp index ce4533f..b6fcb3a 100644 --- a/include/webcpp/crypto/curves/x25519.hpp +++ b/include/webcpp/crypto/curves/x25519.hpp @@ -26,12 +26,14 @@ #include #include +#include #include #include #include #include #include #include +#include #include #include #include // lint-world: random_device draws generate()'s secret @@ -50,46 +52,44 @@ namespace webcpp::crypto::detail { +/** + * What an X25519 key pair stores on a backend: the backend's own key, its bytes or a handle; a + * backend's header specialises it with its engine. The primary is empty: nothing names it on a + * backend without the family, since its engine refuses the backend where the family is called. + */ +template +struct x25519_state {}; + /** The work of X25519 on a backend; the primary refuses (defined at the end of this header). */ template struct x25519_engine; /** - * X25519's work on a backend, without a guard (design R16): the public key of a secret key and - * the shared secret of a secret key and a peer's public key, which the key pair and the - * asynchronous family call once their own guard is held. + * X25519's work on a backend, without a guard (design R16): the shared secret of a key pair's state + * and a peer's public key, which the key pair and the asynchronous family call once their own + * guard is held. * * @tparam Backend The backend. */ template struct x25519_operations { - /** - * The public key of a secret key: its product with the base point, `u = 9`. - * - * @param secret_key 32 bytes; any 32 bytes are a secret key (RFC 7748 clamps them). - * @param public_bytes The public key's 32 bytes, written. - * @return Nothing; `backend_failure`. - */ - [[nodiscard]] static boost::system::result base( - std::span secret_key, - std::span public_bytes) noexcept { - return engine::base(secret_key, public_bytes); - } + /** The key pair's state on the backend. */ + using state = x25519_state; /** - * The shared secret of a secret key and a peer's public key, refused when it is all zero. + * The shared secret of a key pair's state and a peer's public key, refused when it is all + * zero. * - * @param secret_key 32 bytes. + * @param keyed_state A key pair's state. * @param peer_public_key 32 bytes. * @return 32 secret bytes; `weak_public_key` for a peer key of low order, whose shared secret * is all zero; `backend_failure`. */ [[nodiscard]] static boost::system::result> agree( - std::span secret_key, - std::span peer_public_key) noexcept { + state const& keyed_state, std::span peer_public_key) noexcept { secure::secret<32> shared_bytes; auto const engine_done = - engine::agree(secret_key, peer_public_key, shared_bytes.writable()); + engine::agree(keyed_state, peer_public_key, shared_bytes.writable()); if (!engine_done) { return engine_done.error(); } @@ -207,8 +207,9 @@ class public_key { }; /** - * An X25519 key pair (RFC 7748): its 32-byte secret key, wiped by every move and by the - * destructor, and its public key, computed once when it is made. + * An X25519 key pair (RFC 7748): its backend's state, which holds the 32-byte secret key (or a + * handle to it) and is wiped by every move and by the destructor, and its public key, computed once + * when it is made. * * It agrees, with `agree(peer)`; it does not sign. * @@ -217,6 +218,8 @@ class public_key { template > class basic_keypair { using operations = detail::x25519_operations; + using state_type = detail::x25519_state; + using engine = detail::x25519_engine; friend struct detail::x25519_access; // The asynchronous family's error completions make the empty object a move leaves. @@ -251,23 +254,56 @@ class basic_keypair { // Never compiled into a program: the assertion above stopped the build. return error::backend_failure; } else { - if (secret_bytes.size() != secret_key_size) { - return error::invalid_key_size; + // The trait first, then the capabilities (design D3's amendment, D9). + static_assert(detail::secret_keys_enter_v, + "webcpp::crypto: this backend keeps its keys: no secret key enters it " + "(crypto::imports_secret_keys_v is false), so X25519's from_secret, " + "which needs crypto::capabilities::x25519_import, is not available on " + "it; make a key with generate."); + if constexpr (detail::specialized_engine_v && + detail::secret_keys_enter_v) { + static_assert(detail::backend::x25519_import, + "webcpp::crypto: this backend has X25519 but not " + "crypto::capabilities::x25519_import: from_secret is not available " + "on it; make a key with generate."); } - basic_keypair made_pair; - std::ranges::copy(secret_bytes, made_pair.secret_value_.writable().begin()); - auto const engine_done = - operations::base(made_pair.secret_value_.bytes(), made_pair.public_bytes_); - if (!engine_done) { - return engine_done.error(); + if constexpr (detail::specialized_engine_v) { + static_assert(detail::backend::x25519_public, + "webcpp::crypto: this backend has X25519 but not " + "crypto::capabilities::x25519_public: a key pair's public key cannot " + "be computed, and from_secret is not available on it."); + } + if constexpr (!detail::secret_keys_enter_v || + !detail::capability_usable_v> || + !detail::capability_usable_v>) { + // Never compiled into a program: an assertion above stopped the build. + return error::backend_failure; + } else { + if (secret_bytes.size() != secret_key_size) { + return error::invalid_key_size; + } + basic_keypair made_pair; + auto const engine_keyed = engine::import_secret( + made_pair.state_, secret_bytes.template first()); + if (!engine_keyed) { + return engine_keyed.error(); + } + auto const engine_done = + engine::public_key(made_pair.state_, made_pair.public_bytes_); + if (!engine_done) { + return engine_done.error(); + } + made_pair.keyed_ = true; + return made_pair; } - made_pair.keyed_ = true; - return made_pair; } } /** - * Makes a key pair from a fresh secret key, drawn from the system's generator. + * Makes a key pair from a fresh secret key: the backend's own, on a backend that draws its + * keys (design R3), else drawn from the system's generator and imported. * * @return The key pair; `entropy_unavailable` when the system's generator fails or there is * none; `backend_failure`. @@ -281,15 +317,7 @@ class basic_keypair { // Never compiled into a program: the assertion above stopped the build. return error::backend_failure; } else { - secure::secret drawn_secret; - auto const entropy_drawn = - random_device().fill(drawn_secret.writable()); // lint-world: the secret key - if (!entropy_drawn) { - // The generator's not_supported (an Emscripten audio worklet) is the same failure - // for a key pair: one error to handle. - return error::entropy_unavailable; - } - return from_secret(drawn_secret.bytes()); + return generated(); } } @@ -344,9 +372,9 @@ class basic_keypair { * @param moved_from The key pair moved from. */ basic_keypair(basic_keypair&& moved_from) noexcept - : secret_value_(std::move(moved_from.secret_value_)), - public_bytes_(moved_from.public_bytes_), - keyed_(std::exchange(moved_from.keyed_, false)) {} + : public_bytes_(moved_from.public_bytes_), keyed_(std::exchange(moved_from.keyed_, false)) { + engine::move(state_, moved_from.state_); + } /** * Moves over this key pair, whose secret key is wiped first. @@ -356,7 +384,8 @@ class basic_keypair { */ basic_keypair& operator=(basic_keypair&& moved_from) noexcept { if (this != &moved_from) { - secret_value_ = std::move(moved_from.secret_value_); + engine::reset(state_); + engine::move(state_, moved_from.state_); public_bytes_ = moved_from.public_bytes_; keyed_ = std::exchange(moved_from.keyed_, false); } @@ -369,7 +398,7 @@ class basic_keypair { basic_keypair& operator=(basic_keypair const&) = delete; /** Wipes the secret key. */ - ~basic_keypair() = default; + ~basic_keypair() { engine::reset(state_); } /** * The public key, which a peer's `agree` takes: a copy of the one computed when the key pair @@ -388,15 +417,36 @@ class basic_keypair { * The secret key, for a program that keeps the key pair and makes it again with * `from_secret`, or exports it: a copy. * - * @return 32 secret bytes; `invalid_state` moved from. + * @return 32 secret bytes; `invalid_state` moved from; `backend_failure`. */ [[nodiscard]] boost::system::result> secret() const noexcept { - if (!keyed_) { - return error::invalid_state; + // The trait first, then the capability (design D3's amendment, D9). + static_assert(detail::secret_keys_leave_v, + "webcpp::crypto: this backend keeps its keys: no secret key leaves it " + "(crypto::exports_secret_keys_v is false), so X25519's secret(), which needs " + "crypto::capabilities::x25519_export, is not available on it."); + if constexpr (detail::specialized_engine_v && + detail::secret_keys_leave_v) { + static_assert(detail::backend::x25519_export, + "webcpp::crypto: this backend has X25519 but not " + "crypto::capabilities::x25519_export: secret() is not available on it."); + } + if constexpr (!detail::secret_keys_leave_v || + !detail::capability_usable_v>) { + // Never compiled into a program: an assertion above stopped the build. + return error::backend_failure; + } else { + if (!keyed_) { + return error::invalid_state; + } + secure::secret secret_copy; + auto const engine_done = engine::export_secret(state_, secret_copy.writable()); + if (!engine_done) { + return engine_done.error(); + } + return secret_copy; } - secure::secret secret_copy; - std::ranges::copy(secret_value_.bytes(), secret_copy.writable().begin()); - return secret_copy; } /** @@ -420,10 +470,7 @@ class basic_keypair { // Never compiled into a program: the assertion above stopped the build. return error::backend_failure; } else { - if (!keyed_) { - return error::invalid_state; - } - return operations::agree(secret_value_.bytes(), peer_key.bytes()); + return agreed(peer_key); } } @@ -486,7 +533,84 @@ class basic_keypair { private: basic_keypair() noexcept = default; - secure::secret secret_value_; + // The work of generate, which holds the guard, and of a backend's asynchronous generation + // (detail::async_access): the backend's own key when its engine draws one (design R3), its + // public key computed here once, else a secret key from the system's generator, imported. + [[nodiscard]] static boost::system::result generated() noexcept { + if constexpr (detail::backend::x25519_generate) { + if constexpr (detail::specialized_engine_v) { + static_assert(detail::backend::x25519_public, + "webcpp::crypto: this backend has X25519 but not " + "crypto::capabilities::x25519_public: a key pair's public key cannot " + "be computed, and generate is not available on it."); + } + if constexpr (!detail::capability_usable_v>) { + // Never compiled into a program: the assertion above stopped the build. + return error::backend_failure; + } else { + basic_keypair made_pair; + auto const engine_drawn = engine::generate(made_pair.state_); + if (!engine_drawn) { + return engine_drawn.error(); + } + auto const engine_done = + engine::public_key(made_pair.state_, made_pair.public_bytes_); + if (!engine_done) { + return engine_done.error(); + } + made_pair.keyed_ = true; + return made_pair; + } + } else { + // A backend that neither draws its keys nor imports them has no way to make one. + static_assert( + detail::secret_keys_enter_v && + (!detail::specialized_engine_v || + detail::backend::x25519_import), + "webcpp::crypto: this backend has X25519 but neither " + "crypto::capabilities::x25519_generate nor crypto::capabilities::x25519_import: " + "generate has no way to make a key on it."); + secure::secret drawn_secret; + auto const entropy_drawn = + random_device().fill(drawn_secret.writable()); // lint-world: the secret key + if (!entropy_drawn) { + // The generator's not_supported (an Emscripten audio worklet) is the same failure + // for a key pair: one error to handle. + return error::entropy_unavailable; + } + if constexpr (!detail::secret_keys_enter_v || + !detail::capability_usable_v>) { + // Never compiled into a program: the assertion above stopped the build. + return error::backend_failure; + } else { + return from_secret(drawn_secret.bytes()); + } + } + } + + // The work of agree, which holds the guard, and of a backend's asynchronous agreement. + [[nodiscard]] boost::system::result> agreed( + public_key_type const& peer_key) const noexcept { + if constexpr (detail::specialized_engine_v) { + static_assert(detail::backend::x25519_agreement, + "webcpp::crypto: this backend has X25519 but not " + "crypto::capabilities::x25519_agreement: agree is not available on it."); + } + if constexpr (!detail::capability_usable_v>) { + // Never compiled into a program: the assertion above stopped the build. + return error::backend_failure; + } else { + if (!keyed_) { + return error::invalid_state; + } + return operations::agree(state_, peer_key.bytes()); + } + } + + state_type state_{}; std::array public_bytes_{}; bool keyed_ = false; }; @@ -510,6 +634,18 @@ inline constexpr curve_id curve_of_v = curve_id::x25 template inline constexpr curve_id curve_of_v> = curve_id::x25519; +/** + * Whether `Backend`'s X25519 state holds the secret key's 32 bytes as `secret_key`, which + * `x25519_access::secret_bytes` reads for crypto_kx, crypto_box and the sealed box. + * + * @tparam Backend The key pair's backend. + */ +template +inline constexpr bool x25519_state_holds_secret_key = + requires(x25519_state const& engine_state) { + { std::span{engine_state.secret_key} }; + }; + struct x25519_access { /** * Whether a key pair holds a key: false for one moved from, or the empty one of an error @@ -526,7 +662,9 @@ struct x25519_access { } /** - * A key pair's secret key, viewed: valid while the key pair lives and is not moved from. + * A key pair's secret key, viewed, on a backend whose state holds the secret key's bytes as + * `secret_key` (libsodium's, whose crypto_kx, boxes and sealed box take them): valid while the + * key pair lives and is not moved from. * * @tparam Backend The key pair's backend. * @param key_pair A key pair that holds a key (the caller checks with `keyed`); a moved-from @@ -536,7 +674,28 @@ struct x25519_access { template [[nodiscard]] static std::span secret_bytes( curves::x25519::basic_keypair const& key_pair) noexcept { - return key_pair.secret_value_.bytes(); + static_assert(x25519_state_holds_secret_key, + "webcpp::crypto: crypto_kx, crypto_box and the sealed box read an X25519 key " + "pair's secret key from its backend's state, which must hold it as 32 bytes " + "named secret_key: this backend's does not."); + return key_pair.state_.secret_key; + } + + /** + * Writes a key pair's secret key through its engine's `export_secret` (`x25519_export`), for + * its private formats. + * + * @tparam Backend The key pair's backend. + * @param key_pair A key pair that holds a key (the caller checks with `keyed`). + * @param output_bytes 32 bytes, written only on success. + * @return Nothing; `backend_failure`. + */ + template + [[nodiscard]] static boost::system::result export_secret( + curves::x25519::basic_keypair const& key_pair, + std::span output_bytes) noexcept { + return x25519_engine::export_secret(key_pair.state_, + output_bytes); } /** @@ -566,7 +725,22 @@ struct x25519_engine { /** Never called; fails closed. */ template - [[nodiscard]] static boost::system::result base(Arguments&&... /*arguments*/) noexcept { + [[nodiscard]] static boost::system::result import_secret( + Arguments&&... /*arguments*/) noexcept { + return error::backend_failure; + } + + /** Never called; fails closed. */ + template + [[nodiscard]] static boost::system::result public_key( + Arguments&&... /*arguments*/) noexcept { + return error::backend_failure; + } + + /** Never called; fails closed. */ + template + [[nodiscard]] static boost::system::result export_secret( + Arguments&&... /*arguments*/) noexcept { return error::backend_failure; } @@ -575,6 +749,14 @@ struct x25519_engine { [[nodiscard]] static boost::system::result agree(Arguments&&... /*arguments*/) noexcept { return error::backend_failure; } + + /** Never called. */ + template + static void move(Arguments&&... /*arguments*/) noexcept {} + + /** Never called. */ + template + static void reset(Arguments&&... /*arguments*/) noexcept {} }; } // namespace webcpp::crypto::detail diff --git a/include/webcpp/crypto/curves/x25519/formats.hpp b/include/webcpp/crypto/curves/x25519/formats.hpp index ce88e93..1078a5d 100644 --- a/include/webcpp/crypto/curves/x25519/formats.hpp +++ b/include/webcpp/crypto/curves/x25519/formats.hpp @@ -20,7 +20,8 @@ The key pair's private formats exist on a backend whose secret is in the program; on a backend whose key pairs live in WebCrypto (`detail::asynchronous_backend_v`), codecs' verbs refuse them, naming WebCrypto's `exportKey` (design D7). A public key, which names no backend, is - encoded and decoded on the family's default, libsodium on every target. + encoded and decoded with none: RFC 8410's layouts are constants around the key + (`detail/rfc8410.hpp`), and a key pair's need of its backend only its key capabilities. @see "Key formats: raw, SPKI, PKCS#8, DER and PEM", in the guide. */ @@ -33,7 +34,8 @@ #include #include #include -#include +#include +#include #include #include #include @@ -68,30 +70,46 @@ inline constexpr std::array x25519_pkcs8_prefix{ 0x04, 0x22, 0x04, 0x20, // OCTET STRING, 34 bytes: an OCTET STRING, 32 }; -/** - * X25519's key formats on a backend; the primary refuses (defined at the end of this header). A - * backend's specialisation provides `encode_spki(public_key, out)`, - * `decode_spki(spki, public_key)`, `encode_pkcs8(secret_key, out)` and - * `decode_pkcs8(pkcs8, secret_key)`, over spans of the formats' fixed sizes, the decoders - * returning `invalid_encoding` for any other bytes than the one encoding. - */ -template -struct x25519_formats_engine; - /** The size of X25519's SPKI, RFC 8410's one size for an X25519 public key. */ inline constexpr std::size_t x25519_spki_size = x25519_spki_prefix.size() + 32; /** The size of X25519's PKCS#8, version 1: the secret key alone. */ inline constexpr std::size_t x25519_pkcs8_size = x25519_pkcs8_prefix.size() + 32; +/** + * Whether a key pair of `Backend` lets its secret key leave and enter its backend, as its private + * formats do: the backend's secret-key traits, for an engine its header specialises (design D3's + * amendment). + * + * @tparam Backend The key pair's backend. + */ +template +inline constexpr bool x25519_secret_passes_v = + secret_keys_leave_v, Backend> && + secret_keys_enter_v, Backend>; + /** * Whether a key pair of `Backend` has X25519's private formats: its secret is in the program, on - * every backend but one whose key pairs live in WebCrypto (design D7). + * every backend but one that keeps its keys (design D3's amendment) or whose key pairs live in + * WebCrypto (design D7). * * @tparam Backend The key pair's backend. */ template -inline constexpr bool x25519_private_formats_v = !asynchronous_backend_v; +inline constexpr bool x25519_private_formats_v = + x25519_secret_passes_v && !asynchronous_backend_v; + +/** + * Why a key pair of `Backend` has no private format: its backend keeps its keys, which is said + * first, for `raw` apart from `pkcs8` and `pem(pkcs8)`, or its secret lives in WebCrypto. + * + * @tparam Backend The key pair's backend, one without X25519's private formats. + * @tparam Raw Whether the format is `raw`. + */ +template +inline constexpr refusal_reason x25519_private_refusal_v = + x25519_secret_passes_v ? refusal_reason::private_on_asynchronous + : private_kept_reason_v; /** An X25519 public key has `raw`, `spki` and `pem(spki)`. */ template <> @@ -114,37 +132,40 @@ struct formats_of> { }; /** - * A key pair whose secret lives in WebCrypto has no `raw` (design D7). + * A key pair whose backend keeps its keys, or whose secret lives in WebCrypto, has no `raw` + * (design D3's amendment, D7). * - * @tparam Backend The key pair's backend, one whose key pairs live in WebCrypto. + * @tparam Backend The key pair's backend, one without private formats. */ template requires(!x25519_private_formats_v) inline constexpr refusal_reason refusal_reason_v, curves::x25519::basic_keypair> = - refusal_reason::private_on_asynchronous; + x25519_private_refusal_v; /** - * A key pair whose secret lives in WebCrypto has no `pkcs8` (design D7). + * A key pair whose backend keeps its keys, or whose secret lives in WebCrypto, has no `pkcs8` + * (design D3's amendment, D7). * - * @tparam Backend The key pair's backend, one whose key pairs live in WebCrypto. + * @tparam Backend The key pair's backend, one without private formats. */ template requires(!x25519_private_formats_v) inline constexpr refusal_reason refusal_reason_v> = - refusal_reason::private_on_asynchronous; + x25519_private_refusal_v; /** - * A key pair whose secret lives in WebCrypto has no `pem(pkcs8)` (design D7). + * A key pair whose backend keeps its keys, or whose secret lives in WebCrypto, has no `pem(pkcs8)` + * (design D3's amendment, D7). * - * @tparam Backend The key pair's backend, one whose key pairs live in WebCrypto. + * @tparam Backend The key pair's backend, one without private formats. */ template requires(!x25519_private_formats_v) inline constexpr refusal_reason refusal_reason_v, curves::x25519::basic_keypair> = - refusal_reason::private_on_asynchronous; + x25519_private_refusal_v; } // namespace webcpp::crypto::detail @@ -228,35 +249,30 @@ struct value_codec, crypto::curves::x25519::public_key } /** - * Writes the key's SPKI. + * Writes the key's SPKI: RFC 8410's layout, constants around the key, with no backend. * - * @tparam Backend The backend whose engine writes it: the family's default, a template - * parameter so that a program that never encodes an SPKI needs no backend linked. * @param key The key. * @param output_bytes The caller's output. * @return 44; `output_too_small`, with nothing written. */ - template > [[nodiscard]] static result encode(crypto::formats::spki_t<> const& /*format*/, crypto::curves::x25519::public_key const& key, std::span output_bytes) noexcept { if (output_bytes.size() < max_encoded_size) { return error::output_too_small; } - crypto::detail::x25519_formats_engine::encode_spki( - key.bytes(), output_bytes.first()); + crypto::detail::rfc8410::encode(crypto::detail::x25519_spki_prefix, key.bytes(), + output_bytes.first()); return max_encoded_size; } /** * 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. + * X25519's prefix, then the key, and nothing after; no backend reads it. * - * @tparam Backend The backend whose engine reads it: the family's default, as `encode`'s. * @param input_bytes The DER. * @return The public key; `invalid_encoding`. */ - template > [[nodiscard]] static result decode( crypto::formats::spki_t<> const& /*format*/, std::span input_bytes) noexcept { @@ -266,8 +282,8 @@ struct value_codec, crypto::curves::x25519::public_key } std::array key_bytes{}; auto const decoded_key = - crypto::detail::x25519_formats_engine::decode_spki( - input_bytes.first(), key_bytes); + crypto::detail::rfc8410::decode(crypto::detail::x25519_spki_prefix, + input_bytes.first(), key_bytes); if (!decoded_key) { return decoded_key.error(); } @@ -385,7 +401,8 @@ struct value_codec encode(crypto::formats::pkcs8_t const& /*format*/, keypair_type const& key_pair, @@ -398,9 +415,14 @@ struct value_codec::encode_pkcs8( - crypto::detail::x25519_access::secret_bytes(key_pair), - output_bytes.first()); + secure::secret secret_key; + auto const exported = + crypto::detail::x25519_access::export_secret(key_pair, secret_key.writable()); + if (!exported) { + return exported.error(); + } + crypto::detail::rfc8410::encode(crypto::detail::x25519_pkcs8_prefix, secret_key.bytes(), + output_bytes.first()); return max_encoded_size; } @@ -420,9 +442,9 @@ struct value_codec secret_key; - auto const decoded_key = - crypto::detail::x25519_formats_engine::decode_pkcs8( - input_bytes.first(), secret_key.writable()); + auto const decoded_key = crypto::detail::rfc8410::decode( + crypto::detail::x25519_pkcs8_prefix, input_bytes.first(), + secret_key.writable()); if (!decoded_key) { return decoded_key.error(); } @@ -511,52 +533,4 @@ auto basic_keypair::decode(Format const& format, Input const& input) no } // namespace webcpp::crypto::curves::x25519 -namespace webcpp::crypto::detail { - -/** - * X25519's key formats on a backend whose header does not specialise them: the family's - * refusal, which names what the program needs (`detail/capabilities.hpp`). Its functions are - * never called: the refusal stops the build where the class is instantiated, and they keep the - * compiler from adding errors of their own after it; those that return report - * `backend_failure`, so that a path the refusal missed fails closed. - */ -template -struct x25519_formats_engine { - WEBCPP_CRYPTO_DETAIL_REFUSE_X25519(Backend); - - /** Never called. */ - template - static void encode_spki(Arguments&&... /*arguments*/) noexcept {} - - /** Never called; fails closed. */ - template - [[nodiscard]] static boost::system::result decode_spki( - Arguments&&... /*arguments*/) noexcept { - return error::backend_failure; - } - - /** Never called. */ - template - static void encode_pkcs8(Arguments&&... /*arguments*/) noexcept {} - - /** Never called; fails closed. */ - template - [[nodiscard]] static boost::system::result decode_pkcs8( - Arguments&&... /*arguments*/) noexcept { - return error::backend_failure; - } -}; - -} // namespace webcpp::crypto::detail - -/** Defined once this header's declarations are, which libsodium's engine specialises. */ -// NOLINTNEXTLINE(modernize-macro-to-enum): read by backends/sodium.hpp's #if, not a value -#define WEBCPP_CRYPTO_DETAIL_X25519_FORMATS_DECLARED 1 - -// The default backend's engine, when the program links it (design D32): libsodium on every -// target. Its header specialises it for this header, wherever it was first included. -#if defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_X25519_SODIUM) && defined(WEBCPP_CRYPTO_HAS_SODIUM) -#include -#endif - #endif // WEBCPP_CRYPTO_CURVES_X25519_FORMATS_HPP diff --git a/include/webcpp/crypto/detail/async_access.hpp b/include/webcpp/crypto/detail/async_access.hpp index c9f698c..e516ca3 100644 --- a/include/webcpp/crypto/detail/async_access.hpp +++ b/include/webcpp/crypto/detail/async_access.hpp @@ -66,6 +66,51 @@ struct async_access { static constexpr bool makes_empty_v = requires { { T{} } noexcept; }; + + /** + * A key pair's generation, without the guard and the synchronous form's refusal: the work an + * asynchronous engine runs for `generate`, its backend's own key when the engine + * draws one (design R3). The engine's caller holds the guard. + * + * @tparam Keypair An Ed25519, an X25519 or a P-256 key pair. + * @return The key pair, or the error `generate` would give. + */ + template + [[nodiscard]] static auto generated() noexcept { + return Keypair::generated(); + } + + /** + * A key pair's agreement with a peer's public key, without the guard and the synchronous + * form's refusal: the work an asynchronous engine runs for `agree`. + * + * @tparam Keypair An X25519 or a P-256 key pair. + * @tparam PeerKey The peer's public key's type, the key pair's `public_key_type`. + * @param key_pair The key pair. + * @param peer_key The peer's public key. + * @return The shared secret, or the error `agree` would give. + */ + template + [[nodiscard]] static auto agreed(Keypair const& key_pair, PeerKey const& peer_key) noexcept { + return key_pair.agreed(peer_key); + } + + /** + * A P-256 key pair's signature of a digest, S made low, without the guard and the synchronous + * form's refusal: the work an asynchronous engine runs for `sign` once it has hashed the + * message. + * + * @tparam Keypair A P-256 key pair. + * @tparam Digest The digest's view, 32 bytes. + * @param key_pair The key pair. + * @param digest_bytes The message's SHA-256. + * @return The signature, or the error `sign` would give. + */ + template + [[nodiscard]] static auto signed_digest(Keypair const& key_pair, + Digest const& digest_bytes) noexcept { + return key_pair.signed_digest(digest_bytes); + } }; } // namespace webcpp::crypto::detail diff --git a/include/webcpp/crypto/detail/backend/asynchronous.hpp b/include/webcpp/crypto/detail/backend/asynchronous.hpp new file mode 100644 index 0000000..10bfc01 --- /dev/null +++ b/include/webcpp/crypto/detail/backend/asynchronous.hpp @@ -0,0 +1,114 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_CRYPTO_DETAIL_BACKEND_ASYNCHRONOUS_HPP +#define WEBCPP_CRYPTO_DETAIL_BACKEND_ASYNCHRONOUS_HPP + +#include +#include +#include + +/** + * The asynchronous capabilities (design D4, D6): the static members of a backend's + * `detail::async_engine` that `async.hpp` calls, in the shape it documents: the executor + * the completion is posted to first, the public function's other arguments, the completion token + * last, forwarded; a public function's explicit template argument goes to a member template of the + * same name. + * + * Each concept passes what `async.hpp` passes, as a const lvalue wherever the call passes an + * object the engine must not change (the executor, a key pair, a public key, a signature, a + * scheme or policy tag, a view): an engine that takes one by value or by const reference accepts + * every call `async.hpp` makes, and one that takes it by mutable or rvalue reference is refused. + * An AEAD is the one object passed as a mutable lvalue (its `async_seal` and `async_open` are + * non-const members). The concepts take the executor and token types as parameters, so that they + * hold for any executor and token the program gives; what an engine returns is the token's + * `async_result`, which they do not constrain, nor noexcept: the completion signatures are the + * public functions', checked where the public functions are tested. + * + * The contract the concepts cannot state (design D2), which an engine keeps: + * - the objects passed by reference (a key pair, a public key, an AEAD) and the bytes the views + * hold are the caller's until the completion, as the public functions say, and no longer: an + * engine keeps a view, never a reference to the caller's argument; + * - the public function holds `secure::timing_guard` before it calls the engine; + * - the engine posts the completion through the executor, never runs the handler inline, and + * reports errors through it as `crypto::error` codes; + * - it allocates nothing of the program's but through the handler's associated allocator. + */ +namespace webcpp::crypto::detail::backend { + +/** `from_secret(executor, secret, token)`: a key pair from its secret bytes. */ +template +concept async_import_secret = + requires(Executor const& completion_executor, std::span const& secret_bytes, + Token&& token) { + Engine::template from_secret(completion_executor, secret_bytes, + std::forward(token)); + }; + +/** `from_key(executor, key, token)`: a cipher from its key. */ +template +concept async_import_key = requires(Executor const& completion_executor, + std::span const& key_bytes, Token&& token) { + Engine::template from_key(completion_executor, key_bytes, std::forward(token)); +}; + +/** `generate(executor, token)`: a key pair the backend draws. */ +template +concept async_generate = requires(Executor const& completion_executor, Token&& token) { + Engine::template generate(completion_executor, std::forward(token)); +}; + +/** `seal(executor, aead, nonce, associated_data, data, token)`. */ +template +concept async_seal = requires(Executor const& completion_executor, Aead& aead, + std::span const& nonce_bytes, + std::span const& associated_data_bytes, + std::span const& data_bytes, Token&& token) { + Engine::seal(completion_executor, aead, nonce_bytes, associated_data_bytes, data_bytes, + std::forward(token)); +}; + +/** `open(executor, aead, nonce, associated_data, data, tag, token)`. */ +template +concept async_open = requires(Executor const& completion_executor, Aead& aead, + std::span const& nonce_bytes, + std::span const& associated_data_bytes, + std::span const& data_bytes, + std::span const& tag_bytes, Token&& token) { + Engine::open(completion_executor, aead, nonce_bytes, associated_data_bytes, data_bytes, + tag_bytes, std::forward(token)); +}; + +/** `sign(executor, key_pair, scheme, input, token)`: the message itself, as a view. */ +template +concept async_sign = requires(Executor const& completion_executor, Keypair const& key_pair, + Scheme const& signing_scheme, + std::span const& input_bytes, Token&& token) { + Engine::sign(completion_executor, key_pair, signing_scheme, input_bytes, + std::forward(token)); +}; + +/** `verify(executor, scheme, policy, signature, input, public_key, token)`. */ +template +concept async_verify = requires(Executor const& completion_executor, Scheme const& signing_scheme, + Policy const& verification_policy, Signature const& signature, + std::span const& input_bytes, + PublicKey const& public_key, Token&& token) { + Engine::verify(completion_executor, signing_scheme, verification_policy, signature, input_bytes, + public_key, std::forward(token)); +}; + +/** `agree(executor, key_pair, peer_public_key, token)`. */ +template +concept async_agree = requires(Executor const& completion_executor, Keypair const& key_pair, + PeerPublicKey const& peer_public_key, Token&& token) { + Engine::agree(completion_executor, key_pair, peer_public_key, std::forward(token)); +}; + +} // namespace webcpp::crypto::detail::backend + +#endif // WEBCPP_CRYPTO_DETAIL_BACKEND_ASYNCHRONOUS_HPP diff --git a/include/webcpp/crypto/detail/backend/boxes.hpp b/include/webcpp/crypto/detail/backend/boxes.hpp new file mode 100644 index 0000000..443f587 --- /dev/null +++ b/include/webcpp/crypto/detail/backend/boxes.hpp @@ -0,0 +1,101 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_CRYPTO_DETAIL_BACKEND_BOXES_HPP +#define WEBCPP_CRYPTO_DETAIL_BACKEND_BOXES_HPP + +#include +#include + +#include + +#include +#include +#include +#include + +/** + * The public-key boxes and the key exchange (design D4): crypto_box, the sealed box and + * crypto_kx, over X25519 keys of 32 bytes. + */ +namespace webcpp::crypto::detail::backend { + +/** + * The nonce and tag sizes of both crypto_box families (XSalsa20-Poly1305 and + * XChaCha20-Poly1305), whose family types are tags without sizes. + */ +inline constexpr std::size_t box_nonce_size = 24; +/** See @ref box_nonce_size. */ +inline constexpr std::size_t box_tag_size = 16; + +/** crypto_kx's seed, an X25519 secret's size. */ +inline constexpr std::size_t kx_seed_size = x25519_key_size; +/** crypto_kx's session keys' size, each. */ +inline constexpr std::size_t kx_session_key_size = 32; + +/** + * crypto_box: `init(state, own_secret_key, peer_public_key)` precomputes the shared key, then + * `seal` and `open` as a secret box's, with a nonce of `box_nonce_size` bytes. Both families + * (XSalsa20-Poly1305, XChaCha20-Poly1305) share the sizes and their family types are tags without + * them, so the concept takes no family (D4 wrote `box`; STATUS.md ruling 1.1-M1). + */ +template +concept box = + stateful_engine && + requires(Engine::state& engine_state, + std::span own_secret_key, + std::span peer_public_key, + std::span nonce_bytes, + std::span data_bytes, boost::hash2::digest& tag_output, + std::array const& expected_tag) { + { Engine::init(engine_state, own_secret_key, peer_public_key) } noexcept -> fallible; + { Engine::seal(engine_state, nonce_bytes, data_bytes, tag_output) } noexcept -> fallible; + { Engine::open(engine_state, nonce_bytes, data_bytes, expected_tag) } noexcept -> fallible; + }; + +/** + * The sealed box: static `seal(recipient_public_key, message, output)` with a fresh ephemeral key, + * and `open(recipient_public_key, recipient_secret_key, sealed, output)`; no state. D4's text had + * `open(recipient, sealed, out)`; the concept follows the engine, which takes the recipient's two + * keys (STATUS.md ruling 1.1-M2). + */ +template +concept sealed_box = + requires(std::span recipient_public_key, + std::span recipient_secret_key, + std::span input_bytes, std::span output_bytes) { + { Engine::seal(recipient_public_key, input_bytes, output_bytes) } noexcept -> fallible; + { + Engine::open(recipient_public_key, recipient_secret_key, input_bytes, output_bytes) + } noexcept -> fallible; + }; + +/** + * crypto_kx: `seed_keypair(seed, secret_key)` derives a key pair from a seed, and `client` and + * `server` derive the two session keys from the own key pair and the peer's public key; no state. + * D4's text named them `derive_from_seed`, `client_session_keys` and `server_session_keys`; the + * concept follows the engine's names (STATUS.md ruling 1.1-M2). + */ +template +concept kx = requires(std::span seed_bytes, + std::span secret_key_output, + std::span secret_key, + std::span public_key, + std::span peer_public_key, + std::span receive_key, + std::span transmit_key) { + { Engine::seed_keypair(seed_bytes, secret_key_output) } noexcept -> fallible; + { + Engine::client(secret_key, public_key, peer_public_key, receive_key, transmit_key) + } noexcept -> fallible; + { + Engine::server(secret_key, public_key, peer_public_key, receive_key, transmit_key) + } noexcept -> fallible; +}; + +} // namespace webcpp::crypto::detail::backend + +#endif // WEBCPP_CRYPTO_DETAIL_BACKEND_BOXES_HPP diff --git a/include/webcpp/crypto/detail/backend/common.hpp b/include/webcpp/crypto/detail/backend/common.hpp new file mode 100644 index 0000000..c6c156c --- /dev/null +++ b/include/webcpp/crypto/detail/backend/common.hpp @@ -0,0 +1,53 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_CRYPTO_DETAIL_BACKEND_COMMON_HPP +#define WEBCPP_CRYPTO_DETAIL_BACKEND_COMMON_HPP + +#include + +#include + +/** + * The capability concepts: what crypto's public types require of the engines of the backends + * crypto ships, an internal contract (design D1, D10). Each concept is named after the + * capability, never after a backend, and is a conjunction of the shared requirements + * (`stateful_engine`, `keyed_init`) and one requires-expression that lists the operations, so that + * a compiler names the requirement an engine fails. + * + * What every capability shares (design D2), beyond what a concept checks: + * + * - Timing guard: the public function holds `detail::timing_guard`; an engine function never holds + * one and never calls a public function. + * - Allocation: an engine never allocates through the C++ heap or a program's allocator; a backend + * library's own allocations are the backend's, named in its table row; a failed allocation + * inside the library is `backend_failure` or `errc::not_enough_memory`, never an exception. + * - Thread safety: engine functions may run concurrently on distinct states; a backend's global + * initialisation is idempotent, thread-safe and done by the engine. + * - Wiping: `reset` wipes every secret the state holds and releases any handle; `move` leaves the + * source as `reset` does; a secret written into a caller's span is written only on success. + * - Canary: an engine reads its backend's canary before its first library call. + * - Errors: values of `crypto::error` only, never an exception. + */ +namespace webcpp::crypto::detail::backend { + +/** An operation's result where it can fail and returns nothing. */ +template +concept fallible = std::same_as>; + +/** + * An engine whose objects keep a state: `typename Engine::state`, with `move(target, source)` + * leaving the source as `reset` leaves it, and `reset(state)` wiping it, both `noexcept`. + */ +template +concept stateful_engine = requires(Engine::state& target_state, Engine::state& source_state) { + { Engine::move(target_state, source_state) } noexcept -> std::same_as; + { Engine::reset(target_state) } noexcept -> std::same_as; +}; + +} // namespace webcpp::crypto::detail::backend + +#endif // WEBCPP_CRYPTO_DETAIL_BACKEND_COMMON_HPP diff --git a/include/webcpp/crypto/detail/backend/concepts.hpp b/include/webcpp/crypto/detail/backend/concepts.hpp new file mode 100644 index 0000000..2e1555a --- /dev/null +++ b/include/webcpp/crypto/detail/backend/concepts.hpp @@ -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) + +#ifndef WEBCPP_CRYPTO_DETAIL_BACKEND_CONCEPTS_HPP +#define WEBCPP_CRYPTO_DETAIL_BACKEND_CONCEPTS_HPP + +// Every capability concept of detail::backend (design D1). +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#endif // WEBCPP_CRYPTO_DETAIL_BACKEND_CONCEPTS_HPP diff --git a/include/webcpp/crypto/detail/backend/ed25519.hpp b/include/webcpp/crypto/detail/backend/ed25519.hpp new file mode 100644 index 0000000..639ff82 --- /dev/null +++ b/include/webcpp/crypto/detail/backend/ed25519.hpp @@ -0,0 +1,111 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_CRYPTO_DETAIL_BACKEND_ED25519_HPP +#define WEBCPP_CRYPTO_DETAIL_BACKEND_ED25519_HPP + +#include +#include + +#include +#include +#include +#include + +/** + * Ed25519's capabilities (design D4), the key ones per @ref key_import and its siblings, over the + * shared @ref secret_key_size. + */ +namespace webcpp::crypto::detail::backend { + +/** Ed25519's public key size. */ +inline constexpr std::size_t ed25519_public_key_size = 32; +/** Ed25519's signature size. */ +inline constexpr std::size_t ed25519_signature_size = 64; +/** Ed25519ph's prehash size, a SHA-512 digest. */ +inline constexpr std::size_t ed25519ph_digest_size = 64; +/** The size of an X25519 key the birational map gives. */ +inline constexpr std::size_t ed25519_x25519_key_size = 32; + +/** Ed25519 from its seed, the secret of @ref secret_key_size bytes. */ +template +concept ed25519_import = key_import; +/** Ed25519 drawn by the backend. */ +template +concept ed25519_generate = key_generate; +/** Ed25519's public key. */ +template +concept ed25519_public = key_public; +/** Ed25519's seed back. */ +template +concept ed25519_export = key_export; + +/** `sign(state, message, signature)`: RFC 8032's Ed25519 over the whole message. */ +template +concept ed25519_signing = + stateful_engine && + requires(Engine::state const& engine_state, std::span message_bytes, + std::span signature_output) { + { Engine::sign(engine_state, message_bytes, signature_output) } noexcept -> fallible; + }; + +/** + * `verify(public_key, message, signature)`: on public data, no state; `invalid_signature` when + * the signature does not hold. + */ +template +concept ed25519_verifying = + requires(std::span public_key, + std::span message_bytes, + std::span signature_bytes) { + { Engine::verify(public_key, message_bytes, signature_bytes) } noexcept -> fallible; + }; + +/** + * The birational map to X25519: `x25519_secret(state, out)` from the key pair and + * `to_x25519_public(public_key, out)` from the public key. + * + * `x25519_secret` is an export in all but name: the derived X25519 secret leaves the backend, + * written only on success. A backend whose Ed25519 keys never leave it has no + * @ref ed25519_export and has no `x25519_secret` either; `exports_secret_keys_v` governs both + * (task 3.1). + */ +template +concept ed25519_to_x25519 = + stateful_engine && + requires(Engine::state const& engine_state, + std::span public_key, + std::span output_bytes) { + { Engine::x25519_secret(engine_state, output_bytes) } noexcept -> fallible; + { Engine::to_x25519_public(public_key, output_bytes) } noexcept -> fallible; + }; + +/** + * Ed25519ph (RFC 8032's prehashed variant) over a key engine `KeyEngine`: `begin(state)`, + * `update(state, piece)` any number of times, then `sign(state, key_state, signature)` or + * `verify(state, public_key, signature)`; and the one-shot `sign_digest` and `verify_digest` over + * a SHA-512 digest the program made; `reset(state)` wipes a message left unfinished. The state is + * a hashing state with no secret and no handle, so it needs no `move`. + */ +template +concept ed25519ph = requires(Engine::state& begun_state, KeyEngine::state const& key_state, + std::span piece_bytes, + std::span public_key, + std::span digest_bytes, + std::span signature_bytes, + std::span signature_output) { + { Engine::begin(begun_state) } noexcept -> fallible; + { Engine::update(begun_state, piece_bytes) } noexcept -> std::same_as; + { Engine::sign(begun_state, key_state, signature_output) } noexcept -> fallible; + { Engine::verify(begun_state, public_key, signature_bytes) } noexcept -> fallible; + { Engine::sign_digest(key_state, digest_bytes, signature_output) } noexcept -> fallible; + { Engine::verify_digest(public_key, digest_bytes, signature_bytes) } noexcept -> fallible; + { Engine::reset(begun_state) } noexcept -> std::same_as; +}; + +} // namespace webcpp::crypto::detail::backend + +#endif // WEBCPP_CRYPTO_DETAIL_BACKEND_ED25519_HPP diff --git a/include/webcpp/crypto/detail/backend/entropy.hpp b/include/webcpp/crypto/detail/backend/entropy.hpp new file mode 100644 index 0000000..be75a8e --- /dev/null +++ b/include/webcpp/crypto/detail/backend/entropy.hpp @@ -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) + +#ifndef WEBCPP_CRYPTO_DETAIL_BACKEND_ENTROPY_HPP +#define WEBCPP_CRYPTO_DETAIL_BACKEND_ENTROPY_HPP + +#include + +#include +#include + +namespace webcpp::crypto::detail::backend { + +/** + * The entropy source (design D4): `fill(bytes)` fills every byte or fails, with + * `entropy_unavailable`, or `errc::not_supported` where there is no source; never a partial fill + * reported as success. + * + * Beyond the concept (design D2): `fill` holds no state, so programs call it concurrently from any + * thread; it allocates nothing of the C++ heap or the program's; a source that is a backend + * library reads its canary before its first call, as every engine does. + */ +template +concept entropy_source = requires(std::span output_bytes) { + { Source::fill(output_bytes) } noexcept -> fallible; +}; + +} // namespace webcpp::crypto::detail::backend + +#endif // WEBCPP_CRYPTO_DETAIL_BACKEND_ENTROPY_HPP diff --git a/include/webcpp/crypto/detail/backend/keys.hpp b/include/webcpp/crypto/detail/backend/keys.hpp new file mode 100644 index 0000000..c717c0c --- /dev/null +++ b/include/webcpp/crypto/detail/backend/keys.hpp @@ -0,0 +1,76 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_CRYPTO_DETAIL_BACKEND_KEYS_HPP +#define WEBCPP_CRYPTO_DETAIL_BACKEND_KEYS_HPP + +#include + +#include +#include +#include + +/** + * The key capabilities (design D3, D4), split by what each does to the key, with the same + * operation names on every curve: + * + * | Capability | Operation | Needs the secret in memory | + * | --- | --- | --- | + * | `*_import` | `import_secret(state, secret)` | yes, briefly | + * | `*_generate` | `generate(state)`, the backend drawing the secret | no | + * | `*_public` | `public_key(state, out)` | no | + * | the uses | `sign`, `agree`, `ecdh_x`, ... on `state const&` | no | + * | `*_export` | `export_secret(state, out)` | yes | + * + * A state may be an opaque handle: every use reads the state only through its engine, so a + * backend whose keys never leave it implements generate, public and the uses without import or + * export. Each key engine is a `stateful_engine` (`move`, `reset` releasing a handle). Export may + * fail at run time (`not_supported`, a key a token holds), so it returns `result`. + * + * The four key concepts take no curve: every curve's import, generate and export are the same + * constraint (`ed25519_import`, `x25519_import` and `p256_import` all name @ref key_import, over + * the shared @ref secret_key_size), and only `*_public` differs by its size. A concept therefore + * does not tell an X25519 engine from a P-256 one; the engine's family does, as its table cell + * carries it (task 3.1). + */ +namespace webcpp::crypto::detail::backend { + +/** A curve's secret key size, the same for its three curves here: 32 bytes. */ +inline constexpr std::size_t secret_key_size = 32; + +/** `import_secret(state, secret)`: a key from its secret bytes, refused when out of range. */ +template +concept key_import = stateful_engine && + requires(Engine::state& engine_state, + std::span secret_bytes) { + { Engine::import_secret(engine_state, secret_bytes) } noexcept -> fallible; + }; + +/** `generate(state)`: a key whose secret the backend draws itself. */ +template +concept key_generate = stateful_engine && requires(Engine::state& engine_state) { + { Engine::generate(engine_state) } noexcept -> fallible; +}; + +/** `export_secret(state, out)`: the secret bytes back, written only on success. */ +template +concept key_export = + stateful_engine && requires(Engine::state const& engine_state, + std::span secret_output) { + { Engine::export_secret(engine_state, secret_output) } noexcept -> fallible; + }; + +/** `public_key(state, out)`: the public key of a state, of `PublicSize` bytes. */ +template +concept key_public = + stateful_engine && + requires(Engine::state const& engine_state, std::span public_output) { + { Engine::public_key(engine_state, public_output) } noexcept -> fallible; + }; + +} // namespace webcpp::crypto::detail::backend + +#endif // WEBCPP_CRYPTO_DETAIL_BACKEND_KEYS_HPP diff --git a/include/webcpp/crypto/detail/backend/p256.hpp b/include/webcpp/crypto/detail/backend/p256.hpp new file mode 100644 index 0000000..9dcdeeb --- /dev/null +++ b/include/webcpp/crypto/detail/backend/p256.hpp @@ -0,0 +1,140 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_CRYPTO_DETAIL_BACKEND_P256_HPP +#define WEBCPP_CRYPTO_DETAIL_BACKEND_P256_HPP + +#include +#include + +#include +#include +#include +#include + +/** + * P-256's capabilities (design D4), the key ones per @ref key_import and its siblings, over the + * shared @ref secret_key_size. + */ +namespace webcpp::crypto::detail::backend { + +/** P-256's uncompressed point size: 0x04, x, y. */ +inline constexpr std::size_t p256_point_size = 65; +/** P-256's field element and scalar size: a coordinate, a digest, a shared x. */ +inline constexpr std::size_t p256_element_size = 32; +/** P-256's ECDSA signature size, r || s. */ +inline constexpr std::size_t p256_signature_size = 64; +/** The longest DER form of a P-256 ECDSA signature. */ +inline constexpr std::size_t p256_der_max_size = 72; + +/** P-256 from its scalar, `0 < d < n`. */ +template +concept p256_import = key_import; +/** P-256 drawn by the backend. */ +template +concept p256_generate = key_generate; +/** P-256's public point, uncompressed. */ +template +concept p256_public = key_public; +/** P-256's scalar back. */ +template +concept p256_export = key_export; + +/** + * P-256's points, on public data and with no state: `valid_point(point)` and + * `decompress(parity_prefix, x, y)`, each a predicate. + */ +template +concept p256_point = + requires(std::span point_bytes, std::uint8_t parity_prefix, + std::span x_bytes, + std::span y_output) { + { Engine::valid_point(point_bytes) } noexcept -> std::same_as; + { Engine::decompress(parity_prefix, x_bytes, y_output) } noexcept -> std::same_as; + }; + +/** `sign(state, digest, signature)`: ECDSA over a 32-byte digest, the signature r || s. */ +template +concept p256_ecdsa_signing = + stateful_engine && + requires(Engine::state const& engine_state, + std::span digest_bytes, + std::span signature_output) { + { Engine::sign(engine_state, digest_bytes, signature_output) } noexcept -> fallible; + }; + +/** `verify(point, digest, signature)`: on public data, a predicate. */ +template +concept p256_ecdsa_verifying = + requires(std::span point_bytes, + std::span digest_bytes, + std::span signature_bytes) { + { + Engine::verify(point_bytes, digest_bytes, signature_bytes) + } noexcept -> std::same_as; + }; + +/** + * `sign_message(state, message, signature)`: ECDSA with SHA-256 over the message itself, the + * signature r || s. The form of a backend that hashes inside and takes no digest, as WebCrypto's + * ECDSA does (the browser backend's synchronous `sign`); a backend has this form, the digest one + * (@ref p256_ecdsa_signing) or both. A message is signed on either form; a prehashed digest only on + * the digest form, which a message-only backend refuses. + * + * The two forms differ by name on purpose: a 32-byte digest view converts to a view of any length, + * so an engine's `sign` that took a message would also satisfy the digest concept were the names + * the same. `sign` is always the digest form, `sign_message` always the message form. + */ +template +concept p256_ecdsa_message_signing = + stateful_engine && + requires(Engine::state const& engine_state, std::span message_bytes, + std::span signature_output) { + { + Engine::sign_message(engine_state, message_bytes, signature_output) + } noexcept -> fallible; + }; + +/** + * `verify_message(point, message, signature)`: on public data, ECDSA with SHA-256 over the message + * itself; `invalid_signature` when the signature does not verify, another error when the backend + * fails. The message form beside @ref p256_ecdsa_verifying, as for signing. + */ +template +concept p256_ecdsa_message_verifying = + requires(std::span point_bytes, + std::span message_bytes, + std::span signature_bytes) { + { + Engine::verify_message(point_bytes, message_bytes, signature_bytes) + } noexcept -> fallible; + }; + +/** `ecdh_x(state, peer_point, shared)`: the shared point's x coordinate (WebCrypto's form). */ +template +concept p256_ecdh = + stateful_engine && requires(Engine::state const& engine_state, + std::span peer_point, + std::span shared_output) { + { Engine::ecdh_x(engine_state, peer_point, shared_output) } noexcept -> fallible; + }; + +/** + * ECDSA's DER signature form, on public data: `to_der(signature, out)` gives the DER length (at + * most @ref p256_der_max_size), `from_der(der, signature)` is a predicate. + */ +template +concept ecdsa_der = requires(std::span signature_bytes, + std::span der_output, + std::span der_bytes, + std::span signature_output) { + { Engine::to_der(signature_bytes, der_output) } noexcept -> std::same_as; + { Engine::from_der(der_bytes, signature_output) } noexcept -> std::same_as; +}; + +} // namespace webcpp::crypto::detail::backend + +#endif // WEBCPP_CRYPTO_DETAIL_BACKEND_P256_HPP diff --git a/include/webcpp/crypto/detail/backend/secp256k1.hpp b/include/webcpp/crypto/detail/backend/secp256k1.hpp new file mode 100644 index 0000000..472064d --- /dev/null +++ b/include/webcpp/crypto/detail/backend/secp256k1.hpp @@ -0,0 +1,419 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_CRYPTO_DETAIL_BACKEND_SECP256K1_HPP +#define WEBCPP_CRYPTO_DETAIL_BACKEND_SECP256K1_HPP + +#include +#include + +#include +#include +#include +#include + +/** + * secp256k1's capabilities (design D4, D8): the key ones per @ref key_import and its siblings, over + * the shared @ref secret_key_size, then one concept per protocol. + * + * secp256k1's engines are `detail::secp256k1_engine`, one specialization per + * capability tag of @ref secp256k1_capabilities. The key engine holds the key pair's state; every + * other engine has none of its own and reads the key engine's, which it names `key_state` (as + * Ed25519ph names its key engine). The curve's public data are the engines' own types, which every + * engine that takes one names: a point (`point`), an x-only key (`xonly_point`), and MuSig2's and + * silent payments' objects. The public types hold those values and hand them to the engines; a + * function over many objects carves arrays of pointers to them from the caller's workspace and + * passes the arrays. + */ +namespace webcpp::crypto::detail::backend { + +/** The size of a SEC1 compressed point: 02 or 03, then x. */ +inline constexpr std::size_t secp256k1_compressed_size = 33; +/** The size of a SEC1 uncompressed point: 04, x, y. */ +inline constexpr std::size_t secp256k1_uncompressed_size = 65; +/** The size of a BIP340 x-only key, of a digest, of a tweak and of the randomness inputs. */ +inline constexpr std::size_t secp256k1_element_size = 32; +/** The size of an ECDSA or a Schnorr signature: r then s, or BIP340's R.x then s. */ +inline constexpr std::size_t secp256k1_signature_size = 64; +/** The size of a recoverable signature: r, s, then the recovery id. */ +inline constexpr std::size_t secp256k1_recoverable_size = 65; +/** The longest strict DER form of an ECDSA signature. */ +inline constexpr std::size_t secp256k1_der_max_size = 72; +/** The size of an ElligatorSwift encoding. */ +inline constexpr std::size_t secp256k1_ellswift_size = 64; +/** The size of a MuSig2 public or aggregate nonce: two compressed points. */ +inline constexpr std::size_t secp256k1_musig_nonce_size = 66; +/** The size of a serialized silent payments outpoint, the smallest of a transaction. */ +inline constexpr std::size_t secp256k1_outpoint_size = 36; + +/** The capability tags of `secp256k1_engine` (design D8). */ +namespace secp256k1_capabilities { + +/** The key pair: import, public, export, and the key pair's own x-only form. */ +struct key {}; + +/** The public points and x-only keys: parse, serialize, compare, the x-only form. */ +struct point {}; + +/** ECDSA over a 32-byte digest, and its signature's forms: low S and DER. */ +struct ecdsa {}; + +/** BIP340's Schnorr signatures. */ +struct schnorr {}; + +/** Recoverable ECDSA: the signature with its recovery id, and the key it recovers. */ +struct recoverable {}; + +/** ECDH in its three forms: the shared x, libsecp256k1's hashed form and the shared point. */ +struct ecdh {}; + +/** The tweaks of secret keys, points, x-only keys and key pairs, and the sum of points. */ +struct tweak {}; + +/** ElligatorSwift's encoding and BIP 324's key exchange. */ +struct ellswift {}; + +/** MuSig2 (BIP327). */ +struct musig {}; + +/** Silent payments (BIP352). */ +struct silent_payments {}; + +} // namespace secp256k1_capabilities + +/** + * secp256k1 from its secret key, in a signing context of its own: `context_size()`, the bytes the + * public layer allocates for it (an engine never allocates, design D2); `valid_secret(secret)`, + * the secret's check before any allocation; `start(state, storage, seed)`, the context made in + * that storage and randomised; then `import_secret`. `reset` destroys the context and leaves its + * storage to the public layer. + */ +template +concept secp256k1_import = + key_import && requires(Engine::state& engine_state, void* context_storage, + std::span secret_bytes) { + { Engine::context_size() } noexcept -> std::same_as; + { Engine::valid_secret(secret_bytes) } noexcept -> std::same_as; + { Engine::start(engine_state, context_storage, secret_bytes) } noexcept -> fallible; + }; +/** secp256k1 drawn by the backend. */ +template +concept secp256k1_generate = key_generate; + +/** + * secp256k1's public key: `public_key(state, out)`, compressed, as every curve's; and the key's + * `point` (`public_point(state, point)`) and BIP340 x-only form with the parity of its y + * (`xonly_key(state, xonly, parity)`), both public, which the curve's public types hold. + */ +template +concept secp256k1_public = key_public && + requires(Engine::state const& engine_state, Engine::point& point_output, + Engine::xonly_point& xonly_output, int& parity_output) { + { + Engine::public_point(engine_state, point_output) + } noexcept -> std::same_as; + { + Engine::xonly_key(engine_state, xonly_output, parity_output) + } noexcept -> std::same_as; + }; + +/** secp256k1's secret key back. */ +template +concept secp256k1_export = key_export; + +/** + * The points and x-only keys, on public data and with no state: `parse` (a SEC1 point of 33 or 65 + * bytes, a predicate), `serialize` in both forms, `compare` (a total order, negative, zero or + * positive), `to_xonly` (the parity dropped), and the x-only key's `parse_xonly`, + * `serialize_xonly` and `compare_xonly`. + */ +template +concept secp256k1_point = + requires(std::span encoded_bytes, Engine::point& point_output, + Engine::point const& point_value, + std::span compressed_output, + std::span uncompressed_output, + std::span xonly_bytes, + Engine::xonly_point& xonly_output, Engine::xonly_point const& xonly_value, + std::span xonly_bytes_output) { + { Engine::parse(encoded_bytes, point_output) } noexcept -> std::same_as; + { Engine::serialize(point_value, compressed_output) } noexcept -> std::same_as; + { Engine::serialize(point_value, uncompressed_output) } noexcept -> std::same_as; + { Engine::compare(point_value, point_value) } noexcept -> std::same_as; + { Engine::to_xonly(point_value, xonly_output) } noexcept -> std::same_as; + { Engine::parse_xonly(xonly_bytes, xonly_output) } noexcept -> std::same_as; + { Engine::serialize_xonly(xonly_value, xonly_bytes_output) } noexcept -> std::same_as; + { Engine::compare_xonly(xonly_value, xonly_value) } noexcept -> std::same_as; + }; + +/** + * `sign(key_state, digest, extra_entropy, signature)`: ECDSA over a 32-byte digest, RFC 6979's + * nonce with `extra_entropy` (empty, or 32 bytes mixed in: hedged; another size is refused), the + * signature r || s, low S. + */ +template +concept secp256k1_ecdsa_signing = + requires(Engine::key_state const& key_state, + std::span digest_bytes, + std::span extra_entropy, + std::span signature_output) { + { + Engine::sign(key_state, digest_bytes, extra_entropy, signature_output) + } noexcept -> fallible; + }; + +/** `verify(point, digest, signature)`: on public data, a predicate; a high S does not verify. */ +template +concept secp256k1_ecdsa_verifying = + requires(Engine::point const& point_value, + std::span digest_bytes, + std::span signature_bytes) { + { + Engine::verify(point_value, digest_bytes, signature_bytes) + } noexcept -> std::same_as; + }; + +/** + * An ECDSA signature's forms, on public data: `valid_compact` (0 < r, s < n), `is_low_s`, + * `low_s(signature, low, was_high)` (false when not valid), `to_der(signature, der, size)` (false + * when not valid) and `from_der(der, signature)` (false for anything that is not strict DER of a + * valid signature). + */ +template +concept secp256k1_ecdsa_forms = + requires(std::span signature_bytes, + std::span signature_output, bool& was_high, + std::span der_output, std::size_t& der_size, + std::span der_bytes) { + { Engine::valid_compact(signature_bytes) } noexcept -> std::same_as; + { Engine::is_low_s(signature_bytes) } noexcept -> std::same_as; + { + Engine::low_s(signature_bytes, signature_output, was_high) + } noexcept -> std::same_as; + { Engine::to_der(signature_bytes, der_output, der_size) } noexcept -> std::same_as; + { Engine::from_der(der_bytes, signature_output) } noexcept -> std::same_as; + }; + +/** + * `sign(key_state, message, auxiliary_random, signature)`: BIP340's Schnorr signature of a message + * of any length, with its 32 bytes of auxiliary randomness. + */ +template +concept secp256k1_schnorr_signing = + requires(Engine::key_state const& key_state, std::span message_bytes, + std::span auxiliary_random, + std::span signature_output) { + { + Engine::sign(key_state, message_bytes, auxiliary_random, signature_output) + } noexcept -> fallible; + }; + +/** `verify(xonly_point, message, signature)`: on public data, a predicate. */ +template +concept secp256k1_schnorr_verifying = + requires(Engine::xonly_point const& xonly_value, std::span message_bytes, + std::span signature_bytes) { + { + Engine::verify(xonly_value, message_bytes, signature_bytes) + } noexcept -> std::same_as; + }; + +/** + * Recoverable ECDSA: `sign(key_state, digest, signature)`, r, s and the recovery id; and + * `recover(signature, digest, point)`, a predicate on public data that refuses an id above 3; a + * high S is the caller's to refuse first, with the ECDSA engine's `is_low_s`. + */ +template +concept secp256k1_recoverable = + requires(Engine::key_state const& key_state, + std::span digest_bytes, + std::span signature_output, + std::span signature_bytes, + Engine::point& point_output) { + { Engine::sign(key_state, digest_bytes, signature_output) } noexcept -> fallible; + { + Engine::recover(signature_bytes, digest_bytes, point_output) + } noexcept -> std::same_as; + }; + +/** + * ECDH with a peer's point: `shared_x` (the shared point's x), `shared_hashed` (libsecp256k1's + * SHA-256 of the compressed shared point) and `shared_point` (SEC1 uncompressed), each a secret. + */ +template +concept secp256k1_ecdh = + requires(Engine::key_state const& key_state, Engine::point const& peer_point, + std::span shared_output, + std::span point_output) { + { Engine::shared_x(key_state, peer_point, shared_output) } noexcept -> fallible; + { Engine::shared_hashed(key_state, peer_point, shared_output) } noexcept -> fallible; + { Engine::shared_point(key_state, peer_point, point_output) } noexcept -> fallible; + }; + +/** + * The tweaks: of a secret key (`secret_add`, `secret_mul`, `secret_negate`, the key checked first, + * each refusing with `invalid_secret_key`), of a point in place (`point_add`, `point_mul`, + * `point_negate`, predicates), of an x-only key (`xonly_add`, the tweaked key and its parity, and + * `xonly_check`, BIP341's commitment check), of a key pair in place (`key_xonly_add`), and the sum + * of points (`combine`, over an array of pointers the caller carved). + */ +template +concept secp256k1_tweak = requires( + Engine::key_state& key_state, + std::span secret_bytes, + std::span tweak_bytes, + std::span secret_output, Engine::point& point_value, + Engine::xonly_point const& xonly_value, Engine::xonly_point& xonly_output, int& parity_output, + int parity_value, std::span point_pointers) { + { Engine::secret_add(secret_bytes, tweak_bytes, secret_output) } noexcept -> fallible; + { Engine::secret_mul(secret_bytes, tweak_bytes, secret_output) } noexcept -> fallible; + { Engine::secret_negate(secret_bytes, secret_output) } noexcept -> fallible; + { Engine::point_add(point_value, tweak_bytes) } noexcept -> std::same_as; + { Engine::point_mul(point_value, tweak_bytes) } noexcept -> std::same_as; + { Engine::point_negate(point_value) } noexcept -> std::same_as; + { + Engine::xonly_add(xonly_value, tweak_bytes, xonly_output, parity_output) + } noexcept -> std::same_as; + { + Engine::xonly_check(xonly_value, tweak_bytes, xonly_value, parity_value) + } noexcept -> std::same_as; + { Engine::key_xonly_add(key_state, tweak_bytes) } noexcept -> std::same_as; + { Engine::combine(point_pointers, point_value) } noexcept -> std::same_as; +}; + +/** + * ElligatorSwift: `encode(point, randomness, encoding)` and `decode(encoding, point)` on public + * data, `create(key_state, randomness, encoding)` from the key pair, and BIP 324's + * `xdh(key_state, initiator, responder, responder_side, shared)`. + */ +template +concept secp256k1_ellswift = + requires(Engine::key_state const& key_state, Engine::point const& point_value, + Engine::point& point_output, + std::span randomness_bytes, + std::span encoding_output, + std::span encoding_bytes, + bool responder_side, std::span shared_output) { + { + Engine::encode(point_value, randomness_bytes, encoding_output) + } noexcept -> std::same_as; + { Engine::decode(encoding_bytes, point_output) } noexcept -> std::same_as; + { Engine::create(key_state, randomness_bytes, encoding_output) } noexcept -> fallible; + { + Engine::xdh(key_state, encoding_bytes, encoding_bytes, responder_side, shared_output) + } noexcept -> fallible; + }; + +/** + * MuSig2 over the engine's objects (`key_cache`, `public_nonce`, `aggregate_nonce`, `session`, + * `partial_signature`, `secret_nonce`): key aggregation and its tweaks, nonce generation (from the + * session's randomness, which the engine zeroes), nonce aggregation and processing, partial + * signing, verifying and aggregation, and the serial forms. + */ +template +concept secp256k1_musig = requires( + Engine::key_state const& key_state, Engine::point const& point_value, + Engine::point& point_output, Engine::key_cache& cache_output, + Engine::key_cache const& cache_value, Engine::public_nonce& public_output, + Engine::public_nonce const& public_value, Engine::aggregate_nonce& aggregate_output, + Engine::aggregate_nonce const& aggregate_value, Engine::session& session_output, + Engine::session const& session_value, Engine::partial_signature& partial_output, + Engine::partial_signature const& partial_value, Engine::secret_nonce& secret_value, + std::span point_pointers, + std::span nonce_pointers, + std::span partial_pointers, + std::span element_bytes, + std::span random_bytes, + std::span optional_bytes, + std::span signature_output, + std::span nonce_bytes, + std::span nonce_output, + std::span element_output) { + { Engine::key_aggregate(point_pointers, cache_output) } noexcept -> std::same_as; + { Engine::aggregate_point(cache_value, point_output) } noexcept -> std::same_as; + { Engine::tweak_add(cache_output, element_bytes) } noexcept -> std::same_as; + { Engine::tweak_xonly_add(cache_output, element_bytes) } noexcept -> std::same_as; + { + Engine::nonce_generate(key_state, random_bytes, optional_bytes, cache_value, optional_bytes, + secret_value, public_output) + } noexcept -> fallible; + { Engine::nonce_aggregate(nonce_pointers, aggregate_output) } noexcept -> std::same_as; + { + Engine::nonce_process(aggregate_value, element_bytes, cache_value, session_output) + } noexcept -> std::same_as; + { + Engine::partial_sign(key_state, secret_value, cache_value, session_value, partial_output) + } noexcept -> fallible; + { + Engine::partial_verify(partial_value, public_value, point_value, cache_value, session_value) + } noexcept -> std::same_as; + { + Engine::partial_aggregate(session_value, partial_pointers, signature_output) + } noexcept -> std::same_as; + { Engine::parse(nonce_bytes, public_output) } noexcept -> std::same_as; + { Engine::serialize(public_value, nonce_output) } noexcept -> std::same_as; + { Engine::parse(nonce_bytes, aggregate_output) } noexcept -> std::same_as; + { Engine::serialize(aggregate_value, nonce_output) } noexcept -> std::same_as; + { Engine::parse(element_bytes, partial_output) } noexcept -> std::same_as; + { Engine::serialize(partial_value, element_output) } noexcept -> std::same_as; +}; + +/** + * Silent payments over the engine's objects (`recipient`, `summary`, `found_output`): the sender's + * outputs from the inputs' key pairs (a group past BIP 352's limit told apart by + * `over_group_limit`), a label of a scan key, a labelled spend key, the summary of a transaction's + * inputs, and the recipient's scan, whose found outputs the caller reads through + * `found_output_key`, `found_tweak` and `found_label`. A scan with labels calls back through a + * `label_lookup` the caller passes; a null one scans without labels. An empty span of inputs + * passes a null data, as libsecp256k1 requires of a side with no input. + */ +template +concept secp256k1_silent_payments = requires( + Engine::key_state const& key_state, Engine::point const& point_value, + Engine::point& point_output, Engine::recipient& recipient_output, + std::span recipient_pointers, + std::span xonly_outputs, + std::span xonly_pointers, + std::span point_pointers, + std::span key_handles, + std::span secret_pointers, + std::span outpoint_bytes, + std::uint32_t label_number, std::span label_output, + std::span label_bytes, + std::span element_output, Engine::summary& summary_output, + Engine::summary const& summary_value, std::span found_pointers, + std::uint32_t& found_count, Engine::label_lookup const* label_lookup, + Engine::found_output const& found_value) { + { Engine::key_handle_of(key_state) } noexcept -> std::same_as; + { + Engine::make_recipient(point_value, point_value, std::size_t{}, recipient_output) + } noexcept -> std::same_as; + { + Engine::create_outputs(key_state, xonly_outputs, recipient_pointers, outpoint_bytes, + key_handles, secret_pointers) + } noexcept -> std::same_as; + { Engine::over_group_limit(recipient_pointers) } noexcept -> std::same_as; + { + Engine::create_label(key_state, label_number, label_output, element_output) + } noexcept -> fallible; + { Engine::labeled_spend_key(point_value, label_bytes, point_output) } noexcept -> fallible; + { + Engine::make_summary(outpoint_bytes, xonly_pointers, point_pointers, summary_output) + } noexcept -> std::same_as; + { + Engine::scan(key_state, summary_value, point_value, xonly_pointers, found_pointers, + found_count, label_lookup) + } noexcept -> fallible; + { Engine::found_output_key(found_value, element_output) } noexcept -> std::same_as; + { + Engine::found_tweak(found_value) + } noexcept -> std::same_as>; + { Engine::found_label(found_value, label_output) } noexcept -> std::same_as; +}; + +} // namespace webcpp::crypto::detail::backend + +#endif // WEBCPP_CRYPTO_DETAIL_BACKEND_SECP256K1_HPP diff --git a/include/webcpp/crypto/detail/backend/symmetric.hpp b/include/webcpp/crypto/detail/backend/symmetric.hpp new file mode 100644 index 0000000..2c4894f --- /dev/null +++ b/include/webcpp/crypto/detail/backend/symmetric.hpp @@ -0,0 +1,141 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_CRYPTO_DETAIL_BACKEND_SYMMETRIC_HPP +#define WEBCPP_CRYPTO_DETAIL_BACKEND_SYMMETRIC_HPP + +#include + +#include + +#include +#include +#include +#include +#include + +/** + * The symmetric capabilities (design D4): the AES block cipher, GCM, the AEADs, the secret boxes, + * the raw stream cipher and the single-use key authenticator. Every operation is `noexcept`; one + * that can fail returns `result`; outputs are written into the caller's spans. + */ +namespace webcpp::crypto::detail::backend { + +/** A keyed state's `init(state, key)`: the key's bytes, of a size the public type has checked. */ +template +concept keyed_init = + requires(Engine::state& engine_state, std::span key_bytes) { + { Engine::init(engine_state, key_bytes) } noexcept -> fallible; + }; + +/** + * The AES block cipher: `init`, then `encrypt` and `decrypt` of one 16-byte block in place. + * + * The key size is not a parameter of the concept (D4 wrote `block_cipher`): `init` + * takes the key as a dynamic span the public type has sized, so no expression could check it; the + * engine is one class per key size, `block_engine`, and the table's cells assert + * the concept per key size (STATUS.md ruling 1.1-I2). + */ +template +concept block_cipher = stateful_engine && keyed_init && + requires(Engine::state& engine_state, std::span block_bytes) { + { Engine::encrypt(engine_state, block_bytes) } noexcept -> fallible; + { Engine::decrypt(engine_state, block_bytes) } noexcept -> fallible; + }; + +/** + * GCM over a block cipher, one-shot and incremental alike: `start(state, is_sealing, nonce, + * associated_data)`, `run(state, data)` in place, any number of times, then `tag(state, out)` on + * sealing or `check(state, tag)` on opening (the comparison in constant time, its verdict + * `authentication_failed`), and `abandon(state)` for a message left unfinished. + * + * As for @ref block_cipher, the key size is the engine class's, not the concept's (ruling 1.1-I2). + */ +template +concept gcm = + stateful_engine && keyed_init && + requires( + Engine::state& engine_state, bool is_sealing, std::span nonce_bytes, + std::span associated_data_bytes, std::span data_bytes, + boost::hash2::digest<16>& tag_output, std::array const& expected_tag) { + { + Engine::start(engine_state, is_sealing, nonce_bytes, associated_data_bytes) + } noexcept -> fallible; + { Engine::run(engine_state, data_bytes) } noexcept -> fallible; + { Engine::tag(engine_state, tag_output) } noexcept -> fallible; + { Engine::check(engine_state, expected_tag) } noexcept -> fallible; + { Engine::abandon(engine_state) } noexcept -> std::same_as; + }; + +/** + * An AEAD of a family: `seal(state, nonce, associated_data, data, tag)` encrypts the data in place + * and writes the tag; `open(state, nonce, associated_data, data, tag)` checks the tag in constant + * time and decrypts in place only when it holds (`authentication_failed` otherwise). The tag has + * the family's `tag_size`; the nonce is a dynamic span, its size the family's, checked by the + * public type, so it is not part of the contract. + */ +template +concept aead = + stateful_engine && keyed_init && + requires(Engine::state& engine_state, std::span nonce_bytes, + std::span associated_data_bytes, + std::span data_bytes, boost::hash2::digest& tag_output, + std::array const& expected_tag) { + { + Engine::seal(engine_state, nonce_bytes, associated_data_bytes, data_bytes, tag_output) + } noexcept -> fallible; + { + Engine::open(engine_state, nonce_bytes, associated_data_bytes, data_bytes, expected_tag) + } noexcept -> fallible; + }; + +/** + * A secret box of a family: an AEAD without associated data, its nonce the family's + * `nonce_size`. + */ +template +concept authenticated_box = + stateful_engine && keyed_init && + requires(Engine::state& engine_state, + std::span nonce_bytes, + std::span data_bytes, boost::hash2::digest& tag_output, + std::array const& expected_tag) { + { Engine::seal(engine_state, nonce_bytes, data_bytes, tag_output) } noexcept -> fallible; + { Engine::open(engine_state, nonce_bytes, data_bytes, expected_tag) } noexcept -> fallible; + }; + +/** + * A raw stream cipher of a family (primitives' D4): `apply(state, nonce, initial_counter, data)` + * XORs the keystream from block `initial_counter` into the data in place; the nonce has the + * family's `nonce_size`, the counter its `counter_type`, and the public type has checked that the + * data is non-empty and within the counter. + */ +template +concept stream_cipher = + stateful_engine && keyed_init && + requires(Engine::state& engine_state, + std::span nonce_bytes, + Family::counter_type initial_counter, std::span data_bytes) { + { + Engine::apply(engine_state, nonce_bytes, initial_counter, data_bytes) + } noexcept -> fallible; + }; + +/** + * A single-use key authenticator of a family (primitives' D14): one static + * `authenticate(key, message, tag)` and no state, since no object keeps a key; the comparison of + * `verify` is crypto's own, in constant time, so the engine has no `verify`. + */ +template +concept authenticator = requires(std::span key_bytes, + std::span message_bytes, + std::span tag_bytes) { + { Engine::authenticate(key_bytes, message_bytes, tag_bytes) } noexcept -> fallible; +}; + +} // namespace webcpp::crypto::detail::backend + +#endif // WEBCPP_CRYPTO_DETAIL_BACKEND_SYMMETRIC_HPP diff --git a/include/webcpp/crypto/detail/backend/x25519.hpp b/include/webcpp/crypto/detail/backend/x25519.hpp new file mode 100644 index 0000000..5253f8f --- /dev/null +++ b/include/webcpp/crypto/detail/backend/x25519.hpp @@ -0,0 +1,52 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_CRYPTO_DETAIL_BACKEND_X25519_HPP +#define WEBCPP_CRYPTO_DETAIL_BACKEND_X25519_HPP + +#include +#include + +#include +#include +#include + +/** + * X25519's capabilities (design D4), the key ones per @ref key_import and its siblings, over the + * shared @ref secret_key_size. + */ +namespace webcpp::crypto::detail::backend { + +/** The size of an X25519 key, secret or public, and of its shared secret. */ +inline constexpr std::size_t x25519_key_size = 32; + +/** X25519 from its secret bytes. */ +template +concept x25519_import = key_import; +/** X25519 drawn by the backend. */ +template +concept x25519_generate = key_generate; +/** X25519's public key, its base-point multiple. */ +template +concept x25519_public = key_public; +/** X25519's secret back. */ +template +concept x25519_export = key_export; + +/** `agree(state, peer_public_key, shared)`: refuses an all-zero shared secret. */ +template +concept x25519_agreement = stateful_engine && + requires(Engine::state const& engine_state, + std::span peer_public_key, + std::span shared_output) { + { + Engine::agree(engine_state, peer_public_key, shared_output) + } noexcept -> fallible; + }; + +} // namespace webcpp::crypto::detail::backend + +#endif // WEBCPP_CRYPTO_DETAIL_BACKEND_X25519_HPP diff --git a/include/webcpp/crypto/detail/capabilities.hpp b/include/webcpp/crypto/detail/capabilities.hpp index 5004455..0450845 100644 --- a/include/webcpp/crypto/detail/capabilities.hpp +++ b/include/webcpp/crypto/detail/capabilities.hpp @@ -130,6 +130,334 @@ struct ed25519ph; } // namespace webcpp::crypto::tags +namespace webcpp::crypto::capabilities { + +/** + * The capability `gcm` of the family AES-GCM, an operation `supports_v` counts: AES-GCM's `seal` + * and `open`, with a 128-, 192- or 256-bit key. + */ +struct gcm; + +/** + * The capability `aes_block` of the family AES block cipher, an operation `supports_v` counts: the + * AES block cipher, one 16-byte block with a 128-, 192- or 256-bit key. + */ +struct aes_block; + +/** + * The capability `secp256k1_import` of the family secp256k1, a key made from secret bytes the + * program gives: `from_secret` of a secp256k1 key pair. + */ +struct secp256k1_import; + +/** + * The capability `secp256k1_generate` of the family secp256k1, a key whose secret the backend + * draws: `generate` of a secp256k1 key pair drawn by the backend. + */ +struct secp256k1_generate; + +/** + * The capability `secp256k1_public` of the family secp256k1, the public key of a key: + * `public_key()` of a secp256k1 key pair. + */ +struct secp256k1_public; + +/** + * The capability `secp256k1_export` of the family secp256k1, secret bytes of a key handed out of + * the backend: `secret()`, `pkcs8` and the private PEM of a secp256k1 key pair. + */ +struct secp256k1_export; + +/** + * The capability `secp256k1_point` of the family secp256k1, an operation on public values the + * family's types need: a secp256k1 public key's points and x-only keys: read, written and compared. + */ +struct secp256k1_point; + +/** + * The capability `secp256k1_ecdsa_signing` of the family secp256k1, an operation `supports_v` + * counts: ECDSA signing with a secp256k1 key pair. + */ +struct secp256k1_ecdsa_signing; + +/** + * The capability `secp256k1_ecdsa_verifying` of the family secp256k1, an operation `supports_v` + * counts: ECDSA verifying with a secp256k1 public key. + */ +struct secp256k1_ecdsa_verifying; + +/** + * The capability `secp256k1_ecdsa_forms` of the family secp256k1, an operation on public values the + * family's types need: a secp256k1 ECDSA signature's forms: compact, low S and DER. + */ +struct secp256k1_ecdsa_forms; + +/** + * The capability `secp256k1_schnorr_signing` of the family secp256k1, an operation `supports_v` + * counts: BIP 340's Schnorr signing with a secp256k1 key pair. + */ +struct secp256k1_schnorr_signing; + +/** + * The capability `secp256k1_schnorr_verifying` of the family secp256k1, an operation `supports_v` + * counts: BIP 340's Schnorr verifying with an x-only public key. + */ +struct secp256k1_schnorr_verifying; + +/** + * The capability `secp256k1_recoverable` of the family secp256k1, an operation `supports_v` counts: + * recoverable ECDSA: signing, and the public key recovered from a signature. + */ +struct secp256k1_recoverable; + +/** + * The capability `secp256k1_ecdh` of the family secp256k1, an operation `supports_v` counts: + * `agree` of a secp256k1 key pair with a peer's public key. + */ +struct secp256k1_ecdh; + +/** + * The capability `secp256k1_tweak` of the family secp256k1, an operation on public values the + * family's types need: the tweaks of secp256k1's keys (BIP 32, BIP 341): added to or multiplied + * into a key, and points combined. + */ +struct secp256k1_tweak; + +/** + * The capability `ed25519_import` of the family Ed25519, a key made from secret bytes the program + * gives: `from_secret` of an Ed25519 key pair, from its seed. + */ +struct ed25519_import; + +/** + * The capability `ed25519_generate` of the family Ed25519, a key whose secret the backend draws: + * `generate` of an Ed25519 key pair drawn by the backend. + */ +struct ed25519_generate; + +/** + * The capability `ed25519_public` of the family Ed25519, the public key of a key: `public_key()` of + * an Ed25519 key pair. + */ +struct ed25519_public; + +/** + * The capability `ed25519_export` of the family Ed25519, secret bytes of a key handed out of the + * backend: `secret()`, `pkcs8` and the private PEM of an Ed25519 key pair. + */ +struct ed25519_export; + +/** + * The capability `ed25519_signing` of the family Ed25519, an operation `supports_v` counts: Ed25519 + * signing of a message. + */ +struct ed25519_signing; + +/** + * The capability `ed25519_verifying` of the family Ed25519, an operation `supports_v` counts: + * Ed25519 verifying of a message. + */ +struct ed25519_verifying; + +/** + * The capability `ed25519_to_x25519` of the family Ed25519, secret bytes of a key handed out of the + * backend: an Ed25519 key pair's X25519 secret and an Ed25519 public key's X25519 public key. + */ +struct ed25519_to_x25519; + +/** + * The capability `ed25519ph` of the family Ed25519, an operation `supports_v` counts: Ed25519ph, + * signing and verifying a SHA-512 digest. + */ +struct ed25519ph; + +/** + * The capability `x25519_import` of the family X25519, a key made from secret bytes the program + * gives: `from_secret` of an X25519 key pair. + */ +struct x25519_import; + +/** + * The capability `x25519_generate` of the family X25519, a key whose secret the backend draws: + * `generate` of an X25519 key pair drawn by the backend. + */ +struct x25519_generate; + +/** + * The capability `x25519_public` of the family X25519, the public key of a key: `public_key()` of + * an X25519 key pair. + */ +struct x25519_public; + +/** + * The capability `x25519_export` of the family X25519, secret bytes of a key handed out of the + * backend: `secret()`, `pkcs8` and the private PEM of an X25519 key pair. + */ +struct x25519_export; + +/** + * The capability `x25519_agreement` of the family X25519, an operation `supports_v` counts: `agree` + * of an X25519 key pair with a peer's public key. + */ +struct x25519_agreement; + +/** + * The capability `kx` of the family crypto_kx, an operation `supports_v` counts: libsodium's key + * exchange: a client's and a server's session keys. + */ +struct kx; + +/** + * The capability `chacha20_poly1305` of the family ChaCha20-Poly1305, an operation `supports_v` + * counts: ChaCha20-Poly1305's `seal` and `open` (RFC 8439). + */ +struct chacha20_poly1305; + +/** + * The capability `chacha20_poly1305_original` of the family original ChaCha20-Poly1305, an + * operation `supports_v` counts: the original ChaCha20-Poly1305's `seal` and `open`, its 8-byte + * nonce. + */ +struct chacha20_poly1305_original; + +/** + * The capability `xchacha20_poly1305` of the family XChaCha20-Poly1305, an operation `supports_v` + * counts: XChaCha20-Poly1305's `seal` and `open`. + */ +struct xchacha20_poly1305; + +/** + * The capability `chacha20` of the family ChaCha20, an operation `supports_v` counts: ChaCha20's + * keystream applied to bytes. + */ +struct chacha20; + +/** + * The capability `poly1305` of the family Poly1305, an operation `supports_v` counts: Poly1305's + * tag of a message under a single-use key, and its verification. + */ +struct poly1305; + +/** + * The capability `secretbox_xsalsa20poly1305` of the family XSalsa20-Poly1305 secret box, an + * operation `supports_v` counts: the secret box over XSalsa20-Poly1305: `seal` and `open` with a + * shared key. + */ +struct secretbox_xsalsa20poly1305; + +/** + * The capability `secretbox_xchacha20poly1305` of the family XChaCha20-Poly1305 secret box, an + * operation `supports_v` counts: the secret box over XChaCha20-Poly1305: `seal` and `open` with a + * shared key. + */ +struct secretbox_xchacha20poly1305; + +/** + * The capability `box_xsalsa20poly1305` of the family X25519-XSalsa20-Poly1305 box, an operation + * `supports_v` counts: the public-key box over XSalsa20-Poly1305: `seal` and `open` between two key + * pairs. + */ +struct box_xsalsa20poly1305; + +/** + * The capability `box_xchacha20poly1305` of the family X25519-XChaCha20-Poly1305 box, an operation + * `supports_v` counts: the public-key box over XChaCha20-Poly1305: `seal` and `open` between two + * key pairs. + */ +struct box_xchacha20poly1305; + +/** + * The capability `sealed_box` of the family X25519-XSalsa20-Poly1305 sealed box, an operation + * `supports_v` counts: the sealed box: `seal` to a public key, `open` with its key pair. + */ +struct sealed_box; + +/** + * The capability `secp256k1_ellswift` of the family ElligatorSwift, an operation `supports_v` + * counts: ElligatorSwift's encodings and BIP 324's shared secret. + */ +struct secp256k1_ellswift; + +/** + * The capability `secp256k1_musig` of the family MuSig2, an operation `supports_v` counts: MuSig2's + * aggregated keys, nonces and partial signatures. + */ +struct secp256k1_musig; + +/** + * The capability `secp256k1_silent_payments` of the family BIP 352 silent payments, an operation + * `supports_v` counts: BIP 352's silent payments: the sender's outputs and the recipient's scan. + */ +struct secp256k1_silent_payments; + +/** + * The capability `p256_import` of the family P-256, a key made from secret bytes the program gives: + * `from_secret` of a P-256 key pair. + */ +struct p256_import; + +/** + * The capability `p256_generate` of the family P-256, a key whose secret the backend draws: + * `generate` of a P-256 key pair drawn by the backend. + */ +struct p256_generate; + +/** + * The capability `p256_public` of the family P-256, the public key of a key: `public_key()` of a + * P-256 key pair. + */ +struct p256_public; + +/** + * The capability `p256_export` of the family P-256, secret bytes of a key handed out of the + * backend: `secret()`, `pkcs8` and the private PEM of a P-256 key pair. + */ +struct p256_export; + +/** + * The capability `p256_point` of the family P-256, an operation on public values the family's types + * need: a P-256 public key's points: checked on the curve, and decompressed. + */ +struct p256_point; + +/** + * The capability `p256_ecdsa_signing` of the family P-256, an operation `supports_v` counts: ECDSA + * signing of a SHA-256 digest with a P-256 key pair. + */ +struct p256_ecdsa_signing; + +/** + * The capability `p256_ecdsa_verifying` of the family P-256, an operation `supports_v` counts: + * ECDSA verifying of a SHA-256 digest with a P-256 public key. + */ +struct p256_ecdsa_verifying; + +/** + * The capability `p256_ecdsa_message_signing` of the family P-256, an operation `supports_v` + * counts: ECDSA signing of a message, hashed with SHA-256 inside the backend. + */ +struct p256_ecdsa_message_signing; + +/** + * The capability `p256_ecdsa_message_verifying` of the family P-256, an operation `supports_v` + * counts: ECDSA verifying of a message, hashed with SHA-256 inside the backend. + */ +struct p256_ecdsa_message_verifying; + +/** + * The capability `p256_ecdh` of the family P-256, an operation `supports_v` counts: `agree` of a + * P-256 key pair with a peer's public key. + */ +struct p256_ecdh; + +/** + * The capability `p256_ecdsa_der` of the family P-256, an operation on public values the family's + * types need: a P-256 ECDSA signature's DER, written and read. + */ +struct p256_ecdsa_der; + +} // namespace webcpp::crypto::capabilities + namespace webcpp::crypto::detail { /** @@ -348,6 +676,294 @@ template <> inline constexpr bool linked = true; #endif +/** + * One capability cell of the table on the target being compiled (design D7, R8): + * whether `Backend`'s engine has the capability `Capability`. False but where a + * specialisation below makes it true. + * + * @tparam Capability A capability tag of `capabilities`. + * @tparam Backend A backend tag of `backends`. + */ +template +inline constexpr bool capability_supported = false; + +// Each capability cell on its family's targets. +// clang-format off +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +template <> +inline constexpr bool capability_supported = true; +#endif +// clang-format on + +/** + * Whether secret key bytes may leave `Backend` (design D3's and D6's amendments): the table's + * `exports_secret_keys` of its row, true unless the row says false. False for any type that is no + * backend of the table. + * + * @tparam Backend A backend tag of `backends`. + */ +template +inline constexpr bool exports_secret_keys_v = false; +template <> +inline constexpr bool exports_secret_keys_v = true; +template <> +inline constexpr bool exports_secret_keys_v = true; +template <> +inline constexpr bool exports_secret_keys_v = true; +template <> +inline constexpr bool exports_secret_keys_v = true; +template <> +inline constexpr bool exports_secret_keys_v = true; + +/** + * Whether secret key bytes may enter `Backend` (design D3's and D6's amendments): the table's + * `imports_secret_keys` of its row, true unless the row says false. False for any type that is no + * backend of the table. + * + * @tparam Backend A backend tag of `backends`. + */ +template +inline constexpr bool imports_secret_keys_v = false; +template <> +inline constexpr bool imports_secret_keys_v = true; +template <> +inline constexpr bool imports_secret_keys_v = true; +template <> +inline constexpr bool imports_secret_keys_v = true; +template <> +inline constexpr bool imports_secret_keys_v = true; +template <> +inline constexpr bool imports_secret_keys_v = true; + +/** + * A list of backend tags. + * + * @tparam Backends The tags. + */ +template +struct backend_list {}; + +/** + * The backends crypto ships, every tag of `backends` built for a target of its own: + * the list over which `capabilities_test` checks that an engine meeting a + * capability's concept has its cell (design D5, R7). + */ +// clang-format off +using shipped_backends = backend_list; +// clang-format on + } // namespace webcpp::crypto::detail // The body of each family's primary engine, which a backend reaches where its diff --git a/include/webcpp/crypto/detail/engines.hpp b/include/webcpp/crypto/detail/engines.hpp index 72e7390..4e6cd94 100644 --- a/include/webcpp/crypto/detail/engines.hpp +++ b/include/webcpp/crypto/detail/engines.hpp @@ -17,6 +17,36 @@ namespace webcpp::crypto::detail { template inline constexpr bool dependent_false = false; +/** + * The specialisation marker (design D5, R7): true for an engine a backend's header specialises + * to do the work, which the header states beside the specialisation; false for a family's + * refusing primary and for a backend's own refusal (BearSSL's `block_engine`), which are no + * capability even where their bodies happen to meet a concept. `capabilities_test` counts an + * engine against the table only where the marker is true. + * + * It is a variable template beside the engine, not a member: reading a member instantiates the + * class, and a refusing primary's body is its refusal, which would stop the build of the check + * itself. + * + * @tparam Engine An engine type, which this never instantiates. + */ +template +inline constexpr bool specialized_engine_v = false; + +/** + * Whether a public member may call `Engine` for a capability that the engine has when `Has` (its + * concept, design D9): always for an engine no backend's header specialises, the family's primary, + * whose generated refusal speaks first, or a test's unmarked stand-in, taken at its word; for a + * specialised one, when it has the capability. A member asserts the concept itself, so that the + * compiler names the operation an engine lacks, and reads this to call the engine only where the + * assertion holds, so that its message is the build's one. + * + * @tparam Engine An engine type. + * @tparam Has Whether it meets the capability's concept. + */ +template +inline constexpr bool capability_usable_v = !specialized_engine_v || Has; + /** * What a backend's header specialises, per algorithm: a state, which an object stores and * which never refuses, and an engine, used only inside the algorithm's member functions. The @@ -93,6 +123,15 @@ struct stream_engine; template struct authenticator_engine; +/** + * The work of a secp256k1 capability on a backend (design D8), one specialisation per tag of + * `backend::secp256k1_capabilities` in the backend's header, which asserts each against its + * concept. No primary is defined: secp256k1 has one backend, and its functions refuse any other + * with the family's generated refusal (`secp256k1_refuses_others`) before they name an engine. + */ +template +struct secp256k1_engine; + /** * Reads a backend's canary with a volatile load, which no linker can drop: a program built * without the backend's library, or with one of another commit or configuration, then diff --git a/include/webcpp/crypto/detail/entropy.hpp b/include/webcpp/crypto/detail/entropy.hpp index 07334c8..b5549ff 100644 --- a/include/webcpp/crypto/detail/entropy.hpp +++ b/include/webcpp/crypto/detail/entropy.hpp @@ -9,6 +9,7 @@ #include +#include #include #include #include @@ -153,6 +154,26 @@ inline constexpr std::size_t entropy_piece = 256; return {}; } +/** + * The system's entropy as an entropy source (`backend::entropy_source`, design D4): what the + * library's generator draws from, and what a backend's own generation would draw from. + */ +struct system_entropy { + /** + * Fills `output_bytes` from the platform's source (@ref fill_from_system). + * + * @param output_bytes The bytes to fill; zeroed on error. + * @return Nothing; `error::entropy_unavailable` when the source fails; `errc::not_supported` + * where there is none (an Emscripten audio worklet). + */ + [[nodiscard]] static boost::system::result fill( + std::span output_bytes) noexcept { + return fill_from_system(output_bytes); + } +}; + +static_assert(backend::entropy_source); + } // namespace webcpp::crypto::detail #endif // WEBCPP_CRYPTO_DETAIL_ENTROPY_HPP diff --git a/include/webcpp/crypto/detail/families.hpp b/include/webcpp/crypto/detail/families.hpp new file mode 100644 index 0000000..064e079 --- /dev/null +++ b/include/webcpp/crypto/detail/families.hpp @@ -0,0 +1,125 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_CRYPTO_DETAIL_FAMILIES_HPP +#define WEBCPP_CRYPTO_DETAIL_FAMILIES_HPP + +// The symmetric families whose sizes the engine concepts read (detail/backend/symmetric.hpp): +// defined here, apart from their public headers, so that a backend header, which includes none +// of those, can assert its engines' concepts after each specialization (design D5). A program +// names them through the public headers, which include this one. + +#include +#include + +namespace webcpp::crypto::families { + +/** RFC 8439's ChaCha20-Poly1305: a 32-byte key, a 12-byte nonce, a 16-byte tag. */ +struct chacha20_poly1305 { + /** The key's size. */ + static constexpr std::size_t key_size = 32; + /** The nonce's size, exactly (RFC 8439 section 2.8). */ + static constexpr std::size_t nonce_size = 12; + /** The tag's size. */ + static constexpr std::size_t tag_size = 16; + /** The longest message, 2^38 - 64 bytes: ChaCha20's 32-bit block counter (section 2.8). */ + static constexpr std::uint64_t max_message_size = (std::uint64_t{1} << 38U) - 64; + /** The longest associated data, 2^64 - 1 bytes (section 2.8). */ + static constexpr std::uint64_t max_associated_data_size = ~std::uint64_t{0}; +}; + +/** + * The original ChaCha20-Poly1305, an 8-byte nonce and a 64-bit block counter, as libsodium's + * `crypto_aead_chacha20poly1305` has it. + */ +struct chacha20_poly1305_original { + /** The key's size. */ + static constexpr std::size_t key_size = 32; + /** The nonce's size, exactly. */ + static constexpr std::size_t nonce_size = 8; + /** The tag's size. */ + static constexpr std::size_t tag_size = 16; + /** The longest message, 2^64 - 17 bytes. */ + static constexpr std::uint64_t max_message_size = ~std::uint64_t{0} - 16; + /** The longest associated data, 2^64 - 1 bytes. */ + static constexpr std::uint64_t max_associated_data_size = ~std::uint64_t{0}; +}; + +/** XChaCha20-Poly1305, a 24-byte nonce safe to draw at random. */ +struct xchacha20_poly1305 { + /** The key's size. */ + static constexpr std::size_t key_size = 32; + /** The nonce's size, exactly. */ + static constexpr std::size_t nonce_size = 24; + /** The tag's size. */ + static constexpr std::size_t tag_size = 16; + /** The longest message, 2^64 - 17 bytes. */ + static constexpr std::uint64_t max_message_size = ~std::uint64_t{0} - 16; + /** The longest associated data, 2^64 - 1 bytes. */ + static constexpr std::uint64_t max_associated_data_size = ~std::uint64_t{0}; +}; + +/** RFC 8439's ChaCha20: a 32-byte key, a 12-byte nonce, a 32-bit block counter. */ +struct chacha20 { + /** The key's size. */ + static constexpr std::size_t key_size = 32; + /** The nonce's size, exactly (RFC 8439 section 2.3). */ + static constexpr std::size_t nonce_size = 12; + /** The block's size: the keystream is made one 64-byte block per counter value. */ + static constexpr std::size_t block_size = 64; + /** The block counter, RFC 8439's 32 bits. */ + using counter_type = std::uint32_t; + /** The longest data from counter 0, 2^38 bytes: 2^32 blocks of 64 bytes. */ + static constexpr std::uint64_t max_message_size = std::uint64_t{1} << 38U; +}; + +/** RFC 8439's Poly1305: a 32-byte one-time key, r and s, and a 16-byte tag. */ +struct poly1305 { + /** The key's size: r and s, RFC 8439 section 2.5. */ + static constexpr std::size_t key_size = 32; + /** The tag's size. */ + static constexpr std::size_t tag_size = 16; +}; + +/** + * NaCl's and libsodium's `crypto_secretbox`, XSalsa20-Poly1305: a 32-byte key, a 24-byte nonce + * safe to draw at random, a 16-byte tag, and no associated data. + */ +struct secretbox_xsalsa20poly1305 { + /** The key's size. */ + static constexpr std::size_t key_size = 32; + /** The nonce's size, exactly. */ + static constexpr std::size_t nonce_size = 24; + /** The tag's size. */ + static constexpr std::size_t tag_size = 16; + /** + * The longest message, 2^64 - 17 bytes: libsodium's `crypto_secretbox_MESSAGEBYTES_MAX` on a + * 64-bit target. + * + * On a 32-bit target, wasm32 among them, libsodium's is 2^32 - 17 bytes, more than a + * message there can be, since the 4 GiB of memory also hold the program. + */ + static constexpr std::uint64_t max_message_size = ~std::uint64_t{0} - 16; +}; + +/** + * libsodium's `crypto_secretbox_xchacha20poly1305`: `crypto_secretbox` with XChaCha20 in place + * of XSalsa20, a 24-byte nonce safe to draw at random, and no associated data. + */ +struct secretbox_xchacha20poly1305 { + /** The key's size. */ + static constexpr std::size_t key_size = 32; + /** The nonce's size, exactly. */ + static constexpr std::size_t nonce_size = 24; + /** The tag's size. */ + static constexpr std::size_t tag_size = 16; + /** The longest message, 2^64 - 17 bytes. */ + static constexpr std::uint64_t max_message_size = ~std::uint64_t{0} - 16; +}; + +} // namespace webcpp::crypto::families + +#endif // WEBCPP_CRYPTO_DETAIL_FAMILIES_HPP diff --git a/include/webcpp/crypto/detail/rfc8410.hpp b/include/webcpp/crypto/detail/rfc8410.hpp new file mode 100644 index 0000000..a18b5e4 --- /dev/null +++ b/include/webcpp/crypto/detail/rfc8410.hpp @@ -0,0 +1,85 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +#ifndef WEBCPP_CRYPTO_DETAIL_RFC8410_HPP +#define WEBCPP_CRYPTO_DETAIL_RFC8410_HPP + +#include + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include + +/** + * RFC 8410's fixed layouts for Ed25519's and X25519's SPKI and PKCS#8: a prefix, then the 32 key + * bytes. RFC 8410 fixes the layout around the key, so writing and reading it is constants rather + * than cryptography: no backend is called (backend-concepts design D4, the formats engines + * dissolved), and a key's formats need of its backend only the key capabilities, `*_public`, + * `*_import` and `*_export`. A decoding is accepted only where its prefix is the one encoding the + * key gives, compared with `constant_time_equal`, and its size the one size (the callers check it), + * which is the formats change's re-encoding test for a fixed layout (its D30). + */ +namespace webcpp::crypto::detail::rfc8410 { + +/** The size of the key RFC 8410's layouts hold for Ed25519 and X25519. */ +inline constexpr std::size_t key_size = 32; + +/** + * Writes the prefix, then the key. + * + * @tparam PrefixSize The prefix's size. + * @param prefix_bytes The format's prefix. + * @param key_bytes The key. + * @param output_bytes The prefix's size and the key's. + */ +template +void encode(std::array const& prefix_bytes, + std::span key_bytes, + std::span output_bytes) noexcept { + std::ranges::copy(key_bytes, std::ranges::copy(prefix_bytes, output_bytes.begin()).out); +} + +/** + * Copies the key out of an encoding whose prefix is the format's. + * + * Whether the prefix is the format's is public, since it is reported: marked so for the + * constant-time checks, for an encoding read from a secret text (a PKCS#8's PEM), whose prefix + * carries the text's secrecy through its base64. + * + * @tparam PrefixSize The prefix's size. + * @param prefix_bytes The format's prefix. + * @param der_bytes The prefix's size and the key's. + * @param key_bytes The key, written only when the prefix is the format's. + * @return Nothing; `invalid_encoding`. + */ +template +[[nodiscard]] boost::system::result decode( + std::array const& prefix_bytes, + std::span der_bytes, + std::span key_bytes) noexcept { + // Not const: the branch reads it again after the mark (secure::declassify's tip). + // NOLINTNEXTLINE(misc-const-correctness): see above + bool prefix_matches = + secure::constant_time_equal(der_bytes.template first(), prefix_bytes); + secure::declassify(prefix_matches); + if (!prefix_matches) { + return error::invalid_encoding; + } + std::ranges::copy(der_bytes.template last(), key_bytes.begin()); + return {}; +} + +} // namespace webcpp::crypto::detail::rfc8410 + +#endif // WEBCPP_CRYPTO_DETAIL_RFC8410_HPP diff --git a/include/webcpp/crypto/detail/secret_keys.hpp b/include/webcpp/crypto/detail/secret_keys.hpp new file mode 100644 index 0000000..5ee65a0 --- /dev/null +++ b/include/webcpp/crypto/detail/secret_keys.hpp @@ -0,0 +1,47 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The secret-key traits as a public member asks them of a key's engine (backend-concepts design +// D3's and D6's amendments, D9): a member that would take secret key bytes into the backend, or +// give them out, asks these before it asserts the capability it uses, so that a backend whose keys +// never leave it is refused by the trait, in one message, before any capability is named. + +#ifndef WEBCPP_CRYPTO_DETAIL_SECRET_KEYS_HPP +#define WEBCPP_CRYPTO_DETAIL_SECRET_KEYS_HPP + +#include +#include + +namespace webcpp::crypto::detail { + +/** + * Whether secret key bytes may leave `Backend` through `Engine`: the backend's + * `exports_secret_keys_v` for an engine its header specialises (`specialized_engine_v`); true for + * the family's primary engine, whose generated refusal speaks first, and for a test's unmarked + * stand-in, taken at its word. + * + * @tparam Engine The key's engine. + * @tparam Backend Its backend. + */ +template +inline constexpr bool secret_keys_leave_v = + !specialized_engine_v || exports_secret_keys_v; + +/** + * Whether secret key bytes may enter `Backend` through `Engine`: the backend's + * `imports_secret_keys_v` for an engine its header specialises, true otherwise, as + * @ref secret_keys_leave_v. + * + * @tparam Engine The key's engine. + * @tparam Backend Its backend. + */ +template +inline constexpr bool secret_keys_enter_v = + !specialized_engine_v || imports_secret_keys_v; + +} // namespace webcpp::crypto::detail + +#endif // WEBCPP_CRYPTO_DETAIL_SECRET_KEYS_HPP diff --git a/include/webcpp/crypto/formats.hpp b/include/webcpp/crypto/formats.hpp index 9b8b76b..8beaf78 100644 --- a/include/webcpp/crypto/formats.hpp +++ b/include/webcpp/crypto/formats.hpp @@ -650,8 +650,23 @@ enum class refusal_reason : unsigned char { xonly_into_public_key, /** A private format of a key pair whose secret lives in WebCrypto. */ private_on_asynchronous, + /** `raw` of a key pair whose backend keeps its keys (design D3's amendment). */ + private_kept_raw, + /** `pkcs8` or `pem(pkcs8)` of a key pair whose backend keeps its keys, as `private_kept_raw`. + */ + private_kept_pkcs8, }; +/** + * The reason of a private format refused because its backend keeps its keys: `raw`'s, or the one + * `pkcs8` and `pem(pkcs8)` share. + * + * @tparam Raw Whether the format is `raw`. + */ +template +inline constexpr refusal_reason private_kept_reason_v = + Raw ? refusal_reason::private_kept_raw : refusal_reason::private_kept_pkcs8; + /** * The reason a curve gives for refusing `Format` on `T` in both directions; `none` unless the * curve's formats header specializes it. @@ -818,6 +833,15 @@ constexpr void refuse_for_reason() noexcept { 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"); + static_assert(Reason != refusal_reason::private_kept_raw, + "webcpp::crypto: this backend keeps its keys: no secret key leaves or enters it " + "(crypto::exports_secret_keys_v or crypto::imports_secret_keys_v is false), so a " + "key pair's formats::raw, its secret key's bytes, is not available on it"); + static_assert( + Reason != refusal_reason::private_kept_pkcs8, + "webcpp::crypto: this backend keeps its keys: no secret key leaves or enters it " + "(crypto::exports_secret_keys_v or crypto::imports_secret_keys_v is false), so a key " + "pair's formats::pkcs8 and formats::pem(formats::pkcs8) are not available on it"); } /** diff --git a/include/webcpp/crypto/key_exchange/kx.hpp b/include/webcpp/crypto/key_exchange/kx.hpp index ce84013..5bfdd25 100644 --- a/include/webcpp/crypto/key_exchange/kx.hpp +++ b/include/webcpp/crypto/key_exchange/kx.hpp @@ -32,6 +32,7 @@ #include #include +#include #include #include #include @@ -46,6 +47,7 @@ #include #include #include +#include #include namespace webcpp::crypto::detail { @@ -67,6 +69,27 @@ template inline constexpr bool kx_engine_defined = supported && linked; +/** + * Whether crypto_kx's engine on a backend has its capability (design D9): true for the family's + * primary engine, whose generated refusal speaks, and for a test's unmarked stand-in, taken at its + * word; for an engine a backend's header specialises (`specialized_engine_v`), the capability, + * asserted by a message that names it. Each public member that calls the engine asks it first. + * + * @tparam Engine crypto_kx's engine on the backend. + * @return Whether the member may call the engine. + */ +template +constexpr bool kx_capability_checked() noexcept { + if constexpr (!specialized_engine_v) { + return true; + } else { + static_assert(backend::kx, + "webcpp::crypto: this backend has crypto_kx but not " + "crypto::capabilities::kx: the session keys are not available on it."); + return backend::kx; + } +} + } // namespace webcpp::crypto::detail namespace webcpp::crypto::key_exchange { @@ -155,25 +178,30 @@ class kx_keypair { [[nodiscard]] static boost::system::result derive_from_seed( std::span seed_bytes) noexcept { secure::timing_guard const timing_scope; - if (seed_bytes.size() != seed_size) { - return error::invalid_key_size; - } - if constexpr (!detail::kx_engine_defined) { - // The engine's refusal stops the build here, and X25519's key pair is not made, so - // that its own refusal adds no second error (never compiled into a program). - return engine::seed_keypair(seed_bytes).error(); + if constexpr (!detail::kx_capability_checked()) { + // Never compiled into a program: the capability's assertion stopped the build. + return error::backend_failure; } else { - secure::secret derived_secret; - auto const engine_derived = engine::seed_keypair(seed_bytes.template first(), - derived_secret.writable()); - if (!engine_derived) { - return engine_derived.error(); + if (seed_bytes.size() != seed_size) { + return error::invalid_key_size; } - auto derived_pair = keypair_type::from_secret(derived_secret.bytes()); - if (!derived_pair) { - return derived_pair.error(); + if constexpr (!detail::kx_engine_defined) { + // The engine's refusal stops the build here, and X25519's key pair is not made, so + // that its own refusal adds no second error (never compiled into a program). + return engine::seed_keypair(seed_bytes).error(); + } else { + secure::secret derived_secret; + auto const engine_derived = engine::seed_keypair( + seed_bytes.template first(), derived_secret.writable()); + if (!engine_derived) { + return engine_derived.error(); + } + auto derived_pair = keypair_type::from_secret(derived_secret.bytes()); + if (!derived_pair) { + return derived_pair.error(); + } + return kx_keypair(std::move(derived_pair).unsafe_value()); } - return kx_keypair(std::move(derived_pair).unsafe_value()); } } @@ -273,26 +301,40 @@ class kx_keypair { template [[nodiscard]] boost::system::result session( public_key_type const& peer_public_key) const noexcept { - if (!access::keyed(key_pair_)) { - return error::invalid_state; - } - session_keys derived_keys; - auto const secret_bytes = access::secret_bytes(key_pair_); - auto const public_bytes = access::public_bytes(key_pair_); - std::span const peer_bytes = peer_public_key.bytes(); - auto const engine_done = - Client - ? engine::client(secret_bytes, public_bytes, peer_bytes, - derived_keys.receive.writable(), derived_keys.transmit.writable()) - : engine::server(secret_bytes, public_bytes, peer_bytes, - derived_keys.receive.writable(), derived_keys.transmit.writable()); - if (!engine_done) { - return engine_done.error(); + if constexpr (!detail::kx_capability_checked()) { + // Never compiled into a program: the capability's assertion stopped the build. + return error::backend_failure; + } else { + if (!access::keyed(key_pair_)) { + return error::invalid_state; + } + session_keys derived_keys; + auto const secret_bytes = access::secret_bytes(key_pair_); + auto const public_bytes = access::public_bytes(key_pair_); + std::span const peer_bytes = + peer_public_key.bytes(); + auto const engine_done = Client ? engine::client(secret_bytes, public_bytes, peer_bytes, + derived_keys.receive.writable(), + derived_keys.transmit.writable()) + : engine::server(secret_bytes, public_bytes, peer_bytes, + derived_keys.receive.writable(), + derived_keys.transmit.writable()); + if (!engine_done) { + return engine_done.error(); + } + return derived_keys; } - return derived_keys; } - keypair_type key_pair_; + // On a backend without crypto_kx the engine's refusal stops the build, and the key pair holds + // no X25519 key pair: X25519's special members, which call its engine, would add X25519's + // own refusal after the first (never compiled into a program). + struct refused_keypair {}; + + using held_type = + std::conditional_t, keypair_type, refused_keypair>; + + held_type key_pair_; }; } // namespace webcpp::crypto::key_exchange diff --git a/include/webcpp/crypto/public_key_encryption/box.hpp b/include/webcpp/crypto/public_key_encryption/box.hpp index 039739f..b1bb83a 100644 --- a/include/webcpp/crypto/public_key_encryption/box.hpp +++ b/include/webcpp/crypto/public_key_encryption/box.hpp @@ -34,6 +34,7 @@ #include #include +#include #include #include #include @@ -93,6 +94,38 @@ template using box_default_family = std::conditional_t, Family, families::box_xsalsa20poly1305>; +/** + * Whether the engine of a public-key box family on a backend has its capability (design D9): true + * for the family's primary engine, whose generated refusal speaks, and for a test's unmarked + * stand-in, taken at its word; for an engine a backend's header specialises + * (`specialized_engine_v`), the capability, asserted by a message that names it. Each public member + * that calls the engine asks it first. + * + * @tparam Family The box's family. + * @tparam Engine Its engine on the backend. + * @return Whether the member may call the engine. + */ +template +constexpr bool box_capability_checked() noexcept { + if constexpr (!specialized_engine_v) { + return true; + } else { + if constexpr (std::is_same_v) { + static_assert( + backend::box, + "webcpp::crypto: this backend has the XSalsa20-Poly1305 box but not " + "crypto::capabilities::box_xsalsa20poly1305: the box is not available on it."); + } + if constexpr (std::is_same_v) { + static_assert( + backend::box, + "webcpp::crypto: this backend has the XChaCha20-Poly1305 box but not " + "crypto::capabilities::box_xchacha20poly1305: the box is not available on it."); + } + return backend::box; + } +} + } // namespace webcpp::crypto::detail namespace webcpp::crypto::public_key_encryption { @@ -177,23 +210,28 @@ class basic_box { [[nodiscard]] static boost::system::result from_keys( keypair_type const& own_keypair, public_key_type const& peer_public_key) noexcept { secure::timing_guard const timing_scope; - if constexpr (detail::asynchronous_backend_v) { - // WebCrypto has no crypto_box: the refusal names a native backend (design D6). - detail::refuse_aead_on_asynchronous_backend(); + if constexpr (!detail::box_capability_checked()) { + // Never compiled into a program: the capability's assertion stopped the build. return error::backend_failure; } else { - if (!detail::x25519_access::keyed(own_keypair)) { - return error::invalid_state; - } - basic_box made_object; - auto const agreement_result = - engine::init(made_object.state_, detail::x25519_access::secret_bytes(own_keypair), - std::span(peer_public_key.bytes())); - if (!agreement_result) { - return agreement_result.error(); + if constexpr (detail::asynchronous_backend_v) { + // WebCrypto has no crypto_box: the refusal names a native backend (design D6). + detail::refuse_aead_on_asynchronous_backend(); + return error::backend_failure; + } else { + if (!detail::x25519_access::keyed(own_keypair)) { + return error::invalid_state; + } + basic_box made_object; + auto const agreement_result = engine::init( + made_object.state_, detail::x25519_access::secret_bytes(own_keypair), + std::span(peer_public_key.bytes())); + if (!agreement_result) { + return agreement_result.error(); + } + made_object.keyed_ = true; + return made_object; } - made_object.keyed_ = true; - return made_object; } } @@ -253,23 +291,28 @@ class basic_box { [[nodiscard]] boost::system::result seal( std::span nonce_bytes, std::span data_bytes) noexcept { secure::timing_guard const timing_scope; - if constexpr (detail::asynchronous_backend_v) { - // WebCrypto has no crypto_box: the refusal names a native backend (design D6). - detail::refuse_aead_on_asynchronous_backend(); + if constexpr (!detail::box_capability_checked()) { + // Never compiled into a program: the capability's assertion stopped the build. return error::backend_failure; } else { - auto const guard_result = guard_message(nonce_bytes, data_bytes.size(), tag_size); - if (!guard_result) { - return guard_result.error(); + if constexpr (detail::asynchronous_backend_v) { + // WebCrypto has no crypto_box: the refusal names a native backend (design D6). + detail::refuse_aead_on_asynchronous_backend(); + return error::backend_failure; + } else { + auto const guard_result = guard_message(nonce_bytes, data_bytes.size(), tag_size); + if (!guard_result) { + return guard_result.error(); + } + result_type tag_bytes{}; + auto const seal_result = + engine::seal(state_, nonce_bytes.first(), data_bytes, tag_bytes); + if (!seal_result) { + secure::erase_secret(data_bytes); + return seal_result.error(); + } + return tag_bytes; } - result_type tag_bytes{}; - auto const seal_result = - engine::seal(state_, nonce_bytes.first(), data_bytes, tag_bytes); - if (!seal_result) { - secure::erase_secret(data_bytes); - return seal_result.error(); - } - return tag_bytes; } } @@ -318,26 +361,31 @@ class basic_box { std::span nonce_bytes, std::span data_bytes, std::span tag_bytes) noexcept { secure::timing_guard const timing_scope; - if constexpr (detail::asynchronous_backend_v) { - // WebCrypto has no crypto_box: the refusal names a native backend (design D6). - detail::refuse_aead_on_asynchronous_backend(); + if constexpr (!detail::box_capability_checked()) { + // Never compiled into a program: the capability's assertion stopped the build. return error::backend_failure; } else { - auto const guard_result = - guard_message(nonce_bytes, data_bytes.size(), tag_bytes.size()); - if (!guard_result) { - return guard_result.error(); - } - // The tag may lie in data, which decryption overwrites: a copy is checked. - std::array expected_tag{}; - std::ranges::copy(tag_bytes, expected_tag.begin()); - auto const open_result = - engine::open(state_, nonce_bytes.first(), data_bytes, expected_tag); - if (!open_result) { - secure::erase_secret(data_bytes); - return open_result.error(); + if constexpr (detail::asynchronous_backend_v) { + // WebCrypto has no crypto_box: the refusal names a native backend (design D6). + detail::refuse_aead_on_asynchronous_backend(); + return error::backend_failure; + } else { + auto const guard_result = + guard_message(nonce_bytes, data_bytes.size(), tag_bytes.size()); + if (!guard_result) { + return guard_result.error(); + } + // The tag may lie in data, which decryption overwrites: a copy is checked. + std::array expected_tag{}; + std::ranges::copy(tag_bytes, expected_tag.begin()); + auto const open_result = + engine::open(state_, nonce_bytes.first(), data_bytes, expected_tag); + if (!open_result) { + secure::erase_secret(data_bytes); + return open_result.error(); + } + return {}; } - return {}; } } diff --git a/include/webcpp/crypto/public_key_encryption/sealed_box.hpp b/include/webcpp/crypto/public_key_encryption/sealed_box.hpp index a7a04e7..b3d28e6 100644 --- a/include/webcpp/crypto/public_key_encryption/sealed_box.hpp +++ b/include/webcpp/crypto/public_key_encryption/sealed_box.hpp @@ -27,6 +27,7 @@ #include #include +#include #include #include #include @@ -51,6 +52,28 @@ namespace webcpp::crypto::detail { template struct sealed_box_engine; +/** + * Whether the sealed box's engine on a backend has its capability (design D9): true for the + * family's primary engine, whose generated refusal speaks, and for a test's unmarked stand-in, + * taken at its word; for an engine a backend's header specialises (`specialized_engine_v`), the + * capability, asserted by a message that names it. Each public member that calls the engine asks it + * first. + * + * @tparam Engine The sealed box's engine on the backend. + * @return Whether the member may call the engine. + */ +template +constexpr bool sealed_box_capability_checked() noexcept { + if constexpr (!specialized_engine_v) { + return true; + } else { + static_assert(backend::sealed_box, + "webcpp::crypto: this backend has the sealed box but not " + "crypto::capabilities::sealed_box: the box is not available on it."); + return backend::sealed_box; + } +} + } // namespace webcpp::crypto::detail namespace webcpp::crypto::public_key_encryption { @@ -112,18 +135,23 @@ struct basic_sealed_box { public_key_type const& recipient_public_key, std::span message_bytes, std::span output_bytes) noexcept { secure::timing_guard const timing_scope; - if (output_bytes.size() < overhead || - output_bytes.size() - overhead != message_bytes.size()) { - return error::invalid_input_size; - } - auto const seal_result = - engine::seal(std::span(recipient_public_key.bytes()), - message_bytes, output_bytes); - if (!seal_result) { - secure::erase_secret(output_bytes); - return seal_result.error(); + if constexpr (!detail::sealed_box_capability_checked()) { + // Never compiled into a program: the capability's assertion stopped the build. + return error::backend_failure; + } else { + if (output_bytes.size() < overhead || + output_bytes.size() - overhead != message_bytes.size()) { + return error::invalid_input_size; + } + auto const seal_result = + engine::seal(std::span(recipient_public_key.bytes()), + message_bytes, output_bytes); + if (!seal_result) { + secure::erase_secret(output_bytes); + return seal_result.error(); + } + return {}; } - return {}; } /** @@ -147,21 +175,26 @@ struct basic_sealed_box { keypair_type const& recipient_keypair, std::span sealed_bytes, std::span output_bytes) noexcept { secure::timing_guard const timing_scope; - if (sealed_bytes.size() < overhead || - output_bytes.size() != sealed_bytes.size() - overhead) { - return error::invalid_input_size; - } - if (!detail::x25519_access::keyed(recipient_keypair)) { - return error::invalid_state; - } - auto const open_result = engine::open( - detail::x25519_access::public_bytes(recipient_keypair), - detail::x25519_access::secret_bytes(recipient_keypair), sealed_bytes, output_bytes); - if (!open_result) { - secure::erase_secret(output_bytes); - return open_result.error(); + if constexpr (!detail::sealed_box_capability_checked()) { + // Never compiled into a program: the capability's assertion stopped the build. + return error::backend_failure; + } else { + if (sealed_bytes.size() < overhead || + output_bytes.size() != sealed_bytes.size() - overhead) { + return error::invalid_input_size; + } + if (!detail::x25519_access::keyed(recipient_keypair)) { + return error::invalid_state; + } + auto const open_result = engine::open( + detail::x25519_access::public_bytes(recipient_keypair), + detail::x25519_access::secret_bytes(recipient_keypair), sealed_bytes, output_bytes); + if (!open_result) { + secure::erase_secret(output_bytes); + return open_result.error(); + } + return {}; } - return {}; } private: diff --git a/include/webcpp/crypto/random_device.hpp b/include/webcpp/crypto/random_device.hpp index cfdbd73..6e09223 100644 --- a/include/webcpp/crypto/random_device.hpp +++ b/include/webcpp/crypto/random_device.hpp @@ -88,7 +88,7 @@ class random_device { // lint-world: the system's entropy, this class's purpose // A member, so that a generator of another kind can stand in for this one. // NOLINTNEXTLINE(readability-convert-member-functions-to-static) [[nodiscard]] boost::system::result fill(std::span output_bytes) noexcept { - return detail::fill_from_system(output_bytes); + return detail::system_entropy::fill(output_bytes); } #ifndef WEBCPP_CRYPTO_NO_EXCEPTIONS diff --git a/include/webcpp/crypto/secret_key_encryption/secretbox.hpp b/include/webcpp/crypto/secret_key_encryption/secretbox.hpp index 6499f33..4d54047 100644 --- a/include/webcpp/crypto/secret_key_encryption/secretbox.hpp +++ b/include/webcpp/crypto/secret_key_encryption/secretbox.hpp @@ -31,9 +31,11 @@ #include #include +#include #include #include #include +#include #include #include #include // crypto::from_key, which serves its from_key (design R23) @@ -51,46 +53,6 @@ #include #include -namespace webcpp::crypto::families { - -/** - * NaCl's and libsodium's `crypto_secretbox`, XSalsa20-Poly1305: a 32-byte key, a 24-byte nonce - * safe to draw at random, a 16-byte tag, and no associated data. - */ -struct secretbox_xsalsa20poly1305 { - /** The key's size. */ - static constexpr std::size_t key_size = 32; - /** The nonce's size, exactly. */ - static constexpr std::size_t nonce_size = 24; - /** The tag's size. */ - static constexpr std::size_t tag_size = 16; - /** - * The longest message, 2^64 - 17 bytes: libsodium's `crypto_secretbox_MESSAGEBYTES_MAX` on a - * 64-bit target. - * - * On a 32-bit target, wasm32 among them, libsodium's is 2^32 - 17 bytes, more than a - * message there can be, since the 4 GiB of memory also hold the program. - */ - static constexpr std::uint64_t max_message_size = ~std::uint64_t{0} - 16; -}; - -/** - * libsodium's `crypto_secretbox_xchacha20poly1305`: `crypto_secretbox` with XChaCha20 in place - * of XSalsa20, a 24-byte nonce safe to draw at random, and no associated data. - */ -struct secretbox_xchacha20poly1305 { - /** The key's size. */ - static constexpr std::size_t key_size = 32; - /** The nonce's size, exactly. */ - static constexpr std::size_t nonce_size = 24; - /** The tag's size. */ - static constexpr std::size_t tag_size = 16; - /** The longest message, 2^64 - 17 bytes. */ - static constexpr std::uint64_t max_message_size = ~std::uint64_t{0} - 16; -}; - -} // namespace webcpp::crypto::families - namespace webcpp::crypto::detail { /** @@ -197,6 +159,38 @@ struct secretbox_engine : secretbox_refusal { static void reset(Arguments&&... /*arguments*/) noexcept {} }; +/** + * Whether the engine of a secret box family on a backend has its capability (design D9): true for + * the family's primary engine, whose generated refusal speaks, and for a test's unmarked stand-in, + * taken at its word; for an engine a backend's header specialises (`specialized_engine_v`), the + * capability, asserted by a message that names it. Each public member that calls the engine asks it + * first. + * + * @tparam Family The secret box's family. + * @tparam Engine Its engine on the backend. + * @return Whether the member may call the engine. + */ +template +constexpr bool secretbox_capability_checked() noexcept { + if constexpr (!specialized_engine_v) { + return true; + } else { + if constexpr (std::is_same_v) { + static_assert(backend::authenticated_box, + "webcpp::crypto: this backend has the XSalsa20-Poly1305 secret box but " + "not crypto::capabilities::secretbox_xsalsa20poly1305: the box is not " + "available on it."); + } + if constexpr (std::is_same_v) { + static_assert(backend::authenticated_box, + "webcpp::crypto: this backend has the XChaCha20-Poly1305 secret box but " + "not crypto::capabilities::secretbox_xchacha20poly1305: the box is not " + "available on it."); + } + return backend::authenticated_box; + } +} + } // namespace webcpp::crypto::detail namespace webcpp::crypto::secret_key_encryption { @@ -254,21 +248,27 @@ class basic_secretbox { [[nodiscard]] static boost::system::result from_key( std::span key_bytes) noexcept { secure::timing_guard const timing_scope; - if constexpr (detail::asynchronous_backend_v) { - // WebCrypto has no such construction: the refusal names a native backend (design D6). - detail::refuse_aead_on_asynchronous_backend(); + if constexpr (!detail::secretbox_capability_checked()) { + // Never compiled into a program: the capability's assertion stopped the build. return error::backend_failure; } else { - if (key_bytes.size() != key_size) { - return error::invalid_key_size; + if constexpr (detail::asynchronous_backend_v) { + // WebCrypto has no such construction: the refusal names a native backend (design + // D6). + detail::refuse_aead_on_asynchronous_backend(); + return error::backend_failure; + } else { + if (key_bytes.size() != key_size) { + return error::invalid_key_size; + } + basic_secretbox made_object; + auto const key_result = engine::init(made_object.state_, key_bytes); + if (!key_result) { + return key_result.error(); + } + made_object.keyed_ = true; + return made_object; } - basic_secretbox made_object; - auto const key_result = engine::init(made_object.state_, key_bytes); - if (!key_result) { - return key_result.error(); - } - made_object.keyed_ = true; - return made_object; } } @@ -355,23 +355,29 @@ class basic_secretbox { [[nodiscard]] boost::system::result seal( std::span nonce_bytes, std::span data_bytes) noexcept { secure::timing_guard const timing_scope; - if constexpr (detail::asynchronous_backend_v) { - // WebCrypto has no such construction: the refusal names a native backend (design D6). - detail::refuse_aead_on_asynchronous_backend(); + if constexpr (!detail::secretbox_capability_checked()) { + // Never compiled into a program: the capability's assertion stopped the build. return error::backend_failure; } else { - auto const guard_result = guard_message(nonce_bytes, data_bytes.size(), tag_size); - if (!guard_result) { - return guard_result.error(); - } - result_type tag_bytes{}; - auto const seal_result = - engine::seal(state_, nonce_bytes.first(), data_bytes, tag_bytes); - if (!seal_result) { - secure::erase_secret(data_bytes); - return seal_result.error(); + if constexpr (detail::asynchronous_backend_v) { + // WebCrypto has no such construction: the refusal names a native backend (design + // D6). + detail::refuse_aead_on_asynchronous_backend(); + return error::backend_failure; + } else { + auto const guard_result = guard_message(nonce_bytes, data_bytes.size(), tag_size); + if (!guard_result) { + return guard_result.error(); + } + result_type tag_bytes{}; + auto const seal_result = + engine::seal(state_, nonce_bytes.first(), data_bytes, tag_bytes); + if (!seal_result) { + secure::erase_secret(data_bytes); + return seal_result.error(); + } + return tag_bytes; } - return tag_bytes; } } @@ -420,26 +426,32 @@ class basic_secretbox { std::span nonce_bytes, std::span data_bytes, std::span tag_bytes) noexcept { secure::timing_guard const timing_scope; - if constexpr (detail::asynchronous_backend_v) { - // WebCrypto has no such construction: the refusal names a native backend (design D6). - detail::refuse_aead_on_asynchronous_backend(); + if constexpr (!detail::secretbox_capability_checked()) { + // Never compiled into a program: the capability's assertion stopped the build. return error::backend_failure; } else { - auto const guard_result = - guard_message(nonce_bytes, data_bytes.size(), tag_bytes.size()); - if (!guard_result) { - return guard_result.error(); - } - // The tag may lie in data, which decryption overwrites: a copy is checked. - std::array expected_tag{}; - std::ranges::copy(tag_bytes, expected_tag.begin()); - auto const open_result = - engine::open(state_, nonce_bytes.first(), data_bytes, expected_tag); - if (!open_result) { - secure::erase_secret(data_bytes); - return open_result.error(); + if constexpr (detail::asynchronous_backend_v) { + // WebCrypto has no such construction: the refusal names a native backend (design + // D6). + detail::refuse_aead_on_asynchronous_backend(); + return error::backend_failure; + } else { + auto const guard_result = + guard_message(nonce_bytes, data_bytes.size(), tag_bytes.size()); + if (!guard_result) { + return guard_result.error(); + } + // The tag may lie in data, which decryption overwrites: a copy is checked. + std::array expected_tag{}; + std::ranges::copy(tag_bytes, expected_tag.begin()); + auto const open_result = + engine::open(state_, nonce_bytes.first(), data_bytes, expected_tag); + if (!open_result) { + secure::erase_secret(data_bytes); + return open_result.error(); + } + return {}; } - return {}; } } diff --git a/include/webcpp/crypto/signing.hpp b/include/webcpp/crypto/signing.hpp index 7728bc6..d94f1e1 100644 --- a/include/webcpp/crypto/signing.hpp +++ b/include/webcpp/crypto/signing.hpp @@ -559,6 +559,31 @@ inline constexpr bool signs_with_v = false; template inline constexpr bool verifies_with_v = false; +/** + * Whether the key pair `Keypair` signs a digest given as `signing_schemes::prehashed` with + * `Scheme`, where its curve signs with the scheme: true, unless the curve's header says its + * backend's engine lacks the digest form (P-256's on a backend with the message form alone). + * + * A curve's header specialises it, as `signs_with_v`. + * + * @tparam Keypair A key pair's type, without its reference and qualifiers. + * @tparam Scheme A scheme tag. + */ +template +inline constexpr bool signs_digest_v = true; + +/** + * Whether the public key `PublicKey` verifies a digest given as `signing_schemes::prehashed` with + * `Scheme`, as `signs_digest_v` asks the key pair. + * + * A curve's header specialises it, as `verifies_with_v`. + * + * @tparam PublicKey A curve's public key type, without its reference and qualifiers. + * @tparam Scheme A scheme tag. + */ +template +inline constexpr bool verifies_digest_v = true; + /** * The backend of a key type, `void` for a byte key; each curve specialises it for its own, in * its header, which is included before the trait is used on its keys. @@ -1035,7 +1060,8 @@ constexpr void refuse_missing_policy() noexcept { /** * Whether the key pair `Keypair` signs `Input` with `Scheme`: when its curve has the scheme and - * the input is a message, or a marker of the scheme's digest size on a backend that signs one. + * the input is a message, or a marker of the scheme's digest size on a backend that signs one + * (for P-256, one with `capabilities::p256_ecdsa_signing`). * * @tparam Keypair A key pair's type. * @tparam Scheme A scheme tag. @@ -1045,14 +1071,17 @@ template concept can_sign = detail::signs_with_v, Scheme> && detail::input_valid_v, - typename detail::key_backend>::type>; + typename detail::key_backend>::type> && + (!detail::is_prehashed_v> || + detail::signs_digest_v, Scheme>); /** * Whether `crypto::verify` checks a signature of the type `Signature` and of `Scheme` over `Input` * 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. + * of the scheme's digest size on a backend that verifies one (for P-256, one with + * `capabilities::p256_ecdsa_verifying`). * * @tparam Scheme A scheme tag. * @tparam Policy A verification policy's type. @@ -1068,7 +1097,9 @@ concept can_verify = std::is_same_v, detail::signature_of_t, Scheme>> && detail::input_valid_v, - typename detail::key_backend>::type>; + typename detail::key_backend>::type> && + (!detail::is_prehashed_v> || + detail::verifies_digest_v, Scheme>); /** * Stops the build: no curve verifies a signature of `Scheme` against this public key. diff --git a/include/webcpp/crypto/supports.hpp b/include/webcpp/crypto/supports.hpp index 72c6bbe..df1ebde 100644 --- a/include/webcpp/crypto/supports.hpp +++ b/include/webcpp/crypto/supports.hpp @@ -5,8 +5,9 @@ // https://www.boost.org/LICENSE_1_0.txt) /** - Whether a backend has an algorithm on the target being compiled, as the capability table, - `doc/tables/crypto.json`, says. + Whether a backend has an algorithm, or one capability of it, on the target being compiled, and + whether secret key bytes may leave it or enter it, as the capability table, + `doc/tables/crypto.json`, says. None of it needs a backend's header or library. @see "The backends", in the guide. */ @@ -21,7 +22,10 @@ namespace webcpp::crypto { /** * `true` exactly where the capability table says that `Backend` has `Algorithm` on the target - * being compiled. + * being compiled: the algorithm's use operations (signing and verifying for a signature + * algorithm, agreement for an agreement, sealing and opening for an AEAD or a box, the + * operation of the rest), whatever the backend has of importing, generating and exporting its + * keys, which `supports_capability_v` answers. * * A cell decided at run time is `true` too: its factory then reports `not_supported` on a * machine that lacks it. It needs no backend's header and no library: a program asks it of a @@ -35,6 +39,49 @@ template inline constexpr bool supports_v = detail::supported; +/** + * `true` exactly where the capability table says that `Backend` has the capability `Capability` + * on the target being compiled. + * + * One cell per capability, finer than `supports_v`, so that a program asks before it calls what + * a backend may lack, as `supports_capability_v` before + * `secret()`. P-256's ECDSA comes in a digest form (`p256_ecdsa_signing`, + * `p256_ecdsa_verifying`), which signs a prehashed digest, and a message form + * (`p256_ecdsa_message_signing`, `p256_ecdsa_message_verifying`), which hashes inside; + * `supports_v` counts either. Like `supports_v`, it needs no backend's header and no library. + * + * @tparam Capability A capability tag of `capabilities`. + * @tparam Backend A backend tag of `backends`. + */ +template +inline constexpr bool supports_capability_v = detail::capability_supported; + +/** + * Whether the bytes of a secret key that `Backend` holds may leave it. + * + * They leave it through `secret()`, the private formats (`pkcs8`, `pem(pkcs8)`, a key pair's + * `raw`) and Ed25519's conversion to an X25519 key pair. True for every backend crypto ships; false + * for a backend whose keys never leave it, which then has no export capability. It needs no + * backend's header and no library. + * + * @tparam Backend A backend tag of `backends`. + */ +template +inline constexpr bool exports_secret_keys_v = detail::exports_secret_keys_v; + +/** + * Whether the bytes of a secret key may enter `Backend`. + * + * They enter it through a key pair's `from_secret`, `async_from_secret` and private decodes; a + * cipher's `from_key` does not consult it. True for every backend crypto ships; false for a backend + * that only generates its keys, which then has no import capability. It needs no backend's header + * and no library. + * + * @tparam Backend A backend tag of `backends`. + */ +template +inline constexpr bool imports_secret_keys_v = detail::imports_secret_keys_v; + } // namespace webcpp::crypto #endif // WEBCPP_CRYPTO_SUPPORTS_HPP diff --git a/include/webcpp/crypto/unauthenticated_encryption/stream_cipher.hpp b/include/webcpp/crypto/unauthenticated_encryption/stream_cipher.hpp index f540775..b7845d7 100644 --- a/include/webcpp/crypto/unauthenticated_encryption/stream_cipher.hpp +++ b/include/webcpp/crypto/unauthenticated_encryption/stream_cipher.hpp @@ -67,6 +67,7 @@ template // The parentheses keep windows.h's max macro out. // NOLINTBEGIN(readability-redundant-parentheses) std::uint64_t const blocks_after_first = + // NOLINTNEXTLINE(readability-redundant-parentheses): they stop 's macro max std::uint64_t{(std::numeric_limits::max)()} - initial_counter; // NOLINTEND(readability-redundant-parentheses) return blocks != 0 && blocks - 1 > blocks_after_first; diff --git a/test/Jamfile b/test/Jamfile index 93fc688..a302208 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -32,7 +32,14 @@ webcpp.headers-alone crypto : ../include : crypto.hpp crypto/config.hpp crypto/ciphers/aes.hpp crypto/ciphers/gcm.hpp crypto/random_device.hpp crypto/detail/bytes.hpp crypto/detail/engines.hpp crypto/detail/entropy.hpp crypto/detail/limits.hpp - crypto/detail/windows.hpp + crypto/detail/secret_keys.hpp + crypto/detail/backend/common.hpp crypto/detail/backend/symmetric.hpp + crypto/detail/backend/boxes.hpp crypto/detail/backend/keys.hpp + crypto/detail/backend/ed25519.hpp crypto/detail/backend/x25519.hpp + crypto/detail/backend/p256.hpp crypto/detail/backend/entropy.hpp + crypto/detail/backend/asynchronous.hpp crypto/detail/backend/concepts.hpp + crypto/detail/backend/secp256k1.hpp + crypto/detail/windows.hpp crypto/detail/families.hpp crypto/detail/rfc8410.hpp crypto/supports.hpp crypto/detail/capabilities.hpp crypto/detail/defaults.hpp crypto/detail/async_access.hpp crypto/ciphers/aead.hpp crypto/ciphers/chacha20_poly1305.hpp @@ -796,8 +803,18 @@ crypto-run verification_policies : verification_policies_test.cpp # Wycheproof's X25519 file, every case. crypto-run x25519_sodium : x25519_sodium_test.cpp : /third_party//sodium ; # X25519's generic layer on a stand-in engine that does not refuse an all-zero -# shared secret: agree refuses it itself (design D8). +# shared secret: agree refuses it itself (design D8); an engine's error passed +# on by agree, from_secret, secret() and the PKCS#8 encode, which then writes +# nothing. crypto-run x25519_mock : x25519_mock_test.cpp ; +# Ed25519's and P-256's key pairs on a stand-in engine that fails public_key and +# export_secret: public_key(), secret() and Ed25519's PKCS#8 encode pass the +# error on, and the encode writes nothing (backend concepts, task 2.1). +crypto-run keypair_engine_failure : keypair_engine_failure_test.cpp ; +# RFC 8410's public-key formats in a program that links no backend: an Ed25519 +# and an X25519 SPKI encoded and decoded, and detail::rfc8410 directly, its +# refusal of another prefix leaving the key unwritten (task 2.1). +crypto-run rfc8410_no_backend : rfc8410_no_backend_test.cpp ; # ciphers::basic_chacha20_poly1305's, secret_key_encryption::basic_secretbox's # and public_key_encryption::basic_box's generic layer on a stand-in engine # that writes the data before it fails: a failed seal zeroes it, as a failed @@ -1037,6 +1054,11 @@ crypto-run capabilities_emscripten : capabilities_test.cpp /third_party//secp256k1 /third_party//sodium : emscripten ; +# supports_v, supports_capability_v and the secret-key traits with no backend's +# header and no library linked (design D7, R1, R8). +crypto-run supports_header_free : supports_header_free_test.cpp + : : native wasip2 wasip3 emscripten ; + # ctaes against OpenSSL on 10,000 random keys of each size (spec section 8.2), # on native, wasip2 and wasip3 (on WASI OpenSSL runs its portable C code). crypto-run agreement_aes : agreement_aes_test.cpp @@ -1181,3 +1203,42 @@ webcpp.compile doc_sign : ../../../tools/test/fixtures/crypto_jamfiles/sign/sign webcpp.compile doc_sign_small : ../../../tools/test/fixtures/crypto_jamfiles/sign_small/sign.cpp : /third_party//secp256k1 small ; + +# The capability concepts of detail::backend (backend-concepts design D4), one +# test per area header: every engine the table lists satisfies its concept, on +# every backend the target builds; a stand-in (support/backend_stand_in.hpp) +# satisfies it when complete and fails it with any one operation missing, not +# noexcept or of another result, or any one parameter of another shape. +crypto-run backend_concepts_symmetric : backend_concepts_symmetric_test.cpp + : /third_party//bearssl /third_party//ctaes + /third_party//sodium /webcpp/crypto//openssl + : native wasip2 wasip3 ; +crypto-run backend_concepts_symmetric_emscripten : backend_concepts_symmetric_test.cpp + : /third_party//bearssl /third_party//ctaes + /third_party//sodium + : emscripten ; +crypto-run backend_concepts_boxes : backend_concepts_boxes_test.cpp + : /third_party//sodium + : native wasip2 wasip3 emscripten ; +crypto-run backend_concepts_keys : backend_concepts_keys_test.cpp + : /third_party//bearssl /third_party//sodium + : native wasip2 wasip3 emscripten ; +crypto-run backend_concepts_asynchronous : backend_concepts_asynchronous_test.cpp + : : native wasip2 wasip3 emscripten ; +# P-256's sign and verify of a message on a backend whose engine has the message +# form alone (backends/message_only.hpp, design D9): the message reaches the +# engine whole, and the signature comes back low S. +crypto-run p256_message_form : p256_message_form_test.cpp + : : native wasip2 wasip3 emscripten ; +crypto-run backend_concepts_secp256k1 : backend_concepts_secp256k1_test.cpp + : /third_party//secp256k1 + : native wasip2 wasip3 emscripten ; +# The test-only opaque backend (backends/opaque.hpp, design D3, R3, R6, R9), +# outside the table: P-256 and X25519 keys the backend draws and never gives +# out, its engines' concepts, generate() through the backend's own generation, +# real keys checked against BearSSL and libsodium, and its form that completes +# by itself through the async_* concepts and the public asynchronous functions. +crypto-run opaque_backend : opaque_backend_test.cpp + : /third_party//bearssl /third_party//sodium + /webcpp/asio//asio + : native wasip2 wasip3 emscripten ; diff --git a/test/aead_box_mock_test.cpp b/test/aead_box_mock_test.cpp index d4c336e..40792cf 100644 --- a/test/aead_box_mock_test.cpp +++ b/test/aead_box_mock_test.cpp @@ -91,24 +91,52 @@ struct aead_engine { aead_state& /*state*/) noexcept {} }; +/** What the stand-in's X25519 key pair stores: its secret key, which the box reads. */ +template <> +struct x25519_state { + std::array secret_key{}; +}; + /** The stand-in's X25519, for the box's key pair: any secret key has a public key of 9s. */ template <> struct x25519_engine { + using state = x25519_state; + + /** Keeps the secret key. */ + [[nodiscard]] static boost::system::result import_secret( + state& keyed_state, std::span secret_key) noexcept { + std::ranges::copy(secret_key, keyed_state.secret_key.begin()); + return {}; + } + /** Writes a public key of 9s. */ - [[nodiscard]] static boost::system::result base( - std::span /*secret_key*/, - std::span public_bytes) noexcept { + [[nodiscard]] static boost::system::result public_key( + state const& /*keyed_state*/, std::span public_bytes) noexcept { std::ranges::fill(public_bytes, std::uint8_t{9}); return {}; } + /** Never called by the box. */ + [[nodiscard]] static boost::system::result export_secret( + state const& /*keyed_state*/, std::span /*secret_bytes*/) noexcept { + return error::backend_failure; + } + /** Never called by the box, which agrees through its own engine. */ [[nodiscard]] static boost::system::result agree( - std::span /*secret_key*/, - std::span /*peer_public_key*/, + state const& /*keyed_state*/, std::span /*peer_public_key*/, std::span /*shared_bytes*/) noexcept { return error::backend_failure; } + + /** Takes the secret key. */ + static void move(state& target_state, state& source_state) noexcept { + target_state = source_state; + source_state = {}; + } + + /** Forgets the secret key. */ + static void reset(state& keyed_state) noexcept { keyed_state = {}; } }; /** The stand-in's XSalsa20-Poly1305 box: every call writes the data first, then answers. */ diff --git a/test/async_agree_engine_test.cpp b/test/async_agree_engine_test.cpp index f266851..3443a2c 100644 --- a/test/async_agree_engine_test.cpp +++ b/test/async_agree_engine_test.cpp @@ -69,6 +69,18 @@ template <> struct p_curve_engine { using state = p_curve_state; + static void move(state& /*target_state*/, state& /*source_state*/) noexcept {} + + static void reset(state& /*engine_state*/) noexcept {} +}; + +// X25519's key pair moves and resets its state: the stand-in's state holds nothing. +template <> +struct x25519_engine { + using state = x25519_state; + + static void move(state& /*target_state*/, state& /*source_state*/) noexcept {} + static void reset(state& /*engine_state*/) noexcept {} }; diff --git a/test/async_verify_engine_test.cpp b/test/async_verify_engine_test.cpp index 18a555f..47bbb45 100644 --- a/test/async_verify_engine_test.cpp +++ b/test/async_verify_engine_test.cpp @@ -60,6 +60,8 @@ template <> struct p_curve_engine { using state = p_curve_state; + static void move(state& /*target_state*/, state& /*source_state*/) noexcept {} + static void reset(state& /*engine_state*/) noexcept {} }; diff --git a/test/backend_concepts_asynchronous_test.cpp b/test/backend_concepts_asynchronous_test.cpp new file mode 100644 index 0000000..b444f72 --- /dev/null +++ b/test/backend_concepts_asynchronous_test.cpp @@ -0,0 +1,267 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the 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 asynchronous capability concepts of detail::backend (backend-concepts design D4, D6): a +// stand-in `async_engine` (support/backend_stand_in.hpp's defect selector) satisfies every concept +// when complete, and fails them with any one operation missing or any one parameter of another +// shape than `async.hpp`'s call accepts: another executor type, the executor or a key pair, a +// public key, a signature, a scheme or a policy taken by mutable reference (the call passes const +// lvalues), the AEAD taken by rvalue reference (the call passes it as a mutable lvalue), another +// token type, a fixed-extent view where the call passes a dynamic one, and a from_secret, from_key +// or generate that is not a member template. The concepts constrain neither noexcept nor the +// result, both the completion token's. No backend ships an asynchronous engine; task 2.3's +// test-only opaque backend asserts them on a real one. + +#include "support/backend_stand_in.hpp" + +#include + +namespace backend = webcpp::crypto::detail::backend; + +namespace { + +using backend_stand_in::bytes; +using backend_stand_in::const_bytes; +using backend_stand_in::defect; +using backend_stand_in::fixed_input; +using backend_stand_in::fixed_output; +using backend_stand_in::present; +using backend_stand_in::shape_of; + +/** The executor the program gives. */ +struct stand_in_executor {}; + +/** An executor the program does not give. */ +struct other_executor {}; + +/** The completion token, taken by value. */ +struct stand_in_token {}; + +/** A token the program does not give. */ +struct other_token {}; + +/** The public types the operations take. */ +struct stand_in_keypair {}; + +struct stand_in_cipher {}; + +struct stand_in_aead {}; + +struct stand_in_scheme {}; + +struct stand_in_policy {}; + +struct stand_in_signature {}; + +struct stand_in_public_key {}; + +inline constexpr int from_secret_op = backend_stand_in::first_op; +inline constexpr int from_key_op = from_secret_op + 1; +inline constexpr int generate_op = from_key_op + 1; +inline constexpr int seal_op = generate_op + 1; +inline constexpr int open_op = seal_op + 1; +inline constexpr int sign_op = open_op + 1; +inline constexpr int verify_op = sign_op + 1; +inline constexpr int agree_op = verify_op + 1; + +/** The number of operation `Operation`'s parameter shape `Parameter`, apart from operations'. */ +template +inline constexpr int shape = 100 + (Operation * 10) + Parameter; + +/** The executor of another type. */ +inline constexpr int other_executor_shape = 0; +/** The executor by mutable reference. */ +inline constexpr int mutable_executor_shape = 1; +/** The token of another type. */ +inline constexpr int token_shape = 2; +/** The operation's first object (a key pair, the AEAD, a scheme) or view. */ +inline constexpr int first_shape = 3; +/** Not a member template. */ +inline constexpr int template_shape = 4; +/** The operation's further parameters, from this one. */ +inline constexpr int next_shape = 5; + +/** Operation `Operation`'s parameter `Parameter`: `Right`, or `Wrong` under its defect. */ +template +using parameter_of = shape_of, Right, Wrong>; + +/** The executor operation `Operation` takes, or one of the two wrong ones under their defects. */ +template +using executor_of = parameter_of, + other_executor const&>; + +/** The token operation `Operation` takes, or another type under its defect. */ +template +using token_of = parameter_of; + +/** A view operation `Operation` reads at `Parameter`, or a fixed one under its defect. */ +template +using input_of = parameter_of>; + +/** Whether operation `Operation` is a member template under `Defect`. */ +template +inline constexpr bool member_template = Defect.target != shape || + Defect.kind != backend_stand_in::flaw::wrong_shape; + +template +struct async_stand_in { + template + static void from_secret(executor_of /*completion_executor*/, + input_of /*secret_bytes*/, + token_of /*token*/) + requires present && member_template + {} + + static void from_secret(stand_in_executor const& /*completion_executor*/, + const_bytes /*secret_bytes*/, stand_in_token /*token*/) + requires present && (!member_template) + {} + + template + static void from_key(executor_of /*completion_executor*/, + input_of /*key_bytes*/, + token_of /*token*/) + requires present && member_template + {} + + static void from_key(stand_in_executor const& /*completion_executor*/, + const_bytes /*key_bytes*/, stand_in_token /*token*/) + requires present && (!member_template) + {} + + template + static void generate(executor_of /*completion_executor*/, + token_of /*token*/) + requires present && member_template + {} + + static void generate(stand_in_executor const& /*completion_executor*/, stand_in_token /*token*/) + requires present && (!member_template) + {} + + static void seal( + executor_of /*completion_executor*/, + parameter_of /*aead*/, + input_of /*nonce_bytes*/, + input_of /*associated_data_bytes*/, + parameter_of> /*data_bytes*/, + token_of /*token*/) + requires present + {} + + static void open( + executor_of /*completion_executor*/, + parameter_of /*aead*/, + input_of /*nonce_bytes*/, + input_of /*associated_data_bytes*/, + parameter_of> /*data_bytes*/, + input_of /*tag_bytes*/, + token_of /*token*/) + requires present + {} + + static void sign(executor_of /*completion_executor*/, + parameter_of /*key_pair*/, + parameter_of /*signing_scheme*/, + input_of /*input_bytes*/, + token_of /*token*/) + requires present + {} + + static void verify(executor_of /*completion_executor*/, + parameter_of /*signing_scheme*/, + parameter_of /*verification_policy*/, + parameter_of /*signature*/, + input_of /*input_bytes*/, + parameter_of /*public_key*/, + token_of /*token*/) + requires present + {} + + static void agree(executor_of /*completion_executor*/, + parameter_of /*key_pair*/, + parameter_of /*peer_public_key*/, + token_of /*token*/) + requires present + {} +}; + +template +struct async_satisfied { + using engine = async_stand_in; + using executor = stand_in_executor; + using token = stand_in_token; + static constexpr bool value = + backend::async_import_secret && + backend::async_import_key && + backend::async_generate && + backend::async_seal && + backend::async_open && + backend::async_sign && + backend::async_verify && + backend::async_agree; +}; + +static_assert(backend_stand_in::rejects_every_absence); + +/** The executor's and the token's shapes, which every operation has. */ +template +inline constexpr bool rejects_every_executor_and_token = + (backend_stand_in::rejects_every_shape, + shape, + shape> && + ...); + +static_assert(rejects_every_executor_and_token); + +// The member templates and the views of from_secret and from_key. +static_assert(backend_stand_in::rejects_every_shape< + async_satisfied, shape, + shape, shape, + shape, shape>); + +// The AEAD and the views of seal and open. +static_assert( + backend_stand_in::rejects_every_shape< + async_satisfied, shape, shape, + shape, shape, shape, + shape, shape, shape, + shape>); + +// The key pair, the scheme, the policy, the signature, the public keys and the input views of +// sign, verify and agree. +static_assert(backend_stand_in::rejects_every_shape< + async_satisfied, shape, shape, + shape, shape, + shape, shape, + shape, shape, + shape, shape>); + +// An engine without asynchronous operations has none of the capabilities: a synchronous backend. +struct synchronous_engine {}; + +static_assert(!backend::async_generate); + +} // namespace + +int main() { + return 0; +} diff --git a/test/backend_concepts_boxes_test.cpp b/test/backend_concepts_boxes_test.cpp new file mode 100644 index 0000000..45bbd10 --- /dev/null +++ b/test/backend_concepts_boxes_test.cpp @@ -0,0 +1,246 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the 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 box capability concepts of detail::backend (backend-concepts design D1, D2, D4): every +// engine the table lists for crypto_box, the sealed box and crypto_kx satisfies its concept on +// every backend this target links; the concepts' sizes are the public types'; and for each +// concept a stand-in engine (support/backend_stand_in.hpp) satisfies it when complete and fails +// it with any one operation missing, not noexcept or of another result, or any one size parameter +// of another size, so that each requirement is shown to be checked. + +#include "support/backend_stand_in.hpp" + +#include +#include +#include +#include +#include + +#ifdef WEBCPP_CRYPTO_HAS_SODIUM +#include +#endif + +#include + +#include +#include +#include + +namespace backend = webcpp::crypto::detail::backend; +namespace key_exchange = webcpp::crypto::key_exchange; +namespace detail = webcpp::crypto::detail; +namespace families = webcpp::crypto::families; +namespace backends = webcpp::crypto::backends; + +namespace { + +// The shipped engines, on the backends this target links (the table's cells, crypto.json). + +#ifdef WEBCPP_CRYPTO_HAS_SODIUM +static_assert(backend::box>); +static_assert(backend::box>); +static_assert( + backend::sealed_box>); +static_assert(backend::kx>); +// libsodium's X25519 state holds the secret key's bytes, which kx and the boxes read. +static_assert(detail::x25519_state_holds_secret_key); + +// The concepts' sizes are the public types'. +static_assert(backend::kx_seed_size == key_exchange::kx_keypair::seed_size); +static_assert(backend::x25519_key_size == + key_exchange::kx_keypair::public_key_size); +static_assert(backend::kx_session_key_size == + key_exchange::kx_keypair::session_key_size); +#endif + +// Stand-ins. + +using backend_stand_in::bytes; +using backend_stand_in::const_bytes; +using backend_stand_in::defect; +using backend_stand_in::done; +using backend_stand_in::first_op; +using backend_stand_in::init_op; +using backend_stand_in::move_op; +using backend_stand_in::nothrow; +using backend_stand_in::present; +using backend_stand_in::reset_op; +using backend_stand_in::result_of; +using backend_stand_in::result_void; +using backend_stand_in::shape_of; +using backend_stand_in::sized_input; +using backend_stand_in::sized_output; +using backend_stand_in::state_operations; +using backend_stand_in::state_type; + +inline constexpr std::size_t key_size = backend::x25519_key_size; + +// box: init with the own secret key and the peer's public key, seal and open. + +inline constexpr int seal_op = first_op; +inline constexpr int open_op = first_op + 1; +inline constexpr int box_secret_shape = first_op + 2; +inline constexpr int box_peer_shape = first_op + 3; +inline constexpr int box_seal_nonce_shape = first_op + 4; +inline constexpr int box_open_nonce_shape = first_op + 5; +inline constexpr int box_tag_shape = first_op + 6; +inline constexpr int box_check_shape = first_op + 7; + +template +struct box_stand_in : state_operations { + static result_of init( + state_type& /*engine_state*/, sized_input /*own_key*/, + sized_input /*peer_key*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of seal( + state_type& /*engine_state*/, + sized_input /*nonce_bytes*/, + bytes /*data_bytes*/, + shape_of&, + boost::hash2::digest&> /*tag_bytes*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of open( + state_type& /*engine_state*/, + sized_input /*nonce_bytes*/, + bytes /*data_bytes*/, + shape_of const&, + std::array const&> /*tag_bytes*/) noexcept(nothrow) + requires present + { + return done>(); + } +}; + +template +struct box_satisfied { + static constexpr bool value = backend::box>; +}; + +static_assert(backend_stand_in::rejects_every_defect); +static_assert(backend_stand_in::rejects_every_shape); + +// sealed_box: static seal and open, no state. + +inline constexpr int sealed_seal_op = 0; +inline constexpr int sealed_open_op = 1; +inline constexpr int sealed_seal_public_shape = 2; +inline constexpr int sealed_open_public_shape = 3; +inline constexpr int sealed_open_secret_shape = 4; + +template +struct sealed_box_stand_in { + static result_of seal( + sized_input /*recipient_public_key*/, + const_bytes /*message_bytes*/, + bytes /*sealed_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of open( + sized_input /*recipient_public_key*/, + sized_input /*recipient_secret_key*/, + const_bytes /*sealed_bytes*/, + bytes /*message_output*/) noexcept(nothrow) + requires present + { + return done>(); + } +}; + +template +struct sealed_box_satisfied { + static constexpr bool value = backend::sealed_box>; +}; + +static_assert( + backend_stand_in::rejects_every_defect); +static_assert( + backend_stand_in::rejects_every_shape); + +// kx: static seed_keypair, client and server, no state; every key's size. + +inline constexpr int seed_keypair_op = 0; +inline constexpr int client_op = 1; +inline constexpr int server_op = 2; +inline constexpr int seed_shape = 3; +inline constexpr int seed_secret_shape = 4; +/** The first of client's five shapes (secret, public, peer, receive, transmit); server's follow. */ +inline constexpr int client_shape = 5; +inline constexpr int server_shape = 10; + +template +struct kx_stand_in { + static result_of seed_keypair( + sized_input /*seed_bytes*/, + sized_output /*secret_key_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of client( + sized_input /*secret_key*/, + sized_input /*public_key*/, + sized_input /*peer_public_key*/, + sized_output /*receive_key*/, + sized_output /*transmit_key*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of server( + sized_input /*secret_key*/, + sized_input /*public_key*/, + sized_input /*peer_public_key*/, + sized_output /*receive_key*/, + sized_output /*transmit_key*/) noexcept(nothrow) + requires present + { + return done>(); + } +}; + +template +struct kx_satisfied { + static constexpr bool value = backend::kx>; +}; + +static_assert( + backend_stand_in::rejects_every_defect); +static_assert(backend_stand_in::rejects_every_shape< + kx_satisfied, seed_shape, seed_secret_shape, client_shape, client_shape + 1, + client_shape + 2, client_shape + 3, client_shape + 4, server_shape, server_shape + 1, + server_shape + 2, server_shape + 3, server_shape + 4>); + +} // namespace + +int main() { + return 0; +} diff --git a/test/backend_concepts_keys_test.cpp b/test/backend_concepts_keys_test.cpp new file mode 100644 index 0000000..7ec66e8 --- /dev/null +++ b/test/backend_concepts_keys_test.cpp @@ -0,0 +1,706 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the 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 key capability concepts of detail::backend (backend-concepts design D3, D4): Ed25519's, +// X25519's and P-256's, split by import, generate, public, use and export; P-256's points and DER; +// and the entropy source. +// +// - The shipped engines whose shape is already the concepts' satisfy them: Ed25519's verifying and +// Ed25519ph on libsodium, P-256's points, verifying and DER on BearSSL. The key engines take the +// concepts' names (`import_secret`, `public_key`, `export_secret`, `move`) in task 2.1, which +// asserts them in the backend headers. +// - For each curve a stand-in engine (support/backend_stand_in.hpp) satisfies every concept of the +// curve when complete and fails them with any one operation missing, not noexcept or of another +// result, or any one size or type parameter of another shape (a fixed-extent view where the +// concept passes a dynamic one, a view where it passes a byte). +// - An opaque key (design D3), a stand-in without import and export, satisfies generate, public and +// every use, and neither import nor export. +// - P-256 signs and verifies in a digest form, a message form or both: a WebCrypto-like engine with +// the message form alone satisfies it and not the digest one. + +#include "support/backend_stand_in.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace backend = webcpp::crypto::detail::backend; +namespace detail = webcpp::crypto::detail; +namespace families = webcpp::crypto::families; +namespace backends = webcpp::crypto::backends; + +namespace { + +// The shipped curve engines, every concept their table cells promise: their backend headers +// assert the same after each specialization (design D5), and this test names them again. + +#ifdef WEBCPP_CRYPTO_HAS_SODIUM +using sodium_ed25519 = detail::ed25519_engine; +static_assert(backend::ed25519_import && backend::ed25519_public && + backend::ed25519_export); +static_assert(backend::ed25519_signing && + backend::ed25519_verifying && + backend::ed25519_to_x25519); +static_assert( + backend::ed25519ph, + sodium_ed25519>); + +using sodium_x25519 = detail::x25519_engine; +static_assert(backend::x25519_import && backend::x25519_public && + backend::x25519_export && backend::x25519_agreement); +#endif + +#ifdef WEBCPP_CRYPTO_HAS_BEARSSL +using bearssl_p256 = detail::p_curve_engine; +static_assert(backend::p256_import && backend::p256_public && + backend::p256_export); +static_assert(backend::p256_point && backend::p256_ecdsa_signing && + backend::p256_ecdsa_verifying && backend::p256_ecdh); +static_assert(backend::ecdsa_der); +#endif + +using backend_stand_in::const_bytes; +using backend_stand_in::defect; +using backend_stand_in::done; +using backend_stand_in::first_op; +using backend_stand_in::flaw; +using backend_stand_in::move_op; +using backend_stand_in::nothrow; +using backend_stand_in::present; +using backend_stand_in::reset_op; +using backend_stand_in::result_of; +using backend_stand_in::result_void; +using backend_stand_in::shape_of; +using backend_stand_in::sized_input; +using backend_stand_in::sized_output; +using backend_stand_in::state_operations; +using backend_stand_in::state_type; + +// The key capabilities every curve shares: import, generate, public and export. + +inline constexpr int import_op = first_op; +inline constexpr int generate_op = first_op + 1; +inline constexpr int public_op = first_op + 2; +inline constexpr int export_op = first_op + 3; +inline constexpr int import_shape = first_op + 4; +inline constexpr int public_shape = first_op + 5; +inline constexpr int export_shape = first_op + 6; +/** The first number a curve's own operations and shapes take. */ +inline constexpr int curve_op = first_op + 7; + +/** A key engine whose public key has `PublicSize` bytes. */ +template +struct key_stand_in : state_operations { + static result_of import_secret( + state_type& /*engine_state*/, + sized_input /*secret_bytes*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of generate( + state_type& /*engine_state*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of public_key( + state_type const& /*engine_state*/, + sized_output /*public_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of export_secret( + state_type const& /*engine_state*/, + sized_output /*secret_output*/) noexcept(nothrow) + requires present + { + return done>(); + } +}; + +/** The defect that leaves `Operation` out. */ +template +inline constexpr defect without = defect{.target = Operation, .kind = flaw::missing}; + +/** A view of any length, or a fixed-extent one under shape `Target`'s defect. */ +template +using dynamic_input = shape_of>; + +// Ed25519: signing, verifying and the map to X25519, over the key capabilities. + +inline constexpr int sign_op = curve_op; +inline constexpr int verify_op = curve_op + 1; +inline constexpr int x25519_secret_op = curve_op + 2; +inline constexpr int to_x25519_public_op = curve_op + 3; +inline constexpr int ed_sign_shape = curve_op + 4; +inline constexpr int ed_verify_key_shape = curve_op + 5; +inline constexpr int ed_verify_signature_shape = curve_op + 6; +inline constexpr int ed_x25519_secret_shape = curve_op + 7; +inline constexpr int ed_to_x25519_input_shape = curve_op + 8; +inline constexpr int ed_to_x25519_output_shape = curve_op + 9; +inline constexpr int ed_sign_message_shape = curve_op + 10; +inline constexpr int ed_verify_message_shape = curve_op + 11; + +template +struct ed25519_stand_in : key_stand_in { + static result_of sign( + state_type const& /*engine_state*/, + dynamic_input /*message_bytes*/, + sized_output + /*signature_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of verify( + sized_input + /*public_key*/, + dynamic_input /*message_bytes*/, + sized_input + /*signature_bytes*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of x25519_secret( + state_type const& /*engine_state*/, + sized_output + /*secret_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of to_x25519_public( + sized_input + /*public_key*/, + sized_output + /*public_output*/) noexcept(nothrow) + requires present + { + return done>(); + } +}; + +template +struct ed25519_satisfied { + using engine = ed25519_stand_in; + static constexpr bool value = + backend::ed25519_import && backend::ed25519_generate && + backend::ed25519_public && backend::ed25519_export && + backend::ed25519_signing && backend::ed25519_verifying && + backend::ed25519_to_x25519; +}; + +static_assert(backend_stand_in::rejects_every_defect< + ed25519_satisfied, move_op, reset_op, import_op, generate_op, public_op, export_op, + sign_op, verify_op, x25519_secret_op, to_x25519_public_op>); +static_assert(backend_stand_in::rejects_every_shape< + ed25519_satisfied, import_shape, public_shape, export_shape, ed_sign_shape, + ed_verify_key_shape, ed_verify_signature_shape, ed_x25519_secret_shape, + ed_to_x25519_input_shape, ed_to_x25519_output_shape, ed_sign_message_shape, + ed_verify_message_shape>); + +// Ed25519ph over the complete Ed25519 stand-in: its own hashing state, no move. + +using ed25519_key = ed25519_stand_in; +inline constexpr int begin_op = first_op; +inline constexpr int update_op = first_op + 1; +inline constexpr int ph_sign_op = first_op + 2; +inline constexpr int ph_verify_op = first_op + 3; +inline constexpr int sign_digest_op = first_op + 4; +inline constexpr int verify_digest_op = first_op + 5; +inline constexpr int ph_reset_op = first_op + 6; +inline constexpr int ph_key_state_shape = first_op + 7; +inline constexpr int ph_sign_shape = first_op + 8; +inline constexpr int ph_verify_key_shape = first_op + 9; +inline constexpr int ph_verify_signature_shape = first_op + 10; +inline constexpr int sign_digest_digest_shape = first_op + 11; +inline constexpr int sign_digest_key_state_shape = first_op + 12; +inline constexpr int sign_digest_output_shape = first_op + 13; +inline constexpr int verify_digest_key_shape = first_op + 14; +inline constexpr int verify_digest_digest_shape = first_op + 15; +inline constexpr int verify_digest_signature_shape = first_op + 16; +inline constexpr int update_piece_shape = first_op + 17; + +/** The hashing state of Ed25519ph's stand-in. */ +struct hashing_state {}; + +/** A key state that is not the key engine's. */ +struct other_key_state {}; + +/** The key engine's state, or another type under shape `Target`'s defect. */ +template +using key_state = shape_of; + +template +struct ed25519ph_stand_in { + using state = hashing_state; + + static result_of begin(hashing_state& /*begun_state*/) noexcept( + nothrow) + requires present + { + return done>(); + } + + static result_of update( + hashing_state& /*begun_state*/, + dynamic_input /*piece_bytes*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of sign( + hashing_state& /*begun_state*/, key_state /*key_state*/, + sized_output + /*signature_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of verify( + hashing_state& /*begun_state*/, + sized_input + /*public_key*/, + sized_input + /*signature_bytes*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of sign_digest( + key_state /*key_state*/, + sized_input + /*digest_bytes*/, + sized_output + /*signature_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of verify_digest( + sized_input + /*public_key*/, + sized_input + /*digest_bytes*/, + sized_input + /*signature_bytes*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of reset(hashing_state& /*begun_state*/) noexcept( + nothrow) + requires present + { + return done>(); + } +}; + +template +struct ed25519ph_satisfied { + static constexpr bool value = backend::ed25519ph, ed25519_key>; +}; + +static_assert(backend_stand_in::rejects_every_defect); +static_assert(backend_stand_in::rejects_every_shape< + ed25519ph_satisfied, ph_key_state_shape, ph_sign_shape, ph_verify_key_shape, + ph_verify_signature_shape, sign_digest_digest_shape, sign_digest_key_state_shape, + sign_digest_output_shape, verify_digest_key_shape, verify_digest_digest_shape, + verify_digest_signature_shape, update_piece_shape>); + +// X25519: agreement, over the key capabilities. + +inline constexpr int agree_op = curve_op; +inline constexpr int agree_peer_shape = curve_op + 1; +inline constexpr int agree_output_shape = curve_op + 2; + +template +struct x25519_stand_in : key_stand_in { + static result_of agree( + state_type const& /*engine_state*/, + sized_input /*peer_public_key*/, + sized_output /*shared_output*/) noexcept(nothrow) + requires present + { + return done>(); + } +}; + +template +struct x25519_satisfied { + using engine = x25519_stand_in; + static constexpr bool value = + backend::x25519_import && backend::x25519_generate && + backend::x25519_public && backend::x25519_export && + backend::x25519_agreement; +}; + +static_assert(backend_stand_in::rejects_every_defect); +static_assert( + backend_stand_in::rejects_every_shape); + +// P-256: points, ECDSA signing and verifying, ECDH and DER, over the key capabilities. + +inline constexpr int valid_point_op = curve_op; +inline constexpr int decompress_op = curve_op + 1; +inline constexpr int p_sign_op = curve_op + 2; +inline constexpr int p_verify_op = curve_op + 3; +inline constexpr int ecdh_op = curve_op + 4; +inline constexpr int to_der_op = curve_op + 5; +inline constexpr int from_der_op = curve_op + 6; +inline constexpr int valid_point_shape = curve_op + 7; +inline constexpr int decompress_x_shape = curve_op + 8; +inline constexpr int decompress_y_shape = curve_op + 9; +inline constexpr int p_sign_digest_shape = curve_op + 10; +inline constexpr int p_sign_output_shape = curve_op + 11; +inline constexpr int p_verify_point_shape = curve_op + 12; +inline constexpr int p_verify_digest_shape = curve_op + 13; +inline constexpr int p_verify_signature_shape = curve_op + 14; +inline constexpr int ecdh_peer_shape = curve_op + 15; +inline constexpr int ecdh_output_shape = curve_op + 16; +inline constexpr int to_der_signature_shape = curve_op + 17; +inline constexpr int to_der_output_shape = curve_op + 18; +inline constexpr int from_der_output_shape = curve_op + 19; +inline constexpr int p_sign_message_op = curve_op + 20; +inline constexpr int p_verify_message_op = curve_op + 21; +inline constexpr int p_sign_message_shape = curve_op + 22; +inline constexpr int p_sign_message_output_shape = curve_op + 23; +inline constexpr int p_verify_message_point_shape = curve_op + 24; +inline constexpr int p_verify_message_shape = curve_op + 25; +inline constexpr int p_verify_message_signature_shape = curve_op + 26; +inline constexpr int decompress_prefix_shape = curve_op + 27; +inline constexpr int from_der_input_shape = curve_op + 28; + +template +struct p256_stand_in : key_stand_in { + static result_of valid_point( + sized_input /*point_bytes*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of decompress( + shape_of /*parity_prefix*/, + sized_input /*x_bytes*/, + sized_output /*y_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of sign( + state_type const& /*engine_state*/, + sized_input /*digest_bytes*/, + sized_output + /*signature_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of verify( + sized_input /*point_bytes*/, + sized_input /*digest_bytes*/, + sized_input + /*signature_bytes*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of ecdh_x( + state_type const& /*engine_state*/, + sized_input /*peer_point*/, + sized_output /*shared_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of to_der( + sized_input + /*signature_bytes*/, + sized_output /*der_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of from_der( + dynamic_input /*der_bytes*/, + sized_output + /*signature_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of sign_message( + state_type const& /*engine_state*/, + dynamic_input /*message_bytes*/, + sized_output + /*signature_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of verify_message( + sized_input + /*point_bytes*/, + dynamic_input /*message_bytes*/, + sized_input + /*signature_bytes*/) noexcept(nothrow) + requires present + { + return done>(); + } +}; + +template +struct p256_satisfied { + using engine = p256_stand_in; + static constexpr bool value = + backend::p256_import && backend::p256_generate && + backend::p256_public && backend::p256_export && + backend::p256_point && backend::p256_ecdsa_signing && + backend::p256_ecdsa_verifying && backend::p256_ecdsa_message_signing && + backend::p256_ecdsa_message_verifying && backend::p256_ecdh && + backend::ecdsa_der; +}; + +static_assert(backend_stand_in::rejects_every_defect< + p256_satisfied, move_op, reset_op, import_op, generate_op, public_op, export_op, + valid_point_op, decompress_op, p_sign_op, p_verify_op, ecdh_op, to_der_op, + from_der_op, p_sign_message_op, p_verify_message_op>); +static_assert(backend_stand_in::rejects_every_shape< + p256_satisfied, import_shape, public_shape, export_shape, valid_point_shape, + decompress_x_shape, decompress_y_shape, p_sign_digest_shape, p_sign_output_shape, + p_verify_point_shape, p_verify_digest_shape, p_verify_signature_shape, + ecdh_peer_shape, ecdh_output_shape, to_der_signature_shape, to_der_output_shape, + from_der_output_shape, p_sign_message_shape, p_sign_message_output_shape, + p_verify_message_point_shape, p_verify_message_shape, + p_verify_message_signature_shape, decompress_prefix_shape, from_der_input_shape>); + +// The opaque key (design D3): without import and export, a key engine still generates, gives its +// public key and is used; it neither imports nor exports. Each of import and export is its own +// capability: an engine that only imports, or only exports, is a valid shape too. + +template +inline constexpr bool opaque_p256 = + backend::p256_generate && backend::p256_public && + backend::p256_ecdsa_signing && backend::p256_ecdh && + !backend::p256_import && !backend::p256_export; + +template +inline constexpr bool opaque_x25519 = + backend::x25519_generate && backend::x25519_public && + backend::x25519_agreement && !backend::x25519_import && + !backend::x25519_export; + +/** The opaque P-256 key: generate, public and the uses. */ +struct opaque_p256_engine { + using state = state_type; + + static void move(state_type& /*target_state*/, state_type& /*source_state*/) noexcept {} + + static void reset(state_type& /*engine_state*/) noexcept {} + + static result_void generate(state_type& /*engine_state*/) noexcept { return {}; } + + static result_void public_key( + state_type const& /*engine_state*/, + backend_stand_in::fixed_output /*public_output*/) noexcept { + return {}; + } + + static result_void sign( + state_type const& /*engine_state*/, + backend_stand_in::fixed_input /*digest_bytes*/, + backend_stand_in::fixed_output< + backend::p256_signature_size> /*signature_output*/) noexcept { + return {}; + } + + static result_void ecdh_x( + state_type const& /*engine_state*/, + backend_stand_in::fixed_input /*peer_point*/, + backend_stand_in::fixed_output /*shared_output*/) noexcept { + return {}; + } +}; + +/** The opaque X25519 key: generate, public and agreement. */ +struct opaque_x25519_engine { + using state = state_type; + + static void move(state_type& /*target_state*/, state_type& /*source_state*/) noexcept {} + + static void reset(state_type& /*engine_state*/) noexcept {} + + static result_void generate(state_type& /*engine_state*/) noexcept { return {}; } + + static result_void public_key( + state_type const& /*engine_state*/, + backend_stand_in::fixed_output /*public_output*/) noexcept { + return {}; + } + + static result_void agree( + state_type const& /*engine_state*/, + backend_stand_in::fixed_input /*peer_public_key*/, + backend_stand_in::fixed_output /*shared_output*/) noexcept { + return {}; + } +}; + +static_assert(opaque_p256); +static_assert(opaque_x25519); +// Import and export are separate capabilities: leaving one out keeps the other. +static_assert(!backend::p256_import>> && + backend::p256_export>>); +static_assert(backend::x25519_import>> && + !backend::x25519_export>>); +// A key engine with no state operations is no key engine, however complete its uses. +static_assert(!backend::p256_ecdsa_signing>>); +static_assert(!backend::p256_ecdsa_message_signing>>); + +// P-256's two signing forms (design D4): an engine that hashes inside, as WebCrypto does, has the +// message form alone; BearSSL's has the digest form alone. Each is a capability of its own. + +/** A WebCrypto-like opaque P-256 key: it signs and verifies messages, never digests. */ +struct message_p256_engine { + using state = state_type; + + static void move(state_type& /*target_state*/, state_type& /*source_state*/) noexcept {} + + static void reset(state_type& /*engine_state*/) noexcept {} + + static result_void generate(state_type& /*engine_state*/) noexcept { return {}; } + + static result_void sign_message( + state_type const& /*engine_state*/, const_bytes /*message_bytes*/, + backend_stand_in::fixed_output< + backend::p256_signature_size> /*signature_output*/) noexcept { + return {}; + } + + static result_void verify_message( + backend_stand_in::fixed_input /*point_bytes*/, + const_bytes /*message_bytes*/, + backend_stand_in::fixed_input /*signature_bytes*/) noexcept { + return {}; + } +}; + +static_assert(backend::p256_ecdsa_message_signing && + backend::p256_ecdsa_message_verifying); +static_assert(!backend::p256_ecdsa_signing && + !backend::p256_ecdsa_verifying); +// The forms differ by name, not by shape: an engine whose `sign` and `verify` take a view of any +// length satisfies the digest concepts (a 32-byte digest converts to it) and never the message +// ones, which only `sign_message` and `verify_message` satisfy. + +/** An engine whose digest-form `sign` and `verify` take a view of any length. */ +struct dynamic_digest_p256_engine { + using state = state_type; + + static void move(state_type& /*target_state*/, state_type& /*source_state*/) noexcept {} + + static void reset(state_type& /*engine_state*/) noexcept {} + + static result_void sign(state_type const& /*engine_state*/, const_bytes /*digest_bytes*/, + backend_stand_in::fixed_output< + backend::p256_signature_size> /*signature_output*/) noexcept { + return {}; + } + + static bool verify( + backend_stand_in::fixed_input /*point_bytes*/, + const_bytes /*digest_bytes*/, + backend_stand_in::fixed_input /*signature_bytes*/) noexcept { + return true; + } +}; + +static_assert(backend::p256_ecdsa_signing && + backend::p256_ecdsa_verifying); +static_assert(!backend::p256_ecdsa_message_signing && + !backend::p256_ecdsa_message_verifying); +#ifdef WEBCPP_CRYPTO_HAS_BEARSSL +static_assert(!backend::p256_ecdsa_message_signing && + !backend::p256_ecdsa_message_verifying); +#endif + +// The entropy source. + +inline constexpr int fill_op = first_op; + +template +struct entropy_stand_in { + static result_of fill( + backend_stand_in::bytes /*output_bytes*/) noexcept(nothrow) + requires present + { + return done>(); + } +}; + +template +struct entropy_satisfied { + static constexpr bool value = backend::entropy_source>; +}; + +static_assert(backend_stand_in::rejects_every_defect); + +} // namespace + +int main() { + return 0; +} diff --git a/test/backend_concepts_secp256k1_test.cpp b/test/backend_concepts_secp256k1_test.cpp new file mode 100644 index 0000000..fa11555 --- /dev/null +++ b/test/backend_concepts_secp256k1_test.cpp @@ -0,0 +1,1531 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// secp256k1's capability concepts of detail::backend (backend-concepts design D4, D8): the key +// pair's, the points', ECDSA's and its signature's forms, Schnorr's, recoverable ECDSA's, ECDH's, +// the tweaks', ElligatorSwift's, MuSig2's and silent payments'. +// +// - libsecp256k1's engines satisfy them: its backend header asserts each after its specialization +// (design D5), and this test names them again. +// - For each capability a stand-in engine (support/backend_stand_in.hpp) satisfies its concepts +// when complete and fails them with any one operation missing, not noexcept or of another result, +// or any one parameter of another shape (a view of another size, a view where the concept passes +// another, an object of another type, the key state of another engine), every parameter of +// every operation included. +// - The engines' own guards, which the public functions refuse before them, run on libsecp256k1's +// engines directly: ECDSA's extra entropy of a size other than 0 or 32, a recovery id above 3, +// and DER that is no valid signature's. + +#include "support/backend_stand_in.hpp" + +#include +#include +#include + +#include +#include + +#ifdef WEBCPP_CRYPTO_HAS_SECP256K1 +#include +#include +#endif + +#include + +#include +#include +#include +#include + +namespace backend = webcpp::crypto::detail::backend; +namespace capabilities = webcpp::crypto::detail::backend::secp256k1_capabilities; + +namespace { + +#ifdef WEBCPP_CRYPTO_HAS_SECP256K1 +// libsecp256k1's engines, every concept of each capability. +template +using shipped = webcpp::crypto::detail::secp256k1_engine_of; +static_assert(backend::secp256k1_import> && + backend::secp256k1_public> && + backend::secp256k1_export>); +static_assert(backend::secp256k1_point>); +static_assert(backend::secp256k1_ecdsa_signing> && + backend::secp256k1_ecdsa_verifying> && + backend::secp256k1_ecdsa_forms>); +static_assert(backend::secp256k1_schnorr_signing> && + backend::secp256k1_schnorr_verifying>); +static_assert(backend::secp256k1_recoverable>); +static_assert(backend::secp256k1_ecdh>); +static_assert(backend::secp256k1_tweak>); +static_assert(backend::secp256k1_ellswift>); +static_assert(backend::secp256k1_musig>); +static_assert(backend::secp256k1_silent_payments>); +// libsecp256k1 draws no key itself: a key pair's generation is the public layer's (task 2.1). +static_assert(!backend::secp256k1_generate>); +#endif + +using backend_stand_in::const_bytes; +using backend_stand_in::defect; +using backend_stand_in::done; +using backend_stand_in::first_op; +using backend_stand_in::move_op; +using backend_stand_in::nothrow; +using backend_stand_in::present; +using backend_stand_in::reset_op; +using backend_stand_in::result_of; +using backend_stand_in::result_void; +using backend_stand_in::shape_of; +using backend_stand_in::sized_input; +using backend_stand_in::sized_output; +using backend_stand_in::state_operations; +using backend_stand_in::state_type; + +/** A view of any length, or a fixed-extent one under shape `Target`'s defect. */ +template +using dynamic_input = shape_of>; + +/** The stand-ins' point. */ +struct point_type {}; + +/** The stand-ins' x-only key. */ +struct xonly_type {}; + +/** An object of a type no concept takes. */ +struct other_type {}; + +/** The stand-ins' key state, which the use engines name. */ +using key_type = state_type; + +/** `Right`, or a reference to `other_type` under shape `Target`'s defect. */ +template +using typed = shape_of; + +/** `Right`, or a writable reference to `other_type` under shape `Target`'s defect. */ +template +using typed_output = shape_of; + +/** An `int&` output, or a `bool&` one under shape `Target`'s defect. */ +template +using int_output = shape_of; + +// The key pair: import (with its context's size, its check and its start), generate, public (with +// the point and the x-only key) and export. + +inline constexpr int import_op = first_op; +inline constexpr int generate_op = first_op + 1; +inline constexpr int public_op = first_op + 2; +inline constexpr int export_op = first_op + 3; +inline constexpr int context_size_op = first_op + 4; +inline constexpr int valid_secret_op = first_op + 5; +inline constexpr int start_op = first_op + 6; +inline constexpr int public_point_op = first_op + 7; +inline constexpr int xonly_key_op = first_op + 8; +inline constexpr int import_shape = first_op + 9; +inline constexpr int public_shape = first_op + 10; +inline constexpr int export_shape = first_op + 11; +inline constexpr int valid_secret_shape = first_op + 12; +inline constexpr int start_storage_shape = first_op + 13; +inline constexpr int start_seed_shape = first_op + 14; +inline constexpr int public_point_shape = first_op + 15; +inline constexpr int xonly_key_shape = first_op + 16; +inline constexpr int parity_shape = first_op + 17; + +template +struct key_stand_in : state_operations { + using point = point_type; + using xonly_point = xonly_type; + + static result_of import_secret( + state_type& /*engine_state*/, + sized_input /*secret_bytes*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of generate( + state_type& /*engine_state*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of public_key( + state_type const& /*engine_state*/, + sized_output< + Defect, public_shape, + backend::secp256k1_compressed_size> /*public_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of export_secret( + state_type const& /*engine_state*/, + sized_output /*secret_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of context_size() noexcept( + nothrow) + requires present + { + return done>(); + } + + static result_of valid_secret( + sized_input /*secret_bytes*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of start( + state_type& /*engine_state*/, + shape_of /*context_storage*/, + sized_input /*seed_bytes*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of public_point( + state_type const& /*engine_state*/, + typed_output /*point_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of xonly_key( + state_type const& /*engine_state*/, + typed_output /*xonly_output*/, + int_output /*parity_output*/) noexcept(nothrow) + requires present + { + return done>(); + } +}; + +template +struct key_satisfied { + using engine = key_stand_in; + static constexpr bool value = + backend::secp256k1_import && backend::secp256k1_generate && + backend::secp256k1_public && backend::secp256k1_export; +}; + +static_assert(backend_stand_in::rejects_every_defect< + key_satisfied, move_op, reset_op, import_op, generate_op, public_op, export_op, + context_size_op, valid_secret_op, start_op, public_point_op, xonly_key_op>); +static_assert( + backend_stand_in::rejects_every_shape); + +// An opaque key, the backend's own (design D3): no import and no export, generate and the rest. +static_assert(!backend::secp256k1_import< + key_stand_in>); +static_assert( + backend::secp256k1_generate< + key_stand_in> && + backend::secp256k1_public< + key_stand_in>); + +/** The key state of the use engines' stand-ins, or another engine's under shape `Target`'s defect. + */ +template +using key_state_input = typed; + +/** An object of type `Object` as input, or another type's under shape `Target`'s defect. */ +template +using object_in = typed; +/** An object of type `Object` as output, or another type's under shape `Target`'s defect. */ +template +using object_out = typed_output; +/** 32 bytes in, or 31 under shape `Target`'s defect. */ +template +using element_in = sized_input; +/** 32 bytes out, or 31 under shape `Target`'s defect. */ +template +using element_out = sized_output; +/** Pointers to `Object`s, or to another type under shape `Target`'s defect. */ +template +using pointers_in = + shape_of, std::span>; + +// The points and x-only keys. + +inline constexpr int parse_op = first_op; +inline constexpr int serialize_compressed_op = first_op + 1; +inline constexpr int serialize_uncompressed_op = first_op + 2; +inline constexpr int compare_op = first_op + 3; +inline constexpr int to_xonly_op = first_op + 4; +inline constexpr int parse_xonly_op = first_op + 5; +inline constexpr int serialize_xonly_op = first_op + 6; +inline constexpr int compare_xonly_op = first_op + 7; +inline constexpr int parse_input_shape = first_op + 8; +inline constexpr int parse_output_shape = first_op + 9; +inline constexpr int compressed_point_shape = first_op + 10; +inline constexpr int compressed_shape = first_op + 11; +inline constexpr int uncompressed_point_shape = first_op + 12; +inline constexpr int uncompressed_shape = first_op + 13; +inline constexpr int compare_left_shape = first_op + 14; +inline constexpr int compare_right_shape = first_op + 15; +inline constexpr int to_xonly_point_shape = first_op + 16; +inline constexpr int to_xonly_shape = first_op + 17; +inline constexpr int parse_xonly_input_shape = first_op + 18; +inline constexpr int parse_xonly_output_shape = first_op + 19; +inline constexpr int serialize_xonly_key_shape = first_op + 20; +inline constexpr int serialize_xonly_shape = first_op + 21; +inline constexpr int compare_xonly_left_shape = first_op + 22; +inline constexpr int compare_xonly_right_shape = first_op + 23; + +template +struct point_stand_in { + using point = point_type; + using xonly_point = xonly_type; + + static result_of parse( + dynamic_input /*encoded_bytes*/, + object_out /*point_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of serialize( + object_in /*point_value*/, + sized_output + /*compressed_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of serialize( + object_in /*point_value*/, + sized_output + /*uncompressed_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of compare( + object_in /*left_point*/, + object_in /*right_point*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of to_xonly( + object_in /*point_value*/, + object_out /*xonly_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of parse_xonly( + element_in /*xonly_bytes*/, + object_out /*xonly_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of serialize_xonly( + object_in /*xonly_value*/, + element_out /*xonly_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of compare_xonly( + object_in /*left_key*/, + object_in /*right_key*/) noexcept(nothrow) + requires present + { + return done>(); + } +}; + +template +struct point_satisfied { + static constexpr bool value = backend::secp256k1_point>; +}; + +static_assert(backend_stand_in::rejects_every_defect< + point_satisfied, parse_op, serialize_compressed_op, serialize_uncompressed_op, + compare_op, to_xonly_op, parse_xonly_op, serialize_xonly_op, compare_xonly_op>); +static_assert(backend_stand_in::rejects_every_shape< + point_satisfied, parse_input_shape, parse_output_shape, compressed_point_shape, + compressed_shape, uncompressed_point_shape, uncompressed_shape, compare_left_shape, + compare_right_shape, to_xonly_point_shape, to_xonly_shape, parse_xonly_input_shape, + parse_xonly_output_shape, serialize_xonly_key_shape, serialize_xonly_shape, + compare_xonly_left_shape, compare_xonly_right_shape>); + +// ECDSA over a digest, and its signature's forms. + +inline constexpr int ecdsa_sign_op = first_op; +inline constexpr int ecdsa_verify_op = first_op + 1; +inline constexpr int valid_compact_op = first_op + 2; +inline constexpr int is_low_s_op = first_op + 3; +inline constexpr int low_s_op = first_op + 4; +inline constexpr int to_der_op = first_op + 5; +inline constexpr int from_der_op = first_op + 6; +inline constexpr int sign_key_shape = first_op + 7; +inline constexpr int sign_digest_shape = first_op + 8; +inline constexpr int sign_entropy_shape = first_op + 9; +inline constexpr int sign_output_shape = first_op + 10; +inline constexpr int verify_point_shape = first_op + 11; +inline constexpr int verify_digest_shape = first_op + 12; +inline constexpr int verify_signature_shape = first_op + 13; +inline constexpr int valid_compact_shape = first_op + 14; +inline constexpr int is_low_s_shape = first_op + 15; +inline constexpr int low_s_input_shape = first_op + 16; +inline constexpr int low_s_output_shape = first_op + 17; +inline constexpr int was_high_shape = first_op + 18; +inline constexpr int to_der_input_shape = first_op + 19; +inline constexpr int der_output_shape = first_op + 20; +inline constexpr int der_size_shape = first_op + 21; +inline constexpr int from_der_input_shape = first_op + 22; +inline constexpr int from_der_output_shape = first_op + 23; + +/** A compact signature in, or a view of another size under shape `Target`'s defect. */ +template +using signature_in = sized_input; +/** A compact signature out, or a view of another size under shape `Target`'s defect. */ +template +using signature_out = sized_output; + +template +struct ecdsa_stand_in { + using key_state = key_type; + using point = point_type; + + static result_of sign( + key_state_input /*key_state*/, + element_in /*digest_bytes*/, + dynamic_input /*extra_entropy*/, + signature_out /*signature_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of verify( + object_in /*point_value*/, + element_in /*digest_bytes*/, + signature_in /*signature_bytes*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of + valid_compact(signature_in /*signature_bytes*/) noexcept( + nothrow) + requires present + { + return done>(); + } + + static result_of + is_low_s(signature_in /*signature_bytes*/) noexcept( + nothrow) + requires present + { + return done>(); + } + + static result_of low_s( + signature_in /*signature_bytes*/, + signature_out /*low_output*/, + shape_of /*was_high*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of to_der( + signature_in /*signature_bytes*/, + sized_output /*der_output*/, + shape_of /*der_size*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of from_der( + dynamic_input /*der_bytes*/, + signature_out /*signature_output*/) noexcept(nothrow) + requires present + { + return done>(); + } +}; + +template +struct ecdsa_satisfied { + using engine = ecdsa_stand_in; + static constexpr bool value = backend::secp256k1_ecdsa_signing && + backend::secp256k1_ecdsa_verifying && + backend::secp256k1_ecdsa_forms; +}; + +static_assert(backend_stand_in::rejects_every_defect); +static_assert( + backend_stand_in::rejects_every_shape< + ecdsa_satisfied, sign_key_shape, sign_digest_shape, sign_entropy_shape, sign_output_shape, + verify_point_shape, verify_digest_shape, verify_signature_shape, valid_compact_shape, + is_low_s_shape, low_s_input_shape, low_s_output_shape, was_high_shape, to_der_input_shape, + der_output_shape, der_size_shape, from_der_input_shape, from_der_output_shape>); + +// BIP340's Schnorr. + +inline constexpr int schnorr_sign_op = first_op; +inline constexpr int schnorr_verify_op = first_op + 1; +inline constexpr int schnorr_key_shape = first_op + 2; +inline constexpr int schnorr_message_shape = first_op + 3; +inline constexpr int schnorr_auxiliary_shape = first_op + 4; +inline constexpr int schnorr_output_shape = first_op + 5; +inline constexpr int schnorr_xonly_shape = first_op + 6; +inline constexpr int schnorr_verify_message_shape = first_op + 7; +inline constexpr int schnorr_signature_shape = first_op + 8; + +template +struct schnorr_stand_in { + using key_state = key_type; + using xonly_point = xonly_type; + + static result_of sign( + key_state_input /*key_state*/, + dynamic_input /*message_bytes*/, + element_in /*auxiliary_random*/, + signature_out /*signature_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of verify( + object_in /*xonly_value*/, + dynamic_input /*message_bytes*/, + signature_in< + Defect, + schnorr_signature_shape> /*signature_bytes*/) noexcept(nothrow) + requires present + { + return done>(); + } +}; + +template +struct schnorr_satisfied { + using engine = schnorr_stand_in; + static constexpr bool value = + backend::secp256k1_schnorr_signing && backend::secp256k1_schnorr_verifying; +}; + +static_assert( + backend_stand_in::rejects_every_defect); +static_assert(backend_stand_in::rejects_every_shape< + schnorr_satisfied, schnorr_key_shape, schnorr_message_shape, schnorr_auxiliary_shape, + schnorr_output_shape, schnorr_xonly_shape, schnorr_verify_message_shape, + schnorr_signature_shape>); + +// Recoverable ECDSA. + +inline constexpr int recoverable_sign_op = first_op; +inline constexpr int recover_op = first_op + 1; +inline constexpr int recoverable_key_shape = first_op + 2; +inline constexpr int recoverable_digest_shape = first_op + 3; +inline constexpr int recoverable_output_shape = first_op + 4; +inline constexpr int recover_signature_shape = first_op + 5; +inline constexpr int recover_digest_shape = first_op + 6; +inline constexpr int recover_point_shape = first_op + 7; + +template +struct recoverable_stand_in { + using key_state = key_type; + using point = point_type; + + static result_of sign( + key_state_input /*key_state*/, + element_in /*digest_bytes*/, + sized_output + /*signature_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of recover( + sized_input + /*signature_bytes*/, + element_in /*digest_bytes*/, + object_out /*point_output*/) noexcept(nothrow) + requires present + { + return done>(); + } +}; + +template +struct recoverable_satisfied { + static constexpr bool value = backend::secp256k1_recoverable>; +}; + +static_assert( + backend_stand_in::rejects_every_defect); +static_assert(backend_stand_in::rejects_every_shape< + recoverable_satisfied, recoverable_key_shape, recoverable_digest_shape, + recoverable_output_shape, recover_signature_shape, recover_digest_shape, + recover_point_shape>); + +// ECDH in its three forms. + +inline constexpr int shared_x_op = first_op; +inline constexpr int shared_hashed_op = first_op + 1; +inline constexpr int shared_point_op = first_op + 2; +inline constexpr int shared_x_key_shape = first_op + 3; +inline constexpr int shared_x_peer_shape = first_op + 4; +inline constexpr int shared_x_shape = first_op + 5; +inline constexpr int shared_hashed_key_shape = first_op + 6; +inline constexpr int shared_hashed_peer_shape = first_op + 7; +inline constexpr int shared_hashed_shape = first_op + 8; +inline constexpr int shared_point_key_shape = first_op + 9; +inline constexpr int shared_point_peer_shape = first_op + 10; +inline constexpr int shared_point_shape = first_op + 11; + +template +struct ecdh_stand_in { + using key_state = key_type; + using point = point_type; + + static result_of shared_x( + key_state_input /*key_state*/, + object_in /*peer_point*/, + element_out /*shared_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of shared_hashed( + key_state_input /*key_state*/, + object_in /*peer_point*/, + element_out /*shared_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of shared_point( + key_state_input /*key_state*/, + object_in /*peer_point*/, + sized_output + /*point_output*/) noexcept(nothrow) + requires present + { + return done>(); + } +}; + +template +struct ecdh_satisfied { + static constexpr bool value = backend::secp256k1_ecdh>; +}; + +static_assert(backend_stand_in::rejects_every_defect); +static_assert(backend_stand_in::rejects_every_shape< + ecdh_satisfied, shared_x_key_shape, shared_x_peer_shape, shared_x_shape, + shared_hashed_key_shape, shared_hashed_peer_shape, shared_hashed_shape, + shared_point_key_shape, shared_point_peer_shape, shared_point_shape>); + +// The tweaks and the sum of points. + +inline constexpr int secret_add_op = first_op; +inline constexpr int secret_mul_op = first_op + 1; +inline constexpr int secret_negate_op = first_op + 2; +inline constexpr int point_add_op = first_op + 3; +inline constexpr int point_mul_op = first_op + 4; +inline constexpr int point_negate_op = first_op + 5; +inline constexpr int xonly_add_op = first_op + 6; +inline constexpr int xonly_check_op = first_op + 7; +inline constexpr int key_xonly_add_op = first_op + 8; +inline constexpr int combine_op = first_op + 9; +inline constexpr int add_secret_shape = first_op + 10; +inline constexpr int add_tweak_shape = first_op + 11; +inline constexpr int add_output_shape = first_op + 12; +inline constexpr int mul_secret_shape = first_op + 13; +inline constexpr int mul_tweak_shape = first_op + 14; +inline constexpr int mul_output_shape = first_op + 15; +inline constexpr int negate_secret_shape = first_op + 16; +inline constexpr int negate_output_shape = first_op + 17; +inline constexpr int point_add_value_shape = first_op + 18; +inline constexpr int point_add_tweak_shape = first_op + 19; +inline constexpr int point_mul_value_shape = first_op + 20; +inline constexpr int point_mul_tweak_shape = first_op + 21; +inline constexpr int point_negate_value_shape = first_op + 22; +inline constexpr int xonly_add_value_shape = first_op + 23; +inline constexpr int xonly_add_tweak_shape = first_op + 24; +inline constexpr int xonly_add_output_shape = first_op + 25; +inline constexpr int xonly_add_parity_shape = first_op + 26; +inline constexpr int check_value_shape = first_op + 27; +inline constexpr int check_tweak_shape = first_op + 28; +inline constexpr int check_tweaked_shape = first_op + 29; +inline constexpr int check_parity_shape = first_op + 30; +inline constexpr int key_xonly_shape = first_op + 31; +inline constexpr int key_xonly_tweak_shape = first_op + 32; +inline constexpr int combine_pointers_shape = first_op + 33; +inline constexpr int combine_output_shape = first_op + 34; + +template +struct tweak_stand_in { + using key_state = key_type; + using point = point_type; + using xonly_point = xonly_type; + + static result_of secret_add( + element_in /*secret_bytes*/, + element_in /*tweak_bytes*/, + element_out /*secret_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of secret_mul( + element_in /*secret_bytes*/, + element_in /*tweak_bytes*/, + element_out /*secret_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of secret_negate( + element_in /*secret_bytes*/, + element_out /*secret_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of point_add( + object_out /*point_value*/, + element_in /*tweak_bytes*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of point_mul( + object_out /*point_value*/, + element_in /*tweak_bytes*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of + point_negate(object_out /*point_value*/) noexcept( + nothrow) + requires present + { + return done>(); + } + + static result_of xonly_add( + object_in /*xonly_value*/, + element_in /*tweak_bytes*/, + object_out /*xonly_output*/, + int_output /*parity_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of xonly_check( + object_in /*xonly_value*/, + element_in /*tweak_bytes*/, + object_in /*tweaked_value*/, + shape_of /*tweaked_parity*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of key_xonly_add( + object_out /*key_state*/, + element_in /*tweak_bytes*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of combine( + pointers_in /*point_pointers*/, + object_out /*point_output*/) noexcept(nothrow) + requires present + { + return done>(); + } +}; + +template +struct tweak_satisfied { + static constexpr bool value = backend::secp256k1_tweak>; +}; + +static_assert( + backend_stand_in::rejects_every_defect< + tweak_satisfied, secret_add_op, secret_mul_op, secret_negate_op, point_add_op, point_mul_op, + point_negate_op, xonly_add_op, xonly_check_op, key_xonly_add_op, combine_op>); +static_assert( + backend_stand_in::rejects_every_shape< + tweak_satisfied, add_secret_shape, add_tweak_shape, add_output_shape, mul_secret_shape, + mul_tweak_shape, mul_output_shape, negate_secret_shape, negate_output_shape, + point_add_value_shape, point_add_tweak_shape, point_mul_value_shape, point_mul_tweak_shape, + point_negate_value_shape, xonly_add_value_shape, xonly_add_tweak_shape, + xonly_add_output_shape, xonly_add_parity_shape, check_value_shape, check_tweak_shape, + check_tweaked_shape, check_parity_shape, key_xonly_shape, key_xonly_tweak_shape, + combine_pointers_shape, combine_output_shape>); + +// ElligatorSwift. + +inline constexpr int encode_op = first_op; +inline constexpr int decode_op = first_op + 1; +inline constexpr int create_op = first_op + 2; +inline constexpr int xdh_op = first_op + 3; +inline constexpr int encode_point_shape = first_op + 4; +inline constexpr int encode_randomness_shape = first_op + 5; +inline constexpr int encode_output_shape = first_op + 6; +inline constexpr int decode_input_shape = first_op + 7; +inline constexpr int decode_output_shape = first_op + 8; +inline constexpr int create_key_shape = first_op + 9; +inline constexpr int create_randomness_shape = first_op + 10; +inline constexpr int create_output_shape = first_op + 11; +inline constexpr int xdh_key_shape = first_op + 12; +inline constexpr int xdh_initiator_shape = first_op + 13; +inline constexpr int xdh_responder_shape = first_op + 14; +inline constexpr int xdh_side_shape = first_op + 15; +inline constexpr int xdh_output_shape = first_op + 16; + +/** An ElligatorSwift encoding, or a view of another size under shape `Target`'s defect. */ +template +using encoding_in = sized_input; +/** An ElligatorSwift encoding out, or a view of another size under shape `Target`'s defect. */ +template +using encoding_out = sized_output; + +template +struct ellswift_stand_in { + using key_state = key_type; + using point = point_type; + + static result_of encode( + object_in /*point_value*/, + element_in /*randomness_bytes*/, + encoding_out /*encoding_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of decode( + encoding_in /*encoding_bytes*/, + object_out /*point_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of create( + key_state_input /*key_state*/, + element_in /*randomness_bytes*/, + encoding_out /*encoding_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of xdh( + key_state_input /*key_state*/, + encoding_in /*initiator_encoding*/, + encoding_in /*responder_encoding*/, + shape_of /*responder_side*/, + element_out /*shared_output*/) noexcept(nothrow) + requires present + { + return done>(); + } +}; + +template +struct ellswift_satisfied { + static constexpr bool value = backend::secp256k1_ellswift>; +}; + +static_assert(backend_stand_in::rejects_every_defect); +static_assert(backend_stand_in::rejects_every_shape< + ellswift_satisfied, encode_point_shape, encode_randomness_shape, encode_output_shape, + decode_input_shape, decode_output_shape, create_key_shape, create_randomness_shape, + create_output_shape, xdh_key_shape, xdh_initiator_shape, xdh_responder_shape, + xdh_side_shape, xdh_output_shape>); + +// MuSig2. + +/** The MuSig2 stand-in's objects. */ +struct key_cache_type {}; + +struct public_nonce_type {}; + +struct aggregate_nonce_type {}; + +struct session_type {}; + +struct partial_signature_type {}; + +struct secret_nonce_type {}; + +inline constexpr int key_aggregate_op = first_op; +inline constexpr int aggregate_point_op = first_op + 1; +inline constexpr int musig_tweak_add_op = first_op + 2; +inline constexpr int musig_tweak_xonly_add_op = first_op + 3; +inline constexpr int nonce_generate_op = first_op + 4; +inline constexpr int nonce_aggregate_op = first_op + 5; +inline constexpr int nonce_process_op = first_op + 6; +inline constexpr int partial_sign_op = first_op + 7; +inline constexpr int partial_verify_op = first_op + 8; +inline constexpr int partial_aggregate_op = first_op + 9; +inline constexpr int parse_public_op = first_op + 10; +inline constexpr int serialize_public_op = first_op + 11; +inline constexpr int parse_aggregate_op = first_op + 12; +inline constexpr int serialize_aggregate_op = first_op + 13; +inline constexpr int parse_partial_op = first_op + 14; +inline constexpr int serialize_partial_op = first_op + 15; +inline constexpr int key_pointers_shape = first_op + 16; +inline constexpr int cache_output_shape = first_op + 17; +inline constexpr int aggregate_cache_shape = first_op + 18; +inline constexpr int aggregate_point_shape = first_op + 19; +inline constexpr int tweak_add_cache_shape = first_op + 20; +inline constexpr int tweak_add_shape = first_op + 21; +inline constexpr int tweak_xonly_cache_shape = first_op + 22; +inline constexpr int tweak_xonly_shape = first_op + 23; +inline constexpr int nonce_key_shape = first_op + 24; +inline constexpr int nonce_random_shape = first_op + 25; +inline constexpr int nonce_message_shape = first_op + 26; +inline constexpr int nonce_cache_shape = first_op + 27; +inline constexpr int nonce_extra_shape = first_op + 28; +inline constexpr int nonce_secret_shape = first_op + 29; +inline constexpr int nonce_public_shape = first_op + 30; +inline constexpr int nonce_pointers_shape = first_op + 31; +inline constexpr int nonce_aggregate_output_shape = first_op + 32; +inline constexpr int process_aggregate_shape = first_op + 33; +inline constexpr int process_message_shape = first_op + 34; +inline constexpr int process_cache_shape = first_op + 35; +inline constexpr int process_session_shape = first_op + 36; +inline constexpr int partial_sign_key_shape = first_op + 37; +inline constexpr int partial_sign_nonce_shape = first_op + 38; +inline constexpr int partial_sign_cache_shape = first_op + 39; +inline constexpr int partial_sign_session_shape = first_op + 40; +inline constexpr int partial_sign_output_shape = first_op + 41; +inline constexpr int partial_verify_partial_shape = first_op + 42; +inline constexpr int partial_verify_nonce_shape = first_op + 43; +inline constexpr int partial_verify_point_shape = first_op + 44; +inline constexpr int partial_verify_cache_shape = first_op + 45; +inline constexpr int partial_verify_session_shape = first_op + 46; +inline constexpr int partial_aggregate_session_shape = first_op + 47; +inline constexpr int partial_pointers_shape = first_op + 48; +inline constexpr int partial_aggregate_output_shape = first_op + 49; +inline constexpr int parse_public_input_shape = first_op + 50; +inline constexpr int parse_public_output_shape = first_op + 51; +inline constexpr int serialize_public_value_shape = first_op + 52; +inline constexpr int serialize_public_output_shape = first_op + 53; +inline constexpr int parse_aggregate_input_shape = first_op + 54; +inline constexpr int parse_aggregate_output_shape = first_op + 55; +inline constexpr int serialize_aggregate_value_shape = first_op + 56; +inline constexpr int serialize_aggregate_output_shape = first_op + 57; +inline constexpr int parse_partial_input_shape = first_op + 58; +inline constexpr int parse_partial_output_shape = first_op + 59; +inline constexpr int serialize_partial_value_shape = first_op + 60; +inline constexpr int serialize_partial_output_shape = first_op + 61; + +/** A MuSig2 nonce's bytes, or a view of another size under shape `Target`'s defect. */ +template +using nonce_in = sized_input; +/** A MuSig2 nonce's bytes out, or a view of another size under shape `Target`'s defect. */ +template +using nonce_out = sized_output; + +template +struct musig_stand_in { + using key_state = key_type; + using point = point_type; + using key_cache = key_cache_type; + using public_nonce = public_nonce_type; + using aggregate_nonce = aggregate_nonce_type; + using session = session_type; + using partial_signature = partial_signature_type; + using secret_nonce = secret_nonce_type; + + static result_of key_aggregate( + pointers_in /*point_pointers*/, + object_out /*cache_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of aggregate_point( + object_in /*cache_value*/, + object_out /*point_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of tweak_add( + object_out /*cache_value*/, + element_in /*tweak_bytes*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of tweak_xonly_add( + object_out /*cache_value*/, + element_in /*tweak_bytes*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of nonce_generate( + key_state_input /*key_state*/, + element_out /*session_random*/, + dynamic_input /*message_bytes*/, + object_in /*cache_value*/, + dynamic_input /*extra_input*/, + object_out /*secret_output*/, + object_out /*public_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of nonce_aggregate( + pointers_in /*nonce_pointers*/, + object_out + /*aggregate_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of nonce_process( + object_in /*aggregate_value*/, + element_in /*message_bytes*/, + object_in /*cache_value*/, + object_out /*session_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of partial_sign( + key_state_input /*key_state*/, + object_out /*secret_value*/, + object_in /*cache_value*/, + object_in /*session_value*/, + object_out + /*partial_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of partial_verify( + object_in /*partial_value*/, + object_in /*public_value*/, + object_in /*point_value*/, + object_in /*cache_value*/, + object_in /*session_value*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of partial_aggregate( + object_in /*session_value*/, + pointers_in /*partial_pointers*/, + signature_out< + Defect, + partial_aggregate_output_shape> /*signature_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of parse( + nonce_in /*nonce_bytes*/, + object_out /*public_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of serialize( + object_in /*public_value*/, + nonce_out< + Defect, + serialize_public_output_shape> /*nonce_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of parse( + nonce_in /*nonce_bytes*/, + object_out + /*aggregate_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of serialize( + object_in + /*aggregate_value*/, + nonce_out< + Defect, + serialize_aggregate_output_shape> /*nonce_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of parse( + element_in /*signature_bytes*/, + object_out + /*partial_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of serialize( + object_in + /*partial_value*/, + element_out< + Defect, + serialize_partial_output_shape> /*signature_output*/) noexcept(nothrow) + requires present + { + return done>(); + } +}; + +template +struct musig_satisfied { + static constexpr bool value = backend::secp256k1_musig>; +}; + +static_assert(backend_stand_in::rejects_every_defect< + musig_satisfied, key_aggregate_op, aggregate_point_op, musig_tweak_add_op, + musig_tweak_xonly_add_op, nonce_generate_op, nonce_aggregate_op, nonce_process_op, + partial_sign_op, partial_verify_op, partial_aggregate_op, parse_public_op, + serialize_public_op, parse_aggregate_op, serialize_aggregate_op, parse_partial_op, + serialize_partial_op>); +static_assert( + backend_stand_in::rejects_every_shape< + musig_satisfied, key_pointers_shape, cache_output_shape, aggregate_cache_shape, + aggregate_point_shape, tweak_add_cache_shape, tweak_add_shape, tweak_xonly_cache_shape, + tweak_xonly_shape, nonce_key_shape, nonce_random_shape, nonce_message_shape, + nonce_cache_shape, nonce_extra_shape, nonce_secret_shape, nonce_public_shape, + nonce_pointers_shape, nonce_aggregate_output_shape, process_aggregate_shape, + process_message_shape, process_cache_shape, process_session_shape, partial_sign_key_shape, + partial_sign_nonce_shape, partial_sign_cache_shape, partial_sign_session_shape, + partial_sign_output_shape, partial_verify_partial_shape, partial_verify_nonce_shape, + partial_verify_point_shape, partial_verify_cache_shape, partial_verify_session_shape, + partial_aggregate_session_shape, partial_pointers_shape, partial_aggregate_output_shape, + parse_public_input_shape, parse_public_output_shape, serialize_public_value_shape, + serialize_public_output_shape, parse_aggregate_input_shape, parse_aggregate_output_shape, + serialize_aggregate_value_shape, serialize_aggregate_output_shape, + parse_partial_input_shape, parse_partial_output_shape, serialize_partial_value_shape, + serialize_partial_output_shape>); + +// Silent payments. + +/** The silent payments stand-in's objects. */ +struct recipient_type {}; + +struct summary_type {}; + +struct found_output_type {}; + +struct label_lookup_type {}; + +using key_handle_type = int const*; + +inline constexpr int key_handle_of_op = first_op; +inline constexpr int make_recipient_op = first_op + 1; +inline constexpr int create_outputs_op = first_op + 2; +inline constexpr int over_group_limit_op = first_op + 3; +inline constexpr int create_label_op = first_op + 4; +inline constexpr int labeled_spend_key_op = first_op + 5; +inline constexpr int make_summary_op = first_op + 6; +inline constexpr int scan_op = first_op + 7; +inline constexpr int found_output_key_op = first_op + 8; +inline constexpr int found_tweak_op = first_op + 9; +inline constexpr int found_label_op = first_op + 10; +inline constexpr int handle_key_shape = first_op + 11; +inline constexpr int recipient_scan_shape = first_op + 12; +inline constexpr int recipient_spend_shape = first_op + 13; +inline constexpr int recipient_index_shape = first_op + 14; +inline constexpr int recipient_output_shape = first_op + 15; +inline constexpr int outputs_key_shape = first_op + 16; +inline constexpr int outputs_shape = first_op + 17; +inline constexpr int recipients_shape = first_op + 18; +inline constexpr int outpoint_shape = first_op + 19; +inline constexpr int handles_shape = first_op + 20; +inline constexpr int secrets_shape = first_op + 21; +inline constexpr int limit_recipients_shape = first_op + 22; +inline constexpr int label_key_shape = first_op + 23; +inline constexpr int label_number_shape = first_op + 24; +inline constexpr int label_output_shape = first_op + 25; +inline constexpr int label_tweak_shape = first_op + 26; +inline constexpr int labeled_spend_shape = first_op + 27; +inline constexpr int label_input_shape = first_op + 28; +inline constexpr int labeled_output_shape = first_op + 29; +inline constexpr int summary_outpoint_shape = first_op + 30; +inline constexpr int summary_xonly_shape = first_op + 31; +inline constexpr int summary_points_shape = first_op + 32; +inline constexpr int summary_output_shape = first_op + 33; +inline constexpr int scan_key_shape = first_op + 34; +inline constexpr int scan_summary_shape = first_op + 35; +inline constexpr int scan_spend_shape = first_op + 36; +inline constexpr int scan_outputs_shape = first_op + 37; +inline constexpr int found_pointers_shape = first_op + 38; +inline constexpr int found_count_shape = first_op + 39; +inline constexpr int lookup_shape = first_op + 40; +inline constexpr int found_key_value_shape = first_op + 41; +inline constexpr int found_key_shape = first_op + 42; +inline constexpr int found_tweak_value_shape = first_op + 43; +inline constexpr int found_label_value_shape = first_op + 44; +inline constexpr int found_label_shape = first_op + 45; + +/** A compressed point's bytes out, or a view of another size under shape `Target`'s defect. */ +template +using compressed_out = sized_output; + +template +struct silent_payments_stand_in { + using key_state = key_type; + using point = point_type; + using xonly_point = xonly_type; + using recipient = recipient_type; + using summary = summary_type; + using found_output = found_output_type; + using key_handle = key_handle_type; + using label_lookup = label_lookup_type; + + static result_of + key_handle_of(key_state_input /*key_state*/) noexcept( + nothrow) + requires present + { + return done>(); + } + + static result_of make_recipient( + object_in /*scan_point*/, + object_in /*spend_point*/, + shape_of /*recipient_index*/, + object_out /*recipient_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of create_outputs( + key_state_input /*first_input*/, + shape_of, std::span> + /*output_pointers*/, + shape_of, + std::span> /*recipient_pointers*/, + sized_input /*outpoint_bytes*/, + shape_of, + std::span> /*taproot_handles*/, + shape_of< + Defect, secrets_shape, std::span, + std::span< + other_type const* const>> /*plain_secrets*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of over_group_limit( + shape_of< + Defect, limit_recipients_shape, std::span, + std::span< + other_type const*>> /*recipient_pointers*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of create_label( + key_state_input /*key_state*/, + shape_of /*label_number*/, + compressed_out /*label_output*/, + element_out /*tweak_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of labeled_spend_key( + object_in /*spend_point*/, + sized_input + /*label_bytes*/, + object_out /*point_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of make_summary( + sized_input + /*outpoint_bytes*/, + pointers_in /*xonly_pointers*/, + pointers_in /*point_pointers*/, + object_out /*summary_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of scan( + key_state_input /*key_state*/, + object_in /*summary_value*/, + object_in /*spend_point*/, + pointers_in /*output_pointers*/, + shape_of, + std::span> /*found_pointers*/, + shape_of /*found_count*/, + shape_of + /*lookup_context*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of found_output_key( + object_in /*found_value*/, + element_out /*key_output*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of> + found_tweak( + object_in /*found_value*/) noexcept(nothrow) + requires present + { + return done>>(); + } + + static result_of found_label( + object_in /*found_value*/, + compressed_out< + Defect, found_label_shape> /*label_output*/) noexcept(nothrow) + requires present + { + return done>(); + } +}; + +template +struct silent_payments_satisfied { + static constexpr bool value = + backend::secp256k1_silent_payments>; +}; + +static_assert(backend_stand_in::rejects_every_defect< + silent_payments_satisfied, key_handle_of_op, make_recipient_op, create_outputs_op, + over_group_limit_op, create_label_op, labeled_spend_key_op, make_summary_op, scan_op, + found_output_key_op, found_tweak_op, found_label_op>); +static_assert( + backend_stand_in::rejects_every_shape< + silent_payments_satisfied, handle_key_shape, recipient_scan_shape, recipient_spend_shape, + recipient_index_shape, recipient_output_shape, outputs_key_shape, outputs_shape, + recipients_shape, outpoint_shape, handles_shape, secrets_shape, limit_recipients_shape, + label_key_shape, label_number_shape, label_output_shape, label_tweak_shape, + labeled_spend_shape, label_input_shape, labeled_output_shape, summary_outpoint_shape, + summary_xonly_shape, summary_points_shape, summary_output_shape, scan_key_shape, + scan_summary_shape, scan_spend_shape, scan_outputs_shape, found_pointers_shape, + found_count_shape, lookup_shape, found_key_value_shape, found_key_shape, + found_tweak_value_shape, found_label_value_shape, found_label_shape>); + +#ifdef WEBCPP_CRYPTO_HAS_SECP256K1 +// The engines' own guards, which the public functions never reach (review 2.2 M2): their +// refusals run here on libsecp256k1's engines directly. + +using ecdsa_engine = shipped; +using recoverable_engine = shipped; + +/** A key pair of the secret key 1. */ +webcpp::crypto::curves::secp256k1::keypair key_of_one() { + std::array secret_bytes{}; + secret_bytes.back() = 1; + return webcpp::crypto::curves::secp256k1::keypair::from_secret(secret_bytes).value(); +} + +void extra_entropy_sizes() { + auto const key_pair = key_of_one(); + auto const& key_state = webcpp::crypto::detail::secp256k1_access::key_state(key_pair); + std::array const digest_bytes{1, 2, 3}; + std::array signature_bytes{}; + std::array const entropy_bytes{7}; + BOOST_TEST(ecdsa_engine::sign(key_state, digest_bytes, {}, signature_bytes).has_value()); + BOOST_TEST( + ecdsa_engine::sign(key_state, digest_bytes, entropy_bytes, signature_bytes).has_value()); + // libsecp256k1 reads 32 bytes of extra entropy: another size is refused before it. + for (std::size_t const size : {std::size_t{1}, std::size_t{31}}) { + BOOST_TEST(ecdsa_engine::sign(key_state, digest_bytes, + std::span(entropy_bytes).first(size), + signature_bytes) + .error() == webcpp::crypto::error::backend_failure); + } + std::array const too_long{}; + BOOST_TEST(ecdsa_engine::sign(key_state, digest_bytes, too_long, signature_bytes).error() == + webcpp::crypto::error::backend_failure); +} + +void recovery_id_guard() { + auto const key_pair = key_of_one(); + auto const& key_state = webcpp::crypto::detail::secp256k1_access::key_state(key_pair); + std::array const digest_bytes{4, 5, 6}; + std::array signature_bytes{}; + BOOST_TEST(recoverable_engine::sign(key_state, digest_bytes, signature_bytes).has_value()); + webcpp::crypto::detail::secp256k1_point recovered{}; + BOOST_TEST(recoverable_engine::recover(signature_bytes, digest_bytes, recovered)); + // An id above 3 is refused by the engine itself, before libsecp256k1. + for (std::uint8_t const recovery_id : {std::uint8_t{4}, std::uint8_t{27}, std::uint8_t{255}}) { + signature_bytes.back() = recovery_id; + BOOST_TEST(!recoverable_engine::recover(signature_bytes, digest_bytes, recovered)); + } +} + +void der_refusals() { + std::array signature_bytes{}; + std::array der_bytes{}; + std::size_t der_size = 0; + // r and s zero: no valid signature, nothing written. + BOOST_TEST(!ecdsa_engine::to_der(signature_bytes, der_bytes, der_size)); + BOOST_TEST_EQ(der_size, 0U); + std::array const not_der{0x30, 0x01, 0x00}; + BOOST_TEST(!ecdsa_engine::from_der(not_der, signature_bytes)); + BOOST_TEST(!ecdsa_engine::from_der({}, signature_bytes)); +} +#endif + +} // namespace + +int main() { +#ifdef WEBCPP_CRYPTO_HAS_SECP256K1 + extra_entropy_sizes(); + recovery_id_guard(); + der_refusals(); +#endif + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/backend_concepts_symmetric_test.cpp b/test/backend_concepts_symmetric_test.cpp new file mode 100644 index 0000000..fdea099 --- /dev/null +++ b/test/backend_concepts_symmetric_test.cpp @@ -0,0 +1,406 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the 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 symmetric capability concepts of detail::backend (backend-concepts design D1, D2, D4): +// every engine the table lists for the AES block cipher, GCM, the AEADs, the secret boxes, the raw +// stream cipher and the single-use key authenticator satisfies its concept on every backend this +// target links; and for each concept a stand-in engine (support/backend_stand_in.hpp) satisfies +// it when complete and fails it with any one operation missing, not noexcept or of another result, +// or any one size or type parameter of another shape, so that each requirement is shown to be +// checked. + +#include "support/backend_stand_in.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef WEBCPP_CRYPTO_HAS_BEARSSL +#include +#endif +#ifdef WEBCPP_CRYPTO_HAS_CTAES +#include +#endif +#ifdef WEBCPP_CRYPTO_HAS_OPENSSL +#include +#endif +#ifdef WEBCPP_CRYPTO_HAS_SODIUM +#include +#endif + +#include + +#include +#include +#include + +namespace backend = webcpp::crypto::detail::backend; +namespace detail = webcpp::crypto::detail; +namespace families = webcpp::crypto::families; +namespace backends = webcpp::crypto::backends; + +namespace { + +// The shipped engines, on the backends this target links (the table's cells, crypto.json). + +template +inline constexpr bool all_gcm = (backend::gcm> && ...); + +template +inline constexpr bool all_block = + (backend::block_cipher> && ...); + +#ifdef WEBCPP_CRYPTO_HAS_BEARSSL +static_assert(all_gcm); +static_assert(backend::aead, + families::chacha20_poly1305>); +static_assert(backend::stream_cipher, + families::chacha20>); +#endif + +#ifdef WEBCPP_CRYPTO_HAS_CTAES +static_assert(all_block); +#endif + +#ifdef WEBCPP_CRYPTO_HAS_BEARSSL +// BearSSL's block_engine is a refusal of its own (it exports AES only inside its modes), whose +// templated members, with their explicit return types, meet block_cipher's requirements without +// instantiating the refusal (ruling 1.1-M10): it carries no specialisation marker, so the table's +// two-way check never counts it as a capability (design D5, R7). +static_assert(!detail::specialized_engine_v>); +static_assert(!detail::specialized_engine_v>); +static_assert(!detail::specialized_engine_v>); +static_assert(detail::specialized_engine_v>); +#endif + +#ifdef WEBCPP_CRYPTO_HAS_OPENSSL +static_assert(all_gcm); +static_assert(all_block); +static_assert(backend::aead, + families::chacha20_poly1305>); +static_assert(backend::stream_cipher, + families::chacha20>); +static_assert( + backend::authenticator, + families::poly1305>); +#endif + +#ifdef WEBCPP_CRYPTO_HAS_SODIUM +template +using sodium_aead = detail::aead_engine; +static_assert(backend::aead, families::chacha20_poly1305>); +static_assert(backend::aead, + families::chacha20_poly1305_original>); +static_assert( + backend::aead, families::xchacha20_poly1305>); +static_assert(backend::stream_cipher, + families::chacha20>); +static_assert( + backend::authenticator, + families::poly1305>); +static_assert(backend::authenticated_box< + detail::secretbox_engine, + families::secretbox_xsalsa20poly1305>); +static_assert(backend::authenticated_box< + detail::secretbox_engine, + families::secretbox_xchacha20poly1305>); +#endif + +// Stand-ins, their sizes and types the families' own. + +using backend_stand_in::bytes; +using backend_stand_in::const_bytes; +using backend_stand_in::defect; +using backend_stand_in::done; +using backend_stand_in::first_op; +using backend_stand_in::init_op; +using backend_stand_in::keyed_operations; +using backend_stand_in::move_op; +using backend_stand_in::nothrow; +using backend_stand_in::present; +using backend_stand_in::reset_op; +using backend_stand_in::result_of; +using backend_stand_in::result_void; +using backend_stand_in::shape_of; +using backend_stand_in::sized_input; +using backend_stand_in::sized_output; +using backend_stand_in::state_type; + +/** A tag output of `Size` bytes, or of one byte less under shape `Target`'s defect. */ +template +using tag_output = + shape_of&, boost::hash2::digest&>; + +/** An expected tag of `Size` bytes, or of one byte less under shape `Target`'s defect. */ +template +using expected_tag = shape_of const&, + std::array const&>; + +// block_cipher: encrypt and decrypt, over keyed state operations. + +inline constexpr int encrypt_op = first_op; +inline constexpr int decrypt_op = first_op + 1; + +template +struct block_stand_in : keyed_operations { + static result_of encrypt( + state_type& /*engine_state*/, bytes /*block_bytes*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of decrypt( + state_type& /*engine_state*/, bytes /*block_bytes*/) noexcept(nothrow) + requires present + { + return done>(); + } +}; + +template +struct block_satisfied { + static constexpr bool value = backend::block_cipher>; +}; + +static_assert(backend_stand_in::rejects_every_defect); + +// gcm: start, run, tag, check and abandon; the tag's two sizes. + +inline constexpr int start_op = first_op; +inline constexpr int run_op = first_op + 1; +inline constexpr int tag_op = first_op + 2; +inline constexpr int check_op = first_op + 3; +inline constexpr int abandon_op = first_op + 4; +inline constexpr int gcm_tag_shape = first_op + 5; +inline constexpr int gcm_check_shape = first_op + 6; +inline constexpr std::size_t gcm_tag_size = 16; + +template +struct gcm_stand_in : keyed_operations { + static result_of start( + state_type& /*engine_state*/, bool /*is_sealing*/, const_bytes /*nonce_bytes*/, + const_bytes /*associated_data_bytes*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of run( + state_type& /*engine_state*/, bytes /*data_bytes*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of tag( + state_type& /*engine_state*/, + tag_output /*tag_bytes*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of check( + state_type& /*engine_state*/, + expected_tag /*tag_bytes*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of abandon(state_type& /*engine_state*/) noexcept( + nothrow) + requires present + { + return done>(); + } +}; + +template +struct gcm_satisfied { + static constexpr bool value = backend::gcm>; +}; + +static_assert( + backend_stand_in::rejects_every_defect); +static_assert(backend_stand_in::rejects_every_shape); + +// aead: seal and open, the family's tag size. + +using aead_family = families::chacha20_poly1305; +inline constexpr int seal_op = first_op; +inline constexpr int open_op = first_op + 1; +inline constexpr int aead_tag_shape = first_op + 2; +inline constexpr int aead_check_shape = first_op + 3; + +template +struct aead_stand_in : keyed_operations { + static result_of seal( + state_type& /*engine_state*/, const_bytes /*nonce_bytes*/, + const_bytes /*associated_data_bytes*/, bytes /*data_bytes*/, + tag_output /*tag_bytes*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of open( + state_type& /*engine_state*/, const_bytes /*nonce_bytes*/, + const_bytes /*associated_data_bytes*/, bytes /*data_bytes*/, + expected_tag /*tag_bytes*/) noexcept(nothrow) + requires present + { + return done>(); + } +}; + +template +struct aead_satisfied { + static constexpr bool value = backend::aead, aead_family>; +}; + +static_assert(backend_stand_in::rejects_every_defect); +static_assert( + backend_stand_in::rejects_every_shape); + +// authenticated_box: seal and open without associated data, the family's nonce and tag sizes. + +using secretbox_family = families::secretbox_xsalsa20poly1305; +inline constexpr int secretbox_seal_nonce_shape = first_op + 2; +inline constexpr int secretbox_open_nonce_shape = first_op + 3; +inline constexpr int secretbox_tag_shape = first_op + 4; +inline constexpr int secretbox_check_shape = first_op + 5; + +template +struct secretbox_stand_in : keyed_operations { + static result_of seal( + state_type& /*engine_state*/, + sized_input + /*nonce_bytes*/, + bytes /*data_bytes*/, + tag_output /*tag_bytes*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of open( + state_type& /*engine_state*/, + sized_input + /*nonce_bytes*/, + bytes /*data_bytes*/, + expected_tag + /*tag_bytes*/) noexcept(nothrow) + requires present + { + return done>(); + } +}; + +template +struct secretbox_satisfied { + static constexpr bool value = + backend::authenticated_box, secretbox_family>; +}; + +static_assert(backend_stand_in::rejects_every_defect); +static_assert(backend_stand_in::rejects_every_shape); + +// stream_cipher: apply, the family's nonce size and counter type. The counter is taken by value, +// so any integer type converts, wider or narrower; the wrong shape is a counter the family's type +// cannot become, and the width is the family's, pinned by the public type. + +using stream_family = families::chacha20; +inline constexpr int apply_op = first_op; +inline constexpr int stream_nonce_shape = first_op + 1; +inline constexpr int stream_counter_shape = first_op + 2; + +/** A counter the family's `counter_type` does not convert to. */ +struct unrelated_counter {}; + +template +struct stream_stand_in : keyed_operations { + static result_of apply( + state_type& /*engine_state*/, + sized_input /*nonce_bytes*/, + shape_of + /*initial_counter*/, + bytes /*data_bytes*/) noexcept(nothrow) + requires present + { + return done>(); + } +}; + +template +struct stream_satisfied { + static constexpr bool value = backend::stream_cipher, stream_family>; +}; + +static_assert( + backend_stand_in::rejects_every_defect); +static_assert(backend_stand_in::rejects_every_shape); + +// authenticator: one static authenticate, no state; the family's key and tag sizes. + +using authenticator_family = families::poly1305; +inline constexpr int authenticate_op = 0; +inline constexpr int authenticator_key_shape = 1; +inline constexpr int authenticator_tag_shape = 2; + +template +struct authenticator_stand_in { + static result_of authenticate( + sized_input + /*key_bytes*/, + const_bytes /*message_bytes*/, + sized_output + /*tag_bytes*/) noexcept(nothrow) + requires present + { + return done>(); + } +}; + +template +struct authenticator_satisfied { + static constexpr bool value = + backend::authenticator, authenticator_family>; +}; + +static_assert(backend_stand_in::rejects_every_defect); +static_assert(backend_stand_in::rejects_every_shape< + authenticator_satisfied, authenticator_key_shape, authenticator_tag_shape>); + +// The concepts do not overlap: a stream cipher is no AEAD, an AEAD no stream cipher, and a secret +// box (no associated data) no AEAD. +static_assert(!backend::aead, aead_family>); +static_assert(!backend::stream_cipher, stream_family>); +static_assert(!backend::aead, aead_family>); + +} // namespace + +int main() { + return 0; +} diff --git a/test/backends/message_only.hpp b/test/backends/message_only.hpp new file mode 100644 index 0000000..1fa9988 --- /dev/null +++ b/test/backends/message_only.hpp @@ -0,0 +1,179 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the 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 test-only P-256 backend for the message tests of the capability assertions (backend-concepts +// design D5, D9): its engine, marked as its header's own (`specialized_engine_v`), as a shipped +// backend's is, signs and verifies a message, never a digest (`p256_ecdsa_message_signing`, +// `p256_ecdsa_message_verifying`, the form WebCrypto's ECDSA has), draws its keys and gives their +// public point, and checks a point without decompressing one (`valid_point` and no `decompress`, +// so not `p256_point`). Its operations are stand-ins with known answers, which +// p256_message_form_test runs: a key is a handle, its point fixed bytes, and a signature of a +// message carries the message's size in r and a high S, which crypto makes low; the message tests +// compile against it, and stop. + +#ifndef WEBCPP_TEST_CRYPTO_BACKENDS_MESSAGE_ONLY_HPP +#define WEBCPP_TEST_CRYPTO_BACKENDS_MESSAGE_ONLY_HPP + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include + +namespace webcpp::test::message_only_backend { + +/** The backend's tag. */ +struct message_only {}; + +/** Its state: a handle, as an opaque key's. */ +struct handle_state { + /** The key's index in the backend. */ + std::size_t handle = 0; +}; + +} // namespace webcpp::test::message_only_backend + +namespace webcpp::crypto::detail { + +/** P-256's state on the message-only backend: a handle. */ +template <> +struct p_curve_state + : test::message_only_backend::handle_state {}; + +} // namespace webcpp::crypto::detail + +namespace webcpp::test::message_only_backend { + +/** The order n of P-256 less one: a high S, which crypto's low-S form replaces with 1. */ +inline constexpr std::array order_less_one{ + 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xbc, 0xe6, 0xfa, 0xad, 0xa7, 0x17, 0x9e, 0x84, 0xf3, 0xb9, 0xca, 0xc2, 0xfc, 0x63, 0x25, 0x50, +}; + +/** The byte every coordinate of a key's point holds. */ +inline constexpr std::uint8_t point_byte = 0x11; + +/** The number of `verify_message` calls the engine has had, which a test resets and reads. */ +[[nodiscard]] inline std::size_t& verify_message_calls() noexcept { + static std::size_t calls = 0; + return calls; +} + +/** Its engine: the message form of ECDSA, generation, the public point, a point's check. */ +struct p256_engine { + /** The state. */ + using state = crypto::detail::p_curve_state; + + /** Draws a key: the handle 1. */ + [[nodiscard]] static boost::system::result generate(state& key_state) noexcept { + key_state.handle = 1; + return {}; + } + + /** The public point: the uncompressed prefix, then `point_byte` throughout. */ + [[nodiscard]] static boost::system::result public_key( + state const& /*key_state*/, std::span point_output) noexcept { + point_output[0] = 0x04; + std::ranges::fill(point_output.subspan(1), point_byte); + return {}; + } + + /** + * Signs a message, which it would hash: r the message's size, at most 255, and S the high + * `order_less_one`. + */ + [[nodiscard]] static boost::system::result sign_message( + state const& key_state, std::span message_bytes, + std::span signature_output) noexcept { + if (key_state.handle == 0 || message_bytes.size() > 255) { + return crypto::error::backend_failure; + } + std::ranges::fill(signature_output.first<32>(), std::uint8_t{0}); + signature_output[31] = static_cast(message_bytes.size()); + std::ranges::copy(order_less_one, signature_output.last<32>().begin()); + return {}; + } + + /** + * Verifies a signature of a message, which it would hash: valid when r is the message's size + * and S is 1, `sign_message`'s signature made low S; `invalid_signature` otherwise. Counts the + * call in `verify_message_calls`. + */ + [[nodiscard]] static boost::system::result verify_message( + std::span /*point_bytes*/, + std::span message_bytes, + std::span signature_bytes) noexcept { + ++verify_message_calls(); + std::array expected{}; + expected[31] = static_cast(message_bytes.size()); + expected[63] = 1; + if (message_bytes.size() > 255 || !std::ranges::equal(signature_bytes, expected)) { + return crypto::error::invalid_signature; + } + return {}; + } + + /** Whether a point is on the curve. */ + [[nodiscard]] static bool valid_point( + std::span /*point_bytes*/) noexcept { + return false; + } + + /** Moves a state, leaving the source as `reset` leaves it. */ + static void move(state& target_state, state& source_state) noexcept { + target_state.handle = source_state.handle; + source_state.handle = 0; + } + + /** Releases a state. */ + static void reset(state& key_state) noexcept { key_state.handle = 0; } +}; + +} // namespace webcpp::test::message_only_backend + +namespace webcpp::crypto::detail { + +/** P-256's engine on the message-only backend. */ +template <> +struct p_curve_engine + : test::message_only_backend::p256_engine {}; + +/** The engine is this header's own, as a shipped backend's is (design D9). */ +template <> +inline constexpr bool + specialized_engine_v> = + true; + +} // namespace webcpp::crypto::detail + +// The split the message tests rely on. +static_assert( + webcpp::crypto::detail::backend::p256_ecdsa_message_signing< + webcpp::crypto::detail::p_curve_engine>); +static_assert( + !webcpp::crypto::detail::backend::p256_ecdsa_signing>); +static_assert( + webcpp::crypto::detail::backend::p256_ecdsa_message_verifying< + webcpp::crypto::detail::p_curve_engine>); +static_assert( + !webcpp::crypto::detail::backend::p256_ecdsa_verifying>); +static_assert( + !webcpp::crypto::detail::backend::p256_point>); + +#endif // WEBCPP_TEST_CRYPTO_BACKENDS_MESSAGE_ONLY_HPP diff --git a/test/backends/opaque.hpp b/test/backends/opaque.hpp new file mode 100644 index 0000000..00f2515 --- /dev/null +++ b/test/backends/opaque.hpp @@ -0,0 +1,498 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the 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-only opaque backend (backend-concepts design D3, R6, R9): P-256 and X25519 whose keys +// never leave it, so that the opaque shape is proven before part B's browser backend exists. +// +// - A key pair's state is a handle into a table of keys the backend owns; every use reads the key +// through the engine, by its handle. The keys are real: the table holds BearSSL's P-256 states +// and libsodium's X25519 states, so that a signature verifies, and an agreement agrees, against +// the shipped backends. +// - Its engines implement `*_generate` (the backend draws the key), `*_public` and the uses, never +// `*_import` nor `*_export`: `from_secret` and `secret()` are not available on it. P-256's +// synchronous engine signs and verifies a digest (`p256_ecdsa_signing`, `p256_ecdsa_verifying`), +// never a message: the message form is the asynchronous engine's, which hashes it. +// - `opaque` is synchronous; `opaque_async` completes by itself (`asynchronous_backend_v`), its +// `async_engine` running the same engines and posting each completion through `asio::post`, so +// that the `async_*` concepts are tested on an engine of this change. +// - It is a test tool, not a shipped backend: outside `crypto.json`, `supports_v` and the two-way +// check of the table against the concepts (R6). Not thread-safe: one test drives it. + +#ifndef WEBCPP_TEST_CRYPTO_BACKENDS_OPAQUE_HPP +#define WEBCPP_TEST_CRYPTO_BACKENDS_OPAQUE_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include + +namespace webcpp::test::opaque_backend { + +/** The synchronous opaque backend. */ +struct opaque {}; + +/** The opaque backend that completes by itself. */ +struct opaque_async {}; + +/** A key pair's state on the opaque backend: a handle into its table, 0 for none. */ +struct handle_state { + /** The slot's index plus one; 0 when the state holds no key. */ + std::uint32_t handle = 0; +}; + +/** How many keys of each curve the table holds at once. */ +inline constexpr std::size_t table_capacity = 8; + +template +struct p256_engine; + +template +struct x25519_engine; + +/** + * The keys of one curve the backend owns, each a shipped backend's state, and what the tests read + * of it: how many keys it holds and how many it drew. + * + * @tparam KeyEngine The shipped engine whose states the table holds. + */ +template +class key_table { +public: + /** The shipped engine's state. */ + using state = KeyEngine::state; + + /** + * Takes a free slot. + * + * @return Its handle, or 0 when the table is full. + */ + [[nodiscard]] std::uint32_t acquire() noexcept { + for (std::size_t slot_index = 0; slot_index < table_capacity; ++slot_index) { + if (!used_[slot_index]) { + used_[slot_index] = true; + ++held_; + ++drawn_; + return static_cast(slot_index + 1); + } + } + return 0; + } + + /** + * Wipes and frees a handle's slot; nothing for the handle 0. + * + * @param key_handle A handle `acquire` gave, or 0. + */ + void release(std::uint32_t key_handle) noexcept { + if (key_handle == 0) { + return; + } + KeyEngine::reset(states_[key_handle - 1]); + used_[key_handle - 1] = false; + --held_; + } + + /** How many keys the table holds now. */ + [[nodiscard]] std::size_t held() const noexcept { return held_; } + + /** How many keys the table has drawn since the program started. */ + [[nodiscard]] std::size_t drawn() const noexcept { return drawn_; } + +private: + // The engines alone read a key, by its handle: a test reads what the table counts, never a + // key's secret state. + template + friend struct p256_engine; + template + friend struct x25519_engine; + + /** + * The key of a handle. + * + * @param key_handle A handle `acquire` gave. + * @return Its shipped state. + */ + [[nodiscard]] state& at(std::uint32_t key_handle) noexcept { return states_[key_handle - 1]; } + + std::array states_{}; + std::array used_{}; + std::size_t held_ = 0; + std::size_t drawn_ = 0; +}; + +/** BearSSL's P-256 engine, whose states hold the backend's P-256 keys. */ +using p256_key_engine = + crypto::detail::p_curve_engine; +/** libsodium's X25519 engine, whose states hold the backend's X25519 keys. */ +using x25519_key_engine = + crypto::detail::x25519_engine; + +/** The backend's P-256 keys, shared by both forms. */ +inline key_table& p256_table() noexcept { + static key_table keys; + return keys; +} + +/** The backend's X25519 keys, shared by both forms. */ +inline key_table& x25519_table() noexcept { + static key_table keys; + return keys; +} + +/** + * P-256 on the opaque backend: `p256_generate`, `p256_public`, the digest forms of signing and + * verifying, ECDH, the point's and DER's operations; no import, no export. + * + * @tparam Backend `opaque` or `opaque_async`. + */ +template +struct p256_engine { + /** The key pair's state, a handle. */ + using state = crypto::detail::p_curve_state; + + /** + * Draws a key in the backend: a scalar from the system's generator, below the group order, + * kept in a slot of the table and never given out. + * + * @param engine_state The key pair's state, which holds no key. + * @return Nothing; `entropy_unavailable`; `backend_failure` when the table is full. + */ + [[nodiscard]] static boost::system::result generate(state& engine_state) noexcept { + secure::secret<32> scalar_bytes; + crypto::random_device random_source; // lint-world: the backend's own key + do { + if (!random_source.fill(scalar_bytes.writable())) { + return crypto::error::entropy_unavailable; + } + } while (!crypto::detail::p_curve_scalar_valid( + scalar_bytes.bytes(), crypto::detail::p_curve_traits::order)); + auto const key_handle = p256_table().acquire(); + if (key_handle == 0) { + return crypto::error::backend_failure; + } + auto const imported = + p256_key_engine::import_secret(p256_table().at(key_handle), scalar_bytes.bytes()); + if (!imported) { + p256_table().release(key_handle); + return imported.error(); + } + engine_state.handle = key_handle; + return {}; + } + + /** The key's public point, uncompressed. */ + [[nodiscard]] static boost::system::result public_key( + state const& engine_state, std::span point_output) noexcept { + return p256_key_engine::public_key(p256_table().at(engine_state.handle), point_output); + } + + /** ECDSA over a digest with the key, by its handle. */ + [[nodiscard]] static boost::system::result sign( + state const& engine_state, std::span digest_bytes, + std::span signature_output) noexcept { + return p256_key_engine::sign(p256_table().at(engine_state.handle), digest_bytes, + signature_output); + } + + /** ECDH's shared x with the key, by its handle. */ + [[nodiscard]] static boost::system::result ecdh_x( + state const& engine_state, std::span peer_point, + std::span shared_output) noexcept { + return p256_key_engine::ecdh_x(p256_table().at(engine_state.handle), peer_point, + shared_output); + } + + /** On public data: whether a point is on the curve. */ + [[nodiscard]] static bool valid_point(std::span point_bytes) noexcept { + return p256_key_engine::valid_point(point_bytes); + } + + /** On public data: a compressed point's y. */ + [[nodiscard]] static bool decompress(std::uint8_t parity_prefix, + std::span x_bytes, + std::span y_output) noexcept { + return p256_key_engine::decompress(parity_prefix, x_bytes, y_output); + } + + /** On public data: ECDSA's verification of a digest. */ + [[nodiscard]] static bool verify(std::span point_bytes, + std::span digest_bytes, + std::span signature_bytes) noexcept { + return p256_key_engine::verify(point_bytes, digest_bytes, signature_bytes); + } + + /** On public data: a signature's DER. */ + [[nodiscard]] static std::size_t to_der(std::span signature_bytes, + std::span der_output) noexcept { + return p256_key_engine::to_der(signature_bytes, der_output); + } + + /** On public data: a signature from its DER. */ + [[nodiscard]] static bool from_der(std::span der_bytes, + std::span signature_output) noexcept { + return p256_key_engine::from_der(der_bytes, signature_output); + } + + /** Takes the source's handle; the source holds none after. */ + static void move(state& target_state, state& source_state) noexcept { + target_state.handle = source_state.handle; + source_state.handle = 0; + } + + /** Wipes and frees the key's slot; the state holds no handle after. */ + static void reset(state& engine_state) noexcept { + p256_table().release(engine_state.handle); + engine_state.handle = 0; + } +}; + +/** + * X25519 on the opaque backend: `x25519_generate`, `x25519_public` and the agreement; no import, + * no export. + * + * @tparam Backend `opaque` or `opaque_async`. + */ +template +struct x25519_engine { + /** The key pair's state, a handle. */ + using state = crypto::detail::x25519_state; + + /** + * Draws a key in the backend: 32 bytes from the system's generator, kept in a slot of the + * table and never given out. + * + * @param engine_state The key pair's state, which holds no key. + * @return Nothing; `entropy_unavailable`; `backend_failure` when the table is full. + */ + [[nodiscard]] static boost::system::result generate(state& engine_state) noexcept { + secure::secret<32> secret_bytes; + if (!crypto::random_device().fill( // lint-world: the backend's own key + secret_bytes.writable())) { + return crypto::error::entropy_unavailable; + } + auto const key_handle = x25519_table().acquire(); + if (key_handle == 0) { + return crypto::error::backend_failure; + } + auto const imported = + x25519_key_engine::import_secret(x25519_table().at(key_handle), secret_bytes.bytes()); + if (!imported) { + x25519_table().release(key_handle); + return imported.error(); + } + engine_state.handle = key_handle; + return {}; + } + + /** The key's public key. */ + [[nodiscard]] static boost::system::result public_key( + state const& engine_state, std::span public_output) noexcept { + return x25519_key_engine::public_key(x25519_table().at(engine_state.handle), public_output); + } + + /** The shared secret with the key, by its handle. */ + [[nodiscard]] static boost::system::result agree( + state const& engine_state, std::span peer_public_key, + std::span shared_output) noexcept { + return x25519_key_engine::agree(x25519_table().at(engine_state.handle), peer_public_key, + shared_output); + } + + /** Takes the source's handle; the source holds none after. */ + static void move(state& target_state, state& source_state) noexcept { + target_state.handle = source_state.handle; + source_state.handle = 0; + } + + /** Wipes and frees the key's slot; the state holds no handle after. */ + static void reset(state& engine_state) noexcept { + x25519_table().release(engine_state.handle); + engine_state.handle = 0; + } +}; + +} // namespace webcpp::test::opaque_backend + +namespace webcpp::crypto::detail { + +/** P-256's state on the synchronous opaque backend: a handle. */ +template <> +struct p_curve_state + : test::opaque_backend::handle_state {}; + +/** P-256's state on the opaque backend that completes by itself: a handle. */ +template <> +struct p_curve_state + : test::opaque_backend::handle_state {}; + +/** P-256's engine on the synchronous opaque backend. */ +template <> +struct p_curve_engine + : test::opaque_backend::p256_engine {}; + +/** P-256's engine on the opaque backend that completes by itself. */ +template <> +struct p_curve_engine + : test::opaque_backend::p256_engine {}; + +/** X25519's state on the synchronous opaque backend: a handle. */ +template <> +struct x25519_state + : test::opaque_backend::handle_state {}; + +/** X25519's state on the opaque backend that completes by itself: a handle. */ +template <> +struct x25519_state + : test::opaque_backend::handle_state {}; + +/** X25519's engine on the synchronous opaque backend. */ +template <> +struct x25519_engine + : test::opaque_backend::x25519_engine {}; + +/** X25519's engine on the opaque backend that completes by itself. */ +template <> +struct x25519_engine + : test::opaque_backend::x25519_engine {}; + +/** + * The engines are this header's own, as a shipped backend's are (design D9): a public member + * refuses, by its message, what they do not implement, and the secret-key traits, false for a + * backend outside the table, refuse `from_secret` and `secret()` first. + */ +template <> +inline constexpr bool + specialized_engine_v> = true; + +/** As the synchronous form's. */ +template <> +inline constexpr bool + specialized_engine_v> = true; + +/** As P-256's. */ +template <> +inline constexpr bool + specialized_engine_v> = true; + +/** As P-256's. */ +template <> +inline constexpr bool + specialized_engine_v> = + true; + +/** The second form completes by itself. */ +template <> +inline constexpr bool asynchronous_backend_v = true; + +/** + * The operations of the opaque backend that completes by itself (`async.hpp`'s shapes): each runs + * the key pair's work on the opaque engines when the operation is initiated and posts its + * completion to the executor (`complete_by_post`, through `asio::post`), never inline. P-256 and + * X25519 alone: generation, P-256's signing and verifying of a message, which it hashes with + * SHA-256 as WebCrypto's ECDSA does, and both curves' agreement. No `from_secret`: its keys are + * the backend's own. + */ +template <> +struct async_engine { + /** + * A key pair the backend draws. + * + * @tparam Keypair P-256's or X25519's key pair on this backend. + * @param completion_executor The executor the completion is posted to. + * @param completion_token The completion token, of signature `void(error_code, Keypair)`. + * @return What the completion token's `async_result` gives. + */ + template + static auto generate(Executor const& completion_executor, CompletionToken&& completion_token) { + return complete_by_post(completion_executor, completion_token, + []() noexcept { return async_access::generated(); }); + } + + /** + * ECDSA over SHA-256 of a message with a P-256 key pair: the message hashed here, its digest + * signed by the key's handle, S made low as the synchronous `sign` makes it. + * + * @param completion_executor The executor the completion is posted to. + * @param key_pair The key pair, the caller's until the completion. + * @param message_bytes The message, viewed until the completion. + * @param completion_token The completion token, of signature `void(error_code, signature)`. + * @return What the completion token's `async_result` gives. + */ + template + static auto sign(Executor const& completion_executor, Keypair const& key_pair, + signing_schemes::ecdsa_sha256_t /*signing_scheme*/, + std::span message_bytes, + CompletionToken&& completion_token) { + return complete_by_post( + completion_executor, completion_token, [&key_pair, message_bytes]() noexcept { + return async_access::signed_digest(key_pair, sha256_of(message_bytes)); + }); + } + + /** + * ECDSA over SHA-256 of a message against a P-256 public key, under the policy `async.hpp` has + * already applied. + * + * @param completion_executor The executor the completion is posted to. + * @param signature_value The signature, copied into the operation. + * @param message_bytes The message, viewed until the completion. + * @param public_key The public key, copied into the operation. + * @param completion_token The completion token, of signature `void(error_code)`. + * @return What the completion token's `async_result` gives. + */ + template + static auto verify( + Executor const& completion_executor, signing_schemes::ecdsa_sha256_t /*signing_scheme*/, + Policy /*verification_policy*/, curves::p256::ecdsa_signature const& signature_value, + std::span message_bytes, + curves::p256::basic_public_key const& public_key, + CompletionToken&& completion_token) { + return complete_by_post(completion_executor, completion_token, + [signature_value, message_bytes, public_key]() noexcept { + return p256_verify( + signature_value.bytes(), message_bytes, + p_curve_access::point(public_key)); + }); + } + + /** + * The agreement of a P-256 or an X25519 key pair with a peer's public key. + * + * @param completion_executor The executor the completion is posted to. + * @param key_pair The key pair, the caller's until the completion. + * @param peer_key The peer's public key, copied into the operation. + * @param completion_token The completion token, of signature `void(error_code, secret<32>)`. + * @return What the completion token's `async_result` gives. + */ + template + static auto agree(Executor const& completion_executor, Keypair const& key_pair, + PeerKey const& peer_key, CompletionToken&& completion_token) { + return complete_by_post( + completion_executor, completion_token, + [&key_pair, peer_key]() noexcept { return async_access::agreed(key_pair, peer_key); }); + } +}; + +} // namespace webcpp::crypto::detail + +#endif // WEBCPP_TEST_CRYPTO_BACKENDS_OPAQUE_HPP diff --git a/test/capabilities_test.cpp b/test/capabilities_test.cpp index 782b7d9..8965aa8 100644 --- a/test/capabilities_test.cpp +++ b/test/capabilities_test.cpp @@ -25,6 +25,9 @@ #include #include #include +#include +#include +#include #include #include #include @@ -52,6 +55,1241 @@ #include +#include + +namespace webcpp::crypto::detail::capability_check { + +namespace { + +// Per capability: whether an engine meets its concept, asked only of a marked +// engine (the primary false, the specialisation for a marked one reads the +// concept), and how many of its engines on a backend do, one engine a line. The +// formatter is off: an engine's type name, which the generator writes whole, makes +// lines it cannot break. +// clang-format off + +/** Whether `Engine`, of `Backend`, is marked and meets `backend::gcm`, for the capability `gcm`. */ +template > +constexpr bool meets_gcm = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_gcm = backend::gcm; + +/** How many engines of the capability `gcm` on `Backend` are marked and meet `backend::gcm`. */ +template +constexpr std::size_t gcm() { + return (meets_gcm> ? 1U : 0U) + + (meets_gcm> ? 1U : 0U) + + (meets_gcm> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::block_cipher`, for the capability + * `aes_block`. + */ +template > +constexpr bool meets_aes_block = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_aes_block = backend::block_cipher; + +/** + * How many engines of the capability `aes_block` on `Backend` are marked and meet + * `backend::block_cipher`. + */ +template +constexpr std::size_t aes_block() { + return (meets_aes_block> ? 1U : 0U) + + (meets_aes_block> ? 1U : 0U) + + (meets_aes_block> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::secp256k1_import`, for the + * capability `secp256k1_import`. + */ +template > +constexpr bool meets_secp256k1_import = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_secp256k1_import = backend::secp256k1_import; + +/** + * How many engines of the capability `secp256k1_import` on `Backend` are marked and meet + * `backend::secp256k1_import`. + */ +template +constexpr std::size_t secp256k1_import() { + return (meets_secp256k1_import> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::secp256k1_generate`, for the + * capability `secp256k1_generate`. + */ +template > +constexpr bool meets_secp256k1_generate = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_secp256k1_generate = backend::secp256k1_generate; + +/** + * How many engines of the capability `secp256k1_generate` on `Backend` are marked and meet + * `backend::secp256k1_generate`. + */ +template +constexpr std::size_t secp256k1_generate() { + return (meets_secp256k1_generate> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::secp256k1_public`, for the + * capability `secp256k1_public`. + */ +template > +constexpr bool meets_secp256k1_public = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_secp256k1_public = backend::secp256k1_public; + +/** + * How many engines of the capability `secp256k1_public` on `Backend` are marked and meet + * `backend::secp256k1_public`. + */ +template +constexpr std::size_t secp256k1_public() { + return (meets_secp256k1_public> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::secp256k1_export`, for the + * capability `secp256k1_export`. + */ +template > +constexpr bool meets_secp256k1_export = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_secp256k1_export = backend::secp256k1_export; + +/** + * How many engines of the capability `secp256k1_export` on `Backend` are marked and meet + * `backend::secp256k1_export`. + */ +template +constexpr std::size_t secp256k1_export() { + return (meets_secp256k1_export> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::secp256k1_point`, for the + * capability `secp256k1_point`. + */ +template > +constexpr bool meets_secp256k1_point = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_secp256k1_point = backend::secp256k1_point; + +/** + * How many engines of the capability `secp256k1_point` on `Backend` are marked and meet + * `backend::secp256k1_point`. + */ +template +constexpr std::size_t secp256k1_point() { + return (meets_secp256k1_point> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::secp256k1_ecdsa_signing`, for the + * capability `secp256k1_ecdsa_signing`. + */ +template > +constexpr bool meets_secp256k1_ecdsa_signing = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_secp256k1_ecdsa_signing = backend::secp256k1_ecdsa_signing; + +/** + * How many engines of the capability `secp256k1_ecdsa_signing` on `Backend` are marked and meet + * `backend::secp256k1_ecdsa_signing`. + */ +template +constexpr std::size_t secp256k1_ecdsa_signing() { + return (meets_secp256k1_ecdsa_signing> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::secp256k1_ecdsa_verifying`, for the + * capability `secp256k1_ecdsa_verifying`. + */ +template > +constexpr bool meets_secp256k1_ecdsa_verifying = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_secp256k1_ecdsa_verifying = backend::secp256k1_ecdsa_verifying; + +/** + * How many engines of the capability `secp256k1_ecdsa_verifying` on `Backend` are marked and meet + * `backend::secp256k1_ecdsa_verifying`. + */ +template +constexpr std::size_t secp256k1_ecdsa_verifying() { + return (meets_secp256k1_ecdsa_verifying> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::secp256k1_ecdsa_forms`, for the + * capability `secp256k1_ecdsa_forms`. + */ +template > +constexpr bool meets_secp256k1_ecdsa_forms = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_secp256k1_ecdsa_forms = backend::secp256k1_ecdsa_forms; + +/** + * How many engines of the capability `secp256k1_ecdsa_forms` on `Backend` are marked and meet + * `backend::secp256k1_ecdsa_forms`. + */ +template +constexpr std::size_t secp256k1_ecdsa_forms() { + return (meets_secp256k1_ecdsa_forms> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::secp256k1_schnorr_signing`, for the + * capability `secp256k1_schnorr_signing`. + */ +template > +constexpr bool meets_secp256k1_schnorr_signing = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_secp256k1_schnorr_signing = backend::secp256k1_schnorr_signing; + +/** + * How many engines of the capability `secp256k1_schnorr_signing` on `Backend` are marked and meet + * `backend::secp256k1_schnorr_signing`. + */ +template +constexpr std::size_t secp256k1_schnorr_signing() { + return (meets_secp256k1_schnorr_signing> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::secp256k1_schnorr_verifying`, for + * the capability `secp256k1_schnorr_verifying`. + */ +template > +constexpr bool meets_secp256k1_schnorr_verifying = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_secp256k1_schnorr_verifying = backend::secp256k1_schnorr_verifying; + +/** + * How many engines of the capability `secp256k1_schnorr_verifying` on `Backend` are marked and meet + * `backend::secp256k1_schnorr_verifying`. + */ +template +constexpr std::size_t secp256k1_schnorr_verifying() { + return (meets_secp256k1_schnorr_verifying> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::secp256k1_recoverable`, for the + * capability `secp256k1_recoverable`. + */ +template > +constexpr bool meets_secp256k1_recoverable = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_secp256k1_recoverable = backend::secp256k1_recoverable; + +/** + * How many engines of the capability `secp256k1_recoverable` on `Backend` are marked and meet + * `backend::secp256k1_recoverable`. + */ +template +constexpr std::size_t secp256k1_recoverable() { + return (meets_secp256k1_recoverable> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::secp256k1_ecdh`, for the capability + * `secp256k1_ecdh`. + */ +template > +constexpr bool meets_secp256k1_ecdh = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_secp256k1_ecdh = backend::secp256k1_ecdh; + +/** + * How many engines of the capability `secp256k1_ecdh` on `Backend` are marked and meet + * `backend::secp256k1_ecdh`. + */ +template +constexpr std::size_t secp256k1_ecdh() { + return (meets_secp256k1_ecdh> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::secp256k1_tweak`, for the + * capability `secp256k1_tweak`. + */ +template > +constexpr bool meets_secp256k1_tweak = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_secp256k1_tweak = backend::secp256k1_tweak; + +/** + * How many engines of the capability `secp256k1_tweak` on `Backend` are marked and meet + * `backend::secp256k1_tweak`. + */ +template +constexpr std::size_t secp256k1_tweak() { + return (meets_secp256k1_tweak> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::ed25519_import`, for the capability + * `ed25519_import`. + */ +template > +constexpr bool meets_ed25519_import = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_ed25519_import = backend::ed25519_import; + +/** + * How many engines of the capability `ed25519_import` on `Backend` are marked and meet + * `backend::ed25519_import`. + */ +template +constexpr std::size_t ed25519_import() { + return (meets_ed25519_import> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::ed25519_generate`, for the + * capability `ed25519_generate`. + */ +template > +constexpr bool meets_ed25519_generate = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_ed25519_generate = backend::ed25519_generate; + +/** + * How many engines of the capability `ed25519_generate` on `Backend` are marked and meet + * `backend::ed25519_generate`. + */ +template +constexpr std::size_t ed25519_generate() { + return (meets_ed25519_generate> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::ed25519_public`, for the capability + * `ed25519_public`. + */ +template > +constexpr bool meets_ed25519_public = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_ed25519_public = backend::ed25519_public; + +/** + * How many engines of the capability `ed25519_public` on `Backend` are marked and meet + * `backend::ed25519_public`. + */ +template +constexpr std::size_t ed25519_public() { + return (meets_ed25519_public> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::ed25519_export`, for the capability + * `ed25519_export`. + */ +template > +constexpr bool meets_ed25519_export = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_ed25519_export = backend::ed25519_export; + +/** + * How many engines of the capability `ed25519_export` on `Backend` are marked and meet + * `backend::ed25519_export`. + */ +template +constexpr std::size_t ed25519_export() { + return (meets_ed25519_export> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::ed25519_signing`, for the + * capability `ed25519_signing`. + */ +template > +constexpr bool meets_ed25519_signing = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_ed25519_signing = backend::ed25519_signing; + +/** + * How many engines of the capability `ed25519_signing` on `Backend` are marked and meet + * `backend::ed25519_signing`. + */ +template +constexpr std::size_t ed25519_signing() { + return (meets_ed25519_signing> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::ed25519_verifying`, for the + * capability `ed25519_verifying`. + */ +template > +constexpr bool meets_ed25519_verifying = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_ed25519_verifying = backend::ed25519_verifying; + +/** + * How many engines of the capability `ed25519_verifying` on `Backend` are marked and meet + * `backend::ed25519_verifying`. + */ +template +constexpr std::size_t ed25519_verifying() { + return (meets_ed25519_verifying> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::ed25519_to_x25519`, for the + * capability `ed25519_to_x25519`. + */ +template > +constexpr bool meets_ed25519_to_x25519 = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_ed25519_to_x25519 = backend::ed25519_to_x25519; + +/** + * How many engines of the capability `ed25519_to_x25519` on `Backend` are marked and meet + * `backend::ed25519_to_x25519`. + */ +template +constexpr std::size_t ed25519_to_x25519() { + return (meets_ed25519_to_x25519> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::ed25519ph`, for the capability + * `ed25519ph`. + */ +template > +constexpr bool meets_ed25519ph = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_ed25519ph = backend::ed25519ph>; + +/** + * How many engines of the capability `ed25519ph` on `Backend` are marked and meet + * `backend::ed25519ph`. + */ +template +constexpr std::size_t ed25519ph() { + return (meets_ed25519ph> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::x25519_import`, for the capability + * `x25519_import`. + */ +template > +constexpr bool meets_x25519_import = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_x25519_import = backend::x25519_import; + +/** + * How many engines of the capability `x25519_import` on `Backend` are marked and meet + * `backend::x25519_import`. + */ +template +constexpr std::size_t x25519_import() { + return (meets_x25519_import> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::x25519_generate`, for the + * capability `x25519_generate`. + */ +template > +constexpr bool meets_x25519_generate = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_x25519_generate = backend::x25519_generate; + +/** + * How many engines of the capability `x25519_generate` on `Backend` are marked and meet + * `backend::x25519_generate`. + */ +template +constexpr std::size_t x25519_generate() { + return (meets_x25519_generate> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::x25519_public`, for the capability + * `x25519_public`. + */ +template > +constexpr bool meets_x25519_public = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_x25519_public = backend::x25519_public; + +/** + * How many engines of the capability `x25519_public` on `Backend` are marked and meet + * `backend::x25519_public`. + */ +template +constexpr std::size_t x25519_public() { + return (meets_x25519_public> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::x25519_export`, for the capability + * `x25519_export`. + */ +template > +constexpr bool meets_x25519_export = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_x25519_export = backend::x25519_export; + +/** + * How many engines of the capability `x25519_export` on `Backend` are marked and meet + * `backend::x25519_export`. + */ +template +constexpr std::size_t x25519_export() { + return (meets_x25519_export> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::x25519_agreement`, for the + * capability `x25519_agreement`. + */ +template > +constexpr bool meets_x25519_agreement = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_x25519_agreement = backend::x25519_agreement; + +/** + * How many engines of the capability `x25519_agreement` on `Backend` are marked and meet + * `backend::x25519_agreement`. + */ +template +constexpr std::size_t x25519_agreement() { + return (meets_x25519_agreement> ? 1U : 0U); +} + +/** Whether `Engine`, of `Backend`, is marked and meets `backend::kx`, for the capability `kx`. */ +template > +constexpr bool meets_kx = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_kx = backend::kx; + +/** How many engines of the capability `kx` on `Backend` are marked and meet `backend::kx`. */ +template +constexpr std::size_t kx() { + return (meets_kx> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::aead`, for the capability + * `chacha20_poly1305`. + */ +template > +constexpr bool meets_chacha20_poly1305 = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_chacha20_poly1305 = backend::aead; + +/** + * How many engines of the capability `chacha20_poly1305` on `Backend` are marked and meet + * `backend::aead`. + */ +template +constexpr std::size_t chacha20_poly1305() { + return (meets_chacha20_poly1305> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::aead`, for the capability + * `chacha20_poly1305_original`. + */ +template > +constexpr bool meets_chacha20_poly1305_original = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_chacha20_poly1305_original = backend::aead; + +/** + * How many engines of the capability `chacha20_poly1305_original` on `Backend` are marked and meet + * `backend::aead`. + */ +template +constexpr std::size_t chacha20_poly1305_original() { + return (meets_chacha20_poly1305_original> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::aead`, for the capability + * `xchacha20_poly1305`. + */ +template > +constexpr bool meets_xchacha20_poly1305 = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_xchacha20_poly1305 = backend::aead; + +/** + * How many engines of the capability `xchacha20_poly1305` on `Backend` are marked and meet + * `backend::aead`. + */ +template +constexpr std::size_t xchacha20_poly1305() { + return (meets_xchacha20_poly1305> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::stream_cipher`, for the capability + * `chacha20`. + */ +template > +constexpr bool meets_chacha20 = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_chacha20 = backend::stream_cipher; + +/** + * How many engines of the capability `chacha20` on `Backend` are marked and meet + * `backend::stream_cipher`. + */ +template +constexpr std::size_t chacha20() { + return (meets_chacha20> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::authenticator`, for the capability + * `poly1305`. + */ +template > +constexpr bool meets_poly1305 = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_poly1305 = backend::authenticator; + +/** + * How many engines of the capability `poly1305` on `Backend` are marked and meet + * `backend::authenticator`. + */ +template +constexpr std::size_t poly1305() { + return (meets_poly1305> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::authenticated_box`, for the + * capability `secretbox_xsalsa20poly1305`. + */ +template > +constexpr bool meets_secretbox_xsalsa20poly1305 = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_secretbox_xsalsa20poly1305 = backend::authenticated_box; + +/** + * How many engines of the capability `secretbox_xsalsa20poly1305` on `Backend` are marked and meet + * `backend::authenticated_box`. + */ +template +constexpr std::size_t secretbox_xsalsa20poly1305() { + return (meets_secretbox_xsalsa20poly1305> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::authenticated_box`, for the + * capability `secretbox_xchacha20poly1305`. + */ +template > +constexpr bool meets_secretbox_xchacha20poly1305 = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_secretbox_xchacha20poly1305 = backend::authenticated_box; + +/** + * How many engines of the capability `secretbox_xchacha20poly1305` on `Backend` are marked and meet + * `backend::authenticated_box`. + */ +template +constexpr std::size_t secretbox_xchacha20poly1305() { + return (meets_secretbox_xchacha20poly1305> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::box`, for the capability + * `box_xsalsa20poly1305`. + */ +template > +constexpr bool meets_box_xsalsa20poly1305 = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_box_xsalsa20poly1305 = backend::box; + +/** + * How many engines of the capability `box_xsalsa20poly1305` on `Backend` are marked and meet + * `backend::box`. + */ +template +constexpr std::size_t box_xsalsa20poly1305() { + return (meets_box_xsalsa20poly1305> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::box`, for the capability + * `box_xchacha20poly1305`. + */ +template > +constexpr bool meets_box_xchacha20poly1305 = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_box_xchacha20poly1305 = backend::box; + +/** + * How many engines of the capability `box_xchacha20poly1305` on `Backend` are marked and meet + * `backend::box`. + */ +template +constexpr std::size_t box_xchacha20poly1305() { + return (meets_box_xchacha20poly1305> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::sealed_box`, for the capability + * `sealed_box`. + */ +template > +constexpr bool meets_sealed_box = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_sealed_box = backend::sealed_box; + +/** + * How many engines of the capability `sealed_box` on `Backend` are marked and meet + * `backend::sealed_box`. + */ +template +constexpr std::size_t sealed_box() { + return (meets_sealed_box> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::secp256k1_ellswift`, for the + * capability `secp256k1_ellswift`. + */ +template > +constexpr bool meets_secp256k1_ellswift = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_secp256k1_ellswift = backend::secp256k1_ellswift; + +/** + * How many engines of the capability `secp256k1_ellswift` on `Backend` are marked and meet + * `backend::secp256k1_ellswift`. + */ +template +constexpr std::size_t secp256k1_ellswift() { + return (meets_secp256k1_ellswift> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::secp256k1_musig`, for the + * capability `secp256k1_musig`. + */ +template > +constexpr bool meets_secp256k1_musig = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_secp256k1_musig = backend::secp256k1_musig; + +/** + * How many engines of the capability `secp256k1_musig` on `Backend` are marked and meet + * `backend::secp256k1_musig`. + */ +template +constexpr std::size_t secp256k1_musig() { + return (meets_secp256k1_musig> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::secp256k1_silent_payments`, for the + * capability `secp256k1_silent_payments`. + */ +template > +constexpr bool meets_secp256k1_silent_payments = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_secp256k1_silent_payments = backend::secp256k1_silent_payments; + +/** + * How many engines of the capability `secp256k1_silent_payments` on `Backend` are marked and meet + * `backend::secp256k1_silent_payments`. + */ +template +constexpr std::size_t secp256k1_silent_payments() { + return (meets_secp256k1_silent_payments> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::p256_import`, for the capability + * `p256_import`. + */ +template > +constexpr bool meets_p256_import = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_p256_import = backend::p256_import; + +/** + * How many engines of the capability `p256_import` on `Backend` are marked and meet + * `backend::p256_import`. + */ +template +constexpr std::size_t p256_import() { + return (meets_p256_import> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::p256_generate`, for the capability + * `p256_generate`. + */ +template > +constexpr bool meets_p256_generate = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_p256_generate = backend::p256_generate; + +/** + * How many engines of the capability `p256_generate` on `Backend` are marked and meet + * `backend::p256_generate`. + */ +template +constexpr std::size_t p256_generate() { + return (meets_p256_generate> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::p256_public`, for the capability + * `p256_public`. + */ +template > +constexpr bool meets_p256_public = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_p256_public = backend::p256_public; + +/** + * How many engines of the capability `p256_public` on `Backend` are marked and meet + * `backend::p256_public`. + */ +template +constexpr std::size_t p256_public() { + return (meets_p256_public> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::p256_export`, for the capability + * `p256_export`. + */ +template > +constexpr bool meets_p256_export = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_p256_export = backend::p256_export; + +/** + * How many engines of the capability `p256_export` on `Backend` are marked and meet + * `backend::p256_export`. + */ +template +constexpr std::size_t p256_export() { + return (meets_p256_export> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::p256_point`, for the capability + * `p256_point`. + */ +template > +constexpr bool meets_p256_point = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_p256_point = backend::p256_point; + +/** + * How many engines of the capability `p256_point` on `Backend` are marked and meet + * `backend::p256_point`. + */ +template +constexpr std::size_t p256_point() { + return (meets_p256_point> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::p256_ecdsa_signing`, for the + * capability `p256_ecdsa_signing`. + */ +template > +constexpr bool meets_p256_ecdsa_signing = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_p256_ecdsa_signing = backend::p256_ecdsa_signing; + +/** + * How many engines of the capability `p256_ecdsa_signing` on `Backend` are marked and meet + * `backend::p256_ecdsa_signing`. + */ +template +constexpr std::size_t p256_ecdsa_signing() { + return (meets_p256_ecdsa_signing> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::p256_ecdsa_verifying`, for the + * capability `p256_ecdsa_verifying`. + */ +template > +constexpr bool meets_p256_ecdsa_verifying = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_p256_ecdsa_verifying = backend::p256_ecdsa_verifying; + +/** + * How many engines of the capability `p256_ecdsa_verifying` on `Backend` are marked and meet + * `backend::p256_ecdsa_verifying`. + */ +template +constexpr std::size_t p256_ecdsa_verifying() { + return (meets_p256_ecdsa_verifying> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::p256_ecdsa_message_signing`, for + * the capability `p256_ecdsa_message_signing`. + */ +template > +constexpr bool meets_p256_ecdsa_message_signing = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_p256_ecdsa_message_signing = backend::p256_ecdsa_message_signing; + +/** + * How many engines of the capability `p256_ecdsa_message_signing` on `Backend` are marked and meet + * `backend::p256_ecdsa_message_signing`. + */ +template +constexpr std::size_t p256_ecdsa_message_signing() { + return (meets_p256_ecdsa_message_signing> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::p256_ecdsa_message_verifying`, for + * the capability `p256_ecdsa_message_verifying`. + */ +template > +constexpr bool meets_p256_ecdsa_message_verifying = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_p256_ecdsa_message_verifying = backend::p256_ecdsa_message_verifying; + +/** + * How many engines of the capability `p256_ecdsa_message_verifying` on `Backend` are marked and + * meet `backend::p256_ecdsa_message_verifying`. + */ +template +constexpr std::size_t p256_ecdsa_message_verifying() { + return (meets_p256_ecdsa_message_verifying> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::p256_ecdh`, for the capability + * `p256_ecdh`. + */ +template > +constexpr bool meets_p256_ecdh = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_p256_ecdh = backend::p256_ecdh; + +/** + * How many engines of the capability `p256_ecdh` on `Backend` are marked and meet + * `backend::p256_ecdh`. + */ +template +constexpr std::size_t p256_ecdh() { + return (meets_p256_ecdh> ? 1U : 0U); +} + +/** + * Whether `Engine`, of `Backend`, is marked and meets `backend::ecdsa_der`, for the capability + * `p256_ecdsa_der`. + */ +template > +constexpr bool meets_p256_ecdsa_der = false; +/** A marked engine: its concept. */ +template +constexpr bool meets_p256_ecdsa_der = backend::ecdsa_der; + +/** + * How many engines of the capability `p256_ecdsa_der` on `Backend` are marked and meet + * `backend::ecdsa_der`. + */ +template +constexpr std::size_t p256_ecdsa_der() { + return (meets_p256_ecdsa_der> ? 1U : 0U); +} + +// clang-format on + +/** + * The table against `Backend`'s engines, where the target links it: each + * assertion instantiates with the class, which the fold below does. + * + * @tparam Backend A backend tag of `detail::shipped_backends`. + */ +template +struct table_meets_engines { + // clang-format off + static_assert(!linked || gcm() == + (capability_supported ? 3U : 0U), + "crypto.json's cell gcm disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::gcm (design D5)"); + static_assert(!linked || aes_block() == + (capability_supported ? 3U : 0U), + "crypto.json's cell aes_block disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::block_cipher (design D5)"); + static_assert(!linked || secp256k1_import() == + (capability_supported ? 1U : 0U), + "crypto.json's cell secp256k1_import disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::secp256k1_import (design D5)"); + static_assert(!linked || secp256k1_generate() == + (capability_supported ? 1U : 0U), + "crypto.json's cell secp256k1_generate disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::secp256k1_generate (design D5)"); + static_assert(!linked || secp256k1_public() == + (capability_supported ? 1U : 0U), + "crypto.json's cell secp256k1_public disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::secp256k1_public (design D5)"); + static_assert(!linked || secp256k1_export() == + (capability_supported ? 1U : 0U), + "crypto.json's cell secp256k1_export disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::secp256k1_export (design D5)"); + static_assert(!linked || secp256k1_point() == + (capability_supported ? 1U : 0U), + "crypto.json's cell secp256k1_point disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::secp256k1_point (design D5)"); + static_assert(!linked || secp256k1_ecdsa_signing() == + (capability_supported ? 1U : 0U), + "crypto.json's cell secp256k1_ecdsa_signing disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::secp256k1_ecdsa_signing (design D5)"); + static_assert(!linked || secp256k1_ecdsa_verifying() == + (capability_supported ? 1U : 0U), + "crypto.json's cell secp256k1_ecdsa_verifying disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::secp256k1_ecdsa_verifying (design D5)"); + static_assert(!linked || secp256k1_ecdsa_forms() == + (capability_supported ? 1U : 0U), + "crypto.json's cell secp256k1_ecdsa_forms disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::secp256k1_ecdsa_forms (design D5)"); + static_assert(!linked || secp256k1_schnorr_signing() == + (capability_supported ? 1U : 0U), + "crypto.json's cell secp256k1_schnorr_signing disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::secp256k1_schnorr_signing (design D5)"); + static_assert(!linked || secp256k1_schnorr_verifying() == + (capability_supported ? 1U : 0U), + "crypto.json's cell secp256k1_schnorr_verifying disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::secp256k1_schnorr_verifying (design D5)"); + static_assert(!linked || secp256k1_recoverable() == + (capability_supported ? 1U : 0U), + "crypto.json's cell secp256k1_recoverable disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::secp256k1_recoverable (design D5)"); + static_assert(!linked || secp256k1_ecdh() == + (capability_supported ? 1U : 0U), + "crypto.json's cell secp256k1_ecdh disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::secp256k1_ecdh (design D5)"); + static_assert(!linked || secp256k1_tweak() == + (capability_supported ? 1U : 0U), + "crypto.json's cell secp256k1_tweak disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::secp256k1_tweak (design D5)"); + static_assert(!linked || ed25519_import() == + (capability_supported ? 1U : 0U), + "crypto.json's cell ed25519_import disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::ed25519_import (design D5)"); + static_assert(!linked || ed25519_generate() == + (capability_supported ? 1U : 0U), + "crypto.json's cell ed25519_generate disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::ed25519_generate (design D5)"); + static_assert(!linked || ed25519_public() == + (capability_supported ? 1U : 0U), + "crypto.json's cell ed25519_public disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::ed25519_public (design D5)"); + static_assert(!linked || ed25519_export() == + (capability_supported ? 1U : 0U), + "crypto.json's cell ed25519_export disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::ed25519_export (design D5)"); + static_assert(!linked || ed25519_signing() == + (capability_supported ? 1U : 0U), + "crypto.json's cell ed25519_signing disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::ed25519_signing (design D5)"); + static_assert(!linked || ed25519_verifying() == + (capability_supported ? 1U : 0U), + "crypto.json's cell ed25519_verifying disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::ed25519_verifying (design D5)"); + static_assert(!linked || ed25519_to_x25519() == + (capability_supported ? 1U : 0U), + "crypto.json's cell ed25519_to_x25519 disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::ed25519_to_x25519 (design D5)"); + static_assert(!linked || ed25519ph() == + (capability_supported ? 1U : 0U), + "crypto.json's cell ed25519ph disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::ed25519ph (design D5)"); + static_assert(!linked || x25519_import() == + (capability_supported ? 1U : 0U), + "crypto.json's cell x25519_import disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::x25519_import (design D5)"); + static_assert(!linked || x25519_generate() == + (capability_supported ? 1U : 0U), + "crypto.json's cell x25519_generate disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::x25519_generate (design D5)"); + static_assert(!linked || x25519_public() == + (capability_supported ? 1U : 0U), + "crypto.json's cell x25519_public disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::x25519_public (design D5)"); + static_assert(!linked || x25519_export() == + (capability_supported ? 1U : 0U), + "crypto.json's cell x25519_export disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::x25519_export (design D5)"); + static_assert(!linked || x25519_agreement() == + (capability_supported ? 1U : 0U), + "crypto.json's cell x25519_agreement disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::x25519_agreement (design D5)"); + static_assert(!linked || kx() == + (capability_supported ? 1U : 0U), + "crypto.json's cell kx disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::kx (design D5)"); + static_assert(!linked || chacha20_poly1305() == + (capability_supported ? 1U : 0U), + "crypto.json's cell chacha20_poly1305 disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::aead (design D5)"); + static_assert(!linked || chacha20_poly1305_original() == + (capability_supported ? 1U : 0U), + "crypto.json's cell chacha20_poly1305_original disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::aead (design D5)"); + static_assert(!linked || xchacha20_poly1305() == + (capability_supported ? 1U : 0U), + "crypto.json's cell xchacha20_poly1305 disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::aead (design D5)"); + static_assert(!linked || chacha20() == + (capability_supported ? 1U : 0U), + "crypto.json's cell chacha20 disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::stream_cipher (design D5)"); + static_assert(!linked || poly1305() == + (capability_supported ? 1U : 0U), + "crypto.json's cell poly1305 disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::authenticator (design D5)"); + static_assert(!linked || secretbox_xsalsa20poly1305() == + (capability_supported ? 1U : 0U), + "crypto.json's cell secretbox_xsalsa20poly1305 disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::authenticated_box (design D5)"); + static_assert(!linked || secretbox_xchacha20poly1305() == + (capability_supported ? 1U : 0U), + "crypto.json's cell secretbox_xchacha20poly1305 disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::authenticated_box (design D5)"); + static_assert(!linked || box_xsalsa20poly1305() == + (capability_supported ? 1U : 0U), + "crypto.json's cell box_xsalsa20poly1305 disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::box (design D5)"); + static_assert(!linked || box_xchacha20poly1305() == + (capability_supported ? 1U : 0U), + "crypto.json's cell box_xchacha20poly1305 disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::box (design D5)"); + static_assert(!linked || sealed_box() == + (capability_supported ? 1U : 0U), + "crypto.json's cell sealed_box disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::sealed_box (design D5)"); + static_assert(!linked || secp256k1_ellswift() == + (capability_supported ? 1U : 0U), + "crypto.json's cell secp256k1_ellswift disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::secp256k1_ellswift (design D5)"); + static_assert(!linked || secp256k1_musig() == + (capability_supported ? 1U : 0U), + "crypto.json's cell secp256k1_musig disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::secp256k1_musig (design D5)"); + static_assert(!linked || secp256k1_silent_payments() == + (capability_supported ? 1U : 0U), + "crypto.json's cell secp256k1_silent_payments disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::secp256k1_silent_payments (design D5)"); + static_assert(!linked || p256_import() == + (capability_supported ? 1U : 0U), + "crypto.json's cell p256_import disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::p256_import (design D5)"); + static_assert(!linked || p256_generate() == + (capability_supported ? 1U : 0U), + "crypto.json's cell p256_generate disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::p256_generate (design D5)"); + static_assert(!linked || p256_public() == + (capability_supported ? 1U : 0U), + "crypto.json's cell p256_public disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::p256_public (design D5)"); + static_assert(!linked || p256_export() == + (capability_supported ? 1U : 0U), + "crypto.json's cell p256_export disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::p256_export (design D5)"); + static_assert(!linked || p256_point() == + (capability_supported ? 1U : 0U), + "crypto.json's cell p256_point disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::p256_point (design D5)"); + static_assert(!linked || p256_ecdsa_signing() == + (capability_supported ? 1U : 0U), + "crypto.json's cell p256_ecdsa_signing disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::p256_ecdsa_signing (design D5)"); + static_assert(!linked || p256_ecdsa_verifying() == + (capability_supported ? 1U : 0U), + "crypto.json's cell p256_ecdsa_verifying disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::p256_ecdsa_verifying (design D5)"); + static_assert(!linked || p256_ecdsa_message_signing() == + (capability_supported ? 1U : 0U), + "crypto.json's cell p256_ecdsa_message_signing disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::p256_ecdsa_message_signing (design D5)"); + static_assert(!linked || p256_ecdsa_message_verifying() == + (capability_supported ? 1U : 0U), + "crypto.json's cell p256_ecdsa_message_verifying disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::p256_ecdsa_message_verifying (design D5)"); + static_assert(!linked || p256_ecdh() == + (capability_supported ? 1U : 0U), + "crypto.json's cell p256_ecdh disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::p256_ecdh (design D5)"); + static_assert(!linked || p256_ecdsa_der() == + (capability_supported ? 1U : 0U), + "crypto.json's cell p256_ecdsa_der disagrees with this backend's engines: it is present exactly where each engine is specialised and meets backend::ecdsa_der (design D5)"); + static_assert(!linked || exports_secret_keys_v || + (secp256k1_export() + ed25519_export() + ed25519_to_x25519() + x25519_export() + p256_export()) == 0U, + "a backend whose exports_secret_keys_v is false has an engine that meets a export concept"); + static_assert(!linked || !exports_secret_keys_v || + secp256k1_import() == 0U || (secp256k1_export() == 1U), + "a backend whose exports_secret_keys_v is true lacks secp256k1's export, which its import asks"); + static_assert(!linked || !exports_secret_keys_v || + ed25519_import() == 0U || (ed25519_export() == 1U && ed25519_to_x25519() == 1U), + "a backend whose exports_secret_keys_v is true lacks Ed25519's export, which its import asks"); + static_assert(!linked || !exports_secret_keys_v || + x25519_import() == 0U || (x25519_export() == 1U), + "a backend whose exports_secret_keys_v is true lacks X25519's export, which its import asks"); + static_assert(!linked || !exports_secret_keys_v || + p256_import() == 0U || (p256_export() == 1U), + "a backend whose exports_secret_keys_v is true lacks P-256's export, which its import asks"); + static_assert(!linked || imports_secret_keys_v || + (secp256k1_import() + ed25519_import() + x25519_import() + p256_import()) == 0U, + "a backend whose imports_secret_keys_v is false has an engine that meets a import concept"); + static_assert(!linked || !imports_secret_keys_v || + secp256k1_public() == 0U || (secp256k1_import() == 1U), + "a backend whose imports_secret_keys_v is true lacks secp256k1's import, which its public asks"); + static_assert(!linked || !imports_secret_keys_v || + ed25519_public() == 0U || (ed25519_import() == 1U), + "a backend whose imports_secret_keys_v is true lacks Ed25519's import, which its public asks"); + static_assert(!linked || !imports_secret_keys_v || + x25519_public() == 0U || (x25519_import() == 1U), + "a backend whose imports_secret_keys_v is true lacks X25519's import, which its public asks"); + static_assert(!linked || !imports_secret_keys_v || + p256_public() == 0U || (p256_import() == 1U), + "a backend whose imports_secret_keys_v is true lacks P-256's import, which its public asks"); + // clang-format on + + /** Read by the fold below, which instantiates the class. */ + static constexpr bool checked = true; +}; + +/** + * Checks the table against each shipped backend's engines. + * + * @tparam Backends The backends of `detail::shipped_backends`. + * @return True. + */ +template +constexpr bool every_backend_checked(backend_list /*backends*/) { + return (table_meets_engines::checked && ...); +} + +static_assert(every_backend_checked(shipped_backends{})); + +} // namespace + +} // namespace webcpp::crypto::detail::capability_check + namespace { namespace crypto = webcpp::crypto; @@ -207,6 +1445,11 @@ static_assert(crypto::supports_v, bac #else static_assert(!crypto::supports_v, backends::bearssl>); #endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif // AES-GCM on openssl: native, wasip2, wasip3. #if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) static_assert(crypto::supports_v, backends::openssl>); @@ -223,19 +1466,28 @@ static_assert(crypto::supports_v, bac #else static_assert(!crypto::supports_v, backends::openssl>); #endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif // AES-GCM on ctaes: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::ctaes>); static_assert(!crypto::supports_v, backends::ctaes>); static_assert(!crypto::supports_v, backends::ctaes>); // AES-GCM on secp256k1: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::secp256k1>); static_assert(!crypto::supports_v, backends::secp256k1>); static_assert(!crypto::supports_v, backends::secp256k1>); // AES-GCM on sodium: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::sodium>); static_assert(!crypto::supports_v, backends::sodium>); static_assert(!crypto::supports_v, backends::sodium>); // AES block cipher on bearssl: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::bearssl>); static_assert(!crypto::supports_v, backends::bearssl>); static_assert(!crypto::supports_v, backends::bearssl>); @@ -255,6 +1507,11 @@ static_assert(crypto::supports_v, b #else static_assert(!crypto::supports_v, backends::openssl>); #endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif // AES block cipher on ctaes: native, wasip2, wasip3, emscripten. #if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) static_assert(crypto::supports_v, backends::ctaes>); @@ -271,19 +1528,65 @@ static_assert(crypto::supports_v, b #else static_assert(!crypto::supports_v, backends::ctaes>); #endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif // AES block cipher on secp256k1: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::secp256k1>); static_assert(!crypto::supports_v, backends::secp256k1>); static_assert(!crypto::supports_v, backends::secp256k1>); // AES block cipher on sodium: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::sodium>); static_assert(!crypto::supports_v, backends::sodium>); static_assert(!crypto::supports_v, backends::sodium>); // secp256k1 on bearssl: none. +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::bearssl>); // secp256k1 on openssl: none. +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::openssl>); // secp256k1 on ctaes: none. +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::ctaes>); // secp256k1 on secp256k1: native, wasip2, wasip3, emscripten. #if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) @@ -291,18 +1594,124 @@ static_assert(crypto::supports_v, backends::secp256k1>); #endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif +static_assert(!crypto::supports_capability_v); +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif // secp256k1 on sodium: none. +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::sodium>); // Ed25519 on bearssl: none. +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::bearssl>); static_assert(!crypto::supports_v, backends::bearssl>); // Ed25519 on openssl: none. +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::openssl>); static_assert(!crypto::supports_v, backends::openssl>); // Ed25519 on ctaes: none. +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::ctaes>); static_assert(!crypto::supports_v, backends::ctaes>); // Ed25519 on secp256k1: none. +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::secp256k1>); static_assert(!crypto::supports_v, backends::secp256k1>); // Ed25519 on sodium: native, wasip2, wasip3, emscripten. @@ -316,13 +1725,69 @@ static_assert(crypto::supports_v, #else static_assert(!crypto::supports_v, backends::sodium>); #endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif +static_assert(!crypto::supports_capability_v); +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif // X25519 on bearssl: none. +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::bearssl>); // X25519 on openssl: none. +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::openssl>); // X25519 on ctaes: none. +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::ctaes>); // X25519 on secp256k1: none. +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::secp256k1>); // X25519 on sodium: native, wasip2, wasip3, emscripten. #if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) @@ -330,13 +1795,38 @@ static_assert(crypto::supports_v, #else static_assert(!crypto::supports_v, backends::sodium>); #endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif +static_assert(!crypto::supports_capability_v); +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif // crypto_kx on bearssl: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::bearssl>); // crypto_kx on openssl: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::openssl>); // crypto_kx on ctaes: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::ctaes>); // crypto_kx on secp256k1: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::secp256k1>); // crypto_kx on sodium: native, wasip2, wasip3, emscripten. #if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) @@ -344,21 +1834,38 @@ static_assert(crypto::supports_v, backends #else static_assert(!crypto::supports_v, backends::sodium>); #endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif // ChaCha20-Poly1305 on bearssl: native, wasip2, wasip3, emscripten. #if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) static_assert(crypto::supports_v, backends::bearssl>); #else static_assert(!crypto::supports_v, backends::bearssl>); #endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif // ChaCha20-Poly1305 on openssl: native, wasip2, wasip3. #if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) static_assert(crypto::supports_v, backends::openssl>); #else static_assert(!crypto::supports_v, backends::openssl>); #endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif // ChaCha20-Poly1305 on ctaes: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::ctaes>); // ChaCha20-Poly1305 on secp256k1: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::secp256k1>); // ChaCha20-Poly1305 on sodium: native, wasip2, wasip3, emscripten. #if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) @@ -366,13 +1873,22 @@ static_assert(crypto::supports_v, backends::sodium>); #endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif // original ChaCha20-Poly1305 on bearssl: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::bearssl>); // original ChaCha20-Poly1305 on openssl: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::openssl>); // original ChaCha20-Poly1305 on ctaes: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::ctaes>); // original ChaCha20-Poly1305 on secp256k1: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::secp256k1>); // original ChaCha20-Poly1305 on sodium: native, wasip2, wasip3, emscripten. #if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) @@ -380,13 +1896,22 @@ static_assert(crypto::supports_v, backends::sodium>); #endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif // XChaCha20-Poly1305 on bearssl: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::bearssl>); // XChaCha20-Poly1305 on openssl: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::openssl>); // XChaCha20-Poly1305 on ctaes: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::ctaes>); // XChaCha20-Poly1305 on secp256k1: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::secp256k1>); // XChaCha20-Poly1305 on sodium: native, wasip2, wasip3, emscripten. #if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) @@ -394,21 +1919,38 @@ static_assert(crypto::supports_v, backends::sodium>); #endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif // ChaCha20 on bearssl: native, wasip2, wasip3, emscripten. #if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) static_assert(crypto::supports_v, backends::bearssl>); #else static_assert(!crypto::supports_v, backends::bearssl>); #endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif // ChaCha20 on openssl: native, wasip2, wasip3. #if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) static_assert(crypto::supports_v, backends::openssl>); #else static_assert(!crypto::supports_v, backends::openssl>); #endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif // ChaCha20 on ctaes: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::ctaes>); // ChaCha20 on secp256k1: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::secp256k1>); // ChaCha20 on sodium: native, wasip2, wasip3, emscripten. #if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) @@ -416,7 +1958,13 @@ static_assert(crypto::supports_v, backends::sodium>); #endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif // Poly1305 on bearssl: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::bearssl>); // Poly1305 on openssl: native, wasip2, wasip3. #if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) @@ -424,9 +1972,16 @@ static_assert(crypto::supports_v, backends::openssl>); #endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif // Poly1305 on ctaes: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::ctaes>); // Poly1305 on secp256k1: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::secp256k1>); // Poly1305 on sodium: native, wasip2, wasip3, emscripten. #if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) @@ -434,13 +1989,22 @@ static_assert(crypto::supports_v, backends::sodium>); #endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif // XSalsa20-Poly1305 secret box on bearssl: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::bearssl>); // XSalsa20-Poly1305 secret box on openssl: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::openssl>); // XSalsa20-Poly1305 secret box on ctaes: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::ctaes>); // XSalsa20-Poly1305 secret box on secp256k1: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::secp256k1>); // XSalsa20-Poly1305 secret box on sodium: native, wasip2, wasip3, emscripten. #if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) @@ -448,13 +2012,22 @@ static_assert(crypto::supports_v, backends::sodium>); #endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif // XChaCha20-Poly1305 secret box on bearssl: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::bearssl>); // XChaCha20-Poly1305 secret box on openssl: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::openssl>); // XChaCha20-Poly1305 secret box on ctaes: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::ctaes>); // XChaCha20-Poly1305 secret box on secp256k1: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::secp256k1>); // XChaCha20-Poly1305 secret box on sodium: native, wasip2, wasip3, emscripten. #if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) @@ -462,13 +2035,22 @@ static_assert(crypto::supports_v, backends::sodium>); #endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif // X25519-XSalsa20-Poly1305 box on bearssl: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::bearssl>); // X25519-XSalsa20-Poly1305 box on openssl: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::openssl>); // X25519-XSalsa20-Poly1305 box on ctaes: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::ctaes>); // X25519-XSalsa20-Poly1305 box on secp256k1: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::secp256k1>); // X25519-XSalsa20-Poly1305 box on sodium: native, wasip2, wasip3, emscripten. #if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) @@ -476,13 +2058,22 @@ static_assert(crypto::supports_v, backends::sodium>); #endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif // X25519-XChaCha20-Poly1305 box on bearssl: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::bearssl>); // X25519-XChaCha20-Poly1305 box on openssl: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::openssl>); // X25519-XChaCha20-Poly1305 box on ctaes: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::ctaes>); // X25519-XChaCha20-Poly1305 box on secp256k1: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::secp256k1>); // X25519-XChaCha20-Poly1305 box on sodium: native, wasip2, wasip3, emscripten. #if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) @@ -490,13 +2081,22 @@ static_assert(crypto::supports_v, backends::sodium>); #endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif // X25519-XSalsa20-Poly1305 sealed box on bearssl: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::bearssl>); // X25519-XSalsa20-Poly1305 sealed box on openssl: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::openssl>); // X25519-XSalsa20-Poly1305 sealed box on ctaes: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::ctaes>); // X25519-XSalsa20-Poly1305 sealed box on secp256k1: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::secp256k1>); // X25519-XSalsa20-Poly1305 sealed box on sodium: native, wasip2, wasip3, emscripten. #if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) @@ -504,11 +2104,19 @@ static_assert(crypto::supports_v, backends::sodium>); #endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif // ElligatorSwift on bearssl: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::bearssl>); // ElligatorSwift on openssl: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::openssl>); // ElligatorSwift on ctaes: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::ctaes>); // ElligatorSwift on secp256k1: native, wasip2, wasip3, emscripten. #if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) @@ -516,13 +2124,22 @@ static_assert(crypto::supports_v, backends::secp256k1>); #endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif // ElligatorSwift on sodium: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::sodium>); // MuSig2 on bearssl: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::bearssl>); // MuSig2 on openssl: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::openssl>); // MuSig2 on ctaes: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::ctaes>); // MuSig2 on secp256k1: native, wasip2, wasip3, emscripten. #if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) @@ -530,13 +2147,22 @@ static_assert(crypto::supports_v, backends::secp256k1>); #endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif // MuSig2 on sodium: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::sodium>); // BIP 352 silent payments on bearssl: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::bearssl>); // BIP 352 silent payments on openssl: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::openssl>); // BIP 352 silent payments on ctaes: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::ctaes>); // BIP 352 silent payments on secp256k1: native, wasip2, wasip3, emscripten. #if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) @@ -544,7 +2170,13 @@ static_assert(crypto::supports_v, backends::secp256k1>); #endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif // BIP 352 silent payments on sodium: none. +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::sodium>); // P-256 on bearssl: native, wasip2, wasip3, emscripten. #if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) @@ -552,14 +2184,111 @@ static_assert(crypto::supports_v, back #else static_assert(!crypto::supports_v, backends::bearssl>); #endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif +static_assert(!crypto::supports_capability_v); +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif +#if defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN) +static_assert(crypto::supports_capability_v); +#else +static_assert(!crypto::supports_capability_v); +#endif // P-256 on openssl: none. +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::openssl>); // P-256 on ctaes: none. +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::ctaes>); // P-256 on secp256k1: none. +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::secp256k1>); // P-256 on sodium: none. +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); +static_assert(!crypto::supports_capability_v); static_assert(!crypto::supports_v, backends::sodium>); +static_assert(crypto::exports_secret_keys_v); +static_assert(crypto::imports_secret_keys_v); +static_assert(crypto::exports_secret_keys_v); +static_assert(crypto::imports_secret_keys_v); +static_assert(crypto::exports_secret_keys_v); +static_assert(crypto::imports_secret_keys_v); +static_assert(crypto::exports_secret_keys_v); +static_assert(crypto::imports_secret_keys_v); +static_assert(crypto::exports_secret_keys_v); +static_assert(crypto::imports_secret_keys_v); // clang-format on // NOLINTNEXTLINE(readability-function-cognitive-complexity): one check per cell diff --git a/test/keypair_engine_failure_test.cpp b/test/keypair_engine_failure_test.cpp new file mode 100644 index 0000000..289854d --- /dev/null +++ b/test/keypair_engine_failure_test.cpp @@ -0,0 +1,173 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the 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 key engines' fallible public_key and export_secret (backend concepts, task 2.1): on a +// stand-in backend whose engine fails them, an Ed25519 and a P-256 key pair's public_key() and +// secret() pass the engine's error on, and Ed25519's PKCS#8 encode, which exports first, writes +// nothing. The shipped engines never fail there, so only a stand-in reaches these paths. + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include + +namespace webcpp::test { +namespace { + +/** A backend tag for the key pairs' generic layer alone. */ +struct failing_stand_in {}; + +/** The error public_key and export_secret return, when set; import always succeeds. */ +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the knob a test turns +boost::system::error_code failing_stand_in_error; + +/** The knob's error, or success. */ +boost::system::result knob() noexcept { + if (failing_stand_in_error) { + return failing_stand_in_error; + } + return {}; +} + +} // namespace +} // namespace webcpp::test + +namespace webcpp::crypto::detail { + +/** The stand-in's Ed25519 key engine: its state holds nothing. */ +template <> +struct ed25519_engine { + using state = ed25519_state; + + /** Succeeds. */ + [[nodiscard]] static boost::system::result import_secret( + state& /*keyed_state*/, std::span /*seed_bytes*/) noexcept { + return {}; + } + + /** Writes zeros, or returns the knob's error. */ + [[nodiscard]] static boost::system::result public_key( + state const& /*keyed_state*/, std::span output_bytes) noexcept { + std::ranges::fill(output_bytes, std::uint8_t{0}); + return test::knob(); + } + + /** Writes zeros, or returns the knob's error. */ + [[nodiscard]] static boost::system::result export_secret( + state const& /*keyed_state*/, std::span output_bytes) noexcept { + std::ranges::fill(output_bytes, std::uint8_t{0}); + return test::knob(); + } + + /** Nothing to move. */ + static void move(state& /*target_state*/, state& /*source_state*/) noexcept {} + + /** Nothing to wipe. */ + static void reset(state& /*keyed_state*/) noexcept {} +}; + +/** The stand-in's P-256 key engine: its state holds nothing. */ +template <> +struct p_curve_engine { + using state = p_curve_state; + + /** Succeeds. */ + [[nodiscard]] static boost::system::result import_secret( + state& /*keyed_state*/, std::span /*scalar_bytes*/) noexcept { + return {}; + } + + /** Writes zeros, or returns the knob's error. */ + [[nodiscard]] static boost::system::result public_key( + state const& /*keyed_state*/, std::span output_bytes) noexcept { + std::ranges::fill(output_bytes, std::uint8_t{0}); + return test::knob(); + } + + /** Writes zeros, or returns the knob's error. */ + [[nodiscard]] static boost::system::result export_secret( + state const& /*keyed_state*/, std::span output_bytes) noexcept { + std::ranges::fill(output_bytes, std::uint8_t{0}); + return test::knob(); + } + + /** Nothing to move. */ + static void move(state& /*target_state*/, state& /*source_state*/) noexcept {} + + /** Nothing to wipe. */ + static void reset(state& /*keyed_state*/) noexcept {} +}; + +} // namespace webcpp::crypto::detail + +namespace { + +namespace crypto = webcpp::crypto; +namespace test = webcpp::test; + +using ed25519_keypair = crypto::curves::ed25519::basic_keypair; +using p256_keypair = crypto::curves::p256::basic_keypair; + +/** Whether `made` failed with the engine's error. */ +template +bool failed_with_backend_failure(Result const& made) { + return !made.has_value() && made.error() == crypto::error::backend_failure; +} + +void ed25519_errors_passed_on() { + test::failing_stand_in_error = {}; + std::array const seed{1}; + auto const key = ed25519_keypair::from_secret(seed).value(); + BOOST_TEST(key.public_key().has_value()); + + test::failing_stand_in_error = crypto::error::backend_failure; + BOOST_TEST(failed_with_backend_failure(key.public_key())); + BOOST_TEST(failed_with_backend_failure(key.secret())); + + // The PKCS#8 encode exports first: on the engine's error it writes nothing. + std::array output{}; + std::ranges::fill(output, std::uint8_t{0xa5}); + auto const written = + webcpp::codecs::value_codec::encode( + crypto::formats::pkcs8, key, output); + BOOST_TEST(failed_with_backend_failure(written)); + BOOST_TEST(std::ranges::all_of(output, [](std::uint8_t byte) { return byte == 0xa5; })); + BOOST_TEST(failed_with_backend_failure(webcpp::codecs::encode(crypto::formats::pkcs8, key))); + test::failing_stand_in_error = {}; +} + +void p256_errors_passed_on() { + test::failing_stand_in_error = {}; + std::array scalar{}; + scalar.back() = 1; + auto const key = p256_keypair::from_secret(scalar).value(); + BOOST_TEST(key.secret().has_value()); + + test::failing_stand_in_error = crypto::error::backend_failure; + BOOST_TEST(failed_with_backend_failure(key.public_key())); + BOOST_TEST(failed_with_backend_failure(key.secret())); + test::failing_stand_in_error = {}; +} + +} // namespace + +int main() { + ed25519_errors_passed_on(); + p256_errors_passed_on(); + return test::exit_status(boost::report_errors()); +} diff --git a/test/messages/Jamfile b/test/messages/Jamfile index 33eb20b..24d4924 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -136,6 +136,16 @@ build-project verify_free_asynchronous_backend ; build-project sign_asynchronous_backend ; build-project agree_asynchronous_backend ; build-project x25519_asynchronous_backend ; +build-project opaque_async_synchronous ; +build-project opaque_keys_kept ; +build-project opaque_async_from_secret ; +build-project opaque_async_engine_missing ; +build-project kept_async_engine_imports ; +build-project p256_prehashed_message_only ; +build-project p256_operation_named ; +build-project secp256k1_other_backend_first ; +build-project chacha20_capability_missing ; +build-project secretbox_capability_missing ; build-project seal_asynchronous_backend ; build-project open_asynchronous_backend ; build-project verify_member_ed25519_ecdsa ; diff --git a/test/messages/chacha20_capability_missing/Jamfile b/test/messages/chacha20_capability_missing/Jamfile new file mode 100644 index 0000000..c2e22b0 --- /dev/null +++ b/test/messages/chacha20_capability_missing/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the assertion is the compile's only error, so the engine's own error, +# of the apply it lacks, after it fails the test; its notes are checked, the +# concept's and the operation's. +webcpp.compile-diagnostic chacha20_capability_missing : chacha20_capability_missing.cpp + : + : native wasip2 wasip3 : alone ; diff --git a/test/messages/chacha20_capability_missing/chacha20_capability_missing.cpp b/test/messages/chacha20_capability_missing/chacha20_capability_missing.cpp new file mode 100644 index 0000000..1f91ee9 --- /dev/null +++ b/test/messages/chacha20_capability_missing/chacha20_capability_missing.cpp @@ -0,0 +1,89 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// On a test-only backend whose ChaCha20 engine, marked as its own, is keyed but has no apply, the +// cipher's from_key and apply_keystream stop with the assertion that names the family's capability, +// chacha20, and the compiler's notes name the concept and the operation the engine lacks, apply; +// one error, the capability's, asked by both members (backend-concepts design D5, D9: the symmetric +// families). + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/crypto/ciphers/stream_cipher.hpp:* {{webcpp::crypto: this backend has ChaCha20 but not crypto::capabilities::chacha20: the stream cipher is not available on it.}} +// expected-note@webcpp/crypto/ciphers/stream_cipher.hpp:* {{because 'backend::stream_cipher<}} +// expected-note@webcpp/crypto/detail/backend/symmetric.hpp:* {{no member named 'apply'}} +// clang-format on +#include +#include +#include +#include + +#include + +#include +#include +#include + +namespace { + +/** A test-only backend whose ChaCha20 engine is keyed but has no apply. */ +struct keyed_only {}; + +} // namespace + +namespace webcpp::crypto::detail { + +/** ChaCha20's engine on that backend: init, move and reset, and no apply. */ +template <> +struct stream_engine { + /** The state. */ + using state = stream_state; + + /** Keys a state. */ + [[nodiscard]] static boost::system::result init( + state& /*cipher_state*/, std::span /*key_bytes*/) noexcept { + return error::backend_failure; + } + + /** Moves a state. */ + static void move(state& /*target_state*/, state& /*source_state*/) noexcept {} + + /** Wipes a state. */ + static void reset(state& /*cipher_state*/) noexcept {} +}; + +/** The engine is this program's own, as a shipped backend's is (design D9). */ +template <> +inline constexpr bool specialized_engine_v> = true; + +} // namespace webcpp::crypto::detail + +namespace { + +using cipher_type = + webcpp::crypto::ciphers::basic_chacha20; + +/** Makes the cipher under a key on that backend. */ +bool keyed() { + std::array const key_bytes{}; + return cipher_type::from_key(key_bytes).has_value(); +} + +/** Applies the keystream with the cipher of that backend. */ +bool applied(cipher_type& cipher, std::span data_bytes) { + std::array const nonce_bytes{}; + return cipher.apply_keystream(nonce_bytes, data_bytes, 1).has_value(); +} + +} // namespace + +// The functions are compiled, which is the test; they are never run. +int main() { + static_cast(&keyed); + static_cast(&applied); + return 0; +} diff --git a/test/messages/kept_async_engine_imports/Jamfile b/test/messages/kept_async_engine_imports/Jamfile new file mode 100644 index 0000000..8f9b93d --- /dev/null +++ b/test/messages/kept_async_engine_imports/Jamfile @@ -0,0 +1,17 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the trait's refusal is the compile's only error, and a build that +# compiles the engine's import instead fails the test. The opaque backend's +# header includes BearSSL's and libsodium's, whose usage requirements give +# their include paths. +webcpp.compile-diagnostic kept_async_engine_imports : kept_async_engine_imports.cpp + : /third_party//bearssl /third_party//sodium /webcpp/asio//asio + : native wasip2 wasip3 : alone ; diff --git a/test/messages/kept_async_engine_imports/kept_async_engine_imports.cpp b/test/messages/kept_async_engine_imports/kept_async_engine_imports.cpp new file mode 100644 index 0000000..0ebf875 --- /dev/null +++ b/test/messages/kept_async_engine_imports/kept_async_engine_imports.cpp @@ -0,0 +1,111 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// On a backend that completes by itself and keeps its keys (crypto::imports_secret_keys_v false), +// a P-256 key pair's async_from_secret stops with the import trait's refusal even where the +// backend's engine has an async_import_secret: the trait speaks before any capability, as the +// synchronous from_secret's does (backend-concepts design D6's amendment, D9). The backend here is +// this test's own: the opaque backend's engines, and an asynchronous engine whose from_secret +// would import. + +// 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: this backend keeps its keys: no secret key enters it (crypto::imports_secret_keys_v is false), so async_from_secret is not available on it; make a key with async_generate.}} +// clang-format on +#include "../../backends/opaque.hpp" + +#include +#include +#include + +#include +#include + +#include +#include +#include + +namespace webcpp::test::kept_importing { + +/** A backend that completes by itself, keeps its keys, and whose engine would import one. */ +struct kept_importing {}; + +} // namespace webcpp::test::kept_importing + +namespace webcpp::crypto::detail { + +/** P-256's state: the opaque backend's handle. */ +template <> +struct p_curve_state + : test::opaque_backend::handle_state {}; + +/** P-256's engine: the opaque backend's. */ +template <> +struct p_curve_engine + : test::opaque_backend::p256_engine {}; + +/** The engine is this test's own, as a shipped backend's is. */ +template <> +inline constexpr bool + specialized_engine_v> = + true; + +/** The backend completes by itself. */ +template <> +inline constexpr bool asynchronous_backend_v = true; + +/** An asynchronous engine with `from_secret`, which the import trait must refuse before it. */ +template <> +struct async_engine { + /** + * A key pair from its secret bytes, which this backend's trait says never enter it. + * + * @tparam Keypair P-256's key pair on this backend. + * @param completion_executor The executor the completion is posted to. + * @param secret_bytes The secret bytes. + * @param completion_token The completion token, of signature `void(error_code, Keypair)`. + * @return What the completion token's `async_result` gives. + */ + template + static auto from_secret(Executor const& completion_executor, + std::span secret_bytes, + CompletionToken&& completion_token) { + static_cast(secret_bytes); + return complete_by_post(completion_executor, completion_token, []() noexcept { + return boost::system::result(error::backend_failure); + }); + } +}; + +} // namespace webcpp::crypto::detail + +namespace { + +using p256_keypair = + webcpp::crypto::curves::p256::basic_keypair; + +static_assert( + webcpp::crypto::detail::backend::async_import_secret< + webcpp::crypto::detail::async_engine, + p256_keypair, webcpp::asio::io_context::executor_type, + void (*)(boost::system::error_code, p256_keypair)>, + "the stand-in engine has the capability, so only the trait can refuse"); + +/** Makes a P-256 key pair from a scalar, asynchronously, on that backend. */ +void imported(webcpp::asio::io_context& context) { + static constexpr std::array scalar{1}; + p256_keypair::async_from_secret(context.get_executor(), scalar, + [](boost::system::error_code, p256_keypair) {}); +} + +} // namespace + +// The function is compiled, which is the test; it is never run. +int main() { + static_cast(&imported); + return 0; +} diff --git a/test/messages/opaque_async_engine_missing/Jamfile b/test/messages/opaque_async_engine_missing/Jamfile new file mode 100644 index 0000000..7c0c7c9 --- /dev/null +++ b/test/messages/opaque_async_engine_missing/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the two assertions are the compile's only errors, so an engine's error +# after it fails the test. The opaque backend's header includes BearSSL's and +# libsodium's, whose usage requirements give their include paths. +webcpp.compile-diagnostic opaque_async_engine_missing : opaque_async_engine_missing.cpp + : /third_party//bearssl /third_party//sodium /webcpp/asio//asio + : native wasip2 wasip3 : alone ; diff --git a/test/messages/opaque_async_engine_missing/opaque_async_engine_missing.cpp b/test/messages/opaque_async_engine_missing/opaque_async_engine_missing.cpp new file mode 100644 index 0000000..c246955 --- /dev/null +++ b/test/messages/opaque_async_engine_missing/opaque_async_engine_missing.cpp @@ -0,0 +1,54 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// On the test-only opaque backend's form that completes by itself (test/backends/opaque.hpp), +// whose asynchronous engine verifies P-256 alone, Ed25519's async_verify stops with the assertion +// that names the engine's missing form, async_verify, and with that error alone: the engine is +// called only in the branch the form opens, and the other completes with the operation's own +// result (backend-concepts design D9, review 3.2's M4). The key and the signature are parameters +// of their caller. + +// 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: this backend completes by itself, and its engine has no async_verify: async_verify is not available on it.}} +// clang-format on +#include "../../backends/opaque.hpp" + +#include +#include +#include +#include + +#include + +#include +#include +#include + +namespace { + +namespace crypto = webcpp::crypto; +using webcpp::test::opaque_backend::opaque_async; + +/** Verifies an Ed25519 signature of a message, asynchronously, on that form. */ +void verified(webcpp::asio::io_context& context, + crypto::curves::ed25519::public_key const& public_key, + crypto::curves::ed25519::signature const& signature) { + static constexpr std::array message{1, 2, 3}; + crypto::async_verify(context.get_executor(), crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, signature, + std::span(message), public_key, + [](boost::system::error_code) {}); +} + +} // namespace + +// The functions are compiled, which is the test; they are never run. +int main() { + static_cast(&verified); + return 0; +} diff --git a/test/messages/opaque_async_from_secret/Jamfile b/test/messages/opaque_async_from_secret/Jamfile new file mode 100644 index 0000000..c33490f --- /dev/null +++ b/test/messages/opaque_async_from_secret/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the trait's refusal is the compile's only error, so an engine's error +# after it fails the test. The opaque backend's header includes BearSSL's and +# libsodium's, whose usage requirements give their include paths. +webcpp.compile-diagnostic opaque_async_from_secret : opaque_async_from_secret.cpp + : /third_party//bearssl /third_party//sodium /webcpp/asio//asio + : native wasip2 wasip3 : alone ; diff --git a/test/messages/opaque_async_from_secret/opaque_async_from_secret.cpp b/test/messages/opaque_async_from_secret/opaque_async_from_secret.cpp new file mode 100644 index 0000000..ed6c750 --- /dev/null +++ b/test/messages/opaque_async_from_secret/opaque_async_from_secret.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) + +// On the test-only opaque backend's form that completes by itself (test/backends/opaque.hpp), whose +// keys never leave it and whose engine has no async_import_secret, a P-256 key pair's +// async_from_secret stops with the refusal of the import trait, which names imports_secret_keys_v +// and async_generate, and with that error alone (backend-concepts design D6's amendment, D9). + +// 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: this backend keeps its keys: no secret key enters it (crypto::imports_secret_keys_v is false), so async_from_secret is not available on it; make a key with async_generate.}} +// clang-format on +#include "../../backends/opaque.hpp" + +#include +#include +#include + +#include + +#include +#include + +namespace { + +using p256_keypair = + webcpp::crypto::curves::p256::basic_keypair; + +/** Makes a P-256 key pair from a scalar, asynchronously, on that form. */ +void imported(webcpp::asio::io_context& context) { + static constexpr std::array scalar{1}; + p256_keypair::async_from_secret(context.get_executor(), scalar, + [](boost::system::error_code, p256_keypair) {}); +} + +} // namespace + +// The function is compiled, which is the test; it is never run. +int main() { + static_cast(&imported); + return 0; +} diff --git a/test/messages/opaque_async_synchronous/Jamfile b/test/messages/opaque_async_synchronous/Jamfile new file mode 100644 index 0000000..2fa605b --- /dev/null +++ b/test/messages/opaque_async_synchronous/Jamfile @@ -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) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusals are the compile's only errors, so a regression that puts +# another error before or after them fails the test. The opaque backend's +# header includes BearSSL's and libsodium's, whose usage requirements give +# their include paths. +webcpp.compile-diagnostic opaque_async_synchronous : opaque_async_synchronous.cpp + : /third_party//bearssl /third_party//sodium + /webcpp/asio//asio + : native wasip2 wasip3 : alone ; diff --git a/test/messages/opaque_async_synchronous/opaque_async_synchronous.cpp b/test/messages/opaque_async_synchronous/opaque_async_synchronous.cpp new file mode 100644 index 0000000..07ee9f5 --- /dev/null +++ b/test/messages/opaque_async_synchronous/opaque_async_synchronous.cpp @@ -0,0 +1,76 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// On the test-only opaque backend's form that completes by itself (test/backends/opaque.hpp, +// whose engines do draw, sign and agree), a P-256 key pair's generate, sign and agree, and an +// X25519 key pair's generate and agree, each stop with the refusal that names its asynchronous +// form, and with those errors alone: the refusal speaks before the engine, which has the operation, +// is reached. The key pairs and the peer are parameters of their callers. + +// 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: generate on this backend completes asynchronously: call async_generate.}} +// expected-error@webcpp/crypto/curves/p256.hpp:* {{webcpp::crypto: sign on this backend completes asynchronously: call async_sign.}} +// expected-error@webcpp/crypto/curves/p256.hpp:* {{webcpp::crypto: agree on this backend completes asynchronously: call async_agree.}} +// expected-error@webcpp/crypto/curves/x25519.hpp:* {{webcpp::crypto: generate on this backend completes asynchronously: call async_generate.}} +// expected-error@webcpp/crypto/curves/x25519.hpp:* {{webcpp::crypto: agree on this backend completes asynchronously: call async_agree.}} +// clang-format on +#include "../../backends/opaque.hpp" + +#include +#include +#include +#include + +#include +#include + +namespace { + +namespace crypto = webcpp::crypto; +using webcpp::test::opaque_backend::opaque_async; +using p256_keypair = crypto::curves::p256::basic_keypair; + +/** Draws a P-256 key pair on the form that completes by itself. */ +bool drawn_p256() { + return p256_keypair::generate().has_value(); +} + +/** Signs with a P-256 key pair of that form. */ +bool signed_message(p256_keypair const& key) { + std::array const message{'h', 'e', 'l', 'l', 'o'}; + return crypto::sign(key, crypto::signing_schemes::ecdsa_sha256, message).has_value(); +} + +/** Agrees with a P-256 key pair and a peer of that form. */ +bool agreed(p256_keypair const& key, + crypto::curves::p256::basic_public_key const& peer) { + return crypto::agree(key, peer).has_value(); +} + +/** Draws an X25519 key pair on that form. */ +bool drawn_x25519() { + return crypto::curves::x25519::basic_keypair::generate().has_value(); +} + +/** Agrees with an X25519 key pair of that form. */ +bool agreed_x25519(crypto::curves::x25519::basic_keypair const& key, + crypto::curves::x25519::public_key const& peer) { + return crypto::agree(key, peer).has_value(); +} + +} // namespace + +// The functions are compiled, which is the test; they are never run. +int main() { + static_cast(&drawn_p256); + static_cast(&signed_message); + static_cast(&agreed); + static_cast(&drawn_x25519); + static_cast(&agreed_x25519); + return 0; +} diff --git a/test/messages/opaque_keys_kept/Jamfile b/test/messages/opaque_keys_kept/Jamfile new file mode 100644 index 0000000..657c506 --- /dev/null +++ b/test/messages/opaque_keys_kept/Jamfile @@ -0,0 +1,17 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the trait's refusals are the compile's only errors, so a capability +# assertion or an engine's error after them fails the test. The opaque backend's +# header includes BearSSL's and libsodium's, whose usage requirements give their +# include paths. +webcpp.compile-diagnostic opaque_keys_kept : opaque_keys_kept.cpp + : /third_party//bearssl /third_party//sodium /webcpp/asio//asio + : native wasip2 wasip3 : alone ; diff --git a/test/messages/opaque_keys_kept/opaque_keys_kept.cpp b/test/messages/opaque_keys_kept/opaque_keys_kept.cpp new file mode 100644 index 0000000..e852e5c --- /dev/null +++ b/test/messages/opaque_keys_kept/opaque_keys_kept.cpp @@ -0,0 +1,89 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// On the test-only opaque backend (test/backends/opaque.hpp), whose keys never leave it, a P-256 +// key pair's from_secret and secret(), an X25519 key pair's from_secret and secret(), a P-256 key +// pair's pkcs8 and an X25519 key pair's raw form each stop with the refusal of the secret-key +// trait, which names crypto::imports_secret_keys_v or crypto::exports_secret_keys_v (raw with its +// own sentence, pkcs8 with the one pem(pkcs8) shares), and with those errors alone: the trait +// speaks before the capability its engine lacks (p256_import, p256_export, x25519_import, +// x25519_export), whose assertion would name it (backend-concepts design D3's and D6's amendments, +// D9). The key pairs are parameters of their callers. + +// 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: this backend keeps its keys: no secret key enters it (crypto::imports_secret_keys_v is false), so P-256's from_secret, which needs crypto::capabilities::p256_import, is not available on it; make a key with generate.}} +// expected-error@webcpp/crypto/curves/p256.hpp:* {{webcpp::crypto: this backend keeps its keys: no secret key leaves it (crypto::exports_secret_keys_v is false), so P-256's secret(), which needs crypto::capabilities::p256_export, is not available on it.}} +// expected-error@webcpp/crypto/curves/x25519.hpp:* {{webcpp::crypto: this backend keeps its keys: no secret key enters it (crypto::imports_secret_keys_v is false), so X25519's from_secret, which needs crypto::capabilities::x25519_import, is not available on it; make a key with generate.}} +// expected-error@webcpp/crypto/curves/x25519.hpp:* {{webcpp::crypto: this backend keeps its keys: no secret key leaves it (crypto::exports_secret_keys_v is false), so X25519's secret(), which needs crypto::capabilities::x25519_export, is not available on it.}} +// expected-error@webcpp/crypto/formats.hpp:* {{webcpp::crypto: this backend keeps its keys: no secret key leaves or enters it (crypto::exports_secret_keys_v or crypto::imports_secret_keys_v is false), so a key pair's formats::raw, its secret key's bytes, is not available on it}} +// expected-error@webcpp/crypto/formats.hpp:* {{webcpp::crypto: this backend keeps its keys: no secret key leaves or enters it (crypto::exports_secret_keys_v or crypto::imports_secret_keys_v is false), so a key pair's formats::pkcs8 and formats::pem(formats::pkcs8) are not available on it}} +// clang-format on +#include "../../backends/opaque.hpp" + +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace crypto = webcpp::crypto; +using webcpp::test::opaque_backend::opaque; +using p256_keypair = crypto::curves::p256::basic_keypair; +using x25519_keypair = crypto::curves::x25519::basic_keypair; + +/** Makes a P-256 key pair from a scalar on the opaque backend. */ +bool imported_p256() { + std::array const scalar{1}; + return p256_keypair::from_secret(scalar).has_value(); +} + +/** Asks a P-256 key pair of the opaque backend for its scalar. */ +bool exported_p256(p256_keypair const& key_pair) { + return key_pair.secret().has_value(); +} + +/** Makes an X25519 key pair from a secret key on the opaque backend. */ +bool imported_x25519() { + std::array const secret_key{1}; + return x25519_keypair::from_secret(secret_key).has_value(); +} + +/** Asks an X25519 key pair of the opaque backend for its secret key. */ +bool exported_x25519(x25519_keypair const& key_pair) { + return key_pair.secret().has_value(); +} + +/** Encodes a P-256 key pair of the opaque backend in PKCS#8. */ +bool p256_pkcs8(p256_keypair const& key_pair) { + return codecs::encode(crypto::formats::pkcs8, key_pair).has_value(); +} + +/** Encodes an X25519 key pair of the opaque backend in its raw form. */ +bool x25519_raw(x25519_keypair const& key_pair) { + return codecs::encode(crypto::formats::raw, key_pair).has_value(); +} + +} // namespace + +// The functions are compiled, which is the test; they are never run. +int main() { + static_cast(&imported_p256); + static_cast(&exported_p256); + static_cast(&imported_x25519); + static_cast(&exported_x25519); + static_cast(&p256_pkcs8); + static_cast(&x25519_raw); + return 0; +} diff --git a/test/messages/p256_operation_named/Jamfile b/test/messages/p256_operation_named/Jamfile new file mode 100644 index 0000000..19c1092 --- /dev/null +++ b/test/messages/p256_operation_named/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the assertion is the compile's only error, so the engine's own error, +# of the decompress it lacks, after it fails the test; its notes are checked, +# the concept's and the operation's. +webcpp.compile-diagnostic p256_operation_named : p256_operation_named.cpp + : + : native wasip2 wasip3 : alone ; diff --git a/test/messages/p256_operation_named/p256_operation_named.cpp b/test/messages/p256_operation_named/p256_operation_named.cpp new file mode 100644 index 0000000..6769afa --- /dev/null +++ b/test/messages/p256_operation_named/p256_operation_named.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) + +// On a test-only P-256 backend whose engine checks a point but has no decompress +// (test/backends/message_only.hpp), a public key's from_bytes stops with the assertion that names +// the capability it uses, p256_point, and the compiler's notes name the operation the engine lacks, +// decompress: the diagnostic of backend-concepts design D5, the concept and the operation, at the +// member that needs them (D9, ruling 1.1-M7). + +// 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: this backend has P-256 but not crypto::capabilities::p256_point: a public key's point cannot be checked, and from_bytes is not available on it.}} +// expected-note@webcpp/crypto/curves/p256.hpp:* {{does not satisfy 'p256_point'}} +// expected-note@webcpp/crypto/detail/backend/p256.hpp:* {{because 'Engine::decompress(parity_prefix, x_bytes, y_output)' would be invalid: no member named 'decompress'}} +// clang-format on +#include "../../backends/message_only.hpp" + +#include + +#include +#include + +/** Makes a public key of the message-only backend from a compressed point. */ +int main() { + std::array point_bytes{}; + point_bytes[0] = 0x02; + auto const made_key = webcpp::crypto::curves::p256::basic_public_key< + webcpp::test::message_only_backend::message_only>::from_bytes(point_bytes); + return made_key ? 0 : 1; +} diff --git a/test/messages/p256_prehashed_message_only/Jamfile b/test/messages/p256_prehashed_message_only/Jamfile new file mode 100644 index 0000000..22e1a0d --- /dev/null +++ b/test/messages/p256_prehashed_message_only/Jamfile @@ -0,0 +1,15 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the assertions are the compile's only errors, so an engine's error +# after them, of the digest form it lacks, fails the test. +webcpp.compile-diagnostic p256_prehashed_message_only : p256_prehashed_message_only.cpp + : + : native wasip2 wasip3 : alone ; diff --git a/test/messages/p256_prehashed_message_only/p256_prehashed_message_only.cpp b/test/messages/p256_prehashed_message_only/p256_prehashed_message_only.cpp new file mode 100644 index 0000000..7067f0a --- /dev/null +++ b/test/messages/p256_prehashed_message_only/p256_prehashed_message_only.cpp @@ -0,0 +1,82 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// On a test-only P-256 backend whose engine signs and verifies a message, never a digest +// (test/backends/message_only.hpp, the form WebCrypto's ECDSA has), sign and verify of +// crypto::signing_schemes::prehashed each stop with the assertion that names the digest form's +// capability, crypto::capabilities::p256_ecdsa_signing or p256_ecdsa_verifying, once though each +// is asked by crypto's function and by the member, and with those errors alone (backend-concepts +// design D9, ruling 1.2-I2); a message signs and verifies there, which p256_message_form_test +// runs. The key pair and the public key are parameters of their callers. + +// 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: this backend has P-256 but not crypto::capabilities::p256_ecdsa_signing: sign of crypto::signing_schemes::prehashed is not available on it; sign the message.}} +// expected-error@webcpp/crypto/curves/p256.hpp:* {{webcpp::crypto: this backend has P-256 but not crypto::capabilities::p256_ecdsa_verifying: verify of crypto::signing_schemes::prehashed is not available on it; verify the message.}} +// clang-format on +#include "../../backends/message_only.hpp" + +#include +#include +#include + +#include +#include + +namespace { + +namespace crypto = webcpp::crypto; +using webcpp::test::message_only_backend::message_only; +using p256_keypair = crypto::curves::p256::basic_keypair; +using p256_public_key = crypto::curves::p256::basic_public_key; + +/** Signs a digest with a key pair of the message-only backend, by crypto's function. */ +bool signed_digest(p256_keypair const& key_pair) { + std::array const digest{}; + return crypto::sign(key_pair, crypto::signing_schemes::ecdsa_sha256, + crypto::signing_schemes::prehashed{digest}) + .has_value(); +} + +/** Signs a digest with a key pair of the message-only backend, by the member. */ +bool member_signed_digest(p256_keypair const& key_pair) { + std::array const digest{}; + return key_pair + .sign(crypto::signing_schemes::ecdsa_sha256, crypto::signing_schemes::prehashed{digest}) + .has_value(); +} + +/** Verifies a signature of a digest with a public key of the message-only backend. */ +bool verified_digest(p256_public_key const& public_key, + crypto::curves::p256::ecdsa_signature const& signature) { + std::array const digest{}; + return crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::any_s, signature, + crypto::signing_schemes::prehashed{digest}, public_key) + .has_value(); +} + +/** Verifies a signature of a digest by the member, under the other policy. */ +bool member_verified_digest(p256_public_key const& public_key, + crypto::curves::p256::ecdsa_signature const& signature) { + std::array const digest{}; + return public_key + .verify(crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::low_s_only, + signature, crypto::signing_schemes::prehashed{digest}) + .has_value(); +} + +} // namespace + +// The functions are compiled, which is the test; they are never run. +int main() { + static_cast(&signed_digest); + static_cast(&member_signed_digest); + static_cast(&verified_digest); + static_cast(&member_verified_digest); + return 0; +} diff --git a/test/messages/secp256k1_other_backend_first/Jamfile b/test/messages/secp256k1_other_backend_first/Jamfile new file mode 100644 index 0000000..1df014f --- /dev/null +++ b/test/messages/secp256k1_other_backend_first/Jamfile @@ -0,0 +1,15 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so an engine's error or a +# capability assertion after it fails the test. +webcpp.compile-diagnostic secp256k1_other_backend_first : secp256k1_other_backend_first.cpp + : /third_party//bearssl /third_party//secp256k1 + : native wasip2 : alone ; diff --git a/test/messages/secp256k1_other_backend_first/secp256k1_other_backend_first.cpp b/test/messages/secp256k1_other_backend_first/secp256k1_other_backend_first.cpp new file mode 100644 index 0000000..b371109 --- /dev/null +++ b/test/messages/secp256k1_other_backend_first/secp256k1_other_backend_first.cpp @@ -0,0 +1,47 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// secp256k1's key pair and public key refuse a backend other than libsecp256k1 with the family's +// generated refusal (secp256k1_refuses_others), and with that error alone: no secp256k1_engine is +// named, since it has no primary template, and no capability assertion speaks after it +// (backend-concepts design D9, review 2.2 M5). + +// 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: bearssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten).}} +// clang-format on +#include +#include + +#include +#include + +namespace { + +namespace secp256k1 = webcpp::crypto::curves::secp256k1; +using webcpp::crypto::backends::bearssl; + +/** Makes a key pair from a scalar on BearSSL. */ +bool imported() { + std::array const scalar{1}; + return secp256k1::basic_keypair::from_secret(scalar).has_value(); +} + +/** Makes a public key from a point on BearSSL. */ +bool parsed() { + std::array const point_bytes{}; + return secp256k1::public_key::from_bytes(point_bytes).has_value(); +} + +} // namespace + +// The functions are compiled, which is the test; they are never run. +int main() { + static_cast(&imported); + static_cast(&parsed); + return 0; +} diff --git a/test/messages/secretbox_capability_missing/Jamfile b/test/messages/secretbox_capability_missing/Jamfile new file mode 100644 index 0000000..a6bef50 --- /dev/null +++ b/test/messages/secretbox_capability_missing/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# alone: the assertion is the compile's only error, so the engine's own error, +# of the open it lacks, after it fails the test; its notes are checked, the +# concept's and the operation's. +webcpp.compile-diagnostic secretbox_capability_missing : secretbox_capability_missing.cpp + : + : native wasip2 wasip3 : alone ; diff --git a/test/messages/secretbox_capability_missing/secretbox_capability_missing.cpp b/test/messages/secretbox_capability_missing/secretbox_capability_missing.cpp new file mode 100644 index 0000000..6e74772 --- /dev/null +++ b/test/messages/secretbox_capability_missing/secretbox_capability_missing.cpp @@ -0,0 +1,92 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// On a test-only backend whose XSalsa20-Poly1305 secret box engine, marked as its own, seals and +// does not open, the box's open stops with the assertion that names the family's capability, +// secretbox_xsalsa20poly1305, and the compiler's notes name the concept and the operation the +// engine lacks, open (backend-concepts design D5, D9: the boxes). The box is a parameter of its +// caller. + +// 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/secret_key_encryption/secretbox.hpp:* {{webcpp::crypto: this backend has the XSalsa20-Poly1305 secret box but not crypto::capabilities::secretbox_xsalsa20poly1305: the box is not available on it.}} +// expected-note@webcpp/crypto/secret_key_encryption/secretbox.hpp:* {{because 'backend::authenticated_box<}} +// expected-note@webcpp/crypto/detail/backend/symmetric.hpp:* {{no member named 'open'}} +// clang-format on +#include +#include +#include +#include + +#include +#include + +#include +#include +#include + +namespace { + +/** A test-only backend whose secret box engine seals and does not open. */ +struct sealing_only {}; + +} // namespace + +namespace webcpp::crypto::detail { + +/** The XSalsa20-Poly1305 secret box's engine on that backend: no open. */ +template <> +struct secretbox_engine { + /** The state. */ + using state = secretbox_state; + + /** Keys a state. */ + [[nodiscard]] static boost::system::result init( + state& /*box_state*/, std::span /*key_bytes*/) noexcept { + return error::backend_failure; + } + + /** Seals in place. */ + [[nodiscard]] static boost::system::result seal( + state& /*box_state*/, std::span /*nonce_bytes*/, + std::span /*data_bytes*/, boost::hash2::digest<16>& /*tag_output*/) noexcept { + return error::backend_failure; + } + + /** Moves a state. */ + static void move(state& /*target_state*/, state& /*source_state*/) noexcept {} + + /** Wipes a state. */ + static void reset(state& /*box_state*/) noexcept {} +}; + +/** The engine is this program's own, as a shipped backend's is (design D9). */ +template <> +inline constexpr bool + specialized_engine_v> = + true; + +} // namespace webcpp::crypto::detail + +namespace { + +using box_type = webcpp::crypto::secret_key_encryption::secretbox; + +/** Opens a box with the secret box of that backend. */ +bool opened(box_type& box, std::span data_bytes, + std::span tag_bytes) { + std::array const nonce_bytes{}; + return box.open(nonce_bytes, data_bytes, tag_bytes).has_value(); +} + +} // namespace + +// The function is compiled, which is the test; it is never run. +int main() { + static_cast(&opened); + return 0; +} diff --git a/test/messages/x25519_asynchronous_backend/x25519_asynchronous_backend.cpp b/test/messages/x25519_asynchronous_backend/x25519_asynchronous_backend.cpp index 793b9bf..f223eae 100644 --- a/test/messages/x25519_asynchronous_backend/x25519_asynchronous_backend.cpp +++ b/test/messages/x25519_asynchronous_backend/x25519_asynchronous_backend.cpp @@ -7,8 +7,8 @@ // An X25519 key pair's from_secret, generate and agree (through the free crypto::agree) on a // backend that completes by itself (a stand-in whose detail::asynchronous_backend_v is true) each // stop with the refusal that names its asynchronous form, and with those errors alone: no engine -// is reached. The key pair and the peer are parameters of agree's caller, since making them would -// run the stand-in's engine. +// operation is reached. The stand-in's engine has only what the key pair's special members call, +// move and reset; the key pair and the peer are parameters of agree's caller. // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. @@ -30,8 +30,22 @@ struct stand_in_browser {}; } // namespace +namespace webcpp::crypto::detail { + +template <> +inline constexpr bool asynchronous_backend_v = true; + +// X25519's key pair moves and resets its state: the stand-in's state holds nothing. template <> -inline constexpr bool webcpp::crypto::detail::asynchronous_backend_v = true; +struct x25519_engine { + using state = x25519_state; + + static void move(state& /*target_state*/, state& /*source_state*/) noexcept {} + + static void reset(state& /*engine_state*/) noexcept {} +}; + +} // namespace webcpp::crypto::detail namespace { diff --git a/test/msvc/Jamfile b/test/msvc/Jamfile index b13a185..2db1567 100644 --- a/test/msvc/Jamfile +++ b/test/msvc/Jamfile @@ -188,6 +188,16 @@ build-project iv_size_removed ; build-project make_removed ; build-project musig_nonce_gen_removed ; build-project musig_nonce_gen_removed_call ; +build-project opaque_async_synchronous ; +build-project opaque_keys_kept ; +build-project opaque_async_from_secret ; +build-project opaque_async_engine_missing ; +build-project kept_async_engine_imports ; +build-project p256_prehashed_message_only ; +build-project p256_operation_named ; +build-project secp256k1_other_backend_first ; +build-project chacha20_capability_missing ; +build-project secretbox_capability_missing ; build-project open_asynchronous_backend ; build-project ph_removed ; build-project prehashed_dynamic ; diff --git a/test/msvc/chacha20_capability_missing/Jamfile b/test/msvc/chacha20_capability_missing/Jamfile new file mode 100644 index 0000000..bd3e22e --- /dev/null +++ b/test/msvc/chacha20_capability_missing/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail chacha20_capability_missing : app.cpp + : /webcpp/crypto//crypto + : native ; diff --git a/test/msvc/chacha20_capability_missing/app.cpp b/test/msvc/chacha20_capability_missing/app.cpp new file mode 100644 index 0000000..d356dfe --- /dev/null +++ b/test/msvc/chacha20_capability_missing/app.cpp @@ -0,0 +1,85 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the 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 MSVC twin of test/messages/chacha20_capability_missing/chacha20_capability_missing.cpp: the +// same program does not compile on MSVC, whose text is not checked; clang checks it there. +// +// On a test-only backend whose ChaCha20 engine, marked as its own, is keyed but has no apply, the +// cipher's from_key and apply_keystream stop with the assertion that names the family's capability, +// chacha20, and the compiler's notes name the concept and the operation the engine lacks, apply; +// one error, the capability's, asked by both members (backend-concepts design D5, D9: the symmetric +// families). + +#include +#include +#include +#include + +#include + +#include +#include +#include + +namespace { + +/** A test-only backend whose ChaCha20 engine is keyed but has no apply. */ +struct keyed_only {}; + +} // namespace + +namespace webcpp::crypto::detail { + +/** ChaCha20's engine on that backend: init, move and reset, and no apply. */ +template <> +struct stream_engine { + /** The state. */ + using state = stream_state; + + /** Keys a state. */ + [[nodiscard]] static boost::system::result init( + state& /*cipher_state*/, std::span /*key_bytes*/) noexcept { + return error::backend_failure; + } + + /** Moves a state. */ + static void move(state& /*target_state*/, state& /*source_state*/) noexcept {} + + /** Wipes a state. */ + static void reset(state& /*cipher_state*/) noexcept {} +}; + +/** The engine is this program's own, as a shipped backend's is (design D9). */ +template <> +inline constexpr bool specialized_engine_v> = true; + +} // namespace webcpp::crypto::detail + +namespace { + +using cipher_type = + webcpp::crypto::ciphers::basic_chacha20; + +/** Makes the cipher under a key on that backend. */ +bool keyed() { + std::array const key_bytes{}; + return cipher_type::from_key(key_bytes).has_value(); +} + +/** Applies the keystream with the cipher of that backend. */ +bool applied(cipher_type& cipher, std::span data_bytes) { + std::array const nonce_bytes{}; + return cipher.apply_keystream(nonce_bytes, data_bytes, 1).has_value(); +} + +} // namespace + +// The functions are compiled, which is the test; they are never run. +int main() { + static_cast(&keyed); + static_cast(&applied); + return 0; +} diff --git a/test/msvc/kept_async_engine_imports/Jamfile b/test/msvc/kept_async_engine_imports/Jamfile new file mode 100644 index 0000000..477f3f3 --- /dev/null +++ b/test/msvc/kept_async_engine_imports/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 kept_async_engine_imports : app.cpp + : /webcpp/crypto//crypto /third_party//bearssl /third_party//sodium /webcpp/asio//asio + : native ; diff --git a/test/msvc/kept_async_engine_imports/app.cpp b/test/msvc/kept_async_engine_imports/app.cpp new file mode 100644 index 0000000..5a25b44 --- /dev/null +++ b/test/msvc/kept_async_engine_imports/app.cpp @@ -0,0 +1,109 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The MSVC twin of test/messages/kept_async_engine_imports/kept_async_engine_imports.cpp: the same +// program does not compile on MSVC, whose text is not checked; clang checks it there. +// +// On a backend that completes by itself and keeps its keys (crypto::imports_secret_keys_v false), +// a P-256 key pair's async_from_secret stops with the import trait's refusal even where the +// backend's engine has an async_import_secret: the trait speaks before any capability, as the +// synchronous from_secret's does (backend-concepts design D6's amendment, D9). The backend here is +// this test's own: the opaque backend's engines, and an asynchronous engine whose from_secret +// would import. + +#include "../../backends/opaque.hpp" + +#include +#include +#include + +#include +#include + +#include +#include +#include + +namespace webcpp::test::kept_importing { + +/** A backend that completes by itself, keeps its keys, and whose engine would import one. */ +struct kept_importing {}; + +} // namespace webcpp::test::kept_importing + +namespace webcpp::crypto::detail { + +/** P-256's state: the opaque backend's handle. */ +template <> +struct p_curve_state + : test::opaque_backend::handle_state {}; + +/** P-256's engine: the opaque backend's. */ +template <> +struct p_curve_engine + : test::opaque_backend::p256_engine {}; + +/** The engine is this test's own, as a shipped backend's is. */ +template <> +inline constexpr bool + specialized_engine_v> = + true; + +/** The backend completes by itself. */ +template <> +inline constexpr bool asynchronous_backend_v = true; + +/** An asynchronous engine with `from_secret`, which the import trait must refuse before it. */ +template <> +struct async_engine { + /** + * A key pair from its secret bytes, which this backend's trait says never enter it. + * + * @tparam Keypair P-256's key pair on this backend. + * @param completion_executor The executor the completion is posted to. + * @param secret_bytes The secret bytes. + * @param completion_token The completion token, of signature `void(error_code, Keypair)`. + * @return What the completion token's `async_result` gives. + */ + template + static auto from_secret(Executor const& completion_executor, + std::span secret_bytes, + CompletionToken&& completion_token) { + static_cast(secret_bytes); + return complete_by_post(completion_executor, completion_token, []() noexcept { + return boost::system::result(error::backend_failure); + }); + } +}; + +} // namespace webcpp::crypto::detail + +namespace { + +using p256_keypair = + webcpp::crypto::curves::p256::basic_keypair; + +static_assert( + webcpp::crypto::detail::backend::async_import_secret< + webcpp::crypto::detail::async_engine, + p256_keypair, webcpp::asio::io_context::executor_type, + void (*)(boost::system::error_code, p256_keypair)>, + "the stand-in engine has the capability, so only the trait can refuse"); + +/** Makes a P-256 key pair from a scalar, asynchronously, on that backend. */ +void imported(webcpp::asio::io_context& context) { + static constexpr std::array scalar{1}; + p256_keypair::async_from_secret(context.get_executor(), scalar, + [](boost::system::error_code, p256_keypair) {}); +} + +} // namespace + +// The function is compiled, which is the test; it is never run. +int main() { + static_cast(&imported); + return 0; +} diff --git a/test/msvc/opaque_async_engine_missing/Jamfile b/test/msvc/opaque_async_engine_missing/Jamfile new file mode 100644 index 0000000..dd68433 --- /dev/null +++ b/test/msvc/opaque_async_engine_missing/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 opaque_async_engine_missing : app.cpp + : /webcpp/crypto//crypto /third_party//bearssl /third_party//sodium /webcpp/asio//asio + : native ; diff --git a/test/msvc/opaque_async_engine_missing/app.cpp b/test/msvc/opaque_async_engine_missing/app.cpp new file mode 100644 index 0000000..1a57d2a --- /dev/null +++ b/test/msvc/opaque_async_engine_missing/app.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 MSVC twin of test/messages/opaque_async_engine_missing/opaque_async_engine_missing.cpp: the +// same program does not compile on MSVC, whose text is not checked; clang checks it there. +// +// On the test-only opaque backend's form that completes by itself (test/backends/opaque.hpp), +// whose asynchronous engine verifies P-256 alone, Ed25519's async_verify stops with the assertion +// that names the engine's missing form, async_verify, and with that error alone: the engine is +// called only in the branch the form opens, and the other completes with the operation's own +// result (backend-concepts design D9, review 3.2's M4). The key and the signature are parameters +// of their caller. + +#include "../../backends/opaque.hpp" + +#include +#include +#include +#include + +#include + +#include +#include +#include + +namespace { + +namespace crypto = webcpp::crypto; +using webcpp::test::opaque_backend::opaque_async; + +/** Verifies an Ed25519 signature of a message, asynchronously, on that form. */ +void verified(webcpp::asio::io_context& context, + crypto::curves::ed25519::public_key const& public_key, + crypto::curves::ed25519::signature const& signature) { + static constexpr std::array message{1, 2, 3}; + crypto::async_verify(context.get_executor(), crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, signature, + std::span(message), public_key, + [](boost::system::error_code) {}); +} + +} // namespace + +// The functions are compiled, which is the test; they are never run. +int main() { + static_cast(&verified); + return 0; +} diff --git a/test/msvc/opaque_async_from_secret/Jamfile b/test/msvc/opaque_async_from_secret/Jamfile new file mode 100644 index 0000000..3c66c30 --- /dev/null +++ b/test/msvc/opaque_async_from_secret/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 opaque_async_from_secret : app.cpp + : /webcpp/crypto//crypto /third_party//bearssl /third_party//sodium /webcpp/asio//asio + : native ; diff --git a/test/msvc/opaque_async_from_secret/app.cpp b/test/msvc/opaque_async_from_secret/app.cpp new file mode 100644 index 0000000..1fd6e3a --- /dev/null +++ b/test/msvc/opaque_async_from_secret/app.cpp @@ -0,0 +1,44 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The MSVC twin of test/messages/opaque_async_from_secret/opaque_async_from_secret.cpp: the same +// program does not compile on MSVC, whose text is not checked; clang checks it there. +// +// On the test-only opaque backend's form that completes by itself (test/backends/opaque.hpp), whose +// keys never leave it and whose engine has no async_import_secret, a P-256 key pair's +// async_from_secret stops with the refusal of the import trait, which names imports_secret_keys_v +// and async_generate, and with that error alone (backend-concepts design D6's amendment, D9). + +#include "../../backends/opaque.hpp" + +#include +#include +#include + +#include + +#include +#include + +namespace { + +using p256_keypair = + webcpp::crypto::curves::p256::basic_keypair; + +/** Makes a P-256 key pair from a scalar, asynchronously, on that form. */ +void imported(webcpp::asio::io_context& context) { + static constexpr std::array scalar{1}; + p256_keypair::async_from_secret(context.get_executor(), scalar, + [](boost::system::error_code, p256_keypair) {}); +} + +} // namespace + +// The function is compiled, which is the test; it is never run. +int main() { + static_cast(&imported); + return 0; +} diff --git a/test/msvc/opaque_async_synchronous/Jamfile b/test/msvc/opaque_async_synchronous/Jamfile new file mode 100644 index 0000000..79797f2 --- /dev/null +++ b/test/msvc/opaque_async_synchronous/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 opaque_async_synchronous : app.cpp + : /webcpp/crypto//crypto /third_party//bearssl + /third_party//sodium /webcpp/asio//asio + : native ; diff --git a/test/msvc/opaque_async_synchronous/app.cpp b/test/msvc/opaque_async_synchronous/app.cpp new file mode 100644 index 0000000..1234512 --- /dev/null +++ b/test/msvc/opaque_async_synchronous/app.cpp @@ -0,0 +1,70 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The MSVC twin of test/messages/opaque_async_synchronous/opaque_async_synchronous.cpp: the same +// program does not compile on MSVC, whose text is not checked; clang checks it there. +// +// On the test-only opaque backend's form that completes by itself (test/backends/opaque.hpp, +// whose engines do draw, sign and agree), a P-256 key pair's generate, sign and agree, and an +// X25519 key pair's generate and agree, each stop with the refusal that names its asynchronous +// form, and with those errors alone: the refusal speaks before the engine, which has the operation, +// is reached. The key pairs and the peer are parameters of their callers. + +#include "../../backends/opaque.hpp" + +#include +#include +#include +#include + +#include +#include + +namespace { + +namespace crypto = webcpp::crypto; +using webcpp::test::opaque_backend::opaque_async; +using p256_keypair = crypto::curves::p256::basic_keypair; + +/** Draws a P-256 key pair on the form that completes by itself. */ +bool drawn_p256() { + return p256_keypair::generate().has_value(); +} + +/** Signs with a P-256 key pair of that form. */ +bool signed_message(p256_keypair const& key) { + std::array const message{'h', 'e', 'l', 'l', 'o'}; + return crypto::sign(key, crypto::signing_schemes::ecdsa_sha256, message).has_value(); +} + +/** Agrees with a P-256 key pair and a peer of that form. */ +bool agreed(p256_keypair const& key, + crypto::curves::p256::basic_public_key const& peer) { + return crypto::agree(key, peer).has_value(); +} + +/** Draws an X25519 key pair on that form. */ +bool drawn_x25519() { + return crypto::curves::x25519::basic_keypair::generate().has_value(); +} + +/** Agrees with an X25519 key pair of that form. */ +bool agreed_x25519(crypto::curves::x25519::basic_keypair const& key, + crypto::curves::x25519::public_key const& peer) { + return crypto::agree(key, peer).has_value(); +} + +} // namespace + +// The functions are compiled, which is the test; they are never run. +int main() { + static_cast(&drawn_p256); + static_cast(&signed_message); + static_cast(&agreed); + static_cast(&drawn_x25519); + static_cast(&agreed_x25519); + return 0; +} diff --git a/test/msvc/opaque_keys_kept/Jamfile b/test/msvc/opaque_keys_kept/Jamfile new file mode 100644 index 0000000..0c843fa --- /dev/null +++ b/test/msvc/opaque_keys_kept/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 opaque_keys_kept : app.cpp + : /webcpp/crypto//crypto /third_party//bearssl /third_party//sodium /webcpp/asio//asio + : native ; diff --git a/test/msvc/opaque_keys_kept/app.cpp b/test/msvc/opaque_keys_kept/app.cpp new file mode 100644 index 0000000..61e1855 --- /dev/null +++ b/test/msvc/opaque_keys_kept/app.cpp @@ -0,0 +1,82 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The MSVC twin of test/messages/opaque_keys_kept/opaque_keys_kept.cpp: the same program does not +// compile on MSVC, whose text is not checked; clang checks it there. +// +// On the test-only opaque backend (test/backends/opaque.hpp), whose keys never leave it, a P-256 +// key pair's from_secret and secret(), an X25519 key pair's from_secret and secret(), a P-256 key +// pair's pkcs8 and an X25519 key pair's raw form each stop with the refusal of the secret-key +// trait, which names crypto::imports_secret_keys_v or crypto::exports_secret_keys_v (raw with its +// own sentence, pkcs8 with the one pem(pkcs8) shares), and with those errors alone: the trait +// speaks before the capability its engine lacks (p256_import, p256_export, x25519_import, +// x25519_export), whose assertion would name it (backend-concepts design D3's and D6's amendments, +// D9). The key pairs are parameters of their callers. + +#include "../../backends/opaque.hpp" + +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace crypto = webcpp::crypto; +using webcpp::test::opaque_backend::opaque; +using p256_keypair = crypto::curves::p256::basic_keypair; +using x25519_keypair = crypto::curves::x25519::basic_keypair; + +/** Makes a P-256 key pair from a scalar on the opaque backend. */ +bool imported_p256() { + std::array const scalar{1}; + return p256_keypair::from_secret(scalar).has_value(); +} + +/** Asks a P-256 key pair of the opaque backend for its scalar. */ +bool exported_p256(p256_keypair const& key_pair) { + return key_pair.secret().has_value(); +} + +/** Makes an X25519 key pair from a secret key on the opaque backend. */ +bool imported_x25519() { + std::array const secret_key{1}; + return x25519_keypair::from_secret(secret_key).has_value(); +} + +/** Asks an X25519 key pair of the opaque backend for its secret key. */ +bool exported_x25519(x25519_keypair const& key_pair) { + return key_pair.secret().has_value(); +} + +/** Encodes a P-256 key pair of the opaque backend in PKCS#8. */ +bool p256_pkcs8(p256_keypair const& key_pair) { + return codecs::encode(crypto::formats::pkcs8, key_pair).has_value(); +} + +/** Encodes an X25519 key pair of the opaque backend in its raw form. */ +bool x25519_raw(x25519_keypair const& key_pair) { + return codecs::encode(crypto::formats::raw, key_pair).has_value(); +} + +} // namespace + +// The functions are compiled, which is the test; they are never run. +int main() { + static_cast(&imported_p256); + static_cast(&exported_p256); + static_cast(&imported_x25519); + static_cast(&exported_x25519); + static_cast(&p256_pkcs8); + static_cast(&x25519_raw); + return 0; +} diff --git a/test/msvc/p256_operation_named/Jamfile b/test/msvc/p256_operation_named/Jamfile new file mode 100644 index 0000000..f3610a1 --- /dev/null +++ b/test/msvc/p256_operation_named/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 p256_operation_named : app.cpp + : /webcpp/crypto//crypto + : native ; diff --git a/test/msvc/p256_operation_named/app.cpp b/test/msvc/p256_operation_named/app.cpp new file mode 100644 index 0000000..d5d6f9f --- /dev/null +++ b/test/msvc/p256_operation_named/app.cpp @@ -0,0 +1,30 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The MSVC twin of test/messages/p256_operation_named/p256_operation_named.cpp: the same program +// does not compile on MSVC, whose text is not checked; clang checks it there. +// +// On a test-only P-256 backend whose engine checks a point but has no decompress +// (test/backends/message_only.hpp), a public key's from_bytes stops with the assertion that names +// the capability it uses, p256_point, and the compiler's notes name the operation the engine lacks, +// decompress: the diagnostic of backend-concepts design D5, the concept and the operation, at the +// member that needs them (D9, ruling 1.1-M7). + +#include "../../backends/message_only.hpp" + +#include + +#include +#include + +/** Makes a public key of the message-only backend from a compressed point. */ +int main() { + std::array point_bytes{}; + point_bytes[0] = 0x02; + auto const made_key = webcpp::crypto::curves::p256::basic_public_key< + webcpp::test::message_only_backend::message_only>::from_bytes(point_bytes); + return made_key ? 0 : 1; +} diff --git a/test/msvc/p256_prehashed_message_only/Jamfile b/test/msvc/p256_prehashed_message_only/Jamfile new file mode 100644 index 0000000..6b193e1 --- /dev/null +++ b/test/msvc/p256_prehashed_message_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 p256_prehashed_message_only : app.cpp + : /webcpp/crypto//crypto + : native ; diff --git a/test/msvc/p256_prehashed_message_only/app.cpp b/test/msvc/p256_prehashed_message_only/app.cpp new file mode 100644 index 0000000..fda4b75 --- /dev/null +++ b/test/msvc/p256_prehashed_message_only/app.cpp @@ -0,0 +1,79 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the 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 MSVC twin of test/messages/p256_prehashed_message_only/p256_prehashed_message_only.cpp: the +// same program does not compile on MSVC, whose text is not checked; clang checks it there. +// +// On a test-only P-256 backend whose engine signs and verifies a message, never a digest +// (test/backends/message_only.hpp, the form WebCrypto's ECDSA has), sign and verify of +// crypto::signing_schemes::prehashed each stop with the assertion that names the digest form's +// capability, crypto::capabilities::p256_ecdsa_signing or p256_ecdsa_verifying, once though each +// is asked by crypto's function and by the member, and with those errors alone (backend-concepts +// design D9, ruling 1.2-I2); a message signs and verifies there, which p256_message_form_test +// runs. The key pair and the public key are parameters of their callers. + +#include "../../backends/message_only.hpp" + +#include +#include +#include + +#include +#include + +namespace { + +namespace crypto = webcpp::crypto; +using webcpp::test::message_only_backend::message_only; +using p256_keypair = crypto::curves::p256::basic_keypair; +using p256_public_key = crypto::curves::p256::basic_public_key; + +/** Signs a digest with a key pair of the message-only backend, by crypto's function. */ +bool signed_digest(p256_keypair const& key_pair) { + std::array const digest{}; + return crypto::sign(key_pair, crypto::signing_schemes::ecdsa_sha256, + crypto::signing_schemes::prehashed{digest}) + .has_value(); +} + +/** Signs a digest with a key pair of the message-only backend, by the member. */ +bool member_signed_digest(p256_keypair const& key_pair) { + std::array const digest{}; + return key_pair + .sign(crypto::signing_schemes::ecdsa_sha256, crypto::signing_schemes::prehashed{digest}) + .has_value(); +} + +/** Verifies a signature of a digest with a public key of the message-only backend. */ +bool verified_digest(p256_public_key const& public_key, + crypto::curves::p256::ecdsa_signature const& signature) { + std::array const digest{}; + return crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::any_s, signature, + crypto::signing_schemes::prehashed{digest}, public_key) + .has_value(); +} + +/** Verifies a signature of a digest by the member, under the other policy. */ +bool member_verified_digest(p256_public_key const& public_key, + crypto::curves::p256::ecdsa_signature const& signature) { + std::array const digest{}; + return public_key + .verify(crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::low_s_only, + signature, crypto::signing_schemes::prehashed{digest}) + .has_value(); +} + +} // namespace + +// The functions are compiled, which is the test; they are never run. +int main() { + static_cast(&signed_digest); + static_cast(&member_signed_digest); + static_cast(&verified_digest); + static_cast(&member_verified_digest); + return 0; +} diff --git a/test/msvc/secp256k1_other_backend_first/Jamfile b/test/msvc/secp256k1_other_backend_first/Jamfile new file mode 100644 index 0000000..69fe3e3 --- /dev/null +++ b/test/msvc/secp256k1_other_backend_first/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 secp256k1_other_backend_first : app.cpp + : /webcpp/crypto//crypto /third_party//bearssl /third_party//secp256k1 + : native ; diff --git a/test/msvc/secp256k1_other_backend_first/app.cpp b/test/msvc/secp256k1_other_backend_first/app.cpp new file mode 100644 index 0000000..81e121a --- /dev/null +++ b/test/msvc/secp256k1_other_backend_first/app.cpp @@ -0,0 +1,45 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The MSVC twin of test/messages/secp256k1_other_backend_first/secp256k1_other_backend_first.cpp: +// the same program does not compile on MSVC, whose text is not checked; clang checks it there. +// +// secp256k1's key pair and public key refuse a backend other than libsecp256k1 with the family's +// generated refusal (secp256k1_refuses_others), and with that error alone: no secp256k1_engine is +// named, since it has no primary template, and no capability assertion speaks after it +// (backend-concepts design D9, review 2.2 M5). + +#include +#include + +#include +#include + +namespace { + +namespace secp256k1 = webcpp::crypto::curves::secp256k1; +using webcpp::crypto::backends::bearssl; + +/** Makes a key pair from a scalar on BearSSL. */ +bool imported() { + std::array const scalar{1}; + return secp256k1::basic_keypair::from_secret(scalar).has_value(); +} + +/** Makes a public key from a point on BearSSL. */ +bool parsed() { + std::array const point_bytes{}; + return secp256k1::public_key::from_bytes(point_bytes).has_value(); +} + +} // namespace + +// The functions are compiled, which is the test; they are never run. +int main() { + static_cast(&imported); + static_cast(&parsed); + return 0; +} diff --git a/test/msvc/secretbox_capability_missing/Jamfile b/test/msvc/secretbox_capability_missing/Jamfile new file mode 100644 index 0000000..b4346ad --- /dev/null +++ b/test/msvc/secretbox_capability_missing/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 secretbox_capability_missing : app.cpp + : /webcpp/crypto//crypto + : native ; diff --git a/test/msvc/secretbox_capability_missing/app.cpp b/test/msvc/secretbox_capability_missing/app.cpp new file mode 100644 index 0000000..f2ae601 --- /dev/null +++ b/test/msvc/secretbox_capability_missing/app.cpp @@ -0,0 +1,88 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the 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 MSVC twin of test/messages/secretbox_capability_missing/secretbox_capability_missing.cpp: the +// same program does not compile on MSVC, whose text is not checked; clang checks it there. +// +// On a test-only backend whose XSalsa20-Poly1305 secret box engine, marked as its own, seals and +// does not open, the box's open stops with the assertion that names the family's capability, +// secretbox_xsalsa20poly1305, and the compiler's notes name the concept and the operation the +// engine lacks, open (backend-concepts design D5, D9: the boxes). The box is a parameter of its +// caller. + +#include +#include +#include +#include + +#include +#include + +#include +#include +#include + +namespace { + +/** A test-only backend whose secret box engine seals and does not open. */ +struct sealing_only {}; + +} // namespace + +namespace webcpp::crypto::detail { + +/** The XSalsa20-Poly1305 secret box's engine on that backend: no open. */ +template <> +struct secretbox_engine { + /** The state. */ + using state = secretbox_state; + + /** Keys a state. */ + [[nodiscard]] static boost::system::result init( + state& /*box_state*/, std::span /*key_bytes*/) noexcept { + return error::backend_failure; + } + + /** Seals in place. */ + [[nodiscard]] static boost::system::result seal( + state& /*box_state*/, std::span /*nonce_bytes*/, + std::span /*data_bytes*/, boost::hash2::digest<16>& /*tag_output*/) noexcept { + return error::backend_failure; + } + + /** Moves a state. */ + static void move(state& /*target_state*/, state& /*source_state*/) noexcept {} + + /** Wipes a state. */ + static void reset(state& /*box_state*/) noexcept {} +}; + +/** The engine is this program's own, as a shipped backend's is (design D9). */ +template <> +inline constexpr bool + specialized_engine_v> = + true; + +} // namespace webcpp::crypto::detail + +namespace { + +using box_type = webcpp::crypto::secret_key_encryption::secretbox; + +/** Opens a box with the secret box of that backend. */ +bool opened(box_type& box, std::span data_bytes, + std::span tag_bytes) { + std::array const nonce_bytes{}; + return box.open(nonce_bytes, data_bytes, tag_bytes).has_value(); +} + +} // namespace + +// The function is compiled, which is the test; it is never run. +int main() { + static_cast(&opened); + return 0; +} diff --git a/test/msvc/x25519_asynchronous_backend/app.cpp b/test/msvc/x25519_asynchronous_backend/app.cpp index 20f3397..cd49762 100644 --- a/test/msvc/x25519_asynchronous_backend/app.cpp +++ b/test/msvc/x25519_asynchronous_backend/app.cpp @@ -10,8 +10,8 @@ // An X25519 key pair's from_secret, generate and agree (through the free crypto::agree) on a // backend that completes by itself (a stand-in whose detail::asynchronous_backend_v is true) each // stop with the refusal that names its asynchronous form, and with those errors alone: no engine -// is reached. The key pair and the peer are parameters of agree's caller, since making them would -// run the stand-in's engine. +// operation is reached. The stand-in's engine has only what the key pair's special members call, +// move and reset; the key pair and the peer are parameters of agree's caller. // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each // whole text stays on one line. @@ -30,8 +30,22 @@ struct stand_in_browser {}; } // namespace +namespace webcpp::crypto::detail { + +template <> +inline constexpr bool asynchronous_backend_v = true; + +// X25519's key pair moves and resets its state: the stand-in's state holds nothing. template <> -inline constexpr bool webcpp::crypto::detail::asynchronous_backend_v = true; +struct x25519_engine { + using state = x25519_state; + + static void move(state& /*target_state*/, state& /*source_state*/) noexcept {} + + static void reset(state& /*engine_state*/) noexcept {} +}; + +} // namespace webcpp::crypto::detail namespace { diff --git a/test/opaque_backend_test.cpp b/test/opaque_backend_test.cpp new file mode 100644 index 0000000..78d5d8f --- /dev/null +++ b/test/opaque_backend_test.cpp @@ -0,0 +1,860 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the 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 opaque key (backend-concepts design D3, R3, R6, R9) on the test-only opaque backend +// (backends/opaque.hpp), P-256 and X25519, whose keys never leave it: +// +// - its engines satisfy `*_generate`, `*_public` and the uses, and neither `*_import` nor +// `*_export`; P-256's signs and verifies a digest, never a message; its asynchronous engine +// satisfies `async_generate`, `async_sign`, `async_verify` and `async_agree` on P-256 and +// X25519, and not `async_import_secret`; +// - it is outside the table: `supports_v` answers no for it (R6); +// - generate() makes a key through the backend's own generation (R3): the backend's table draws +// it and the key pair holds a handle; the key is real, its signature verifying on BearSSL and its +// agreement agreeing with BearSSL's and libsodium's key pairs; a low-order X25519 peer is +// `weak_public_key`; +// - a public key on it decompresses a point, refuses one off the curve, and writes and reads a +// signature's DER, through its engine's operations on public data; +// - a move takes the handle (the source's public_key, sign and agree are `invalid_state`), the +// destructor frees the key, a full table is `backend_failure` on both curves; +// - on the form that completes by itself, async_generate, async_sign, async_verify and +// async_agree reach its engine and complete through the executor, never inline, with the same +// answers; a changed signature completes with `invalid_signature`, a full table with +// `backend_failure` and a key pair holding no key; with `asio::deferred` the engine runs when +// the operation is launched, not when it is made; the completion runs on the executor passed, +// not on another context's; +// - async_generate on the synchronous form draws through the backend's generate() and posts its +// completion; +// - Ed25519's generate() takes the engine's own generation when the engine has one (R3): a +// stand-in backend, libsodium's engine with a `generate` that draws its seed, signs with the key +// pair it makes, whose public key is libsodium's of that seed, and its engine's error is +// generate's. +// +// The synchronous calls on the form that completes by itself (generate, sign, agree) are refused +// by name: message test `opaque_async_synchronous`. The refusals of the public types that an +// opaque key cannot have, by the secret-key traits before any capability, are message tests on +// this backend: `opaque_keys_kept` (`from_secret`, `secret()`, PKCS#8, a key pair's raw form) and +// `opaque_async_from_secret`; their reasons are checked here too, at compile time. + +#include "backends/opaque.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +/** + * A backend whose Ed25519 engine draws its own key: libsodium's engine, with a `generate` that + * draws a seed and imports it, so that a key pair's generate() takes the engine's branch (R3). + */ +struct ed25519_drawing {}; + +/** What the stand-in's generate did, and whether it refuses its next draw. */ +struct ed25519_draws { + /** How many seeds it drew. */ + std::size_t count = 0; + /** The last seed it drew, which the test makes a libsodium key pair of. */ + std::array last_seed{}; + /** When set, the next draw is `backend_failure`, and the flag is cleared. */ + bool refuse_next = false; +}; + +/** The stand-in's draws, for the whole program. */ +ed25519_draws& ed25519_drawn() noexcept { + static ed25519_draws draws; + return draws; +} + +} // namespace + +namespace webcpp::crypto::detail { + +/** The stand-in's Ed25519 state: libsodium's. */ +template <> +struct ed25519_state + : ed25519_state {}; + +/** The stand-in's Ed25519 engine: libsodium's, and a generate that draws the seed itself. */ +template <> +struct ed25519_engine + : ed25519_engine { + /** The key pair's state. */ + using state = ed25519_state; + + /** + * Draws a seed from the system's generator, keeps a copy for the test and makes the key of it. + * + * @param engine_state The key pair's state, which holds no key. + * @return Nothing; `entropy_unavailable`; `backend_failure` when the test asked for it. + */ + [[nodiscard]] static boost::system::result generate(state& engine_state) noexcept { + auto& draws = ed25519_drawn(); + if (draws.refuse_next) { + draws.refuse_next = false; + return error::backend_failure; + } + secure::secret<32> seed_bytes; + if (!random_device().fill(seed_bytes.writable())) { // lint-world: the stand-in's own key + return error::entropy_unavailable; + } + ++draws.count; + std::ranges::copy(seed_bytes.bytes(), draws.last_seed.begin()); + return ed25519_engine::import_secret( + engine_state, seed_bytes.bytes()); + } +}; + +} // namespace webcpp::crypto::detail + +namespace { + +namespace asio = webcpp::asio; +namespace crypto = webcpp::crypto; +namespace backend = webcpp::crypto::detail::backend; +namespace opaque_backend = webcpp::test::opaque_backend; +using opaque_backend::opaque; +using opaque_backend::opaque_async; + +using p256_keypair = crypto::curves::p256::basic_keypair; +using p256_async_keypair = crypto::curves::p256::basic_keypair; +using x25519_keypair = crypto::curves::x25519::basic_keypair; +using x25519_async_keypair = crypto::curves::x25519::basic_keypair; +using signature_type = crypto::curves::p256::ecdsa_signature; + +// The engines: the opaque split of design D3, on both forms. +template +using p256_engine = crypto::detail::p_curve_engine; +template +using x25519_engine = crypto::detail::x25519_engine; + +template +constexpr bool opaque_p256 = + backend::p256_generate> && backend::p256_public> && + backend::p256_ecdsa_signing> && + backend::p256_ecdsa_verifying> && + backend::p256_ecdh> && backend::p256_point> && + backend::ecdsa_der> && !backend::p256_import> && + !backend::p256_export> && + !backend::p256_ecdsa_message_signing> && + !backend::p256_ecdsa_message_verifying>; +template +constexpr bool opaque_x25519 = backend::x25519_generate> && + backend::x25519_public> && + backend::x25519_agreement> && + !backend::x25519_import> && + !backend::x25519_export>; +static_assert(opaque_p256 && opaque_p256); +static_assert(opaque_x25519 && opaque_x25519); + +// The asynchronous engine, with an executor and a callback as a program passes them. +using async_engine = crypto::detail::async_engine; +using executor_type = asio::io_context::executor_type; +using keypair_callback_p256 = void (*)(boost::system::error_code, p256_async_keypair); +using keypair_callback_x25519 = void (*)(boost::system::error_code, x25519_async_keypair); +using signature_callback = void (*)(boost::system::error_code, signature_type); +using code_callback = void (*)(boost::system::error_code); +using secret_callback = void (*)(boost::system::error_code, webcpp::secure::secret<32>); +static_assert(backend::async_generate); +static_assert(backend::async_generate); +static_assert( + backend::async_sign); +static_assert(backend::async_verify, + executor_type, code_callback>); +static_assert(backend::async_agree, + executor_type, secret_callback>); +static_assert( + backend::async_agree); +static_assert(!backend::async_import_secret); + +// Outside the table (R6): supports_v knows the shipped backends alone. +static_assert(!crypto::supports_v); +static_assert(!crypto::supports_v); + +// Its engines are marked as its header's own (D9), and its keys are kept (D3's amendment): the +// secret-key traits refuse them, so the private formats of its key pairs are refused for that +// reason, said before WebCrypto's on the form that completes by itself; the message is message +// test `opaque_keys_kept`'s. +static_assert(crypto::detail::specialized_engine_v> && + crypto::detail::specialized_engine_v>); +static_assert(!crypto::detail::secret_keys_leave_v, opaque> && + !crypto::detail::secret_keys_enter_v, opaque_async>); + +/** + * Whether crypto refuses `Format` on `Keypair`, both ways, because its backend keeps its keys, for + * the reason `Reason`: `raw` has its own, `pkcs8` and `pem(pkcs8)` share one. + */ +template +constexpr bool refused_as_kept() noexcept { + using declaration = webcpp::codecs::value_formats; + return crypto::detail::refusal_reason_v == Reason && + declaration::template has_reason && + declaration::template has_reason && + !webcpp::codecs::encodable && + !webcpp::codecs::decodable; +} + +/** The private formats of `Keypair`, each refused because its backend keeps its keys. */ +template +constexpr bool private_formats_kept = + refused_as_kept, Keypair, + crypto::detail::refusal_reason::private_kept_raw>() && + refused_as_kept() && + refused_as_kept, Keypair, + crypto::detail::refusal_reason::private_kept_pkcs8>(); +static_assert(private_formats_kept && private_formats_kept); +static_assert(private_formats_kept && private_formats_kept); + +// The Ed25519 stand-in draws its own key, and imports too: generate() takes the engine's branch. +using ed25519_drawing_engine = + crypto::detail::ed25519_engine; +static_assert(backend::ed25519_generate && + backend::ed25519_public && + backend::ed25519_signing); + +std::vector bytes_of(std::string_view text) { + return {text.begin(), text.end()}; +} + +/** The P-256 public key on BearSSL of the same point. */ +crypto::curves::p256::basic_public_key on_bearssl( + std::span point_bytes) { + return crypto::curves::p256::basic_public_key::from_bytes( + point_bytes) + .value(); +} + +void p256_generated_by_the_backend() { + auto const& keys = opaque_backend::p256_table(); + auto const drawn_before = keys.drawn(); + { + auto const key_pair = p256_keypair::generate(); + BOOST_TEST(key_pair.has_value()); + if (!key_pair) { + return; + } + // The backend drew it: one more key in its table, none drawn by the public layer. + BOOST_TEST_EQ(keys.drawn(), drawn_before + 1); + BOOST_TEST_EQ(keys.held(), 1U); + + auto const message = bytes_of("the opaque key signs"); + auto const signature = key_pair->sign(crypto::signing_schemes::ecdsa_sha256, message); + BOOST_TEST(signature.has_value()); + auto const public_key = key_pair->public_key(); + BOOST_TEST(public_key.has_value()); + if (!signature || !public_key) { + return; + } + BOOST_TEST(signature->low_s()); + // Verified on the opaque backend and on BearSSL: the key is a real P-256 key. + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *signature, message, + *public_key) + .has_value()); + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *signature, message, + on_bearssl(public_key->uncompressed())) + .has_value()); + auto changed = bytes_of("the opaque key signs"); + changed[0] ^= 1U; + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *signature, changed, + *public_key) == crypto::error::invalid_signature); + + // ECDH with a BearSSL key pair: both sides give the same x. + auto const peer = + crypto::curves::p256::basic_keypair::generate(); + BOOST_TEST(peer.has_value()); + if (!peer) { + return; + } + auto const peer_on_opaque = crypto::curves::p256::basic_public_key::from_bytes( + peer->public_key()->uncompressed()); + BOOST_TEST(peer_on_opaque.has_value()); + auto const ours = key_pair->agree(*peer_on_opaque); + auto const theirs = peer->agree(on_bearssl(public_key->uncompressed())); + BOOST_TEST(ours.has_value()); + BOOST_TEST(theirs.has_value()); + if (ours && theirs) { + BOOST_TEST(std::ranges::equal(ours->bytes(), theirs->bytes())); + } + } + // The destructor freed the key. + BOOST_TEST_EQ(keys.held(), 0U); +} + +void p256_moved_and_full() { + auto const& keys = opaque_backend::p256_table(); + { + auto first = p256_keypair::generate(); + BOOST_TEST(first.has_value()); + if (!first) { + return; + } + // A move takes the handle: the source refuses, the table holds the one key. + p256_keypair const moved = std::move(*first); + BOOST_TEST(first->public_key().error() == crypto::error::invalid_state); + auto const message = bytes_of("moved from"); + BOOST_TEST(first->sign(crypto::signing_schemes::ecdsa_sha256, message).error() == + crypto::error::invalid_state); + auto const moved_public_key = moved.public_key(); + BOOST_TEST(moved_public_key.has_value()); + if (moved_public_key) { + BOOST_TEST(first->agree(*moved_public_key).error() == crypto::error::invalid_state); + } + BOOST_TEST_EQ(keys.held(), 1U); + + std::vector held; + for (std::size_t index = 1; index < opaque_backend::table_capacity; ++index) { + auto made = p256_keypair::generate(); + BOOST_TEST(made.has_value()); + if (made) { + held.push_back(std::move(*made)); + } + } + BOOST_TEST_EQ(keys.held(), opaque_backend::table_capacity); + // A full table refuses the next key. + auto const refused = p256_keypair::generate(); + BOOST_TEST(refused.error() == crypto::error::backend_failure); + } + BOOST_TEST_EQ(keys.held(), 0U); +} + +void x25519_generated_by_the_backend() { + auto const& keys = opaque_backend::x25519_table(); + auto const drawn_before = keys.drawn(); + { + auto const key_pair = x25519_keypair::generate(); + BOOST_TEST(key_pair.has_value()); + if (!key_pair) { + return; + } + BOOST_TEST_EQ(keys.drawn(), drawn_before + 1); + BOOST_TEST_EQ(keys.held(), 1U); + + // The agreement with a libsodium key pair: both sides give the same secret. + auto const peer = + crypto::curves::x25519::basic_keypair::generate(); + BOOST_TEST(peer.has_value()); + if (!peer) { + return; + } + auto const ours = key_pair->agree(*peer->public_key()); + auto const theirs = peer->agree(*key_pair->public_key()); + BOOST_TEST(ours.has_value()); + BOOST_TEST(theirs.has_value()); + if (ours && theirs) { + BOOST_TEST(std::ranges::equal(ours->bytes(), theirs->bytes())); + } + + // A move takes the handle. + auto second = x25519_keypair::generate(); + BOOST_TEST(second.has_value()); + if (second) { + x25519_keypair const moved = std::move(*second); + BOOST_TEST(second->public_key().error() == crypto::error::invalid_state); + BOOST_TEST(second->agree(*peer->public_key()).error() == crypto::error::invalid_state); + BOOST_TEST(moved.agree(*peer->public_key()).has_value()); + BOOST_TEST_EQ(keys.held(), 2U); + } + BOOST_TEST_EQ(keys.held(), 1U); + + // A peer key of low order: the shared secret would be all zero, and is refused. + std::array const zero_point{}; + auto const low_order = crypto::curves::x25519::public_key::from_bytes(zero_point); + BOOST_TEST(low_order.has_value()); + if (low_order) { + BOOST_TEST(key_pair->agree(*low_order).error() == crypto::error::weak_public_key); + } + } + BOOST_TEST_EQ(keys.held(), 0U); +} + +void x25519_full() { + auto const& keys = opaque_backend::x25519_table(); + { + std::vector held; + for (std::size_t index = 0; index < opaque_backend::table_capacity; ++index) { + auto made = x25519_keypair::generate(); + BOOST_TEST(made.has_value()); + if (made) { + held.push_back(std::move(*made)); + } + } + BOOST_TEST_EQ(keys.held(), opaque_backend::table_capacity); + auto const refused = x25519_keypair::generate(); + BOOST_TEST(refused.error() == crypto::error::backend_failure); + } + BOOST_TEST_EQ(keys.held(), 0U); +} + +// A public key on the opaque backend reads a compressed point, refuses a point off the curve, and +// writes and reads a signature's DER, each through its engine's operations on public data. +void p256_public_data() { + auto const key_pair = p256_keypair::generate(); + BOOST_TEST(key_pair.has_value()); + if (!key_pair) { + return; + } + auto const public_key = key_pair->public_key(); + BOOST_TEST(public_key.has_value()); + if (!public_key) { + return; + } + using public_key_type = crypto::curves::p256::basic_public_key; + auto const decompressed = public_key_type::from_bytes(public_key->compressed()); + BOOST_TEST(decompressed.has_value()); + if (decompressed) { + BOOST_TEST(decompressed->uncompressed() == public_key->uncompressed()); + } + auto off_curve = public_key->uncompressed(); + off_curve.back() ^= 1U; + BOOST_TEST(public_key_type::from_bytes(off_curve).error() == crypto::error::invalid_public_key); + + auto const message = bytes_of("the opaque key's DER"); + auto const signature = key_pair->sign(crypto::signing_schemes::ecdsa_sha256, message); + BOOST_TEST(signature.has_value()); + if (!signature) { + return; + } + using der_codec = webcpp::codecs::value_codec; + std::array der_bytes{}; + auto const der_size = der_codec::encode(crypto::formats::der, *signature, der_bytes); + BOOST_TEST(der_size.has_value()); + if (!der_size) { + return; + } + // The same DER as BearSSL's, and read back to the same signature. + std::array bearssl_der{}; + auto const bearssl_size = + der_codec::encode(crypto::formats::der, *signature, bearssl_der); + BOOST_TEST(bearssl_size.has_value()); + if (bearssl_size) { + BOOST_TEST(std::ranges::equal(std::span(der_bytes).first(*der_size), + std::span(bearssl_der).first(*bearssl_size))); + } + auto const read_back = + der_codec::decode(crypto::formats::der, std::span(der_bytes).first(*der_size)); + BOOST_TEST(read_back.has_value()); + if (read_back) { + BOOST_TEST(std::ranges::equal(read_back->bytes(), signature->bytes())); + } + BOOST_TEST( + der_codec::decode(crypto::formats::der, std::span(der_bytes).first(*der_size - 1)) + .error() == crypto::error::invalid_signature); +} + +// Ed25519's generate() on a backend whose engine draws its own key: the engine's key, which signs +// and is libsodium's key of the seed the engine drew, and the engine's error. +void ed25519_generated_by_the_engine() { + using keypair = crypto::curves::ed25519::basic_keypair; + auto& draws = ed25519_drawn(); + auto const count_before = draws.count; + auto const key_pair = keypair::generate(); + BOOST_TEST(key_pair.has_value()); + if (!key_pair) { + return; + } + BOOST_TEST_EQ(draws.count, count_before + 1); + auto const public_key = key_pair->public_key(); + BOOST_TEST(public_key.has_value()); + auto const on_sodium = + crypto::curves::ed25519::basic_keypair::from_secret( + draws.last_seed); + BOOST_TEST(on_sodium.has_value()); + if (!public_key || !on_sodium) { + return; + } + BOOST_TEST(public_key->bytes() == on_sodium->public_key()->bytes()); + + auto const message = bytes_of("the engine's own Ed25519 key signs"); + auto const signature = key_pair->sign(crypto::signing_schemes::eddsa, message); + BOOST_TEST(signature.has_value()); + if (!signature) { + return; + } + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, *signature, message, + *public_key) + .has_value()); + auto changed = bytes_of("the engine's own Ed25519 key signs"); + changed[0] ^= 1U; + BOOST_TEST(crypto::verify(crypto::signing_schemes::eddsa, + crypto::verification_policies::canonical, *signature, changed, + *public_key) == crypto::error::invalid_signature); + + // The engine's error is generate's, and nothing is drawn. + draws.refuse_next = true; + auto const refused = keypair::generate(); + BOOST_TEST(refused.error() == crypto::error::backend_failure); + BOOST_TEST_EQ(draws.count, count_before + 1); +} + +// What a completion saw: its calls, whether the initiating call had returned, its error code and +// its value, if it has one. +template +struct completed { + int calls = 0; + bool after_return = false; + boost::system::error_code code; + std::optional> value; +}; + +// Starts `start(executor, token)` with a callback, runs the context and returns what the callback +// saw: one completion, after the initiating call returned. +template +completed complete(asio::io_context& context, Start start) { + completed done; + bool returned = false; + start(context.get_executor(), + [&done, &returned](boost::system::error_code code, Value... value) { + ++done.calls; + done.after_return = returned; + done.code = code; + done.value = std::tuple(std::move(value)...); + }); + returned = true; + BOOST_TEST_EQ(done.calls, 0); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(done.calls, 1); + BOOST_TEST(done.after_return); + return done; +} + +template +std::optional generated_async(asio::io_context& context) { + auto made = complete(context, [](auto const& executor, auto&& token) { + return crypto::async_generate(executor, std::forward(token)); + }); + BOOST_TEST(!made.code); + if (made.code || !made.value.has_value()) { + return std::nullopt; + } + return std::move(std::get<0>(*made.value)); +} + +void p256_asynchronous() { + asio::io_context context; + auto const& keys = opaque_backend::p256_table(); + auto const drawn_before = keys.drawn(); + { + auto key_pair = generated_async(context); + BOOST_TEST(key_pair.has_value()); + if (!key_pair) { + return; + } + BOOST_TEST_EQ(keys.drawn(), drawn_before + 1); + auto const public_key = key_pair->public_key(); + BOOST_TEST(public_key.has_value()); + if (!public_key) { + return; + } + + auto const message = bytes_of("the opaque key signs asynchronously"); + auto const signed_message = complete(context, [&](auto const& executor, + auto&& token) { + return crypto::async_sign(executor, *key_pair, crypto::signing_schemes::ecdsa_sha256, + message, std::forward(token)); + }); + BOOST_TEST(!signed_message.code); + if (signed_message.code || !signed_message.value) { + return; + } + auto const& signature = std::get<0>(*signed_message.value); + BOOST_TEST(signature.low_s()); + // The key is real: BearSSL verifies its signature. + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, signature, message, + on_bearssl(public_key->uncompressed())) + .has_value()); + + auto const verified = complete<>(context, [&](auto const& executor, auto&& token) { + return crypto::async_verify(executor, crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, signature, + message, *public_key, std::forward(token)); + }); + BOOST_TEST(!verified.code); + auto changed = bytes_of("the opaque key signs asynchronously"); + changed[0] ^= 1U; + auto const refused = complete<>(context, [&](auto const& executor, auto&& token) { + return crypto::async_verify(executor, crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::any_s, signature, changed, + *public_key, std::forward(token)); + }); + BOOST_TEST(refused.code == crypto::error::invalid_signature); + + // Two keys of the backend agree. + auto peer = generated_async(context); + BOOST_TEST(peer.has_value()); + if (!peer) { + return; + } + using secret_type = webcpp::secure::secret<32>; + auto const ours = complete(context, [&](auto const& executor, auto&& token) { + return crypto::async_agree(executor, *key_pair, *peer->public_key(), + std::forward(token)); + }); + auto const theirs = complete(context, [&](auto const& executor, auto&& token) { + return crypto::async_agree(executor, *peer, *public_key, + std::forward(token)); + }); + BOOST_TEST(!ours.code); + BOOST_TEST(!theirs.code); + if (ours.value && theirs.value) { + BOOST_TEST(std::ranges::equal(std::get<0>(*ours.value).bytes(), + std::get<0>(*theirs.value).bytes())); + } + } + BOOST_TEST_EQ(keys.held(), 0U); +} + +void x25519_asynchronous() { + asio::io_context context; + auto const& keys = opaque_backend::x25519_table(); + { + auto key_pair = generated_async(context); + BOOST_TEST(key_pair.has_value()); + if (!key_pair) { + return; + } + BOOST_TEST_EQ(keys.held(), 1U); + auto const peer = + crypto::curves::x25519::basic_keypair::generate(); + BOOST_TEST(peer.has_value()); + if (!peer) { + return; + } + using secret_type = webcpp::secure::secret<32>; + auto const ours = complete(context, [&](auto const& executor, auto&& token) { + return crypto::async_agree(executor, *key_pair, *peer->public_key(), + std::forward(token)); + }); + auto const theirs = peer->agree(*key_pair->public_key()); + BOOST_TEST(!ours.code); + BOOST_TEST(theirs.has_value()); + if (ours.value && theirs) { + BOOST_TEST(std::ranges::equal(std::get<0>(*ours.value).bytes(), theirs->bytes())); + } + } + BOOST_TEST_EQ(keys.held(), 0U); +} + +// A full table on the form that completes by itself: the completion is `backend_failure` with a +// key pair that holds no key. The two forms share the table, so the synchronous form fills it. +void p256_asynchronous_full() { + asio::io_context context; + auto const& keys = opaque_backend::p256_table(); + { + std::vector held; + for (std::size_t index = 0; index < opaque_backend::table_capacity; ++index) { + auto made = p256_keypair::generate(); + BOOST_TEST(made.has_value()); + if (made) { + held.push_back(std::move(*made)); + } + } + auto const refused = + complete(context, [](auto const& executor, auto&& token) { + return crypto::async_generate( + executor, std::forward(token)); + }); + BOOST_TEST(refused.code == crypto::error::backend_failure); + if (refused.value) { + BOOST_TEST(std::get<0>(*refused.value).public_key().error() == + crypto::error::invalid_state); + } + BOOST_TEST_EQ(keys.held(), opaque_backend::table_capacity); + } + BOOST_TEST_EQ(keys.held(), 0U); +} + +// async_generate on the synchronous form: the backend's generate() draws the key, the completion +// is posted. +void p256_async_generate_on_the_synchronous_form() { + asio::io_context context; + auto const& keys = opaque_backend::p256_table(); + auto const drawn_before = keys.drawn(); + { + auto const key_pair = generated_async(context); + BOOST_TEST(key_pair.has_value()); + if (!key_pair) { + return; + } + BOOST_TEST_EQ(keys.drawn(), drawn_before + 1); + BOOST_TEST_EQ(keys.held(), 1U); + auto const message = bytes_of("drawn asynchronously, signed synchronously"); + auto const signature = key_pair->sign(crypto::signing_schemes::ecdsa_sha256, message); + auto const public_key = key_pair->public_key(); + BOOST_TEST(signature.has_value()); + BOOST_TEST(public_key.has_value()); + if (signature && public_key) { + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *signature, + message, on_bearssl(public_key->uncompressed())) + .has_value()); + } + } + BOOST_TEST_EQ(keys.held(), 0U); +} + +// With asio::deferred, the engine runs when the operation is launched, not when it is made: the +// table draws nothing until then, and the agreement completes with the same secret. +void deferred_operations() { + asio::io_context context; + auto const& keys = opaque_backend::p256_table(); + auto const drawn_before = keys.drawn(); + { + auto generating = + crypto::async_generate(context.get_executor(), asio::deferred); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(keys.drawn(), drawn_before); + + std::optional key_pair; + int calls = 0; + std::move(generating)( + [&key_pair, &calls](boost::system::error_code code, p256_async_keypair made) { + ++calls; + BOOST_TEST(!code); + key_pair.emplace(std::move(made)); + }); + // Launched: the engine drew the key; the completion waits for the context. + BOOST_TEST_EQ(keys.drawn(), drawn_before + 1); + BOOST_TEST_EQ(calls, 0); + context.restart(); + context.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(calls, 1); + if (!key_pair) { + return; + } + + auto peer = generated_async(context); + BOOST_TEST(peer.has_value()); + if (!peer) { + return; + } + auto const peer_key = peer->public_key(); + auto const own_key = key_pair->public_key(); + BOOST_TEST(peer_key.has_value()); + BOOST_TEST(own_key.has_value()); + if (!peer_key || !own_key) { + return; + } + auto agreeing = + crypto::async_agree(context.get_executor(), *key_pair, *peer_key, asio::deferred); + using secret_type = webcpp::secure::secret<32>; + std::optional ours; + std::move(agreeing)([&ours](boost::system::error_code code, secret_type shared) { + BOOST_TEST(!code); + ours.emplace(std::move(shared)); + }); + BOOST_TEST(!ours.has_value()); + auto const theirs = complete(context, [&](auto const& executor, auto&& token) { + return crypto::async_agree(executor, *peer, *own_key, + std::forward(token)); + }); + BOOST_TEST(ours.has_value()); + BOOST_TEST(!theirs.code); + if (ours && theirs.value) { + BOOST_TEST(std::ranges::equal(ours->bytes(), std::get<0>(*theirs.value).bytes())); + } + } + BOOST_TEST_EQ(keys.held(), 0U); +} + +// The completion runs on the executor passed, not on another context's: running the other context +// completes nothing. +void completion_on_the_executor_passed() { + asio::io_context initiating; + asio::io_context completing; + auto const& keys = opaque_backend::x25519_table(); + { + std::optional key_pair; + int calls = 0; + crypto::async_generate( + completing.get_executor(), + [&key_pair, &calls](boost::system::error_code code, x25519_async_keypair made) { + ++calls; + BOOST_TEST(!code); + key_pair.emplace(std::move(made)); + }); + initiating.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(calls, 0); + completing.run(); // lint-run: the test's event loop + BOOST_TEST_EQ(calls, 1); + BOOST_TEST(key_pair.has_value()); + if (key_pair) { + BOOST_TEST(key_pair->public_key().has_value()); + } + } + BOOST_TEST_EQ(keys.held(), 0U); +} + +} // namespace + +int main() { + p256_generated_by_the_backend(); + p256_moved_and_full(); + x25519_generated_by_the_backend(); + x25519_full(); + p256_public_data(); + ed25519_generated_by_the_engine(); + p256_asynchronous(); + x25519_asynchronous(); + p256_asynchronous_full(); + p256_async_generate_on_the_synchronous_form(); + deferred_operations(); + completion_on_the_executor_passed(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/p256_message_form_test.cpp b/test/p256_message_form_test.cpp new file mode 100644 index 0000000..1d284b7 --- /dev/null +++ b/test/p256_message_form_test.cpp @@ -0,0 +1,177 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the 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 sign and verify of a message on a backend whose engine has the message form alone +// (test/backends/message_only.hpp, the form WebCrypto's ECDSA has): the message reaches the +// engine's sign_message and verify_message whole, not its SHA-256, the signature comes back low S, +// and the policy is checked before the engine (backend-concepts design D9, review 3.2's I1). The +// calls ask the predicate by which supports_v counts a message signed on either form, which the +// static_asserts below check of the helpers; the stand-in is outside the table, so supports_v +// itself is not asked. Prehashed input refuses on such a backend (message test +// p256_prehashed_message_only), and can_sign and can_verify say so. + +#include "backends/message_only.hpp" + +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include + +namespace { + +namespace crypto = webcpp::crypto; +using webcpp::test::message_only_backend::message_only; +using p256_keypair = crypto::curves::p256::basic_keypair; +using p256_public_key = crypto::curves::p256::basic_public_key; +using engine = crypto::detail::p_curve_engine; + +// The forms the backend has: the message's alone, both ways. +static_assert(crypto::detail::backend::p256_ecdsa_message_signing && + !crypto::detail::backend::p256_ecdsa_signing); +static_assert(crypto::detail::backend::p256_ecdsa_message_verifying && + !crypto::detail::backend::p256_ecdsa_verifying); +static_assert(crypto::detail::p256_signing_checked() && + crypto::detail::p256_verifying_checked()); + +// can_sign and can_verify agree with sign and verify (final review M4): a message, yes; a digest, +// which needs the digest form the backend lacks, no, as sign and verify refuse it. +using message_view = std::span; +using digest_marker = crypto::signing_schemes::prehashed<32>; +static_assert( + crypto::can_sign); +static_assert( + !crypto::can_sign); +static_assert(crypto::can_verify< + crypto::signing_schemes::ecdsa_sha256_t, crypto::verification_policies::low_s_only_t, + crypto::curves::p256::ecdsa_signature, message_view, p256_public_key>); +static_assert(!crypto::can_verify< + crypto::signing_schemes::ecdsa_sha256_t, crypto::verification_policies::low_s_only_t, + crypto::curves::p256::ecdsa_signature, digest_marker, p256_public_key>); + +// The query stays a query where no backend's header specialises P-256's engine (final re-review +// N1): on a backend without P-256 (libsodium) and on the default key pair, whose backend's header +// this test does not include, the primary engine is taken at its word and nothing stops the build; +// the key pair's own sign is what refuses it. +using sodium_keypair = crypto::curves::p256::basic_keypair; +using sodium_public_key = crypto::curves::p256::basic_public_key; +static_assert( + crypto::can_sign); +static_assert(crypto::can_verify< + crypto::signing_schemes::ecdsa_sha256_t, crypto::verification_policies::low_s_only_t, + crypto::curves::p256::ecdsa_signature, digest_marker, sodium_public_key>); +static_assert(crypto::can_sign); +static_assert( + crypto::can_verify< + crypto::signing_schemes::ecdsa_sha256_t, crypto::verification_policies::low_s_only_t, + crypto::curves::p256::ecdsa_signature, digest_marker, crypto::curves::p256::public_key>); + +/** A message whose SHA-256 is 32 bytes, so a signature of the digest would carry 32 in r. */ +constexpr std::array message{'h', 'e', 'l', 'l', 'o'}; + +/** The signature the engine makes of `message`, made low S: r the message's size, S 1. */ +std::array low_signature_bytes() { + std::array expected{}; + expected[31] = static_cast(message.size()); + expected[63] = 1; + return expected; +} + +/** The message's signature, by `crypto::sign` and by the key pair's member. */ +void signs_the_message(p256_keypair const& key_pair) { + auto const by_function = crypto::sign(key_pair, crypto::signing_schemes::ecdsa_sha256, + std::span(message)); + BOOST_TEST(by_function.has_value()); + auto const by_member = key_pair.sign(crypto::signing_schemes::ecdsa_sha256, + std::span(message)); + BOOST_TEST(by_member.has_value()); + if (by_function && by_member) { + auto const expected = low_signature_bytes(); + BOOST_TEST(std::ranges::equal(by_function->bytes(), expected)); + BOOST_TEST(std::ranges::equal(by_member->bytes(), expected)); + } +} + +/** The signature verifies under both policies, by `crypto::verify` and by the key's member. */ +void verifies_the_message(p256_keypair const& key_pair, p256_public_key const& public_key) { + auto const signature = crypto::sign(key_pair, crypto::signing_schemes::ecdsa_sha256, + std::span(message)); + if (!BOOST_TEST(signature.has_value())) { + return; + } + BOOST_TEST(crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *signature, + std::span(message), public_key) + .has_value()); + BOOST_TEST(public_key + .verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::any_s, *signature, + std::span(message)) + .has_value()); + + // Another message: the engine's verdict, invalid_signature. + std::array const other{'h', 'e', 'l', 'p'}; + auto const refused = + crypto::verify(crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::any_s, + *signature, std::span(other), public_key); + BOOST_TEST(!refused.has_value()); + if (!refused) { + BOOST_TEST(refused.error() == boost::system::error_code(crypto::error::invalid_signature)); + } +} + +/** + * A high S is refused under low_s_only before the engine, which is never called, and reaches it + * under any_s. + */ +void refuses_high_s_before_the_engine(p256_public_key const& public_key) { + auto high_bytes = low_signature_bytes(); + std::ranges::copy(webcpp::test::message_only_backend::order_less_one, + std::span(high_bytes).last<32>().begin()); + auto const high_signature = crypto::curves::p256::ecdsa_signature::from_bytes(high_bytes); + if (!BOOST_TEST(high_signature.has_value())) { + return; + } + auto& engine_calls = webcpp::test::message_only_backend::verify_message_calls(); + engine_calls = 0; + auto const refused = crypto::verify(crypto::signing_schemes::ecdsa_sha256, + crypto::verification_policies::low_s_only, *high_signature, + std::span(message), public_key); + BOOST_TEST(!refused.has_value()); + BOOST_TEST_EQ(engine_calls, 0U); + + // Under any_s the same signature reaches the engine, which refuses its S. + auto const by_engine = + crypto::verify(crypto::signing_schemes::ecdsa_sha256, crypto::verification_policies::any_s, + *high_signature, std::span(message), public_key); + BOOST_TEST(!by_engine.has_value()); + BOOST_TEST_EQ(engine_calls, 1U); +} + +} // namespace + +int main() { + auto const key_pair = p256_keypair::generate(); + if (!BOOST_TEST(key_pair.has_value())) { + return boost::report_errors(); + } + auto const public_key = key_pair->public_key(); + if (!BOOST_TEST(public_key.has_value())) { + return boost::report_errors(); + } + signs_the_message(*key_pair); + verifies_the_message(*key_pair, *public_key); + refuses_high_s_before_the_engine(*public_key); + return boost::report_errors(); +} diff --git a/test/rfc8410_no_backend_test.cpp b/test/rfc8410_no_backend_test.cpp new file mode 100644 index 0000000..a84804f --- /dev/null +++ b/test/rfc8410_no_backend_test.cpp @@ -0,0 +1,116 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// RFC 8410's public-key formats need no backend (backend concepts, task 2.1): a program that links +// none encodes and decodes an Ed25519 and an X25519 SubjectPublicKeyInfo, RFC 8410's own Ed25519 +// example to the byte; and detail::rfc8410 itself writes the prefix and the key, reads the key +// back, and leaves the key untouched when the prefix is not the format's. + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include + +#if defined(WEBCPP_CRYPTO_HAS_BEARSSL) || defined(WEBCPP_CRYPTO_HAS_OPENSSL) || \ + defined(WEBCPP_CRYPTO_HAS_CTAES) || defined(WEBCPP_CRYPTO_HAS_SECP256K1) || \ + defined(WEBCPP_CRYPTO_HAS_SODIUM) +#error "this program links no backend: its project must not name one" +#endif + +namespace { + +namespace crypto = webcpp::crypto; +namespace codecs = webcpp::codecs; +namespace formats = crypto::formats; +namespace rfc8410 = crypto::detail::rfc8410; + +/** RFC 8410 section 10.1's Ed25519 public key, as its SubjectPublicKeyInfo. */ +constexpr std::array ed25519_spki{ + 0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00, 0x19, 0xbf, 0x44, + 0x09, 0x69, 0x84, 0xcd, 0xfe, 0x85, 0x41, 0xba, 0xc1, 0x67, 0xdc, 0x3b, 0x96, 0xc8, 0x50, + 0x86, 0xaa, 0x30, 0xb6, 0xb6, 0xcb, 0x0c, 0x5c, 0x38, 0xad, 0x70, 0x31, 0x66, 0xe1, +}; + +void ed25519_spki_without_backend() { + auto const decoded = + codecs::decode(formats::spki, ed25519_spki); + if (!BOOST_TEST(decoded.has_value())) { + return; + } + BOOST_TEST(std::ranges::equal(decoded->bytes(), std::span{ed25519_spki}.last<32>())); + auto const encoded = codecs::encode(formats::spki, *decoded); + BOOST_TEST(encoded.has_value() && std::ranges::equal(encoded->view(), ed25519_spki)); +} + +void x25519_spki_without_backend() { + std::array key_bytes{}; + for (std::size_t index = 0; index < key_bytes.size(); ++index) { + key_bytes.at(index) = static_cast(index + 1); + } + auto const key = crypto::curves::x25519::public_key::from_bytes(key_bytes); + if (!BOOST_TEST(key.has_value())) { + return; + } + auto const encoded = codecs::encode(formats::spki, *key); + if (!BOOST_TEST(encoded.has_value())) { + return; + } + BOOST_TEST_EQ(encoded->view().size(), 44U); + BOOST_TEST( + std::ranges::equal(encoded->view().subspan(0, 12), crypto::detail::x25519_spki_prefix)); + auto const decoded = + codecs::decode(formats::spki, encoded->view()); + BOOST_TEST(decoded.has_value() && *decoded == *key); +} + +void rfc8410_directly() { + constexpr std::array prefix{0x01, 0x02, 0x03}; + std::array key_bytes{}; + std::ranges::fill(key_bytes, std::uint8_t{0x42}); + + std::array encoding{}; + rfc8410::encode(prefix, std::span{key_bytes}, + std::span{encoding}); + BOOST_TEST(std::ranges::equal(std::span{encoding}.first<3>(), prefix)); + BOOST_TEST(std::ranges::equal(std::span{encoding}.last<32>(), key_bytes)); + + std::array read_back{}; + BOOST_TEST(rfc8410::decode(prefix, std::span{encoding}, + std::span{read_back}) + .has_value()); + BOOST_TEST(read_back == key_bytes); + + // A prefix that is not the format's: invalid_encoding, and the key is not written. + encoding.at(1) ^= 0x80U; + std::array untouched{}; + std::ranges::fill(untouched, std::uint8_t{0xa5}); + auto const refused = rfc8410::decode(prefix, std::span{encoding}, + std::span{untouched}); + BOOST_TEST(!refused.has_value() && refused.error() == crypto::error::invalid_encoding); + BOOST_TEST(std::ranges::all_of(untouched, [](std::uint8_t byte) { return byte == 0xa5; })); +} + +} // namespace + +int main() { + ed25519_spki_without_backend(); + x25519_spki_without_backend(); + rfc8410_directly(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/secp256k1_formats_test.cpp b/test/secp256k1_formats_test.cpp index e5ec00f..77608fb 100644 --- a/test/secp256k1_formats_test.cpp +++ b/test/secp256k1_formats_test.cpp @@ -1173,9 +1173,10 @@ void ecdh_spki_case(std::string const& label, std::string_view hex, spki_counts& bool const uncompressed = hex.size() == std::size_t{2} * 88 && hex.starts_with(uncompressed_prefix); bool const compressed = hex.size() == std::size_t{2} * 56 && hex.starts_with(compressed_prefix); - secp256k1_pubkey point{}; - bool const parses = (uncompressed || compressed) && crypto::detail::secp256k1_parse_public_key( - std::span(encoding).subspan(23), point); + crypto::detail::secp256k1_point point{}; + bool const parses = + (uncompressed || compressed) && + crypto::detail::secp256k1_point_engine::parse(std::span(encoding).subspan(23), point); if (!uncompressed && !compressed) { ++counts.other; } else { diff --git a/test/support/backend_stand_in.hpp b/test/support/backend_stand_in.hpp new file mode 100644 index 0000000..be40d2a --- /dev/null +++ b/test/support/backend_stand_in.hpp @@ -0,0 +1,165 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the 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 defect selector of the capability concept tests (backend-concepts design D4, task 1.1's +// review I1): a stand-in engine is a class template over a `defect`, complete when the defect is +// none, and otherwise with exactly one operation missing, not noexcept or of another result, or +// with exactly one parameter of another shape (a size or a type the concept does not take). +// `rejects_every_defect` then shows that the concept takes the complete engine and refuses every +// defect of every operation and shape it lists, so that each requirement is shown to be checked. +// +// Operations and shapes are numbered by the stand-in, the shared state ones first: `move_op`, +// `reset_op` and `init_op`; a stand-in's own operations from `first_op`. + +#ifndef WEBCPP_TEST_CRYPTO_SUPPORT_BACKEND_STAND_IN_HPP +#define WEBCPP_TEST_CRYPTO_SUPPORT_BACKEND_STAND_IN_HPP + +#include + +#include +#include +#include +#include + +namespace backend_stand_in { + +/** An operation's result where it can fail and returns nothing. */ +using result_void = boost::system::result; +/** A view of bytes to write. */ +using bytes = std::span; +/** A view of bytes to read. */ +using const_bytes = std::span; +/** A view of exactly `Size` bytes to read. */ +template +using fixed_input = std::span; +/** A view of exactly `Size` bytes to write. */ +template +using fixed_output = std::span; + +/** What is wrong with a stand-in, if anything. */ +enum class flaw : std::uint8_t { + none, ///< The stand-in is complete. + missing, ///< The operation is absent. + throwing, ///< The operation is not noexcept. + wrong_result, ///< The operation returns another type. + wrong_shape, ///< The parameter has another size or type. +}; + +/** One defect: the operation or shape it hits, and how. */ +struct defect { + int target = -1; ///< The operation's or shape's number. + flaw kind = flaw::none; ///< What is wrong with it. +}; + +/** The number of a state's `move`. */ +inline constexpr int move_op = 0; +/** The number of a state's `reset`. */ +inline constexpr int reset_op = 1; +/** The number of a keyed state's `init`. */ +inline constexpr int init_op = 2; +/** The first number of a stand-in's own operations. */ +inline constexpr int first_op = 3; + +/** Whether operation `Target` is present under `Defect`. */ +template +inline constexpr bool present = Defect.target != Target || Defect.kind != flaw::missing; + +/** Whether operation `Target` is noexcept under `Defect`. */ +template +inline constexpr bool nothrow = Defect.target != Target || Defect.kind != flaw::throwing; + +/** Another result than `Result`: `bool` for `result`, `result` for any other. */ +template +using other_result = std::conditional_t, bool, result_void>; + +/** Operation `Target`'s result under `Defect`: `Result`, or another one. */ +template +using result_of = std::conditional_t, Result>; + +/** Shape `Target`'s parameter type under `Defect`: `Right`, or `Wrong`. */ +template +using shape_of = + std::conditional_t; + +/** A fixed view of `Size` bytes to read, or of one byte less under shape `Target`'s defect. */ +template +using sized_input = shape_of, fixed_input>; + +/** A fixed view of `Size` bytes to write, or of one byte less under shape `Target`'s defect. */ +template +using sized_output = shape_of, fixed_output>; + +/** The default value of `Result`, the stand-ins' every result. */ +template +constexpr Result done() noexcept { + return Result(); +} + +/** The state of every stand-in. */ +struct state_type {}; + +/** `move` and `reset`, each of which a defect may hit. */ +template +struct state_operations { + using state = state_type; + + static result_of move( + state& /*target_state*/, state& /*source_state*/) noexcept(nothrow) + requires present + { + return done>(); + } + + static result_of reset(state& /*engine_state*/) noexcept( + nothrow) + requires present + { + return done>(); + } +}; + +/** `move`, `reset` and a one-key `init(state, key)`, each of which a defect may hit. */ +template +struct keyed_operations : state_operations { + static result_of init( + state_type& /*engine_state*/, const_bytes /*key_bytes*/) noexcept(nothrow) + requires present + { + return done>(); + } +}; + +/** + * Whether `Satisfied::value` holds for the complete stand-in and fails for each of the + * missing, throwing and wrong-result defects of every operation in `Operations`. + */ +template