From 20a4e07f24a131e8ed0abcd224884c41024ffec1 Mon Sep 17 00:00:00 2001 From: R Date: Fri, 20 Nov 2026 23:28:55 -0300 Subject: [PATCH 01/28] crypto: P-256 key pairs from a raw scalar and validated public keys on BearSSL, with the family p256 and its default --- AGENTS.md | 3 +- build.jam | 13 +- doc/changelog.adoc | 2 +- doc/crypto.adoc | 2 + doc/curves.adoc | 15 +- doc/generated/backends-p256_keypair.adoc | 35 ++ doc/generated/backends-p256_public_key.adoc | 30 ++ doc/generated/default-aliases.adoc | 5 + doc/generated/defaults.adoc | 6 + doc/generated/jamfiles.adoc | 16 + doc/generated/matrix.adoc | 27 ++ doc/generated/messages.adoc | 48 +++ doc/generated/namespace-curves.adoc | 14 +- doc/generated/sizes.adoc | 18 + doc/generated/use-cases.adoc | 11 +- doc/llms.txt | 15 +- doc/p256.adoc | 94 +++++ doc/tables/crypto.json | 59 ++- example/Jamfile | 5 + example/p256_keys.cpp | 83 +++++ example/p256_keys.expected | 7 + include/webcpp/crypto.hpp | 8 +- include/webcpp/crypto/backends/bearssl.hpp | 110 +++++- include/webcpp/crypto/curves/p256.hpp | 338 ++++++++++++++++++ include/webcpp/crypto/detail/capabilities.hpp | 49 +++ include/webcpp/crypto/detail/defaults.hpp | 8 + include/webcpp/crypto/detail/p_curves.hpp | 133 +++++++ test/Jamfile | 21 +- test/allocation_bearssl_test.cpp | 18 +- test/capabilities_test.cpp | 24 ++ test/convenience_header_test.cpp | 11 +- test/default_backend_test.cpp | 8 + test/hex_test.cpp | 37 ++ test/messages/Jamfile | 2 + test/messages/p256_default_not_linked/Jamfile | 12 + .../p256_default_not_linked.cpp | 23 ++ test/messages/p256_on_sodium/Jamfile | 12 + .../p256_on_sodium/p256_on_sodium.cpp | 26 ++ test/msvc/Jamfile | 2 + test/msvc/p256_default_not_linked/Jamfile | 9 + test/msvc/p256_default_not_linked/app.cpp | 18 + test/msvc/p256_on_sodium/Jamfile | 9 + test/msvc/p256_on_sodium/app.cpp | 22 ++ test/p256_keys_bearssl_test.cpp | 292 +++++++++++++++ test/support/hex.hpp | 42 +++ test/support/p256_data.hpp | 38 ++ test/support/timing_seam.hpp | 23 +- test/timing_coverage_bearssl_test.cpp | 54 +++ test/windows_h_after_test.cpp | 1 + test/windows_h_before_test.cpp | 1 + 50 files changed, 1825 insertions(+), 34 deletions(-) create mode 100644 doc/generated/backends-p256_keypair.adoc create mode 100644 doc/generated/backends-p256_public_key.adoc create mode 100644 doc/p256.adoc create mode 100644 example/p256_keys.cpp create mode 100644 example/p256_keys.expected create mode 100644 include/webcpp/crypto/curves/p256.hpp create mode 100644 include/webcpp/crypto/detail/p_curves.hpp create mode 100644 test/hex_test.cpp create mode 100644 test/messages/p256_default_not_linked/Jamfile create mode 100644 test/messages/p256_default_not_linked/p256_default_not_linked.cpp create mode 100644 test/messages/p256_on_sodium/Jamfile create mode 100644 test/messages/p256_on_sodium/p256_on_sodium.cpp create mode 100644 test/msvc/p256_default_not_linked/Jamfile create mode 100644 test/msvc/p256_default_not_linked/app.cpp create mode 100644 test/msvc/p256_on_sodium/Jamfile create mode 100644 test/msvc/p256_on_sodium/app.cpp create mode 100644 test/p256_keys_bearssl_test.cpp create mode 100644 test/support/p256_data.hpp diff --git a/AGENTS.md b/AGENTS.md index aa184ecd..75edcc04 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -40,7 +40,8 @@ specific to crypto. - An algorithm type does every guard; a backend's header supplies only the six traits of `detail/engines.hpp` (`block_state`, `block_engine`, `gcm_state`, `gcm_engine`, `aead_state`, - `aead_engine`) and, for the curves and `hybrid`, the functions of its own header. + `aead_engine`), the two of `detail/p_curves.hpp` per P-curve (`p_curve_state`, + `p_curve_engine`) and, for the other curves and `hybrid`, the functions of its own header. - A new public function that calls a backend holds `detail::timing_guard` as its first statement (it sets arm64's DIT for the call, `detail/timing.hpp`) and joins the coverage test of its backend, `test/timing_coverage__test.cpp`, which checks through the seam diff --git a/build.jam b/build.jam index 1b3d1f62..1b6d9ba4 100644 --- a/build.jam +++ b/build.jam @@ -4,7 +4,7 @@ # accompanying file LICENSE_1_0.txt or copy at # https://www.boost.org/LICENSE_1_0.txt) -# crypto: authenticated encryption, randomness, secp256k1, Ed25519 and X25519 +# crypto: authenticated encryption, randomness, secp256k1, Ed25519, X25519 and P-256 # over C backends. # A program names /webcpp/crypto//crypto and the library of each backend it # uses, /third_party// (third_party/Jamfile), or, for OpenSSL, @@ -243,4 +243,15 @@ rule secp256k1_silent_payments-default-linked ( properties * ) } } alias secp256k1_silent_payments-default : : : : @secp256k1_silent_payments-default-linked ; +rule p256-default-linked ( properties * ) +{ + switch [ webcpp-target.target-of $(properties) ] + { + case native : return /third_party//bearssl ; + case wasip2 : return /third_party//bearssl ; + case wasip3 : return /third_party//bearssl ; + case emscripten : return /third_party//bearssl ; + } +} +alias p256-default : : : : @p256-default-linked ; # generate.py: end the defaults' aliases diff --git a/doc/changelog.adoc b/doc/changelog.adoc index f69b6660..5604b69f 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -19,7 +19,7 @@ of every version are on webcpp's index page. * Added crypto, C-backed primitives setting DIT on arm64 macOS and Linux: ciphers, curves, randomness, fixed-value errors in webcpp.crypto, `+[[nodiscard]]+` results, WEBCPP_CRYPTO_HAS_THREADS, defined natively and with Emscripten's -pthread unless WEBCPP_CRYPTO_NO_THREADS is. * Added equal, random_device, pem (PEM on libsodium), ciphers::aes128, aes192 and aes256, the AES block cipher, and ciphers::gcm, aes128_gcm and aes256_gcm: AES-GCM in place, incremental seal, failed opens zeroing data. * Added supports_v with its family tags, the capability table per target, default_backend_t and /webcpp/crypto//-default per family and target (secp256k1's modules among them), and refusals naming their Jamfile line. -* Added backends::bearssl (AES-GCM alone, allocating nothing), backends::openssl via /webcpp/crypto//openssl natively and on WASI (allocating at make only, or natively in openssl_memory_resource with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE), and backends::ctaes (block cipher alone). +* Added backends::bearssl (AES-GCM, ChaCha20-Poly1305, P-256 key pairs; allocating nothing), backends::openssl natively and on WASI (allocating at make only, or in openssl_memory_resource with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE), and backends::ctaes (block cipher alone). * Added curves::secp256k1: key pairs, BIP340, hedged and recoverable ECDSA, raw and hashed ECDH, strict DER, low-S, tweaks, SPKI, PKCS#8, PEM, BIP 324's ElligatorSwift, BIP 327's MuSig2, BIP 352's silent payments. * Added curves::ed25519 and curves::x25519 on libsodium: strict verification over twelve edge cases, Ed25519ph over hash's sha2_512 (/webcpp/crypto//crypto brings hash), the conversion, agree refusing all-zero secrets, RFC 8410's SPKI and PKCS#8. * Added backends::sodium on /third_party//sodium, shared with webcpp::hash, every backend's link-time canary and C suite, and ciphers::aead: chacha20_poly1305 (also BearSSL, OpenSSL), the original form, xchacha20_poly1305, failed seals and opens zeroing data. diff --git a/doc/crypto.adoc b/doc/crypto.adoc index a3dc4cdb..4e5ffe6e 100644 --- a/doc/crypto.adoc +++ b/doc/crypto.adoc @@ -62,6 +62,8 @@ include::x25519.adoc[] include::kx.adoc[] +include::p256.adoc[] + include::formats.adoc[] include::hybrid.adoc[] diff --git a/doc/curves.adoc b/doc/curves.adoc index 4630790a..2e896299 100644 --- a/doc/curves.adoc +++ b/doc/curves.adoc @@ -15,8 +15,8 @@ back from the point to the number is infeasible. On a curve a program can on a key*, so that two parties who only exchanged public keys share a secret (link:https://en.wikipedia.org/wiki/Elliptic-curve_Diffie%E2%80%93Hellman[Wikipedia]). -The namespace `webcpp::crypto::curves` holds three curves in this version, the -three columns of the table below. The first is secp256k1 (link:https://www.secg.org/sec2-v2.pdf[SEC 2]; +The namespace `webcpp::crypto::curves` holds four curves in this version, the +columns of the table below. The first is secp256k1 (link:https://www.secg.org/sec2-v2.pdf[SEC 2]; link:https://en.bitcoin.it/wiki/Secp256k1[Bitcoin Wiki]), the curve of Bitcoin, Ethereum and Nostr (<>). This version covers Bitcoin's keys and signatures, Nostr's event signatures (NIP-01) and the raw @@ -63,10 +63,13 @@ pieces (link:https://www.rfc-editor.org/rfc/rfc8032[RFC 8032]; Curve25519, the same curve in another form, with the conversion of an Ed25519 key to it (link:https://www.rfc-editor.org/rfc/rfc7748[RFC 7748]; <>), and libsodium's key exchange on it, `crypto_kx` -(<>). A program chooses a curve for compatibility: a signature on one -curve is checked only with that curve, and the curve of passkeys and TLS -certificates, P-256, is another, which this version does not offer. Ed25519's -and X25519's keys leave a program, and enter it, in the standard forms OpenSSL +(<>). The fourth is P-256, NIST's curve of FIPS 186-5, the curve of +browsers' WebCrypto, of passkeys and of TLS certificates, on BearSSL: key pairs +made from a scalar or drawn, and public keys validated once +(link:https://csrc.nist.gov/pubs/fips/186-5/final[FIPS 186-5]; +<>). A program chooses a curve for compatibility: a signature on +one curve is checked only with that curve, and a browser's peer needs P-256. +Ed25519's and X25519's keys leave a program, and enter it, in the standard forms OpenSSL and WebCrypto use, SPKI and PKCS#8, as DER or PEM text (<>). include::generated/namespace-curves.adoc[] diff --git a/doc/generated/backends-p256_keypair.adoc b/doc/generated/backends-p256_keypair.adoc new file mode 100644 index 00000000..941979e8 --- /dev/null +++ b/doc/generated/backends-p256_keypair.adoc @@ -0,0 +1,35 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, +// the message tests and the Jamfile fixtures: run it again, never edit this file. + +The backends of `+curves::p256::keypair+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|BearSSL +|`+/third_party//bearssl+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+p256_keys_bearssl+`, `+allocation_bearssl+`) + +|libsodium +|`+/third_party//sodium+` +|`++` +|refused at compile time (`+p256_on_sodium+`) +|=== + +A call that names no backend takes the family's default on each target, whatever the program links, as <> gives it with its reasons and tests: + +[cols="1,1",options="header"] +|=== +|Target |Default + +|native, wasip2, wasip3, emscripten +|BearSSL +|=== diff --git a/doc/generated/backends-p256_public_key.adoc b/doc/generated/backends-p256_public_key.adoc new file mode 100644 index 00000000..a24b63d6 --- /dev/null +++ b/doc/generated/backends-p256_public_key.adoc @@ -0,0 +1,30 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, +// the message tests and the Jamfile fixtures: run it again, never edit this file. + +The backends of `+curves::p256::public_key+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|BearSSL +|`+/third_party//bearssl+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+p256_keys_bearssl+`, `+allocation_bearssl+`) +|=== + +A call that names no backend takes the family's default on each target, whatever the program links, as <> gives it with its reasons and tests: + +[cols="1,1",options="header"] +|=== +|Target |Default + +|native, wasip2, wasip3, emscripten +|BearSSL +|=== diff --git a/doc/generated/default-aliases.adoc b/doc/generated/default-aliases.adoc index 511a435e..54c06697 100644 --- a/doc/generated/default-aliases.adoc +++ b/doc/generated/default-aliases.adoc @@ -95,4 +95,9 @@ |BIP 352 silent payments |`+/third_party//secp256k1+` on every target |<> + +|`+/webcpp/crypto//p256-default+` +|P-256 +|`+/third_party//bearssl+` on every target +|<> |=== diff --git a/doc/generated/defaults.adoc b/doc/generated/defaults.adoc index 4f46ec99..733a21b9 100644 --- a/doc/generated/defaults.adoc +++ b/doc/generated/defaults.adoc @@ -136,4 +136,10 @@ |libsecp256k1 |the only backend (link:https://github.com/bitcoin-core/secp256k1#readme[libsecp256k1's README]) |`+secp256k1_silent_payments+`, `+default_backend_none_linked+` + +|P-256 +|native, wasip2, wasip3, emscripten +|BearSSL +|the one backend of the P-curves on all four targets, constant time by design and allocating nothing (link:https://www.bearssl.org/[BearSSL, its home page]); OpenSSL and Botan join in increments 8 and 7 +|`+p256_keys_bearssl+`, `+default_backend_none_linked+` |=== diff --git a/doc/generated/jamfiles.adoc b/doc/generated/jamfiles.adoc index c46be348..e928e727 100644 --- a/doc/generated/jamfiles.adoc +++ b/doc/generated/jamfiles.adoc @@ -199,6 +199,22 @@ It prints: include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/openssl_linked/openssl_linked.outcome[tag=output] ---- +`+p256_default+`:: RFC 6979's P-256 key made from its scalar on P-256's default on every target, its public key RFC 6979's, with the one line `+/webcpp/crypto//p256-default+`, which links BearSSL. ++ +Its Jamfile, built and run on native, wasip2, wasip3, emscripten: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/p256_default/Jamfile[tag=jamfile] +---- ++ +It prints: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/p256_default/p256_default.outcome[tag=output] +---- + `+pem_default+`:: RFC 8410's Ed25519 public key read from PEM and armoured again to the same text on PEM's default on every target, with the one line `+/webcpp/crypto//pem-default+`, which links libsodium. + Its Jamfile, built and run on native, wasip2, wasip3, emscripten: diff --git a/doc/generated/matrix.adoc b/doc/generated/matrix.adoc index 795f8f4e..ca1ee9be 100644 --- a/doc/generated/matrix.adoc +++ b/doc/generated/matrix.adoc @@ -225,6 +225,21 @@ |libsecp256k1 |native, wasip2, wasip3, emscripten |`+secp256k1_silent_payments+` + +|`+curves::p256::keypair+` +|BearSSL +|native, wasip2, wasip3, emscripten +|`+p256_keys_bearssl+`, `+allocation_bearssl+` + +|`+curves::p256::keypair+` +|libsodium +|refused at compile time +|`+p256_on_sodium+` + +|`+curves::p256::public_key+` +|BearSSL +|native, wasip2, wasip3, emscripten +|`+p256_keys_bearssl+`, `+allocation_bearssl+` |=== The same, by target: the backends each operation runs on. @@ -442,4 +457,16 @@ The same, by target: the backends each operation runs on. |libsecp256k1 |libsecp256k1 |libsecp256k1 + +|`+curves::p256::keypair+` +|BearSSL +|BearSSL +|BearSSL +|BearSSL + +|`+curves::p256::public_key+` +|BearSSL +|BearSSL +|BearSSL +|BearSSL |=== diff --git a/doc/generated/messages.adoc b/doc/generated/messages.adoc index e76f17c0..18c71d30 100644 --- a/doc/generated/messages.adoc +++ b/doc/generated/messages.adoc @@ -199,6 +199,18 @@ The fix: Name `+/webcpp/crypto//openssl+`, which builds OpenSSL 3.5.9; without b 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>+`. +|`+p256_default_not_linked+` +|native, wasip2, wasip3 +|`+webcpp::crypto: P-256's default backend on this target is BearSSL, which is not linked, and the one backend that has it there. Add /webcpp/crypto//p256-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//p256-default ; (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)+` + +The fix: Add `+/webcpp/crypto//p256-default+`, which links `+/third_party//bearssl+` on every target. + +|`+p256_on_sodium+` +|native, wasip2, wasip3 +|`+webcpp::crypto: sodium has no P-256. The backends that have it: bearssl (native, wasip2, wasip3, emscripten).+` + +The fix: Leave the backend out, as in `+curves::p256::keypair+`, or name `+backends::bearssl+`, and add `+/third_party//bearssl+`. + |`+pem_default_not_linked+` |native, wasip2, wasip3 |`+webcpp::crypto: PEM's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//pem-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//pem-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)+` @@ -788,6 +800,34 @@ On each target, the build's output contains: * emscripten: ** `+webcpp::crypto: /webcpp/crypto//openssl is named in a build for Emscripten, where webcpp does not build OpenSSL.+` +`+p256_default_not_linked_on_emscripten+`:: A program for Emscripten that makes a P-256 key pair on its default, BearSSL, and links none. The fix: As `+p256_default_not_linked+`. ++ +Its Jamfile: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/p256_default_not_linked_on_emscripten/Jamfile[tag=jamfile] +---- ++ +On each target, the build's output contains: ++ +* emscripten: +** `+webcpp::crypto: P-256's default backend on this target is BearSSL, which is not linked, and the one backend that has it there. Add /webcpp/crypto//p256-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//p256-default ; (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)+` + +`+p256_on_sodium_on_emscripten+`:: A program for Emscripten that names libsodium, which has no P-256, in a P-256 key pair's type. The fix: As `+p256_on_sodium+`. ++ +Its Jamfile: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/p256_on_sodium_on_emscripten/Jamfile[tag=jamfile] +---- ++ +On each target, the build's output contains: ++ +* emscripten: +** `+webcpp::crypto: sodium has no P-256. The backends that have it: bearssl (native, wasip2, wasip3, emscripten).+` + `+pem_default_not_linked_on_emscripten+`:: A program for Emscripten that armours DER as PEM on its default, libsodium, and links none. The fix: As `+pem_default_not_linked+`. + Its Jamfile: @@ -1006,6 +1046,14 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |Name `+/webcpp/crypto//openssl+`, which builds OpenSSL 3.5.9; without b2, put OpenSSL 3's `+include/+` first. +|`+p256_default_not_linked+` +|the compile +|Add `+/webcpp/crypto//p256-default+`, which links `+/third_party//bearssl+` on every target. + +|`+p256_on_sodium+` +|the compile +|Leave the backend out, as in `+curves::p256::keypair+`, or name `+backends::bearssl+`, and add `+/third_party//bearssl+`. + |`+pem_default_not_linked+` |the compile |Add `+/webcpp/crypto//pem-default+`, which links `+/third_party//sodium+` on every target. diff --git a/doc/generated/namespace-curves.adoc b/doc/generated/namespace-curves.adoc index f1b85eae..3a7cb050 100644 --- a/doc/generated/namespace-curves.adoc +++ b/doc/generated/namespace-curves.adoc @@ -7,57 +7,67 @@ // Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, // the message tests and the Jamfile fixtures: run it again, never edit this file. -[cols="2h,5,5,5",options="header"] +[cols="2h,5,5,5,5",options="header"] |=== -|Curve |`secp256k1` |`ed25519` |`x25519` +|Curve |`secp256k1` |`ed25519` |`x25519` |`p256` |What it does |BIP 340 Schnorr and ECDSA signatures, recoverable signatures, ECDH in three forms, tweaks, ElligatorSwift, MuSig2, silent payments, SPKI and PKCS#8 |Ed25519 signatures, and Ed25519ph over SHA-512 for a message given in pieces; the X25519 secret key of a key pair |Key agreement (Diffie-Hellman on Curve25519): two parties who exchanged public keys share a 32-byte secret; `kx_keypair`, libsodium's `crypto_kx`, gives a client and a server a session key for each direction +|Key pairs made from a 32-byte scalar or drawn from `random_device`, and public keys validated once, as SEC 1's uncompressed point or two coordinates |Security level |about 128 bits (link:https://www.secg.org/sec2-v2.pdf[SEC 2, Recommended Elliptic Curve Domain Parameters]) |about 128 bits (link:https://www.rfc-editor.org/rfc/rfc8032[RFC 8032, the Edwards-curve Digital Signature Algorithm (EdDSA)]) |about 128 bits (link:https://www.rfc-editor.org/rfc/rfc7748[RFC 7748, Elliptic Curves for Security (X25519 and X448)]) +|about 128 bits (link:https://www.secg.org/sec2-v2.pdf[SEC 2, Recommended Elliptic Curve Domain Parameters]) |Key sizes |secret 32 bytes; public 33 bytes compressed, 65 bytes uncompressed (link:https://www.secg.org/sec1-v2.pdf[SEC 1 version 2, Elliptic Curve Cryptography, sections 2.3.3 and 2.3.4: a point's encodings]), 32 bytes x-only, 64 bytes as ElligatorSwift (link:https://github.com/bitcoin/bips/blob/master/bip-0324.mediawiki[BIP 324, version 2 P2P encrypted transport protocol]); SPKI 56 or 88 bytes (link:https://www.rfc-editor.org/rfc/rfc5480[RFC 5480, Elliptic Curve Cryptography Subject Public Key Information]), PKCS#8 135 bytes (link:https://www.rfc-editor.org/rfc/rfc5208[RFC 5208, PKCS #8: Private-Key Information Syntax], link:https://www.rfc-editor.org/rfc/rfc5915[RFC 5915, Elliptic Curve Private Key Structure]) |secret 32 bytes (the seed); public 32 bytes |secret 32 bytes; public 32 bytes +|secret 32 bytes (the scalar); public 65 bytes uncompressed (link:https://www.secg.org/sec1-v2.pdf[SEC 1 version 2, Elliptic Curve Cryptography, sections 2.3.3 and 2.3.4: a point's encodings]) |Signature sizes |64 bytes, MuSig2's aggregate too (link:https://github.com/bitcoin/bips/blob/master/bip-0327.mediawiki[BIP 327, MuSig2 for BIP340-compatible multi-signatures]); 65 bytes recoverable; ECDSA in DER up to 72 |64 bytes |none: no signatures +|none yet: ECDSA comes next |Speed |BIP340 signature of a 32-byte message: native, libsecp256k1 9.02 µs; wasip2, libsecp256k1 53.9 µs; wasip3, libsecp256k1 65.9 µs; emscripten, libsecp256k1 63.9 µs (2026-11-20, Apple M5 Max, under load: read the spread; <>) |signature of a 32-byte message: native, libsodium 8.2 µs; wasip2, libsodium 19.8 µs; wasip3, libsodium 25.5 µs; emscripten, libsodium 20.6 µs (2026-11-20, Apple M5 Max, under load: read the spread; <>) |agreement of a secret key and a public key: native, libsodium 17.9 µs; wasip2, libsodium 49.5 µs; wasip3, libsodium 56 µs; emscripten, libsodium 41.3 µs (2026-11-20, Apple M5 Max, under load: read the spread; <>) +|not measured yet |Constant time, measured |libsecp256k1: native, Valgrind's memcheck (Linux; libsecp256k1's own `+ctime_tests.c+`, and webcpp's code around it: the key pair's making, its signatures and x-only tweak, ECDH in three forms, the secret key's tweaks and negation, and PKCS#8), MemorySanitizer (Linux, clang; the same paths as memcheck's) and dudect (judged off the runners GitHub hosts; `+ecdh_x+`), nothing found; wasip2, dudect (judged off the runners GitHub hosts; `+ecdh_x+`), nothing found; not measured yet on wasip3, emscripten (<>) |libsodium: native, Valgrind's memcheck (Linux), MemorySanitizer (Linux, clang) and dudect (judged off the runners GitHub hosts), nothing found; wasip2, dudect (judged off the runners GitHub hosts), nothing found; not measured yet on wasip3, emscripten (<>) |libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found, and dudect (judged off the runners GitHub hosts): 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 and Android where the CPU has it, as Apple requires of constant-time code (link:https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Enable-DIT-for-constant-time-cryptographic-operations[Apple, Writing ARM64 code for Apple platforms: enable DIT for constant-time cryptographic operations]); the lane's dudect sets nothing itself and measures what a program gets: \|t\| 1.8 to 2.8 against the threshold 10 (2026-11-21, five runs), while its `dudect_planted`, an early-exit scan of the secret key run inside the same guard, reads \|t\| 66.72 and 65.53 (2026-11-21): DIT does not hide a leak. Without DIT, dudect times `agree` with an all-zero secret key against random ones at \|t\| 6.7 to 14.5 (2026-11-19) and 4.3 to 7.8 (2026-11-21, three runs): about one nanosecond in 15 µs. Each on an Apple M5 Max, from a release build. libsodium does not set DIT, and webcpp sets nothing on x86, WebAssembly or Windows on ARM64; wasip2, dudect (judged off the runners GitHub hosts): an open finding, its cause measured: dudect times `agree` with an all-zero secret key against random ones at \|t\| 13 to 32 (2026-11-18; a fixed key against another fixed key: 22.9) and 107 to 260 (2026-11-19), and 25.25 in the lane on 2026-11-21, against the threshold 10, under wasmtime 47 on an Apple M5 Max, from a release build. The cause is Apple silicon's DIT (data-independent timing), which wasmtime does not set (link:https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Enable-DIT-for-constant-time-cryptographic-operations[Apple, Writing ARM64 code for Apple platforms: enable DIT for constant-time cryptographic operations]): with DIT set in wasmtime's main thread, an experiment and not the lane, the same case reads \|t\| 1.5 to 2.1; no branch on a secret was found in the WebAssembly or in wasmtime's compiled code. The lane cannot set DIT from inside the WebAssembly, so it prints this value on wasip2 without judging it; the CI's x86-64 run measures it next; not measured yet on wasip3, emscripten (<>) +|BearSSL: not measured yet (<>) |Standards |link:https://www.secg.org/sec2-v2.pdf[SEC 2, Recommended Elliptic Curve Domain Parameters], link:https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki[BIP 340, Schnorr signatures for secp256k1], link:https://www.rfc-editor.org/rfc/rfc6979[RFC 6979, deterministic ECDSA nonces], link:https://github.com/bitcoin/bips/blob/master/bip-0324.mediawiki[BIP 324, version 2 P2P encrypted transport protocol], link:https://github.com/bitcoin/bips/blob/master/bip-0327.mediawiki[BIP 327, MuSig2 for BIP340-compatible multi-signatures], link:https://github.com/bitcoin/bips/blob/master/bip-0352.mediawiki[BIP 352, Silent Payments] |link:https://www.rfc-editor.org/rfc/rfc8032[RFC 8032, the Edwards-curve Digital Signature Algorithm (EdDSA)], link:https://csrc.nist.gov/pubs/fips/186-5/final[FIPS 186-5, the Digital Signature Standard, which adds EdDSA] |link:https://www.rfc-editor.org/rfc/rfc7748[RFC 7748, Elliptic Curves for Security (X25519 and X448)] +|link:https://csrc.nist.gov/pubs/fips/186-5/final[FIPS 186-5, the Digital Signature Standard, which adds EdDSA], link:https://www.secg.org/sec2-v2.pdf[SEC 2, Recommended Elliptic Curve Domain Parameters], link:https://www.secg.org/sec1-v2.pdf[SEC 1 version 2, Elliptic Curve Cryptography, sections 2.3.3 and 2.3.4: a point's encodings] |Ecosystems that require it |Bitcoin (link:https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki[BIP 340, Schnorr signatures for secp256k1]), Ethereum (link:https://ethereum.github.io/yellowpaper/paper.pdf[The Ethereum yellow paper, appendix F: ECDSA on secp256k1]), Nostr (link:https://github.com/nostr-protocol/nips/blob/master/01.md[Nostr NIP-01, events signed with BIP 340 on secp256k1]) |SSH keys (link:https://www.rfc-editor.org/rfc/rfc8709[RFC 8709, Ed25519 and Ed448 public keys for SSH]), Signal's signatures on its Curve25519 keys (link:https://signal.org/docs/specifications/xeddsa/[Signal, the XEdDSA and VXEdDSA signature schemes]), Tor's identity keys (link:https://spec.torproject.org/cert-spec.html[Tor's specifications, Ed25519 certificates]), Solana's accounts (link:https://solana.com/docs/core/accounts[Solana's documentation, accounts and their Ed25519 keys]) |TLS 1.3 (link:https://www.rfc-editor.org/rfc/rfc8446#section-4.2.7[RFC 8446, TLS 1.3, section 4.2.7 (supported groups)]), SSH (link:https://www.rfc-editor.org/rfc/rfc8731[RFC 8731, Secure Shell key exchange with Curve25519]), WireGuard (link:https://www.wireguard.com/protocol/[WireGuard's protocol, cryptography]), Signal (link:https://signal.org/docs/specifications/x3dh/[Signal, the X3DH key agreement protocol]) +|passkeys' ES256 (link:https://www.w3.org/TR/webauthn-2/#sctn-alg-identifier[W3C Web Authentication, its algorithm identifiers: ES256 is ECDSA on P-256 with SHA-256]), TLS 1.3 (link:https://www.rfc-editor.org/rfc/rfc8446#section-4.2.7[RFC 8446, TLS 1.3, section 4.2.7 (supported groups)]) |Browsers' WebCrypto |no: WebCrypto offers P-256, P-384, P-521, Ed25519 and X25519, not secp256k1 (link:https://www.w3.org/TR/WebCryptoAPI/[W3C Web Cryptography API]) |yes: Ed25519 (link:https://www.w3.org/TR/WebCryptoAPI/[W3C Web Cryptography API]) |yes: X25519 (link:https://www.w3.org/TR/WebCryptoAPI/[W3C Web Cryptography API]) +|yes: P-256, for ECDSA and ECDH (link:https://www.w3.org/TR/WebCryptoAPI/[W3C Web Cryptography API]) |Choose it for compatibility with |Bitcoin's keys and signatures; Nostr's event signatures (link:https://github.com/nostr-protocol/nips/blob/master/01.md[Nostr NIP-01, events signed with BIP 340 on secp256k1]); Ethereum's ECDSA verification with a known key; ECDH in the raw x-coordinate form of Nostr's encrypted messages (link:https://github.com/nostr-protocol/nips/blob/master/44.md[Nostr NIP-44, encrypted payloads]); Ethereum's recoverable signatures and uncompressed keys (link:https://ethereum.github.io/yellowpaper/paper.pdf[The Ethereum yellow paper, appendix F: ECDSA on secp256k1]), the address hashing being a domain library's; BIP 32's tweaks of the full key, its derivation of the tweak being a domain library's (link:https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki[BIP 32, hierarchical deterministic wallets]); keys exchanged with OpenSSL as SPKI or PKCS#8 (link:https://www.rfc-editor.org/rfc/rfc5480[RFC 5480, Elliptic Curve Cryptography Subject Public Key Information], link:https://www.rfc-editor.org/rfc/rfc5915[RFC 5915, Elliptic Curve Private Key Structure]), in DER or PEM (link:https://www.rfc-editor.org/rfc/rfc7468[RFC 7468, textual encodings of PKIX, PKCS and CMS structures (PEM)]); Bitcoin's version 2 transport, whose keys are ElligatorSwift encodings (link:https://github.com/bitcoin/bips/blob/master/bip-0324.mediawiki[BIP 324, version 2 P2P encrypted transport protocol]); MuSig2's multisignatures (link:https://github.com/bitcoin/bips/blob/master/bip-0327.mediawiki[BIP 327, MuSig2 for BIP340-compatible multi-signatures]); silent payments (link:https://github.com/bitcoin/bips/blob/master/bip-0352.mediawiki[BIP 352, Silent Payments]), the addresses and transactions being a domain library's |SSH, Tor and Solana keys and signatures, and any protocol that names RFC 8032's Ed25519 or Ed25519ph; verification is strict (libsodium's rules), which some lenient verifiers are not. Not Bitcoin, Ethereum or Nostr, whose keys are secp256k1's |TLS 1.3's and SSH's key exchange, WireGuard, Signal; libsodium's `crypto_box` keys, and the session keys of `crypto_kx` with `kx_keypair` (link:https://doc.libsodium.org/key_exchange[libsodium's documentation, key exchange]). The Ed25519 public key of a peer converts with `curves::ed25519::to_x25519_public`. A shared secret goes through a KDF before it keys a cipher. Every case of Wycheproof's X25519 file is tested (link:https://github.com/C2SP/wycheproof[Project Wycheproof, test vectors for cryptographic libraries]) +|Browsers' WebCrypto, whose raw export of a P-256 public key is the uncompressed point `public_key::make` takes (link:https://www.w3.org/TR/WebCryptoAPI/[W3C Web Cryptography API]); passkeys and TLS. Not Bitcoin, Ethereum or Nostr, whose keys are secp256k1's |=== diff --git a/doc/generated/sizes.adoc b/doc/generated/sizes.adoc index 5d1d7391..41efe3a5 100644 --- a/doc/generated/sizes.adoc +++ b/doc/generated/sizes.adoc @@ -162,6 +162,24 @@ The lane sizes measured on 2026-11-19, at variant=release: native, clang-21 on D |+1,318,313 B, gzip +1,147,745 B |+1,320,113 B, gzip +1,148,250 B |+215,607 B, gzip +77,908 B + +|P-256 on BearSSL: ECDSA signature of a 32-byte SHA-256 digest +|not measured yet +|not measured yet +|not measured yet +|not measured yet + +|P-256 on BearSSL: ECDSA verification of a 32-byte SHA-256 digest +|not measured yet +|not measured yet +|not measured yet +|not measured yet + +|P-256 on BearSSL: x coordinate of the ECDH shared point with a peer's public key +|not measured yet +|not measured yet +|not measured yet +|not measured yet |=== OpenSSL: its cells differ by a few bytes whatever the operation: each fetches its algorithm by name from OpenSSL's default provider (link:https://docs.openssl.org/3.5/man7/crypto/[OpenSSL 3.5's crypto(7), algorithm fetching]), and a static link brings the provider's algorithms with it, not the operation's alone. diff --git a/doc/generated/use-cases.adoc b/doc/generated/use-cases.adoc index 8a4c9ec1..5511b05c 100644 --- a/doc/generated/use-cases.adoc +++ b/doc/generated/use-cases.adoc @@ -243,9 +243,10 @@ `+/webcpp/crypto//x25519-default+` |<> -|Use P-256 (passkeys, JWT's ES256) -|None in this version: secp256k1, Ed25519 and X25519 keys and signatures do not interoperate with this curve -|none -|none -|<> +|Signatures and key agreement a browser's WebCrypto verifies and derives (P-256 with SHA-256), webcpp::trystero's handshakes +|In `+curves::p256+`: `+keypair::make+`, `+keypair::generate+`, `+keypair::public_key+`, `+keypair::secret_scalar+`, `+public_key::make+` +|BearSSL +|`+/webcpp/crypto//crypto+` + +`+/webcpp/crypto//p256-default+` +|<> |=== diff --git a/doc/llms.txt b/doc/llms.txt index 1a4650e4..515b5924 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -1,6 +1,6 @@ # webcpp::crypto -> Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA and recoverable signatures, ECDH, tweaks, ElligatorSwift, MuSig2, silent payments), Ed25519 and Ed25519ph (RFC 8032), X25519 (RFC 7748), their keys in SPKI, PKCS#8 (RFC 8410) and PEM, libsodium's crypto_kx, the ChaCha20-Poly1305 AEADs, libsodium's secret boxes, boxes and sealed boxes, a random_device on the system's generator and a constant-time equal, each over a widely used, reviewed C library (BearSSL, OpenSSL, ctaes, libsecp256k1, libsodium) that the program names in its Jamfile. Hashing and HMAC are Boost.Hash2's; HKDF and password hashing are webcpp::hash's. Every failure is a boost::system::result value. Protocols (Bitcoin, Ethereum, Nostr) belong to domain libraries built on these primitives. +> Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA and recoverable signatures, ECDH, tweaks, ElligatorSwift, MuSig2, silent payments), Ed25519 and Ed25519ph (RFC 8032), X25519 (RFC 7748), P-256 key pairs and public keys on BearSSL, their keys in SPKI, PKCS#8 (RFC 8410) and PEM, libsodium's crypto_kx, the ChaCha20-Poly1305 AEADs, libsodium's secret boxes, boxes and sealed boxes, a random_device on the system's generator and a constant-time equal, each over a widely used, reviewed C library (BearSSL, OpenSSL, ctaes, libsecp256k1, libsodium) that the program names in its Jamfile. Hashing and HMAC are Boost.Hash2's; HKDF and password hashing are webcpp::hash's. Every failure is a boost::system::result value. Protocols (Bitcoin, Ethereum, Nostr) belong to domain libraries built on these primitives. Generated by doc/tables/generate.py with the page's tables. Page: https://webcpporg.github.io/libs/crypto/ @@ -169,6 +169,14 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - create_labeled_spend_key: The spend key of a labelled address (`..._create_labeled_spend_pubkey`). - make_prevouts_summary: The prevouts' summary (`..._recipient_prevouts_summary_create`) from the eligible inputs' public keys. - 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, a `secret<32>`. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten. Default: BearSSL on native, wasip2, wasip3, emscripten. Use it to: signatures and key agreement a browser's WebCrypto verifies and derives (P-256 with SHA-256), webcpp::trystero's handshakes. + - make: Makes a key pair from its secret scalar, as a program that kept `secret_scalar` 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). + - public_key: The public key, computed when the key pair was made. + - secret_scalar: The secret scalar, for a program that keeps the key pair and makes it again with `make`. +- [curves::p256::public_key](https://webcpporg.github.io/libs/crypto/#crypto-p256-keys): A validated P-256 public key, made from SEC 1's 65-byte uncompressed point or from its two coordinates; a point off the curve, a coordinate not below p or another form is `invalid_public_key`. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten. Default: BearSSL on native, wasip2, wasip3, emscripten. Use it to: signatures and key agreement a browser's WebCrypto verifies and derives (P-256 with SHA-256), webcpp::trystero's handshakes. + - make: Makes a public key from SEC 1's uncompressed point, as WebCrypto's `exportKey("raw")` writes it. + - uncompressed: The point, as WebCrypto's `exportKey("raw")` writes it. ## webcpp::crypto::hybrid @@ -207,6 +215,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - ElligatorSwift, native, wasip2, wasip3, emscripten: libsecp256k1; the only backend ([libsecp256k1's README](https://github.com/bitcoin-core/secp256k1#readme)). - MuSig2, native, wasip2, wasip3, emscripten: libsecp256k1; the only backend ([libsecp256k1's README](https://github.com/bitcoin-core/secp256k1#readme)). - BIP 352 silent payments, native, wasip2, wasip3, emscripten: libsecp256k1; the only backend ([libsecp256k1's README](https://github.com/bitcoin-core/secp256k1#readme)). +- P-256, native, wasip2, wasip3, emscripten: BearSSL; the one backend of the P-curves on all four targets, constant time by design and allocating nothing ([BearSSL, its home page](https://www.bearssl.org/)); OpenSSL and Botan join in increments 8 and 7. ## Constant time, measured @@ -228,6 +237,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - ElligatorSwift: libsecp256k1: native, Valgrind's memcheck (Linux; libsecp256k1's own `ctime_tests.c`, and webcpp's `ellswift_create` and `ellswift_xdh` around it) and MemorySanitizer (Linux, clang; the same paths as memcheck's), nothing found; not measured yet on wasip2, wasip3, emscripten. - MuSig2: libsecp256k1: native, Valgrind's memcheck (Linux; libsecp256k1's own `ctime_tests.c`, and webcpp's `nonce_gen` and `partial_sign` around it) and MemorySanitizer (Linux, clang; the same paths as memcheck's), nothing found; not measured yet on wasip2, wasip3, emscripten. - BIP 352 silent payments: libsecp256k1: native, Valgrind's memcheck (Linux; libsecp256k1's own `ctime_tests.c`, and webcpp's `create_outputs`, `create_label` and `scan_outputs` around it, each workspace's wipe included) and MemorySanitizer (Linux, clang; the same paths as memcheck's), nothing found; not measured yet on wasip2, wasip3, emscripten. +- P-256: BearSSL: not measured yet. ## Rules of use @@ -279,7 +289,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [Send messages between two people who know each other's public keys, as NaCl's and libsodium's crypto_box](https://webcpporg.github.io/libs/crypto/#crypto-box): `box::make`, `box::seal`, `box::open` (webcpp::crypto::hybrid); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//box_xsalsa20poly1305-default. Example: example/box_messages.cpp. - [Let anyone send a message that only the recipient can read, without saying who sent it (anonymous feedback, a drop box)](https://webcpporg.github.io/libs/crypto/#crypto-sealed-box): `sealed_box::seal`, `sealed_box::open` (webcpp::crypto::hybrid); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//sealed_box-default. Example: example/file_share.cpp. - [Share a file with someone known only by a public key, as a file-sharing app does](https://webcpporg.github.io/libs/crypto/#crypto-everyday-files): `ciphers::secretbox<>` for the file under a key drawn for it, `hybrid::sealed_box::seal` for that key (webcpp::crypto); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//secretbox_xsalsa20poly1305-default /webcpp/crypto//sealed_box-default /webcpp/crypto//x25519-default. Example: example/file_share.cpp. -- [Use P-256 (passkeys, JWT's ES256)](https://webcpporg.github.io/libs/crypto/#crypto-curves): secp256k1, Ed25519 and X25519 keys and signatures do not interoperate with this curve (none in this version); backend none; Jamfile none. +- [Signatures and key agreement a browser's WebCrypto verifies and derives (P-256 with SHA-256), webcpp::trystero's handshakes](https://webcpporg.github.io/libs/crypto/#crypto-p256-keys): `keypair::make`, `keypair::generate`, `keypair::public_key`, `keypair::secret_scalar`, `public_key::make` (webcpp::crypto::curves::p256); backend BearSSL; Jamfile /webcpp/crypto//crypto /webcpp/crypto//p256-default. Example: example/p256_keys.cpp. ## Examples @@ -303,6 +313,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - example/musig_wallet.cpp: A wallet split across two devices, a phone and a laptop, whose coins move only when both sign (BIP 327's MuSig2): the two public keys are sorted and aggregated into one; each device makes a nonce and sends its public half; each signs its part once every public nonce is in; the parts add up to one BIP 340 signature under the one x-only key, which on the chain looks like any single signer's. The devices' secrets are fixed here, so that the program runs the same each time; a real wallet draws them from crypto's random device. The nonces are fresh in every run, drawn inside nonce_gen; nothing random is printed. - example/openssl_memory.cpp: Sends every allocation of OpenSSL's to the program's own memory resource, natively, then seals and opens one block with AES-256-GCM on OpenSSL, on a worker thread as an audio engine's or a server's would. Built with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE, /webcpp/crypto//openssl and threads (example/Jamfile). - example/order_reference.cpp: Turns a sequential order id into an opaque 16-byte reference with the raw AES block cipher, and back. Customers then cannot guess other orders' numbers. This is NOT authenticated encryption: a forged reference still decrypts, to garbage, so the program checks the padding. +- example/p256_keys.cpp: Makes a P-256 key pair from RFC 6979's key, prints its public key as the 65 bytes WebCrypto's exportKey("raw") gives, keeps its scalar and makes the same key pair from it again, then imports that public key as a peer's and refuses the same bytes with one bit changed. Draws a fresh key pair too, whose bytes differ on every run and are not printed. - example/recover_signer.cpp: Finds who signed a message without being sent their key, as Ethereum finds a transaction's signer: a wallet signs a message's hash with a recoverable signature, and a reader that holds no key recovers the signer's public key from the signature and the hash, then compares it with the key the wallet published. Recovery always finds some key, so the comparison is the check: a changed message recovers another key. - example/reset_token.cpp: Draws a 32-byte password-reset token and a six-digit one-time code from the system's random generator. Tokens that can be guessed or repeated let an attacker take over accounts, so both come from random_device, never from rand() or the clock. - example/schnorr_sign.cpp: Signs BIP340's first test vector with secp256k1 and verifies it, then tweaks the key pair by a 32-byte tweak, as a domain library derives one, and signs and verifies under the tweaked key. Prints each key and signature in hex. diff --git a/doc/p256.adoc b/doc/p256.adoc new file mode 100644 index 00000000..9645b514 --- /dev/null +++ b/doc/p256.adoc @@ -0,0 +1,94 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +[#crypto-p256] +=== P-256 + +`` is P-256, NIST's elliptic curve of FIPS 186-5 +(link:https://csrc.nist.gov/pubs/fips/186-5/final[FIPS 186-5]), also named +secp256r1 (link:https://www.secg.org/sec2-v2.pdf[SEC 2]), on BearSSL +(`/third_party//bearssl`, or `/webcpp/crypto//p256-default`, which links it on +every target), in the namespace `webcpp::crypto::curves::p256`. It is the curve +every browser's WebCrypto has (link:https://www.w3.org/TR/WebCryptoAPI/[W3C]), +the curve of passkeys, whose ES256 is ECDSA on P-256 with SHA-256 +(link:https://www.w3.org/TR/webauthn-2/#sctn-alg-identifier[W3C Web +Authentication]), and a key-agreement group of every TLS 1.3 client +(link:https://www.rfc-editor.org/rfc/rfc8446#section-4.2.7[RFC 8446]). An +ordinary application uses it to sign what a browser verifies and to agree on a +key with a browser, which derives the same secret with WebCrypto: the +handshakes of webcpp::trystero, whose peers run in browsers, are both. Its keys +do not interoperate with secp256k1's, Ed25519's or X25519's: a peer on P-256 +needs P-256. + +BearSSL is the family's one backend in this version, on all four targets: +constant time by design and allocating nothing +(link:https://www.bearssl.org/[BearSSL]). Natively it runs BearSSL's 64-bit +multiplications where the compiler has them, and the 32-bit code on WebAssembly, +whose 128-bit product is a library call whose timing nobody states. + +[#crypto-p256-keys] +==== Key pairs and public keys + +A P-256 secret key is a number, the *scalar* d, 32 bytes big-endian, between 1 +and the group order n minus 1; the public key is the point d times the +curve's generator (link:https://csrc.nist.gov/pubs/fips/186-5/final[FIPS +186-5]). `keypair::make(scalar)` makes a key pair from a scalar a program kept, +and refuses a scalar of another size with `invalid_key_size` and a scalar 0, +n or above with `invalid_secret_key`: that check runs in webcpp, in time +independent of the scalar, before BearSSL sees it. `keypair::generate()` draws +the scalar from `random_device`. `secret_scalar()` gives the scalar back as a +`secret<32>`, which wipes itself, and `make` of it gives the same key pair: the +way a program stores a key pair and loads it again. The key pair computes its +public point once, when it is made, wipes the scalar when it is moved from and +destroyed, and answers `invalid_state` moved from. + +A `public_key` is a point that the type guarantees valid, kept as SEC 1's +*uncompressed* form, 65 bytes: 04, then x and y +(link:https://www.secg.org/sec1-v2.pdf[SEC 1, section 2.3.3]), the bytes +WebCrypto's `exportKey("raw")` writes and `importKey("raw")` reads +(link:https://www.w3.org/TR/WebCryptoAPI/[W3C]). `public_key::make(bytes)` +makes one from those 65 bytes, `public_key::make(x, y)` from the two +coordinates, as a JSON Web Key carries them, and `uncompressed()` writes the +65 bytes back; the key pair's `public_key()` gives its own. A point refused is +`invalid_public_key`: another size, another first byte, a coordinate not below +the field prime p, a point off the curve. A `public_key` holds nothing secret +and is copied freely. + +include::generated/backends-p256_keypair.adoc[] + +include::generated/backends-p256_public_key.adoc[] + +*Example.* RFC 6979's P-256 key made from its scalar, its public key exported, +the key pair made again from its kept scalar, the public key imported as a +peer's, the same bytes with one bit changed refused, and a key pair drawn from +the system's generator: + +[source,cpp] +---- +include::{examples}/p256_keys.cpp[tag=program] +---- + +[listing] +---- +include::{examples}/p256_keys.expected[] +---- + +*Pitfalls.* + +* A scalar stored outside a `secret<32>` outlives the key pair: the key pair +and `secret_scalar`'s result wipe their bytes, but a copy in a string, a log or +a file stays where it was written. Keep the scalar in the `secret<32>` until it +is encrypted or written to the key store, and never print it. +* A peer's key is made into a `public_key` once, where it arrives, and kept: +made again for every message, it costs a point check each time, and code that +keeps the bytes instead may skip the check on some path. The check matters: a +point off the curve, combined with a secret key, is how invalid-curve attacks +begin (link:https://en.wikipedia.org/wiki/Elliptic-curve_Diffie%E2%80%93Hellman[Wikipedia]). +* The compressed form, 33 bytes that start with 02 or 03 +(link:https://www.secg.org/sec1-v2.pdf[SEC 1, section 2.3.3]), is refused with +`invalid_public_key`: BearSSL decodes uncompressed points alone. WebCrypto's +raw export is uncompressed, so a browser's key arrives in the form `make` +takes; a key a tool sends compressed is decompressed by that tool first. diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 65ec1a93..eae5a8da 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -1,7 +1,7 @@ { "comment": "The data of crypto's generated tables and of llms.txt; doc/tables/generate.py reads it with the test Jamfiles, the message tests and the superproject's Jamfile fixtures, and writes doc/generated/, doc/llms.txt, include/webcpp/crypto/detail/capabilities.hpp, include/webcpp/crypto/detail/defaults.hpp and test/capabilities_test.cpp. The capability table is `families`: per family its algorithms, the targets on which each backend has it (each claimed only where a test of the family's operations on that backend runs), constant time per target where it differs from the backend's own `constant_time` (X25519 on wasip2, an open finding, and natively without arm64's DIT, the cause of both), with `constant_time_checker` naming the checker that measured it where that is not every checker of the target, and the default per target, one whatever the program links (design D32), with its reason and the tests that fix it (a row of some of `compilers` restates its target's default for them, with a reason of their own, and each compiler of a target has one row), from which come include/webcpp/crypto/detail/defaults.hpp and the refusal that says what a program whose default is not linked needs; a backend with `targets`, where it is built, is a tag of `backends`. A name in a text is written between backticks, as Markdown writes code: the tables show it as code and llms.txt keeps the backticks. A comparison table's cell {speed:} or {constant_time:} is written from doc/performance.json or from the family's `constant_time`, and each cell of a column a namespace lists in `cited` cites a source or begins with \"none\". Edit this file, then run python3 libs/crypto/doc/tables/generate.py; the doc build runs it with --check.", "page": "https://webcpporg.github.io/libs/crypto/", - "llms": "Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA and recoverable signatures, ECDH, tweaks, ElligatorSwift, MuSig2, silent payments), Ed25519 and Ed25519ph (RFC 8032), X25519 (RFC 7748), their keys in SPKI, PKCS#8 (RFC 8410) and PEM, libsodium's crypto_kx, the ChaCha20-Poly1305 AEADs, libsodium's secret boxes, boxes and sealed boxes, a random_device on the system's generator and a constant-time equal, each over a widely used, reviewed C library (BearSSL, OpenSSL, ctaes, libsecp256k1, libsodium) that the program names in its Jamfile. Hashing and HMAC are Boost.Hash2's; HKDF and password hashing are webcpp::hash's. Every failure is a boost::system::result value. Protocols (Bitcoin, Ethereum, Nostr) belong to domain libraries built on these primitives.", + "llms": "Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA and recoverable signatures, ECDH, tweaks, ElligatorSwift, MuSig2, silent payments), Ed25519 and Ed25519ph (RFC 8032), X25519 (RFC 7748), P-256 key pairs and public keys on BearSSL, their keys in SPKI, PKCS#8 (RFC 8410) and PEM, libsodium's crypto_kx, the ChaCha20-Poly1305 AEADs, libsodium's secret boxes, boxes and sealed boxes, a random_device on the system's generator and a constant-time equal, each over a widely used, reviewed C library (BearSSL, OpenSSL, ctaes, libsecp256k1, libsodium) that the program names in its Jamfile. Hashing and HMAC are Boost.Hash2's; HKDF and password hashing are webcpp::hash's. Every failure is a boost::system::result value. Protocols (Bitcoin, Ethereum, Nostr) belong to domain libraries built on these primitives.", "targets": ["native", "wasip2", "wasip3", "emscripten"], "compilers": {"clang": "Clang", "gcc": "GCC", "msvc": "MSVC"}, "checkers": {"memcheck": "Valgrind's memcheck (Linux)", "msan": "MemorySanitizer (Linux, clang)", "dudect": "dudect (judged off the runners GitHub hosts)"}, @@ -39,6 +39,8 @@ "bcryptgenrandom": ["Microsoft, BCryptGenRandom", "https://learn.microsoft.com/en-us/windows/win32/api/bcrypt/nf-bcrypt-bcryptgenrandom"], "getrandomvalues": ["W3C Web Cryptography API, getRandomValues", "https://www.w3.org/TR/WebCryptoAPI/#Crypto-method-getRandomValues"], "wasi-random": ["WASI, wasi:random", "https://github.com/WebAssembly/wasi-random"], + "bearssl": ["BearSSL, its home page", "https://www.bearssl.org/"], + "webauthn": ["W3C Web Authentication, its algorithm identifiers: ES256 is ECDSA on P-256 with SHA-256", "https://www.w3.org/TR/webauthn-2/#sctn-alg-identifier"], "bearssl-ct": ["BearSSL, constant-time crypto", "https://www.bearssl.org/constanttime.html"], "bearssl-ctmul": ["BearSSL, constant-time multiplications", "https://www.bearssl.org/ctmul.html"], "ctaes": ["ctaes, constant-time AES", "https://github.com/bitcoin/bitcoin/tree/master/src/crypto/ctaes"], @@ -645,6 +647,31 @@ "what": "BIP 352's silent payments: the sender's outputs to a reusable address of a scan and a spend key, the recipient's labels, and its scan of a transaction's outputs.", "section": "crypto-secp256k1-silent-payments", "backends": {"secp256k1": {"tests": ["secp256k1_silent_payments"]}} + }, + { + "id": "p256_keypair", + "family": "p256", + "functions": ["basic_keypair::make", "generate", "public_key", "secret_scalar"], + "namespace": "curves", + "api": "curves::p256::keypair", + "header": "", + "what": "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, a `secret<32>`.", + "section": "crypto-p256-keys", + "backends": { + "bearssl": {"tests": ["p256_keys_bearssl", "allocation_bearssl"]}, + "sodium": {"refused": "p256_on_sodium"} + } + }, + { + "id": "p256_public_key", + "family": "p256", + "functions": ["basic_public_key::make", "uncompressed"], + "namespace": "curves", + "api": "curves::p256::public_key", + "header": "", + "what": "A validated P-256 public key, made from SEC 1's 65-byte uncompressed point or from its two coordinates; a point off the curve, a coordinate not below p or another form is `invalid_public_key`.", + "section": "crypto-p256-keys", + "backends": {"bearssl": {"tests": ["p256_keys_bearssl", "allocation_bearssl"]}} } ], "families": [ @@ -970,6 +997,24 @@ "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"}} } + }, + { + "name": "p256", + "title": "P-256", + "group": "curves::p256", + "since": "0.3", + "measured": "ECDSA signature of a 32-byte SHA-256 digest", + "sized_operations": {"verify_ecdsa": "ECDSA verification of a 32-byte SHA-256 digest", "ecdh_x": "x coordinate of the ECDH shared point with a peer's public key"}, + "header": "", + "names": [ + {"name": "p256", "title": "P-256", "type": "curves::p256::basic_keypair<{backend}>"} + ], + "default": [ + {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "bearssl", "tests": ["p256_keys_bearssl", "default_backend_none_linked"], "why": "the one backend of the P-curves on all four targets, constant time by design and allocating nothing ({bearssl}); OpenSSL and Botan join in increments 8 and 7"} + ], + "backends": { + "bearssl": {"targets": "all"} + } } ], "rules": [ @@ -1037,7 +1082,8 @@ "rows": [ ["`secp256k1`", "BIP 340 Schnorr and ECDSA signatures, recoverable signatures, ECDH in three forms, tweaks, ElligatorSwift, MuSig2, silent payments, SPKI and PKCS#8", "about 128 bits ({sec2})", "secret 32 bytes; public 33 bytes compressed, 65 bytes uncompressed ({sec1}), 32 bytes x-only, 64 bytes as ElligatorSwift ({bip324}); SPKI 56 or 88 bytes ({rfc5480}), PKCS#8 135 bytes ({rfc5208}, {rfc5915})", "64 bytes, MuSig2's aggregate too ({bip327}); 65 bytes recoverable; ECDSA in DER up to 72", "{speed:secp256k1}", "{constant_time:secp256k1}", "{sec2}, {bip340}, {rfc6979}, {bip324}, {bip327}, {bip352}", "Bitcoin ({bip340}), Ethereum ({ethereum}), Nostr ({nip01})", "no: WebCrypto offers P-256, P-384, P-521, Ed25519 and X25519, not secp256k1 ({webcrypto})", "Bitcoin's keys and signatures; Nostr's event signatures ({nip01}); Ethereum's ECDSA verification with a known key; ECDH in the raw x-coordinate form of Nostr's encrypted messages ({nip44}); Ethereum's recoverable signatures and uncompressed keys ({ethereum}), the address hashing being a domain library's; BIP 32's tweaks of the full key, its derivation of the tweak being a domain library's ({bip32}); keys exchanged with OpenSSL as SPKI or PKCS#8 ({rfc5480}, {rfc5915}), in DER or PEM ({rfc7468}); Bitcoin's version 2 transport, whose keys are ElligatorSwift encodings ({bip324}); MuSig2's multisignatures ({bip327}); silent payments ({bip352}), the addresses and transactions being a domain library's"], ["`ed25519`", "Ed25519 signatures, and Ed25519ph over SHA-512 for a message given in pieces; the X25519 secret key of a key pair", "about 128 bits ({rfc8032})", "secret 32 bytes (the seed); public 32 bytes", "64 bytes", "{speed:ed25519}", "{constant_time:ed25519}", "{rfc8032}, {fips186-5}", "SSH keys ({rfc8709}), Signal's signatures on its Curve25519 keys ({signal-xeddsa}), Tor's identity keys ({tor-cert-spec}), Solana's accounts ({solana-accounts})", "yes: Ed25519 ({webcrypto})", "SSH, Tor and Solana keys and signatures, and any protocol that names RFC 8032's Ed25519 or Ed25519ph; verification is strict (libsodium's rules), which some lenient verifiers are not. Not Bitcoin, Ethereum or Nostr, whose keys are secp256k1's"], - ["`x25519`", "Key agreement (Diffie-Hellman on Curve25519): two parties who exchanged public keys share a 32-byte secret; `kx_keypair`, libsodium's `crypto_kx`, gives a client and a server a session key for each direction", "about 128 bits ({rfc7748})", "secret 32 bytes; public 32 bytes", "none: no signatures", "{speed:x25519}", "{constant_time:x25519}", "{rfc7748}", "TLS 1.3 ({rfc8446-groups}), SSH ({rfc8731}), WireGuard ({wireguard}), Signal ({x3dh})", "yes: X25519 ({webcrypto})", "TLS 1.3's and SSH's key exchange, WireGuard, Signal; libsodium's `crypto_box` keys, and the session keys of `crypto_kx` with `kx_keypair` ({libsodium-kx}). The Ed25519 public key of a peer converts with `curves::ed25519::to_x25519_public`. A shared secret goes through a KDF before it keys a cipher. Every case of Wycheproof's X25519 file is tested ({wycheproof})"] + ["`x25519`", "Key agreement (Diffie-Hellman on Curve25519): two parties who exchanged public keys share a 32-byte secret; `kx_keypair`, libsodium's `crypto_kx`, gives a client and a server a session key for each direction", "about 128 bits ({rfc7748})", "secret 32 bytes; public 32 bytes", "none: no signatures", "{speed:x25519}", "{constant_time:x25519}", "{rfc7748}", "TLS 1.3 ({rfc8446-groups}), SSH ({rfc8731}), WireGuard ({wireguard}), Signal ({x3dh})", "yes: X25519 ({webcrypto})", "TLS 1.3's and SSH's key exchange, WireGuard, Signal; libsodium's `crypto_box` keys, and the session keys of `crypto_kx` with `kx_keypair` ({libsodium-kx}). The Ed25519 public key of a peer converts with `curves::ed25519::to_x25519_public`. A shared secret goes through a KDF before it keys a cipher. Every case of Wycheproof's X25519 file is tested ({wycheproof})"], + ["`p256`", "Key pairs made from a 32-byte scalar or drawn from `random_device`, and public keys validated once, as SEC 1's uncompressed point or two coordinates", "about 128 bits ({sec2})", "secret 32 bytes (the scalar); public 65 bytes uncompressed ({sec1})", "none yet: ECDSA comes next", "{speed:p256}", "{constant_time:p256}", "{fips186-5}, {sec2}, {sec1}", "passkeys' ES256 ({webauthn}), TLS 1.3 ({rfc8446-groups})", "yes: P-256, for ECDSA and ECDH ({webcrypto})", "Browsers' WebCrypto, whose raw export of a P-256 public key is the uncompressed point `public_key::make` takes ({webcrypto}); passkeys and TLS. Not Bitcoin, Ethereum or Nostr, whose keys are secp256k1's"] ] }, "hybrid": { @@ -1085,7 +1131,7 @@ {"need": "Send messages between two people who know each other's public keys, as NaCl's and libsodium's crypto_box", "namespace": "webcpp::crypto::hybrid", "api": "`box::make`, `box::seal`, `box::open`", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//box_xsalsa20poly1305-default", "example": "box_messages", "section": "crypto-box"}, {"need": "Let anyone send a message that only the recipient can read, without saying who sent it (anonymous feedback, a drop box)", "namespace": "webcpp::crypto::hybrid", "api": "`sealed_box::seal`, `sealed_box::open`", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//sealed_box-default", "example": "file_share", "section": "crypto-sealed-box"}, {"need": "Share a file with someone known only by a public key, as a file-sharing app does", "namespace": "webcpp::crypto", "api": "`ciphers::secretbox<>` for the file under a key drawn for it, `hybrid::sealed_box::seal` for that key", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//secretbox_xsalsa20poly1305-default /webcpp/crypto//sealed_box-default /webcpp/crypto//x25519-default", "example": "file_share", "section": "crypto-everyday-files"}, - {"need": "Use P-256 (passkeys, JWT's ES256)", "namespace": "none in this version", "api": "secp256k1, Ed25519 and X25519 keys and signatures do not interoperate with this curve", "backend": "none", "jamfile": "none", "example": "", "section": "crypto-curves"} + {"need": "Signatures and key agreement a browser's WebCrypto verifies and derives (P-256 with SHA-256), webcpp::trystero's handshakes", "namespace": "webcpp::crypto::curves::p256", "api": "`keypair::make`, `keypair::generate`, `keypair::public_key`, `keypair::secret_scalar`, `public_key::make`", "backend": "BearSSL", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//p256-default", "example": "p256_keys", "section": "crypto-p256-keys"} ], "fixtures": { "web": "A web application: AES-256-GCM on BearSSL, the default on WebAssembly.", @@ -1099,6 +1145,7 @@ "secp256k1_ellswift_default": "Two key pairs' ElligatorSwift encodings, each decoded to its public key, and both sides of BIP 324's exchange agreeing, on ElligatorSwift's default on every target, with the one line `/webcpp/crypto//secp256k1_ellswift-default`, which links libsecp256k1.", "secp256k1_musig_default": "Two key pairs' public keys aggregated with BIP 327's MuSig2, a message signed in its two rounds and the aggregate verified as one BIP 340 signature, on MuSig2's default on every target, with the one line `/webcpp/crypto//secp256k1_musig-default`, which links libsecp256k1.", "secp256k1_silent_payments_default": "A BIP 352 silent payments recipient, its scan and spend keys, paid from one input and the payment found by a scan of the output, on silent payments' default on every target, with the one line `/webcpp/crypto//secp256k1_silent_payments-default`, which links libsecp256k1.", + "p256_default": "RFC 6979's P-256 key made from its scalar on P-256's default on every target, its public key RFC 6979's, with the one line `/webcpp/crypto//p256-default`, which links BearSSL.", "ed25519_default": "RFC 8032's first Ed25519 test, signed and verified on Ed25519's default on every target, with the one line `/webcpp/crypto//ed25519-default`, which links libsodium.", "x25519_default": "RFC 7748's shared secret on X25519's default on every target, with the one line `/webcpp/crypto//x25519-default`, which links libsodium.", "kx_default": "libsodium's `crypto_kx` test, the client's and the server's session keys from each other's public key, on its default on every target, with the one line `/webcpp/crypto//kx-default`, which links libsodium.", @@ -1143,6 +1190,8 @@ "box_default_not_linked_on_emscripten": "A program for Emscripten that calls the secret boxes, the boxes and the sealed box on their default, libsodium, and links none.", "kx_default_not_linked_on_emscripten": "A program for Emscripten that makes a `crypto_kx` key pair on its default, libsodium, and links none.", "box_not_a_family_on_emscripten": "A program for Emscripten that gives `hybrid::basic_box` a type that is no box family.", + "p256_default_not_linked_on_emscripten": "A program for Emscripten that makes a P-256 key pair on its default, BearSSL, and links none.", + "p256_on_sodium_on_emscripten": "A program for Emscripten that names libsodium, which has no P-256, in a P-256 key pair's type.", "x25519_default_not_linked_on_emscripten": "A program for Emscripten that agrees an X25519 shared secret on its default, libsodium, and links none.", "pem_default_not_linked_on_emscripten": "A program for Emscripten that armours DER as PEM on its default, libsodium, and links none.", "chacha_header_not_included_on_emscripten": "A program for Emscripten that names BearSSL in ChaCha20-Poly1305's type without including BearSSL's header.", @@ -1211,6 +1260,10 @@ "heavy_without_threads_on_emscripten": "As `heavy_without_threads`: on Emscripten, add `multi`.", "chacha_on_ctaes_on_emscripten": "As `chacha_on_ctaes`.", "aead_not_a_family_on_emscripten": "As `aead_not_a_family`.", + "p256_default_not_linked": "Add `/webcpp/crypto//p256-default`, which links `/third_party//bearssl` on every target.", + "p256_default_not_linked_on_emscripten": "As `p256_default_not_linked`.", + "p256_on_sodium": "Leave the backend out, as in `curves::p256::keypair`, or name `backends::bearssl`, and add `/third_party//bearssl`.", + "p256_on_sodium_on_emscripten": "As `p256_on_sodium`.", "x25519_default_not_linked": "Add `/webcpp/crypto//x25519-default`, which links `/third_party//sodium` on every target.", "pem_default_not_linked": "Add `/webcpp/crypto//pem-default`, which links `/third_party//sodium` on every target.", "chacha_header_not_included": "Include the backend's header the message names, as ``, and add its library, as `/third_party//bearssl`.", diff --git a/example/Jamfile b/example/Jamfile index 1bb07bed..661895dd 100644 --- a/example/Jamfile +++ b/example/Jamfile @@ -115,6 +115,11 @@ webcpp.example openssl_memory.cpp # Ed25519ph's test given in two pieces, on the family's default. webcpp.example ed25519_sign.cpp : /webcpp/crypto//ed25519-default ; +# The guide's P-256 key pair program: RFC 6979's key made from its scalar, its +# public key exported and imported as a peer's, a tampered point refused, and a +# key pair drawn from the system's generator. +webcpp.example p256_keys.cpp : /webcpp/crypto//p256-default ; + # The guide's X25519 program: RFC 7748's Alice and Bob, the agreement of two # Ed25519 key pairs through their X25519 forms, and a peer of low order # refused, on the family's default. diff --git a/example/p256_keys.cpp b/example/p256_keys.cpp new file mode 100644 index 00000000..e75a7943 --- /dev/null +++ b/example/p256_keys.cpp @@ -0,0 +1,83 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Makes a P-256 key pair from RFC 6979's key, prints its public key as the 65 bytes WebCrypto's +// exportKey("raw") gives, keeps its scalar and makes the same key pair from it again, then imports +// that public key as a peer's and refuses the same bytes with one bit changed. Draws a fresh key +// pair too, whose bytes differ on every run and are not printed. +// tag::program[] +#include + +#include +#include +#include +#include +#include + +namespace p256 = webcpp::crypto::curves::p256; + +namespace { + +// Prints bytes in hex after a name, 32 bytes (64 digits) to a line, the lines after the first +// indented under the first, so that a long value stays readable on a narrow page. +void print(char const* name, std::span bytes) { + int const indent = std::printf("%s ", name); + for (std::size_t i = 0; i < bytes.size(); ++i) { + if (i != 0 && i % 32 == 0) { + std::printf("\n%*s", indent, ""); + } + std::printf("%02x", bytes[i]); + } + std::printf("\n"); +} + +} // namespace + +int main() { + // RFC 6979 section A.2.5's key: a published scalar, never a real key. + std::array const scalar{ + 0xc9, 0xaf, 0xa9, 0xd8, 0x45, 0xba, 0x75, 0x16, 0x6b, 0x5c, 0x21, + 0x57, 0x67, 0xb1, 0xd6, 0x93, 0x4e, 0x50, 0xc3, 0xdb, 0x36, 0xe8, + 0x9b, 0x12, 0x7b, 0x8a, 0x62, 0x2b, 0x12, 0x0f, 0x67, 0x21, + }; + auto const key = p256::keypair::make(scalar); + if (!key) { + std::printf("failed\n"); + return 1; + } + auto const public_key = key->public_key(); + // Kept, the scalar stays a secret<32>, wiped when it goes; it makes the same key pair again. + auto const kept = key->secret_scalar(); + if (!public_key || !kept) { + std::printf("failed\n"); + return 1; + } + std::array const exported = public_key->uncompressed(); + // 65 bytes: the prefix 04, then x and y, 32 bytes each. + std::printf("public key %02x, then x and y\n", exported[0]); + print("x ", std::span(exported).subspan(1, p256::coordinate_size)); + print("y ", std::span(exported).subspan(1 + p256::coordinate_size)); + auto const reloaded = p256::keypair::make(kept->bytes()); + auto const reloaded_public = reloaded ? reloaded->public_key() : reloaded.error(); + bool const same = reloaded_public && reloaded_public->uncompressed() == exported; + std::printf("reloaded %s\n", same ? "same key" : "FAILED"); + + // A peer's key arrives as bytes: made once into a public_key, which checks the point. + auto const peer = p256::public_key::make(exported); + std::printf("peer key %s\n", peer ? "valid" : "refused"); + std::array tampered = exported; + tampered.back() ^= 0x01U; + auto const forged = p256::public_key::make(tampered); + std::printf("tampered %s: %s\n", forged ? "valid" : "refused", + forged ? "" : forged.error().message().c_str()); + + // A real program draws its key pair from the system's generator. + auto const fresh = p256::keypair::generate(); + std::printf("generated %s\n", fresh ? "a fresh key pair" : "FAILED"); + return 0; +} + +// end::program[] diff --git a/example/p256_keys.expected b/example/p256_keys.expected new file mode 100644 index 00000000..8fbb142c --- /dev/null +++ b/example/p256_keys.expected @@ -0,0 +1,7 @@ +public key 04, then x and y +x 60fed4ba255a9d31c961eb74c6356d68c049b8923b61fa6ce669622e60f29fb6 +y 7903fe1008b8bc99a41ae9e95628bc64f2f1b20c2d7e9f5177a3c294d4462299 +reloaded same key +peer key valid +tampered refused: the public key is not a point of the curve +generated a fresh key pair diff --git a/include/webcpp/crypto.hpp b/include/webcpp/crypto.hpp index 6338a999..61e4a223 100644 --- a/include/webcpp/crypto.hpp +++ b/include/webcpp/crypto.hpp @@ -8,9 +8,10 @@ Every header of webcpp::crypto that needs no backend, the header of each backend the build links with what it alone holds (libsecp256k1's secp256k1; libsodium's Ed25519 and X25519 with their key formats, `crypto_kx`, boxes and sealed boxes), `ciphers/aes256_gcm.hpp`, whose `aes128_gcm` and - `aes256_gcm` name AES-GCM's default backend, and `ciphers/chacha20_poly1305.hpp`, - `ciphers/secretbox.hpp` and `pem.hpp`, whose AEADs and PEM name libsodium: a program that does - not link the default names another in the type, as + `aes256_gcm` name AES-GCM's default backend, `ciphers/chacha20_poly1305.hpp`, + `ciphers/secretbox.hpp` and `pem.hpp`, whose AEADs and PEM name libsodium, and + `curves/p256.hpp`, whose key pairs name BearSSL: a program that does not link the default names + another in the type, as `ciphers::gcm>` on WebAssembly or `ciphers::chacha20_poly1305`, or, for the original ChaCha20-Poly1305, XChaCha20-Poly1305 and the secret boxes, which libsodium alone has, links libsodium. @@ -26,6 +27,7 @@ #include #include #include +#include #include #include #include diff --git a/include/webcpp/crypto/backends/bearssl.hpp b/include/webcpp/crypto/backends/bearssl.hpp index e7bbeda9..e3ab8e0d 100644 --- a/include/webcpp/crypto/backends/bearssl.hpp +++ b/include/webcpp/crypto/backends/bearssl.hpp @@ -6,8 +6,8 @@ /** The backend BearSSL: BearSSL's own C code, built from its sources by - `/third_party//bearssl`. It serves `ciphers::gcm>` and - `ciphers::chacha20_poly1305`, and has no block cipher. + `/third_party//bearssl`. It serves `ciphers::gcm>`, + `ciphers::chacha20_poly1305` and `curves::p256`, and has no block cipher. @see "The backends", in the guide. */ @@ -28,6 +28,7 @@ #include #include #include +#include #include #include #include @@ -403,6 +404,111 @@ struct aead_engine { static void reset(state& engine_state) noexcept { wipe_object(engine_state.key); } }; +/** + * BearSSL's P-256 code for this target: natively the 64-bit multiplications of br_ec_p256_m62 + * where BearSSL has them (__int128, or MSVC's _umul128), else br_ec_p256_m31; on WebAssembly + * br_ec_p256_m31 always, since wasm32's 128-bit product is a compiler-rt call whose timing nobody + * states (design D36). Each is constant time (BearSSL's documentation). + * + * @return The implementation of the curve's arithmetic. + */ +[[nodiscard]] inline br_ec_impl const* bearssl_p256() noexcept { +#ifndef WEBCPP_CRYPTO_WEBASSEMBLY + if (br_ec_impl const* wide = br_ec_p256_m62_get()) { + return wide; + } +#endif + return &br_ec_p256_m31; +} + +/** A P-256 key pair's state on BearSSL: the scalar and the point, in the object. */ +template <> +struct p_curve_state { + /** The secret scalar d, big-endian. */ + std::array scalar{}; + /** The public point d * G, SEC 1's uncompressed form. */ + std::array point{}; +}; + +/** + * P-256 on BearSSL: the point of a key pair computed once by `mulgen`, and a public point checked + * by BearSSL's decoding. BearSSL allocates nothing; its curve code never fails on a valid input. + */ +template <> +struct p_curve_engine { + /** The state. */ + using state = p_curve_state; + + /** + * Keeps the scalar and computes its public point. + * + * @param keyed An empty state. + * @param scalar 32 bytes, 0 < d < n (the family's header has checked them). + * @return Nothing; `backend_failure`, which a valid scalar cannot cause. + */ + [[nodiscard]] static boost::system::result make( + state& keyed, std::span scalar) noexcept { + WEBCPP_CRYPTO_DETAIL_P_CURVE_ENGINE_ENTERED(); + read_canary(WEBCPP_CRYPTO_DETAIL_BEARSSL_CANARY); + std::ranges::copy(scalar, keyed.scalar.begin()); + if (bearssl_p256()->mulgen(keyed.point.data(), keyed.scalar.data(), keyed.scalar.size(), + BR_EC_secp256r1) != keyed.point.size()) { + reset(keyed); + return error::backend_failure; + } + return {}; + } + + /** + * Whether an uncompressed point is on the curve, its coordinates below p. + * + * @param point 65 bytes, whose first byte is 04 (the family's header has checked it). + * @return Whether BearSSL decodes it. + */ + [[nodiscard]] static bool valid_point(std::span point) noexcept { + WEBCPP_CRYPTO_DETAIL_P_CURVE_ENGINE_ENTERED(); + read_canary(WEBCPP_CRYPTO_DETAIL_BEARSSL_CANARY); + // BearSSL decodes, and so checks, a point only to multiply it: by 1 it comes back as it + // was, re-encoded, when its coordinates are below p and on the curve (design D36). + std::array decoded{}; + std::ranges::copy(point, decoded.begin()); + constexpr std::array one{1}; + return bearssl_p256()->mul(decoded.data(), decoded.size(), one.data(), one.size(), + BR_EC_secp256r1) == 1 && + std::ranges::equal(decoded, point); + } + + /** + * Copies the public point; no BearSSL call. + * + * @param keyed A keyed state. + * @param output 65 bytes. + */ + static void public_point(state const& keyed, std::span output) noexcept { + std::ranges::copy(keyed.point, output.begin()); + } + + /** + * Copies the secret scalar; no BearSSL call. + * + * @param keyed A keyed state. + * @param output 32 bytes, a `secret<32>`'s. + */ + static void scalar(state const& keyed, std::span output) noexcept { + std::ranges::copy(keyed.scalar, output.begin()); + } + + /** + * Wipes the scalar and the point; the state is empty. + * + * @param keyed Any state. + */ + static void reset(state& keyed) noexcept { + wipe_object(keyed.scalar); + wipe_object(keyed.point); + } +}; + /** * 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/curves/p256.hpp b/include/webcpp/crypto/curves/p256.hpp new file mode 100644 index 00000000..a8703b19 --- /dev/null +++ b/include/webcpp/crypto/curves/p256.hpp @@ -0,0 +1,338 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the 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, NIST's curve of FIPS 186-5 (secp256r1): a key pair made from its 32-byte scalar or drawn + from the system's generator, and a public key validated once, as SEC 1's uncompressed point. + + The family's default backend, BearSSL on every target, is included when the program links it; + a program that uses the family without linking it stops where it calls it, with the Jamfile + line that links it. + + @see "P-256", in the guide. +*/ +#ifndef WEBCPP_CRYPTO_CURVES_P256_HPP +#define WEBCPP_CRYPTO_CURVES_P256_HPP + +#include + +#include +#include +#include +#include +#include +#include // lint-world: random_device draws generate()'s scalar +#include + +#include + +#include +#include +#include +#include +#include +#include + +namespace webcpp::crypto::curves::p256 { + +/** The size of a secret key, the scalar d, big-endian. */ +inline constexpr std::size_t secret_key_size = 32; +/** The size of a coordinate, x or y, big-endian. */ +inline constexpr std::size_t coordinate_size = 32; +/** The size of a public key, SEC 1's uncompressed point 04 || x || y. */ +inline constexpr std::size_t public_key_size = 65; +/** The size of the digest ECDSA signs, SHA-256's. */ +inline constexpr std::size_t digest_size = 32; +/** The size of a signature, r || s (IEEE P1363, WebCrypto's form). */ +inline constexpr std::size_t signature_size = 64; +/** The longest strict DER encoding of a signature. */ +inline constexpr std::size_t max_der_size = 72; + +/** + * A P-256 public key, validated: a point on the curve, its coordinates below p, never the + * identity, kept as SEC 1's uncompressed point. + * + * It holds nothing secret and is copied freely; it is made only by the functions that return + * one, so that it is always valid: a peer's key is made once, where it arrives, and kept. + * + * @tparam Backend The backend that checks the point; by default the family's + * (`default_backend_t`). + */ +template > +class basic_public_key { + using engine = detail::p_curve_engine; + + friend struct detail::p_curve_access; + +public: + /** The family, for `supports_v`. */ + using family_type = families::p256; + /** The algorithm, for `supports_v`. */ + using name_type = families::p256; + /** The backend. */ + using backend_type = Backend; + /** The size of the encoded point. */ + static constexpr std::size_t public_key_size = p256::public_key_size; + /** The size of a coordinate. */ + static constexpr std::size_t coordinate_size = p256::coordinate_size; + + /** + * Makes a public key from SEC 1's uncompressed point, as WebCrypto's `exportKey("raw")` + * writes it. + * + * @param uncompressed_point 65 bytes: 04, x, y. + * @return The public key; `invalid_public_key` for another size, another first byte (the + * compressed form included), a coordinate not below p or a point off the curve. + */ + [[nodiscard]] static boost::system::result make( + std::span uncompressed_point) noexcept { + detail::timing_guard const timing; + if (uncompressed_point.size() != public_key_size || uncompressed_point[0] != 0x04) { + return error::invalid_public_key; + } + return checked(uncompressed_point.template first()); + } + + /** + * Makes a public key from its two coordinates, as a JSON Web Key's `x` and `y` carry them. + * + * @param x 32 bytes, big-endian. + * @param y 32 bytes, big-endian. + * @return The public key; `invalid_public_key` for a coordinate not below p or a point off + * the curve. + */ + [[nodiscard]] static boost::system::result make( + std::span x, + std::span y) noexcept { + detail::timing_guard const timing; + std::array point{0x04}; + std::ranges::copy(x, point.begin() + 1); + std::ranges::copy(y, point.begin() + 1 + coordinate_size); + return checked(point); + } + + /** + * The point, as WebCrypto's `exportKey("raw")` writes it. + * + * @return 65 bytes: 04, x, y. + */ + [[nodiscard]] std::array uncompressed() const noexcept { + return point_; + } + +private: + basic_public_key() noexcept = default; + + // The backend's check of a point whose size and first byte are checked, and the key made of + // it: the work of both make, which hold their own guards. + [[nodiscard]] static boost::system::result checked( + std::span point) noexcept { + if (!engine::valid_point(point)) { + return error::invalid_public_key; + } + basic_public_key made; + std::ranges::copy(point, made.point_.begin()); + return made; + } + + std::array point_{}; +}; + +/** The public key on the default backend. */ +using public_key = basic_public_key<>; + +/** + * A P-256 key pair: its secret scalar d, kept by the backend and wiped by every move and by the + * destructor, and its public point d * G, computed once when it is made. + * + * @tparam Backend The backend; by default the family's (`default_backend_t`). + */ +template > +class basic_keypair { + using state_type = detail::p_curve_state; + using engine = detail::p_curve_engine; + using traits = detail::p_curve_traits; + +public: + /** The family, for `supports_v`. */ + using family_type = families::p256; + /** The algorithm, for `supports_v`. */ + using name_type = families::p256; + /** The backend. */ + using backend_type = Backend; + /** The size of the secret scalar. */ + static constexpr std::size_t secret_key_size = p256::secret_key_size; + /** The size of the public key, SEC 1's uncompressed point. */ + static constexpr std::size_t public_key_size = p256::public_key_size; + + /** + * Makes a key pair from its secret scalar, as a program that kept `secret_scalar` loads it + * again. + * + * @param secret_scalar 32 bytes, big-endian, not zero and below the group order n. + * @return The key pair; `invalid_key_size`; `invalid_secret_key` for a scalar 0 or not below + * n, refused before the backend; `backend_failure`. + */ + [[nodiscard]] static boost::system::result make( + std::span secret_scalar) noexcept { + detail::timing_guard const timing; + if (secret_scalar.size() != secret_key_size) { + return error::invalid_key_size; + } + auto const scalar = secret_scalar.template first(); + if (!detail::p_curve_scalar_valid(scalar, traits::order)) { + return error::invalid_secret_key; + } + basic_keypair made; + auto const keyed = engine::make(made.state_, scalar); + if (!keyed) { + return keyed.error(); + } + made.keyed_ = true; + return made; + } + + /** + * 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). + * + * @return The key pair; `entropy_unavailable` when the system's generator fails or there is + * none; `backend_failure`. + */ + [[nodiscard]] static boost::system::result generate() noexcept { + detail::timing_guard const timing; + secret scalar; + random_device device; // lint-world: the scalar + do { + if (!device.fill(scalar.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(), traits::order)); + return make(scalar.bytes()); + } + + /** + * Moves the key pair; the source is wiped and empty. + * + * @param other The key pair moved from. + */ + basic_keypair(basic_keypair&& other) noexcept : keyed_(std::exchange(other.keyed_, false)) { + state_ = other.state_; + engine::reset(other.state_); + } + + /** + * Moves over this key pair, which is wiped first. + * + * @param other The key pair moved from, wiped and empty after. + * @return This key pair. + */ + basic_keypair& operator=(basic_keypair&& other) noexcept { + if (this != &other) { + engine::reset(state_); + keyed_ = std::exchange(other.keyed_, false); + state_ = other.state_; + engine::reset(other.state_); + } + return *this; + } + + /** Not copyable: a secret key has one owner. */ + basic_keypair(basic_keypair const&) = delete; + /** Not copyable: a secret key has one owner. */ + basic_keypair& operator=(basic_keypair const&) = delete; + + /** Wipes the secret scalar. */ + ~basic_keypair() { engine::reset(state_); } + + /** + * The public key, computed when the key pair was made. + * + * @return The public key; `invalid_state` moved from. + */ + [[nodiscard]] boost::system::result> public_key() const noexcept { + if (!keyed_) { + return error::invalid_state; + } + auto key = detail::p_curve_access::blank>(); + engine::public_point(state_, detail::p_curve_access::point(key)); + return key; + } + + /** + * The secret scalar, for a program that keeps the key pair and makes it again with `make`. + * + * @return 32 secret bytes, big-endian; `invalid_state` moved from. + */ + [[nodiscard]] boost::system::result> secret_scalar() const noexcept { + if (!keyed_) { + return error::invalid_state; + } + secret scalar; + engine::scalar(state_, scalar.writable()); + return scalar; + } + +private: + basic_keypair() noexcept = default; + + state_type state_{}; + bool keyed_ = false; +}; + +/** The key pair on the default backend. */ +using keypair = basic_keypair<>; + +} // namespace webcpp::crypto::curves::p256 + +namespace webcpp::crypto::detail { + +/** + * P-256's engine on a backend whose header does not specialise it: the family's refusal, which + * names what the program needs (`detail/capabilities.hpp`). Its functions are never 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 answer fail closed, `backend_failure` or `false`. + */ +template +struct p_curve_engine { + WEBCPP_CRYPTO_DETAIL_REFUSE_P256(Backend); + + /** Never called; fails closed. */ + template + [[nodiscard]] static boost::system::result make(Arguments&&... /*arguments*/) noexcept { + return error::backend_failure; + } + + /** Never called; fails closed. */ + template + [[nodiscard]] static bool valid_point(Arguments&&... /*arguments*/) noexcept { + return false; + } + + /** Never called. */ + template + static void public_point(Arguments&&... /*arguments*/) noexcept {} + + /** Never called. */ + template + static void scalar(Arguments&&... /*arguments*/) noexcept {} + + /** Never called. */ + template + static void reset(Arguments&&... /*arguments*/) noexcept {} +}; + +} // namespace webcpp::crypto::detail + +// The default backend's engine, when the program links it (design D32): BearSSL on every target. +// Its header specialises it for this header, wherever it was first included. +#if defined(WEBCPP_CRYPTO_DETAIL_DEFAULT_P256_BEARSSL) && defined(WEBCPP_CRYPTO_HAS_BEARSSL) +#include +#endif + +#endif // WEBCPP_CRYPTO_CURVES_P256_HPP diff --git a/include/webcpp/crypto/detail/capabilities.hpp b/include/webcpp/crypto/detail/capabilities.hpp index b88f74fb..b3a9a979 100644 --- a/include/webcpp/crypto/detail/capabilities.hpp +++ b/include/webcpp/crypto/detail/capabilities.hpp @@ -84,6 +84,9 @@ struct secp256k1_musig; */ struct secp256k1_silent_payments; +/** The family P-256, of `curves::p256`, also the tag of its one algorithm. */ +struct p256; + } // namespace webcpp::crypto::families namespace webcpp::crypto::tags { @@ -274,6 +277,11 @@ inline constexpr bool supported inline constexpr bool supported = true; #endif +// 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) +template <> +inline constexpr bool supported = true; +#endif // clang-format on /** @@ -1118,6 +1126,47 @@ inline constexpr bool linked = true; static_assert(!std::is_same_v, "webcpp::crypto: sodium has no BIP 352 silent payments. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten)."); \ static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: BIP 352 silent payments has no backend of that name. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten).") #endif +#ifdef WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE +/** The refusals of the family P-256's primary engine for `Backend`, on native. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_P256(Backend) \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::bearssl>, "webcpp::crypto: P-256's default backend on this target is BearSSL, which is not linked, and the one backend that has it there. Add /webcpp/crypto//p256-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//p256-default ; (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::bearssl>, "webcpp::crypto: bearssl's P-256 is in , which the program does not include. Include it, and add /third_party//bearssl to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no P-256. The backends that have it: bearssl (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no P-256. The backends that have it: bearssl (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no P-256. The backends that have it: bearssl (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: sodium has no P-256. The backends that have it: bearssl (native, wasip2, wasip3, emscripten)."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: P-256 has no backend of that name. The backends that have it: bearssl (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_WASIP2) +/** The refusals of the family P-256's primary engine for `Backend`, on wasip2. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_P256(Backend) \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::bearssl>, "webcpp::crypto: P-256's default backend on this target is BearSSL, which is not linked, and the one backend that has it there. Add /webcpp/crypto//p256-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//p256-default ; (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::bearssl>, "webcpp::crypto: bearssl's P-256 is in , which the program does not include. Include it, and add /third_party//bearssl to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no P-256. The backends that have it: bearssl (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no P-256. The backends that have it: bearssl (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no P-256. The backends that have it: bearssl (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: sodium has no P-256. The backends that have it: bearssl (native, wasip2, wasip3, emscripten)."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: P-256 has no backend of that name. The backends that have it: bearssl (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_WASIP3) +/** The refusals of the family P-256's primary engine for `Backend`, on wasip3. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_P256(Backend) \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::bearssl>, "webcpp::crypto: P-256's default backend on this target is BearSSL, which is not linked, and the one backend that has it there. Add /webcpp/crypto//p256-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//p256-default ; (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::bearssl>, "webcpp::crypto: bearssl's P-256 is in , which the program does not include. Include it, and add /third_party//bearssl to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no P-256. The backends that have it: bearssl (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no P-256. The backends that have it: bearssl (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no P-256. The backends that have it: bearssl (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: sodium has no P-256. The backends that have it: bearssl (native, wasip2, wasip3, emscripten)."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: P-256 has no backend of that name. The backends that have it: bearssl (native, wasip2, wasip3, emscripten).") +#elif defined(WEBCPP_TARGET_EMSCRIPTEN) +/** The refusals of the family P-256's primary engine for `Backend`, on emscripten. */ +#define WEBCPP_CRYPTO_DETAIL_REFUSE_P256(Backend) \ + static_assert(!std::is_same_v || ::webcpp::crypto::detail::linked<::webcpp::crypto::backends::bearssl>, "webcpp::crypto: P-256's default backend on this target is BearSSL, which is not linked, and the one backend that has it there. Add /webcpp/crypto//p256-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//p256-default ; (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)"); \ + static_assert(!std::is_same_v || !::webcpp::crypto::detail::linked<::webcpp::crypto::backends::bearssl>, "webcpp::crypto: bearssl's P-256 is in , which the program does not include. Include it, and add /third_party//bearssl to the program's Jamfile."); \ + static_assert(!std::is_same_v, "webcpp::crypto: openssl has no P-256. The backends that have it: bearssl (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: ctaes has no P-256. The backends that have it: bearssl (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: secp256k1 has no P-256. The backends that have it: bearssl (native, wasip2, wasip3, emscripten)."); \ + static_assert(!std::is_same_v, "webcpp::crypto: sodium has no P-256. The backends that have it: bearssl (native, wasip2, wasip3, emscripten)."); \ + static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "webcpp::crypto: P-256 has no backend of that name. The backends that have it: bearssl (native, wasip2, wasip3, emscripten).") +#endif // clang-format on #endif // WEBCPP_CRYPTO_DETAIL_CAPABILITIES_HPP diff --git a/include/webcpp/crypto/detail/defaults.hpp b/include/webcpp/crypto/detail/defaults.hpp index 08395676..25fd1f65 100644 --- a/include/webcpp/crypto/detail/defaults.hpp +++ b/include/webcpp/crypto/detail/defaults.hpp @@ -185,6 +185,14 @@ struct default_backend_of { /** `backends::secp256k1`. */ using type = backends::secp256k1; }; +/** Defined where BearSSL is the default of P-256. */ +#define WEBCPP_CRYPTO_DETAIL_DEFAULT_P256_BEARSSL 1 +/** The default of P-256 on native, wasip2, wasip3, emscripten: BearSSL. */ +template <> +struct default_backend_of { + /** `backends::bearssl`. */ + using type = backends::bearssl; +}; // clang-format on /** diff --git a/include/webcpp/crypto/detail/p_curves.hpp b/include/webcpp/crypto/detail/p_curves.hpp new file mode 100644 index 00000000..15511ae7 --- /dev/null +++ b/include/webcpp/crypto/detail/p_curves.hpp @@ -0,0 +1,133 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the 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_P_CURVES_HPP +#define WEBCPP_CRYPTO_DETAIL_P_CURVES_HPP + +#include + +#include +#include + +#include +#include +#include +#include + +/* + * WEBCPP_CRYPTO_DETAIL_P_CURVE_ENGINE_ENTERED() runs first in each function of a backend's P-curve + * engine that calls the backend's code. Nothing in a program's build; a test defines it before its + * first include to count those calls, so that it sees a refusal that the family's header makes + * before the backend (test/p256_keys_bearssl_test.cpp). + */ +#ifndef WEBCPP_CRYPTO_DETAIL_P_CURVE_ENGINE_ENTERED +/** Marks a call of a P-curve engine's backend code: nothing in a program's build. */ +#define WEBCPP_CRYPTO_DETAIL_P_CURVE_ENGINE_ENTERED() static_cast(0) +#endif + +namespace webcpp::crypto::detail { + +/** A P-curve's constants: its sizes, the group order and its half, big-endian. */ +template +struct p_curve_traits; + +/** P-256's constants (FIPS 186-5; SEC 2). */ +template <> +struct p_curve_traits { + /** The size of a scalar, and of a coordinate. */ + static constexpr std::size_t scalar_size = 32; + /** The size of the digest ECDSA signs, SHA-256's. */ + static constexpr std::size_t digest_size = 32; + /** The longest strict DER encoding of an ECDSA signature. */ + static constexpr std::size_t max_der_size = 72; + /** n, the group order (FIPS 186-5; SEC 2). */ + static constexpr std::array order{ + 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xbc, 0xe6, 0xfa, 0xad, 0xa7, 0x17, + 0x9e, 0x84, 0xf3, 0xb9, 0xca, 0xc2, 0xfc, 0x63, 0x25, 0x51, + }; + /** (n - 1) / 2, the largest S of a low-S signature. */ + static constexpr std::array half_order{ + 0x7f, 0xff, 0xff, 0xff, 0x80, 0x00, 0x00, 0x00, 0x7f, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xde, 0x73, 0x7d, 0x56, 0xd3, 0x8b, + 0xcf, 0x42, 0x79, 0xdc, 0xe5, 0x61, 0x7e, 0x31, 0x92, 0xa8, + }; +}; + +/** + * Whether 0 < value < bound, both big-endian of N bytes, in time independent of `value`: the + * borrow of value - bound and the OR of value's bytes over every byte, as BearSSL's br_ec_keygen + * computes them. The verdict alone is declassified: whether a key is valid is public. + * + * @param value The secret scalar. + * @param bound The group order. + * @return Whether the scalar is in range. + */ +template +[[nodiscard]] bool p_curve_scalar_valid(std::span value, + std::array const& bound) noexcept { + unsigned borrow = 0; + unsigned nonzero = 0; + for (std::size_t i = N; i-- > 0;) { + borrow = ((static_cast(value[i]) - bound[i] - borrow) >> 8U) & 1U; + nonzero |= value[i]; + } + // Not const: the comparison below must read the variable again after the declassifying + // client request, whose memory clobber reaches a mutable object only. + // NOLINTNEXTLINE(misc-const-correctness): see above + unsigned verdict = borrow & ((nonzero + 0xffU) >> 8U); + WEBCPP_CRYPTO_DETAIL_DECLASSIFY(&verdict, sizeof verdict); + return verdict != 0; +} + +/** + * What a P-curve key pair stores on a backend whose header does not specialise it: nothing, since + * its engine refuses the backend where the family is called. + */ +template +struct p_curve_state {}; + +/** + * The work of a P-curve on a backend: a backend's header specialises it per curve, and each + * curve's header defines the refusal for the others (`curves/p256.hpp`). + */ +template +struct p_curve_engine; + +/** + * The one door into a P-curve's opaque types (a public key, whose default constructor is + * private): the family's functions make one through it and write its point before they return + * it. It hands out nothing a caller of crypto could not already do. + */ +struct p_curve_access { + /** + * An object of an opaque type, not yet written: the function that returns it writes it + * first. + * + * @tparam Opaque The type, whose default constructor is private. + * @return The unwritten object. + */ + template + [[nodiscard]] static Opaque blank() noexcept { + return Opaque(); + } + + /** + * A public key's point, to be written by the function that makes the key. + * + * @tparam PublicKey The public key's type. + * @param key The public key. + * @return Its encoded point. + */ + template + [[nodiscard]] static auto& point(PublicKey& key) noexcept { + return key.point_; + } +}; + +} // namespace webcpp::crypto::detail + +#endif // WEBCPP_CRYPTO_DETAIL_P_CURVES_HPP diff --git a/test/Jamfile b/test/Jamfile index 16f9d418..4a0fca03 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -34,12 +34,13 @@ webcpp.headers-alone crypto : ../include : crypto.hpp crypto/config.hpp crypto/detail/windows.hpp crypto/detail/wipe.hpp crypto/secret.hpp crypto/supports.hpp crypto/detail/capabilities.hpp crypto/detail/defaults.hpp crypto/detail/heavy.hpp crypto/detail/timing.hpp crypto/ciphers/aead.hpp - crypto/ciphers/chacha20_poly1305.hpp crypto/ciphers/secretbox.hpp crypto/pem.hpp ; + crypto/ciphers/chacha20_poly1305.hpp crypto/ciphers/secretbox.hpp crypto/pem.hpp + crypto/detail/p_curves.hpp ; -# The backend BearSSL's header and the default backend's, with BearSSL linked, -# on every target. +# The backend BearSSL's header and the default backend's, and P-256's, with +# BearSSL linked, on every target. webcpp.headers-alone crypto : ../include - : crypto/ciphers/aes256_gcm.hpp crypto/backends/bearssl.hpp + : crypto/ciphers/aes256_gcm.hpp crypto/backends/bearssl.hpp crypto/curves/p256.hpp : /third_party//bearssl ; # The backend OpenSSL's header, with OpenSSL linked; BearSSL, # ctaes, libsecp256k1 and libsodium are linked too, so that every public @@ -104,6 +105,9 @@ webcpp.compile-diagnostic heavy_refusal_forgotten : heavy_refusal_forgotten_test crypto-run error : error_test.cpp ; crypto-run equal : equal_test.cpp ; +# The tests' hex readers: hex at compile time, from_hex and to_hex at run +# time. +crypto-run hex : hex_test.cpp ; # detail::timing_guard sets DIT for its scope where the CPU has it and leaves # the thread's state as it found it; its seam fires on every target; equal # enters it. timing_threads adds a second thread, natively, with threads. @@ -367,6 +371,12 @@ crypto-run default_both_wasm : default_both_wasm_test.cpp : /third_party//bearssl /webcpp/crypto//openssl : wasip2 wasip3 ; +# P-256 on BearSSL: RFC 6979's key, the scalar's range checked before BearSSL, +# generate, public keys from a point and from coordinates and their refusals, +# a moved-from key pair, and its storage zero once moved from and destroyed: +# optimised, every call inlined, as ed25519_wipe_sodium's. +crypto-run p256_keys_bearssl : p256_keys_bearssl_test.cpp + : /third_party//bearssl $(OPTIMISED) full ; # The backend ctaes: the AES block cipher alone, on every target; FIPS-197 only # (ruling R5). crypto-run aes_ctaes : aes_ctaes_test.cpp : /third_party//ctaes ; @@ -587,6 +597,9 @@ webcpp.compile doc_secp256k1_default_app webcpp.compile doc_ed25519_default_app : ../../../tools/test/fixtures/crypto_jamfiles/ed25519_default/app.cpp : /webcpp/crypto//ed25519-default ; +webcpp.compile doc_p256_default_app + : ../../../tools/test/fixtures/crypto_jamfiles/p256_default/app.cpp + : /webcpp/crypto//p256-default ; webcpp.compile doc_x25519_default_app : ../../../tools/test/fixtures/crypto_jamfiles/x25519_default/app.cpp : /webcpp/crypto//x25519-default ; diff --git a/test/allocation_bearssl_test.cpp b/test/allocation_bearssl_test.cpp index ea04869d..1db6f073 100644 --- a/test/allocation_bearssl_test.cpp +++ b/test/allocation_bearssl_test.cpp @@ -5,18 +5,21 @@ // https://www.boost.org/LICENSE_1_0.txt) // On BearSSL nothing allocates (spec section 3.2): make, seal, open, the incremental seal, -// equal and random_device's fill, and ChaCha20-Poly1305's make, seal, open (good and failed) -// and move make no call of operator new, nor of the C library's +// equal and random_device's fill, ChaCha20-Poly1305's make, seal, open (good and failed) +// and move, and P-256's key pair make and generate and public key make (of a point and of +// coordinates) make no call of operator new, nor of the C library's // allocator where the target lets a program count it; a control proves the counter moves. #include #include +#include #include #include // lint-world: a test #include #include "support/counting.hpp" #include "support/gcm_checks.hpp" +#include "support/p256_data.hpp" #include @@ -25,6 +28,7 @@ #include #include #include +#include #include int main() { @@ -67,6 +71,16 @@ int main() { BOOST_TEST(sealer->open(iv, iv, data, forged).error() == crypto::error::authentication_failed); chacha const moved = std::move(*sealer); + namespace p256 = crypto::curves::p256; + namespace data = webcpp::test::p256; + using keypair = p256::basic_keypair; + using public_key = p256::basic_public_key; + auto const pair = keypair::make(data::rfc6979_scalar); + BOOST_TEST(pair.has_value()); + BOOST_TEST(keypair::generate().has_value()); + std::span const point(data::rfc6979_public); + BOOST_TEST(public_key::make(point).has_value()); + BOOST_TEST(public_key::make(point.subspan<1, 32>(), point.subspan<33, 32>()).has_value()); } BOOST_TEST_EQ(webcpp::test::allocations(), before); return webcpp::test::exit_status(boost::report_errors()); diff --git a/test/capabilities_test.cpp b/test/capabilities_test.cpp index 61b37d51..53c6c9bc 100644 --- a/test/capabilities_test.cpp +++ b/test/capabilities_test.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -174,6 +175,12 @@ struct refuses_secp256k1_silent_payments { WEBCPP_CRYPTO_DETAIL_REFUSE_SECP256K1_SILENT_PAYMENTS(Backend); }; +/** The refusals of P-256, parsed: nothing instantiates it. */ +template +struct refuses_p256 { + WEBCPP_CRYPTO_DETAIL_REFUSE_P256(Backend); +}; + } // namespace // clang-format off @@ -506,6 +513,20 @@ 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) +static_assert(crypto::supports_v, backends::bearssl>); +#else +static_assert(!crypto::supports_v, backends::bearssl>); +#endif +// P-256 on openssl: none. +static_assert(!crypto::supports_v, backends::openssl>); +// P-256 on ctaes: none. +static_assert(!crypto::supports_v, backends::ctaes>); +// P-256 on secp256k1: none. +static_assert(!crypto::supports_v, backends::secp256k1>); +// P-256 on sodium: none. +static_assert(!crypto::supports_v, backends::sodium>); // clang-format on // NOLINTNEXTLINE(readability-function-cognitive-complexity): one check per cell @@ -594,6 +615,9 @@ int main() { #endif #if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN)) && defined(WEBCPP_CRYPTO_HAS_SODIUM) BOOST_TEST((webcpp::test::made, families::sealed_box, families::sealed_box, backends::sodium>())); +#endif +#if (defined(WEBCPP_CRYPTO_DETAIL_TARGET_NATIVE) || defined(WEBCPP_TARGET_WASIP2) || defined(WEBCPP_TARGET_WASIP3) || defined(WEBCPP_TARGET_EMSCRIPTEN)) && defined(WEBCPP_CRYPTO_HAS_BEARSSL) + BOOST_TEST((webcpp::test::made, families::p256, families::p256, backends::bearssl>())); #endif // clang-format on return webcpp::test::exit_status(boost::report_errors()); diff --git a/test/convenience_header_test.cpp b/test/convenience_header_test.cpp index 025f7872..33f05762 100644 --- a/test/convenience_header_test.cpp +++ b/test/convenience_header_test.cpp @@ -5,7 +5,9 @@ // https://www.boost.org/LICENSE_1_0.txt) // The convenience header with no backend linked compiles, links and runs (spec section 2.1): this -// program includes alone, names no backend, links none, and calls equal. +// program includes alone, names no backend, links none, and calls equal. The +// headers whose families name a default backend it does not link are there all the same: P-256's +// key pair names BearSSL. #include #include @@ -15,6 +17,7 @@ #include #include +#include #if defined(WEBCPP_CRYPTO_HAS_BEARSSL) || defined(WEBCPP_CRYPTO_HAS_OPENSSL) || \ defined(WEBCPP_CRYPTO_HAS_CTAES) || defined(WEBCPP_CRYPTO_HAS_SECP256K1) || \ @@ -22,6 +25,12 @@ #error "this program links no backend: its project must not name one" #endif +// curves/p256.hpp is included, and its key pair names its default, BearSSL, which is not linked. +static_assert(std::is_same_v); +static_assert(webcpp::crypto::supports_v); + int main() { std::array const zero{}; std::array other{}; diff --git a/test/default_backend_test.cpp b/test/default_backend_test.cpp index 3710799e..5bf71cab 100644 --- a/test/default_backend_test.cpp +++ b/test/default_backend_test.cpp @@ -138,6 +138,14 @@ static_assert( #error "secretbox.hpp, box.hpp and sealed_box.hpp are not told to include libsodium's header" #endif +// P-256: BearSSL, the one backend of the P-curves, on every target. +static_assert(std::is_same_v, backends::bearssl>); +#ifndef WEBCPP_CRYPTO_DETAIL_DEFAULT_P256_BEARSSL +#error "curves/p256.hpp is told to include another header than BearSSL's" +#endif +static_assert(crypto::detail::supported>); + // secp256k1's modules, each a family of its own: libsecp256k1, the only backend, on every target. static_assert( std::is_same_v, backends::secp256k1>); diff --git a/test/hex_test.cpp b/test/hex_test.cpp new file mode 100644 index 00000000..e2b10bd5 --- /dev/null +++ b/test/hex_test.cpp @@ -0,0 +1,37 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The tests' hex readers (support/hex.hpp): hex decodes at compile time, either case, into the +// bytes from_hex decodes at run time; to_hex writes them back in lower case. + +#include + +#include "support/hex.hpp" + +#include + +#include +#include +#include + +namespace { + +namespace test = webcpp::test; + +// Decoded by the compiler: a wrong byte fails the build. +static_assert(test::hex<4>("00ff7Fa0") == std::array{0x00, 0xff, 0x7f, 0xa0}); +static_assert(test::hex<0>("").empty()); + +constexpr auto mixed = test::hex<8>("0123456789AbCdEf"); + +} // namespace + +int main() { + auto const decoded = test::from_hex("0123456789abcdef"); + BOOST_TEST(std::ranges::equal(mixed, decoded)); + BOOST_TEST_EQ(test::to_hex(mixed), "0123456789abcdef"); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/messages/Jamfile b/test/messages/Jamfile index 3391ac9e..b82a2fe4 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -47,3 +47,5 @@ build-project ellswift_other_backend ; build-project musig_other_backend ; build-project silent_payments_other_backend ; build-project label_lookup_by_value ; +build-project p256_default_not_linked ; +build-project p256_on_sodium ; diff --git a/test/messages/p256_default_not_linked/Jamfile b/test/messages/p256_default_not_linked/Jamfile new file mode 100644 index 00000000..a7c2e140 --- /dev/null +++ b/test/messages/p256_default_not_linked/Jamfile @@ -0,0 +1,12 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +webcpp.compile-diagnostic p256_default_not_linked : p256_default_not_linked.cpp + : : native wasip2 wasip3 ; diff --git a/test/messages/p256_default_not_linked/p256_default_not_linked.cpp b/test/messages/p256_default_not_linked/p256_default_not_linked.cpp new file mode 100644 index 00000000..42f3a681 --- /dev/null +++ b/test/messages/p256_default_not_linked/p256_default_not_linked.cpp @@ -0,0 +1,23 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A program that makes a P-256 key pair on its default backend, BearSSL on every target, and +// does not link it stops where it makes it, with the line that links it. + +// clang-format off +// expected-error@webcpp/crypto/curves/p256.hpp:* {{webcpp::crypto: P-256's default backend on this target is BearSSL, which is not linked, and the one backend that has it there. Add /webcpp/crypto//p256-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//p256-default ; (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)}} +// clang-format on + +#include + +#include +#include + +int main() { + std::array scalar{}; + scalar.back() = 1; + return webcpp::crypto::curves::p256::keypair::make(scalar) ? 0 : 1; +} diff --git a/test/messages/p256_on_sodium/Jamfile b/test/messages/p256_on_sodium/Jamfile new file mode 100644 index 00000000..8e1f4648 --- /dev/null +++ b/test/messages/p256_on_sodium/Jamfile @@ -0,0 +1,12 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +webcpp.compile-diagnostic p256_on_sodium : p256_on_sodium.cpp + : /third_party//sodium : native wasip2 wasip3 ; diff --git a/test/messages/p256_on_sodium/p256_on_sodium.cpp b/test/messages/p256_on_sodium/p256_on_sodium.cpp new file mode 100644 index 00000000..b21e9c12 --- /dev/null +++ b/test/messages/p256_on_sodium/p256_on_sodium.cpp @@ -0,0 +1,26 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A P-256 key pair named with libsodium, which has no P-256, stops where it is made, with the +// capability table's refusal, which names the backends that have it. + +// clang-format off +// expected-error@webcpp/crypto/curves/p256.hpp:* {{webcpp::crypto: sodium has no P-256. The backends that have it: bearssl (native, wasip2, wasip3, emscripten).}} +// clang-format on + +#include + +#include +#include + +int main() { + std::array scalar{}; + scalar.back() = 1; + return webcpp::crypto::curves::p256::basic_keypair::make( + scalar) + ? 0 + : 1; +} diff --git a/test/msvc/Jamfile b/test/msvc/Jamfile index 7329e374..89d09e39 100644 --- a/test/msvc/Jamfile +++ b/test/msvc/Jamfile @@ -65,3 +65,5 @@ build-project ellswift_other_backend ; build-project musig_other_backend ; build-project silent_payments_other_backend ; build-project label_lookup_by_value ; +build-project p256_default_not_linked ; +build-project p256_on_sodium ; diff --git a/test/msvc/p256_default_not_linked/Jamfile b/test/msvc/p256_default_not_linked/Jamfile new file mode 100644 index 00000000..f0789834 --- /dev/null +++ b/test/msvc/p256_default_not_linked/Jamfile @@ -0,0 +1,9 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail p256_default_not_linked : app.cpp : /webcpp/crypto//crypto : native ; diff --git a/test/msvc/p256_default_not_linked/app.cpp b/test/msvc/p256_default_not_linked/app.cpp new file mode 100644 index 00000000..68a81287 --- /dev/null +++ b/test/msvc/p256_default_not_linked/app.cpp @@ -0,0 +1,18 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A P-256 key pair on its default, BearSSL, not linked, stops where it is made: on MSVC the +// compile fails. The text is checked on clang, in test/messages/p256_default_not_linked. +#include + +#include +#include + +int main() { + std::array scalar{}; + scalar.back() = 1; + return webcpp::crypto::curves::p256::keypair::make(scalar) ? 0 : 1; +} diff --git a/test/msvc/p256_on_sodium/Jamfile b/test/msvc/p256_on_sodium/Jamfile new file mode 100644 index 00000000..9560ed19 --- /dev/null +++ b/test/msvc/p256_on_sodium/Jamfile @@ -0,0 +1,9 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail p256_on_sodium : app.cpp : /webcpp/crypto//crypto /third_party//sodium : native ; diff --git a/test/msvc/p256_on_sodium/app.cpp b/test/msvc/p256_on_sodium/app.cpp new file mode 100644 index 00000000..7ffab258 --- /dev/null +++ b/test/msvc/p256_on_sodium/app.cpp @@ -0,0 +1,22 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A P-256 key pair named with libsodium, which has no P-256, stops at the capability table's +// refusal: on MSVC the compile fails. The text is checked on clang, in +// test/messages/p256_on_sodium. +#include + +#include +#include + +int main() { + std::array scalar{}; + scalar.back() = 1; + return webcpp::crypto::curves::p256::basic_keypair::make( + scalar) + ? 0 + : 1; +} diff --git a/test/p256_keys_bearssl_test.cpp b/test/p256_keys_bearssl_test.cpp new file mode 100644 index 00000000..c8c663d9 --- /dev/null +++ b/test/p256_keys_bearssl_test.cpp @@ -0,0 +1,292 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the 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 key pairs and public keys on BearSSL: RFC 6979's key made from its scalar, its public +// point the RFC's and its scalar read back; the scalar's range, 0 < d < n, checked before +// BearSSL (the engine's seam counts its calls); generate; a public key from its point and from +// its coordinates, and every refusal of a point (sizes, prefixes, the compressed form, off the +// curve, a coordinate not below p, the identity's encodings); a moved-from key pair; the key +// pair's storage zero once moved from and once destroyed, read at -O2 with every call inlined +// (the Jamfile's requirements), as ed25519_wipe_sodium_test.cpp reads Ed25519's; and the types' +// traits. + +#include + +namespace { + +// The engine's calls: the seam of detail/p_curves.hpp, defined before any crypto header. +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the seam's counter +std::size_t engine_calls = 0; + +} // namespace + +/** Counts a call of the P-curve engine. */ +#define WEBCPP_CRYPTO_DETAIL_P_CURVE_ENGINE_ENTERED() (++engine_calls) + +#include +#include +#include +#include +#include + +#include "support/p256_data.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace crypto = webcpp::crypto; +namespace p256 = webcpp::crypto::curves::p256; +namespace data = webcpp::test::p256; + +using crypto::error; +using p256::keypair; +using p256::public_key; + +constexpr std::size_t keypair_state = + sizeof(crypto::detail::p_curve_state); + +static_assert(std::is_standard_layout_v); +static_assert(keypair_state == 32 + 65); + +// A function the optimiser cannot see into, so that what it is handed is read from memory. +#if defined(_MSC_VER) && !defined(__clang__) +#define WEBCPP_TEST_NOINLINE __declspec(noinline) +#else +#define WEBCPP_TEST_NOINLINE __attribute__((noinline)) +#endif + +// Whether every byte at `where` is zero, read through a volatile pointer in a function that is +// never inlined. It may be handed the storage of an object that is gone (the destructor's +// check), so it is exempt from the sanitizers that would stop that read. +#if defined(__clang__) || defined(__GNUC__) +__attribute__((no_sanitize("address"))) +#endif +WEBCPP_TEST_NOINLINE bool memory_is_zero(void const* where, std::size_t count) { + auto const volatile* const bytes = static_cast(where); + for (std::size_t i = 0; i < count; ++i) { + if (bytes[i] != 0) { + return false; + } + } + return true; +} + +/** `value` with `last` as its last byte. */ +std::array with_last_byte(std::array value, std::uint8_t last) { + value.back() = last; + return value; +} + +void make_from_rfc6979_scalar() { + auto const made = keypair::make(data::rfc6979_scalar); + if (!BOOST_TEST(made.has_value())) { + return; + } + auto const point = made->public_key(); + if (BOOST_TEST(point.has_value())) { + BOOST_TEST(point->uncompressed() == data::rfc6979_public); + } + auto const scalar = made->secret_scalar(); + if (BOOST_TEST(scalar.has_value())) { + BOOST_TEST(std::ranges::equal(scalar->bytes(), data::rfc6979_scalar)); + } +} + +void scalar_out_of_range() { + std::array const zero{}; + std::array all_ones{}; + all_ones.fill(0xff); + BOOST_TEST(keypair::make(zero).error() == error::invalid_secret_key); + BOOST_TEST(keypair::make(data::order).error() == error::invalid_secret_key); + BOOST_TEST(keypair::make(with_last_byte(data::order, 0x52)).error() == + error::invalid_secret_key); + BOOST_TEST(keypair::make(all_ones).error() == error::invalid_secret_key); + BOOST_TEST(keypair::make(with_last_byte(data::order, 0x50)).has_value()); + BOOST_TEST(keypair::make(with_last_byte(zero, 0x01)).has_value()); + std::array const long_scalar{}; + BOOST_TEST(keypair::make(std::span(data::rfc6979_scalar).first(31)).error() == + error::invalid_key_size); + BOOST_TEST(keypair::make(long_scalar).error() == error::invalid_key_size); +} + +void scalar_check_reaches_no_backend() { + // The control: a valid scalar reaches the engine, so the counter can move. + engine_calls = 0; + BOOST_TEST(keypair::make(data::rfc6979_scalar).has_value()); + BOOST_TEST_GT(engine_calls, 0U); + engine_calls = 0; + BOOST_TEST(keypair::make(data::order).error() == error::invalid_secret_key); + BOOST_TEST_EQ(engine_calls, 0U); +} + +void generate_makes_distinct_valid_keys() { + auto const first = keypair::generate(); + auto const second = keypair::generate(); + if (!BOOST_TEST(first.has_value()) || !BOOST_TEST(second.has_value())) { + return; + } + auto const first_scalar = first->secret_scalar(); + auto const second_scalar = second->secret_scalar(); + if (BOOST_TEST(first_scalar.has_value()) && BOOST_TEST(second_scalar.has_value())) { + BOOST_TEST(!std::ranges::equal(first_scalar->bytes(), second_scalar->bytes())); + } + for (auto const* const pair : {&*first, &*second}) { + auto const point = pair->public_key(); + if (BOOST_TEST(point.has_value())) { + auto const again = public_key::make(point->uncompressed()); + if (BOOST_TEST(again.has_value())) { + BOOST_TEST(again->uncompressed() == point->uncompressed()); + } + } + } +} + +void public_key_from_point_and_coordinates() { + std::span const point(data::rfc6979_public); + auto const from_point = public_key::make(point); + auto const from_coordinates = + public_key::make(point.subspan<1, p256::coordinate_size>(), + point.subspan<1 + p256::coordinate_size, p256::coordinate_size>()); + if (BOOST_TEST(from_point.has_value()) && BOOST_TEST(from_coordinates.has_value())) { + BOOST_TEST(from_point->uncompressed() == data::rfc6979_public); + BOOST_TEST(from_coordinates->uncompressed() == from_point->uncompressed()); + } +} + +void public_key_refusals() { + auto const refused = [](std::span point) { + return public_key::make(point).error() == error::invalid_public_key; + }; + std::array longer{}; + std::ranges::copy(data::rfc6979_public, longer.begin()); + BOOST_TEST(refused(std::span(data::rfc6979_public).first(64))); + BOOST_TEST(refused(longer)); + // The compressed form: BearSSL decodes uncompressed points alone (design D36). + std::array compressed{}; + std::ranges::copy(std::span(data::rfc6979_public).first(33), compressed.begin()); + compressed[0] = 0x02; + BOOST_TEST(refused(compressed)); + auto other_prefix = data::rfc6979_public; + other_prefix[0] = 0x05; + BOOST_TEST(refused(other_prefix)); + // y + 1: off the curve (the last byte of y is 0x99, so no carry). + auto off_curve = data::rfc6979_public; + ++off_curve.back(); + BOOST_TEST(refused(off_curve)); + // x = p, with the RFC's y. + auto x_is_p = data::rfc6979_public; + std::ranges::copy(data::field_prime, x_is_p.begin() + 1); + BOOST_TEST(refused(x_is_p)); + std::array zeros{}; + BOOST_TEST(refused(zeros)); + // 04 and zeros: (0, 0) is not on the curve, the identity has no affine form. + zeros[0] = 0x04; + BOOST_TEST(refused(zeros)); + // The coordinates' overload refuses as the point's does. + std::span const off(off_curve); + BOOST_TEST(public_key::make(off.subspan<1, 32>(), off.subspan<33, 32>()).error() == + error::invalid_public_key); +} + +void moved_from() { + auto made = keypair::make(data::rfc6979_scalar); + if (!BOOST_TEST(made.has_value())) { + return; + } + keypair& a = *made; + keypair const b = std::move(a); + // NOLINTBEGIN(bugprone-use-after-move,clang-analyzer-cplusplus.Move): the moved-from state + // is what is tested. + BOOST_TEST(a.public_key().error() == error::invalid_state); + BOOST_TEST(a.secret_scalar().error() == error::invalid_state); + // NOLINTEND(bugprone-use-after-move,clang-analyzer-cplusplus.Move) + auto const point = b.public_key(); + if (BOOST_TEST(point.has_value())) { + BOOST_TEST(point->uncompressed() == data::rfc6979_public); + } + auto const scalar = b.secret_scalar(); + if (BOOST_TEST(scalar.has_value())) { + BOOST_TEST(std::ranges::equal(scalar->bytes(), data::rfc6979_scalar)); + } + // Moved over: the target holds the source's key, and the source is empty. + auto other = keypair::make(with_last_byte(std::array{}, 0x01)); + if (BOOST_TEST(other.has_value())) { + a = std::move(*other); + // NOLINTNEXTLINE(bugprone-use-after-move,clang-analyzer-cplusplus.Move): tested + BOOST_TEST(other->public_key().error() == error::invalid_state); + BOOST_TEST(a.public_key().has_value()); + } +} + +void wipe() { + auto made = keypair::make(data::rfc6979_scalar); + if (!BOOST_TEST(made.has_value())) { + return; + } + // Alive, the state holds the scalar and the point: the checks below can fail. + BOOST_TEST(!memory_is_zero(&*made, keypair_state)); + + keypair taken = std::move(*made); + BOOST_TEST(memory_is_zero(&*made, keypair_state)); + + auto other = keypair::make(data::rfc6979_scalar); + if (BOOST_TEST(other.has_value())) { + taken = std::move(*other); + BOOST_TEST(memory_is_zero(&*other, keypair_state)); + } + + // Destroyed in storage this frame owns: its bytes are read after the destructor. + alignas(keypair) std::array storage{}; + keypair* const placed = + std::construct_at(reinterpret_cast(storage.data()), std::move(taken)); + BOOST_TEST(!memory_is_zero(placed, keypair_state)); + std::destroy_at(placed); + BOOST_TEST(memory_is_zero(storage.data(), keypair_state)); +} + +void traits() { + static_assert(!std::is_copy_constructible_v); + static_assert(!std::is_copy_assignable_v); + static_assert(std::is_nothrow_move_constructible_v); + static_assert(std::is_nothrow_move_assignable_v); + static_assert(!std::is_default_constructible_v); + static_assert(std::is_copy_constructible_v); + static_assert(!std::is_default_constructible_v); + static_assert(crypto::supports_v); + static_assert(!crypto::supports_v); + static_assert(crypto::supports_v); + static_assert(std::is_same_v, + crypto::backends::bearssl>); + static_assert(p256::secret_key_size == 32 && p256::coordinate_size == 32 && + p256::public_key_size == 65 && p256::digest_size == 32 && + p256::signature_size == 64 && p256::max_der_size == 72); + static_assert(std::is_same_v().secret_scalar()), + boost::system::result>>); +} + +} // namespace + +int main() { + make_from_rfc6979_scalar(); + scalar_out_of_range(); + scalar_check_reaches_no_backend(); + generate_makes_distinct_valid_keys(); + public_key_from_point_and_coordinates(); + public_key_refusals(); + moved_from(); + wipe(); + traits(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/support/hex.hpp b/test/support/hex.hpp index 4f358a92..8f27fcb6 100644 --- a/test/support/hex.hpp +++ b/test/support/hex.hpp @@ -7,6 +7,7 @@ #ifndef WEBCPP_TEST_CRYPTO_SUPPORT_HEX_HPP #define WEBCPP_TEST_CRYPTO_SUPPORT_HEX_HPP +#include #include #include #include @@ -30,6 +31,47 @@ inline std::vector from_hex(std::string_view hex) { return bytes; } +/** + * Not constexpr: a `hex` whose digits reach it is not a constant expression, so a malformed + * vector stops the compile where it is written. + */ +inline void malformed_hex() noexcept {} + +/** + * The `N` bytes a string of `2 * N` hex digits writes, decoded at compile time: a test's + * constant vectors, `inline constexpr auto key = hex<32>("...")`. Digits of another count, or a + * character that is not a hex digit, stop the compile. + * + * @tparam N The number of bytes. + * @param digits Hex digits, either case. + * @return The bytes. + */ +template +consteval std::array hex(std::string_view digits) { + if (digits.size() != 2 * N) { + malformed_hex(); + } + auto const digit = [](char c) -> std::uint8_t { + if (c >= '0' && c <= '9') { + return static_cast(c - '0'); + } + if (c >= 'a' && c <= 'f') { + return static_cast(c - 'a' + 10); + } + if (c >= 'A' && c <= 'F') { + return static_cast(c - 'A' + 10); + } + malformed_hex(); + return 0; + }; + std::array bytes{}; + for (std::size_t i = 0; i < N; ++i) { + auto const high = static_cast(digit(digits[2 * i]) << 4U); + bytes[i] = static_cast(high | digit(digits[(2 * i) + 1])); + } + return bytes; +} + /** Lower-case hex of bytes, for a failure's message. */ inline std::string to_hex(std::span bytes) { static constexpr std::string_view digits = "0123456789abcdef"; diff --git a/test/support/p256_data.hpp b/test/support/p256_data.hpp new file mode 100644 index 00000000..2ba1e25b --- /dev/null +++ b/test/support/p256_data.hpp @@ -0,0 +1,38 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the 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 P-256 constants the P-256 tests share, each with its source: RFC 6979's key, the group +// order n and (n - 1) / 2, and the field prime p. + +#ifndef WEBCPP_TEST_CRYPTO_SUPPORT_P256_DATA_HPP +#define WEBCPP_TEST_CRYPTO_SUPPORT_P256_DATA_HPP + +#include "hex.hpp" + +#include +#include + +namespace webcpp::test::p256 { + +// RFC 6979, section A.2.5: the P-256 key. +inline constexpr auto rfc6979_scalar = + hex<32>("c9afa9d845ba75166b5c215767b1d6934e50c3db36e89b127b8a622b120f6721"); +// RFC 6979, section A.2.5: its public key, d * G, as SEC 1's uncompressed point 04 || Ux || Uy. +inline constexpr auto rfc6979_public = hex<65>( + "0460fed4ba255a9d31c961eb74c6356d68c049b8923b61fa6ce669622e60f29fb6" + "7903fe1008b8bc99a41ae9e95628bc64f2f1b20c2d7e9f5177a3c294d4462299"); +// FIPS 186-5 / SEC 2: the group order n, and (n - 1) / 2, the largest low S. +inline constexpr auto order = + hex<32>("ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"); +inline constexpr auto half_order = + hex<32>("7fffffff800000007fffffffffffffffde737d56d38bcf4279dce5617e3192a8"); +// FIPS 186-5 / SEC 2: the field prime p, which no coordinate reaches. +inline constexpr auto field_prime = + hex<32>("ffffffff00000001000000000000000000000000ffffffffffffffffffffffff"); + +} // namespace webcpp::test::p256 + +#endif // WEBCPP_TEST_CRYPTO_SUPPORT_P256_DATA_HPP diff --git a/test/support/timing_seam.hpp b/test/support/timing_seam.hpp index 3d8931be..c12cd3c4 100644 --- a/test/support/timing_seam.hpp +++ b/test/support/timing_seam.hpp @@ -9,7 +9,8 @@ // function that holds it, on every target, also where DIT does not apply. require_enters then // checks that a call entered a guard, and that the first, the outermost since a guard is its // function's first statement, is the one of the function the check names: a public function that -// forgot its own guard fails, also when it calls another guarded function. +// forgot its own guard fails, also when it calls another guarded function. uncovered checks the +// converse: a function that calls no backend's code enters no guard. #ifndef WEBCPP_TEST_CRYPTO_SUPPORT_TIMING_SEAM_HPP #define WEBCPP_TEST_CRYPTO_SUPPORT_TIMING_SEAM_HPP @@ -279,6 +280,26 @@ void require_enters(std::string_view name, Call&& call) { require_enters(name, name, std::forward(call)); } +/** + * Runs `call` and reports an error when it entered a detail::timing_guard: a public function that + * calls no backend's code holds none (the data-independent-timing change's ruling R4). A guard + * added to one by mistake costs every call, and makes the rule "a guard where the backend runs" + * harder to check. + * + * @param name What the call is, `:: on `, as an error names it. + * @param call The call, with its arguments bound. + */ +template +void uncovered(std::string_view name, Call&& call) { + std::size_t const before = timing_entries; + std::forward(call)(); + if (timing_entries != before) { + std::string const message = + std::string(name) + " entered a detail::timing_guard it should not hold"; + BOOST_ERROR(message.c_str()); + } +} + } // namespace webcpp::test #endif // WEBCPP_TEST_CRYPTO_SUPPORT_TIMING_SEAM_HPP diff --git a/test/timing_coverage_bearssl_test.cpp b/test/timing_coverage_bearssl_test.cpp index 5fdfef73..143099c5 100644 --- a/test/timing_coverage_bearssl_test.cpp +++ b/test/timing_coverage_bearssl_test.cpp @@ -15,6 +15,8 @@ // - AES-GCM, gcm, gcm and gcm: make, the move constructor and move // assignment (ruling R3), seal, open, begin_seal, update, result. // - ChaCha20-Poly1305, aead: make, seal, open. +// - P-256, curves::p256: basic_keypair::make, generate; basic_public_key::make (both); not +// guarded (no BearSSL call): public_key, secret_scalar, uncompressed. #include "support/timing_seam.hpp" @@ -22,12 +24,18 @@ #include #include #include +#include +#include #include +#include "support/p256_data.hpp" #include "support/timing_coverage.hpp" #include +#include +#include + namespace { namespace crypto = webcpp::crypto; @@ -45,9 +53,55 @@ void cover_ciphers() { "bearssl"); } +// P-256: the key pair's make and generate, the public key's two make, each refused once before +// BearSSL; the functions that copy what the key pair holds enter no guard. +void cover_p256_keys() { + namespace p256 = crypto::curves::p256; + namespace data = webcpp::test::p256; + using keypair = p256::basic_keypair; + using public_key = p256::basic_public_key; + webcpp::test::covered("p256::basic_keypair::make on bearssl", + [] { BOOST_TEST(keypair::make(data::rfc6979_scalar).has_value()); }); + webcpp::test::covered("p256::basic_keypair::make of the order on bearssl", [] { + BOOST_TEST(keypair::make(data::order).error() == crypto::error::invalid_secret_key); + }); + webcpp::test::covered("p256::basic_keypair::generate on bearssl", + [] { BOOST_TEST(keypair::generate().has_value()); }); + std::span const point(data::rfc6979_public); + webcpp::test::covered("p256::basic_public_key::make of a point on bearssl", + "basic_public_key::make", + [point] { BOOST_TEST(public_key::make(point).has_value()); }); + webcpp::test::covered( + "p256::basic_public_key::make of coordinates on bearssl", "basic_public_key::make", + [point] { + BOOST_TEST( + public_key::make(point.subspan<1, 32>(), point.subspan<33, 32>()).has_value()); + }); + webcpp::test::covered("p256::basic_public_key::make of 64 bytes on bearssl", + "basic_public_key::make", [point] { + BOOST_TEST(public_key::make(point.first(64)).error() == + crypto::error::invalid_public_key); + }); + auto const made = keypair::make(data::rfc6979_scalar); + if (!BOOST_TEST(made.has_value())) { + return; + } + webcpp::test::uncovered("p256::basic_keypair::public_key on bearssl", + [&made] { BOOST_TEST(made->public_key().has_value()); }); + webcpp::test::uncovered("p256::basic_keypair::secret_scalar on bearssl", + [&made] { BOOST_TEST(made->secret_scalar().has_value()); }); + auto const key = made->public_key(); + if (!BOOST_TEST(key.has_value())) { + return; + } + webcpp::test::uncovered("p256::basic_public_key::uncompressed on bearssl", + [&key] { BOOST_TEST(key->uncompressed() == data::rfc6979_public); }); +} + } // namespace int main() { cover_ciphers(); + cover_p256_keys(); return webcpp::test::exit_status(boost::report_errors()); } diff --git a/test/windows_h_after_test.cpp b/test/windows_h_after_test.cpp index fb1ab75b..937f2e04 100644 --- a/test/windows_h_after_test.cpp +++ b/test/windows_h_after_test.cpp @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include diff --git a/test/windows_h_before_test.cpp b/test/windows_h_before_test.cpp index 92ee1a67..6eb95f77 100644 --- a/test/windows_h_before_test.cpp +++ b/test/windows_h_before_test.cpp @@ -39,6 +39,7 @@ #include #include #include +#include #include #include #include From 5fdce8752e956ed74c482cb209894aa6829cd42e Mon Sep 17 00:00:00 2001 From: R Date: Sat, 21 Nov 2026 00:20:07 -0300 Subject: [PATCH 02/28] crypto: P-256's tests pin the non-canonical coordinates and the backend choice, and its pages fix the wording the review found --- doc/changelog.adoc | 2 +- doc/generated/namespace-curves.adoc | 4 ++-- doc/llms.txt | 2 +- doc/p256.adoc | 5 +++-- doc/tables/crypto.json | 4 ++-- include/webcpp/crypto/detail/p_curves.hpp | 5 +++-- test/p256_keys_bearssl_test.cpp | 18 ++++++++++++++++++ test/support/p256_data.hpp | 15 +++++++++++++++ 8 files changed, 45 insertions(+), 10 deletions(-) diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 5604b69f..64d9fd96 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -19,7 +19,7 @@ of every version are on webcpp's index page. * Added crypto, C-backed primitives setting DIT on arm64 macOS and Linux: ciphers, curves, randomness, fixed-value errors in webcpp.crypto, `+[[nodiscard]]+` results, WEBCPP_CRYPTO_HAS_THREADS, defined natively and with Emscripten's -pthread unless WEBCPP_CRYPTO_NO_THREADS is. * Added equal, random_device, pem (PEM on libsodium), ciphers::aes128, aes192 and aes256, the AES block cipher, and ciphers::gcm, aes128_gcm and aes256_gcm: AES-GCM in place, incremental seal, failed opens zeroing data. * Added supports_v with its family tags, the capability table per target, default_backend_t and /webcpp/crypto//-default per family and target (secp256k1's modules among them), and refusals naming their Jamfile line. -* Added backends::bearssl (AES-GCM, ChaCha20-Poly1305, P-256 key pairs; allocating nothing), backends::openssl natively and on WASI (allocating at make only, or in openssl_memory_resource with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE), and backends::ctaes (block cipher alone). +* Added backends::bearssl (AES-GCM, ChaCha20-Poly1305, P-256 key pairs; allocating nothing), backends::openssl natively and on WASI (allocating at make, or natively in openssl_memory_resource with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE), and backends::ctaes (block cipher alone). * Added curves::secp256k1: key pairs, BIP340, hedged and recoverable ECDSA, raw and hashed ECDH, strict DER, low-S, tweaks, SPKI, PKCS#8, PEM, BIP 324's ElligatorSwift, BIP 327's MuSig2, BIP 352's silent payments. * Added curves::ed25519 and curves::x25519 on libsodium: strict verification over twelve edge cases, Ed25519ph over hash's sha2_512 (/webcpp/crypto//crypto brings hash), the conversion, agree refusing all-zero secrets, RFC 8410's SPKI and PKCS#8. * Added backends::sodium on /third_party//sodium, shared with webcpp::hash, every backend's link-time canary and C suite, and ciphers::aead: chacha20_poly1305 (also BearSSL, OpenSSL), the original form, xchacha20_poly1305, failed seals and opens zeroing data. diff --git a/doc/generated/namespace-curves.adoc b/doc/generated/namespace-curves.adoc index 3a7cb050..55032bfb 100644 --- a/doc/generated/namespace-curves.adoc +++ b/doc/generated/namespace-curves.adoc @@ -49,9 +49,9 @@ |Standards |link:https://www.secg.org/sec2-v2.pdf[SEC 2, Recommended Elliptic Curve Domain Parameters], link:https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki[BIP 340, Schnorr signatures for secp256k1], link:https://www.rfc-editor.org/rfc/rfc6979[RFC 6979, deterministic ECDSA nonces], link:https://github.com/bitcoin/bips/blob/master/bip-0324.mediawiki[BIP 324, version 2 P2P encrypted transport protocol], link:https://github.com/bitcoin/bips/blob/master/bip-0327.mediawiki[BIP 327, MuSig2 for BIP340-compatible multi-signatures], link:https://github.com/bitcoin/bips/blob/master/bip-0352.mediawiki[BIP 352, Silent Payments] -|link:https://www.rfc-editor.org/rfc/rfc8032[RFC 8032, the Edwards-curve Digital Signature Algorithm (EdDSA)], link:https://csrc.nist.gov/pubs/fips/186-5/final[FIPS 186-5, the Digital Signature Standard, which adds EdDSA] +|link:https://www.rfc-editor.org/rfc/rfc8032[RFC 8032, the Edwards-curve Digital Signature Algorithm (EdDSA)], link:https://csrc.nist.gov/pubs/fips/186-5/final[FIPS 186-5, the Digital Signature Standard] |link:https://www.rfc-editor.org/rfc/rfc7748[RFC 7748, Elliptic Curves for Security (X25519 and X448)] -|link:https://csrc.nist.gov/pubs/fips/186-5/final[FIPS 186-5, the Digital Signature Standard, which adds EdDSA], link:https://www.secg.org/sec2-v2.pdf[SEC 2, Recommended Elliptic Curve Domain Parameters], link:https://www.secg.org/sec1-v2.pdf[SEC 1 version 2, Elliptic Curve Cryptography, sections 2.3.3 and 2.3.4: a point's encodings] +|link:https://csrc.nist.gov/pubs/fips/186-5/final[FIPS 186-5, the Digital Signature Standard], link:https://www.secg.org/sec2-v2.pdf[SEC 2, Recommended Elliptic Curve Domain Parameters], link:https://www.secg.org/sec1-v2.pdf[SEC 1 version 2, Elliptic Curve Cryptography, sections 2.3.3 and 2.3.4: a point's encodings] |Ecosystems that require it |Bitcoin (link:https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki[BIP 340, Schnorr signatures for secp256k1]), Ethereum (link:https://ethereum.github.io/yellowpaper/paper.pdf[The Ethereum yellow paper, appendix F: ECDSA on secp256k1]), Nostr (link:https://github.com/nostr-protocol/nips/blob/master/01.md[Nostr NIP-01, events signed with BIP 340 on secp256k1]) diff --git a/doc/llms.txt b/doc/llms.txt index 515b5924..0b6f5627 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -1,6 +1,6 @@ # webcpp::crypto -> Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA and recoverable signatures, ECDH, tweaks, ElligatorSwift, MuSig2, silent payments), Ed25519 and Ed25519ph (RFC 8032), X25519 (RFC 7748), P-256 key pairs and public keys on BearSSL, their keys in SPKI, PKCS#8 (RFC 8410) and PEM, libsodium's crypto_kx, the ChaCha20-Poly1305 AEADs, libsodium's secret boxes, boxes and sealed boxes, a random_device on the system's generator and a constant-time equal, each over a widely used, reviewed C library (BearSSL, OpenSSL, ctaes, libsecp256k1, libsodium) that the program names in its Jamfile. Hashing and HMAC are Boost.Hash2's; HKDF and password hashing are webcpp::hash's. Every failure is a boost::system::result value. Protocols (Bitcoin, Ethereum, Nostr) belong to domain libraries built on these primitives. +> Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA and recoverable signatures, ECDH, tweaks, ElligatorSwift, MuSig2, silent payments), Ed25519 and Ed25519ph (RFC 8032), X25519 (RFC 7748), their keys in SPKI, PKCS#8 (RFC 8410) and PEM, P-256 key pairs and public keys on BearSSL, libsodium's crypto_kx, the ChaCha20-Poly1305 AEADs, libsodium's secret boxes, boxes and sealed boxes, a random_device on the system's generator and a constant-time equal, each over a widely used, reviewed C library (BearSSL, OpenSSL, ctaes, libsecp256k1, libsodium) that the program names in its Jamfile. Hashing and HMAC are Boost.Hash2's; HKDF and password hashing are webcpp::hash's. Every failure is a boost::system::result value. Protocols (Bitcoin, Ethereum, Nostr) belong to domain libraries built on these primitives. Generated by doc/tables/generate.py with the page's tables. Page: https://webcpporg.github.io/libs/crypto/ diff --git a/doc/p256.adoc b/doc/p256.adoc index 9645b514..e14a70ec 100644 --- a/doc/p256.adoc +++ b/doc/p256.adoc @@ -79,14 +79,15 @@ include::{examples}/p256_keys.expected[] *Pitfalls.* * A scalar stored outside a `secret<32>` outlives the key pair: the key pair -and `secret_scalar`'s result wipe their bytes, but a copy in a string, a log or +and the `secret<32>` that `secret_scalar` returns wipe their bytes, but a copy in a string, a log or a file stays where it was written. Keep the scalar in the `secret<32>` until it is encrypted or written to the key store, and never print it. * A peer's key is made into a `public_key` once, where it arrives, and kept: made again for every message, it costs a point check each time, and code that keeps the bytes instead may skip the check on some path. The check matters: a point off the curve, combined with a secret key, is how invalid-curve attacks -begin (link:https://en.wikipedia.org/wiki/Elliptic-curve_Diffie%E2%80%93Hellman[Wikipedia]). +begin, which is why SEC 1 has a peer's public key validated before it is used +(link:https://www.secg.org/sec1-v2.pdf[SEC 1, section 3.2.2]). * The compressed form, 33 bytes that start with 02 or 03 (link:https://www.secg.org/sec1-v2.pdf[SEC 1, section 2.3.3]), is refused with `invalid_public_key`: BearSSL decodes uncompressed points alone. WebCrypto's diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index eae5a8da..c320fd89 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -1,7 +1,7 @@ { "comment": "The data of crypto's generated tables and of llms.txt; doc/tables/generate.py reads it with the test Jamfiles, the message tests and the superproject's Jamfile fixtures, and writes doc/generated/, doc/llms.txt, include/webcpp/crypto/detail/capabilities.hpp, include/webcpp/crypto/detail/defaults.hpp and test/capabilities_test.cpp. The capability table is `families`: per family its algorithms, the targets on which each backend has it (each claimed only where a test of the family's operations on that backend runs), constant time per target where it differs from the backend's own `constant_time` (X25519 on wasip2, an open finding, and natively without arm64's DIT, the cause of both), with `constant_time_checker` naming the checker that measured it where that is not every checker of the target, and the default per target, one whatever the program links (design D32), with its reason and the tests that fix it (a row of some of `compilers` restates its target's default for them, with a reason of their own, and each compiler of a target has one row), from which come include/webcpp/crypto/detail/defaults.hpp and the refusal that says what a program whose default is not linked needs; a backend with `targets`, where it is built, is a tag of `backends`. A name in a text is written between backticks, as Markdown writes code: the tables show it as code and llms.txt keeps the backticks. A comparison table's cell {speed:} or {constant_time:} is written from doc/performance.json or from the family's `constant_time`, and each cell of a column a namespace lists in `cited` cites a source or begins with \"none\". Edit this file, then run python3 libs/crypto/doc/tables/generate.py; the doc build runs it with --check.", "page": "https://webcpporg.github.io/libs/crypto/", - "llms": "Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA and recoverable signatures, ECDH, tweaks, ElligatorSwift, MuSig2, silent payments), Ed25519 and Ed25519ph (RFC 8032), X25519 (RFC 7748), P-256 key pairs and public keys on BearSSL, their keys in SPKI, PKCS#8 (RFC 8410) and PEM, libsodium's crypto_kx, the ChaCha20-Poly1305 AEADs, libsodium's secret boxes, boxes and sealed boxes, a random_device on the system's generator and a constant-time equal, each over a widely used, reviewed C library (BearSSL, OpenSSL, ctaes, libsecp256k1, libsodium) that the program names in its Jamfile. Hashing and HMAC are Boost.Hash2's; HKDF and password hashing are webcpp::hash's. Every failure is a boost::system::result value. Protocols (Bitcoin, Ethereum, Nostr) belong to domain libraries built on these primitives.", + "llms": "Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA and recoverable signatures, ECDH, tweaks, ElligatorSwift, MuSig2, silent payments), Ed25519 and Ed25519ph (RFC 8032), X25519 (RFC 7748), their keys in SPKI, PKCS#8 (RFC 8410) and PEM, P-256 key pairs and public keys on BearSSL, libsodium's crypto_kx, the ChaCha20-Poly1305 AEADs, libsodium's secret boxes, boxes and sealed boxes, a random_device on the system's generator and a constant-time equal, each over a widely used, reviewed C library (BearSSL, OpenSSL, ctaes, libsecp256k1, libsodium) that the program names in its Jamfile. Hashing and HMAC are Boost.Hash2's; HKDF and password hashing are webcpp::hash's. Every failure is a boost::system::result value. Protocols (Bitcoin, Ethereum, Nostr) belong to domain libraries built on these primitives.", "targets": ["native", "wasip2", "wasip3", "emscripten"], "compilers": {"clang": "Clang", "gcc": "GCC", "msvc": "MSVC"}, "checkers": {"memcheck": "Valgrind's memcheck (Linux)", "msan": "MemorySanitizer (Linux, clang)", "dudect": "dudect (judged off the runners GitHub hosts)"}, @@ -78,7 +78,7 @@ "wireguard": ["WireGuard's protocol, cryptography", "https://www.wireguard.com/protocol/"], "x3dh": ["Signal, the X3DH key agreement protocol", "https://signal.org/docs/specifications/x3dh/"], "libsodium-kx": ["libsodium's documentation, key exchange", "https://doc.libsodium.org/key_exchange"], - "fips186-5": ["FIPS 186-5, the Digital Signature Standard, which adds EdDSA", "https://csrc.nist.gov/pubs/fips/186-5/final"], + "fips186-5": ["FIPS 186-5, the Digital Signature Standard", "https://csrc.nist.gov/pubs/fips/186-5/final"], "rfc8709": ["RFC 8709, Ed25519 and Ed448 public keys for SSH", "https://www.rfc-editor.org/rfc/rfc8709"], "signal-xeddsa": ["Signal, the XEdDSA and VXEdDSA signature schemes", "https://signal.org/docs/specifications/xeddsa/"], "tor-cert-spec": ["Tor's specifications, Ed25519 certificates", "https://spec.torproject.org/cert-spec.html"], diff --git a/include/webcpp/crypto/detail/p_curves.hpp b/include/webcpp/crypto/detail/p_curves.hpp index 15511ae7..09a0e707 100644 --- a/include/webcpp/crypto/detail/p_curves.hpp +++ b/include/webcpp/crypto/detail/p_curves.hpp @@ -99,8 +99,9 @@ struct p_curve_engine; /** * The one door into a P-curve's opaque types (a public key, whose default constructor is - * private): the family's functions make one through it and write its point before they return - * it. It hands out nothing a caller of crypto could not already do. + * private), for the family's own functions alone: they make one through it and write its point + * before they return it. A key made through it is not validated: only a point a key pair + * computed or the backend checked may be written into it. */ struct p_curve_access { /** diff --git a/test/p256_keys_bearssl_test.cpp b/test/p256_keys_bearssl_test.cpp index c8c663d9..6c9baff3 100644 --- a/test/p256_keys_bearssl_test.cpp +++ b/test/p256_keys_bearssl_test.cpp @@ -189,6 +189,13 @@ void public_key_refusals() { auto x_is_p = data::rfc6979_public; std::ranges::copy(data::field_prime, x_is_p.begin() + 1); BOOST_TEST(refused(x_is_p)); + // A coordinate not below p of a point on the curve: (0, y0) and (x1, 1) are on it, and + // accepted; written with x + p and y + p, the same points are refused, the curve's equation + // alone would not refuse them. + BOOST_TEST(!refused(data::point_x_zero)); + BOOST_TEST(refused(data::point_x_zero_plus_p)); + BOOST_TEST(!refused(data::point_y_one)); + BOOST_TEST(refused(data::point_y_one_plus_p)); std::array zeros{}; BOOST_TEST(refused(zeros)); // 04 and zeros: (0, 0) is not on the curve, the identity has no affine form. @@ -200,6 +207,16 @@ void public_key_refusals() { error::invalid_public_key); } +void backend_choice() { + // Design D36: natively m62 where BearSSL has it, else m31; on WebAssembly m31 always. +#ifdef WEBCPP_CRYPTO_WEBASSEMBLY + BOOST_TEST(crypto::detail::bearssl_p256() == &br_ec_p256_m31); +#else + br_ec_impl const* const wide = br_ec_p256_m62_get(); + BOOST_TEST(crypto::detail::bearssl_p256() == (wide != nullptr ? wide : &br_ec_p256_m31)); +#endif +} + void moved_from() { auto made = keypair::make(data::rfc6979_scalar); if (!BOOST_TEST(made.has_value())) { @@ -285,6 +302,7 @@ int main() { generate_makes_distinct_valid_keys(); public_key_from_point_and_coordinates(); public_key_refusals(); + backend_choice(); moved_from(); wipe(); traits(); diff --git a/test/support/p256_data.hpp b/test/support/p256_data.hpp index 2ba1e25b..51ac8054 100644 --- a/test/support/p256_data.hpp +++ b/test/support/p256_data.hpp @@ -32,6 +32,21 @@ inline constexpr auto half_order = // FIPS 186-5 / SEC 2: the field prime p, which no coordinate reaches. inline constexpr auto field_prime = hex<32>("ffffffff00000001000000000000000000000000ffffffffffffffffffffffff"); +// Points on the curve, computed on 2026-11-21 from FIPS 186-5's b with p = 3 mod 4: (0, y0), +// y0 = b^((p + 1) / 4), and (x1, 1), x1 a root of x^3 - 3x + b - 1; each checked against the +// curve's equation. Then the same points with x + p and with y + p, which fit in 32 bytes. +inline constexpr auto point_x_zero = hex<65>( + "040000000000000000000000000000000000000000000000000000000000000000" + "66485c780e2f83d72433bd5d84a06bb6541c2af31dae871728bf856a174f93f4"); +inline constexpr auto point_x_zero_plus_p = hex<65>( + "04ffffffff00000001000000000000000000000000ffffffffffffffffffffffff" + "66485c780e2f83d72433bd5d84a06bb6541c2af31dae871728bf856a174f93f4"); +inline constexpr auto point_y_one = hex<65>( + "048d0177ebab9c6e9e10db6dd095dbac0d6375e8a97b70f611875d877f0069d2c7" + "0000000000000000000000000000000000000000000000000000000000000001"); +inline constexpr auto point_y_one_plus_p = hex<65>( + "048d0177ebab9c6e9e10db6dd095dbac0d6375e8a97b70f611875d877f0069d2c7" + "ffffffff00000001000000000000000000000001000000000000000000000000"); } // namespace webcpp::test::p256 From 3364579c9007ac6af66b3f6d973c83fd56e84855 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 21 Nov 2026 00:38:26 -0300 Subject: [PATCH 03/28] crypto: P-256 ECDSA on BearSSL with RFC 6979's nonce, raw and DER, and low S as two primitives, against RFC 6979 and Wycheproof --- doc/changelog.adoc | 2 +- doc/curves.adoc | 5 +- doc/generated/backends-p256_ecdsa.adoc | 35 +++ doc/generated/defaults.adoc | 2 +- doc/generated/matrix.adoc | 16 + doc/generated/namespace-curves.adoc | 6 +- doc/generated/use-cases.adoc | 9 +- doc/llms.txt | 15 +- doc/p256.adoc | 96 ++++++ doc/tables/crypto.json | 27 +- example/Jamfile | 3 + example/p256_sign.cpp | 105 +++++++ example/p256_sign.expected | 10 + include/webcpp/crypto/backends/bearssl.hpp | 120 ++++++- include/webcpp/crypto/curves/p256.hpp | 178 ++++++++++- include/webcpp/crypto/detail/p_curves.hpp | 60 ++++ test/Jamfile | 8 + test/allocation_bearssl_test.cpp | 53 +++- test/p256_ecdsa_bearssl_test.cpp | 348 +++++++++++++++++++++ test/p256_keys_bearssl_test.cpp | 2 + test/p256_wycheproof_bearssl_test.cpp | 174 +++++++++++ test/support/p256_data.hpp | 16 +- test/timing_coverage_bearssl_test.cpp | 61 +++- test/timing_test.cpp | 19 +- 24 files changed, 1336 insertions(+), 34 deletions(-) create mode 100644 doc/generated/backends-p256_ecdsa.adoc create mode 100644 example/p256_sign.cpp create mode 100644 example/p256_sign.expected create mode 100644 test/p256_ecdsa_bearssl_test.cpp create mode 100644 test/p256_wycheproof_bearssl_test.cpp diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 64d9fd96..3a6c06ad 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -19,7 +19,7 @@ of every version are on webcpp's index page. * Added crypto, C-backed primitives setting DIT on arm64 macOS and Linux: ciphers, curves, randomness, fixed-value errors in webcpp.crypto, `+[[nodiscard]]+` results, WEBCPP_CRYPTO_HAS_THREADS, defined natively and with Emscripten's -pthread unless WEBCPP_CRYPTO_NO_THREADS is. * Added equal, random_device, pem (PEM on libsodium), ciphers::aes128, aes192 and aes256, the AES block cipher, and ciphers::gcm, aes128_gcm and aes256_gcm: AES-GCM in place, incremental seal, failed opens zeroing data. * Added supports_v with its family tags, the capability table per target, default_backend_t and /webcpp/crypto//-default per family and target (secp256k1's modules among them), and refusals naming their Jamfile line. -* Added backends::bearssl (AES-GCM, ChaCha20-Poly1305, P-256 key pairs; allocating nothing), backends::openssl natively and on WASI (allocating at make, or natively in openssl_memory_resource with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE), and backends::ctaes (block cipher alone). +* Added backends::bearssl (AES-GCM, ChaCha20-Poly1305, P-256 key pairs and ECDSA; allocating nothing), backends::openssl natively and on WASI (allocating at make, or natively in openssl_memory_resource with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE), and backends::ctaes (block cipher alone). * Added curves::secp256k1: key pairs, BIP340, hedged and recoverable ECDSA, raw and hashed ECDH, strict DER, low-S, tweaks, SPKI, PKCS#8, PEM, BIP 324's ElligatorSwift, BIP 327's MuSig2, BIP 352's silent payments. * Added curves::ed25519 and curves::x25519 on libsodium: strict verification over twelve edge cases, Ed25519ph over hash's sha2_512 (/webcpp/crypto//crypto brings hash), the conversion, agree refusing all-zero secrets, RFC 8410's SPKI and PKCS#8. * Added backends::sodium on /third_party//sodium, shared with webcpp::hash, every backend's link-time canary and C suite, and ciphers::aead: chacha20_poly1305 (also BearSSL, OpenSSL), the original form, xchacha20_poly1305, failed seals and opens zeroing data. diff --git a/doc/curves.adoc b/doc/curves.adoc index 2e896299..f60befbd 100644 --- a/doc/curves.adoc +++ b/doc/curves.adoc @@ -65,9 +65,10 @@ key to it (link:https://www.rfc-editor.org/rfc/rfc7748[RFC 7748]; <>), and libsodium's key exchange on it, `crypto_kx` (<>). The fourth is P-256, NIST's curve of FIPS 186-5, the curve of browsers' WebCrypto, of passkeys and of TLS certificates, on BearSSL: key pairs -made from a scalar or drawn, and public keys validated once +made from a scalar or drawn, public keys validated once, and ECDSA with RFC +6979's nonce, raw and DER, with low S as two functions (link:https://csrc.nist.gov/pubs/fips/186-5/final[FIPS 186-5]; -<>). A program chooses a curve for compatibility: a signature on +<>, <>). A program chooses a curve for compatibility: a signature on one curve is checked only with that curve, and a browser's peer needs P-256. Ed25519's and X25519's keys leave a program, and enter it, in the standard forms OpenSSL and WebCrypto use, SPKI and PKCS#8, as DER or PEM text (<>). diff --git a/doc/generated/backends-p256_ecdsa.adoc b/doc/generated/backends-p256_ecdsa.adoc new file mode 100644 index 00000000..e0fc5986 --- /dev/null +++ b/doc/generated/backends-p256_ecdsa.adoc @@ -0,0 +1,35 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, +// the message tests and the Jamfile fixtures: run it again, never edit this file. + +The backends of `+curves::p256::keypair::sign_ecdsa+`, `+verify_ecdsa+`, `+to_der+`, `+from_der+`, `+normalize_ecdsa+`, `+check_low_s+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|BearSSL +|`+/third_party//bearssl+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+p256_ecdsa_bearssl+`, `+p256_wycheproof_bearssl+`, `+allocation_bearssl+`) + +|libsodium +|`+/third_party//sodium+` +|`++` +|refused at compile time (`+p256_on_sodium+`) +|=== + +A call that names no backend takes the family's default on each target, whatever the program links, as <> gives it with its reasons and tests: + +[cols="1,1",options="header"] +|=== +|Target |Default + +|native, wasip2, wasip3, emscripten +|BearSSL +|=== diff --git a/doc/generated/defaults.adoc b/doc/generated/defaults.adoc index 733a21b9..f68857bc 100644 --- a/doc/generated/defaults.adoc +++ b/doc/generated/defaults.adoc @@ -141,5 +141,5 @@ |native, wasip2, wasip3, emscripten |BearSSL |the one backend of the P-curves on all four targets, constant time by design and allocating nothing (link:https://www.bearssl.org/[BearSSL, its home page]); OpenSSL and Botan join in increments 8 and 7 -|`+p256_keys_bearssl+`, `+default_backend_none_linked+` +|`+p256_keys_bearssl+`, `+p256_ecdsa_bearssl+`, `+default_backend_none_linked+` |=== diff --git a/doc/generated/matrix.adoc b/doc/generated/matrix.adoc index ca1ee9be..aa77d09f 100644 --- a/doc/generated/matrix.adoc +++ b/doc/generated/matrix.adoc @@ -240,6 +240,16 @@ |BearSSL |native, wasip2, wasip3, emscripten |`+p256_keys_bearssl+`, `+allocation_bearssl+` + +|`+curves::p256::keypair::sign_ecdsa+`, `+verify_ecdsa+`, `+to_der+`, `+from_der+`, `+normalize_ecdsa+`, `+check_low_s+` +|BearSSL +|native, wasip2, wasip3, emscripten +|`+p256_ecdsa_bearssl+`, `+p256_wycheproof_bearssl+`, `+allocation_bearssl+` + +|`+curves::p256::keypair::sign_ecdsa+`, `+verify_ecdsa+`, `+to_der+`, `+from_der+`, `+normalize_ecdsa+`, `+check_low_s+` +|libsodium +|refused at compile time +|`+p256_on_sodium+` |=== The same, by target: the backends each operation runs on. @@ -469,4 +479,10 @@ The same, by target: the backends each operation runs on. |BearSSL |BearSSL |BearSSL + +|`+curves::p256::keypair::sign_ecdsa+`, `+verify_ecdsa+`, `+to_der+`, `+from_der+`, `+normalize_ecdsa+`, `+check_low_s+` +|BearSSL +|BearSSL +|BearSSL +|BearSSL |=== diff --git a/doc/generated/namespace-curves.adoc b/doc/generated/namespace-curves.adoc index 55032bfb..990b6d75 100644 --- a/doc/generated/namespace-curves.adoc +++ b/doc/generated/namespace-curves.adoc @@ -15,7 +15,7 @@ |BIP 340 Schnorr and ECDSA signatures, recoverable signatures, ECDH in three forms, tweaks, ElligatorSwift, MuSig2, silent payments, SPKI and PKCS#8 |Ed25519 signatures, and Ed25519ph over SHA-512 for a message given in pieces; the X25519 secret key of a key pair |Key agreement (Diffie-Hellman on Curve25519): two parties who exchanged public keys share a 32-byte secret; `kx_keypair`, libsodium's `crypto_kx`, gives a client and a server a session key for each direction -|Key pairs made from a 32-byte scalar or drawn from `random_device`, and public keys validated once, as SEC 1's uncompressed point or two coordinates +|Key pairs made from a 32-byte scalar or drawn from `random_device`, public keys validated once, as SEC 1's uncompressed point or two coordinates, and ECDSA over a SHA-256 digest with RFC 6979's nonce, raw and DER, and low S checked or normalized |Security level |about 128 bits (link:https://www.secg.org/sec2-v2.pdf[SEC 2, Recommended Elliptic Curve Domain Parameters]) @@ -33,7 +33,7 @@ |64 bytes, MuSig2's aggregate too (link:https://github.com/bitcoin/bips/blob/master/bip-0327.mediawiki[BIP 327, MuSig2 for BIP340-compatible multi-signatures]); 65 bytes recoverable; ECDSA in DER up to 72 |64 bytes |none: no signatures -|none yet: ECDSA comes next +|ECDSA: 64 bytes, r and s (link:https://standards.ieee.org/ieee/1363/2049/[IEEE 1363-2000, Standard Specifications for Public-Key Cryptography: a signature as the two integers r and s, each at the order's length]); in DER up to 72 (link:https://www.rfc-editor.org/rfc/rfc3279#section-2.2.3[RFC 3279, section 2.2.3: an ECDSA signature in X.509, the DER of a SEQUENCE of the INTEGERs r and s]) |Speed |BIP340 signature of a 32-byte message: native, libsecp256k1 9.02 µs; wasip2, libsecp256k1 53.9 µs; wasip3, libsecp256k1 65.9 µs; emscripten, libsecp256k1 63.9 µs (2026-11-20, Apple M5 Max, under load: read the spread; <>) @@ -51,7 +51,7 @@ |link:https://www.secg.org/sec2-v2.pdf[SEC 2, Recommended Elliptic Curve Domain Parameters], link:https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki[BIP 340, Schnorr signatures for secp256k1], link:https://www.rfc-editor.org/rfc/rfc6979[RFC 6979, deterministic ECDSA nonces], link:https://github.com/bitcoin/bips/blob/master/bip-0324.mediawiki[BIP 324, version 2 P2P encrypted transport protocol], link:https://github.com/bitcoin/bips/blob/master/bip-0327.mediawiki[BIP 327, MuSig2 for BIP340-compatible multi-signatures], link:https://github.com/bitcoin/bips/blob/master/bip-0352.mediawiki[BIP 352, Silent Payments] |link:https://www.rfc-editor.org/rfc/rfc8032[RFC 8032, the Edwards-curve Digital Signature Algorithm (EdDSA)], link:https://csrc.nist.gov/pubs/fips/186-5/final[FIPS 186-5, the Digital Signature Standard] |link:https://www.rfc-editor.org/rfc/rfc7748[RFC 7748, Elliptic Curves for Security (X25519 and X448)] -|link:https://csrc.nist.gov/pubs/fips/186-5/final[FIPS 186-5, the Digital Signature Standard], link:https://www.secg.org/sec2-v2.pdf[SEC 2, Recommended Elliptic Curve Domain Parameters], link:https://www.secg.org/sec1-v2.pdf[SEC 1 version 2, Elliptic Curve Cryptography, sections 2.3.3 and 2.3.4: a point's encodings] +|link:https://csrc.nist.gov/pubs/fips/186-5/final[FIPS 186-5, the Digital Signature Standard], link:https://www.secg.org/sec2-v2.pdf[SEC 2, Recommended Elliptic Curve Domain Parameters], link:https://www.secg.org/sec1-v2.pdf[SEC 1 version 2, Elliptic Curve Cryptography, sections 2.3.3 and 2.3.4: a point's encodings], link:https://www.rfc-editor.org/rfc/rfc6979[RFC 6979, deterministic ECDSA nonces] |Ecosystems that require it |Bitcoin (link:https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki[BIP 340, Schnorr signatures for secp256k1]), Ethereum (link:https://ethereum.github.io/yellowpaper/paper.pdf[The Ethereum yellow paper, appendix F: ECDSA on secp256k1]), Nostr (link:https://github.com/nostr-protocol/nips/blob/master/01.md[Nostr NIP-01, events signed with BIP 340 on secp256k1]) diff --git a/doc/generated/use-cases.adoc b/doc/generated/use-cases.adoc index 5511b05c..e4b2b881 100644 --- a/doc/generated/use-cases.adoc +++ b/doc/generated/use-cases.adoc @@ -243,10 +243,17 @@ `+/webcpp/crypto//x25519-default+` |<> -|Signatures and key agreement a browser's WebCrypto verifies and derives (P-256 with SHA-256), webcpp::trystero's handshakes +|Make and keep a P-256 key pair, and import a browser's public key (WebCrypto's raw form), as webcpp::trystero's peers do |In `+curves::p256+`: `+keypair::make+`, `+keypair::generate+`, `+keypair::public_key+`, `+keypair::secret_scalar+`, `+public_key::make+` |BearSSL |`+/webcpp/crypto//crypto+` + `+/webcpp/crypto//p256-default+` |<> + +|Sign what a browser's WebCrypto verifies and verify what it signs (ECDSA on P-256 with SHA-256), low S where a protocol requires it, as webcpp::trystero's handshakes +|In `+curves::p256+`: `+keypair::sign_ecdsa+`, `+verify_ecdsa+`, `+normalize_ecdsa+`, `+check_low_s+`; `+to_der+`, `+from_der+` for X.509 +|BearSSL +|`+/webcpp/crypto//crypto+` + +`+/webcpp/crypto//p256-default+` +|<> |=== diff --git a/doc/llms.txt b/doc/llms.txt index 0b6f5627..a2fe0c1e 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -169,14 +169,21 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - create_labeled_spend_key: The spend key of a labelled address (`..._create_labeled_spend_pubkey`). - make_prevouts_summary: The prevouts' summary (`..._recipient_prevouts_summary_create`) from the eligible inputs' public keys. - 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, a `secret<32>`. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten. Default: BearSSL on native, wasip2, wasip3, emscripten. Use it to: signatures and key agreement a browser's WebCrypto verifies and derives (P-256 with SHA-256), webcpp::trystero's handshakes. +- [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, a `secret<32>`. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten. Default: BearSSL on native, wasip2, wasip3, emscripten. Use it to: make and keep a P-256 key pair, and import a browser's public key (WebCrypto's raw form), as webcpp::trystero's peers do. - make: Makes a key pair from its secret scalar, as a program that kept `secret_scalar` 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). - public_key: The public key, computed when the key pair was made. - secret_scalar: The secret scalar, for a program that keeps the key pair and makes it again with `make`. -- [curves::p256::public_key](https://webcpporg.github.io/libs/crypto/#crypto-p256-keys): A validated P-256 public key, made from SEC 1's 65-byte uncompressed point or from its two coordinates; a point off the curve, a coordinate not below p or another form is `invalid_public_key`. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten. Default: BearSSL on native, wasip2, wasip3, emscripten. Use it to: signatures and key agreement a browser's WebCrypto verifies and derives (P-256 with SHA-256), webcpp::trystero's handshakes. +- [curves::p256::public_key](https://webcpporg.github.io/libs/crypto/#crypto-p256-keys): A validated P-256 public key, made from SEC 1's 65-byte uncompressed point or from its two coordinates; a point off the curve, a coordinate not below p or another form is `invalid_public_key`. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten. Default: BearSSL on native, wasip2, wasip3, emscripten. Use it to: make and keep a P-256 key pair, and import a browser's public key (WebCrypto's raw form), as webcpp::trystero's peers do. - make: Makes a public key from SEC 1's uncompressed point, as WebCrypto's `exportKey("raw")` writes it. - uncompressed: The point, as WebCrypto's `exportKey("raw")` writes it. +- [curves::p256::keypair::sign_ecdsa, verify_ecdsa, to_der, from_der, normalize_ecdsa, check_low_s](https://webcpporg.github.io/libs/crypto/#crypto-p256-ecdsa): ECDSA over a SHA-256 digest with RFC 6979's nonce, r and s as 64 bytes, verified whatever its S; strict DER both ways; low S as two functions, `normalize_ecdsa` and `check_low_s`, for a protocol that requires it. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten. Default: BearSSL on native, wasip2, wasip3, emscripten. Use it to: sign what a browser's WebCrypto verifies and verify what it signs (ECDSA on P-256 with SHA-256), low S where a protocol requires it, as webcpp::trystero's handshakes. + - sign_ecdsa: Signs a SHA-256 digest with ECDSA, RFC 6979's deterministic nonce (no random number is drawn: the same key and digest give the same signature), S as the computation gives it, high or low (`normalize_ecdsa` gives the low form). + - verify_ecdsa: Verifies an ECDSA signature of a SHA-256 digest with a public key. + - to_der: Encodes a signature as strict DER, the ECDSA-Sig-Value SEQUENCE of two INTEGERs that X.509 and OpenSSL carry. + - from_der: Decodes a strict DER signature to its raw form: only the encoding `to_der` writes is accepted. + - normalize_ecdsa: The low-S form of a signature: s replaced by n - s when s is above (n - 1) / 2, returned unchanged otherwise. + - check_low_s: Checks that a signature is in its low-S form, s at most (n - 1) / 2, as a protocol that requires low S checks what it receives. ## webcpp::crypto::hybrid @@ -289,7 +296,8 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [Send messages between two people who know each other's public keys, as NaCl's and libsodium's crypto_box](https://webcpporg.github.io/libs/crypto/#crypto-box): `box::make`, `box::seal`, `box::open` (webcpp::crypto::hybrid); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//box_xsalsa20poly1305-default. Example: example/box_messages.cpp. - [Let anyone send a message that only the recipient can read, without saying who sent it (anonymous feedback, a drop box)](https://webcpporg.github.io/libs/crypto/#crypto-sealed-box): `sealed_box::seal`, `sealed_box::open` (webcpp::crypto::hybrid); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//sealed_box-default. Example: example/file_share.cpp. - [Share a file with someone known only by a public key, as a file-sharing app does](https://webcpporg.github.io/libs/crypto/#crypto-everyday-files): `ciphers::secretbox<>` for the file under a key drawn for it, `hybrid::sealed_box::seal` for that key (webcpp::crypto); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//secretbox_xsalsa20poly1305-default /webcpp/crypto//sealed_box-default /webcpp/crypto//x25519-default. Example: example/file_share.cpp. -- [Signatures and key agreement a browser's WebCrypto verifies and derives (P-256 with SHA-256), webcpp::trystero's handshakes](https://webcpporg.github.io/libs/crypto/#crypto-p256-keys): `keypair::make`, `keypair::generate`, `keypair::public_key`, `keypair::secret_scalar`, `public_key::make` (webcpp::crypto::curves::p256); backend BearSSL; Jamfile /webcpp/crypto//crypto /webcpp/crypto//p256-default. Example: example/p256_keys.cpp. +- [Make and keep a P-256 key pair, and import a browser's public key (WebCrypto's raw form), as webcpp::trystero's peers do](https://webcpporg.github.io/libs/crypto/#crypto-p256-keys): `keypair::make`, `keypair::generate`, `keypair::public_key`, `keypair::secret_scalar`, `public_key::make` (webcpp::crypto::curves::p256); backend BearSSL; Jamfile /webcpp/crypto//crypto /webcpp/crypto//p256-default. Example: example/p256_keys.cpp. +- [Sign what a browser's WebCrypto verifies and verify what it signs (ECDSA on P-256 with SHA-256), low S where a protocol requires it, as webcpp::trystero's handshakes](https://webcpporg.github.io/libs/crypto/#crypto-p256-ecdsa): `keypair::sign_ecdsa`, `verify_ecdsa`, `normalize_ecdsa`, `check_low_s`; `to_der`, `from_der` for X.509 (webcpp::crypto::curves::p256); backend BearSSL; Jamfile /webcpp/crypto//crypto /webcpp/crypto//p256-default. Example: example/p256_sign.cpp. ## Examples @@ -314,6 +322,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - example/openssl_memory.cpp: Sends every allocation of OpenSSL's to the program's own memory resource, natively, then seals and opens one block with AES-256-GCM on OpenSSL, on a worker thread as an audio engine's or a server's would. Built with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE, /webcpp/crypto//openssl and threads (example/Jamfile). - example/order_reference.cpp: Turns a sequential order id into an opaque 16-byte reference with the raw AES block cipher, and back. Customers then cannot guess other orders' numbers. This is NOT authenticated encryption: a forged reference still decrypts, to garbage, so the program checks the padding. - example/p256_keys.cpp: Makes a P-256 key pair from RFC 6979's key, prints its public key as the 65 bytes WebCrypto's exportKey("raw") gives, keeps its scalar and makes the same key pair from it again, then imports that public key as a peer's and refuses the same bytes with one bit changed. Draws a fresh key pair too, whose bytes differ on every run and are not printed. +- example/p256_sign.cpp: Signs the SHA-256 digest of "sample" with RFC 6979's P-256 key and prints the signature, the RFC's own bytes, in the raw form WebCrypto uses; then its low-S form, which a protocol that requires low S sends, and its DER encoding, which X.509 carries; and verifies both forms with the public key alone, and refuses the digest of another message. - example/recover_signer.cpp: Finds who signed a message without being sent their key, as Ethereum finds a transaction's signer: a wallet signs a message's hash with a recoverable signature, and a reader that holds no key recovers the signer's public key from the signature and the hash, then compares it with the key the wallet published. Recovery always finds some key, so the comparison is the check: a changed message recovers another key. - example/reset_token.cpp: Draws a 32-byte password-reset token and a six-digit one-time code from the system's random generator. Tokens that can be guessed or repeated let an attacker take over accounts, so both come from random_device, never from rand() or the clock. - example/schnorr_sign.cpp: Signs BIP340's first test vector with secp256k1 and verifies it, then tweaks the key pair by a 32-byte tweak, as a domain library derives one, and signs and verifies under the tweaked key. Prints each key and signature in hex. diff --git a/doc/p256.adoc b/doc/p256.adoc index e14a70ec..838a6286 100644 --- a/doc/p256.adoc +++ b/doc/p256.adoc @@ -93,3 +93,99 @@ begin, which is why SEC 1 has a peer's public key validated before it is used `invalid_public_key`: BearSSL decodes uncompressed points alone. WebCrypto's raw export is uncompressed, so a browser's key arrives in the form `make` takes; a key a tool sends compressed is decompressed by that tool first. + +[#crypto-p256-ecdsa] +==== ECDSA + +ECDSA signs a *digest*, not a message: the program hashes the message with +SHA-256, then `keypair::sign_ecdsa(digest)` signs those 32 bytes, as +WebCrypto's `sign({name: "ECDSA", hash: "SHA-256"}, ...)` hashes and signs in one +call (link:https://www.w3.org/TR/WebCryptoAPI/[W3C]) and passkeys' ES256 does +(link:https://www.w3.org/TR/webauthn-2/#sctn-alg-identifier[W3C Web +Authentication]): + +[source,cpp] +---- +std::array digest{}; +auto hashed = webcpp::hash::digest_of(digest, message); +auto signature = key.sign_ecdsa(digest); // 64 bytes: r, then s +---- + +The nonce is RFC 6979's (link:https://www.rfc-editor.org/rfc/rfc6979[RFC +6979]): derived from the secret key and the digest, so signing draws no random +number, a weak generator cannot leak the key, and the same key and digest give +the same signature. Every verifier accepts it, WebCrypto's and OpenSSL's +included: a verifier cannot tell how a nonce was made, and the signature is an +ordinary ECDSA signature (link:https://csrc.nist.gov/pubs/fips/186-5/final[FIPS +186-5]). `verify_ecdsa(signature, digest, public_key)` succeeds or returns +`invalid_signature`, also for an r or an s that is 0 or not below the group +order n, refused before BearSSL sees it. + +A signature has two forms. The *raw* form, 64 bytes, r then s at 32 bytes each +(link:https://standards.ieee.org/ieee/1363/2049/[IEEE 1363]), is the one +`sign_ecdsa` and `verify_ecdsa` take: what WebCrypto signs and verifies +(link:https://www.w3.org/TR/WebCryptoAPI/[W3C]) and what a JSON Web Token's +ES256 carries (link:https://www.rfc-editor.org/rfc/rfc7518#section-3.4[RFC +7518, section 3.4]). *DER*, a SEQUENCE of two INTEGERs of 8 to 72 bytes, is the +form of X.509 certificates and OpenSSL +(link:https://www.rfc-editor.org/rfc/rfc3279#section-2.2.3[RFC 3279, section +2.2.3]): `to_der(signature, output)` writes it into at least `max_der_size` +bytes and returns its length, and `from_der(bytes)` reads it back, accepting +strict DER only, the encoding `to_der` writes, and refusing anything else with +`invalid_signature`. + +include::generated/backends-p256_ecdsa.adoc[] + +*Low S.* If (r, s) is a valid signature, (r, n - s) is a valid signature of the +same digest too: anyone can turn one into the other without the key. That is +*malleability*, harmless for most programs, since both say the same signer +signed the same digest, but a protocol that names a message by its signature's +bytes sees two names for one message. FIPS 186-5 and WebCrypto accept both +forms (link:https://csrc.nist.gov/pubs/fips/186-5/final[FIPS 186-5]; +link:https://www.w3.org/TR/WebCryptoAPI/[W3C]), and so does `verify_ecdsa`; +`sign_ecdsa` returns S as RFC 6979 computes it, high or low. Some protocols +accept only the *low-S* form, s at most (n - 1) / 2: Bitcoin's +(link:https://github.com/bitcoin/bips/blob/master/bip-0146.mediawiki[BIP 146]) +and Trystero's, which normalizes what it signs and refuses a high S in what it +reads +(link:https://github.com/dmotz/trystero/blob/0.27.0/packages/core/src/crypto.ts[Trystero +0.27.0]). Such a policy has two halves, and crypto offers each: +`normalize_ecdsa(signature)` returns the low-S form, the same signature when S +is already low, before the signature is sent; `check_low_s(signature)` returns +`invalid_signature` for a high S, before the signature received is verified. +Neither calls BearSSL: both are arithmetic on public bytes. + +*Example.* RFC 6979's key signs the SHA-256 of "sample", which gives the RFC's +own signature, whose S is high; its low-S form, its DER, both forms verified, +and another message's digest refused: + +[source,cpp] +---- +include::{examples}/p256_sign.cpp[tag=program] +---- + +[listing] +---- +include::{examples}/p256_sign.expected[] +---- + +*Pitfalls.* + +* A protocol that requires low S and forgets `normalize_ecdsa` fails about one +signature in two: `sign_ecdsa`'s S is high half the time, and the peer's +`check_low_s` refuses those. The tests that sign a fixed message may pass +every time, the signature being the same; a program sees it at the first +handshake whose S is high. Normalize every signature such a protocol sends, +and check every one it receives. +* `check_low_s` does not verify: a forged signature can have a low S. Check low +S, then verify, and accept the signature only when both succeed. +* Signing a message instead of its digest does not compile: `sign_ecdsa` takes +exactly 32 bytes. A digest of another hash than SHA-256, or a message cut to 32 +bytes, signs, and no WebCrypto peer verifies it, since WebCrypto's ECDSA with +SHA-256 hashes what it verifies with SHA-256 itself. +* A passkey's ES256 is ECDSA on P-256 with SHA-256, and its assertion's +signature arrives in DER +(link:https://www.w3.org/TR/webauthn-2/#sctn-signature-attestation-types[W3C +Web Authentication, section 6.5.5]): `from_der`, then `verify_ecdsa` of the +SHA-256 of what the authenticator signed. Reading the COSE key and building +those signed bytes are WebAuthn's, and stay outside crypto. diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index c320fd89..3ab139cc 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -41,6 +41,11 @@ "wasi-random": ["WASI, wasi:random", "https://github.com/WebAssembly/wasi-random"], "bearssl": ["BearSSL, its home page", "https://www.bearssl.org/"], "webauthn": ["W3C Web Authentication, its algorithm identifiers: ES256 is ECDSA on P-256 with SHA-256", "https://www.w3.org/TR/webauthn-2/#sctn-alg-identifier"], + "webauthn-signatures": ["W3C Web Authentication, section 6.5.5: an ES256 assertion's signature is DER, RFC 3279's Ecdsa-Sig-Value", "https://www.w3.org/TR/webauthn-2/#sctn-signature-attestation-types"], + "ieee1363": ["IEEE 1363-2000, Standard Specifications for Public-Key Cryptography: a signature as the two integers r and s, each at the order's length", "https://standards.ieee.org/ieee/1363/2049/"], + "rfc3279": ["RFC 3279, section 2.2.3: an ECDSA signature in X.509, the DER of a SEQUENCE of the INTEGERs r and s", "https://www.rfc-editor.org/rfc/rfc3279#section-2.2.3"], + "rfc7518": ["RFC 7518, section 3.4: JWS's ES256 signature is r and s, 32 bytes each, not DER", "https://www.rfc-editor.org/rfc/rfc7518#section-3.4"], + "trystero": ["Trystero 0.27.0's crypto.ts: its ECDSA P-256 signatures normalized to low S when made and refused unless low S when read", "https://github.com/dmotz/trystero/blob/0.27.0/packages/core/src/crypto.ts"], "bearssl-ct": ["BearSSL, constant-time crypto", "https://www.bearssl.org/constanttime.html"], "bearssl-ctmul": ["BearSSL, constant-time multiplications", "https://www.bearssl.org/ctmul.html"], "ctaes": ["ctaes, constant-time AES", "https://github.com/bitcoin/bitcoin/tree/master/src/crypto/ctaes"], @@ -672,6 +677,21 @@ "what": "A validated P-256 public key, made from SEC 1's 65-byte uncompressed point or from its two coordinates; a point off the curve, a coordinate not below p or another form is `invalid_public_key`.", "section": "crypto-p256-keys", "backends": {"bearssl": {"tests": ["p256_keys_bearssl", "allocation_bearssl"]}} + }, + { + "id": "p256_ecdsa", + "family": "p256", + "free": true, + "functions": ["basic_keypair::sign_ecdsa", "verify_ecdsa", "to_der", "from_der", "normalize_ecdsa", "check_low_s"], + "namespace": "curves", + "api": "curves::p256::keypair::sign_ecdsa, verify_ecdsa, to_der, from_der, normalize_ecdsa, check_low_s", + "header": "", + "what": "ECDSA over a SHA-256 digest with RFC 6979's nonce, r and s as 64 bytes, verified whatever its S; strict DER both ways; low S as two functions, `normalize_ecdsa` and `check_low_s`, for a protocol that requires it.", + "section": "crypto-p256-ecdsa", + "backends": { + "bearssl": {"tests": ["p256_ecdsa_bearssl", "p256_wycheproof_bearssl", "allocation_bearssl"]}, + "sodium": {"refused": "p256_on_sodium"} + } } ], "families": [ @@ -1010,7 +1030,7 @@ {"name": "p256", "title": "P-256", "type": "curves::p256::basic_keypair<{backend}>"} ], "default": [ - {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "bearssl", "tests": ["p256_keys_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"} + {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "bearssl", "tests": ["p256_keys_bearssl", "p256_ecdsa_bearssl", "default_backend_none_linked"], "why": "the one backend of the P-curves on all four targets, constant time by design and allocating nothing ({bearssl}); OpenSSL and Botan join in increments 8 and 7"} ], "backends": { "bearssl": {"targets": "all"} @@ -1083,7 +1103,7 @@ ["`secp256k1`", "BIP 340 Schnorr and ECDSA signatures, recoverable signatures, ECDH in three forms, tweaks, ElligatorSwift, MuSig2, silent payments, SPKI and PKCS#8", "about 128 bits ({sec2})", "secret 32 bytes; public 33 bytes compressed, 65 bytes uncompressed ({sec1}), 32 bytes x-only, 64 bytes as ElligatorSwift ({bip324}); SPKI 56 or 88 bytes ({rfc5480}), PKCS#8 135 bytes ({rfc5208}, {rfc5915})", "64 bytes, MuSig2's aggregate too ({bip327}); 65 bytes recoverable; ECDSA in DER up to 72", "{speed:secp256k1}", "{constant_time:secp256k1}", "{sec2}, {bip340}, {rfc6979}, {bip324}, {bip327}, {bip352}", "Bitcoin ({bip340}), Ethereum ({ethereum}), Nostr ({nip01})", "no: WebCrypto offers P-256, P-384, P-521, Ed25519 and X25519, not secp256k1 ({webcrypto})", "Bitcoin's keys and signatures; Nostr's event signatures ({nip01}); Ethereum's ECDSA verification with a known key; ECDH in the raw x-coordinate form of Nostr's encrypted messages ({nip44}); Ethereum's recoverable signatures and uncompressed keys ({ethereum}), the address hashing being a domain library's; BIP 32's tweaks of the full key, its derivation of the tweak being a domain library's ({bip32}); keys exchanged with OpenSSL as SPKI or PKCS#8 ({rfc5480}, {rfc5915}), in DER or PEM ({rfc7468}); Bitcoin's version 2 transport, whose keys are ElligatorSwift encodings ({bip324}); MuSig2's multisignatures ({bip327}); silent payments ({bip352}), the addresses and transactions being a domain library's"], ["`ed25519`", "Ed25519 signatures, and Ed25519ph over SHA-512 for a message given in pieces; the X25519 secret key of a key pair", "about 128 bits ({rfc8032})", "secret 32 bytes (the seed); public 32 bytes", "64 bytes", "{speed:ed25519}", "{constant_time:ed25519}", "{rfc8032}, {fips186-5}", "SSH keys ({rfc8709}), Signal's signatures on its Curve25519 keys ({signal-xeddsa}), Tor's identity keys ({tor-cert-spec}), Solana's accounts ({solana-accounts})", "yes: Ed25519 ({webcrypto})", "SSH, Tor and Solana keys and signatures, and any protocol that names RFC 8032's Ed25519 or Ed25519ph; verification is strict (libsodium's rules), which some lenient verifiers are not. Not Bitcoin, Ethereum or Nostr, whose keys are secp256k1's"], ["`x25519`", "Key agreement (Diffie-Hellman on Curve25519): two parties who exchanged public keys share a 32-byte secret; `kx_keypair`, libsodium's `crypto_kx`, gives a client and a server a session key for each direction", "about 128 bits ({rfc7748})", "secret 32 bytes; public 32 bytes", "none: no signatures", "{speed:x25519}", "{constant_time:x25519}", "{rfc7748}", "TLS 1.3 ({rfc8446-groups}), SSH ({rfc8731}), WireGuard ({wireguard}), Signal ({x3dh})", "yes: X25519 ({webcrypto})", "TLS 1.3's and SSH's key exchange, WireGuard, Signal; libsodium's `crypto_box` keys, and the session keys of `crypto_kx` with `kx_keypair` ({libsodium-kx}). The Ed25519 public key of a peer converts with `curves::ed25519::to_x25519_public`. A shared secret goes through a KDF before it keys a cipher. Every case of Wycheproof's X25519 file is tested ({wycheproof})"], - ["`p256`", "Key pairs made from a 32-byte scalar or drawn from `random_device`, and public keys validated once, as SEC 1's uncompressed point or two coordinates", "about 128 bits ({sec2})", "secret 32 bytes (the scalar); public 65 bytes uncompressed ({sec1})", "none yet: ECDSA comes next", "{speed:p256}", "{constant_time:p256}", "{fips186-5}, {sec2}, {sec1}", "passkeys' ES256 ({webauthn}), TLS 1.3 ({rfc8446-groups})", "yes: P-256, for ECDSA and ECDH ({webcrypto})", "Browsers' WebCrypto, whose raw export of a P-256 public key is the uncompressed point `public_key::make` takes ({webcrypto}); passkeys and TLS. Not Bitcoin, Ethereum or Nostr, whose keys are secp256k1's"] + ["`p256`", "Key pairs made from a 32-byte scalar or drawn from `random_device`, public keys validated once, as SEC 1's uncompressed point or two coordinates, and ECDSA over a SHA-256 digest with RFC 6979's nonce, raw and DER, and low S checked or normalized", "about 128 bits ({sec2})", "secret 32 bytes (the scalar); public 65 bytes uncompressed ({sec1})", "ECDSA: 64 bytes, r and s ({ieee1363}); in DER up to 72 ({rfc3279})", "{speed:p256}", "{constant_time:p256}", "{fips186-5}, {sec2}, {sec1}, {rfc6979}", "passkeys' ES256 ({webauthn}), TLS 1.3 ({rfc8446-groups})", "yes: P-256, for ECDSA and ECDH ({webcrypto})", "Browsers' WebCrypto, whose raw export of a P-256 public key is the uncompressed point `public_key::make` takes ({webcrypto}); passkeys and TLS. Not Bitcoin, Ethereum or Nostr, whose keys are secp256k1's"] ] }, "hybrid": { @@ -1131,7 +1151,8 @@ {"need": "Send messages between two people who know each other's public keys, as NaCl's and libsodium's crypto_box", "namespace": "webcpp::crypto::hybrid", "api": "`box::make`, `box::seal`, `box::open`", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//box_xsalsa20poly1305-default", "example": "box_messages", "section": "crypto-box"}, {"need": "Let anyone send a message that only the recipient can read, without saying who sent it (anonymous feedback, a drop box)", "namespace": "webcpp::crypto::hybrid", "api": "`sealed_box::seal`, `sealed_box::open`", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//sealed_box-default", "example": "file_share", "section": "crypto-sealed-box"}, {"need": "Share a file with someone known only by a public key, as a file-sharing app does", "namespace": "webcpp::crypto", "api": "`ciphers::secretbox<>` for the file under a key drawn for it, `hybrid::sealed_box::seal` for that key", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//secretbox_xsalsa20poly1305-default /webcpp/crypto//sealed_box-default /webcpp/crypto//x25519-default", "example": "file_share", "section": "crypto-everyday-files"}, - {"need": "Signatures and key agreement a browser's WebCrypto verifies and derives (P-256 with SHA-256), webcpp::trystero's handshakes", "namespace": "webcpp::crypto::curves::p256", "api": "`keypair::make`, `keypair::generate`, `keypair::public_key`, `keypair::secret_scalar`, `public_key::make`", "backend": "BearSSL", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//p256-default", "example": "p256_keys", "section": "crypto-p256-keys"} + {"need": "Make and keep a P-256 key pair, and import a browser's public key (WebCrypto's raw form), as webcpp::trystero's peers do", "namespace": "webcpp::crypto::curves::p256", "api": "`keypair::make`, `keypair::generate`, `keypair::public_key`, `keypair::secret_scalar`, `public_key::make`", "backend": "BearSSL", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//p256-default", "example": "p256_keys", "section": "crypto-p256-keys"}, + {"need": "Sign what a browser's WebCrypto verifies and verify what it signs (ECDSA on P-256 with SHA-256), low S where a protocol requires it, as webcpp::trystero's handshakes", "namespace": "webcpp::crypto::curves::p256", "api": "`keypair::sign_ecdsa`, `verify_ecdsa`, `normalize_ecdsa`, `check_low_s`; `to_der`, `from_der` for X.509", "backend": "BearSSL", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//p256-default", "example": "p256_sign", "section": "crypto-p256-ecdsa"} ], "fixtures": { "web": "A web application: AES-256-GCM on BearSSL, the default on WebAssembly.", diff --git a/example/Jamfile b/example/Jamfile index 661895dd..98a085a4 100644 --- a/example/Jamfile +++ b/example/Jamfile @@ -119,6 +119,9 @@ webcpp.example ed25519_sign.cpp : /webcpp/crypto//ed25519-default ; # public key exported and imported as a peer's, a tampered point refused, and a # key pair drawn from the system's generator. webcpp.example p256_keys.cpp : /webcpp/crypto//p256-default ; +# The guide's P-256 ECDSA program: RFC 6979's signature of "sample", its low-S +# form and its DER, both forms verified and another digest refused. +webcpp.example p256_sign.cpp : /webcpp/crypto//p256-default ; # The guide's X25519 program: RFC 7748's Alice and Bob, the agreement of two # Ed25519 key pairs through their X25519 forms, and a peer of low order diff --git a/example/p256_sign.cpp b/example/p256_sign.cpp new file mode 100644 index 00000000..48dcbaf2 --- /dev/null +++ b/example/p256_sign.cpp @@ -0,0 +1,105 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Signs the SHA-256 digest of "sample" with RFC 6979's P-256 key and prints the signature, the +// RFC's own bytes, in the raw form WebCrypto uses; then its low-S form, which a protocol that +// requires low S sends, and its DER encoding, which X.509 carries; and verifies both forms with +// the public key alone, and refuses the digest of another message. +// tag::program[] +#include + +#include + +#include +#include +#include +#include +#include +#include + +namespace p256 = webcpp::crypto::curves::p256; + +namespace { + +// Prints bytes in hex after a name, 32 bytes (64 digits) to a line, the lines after the first +// indented under the first, so that a long value stays readable on a narrow page. +void print(char const* name, std::span bytes) { + int const indent = std::printf("%s ", name); + for (std::size_t i = 0; i < bytes.size(); ++i) { + if (i != 0 && i % 32 == 0) { + std::printf("\n%*s", indent, ""); + } + std::printf("%02x", bytes[i]); + } + std::printf("\n"); +} + +// What is signed is a SHA-256 digest, as WebCrypto's ECDSA with SHA-256 hashes the message. +std::array digest_of(std::string_view text) { + std::array digest{}; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): a text's bytes + auto const* const bytes = reinterpret_cast(text.data()); + std::span const message(bytes, text.size()); + if (!webcpp::hash::digest_of(digest, message)) { + digest.fill(0); + } + return digest; +} + +} // namespace + +int main() { + // RFC 6979 section A.2.5's key: a published scalar, never a real key. + std::array const scalar{ + 0xc9, 0xaf, 0xa9, 0xd8, 0x45, 0xba, 0x75, 0x16, 0x6b, 0x5c, 0x21, + 0x57, 0x67, 0xb1, 0xd6, 0x93, 0x4e, 0x50, 0xc3, 0xdb, 0x36, 0xe8, + 0x9b, 0x12, 0x7b, 0x8a, 0x62, 0x2b, 0x12, 0x0f, 0x67, 0x21, + }; + auto const key = p256::keypair::make(scalar); + auto const public_key = key ? key->public_key() : key.error(); + if (!public_key) { + std::printf("failed\n"); + return 1; + } + auto const digest = digest_of("sample"); + + // RFC 6979's nonce: no random number, the same signature for the same key and digest. + auto const signature = key->sign_ecdsa(digest); + if (!signature) { + std::printf("failed\n"); + return 1; + } + print("signature ", *signature); + + // This S is high: a protocol that requires low S sends the normalized form instead. + std::printf("low S %s\n", p256::check_low_s(*signature) ? "yes" : "no"); + auto const low = p256::normalize_ecdsa(*signature); + if (!low) { + std::printf("failed\n"); + return 1; + } + print("low-S form", *low); + + // DER, for X.509 and OpenSSL: at most max_der_size bytes, its length returned. + std::array der{}; + auto const length = p256::to_der(*low, der); + if (!length) { + std::printf("failed\n"); + return 1; + } + print("DER ", std::span(der).first(*length)); + + // The verifier holds the public key, the digest and the signature; nothing secret. + auto const decoded = p256::from_der(std::span(der).first(*length)); + bool const both = p256::verify_ecdsa(*signature, digest, *public_key) && decoded && + p256::verify_ecdsa(*decoded, digest, *public_key); + std::printf("verified %s\n", both ? "both forms" : "FAILED"); + auto const other = p256::verify_ecdsa(*signature, digest_of("test"), *public_key); + std::printf("other text %s\n", other ? "verified" : other.error().message().c_str()); + return 0; +} + +// end::program[] diff --git a/example/p256_sign.expected b/example/p256_sign.expected new file mode 100644 index 00000000..d23cb27f --- /dev/null +++ b/example/p256_sign.expected @@ -0,0 +1,10 @@ +signature efd48b2aacb6a8fd1140dd9cd45e81d69d2c877b56aaf991c34d0ea84eaf3716 + f7cb1c942d657c41d436c7a1b6e29f65f3e900dbb9aff4064dc4ab2f843acda8 +low S no +low-S form efd48b2aacb6a8fd1140dd9cd45e81d69d2c877b56aaf991c34d0ea84eaf3716 + 0834e36ad29a83bf2bc9385e491d6099c8fdf9d1ed67aa7ea5f51f93782857a9 +DER 3045022100efd48b2aacb6a8fd1140dd9cd45e81d69d2c877b56aaf991c34d0e + a84eaf371602200834e36ad29a83bf2bc9385e491d6099c8fdf9d1ed67aa7ea5 + f51f93782857a9 +verified both forms +other text the signature does not verify or is not a valid encoding diff --git a/include/webcpp/crypto/backends/bearssl.hpp b/include/webcpp/crypto/backends/bearssl.hpp index e3ab8e0d..c4ce614d 100644 --- a/include/webcpp/crypto/backends/bearssl.hpp +++ b/include/webcpp/crypto/backends/bearssl.hpp @@ -431,8 +431,9 @@ struct p_curve_state { }; /** - * P-256 on BearSSL: the point of a key pair computed once by `mulgen`, and a public point checked - * by BearSSL's decoding. BearSSL allocates nothing; its curve code never fails on a valid input. + * P-256 on BearSSL: the point of a key pair computed once by `mulgen`, a public point checked + * by BearSSL's decoding, ECDSA with RFC 6979's nonce and its DER conversions. BearSSL allocates + * nothing; its curve code never fails on a valid input. */ template <> struct p_curve_engine { @@ -478,6 +479,121 @@ struct p_curve_engine { std::ranges::equal(decoded, point); } + /** + * Signs a digest with ECDSA and RFC 6979's nonce, S as BearSSL computes it (design D36). + * + * @param keyed A keyed state. + * @param digest The 32-byte SHA-256 digest. + * @param output 64 bytes, r then s. + * @return Nothing; `backend_failure`, which a valid key cannot cause. + */ + [[nodiscard]] static boost::system::result sign( + state const& keyed, std::span digest, + std::span output) noexcept { + WEBCPP_CRYPTO_DETAIL_P_CURVE_ENGINE_ENTERED(); + read_canary(WEBCPP_CRYPTO_DETAIL_BEARSSL_CANARY); + // BearSSL's struct is not const-correct: it only reads the scalar. + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast): see above + auto* const scalar = const_cast(keyed.scalar.data()); + br_ec_private_key const key{ + .curve = BR_EC_secp256r1, + .x = scalar, + .xlen = keyed.scalar.size(), + }; + // RFC 6979's nonce, from HMAC-DRBG over SHA-256: br_sha256_vtable is the hash of the + // nonce's derivation, which RFC 6979 makes the digest's own. No random number is drawn. + if (br_ecdsa_i31_sign_raw(bearssl_p256(), &br_sha256_vtable, digest.data(), &key, + output.data()) != output.size()) { + return error::backend_failure; + } + return {}; + } + + /** + * Verifies an ECDSA signature; a high S is accepted (design D36). + * + * @param point The public key's uncompressed point, valid. + * @param digest The 32-byte SHA-256 digest. + * @param signature 64 bytes, r then s, each in range (the family's header has checked them). + * @return Whether the signature verifies. + */ + [[nodiscard]] static bool verify(std::span point, + std::span digest, + std::span signature) noexcept { + WEBCPP_CRYPTO_DETAIL_P_CURVE_ENGINE_ENTERED(); + read_canary(WEBCPP_CRYPTO_DETAIL_BEARSSL_CANARY); + // BearSSL's struct holds a pointer to non-const bytes, which it only reads: a copy keeps + // the key's own bytes const without a cast. + std::array key_point{}; + std::ranges::copy(point, key_point.begin()); + br_ec_public_key const key{ + .curve = BR_EC_secp256r1, + .q = key_point.data(), + .qlen = key_point.size(), + }; + return br_ecdsa_i31_vrfy_raw(bearssl_p256(), digest.data(), digest.size(), &key, + signature.data(), signature.size()) == 1; + } + + /** + * Encodes a signature as strict DER. + * + * @param signature 64 bytes, r then s, each in range (the family's header has checked them). + * @param output 72 bytes, room for the longest encoding. + * @return The encoding's length, at most 72: 2 + 2 * (2 + 33). + */ + [[nodiscard]] static std::size_t to_der(std::span signature, + std::span output) noexcept { + WEBCPP_CRYPTO_DETAIL_P_CURVE_ENGINE_ENTERED(); + read_canary(WEBCPP_CRYPTO_DETAIL_BEARSSL_CANARY); + // In place, and "by no more than 9 bytes" larger (bearssl_ec.h): room for 64 + 9. + std::array work{}; + std::ranges::copy(signature, work.begin()); + std::size_t const length = br_ecdsa_raw_to_asn1(work.data(), signature.size()); + std::ranges::copy(std::span(work).first(length), output.begin()); + return length; + } + + /** + * Decodes a strict DER signature: BearSSL's decoder, then the re-encoding compared with the + * input, since BearSSL accepts a few forms strict DER refuses. + * + * @param der The encoding, not empty. + * @param output 64 bytes, r then s, padded to 32 bytes each; the caller keeps them only on + * success and checks their range. + * @return Whether the input is strict DER of two integers of at most 32 bytes. + */ + [[nodiscard]] static bool from_der(std::span der, + std::span output) noexcept { + WEBCPP_CRYPTO_DETAIL_P_CURVE_ENGINE_ENTERED(); + read_canary(WEBCPP_CRYPTO_DETAIL_BEARSSL_CANARY); + constexpr std::size_t longest = 72; + if (der.size() > longest) { + return false; + } + // In place, and up to twice the source's length (bearssl_ec.h): room for 2 * 72. + std::array work{}; + std::ranges::copy(der, work.begin()); + // BearSSL strips the integers' leading zeros and writes r and s at the longer one's + // length (ecdsa_atr.c), so a raw form shorter than 64 bytes is padded back to 32 each. + std::size_t const raw_size = br_ecdsa_asn1_to_raw(work.data(), der.size()); + std::size_t const half = raw_size / 2; + if (raw_size == 0 || half > 32) { + return false; + } + std::array raw{}; + std::ranges::copy(std::span(work).first(half), + raw.begin() + (32 - half)); + std::ranges::copy(std::span(work).subspan(half, half), + raw.begin() + (64 - half)); + std::ranges::copy(std::span(raw).first<64>(), output.begin()); + // BearSSL's decoder accepts a long SEQUENCE length, needless zero bytes and a negative + // integer; strict DER is what re-encodes to the same bytes (design D12). + std::size_t const length = br_ecdsa_raw_to_asn1(raw.data(), 64); + return length == der.size() && + std::ranges::equal(std::span(raw).first(length), der); + } + /** * Copies the public point; no BearSSL call. * diff --git a/include/webcpp/crypto/curves/p256.hpp b/include/webcpp/crypto/curves/p256.hpp index a8703b19..f81423f8 100644 --- a/include/webcpp/crypto/curves/p256.hpp +++ b/include/webcpp/crypto/curves/p256.hpp @@ -6,7 +6,9 @@ /** P-256, NIST's curve of FIPS 186-5 (secp256r1): a key pair made from its 32-byte scalar or drawn - from the system's generator, and a public key validated once, as SEC 1's uncompressed point. + from the system's generator, and a public key validated once, as SEC 1's uncompressed point; + ECDSA over a SHA-256 digest with RFC 6979's nonce, its raw and DER forms, and low S as two + functions, one that normalizes and one that checks. The family's default backend, BearSSL on every target, is included when the program links it; a program that uses the family without linking it stops where it calls it, with the Jamfile @@ -278,6 +280,30 @@ class basic_keypair { return scalar; } + /** + * Signs a SHA-256 digest with ECDSA, RFC 6979's deterministic nonce (no random number is + * drawn: the same key and digest give the same signature), S as the computation gives it, + * high or low (`normalize_ecdsa` gives the low form). + * + * @param digest The 32-byte SHA-256 digest of the message, as WebCrypto's ECDSA with SHA-256 + * hashes it. + * @return 64 bytes, r then s (IEEE P1363, WebCrypto's form); `invalid_state` moved from; + * `backend_failure`, which a valid key pair cannot cause. + */ + [[nodiscard]] boost::system::result> sign_ecdsa( + std::span digest) const noexcept { + detail::timing_guard const timing; + if (!keyed_) { + return error::invalid_state; + } + std::array signature{}; + auto const signed_digest = engine::sign(state_, digest, signature); + if (!signed_digest) { + return signed_digest.error(); + } + return signature; + } + private: basic_keypair() noexcept = default; @@ -288,6 +314,132 @@ class basic_keypair { /** The key pair on the default backend. */ using keypair = basic_keypair<>; +/** + * Verifies an ECDSA signature of a SHA-256 digest with a public key. A high S and a low S are both + * accepted, as FIPS 186-5 and WebCrypto accept them; a protocol that requires low S calls + * `check_low_s` too. + * + * @tparam Backend The key's backend, which verifies. + * @param signature 64 bytes, r then s (IEEE P1363, WebCrypto's form); `from_der` reads DER. + * @param digest The 32-byte SHA-256 digest of the message. + * @param key The signer's public key. + * @return Nothing; `invalid_signature` for an r or an s that is 0 or not below n, refused before + * the backend, and for a signature that does not verify. A digest whose value modulo n is 0 (32 + * zero bytes, or n itself), which no SHA-256 of a message gives in practice, is refused too: + * BearSSL's verification refuses a zero multiplier. + */ +template +[[nodiscard]] boost::system::result verify_ecdsa( + std::span signature, + std::span digest, + basic_public_key const& key) noexcept { + detail::timing_guard const timing; + using engine = detail::p_curve_engine; + if (!detail::p_curve_signature_in_range(signature)) { + return error::invalid_signature; + } + if (!engine::verify(detail::p_curve_access::point(key), digest, signature)) { + return error::invalid_signature; + } + return {}; +} + +/** + * Encodes a signature as strict DER, the ECDSA-Sig-Value SEQUENCE of two INTEGERs that X.509 + * and OpenSSL carry. + * + * @tparam Backend The backend that encodes; by default the family's. + * @param signature 64 bytes, r then s. + * @param output At least `max_der_size` bytes, whatever this signature's length; nothing is + * written on an error. + * @return The number of bytes written, 8 to `max_der_size`; `invalid_input_size` when `output` + * is shorter than `max_der_size`; `invalid_signature` when r or s is 0 or not below n. + */ +template > +[[nodiscard]] boost::system::result to_der( + std::span signature, + std::span output) noexcept { + detail::timing_guard const timing; + using engine = detail::p_curve_engine; + if (output.size() < max_der_size) { + return error::invalid_input_size; + } + if (!detail::p_curve_signature_in_range(signature)) { + return error::invalid_signature; + } + std::array der{}; + std::size_t const length = engine::to_der(signature, der); + std::ranges::copy(std::span(der).first(length), output.begin()); + return length; +} + +/** + * Decodes a strict DER signature to its raw form: only the encoding `to_der` writes is accepted. + * + * @tparam Backend The backend that decodes; by default the family's. + * @param der_signature The encoding, exactly: nothing may follow it. + * @return 64 bytes, r then s; `invalid_signature` for anything that is not strict DER (a needless + * zero byte, a long length where a short one holds it, a negative integer, bytes after it, + * nothing), and for an r or an s that is 0 or not below n. + */ +template > +[[nodiscard]] boost::system::result> from_der( + std::span der_signature) noexcept { + detail::timing_guard const timing; + using engine = detail::p_curve_engine; + if (der_signature.empty()) { + return error::invalid_signature; + } + std::array signature{}; + if (!engine::from_der(der_signature, signature) || + !detail::p_curve_signature_in_range(signature)) { + return error::invalid_signature; + } + return signature; +} + +/** + * The low-S form of a signature: s replaced by n - s when s is above (n - 1) / 2, returned + * unchanged otherwise. Both forms verify; a protocol that requires low S normalizes what it + * signs. Arithmetic on public bytes, with no backend. + * + * @param signature 64 bytes, r then s. + * @return 64 bytes, r then s, with s at most (n - 1) / 2; `invalid_signature` when r or s is 0 or + * not below n. + */ +[[nodiscard]] inline boost::system::result> +normalize_ecdsa(std::span signature) noexcept { + if (!detail::p_curve_signature_in_range(signature)) { + return error::invalid_signature; + } + std::array normalized{}; + std::ranges::copy(signature, normalized.begin()); + auto const s = signature.last(); + if (!detail::p_curve_low_s(s)) { + detail::p_curve_negate_scalar( + s, std::span(normalized).last()); + } + return normalized; +} + +/** + * Checks that a signature is in its low-S form, s at most (n - 1) / 2, as a protocol that + * requires low S checks what it receives. Arithmetic on public bytes, with no backend; it does + * not verify the signature (`verify_ecdsa` does). + * + * @param signature 64 bytes, r then s. + * @return Nothing; `invalid_signature` when s is above (n - 1) / 2, and when r or s is 0 or not + * below n. + */ +[[nodiscard]] inline boost::system::result check_low_s( + std::span signature) noexcept { + if (!detail::p_curve_signature_in_range(signature) || + !detail::p_curve_low_s(signature.last())) { + return error::invalid_signature; + } + return {}; +} + } // namespace webcpp::crypto::curves::p256 namespace webcpp::crypto::detail { @@ -314,6 +466,30 @@ struct p_curve_engine { return false; } + /** Never called; fails closed. */ + template + [[nodiscard]] static boost::system::result sign(Arguments&&... /*arguments*/) noexcept { + return error::backend_failure; + } + + /** Never called; fails closed. */ + template + [[nodiscard]] static bool verify(Arguments&&... /*arguments*/) noexcept { + return false; + } + + /** Never called; fails closed: nothing written. */ + template + [[nodiscard]] static std::size_t to_der(Arguments&&... /*arguments*/) noexcept { + return 0; + } + + /** Never called; fails closed. */ + template + [[nodiscard]] static bool from_der(Arguments&&... /*arguments*/) noexcept { + return false; + } + /** Never called. */ template static void public_point(Arguments&&... /*arguments*/) noexcept {} diff --git a/include/webcpp/crypto/detail/p_curves.hpp b/include/webcpp/crypto/detail/p_curves.hpp index 09a0e707..9f39ee1a 100644 --- a/include/webcpp/crypto/detail/p_curves.hpp +++ b/include/webcpp/crypto/detail/p_curves.hpp @@ -83,6 +83,66 @@ template return verdict != 0; } +/** + * Whether an ECDSA signature r || s has 0 < r < n and 0 < s < n, each checked by + * `p_curve_scalar_valid`: a signature is public, the same check serves. + * + * @tparam Curve The curve's family tag. + * @param signature r then s, big-endian, each of the curve's scalar size. + * @return Whether both are in range. + */ +template +[[nodiscard]] bool p_curve_signature_in_range( + std::span::scalar_size> signature) noexcept { + constexpr std::size_t size = p_curve_traits::scalar_size; + bool const r_valid = + p_curve_scalar_valid(signature.template first(), p_curve_traits::order); + bool const s_valid = + p_curve_scalar_valid(signature.template last(), p_curve_traits::order); + return r_valid && s_valid; +} + +/** + * Whether an ECDSA signature's s, already checked 0 < s < n, is low: s <= (n - 1) / 2, the borrow + * of (n - 1) / 2 - s over every byte, the same arithmetic as `p_curve_scalar_valid`'s. A + * signature is public: the verdict is not declassified, it was never secret. + * + * @tparam Curve The curve's family tag. + * @param s The signature's s, big-endian. + * @return Whether s is at most half the group order. + */ +template +[[nodiscard]] bool p_curve_low_s( + std::span::scalar_size> s) noexcept { + constexpr auto const& half = p_curve_traits::half_order; + unsigned borrow = 0; + for (std::size_t i = s.size(); i-- > 0;) { + borrow = ((static_cast(half[i]) - s[i] - borrow) >> 8U) & 1U; + } + return borrow == 0; +} + +/** + * n - s, the other s of the same signature, for an s already checked 0 < s < n, so that the + * result is in that range too: the borrow arithmetic of `p_curve_scalar_valid`, over every byte. + * + * @tparam Curve The curve's family tag. + * @param s The signature's s, big-endian. + * @param output n - s, big-endian; it may not overlap `s`. + */ +template +void p_curve_negate_scalar( + std::span::scalar_size> s, + std::span::scalar_size> output) noexcept { + constexpr auto const& order = p_curve_traits::order; + unsigned borrow = 0; + for (std::size_t i = s.size(); i-- > 0;) { + unsigned const difference = static_cast(order[i]) - s[i] - borrow; + output[i] = static_cast(difference); + borrow = (difference >> 8U) & 1U; + } +} + /** * What a P-curve key pair stores on a backend whose header does not specialise it: nothing, since * its engine refuses the backend where the family is called. diff --git a/test/Jamfile b/test/Jamfile index 4a0fca03..bf80280c 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -377,6 +377,14 @@ crypto-run default_both_wasm : default_both_wasm_test.cpp # optimised, every call inlined, as ed25519_wipe_sodium's. crypto-run p256_keys_bearssl : p256_keys_bearssl_test.cpp : /third_party//bearssl $(OPTIMISED) full ; +# P-256 ECDSA on BearSSL: RFC 6979's signatures, verification of both forms +# and its refusals, low S checked and normalized, DER both ways and its strict +# decoder. +crypto-run p256_ecdsa_bearssl : p256_ecdsa_bearssl_test.cpp : /third_party//bearssl ; +# Wycheproof's P-256 SHA-256 ECDSA vectors, raw (IEEE P1363) and DER. +crypto-run p256_wycheproof_bearssl : p256_wycheproof_bearssl_test.cpp + : /third_party//bearssl /third_party//wycheproof + /webcpp//boost_json ; # The backend ctaes: the AES block cipher alone, on every target; FIPS-197 only # (ruling R5). crypto-run aes_ctaes : aes_ctaes_test.cpp : /third_party//ctaes ; diff --git a/test/allocation_bearssl_test.cpp b/test/allocation_bearssl_test.cpp index 1db6f073..540f151a 100644 --- a/test/allocation_bearssl_test.cpp +++ b/test/allocation_bearssl_test.cpp @@ -6,8 +6,9 @@ // On BearSSL nothing allocates (spec section 3.2): make, seal, open, the incremental seal, // equal and random_device's fill, ChaCha20-Poly1305's make, seal, open (good and failed) -// and move, and P-256's key pair make and generate and public key make (of a point and of -// coordinates) make no call of operator new, nor of the C library's +// and move, and P-256's key pair make and generate, public key make (of a point and of +// coordinates), sign_ecdsa, verify_ecdsa, to_der, from_der, normalize_ecdsa and check_low_s +// make no call of operator new, nor of the C library's // allocator where the target lets a program count it; a control proves the counter moves. #include @@ -31,6 +32,43 @@ #include #include +namespace { + +// P-256's functions, each called once: the key pair's make and generate, the public key's two +// make, and ECDSA's six. +void p256_calls() { + namespace crypto = webcpp::crypto; + namespace p256 = crypto::curves::p256; + namespace data = webcpp::test::p256; + using keypair = p256::basic_keypair; + using public_key = p256::basic_public_key; + auto const pair = keypair::make(data::rfc6979_scalar); + BOOST_TEST(keypair::generate().has_value()); + std::span const point(data::rfc6979_public); + BOOST_TEST(public_key::make(point).has_value()); + BOOST_TEST(public_key::make(point.subspan<1, 32>(), point.subspan<33, 32>()).has_value()); + std::array digest{}; + digest.fill(0x5a); + if (!BOOST_TEST(pair.has_value())) { + return; + } + auto const signature = pair->sign_ecdsa(digest); + auto const key = public_key::make(point); + if (!BOOST_TEST(signature.has_value()) || !BOOST_TEST(key.has_value())) { + return; + } + BOOST_TEST(p256::verify_ecdsa(*signature, digest, *key).has_value()); + std::array der{}; + auto const written = p256::to_der(*signature, der); + if (BOOST_TEST(written.has_value())) { + BOOST_TEST(p256::from_der(std::span(der).first(*written)).has_value()); + } + BOOST_TEST(p256::normalize_ecdsa(*signature).has_value()); + BOOST_TEST(p256::check_low_s(data::rfc6979_test).has_value()); +} + +} // namespace + int main() { namespace crypto = webcpp::crypto; // The control: a malloc of the C library's moves the counter where it is counted. @@ -71,16 +109,7 @@ int main() { BOOST_TEST(sealer->open(iv, iv, data, forged).error() == crypto::error::authentication_failed); chacha const moved = std::move(*sealer); - namespace p256 = crypto::curves::p256; - namespace data = webcpp::test::p256; - using keypair = p256::basic_keypair; - using public_key = p256::basic_public_key; - auto const pair = keypair::make(data::rfc6979_scalar); - BOOST_TEST(pair.has_value()); - BOOST_TEST(keypair::generate().has_value()); - std::span const point(data::rfc6979_public); - BOOST_TEST(public_key::make(point).has_value()); - BOOST_TEST(public_key::make(point.subspan<1, 32>(), point.subspan<33, 32>()).has_value()); + p256_calls(); } BOOST_TEST_EQ(webcpp::test::allocations(), before); return webcpp::test::exit_status(boost::report_errors()); diff --git a/test/p256_ecdsa_bearssl_test.cpp b/test/p256_ecdsa_bearssl_test.cpp new file mode 100644 index 00000000..9db92286 --- /dev/null +++ b/test/p256_ecdsa_bearssl_test.cpp @@ -0,0 +1,348 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the 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 ECDSA on BearSSL: RFC 6979's two SHA-256 signatures byte for byte, the same on every +// signing; verification of both forms of a signature and every refusal (a bit of the digest, of +// r or of s, another key, r or s 0 or n), and the digests 0 modulo n that BearSSL refuses; low S, +// checked and normalized, at its boundary and over 1,000 signatures of random digests; DER both +// ways against encodings written by hand, the short buffer, the strict decoder's refusals and +// integers shorter than 32 bytes. + +#include +#include +#include +#include +#include + +#include "support/p256_data.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace crypto = webcpp::crypto; +namespace p256 = webcpp::crypto::curves::p256; +namespace data = webcpp::test::p256; + +using crypto::error; +using p256::keypair; +using p256::public_key; +using bytes = std::vector; +using signature = std::array; +using digest = std::array; + +// The SHA-256 of a text, with webcpp::hash. +digest sha256(std::string_view text) { + digest out{}; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): the text's bytes + auto const* const bytes = reinterpret_cast(text.data()); + std::span const input(bytes, text.size()); + BOOST_TEST(webcpp::hash::digest_of(out, input).has_value()); + return out; +} + +// r and s of a signature, put together. +signature joined(std::span r, std::span s) { + signature out{}; + std::ranges::copy(r, out.begin()); + std::ranges::copy(s, out.begin() + 32); + return out; +} + +std::span r_of(signature const& value) { + return std::span(value).first<32>(); +} + +std::span s_of(signature const& value) { + return std::span(value).last<32>(); +} + +// Bytes put together, as a DER is written by hand: its headers and its integers. +bytes concat(std::initializer_list> parts) { + bytes out; + for (auto const part : parts) { + out.insert(out.end(), part.begin(), part.end()); + } + return out; +} + +bytes header(std::initializer_list values) { + return values; +} + +void rfc6979_signatures() { + auto const key = keypair::make(data::rfc6979_scalar); + if (!BOOST_TEST(key.has_value())) { + return; + } + auto const sample = key->sign_ecdsa(sha256("sample")); + auto const test = key->sign_ecdsa(sha256("test")); + if (BOOST_TEST(sample.has_value()) && BOOST_TEST(test.has_value())) { + BOOST_TEST(*sample == data::rfc6979_sample); + BOOST_TEST(*test == data::rfc6979_test); + } + auto const again = key->sign_ecdsa(sha256("sample")); + if (BOOST_TEST(again.has_value()) && sample.has_value()) { + BOOST_TEST(*again == *sample); + } +} + +void verify_both_forms() { + auto const key = public_key::make(data::rfc6979_public); + if (!BOOST_TEST(key.has_value())) { + return; + } + auto const sample = sha256("sample"); + auto const test = sha256("test"); + BOOST_TEST(p256::verify_ecdsa(data::rfc6979_sample, sample, *key).has_value()); + BOOST_TEST(p256::verify_ecdsa(data::rfc6979_sample_low_s, sample, *key).has_value()); + BOOST_TEST(p256::verify_ecdsa(data::rfc6979_test, test, *key).has_value()); + + auto const refused = [&key](signature const& value, digest const& hash) { + return p256::verify_ecdsa(value, hash, *key).error() == error::invalid_signature; + }; + BOOST_TEST(refused(data::rfc6979_test, sample)); + auto flipped_digest = test; + flipped_digest[7] ^= 0x10U; + BOOST_TEST(refused(data::rfc6979_test, flipped_digest)); + auto flipped_r = data::rfc6979_test; + flipped_r[3] ^= 0x01U; + BOOST_TEST(refused(flipped_r, test)); + auto flipped_s = data::rfc6979_test; + flipped_s[60] ^= 0x80U; + BOOST_TEST(refused(flipped_s, test)); + + auto const other = keypair::generate(); + if (BOOST_TEST(other.has_value())) { + auto const other_key = other->public_key(); + if (BOOST_TEST(other_key.has_value())) { + BOOST_TEST(p256::verify_ecdsa(data::rfc6979_test, test, *other_key).error() == + error::invalid_signature); + } + } + + std::array const zero{}; + BOOST_TEST(refused(joined(zero, s_of(data::rfc6979_test)), test)); + BOOST_TEST(refused(joined(r_of(data::rfc6979_test), zero), test)); + BOOST_TEST(refused(joined(data::order, s_of(data::rfc6979_test)), test)); + BOOST_TEST(refused(joined(r_of(data::rfc6979_test), data::order), test)); +} + +// A digest that is 0 modulo n (32 zero bytes, or n) signs, and BearSSL's verification refuses +// it, since it refuses a zero multiplier (bearssl_ec.h, muladd): verify_ecdsa's documented limit, +// pinned here so that a BearSSL that changes it is noticed. No SHA-256 of a message gives either. +void zero_digest() { + auto const key = keypair::make(data::rfc6979_scalar); + auto const verifier = public_key::make(data::rfc6979_public); + if (!BOOST_TEST(key.has_value()) || !BOOST_TEST(verifier.has_value())) { + return; + } + for (digest const& hash : {digest{}, data::order}) { + auto const signed_hash = key->sign_ecdsa(hash); + if (BOOST_TEST(signed_hash.has_value())) { + BOOST_TEST(p256::verify_ecdsa(*signed_hash, hash, *verifier).error() == + error::invalid_signature); + } + } +} + +void low_s() { + BOOST_TEST(p256::check_low_s(data::rfc6979_sample).error() == error::invalid_signature); + BOOST_TEST(p256::check_low_s(data::rfc6979_sample_low_s).has_value()); + BOOST_TEST(p256::check_low_s(data::rfc6979_test).has_value()); + auto const normalized = p256::normalize_ecdsa(data::rfc6979_sample); + if (BOOST_TEST(normalized.has_value())) { + BOOST_TEST(*normalized == data::rfc6979_sample_low_s); + } + auto const unchanged = p256::normalize_ecdsa(data::rfc6979_test); + if (BOOST_TEST(unchanged.has_value())) { + BOOST_TEST(*unchanged == data::rfc6979_test); + } + + // The boundary: (n - 1) / 2 is low, one more is high and normalizes to (n - 1) / 2. + auto const r = r_of(data::rfc6979_sample); + auto const half = joined(r, data::half_order); + auto above_half = data::half_order; + ++above_half.back(); // ends with a8: no carry + BOOST_TEST(p256::check_low_s(half).has_value()); + BOOST_TEST(p256::check_low_s(joined(r, above_half)).error() == error::invalid_signature); + auto const lowered = p256::normalize_ecdsa(joined(r, above_half)); + if (BOOST_TEST(lowered.has_value())) { + BOOST_TEST(*lowered == half); + } + + std::array const zero{}; + auto const s = s_of(data::rfc6979_test); + for (auto const& out_of_range : + {joined(zero, s), joined(r, zero), joined(data::order, s), joined(r, data::order)}) { + BOOST_TEST(p256::normalize_ecdsa(out_of_range).error() == error::invalid_signature); + BOOST_TEST(p256::check_low_s(out_of_range).error() == error::invalid_signature); + } +} + +void low_s_random() { + auto const key = keypair::generate(); + if (!BOOST_TEST(key.has_value())) { + return; + } + auto const verifier = key->public_key(); + if (!BOOST_TEST(verifier.has_value())) { + return; + } + std::uint64_t const seed = std::random_device{}(); + std::cout << "low_s_random: seed " << seed << '\n'; + std::mt19937_64 generator(seed); + int high = 0; + for (int i = 0; i < 1000; ++i) { + digest hash{}; + std::ranges::generate(hash, + [&generator] { return static_cast(generator()); }); + auto const signed_hash = key->sign_ecdsa(hash); + if (!BOOST_TEST(signed_hash.has_value())) { + return; + } + BOOST_TEST(p256::verify_ecdsa(*signed_hash, hash, *verifier).has_value()); + if (!p256::check_low_s(*signed_hash)) { + ++high; + } + auto const normalized = p256::normalize_ecdsa(*signed_hash); + if (!BOOST_TEST(normalized.has_value())) { + return; + } + BOOST_TEST(p256::check_low_s(*normalized).has_value()); + BOOST_TEST(p256::verify_ecdsa(*normalized, hash, *verifier).has_value()); + } + std::cout << "low_s_random: " << high << " of 1000 had a high S\n"; + BOOST_TEST_GE(high, 400); + BOOST_TEST_LE(high, 600); +} + +void der_round_trip() { + auto const r = r_of(data::rfc6979_sample); + // The RFC's form: r and s both have their high bit set, so each takes a zero byte. + bytes const rfc_der = concat({ + header({0x30, 0x46, 0x02, 0x21, 0x00}), + r, + header({0x02, 0x21, 0x00}), + s_of(data::rfc6979_sample), + }); + // The low-S form: s starts with 08, its integer has no zero byte. + bytes const low_der = concat({ + header({0x30, 0x45, 0x02, 0x21, 0x00}), + r, + header({0x02, 0x20}), + s_of(data::rfc6979_sample_low_s), + }); + for (auto const& [value, expected] : { + std::pair{data::rfc6979_sample, rfc_der}, + std::pair{data::rfc6979_sample_low_s, low_der}, + }) { + std::array output{}; + auto const written = p256::to_der(value, output); + if (!BOOST_TEST(written.has_value())) { + continue; + } + BOOST_TEST_EQ(*written, expected.size()); + BOOST_TEST(std::ranges::equal(std::span(output).first(*written), expected)); + auto const decoded = p256::from_der(expected); + if (BOOST_TEST(decoded.has_value())) { + BOOST_TEST(*decoded == value); + } + } + BOOST_TEST_EQ(rfc_der.size(), 72U); + BOOST_TEST_EQ(low_der.size(), 71U); + + // A buffer shorter than max_der_size is refused whatever the signature's length, untouched. + for (std::size_t const size : {std::size_t{71}, std::size_t{70}}) { + bytes buffer(size, 0xa5); + BOOST_TEST(p256::to_der(data::rfc6979_sample_low_s, buffer).error() == + error::invalid_input_size); + BOOST_TEST(std::ranges::all_of(buffer, [](std::uint8_t byte) { return byte == 0xa5; })); + } + + std::array const zero{}; + std::array output{}; + BOOST_TEST(p256::to_der(joined(zero, s_of(data::rfc6979_test)), output).error() == + error::invalid_signature); + BOOST_TEST(p256::to_der(joined(r, data::order), output).error() == error::invalid_signature); +} + +void der_strict() { + // r and s both 08 34 ..., the low-S form's s: their high bit is clear, no zero byte needed. + auto const low = s_of(data::rfc6979_sample_low_s); + auto const high = r_of(data::rfc6979_sample); + bytes const strict = concat({header({0x30, 0x44, 0x02, 0x20}), low, header({0x02, 0x20}), low}); + BOOST_TEST(p256::from_der(strict).has_value()); + + auto const refused = [](bytes const& der) { + auto const decoded = p256::from_der(der); + return !decoded.has_value() && decoded.error() == error::invalid_signature; + }; + // A needless leading zero in r. + BOOST_TEST( + refused(concat({header({0x30, 0x45, 0x02, 0x21, 0x00}), low, header({0x02, 0x20}), low}))); + // The SEQUENCE's length in the long form, where the short one holds it. + BOOST_TEST( + refused(concat({header({0x30, 0x81, 0x44, 0x02, 0x20}), low, header({0x02, 0x20}), low}))); + // Bytes after the SEQUENCE. + BOOST_TEST(refused(concat({strict, header({0x00})}))); + // A negative r: its high bit set, without the zero byte. + BOOST_TEST( + refused(concat({header({0x30, 0x44, 0x02, 0x20}), high, header({0x02, 0x20}), low}))); + // r = 0, and s = n. + BOOST_TEST(refused(concat({header({0x30, 0x25, 0x02, 0x01, 0x00, 0x02, 0x20}), low}))); + BOOST_TEST(refused( + concat({header({0x30, 0x45, 0x02, 0x20}), low, header({0x02, 0x21, 0x00}), data::order}))); + BOOST_TEST(refused({})); +} + +void der_short_integers() { + std::array one{}; + one.back() = 0x01; + std::array two{}; + two.back() = 0x02; + auto const low = s_of(data::rfc6979_sample_low_s); + bytes const both_short = header({0x30, 0x06, 0x02, 0x01, 0x01, 0x02, 0x01, 0x02}); + bytes const r_short = concat({header({0x30, 0x25, 0x02, 0x01, 0x01, 0x02, 0x20}), low}); + for (auto const& [value, expected] : + {std::pair{joined(one, two), both_short}, std::pair{joined(one, low), r_short}}) { + std::array output{}; + auto const written = p256::to_der(value, output); + if (BOOST_TEST(written.has_value())) { + BOOST_TEST(std::ranges::equal(std::span(output).first(*written), expected)); + } + auto const decoded = p256::from_der(expected); + if (BOOST_TEST(decoded.has_value())) { + BOOST_TEST(*decoded == value); + } + } +} + +} // namespace + +int main() { + rfc6979_signatures(); + verify_both_forms(); + zero_digest(); + low_s(); + low_s_random(); + der_round_trip(); + der_strict(); + der_short_integers(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/p256_keys_bearssl_test.cpp b/test/p256_keys_bearssl_test.cpp index 6c9baff3..2e6e0d83 100644 --- a/test/p256_keys_bearssl_test.cpp +++ b/test/p256_keys_bearssl_test.cpp @@ -228,6 +228,8 @@ void moved_from() { // is what is tested. BOOST_TEST(a.public_key().error() == error::invalid_state); BOOST_TEST(a.secret_scalar().error() == error::invalid_state); + BOOST_TEST(a.sign_ecdsa(std::array{}).error() == + error::invalid_state); // NOLINTEND(bugprone-use-after-move,clang-analyzer-cplusplus.Move) auto const point = b.public_key(); if (BOOST_TEST(point.has_value())) { diff --git a/test/p256_wycheproof_bearssl_test.cpp b/test/p256_wycheproof_bearssl_test.cpp new file mode 100644 index 00000000..fce57716 --- /dev/null +++ b/test/p256_wycheproof_bearssl_test.cpp @@ -0,0 +1,174 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// P-256 ECDSA on BearSSL against Wycheproof (spec 8.1): the SHA-256 vectors in the raw form, +// IEEE P1363's r || s, through verify_ecdsa, and in DER through from_der then verify_ecdsa. A +// valid case verifies, an invalid one is refused, and an acceptable one, which neither file has +// at its pinned commit, fails the test so that it is read. The valid cases whose S is high are +// counted: verify_ecdsa accepts both forms, as FIPS 186-5 and WebCrypto do (design D36). + +#include +#include +#include +#include +#include + +#include "support/hex.hpp" +#include "support/test_data.hpp" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace crypto = webcpp::crypto; +namespace p256 = webcpp::crypto::curves::p256; +namespace test = webcpp::test; +namespace json = boost::json; + +using signature = std::array; + +json::value load(std::string const& name) { + auto const text = test::read_file(WEBCPP_TEST_WYCHEPROOF "/testvectors_v1/" + name + ".json"); + boost::system::error_code ec; + auto value = json::parse(text, ec); + BOOST_TEST(!ec); + return value; +} + +std::string str(json::value const& v) { + return std::string(std::string_view(v.as_string())); +} + +// Reports a case that went wrong, by its file and its number. +void report(std::string const& name, json::value const& t, std::string_view what) { + std::string message = name; + message += " tcId "; + message += std::to_string(t.at("tcId").to_number()); + message += ": "; + message += what; + BOOST_ERROR(message.c_str()); +} + +std::array sha256(std::span message) { + std::array out{}; + BOOST_TEST(webcpp::hash::digest_of(out, message).has_value()); + return out; +} + +// Whether s is above (n - 1) / 2, the half order, compared byte by byte: public values. +bool high_s(signature const& value) { + static constexpr auto half = crypto::detail::p_curve_traits::half_order; + for (std::size_t i = 0; i < half.size(); ++i) { + if (value[32 + i] != half[i]) { + return value[32 + i] > half[i]; + } + } + return false; +} + +// The counts of one file. +struct counts { + /** Cases read. */ + int total = 0; + /** Valid cases verified. */ + int valid = 0; + /** Invalid cases refused. */ + int invalid = 0; + /** Valid cases whose S is high. */ + int valid_high_s = 0; +}; + +// One file's cases: `decode` turns a case's signature into the raw form, or refuses it; a valid +// case must decode and verify, an invalid one must be refused at either step. +template +counts run(std::string const& name, Decode decode) { + auto const doc = load(name); + counts seen; + for (auto const& group : doc.at("testGroups").as_array()) { + auto const point = test::from_hex(str(group.at("publicKey").at("uncompressed"))); + auto const key = p256::public_key::make(point); + if (!BOOST_TEST(key.has_value())) { + continue; + } + for (auto const& t : group.at("tests").as_array()) { + ++seen.total; + auto const message = test::from_hex(str(t.at("msg"))); + auto const hash = sha256(message); + auto const encoded = test::from_hex(str(t.at("sig"))); + auto const decoded = decode(encoded); + bool const verified = + decoded.has_value() && p256::verify_ecdsa(*decoded, hash, *key).has_value(); + auto const verdict = str(t.at("result")); + if (verdict == "valid") { + ++seen.valid; + if (!verified) { + report(name, t, "valid signature refused"); + } else if (high_s(*decoded)) { + ++seen.valid_high_s; + } + } else if (verdict == "invalid") { + ++seen.invalid; + if (verified) { + report(name, t, "invalid signature verified"); + } + } else { + // None at the pinned commit: a new one is read before it is classified. + report(name, t, verdict + ", not expected"); + } + } + } + std::cout << name << ": tests=" << seen.total << " valid_verified=" << seen.valid + << " invalid_refused=" << seen.invalid << " valid_high_s=" << seen.valid_high_s + << '\n'; + return seen; +} + +void p1363() { + // A signature of another size than 64 bytes is refused before verify_ecdsa, which takes 64. + auto const seen = + run("ecdsa_secp256r1_sha256_p1363_test", + [](std::vector const& encoded) -> boost::system::result { + if (encoded.size() != p256::signature_size) { + return crypto::error::invalid_signature; + } + signature value{}; + std::ranges::copy(encoded, value.begin()); + return value; + }); + BOOST_TEST_EQ(seen.total, 262); + BOOST_TEST_EQ(seen.valid, 173); + BOOST_TEST_EQ(seen.invalid, 89); + BOOST_TEST_EQ(seen.valid_high_s, 70); +} + +void der() { + auto const seen = + run("ecdsa_secp256r1_sha256_test", + [](std::vector const& encoded) { return p256::from_der(encoded); }); + BOOST_TEST_EQ(seen.total, 484); + BOOST_TEST_EQ(seen.valid, 174); + BOOST_TEST_EQ(seen.invalid, 310); + BOOST_TEST_EQ(seen.valid_high_s, 71); +} + +} // namespace + +int main() { + p1363(); + der(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/support/p256_data.hpp b/test/support/p256_data.hpp index 51ac8054..428366a3 100644 --- a/test/support/p256_data.hpp +++ b/test/support/p256_data.hpp @@ -4,8 +4,8 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// The P-256 constants the P-256 tests share, each with its source: RFC 6979's key, the group -// order n and (n - 1) / 2, and the field prime p. +// The P-256 constants the P-256 tests share, each with its source: RFC 6979's key and its two +// SHA-256 signatures, the group order n and (n - 1) / 2, and the field prime p. #ifndef WEBCPP_TEST_CRYPTO_SUPPORT_P256_DATA_HPP #define WEBCPP_TEST_CRYPTO_SUPPORT_P256_DATA_HPP @@ -24,6 +24,18 @@ inline constexpr auto rfc6979_scalar = inline constexpr auto rfc6979_public = hex<65>( "0460fed4ba255a9d31c961eb74c6356d68c049b8923b61fa6ce669622e60f29fb6" "7903fe1008b8bc99a41ae9e95628bc64f2f1b20c2d7e9f5177a3c294d4462299"); +// RFC 6979, section A.2.5, P-256 with SHA-256, message "sample": S is high. +inline constexpr auto rfc6979_sample = hex<64>( + "efd48b2aacb6a8fd1140dd9cd45e81d69d2c877b56aaf991c34d0ea84eaf3716" + "f7cb1c942d657c41d436c7a1b6e29f65f3e900dbb9aff4064dc4ab2f843acda8"); +// n - s of the case above: its low-S form. +inline constexpr auto rfc6979_sample_low_s = hex<64>( + "efd48b2aacb6a8fd1140dd9cd45e81d69d2c877b56aaf991c34d0ea84eaf3716" + "0834e36ad29a83bf2bc9385e491d6099c8fdf9d1ed67aa7ea5f51f93782857a9"); +// RFC 6979, section A.2.5, P-256 with SHA-256, message "test": S is low. +inline constexpr auto rfc6979_test = hex<64>( + "f1abb023518351cd71d881567b1ea663ed3efcf6c5132b354f28d3b0b7d38367" + "019f4113742a2b14bd25926b49c649155f267e60d3814b4c0cc84250e46f0083"); // FIPS 186-5 / SEC 2: the group order n, and (n - 1) / 2, the largest low S. inline constexpr auto order = hex<32>("ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"); diff --git a/test/timing_coverage_bearssl_test.cpp b/test/timing_coverage_bearssl_test.cpp index 143099c5..dba714cb 100644 --- a/test/timing_coverage_bearssl_test.cpp +++ b/test/timing_coverage_bearssl_test.cpp @@ -15,8 +15,10 @@ // - AES-GCM, gcm, gcm and gcm: make, the move constructor and move // assignment (ruling R3), seal, open, begin_seal, update, result. // - ChaCha20-Poly1305, aead: make, seal, open. -// - P-256, curves::p256: basic_keypair::make, generate; basic_public_key::make (both); not -// guarded (no BearSSL call): public_key, secret_scalar, uncompressed. +// - P-256, curves::p256: basic_keypair::make, generate, sign_ecdsa; basic_public_key::make +// (both); verify_ecdsa, to_der, from_der; not guarded (no BearSSL call): public_key, +// secret_scalar, uncompressed, and normalize_ecdsa and check_low_s, which test/timing_test.cpp +// calls without a backend. #include "support/timing_seam.hpp" @@ -33,6 +35,8 @@ #include +#include +#include #include #include @@ -98,10 +102,63 @@ void cover_p256_keys() { [&key] { BOOST_TEST(key->uncompressed() == data::rfc6979_public); }); } +// P-256's ECDSA: the signature, its verification, and DER both ways, each refused once before +// BearSSL (an r of 0, a short buffer, an empty DER). +void cover_p256_ecdsa() { + namespace p256 = crypto::curves::p256; + namespace data = webcpp::test::p256; + using keypair = p256::basic_keypair; + using public_key = p256::basic_public_key; + auto const made = keypair::make(data::rfc6979_scalar); + auto const key = public_key::make(data::rfc6979_public); + if (!BOOST_TEST(made.has_value()) || !BOOST_TEST(key.has_value())) { + return; + } + // SHA-256 of "test" (RFC 6979, section A.2.5), whose signature is data::rfc6979_test. + std::array const digest{ + 0x9f, 0x86, 0xd0, 0x81, 0x88, 0x4c, 0x7d, 0x65, 0x9a, 0x2f, 0xea, + 0xa0, 0xc5, 0x5a, 0xd0, 0x15, 0xa3, 0xbf, 0x4f, 0x1b, 0x2b, 0x0b, + 0x82, 0x2c, 0xd1, 0x5d, 0x6c, 0x15, 0xb0, 0xf0, 0x0a, 0x08, + }; + webcpp::test::covered("p256::basic_keypair::sign_ecdsa on bearssl", [&made, &digest] { + auto const signature = made->sign_ecdsa(digest); + BOOST_TEST(signature.has_value() && *signature == data::rfc6979_test); + }); + webcpp::test::covered("p256::verify_ecdsa on bearssl", [&key, &digest] { + BOOST_TEST(p256::verify_ecdsa(data::rfc6979_test, digest, *key).has_value()); + }); + auto zero_r = data::rfc6979_test; + std::fill_n(zero_r.begin(), 32, std::uint8_t{0}); + webcpp::test::covered("p256::verify_ecdsa of r = 0 on bearssl", [&key, &digest, &zero_r] { + BOOST_TEST(p256::verify_ecdsa(zero_r, digest, *key).error() == + crypto::error::invalid_signature); + }); + std::array der{}; + webcpp::test::covered("p256::to_der on bearssl", [&der] { + BOOST_TEST(p256::to_der(data::rfc6979_test, der).has_value()); + }); + webcpp::test::covered("p256::to_der into 71 bytes on bearssl", [&der] { + BOOST_TEST(p256::to_der(data::rfc6979_test, std::span(der).first(71)).error() == + crypto::error::invalid_input_size); + }); + auto const encoded = p256::to_der(data::rfc6979_test, der); + if (!BOOST_TEST(encoded.has_value())) { + return; + } + webcpp::test::covered("p256::from_der on bearssl", [&der, &encoded] { + auto const decoded = p256::from_der(std::span(der).first(*encoded)); + BOOST_TEST(decoded.has_value() && *decoded == data::rfc6979_test); + }); + webcpp::test::covered("p256::from_der of nothing on bearssl", [] { + BOOST_TEST(p256::from_der({}).error() == crypto::error::invalid_signature); + }); +} + } // namespace int main() { cover_ciphers(); cover_p256_keys(); + cover_p256_ecdsa(); return webcpp::test::exit_status(boost::report_errors()); } diff --git a/test/timing_test.cpp b/test/timing_test.cpp index 86d0de93..1851ce37 100644 --- a/test/timing_test.cpp +++ b/test/timing_test.cpp @@ -9,14 +9,18 @@ // and MSVC; where the CPU has DIT, a guard sets it for its scope and clears it after when it was // clear, leaves it set when it was set, and nests; equal enters its own guard. Built with // WEBCPP_TEST_TIMING_THREADS (timing_threads, native, with threads), a guard on one thread leaves -// another's DIT clear. +// another's DIT clear. P-256's normalize_ecdsa and check_low_s, which call no backend, enter no +// guard: this program links none, and curves/p256.hpp needs none to declare them. #include "support/timing_seam.hpp" +#include #include #include #include +#include "support/p256_data.hpp" + #include #include @@ -196,6 +200,18 @@ void equal_enters() { BOOST_TEST(!detail::dit_is_set()); } +// P-256's low-S functions are arithmetic on public bytes, with no backend: no guard. +void p256_low_s_unguarded() { + namespace p256 = webcpp::crypto::curves::p256; + namespace data = webcpp::test::p256; + webcpp::test::uncovered("p256::normalize_ecdsa", [] { + auto const normalized = p256::normalize_ecdsa(data::rfc6979_sample); + BOOST_TEST(normalized.has_value() && *normalized == data::rfc6979_sample_low_s); + }); + webcpp::test::uncovered("p256::check_low_s", + [] { BOOST_TEST(p256::check_low_s(data::rfc6979_test).has_value()); }); +} + #ifdef WEBCPP_TEST_TIMING_THREADS // While a guard holds DIT on this thread, another thread reads it clear. The other thread is // started before the guard, so that it cannot inherit the state at its creation (Linux's clone @@ -229,6 +245,7 @@ int main() { guard_leaves_set_bit(); nested_guards(); equal_enters(); + p256_low_s_unguarded(); #ifdef WEBCPP_TEST_TIMING_THREADS other_thread_untouched(); #endif From ae82bbd122875a1778949ca5cd6282df14efcef6 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 21 Nov 2026 00:41:25 -0300 Subject: [PATCH 04/28] crypto: P-256 ECDSA's page shows the signing lines from its example, and each Doc Comment's brief is one sentence --- doc/p256.adoc | 10 ++++------ example/p256_sign.cpp | 28 ++++++++++++++------------- include/webcpp/crypto/curves/p256.hpp | 19 +++++++++++------- 3 files changed, 31 insertions(+), 26 deletions(-) diff --git a/doc/p256.adoc b/doc/p256.adoc index 838a6286..12f55b4b 100644 --- a/doc/p256.adoc +++ b/doc/p256.adoc @@ -99,16 +99,14 @@ takes; a key a tool sends compressed is decompressed by that tool first. ECDSA signs a *digest*, not a message: the program hashes the message with SHA-256, then `keypair::sign_ecdsa(digest)` signs those 32 bytes, as -WebCrypto's `sign({name: "ECDSA", hash: "SHA-256"}, ...)` hashes and signs in one +WebCrypto's `+sign({name: "ECDSA", hash: "SHA-256"}, ...)+` hashes and signs in one call (link:https://www.w3.org/TR/WebCryptoAPI/[W3C]) and passkeys' ES256 does (link:https://www.w3.org/TR/webauthn-2/#sctn-alg-identifier[W3C Web Authentication]): [source,cpp] ---- -std::array digest{}; -auto hashed = webcpp::hash::digest_of(digest, message); -auto signature = key.sign_ecdsa(digest); // 64 bytes: r, then s +include::{examples}/p256_sign.cpp[tag=sign,indent=0] ---- The nonce is RFC 6979's (link:https://www.rfc-editor.org/rfc/rfc6979[RFC @@ -172,8 +170,8 @@ include::{examples}/p256_sign.expected[] *Pitfalls.* * A protocol that requires low S and forgets `normalize_ecdsa` fails about one -signature in two: `sign_ecdsa`'s S is high half the time, and the peer's -`check_low_s` refuses those. The tests that sign a fixed message may pass +signature in two: the S of `sign_ecdsa` is high half the time, and +`check_low_s` on the peer's side refuses those. The tests that sign a fixed message may pass every time, the signature being the same; a program sees it at the first handshake whose S is high. Normalize every signature such a protocol sends, and check every one it receives. diff --git a/example/p256_sign.cpp b/example/p256_sign.cpp index 48dcbaf2..2075163f 100644 --- a/example/p256_sign.cpp +++ b/example/p256_sign.cpp @@ -37,16 +37,10 @@ void print(char const* name, std::span bytes) { std::printf("\n"); } -// What is signed is a SHA-256 digest, as WebCrypto's ECDSA with SHA-256 hashes the message. -std::array digest_of(std::string_view text) { - std::array digest{}; +// A text's bytes, the message. +std::span bytes_of(std::string_view text) { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): a text's bytes - auto const* const bytes = reinterpret_cast(text.data()); - std::span const message(bytes, text.size()); - if (!webcpp::hash::digest_of(digest, message)) { - digest.fill(0); - } - return digest; + return {reinterpret_cast(text.data()), text.size()}; } } // namespace @@ -64,10 +58,14 @@ int main() { std::printf("failed\n"); return 1; } - auto const digest = digest_of("sample"); - + // tag::sign[] + // What is signed is the message's SHA-256 digest, as WebCrypto's ECDSA with SHA-256 signs. + std::array digest{}; + auto const hashed = + webcpp::hash::digest_of(digest, bytes_of("sample")); // RFC 6979's nonce: no random number, the same signature for the same key and digest. - auto const signature = key->sign_ecdsa(digest); + auto const signature = hashed ? key->sign_ecdsa(digest) : hashed.error(); + // end::sign[] if (!signature) { std::printf("failed\n"); return 1; @@ -97,7 +95,11 @@ int main() { bool const both = p256::verify_ecdsa(*signature, digest, *public_key) && decoded && p256::verify_ecdsa(*decoded, digest, *public_key); std::printf("verified %s\n", both ? "both forms" : "FAILED"); - auto const other = p256::verify_ecdsa(*signature, digest_of("test"), *public_key); + std::array other_digest{}; + auto const other_hashed = + webcpp::hash::digest_of(other_digest, bytes_of("test")); + auto const other = + other_hashed ? p256::verify_ecdsa(*signature, other_digest, *public_key) : other_hashed; std::printf("other text %s\n", other ? "verified" : other.error().message().c_str()); return 0; } diff --git a/include/webcpp/crypto/curves/p256.hpp b/include/webcpp/crypto/curves/p256.hpp index f81423f8..6fa88f99 100644 --- a/include/webcpp/crypto/curves/p256.hpp +++ b/include/webcpp/crypto/curves/p256.hpp @@ -315,9 +315,10 @@ class basic_keypair { using keypair = basic_keypair<>; /** - * Verifies an ECDSA signature of a SHA-256 digest with a public key. A high S and a low S are both - * accepted, as FIPS 186-5 and WebCrypto accept them; a protocol that requires low S calls - * `check_low_s` too. + * Verifies an ECDSA signature of a SHA-256 digest with a public key. + * + * A high S and a low S are both accepted, as FIPS 186-5 and WebCrypto accept them; a protocol that + * requires low S calls `check_low_s` too. * * @tparam Backend The key's backend, which verifies. * @param signature 64 bytes, r then s (IEEE P1363, WebCrypto's form); `from_der` reads DER. @@ -400,8 +401,10 @@ template > /** * The low-S form of a signature: s replaced by n - s when s is above (n - 1) / 2, returned - * unchanged otherwise. Both forms verify; a protocol that requires low S normalizes what it - * signs. Arithmetic on public bytes, with no backend. + * unchanged otherwise. + * + * Both forms verify; a protocol that requires low S normalizes what it signs. Arithmetic on public + * bytes, with no backend. * * @param signature 64 bytes, r then s. * @return 64 bytes, r then s, with s at most (n - 1) / 2; `invalid_signature` when r or s is 0 or @@ -424,8 +427,10 @@ normalize_ecdsa(std::span signature) noexcep /** * Checks that a signature is in its low-S form, s at most (n - 1) / 2, as a protocol that - * requires low S checks what it receives. Arithmetic on public bytes, with no backend; it does - * not verify the signature (`verify_ecdsa` does). + * requires low S checks what it receives. + * + * Arithmetic on public bytes, with no backend; it does not verify the signature (`verify_ecdsa` + * does). * * @param signature 64 bytes, r then s. * @return Nothing; `invalid_signature` when s is above (n - 1) / 2, and when r or s is 0 or not From 806ad572cc100332206e654620f4fadcf3ec7512 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 21 Nov 2026 00:51:30 -0300 Subject: [PATCH 05/28] crypto: P-256 ECDSA's tests refuse tampering on every signature, cover a moved-from signer and replay their seed, and its pages state what BearSSL leaves on its stack --- doc/backends.adoc | 8 +++ doc/generated/backends-p256_ecdsa.adoc | 2 +- doc/generated/matrix.adoc | 6 +-- doc/llms.txt | 2 +- doc/p256.adoc | 14 +++-- doc/tables/crypto.json | 3 +- test/p256_ecdsa_bearssl_test.cpp | 75 +++++++++++++++++--------- test/timing_coverage_bearssl_test.cpp | 21 +++++++- 8 files changed, 97 insertions(+), 34 deletions(-) diff --git a/doc/backends.adoc b/doc/backends.adoc index 82df30ed..7eba3af0 100644 --- a/doc/backends.adoc +++ b/doc/backends.adoc @@ -40,6 +40,14 @@ OpenSSL is never the system's: the superproject builds it from Natively with Clang and GCC it is built with its assembly; on MSVC, wasip2 and wasip3 it is built `no-asm` (link:https://github.com/openssl/openssl/blob/master/INSTALL.md[INSTALL.md]). +BearSSL zeroes nothing it computes on the stack: its ECDSA signing keeps the +scalar, the nonce and the HMAC-DRBG state that derives the nonce in its own +stack frame and returns without clearing them +(link:https://www.bearssl.org/gitweb/?p=BearSSL;a=blob;f=src/ec/ecdsa_i31_sign_raw.c;hb=7bea48e5e850ab4cafbe68d3765cdaba13a86d6f#l45[ecdsa_i31_sign_raw.c, +lines 45 to 51 and 115 to 135]). webcpp wipes what it owns, a key pair's state +and every `secret`, and cannot reach a callee's frame, which the program's +next calls overwrite. + A program has one copy of each library: libsecp256k1's tables and OpenSSL's state are global symbols, so webcpp's build is never linked with another copy. diff --git a/doc/generated/backends-p256_ecdsa.adoc b/doc/generated/backends-p256_ecdsa.adoc index e0fc5986..7a7b377b 100644 --- a/doc/generated/backends-p256_ecdsa.adoc +++ b/doc/generated/backends-p256_ecdsa.adoc @@ -7,7 +7,7 @@ // Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, // the message tests and the Jamfile fixtures: run it again, never edit this file. -The backends of `+curves::p256::keypair::sign_ecdsa+`, `+verify_ecdsa+`, `+to_der+`, `+from_der+`, `+normalize_ecdsa+`, `+check_low_s+`, from the test programs that run it: +The backends of `+curves::p256::keypair::sign_ecdsa; verify_ecdsa+`, `+to_der+`, `+from_der+`, `+normalize_ecdsa+`, `+check_low_s+`, from the test programs that run it: [cols="1,2,2,4",options="header"] |=== diff --git a/doc/generated/matrix.adoc b/doc/generated/matrix.adoc index aa77d09f..fa35ec0b 100644 --- a/doc/generated/matrix.adoc +++ b/doc/generated/matrix.adoc @@ -241,12 +241,12 @@ |native, wasip2, wasip3, emscripten |`+p256_keys_bearssl+`, `+allocation_bearssl+` -|`+curves::p256::keypair::sign_ecdsa+`, `+verify_ecdsa+`, `+to_der+`, `+from_der+`, `+normalize_ecdsa+`, `+check_low_s+` +|`+curves::p256::keypair::sign_ecdsa; verify_ecdsa+`, `+to_der+`, `+from_der+`, `+normalize_ecdsa+`, `+check_low_s+` |BearSSL |native, wasip2, wasip3, emscripten |`+p256_ecdsa_bearssl+`, `+p256_wycheproof_bearssl+`, `+allocation_bearssl+` -|`+curves::p256::keypair::sign_ecdsa+`, `+verify_ecdsa+`, `+to_der+`, `+from_der+`, `+normalize_ecdsa+`, `+check_low_s+` +|`+curves::p256::keypair::sign_ecdsa; verify_ecdsa+`, `+to_der+`, `+from_der+`, `+normalize_ecdsa+`, `+check_low_s+` |libsodium |refused at compile time |`+p256_on_sodium+` @@ -480,7 +480,7 @@ The same, by target: the backends each operation runs on. |BearSSL |BearSSL -|`+curves::p256::keypair::sign_ecdsa+`, `+verify_ecdsa+`, `+to_der+`, `+from_der+`, `+normalize_ecdsa+`, `+check_low_s+` +|`+curves::p256::keypair::sign_ecdsa; verify_ecdsa+`, `+to_der+`, `+from_der+`, `+normalize_ecdsa+`, `+check_low_s+` |BearSSL |BearSSL |BearSSL diff --git a/doc/llms.txt b/doc/llms.txt index a2fe0c1e..6be8232c 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -177,7 +177,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [curves::p256::public_key](https://webcpporg.github.io/libs/crypto/#crypto-p256-keys): A validated P-256 public key, made from SEC 1's 65-byte uncompressed point or from its two coordinates; a point off the curve, a coordinate not below p or another form is `invalid_public_key`. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten. Default: BearSSL on native, wasip2, wasip3, emscripten. Use it to: make and keep a P-256 key pair, and import a browser's public key (WebCrypto's raw form), as webcpp::trystero's peers do. - make: Makes a public key from SEC 1's uncompressed point, as WebCrypto's `exportKey("raw")` writes it. - uncompressed: The point, as WebCrypto's `exportKey("raw")` writes it. -- [curves::p256::keypair::sign_ecdsa, verify_ecdsa, to_der, from_der, normalize_ecdsa, check_low_s](https://webcpporg.github.io/libs/crypto/#crypto-p256-ecdsa): ECDSA over a SHA-256 digest with RFC 6979's nonce, r and s as 64 bytes, verified whatever its S; strict DER both ways; low S as two functions, `normalize_ecdsa` and `check_low_s`, for a protocol that requires it. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten. Default: BearSSL on native, wasip2, wasip3, emscripten. Use it to: sign what a browser's WebCrypto verifies and verify what it signs (ECDSA on P-256 with SHA-256), low S where a protocol requires it, as webcpp::trystero's handshakes. +- [curves::p256::keypair::sign_ecdsa; verify_ecdsa, to_der, from_der, normalize_ecdsa, check_low_s](https://webcpporg.github.io/libs/crypto/#crypto-p256-ecdsa): ECDSA over a SHA-256 digest with RFC 6979's nonce, r and s as 64 bytes, verified whatever its S; strict DER both ways; low S as two functions, `normalize_ecdsa` and `check_low_s`, for a protocol that requires it. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten. Default: BearSSL on native, wasip2, wasip3, emscripten. Use it to: sign what a browser's WebCrypto verifies and verify what it signs (ECDSA on P-256 with SHA-256), low S where a protocol requires it, as webcpp::trystero's handshakes. - sign_ecdsa: Signs a SHA-256 digest with ECDSA, RFC 6979's deterministic nonce (no random number is drawn: the same key and digest give the same signature), S as the computation gives it, high or low (`normalize_ecdsa` gives the low form). - verify_ecdsa: Verifies an ECDSA signature of a SHA-256 digest with a public key. - to_der: Encodes a signature as strict DER, the ECDSA-Sig-Value SEQUENCE of two INTEGERs that X.509 and OpenSSL carry. diff --git a/doc/p256.adoc b/doc/p256.adoc index 12f55b4b..fb6ee791 100644 --- a/doc/p256.adoc +++ b/doc/p256.adoc @@ -80,7 +80,12 @@ include::{examples}/p256_keys.expected[] * A scalar stored outside a `secret<32>` outlives the key pair: the key pair and the `secret<32>` that `secret_scalar` returns wipe their bytes, but a copy in a string, a log or -a file stays where it was written. Keep the scalar in the `secret<32>` until it +a file stays where it was written. What webcpp wipes is what it owns: BearSSL's +own signing keeps the scalar, the nonce and the state that derives the nonce in +its stack frame and returns without zeroing them +(link:https://www.bearssl.org/gitweb/?p=BearSSL;a=blob;f=src/ec/ecdsa_i31_sign_raw.c;hb=7bea48e5e850ab4cafbe68d3765cdaba13a86d6f#l45[BearSSL's +ecdsa_i31_sign_raw.c, lines 45 to 51 and 115 to 135]), where a later call +overwrites them; nothing in webcpp can reach that frame. Keep the scalar in the `secret<32>` until it is encrypted or written to the key store, and never print it. * A peer's key is made into a `public_key` once, where it arrives, and kept: made again for every message, it costs a point check each time, and code that @@ -97,7 +102,10 @@ takes; a key a tool sends compressed is decompressed by that tool first. [#crypto-p256-ecdsa] ==== ECDSA -ECDSA signs a *digest*, not a message: the program hashes the message with +ECDSA signs bytes so that anyone who holds the public key, a browser's +WebCrypto included, can check who signed them and that nothing changed: a +handshake, a token, a record a peer sends on. It signs a *digest*, not a +message: the program hashes the message with SHA-256, then `keypair::sign_ecdsa(digest)` signs those 32 bytes, as WebCrypto's `+sign({name: "ECDSA", hash: "SHA-256"}, ...)+` hashes and signs in one call (link:https://www.w3.org/TR/WebCryptoAPI/[W3C]) and passkeys' ES256 does @@ -124,7 +132,7 @@ A signature has two forms. The *raw* form, 64 bytes, r then s at 32 bytes each `sign_ecdsa` and `verify_ecdsa` take: what WebCrypto signs and verifies (link:https://www.w3.org/TR/WebCryptoAPI/[W3C]) and what a JSON Web Token's ES256 carries (link:https://www.rfc-editor.org/rfc/rfc7518#section-3.4[RFC -7518, section 3.4]). *DER*, a SEQUENCE of two INTEGERs of 8 to 72 bytes, is the +7518, section 3.4]). *DER*, 8 to 72 bytes: a SEQUENCE of two INTEGERs, is the form of X.509 certificates and OpenSSL (link:https://www.rfc-editor.org/rfc/rfc3279#section-2.2.3[RFC 3279, section 2.2.3]): `to_der(signature, output)` writes it into at least `max_der_size` diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 3ab139cc..3e0f5260 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -42,6 +42,7 @@ "bearssl": ["BearSSL, its home page", "https://www.bearssl.org/"], "webauthn": ["W3C Web Authentication, its algorithm identifiers: ES256 is ECDSA on P-256 with SHA-256", "https://www.w3.org/TR/webauthn-2/#sctn-alg-identifier"], "webauthn-signatures": ["W3C Web Authentication, section 6.5.5: an ES256 assertion's signature is DER, RFC 3279's Ecdsa-Sig-Value", "https://www.w3.org/TR/webauthn-2/#sctn-signature-attestation-types"], + "bearssl-ecdsa-stack": ["BearSSL's ecdsa_i31_sign_raw.c at webcpp's pin, lines 45 to 51 and 115 to 135: the scalar, the nonce and the HMAC-DRBG state in the function's stack frame, never zeroed", "https://www.bearssl.org/gitweb/?p=BearSSL;a=blob;f=src/ec/ecdsa_i31_sign_raw.c;hb=7bea48e5e850ab4cafbe68d3765cdaba13a86d6f#l45"], "ieee1363": ["IEEE 1363-2000, Standard Specifications for Public-Key Cryptography: a signature as the two integers r and s, each at the order's length", "https://standards.ieee.org/ieee/1363/2049/"], "rfc3279": ["RFC 3279, section 2.2.3: an ECDSA signature in X.509, the DER of a SEQUENCE of the INTEGERs r and s", "https://www.rfc-editor.org/rfc/rfc3279#section-2.2.3"], "rfc7518": ["RFC 7518, section 3.4: JWS's ES256 signature is r and s, 32 bytes each, not DER", "https://www.rfc-editor.org/rfc/rfc7518#section-3.4"], @@ -684,7 +685,7 @@ "free": true, "functions": ["basic_keypair::sign_ecdsa", "verify_ecdsa", "to_der", "from_der", "normalize_ecdsa", "check_low_s"], "namespace": "curves", - "api": "curves::p256::keypair::sign_ecdsa, verify_ecdsa, to_der, from_der, normalize_ecdsa, check_low_s", + "api": "curves::p256::keypair::sign_ecdsa; verify_ecdsa, to_der, from_der, normalize_ecdsa, check_low_s", "header": "", "what": "ECDSA over a SHA-256 digest with RFC 6979's nonce, r and s as 64 bytes, verified whatever its S; strict DER both ways; low S as two functions, `normalize_ecdsa` and `check_low_s`, for a protocol that requires it.", "section": "crypto-p256-ecdsa", diff --git a/test/p256_ecdsa_bearssl_test.cpp b/test/p256_ecdsa_bearssl_test.cpp index 9db92286..bc00e97c 100644 --- a/test/p256_ecdsa_bearssl_test.cpp +++ b/test/p256_ecdsa_bearssl_test.cpp @@ -7,7 +7,8 @@ // P-256 ECDSA on BearSSL: RFC 6979's two SHA-256 signatures byte for byte, the same on every // signing; verification of both forms of a signature and every refusal (a bit of the digest, of // r or of s, another key, r or s 0 or n), and the digests 0 modulo n that BearSSL refuses; low S, -// checked and normalized, at its boundary and over 1,000 signatures of random digests; DER both +// checked and normalized, at its boundary and over 1,000 signatures of random digests under a +// key, both drawn from a printed seed that a define replays; DER both // ways against encodings written by hand, the short buffer, the strict decoder's refusals and // integers shorter than 32 bytes. @@ -117,23 +118,30 @@ void verify_both_forms() { return p256::verify_ecdsa(value, hash, *key).error() == error::invalid_signature; }; BOOST_TEST(refused(data::rfc6979_test, sample)); - auto flipped_digest = test; - flipped_digest[7] ^= 0x10U; - BOOST_TEST(refused(data::rfc6979_test, flipped_digest)); - auto flipped_r = data::rfc6979_test; - flipped_r[3] ^= 0x01U; - BOOST_TEST(refused(flipped_r, test)); - auto flipped_s = data::rfc6979_test; - flipped_s[60] ^= 0x80U; - BOOST_TEST(refused(flipped_s, test)); + BOOST_TEST(refused(data::rfc6979_sample, test)); auto const other = keypair::generate(); - if (BOOST_TEST(other.has_value())) { - auto const other_key = other->public_key(); - if (BOOST_TEST(other_key.has_value())) { - BOOST_TEST(p256::verify_ecdsa(data::rfc6979_test, test, *other_key).error() == - error::invalid_signature); - } + auto const other_key = other ? other->public_key() : other.error(); + if (!BOOST_TEST(other_key.has_value())) { + return; + } + // Each signature, the RFC's high S, its low-S form and the low "test" one: one bit of the + // digest, of r or of s flipped, and another key, each refused. + for (auto const& [value, hash] : { + std::pair{data::rfc6979_sample, sample}, + std::pair{data::rfc6979_sample_low_s, sample}, + std::pair{data::rfc6979_test, test}, + }) { + auto flipped_digest = hash; + flipped_digest[7] ^= 0x10U; + BOOST_TEST(refused(value, flipped_digest)); + auto flipped_r = value; + flipped_r[3] ^= 0x01U; + BOOST_TEST(refused(flipped_r, hash)); + auto flipped_s = value; + flipped_s[60] ^= 0x80U; + BOOST_TEST(refused(flipped_s, hash)); + BOOST_TEST(p256::verify_ecdsa(value, hash, *other_key).error() == error::invalid_signature); } std::array const zero{}; @@ -195,23 +203,42 @@ void low_s() { } } +// The seed of low_s_random: drawn on each run and printed; a run is replayed by building with +// the printed value, define=WEBCPP_TEST_P256_SEED= on b2's command line, with -a or a +// build directory of its own, since a define alone does not make b2 build the test again. +std::uint64_t random_seed() { +#ifdef WEBCPP_TEST_P256_SEED + return WEBCPP_TEST_P256_SEED; +#else + return std::random_device{}(); +#endif +} + void low_s_random() { - auto const key = keypair::generate(); - if (!BOOST_TEST(key.has_value())) { - return; + std::uint64_t const seed = random_seed(); + std::cout << "low_s_random: seed " << seed << " (replay: define=WEBCPP_TEST_P256_SEED=" << seed + << ")\n"; + std::mt19937_64 generator(seed); + auto const draw = [&generator](std::span bytes) { + std::ranges::generate(bytes, + [&generator] { return static_cast(generator()); }); + }; + // The key is drawn from the seed too, so that the seed replays the whole run. + std::array scalar{}; + draw(scalar); + auto key = keypair::make(scalar); + while (!key) { + draw(scalar); + key = keypair::make(scalar); } auto const verifier = key->public_key(); if (!BOOST_TEST(verifier.has_value())) { return; } - std::uint64_t const seed = std::random_device{}(); - std::cout << "low_s_random: seed " << seed << '\n'; - std::mt19937_64 generator(seed); int high = 0; for (int i = 0; i < 1000; ++i) { digest hash{}; - std::ranges::generate(hash, - [&generator] { return static_cast(generator()); }); + draw(hash); auto const signed_hash = key->sign_ecdsa(hash); if (!BOOST_TEST(signed_hash.has_value())) { return; diff --git a/test/timing_coverage_bearssl_test.cpp b/test/timing_coverage_bearssl_test.cpp index dba714cb..55330f88 100644 --- a/test/timing_coverage_bearssl_test.cpp +++ b/test/timing_coverage_bearssl_test.cpp @@ -39,6 +39,7 @@ #include #include #include +#include namespace { @@ -102,8 +103,25 @@ void cover_p256_keys() { [&key] { BOOST_TEST(key->uncompressed() == data::rfc6979_public); }); } +// P-256's sign_ecdsa on a moved-from key pair: refused with invalid_state before BearSSL, inside +// its own guard. +void cover_p256_sign_moved_from(std::span digest) { + namespace p256 = crypto::curves::p256; + namespace data = webcpp::test::p256; + using keypair = p256::basic_keypair; + auto source = keypair::make(data::rfc6979_scalar); + if (BOOST_TEST(source.has_value())) { + keypair const taken = std::move(*source); + webcpp::test::covered( + "p256::basic_keypair::sign_ecdsa moved from on bearssl", [&source, &digest] { + // NOLINTNEXTLINE(bugprone-use-after-move,clang-analyzer-cplusplus.Move): tested + BOOST_TEST(source->sign_ecdsa(digest).error() == crypto::error::invalid_state); + }); + } +} + // P-256's ECDSA: the signature, its verification, and DER both ways, each refused once before -// BearSSL (an r of 0, a short buffer, an empty DER). +// BearSSL (a moved-from key pair, an r of 0, a short buffer, an empty DER). void cover_p256_ecdsa() { namespace p256 = crypto::curves::p256; namespace data = webcpp::test::p256; @@ -124,6 +142,7 @@ void cover_p256_ecdsa() { auto const signature = made->sign_ecdsa(digest); BOOST_TEST(signature.has_value() && *signature == data::rfc6979_test); }); + cover_p256_sign_moved_from(digest); webcpp::test::covered("p256::verify_ecdsa on bearssl", [&key, &digest] { BOOST_TEST(p256::verify_ecdsa(data::rfc6979_test, digest, *key).has_value()); }); From 663a5d6e6132ab2e4eb2bf3797ba96b3b441d4fd Mon Sep 17 00:00:00 2001 From: R Date: Sat, 21 Nov 2026 01:08:09 -0300 Subject: [PATCH 06/28] crypto: P-256 ECDH on BearSSL returns the shared point's raw x coordinate as WebCrypto's deriveBits does, against Wycheproof --- doc/changelog.adoc | 2 +- doc/curves.adoc | 7 +- doc/generated/backends-p256_ecdh.adoc | 35 ++ doc/generated/defaults.adoc | 2 +- doc/generated/matrix.adoc | 16 + doc/generated/namespace-curves.adoc | 4 +- doc/generated/use-cases.adoc | 7 + doc/llms.txt | 6 +- doc/p256.adoc | 77 +++++ doc/tables/crypto.json | 24 +- example/Jamfile | 3 + example/p256_ecdh.cpp | 110 ++++++ example/p256_ecdh.expected | 3 + include/webcpp/crypto/backends/bearssl.hpp | 35 +- include/webcpp/crypto/curves/p256.hpp | 35 +- test/Jamfile | 5 + test/allocation_bearssl_test.cpp | 3 +- test/p256_ecdh_bearssl_test.cpp | 384 +++++++++++++++++++++ test/p256_keys_bearssl_test.cpp | 2 + test/timing_coverage_bearssl_test.cpp | 30 +- 20 files changed, 771 insertions(+), 19 deletions(-) create mode 100644 doc/generated/backends-p256_ecdh.adoc create mode 100644 example/p256_ecdh.cpp create mode 100644 example/p256_ecdh.expected create mode 100644 test/p256_ecdh_bearssl_test.cpp diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 3a6c06ad..1ded37e5 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -19,7 +19,7 @@ of every version are on webcpp's index page. * Added crypto, C-backed primitives setting DIT on arm64 macOS and Linux: ciphers, curves, randomness, fixed-value errors in webcpp.crypto, `+[[nodiscard]]+` results, WEBCPP_CRYPTO_HAS_THREADS, defined natively and with Emscripten's -pthread unless WEBCPP_CRYPTO_NO_THREADS is. * Added equal, random_device, pem (PEM on libsodium), ciphers::aes128, aes192 and aes256, the AES block cipher, and ciphers::gcm, aes128_gcm and aes256_gcm: AES-GCM in place, incremental seal, failed opens zeroing data. * Added supports_v with its family tags, the capability table per target, default_backend_t and /webcpp/crypto//-default per family and target (secp256k1's modules among them), and refusals naming their Jamfile line. -* Added backends::bearssl (AES-GCM, ChaCha20-Poly1305, P-256 key pairs and ECDSA; allocating nothing), backends::openssl natively and on WASI (allocating at make, or natively in openssl_memory_resource with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE), and backends::ctaes (block cipher alone). +* Added backends::bearssl (AES-GCM, ChaCha20-Poly1305, P-256 key pairs, ECDSA, ECDH; allocating nothing), backends::openssl natively and on WASI (allocating at make, or natively in openssl_memory_resource with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE), and backends::ctaes (block cipher alone). * Added curves::secp256k1: key pairs, BIP340, hedged and recoverable ECDSA, raw and hashed ECDH, strict DER, low-S, tweaks, SPKI, PKCS#8, PEM, BIP 324's ElligatorSwift, BIP 327's MuSig2, BIP 352's silent payments. * Added curves::ed25519 and curves::x25519 on libsodium: strict verification over twelve edge cases, Ed25519ph over hash's sha2_512 (/webcpp/crypto//crypto brings hash), the conversion, agree refusing all-zero secrets, RFC 8410's SPKI and PKCS#8. * Added backends::sodium on /third_party//sodium, shared with webcpp::hash, every backend's link-time canary and C suite, and ciphers::aead: chacha20_poly1305 (also BearSSL, OpenSSL), the original form, xchacha20_poly1305, failed seals and opens zeroing data. diff --git a/doc/curves.adoc b/doc/curves.adoc index f60befbd..0adbeb13 100644 --- a/doc/curves.adoc +++ b/doc/curves.adoc @@ -65,10 +65,11 @@ key to it (link:https://www.rfc-editor.org/rfc/rfc7748[RFC 7748]; <>), and libsodium's key exchange on it, `crypto_kx` (<>). The fourth is P-256, NIST's curve of FIPS 186-5, the curve of browsers' WebCrypto, of passkeys and of TLS certificates, on BearSSL: key pairs -made from a scalar or drawn, public keys validated once, and ECDSA with RFC -6979's nonce, raw and DER, with low S as two functions +made from a scalar or drawn, public keys validated once, ECDSA with RFC +6979's nonce, raw and DER, with low S as two functions, and ECDH's raw x +coordinate, as WebCrypto's `deriveBits` gives it (link:https://csrc.nist.gov/pubs/fips/186-5/final[FIPS 186-5]; -<>, <>). A program chooses a curve for compatibility: a signature on +<>, <>, <>). A program chooses a curve for compatibility: a signature on one curve is checked only with that curve, and a browser's peer needs P-256. Ed25519's and X25519's keys leave a program, and enter it, in the standard forms OpenSSL and WebCrypto use, SPKI and PKCS#8, as DER or PEM text (<>). diff --git a/doc/generated/backends-p256_ecdh.adoc b/doc/generated/backends-p256_ecdh.adoc new file mode 100644 index 00000000..fe6e8567 --- /dev/null +++ b/doc/generated/backends-p256_ecdh.adoc @@ -0,0 +1,35 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, +// the message tests and the Jamfile fixtures: run it again, never edit this file. + +The backends of `+curves::p256::keypair::ecdh_x+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|BearSSL +|`+/third_party//bearssl+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+p256_ecdh_bearssl+`, `+allocation_bearssl+`) + +|libsodium +|`+/third_party//sodium+` +|`++` +|refused at compile time (`+p256_on_sodium+`) +|=== + +A call that names no backend takes the family's default on each target, whatever the program links, as <> gives it with its reasons and tests: + +[cols="1,1",options="header"] +|=== +|Target |Default + +|native, wasip2, wasip3, emscripten +|BearSSL +|=== diff --git a/doc/generated/defaults.adoc b/doc/generated/defaults.adoc index f68857bc..253e3791 100644 --- a/doc/generated/defaults.adoc +++ b/doc/generated/defaults.adoc @@ -141,5 +141,5 @@ |native, wasip2, wasip3, emscripten |BearSSL |the one backend of the P-curves on all four targets, constant time by design and allocating nothing (link:https://www.bearssl.org/[BearSSL, its home page]); OpenSSL and Botan join in increments 8 and 7 -|`+p256_keys_bearssl+`, `+p256_ecdsa_bearssl+`, `+default_backend_none_linked+` +|`+p256_keys_bearssl+`, `+p256_ecdsa_bearssl+`, `+p256_ecdh_bearssl+`, `+default_backend_none_linked+` |=== diff --git a/doc/generated/matrix.adoc b/doc/generated/matrix.adoc index fa35ec0b..b9fb32cb 100644 --- a/doc/generated/matrix.adoc +++ b/doc/generated/matrix.adoc @@ -250,6 +250,16 @@ |libsodium |refused at compile time |`+p256_on_sodium+` + +|`+curves::p256::keypair::ecdh_x+` +|BearSSL +|native, wasip2, wasip3, emscripten +|`+p256_ecdh_bearssl+`, `+allocation_bearssl+` + +|`+curves::p256::keypair::ecdh_x+` +|libsodium +|refused at compile time +|`+p256_on_sodium+` |=== The same, by target: the backends each operation runs on. @@ -485,4 +495,10 @@ The same, by target: the backends each operation runs on. |BearSSL |BearSSL |BearSSL + +|`+curves::p256::keypair::ecdh_x+` +|BearSSL +|BearSSL +|BearSSL +|BearSSL |=== diff --git a/doc/generated/namespace-curves.adoc b/doc/generated/namespace-curves.adoc index 990b6d75..c77c5eeb 100644 --- a/doc/generated/namespace-curves.adoc +++ b/doc/generated/namespace-curves.adoc @@ -15,7 +15,7 @@ |BIP 340 Schnorr and ECDSA signatures, recoverable signatures, ECDH in three forms, tweaks, ElligatorSwift, MuSig2, silent payments, SPKI and PKCS#8 |Ed25519 signatures, and Ed25519ph over SHA-512 for a message given in pieces; the X25519 secret key of a key pair |Key agreement (Diffie-Hellman on Curve25519): two parties who exchanged public keys share a 32-byte secret; `kx_keypair`, libsodium's `crypto_kx`, gives a client and a server a session key for each direction -|Key pairs made from a 32-byte scalar or drawn from `random_device`, public keys validated once, as SEC 1's uncompressed point or two coordinates, and ECDSA over a SHA-256 digest with RFC 6979's nonce, raw and DER, and low S checked or normalized +|Key pairs made from a 32-byte scalar or drawn from `random_device`, public keys validated once, as SEC 1's uncompressed point or two coordinates, ECDSA over a SHA-256 digest with RFC 6979's nonce, raw and DER, and low S checked or normalized, and ECDH's raw x coordinate |Security level |about 128 bits (link:https://www.secg.org/sec2-v2.pdf[SEC 2, Recommended Elliptic Curve Domain Parameters]) @@ -69,5 +69,5 @@ |Bitcoin's keys and signatures; Nostr's event signatures (link:https://github.com/nostr-protocol/nips/blob/master/01.md[Nostr NIP-01, events signed with BIP 340 on secp256k1]); Ethereum's ECDSA verification with a known key; ECDH in the raw x-coordinate form of Nostr's encrypted messages (link:https://github.com/nostr-protocol/nips/blob/master/44.md[Nostr NIP-44, encrypted payloads]); Ethereum's recoverable signatures and uncompressed keys (link:https://ethereum.github.io/yellowpaper/paper.pdf[The Ethereum yellow paper, appendix F: ECDSA on secp256k1]), the address hashing being a domain library's; BIP 32's tweaks of the full key, its derivation of the tweak being a domain library's (link:https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki[BIP 32, hierarchical deterministic wallets]); keys exchanged with OpenSSL as SPKI or PKCS#8 (link:https://www.rfc-editor.org/rfc/rfc5480[RFC 5480, Elliptic Curve Cryptography Subject Public Key Information], link:https://www.rfc-editor.org/rfc/rfc5915[RFC 5915, Elliptic Curve Private Key Structure]), in DER or PEM (link:https://www.rfc-editor.org/rfc/rfc7468[RFC 7468, textual encodings of PKIX, PKCS and CMS structures (PEM)]); Bitcoin's version 2 transport, whose keys are ElligatorSwift encodings (link:https://github.com/bitcoin/bips/blob/master/bip-0324.mediawiki[BIP 324, version 2 P2P encrypted transport protocol]); MuSig2's multisignatures (link:https://github.com/bitcoin/bips/blob/master/bip-0327.mediawiki[BIP 327, MuSig2 for BIP340-compatible multi-signatures]); silent payments (link:https://github.com/bitcoin/bips/blob/master/bip-0352.mediawiki[BIP 352, Silent Payments]), the addresses and transactions being a domain library's |SSH, Tor and Solana keys and signatures, and any protocol that names RFC 8032's Ed25519 or Ed25519ph; verification is strict (libsodium's rules), which some lenient verifiers are not. Not Bitcoin, Ethereum or Nostr, whose keys are secp256k1's |TLS 1.3's and SSH's key exchange, WireGuard, Signal; libsodium's `crypto_box` keys, and the session keys of `crypto_kx` with `kx_keypair` (link:https://doc.libsodium.org/key_exchange[libsodium's documentation, key exchange]). The Ed25519 public key of a peer converts with `curves::ed25519::to_x25519_public`. A shared secret goes through a KDF before it keys a cipher. Every case of Wycheproof's X25519 file is tested (link:https://github.com/C2SP/wycheproof[Project Wycheproof, test vectors for cryptographic libraries]) -|Browsers' WebCrypto, whose raw export of a P-256 public key is the uncompressed point `public_key::make` takes (link:https://www.w3.org/TR/WebCryptoAPI/[W3C Web Cryptography API]); passkeys and TLS. Not Bitcoin, Ethereum or Nostr, whose keys are secp256k1's +|Browsers' WebCrypto, whose raw export of a P-256 public key is the uncompressed point `public_key::make` takes (link:https://www.w3.org/TR/WebCryptoAPI/[W3C Web Cryptography API]) and whose ECDH `deriveBits` is the raw x `ecdh_x` gives (link:https://www.w3.org/TR/WebCryptoAPI/#ecdh-operations[W3C Web Cryptography API, ECDH's deriveBits: the shared point's x coordinate, its first length bits]); passkeys and TLS. Not Bitcoin, Ethereum or Nostr, whose keys are secp256k1's |=== diff --git a/doc/generated/use-cases.adoc b/doc/generated/use-cases.adoc index e4b2b881..33bb7333 100644 --- a/doc/generated/use-cases.adoc +++ b/doc/generated/use-cases.adoc @@ -256,4 +256,11 @@ |`+/webcpp/crypto//crypto+` + `+/webcpp/crypto//p256-default+` |<> + +|Agree on a key with a browser's WebCrypto (ECDH on P-256, deriveBits), then derive the session's keys with HKDF, as webcpp::trystero's peers do +|In `+curves::p256+`: `+keypair::ecdh_x+`; `+webcpp::hash::hkdf+` for the keys +|BearSSL +|`+/webcpp/crypto//crypto+` + +`+/webcpp/crypto//p256-default+` +|<> |=== diff --git a/doc/llms.txt b/doc/llms.txt index 6be8232c..a65f2f26 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -1,6 +1,6 @@ # webcpp::crypto -> Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA and recoverable signatures, ECDH, tweaks, ElligatorSwift, MuSig2, silent payments), Ed25519 and Ed25519ph (RFC 8032), X25519 (RFC 7748), their keys in SPKI, PKCS#8 (RFC 8410) and PEM, P-256 key pairs and public keys on BearSSL, libsodium's crypto_kx, the ChaCha20-Poly1305 AEADs, libsodium's secret boxes, boxes and sealed boxes, a random_device on the system's generator and a constant-time equal, each over a widely used, reviewed C library (BearSSL, OpenSSL, ctaes, libsecp256k1, libsodium) that the program names in its Jamfile. Hashing and HMAC are Boost.Hash2's; HKDF and password hashing are webcpp::hash's. Every failure is a boost::system::result value. Protocols (Bitcoin, Ethereum, Nostr) belong to domain libraries built on these primitives. +> Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA and recoverable signatures, ECDH, tweaks, ElligatorSwift, MuSig2, silent payments), Ed25519 and Ed25519ph (RFC 8032), X25519 (RFC 7748), their keys in SPKI, PKCS#8 (RFC 8410) and PEM, P-256 key pairs, ECDSA and ECDH on BearSSL, libsodium's crypto_kx, the ChaCha20-Poly1305 AEADs, libsodium's secret boxes, boxes and sealed boxes, a random_device on the system's generator and a constant-time equal, each over a widely used, reviewed C library (BearSSL, OpenSSL, ctaes, libsecp256k1, libsodium) that the program names in its Jamfile. Hashing and HMAC are Boost.Hash2's; HKDF and password hashing are webcpp::hash's. Every failure is a boost::system::result value. Protocols (Bitcoin, Ethereum, Nostr) belong to domain libraries built on these primitives. Generated by doc/tables/generate.py with the page's tables. Page: https://webcpporg.github.io/libs/crypto/ @@ -184,6 +184,8 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - from_der: Decodes a strict DER signature to its raw form: only the encoding `to_der` writes is accepted. - normalize_ecdsa: The low-S form of a signature: s replaced by n - s when s is above (n - 1) / 2, returned unchanged otherwise. - check_low_s: Checks that a signature is in its low-S form, s at most (n - 1) / 2, as a protocol that requires low S checks what it receives. +- [curves::p256::keypair::ecdh_x](https://webcpporg.github.io/libs/crypto/#crypto-p256-ecdh): ECDH with a validated public key: the shared point's raw x coordinate, 32 bytes in a `secret<32>`, as WebCrypto's `deriveBits` gives it; a protocol hashes it into its keys. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten. Default: BearSSL on native, wasip2, wasip3, emscripten. Use it to: agree on a key with a browser's WebCrypto (ECDH on P-256, deriveBits), then derive the session's keys with HKDF, as webcpp::trystero's peers do. + - ecdh_x: ECDH with a peer's public key: the x coordinate of the shared point d * Q, raw, as WebCrypto's `deriveBits` with ECDH on P-256 gives its 256 bits. ## webcpp::crypto::hybrid @@ -298,6 +300,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [Share a file with someone known only by a public key, as a file-sharing app does](https://webcpporg.github.io/libs/crypto/#crypto-everyday-files): `ciphers::secretbox<>` for the file under a key drawn for it, `hybrid::sealed_box::seal` for that key (webcpp::crypto); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//secretbox_xsalsa20poly1305-default /webcpp/crypto//sealed_box-default /webcpp/crypto//x25519-default. Example: example/file_share.cpp. - [Make and keep a P-256 key pair, and import a browser's public key (WebCrypto's raw form), as webcpp::trystero's peers do](https://webcpporg.github.io/libs/crypto/#crypto-p256-keys): `keypair::make`, `keypair::generate`, `keypair::public_key`, `keypair::secret_scalar`, `public_key::make` (webcpp::crypto::curves::p256); backend BearSSL; Jamfile /webcpp/crypto//crypto /webcpp/crypto//p256-default. Example: example/p256_keys.cpp. - [Sign what a browser's WebCrypto verifies and verify what it signs (ECDSA on P-256 with SHA-256), low S where a protocol requires it, as webcpp::trystero's handshakes](https://webcpporg.github.io/libs/crypto/#crypto-p256-ecdsa): `keypair::sign_ecdsa`, `verify_ecdsa`, `normalize_ecdsa`, `check_low_s`; `to_der`, `from_der` for X.509 (webcpp::crypto::curves::p256); backend BearSSL; Jamfile /webcpp/crypto//crypto /webcpp/crypto//p256-default. Example: example/p256_sign.cpp. +- [Agree on a key with a browser's WebCrypto (ECDH on P-256, deriveBits), then derive the session's keys with HKDF, as webcpp::trystero's peers do](https://webcpporg.github.io/libs/crypto/#crypto-p256-ecdh): `keypair::ecdh_x`; `webcpp::hash::hkdf` for the keys (webcpp::crypto::curves::p256); backend BearSSL; Jamfile /webcpp/crypto//crypto /webcpp/crypto//p256-default. Example: example/p256_ecdh.cpp. ## Examples @@ -321,6 +324,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - example/musig_wallet.cpp: A wallet split across two devices, a phone and a laptop, whose coins move only when both sign (BIP 327's MuSig2): the two public keys are sorted and aggregated into one; each device makes a nonce and sends its public half; each signs its part once every public nonce is in; the parts add up to one BIP 340 signature under the one x-only key, which on the chain looks like any single signer's. The devices' secrets are fixed here, so that the program runs the same each time; a real wallet draws them from crypto's random device. The nonces are fresh in every run, drawn inside nonce_gen; nothing random is printed. - example/openssl_memory.cpp: Sends every allocation of OpenSSL's to the program's own memory resource, natively, then seals and opens one block with AES-256-GCM on OpenSSL, on a worker thread as an audio engine's or a server's would. Built with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE, /webcpp/crypto//openssl and threads (example/Jamfile). - example/order_reference.cpp: Turns a sequential order id into an opaque 16-byte reference with the raw AES block cipher, and back. Customers then cannot guess other orders' numbers. This is NOT authenticated encryption: a forged reference still decrypts, to garbage, so the program checks the padding. +- example/p256_ecdh.cpp: Two P-256 key pairs, made from fixed scalars, agree on the shared point's raw x coordinate with ecdh_x, the 256 bits WebCrypto's deriveBits gives with ECDH on P-256; then HKDF-SHA-256 of that x, with webcpp::hash, derives the 32-byte key a protocol would encrypt with. The x coordinate is not a key: the derivation, its salt and its info are the protocol's. Cross-checked by hand once with OpenSSL 4.1.0 (2026-11-21), each scalar s (32 bytes of 11, then of 22) written as SEC 1's ECPrivateKey on prime256v1: echo 30310201010420${s}a00a06082a8648ce3d030107 | xxd -r -p > alice.der openssl ec -inform DER -in alice.der -out alice.pem (likewise bob) openssl pkey -in bob.pem -pubout -out bob_public.pem openssl pkeyutl -derive -inkey alice.pem -peerkey bob_public.pem | xxd -p -c 64 openssl kdf -keylen 32 -kdfopt digest:SHA256 -kdfopt hexkey: -kdfopt salt:"example salt" -kdfopt info:"example chat v1 key" HKDF (one line) which print the x and the key of p256_ecdh.expected. - example/p256_keys.cpp: Makes a P-256 key pair from RFC 6979's key, prints its public key as the 65 bytes WebCrypto's exportKey("raw") gives, keeps its scalar and makes the same key pair from it again, then imports that public key as a peer's and refuses the same bytes with one bit changed. Draws a fresh key pair too, whose bytes differ on every run and are not printed. - example/p256_sign.cpp: Signs the SHA-256 digest of "sample" with RFC 6979's P-256 key and prints the signature, the RFC's own bytes, in the raw form WebCrypto uses; then its low-S form, which a protocol that requires low S sends, and its DER encoding, which X.509 carries; and verifies both forms with the public key alone, and refuses the digest of another message. - example/recover_signer.cpp: Finds who signed a message without being sent their key, as Ethereum finds a transaction's signer: a wallet signs a message's hash with a recoverable signature, and a reader that holds no key recovers the signer's public key from the signature and the hash, then compares it with the key the wallet published. Recovery always finds some key, so the comparison is the check: a changed message recovers another key. diff --git a/doc/p256.adoc b/doc/p256.adoc index fb6ee791..7343276b 100644 --- a/doc/p256.adoc +++ b/doc/p256.adoc @@ -195,3 +195,80 @@ signature arrives in DER Web Authentication, section 6.5.5]): `from_der`, then `verify_ecdsa` of the SHA-256 of what the authenticator signed. Reading the COSE key and building those signed bytes are WebAuthn's, and stay outside crypto. + +[#crypto-p256-ecdh] +==== ECDH + +Two peers that have exchanged public keys, a program and a browser for +instance, agree on a secret that nobody who saw only the public keys can +compute, and key their encryption with it: that is elliptic-curve +Diffie-Hellman, ECDH (link:https://www.secg.org/sec1-v2.pdf[SEC 1, section +3.3.1]). Each side multiplies the other's public point by its own scalar, and +both arrive at the same point, d~A~ times d~B~ times the generator. +`keypair::ecdh_x(peer)` returns that point's x coordinate, 32 bytes big-endian, +as a `secret<32>`, which wipes itself: + +[source,cpp] +---- +include::{examples}/p256_ecdh.cpp[tag=agree,indent=0] +---- + +The raw x is exactly what a browser's WebCrypto gives: +`+deriveBits({name: "ECDH", public: peerKey}, privateKey, 256)+` returns the +shared point's x coordinate, 256 bits +(link:https://www.w3.org/TR/WebCryptoAPI/#ecdh-operations[W3C, ECDH's +operations]), so a program and a browser that hash it the same way derive the +same keys. The peer's key is a `public_key`, validated when it was made, so +`ecdh_x` never sees a point off the curve; it refuses a moved-from key pair +with `invalid_state`. + +The x coordinate is not a key. A Diffie-Hellman value is not uniformly random +(link:https://www.rfc-editor.org/rfc/rfc5869#section-3.3[RFC 5869, section +3.3]): it is always below the field prime and always the x of a point of the +curve, which not every 32-byte value is, so its 256 bits hold less than 256 +bits of entropy. A protocol hashes it into its keys, with a key derivation +function such as HKDF (link:https://www.rfc-editor.org/rfc/rfc5869[RFC 5869]), +which webcpp::hash provides, and with the salt and the info the protocol names: + +[source,cpp] +---- +include::{examples}/p256_ecdh.cpp[tag=derive,indent=0] +---- + +crypto offers no hashed form, as secp256k1's `ecdh` is +(<>): no browser computes one, and the derivation, its +hash, its salt and its info belong to the protocol, not to the primitive. A +program that hashed the point some other way would agree with no WebCrypto +peer. + +include::generated/backends-p256_ecdh.adoc[] + +*Example.* Two key pairs made from fixed scalars agree on the shared x, and +HKDF-SHA-256 derives a 32-byte key from it; the values match OpenSSL's for the +same two scalars: + +[source,cpp] +---- +include::{examples}/p256_ecdh.cpp[tag=program] +---- + +[listing] +---- +include::{examples}/p256_ecdh.expected[] +---- + +*Pitfalls.* + +* Using the x coordinate as an AES key directly. Its bits are not uniform, so +the key is weaker than 256 bits, and it is the same key in every protocol and +every session that uses the same two key pairs that way: a key that leaks from +one leaks from all of them. Hash it with HKDF and the protocol's own info into +one key per purpose. +* Two sides must derive the same way. A program that hashes the x with another +salt, info or hash than its browser peer derives another key, and every message +fails to open with nothing pointing at the cause: read the protocol's +derivation, byte for byte. +* A `deriveBits` length below 256 in the browser gives the first bits of the x +alone (link:https://www.w3.org/TR/WebCryptoAPI/#ecdh-operations[W3C, ECDH's +operations]); the program then takes the same leading bytes of what `ecdh_x` +returns, or the two sides hash different inputs. diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 3e0f5260..948a5984 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -1,7 +1,7 @@ { "comment": "The data of crypto's generated tables and of llms.txt; doc/tables/generate.py reads it with the test Jamfiles, the message tests and the superproject's Jamfile fixtures, and writes doc/generated/, doc/llms.txt, include/webcpp/crypto/detail/capabilities.hpp, include/webcpp/crypto/detail/defaults.hpp and test/capabilities_test.cpp. The capability table is `families`: per family its algorithms, the targets on which each backend has it (each claimed only where a test of the family's operations on that backend runs), constant time per target where it differs from the backend's own `constant_time` (X25519 on wasip2, an open finding, and natively without arm64's DIT, the cause of both), with `constant_time_checker` naming the checker that measured it where that is not every checker of the target, and the default per target, one whatever the program links (design D32), with its reason and the tests that fix it (a row of some of `compilers` restates its target's default for them, with a reason of their own, and each compiler of a target has one row), from which come include/webcpp/crypto/detail/defaults.hpp and the refusal that says what a program whose default is not linked needs; a backend with `targets`, where it is built, is a tag of `backends`. A name in a text is written between backticks, as Markdown writes code: the tables show it as code and llms.txt keeps the backticks. A comparison table's cell {speed:} or {constant_time:} is written from doc/performance.json or from the family's `constant_time`, and each cell of a column a namespace lists in `cited` cites a source or begins with \"none\". Edit this file, then run python3 libs/crypto/doc/tables/generate.py; the doc build runs it with --check.", "page": "https://webcpporg.github.io/libs/crypto/", - "llms": "Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA and recoverable signatures, ECDH, tweaks, ElligatorSwift, MuSig2, silent payments), Ed25519 and Ed25519ph (RFC 8032), X25519 (RFC 7748), their keys in SPKI, PKCS#8 (RFC 8410) and PEM, P-256 key pairs and public keys on BearSSL, libsodium's crypto_kx, the ChaCha20-Poly1305 AEADs, libsodium's secret boxes, boxes and sealed boxes, a random_device on the system's generator and a constant-time equal, each over a widely used, reviewed C library (BearSSL, OpenSSL, ctaes, libsecp256k1, libsodium) that the program names in its Jamfile. Hashing and HMAC are Boost.Hash2's; HKDF and password hashing are webcpp::hash's. Every failure is a boost::system::result value. Protocols (Bitcoin, Ethereum, Nostr) belong to domain libraries built on these primitives.", + "llms": "Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA and recoverable signatures, ECDH, tweaks, ElligatorSwift, MuSig2, silent payments), Ed25519 and Ed25519ph (RFC 8032), X25519 (RFC 7748), their keys in SPKI, PKCS#8 (RFC 8410) and PEM, P-256 key pairs, ECDSA and ECDH on BearSSL, libsodium's crypto_kx, the ChaCha20-Poly1305 AEADs, libsodium's secret boxes, boxes and sealed boxes, a random_device on the system's generator and a constant-time equal, each over a widely used, reviewed C library (BearSSL, OpenSSL, ctaes, libsecp256k1, libsodium) that the program names in its Jamfile. Hashing and HMAC are Boost.Hash2's; HKDF and password hashing are webcpp::hash's. Every failure is a boost::system::result value. Protocols (Bitcoin, Ethereum, Nostr) belong to domain libraries built on these primitives.", "targets": ["native", "wasip2", "wasip3", "emscripten"], "compilers": {"clang": "Clang", "gcc": "GCC", "msvc": "MSVC"}, "checkers": {"memcheck": "Valgrind's memcheck (Linux)", "msan": "MemorySanitizer (Linux, clang)", "dudect": "dudect (judged off the runners GitHub hosts)"}, @@ -46,6 +46,7 @@ "ieee1363": ["IEEE 1363-2000, Standard Specifications for Public-Key Cryptography: a signature as the two integers r and s, each at the order's length", "https://standards.ieee.org/ieee/1363/2049/"], "rfc3279": ["RFC 3279, section 2.2.3: an ECDSA signature in X.509, the DER of a SEQUENCE of the INTEGERs r and s", "https://www.rfc-editor.org/rfc/rfc3279#section-2.2.3"], "rfc7518": ["RFC 7518, section 3.4: JWS's ES256 signature is r and s, 32 bytes each, not DER", "https://www.rfc-editor.org/rfc/rfc7518#section-3.4"], + "webcrypto-ecdh": ["W3C Web Cryptography API, ECDH's deriveBits: the shared point's x coordinate, its first length bits", "https://www.w3.org/TR/WebCryptoAPI/#ecdh-operations"], "trystero": ["Trystero 0.27.0's crypto.ts: its ECDSA P-256 signatures normalized to low S when made and refused unless low S when read", "https://github.com/dmotz/trystero/blob/0.27.0/packages/core/src/crypto.ts"], "bearssl-ct": ["BearSSL, constant-time crypto", "https://www.bearssl.org/constanttime.html"], "bearssl-ctmul": ["BearSSL, constant-time multiplications", "https://www.bearssl.org/ctmul.html"], @@ -693,6 +694,20 @@ "bearssl": {"tests": ["p256_ecdsa_bearssl", "p256_wycheproof_bearssl", "allocation_bearssl"]}, "sodium": {"refused": "p256_on_sodium"} } + }, + { + "id": "p256_ecdh", + "family": "p256", + "functions": ["basic_keypair::ecdh_x"], + "namespace": "curves", + "api": "curves::p256::keypair::ecdh_x", + "header": "", + "what": "ECDH with a validated public key: the shared point's raw x coordinate, 32 bytes in a `secret<32>`, as WebCrypto's `deriveBits` gives it; a protocol hashes it into its keys.", + "section": "crypto-p256-ecdh", + "backends": { + "bearssl": {"tests": ["p256_ecdh_bearssl", "allocation_bearssl"]}, + "sodium": {"refused": "p256_on_sodium"} + } } ], "families": [ @@ -1031,7 +1046,7 @@ {"name": "p256", "title": "P-256", "type": "curves::p256::basic_keypair<{backend}>"} ], "default": [ - {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "bearssl", "tests": ["p256_keys_bearssl", "p256_ecdsa_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"} + {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "bearssl", "tests": ["p256_keys_bearssl", "p256_ecdsa_bearssl", "p256_ecdh_bearssl", "default_backend_none_linked"], "why": "the one backend of the P-curves on all four targets, constant time by design and allocating nothing ({bearssl}); OpenSSL and Botan join in increments 8 and 7"} ], "backends": { "bearssl": {"targets": "all"} @@ -1104,7 +1119,7 @@ ["`secp256k1`", "BIP 340 Schnorr and ECDSA signatures, recoverable signatures, ECDH in three forms, tweaks, ElligatorSwift, MuSig2, silent payments, SPKI and PKCS#8", "about 128 bits ({sec2})", "secret 32 bytes; public 33 bytes compressed, 65 bytes uncompressed ({sec1}), 32 bytes x-only, 64 bytes as ElligatorSwift ({bip324}); SPKI 56 or 88 bytes ({rfc5480}), PKCS#8 135 bytes ({rfc5208}, {rfc5915})", "64 bytes, MuSig2's aggregate too ({bip327}); 65 bytes recoverable; ECDSA in DER up to 72", "{speed:secp256k1}", "{constant_time:secp256k1}", "{sec2}, {bip340}, {rfc6979}, {bip324}, {bip327}, {bip352}", "Bitcoin ({bip340}), Ethereum ({ethereum}), Nostr ({nip01})", "no: WebCrypto offers P-256, P-384, P-521, Ed25519 and X25519, not secp256k1 ({webcrypto})", "Bitcoin's keys and signatures; Nostr's event signatures ({nip01}); Ethereum's ECDSA verification with a known key; ECDH in the raw x-coordinate form of Nostr's encrypted messages ({nip44}); Ethereum's recoverable signatures and uncompressed keys ({ethereum}), the address hashing being a domain library's; BIP 32's tweaks of the full key, its derivation of the tweak being a domain library's ({bip32}); keys exchanged with OpenSSL as SPKI or PKCS#8 ({rfc5480}, {rfc5915}), in DER or PEM ({rfc7468}); Bitcoin's version 2 transport, whose keys are ElligatorSwift encodings ({bip324}); MuSig2's multisignatures ({bip327}); silent payments ({bip352}), the addresses and transactions being a domain library's"], ["`ed25519`", "Ed25519 signatures, and Ed25519ph over SHA-512 for a message given in pieces; the X25519 secret key of a key pair", "about 128 bits ({rfc8032})", "secret 32 bytes (the seed); public 32 bytes", "64 bytes", "{speed:ed25519}", "{constant_time:ed25519}", "{rfc8032}, {fips186-5}", "SSH keys ({rfc8709}), Signal's signatures on its Curve25519 keys ({signal-xeddsa}), Tor's identity keys ({tor-cert-spec}), Solana's accounts ({solana-accounts})", "yes: Ed25519 ({webcrypto})", "SSH, Tor and Solana keys and signatures, and any protocol that names RFC 8032's Ed25519 or Ed25519ph; verification is strict (libsodium's rules), which some lenient verifiers are not. Not Bitcoin, Ethereum or Nostr, whose keys are secp256k1's"], ["`x25519`", "Key agreement (Diffie-Hellman on Curve25519): two parties who exchanged public keys share a 32-byte secret; `kx_keypair`, libsodium's `crypto_kx`, gives a client and a server a session key for each direction", "about 128 bits ({rfc7748})", "secret 32 bytes; public 32 bytes", "none: no signatures", "{speed:x25519}", "{constant_time:x25519}", "{rfc7748}", "TLS 1.3 ({rfc8446-groups}), SSH ({rfc8731}), WireGuard ({wireguard}), Signal ({x3dh})", "yes: X25519 ({webcrypto})", "TLS 1.3's and SSH's key exchange, WireGuard, Signal; libsodium's `crypto_box` keys, and the session keys of `crypto_kx` with `kx_keypair` ({libsodium-kx}). The Ed25519 public key of a peer converts with `curves::ed25519::to_x25519_public`. A shared secret goes through a KDF before it keys a cipher. Every case of Wycheproof's X25519 file is tested ({wycheproof})"], - ["`p256`", "Key pairs made from a 32-byte scalar or drawn from `random_device`, public keys validated once, as SEC 1's uncompressed point or two coordinates, and ECDSA over a SHA-256 digest with RFC 6979's nonce, raw and DER, and low S checked or normalized", "about 128 bits ({sec2})", "secret 32 bytes (the scalar); public 65 bytes uncompressed ({sec1})", "ECDSA: 64 bytes, r and s ({ieee1363}); in DER up to 72 ({rfc3279})", "{speed:p256}", "{constant_time:p256}", "{fips186-5}, {sec2}, {sec1}, {rfc6979}", "passkeys' ES256 ({webauthn}), TLS 1.3 ({rfc8446-groups})", "yes: P-256, for ECDSA and ECDH ({webcrypto})", "Browsers' WebCrypto, whose raw export of a P-256 public key is the uncompressed point `public_key::make` takes ({webcrypto}); passkeys and TLS. Not Bitcoin, Ethereum or Nostr, whose keys are secp256k1's"] + ["`p256`", "Key pairs made from a 32-byte scalar or drawn from `random_device`, public keys validated once, as SEC 1's uncompressed point or two coordinates, ECDSA over a SHA-256 digest with RFC 6979's nonce, raw and DER, and low S checked or normalized, and ECDH's raw x coordinate", "about 128 bits ({sec2})", "secret 32 bytes (the scalar); public 65 bytes uncompressed ({sec1})", "ECDSA: 64 bytes, r and s ({ieee1363}); in DER up to 72 ({rfc3279})", "{speed:p256}", "{constant_time:p256}", "{fips186-5}, {sec2}, {sec1}, {rfc6979}", "passkeys' ES256 ({webauthn}), TLS 1.3 ({rfc8446-groups})", "yes: P-256, for ECDSA and ECDH ({webcrypto})", "Browsers' WebCrypto, whose raw export of a P-256 public key is the uncompressed point `public_key::make` takes ({webcrypto}) and whose ECDH `deriveBits` is the raw x `ecdh_x` gives ({webcrypto-ecdh}); passkeys and TLS. Not Bitcoin, Ethereum or Nostr, whose keys are secp256k1's"] ] }, "hybrid": { @@ -1153,7 +1168,8 @@ {"need": "Let anyone send a message that only the recipient can read, without saying who sent it (anonymous feedback, a drop box)", "namespace": "webcpp::crypto::hybrid", "api": "`sealed_box::seal`, `sealed_box::open`", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//sealed_box-default", "example": "file_share", "section": "crypto-sealed-box"}, {"need": "Share a file with someone known only by a public key, as a file-sharing app does", "namespace": "webcpp::crypto", "api": "`ciphers::secretbox<>` for the file under a key drawn for it, `hybrid::sealed_box::seal` for that key", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//secretbox_xsalsa20poly1305-default /webcpp/crypto//sealed_box-default /webcpp/crypto//x25519-default", "example": "file_share", "section": "crypto-everyday-files"}, {"need": "Make and keep a P-256 key pair, and import a browser's public key (WebCrypto's raw form), as webcpp::trystero's peers do", "namespace": "webcpp::crypto::curves::p256", "api": "`keypair::make`, `keypair::generate`, `keypair::public_key`, `keypair::secret_scalar`, `public_key::make`", "backend": "BearSSL", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//p256-default", "example": "p256_keys", "section": "crypto-p256-keys"}, - {"need": "Sign what a browser's WebCrypto verifies and verify what it signs (ECDSA on P-256 with SHA-256), low S where a protocol requires it, as webcpp::trystero's handshakes", "namespace": "webcpp::crypto::curves::p256", "api": "`keypair::sign_ecdsa`, `verify_ecdsa`, `normalize_ecdsa`, `check_low_s`; `to_der`, `from_der` for X.509", "backend": "BearSSL", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//p256-default", "example": "p256_sign", "section": "crypto-p256-ecdsa"} + {"need": "Sign what a browser's WebCrypto verifies and verify what it signs (ECDSA on P-256 with SHA-256), low S where a protocol requires it, as webcpp::trystero's handshakes", "namespace": "webcpp::crypto::curves::p256", "api": "`keypair::sign_ecdsa`, `verify_ecdsa`, `normalize_ecdsa`, `check_low_s`; `to_der`, `from_der` for X.509", "backend": "BearSSL", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//p256-default", "example": "p256_sign", "section": "crypto-p256-ecdsa"}, + {"need": "Agree on a key with a browser's WebCrypto (ECDH on P-256, deriveBits), then derive the session's keys with HKDF, as webcpp::trystero's peers do", "namespace": "webcpp::crypto::curves::p256", "api": "`keypair::ecdh_x`; `webcpp::hash::hkdf` for the keys", "backend": "BearSSL", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//p256-default", "example": "p256_ecdh", "section": "crypto-p256-ecdh"} ], "fixtures": { "web": "A web application: AES-256-GCM on BearSSL, the default on WebAssembly.", diff --git a/example/Jamfile b/example/Jamfile index 98a085a4..16ed7034 100644 --- a/example/Jamfile +++ b/example/Jamfile @@ -122,6 +122,9 @@ webcpp.example p256_keys.cpp : /webcpp/crypto//p256-default ; # The guide's P-256 ECDSA program: RFC 6979's signature of "sample", its low-S # form and its DER, both forms verified and another digest refused. webcpp.example p256_sign.cpp : /webcpp/crypto//p256-default ; +# The guide's P-256 ECDH program: two key pairs from fixed scalars agree on the +# shared x coordinate, then HKDF-SHA-256 derives a key from it. +webcpp.example p256_ecdh.cpp : /webcpp/crypto//p256-default ; # The guide's X25519 program: RFC 7748's Alice and Bob, the agreement of two # Ed25519 key pairs through their X25519 forms, and a peer of low order diff --git a/example/p256_ecdh.cpp b/example/p256_ecdh.cpp new file mode 100644 index 00000000..db029c5c --- /dev/null +++ b/example/p256_ecdh.cpp @@ -0,0 +1,110 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Two P-256 key pairs, made from fixed scalars, agree on the shared point's raw x coordinate with +// ecdh_x, the 256 bits WebCrypto's deriveBits gives with ECDH on P-256; then HKDF-SHA-256 of that +// x, with webcpp::hash, derives the 32-byte key a protocol would encrypt with. The x coordinate is +// not a key: the derivation, its salt and its info are the protocol's. +// +// Cross-checked by hand once with OpenSSL 4.1.0 (2026-11-21), each scalar s (32 bytes of 11, then +// of 22) written as SEC 1's ECPrivateKey on prime256v1: +// echo 30310201010420${s}a00a06082a8648ce3d030107 | xxd -r -p > alice.der +// openssl ec -inform DER -in alice.der -out alice.pem (likewise bob) +// openssl pkey -in bob.pem -pubout -out bob_public.pem +// openssl pkeyutl -derive -inkey alice.pem -peerkey bob_public.pem | xxd -p -c 64 +// openssl kdf -keylen 32 -kdfopt digest:SHA256 -kdfopt hexkey: +// -kdfopt salt:"example salt" -kdfopt info:"example chat v1 key" HKDF (one line) +// which print the x and the key of p256_ecdh.expected. +// tag::program[] +#include +#include +#include + +#include + +#include + +#include +#include +#include +#include +#include +#include + +namespace crypto = webcpp::crypto; +namespace p256 = webcpp::crypto::curves::p256; + +namespace { + +// Prints bytes in hex after a name. +void print(char const* name, std::span bytes) { + std::printf("%s ", name); + for (std::uint8_t const octet : bytes) { + std::printf("%02x", static_cast(octet)); + } + std::printf("\n"); +} + +// A text's bytes. +std::span bytes_of(std::string_view text) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): a text's bytes + return {reinterpret_cast(text.data()), text.size()}; +} + +// A key pair whose scalar is one byte repeated: a fixed value, so that the output is fixed. A real +// program draws its key pair with keypair::generate(). +boost::system::result from_byte(std::uint8_t fill) { + std::array scalar{}; + scalar.fill(fill); + return p256::keypair::make(scalar); +} + +} // namespace + +int main() { + auto const alice = from_byte(0x11); + auto const bob = from_byte(0x22); + if (!alice || !bob) { + std::printf("failed\n"); + return 1; + } + // Each side sends its public key, the 65 bytes of WebCrypto's exportKey("raw"), and makes the + // other's into a public_key, which checks the point once. + auto const alice_public = alice->public_key(); + auto const bob_public = bob->public_key(); + if (!alice_public || !bob_public) { + std::printf("failed\n"); + return 1; + } + // tag::agree[] + // Each side combines its key pair with the other's public key: the same x, a secret<32>. + auto const alice_x = alice->ecdh_x(*bob_public); + auto const bob_x = bob->ecdh_x(*alice_public); + // end::agree[] + if (!alice_x || !bob_x || !crypto::equal(alice_x->bytes(), bob_x->bytes())) { + std::printf("failed\n"); + return 1; + } + std::printf("shared x both sides agree\n"); + // A real program never prints a shared secret; this one does to show the fixed value. + print("x ", alice_x->bytes()); + + // tag::derive[] + // The x is hashed into the key: HKDF-SHA-256 (RFC 5869) with the protocol's salt and info. + crypto::secret<32> key; + auto const derived = webcpp::hash::hkdf( + key.writable(), bytes_of("example salt"), alice_x->bytes(), + bytes_of("example chat v1 key")); + // end::derive[] + if (!derived) { + std::printf("failed\n"); + return 1; + } + print("HKDF key ", key.bytes()); + return 0; +} + +// end::program[] diff --git a/example/p256_ecdh.expected b/example/p256_ecdh.expected new file mode 100644 index 00000000..da50c02d --- /dev/null +++ b/example/p256_ecdh.expected @@ -0,0 +1,3 @@ +shared x both sides agree +x ccfc261f58193c98ca4ad4a53bbac6f0ee29bc4d48438090446908622ca79af6 +HKDF key ad3dab9fea26c3593d70ea9271f745810814aaf7a0ba9feefcf00548a6df3cf9 diff --git a/include/webcpp/crypto/backends/bearssl.hpp b/include/webcpp/crypto/backends/bearssl.hpp index c4ce614d..2c732eb6 100644 --- a/include/webcpp/crypto/backends/bearssl.hpp +++ b/include/webcpp/crypto/backends/bearssl.hpp @@ -432,7 +432,8 @@ struct p_curve_state { /** * P-256 on BearSSL: the point of a key pair computed once by `mulgen`, a public point checked - * by BearSSL's decoding, ECDSA with RFC 6979's nonce and its DER conversions. BearSSL allocates + * by BearSSL's decoding, ECDSA with RFC 6979's nonce and its DER conversions, ECDH's raw x + * coordinate. BearSSL allocates * nothing; its curve code never fails on a valid input. */ template <> @@ -509,6 +510,38 @@ struct p_curve_engine { return {}; } + /** + * ECDH: the peer's point multiplied by the scalar, and the product's x coordinate. + * + * @param keyed A keyed state. + * @param peer The peer's uncompressed point, valid (its public key was made by BearSSL's + * decoding). + * @param output 32 bytes, a `secret<32>`'s. + * @return Nothing; `backend_failure`, which a valid point and a scalar in range cannot cause. + */ + [[nodiscard]] static boost::system::result ecdh_x( + state const& keyed, std::span peer, + std::span output) noexcept { + WEBCPP_CRYPTO_DETAIL_P_CURVE_ENGINE_ENTERED(); + read_canary(WEBCPP_CRYPTO_DETAIL_BEARSSL_CANARY); + // BearSSL multiplies in place: the copy becomes d * Q, uncompressed, and is wiped after. + std::array shared{}; + std::ranges::copy(peer, shared.begin()); + std::uint32_t const multiplied = + bearssl_p256()->mul(shared.data(), shared.size(), keyed.scalar.data(), + keyed.scalar.size(), BR_EC_secp256r1); + if (multiplied != 1) { + wipe_object(shared); + return error::backend_failure; // a validated point and a scalar in range never fail + } + std::size_t x_size = 0; + std::size_t const x_offset = bearssl_p256()->xoff(BR_EC_secp256r1, &x_size); + std::ranges::copy(std::span(shared).subspan(x_offset, x_size), + output.begin()); + wipe_object(shared); + return {}; + } + /** * Verifies an ECDSA signature; a high S is accepted (design D36). * diff --git a/include/webcpp/crypto/curves/p256.hpp b/include/webcpp/crypto/curves/p256.hpp index 6fa88f99..4b85f691 100644 --- a/include/webcpp/crypto/curves/p256.hpp +++ b/include/webcpp/crypto/curves/p256.hpp @@ -8,7 +8,8 @@ P-256, NIST's curve of FIPS 186-5 (secp256r1): a key pair made from its 32-byte scalar or drawn from the system's generator, and a public key validated once, as SEC 1's uncompressed point; ECDSA over a SHA-256 digest with RFC 6979's nonce, its raw and DER forms, and low S as two - functions, one that normalizes and one that checks. + functions, one that normalizes and one that checks; ECDH's shared point's raw x coordinate, as + WebCrypto's `deriveBits` gives it. The family's default backend, BearSSL on every target, is included when the program links it; a program that uses the family without linking it stops where it calls it, with the Jamfile @@ -304,6 +305,32 @@ class basic_keypair { return signature; } + /** + * ECDH with a peer's public key: the x coordinate of the shared point d * Q, raw, as + * WebCrypto's `deriveBits` with ECDH on P-256 gives its 256 bits. + * + * The x coordinate is not a key: its bits are not uniform. A protocol hashes it into its keys, + * with HKDF for instance; the derivation, its salt and its info are the protocol's. + * + * @param peer The peer's public key, validated when it was made. + * @return 32 secret bytes, big-endian; `invalid_state` moved from; `backend_failure`, which a + * valid key pair and a valid public key cannot cause. + */ + [[nodiscard]] boost::system::result> ecdh_x( + basic_public_key const& peer) const noexcept { + detail::timing_guard const timing; + if (!keyed_) { + return error::invalid_state; + } + secret shared; + auto const derived = + engine::ecdh_x(state_, detail::p_curve_access::point(peer), shared.writable()); + if (!derived) { + return derived.error(); + } + return shared; + } + private: basic_keypair() noexcept = default; @@ -477,6 +504,12 @@ struct p_curve_engine { return error::backend_failure; } + /** Never called; fails closed. */ + template + [[nodiscard]] static boost::system::result ecdh_x(Arguments&&... /*arguments*/) noexcept { + return error::backend_failure; + } + /** Never called; fails closed. */ template [[nodiscard]] static bool verify(Arguments&&... /*arguments*/) noexcept { diff --git a/test/Jamfile b/test/Jamfile index bf80280c..bf9001ee 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -385,6 +385,11 @@ crypto-run p256_ecdsa_bearssl : p256_ecdsa_bearssl_test.cpp : /third_pa crypto-run p256_wycheproof_bearssl : p256_wycheproof_bearssl_test.cpp : /third_party//bearssl /third_party//wycheproof /webcpp//boost_json ; +# P-256 ECDH on BearSSL, the raw x: two sides agree, the algebra's fixed points, +# Wycheproof's ECDH vectors on points, a moved-from key pair. +crypto-run p256_ecdh_bearssl : p256_ecdh_bearssl_test.cpp + : /third_party//bearssl /third_party//wycheproof + /webcpp//boost_json ; # The backend ctaes: the AES block cipher alone, on every target; FIPS-197 only # (ruling R5). crypto-run aes_ctaes : aes_ctaes_test.cpp : /third_party//ctaes ; diff --git a/test/allocation_bearssl_test.cpp b/test/allocation_bearssl_test.cpp index 540f151a..7bd1c284 100644 --- a/test/allocation_bearssl_test.cpp +++ b/test/allocation_bearssl_test.cpp @@ -35,7 +35,7 @@ namespace { // P-256's functions, each called once: the key pair's make and generate, the public key's two -// make, and ECDSA's six. +// make, ECDSA's six and ECDH's ecdh_x. void p256_calls() { namespace crypto = webcpp::crypto; namespace p256 = crypto::curves::p256; @@ -65,6 +65,7 @@ void p256_calls() { } BOOST_TEST(p256::normalize_ecdsa(*signature).has_value()); BOOST_TEST(p256::check_low_s(data::rfc6979_test).has_value()); + BOOST_TEST(pair->ecdh_x(*key).has_value()); } } // namespace diff --git a/test/p256_ecdh_bearssl_test.cpp b/test/p256_ecdh_bearssl_test.cpp new file mode 100644 index 00000000..bca63fd3 --- /dev/null +++ b/test/p256_ecdh_bearssl_test.cpp @@ -0,0 +1,384 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// P-256 ECDH on BearSSL, the shared point's raw x coordinate as WebCrypto's deriveBits gives it: +// two sides agree, 100 times, on key pairs drawn from a printed seed that a define replays; +// fixed points of the algebra, with no table: d * (d * G) is the public point of d * d mod n, +// and d * (2 * G) the public point of 2 * d mod n, those scalars computed in the test by byte +// arithmetic; Wycheproof's ECDH vectors on points (every case: valid ones agree, invalid ones are +// refused, and the compressed points BearSSL does not decode are listed refusals); a moved-from +// key pair; the output's type. + +#include +#include +#include +#include +#include + +#include "support/hex.hpp" +#include "support/p256_data.hpp" +#include "support/test_data.hpp" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace crypto = webcpp::crypto; +namespace p256 = webcpp::crypto::curves::p256; +namespace data = webcpp::test::p256; +namespace test = webcpp::test; +namespace json = boost::json; + +using crypto::error; +using p256::keypair; +using p256::public_key; +using scalar = std::array; + +// The seed of the drawn key pairs: drawn on each run and printed; a run is replayed by building +// with the printed value, define=WEBCPP_TEST_P256_SEED= on b2's command line, with -a or a +// build directory of its own, since a define alone does not make b2 build the test again. +std::uint64_t random_seed() { +#ifdef WEBCPP_TEST_P256_SEED + return WEBCPP_TEST_P256_SEED; +#else + return std::random_device{}(); +#endif +} + +// A key pair from the generator: a scalar make refuses (0, or not below n) is drawn again. +keypair draw(std::mt19937_64& generator) { + for (;;) { + scalar drawn{}; + std::ranges::generate(drawn, + [&generator] { return static_cast(generator()); }); + auto made = keypair::make(drawn); + if (made) { + return std::move(*made); + } + BOOST_TEST(made.error() == error::invalid_secret_key); + } +} + +// a + b mod n, for a and b below n, big-endian bytes: the sum is below 2n, so one subtraction of +// n at most brings it below n. +scalar add_mod_n(scalar const& a, scalar const& b) { + scalar sum{}; + unsigned carry = 0; + for (std::size_t i = sum.size(); i-- > 0;) { + unsigned const total = unsigned{a[i]} + unsigned{b[i]} + carry; + sum[i] = static_cast(total); + carry = total >> 8U; + } + // sum - n, and its borrow: n is subtracted when the sum carried out or is not below n. + scalar reduced{}; + unsigned borrow = 0; + for (std::size_t i = reduced.size(); i-- > 0;) { + unsigned const subtrahend = unsigned{data::order[i]} + borrow; + unsigned const minuend = sum[i]; + reduced[i] = static_cast(minuend - subtrahend); + borrow = minuend < subtrahend ? 1U : 0U; + } + return (carry != 0 || borrow == 0) ? reduced : sum; +} + +// a * b mod n, by doubling and adding over b's bits, the most significant first. +scalar mul_mod_n(scalar const& a, scalar const& b) { + scalar product{}; + for (std::uint8_t const octet : b) { + for (unsigned bit = 8; bit-- > 0;) { + product = add_mod_n(product, product); + if (((unsigned{octet} >> bit) & 1U) != 0) { + product = add_mod_n(product, a); + } + } + } + return product; +} + +// The x coordinate of a key pair's public point, the bytes 1 to 32 of its uncompressed form. +std::array public_x(keypair const& pair) { + std::array x{}; + auto const point = pair.public_key(); + if (BOOST_TEST(point.has_value())) { + auto const bytes = point->uncompressed(); + std::ranges::copy(std::span(bytes).subspan<1, 32>(), x.begin()); + } + return x; +} + +void types() { + auto const a = keypair::make(data::rfc6979_scalar); + if (!BOOST_TEST(a.has_value())) { + return; + } + auto const peer = a->public_key(); + if (!BOOST_TEST(peer.has_value())) { + return; + } + // The output is a secret<32>, which wipes itself. + static_assert(std::is_same_vecdh_x(*peer)), + boost::system::result>>); +} + +// 100 pairs of key pairs drawn from the seed: each side's x is the other's. +void agreement(std::mt19937_64& generator) { + for (int round = 0; round < 100; ++round) { + auto const a = draw(generator); + auto const b = draw(generator); + auto const a_public = a.public_key(); + auto const b_public = b.public_key(); + if (!BOOST_TEST(a_public.has_value()) || !BOOST_TEST(b_public.has_value())) { + return; + } + auto const x_a = a.ecdh_x(*b_public); + auto const x_b = b.ecdh_x(*a_public); + if (!BOOST_TEST(x_a.has_value()) || !BOOST_TEST(x_b.has_value())) { + return; + } + BOOST_TEST(std::ranges::equal(x_a->bytes(), x_b->bytes())); + } +} + +// The arithmetic itself, on values whose answers are known: (n - 1) + 1 = 0, and +// (n - 1) * (n - 1) = (-1) * (-1) = 1. +void modular_arithmetic() { + scalar minus_one = data::order; + minus_one.back() = static_cast(minus_one.back() - 1); + scalar one{}; + one.back() = 1; + BOOST_TEST(add_mod_n(minus_one, one) == scalar{}); + BOOST_TEST(mul_mod_n(minus_one, minus_one) == one); +} + +// One scalar d: ECDH with its own public key, d * (d * G), is the public point of d * d mod n, +// and with 2 * G, d * (2 * G), the public point of 2 * d mod n; their x coordinates compared. +void fixed_points(scalar const& d, public_key const& two_g) { + auto const a = keypair::make(d); + auto const squared = keypair::make(mul_mod_n(d, d)); + auto const doubled = keypair::make(add_mod_n(d, d)); + if (!BOOST_TEST(a.has_value()) || !BOOST_TEST(squared.has_value()) || + !BOOST_TEST(doubled.has_value())) { + return; + } + auto const own = a->public_key(); + if (!BOOST_TEST(own.has_value())) { + return; + } + auto const x_own = a->ecdh_x(*own); + auto const x_doubled = a->ecdh_x(two_g); + if (!BOOST_TEST(x_own.has_value()) || !BOOST_TEST(x_doubled.has_value())) { + return; + } + BOOST_TEST(std::ranges::equal(x_own->bytes(), public_x(*squared))); + BOOST_TEST(std::ranges::equal(x_doubled->bytes(), public_x(*doubled))); +} + +// Fixed points of the algebra, with no table: RFC 6979's scalar, then 8 drawn from the seed, +// each through fixed_points, the scalars d * d and 2 * d mod n computed by bytes, here. +void own_key(std::mt19937_64& generator) { + modular_arithmetic(); + scalar two{}; + two.back() = 2; + auto const doubler = keypair::make(two); + auto const two_g = doubler ? doubler->public_key() : doubler.error(); + if (!BOOST_TEST(two_g.has_value())) { + return; + } + fixed_points(data::rfc6979_scalar, *two_g); + for (int i = 0; i < 8; ++i) { + auto const secret = draw(generator).secret_scalar(); + if (BOOST_TEST(secret.has_value())) { + scalar d{}; + std::ranges::copy(secret->bytes(), d.begin()); + fixed_points(d, *two_g); + } + } +} + +// NOLINTBEGIN(bugprone-use-after-move,clang-analyzer-cplusplus.Move): the moved-from state is what +// is tested. +void moved_from() { + auto made = keypair::make(data::rfc6979_scalar); + if (!BOOST_TEST(made.has_value())) { + return; + } + keypair const taken = std::move(*made); + auto const peer = taken.public_key(); + if (!BOOST_TEST(peer.has_value())) { + return; + } + BOOST_TEST(made->ecdh_x(*peer).error() == error::invalid_state); + BOOST_TEST(taken.ecdh_x(*peer).has_value()); +} + +// NOLINTEND(bugprone-use-after-move,clang-analyzer-cplusplus.Move) + +json::value load(std::string const& name) { + auto const text = test::read_file(WEBCPP_TEST_WYCHEPROOF "/testvectors_v1/" + name + ".json"); + boost::system::error_code ec; + auto value = json::parse(text, ec); + BOOST_TEST(!ec); + return value; +} + +std::string str(json::value const& v) { + return std::string(std::string_view(v.as_string())); +} + +// The counts of the file. +struct counts { + /** Cases run. */ + int total = 0; + /** Valid cases whose x agreed. */ + int valid = 0; + /** Invalid cases refused. */ + int invalid = 0; + /** Acceptable cases. */ + int acceptable = 0; + /** Valid or acceptable cases with a compressed point, refused by public_key::make. */ + int compressed_refused = 0; +}; + +// Whether a case carries a flag. +bool flagged(json::value const& t, std::string_view flag) { + auto const& flags = t.at("flags").as_array(); + return std::ranges::any_of(flags, [flag](json::value const& f) { return str(f) == flag; }); +} + +// A case's private key as 32 bytes: Wycheproof writes it as an ASN.1 integer's bytes, which may +// carry a leading 00, or shorter; the leading zero bytes are stripped and the rest left-padded. +// More than 32 significant bytes is no P-256 scalar: nothing is returned. +std::vector scalar_bytes(std::vector const& integer) { + auto const first = std::ranges::find_if(integer, [](std::uint8_t b) { return b != 0; }); + std::vector const significant(first, integer.end()); + if (significant.size() > 32) { + return {}; + } + std::vector padded(32 - significant.size(), 0); + padded.insert(padded.end(), significant.begin(), significant.end()); + return padded; +} + +// The case's own ECDH, or the error of the step that refused it: keypair::make, public_key::make +// or ecdh_x. +boost::system::result> derive(std::vector const& integer, + std::vector const& point) { + auto const padded = scalar_bytes(integer); + if (padded.empty()) { + return error::invalid_secret_key; + } + auto const pair = keypair::make(padded); + if (!pair) { + return pair.error(); + } + auto const peer = public_key::make(point); + if (!peer) { + return peer.error(); + } + return pair->ecdh_x(*peer); +} + +// Reports a case that went wrong, by its number. +void report(json::value const& t, std::string_view what) { + std::string message = "ecdh_secp256r1_ecpoint_test tcId "; + message += std::to_string(t.at("tcId").to_number()); + message += ": "; + message += what; + BOOST_ERROR(message.c_str()); +} + +// The listed refusal of a valid or acceptable case: a compressed point, which BearSSL does not +// decode. +constexpr std::string_view compressed_reason = + "BearSSL decodes uncompressed points alone, design D36"; + +// One case: an invalid one is refused at one of the three steps; a valid or acceptable one agrees +// with its shared x, unless its point is compressed, an expected refusal of public_key::make, +// printed with its reason; any other outcome fails. +void ecpoint_case(json::value const& t, counts& seen) { + ++seen.total; + auto const verdict = str(t.at("result")); + auto const point = test::from_hex(str(t.at("public"))); + auto const derived = derive(test::from_hex(str(t.at("private"))), point); + if (verdict == "invalid") { + ++seen.invalid; + if (derived.has_value()) { + report(t, "invalid case derived a shared x"); + } + return; + } + if (verdict != "valid" && verdict != "acceptable") { + report(t, verdict + ", not expected"); + return; + } + seen.acceptable += verdict == "acceptable" ? 1 : 0; + bool const compressed = + point.size() == 33 && (flagged(t, "CompressedPoint") || flagged(t, "CompressedPublic")); + if (compressed && public_key::make(point).error() == error::invalid_public_key) { + ++seen.compressed_refused; + std::cout << "ecdh_secp256r1_ecpoint_test tcId " << t.at("tcId").to_number() + << " " << verdict << ", refused by public_key::make: " << compressed_reason + << '\n'; + return; + } + auto const shared = test::from_hex(str(t.at("shared"))); + if (!derived.has_value() || !std::ranges::equal(derived->bytes(), shared)) { + report(t, verdict + " case refused or disagreed"); + return; + } + seen.valid += verdict == "valid" ? 1 : 0; +} + +// Wycheproof's ECDH on P-256 with the peer's key as a bare point (SEC 1's encoding), every case +// through ecpoint_case. +void wycheproof_ecpoint() { + auto const doc = load("ecdh_secp256r1_ecpoint_test"); + counts seen; + for (auto const& group : doc.at("testGroups").as_array()) { + for (auto const& t : group.at("tests").as_array()) { + ecpoint_case(t, seen); + } + } + std::cout << "ecdh_secp256r1_ecpoint_test: tests=" << seen.total + << " valid_agreed=" << seen.valid << " invalid_refused=" << seen.invalid + << " acceptable=" << seen.acceptable + << " compressed_refused=" << seen.compressed_refused << '\n'; + BOOST_TEST_EQ(seen.total, 355); + BOOST_TEST_EQ(seen.valid, 330); + BOOST_TEST_EQ(seen.invalid, 24); + BOOST_TEST_EQ(seen.acceptable, 1); + BOOST_TEST_EQ(seen.compressed_refused, 1); +} + +} // namespace + +int main() { + std::uint64_t const seed = random_seed(); + std::cout << "p256_ecdh_bearssl: seed " << seed + << " (replay: define=WEBCPP_TEST_P256_SEED=" << seed << ")\n"; + std::mt19937_64 generator(seed); + types(); + agreement(generator); + own_key(generator); + moved_from(); + wycheproof_ecpoint(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/p256_keys_bearssl_test.cpp b/test/p256_keys_bearssl_test.cpp index 2e6e0d83..7d407712 100644 --- a/test/p256_keys_bearssl_test.cpp +++ b/test/p256_keys_bearssl_test.cpp @@ -230,6 +230,8 @@ void moved_from() { BOOST_TEST(a.secret_scalar().error() == error::invalid_state); BOOST_TEST(a.sign_ecdsa(std::array{}).error() == error::invalid_state); + auto const peer = b.public_key(); + BOOST_TEST(peer.has_value() && a.ecdh_x(*peer).error() == error::invalid_state); // NOLINTEND(bugprone-use-after-move,clang-analyzer-cplusplus.Move) auto const point = b.public_key(); if (BOOST_TEST(point.has_value())) { diff --git a/test/timing_coverage_bearssl_test.cpp b/test/timing_coverage_bearssl_test.cpp index 55330f88..1e16ac60 100644 --- a/test/timing_coverage_bearssl_test.cpp +++ b/test/timing_coverage_bearssl_test.cpp @@ -15,10 +15,10 @@ // - AES-GCM, gcm, gcm and gcm: make, the move constructor and move // assignment (ruling R3), seal, open, begin_seal, update, result. // - ChaCha20-Poly1305, aead: make, seal, open. -// - P-256, curves::p256: basic_keypair::make, generate, sign_ecdsa; basic_public_key::make -// (both); verify_ecdsa, to_der, from_der; not guarded (no BearSSL call): public_key, -// secret_scalar, uncompressed, and normalize_ecdsa and check_low_s, which test/timing_test.cpp -// calls without a backend. +// - P-256, curves::p256: basic_keypair::make, generate, sign_ecdsa, ecdh_x; +// basic_public_key::make (both); verify_ecdsa, to_der, from_der; not guarded (no BearSSL call): +// public_key, secret_scalar, uncompressed, and normalize_ecdsa and check_low_s, which +// test/timing_test.cpp calls without a backend. #include "support/timing_seam.hpp" @@ -173,11 +173,33 @@ void cover_p256_ecdsa() { }); } +// P-256's ECDH: the shared x of RFC 6979's key with its own public key, and the same call on a +// moved-from key pair, refused with invalid_state before BearSSL, inside its own guard. +void cover_p256_ecdh() { + namespace p256 = crypto::curves::p256; + namespace data = webcpp::test::p256; + using keypair = p256::basic_keypair; + using public_key = p256::basic_public_key; + auto made = keypair::make(data::rfc6979_scalar); + auto const peer = public_key::make(data::rfc6979_public); + if (!BOOST_TEST(made.has_value()) || !BOOST_TEST(peer.has_value())) { + return; + } + webcpp::test::covered("p256::basic_keypair::ecdh_x on bearssl", + [&made, &peer] { BOOST_TEST(made->ecdh_x(*peer).has_value()); }); + keypair const taken = std::move(*made); + webcpp::test::covered("p256::basic_keypair::ecdh_x moved from on bearssl", [&made, &peer] { + // NOLINTNEXTLINE(bugprone-use-after-move,clang-analyzer-cplusplus.Move): tested + BOOST_TEST(made->ecdh_x(*peer).error() == crypto::error::invalid_state); + }); +} + } // namespace int main() { cover_ciphers(); cover_p256_keys(); cover_p256_ecdsa(); + cover_p256_ecdh(); return webcpp::test::exit_status(boost::report_errors()); } From e660ca3b099dd67d890d2bedb5b5e11bb51b8fd3 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 21 Nov 2026 01:38:50 -0300 Subject: [PATCH 07/28] crypto: P-256 ECDH's use case claims nothing of webcpp::trystero, its Wycheproof test requires invalid_public_key and bounds its draws, and its page cites what BearSSL's multiplication leaves on its stack --- doc/generated/use-cases.adoc | 2 +- doc/llms.txt | 4 ++-- doc/p256.adoc | 13 ++++++++++--- doc/tables/crypto.json | 4 +++- include/webcpp/crypto/backends/bearssl.hpp | 3 +-- test/p256_ecdh_bearssl_test.cpp | 15 ++++++++++++--- 6 files changed, 29 insertions(+), 12 deletions(-) diff --git a/doc/generated/use-cases.adoc b/doc/generated/use-cases.adoc index 33bb7333..3de4c759 100644 --- a/doc/generated/use-cases.adoc +++ b/doc/generated/use-cases.adoc @@ -257,7 +257,7 @@ `+/webcpp/crypto//p256-default+` |<> -|Agree on a key with a browser's WebCrypto (ECDH on P-256, deriveBits), then derive the session's keys with HKDF, as webcpp::trystero's peers do +|Agree on a key with a browser's WebCrypto (ECDH on P-256, deriveBits), then derive the session's keys with HKDF |In `+curves::p256+`: `+keypair::ecdh_x+`; `+webcpp::hash::hkdf+` for the keys |BearSSL |`+/webcpp/crypto//crypto+` + diff --git a/doc/llms.txt b/doc/llms.txt index a65f2f26..c5c074c9 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -184,7 +184,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - from_der: Decodes a strict DER signature to its raw form: only the encoding `to_der` writes is accepted. - normalize_ecdsa: The low-S form of a signature: s replaced by n - s when s is above (n - 1) / 2, returned unchanged otherwise. - check_low_s: Checks that a signature is in its low-S form, s at most (n - 1) / 2, as a protocol that requires low S checks what it receives. -- [curves::p256::keypair::ecdh_x](https://webcpporg.github.io/libs/crypto/#crypto-p256-ecdh): ECDH with a validated public key: the shared point's raw x coordinate, 32 bytes in a `secret<32>`, as WebCrypto's `deriveBits` gives it; a protocol hashes it into its keys. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten. Default: BearSSL on native, wasip2, wasip3, emscripten. Use it to: agree on a key with a browser's WebCrypto (ECDH on P-256, deriveBits), then derive the session's keys with HKDF, as webcpp::trystero's peers do. +- [curves::p256::keypair::ecdh_x](https://webcpporg.github.io/libs/crypto/#crypto-p256-ecdh): ECDH with a validated public key: the shared point's raw x coordinate, 32 bytes in a `secret<32>`, as WebCrypto's `deriveBits` gives it; a protocol hashes it into its keys. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten. Default: BearSSL on native, wasip2, wasip3, emscripten. Use it to: agree on a key with a browser's WebCrypto (ECDH on P-256, deriveBits), then derive the session's keys with HKDF. - ecdh_x: ECDH with a peer's public key: the x coordinate of the shared point d * Q, raw, as WebCrypto's `deriveBits` with ECDH on P-256 gives its 256 bits. ## webcpp::crypto::hybrid @@ -300,7 +300,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [Share a file with someone known only by a public key, as a file-sharing app does](https://webcpporg.github.io/libs/crypto/#crypto-everyday-files): `ciphers::secretbox<>` for the file under a key drawn for it, `hybrid::sealed_box::seal` for that key (webcpp::crypto); backend libsodium; Jamfile /webcpp/crypto//crypto /webcpp/crypto//secretbox_xsalsa20poly1305-default /webcpp/crypto//sealed_box-default /webcpp/crypto//x25519-default. Example: example/file_share.cpp. - [Make and keep a P-256 key pair, and import a browser's public key (WebCrypto's raw form), as webcpp::trystero's peers do](https://webcpporg.github.io/libs/crypto/#crypto-p256-keys): `keypair::make`, `keypair::generate`, `keypair::public_key`, `keypair::secret_scalar`, `public_key::make` (webcpp::crypto::curves::p256); backend BearSSL; Jamfile /webcpp/crypto//crypto /webcpp/crypto//p256-default. Example: example/p256_keys.cpp. - [Sign what a browser's WebCrypto verifies and verify what it signs (ECDSA on P-256 with SHA-256), low S where a protocol requires it, as webcpp::trystero's handshakes](https://webcpporg.github.io/libs/crypto/#crypto-p256-ecdsa): `keypair::sign_ecdsa`, `verify_ecdsa`, `normalize_ecdsa`, `check_low_s`; `to_der`, `from_der` for X.509 (webcpp::crypto::curves::p256); backend BearSSL; Jamfile /webcpp/crypto//crypto /webcpp/crypto//p256-default. Example: example/p256_sign.cpp. -- [Agree on a key with a browser's WebCrypto (ECDH on P-256, deriveBits), then derive the session's keys with HKDF, as webcpp::trystero's peers do](https://webcpporg.github.io/libs/crypto/#crypto-p256-ecdh): `keypair::ecdh_x`; `webcpp::hash::hkdf` for the keys (webcpp::crypto::curves::p256); backend BearSSL; Jamfile /webcpp/crypto//crypto /webcpp/crypto//p256-default. Example: example/p256_ecdh.cpp. +- [Agree on a key with a browser's WebCrypto (ECDH on P-256, deriveBits), then derive the session's keys with HKDF](https://webcpporg.github.io/libs/crypto/#crypto-p256-ecdh): `keypair::ecdh_x`; `webcpp::hash::hkdf` for the keys (webcpp::crypto::curves::p256); backend BearSSL; Jamfile /webcpp/crypto//crypto /webcpp/crypto//p256-default. Example: example/p256_ecdh.cpp. ## Examples diff --git a/doc/p256.adoc b/doc/p256.adoc index 7343276b..5daf1deb 100644 --- a/doc/p256.adoc +++ b/doc/p256.adoc @@ -220,7 +220,14 @@ shared point's x coordinate, 256 bits operations]), so a program and a browser that hash it the same way derive the same keys. The peer's key is a `public_key`, validated when it was made, so `ecdh_x` never sees a point off the curve; it refuses a moved-from key pair -with `invalid_state`. +with `invalid_state`. The `secret<32>` and webcpp's own copy of the point are +wiped, but BearSSL's multiplication leaves the values it computes from the +scalar in its stack frame, as its signing does (<>, its +pitfalls; +link:https://www.bearssl.org/gitweb/?p=BearSSL;a=blob;f=src/ec/ec_p256_m62.c;hb=7bea48e5e850ab4cafbe68d3765cdaba13a86d6f#l1251[BearSSL's +ec_p256_m62.c, from line 1251], natively, and +link:https://www.bearssl.org/gitweb/?p=BearSSL;a=blob;f=src/ec/ec_p256_m31.c;hb=7bea48e5e850ab4cafbe68d3765cdaba13a86d6f#l1116[ec_p256_m31.c, +from line 1116], on WebAssembly). The x coordinate is not a key. A Diffie-Hellman value is not uniformly random (link:https://www.rfc-editor.org/rfc/rfc5869#section-3.3[RFC 5869, section @@ -235,8 +242,8 @@ which webcpp::hash provides, and with the salt and the info the protocol names: include::{examples}/p256_ecdh.cpp[tag=derive,indent=0] ---- -crypto offers no hashed form, as secp256k1's `ecdh` is -(<>): no browser computes one, and the derivation, its +Unlike secp256k1, whose `ecdh` hashes the point (<>), +P-256 offers no hashed form: no browser computes one, and the derivation, its hash, its salt and its info belong to the protocol, not to the primitive. A program that hashed the point some other way would agree with no WebCrypto peer. diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 948a5984..5c1f12c1 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -46,6 +46,8 @@ "ieee1363": ["IEEE 1363-2000, Standard Specifications for Public-Key Cryptography: a signature as the two integers r and s, each at the order's length", "https://standards.ieee.org/ieee/1363/2049/"], "rfc3279": ["RFC 3279, section 2.2.3: an ECDSA signature in X.509, the DER of a SEQUENCE of the INTEGERs r and s", "https://www.rfc-editor.org/rfc/rfc3279#section-2.2.3"], "rfc7518": ["RFC 7518, section 3.4: JWS's ES256 signature is r and s, 32 bytes each, not DER", "https://www.rfc-editor.org/rfc/rfc7518#section-3.4"], + "bearssl-mul-stack-m62": ["BearSSL's ec_p256_m62.c at webcpp's pin, point_mul_inner from line 1251: the scalar's running point and the window entries it selects in the function's stack frame, never zeroed", "https://www.bearssl.org/gitweb/?p=BearSSL;a=blob;f=src/ec/ec_p256_m62.c;hb=7bea48e5e850ab4cafbe68d3765cdaba13a86d6f#l1251"], + "bearssl-mul-stack-m31": ["BearSSL's ec_p256_m31.c at webcpp's pin, p256_mul from line 1116: the scalar's running point and the window entries it selects in the function's stack frame, never zeroed", "https://www.bearssl.org/gitweb/?p=BearSSL;a=blob;f=src/ec/ec_p256_m31.c;hb=7bea48e5e850ab4cafbe68d3765cdaba13a86d6f#l1116"], "webcrypto-ecdh": ["W3C Web Cryptography API, ECDH's deriveBits: the shared point's x coordinate, its first length bits", "https://www.w3.org/TR/WebCryptoAPI/#ecdh-operations"], "trystero": ["Trystero 0.27.0's crypto.ts: its ECDSA P-256 signatures normalized to low S when made and refused unless low S when read", "https://github.com/dmotz/trystero/blob/0.27.0/packages/core/src/crypto.ts"], "bearssl-ct": ["BearSSL, constant-time crypto", "https://www.bearssl.org/constanttime.html"], @@ -1169,7 +1171,7 @@ {"need": "Share a file with someone known only by a public key, as a file-sharing app does", "namespace": "webcpp::crypto", "api": "`ciphers::secretbox<>` for the file under a key drawn for it, `hybrid::sealed_box::seal` for that key", "backend": "libsodium", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//secretbox_xsalsa20poly1305-default /webcpp/crypto//sealed_box-default /webcpp/crypto//x25519-default", "example": "file_share", "section": "crypto-everyday-files"}, {"need": "Make and keep a P-256 key pair, and import a browser's public key (WebCrypto's raw form), as webcpp::trystero's peers do", "namespace": "webcpp::crypto::curves::p256", "api": "`keypair::make`, `keypair::generate`, `keypair::public_key`, `keypair::secret_scalar`, `public_key::make`", "backend": "BearSSL", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//p256-default", "example": "p256_keys", "section": "crypto-p256-keys"}, {"need": "Sign what a browser's WebCrypto verifies and verify what it signs (ECDSA on P-256 with SHA-256), low S where a protocol requires it, as webcpp::trystero's handshakes", "namespace": "webcpp::crypto::curves::p256", "api": "`keypair::sign_ecdsa`, `verify_ecdsa`, `normalize_ecdsa`, `check_low_s`; `to_der`, `from_der` for X.509", "backend": "BearSSL", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//p256-default", "example": "p256_sign", "section": "crypto-p256-ecdsa"}, - {"need": "Agree on a key with a browser's WebCrypto (ECDH on P-256, deriveBits), then derive the session's keys with HKDF, as webcpp::trystero's peers do", "namespace": "webcpp::crypto::curves::p256", "api": "`keypair::ecdh_x`; `webcpp::hash::hkdf` for the keys", "backend": "BearSSL", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//p256-default", "example": "p256_ecdh", "section": "crypto-p256-ecdh"} + {"need": "Agree on a key with a browser's WebCrypto (ECDH on P-256, deriveBits), then derive the session's keys with HKDF", "namespace": "webcpp::crypto::curves::p256", "api": "`keypair::ecdh_x`; `webcpp::hash::hkdf` for the keys", "backend": "BearSSL", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//p256-default", "example": "p256_ecdh", "section": "crypto-p256-ecdh"} ], "fixtures": { "web": "A web application: AES-256-GCM on BearSSL, the default on WebAssembly.", diff --git a/include/webcpp/crypto/backends/bearssl.hpp b/include/webcpp/crypto/backends/bearssl.hpp index 2c732eb6..402894a5 100644 --- a/include/webcpp/crypto/backends/bearssl.hpp +++ b/include/webcpp/crypto/backends/bearssl.hpp @@ -433,8 +433,7 @@ struct p_curve_state { /** * P-256 on BearSSL: the point of a key pair computed once by `mulgen`, a public point checked * by BearSSL's decoding, ECDSA with RFC 6979's nonce and its DER conversions, ECDH's raw x - * coordinate. BearSSL allocates - * nothing; its curve code never fails on a valid input. + * coordinate. BearSSL allocates nothing; its curve code never fails on a valid input. */ template <> struct p_curve_engine { diff --git a/test/p256_ecdh_bearssl_test.cpp b/test/p256_ecdh_bearssl_test.cpp index bca63fd3..cf78aa1c 100644 --- a/test/p256_ecdh_bearssl_test.cpp +++ b/test/p256_ecdh_bearssl_test.cpp @@ -63,9 +63,11 @@ std::uint64_t random_seed() { #endif } -// A key pair from the generator: a scalar make refuses (0, or not below n) is drawn again. +// A key pair from the generator: a scalar make refuses (0, or not below n, about once in 2^32) +// is drawn again, 16 times at most; a make that keeps failing fails the test, which goes on with +// RFC 6979's key rather than hang. keypair draw(std::mt19937_64& generator) { - for (;;) { + for (int attempt = 0; attempt < 16; ++attempt) { scalar drawn{}; std::ranges::generate(drawn, [&generator] { return static_cast(generator()); }); @@ -75,6 +77,8 @@ keypair draw(std::mt19937_64& generator) { } BOOST_TEST(made.error() == error::invalid_secret_key); } + BOOST_ERROR("draw: keypair::make refused 16 drawn scalars"); + return *keypair::make(data::rfc6979_scalar); } // a + b mod n, for a and b below n, big-endian bytes: the sum is below 2n, so one subtraction of @@ -319,9 +323,14 @@ void ecpoint_case(json::value const& t, counts& seen) { auto const point = test::from_hex(str(t.at("public"))); auto const derived = derive(test::from_hex(str(t.at("private"))), point); if (verdict == "invalid") { - ++seen.invalid; + // Every invalid case of the file is a defect of its point: refused by public_key::make, + // never by BearSSL's multiplication. if (derived.has_value()) { report(t, "invalid case derived a shared x"); + } else if (derived.error() != error::invalid_public_key) { + report(t, "invalid case refused with another error than invalid_public_key"); + } else { + ++seen.invalid; } return; } From 0a8fb416cb28771a278387cd9a73c164a3bd69e0 Mon Sep 17 00:00:00 2001 From: R Date: Sat, 21 Nov 2026 01:57:44 -0300 Subject: [PATCH 08/28] crypto: SPKI and PKCS#8 for P-256 by RFC 5480's and RFC 5915's fixed layouts, strict, with BearSSL's encoder as their oracle --- doc/changelog.adoc | 2 +- doc/curves.adoc | 13 +- doc/formats.adoc | 17 + doc/generated/backends-p256_formats.adoc | 35 + doc/generated/backends-pem.adoc | 2 +- doc/generated/matrix.adoc | 18 +- doc/generated/use-cases.adoc | 8 + doc/llms.txt | 7 + doc/p256.adoc | 103 +++ doc/tables/crypto.json | 21 +- example/Jamfile | 5 + example/p256_key_formats.cpp | 109 +++ example/p256_key_formats.expected | 6 + include/webcpp/crypto.hpp | 5 +- include/webcpp/crypto/curves/p256/formats.hpp | 211 ++++++ test/Jamfile | 7 + test/allocation_bearssl_test.cpp | 16 +- test/convenience_header_test.cpp | 2 + test/p256_formats_bearssl_test.cpp | 661 ++++++++++++++++++ test/timing_coverage_bearssl_test.cpp | 43 +- test/windows_h_after_test.cpp | 1 + test/windows_h_before_test.cpp | 1 + 22 files changed, 1273 insertions(+), 20 deletions(-) create mode 100644 doc/generated/backends-p256_formats.adoc create mode 100644 example/p256_key_formats.cpp create mode 100644 example/p256_key_formats.expected create mode 100644 include/webcpp/crypto/curves/p256/formats.hpp create mode 100644 test/p256_formats_bearssl_test.cpp diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 1ded37e5..9a8251df 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -19,7 +19,7 @@ of every version are on webcpp's index page. * Added crypto, C-backed primitives setting DIT on arm64 macOS and Linux: ciphers, curves, randomness, fixed-value errors in webcpp.crypto, `+[[nodiscard]]+` results, WEBCPP_CRYPTO_HAS_THREADS, defined natively and with Emscripten's -pthread unless WEBCPP_CRYPTO_NO_THREADS is. * Added equal, random_device, pem (PEM on libsodium), ciphers::aes128, aes192 and aes256, the AES block cipher, and ciphers::gcm, aes128_gcm and aes256_gcm: AES-GCM in place, incremental seal, failed opens zeroing data. * Added supports_v with its family tags, the capability table per target, default_backend_t and /webcpp/crypto//-default per family and target (secp256k1's modules among them), and refusals naming their Jamfile line. -* Added backends::bearssl (AES-GCM, ChaCha20-Poly1305, P-256 key pairs, ECDSA, ECDH; allocating nothing), backends::openssl natively and on WASI (allocating at make, or natively in openssl_memory_resource with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE), and backends::ctaes (block cipher alone). +* Added backends::bearssl (AES-GCM, ChaCha20-Poly1305, P-256 key pairs, ECDSA, ECDH, SPKI and PKCS#8; allocating nothing), backends::openssl natively and on WASI (allocating at make, or natively in openssl_memory_resource with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE), and backends::ctaes (block cipher alone). * Added curves::secp256k1: key pairs, BIP340, hedged and recoverable ECDSA, raw and hashed ECDH, strict DER, low-S, tweaks, SPKI, PKCS#8, PEM, BIP 324's ElligatorSwift, BIP 327's MuSig2, BIP 352's silent payments. * Added curves::ed25519 and curves::x25519 on libsodium: strict verification over twelve edge cases, Ed25519ph over hash's sha2_512 (/webcpp/crypto//crypto brings hash), the conversion, agree refusing all-zero secrets, RFC 8410's SPKI and PKCS#8. * Added backends::sodium on /third_party//sodium, shared with webcpp::hash, every backend's link-time canary and C suite, and ciphers::aead: chacha20_poly1305 (also BearSSL, OpenSSL), the original form, xchacha20_poly1305, failed seals and opens zeroing data. diff --git a/doc/curves.adoc b/doc/curves.adoc index 0adbeb13..3f1e3d50 100644 --- a/doc/curves.adoc +++ b/doc/curves.adoc @@ -66,12 +66,13 @@ key to it (link:https://www.rfc-editor.org/rfc/rfc7748[RFC 7748]; (<>). The fourth is P-256, NIST's curve of FIPS 186-5, the curve of browsers' WebCrypto, of passkeys and of TLS certificates, on BearSSL: key pairs made from a scalar or drawn, public keys validated once, ECDSA with RFC -6979's nonce, raw and DER, with low S as two functions, and ECDH's raw x -coordinate, as WebCrypto's `deriveBits` gives it -(link:https://csrc.nist.gov/pubs/fips/186-5/final[FIPS 186-5]; -<>, <>, <>). A program chooses a curve for compatibility: a signature on +6979's nonce, raw and DER, with low S as two functions, ECDH's raw x +coordinate, as WebCrypto's `deriveBits` gives it, and its keys as SPKI and +PKCS#8 (link:https://csrc.nist.gov/pubs/fips/186-5/final[FIPS 186-5]; +<>, <>, <>, +<>). A program chooses a curve for compatibility: a signature on one curve is checked only with that curve, and a browser's peer needs P-256. -Ed25519's and X25519's keys leave a program, and enter it, in the standard forms OpenSSL -and WebCrypto use, SPKI and PKCS#8, as DER or PEM text (<>). +Ed25519's, X25519's and P-256's keys leave a program, and enter it, in the standard forms +OpenSSL and WebCrypto use, SPKI and PKCS#8, as DER or PEM text (<>). include::generated/namespace-curves.adoc[] diff --git a/doc/formats.adoc b/doc/formats.adoc index c4d48bb4..4ab8a218 100644 --- a/doc/formats.adoc +++ b/doc/formats.adoc @@ -33,6 +33,23 @@ tests compare every byte with OpenSSL's natively and on WASI (`formats_25519_openssl_oracle`) and with node's WebCrypto on Emscripten (`formats_25519_webcrypto_oracle`), 200 keys per curve each. +For P-256, RFC 5480's SPKI and a PKCS#8 holding RFC 5915's ECPrivateKey are +fixed layouts too (link:https://www.rfc-editor.org/rfc/rfc5480[RFC 5480]; +link:https://www.rfc-editor.org/rfc/rfc5915[RFC 5915]), on BearSSL: +`` gives `encode_spki`, `decode_spki`, +`encode_pkcs8` and `decode_pkcs8` in `webcpp::crypto::curves::p256`: an SPKI of 91 bytes with the uncompressed +point, WebCrypto's `exportKey("spki")` form +(link:https://www.w3.org/TR/WebCryptoAPI/#ecdsa-operations-export-key[W3C, +ECDSA's export]), and a PKCS#8 of 138 bytes with the public key and without +the curve inside the ECPrivateKey, OpenSSL's form +(link:https://docs.openssl.org/master/man7/EVP_PKEY-EC/[OpenSSL's EVP_PKEY-EC]) +and BearSSL's, which WebCrypto's `importKey("pkcs8")` reads +(link:https://www.w3.org/TR/WebCryptoAPI/#ecdsa-operations-import-key[W3C, +ECDSA's import]). A compressed point, explicit curve parameters and a PKCS#8 +that carries the curve inside its ECPrivateKey, the form the W3C text gives +WebCrypto's `exportKey("pkcs8")`, are refused; `pem` armours both +(<>). + `` gives, in `webcpp::crypto::curves::ed25519`, `encode_spki(public_key, out)`, `decode_spki(spki)`, `encode_pkcs8(keypair, out)` and `decode_pkcs8(pkcs8)`, diff --git a/doc/generated/backends-p256_formats.adoc b/doc/generated/backends-p256_formats.adoc new file mode 100644 index 00000000..a0bac55d --- /dev/null +++ b/doc/generated/backends-p256_formats.adoc @@ -0,0 +1,35 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, +// the message tests and the Jamfile fixtures: run it again, never edit this file. + +The backends of `+curves::p256::encode_spki+`, `+decode_spki+`, `+encode_pkcs8+`, `+decode_pkcs8+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|BearSSL +|`+/third_party//bearssl+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+p256_formats_bearssl+`, `+allocation_bearssl+`) + +|libsodium +|`+/third_party//sodium+` +|`++` +|refused at compile time (`+p256_on_sodium+`) +|=== + +A call that names no backend takes the family's default on each target, whatever the program links, as <> gives it with its reasons and tests: + +[cols="1,1",options="header"] +|=== +|Target |Default + +|native, wasip2, wasip3, emscripten +|BearSSL +|=== diff --git a/doc/generated/backends-pem.adoc b/doc/generated/backends-pem.adoc index b520a397..f74e7342 100644 --- a/doc/generated/backends-pem.adoc +++ b/doc/generated/backends-pem.adoc @@ -16,7 +16,7 @@ The backends of `+pem::armour+`, `+pem::unarmour+`, from the test programs that |libsodium |`+/third_party//sodium+` |`++` -|native, wasip2, wasip3, emscripten (tested by `+formats_25519_sodium+`, `+formats_25519_openssl_oracle+`, `+allocation_sodium+`) +|native, wasip2, wasip3, emscripten (tested by `+formats_25519_sodium+`, `+formats_25519_openssl_oracle+`, `+allocation_sodium+`, `+p256_formats_bearssl+`) |=== A call that names no backend takes the family's default on each target, whatever the program links, as <> gives it with its reasons and tests: diff --git a/doc/generated/matrix.adoc b/doc/generated/matrix.adoc index b9fb32cb..97a8e21a 100644 --- a/doc/generated/matrix.adoc +++ b/doc/generated/matrix.adoc @@ -129,7 +129,7 @@ |`+pem::armour+`, `+pem::unarmour+` |libsodium |native, wasip2, wasip3, emscripten -|`+formats_25519_sodium+`, `+formats_25519_openssl_oracle+`, `+allocation_sodium+` +|`+formats_25519_sodium+`, `+formats_25519_openssl_oracle+`, `+allocation_sodium+`, `+p256_formats_bearssl+` |`+curves::x25519::kx_keypair+` |libsodium @@ -260,6 +260,16 @@ |libsodium |refused at compile time |`+p256_on_sodium+` + +|`+curves::p256::encode_spki+`, `+decode_spki+`, `+encode_pkcs8+`, `+decode_pkcs8+` +|BearSSL +|native, wasip2, wasip3, emscripten +|`+p256_formats_bearssl+`, `+allocation_bearssl+` + +|`+curves::p256::encode_spki+`, `+decode_spki+`, `+encode_pkcs8+`, `+decode_pkcs8+` +|libsodium +|refused at compile time +|`+p256_on_sodium+` |=== The same, by target: the backends each operation runs on. @@ -501,4 +511,10 @@ The same, by target: the backends each operation runs on. |BearSSL |BearSSL |BearSSL + +|`+curves::p256::encode_spki+`, `+decode_spki+`, `+encode_pkcs8+`, `+decode_pkcs8+` +|BearSSL +|BearSSL +|BearSSL +|BearSSL |=== diff --git a/doc/generated/use-cases.adoc b/doc/generated/use-cases.adoc index 3de4c759..8ce5096b 100644 --- a/doc/generated/use-cases.adoc +++ b/doc/generated/use-cases.adoc @@ -263,4 +263,12 @@ |`+/webcpp/crypto//crypto+` + `+/webcpp/crypto//p256-default+` |<> + +|Export or import a P-256 key in the forms OpenSSL and WebCrypto's spki and pkcs8 use (SPKI, PKCS#8), as DER or PEM text +|In `+curves::p256+`: `+encode_spki+`, `+decode_spki+`, `+encode_pkcs8+`, `+decode_pkcs8+`; `+webcpp::crypto::pem::armour+`, `+unarmour+` +|BearSSL, libsodium for PEM +|`+/webcpp/crypto//crypto+` + +`+/webcpp/crypto//p256-default+` + +`+/webcpp/crypto//pem-default+` +|<> |=== diff --git a/doc/llms.txt b/doc/llms.txt index c5c074c9..f812ea03 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -186,6 +186,11 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - check_low_s: Checks that a signature is in its low-S form, s at most (n - 1) / 2, as a protocol that requires low S checks what it receives. - [curves::p256::keypair::ecdh_x](https://webcpporg.github.io/libs/crypto/#crypto-p256-ecdh): ECDH with a validated public key: the shared point's raw x coordinate, 32 bytes in a `secret<32>`, as WebCrypto's `deriveBits` gives it; a protocol hashes it into its keys. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten. Default: BearSSL on native, wasip2, wasip3, emscripten. Use it to: agree on a key with a browser's WebCrypto (ECDH on P-256, deriveBits), then derive the session's keys with HKDF. - ecdh_x: ECDH with a peer's public key: the x coordinate of the shared point d * Q, raw, as WebCrypto's `deriveBits` with ECDH on P-256 gives its 256 bits. +- [curves::p256::encode_spki, decode_spki, encode_pkcs8, decode_pkcs8](https://webcpporg.github.io/libs/crypto/#crypto-p256-formats): A public key's SPKI (RFC 5480, the uncompressed point, 91 bytes) and a key pair's PKCS#8 (RFC 5915's ECPrivateKey with its public key and no parameters, 138 bytes), by fixed layouts, decoded strictly: any other bytes are `invalid_encoding`; `pem::armour` makes either PEM text. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten. Default: BearSSL on native, wasip2, wasip3, emscripten. Use it to: export or import a P-256 key in the forms OpenSSL and WebCrypto's spki and pkcs8 use (SPKI, PKCS#8), as DER or PEM text. + - encode_spki: Writes a public key's SPKI (RFC 5480, the secp256r1 OID, the uncompressed point) into `output_bytes`: the bytes WebCrypto's `exportKey("spki")` and OpenSSL's `i2d_PUBKEY` write. + - decode_spki: The public key of an SPKI that is exactly what `encode_spki` writes, its point checked as `basic_public_key::make` checks it. + - encode_pkcs8: Writes a key pair's PKCS#8 into `output_bytes`: version 0, and RFC 5915's ECPrivateKey of version 1 with the uncompressed public key and no parameters inside, the form OpenSSL's and BearSSL's encoders write. + - decode_pkcs8: The key pair of a PKCS#8 that is exactly what `encode_pkcs8` writes for its scalar, made as `basic_keypair::make` makes it. ## webcpp::crypto::hybrid @@ -301,6 +306,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [Make and keep a P-256 key pair, and import a browser's public key (WebCrypto's raw form), as webcpp::trystero's peers do](https://webcpporg.github.io/libs/crypto/#crypto-p256-keys): `keypair::make`, `keypair::generate`, `keypair::public_key`, `keypair::secret_scalar`, `public_key::make` (webcpp::crypto::curves::p256); backend BearSSL; Jamfile /webcpp/crypto//crypto /webcpp/crypto//p256-default. Example: example/p256_keys.cpp. - [Sign what a browser's WebCrypto verifies and verify what it signs (ECDSA on P-256 with SHA-256), low S where a protocol requires it, as webcpp::trystero's handshakes](https://webcpporg.github.io/libs/crypto/#crypto-p256-ecdsa): `keypair::sign_ecdsa`, `verify_ecdsa`, `normalize_ecdsa`, `check_low_s`; `to_der`, `from_der` for X.509 (webcpp::crypto::curves::p256); backend BearSSL; Jamfile /webcpp/crypto//crypto /webcpp/crypto//p256-default. Example: example/p256_sign.cpp. - [Agree on a key with a browser's WebCrypto (ECDH on P-256, deriveBits), then derive the session's keys with HKDF](https://webcpporg.github.io/libs/crypto/#crypto-p256-ecdh): `keypair::ecdh_x`; `webcpp::hash::hkdf` for the keys (webcpp::crypto::curves::p256); backend BearSSL; Jamfile /webcpp/crypto//crypto /webcpp/crypto//p256-default. Example: example/p256_ecdh.cpp. +- [Export or import a P-256 key in the forms OpenSSL and WebCrypto's spki and pkcs8 use (SPKI, PKCS#8), as DER or PEM text](https://webcpporg.github.io/libs/crypto/#crypto-p256-formats): `encode_spki`, `decode_spki`, `encode_pkcs8`, `decode_pkcs8`; `webcpp::crypto::pem::armour`, `unarmour` (webcpp::crypto::curves::p256); backend BearSSL, libsodium for PEM; Jamfile /webcpp/crypto//crypto /webcpp/crypto//p256-default /webcpp/crypto//pem-default. Example: example/p256_key_formats.cpp. ## Examples @@ -325,6 +331,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - example/openssl_memory.cpp: Sends every allocation of OpenSSL's to the program's own memory resource, natively, then seals and opens one block with AES-256-GCM on OpenSSL, on a worker thread as an audio engine's or a server's would. Built with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE, /webcpp/crypto//openssl and threads (example/Jamfile). - example/order_reference.cpp: Turns a sequential order id into an opaque 16-byte reference with the raw AES block cipher, and back. Customers then cannot guess other orders' numbers. This is NOT authenticated encryption: a forged reference still decrypts, to garbage, so the program checks the padding. - example/p256_ecdh.cpp: Two P-256 key pairs, made from fixed scalars, agree on the shared point's raw x coordinate with ecdh_x, the 256 bits WebCrypto's deriveBits gives with ECDH on P-256; then HKDF-SHA-256 of that x, with webcpp::hash, derives the 32-byte key a protocol would encrypt with. The x coordinate is not a key: the derivation, its salt and its info are the protocol's. Cross-checked by hand once with OpenSSL 4.1.0 (2026-11-21), each scalar s (32 bytes of 11, then of 22) written as SEC 1's ECPrivateKey on prime256v1: echo 30310201010420${s}a00a06082a8648ce3d030107 | xxd -r -p > alice.der openssl ec -inform DER -in alice.der -out alice.pem (likewise bob) openssl pkey -in bob.pem -pubout -out bob_public.pem openssl pkeyutl -derive -inkey alice.pem -peerkey bob_public.pem | xxd -p -c 64 openssl kdf -keylen 32 -kdfopt digest:SHA256 -kdfopt hexkey: -kdfopt salt:"example salt" -kdfopt info:"example chat v1 key" HKDF (one line) which print the x and the key of p256_ecdh.expected. +- example/p256_key_formats.cpp: RFC 6979's P-256 key in the files other programs read: its public key written as PEM SPKI, the text OpenSSL reads and whose DER a WebCrypto peer's importKey("spki") reads, printed and read back; its key pair written as PEM PKCS#8 for the program's own key file, never printed, and read back. The key is RFC 6979's published one, so that the output is fixed: a real program draws its own. - example/p256_keys.cpp: Makes a P-256 key pair from RFC 6979's key, prints its public key as the 65 bytes WebCrypto's exportKey("raw") gives, keeps its scalar and makes the same key pair from it again, then imports that public key as a peer's and refuses the same bytes with one bit changed. Draws a fresh key pair too, whose bytes differ on every run and are not printed. - example/p256_sign.cpp: Signs the SHA-256 digest of "sample" with RFC 6979's P-256 key and prints the signature, the RFC's own bytes, in the raw form WebCrypto uses; then its low-S form, which a protocol that requires low S sends, and its DER encoding, which X.509 carries; and verifies both forms with the public key alone, and refuses the digest of another message. - example/recover_signer.cpp: Finds who signed a message without being sent their key, as Ethereum finds a transaction's signer: a wallet signs a message's hash with a recoverable signature, and a reader that holds no key recovers the signer's public key from the signature and the hash, then compares it with the key the wallet published. Recovery always finds some key, so the comparison is the check: a changed message recovers another key. diff --git a/doc/p256.adoc b/doc/p256.adoc index 5daf1deb..f5acda92 100644 --- a/doc/p256.adoc +++ b/doc/p256.adoc @@ -279,3 +279,106 @@ derivation, byte for byte. alone (link:https://www.w3.org/TR/WebCryptoAPI/#ecdh-operations[W3C, ECDH's operations]); the program then takes the same leading bytes of what `ecdh_x` returns, or the two sides hash different inputs. + +[#crypto-p256-formats] +==== Keys in files: SPKI, PKCS#8 and PEM + +A key that leaves the program for another one, a browser's WebCrypto, OpenSSL's +command line, a server's configuration file, travels in a standard form that +names its algorithm and its curve. A public key is an *SPKI*, +SubjectPublicKeyInfo (link:https://www.rfc-editor.org/rfc/rfc5480[RFC 5480]); +a key pair is a *PKCS#8* (link:https://www.rfc-editor.org/rfc/rfc5208[RFC +5208]), which for an elliptic curve holds RFC 5915's ECPrivateKey: the scalar, +and optionally the curve and the public key +(link:https://www.rfc-editor.org/rfc/rfc5915[RFC 5915]). These are what +WebCrypto's `exportKey("spki")` and `exportKey("pkcs8")` produce and its +`importKey` reads (link:https://www.w3.org/TR/WebCryptoAPI/[W3C]). + +On P-256 each has one layout, fixed bytes around the key's own: + +* `encode_spki(public_key, output)` writes 91 bytes: 26 that name +id-ecPublicKey and secp256r1 and open the BIT STRING, then the 65-byte +uncompressed point. That is the SPKI WebCrypto exports, the named curve and the +uncompressed form +(link:https://www.w3.org/TR/WebCryptoAPI/#ecdsa-operations-export-key[W3C, +ECDSA's export]); `decode_spki(bytes)` reads it back into a `public_key`, its +point checked as `public_key::make` checks it. +* `encode_pkcs8(keypair, output)` writes 138 bytes: version 0, the same +algorithm, and an ECPrivateKey of version 1 with the scalar and the +uncompressed public key, without the curve inside it. That is the form OpenSSL +writes for a key in its default uncompressed form +(link:https://docs.openssl.org/master/man7/EVP_PKEY-EC/[OpenSSL's EVP_PKEY-EC]), +and BearSSL's own encoder, `br_encode_ec_pkcs8_der`, writes the same bytes, +which the tests compare; `decode_pkcs8(bytes)` reads it into a key pair, made +as `keypair::make` makes one. + +`max_spki_size` and `max_pkcs8_size`, 91 and 138, size the caller's buffers. +The encoders copy what the key and the key pair hold, call no BearSSL code, +and refuse a short buffer with `invalid_input_size` and a moved-from key pair +with `invalid_state`, writing nothing then. + +The decoders are strict (design D30): they accept exactly the bytes the +encoders write, and refuse anything else with `invalid_encoding`. The point +must be on the curve, the scalar between 1 and n - 1, and the public key inside +a PKCS#8 the scalar's own: `decode_pkcs8` makes the key pair and compares its +point with the one the file carries. Refused, too: another curve, a compressed +point (BearSSL decodes uncompressed points alone), explicit curve parameters in +place of the curve's name, a PKCS#8 without its public key, a length in BER's +long form where DER has the short one, a byte left over. Against Wycheproof's +612 P-256 ECDH cases whose peer key is an SPKI, the 330 valid ones decode and +agree on the shared x, the 52 invalid ones are refused, and the 230 acceptable +ones are refused, each for a form the rule refuses: a compressed point (1), +ASN.1 that is not the one DER encoding (222), or explicit parameters (7) +(link:https://github.com/C2SP/wycheproof[Wycheproof]). + +PEM is the DER as base64 text between `-----BEGIN PUBLIC KEY-----` or +`-----BEGIN PRIVATE KEY-----` and its `-----END` line +(link:https://www.rfc-editor.org/rfc/rfc7468[RFC 7468]). `pem::armour` and +`pem::unarmour` (``, <>) write and +read it around these functions' bytes, with the labels `pem::public_key_label` +and `pem::private_key_label`, as strictly as the decoders read DER. PEM runs on +libsodium, whose base64 takes a time that does not depend on the bytes: a +program that writes or reads PEM links `/webcpp/crypto//pem-default` beside +`/webcpp/crypto//p256-default`. + +include::generated/backends-p256_formats.adoc[] + +*Example.* RFC 6979's key: its public key written as PEM SPKI, printed and read +back; its key pair written as PEM PKCS#8, kept in a `secret` and never +printed, and read back: + +[source,cpp] +---- +include::{examples}/p256_key_formats.cpp[tag=program] +---- + +[listing] +---- +include::{examples}/p256_key_formats.expected[] +---- + +*Pitfalls.* + +* The W3C text has a PKCS#8 that WebCrypto exports carry the curve inside its +ECPrivateKey too, as `[0] parameters` +(link:https://www.w3.org/TR/WebCryptoAPI/#ecdsa-operations-export-key[W3C, +ECDSA's export]): 150 bytes, which `decode_pkcs8` refuses like any other +encoding than its own. WebCrypto's `importKey("pkcs8")` reads the 138 bytes +`encode_pkcs8` writes, the parameters being optional there +(link:https://www.w3.org/TR/WebCryptoAPI/#ecdsa-operations-import-key[W3C, +ECDSA's import]), and OpenSSL's `openssl pkey` rewrites a 150-byte file into +the 138-byte form, PKCS#8 being what it writes by default +(link:https://docs.openssl.org/master/man1/openssl-pkey/[OpenSSL's pkey]). +* `-----BEGIN EC PRIVATE KEY-----`, what `openssl ec` writes, is not PKCS#8: it +is RFC 5915's ECPrivateKey alone, with the curve's parameters +(link:https://www.rfc-editor.org/rfc/rfc5915[RFC 5915]), and `pem::unarmour` +refuses its label. `openssl pkey` turns it into a PKCS#8 +(link:https://docs.openssl.org/master/man1/openssl-pkey/[OpenSSL's pkey]). +* A lenient parser lets a file say two things at once: RFC 5915 makes the +public key optional inside ECPrivateKey, so a PKCS#8 can carry a public key +that is not its scalar's, and a program that shows or checks that key, rather +than the one the scalar gives, trusts the wrong key. `decode_pkcs8` refuses +such a file. +* The PKCS#8, as DER or as PEM, is the secret key in clear: base64 is an +encoding, not encryption. Keep it in a `secret`, as the example does, and +seal it before it is written anywhere (<>). diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 5c1f12c1..c7ed742c 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -124,6 +124,7 @@ "bip324": ["BIP 324, version 2 P2P encrypted transport protocol", "https://github.com/bitcoin/bips/blob/master/bip-0324.mediawiki"], "elligatorswift": ["Chavez-Saab, Rodríguez-Henríquez and Tibouchi, SwiftEC: Shallue-van de Woestijne Indifferentiable Function to Elliptic Curves, 2022", "https://eprint.iacr.org/2022/759"], "openssl-evp-pkey-ec": ["OpenSSL's EVP_PKEY-EC: an EC key's point form and its encodings", "https://docs.openssl.org/master/man7/EVP_PKEY-EC/"], + "openssl-pkey": ["OpenSSL's pkey command: a private key written in PKCS#8 by default", "https://docs.openssl.org/master/man1/openssl-pkey/"], "musig2": ["Nick, Ruffing and Seurin, MuSig2: Simple Two-Round Schnorr Multi-Signatures, CRYPTO 2021", "https://eprint.iacr.org/2020/1261"], "bip352": ["BIP 352, Silent Payments", "https://github.com/bitcoin/bips/blob/master/bip-0352.mediawiki"], "libsecp256k1-silentpayments": ["libsecp256k1's silent payments header at webcpp's pin: the smallest outpoint, the outputs to keep, the labels to create", "https://github.com/bitcoin-core/secp256k1/blob/6e2c8bc4ecdc6e71dbe7a368f360d8d453ce435d/include/secp256k1_silentpayments.h"], @@ -456,7 +457,7 @@ "header": "", "what": "PEM (RFC 7468): DER as base64 between `-----BEGIN